diff --git a/cave/ohd.hseb.common/.classpath b/cave/ohd.hseb.common/.classpath deleted file mode 100644 index 78fc66cee2..0000000000 --- a/cave/ohd.hseb.common/.classpath +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/cave/ohd.hseb.common/.project b/cave/ohd.hseb.common/.project deleted file mode 100644 index 74a6158a65..0000000000 --- a/cave/ohd.hseb.common/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.hseb.common - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.pde.PluginNature - - diff --git a/cave/ohd.hseb.common/.settings/org.eclipse.jdt.core.prefs b/cave/ohd.hseb.common/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index e007020a1e..0000000000 --- a/cave/ohd.hseb.common/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -#Thu Mar 26 11:33:13 CDT 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cave/ohd.hseb.common/META-INF/MANIFEST.MF b/cave/ohd.hseb.common/META-INF/MANIFEST.MF deleted file mode 100644 index c21309aa06..0000000000 --- a/cave/ohd.hseb.common/META-INF/MANIFEST.MF +++ /dev/null @@ -1,251 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: RiverAppsCommon Plug-in -Bundle-SymbolicName: ohd.hseb.common -Bundle-Version: 1.0.0.qualifier -Bundle-Vendor: Raytheon -Export-Package: ChartDirector, - RTi.Util.GUI, - RTi.Util.IO, - RTi.Util.Message, - RTi.Util.String, - bsh, - bsh.classpath, - bsh.collection, - bsh.commands, - bsh.org.objectweb.asm, - bsh.reflect, - bsh.servlet, - bsh.util, - bsh.util.lib, - com.klg.jclass, - com.klg.jclass.beans, - com.klg.jclass.beans.resources, - com.klg.jclass.cell, - com.klg.jclass.cell.renderers, - com.klg.jclass.cell.swing, - com.klg.jclass.chart, - com.klg.jclass.chart.applet, - com.klg.jclass.chart.beans, - com.klg.jclass.chart.beans.resources, - com.klg.jclass.chart.customizer, - com.klg.jclass.chart.customizer.resources, - com.klg.jclass.chart.data, - com.klg.jclass.chart.property, - com.klg.jclass.chart.property.html, - com.klg.jclass.chart.resources, - com.klg.jclass.util, - com.klg.jclass.util.graphics, - com.klg.jclass.util.internal, - com.klg.jclass.util.io, - com.klg.jclass.util.io.resources, - com.klg.jclass.util.legend, - com.klg.jclass.util.legend.resources, - com.klg.jclass.util.progress, - com.klg.jclass.util.resources, - com.klg.jclass.util.swing, - com.klg.jclass.util.swing.beans, - com.klg.jclass.util.swing.beans.resources, - com.klg.jclass.util.swing.encode, - com.klg.jclass.util.swing.encode.resources, - com.klg.jclass.util.swing.icons, - com.klg.jclass.util.swing.resources, - com.klg.jclass.util.value, - com.klg.jclass.util.xml, - com.sitraka.licensing, - com.sitraka.licensing.util, - gov.noaa.FWGUI, - gov.noaa.FloodWav.Component, - gov.noaa.flddb, - gov.noaa.fldwav, - gov.noaa.fldwav.component, - gov.noaa.fldwav.controller, - gov.noaa.fldwav.gui, - gov.noaa.fldwav.parser, - gov.noaa.hec.parser, - junit.awtui, - junit.extensions, - junit.framework, - junit.runner, - junit.swingui, - junit.swingui.icons, - junit.textui, - ohd.hseb.bias_trans, - ohd.hseb.color_chooser, - ohd.hseb.damcrest, - ohd.hseb.db, - ohd.hseb.fcstservice, - ohd.hseb.fp_vtec_info, - ohd.hseb.geomap.contour, - ohd.hseb.geomap.model, - ohd.hseb.geomap.projection, - ohd.hseb.grid, - ohd.hseb.gui.util, - ohd.hseb.ihfsdb.generated, - ohd.hseb.measurement, - ohd.hseb.model, - ohd.hseb.model.mkcapi, - ohd.hseb.model.sacsma, - ohd.hseb.pdc_pp, - ohd.hseb.pdc_pp.sample_data_set, - ohd.hseb.prism, - ohd.hseb.timeserieslite, - ohd.hseb.timeserieslite.gui.drawing, - ohd.hseb.timeserieslite.pdc, - ohd.hseb.timeserieslite.rivermon, - ohd.hseb.util, - ohd.hseb.util.gui, - ohd.hseb.util.gui.drawing, - ohd.hseb.util.gui.jchecktree, - ohd.hseb.util.gui.jtable, - ohd.hseb.util.io, - ohd.hseb.util.test, - org.apache.bsf, - org.apache.bsf.dbline, - org.apache.bsf.debug, - org.apache.bsf.debug.clientImpl, - org.apache.bsf.debug.jsdi, - org.apache.bsf.debug.meta, - org.apache.bsf.debug.serverImpl, - org.apache.bsf.debug.util, - org.apache.bsf.engines.jacl, - org.apache.bsf.engines.javascript, - org.apache.bsf.engines.jython, - org.apache.bsf.engines.netrexx, - org.apache.bsf.engines.xslt, - org.apache.bsf.util, - org.apache.bsf.util.cf, - org.apache.bsf.util.event, - org.apache.bsf.util.event.adapters, - org.apache.bsf.util.event.generator, - org.apache.bsf.util.type, - org.apache.taglibs.bsf, - org.jdom, - org.jdom.adapters, - org.jdom.filter, - org.jdom.input, - org.jdom.output, - org.jdom.transform, - org.jdom.xpath, - org.postgresql, - org.postgresql.core, - org.postgresql.core.types, - org.postgresql.core.v2, - org.postgresql.core.v3, - org.postgresql.ds, - org.postgresql.ds.common, - org.postgresql.ds.jdbc23, - org.postgresql.fastpath, - org.postgresql.geometric, - org.postgresql.jdbc2, - org.postgresql.jdbc2.optional, - org.postgresql.jdbc3, - org.postgresql.largeobject, - org.postgresql.ssl, - org.postgresql.translation, - org.postgresql.util, - org.postgresql.xa, - resources.nj22.coords, - resources.nj22.schemas, - resources.nj22.tables, - resources.nj22.ui.icons, - resources.nj22.ui.maps, - resources.nj22.ui.pix, - resources.thredds.dl, - resources.thredds.schemas, - thredds.catalog, - thredds.catalog.crawl, - thredds.catalog.dl, - thredds.catalog.parser.jdom, - thredds.catalog.query, - thredds.catalog.search, - thredds.catalog.search.ui, - thredds.catalog.ui, - thredds.catalog.ui.query, - thredds.catalog.ui.tools, - thredds.cataloggen, - thredds.cataloggen.catalogrefexpander, - thredds.cataloggen.config, - thredds.cataloggen.datasetenhancer, - thredds.cataloggen.inserter, - thredds.crawlabledataset, - thredds.crawlabledataset.filter, - thredds.crawlabledataset.sorter, - thredds.datamodel.gis, - thredds.datatype, - thredds.datatype.prefs, - thredds.dqc, - thredds.ui, - thredds.util, - thredds.util.net, - thredds.viewer.gis, - thredds.viewer.gis.shapefile, - thredds.viewer.gis.worldmap, - thredds.viewer.ui, - thredds.viewer.ui.event, - thredds.viewer.ui.geoloc, - thredds.viewer.ui.table, - thredds.wcs, - ucar.atd.dorade, - ucar.ma2, - ucar.nc2, - ucar.nc2.adde, - ucar.nc2.dataset, - ucar.nc2.dataset.conv, - ucar.nc2.dataset.grid, - ucar.nc2.dataset.transform, - ucar.nc2.dods, - ucar.nc2.dt, - ucar.nc2.dt.fmr, - ucar.nc2.dt.fmrc, - ucar.nc2.dt.grid, - ucar.nc2.dt.image, - ucar.nc2.dt.point, - ucar.nc2.dt.point.decode, - ucar.nc2.dt.radial, - ucar.nc2.dt.trajectory, - ucar.nc2.geotiff, - ucar.nc2.iosp.bufr, - ucar.nc2.iosp.cinrad, - ucar.nc2.iosp.dmsp, - ucar.nc2.iosp.dorade, - ucar.nc2.iosp.gini, - ucar.nc2.iosp.grib, - ucar.nc2.iosp.nexrad2, - ucar.nc2.iosp.nids, - ucar.nc2.ncml, - ucar.nc2.thredds, - ucar.nc2.thredds.server, - ucar.nc2.ui, - ucar.nc2.ui.grid, - ucar.nc2.ui.image, - ucar.nc2.ui.point, - ucar.nc2.units, - ucar.nc2.util, - ucar.unidata.geoloc, - ucar.unidata.geoloc.projection, - ucar.unidata.geoloc.vertical, - ucar.unidata.io, - ucar.unidata.io.bzip2, - ucar.unidata.io.http, - ucar.unidata.util, - ucar.units, - ucar.util.prefs, - ucar.util.prefs.ui -Bundle-ActivationPolicy: lazy -Require-Bundle: ohd.hseb.ihfsdb, - org.postgres -Bundle-ClassPath: externaljars/bsf.jar, - externaljars/bsh-2.0b4.jar, - externaljars/ChartDirector.jar, - externaljars/fldat.jar, - externaljars/ihfsdb.jar, - externaljars/jcchart.jar, - externaljars/jdom.jar, - externaljars/junit.jar, - externaljars/netcdfUI-2.2.22.jar, - externaljars/nlog4j-1.2.21.jar, - externaljars/postgresql-8.3-603.jdbc3.jar, - . -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: com.raytheon.uf.common.ohd diff --git a/cave/ohd.hseb.common/build.properties b/cave/ohd.hseb.common/build.properties deleted file mode 100644 index 5de4576053..0000000000 --- a/cave/ohd.hseb.common/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - bin/ohd/,\ - externaljars/,\ - dist/,\ - externaljars/bsf.jar,\ - externaljars/bsh-2.0b4.jar,\ - externaljars/ChartDirector.jar,\ - externaljars/fldat.jar,\ - externaljars/ihfsdb.jar,\ - externaljars/jcchart.jar,\ - externaljars/jdom.jar,\ - externaljars/junit.jar,\ - externaljars/netcdfUI-2.2.22.jar,\ - externaljars/nlog4j-1.2.21.jar,\ - externaljars/postgresql-8.3-603.jdbc3.jar -src.includes = externaljars/ diff --git a/cave/ohd.hseb.common/build.xml b/cave/ohd.hseb.common/build.xml deleted file mode 100644 index b3de9350ed..0000000000 --- a/cave/ohd.hseb.common/build.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/cave/ohd.hseb.common/dist/ohd_hseb_common.jar b/cave/ohd.hseb.common/dist/ohd_hseb_common.jar deleted file mode 100644 index e89de3dcf0..0000000000 Binary files a/cave/ohd.hseb.common/dist/ohd_hseb_common.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/ChartDirector.jar b/cave/ohd.hseb.common/externaljars/ChartDirector.jar deleted file mode 100644 index c056a55520..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/ChartDirector.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/bsf.jar b/cave/ohd.hseb.common/externaljars/bsf.jar deleted file mode 100755 index caa4dea709..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/bsf.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/bsh-2.0b4.jar b/cave/ohd.hseb.common/externaljars/bsh-2.0b4.jar deleted file mode 100755 index 36fe03d71c..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/bsh-2.0b4.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/fldat.jar b/cave/ohd.hseb.common/externaljars/fldat.jar deleted file mode 100755 index c3cb6a36fc..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/fldat.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/ihfsdb.jar b/cave/ohd.hseb.common/externaljars/ihfsdb.jar deleted file mode 100644 index d0b4e43783..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/ihfsdb.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/jcchart.jar b/cave/ohd.hseb.common/externaljars/jcchart.jar deleted file mode 100644 index 6b7a797954..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/jcchart.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/jdom.jar b/cave/ohd.hseb.common/externaljars/jdom.jar deleted file mode 100644 index 288e64cb5c..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/jdom.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/junit.jar b/cave/ohd.hseb.common/externaljars/junit.jar deleted file mode 100644 index e0c7ded869..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/junit.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/netcdfUI-2.2.22.jar b/cave/ohd.hseb.common/externaljars/netcdfUI-2.2.22.jar deleted file mode 100644 index aa8c22cfd1..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/netcdfUI-2.2.22.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/nlog4j-1.2.21.jar b/cave/ohd.hseb.common/externaljars/nlog4j-1.2.21.jar deleted file mode 100644 index c0fc307783..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/nlog4j-1.2.21.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/externaljars/postgresql-8.3-603.jdbc3.jar b/cave/ohd.hseb.common/externaljars/postgresql-8.3-603.jdbc3.jar deleted file mode 100644 index a9156e958b..0000000000 Binary files a/cave/ohd.hseb.common/externaljars/postgresql-8.3-603.jdbc3.jar and /dev/null differ diff --git a/cave/ohd.hseb.common/ohd.hseb.common.ecl b/cave/ohd.hseb.common/ohd.hseb.common.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDataMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDataMgr.java deleted file mode 100644 index a2f374bb41..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDataMgr.java +++ /dev/null @@ -1,658 +0,0 @@ -package ohd.hseb.bias_trans; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.RWBiasDynRecord; -import ohd.hseb.ihfsdb.generated.RWBiasDynTable; -import ohd.hseb.ihfsdb.generated.RWBiasStatRecord; -import ohd.hseb.ihfsdb.generated.RWBiasStatTable; -import ohd.hseb.ihfsdb.generated.RadarLocRecord; -import ohd.hseb.ihfsdb.generated.RadarLocTable; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -/** - * - * This class is the bridge between the database and the radar bias message for - * the BiasMessageCreator and the BiasMessageReader programs. - * - * @author lawrence - * - */ - -public class BiasDataMgr implements RfcBiasConstants { - private Database _db; - - // private DataOutputStream _outFile; - private File _file; - - private String _fxaLocalSite; - - private String _jdbcUrl; - - private String _rfcId; - - private String _fileName; - - private String _outputFilePath; - - private final String RFC_BIAS_MESSAGE_DIR_TOK = "rfc_bias_output_dir"; - - private final String FXA_LOCAL_SITE_TOK = "FXA_LOCAL_SITE"; - - private List _radarIdList = null; - - public BiasDataMgr(String jdbcUrl) throws Exception { - _jdbcUrl = jdbcUrl; - - _db = new Database(); - - // Create a database connection. - _db.connectWithDriverSearch(_jdbcUrl); - - // Get Tokens needed for queries and to build the file path. - getBiasTokens(); - - } - - public RadarBias getRadarBias(String dateTime) throws Exception { - RadarBias radarBias = new RadarBias(); - radarBias.setDateTime(dateTime); - radarBias.setMemorySpanGroup(getMemorySpanGroup()); - List radarIdList = getRadarIdList(); - radarBias - .setBiasDynGroupList(getBiasDynGroupList(radarIdList, dateTime)); - return radarBias; - } - - private DataOutputStream openOutputFile(String dateTime) - throws FileNotFoundException { - DataOutputStream outFile = null; - - // Create the file path - _fileName = _rfcId + dateTime + "z"; - File file = new File(_outputFilePath, _fileName); - - // Open the bias message file. - try { - outFile = new DataOutputStream(new BufferedOutputStream( - new FileOutputStream(file))); - } catch (FileNotFoundException e) { - System.out.println("Could not open file " + file.toString()); - throw e; - } - - System.out.println("Opened file " + file.toString()); - - return outFile; - } - - private DataInputStream openInputFile(File filePath) - throws FileNotFoundException { - DataInputStream inputStream = null; - - try { - _file = filePath; - inputStream = new DataInputStream(new BufferedInputStream( - new FileInputStream(filePath))); - } catch (FileNotFoundException e) { - System.out.println("Could not open file " + filePath.toString()); - throw e; - } - - System.out.println("Opened file " + filePath.toString()); - return inputStream; - } - - private void getBiasTokens() throws Exception { - AppsDefaults apps_defaults = AppsDefaults.getInstance(); - String token; - - token = apps_defaults.getToken(RFC_BIAS_MESSAGE_DIR_TOK); - - if (token == null || token.length() == 0) { - String message = "Token " + RFC_BIAS_MESSAGE_DIR_TOK - + " not defined."; - throw new Exception(message); - } - - _outputFilePath = token; - - token = apps_defaults.getToken(FXA_LOCAL_SITE_TOK); - - if (token == null || token.length() == 0) { - String message = "Token " + FXA_LOCAL_SITE_TOK + " not defined."; - throw new Exception(message); - } - - _rfcId = token.toUpperCase(); - _fxaLocalSite = _rfcId; - } - - private MemorySpanGroup getMemorySpanGroup() throws Exception { - List biasStatList = null; - RWBiasStatTable biasStat = new RWBiasStatTable(_db); - RWBiasStatRecord record = null; - MemorySpanGroup rwBiasStat = null; - - try { - biasStatList = biasStat.select("WHERE office_id = '" - + _fxaLocalSite + "'"); - - if (!biasStatList.isEmpty()) { - record = (RWBiasStatRecord) biasStatList.get(0); - rwBiasStat = getRWBiasStatFromRecord(record); - } else { - throw new Exception("The RWBiasStat table is empty."); - } - } catch (SQLException e) { - System.out.println(e.getMessage()); - throw e; - } - - return rwBiasStat; - } - - private List loadRadarIdList() { - // List recordList = null;; - RadarLocTable table = new RadarLocTable(_db); - List radarIdList = new ArrayList(); - - try { - List recordList = table - .select("WHERE use_radar = 'T' ORDER BY radid ASC"); - - // Iterator iterator = recordList.iterator(); - - // while ( iterator.hasNext()) - for (RadarLocRecord record : recordList) { - // RadarLocRecord record = (RadarLocRecord) iterator.next(); - radarIdList.add(record.getRadid()); - } - } catch (SQLException e) { - System.out.println(e.getMessage()); - return null; - } - - if (radarIdList.size() == 0) { - System.out.println("No radars found in the RadarLoc table."); - } - - return radarIdList; - } - - public Set loadRadarIdSetForGivenOffice() { - List recordList = null; - RadarLocTable table = new RadarLocTable(_db); - Set radarIdSet = new HashSet(); - - try { - recordList = table.select("WHERE use_radar = 'T' AND office_id = '" - + _rfcId + "' ORDER BY radid ASC"); - - Iterator iterator = recordList.iterator(); - - while (iterator.hasNext()) { - RadarLocRecord record = (RadarLocRecord) iterator.next(); - radarIdSet.add(record.getRadid()); - } - } catch (SQLException e) { - System.out.println(e.getMessage()); - return null; - } - - if (radarIdSet.size() == 0) { - System.out.println("No radars found for " + _rfcId - + " in RadarLoc Table."); - } - - return radarIdSet; - } - - // ---------------------------------------------------------------------------------- - private List getBiasDynGroupList(List radarIdList, String _dateTime) { - Iterator biasDynIterator = null; - Iterator radarIdIterator = null; - List recordList = null; - List biasDynGroupList = new ArrayList(); - RWBiasDynRecord record; - RWBiasDynTable table = new RWBiasDynTable(_db); - String obsTime; - String radarId; - - /* - * Format the obstime as YYYY-MM-DD HH:MM:SS for use in the RWBiasDyn - * query. - */ - obsTime = _dateTime.substring(0, NUM_DIGITS_IN_YEAR) - + "-" - + _dateTime.substring(NUM_DIGITS_IN_YEAR, NUM_DIGITS_IN_YEAR - + NUM_DIGITS_IN_MONTH) - + "-" - + _dateTime.substring(NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH, - NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH - + NUM_DIGITS_IN_DAY) - + " " - + _dateTime.substring(NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH - + NUM_DIGITS_IN_DAY, NUM_DIGITS_IN_YEAR - + NUM_DIGITS_IN_MONTH + NUM_DIGITS_IN_DAY - + NUM_DIGITS_IN_HOUR) + ":00:00"; - - radarIdIterator = radarIdList.iterator(); - - while (radarIdIterator.hasNext()) { - List biasDynSetList = new ArrayList(); - radarId = (String) radarIdIterator.next(); - - try { - recordList = table.select("WHERE radid='" + radarId + "' AND " - + " obstime = '" + obsTime + "' AND office_id = '" - + _fxaLocalSite + "' ORDER BY " + "memspan_ind ASC"); - - biasDynIterator = recordList.iterator(); - - while (biasDynIterator.hasNext()) { - record = (RWBiasDynRecord) biasDynIterator.next(); - biasDynSetList.add(getRWBiasDynFromRecord(record)); - } - - } catch (SQLException e) { - System.out.println(e.getMessage()); - return null; - } - - BiasDynGroup biasDynGroup = new BiasDynGroup(); - biasDynGroup.setRadarId(radarId); - biasDynGroup.setBiasDynSetList(biasDynSetList); - biasDynGroupList.add(biasDynGroup); - } - - return biasDynGroupList; - } - - public List getRadarIdList() { - if (_radarIdList == null) { - _radarIdList = loadRadarIdList(); - } - - return _radarIdList; - } - - private MemorySpanGroup getRWBiasStatFromRecord(RWBiasStatRecord record) { - MemorySpanGroup rwBiasStat = new MemorySpanGroup(); - - rwBiasStat.setMinGrValueBias(record.getMin_gr_value_bias()); - rwBiasStat.setNpairBiasSelect(record.getNpair_bias_select()); - rwBiasStat.setNpairSvarUpdate(record.getNpair_svar_update()); - rwBiasStat.setNumSpan(record.getNum_span()); - rwBiasStat.setStdCut(record.getStd_cut()); - rwBiasStat.setBiasQcOpt(record.getBias_qc_opt()); - rwBiasStat.setInitSpan(record.getInit_span()); - rwBiasStat.setLagCut(record.getLag_cut()); - rwBiasStat.setMemSpan1(record.getMem_span1()); - rwBiasStat.setMemSpan2(record.getMem_span2()); - rwBiasStat.setMemSpan3(record.getMem_span3()); - rwBiasStat.setMemSpan4(record.getMem_span4()); - rwBiasStat.setMemSpan5(record.getMem_span5()); - rwBiasStat.setMemSpan6(record.getMem_span6()); - rwBiasStat.setMemSpan7(record.getMem_span7()); - rwBiasStat.setMemSpan8(record.getMem_span8()); - rwBiasStat.setMemSpan9(record.getMem_span9()); - rwBiasStat.setMemSpan10(record.getMem_span10()); - - return rwBiasStat; - } - - private BiasDynSet getRWBiasDynFromRecord(RWBiasDynRecord record) { - BiasDynSet biasDynSet = new BiasDynSet(); - - biasDynSet.setMeanFieldBias(record.getBias()); - biasDynSet.setMemSpanIndex(record.getMemspan_ind()); - biasDynSet.setGageRadarPairCount(record.getNumpairs()); - biasDynSet.setSumOfGageValues(record.getSumgag()); - biasDynSet.setSumOfRadarValues(record.getSumrad()); - - return biasDynSet; - } - - public void writeRadarBiasToFile(RadarBias radarBias, String dateTime) - throws Exception { - // Open the file - DataOutputStream outFile = openOutputFile(dateTime); - - // Write Header - writeHeader(radarBias, dateTime, outFile); - - // Write body - writeBody(radarBias, outFile); - - // Close File - outFile.close(); - } - - private void writeHeader(RadarBias radarBias, String dateTime, - DataOutputStream outFile) throws IOException { - outFile.writeUTF("BIAS"); - outFile.writeUTF(_rfcId); - outFile.writeUTF(dateTime); - MemorySpanGroup memorySpanGroup = radarBias.getMemorySpanGroup(); - outFile.writeFloat(memorySpanGroup.getMinGrValueBias()); - outFile.writeInt(memorySpanGroup.getNpairBiasSelect()); - outFile.writeInt(memorySpanGroup.getNpairSvarUpdate()); - outFile.writeInt(memorySpanGroup.getStdCut()); - outFile.writeInt(memorySpanGroup.getLagCut()); - outFile.writeInt(memorySpanGroup.getInitSpan()); - outFile.writeInt(memorySpanGroup.getBiasQcOpt()); - outFile.writeInt(memorySpanGroup.getNumSpan()); - outFile.writeFloat(memorySpanGroup.getMemSpan1()); - outFile.writeFloat(memorySpanGroup.getMemSpan2()); - outFile.writeFloat(memorySpanGroup.getMemSpan3()); - outFile.writeFloat(memorySpanGroup.getMemSpan4()); - outFile.writeFloat(memorySpanGroup.getMemSpan5()); - outFile.writeFloat(memorySpanGroup.getMemSpan6()); - outFile.writeFloat(memorySpanGroup.getMemSpan7()); - outFile.writeFloat(memorySpanGroup.getMemSpan8()); - outFile.writeFloat(memorySpanGroup.getMemSpan9()); - outFile.writeFloat(memorySpanGroup.getMemSpan10()); - } - - private void writeBody(RadarBias radarBias, DataOutputStream outFile) - throws IOException { - List biasDynGroupList = radarBias.getBiasDynGroupList(); - - for (int i = 0; i < biasDynGroupList.size(); ++i) { - BiasDynGroup biasDynGroup = (BiasDynGroup) biasDynGroupList.get(i); - outFile.writeUTF(biasDynGroup.getRadarId()); - - List biasDynSetList = biasDynGroup.getBiasDynSetList(); - - outFile.writeInt(biasDynSetList.size()); - - for (int j = 0; j < biasDynSetList.size(); ++j) { - BiasDynSet biasDynSet = (BiasDynSet) biasDynSetList.get(j); - - outFile.writeShort(biasDynSet.getMemSpanIndex()); - outFile.writeDouble(biasDynSet.getGageRadarPairCount()); - outFile.writeFloat(biasDynSet.getSumOfGageValues()); - outFile.writeFloat(biasDynSet.getSumOfRadarValues()); - outFile.writeFloat(biasDynSet.getMeanFieldBias()); - } - - } - - } - - private void readHeader(DataInputStream inputStream, RadarBias radarBias) - throws IOException { - String biasIndicator; - - try { - biasIndicator = inputStream.readUTF(); - - if (biasIndicator.compareTo("BIAS") != 0) { - throw new IOException("Invalid bias message indicator field " - + biasIndicator); - } - - _rfcId = inputStream.readUTF(); - - /* - * If, for some reason, this message originated from this office do - * not process any further. - */ - System.out.println("RFC ID " + _rfcId + " FXA_LOCAL_SITE " - + _fxaLocalSite); - - if (_rfcId.compareTo(_fxaLocalSite) == 0) { - throw new IOException(_file.getPath() - + " originated from this office - " + _fxaLocalSite - + "\nThis file will not be processed."); - } - - radarBias.setDateTime(inputStream.readUTF()); - - MemorySpanGroup memorySpanGroup = new MemorySpanGroup(); - - memorySpanGroup.setMinGrValueBias(inputStream.readFloat()); - memorySpanGroup.setNpairBiasSelect(inputStream.readInt()); - memorySpanGroup.setNpairSvarUpdate(inputStream.readInt()); - memorySpanGroup.setStdCut(inputStream.readInt()); - memorySpanGroup.setLagCut(inputStream.readInt()); - memorySpanGroup.setInitSpan(inputStream.readInt()); - memorySpanGroup.setBiasQcOpt(inputStream.readInt()); - memorySpanGroup.setNumSpan(inputStream.readInt()); - memorySpanGroup.setMemSpan1(inputStream.readFloat()); - memorySpanGroup.setMemSpan2(inputStream.readFloat()); - memorySpanGroup.setMemSpan3(inputStream.readFloat()); - memorySpanGroup.setMemSpan4(inputStream.readFloat()); - memorySpanGroup.setMemSpan5(inputStream.readFloat()); - memorySpanGroup.setMemSpan6(inputStream.readFloat()); - memorySpanGroup.setMemSpan7(inputStream.readFloat()); - memorySpanGroup.setMemSpan8(inputStream.readFloat()); - memorySpanGroup.setMemSpan9(inputStream.readFloat()); - memorySpanGroup.setMemSpan10(inputStream.readFloat()); - - radarBias.setMemorySpanGroup(memorySpanGroup); - } catch (IOException e) { - e.printStackTrace(); - throw e; - } - } - - /** - * @param inputStream - * @param radarBias - */ - private void readBody(DataInputStream inputStream, RadarBias radarBias) - throws IOException { - boolean completeGroup = true; - int biasSetSize; - - /* List biasDynGroupList = radarBias.getBiasDynGroupList(); */ - ArrayList biasDynGroupList = new ArrayList(); - - try { - while (true) { - BiasDynGroup biasDynGroup = new BiasDynGroup(); - - /* Read a Radar Id. Are there any left? */ - biasDynGroup.setRadarId(inputStream.readUTF()); - completeGroup = false; - biasSetSize = inputStream.readInt(); - ArrayList biasDynSetList = new ArrayList(); - - for (int i = 0; i < biasSetSize; ++i) { - BiasDynSet biasDynSet = new BiasDynSet(); - biasDynSet.setMemSpanIndex(inputStream.readShort()); - biasDynSet.setGageRadarPairCount(inputStream.readDouble()); - biasDynSet.setSumOfGageValues(inputStream.readFloat()); - biasDynSet.setSumOfRadarValues(inputStream.readFloat()); - biasDynSet.setMeanFieldBias(inputStream.readFloat()); - - biasDynSetList.add(biasDynSet); - } - - completeGroup = true; - biasDynGroup.setBiasDynSetList(biasDynSetList); - biasDynGroupList.add(biasDynGroup); - } - } catch (EOFException e) { - if (!completeGroup) { - throw new IOException("Error reading bias message file"); - } - - } - - radarBias.setBiasDynGroupList(biasDynGroupList); - } - - public RadarBias readRadarBiasFromFile(File filePath) throws Exception { - RadarBias radarBias = new RadarBias(); - - // Attempt to open the input file. - DataInputStream inputStream = openInputFile(filePath); - - // Read the file header. - readHeader(inputStream, radarBias); - - // Read the file body. - readBody(inputStream, radarBias); - - inputStream.close(); - - return radarBias; - } - - public void writeRadarBiasToDatabase(RadarBias radarBias) throws Exception { - /* Retrieve the list of offices for which to process bias information. */ - Set radarIdSet = loadRadarIdSetForGivenOffice(); - - if (radarIdSet.size() != 0) { - - /* Write to the RWBiasStat table. */ - writeMemorySpanGroup(radarBias); - - /* Write to the RWBiasDyn table. */ - writeBiasDynSet(radarBias, radarIdSet); - } else { - System.out.println("No radars to process for office " + _rfcId - + "."); - } - } - - private void writeMemorySpanGroup(RadarBias radarBias) throws Exception { - /* - * The memory span data from the RadarBias object to the RWBiasStat - * Record. - */ - RWBiasStatRecord record = null; - - try { - RWBiasStatTable table = new RWBiasStatTable(_db); - record = getRecordFromMemorySpan(radarBias.getMemorySpanGroup()); - table.insertOrUpdate(record); - } catch (SQLException e) { - System.out - .println("Could not insert/update record in RWBiasStat table."); - throw e; - } - } - - private void writeBiasDynSet(RadarBias radarBias, Set radarIdSet) - throws Exception { - RWBiasDynRecord record = null; - List biasDynGroupList = radarBias.getBiasDynGroupList(); - List biasDynSetList = null; - BiasDynSet biasDynSet = null; - - BiasDynGroup biasDynGroup = null; - - try { - RWBiasDynTable table = new RWBiasDynTable(_db); - - /* Construct the obstime into the proper format. */ - String obstimeYYYYMMDD = radarBias.getDateTime(); - String obstimeSQL = obstimeYYYYMMDD - .substring(0, NUM_DIGITS_IN_YEAR) - + "-" - + obstimeYYYYMMDD.substring(NUM_DIGITS_IN_YEAR, - NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH) - + "-" - + obstimeYYYYMMDD.substring(NUM_DIGITS_IN_YEAR - + NUM_DIGITS_IN_MONTH, NUM_DIGITS_IN_YEAR - + NUM_DIGITS_IN_MONTH + NUM_DIGITS_IN_DAY) - + " " - + obstimeYYYYMMDD.substring(NUM_DIGITS_IN_YEAR - + NUM_DIGITS_IN_MONTH + NUM_DIGITS_IN_DAY, - NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH - + NUM_DIGITS_IN_DAY + NUM_DIGITS_IN_HOUR) - + ":00:00"; - - // System.out.println("obstimeSQL:" + obstimeSQL); - - for (int i = 0; i < biasDynGroupList.size(); ++i) { - biasDynGroup = (BiasDynGroup) biasDynGroupList.get(i); - - /* Check if this BiasDyn group radar is in the radar map. */ - if (radarIdSet.contains(biasDynGroup.getRadarId())) { - biasDynSetList = biasDynGroup.getBiasDynSetList(); - - for (int j = 0; j < biasDynSetList.size(); ++j) { - biasDynSet = (BiasDynSet) biasDynSetList.get(j); - record = getRecordFromBiasDynSet(biasDynGroup - .getRadarId(), obstimeSQL, biasDynSet); - table.insertOrUpdate(record); - } - } else { - System.out.println("Bias information from office " + _rfcId - + " not stored for Radar " - + biasDynGroup.getRadarId() + "."); - } - } - } catch (SQLException e) { - System.out.println("Could not insert/update the RWBiasDynTable."); - throw e; - } - } - - private RWBiasStatRecord getRecordFromMemorySpan( - MemorySpanGroup memorySpanGroup) { - RWBiasStatRecord record = new RWBiasStatRecord(); - - record.setBias_qc_opt(memorySpanGroup.getBiasQcOpt()); - record.setInit_span(memorySpanGroup.getInitSpan()); - record.setLag_cut(memorySpanGroup.getLagCut()); - record.setMem_span1(memorySpanGroup.getMemSpan1()); - record.setMem_span2(memorySpanGroup.getMemSpan2()); - record.setMem_span3(memorySpanGroup.getMemSpan3()); - record.setMem_span4(memorySpanGroup.getMemSpan4()); - record.setMem_span5(memorySpanGroup.getMemSpan5()); - record.setMem_span6(memorySpanGroup.getMemSpan6()); - record.setMem_span7(memorySpanGroup.getMemSpan7()); - record.setMem_span8(memorySpanGroup.getMemSpan8()); - record.setMem_span9(memorySpanGroup.getMemSpan9()); - record.setMem_span10(memorySpanGroup.getMemSpan10()); - record.setMin_gr_value_bias(memorySpanGroup.getMinGrValueBias()); - record.setNpair_bias_select(memorySpanGroup.getNpairBiasSelect()); - record.setNpair_svar_update(memorySpanGroup.getNpairSvarUpdate()); - record.setNum_span(memorySpanGroup.getNumSpan()); - record.setStd_cut(memorySpanGroup.getStdCut()); - record.setOffice_id(_rfcId); - - return record; - } - - private RWBiasDynRecord getRecordFromBiasDynSet(String radarId, - String obstimeSQL, BiasDynSet biasDynSet) { - RWBiasDynRecord record = new RWBiasDynRecord(); - - record.setBias(biasDynSet.getMeanFieldBias()); - record.setMemspan_ind(biasDynSet.getMemSpanIndex()); - record.setNumpairs(biasDynSet.getGageRadarPairCount()); - record.setObstime(DbTimeHelper - .getLongTimeFromDateTimeString(obstimeSQL)); - record.setRadid(radarId); - record.setSumgag(biasDynSet.getSumOfGageValues()); - record.setSumrad(biasDynSet.getSumOfRadarValues()); - record.setOffice_id(_rfcId); - - return record; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDynGroup.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDynGroup.java deleted file mode 100644 index 874f7b4a12..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDynGroup.java +++ /dev/null @@ -1,46 +0,0 @@ -package ohd.hseb.bias_trans; -import java.util.List; - -public class BiasDynGroup -{ - private String _radarId; - private List _biasDynSetList; - - public BiasDynGroup ( ) - { - } - - public void setRadarId(String radarId) - { - _radarId = radarId; - } - - public String getRadarId() - { - return _radarId; - } - - public void setBiasDynSetList(List biasDynSetList) - { - _biasDynSetList = biasDynSetList; - } - - public List getBiasDynSetList() - { - return _biasDynSetList; - } - - public String toString () - { - - StringBuffer outputBuffer = new StringBuffer ("_radarId = " + _radarId +"\n"); - - - for ( int i = 0; i < _biasDynSetList.size(); ++i ) - { - outputBuffer.append ( _biasDynSetList.get(i)); - } - - return outputBuffer.toString(); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDynSet.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDynSet.java deleted file mode 100644 index f72d832e8c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasDynSet.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.bias_trans; - -public class BiasDynSet -{ - private short _memSpanIndex; /* usually 0 - 9. */ - private double _gageRadarPairCount; - private float _sumOfGageValues; - private float _sumOfRadarValues; - private float _meanFieldBias; - - public void setMemSpanIndex(short memSpanIndex) - { - _memSpanIndex = memSpanIndex; - } - - public short getMemSpanIndex() - { - return _memSpanIndex; - } - - public void setGageRadarPairCount(double numPairs) - { - _gageRadarPairCount = numPairs; - } - - public double getGageRadarPairCount() - { - return _gageRadarPairCount; - } - - public void setSumOfGageValues(float sumGag) - { - _sumOfGageValues = sumGag; - } - - public float getSumOfGageValues() - { - return _sumOfGageValues; - } - - public void setSumOfRadarValues(float sumRad) - { - _sumOfRadarValues = sumRad; - } - - public float getSumOfRadarValues() - { - return _sumOfRadarValues; - } - - public void setMeanFieldBias(float bias) - { - _meanFieldBias = bias; - } - - public float getMeanFieldBias() - { - return _meanFieldBias; - } - - public String toString () - { - String output = "_memspanInd = " + _memSpanIndex + " _numPairs = " + _gageRadarPairCount + " " + - " _sumGag = " + _sumOfGageValues + " _sumRad = " + _sumOfRadarValues + " _bias = " + _meanFieldBias + "\n"; - return output; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasMessageCreator.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasMessageCreator.java deleted file mode 100644 index 4521c1d030..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasMessageCreator.java +++ /dev/null @@ -1,123 +0,0 @@ -package ohd.hseb.bias_trans; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; - -public class BiasMessageCreator -{ - public static final String VERSION = "OB82"; - public static final String RELEASE_DATE = "April 11, 2007"; - public static final String PROGRAM_NAME = "BiasMessageCreator"; - - private static final String _usage = "Usage: " + PROGRAM_NAME + - " "; - - private BiasDataMgr _dataMgr = null; - - private String _dateTime; // YYYYMMDDHH - private String _jdbcUrl; - // ----------------------------------------------------------------------------------------------------- - - public BiasMessageCreator ( String[] args ) throws Exception - { - getBiasArguments ( args ); - - // Create the data manager - setDataMgr( new BiasDataMgr ( _jdbcUrl )); - } - // ----------------------------------------------------------------------------------------------------- - - private void getBiasArguments ( String args [ ]) throws Exception - { - boolean failed = false; - int datetimeAsInteger; - - if ( args.length != 2) - { - failed = true; - } - else - { - - // Process the database name supplied as the first argument. - _jdbcUrl = args[0]; - _dateTime = args[1]; - - // Make sure the time string is the correct length. - if ( _dateTime.length() != RfcBiasConstants.DATEHOUR_LENGTH ) - { - failed = true; - } - - // Make sure the time string is an integer. - try - { - datetimeAsInteger = Integer.parseInt(_dateTime); - } - catch ( NumberFormatException e) - { - failed = true; - } - } - - if ( failed ) - { - throw new Exception (_usage); - } - } - // ----------------------------------------------------------------------------------------------------- - - private void setDataMgr(BiasDataMgr dataMgr) - { - _dataMgr = dataMgr; - } - // ----------------------------------------------------------------------------------------------------- - - private BiasDataMgr getDataMgr() - { - return _dataMgr; - } - // ----------------------------------------------------------------------------------------------------- - - public void process () throws Exception - { - RadarBias radarBias = _dataMgr.getRadarBias( _dateTime ); - - System.out.println ("Bias Message Retrieved.\n" + radarBias ); - - _dataMgr.writeRadarBiasToFile ( radarBias, _dateTime ); - } - // ----------------------------------------------------------------------------------------------------- - /** - * @param args - */ - public static void main(String[] args) - { - long startingTime = System.currentTimeMillis(); - String startingTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startingTime); - - System.out.println("The Starting Time is: " + startingTimeString); - try - { - CodeTimer codeTimer = new CodeTimer(); - codeTimer.start(); - - BiasMessageCreator messageCreator = new BiasMessageCreator( args); - - System.out.println("Starting Program " + PROGRAM_NAME ); - System.out.println("Version: " + VERSION + " Release Date: " + - RELEASE_DATE ); - - messageCreator.process(); - - codeTimer.stop("Create_rfc_bias_message completed in "); - - } - catch ( Exception e) - { - - System.out.println (e.getMessage()); - System.out.println (e.getStackTrace()); - } - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasMessageReader.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasMessageReader.java deleted file mode 100644 index 22ff9439c3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/BiasMessageReader.java +++ /dev/null @@ -1,106 +0,0 @@ -package ohd.hseb.bias_trans; - -import java.io.File; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; - -public class BiasMessageReader -{ - private static final String VERSION = "OB82"; - private static final String RELEASE_DATE = "April 11, 2007"; - private static final String PROGRAM_NAME = "BiasMessageReader"; - - private static final String _usage = "Usage: " + PROGRAM_NAME + - " "; - - private BiasDataMgr _dataMgr = null; - private String _jdbcUrl = null; - private File _filePath = null; - - public BiasMessageReader ( String[] args, String PROGRAM_NAME ) throws Exception - { - getBiasArguments ( args, PROGRAM_NAME); - - // Create the data manager - setDataMgr( new BiasDataMgr ( _jdbcUrl )); - } - - /** - * @param args - */ - private void getBiasArguments ( String args [ ], final String program_name ) throws Exception - { - boolean failed = false; - - if (args.length != 2) - { - failed = true; - } - else - { - // Process the database name supplied via the -d argument. - _jdbcUrl = args[0]; - - // Process the filename/path supplied via the -f argument. - - _filePath = new File ( args[1] ); - System.out.println ("File path for file reader = " + _filePath); - } - - if ( failed ) - { - throw new Exception (_usage); - } - } - - public void process ( ) throws Exception - { - RadarBias radarBias = _dataMgr.readRadarBiasFromFile ( _filePath ); - - System.out.println ("Bias Message Retrieved.\n" + radarBias ); - - _dataMgr.writeRadarBiasToDatabase ( radarBias ); - } - - public static void main(String[] args) - { - long startingTime = System.currentTimeMillis(); - String startingTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startingTime); - System.out.println("The Starting Time is: " + startingTimeString); - - try - { - CodeTimer codeTimer = new CodeTimer(); - codeTimer.start(); - - BiasMessageReader messageReader = new BiasMessageReader( args, PROGRAM_NAME); - - System.out.println("Starting Program " + PROGRAM_NAME ); - System.out.println("Version: " + VERSION + " Release Date: " + - RELEASE_DATE ); - - messageReader.process(); - - codeTimer.stop("process_rfc_bias_message completed in "); - } - catch ( Exception e) - { - System.out.println (e.getMessage()); - System.out.println (e.getStackTrace()); - } - - } - - public void setDataMgr(BiasDataMgr dataMgr) - { - _dataMgr = dataMgr; - } - - public BiasDataMgr getDataMgr() - { - return _dataMgr; - } - -} - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/MemorySpanGroup.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/MemorySpanGroup.java deleted file mode 100644 index dd2aed58f8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/MemorySpanGroup.java +++ /dev/null @@ -1,224 +0,0 @@ -package ohd.hseb.bias_trans; - -public class MemorySpanGroup -{ - private float _minGrValueBias; - private int _npairBiasSelect; - private int _npairSvarUpdate; - private int _stdCut; - private int _lagCut; - private int _initSpan; - private int _biasQcOpt; - private int _numSpan; - private float _memSpan1; - private float _memSpan2; - private float _memSpan3; - private float _memSpan4; - private float _memSpan5; - private float _memSpan6; - private float _memSpan7; - private float _memSpan8; - private float _memSpan9; - private float _memSpan10; - - public MemorySpanGroup ( ) - { - } - - public void setMinGrValueBias(float minGrValueBias) - { - this._minGrValueBias = minGrValueBias; - } - public float getMinGrValueBias() - { - return _minGrValueBias; - } - - public void setNpairBiasSelect(int npairBiasSelect) - { - this._npairBiasSelect = npairBiasSelect; - } - - public int getNpairBiasSelect() - { - return _npairBiasSelect; - } - - public void setNpairSvarUpdate(int npairSvarUpdate) - { - this._npairSvarUpdate = npairSvarUpdate; - } - - public int getNpairSvarUpdate() - { - return _npairSvarUpdate; - } - - public void setStdCut(int stdCut) - { - this._stdCut = stdCut; - } - - public int getStdCut() - { - return _stdCut; - } - - public void setLagCut(int lagCut) - { - this._lagCut = lagCut; - } - - public int getLagCut() - { - return _lagCut; - } - - public void setInitSpan(int initSpan) - { - this._initSpan = initSpan; - } - - public int getInitSpan() - { - return _initSpan; - } - - public void setBiasQcOpt(int biasQcOpt) - { - this._biasQcOpt = biasQcOpt; - } - - public int getBiasQcOpt() - { - return _biasQcOpt; - } - - public void setNumSpan(int numSpan) - { - this._numSpan = numSpan; - } - - public int getNumSpan() - { - return _numSpan; - } - - public void setMemSpan1(float memSpan1) - { - this._memSpan1 = memSpan1; - } - - public float getMemSpan1() - { - return _memSpan1; - } - - public void setMemSpan2(float memSpan2) - { - this._memSpan2 = memSpan2; - } - - public float getMemSpan2() - { - return _memSpan2; - } - - public void setMemSpan3(float memSpan3) - { - this._memSpan3 = memSpan3; - } - - public float getMemSpan3() - { - return _memSpan3; - } - - public void setMemSpan4(float memSpan4) - { - this._memSpan4 = memSpan4; - } - - public float getMemSpan4() - { - return _memSpan4; - } - - public void setMemSpan5(float memSpan5) - { - this._memSpan5 = memSpan5; - } - - public float getMemSpan5() - { - return _memSpan5; - } - - public void setMemSpan6(float memSpan6) - { - this._memSpan6 = memSpan6; - } - - public float getMemSpan6() - { - return _memSpan6; - } - - public void setMemSpan7(float memSpan7) - { - this._memSpan7 = memSpan7; - } - - public float getMemSpan7() - { - return _memSpan7; - } - - public void setMemSpan8(float memSpan8) - { - this._memSpan8 = memSpan8; - } - - public float getMemSpan8() - { - return _memSpan8; - } - - public void setMemSpan9(float memSpan9) - { - this._memSpan9 = memSpan9; - } - - public float getMemSpan9() - { - return _memSpan9; - } - - public void setMemSpan10(float memSpan10) - { - this._memSpan10 = memSpan10; - } - - public float getMemSpan10() - { - return _memSpan10; - } - - public String toString ( ) - { - String output; - output = "Memory Span Info:\n"; - output += "_minGrValueBias = " + _minGrValueBias + "\n" + "_npairBiasSelect = " + _npairBiasSelect +"\n"; - output += "_npairSvarUpdate = " + _npairSvarUpdate + "\n" + "_stdCut = " + _stdCut + "\n"; - output += "_lagCut = " + _lagCut + "\n" + "_initSpan = " + _initSpan + "\n"; - output += "_biasQcOpt = " + _biasQcOpt + "\n" + "_numSpan = " + _numSpan + "\n"; - output += "_memSpan1 = " + _memSpan1 + "\n" + "_memSpan2 = " + _memSpan2 + "\n"; - output += "_memSpan3 = " + _memSpan3 + "\n" + "_memSpan4 = " + _memSpan4 + "\n"; - output += "_memSpan5 = " + _memSpan5 + "\n" + "_memSpan6 = " + _memSpan6 + "\n"; - output += "_memSpan7 = " + _memSpan7 + "\n" + "_memSpan8 = " + _memSpan8 + "\n"; - output += "_memSpan9 = " + _memSpan9 + "\n" + "_memSpan10 = " + _memSpan10 + "\n"; - - return output; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RadarBias.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RadarBias.java deleted file mode 100644 index db3a5d8c19..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RadarBias.java +++ /dev/null @@ -1,53 +0,0 @@ -package ohd.hseb.bias_trans; - -import java.util.List; - -public class RadarBias -{ - private String _dateTime; - private MemorySpanGroup _memorySpanGroup; - private List _biasDynGroupList; - - public void setMemorySpanGroup(MemorySpanGroup memorySpanGroup) - { - _memorySpanGroup = memorySpanGroup; - } - - public MemorySpanGroup getMemorySpanGroup() - { - return _memorySpanGroup; - } - - public void setBiasDynGroupList(List biasDynGroupList) - { - _biasDynGroupList = biasDynGroupList; - } - - public List getBiasDynGroupList() - { - return _biasDynGroupList; - } - - public String toString () - { - String output ="Radar Bias Info: " + "\nDate:" + _dateTime +"\n" + _memorySpanGroup; - - for ( int i = 0; i < _biasDynGroupList.size(); ++i ) - { - output += _biasDynGroupList.get(i); - } - - return output; - } - - public void setDateTime(String dateTime) - { - _dateTime = dateTime; - } - - public String getDateTime() - { - return _dateTime; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RfcBiasConstants.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RfcBiasConstants.java deleted file mode 100644 index 1cd499ad85..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RfcBiasConstants.java +++ /dev/null @@ -1,10 +0,0 @@ -package ohd.hseb.bias_trans; - -public interface RfcBiasConstants -{ - public final int DATEHOUR_LENGTH = 10; - public final int NUM_DIGITS_IN_YEAR = 4; - public final int NUM_DIGITS_IN_MONTH = 2; - public final int NUM_DIGITS_IN_DAY = 2; - public final int NUM_DIGITS_IN_HOUR = 2; -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RfcBiasMessage.java b/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RfcBiasMessage.java deleted file mode 100644 index f4af3361d6..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/bias_trans/RfcBiasMessage.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.bias_trans; - - -public class RfcBiasMessage implements RfcBiasConstants -{ - - public RfcBiasMessage ( ) - { - } - - int write_bias_message ( BiasDataMgr dataMgr ) - { - - write_bias_message_header ( dataMgr ); - - // Retrieve the list of radars to get bias information for. - write_bias_message_header ( dataMgr ); - write_bias_message_body ( dataMgr ); - - return 0; - } - - private int write_bias_message_header ( BiasDataMgr dataMgr ) - { - return 0; - } - - private int write_bias_message_body ( BiasDataMgr dataMgr ) - { - return 0; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorChooserDialog.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorChooserDialog.java deleted file mode 100644 index 1dec7f9f65..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorChooserDialog.java +++ /dev/null @@ -1,2301 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; - -public class ColorChooserDialog extends JDialog implements Runnable -{ - - private static boolean _isRunning = false; - private static Thread _thread = null; - private static long _lastUpdateTime = 0; - - private Container _frameContentPane = getContentPane(); - - private JTabbedPane _tabbedPane = new JTabbedPane(); - private JPanel _tabbedPanePanel = new JPanel( new GridBagLayout() ); - private JComponent _viewPanelTab = new JPanel( new GridBagLayout() ); - private JComponent _editPanelTab = new JPanel( new GridBagLayout() ); - - private JPanel _viewTabComboBoxPanel = new JPanel( new GridBagLayout() ); - private JPanel _editTabComboBoxPanel = new JPanel( new GridBagLayout() ); - private JPanel _viewTabColorsDisplayPanel = new JPanel( new GridBagLayout() ); - - private String[] _setComboBoxString = { "default", "user", "office" }; - private JPanel _viewTabSetComboBoxPanel = new JPanel( new GridBagLayout() ); - private JLabel _viewTabSetComboBoxLabel = new JLabel( "Source" ); - private JLabel _viewTabUsedColorsSetLabel = new JLabel( "" ); - private JLabel _editTabUsedColorsSetLabel = new JLabel( "" ); - private JPanel _viewTabUserIDComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _viewTabUserIDComboBox = new JComboBox(); - private JLabel _viewTabUserIDLabel = new JLabel( "User ID" ); - private JPanel _viewTabColorUseComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _viewTabColorUseComboBox = null; - private JLabel _viewTabColorUseLabel = new JLabel( "Data Type" ); - private String[] _viewTabDurationComboBoxInteger = { "0" }; - private JComboBox _viewTabDurationComboBox = new JComboBox ( _viewTabDurationComboBoxInteger ); - private JPanel _viewTabDurationPanel = new JPanel( new GridBagLayout() ); - private JLabel _viewTabDurationLabel = new JLabel( "Duration" ); - private JLabel _viewTabDurationUnitsLabel = new JLabel( "Hrs" ); - - private JPanel _editTabSetComboBoxPanel = new JPanel( new GridBagLayout() ); - private JLabel _editTabSetComboBoxLabel = new JLabel( "Source" ); - private JComboBox _editTabSetComboBox = new JComboBox( _setComboBoxString ); - private JPanel _editTabUserIDComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _editTabUserIDComboBox = new JComboBox(); - private JLabel _editTabUserIDLabel = new JLabel( "User ID" ); - private JPanel _editTabColorUseComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _editTabColorUseComboBox = null; - private JLabel _editTabColorUseLabel = new JLabel( "Data Type" ); - private String[] _editTabDurationComboBoxDouble = { "0" }; - private JComboBox _editTabDurationComboBox = new JComboBox ( _editTabDurationComboBoxDouble ); - private JPanel _editTabDurationPanel = new JPanel( new GridBagLayout() ); - private JLabel _editTabDurationLabel = new JLabel( "Duration" ); - private JLabel _editTabDurationUnitsLabel = new JLabel( "Hrs" ); - - private JComboBox _editTabSaveAsColorUseComboBox = null; - private JLabel _editTabSaveAsLabel = new JLabel( "Save for datatype:" ); - - private JPanel _editTabModifyColorScaleValueSetPanel = new JPanel( new GridBagLayout() ); - private JPanel _editTabColor = new JPanel(); - private JTextField _editTabScaleValue = new JTextField(); - private JButton _editTabAddColorSet = new JButton( "
Add/Update
Color-Value
Pair
" ); - private JButton _editTabDeleteColorSet = new JButton( "
Delete Color-Value
Pair
" ); - - private JPanel _editTabButtonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAsUserButton = null; - private JButton _saveAsOfficeButton = new JButton( "
Save
as office
" ); - private JButton _deleteUserButton = null; - private JButton _deleteOfficeButton = new JButton( "
Delete
as office
"); - - private JPanel _editTabColorsDisplayPanel = new JPanel( new GridBagLayout() ); - private JPanel _editTabUsedColorsDisplayPanel = new JPanel( new GridBagLayout() ); - - private JPanel _viewTabCloseButtonPanel = new JPanel( new GridBagLayout() ); - private JButton _closeButton = new JButton( "Close" ); - - private JPanel _viewTabVCRButtonColorPanel = new JPanel( new GridBagLayout() ); - private JButton _viewTabVCRLeftColorButton = new JButton( "\u25C4"); - private JButton _viewTabVCRRightColorButton = new JButton( "\u25BA"); - - private JButton _editTabResetColorButton = new JButton( "Undo Unsaved Changes"); - - private JPanel _editTabVCRButtonScaleValuePanel = new JPanel( new GridBagLayout() ); - private JButton _editTabVCRLeftScaleValueButton = new JButton( "\u25C4"); - private JButton _editTabVCRRightScaleValueButton = new JButton( "\u25BA"); - - private ColorChooserDialogDataMgr _dataMgr = null; - - private List _usedColorScaleValueSetList = new ArrayList(); - private String _userID = null; - - private static final int VIEW_PANEL_TAB_ID = 1; - private static final int EDIT_PANEL_TAB_ID = 2; - private int _activeTabID = EDIT_PANEL_TAB_ID; - - private static final int DEFAULT_WIDTH = 600; - private static final int DEFAULT_HEIGHT = 550; - - private static final float MISSING = -9999; - private static final float MINIMUM_VALUE = -8888; - - private ColorScaleValueSet _displayedColorScaleValueSet = null; - private ColorScaleValueSet _usedColorScaleValueSet = null; - private TreeSet _allColorUsesSet = new TreeSet(); - private Set _currentDisplayedDurationSet = null; - private NamedColorMatcher _namedColorMatcher = null; - - private boolean _updatingComboBoxes = false; - - public ColorChooserDialog() - { - } - - public ColorChooserDialog( JFrame owner, ColorChooserDialogDataMgr dataMgr, String userID ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, "Color Scale Manager - User:" + userID, true ); - _dataMgr = dataMgr; - _userID = userID; - _dataMgr.setUserID( userID ); - initGui(); - addListeners(); - } - // ------------------------------------------------------------------------------------- - - private void initGui() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - setLayoutManager(); - addFrameComponenets(); - - updateUsedColorScaleValueSetList(); - updateAllColorUsesSet(); - - addViewPanelTabComponents(); - addEditPanelTabComponents(); - addComboBoxComponents(); - addCloseButtonPanelComponents(); - - initComboBoxes(); - - addToolTips(); - - displayColorScaleValues(); - return; - } - - private void addToolTips() - { - // private JButton _deleteUserButton = null; - // private JButton _deleteOfficeButton = new JButton( "
Delete
as office
"); - - - _editTabResetColorButton.setToolTipText(" Undoes the changes in working
memory for the currently selected
color set, returning it to
what is stored in the database. "); - - _editTabVCRLeftScaleValueButton.setToolTipText(" Selects the previous DataType/Duration
combination for the currently selected source. "); - _editTabVCRRightScaleValueButton.setToolTipText(" Selects the next DataType/Duration
combination for the currently selected source. "); - - _editTabAddColorSet.setToolTipText(" Puts the edited color-value pair
into the set in working memory. "); - _editTabDeleteColorSet.setToolTipText(" Removes the edited color-value
from the set in working memory. "); - - _saveAsUserButton.setToolTipText(" For the current user,
saves the currently selected color set to the database. "); - _saveAsOfficeButton.setToolTipText(" For the office default settings,
saves the currently selected color set to the database. "); - - _deleteUserButton.setToolTipText(" Remove the color set with the currently selected
DataType/Duration combination
from the database for this user. "); - _deleteOfficeButton.setToolTipText(" Remove the color set with the currently selected
DataType/Duration combination
from the database for the office."); - - - } - - private void addCloseButtonPanelComponents() - { - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabCloseButtonPanel, _closeButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void addEditPanelTabComponents() - { - JPanel editTabHorizontalSeparatorPanel = new JPanel(); - JPanel editTabVirticalSeparatorPanel = new JPanel(); - JPanel editTabVirticalSeparatorPanel2 = new JPanel(); - - _editTabButtonPanel.setBorder( BorderFactory.createTitledBorder( "Color-Value Set Database Controls" ) ); - editTabHorizontalSeparatorPanel.setPreferredSize( new Dimension( 50, 250 ) ); - editTabVirticalSeparatorPanel.setPreferredSize( new Dimension( 350, 60 ) ); - editTabVirticalSeparatorPanel2.setPreferredSize( new Dimension( 350, 60 ) ); - _editTabColorUseComboBox = new JComboBox( getColorUseComboBoxString() ); - _editTabUsedColorsDisplayPanel.setBorder( BorderFactory.createTitledBorder( "Used Color Set" ) ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _editPanelTab, _editTabComboBoxPanel, 0, 0, 25, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabColorsDisplayPanel, 0, 1, 25, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, editTabVirticalSeparatorPanel, 0, 6, 7, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabModifyColorScaleValueSetPanel, 8, 6, 10, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, editTabVirticalSeparatorPanel2, 18, 6, 7, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _editPanelTab, editTabHorizontalSeparatorPanel, 0, 11, 25, 10, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabUsedColorsDisplayPanel, 0, 22, 25, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabButtonPanel, 0, 27, 25, 5, 1, 1, GridBagConstraints.BOTH ); - - _editTabColor.setBackground( Color.BLACK ); - _editTabSaveAsColorUseComboBox = new JComboBox( _allColorUsesSet.toArray() ); - - JPanel saveAsColorUseLabelComboBoxPanel = new JPanel(); - JPanel saveDeleteDbButtonPanel = new JPanel(); - JPanel modifyColorSetsPanel = new JPanel( new GridBagLayout() ); - JPanel colorSetPanel = new JPanel( new GridBagLayout() ); - - saveAsColorUseLabelComboBoxPanel.add( _editTabSaveAsLabel ); - saveAsColorUseLabelComboBoxPanel.add( _editTabSaveAsColorUseComboBox ); - saveDeleteDbButtonPanel.add( _saveAsUserButton ); - saveDeleteDbButtonPanel.add( _saveAsOfficeButton ); - saveDeleteDbButtonPanel.add( _deleteUserButton ); - saveDeleteDbButtonPanel.add( _deleteOfficeButton ); - - GridBagConstraints buttonGbc = new GridBagConstraints(); - buttonGbc.insets = new Insets(2,2,2,2); - buttonGbc.weightx = 1; - buttonGbc.weighty = 1; - //JPanel panel, Component component, GridBagConstraints gbc, int column, int row, int width, int height, int fill ) -// ComponentHelper.addPanelComponent( modifyColorSetsPanel, _editTabColor, buttonGbc, 1, 1, 1, 1, GridBagConstraints.BOTH ); -// ComponentHelper.addPanelComponent( modifyColorSetsPanel, _editTabScaleValue, buttonGbc, 1, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( modifyColorSetsPanel, _editTabAddColorSet, buttonGbc, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( modifyColorSetsPanel, _editTabDeleteColorSet, buttonGbc, 1, 2, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( colorSetPanel, _editTabColor, buttonGbc, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( colorSetPanel, _editTabScaleValue, buttonGbc, 1, 2, 1, 1, GridBagConstraints.BOTH ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, colorSetPanel, 1, 1, 1, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, modifyColorSetsPanel, 2, 1, 1, 2, 1, 1, GridBagConstraints.BOTH ); - -/* - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, _editTabColor, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, _editTabScaleValue, 1, 2, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, _editTabAddColorSet, 6, 1, 2, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, _editTabDeleteColorSet, 6, 3, 2, 2, 1, 1, GridBagConstraints.NONE ); -*/ - ComponentHelper.addPanelComponent( _editTabButtonPanel, saveAsColorUseLabelComboBoxPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabButtonPanel, saveDeleteDbButtonPanel, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void addViewPanelTabComponents() - { - JPanel horizontalSeparatorPanel = new JPanel(); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 50, 350 ) ); - - _viewTabColorUseComboBox = new JComboBox( getColorUseComboBoxString() ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _viewPanelTab, _viewTabComboBoxPanel, 0, 0, 25, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _viewPanelTab, _viewTabColorsDisplayPanel, 0, 2, 25, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _viewPanelTab, horizontalSeparatorPanel, 0, 7, 25, 10, 1, 1, GridBagConstraints.BOTH ); - } - - private void addComboBoxComponents() - { - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabSetComboBoxPanel, _viewTabSetComboBoxLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabSetComboBoxPanel, _viewTabUsedColorsSetLabel, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - - ComponentHelper.addPanelComponent( _viewTabUserIDComboBoxPanel, _viewTabUserIDLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabUserIDComboBoxPanel, _viewTabUserIDComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _viewTabColorUseComboBoxPanel, _viewTabColorUseLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabColorUseComboBoxPanel, _viewTabColorUseComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _viewTabDurationPanel, _viewTabDurationLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabDurationPanel, _viewTabDurationComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabDurationPanel, _viewTabDurationUnitsLabel, 2, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - _viewTabUserIDComboBoxPanel.setVisible( false ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabSetComboBoxPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabUserIDComboBoxPanel, 2, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabColorUseComboBoxPanel, 3, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabDurationPanel, 4, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - - - - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _editTabSetComboBoxPanel, _editTabSetComboBoxLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabSetComboBoxPanel, _editTabSetComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabUserIDComboBoxPanel, _editTabUserIDLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabUserIDComboBoxPanel, _editTabUserIDComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabColorUseComboBoxPanel, _editTabColorUseLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabColorUseComboBoxPanel, _editTabColorUseComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabDurationPanel, _editTabDurationLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabDurationPanel, _editTabDurationComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabDurationPanel, _editTabDurationUnitsLabel, 2, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - _editTabUserIDComboBoxPanel.setVisible( false ); - _editTabDurationComboBox.setEditable( true ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabSetComboBoxPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabUserIDComboBoxPanel, 2, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabColorUseComboBoxPanel, 3, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabDurationPanel, 4, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - - _editTabDurationComboBox.setName( "EditTabDuration" ); - _viewTabDurationComboBox.setName( "ViewTabDuration" ); - } - - private void setLayoutManager() - { - _frameContentPane.setLayout( new GridBagLayout() ); - } - - private void addFrameComponenets() - { - _tabbedPane.setPreferredSize( new Dimension( 200, 600 ) ); - - ComponentHelper.addPanelComponent( _tabbedPanePanel, _tabbedPane, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _viewTabComboBoxPanel, 0, 0, 25, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _tabbedPanePanel, 0, 2, 25, 30, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _viewTabCloseButtonPanel, 0, 32, 25, 1, 1, 1, GridBagConstraints.BOTH ); - _viewPanelTab.setName( "ViewPanelTab" ); - _editPanelTab.setName( "EditPanelTab" ); - _tabbedPane.addTab( "Edit Color Sets", _editPanelTab ); - _tabbedPane.addTab( "Browse Color Sets", _viewPanelTab ); - _saveAsUserButton = new JButton( "
Save as
" + _userID + "
" ); - _deleteUserButton = new JButton( "
Delete as
" + _userID + "
"); - _deleteOfficeButton.setEnabled( false ); - _deleteUserButton.setEnabled( false ); - } - - private void displayColorScaleValues() - { - _viewTabColorsDisplayPanel.removeAll(); - _editTabColorsDisplayPanel.removeAll(); - _editTabUsedColorsDisplayPanel.removeAll(); - ColorSet colorSet = null; - ScaleValueSet scaleValueSet = null; - String colorUse = null; - String userIDString = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - colorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - } - else - { - colorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - } - - ColorScaleValueSet colorScaleValueSet = getColorScaleValueSetByColorUse( colorUse ); - - if ( colorScaleValueSet != null ) - { - userIDString = colorScaleValueSet.getUserID(); - - if ( userIDString.equalsIgnoreCase( "HARDCODED" ) ) - { - _viewTabUsedColorsSetLabel.setText( "default" ); - } - else if ( userIDString.equalsIgnoreCase( "default" ) ) - { - _viewTabUsedColorsSetLabel.setText( "office" ); - } - else - { - _viewTabUsedColorsSetLabel.setText( "user (" + userIDString + ")" ); - } - } - - if ( colorScaleValueSet != null ) - { - colorSet = colorScaleValueSet.getColorSet(); - scaleValueSet = colorScaleValueSet.getScaleValueSet(); - } - - if ( ( colorSet != null ) && ( scaleValueSet != null ) ) - { - List namedColorList = colorSet.getNamedColorList(); - int colorSetListSize = namedColorList.size(); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabVCRButtonColorPanel, _viewTabVCRLeftColorButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _viewTabVCRButtonColorPanel, _viewTabVCRRightColorButton, 2, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _viewTabColorsDisplayPanel, _viewTabVCRButtonColorPanel, 1, 1, colorSetListSize, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabVCRButtonScaleValuePanel, _editTabVCRLeftScaleValueButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabVCRButtonScaleValuePanel, _editTabVCRRightScaleValueButton, 2, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabColorsDisplayPanel, _editTabVCRButtonScaleValuePanel, 1, 1, colorSetListSize, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabColorsDisplayPanel, _editTabResetColorButton, 1, 8, colorSetListSize, 1, 1, 1, GridBagConstraints.NONE ); - - for ( int i = 0; i < namedColorList.size(); i++ ) - { - Double scaleValueDouble = (Double) scaleValueSet.getScaleValueSet().get( i ); - NamedColor namedColor = getClosestNamedColor( (Color) namedColorList.get( i ) ); - - addColorValueDisplayPanelToTabContainerPanel( scaleValueDouble, - namedColor, - _viewTabColorsDisplayPanel, - i, - false); - - addColorValueDisplayPanelToTabContainerPanel( scaleValueDouble, - namedColor, - _editTabColorsDisplayPanel, - i, - true); - } //end for - } - _displayedColorScaleValueSet = colorScaleValueSet; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - _usedColorScaleValueSet = getUsedColorScaleValueSetByColorUse( colorUse ); - - if ( _usedColorScaleValueSet != null ) - { - List usedColorSetList = _usedColorScaleValueSet.getColorSet().getNamedColorList(); - List usedScaleValueSetList = _usedColorScaleValueSet.getScaleValueSet().getScaleValueSet(); - - for ( int i = 0; i < usedColorSetList.size(); i++ ) - { - Double scaleValueDouble = (Double) usedScaleValueSetList.get( i ); - NamedColor namedColor = getClosestNamedColor( (Color) usedColorSetList.get( i ) ); - addColorValueDisplayPanelToTabContainerPanel( scaleValueDouble, - namedColor, - _editTabUsedColorsDisplayPanel, - i, - false); - } - - userIDString = _usedColorScaleValueSet.getUserID(); - - if ( userIDString.equalsIgnoreCase( "HARDCODED" ) ) - { - _editTabUsedColorsSetLabel.setText( "default" ); - } - else if ( userIDString.equalsIgnoreCase( "default" ) ) - { - _editTabUsedColorsSetLabel.setText( "office" ); - } - else - { - _editTabUsedColorsSetLabel.setText( "user (" + userIDString + ")" ); - } - } - } - - if ( _usedColorScaleValueSet != null ) - { - _editTabUsedColorsDisplayPanel.setBorder( BorderFactory.createTitledBorder( "Used Color Set - Source: " + _editTabUsedColorsSetLabel.getText() + - " Data-Type: " + _usedColorScaleValueSet.getColorUseString() + - " Duration: " + _usedColorScaleValueSet.getDuration() ) ); - } - - _viewTabColorsDisplayPanel.setVisible( false ); - _viewTabColorsDisplayPanel.setVisible( true ); - _editTabColorsDisplayPanel.setVisible( false ); - _editTabColorsDisplayPanel.setVisible( true ); - _editTabUsedColorsDisplayPanel.setVisible( false ); - _editTabUsedColorsDisplayPanel.setVisible( true ); - } - - // ---------------------------------------------------------------------------------------------------- - private void addColorValueDisplayPanelToTabContainerPanel(Double scaleValueDouble, - NamedColor namedColor, - JPanel colorsDisplayPanel, - int indexOfSlotPanel, - boolean addClickColorSelectionListener) - { - int i = indexOfSlotPanel; - JPanel colorPanel = new JPanel(); - JTextField scaleValueTextField = new JTextField(); - JPanel colorAndScalePairPanel = new JPanel(); - - colorPanel.setBackground( namedColor ); - colorPanel.setBorder( BorderFactory.createRaisedBevelBorder() ); - - colorAndScalePairPanel.setLayout( new GridBagLayout() ); - colorAndScalePairPanel.setPreferredSize( new Dimension( 10, 50 ) ); - - scaleValueTextField.setText( getFormattedDoubleString(scaleValueDouble)); - - scaleValueTextField.setEditable( false ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( colorAndScalePairPanel, colorPanel, 0, 0, 1, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( colorAndScalePairPanel, scaleValueTextField, 0, 5, 1, 5, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( colorsDisplayPanel, colorAndScalePairPanel, i, 2, 1, 5, 1, 1, GridBagConstraints.BOTH ); - - if (addClickColorSelectionListener) - { - colorPanel.addMouseListener( new ClickColorSelectionListener( scaleValueDouble ) ); - scaleValueTextField.addMouseListener( new EditScaleValueTextFieldListener( colorPanel, scaleValueDouble ) ); - } - } - - private void initComboBoxes() - { - String selectedColorUseString = (String) _editTabColorUseComboBox.getSelectedItem(); - _editTabSaveAsColorUseComboBox.setSelectedItem( selectedColorUseString ); - } - - - private List getFilteredColorScaleValueSetList( String userID, String colorUse ) - { - List filteredColorScaleValueSetList = new ArrayList(); -// List databaseColorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - List databaseColorScaleValueSetList = _usedColorScaleValueSetList; -// _dataMgr.resetColorValueTableColorScaleValueSetList(); - - ColorScaleValueSet extractedColorScaleValueSet = null; - - for ( int i = 0; i < databaseColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) databaseColorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( userID ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) ) - { - filteredColorScaleValueSetList.add( extractedColorScaleValueSet ); - } - } - - return filteredColorScaleValueSetList; - } - - private ColorScaleValueSet getUsedColorScaleValueSetByColorUse( String colorUse ) - { - ColorScaleValueSet foundColorScaleValueSet = null; - ColorScaleValueSet returnColorScaleValueSet = null; - - List userColorScaleValueSetList = new ArrayList(); - List officeColorScaleValueSetList = new ArrayList(); -// List flatFileColorScaleValueSetList = _dataMgr.getDefaultColorScaleValueSetList(); - List flatFileColorScaleValueSetList = _usedColorScaleValueSetList; - - userColorScaleValueSetList = getFilteredColorScaleValueSetList( _userID, colorUse ); - officeColorScaleValueSetList = getFilteredColorScaleValueSetList( "default", colorUse ); - - foundColorScaleValueSet = findClosestColorScaleValueSet( userColorScaleValueSetList, colorUse ); - - if ( foundColorScaleValueSet == null ) - { - foundColorScaleValueSet = findClosestColorScaleValueSet( officeColorScaleValueSetList, colorUse ); - } - - if ( foundColorScaleValueSet == null ) - { - foundColorScaleValueSet = findClosestColorScaleValueSet( flatFileColorScaleValueSetList, colorUse ); - } - - returnColorScaleValueSet = new ColorScaleValueSet( foundColorScaleValueSet ); - - return returnColorScaleValueSet; - } - - private ColorScaleValueSet findClosestColorScaleValueSet( List userColorScaleValueSetList, String colorUse ) - { - ColorScaleValueSet foundColorScaleValueSet = null; - double duration = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - - ColorScaleValueSet extractedColorScaleValueSet = null; - List foundColorUseColorScaleValueSetList = new ArrayList(); - - for ( int i = 0; i < userColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) userColorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) ) - { - foundColorUseColorScaleValueSetList.add( extractedColorScaleValueSet ); - } - } - - if ( foundColorUseColorScaleValueSetList.size() > 0 ) - { - foundColorScaleValueSet = getClosestMatchingDurationColorScaleValueSet( foundColorUseColorScaleValueSetList, - duration ); - } - - return foundColorScaleValueSet; - } - - private ColorScaleValueSet getClosestMatchingDurationColorScaleValueSet( List foundColorUseColorScaleValueSetList, - double duration ) - { - ColorScaleValueSet closestMatchingColorScaleValueSet = null; - ColorScaleValueSet extractedColorScaleValueSet = null; - double durationDiff = 1000; - - for ( int i = 0; i < foundColorUseColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) foundColorUseColorScaleValueSetList.get( i ); - - if ( ( Math.abs( extractedColorScaleValueSet.getDuration() - duration ) ) < durationDiff ) - { - durationDiff = Math.abs( extractedColorScaleValueSet.getDuration() - duration ); - closestMatchingColorScaleValueSet = extractedColorScaleValueSet; - } - } - return closestMatchingColorScaleValueSet; - } -/* - private ColorScaleValueSet getUsedColorScaleValueSetByColorUse( String colorUse ) - { - ColorScaleValueSet foundColorScaleValueSet = null; - ColorScaleValueSet extractedColorScaleValueSet = null; - int duration = (Integer) _editTabDurationComboBox.getSelectedItem(); - - for ( int i = 0; i < _usedColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getDuration() == duration ) ) - { - foundColorScaleValueSet = extractedColorScaleValueSet; - } - } - if ( ( _activeTabID == EDIT_PANEL_TAB_ID ) && ( foundColorScaleValueSet == null ) ) - { - for ( int i = 0; i < _usedColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getDuration() == 0 ) ) - { - foundColorScaleValueSet = extractedColorScaleValueSet; - } - } - } - return foundColorScaleValueSet; - } - - private boolean doesUserColorScaleValueSetExist( String colorUse ) - { - - } -*/ - - private void updateAllColorUsesSet() - { - List defaultColorList = _dataMgr.getDefaultColorScaleValueSetList(); - List databaseColorList = _dataMgr.getColorValueTableColorScaleValueSetList(); - ColorScaleValueSet extractedColorScaleValueSet = null; - - for ( int i = 0; i < defaultColorList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) defaultColorList.get( i ); - _allColorUsesSet.add( extractedColorScaleValueSet.getColorUseString() ); - } - for ( int i = 0; i < databaseColorList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) databaseColorList.get( i ); - _allColorUsesSet.add( extractedColorScaleValueSet.getColorUseString() ); - } - } - - private String getFormattedDoubleString(double value) - { - return getFormattedDoubleString(value, "%7.2f"); - } - - private String getFormattedDoubleString(double value, String format) - { - String text = null; - - if ( value == MINIMUM_VALUE ) - { - text = "< Min"; - } - else if ( value == MISSING ) - { - text = "MSG"; - } - else - { - text = String.format(format, value); - } - - return text; - } - - private NamedColor getClosestNamedColor( Color color ) - { - NamedColor namedColor = null; - - if ( _namedColorMatcher == null ) - { - _namedColorMatcher = new NamedColorMatcher( _dataMgr.getRGBColorMap() ); - } - - namedColor = _namedColorMatcher.getClosestNamedColor( color ); - - return namedColor; - } - - private class EditScaleValueTextFieldListener extends MouseAdapter - { - private JPanel _associatedColorPanel = null; - private double _scaleValueDouble = 0; - - public EditScaleValueTextFieldListener( JPanel associatedColorPanel, double scaleValueDouble ) - { - _associatedColorPanel = associatedColorPanel; - _scaleValueDouble = scaleValueDouble; - } - - public void mousePressed( MouseEvent e ) - { - _editTabColor.setBackground( _associatedColorPanel.getBackground() ); - - _editTabScaleValue.setText( getFormattedDoubleString( _scaleValueDouble ) ); - } - } - - private class ClickColorSelectionListener extends MouseAdapter - { - private double _scaleValueDouble = 0; - - public ClickColorSelectionListener( Double scaleValueDouble ) - { - _scaleValueDouble = scaleValueDouble; - } - - public void mousePressed( MouseEvent e ) - { - JPanel panel = (JPanel) e.getSource(); - - _editTabColor.setBackground( panel.getBackground() ); - - _editTabScaleValue.setText( getFormattedDoubleString(_scaleValueDouble ) ); - - displayColorPickerDialog(); - - addColorSet(); -// displayColorScaleValues(); - } - } - - - - private String[] getColorUseComboBoxString() - { - String[] colorUseComboBoxString = null; - List hvDefaultColorList = _dataMgr.getDefaultColorScaleValueSetList(); - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - Set colorUseSet = new HashSet(); - String selectedItem = null; - String colorUseString = null; - - List colorUseNamesList = new ArrayList(); - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedItem = _viewTabUsedColorsSetLabel.getText(); - } - else - { - selectedItem = (String) _editTabSetComboBox.getSelectedItem(); - } - - if ( selectedItem.equalsIgnoreCase( "default" ) ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBoxPanel.setVisible( false ); - } - else - { - _editTabUserIDComboBoxPanel.setVisible( false ); - } - for ( int i = 0; i < hvDefaultColorList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) hvDefaultColorList.get( i ); - colorUseString = colorScaleValueSet.getColorUseString(); - if ( ! colorUseSet.contains( colorUseString ) ) - { - colorUseSet.add( colorUseString ); - colorUseNamesList.add( colorUseString ); - } - } - - colorUseComboBoxString = (String[]) colorUseNamesList.toArray( new String[ colorUseNamesList.size() ] ); - } - - if ( selectedItem.equalsIgnoreCase( "user" ) ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBoxPanel.setVisible( true ); - } - else - { - _editTabUserIDComboBoxPanel.setVisible( true ); - } - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ! colorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) - { - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - } - - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxString = (String[]) colorUseSet.toArray( new String[ colorUseSet.size() ] ); - } - - if ( selectedItem.equalsIgnoreCase( "office" ) ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBoxPanel.setVisible( false ); - } - else - { - _editTabUserIDComboBoxPanel.setVisible( false ); - } - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( colorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) - { - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - } - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxString = (String[]) colorUseSet.toArray( new String[ colorUseSet.size() ] ); - } - - if ( selectedItem.equalsIgnoreCase( "" ) ) - { - //displayUsedColorSets(); - for ( int i = 0; i < _usedColorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxString = (String[]) colorUseSet.toArray( new String[ colorUseSet.size() ] ); - - } - return colorUseComboBoxString; - } - - private void updateUserIDComboBox() - { - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - List userIDsList = new ArrayList(); - Set userIDsSet = new HashSet(); - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ! colorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) - { - userIDsList.add( colorScaleValueSet.getUserID() ); - } - } - - userIDsSet.addAll( userIDsList ); - - Iterator iterator = userIDsSet.iterator(); - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBox.removeAllItems(); - while ( iterator.hasNext() ) - { - String userID = (String) iterator.next(); - - _viewTabUserIDComboBox.addItem( userID ); - } - } - else - { -// _updatingComboBoxes = true; - _editTabUserIDComboBox.removeAllItems(); - while ( iterator.hasNext() ) - { - String userID = (String) iterator.next(); - - _editTabUserIDComboBox.addItem( userID ); - } -// _updatingComboBoxes = false; - } - - if ( userIDsSet.isEmpty() ) - { - _editTabUserIDComboBox.addItem( "-----" ); - } - } - - - private List getDurationSet() - { - String selectedItem = null; - ColorScaleValueSet extractedColorScaleValueSet = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedItem = _viewTabUsedColorsSetLabel.getText(); - } - else - { - selectedItem = (String) _editTabSetComboBox.getSelectedItem(); - } - - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - SortedSet durationSet = new TreeSet (); - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - if ( selectedItem.equalsIgnoreCase( "user" ) ) - { - String selectedUser = null; - String selectedColorUse = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedUser = (String) _viewTabUserIDComboBox.getSelectedItem(); - selectedColorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - - } - else - { - selectedUser = (String) _editTabUserIDComboBox.getSelectedItem(); - selectedColorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - - } - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( selectedUser ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( selectedColorUse ) ) ) - { - durationSet.add( extractedColorScaleValueSet.getDuration() ); - } - } - } - else if ( selectedItem.equalsIgnoreCase( "office" ) ) - { - String selectedColorUse = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedColorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - } - else - { - selectedColorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - } - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( selectedColorUse ) ) ) - { - durationSet.add( extractedColorScaleValueSet.getDuration() ); - } - } - } - } - - if ( ( _activeTabID == VIEW_PANEL_TAB_ID ) || ( selectedItem.equalsIgnoreCase( "default" ) ) ) - { - String selectedColorUse = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedColorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - } - else - { - selectedColorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - } - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - if ( selectedColorUse != null ) - { - for ( int i = 0; i < _usedColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - if ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( selectedColorUse ) ) - { - durationSet.add( extractedColorScaleValueSet.getDuration() ); - } - } - } - } - else - { - durationSet.add( 0.0 ); - } - } - - _currentDisplayedDurationSet = durationSet; - - List sortedDurationStringList = getSortedDurationStringList( durationSet ); - - return sortedDurationStringList; - } - - private List getSortedDurationStringList( SortedSet durationSet ) - { - List sortedDurationDoubleList = new ArrayList ( durationSet ); - List sortedDurationStringList = new ArrayList (); - - - for( Double duration : sortedDurationDoubleList ) - { - sortedDurationStringList.add( getComboBoxDurationString( duration ) ); - } - - return sortedDurationStringList; - } - - - public String getComboBoxDurationString( double doubleValue ) - { - String returnString = ""; - - if ( Math.floor( doubleValue ) == doubleValue ) - { - returnString = "" + ( (int) doubleValue ); - } - else - { - returnString = "" + doubleValue; - } - - return returnString; - } - - private ColorScaleValueSet getColorScaleValueSetByColorUse( String colorUse ) - { - List colorScaleValueSetList = null; - ColorScaleValueSet colorScaleValueSet = null; - String selectedUser = null; - Double selectedDurationDouble = -1.0; - double selectedDuration = -1; - ColorScaleValueSet extractedColorScaleValueSet = null; - - String setComboBoxString = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedDurationDouble = getDurationComboBoxDoubleValue( _viewTabDurationComboBox ); - } - else - { - setComboBoxString = (String) _editTabSetComboBox.getSelectedItem(); - selectedDurationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - } - int i = 0; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) // in Edit Tab - { - if ( ( setComboBoxString.equalsIgnoreCase( "default" ) ) && ( selectedDurationDouble != null ) ) - { - colorScaleValueSetList = _dataMgr.getDefaultColorScaleValueSetList(); - while ( ( i < colorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getDuration() == selectedDurationDouble ) ) - { -// colorScaleValueSet = new ColorScaleValueSet( (ColorScaleValueSet) colorScaleValueSetList.get( i ) ); - colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - } - i++; - } - - } - else if ( ( setComboBoxString.equalsIgnoreCase( "user" ) ) && ( selectedDurationDouble != null ) ) - { - colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedUser = (String) _viewTabUserIDComboBox.getSelectedItem(); - selectedDurationDouble = (Double) _viewTabDurationComboBox.getSelectedItem(); - } - else - { - selectedUser = (String) _editTabUserIDComboBox.getSelectedItem(); - selectedDurationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - } - if ( selectedDurationDouble != null ) - { - selectedDuration = selectedDurationDouble; - - extractedColorScaleValueSet = null; - - while ( ( i < colorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( selectedUser ) ) && - ( extractedColorScaleValueSet.getDuration() == selectedDuration ) ) - { -// colorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); - colorScaleValueSet = extractedColorScaleValueSet; - } - i++; - } - } - - } - else if ( ( setComboBoxString.equalsIgnoreCase( "office" ) ) && ( selectedDurationDouble != null ) ) - { - colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedDurationDouble = (Double) _viewTabDurationComboBox.getSelectedItem(); - } - else - { - selectedDurationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - } - - if ( selectedDurationDouble != null ) - { - selectedDuration = selectedDurationDouble; - - while ( ( i < colorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getDuration() == selectedDuration ) ) - { -// colorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); - colorScaleValueSet = extractedColorScaleValueSet; - } - i++; - } - } - - } - } - else - { - double duration = -1.0; - if ( _viewTabDurationComboBox.getSelectedItem() != null ) - { - Double durationDouble = getDurationComboBoxDoubleValue( _viewTabDurationComboBox ); - duration = durationDouble; - } - - extractedColorScaleValueSet = null; - while ( ( i < _usedColorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - - if ( ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) || - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) ) && - ( ( extractedColorScaleValueSet.getDuration() ) == duration ) ) - { -// colorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); - colorScaleValueSet = extractedColorScaleValueSet; - } - i++; - } - } - return colorScaleValueSet; - } - - private Double getDurationComboBoxDoubleValue( JComboBox comboBox ) - { - Double returnValue = null; - String selectedItem = (String) comboBox.getSelectedItem(); - if ( selectedItem != null ) - { - returnValue = Double.parseDouble( selectedItem ); - } - - return returnValue; - } - - private void updateColorUseComboBox( String userID ) - { - List colorUseComboBoxList = new ArrayList(); - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - Set colorUseSet = new HashSet(); - ColorScaleValueSet colorScaleValueSet = null; - - List colorUseNamesList = new ArrayList(); - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( colorScaleValueSet.getUserID().equalsIgnoreCase( userID ) ) - { - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - } - - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxList.addAll( colorUseSet ); - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabColorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseComboBoxList.size(); i++ ) - { - _viewTabColorUseComboBox.addItem( (String) colorUseComboBoxList.get( i ) ); - } - } - else - { - _editTabColorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseComboBoxList.size(); i++ ) - { - _editTabColorUseComboBox.addItem( (String) colorUseComboBoxList.get( i ) ); - } - } - } - - private void clickLeftVCRButton( JComboBox setComboBox, JComboBox colorUseComboBox, JComboBox durationComboBox ) - { - int index = 0; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - String selectedSetString = (String) setComboBox.getSelectedItem(); - String selectedColorUseString = (String) colorUseComboBox.getSelectedItem(); - - if ( ( selectedSetString.equalsIgnoreCase( "user" ) ) && ( selectedColorUseString.equalsIgnoreCase( "precipitation" ) ) ) - { - index = durationComboBox.getSelectedIndex(); - int durationItemCount = durationComboBox.getItemCount(); - - if ( index == 0 ) - { - index = durationItemCount - 1; - } - else - { - index--; - } - durationComboBox.setSelectedIndex( index ); - - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == 0 ) - { - index = colorUseItemCount - 1; - } - else - { - index--; - } - colorUseComboBox.setSelectedIndex( index ); - } - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == 0 ) - { - index = colorUseItemCount - 1; - } - else - { - index--; - } - colorUseComboBox.setSelectedIndex( index ); - } - - displayColorScaleValues(); - } - - private void clickRightVCRButton( JComboBox setComboBox, JComboBox colorUseComboBox, JComboBox durationComboBox ) - { - int index = 0; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - String selectedSetString = (String) setComboBox.getSelectedItem(); - String selectedColorUseString = (String) colorUseComboBox.getSelectedItem(); - if ( ( selectedSetString.equalsIgnoreCase( "user" ) ) && ( selectedColorUseString.equalsIgnoreCase( "precipitation" ) ) ) - { - index = durationComboBox.getSelectedIndex(); - int durationItemCount = durationComboBox.getItemCount(); - - if ( index == ( durationItemCount - 1 ) ) - { - index = 0; - } - else - { - index++; - } - durationComboBox.setSelectedIndex( index ); - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == ( colorUseItemCount - 1 ) ) - { - index = 0; - } - else - { - index++; - } - colorUseComboBox.setSelectedIndex( index ); - } - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == ( colorUseItemCount - 1 ) ) - { - index = 0; - } - else - { - index++; - } - colorUseComboBox.setSelectedIndex( index ); - } - - displayColorScaleValues(); - } - - private ColorScaleValueSet getNewColorScaleValueSet() - { - ColorScaleValueSet colorScaleValueSet = new ColorScaleValueSet(); - ScaleValueSet scaleValueSet = new ScaleValueSet(); - ColorSet colorSet = new ColorSet(); - - scaleValueSet.addScaleValue( -9999 ); - scaleValueSet.addScaleValue( -8888 ); - - colorSet.addNamedColor( new Color( 0, 0, 0 ) ); - colorSet.addNamedColor( new Color( 102, 102, 102 ) ); - - colorScaleValueSet.setScaleValueSet( scaleValueSet ); - colorScaleValueSet.setColorSet( colorSet ); - return colorScaleValueSet; - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _viewTabColorUseComboBox.addActionListener( new ColorUseComboBoxSelectionListener() ); - _editTabColorUseComboBox.addActionListener( new ColorUseComboBoxSelectionListener() ); - _editTabSetComboBox.addActionListener( new SetComboBoxSelectionListener() ); - _viewTabDurationComboBox.addActionListener( new DurationComboBoxListener() ); - _editTabDurationComboBox.addActionListener( new DurationComboBoxListener() ); - _tabbedPane.addChangeListener( new TabChangeListener() ); - _viewTabVCRLeftColorButton.addActionListener( new ViewTabLeftVCRButtonColorListener() ); - _viewTabVCRRightColorButton.addActionListener( new ViewTabRightVCRButtonColorListener() ); - _editTabVCRLeftScaleValueButton.addActionListener( new EditTabLeftVCRButtonScaleValueListener() ); - _editTabVCRRightScaleValueButton.addActionListener( new EditTabRightVCRButtonScaleValueListener() ); - _frameContentPane.addMouseWheelListener( new ColorUseComboBoxMouseWheelListener() ); - _viewTabUserIDComboBox.addActionListener( new UserIDComboBoxListener() ); - _editTabUserIDComboBox.addActionListener( new UserIDComboBoxListener() ); - _editTabAddColorSet.addActionListener( new AddColorSet() ); - _editTabDeleteColorSet.addActionListener( new DeleteColorSet() ); - _editTabResetColorButton.addActionListener( new ResetColorSetListener() ); - _editTabColor.addMouseListener( new ClickEditTabColor() ); - _saveAsUserButton.addActionListener( new SaveAsUserButtonListener() ); - _saveAsOfficeButton.addActionListener( new SaveAsOfficeButtonListener() ); - _deleteUserButton.addActionListener( new DeleteAsUserButtonListener() ); - _deleteOfficeButton.addActionListener( new DeleteAsOfficeButtonListener() ); - } - - - private class DeleteAsUserButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to delete the user set " + - ( (String) _editTabColorUseComboBox.getSelectedItem() ), "Delete Confirmation" ) ) - { - ColorScaleValueSet colorScaleValueSetToDelete = getCurrentlyDisplayedColorScaleValueSet(); - _dataMgr.deleteAsUser( colorScaleValueSetToDelete ); - _editTabSetComboBox.setSelectedItem( "user" ); - _editTabUserIDComboBox.setSelectedItem( _userID ); - - String colorUseString = colorScaleValueSetToDelete.getColorUseString(); - - if ( userHasColorUse( colorUseString, _userID ) ) - { - _editTabColorUseComboBox.setSelectedItem( colorUseString ); - } - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - setLastUpdateTimeToCurrentTime(); - } - } - } - - private boolean userHasColorUse( String colorUseString, String userID ) - { - boolean foundColorUse = false; - List userColorScaleValueSetList = getFilteredColorScaleValueSetList( userID, colorUseString ); - if ( userColorScaleValueSetList.size() > 0 ) - { - foundColorUse = true; - } - - return foundColorUse; - } - - - private class DeleteAsOfficeButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to delete the office set " + - ( (String) _editTabColorUseComboBox.getSelectedItem() ), "Delete Confirmation" ) ) - { - ColorScaleValueSet colorScaleValueSetToDelete = getCurrentlyDisplayedColorScaleValueSet(); - _dataMgr.deleteAsOffice( colorScaleValueSetToDelete ); - _editTabSetComboBox.setSelectedItem( "office" ); - String colorUseString = colorScaleValueSetToDelete.getColorUseString(); - - if ( userHasColorUse( colorUseString, "default" ) ) - { - _editTabColorUseComboBox.setSelectedItem( colorUseString ); - } - - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - setLastUpdateTimeToCurrentTime(); - } - } - } - - private class SaveAsOfficeButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to save the displayed color set as the office set?", "Save Confirmation" ) ) - { - Double durationDouble = (Double) _editTabDurationComboBox.getSelectedItem(); - ColorScaleValueSet colorScaleValueSetToSave = getCurrentlyDisplayedColorScaleValueSet(); - if ( ( colorScaleValueSetToSave == null ) || ( durationDouble == null ) ) - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "No color set is displayed", "Unable to save" ); - } - else - { - double duration = durationDouble; - String colorUseToSaveString = (String) _editTabSaveAsColorUseComboBox.getSelectedItem(); - - colorScaleValueSetToSave.setDuration( duration ); - colorScaleValueSetToSave.setColorUseString( colorUseToSaveString ); - - _dataMgr.saveAsOffice( colorScaleValueSetToSave ); - setLastUpdateTimeToCurrentTime(); - } - String setString = (String) _editTabSetComboBox.getSelectedItem(); - - if ( setString.equalsIgnoreCase( "default" ) ) - { - _editTabDurationComboBox.setSelectedItem( 0 ); - } - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - } - } - } - - private class SaveAsUserButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to save the displayed color set as your user set?", "Save Confirmation" ) ) - { - Double durationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - ColorScaleValueSet colorScaleValueSetToSave = getCurrentlyDisplayedColorScaleValueSet(); - if ( ( colorScaleValueSetToSave == null ) || ( durationDouble == null ) ) - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "No color set is displayed", "Unable to save" ); - } - else - { - double duration = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - String colorUseToSaveString = (String) _editTabSaveAsColorUseComboBox.getSelectedItem(); - colorScaleValueSetToSave.setDuration( duration ); - colorScaleValueSetToSave.setColorUseString( colorUseToSaveString ); - - _dataMgr.saveAsUser( colorScaleValueSetToSave, duration ); - setLastUpdateTimeToCurrentTime(); - } - String setString = (String) _editTabSetComboBox.getSelectedItem(); - - if ( setString.equalsIgnoreCase( "default" ) ) - { - _editTabDurationComboBox.setSelectedIndex( 0 ); - } - - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - } - } - } - - private ColorScaleValueSet getCurrentlyDisplayedColorScaleValueSet() - { - return _displayedColorScaleValueSet; - } - - private void updateUsedColorScaleValueSetList() - { - _dataMgr.resetColorValueTableColorScaleValueSetList(); - List hvDefaultColorList = _dataMgr.getDefaultColorScaleValueSetList(); - List colorValueTableList = _dataMgr.getColorValueTableColorScaleValueSetList(); - String colorUseString = null; - String userIDString = null; - double duration = 0.0; - Set colorUseNamesSet = new HashSet(); - Set usedColorScaleValueSetsSet = new HashSet(); - ColorScaleValueSet matchingColorScaleValueSet = null; - - ColorScaleValueSet colorScaleValueSet = null; - - _usedColorScaleValueSetList = new ArrayList(); - - // Find used ColorScaleValueSet (user/office/hardcoded) for each default ColorUse - for ( int i = 0; i < hvDefaultColorList.size(); i++ ) - { - colorScaleValueSet = (ColorScaleValueSet) hvDefaultColorList.get( i ); - matchingColorScaleValueSet = findMatchingUsedSet( colorScaleValueSet ); - usedColorScaleValueSetsSet.add( matchingColorScaleValueSet ); - colorUseNamesSet.add( matchingColorScaleValueSet.getColorUseString() ); - } - - // To include "non standard durations" for precip - for ( int i = 0; i < colorValueTableList.size(); i++ ) - { - colorScaleValueSet = (ColorScaleValueSet) colorValueTableList.get( i ); - - userIDString = colorScaleValueSet.getUserID(); - - if ( ( userIDString.equalsIgnoreCase( _userID ) ) || ( userIDString.equalsIgnoreCase( "default" ) ) ) - { - colorUseString = colorScaleValueSet.getColorUseString(); - - matchingColorScaleValueSet = findMatchingUsedSet( colorScaleValueSet ); - usedColorScaleValueSetsSet.add( matchingColorScaleValueSet ); - } - } - _usedColorScaleValueSetList.addAll( usedColorScaleValueSetsSet ); - } - - private ColorScaleValueSet findMatchingUsedSet( ColorScaleValueSet defaultColorScaleValueSet ) - { -// ColorScaleValueSet usedColorScaleValueSet = new ColorScaleValueSet( defaultColorScaleValueSet ); - ColorScaleValueSet usedColorScaleValueSet = ColorScaleValueSet.getCopyOfColorScaleValueSet( defaultColorScaleValueSet ); - - List colorScaleValueSetFromDatabaseList = _dataMgr.getColorValueTableColorScaleValueSetList(); - ColorScaleValueSet extractedColorScaleValueSet = null; - String colorUseName = usedColorScaleValueSet.getColorUseString(); - double duration = usedColorScaleValueSet.getDuration(); - String extractedColorUseString = null; - boolean foundUserSet = false; - int i = 0; - - while ( ( i < colorScaleValueSetFromDatabaseList.size() ) && ( ! foundUserSet ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetFromDatabaseList.get( i ); - extractedColorUseString = extractedColorScaleValueSet.getColorUseString(); - - if ( ( colorUseName.equalsIgnoreCase( extractedColorUseString ) ) && - ( duration == ( extractedColorScaleValueSet.getDuration() ) ) ) - { - String extractedUserIDString = extractedColorScaleValueSet.getUserID(); - - if ( extractedUserIDString.equalsIgnoreCase( "default" ) ) - { - usedColorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); -// usedColorScaleValueSet = ColorScaleValueSet.getCopyOfColorScaleValueSet( extractedColorScaleValueSet ); - } - else if ( extractedUserIDString.equalsIgnoreCase( _userID ) ) - { - usedColorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); -// usedColorScaleValueSet = ColorScaleValueSet.getCopyOfColorScaleValueSet( extractedColorScaleValueSet ); - - foundUserSet = true; - } - } - i++; - } - - return usedColorScaleValueSet; - } - - private class ResetColorSetListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _dataMgr.resetColorValueTableColorScaleValueSetList(); - _dataMgr.resetHvDefaultColorList(); - - displayColorScaleValues(); - } - } - - private void displayColorPickerDialog() - { - ColorHolder colorHolder = new ColorHolder( _editTabColor.getBackground() ); - - ColorPickerDialog colorPicker = new ColorPickerDialog( ColorChooserDialog.this, colorHolder ); - colorPicker.setPreferredSize( new Dimension( 300, 300 ) ); - colorPicker.setVisible( true ); - - NamedColor namedColor = getClosestNamedColor( colorHolder.getColor() ); - - _editTabColor.setBackground( namedColor ); - } - - private class ClickEditTabColor extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - displayColorPickerDialog(); - } - } - - private class DeleteColorSet implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - try - { - double scaleValueToDelete = Double.valueOf( _editTabScaleValue.getText() ); - int i = 0; - int index = -1; - String colorUseComboBoxString = (String) _editTabColorUseComboBox.getSelectedItem(); - ColorScaleValueSet colorScaleValueSet = getColorScaleValueSetByColorUse( colorUseComboBoxString ); - ScaleValueSet scaleValueSet = colorScaleValueSet.getScaleValueSet(); - ColorSet colorSet = colorScaleValueSet.getColorSet(); - - while ( ( i < scaleValueSet.getScaleValueSet().size() ) && ( index == -1 ) ) - { - double scaleValue = (Double) scaleValueSet.getScaleValueSet().get( i ); - - if ( closeEnoughToBeEqual( scaleValueToDelete, scaleValue ) ) - { - index = i; - } - i++; - } - - if ( index != -1 ) - { - scaleValueSet.deleteScaleValueAtIndex( index ); - colorSet.deleteNamedColorAtIndex( index ); - } - - displayColorScaleValues(); - - } - catch ( NumberFormatException error ) - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "Can not delete Missing/Below Threshold value", "Unable to Delete" ); - } - - } - } - - private void addColorSet() - { - String editTabScaleValueString = _editTabScaleValue.getText().trim(); - double newScaleValue = -1; - boolean validScaleValue = true; - - if ( ! editTabScaleValueString.equalsIgnoreCase( "" ) ) - { - if ( editTabScaleValueString.equalsIgnoreCase( "MSG" ) ) - { - newScaleValue = -9999; - } - else if ( editTabScaleValueString.equalsIgnoreCase( "< Min" ) ) - { - newScaleValue = -8888; - } - else - { - try - { - newScaleValue = Double.valueOf( editTabScaleValueString ); - } - catch (NumberFormatException ex ) - { - validScaleValue = false; - } - } - - if ( validScaleValue ) - { - int index = -1; - int i = 0; - boolean replaceValue = false; - - String colorUseComboBoxString = (String) _editTabColorUseComboBox.getSelectedItem(); - ColorScaleValueSet colorScaleValueSet = getColorScaleValueSetByColorUse( colorUseComboBoxString ); - if ( colorScaleValueSet == null ) - { - colorScaleValueSet = _displayedColorScaleValueSet; - Double durationDouble = (Double) _editTabDurationComboBox.getSelectedItem(); - colorScaleValueSet.setColorUseString( colorUseComboBoxString ); - colorScaleValueSet.setDuration( durationDouble ); - _dataMgr.addColorScaleValueSetToColorValueTableList( colorScaleValueSet ); - } - - ScaleValueSet scaleValueSet = colorScaleValueSet.getScaleValueSet(); - ColorSet colorSet = colorScaleValueSet.getColorSet(); - if ( ( scaleValueSet != null ) && ( colorSet != null ) ) - { - while ( ( i < scaleValueSet.getScaleValueSet().size() ) && ( index == -1 ) ) - { - double scaleValue = (Double) scaleValueSet.getScaleValueSet().get( i ); - - if ( closeEnoughToBeEqual(newScaleValue, scaleValue) ) - { - index = i; - replaceValue = true; - } - - if ( newScaleValue < scaleValue ) - { - index = i; - } - i++; - } - } - - if ( index == -1 ) - { - index = i; - } - - if ( replaceValue ) - { - scaleValueSet.replaceScaleValueAtIndex( newScaleValue, index ); - colorSet.replaceNamedColorAtIndex( _editTabColor.getBackground(), index ); - } - else - { - scaleValueSet.addScaleValueAtIndex( newScaleValue, index ); - colorSet.addNamedColorAtIndex( _editTabColor.getBackground(), index ); - } - - _displayedColorScaleValueSet = colorScaleValueSet; - displayColorScaleValues(); - } - else - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "Invalid ScaleValue entered", "Invalid ScaleValue" ); - } - } - } - private class AddColorSet implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - addColorSet(); - } - } - - private boolean closeEnoughToBeEqual(double value1, double value2) - { - boolean result = false; - - if (Math.abs((value1 - value2)) < 0.0001) - { - result = true; - } - - return result; - - } - - private class ViewTabLeftVCRButtonColorListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickLeftVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - - private class ViewTabRightVCRButtonColorListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickRightVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - - private class EditTabLeftVCRButtonScaleValueListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickLeftVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - - private class EditTabRightVCRButtonScaleValueListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickRightVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - - private class ColorUseComboBoxMouseWheelListener implements MouseWheelListener - { - - public void mouseWheelMoved( MouseWheelEvent e ) - { - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - if ( e.getWheelRotation() > 0 ) - { - clickLeftVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - else - { - clickRightVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - else - { - if ( e.getWheelRotation() > 0 ) - { - clickLeftVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - else - { - clickRightVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - } - } - - - private class TabChangeListener implements ChangeListener - { - - public void stateChanged( ChangeEvent e ) - { - JTabbedPane jTabbedPane = (JTabbedPane) e.getSource(); - String activeTabString = jTabbedPane.getSelectedComponent().getName(); - - jTabbedPane.setBackground( Color.LIGHT_GRAY ) ; - - if ( activeTabString.equalsIgnoreCase( "ViewPanelTab" ) ) - { - _activeTabID = VIEW_PANEL_TAB_ID; - _dataMgr.resetColorValueTableColorScaleValueSetList(); - _dataMgr.resetHvDefaultColorList(); -// displayUsedColorSets(); - } - else if ( activeTabString.equalsIgnoreCase( "EditPanelTab" ) ) - { - _activeTabID = EDIT_PANEL_TAB_ID; - _editTabSetComboBox.setSelectedItem( "default" ); - } - displayColorScaleValues(); - } - } - - private class ColorUseComboBoxSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( ! _updatingComboBoxes ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - String colorUseString = (String) _viewTabColorUseComboBox.getSelectedItem(); - - if ( ( colorUseString != null ) && ( ! colorUseString.equalsIgnoreCase( "-----" ) ) ) - { - UpdateDurationComboBoxByColorUseComboBox( _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - else - { - String colorUseString = (String) _editTabColorUseComboBox.getSelectedItem(); - - if ( ( colorUseString != null ) && ( ! colorUseString.equalsIgnoreCase( "-----" ) ) ) - { - UpdateDurationComboBoxByColorUseComboBox( _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - } - } - } - - private void UpdateDurationComboBoxByColorUseComboBox( JComboBox colorUseComboBox, JComboBox durationComboBox ) - { - List durationSet = getDurationSet(); - String selectedColorUseString = (String) colorUseComboBox.getSelectedItem(); - String setString = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - setString = _viewTabUsedColorsSetLabel.getText(); - } - else - { - setString = (String) _editTabSetComboBox.getSelectedItem(); - } - if ( selectedColorUseString != null ) - { - List durationList = new ArrayList( durationSet ); - - durationComboBox.removeAllItems(); - - for( String duration : durationList ) - { - durationComboBox.addItem( duration ); - } - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - _editTabSaveAsColorUseComboBox.setSelectedItem( selectedColorUseString ); - } - } - - if ( colorUseComboBox.getItemCount() > 0 ) - { - displayColorScaleValues(); - } - String colorUseString = (String) _editTabColorUseComboBox.getSelectedItem(); - } - - private class UserIDComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( ! _updatingComboBoxes ) - { - - String selectedUserID = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedUserID = (String) _viewTabUserIDComboBox.getSelectedItem(); - } - else - { - selectedUserID = (String) _editTabUserIDComboBox.getSelectedItem(); - if ( isUsersSet() ) - { - _deleteUserButton.setEnabled( true ); - } - else - { - _deleteUserButton.setEnabled( false ); - } - } - - updateColorUseComboBox( selectedUserID ); - } - } - } - - private class DurationComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( ! _updatingComboBoxes ) - { - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - UpdateColorScaleValuesByDurationUpdate( _viewTabUsedColorsSetLabel.getText(), _viewTabUserIDComboBox ); - } - else // In the edit tab - { - Double durationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - if ( durationDouble != null ) - { - if ( ( _currentDisplayedDurationSet != null ) && ( _currentDisplayedDurationSet.contains( durationDouble ) ) ) - { - String editTabSetComboBoxString = (String) _editTabSetComboBox.getSelectedItem(); - UpdateColorScaleValuesByDurationUpdate( editTabSetComboBoxString, _editTabUserIDComboBox ); - } - } - } - } - } - } - - private void UpdateColorScaleValuesByDurationUpdate( String setComboBoxString, JComboBox userIDComboBox ) - { - String selectedUserID = null; - - if ( setComboBoxString.indexOf( "user" ) != -1 ) - { - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - selectedUserID = (String) userIDComboBox.getSelectedItem(); - } - else - { - selectedUserID = _userID; - } - } - - displayColorScaleValues(); - } - - - private class SetComboBoxSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - populateSetComboBox( _viewTabUsedColorsSetLabel.getText(), _viewTabColorUseComboBox ); - } - else - { - String editTabSetComboBoxString = (String) _editTabSetComboBox.getSelectedItem(); - - populateSetComboBox( editTabSetComboBoxString, _editTabColorUseComboBox ); - if ( isUsersSet() ) - { - _deleteUserButton.setEnabled( true ); - } - else - { - _deleteUserButton.setEnabled( false ); - } - if ( isOfficeSet() ) - { - _deleteOfficeButton.setEnabled( true ); - } - else - { - _deleteOfficeButton.setEnabled( false ); - } - - } - } - } - - private boolean isUsersSet() - { - boolean isUserSet = false; - - String setString = (String) _editTabSetComboBox.getSelectedItem(); - String userID = (String) _editTabUserIDComboBox.getSelectedItem(); - - if ( - ( setString != null ) && - ( userID != null ) && - ( setString.equalsIgnoreCase( "user" ) ) && - ( userID.equalsIgnoreCase( _userID ) ) ) - { - isUserSet = true; - } - - return isUserSet; - } - - private boolean isOfficeSet() - { - boolean isOfficeSet = false; - - String setString = (String) _editTabSetComboBox.getSelectedItem(); - - if ( - ( setString != null ) && - ( setString.equalsIgnoreCase( "office" ) ) ) - { - isOfficeSet = true; - } - - return isOfficeSet; - } - - private void populateSetComboBox( String setComboBoxString, JComboBox colorUseComboBox ) - { - String[] colorUseStringArray = getColorUseComboBoxString(); - - if ( setComboBoxString.equalsIgnoreCase( "default" ) ) - { - colorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseStringArray.length; i++ ) - { - colorUseComboBox.addItem( colorUseStringArray[ i ] ); - } - } - else if ( setComboBoxString.equalsIgnoreCase( "user" ) ) - { - updateUserIDComboBox(); - } - else if ( colorUseStringArray.length == 0 ) // empty database and office is selected - { - colorUseComboBox.removeAllItems(); - colorUseComboBox.addItem( "-----" ); - } - else if ( setComboBoxString.equalsIgnoreCase( "office" ) ) - { - colorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseStringArray.length; i++ ) - { - colorUseComboBox.addItem( colorUseStringArray[ i ] ); - } - displayColorScaleValues(); - } - } - - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - - - public static boolean validateInputParameters( String[] args ) - { - boolean valid = false; - - if ( args.length < 6 ) - { - System.out.println( "ColorChooserDialog " ); - } - else - { - valid = true; - } - - return valid; - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - //shutdown the thread in the ColorChooseDialog and set the _isRunning variable to false; - _thread.stop(); - _lastUpdateTime = -1; //indicate that we are closed - ColorChooserDialog._isRunning = false; - - this.dispose(); - } - - - public static long getLastUpdateTime() - { - return _lastUpdateTime; - } - - private static void setLastUpdateTimeToCurrentTime() - { - //return the time in seconds, so divide by 1000 - _lastUpdateTime = System.currentTimeMillis()/1000; - } - - public static void show(String jdbcConnectionString, String logFilePath, - String applicationName, String userID, String defaultColorFilePath, - String rgbColorFilePath ) - { - if (! _isRunning) //make sure that we don't invoke 2 of these dialogs at a time - { - _lastUpdateTime = 0; //when called a second time, this variable needs to be reset - - ColorChooserDialogDataMgr dataMgr = null; - ColorChooserDialog dialog = null; - boolean validInputParameters = false; - FileLogger logger = null; - - logger = new FileLogger( logFilePath ); - - dataMgr = new ColorChooserDialogDataMgr( jdbcConnectionString, logger, applicationName, defaultColorFilePath, rgbColorFilePath); - - dialog = new ColorChooserDialog( new JFrame(), dataMgr, userID ); - - _thread = new Thread(dialog); - _thread.start(); - _isRunning = true; - } - } - - public void run() - { - //This is here to allow the caller to continue functioning while this window is open - this.setVisible(true); - } - - - public static void main(String[] args) - { - boolean validInputParameters = false; - - validInputParameters = ColorChooserDialog.validateInputParameters( args ); - - if ( validInputParameters == true ) - { - - String jdbcConnectionString = args[0]; - String logFilePath = args[ 1 ]; - String applicationName = args[ 2 ]; - String userID = args[3]; - String defaultColorFilePath = args[ 4 ]; - String rgbColorFilePath = args[ 5 ]; - - show(jdbcConnectionString, logFilePath, applicationName, userID, defaultColorFilePath, rgbColorFilePath); - } - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorChooserDialogDataMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorChooserDialogDataMgr.java deleted file mode 100644 index 002d575152..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorChooserDialogDataMgr.java +++ /dev/null @@ -1,593 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.TreeSet; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.ColorNameRecord; -import ohd.hseb.ihfsdb.generated.ColorNameTable; -import ohd.hseb.ihfsdb.generated.ColorValueRecord; -import ohd.hseb.ihfsdb.generated.ColorValueTable; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.Logger; -import ohd.hseb.util.StringParser; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class ColorChooserDialogDataMgr { - private Database _db = null; - - private Logger _logger = null; - - private String _applicationName = null; - - private List _defaultColorScaleValueSetList = new ArrayList(); - - private List _colorValueTableColorScaleValueSetList = new ArrayList(); - - private HashMap _rgbColorMap = new HashMap(); - - private HashMap _hardCodedColorUseToDatabaseColorUseMap = new HashMap(); - - private String _userID = null; - - private String _defaultColorFilePath = null; - - private String _rgbColorFilePath = null; - - public ColorChooserDialogDataMgr(String baseConnectionString, - Logger logger, String applicationName, String defaultColorFilePath, - String rgbColorFilePath) { - super(); - - _db = new Database(); - _logger = logger; - _applicationName = applicationName; - _defaultColorFilePath = defaultColorFilePath; - _rgbColorFilePath = rgbColorFilePath; - - _db.connectWithDriverSearch(baseConnectionString); - - readRGBTextFile(); - readHydroViewDefaultColorFile(); - readColorValuesFromDatabase(); - // testRgbTextVersusColorNameTable(); - } - - public String getHardCodedColorUse(String colorUse) { - return (String) _hardCodedColorUseToDatabaseColorUseMap.get(colorUse); - } - - public void disconnect() { - _db.disconnect(); - } - - // ------------------------------------------------------------------------ - @Override - public void finalize() { - disconnect(); - } - - public void readColorValuesFromDatabase() { - ColorValueTable table = new ColorValueTable(_db); - ColorValue colorValue = new ColorValue(); - int i = 0; - /* - * String whereClause = "WHERE application_name='" + _applicationName + - * "' AND userid != 'default' " + - * "AND userid != 'factory_default' ORDER BY color_use_name, userid, duration, " - * + "threshold_value"; - */ - String whereClause = "WHERE application_name='" + _applicationName - + "' AND userid != 'factory_default' " - + "ORDER BY color_use_name, userid, duration, threshold_value"; - - List colorValueRecordsList = null; - ColorScaleValueSet colorScaleValueSet = new ColorScaleValueSet(); - ColorSet colorSet = null; - // Color colorObject = null; - ScaleValueSet scaleValueSet = null; - // double scaleValue = 0; - String currentIndexString = null, prevIndexString = null; - CodeTimer timer = new CodeTimer(); - timer.start(); - CodeTimer timer2 = new CodeTimer(); - String colorUseString = null; - - try { - colorValueRecordsList = table.select(whereClause); - } catch (SQLException e) { - e.printStackTrace(); - } - - timer.stop("Finished reading the ColorValue table in "); - timer2.start(); - - for (i = 0; i < colorValueRecordsList.size(); i++) { - colorValue = getColorValueFromColorValueRecord((ColorValueRecord) colorValueRecordsList - .get(i)); - if (i == 0) { - prevIndexString = getColorValueKeyString(colorValue); - scaleValueSet = new ScaleValueSet(); - colorSet = new ColorSet(); - scaleValueSet.addScaleValue(colorValue.getThresholdValue()); - colorSet.addNamedColor(getNamedColorByName(colorValue - .getColorName())); - - colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorValue.getColorUseName()); - if (colorUseString != null) { - colorScaleValueSet.setColorUseString(colorUseString); - } else { - colorScaleValueSet.setColorUseString(colorValue - .getColorUseName()); - } - - colorScaleValueSet.setDuration(colorValue.getDuration()); - colorScaleValueSet.setUserID(colorValue.getUserID()); - } else if (i == (colorValueRecordsList.size() - 1)) // Last entry in - // the records - // list - { - scaleValueSet.addScaleValue(colorValue.getThresholdValue()); - colorSet.addNamedColor(getNamedColorByName(colorValue - .getColorName())); - colorScaleValueSet.setColorSet(colorSet); - colorScaleValueSet.setScaleValueSet(scaleValueSet); - _colorValueTableColorScaleValueSetList.add(colorScaleValueSet); - } else { - currentIndexString = getColorValueKeyString(colorValue); - if (currentIndexString.equalsIgnoreCase(prevIndexString)) // same - // index - { - scaleValueSet.addScaleValue(colorValue.getThresholdValue()); - colorSet.addNamedColor(getNamedColorByName(colorValue - .getColorName())); - } else // new index - { - colorScaleValueSet.setColorSet(colorSet); - colorScaleValueSet.setScaleValueSet(scaleValueSet); - _colorValueTableColorScaleValueSetList - .add(colorScaleValueSet); - prevIndexString = currentIndexString; - scaleValueSet = new ScaleValueSet(); - colorSet = new ColorSet(); - colorScaleValueSet = new ColorScaleValueSet(); - scaleValueSet.addScaleValue(colorValue.getThresholdValue()); - colorSet.addNamedColor(getNamedColorByName(colorValue - .getColorName())); - colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorValue.getColorUseName()); - if (colorUseString != null) { - colorScaleValueSet.setColorUseString(colorUseString); - } else { - colorScaleValueSet.setColorUseString(colorValue - .getColorUseName()); - } - colorScaleValueSet.setDuration(colorValue.getDuration()); - colorScaleValueSet.setUserID(colorValue.getUserID()); - } - } - } - timer2.stop("Finished processing the ColorValue table in "); - } - - private NamedColor getNamedColorByName(String colorName) { - NamedColor namedColor = (NamedColor) getRGBColorMap().get(colorName); - - return namedColor; - } - - private String getColorValueKeyString(ColorValue colorValue) { - return colorValue.getUserID() + "|" + colorValue.getColorUseName() - + "|" + colorValue.getDuration(); - } - - private ColorValue getColorValueFromColorValueRecord(ColorValueRecord record) { - ColorValue colorValue = new ColorValue(); - - colorValue.setApplicationName(record.getApplication_name()); - colorValue.setColorName(record.getColor_name()); - colorValue.setColorUseName(record.getColor_use_name()); - colorValue.setDuration((double) record.getDuration() / (double) 3600); - colorValue.setThresholdUnit(record.getThreshold_unit()); - colorValue.setThresholdValue(record.getThreshold_value()); - colorValue.setUserID(record.getUserid()); - - return colorValue; - } - - private void saveColorScaleValueSet(List colorValueRecordList, - String userID, String colorUseString, double duration) { - ColorValueTable table = new ColorValueTable(_db); - - int durationSecondsInt = (int) (duration * 3600); - - String whereClause = "WHERE userID='" + userID - + "' AND application_name='" + _applicationName + "' AND " - + "color_use_name='" + colorUseString + "' AND duration=" - + durationSecondsInt; - - System.out.println(whereClause); - - try { - table.delete(whereClause); - for (int i = 0; i < colorValueRecordList.size(); i++) { - ColorValueRecord record = (ColorValueRecord) colorValueRecordList - .get(i); - table.insert(record); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - resetHvDefaultColorList(); - resetColorValueTableColorScaleValueSetList(); - } - - public void saveAsOffice(ColorScaleValueSet colorScaleValueSet) { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( - colorScaleValueSet, "default"); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorScaleValueSet.getColorUseString()); - if (colorUseString == null) // Checking to see if the color Use is in - // the hash map. If not, use the original - // name. - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - saveColorScaleValueSet(colorValueRecordList, "default", colorUseString, - colorScaleValueSet.getDuration()); - } - - public void saveAsUser(ColorScaleValueSet colorScaleValueSet, - double duration) { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( - colorScaleValueSet, _userID); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorScaleValueSet.getColorUseString()); - if (colorUseString == null) // Checking to see if the color Use is in - // the hash map. If not, use the original - // name. - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - saveColorScaleValueSet(colorValueRecordList, _userID, colorUseString, - duration); - } - - public void deleteAsUser(ColorScaleValueSet colorScaleValueSet) { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( - colorScaleValueSet, _userID); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorScaleValueSet.getColorUseString()); - - if (colorUseString == null) { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - deleteColorScaleValueSet(colorValueRecordList, _userID, colorUseString, - colorScaleValueSet.getDuration()); - } - - public void deleteAsOffice(ColorScaleValueSet colorScaleValueSet) { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( - colorScaleValueSet, "default"); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorScaleValueSet.getColorUseString()); - - if (colorUseString == null) { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - deleteColorScaleValueSet(colorValueRecordList, "default", - colorUseString, colorScaleValueSet.getDuration()); - } - - private void deleteColorScaleValueSet(List colorValueRecordList, - String userID, String colorUseString, double duration) { - ColorValueTable table = new ColorValueTable(_db); - - String whereClause = "WHERE userID='" + userID - + "' AND application_name='" + _applicationName + "' AND " - + "color_use_name='" + colorUseString + "' AND duration=" - + duration * 3600; - - try { - table.delete(whereClause); - } catch (SQLException e) { - e.printStackTrace(); - } - - resetHvDefaultColorList(); - resetColorValueTableColorScaleValueSetList(); - } - - private List getColorValueRecordListFromColorScaleValueSet( - ColorScaleValueSet colorScaleValueSet, String userID) { - List colorValueRecordList = new ArrayList(); - - ColorValueRecord record = new ColorValueRecord(); - ColorSet colorSet = colorScaleValueSet.getColorSet(); - List colorSetList = colorSet.getNamedColorList(); - List scaleValueSetList = colorScaleValueSet.getScaleValueSet() - .getScaleValueSet(); - String colorUseString = null; - - record.setApplication_name(_applicationName); - colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap - .get(colorScaleValueSet.getColorUseString()); - if (colorUseString == null) // Checking to see if the color Use is in - // the hash map. If not, use the original - // name. - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - record.setColor_use_name(colorUseString); - record.setDuration((int) (colorScaleValueSet.getDuration() * 3600)); - record.setUserid(userID); - record.setThreshold_unit("E"); - - for (int i = 0; i < scaleValueSetList.size(); i++) { - double scaleValue = (Double) scaleValueSetList.get(i); - NamedColor namedColor = (NamedColor) colorSetList.get(i); - - record.setThreshold_value(scaleValue); - record.setColor_name(namedColor.getName()); - - colorValueRecordList.add(record); - record = new ColorValueRecord(record); - } - return colorValueRecordList; - } - - public void setUserID(String userID) { - _userID = userID; - } - - private Set getColorNameTableSet() { - Set colorNameSet = new HashSet(); - ColorNameTable table = new ColorNameTable(_db); - - try { - List recordList = table.select(""); - for (ColorNameRecord record : recordList) { - colorNameSet.add(record.getColor_name()); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return colorNameSet; - } - - public void readRGBTextFile() { - File rgbColorFile = null; - BufferedReader reader = null; - String line = null; - String[] tokenizedString = null; - String colorName = null; - Set nameFromColorNameTableSet = getColorNameTableSet(); - rgbColorFile = new File(_rgbColorFilePath); - - try { - reader = new BufferedReader(new FileReader(rgbColorFile)); - line = reader.readLine(); // discard the first line - line = reader.readLine(); - while (line != null) { - tokenizedString = StringParser.tokenize(line); - colorName = getRGBColorName(tokenizedString); - - // if the read in RGB color name exists in the ColorName table, - // then add to the _rgbColorMap - if (nameFromColorNameTableSet.contains(colorName.toUpperCase())) { - NamedColor namedColor = new NamedColor(colorName, Integer - .parseInt(tokenizedString[0]), Integer - .parseInt(tokenizedString[1]), Integer - .parseInt(tokenizedString[2])); - - _rgbColorMap.put(colorName.toUpperCase(), namedColor); - } - line = reader.readLine(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - private String getRGBColorName(String[] tokenizedName) { - StringBuffer rgbColorName = new StringBuffer(); - - for (int i = 3; i < tokenizedName.length; i++) { - rgbColorName.append(tokenizedName[i]); - - if (i != (tokenizedName.length - 1)) { - rgbColorName.append(" "); - } - } - - return rgbColorName.toString(); - } - - public void readHydroViewDefaultColorFile() { - // String hydroviewDefaultColorFileName = null; - AppsDefaults appsDefaults = AppsDefaults.getInstance(); - File hydroviewDefaultColorFile = null; - BufferedReader reader = null; - String line = null; - String colorSetString = null; - String colorUseString = null; - String colorString = null; - String databaseColorUseString = null; - float scaleValue = 0; - NamedColor namedColor = null; - String[] tokenizedString = null; - - ColorScaleValueSet colorScaleValueSet = null; - ColorSet colorSet = new ColorSet(); - ScaleValueSet scaleValueSet = new ScaleValueSet(); - - hydroviewDefaultColorFile = new File(_defaultColorFilePath); - - try { - reader = new BufferedReader(new FileReader( - hydroviewDefaultColorFile)); - line = reader.readLine(); - while (line != null) { - if (line.trim().length() > 0) // not an empty line - { - tokenizedString = StringParser.tokenize(line); - if (line.indexOf("|") == -1) { - colorString = tokenizedString[0]; - namedColor = getNamedColorByName(colorString); - scaleValue = Float.valueOf(tokenizedString[1]); - colorSet.addNamedColor(namedColor); - scaleValueSet.addScaleValue(scaleValue); - - } else // line read in is the color set name (first line of - // each set) - { - colorScaleValueSet = new ColorScaleValueSet(); - - StringTokenizer tokenizer = new StringTokenizer(line, - "|"); - - colorUseString = tokenizer.nextToken(); - databaseColorUseString = tokenizer.nextToken(); - - insertColorUseStringIntoHashMap(colorUseString, - databaseColorUseString); - - colorScaleValueSet.setColorUseString(colorUseString); - } - } else // empty line - { - colorScaleValueSet.setColorSet(colorSet); - colorScaleValueSet.setScaleValueSet(scaleValueSet); - colorScaleValueSet.setUserID("HARDCODED"); - colorScaleValueSet.setDuration(0); - _defaultColorScaleValueSetList.add(colorScaleValueSet); - colorSet = new ColorSet(); - scaleValueSet = new ScaleValueSet(); - } - line = reader.readLine(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - private void testRgbTextVersusColorNameTable() { - ColorNameTable table = new ColorNameTable(_db); - List extraCrapList = new ArrayList(); - Set rgbHashSet = new TreeSet(_rgbColorMap.keySet()); - List rgbList = new ArrayList(_rgbColorMap.keySet()); - String colorName = null; - - try { - List recordList = table.select(""); - Set recordSet = new TreeSet(); - - for (int i = 0; i < recordList.size(); i++) { - ColorNameRecord record = (ColorNameRecord) recordList.get(i); - colorName = record.getColor_name(); - recordSet.add(getStringWithoutSpaces(colorName)); - if (!rgbHashSet.contains(colorName)) { - extraCrapList.add(colorName); - System.out - .println(colorName - + " is not in the RGB text file but is in the database"); - } - } - - for (int i = 0; i < rgbList.size(); i++) { - String rgbColorName = getStringWithoutSpaces((String) rgbList - .get(i)); - if (!recordSet.contains(rgbColorName)) { - extraCrapList.add(rgbColorName); - System.out - .println(rgbColorName - + " is not in the database but is in the RGB text file"); - } - } - - System.out.println("DONE"); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private String getStringWithoutSpaces(String colorName) { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < colorName.length(); i++) { - char c = colorName.charAt(i); - if (c != ' ') { - buffer.append(c); - } - } - - return buffer.toString(); - } - - private void insertColorUseStringIntoHashMap(String colorUseString, - String databaseColorUseString) { - _hardCodedColorUseToDatabaseColorUseMap.put(colorUseString, - databaseColorUseString); - _hardCodedColorUseToDatabaseColorUseMap.put(databaseColorUseString, - colorUseString); - } - - public List getDefaultColorScaleValueSetList() { - return _defaultColorScaleValueSetList; - } - - public void setApplicationName(String _applicationName) { - this._applicationName = _applicationName; - } - - public String getApplicationName() { - return _applicationName; - } - - public List getColorValueTableColorScaleValueSetList() { - return _colorValueTableColorScaleValueSetList; - } - - public void addColorScaleValueSetToColorValueTableList( - ColorScaleValueSet colorScaleValueSet) { - _colorValueTableColorScaleValueSetList.add(colorScaleValueSet); - } - - public void resetColorValueTableColorScaleValueSetList() { - _colorValueTableColorScaleValueSetList = new ArrayList(); - readColorValuesFromDatabase(); - } - - public void resetHvDefaultColorList() { - _defaultColorScaleValueSetList = new ArrayList(); - readHydroViewDefaultColorFile(); - } - - public HashMap getRGBColorMap() { - return _rgbColorMap; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorHolder.java deleted file mode 100644 index 2cb7f967f1..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorHolder.java +++ /dev/null @@ -1,25 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; - -public class ColorHolder -{ - private Color _color = null; - - public ColorHolder( Color color ) - { - setColor(color); - } - - public void setColor(Color color) - { - _color = color; - } - - public Color getColor() - { - return _color; - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorPickerDialog.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorPickerDialog.java deleted file mode 100644 index cea5ddb44a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorPickerDialog.java +++ /dev/null @@ -1,188 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JDialog; -import javax.swing.JPanel; - -import ohd.hseb.util.gui.ComponentHelper; - -public class ColorPickerDialog extends JDialog -{ - private ColorHolder _colorHolder = null; -// private ColorSet _colorSet = null; -// private int _indexValueOfDefaultColor = 0; - private Container _frameContentPane = getContentPane(); - private JPanel _colorDialogPanel = new JPanel(); - private JColorChooser _jColorChooserDialog = new JColorChooser(); - - private JPanel _buttonPanel = new JPanel(); - private JButton _okButton = new JButton( "OK" ); - private JButton _cancelButton = new JButton( "Cancel" ); - - -/* - public ColorPickerDialog( Frame owner, Color color, ColorSet colorSet ) - { - super( owner, "Color Picker", true ); - - _frameContentPane.setLayout( new GridBagLayout() ); - _colorDialogPanel.setLayout( new GridBagLayout() ); - - _jColorChooserDialog.setColor( color ); - - ComponentHelper.addFrameComponent( _frameContentPane, _colorDialogPanel, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _colorDialogPanel, _jColorChooserDialog, 1, 1, 1, 1, GridBagConstraints.BOTH ); - setSize( 400, 600 ); - - } -*/ -/* - public ColorPickerDialog( JDialog owner, Color color, ColorSet colorSet ) - { - super( owner, "Color Picker", true ); - _colorSet = colorSet; - _defaultColor = color; - initGUI(); - _indexValueOfDefaultColor = getIndexOfDefaultColorFromColorSet(); - - addListeners(); - } -*/ - public ColorPickerDialog( JDialog owner, ColorHolder colorHolder ) - { - super( owner, "Color Picker", true ); - _colorHolder = colorHolder; - initGUI(); -// _indexValueOfDefaultColor = getIndexOfDefaultColorFromColorSet(); - - addListeners(); - } - - - private void initGUI() - { - _frameContentPane.setLayout( new GridBagLayout() ); - _colorDialogPanel.setLayout( new GridBagLayout() ); - _buttonPanel.setLayout( new GridBagLayout() ); - - _jColorChooserDialog.setColor( _colorHolder.getColor() ); - - setSize( 430, 400 ); - _buttonPanel.setPreferredSize( new Dimension( 30, 40 ) ); -// X, Y, #Col, #Row - - ComponentHelper.addFrameComponent( _frameContentPane, _colorDialogPanel, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 1, 2, 1, 3, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _colorDialogPanel, _jColorChooserDialog, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _okButton, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _cancelButton, 2, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _okButton.addActionListener( new OkButtonListener() ); - _cancelButton.addActionListener( windowCloser ); - - - } - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - -/* - private int getIndexOfDefaultColorFromColorSet() - { - List colorList = _colorSet.getNamedColorList(); - Color extractedColor = null; - int index = -1; - - for ( int i = 0; i < colorList.size(); i++ ) - { - extractedColor = (Color) colorList.get( i ); - if ( extractedColor.equals( _defaultColor ) ) - { - index = i; - } - } - - return index; - } -*/ - - private class OkButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _colorHolder.setColor( _jColorChooserDialog.getColor() ); -// ColorPickerDialog.this.setVisible( false ); - closeWindow(); - } - } - - /* - private class OkButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - List colorSetList = _colorSet.getNamedColorList(); - Color colorObject = null; - - colorSetList.set( _indexValueOfDefaultColor, _jColorChooserDialog.getColor() ); - - closeWindow(); - } - } - - - private class OkButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - List colorSetList = _colorSet.getNamedColorList(); - Color colorObject = null; - - colorSetList.set( _indexValueOfDefaultColor, _jColorChooserDialog.getColor() ); - - closeWindow(); - } - } -*/ - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - - public static void main ( String[] args ) - { -// ColorPickerDialog colorPicker = new ColorPickerDialog( new Frame(), Color.blue, true ); -// colorPicker.setVisible( true ); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorScaleValueSet.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorScaleValueSet.java deleted file mode 100644 index 350a190d97..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorScaleValueSet.java +++ /dev/null @@ -1,100 +0,0 @@ -package ohd.hseb.color_chooser; - -public class ColorScaleValueSet -{ - private ColorSet _colorSet = null; - private ScaleValueSet _scaleValueSet = null; - private String _colorUseString = null; - private double _duration = -99999; - private String _userID = null; - - - public ColorScaleValueSet() - { - } - - public ColorScaleValueSet( ColorScaleValueSet colorScaleValueSet ) - { - setColorSet( new ColorSet( colorScaleValueSet.getColorSet() ) ); - setScaleValueSet( new ScaleValueSet( colorScaleValueSet.getScaleValueSet() ) ); - setColorUseString( new String( colorScaleValueSet.getColorUseString() ) ); - setUserID( new String( colorScaleValueSet.getUserID() ) ); - setDuration( colorScaleValueSet.getDuration() ); -/* - setColorSet( colorScaleValueSet.getColorSet() ); - setScaleValueSet( colorScaleValueSet.getScaleValueSet() ); - setColorUseString( colorScaleValueSet.getColorUseString() ); - setUserID( colorScaleValueSet.getUserID() ); - setDuration( colorScaleValueSet.getDuration() ); - */ - } - - public static ColorScaleValueSet getCopyOfColorScaleValueSet( ColorScaleValueSet colorScaleValueSet ) - { - ColorScaleValueSet returnColorScaleValueSet = new ColorScaleValueSet(); - - returnColorScaleValueSet.setColorSet( new ColorSet( colorScaleValueSet.getColorSet() ) ); - returnColorScaleValueSet.setScaleValueSet( new ScaleValueSet( colorScaleValueSet.getScaleValueSet() ) ); - returnColorScaleValueSet.setColorUseString( new String( colorScaleValueSet.getColorUseString() ) ); - returnColorScaleValueSet.setUserID( new String( colorScaleValueSet.getUserID() ) ); - returnColorScaleValueSet.setDuration( colorScaleValueSet.getDuration() ); - - return returnColorScaleValueSet; - } - - public String toString() - { - return _userID + " " + _colorUseString + " " + _duration + "\n" + _colorSet; - } - - public void setColorSet( ColorSet colorSet ) - { - _colorSet = colorSet; - } - - public ColorSet getColorSet() - { - return _colorSet; - } - - public void setScaleValueSet(ScaleValueSet scaleValueSet) - { - _scaleValueSet = scaleValueSet; - } - - public ScaleValueSet getScaleValueSet() - { - return _scaleValueSet; - } - - public void setColorUseString(String colorUseString) - { - _colorUseString = colorUseString; - } - - public String getColorUseString() - { - return _colorUseString; - } - - public void setDuration( double duration ) - { - _duration = duration; - } - - public double getDuration() - { - return _duration; - } - - public void setUserID( String userID ) - { - _userID = userID; - } - - public String getUserID() - { - return _userID; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorSet.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorSet.java deleted file mode 100644 index 724c0b74df..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorSet.java +++ /dev/null @@ -1,72 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - -public class ColorSet -{ - - private List _namedColorList = new ArrayList(); // List of NamedColor objects - - public ColorSet() - { - } - - public ColorSet( ColorSet colorSet ) - { - List namedColorList = colorSet.getNamedColorList(); - - for ( int i = 0; i < namedColorList.size(); i++ ) - { - NamedColor extractedNamedColor = (NamedColor) namedColorList.get( i ); - if ( extractedNamedColor != null ) - { - _namedColorList.add( new NamedColor( extractedNamedColor ) ); - } - } - } - - public ColorSet( List namedColorList ) - { - _namedColorList = namedColorList; - } - - public void addNamedColor( Color colorObject ) - { - _namedColorList.add( colorObject ); - } - - public void addNamedColorAtIndex( Color colorObject, int index ) - { - _namedColorList.add( index, colorObject ); - } - - public void deleteNamedColorAtIndex( int index ) - { - _namedColorList.remove( index ); - } - - public void replaceNamedColorAtIndex( Color colorObject, int index ) - { - _namedColorList.remove( index ); - _namedColorList.add( index, colorObject ); - } - - public String toString() - { - StringBuffer returnString = new StringBuffer(); - for ( int i = 0; i < _namedColorList.size(); i++ ) - { - NamedColor namedColor = (NamedColor) _namedColorList.get( i ); - returnString.append( namedColor + "\n" ); - } - - return returnString.toString(); - } - - public List getNamedColorList() - { - return _namedColorList; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorValue.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorValue.java deleted file mode 100644 index 5f6a45fe5e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ColorValue.java +++ /dev/null @@ -1,87 +0,0 @@ -package ohd.hseb.color_chooser; - -public class ColorValue -{ - private String _userID; - private String _applicationName; - private String _colorUseName; - private double _duration; - private double _thresholdValue; - private String _thresholdUnit; - private String _colorName; - - public void setUserID( String userID ) - { - _userID = userID; - } - - public String getUserID() - { - return _userID; - } - - public void setApplicationName( String applicationName ) - { - _applicationName = applicationName; - } - - public String getApplicationName() - { - return _applicationName; - } - - public void setColorUseName( String colorUseName ) - { - _colorUseName = colorUseName; - } - - public String getColorUseName() - { - return _colorUseName; - } - - public void setDuration( double duration ) - { - _duration = duration; - } - - public double getDuration() - { - return _duration; - } - - public void setThresholdValue( double thresholdValue ) - { - _thresholdValue = thresholdValue; - } - - public double getThresholdValue() - { - return _thresholdValue; - } - - public void setThresholdUnit( String thresholdUnit ) - { - _thresholdUnit = thresholdUnit; - } - - public String getThresholdUnit() - { - return _thresholdUnit; - } - - public void setColorName( String colorName ) - { - _colorName = colorName; - } - - public String getColorName() - { - return _colorName; - } - - public String toString() - { - return _userID + " " + _colorUseName + " " + _duration + " " + _thresholdValue + " " + _colorName; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/NamedColor.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/NamedColor.java deleted file mode 100644 index 6bc74c96ee..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/NamedColor.java +++ /dev/null @@ -1,48 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; - -import ohd.hseb.util.StringParser; - -public class NamedColor extends Color -{ - private String _name = null; - - public NamedColor( String name, int redValue, int greenValue, int blueValue ) - { - super( redValue, greenValue, blueValue ); - String[] tokenizedString = StringParser.tokenize( name ); - StringBuffer nameBuffer = new StringBuffer(); - for ( int i = 0; i < tokenizedString.length; i++ ) - { - nameBuffer.append( tokenizedString[ i ] ); - } - setName( nameBuffer.toString().toUpperCase() ); - } - - public NamedColor( String name, Color color ) - { - this( name, color.getRed(), color.getGreen(), color.getBlue() ); - } - - public NamedColor( NamedColor namedColor ) - { - this( namedColor.getName(), namedColor ); - } - - public String toString() - { - return _name + " " + super.toString(); - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/NamedColorMatcher.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/NamedColorMatcher.java deleted file mode 100644 index b534d90e9c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/NamedColorMatcher.java +++ /dev/null @@ -1,94 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class NamedColorMatcher -{ - List _namedColorList = null; - - public NamedColorMatcher(Map nameToNamedColorMap) - { - _namedColorList = new ArrayList( nameToNamedColorMap.values()); - } - - public NamedColor getClosestNamedColor(Color color) - { - NamedColor bestNamedColor = null; - Set specialWhiteNameSet = new HashSet(); - Set specialBlackNameSet = new HashSet(); - specialWhiteNameSet.add("GRAY100"); - specialBlackNameSet.add("GRAY0"); - - List colorList = _namedColorList; - - for (NamedColor namedColor : colorList) - // for (int i = 0; i < _namedColorList.size(); i++) - { - // NamedColor namedColor = (NamedColor) _namedColorList.get(i); - - if (isCloserColor(color, namedColor, bestNamedColor)) - { - bestNamedColor = namedColor; - } - } - -// System.out.println("Desired Color was " + color); -// System.out.println("Found Named Color was " + bestNamedColor); - if ( bestNamedColor != null ) - { - String bestNamedColorString = bestNamedColor.getName().toUpperCase(); - if ( specialWhiteNameSet.contains( bestNamedColorString ) ) - { - bestNamedColor = new NamedColor( "WHITE", bestNamedColor ); - } - else if ( specialBlackNameSet.contains( bestNamedColorString ) ) - { - bestNamedColor = new NamedColor( "BLACK", bestNamedColor ); - } - } - return bestNamedColor; - } - - // -------------------------------------------------------------------------------------------------------- - private boolean isCloserColor(Color color, NamedColor testNamedColor, NamedColor bestNamedColor) - { - boolean isCloser = false; - - if ( (testNamedColor != null) && (bestNamedColor != null) ) - { - double distanceFromTestNamedColor = getDistance(color, testNamedColor); - double distanceFromBestNamedColor = getDistance(color, bestNamedColor); - - if (distanceFromTestNamedColor < distanceFromBestNamedColor) - { - isCloser = true; - } - } - else if ((bestNamedColor == null) && (testNamedColor != null) ) - { - isCloser = true; - } - return isCloser; - } - // -------------------------------------------------------------------------------------------------------- - private double getDistance(Color color, NamedColor namedColor) - { - double distance = 0.0; - - int redDiff = color.getRed() - namedColor.getRed(); - int greenDiff = color.getGreen() - namedColor.getGreen(); - int blueDiff = color.getBlue() - namedColor.getBlue(); - - //intentionally not taking the square root - Chip - distance = (redDiff * redDiff) + (greenDiff * greenDiff) + (blueDiff * blueDiff); - - return distance; - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ScaleValueSet.java b/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ScaleValueSet.java deleted file mode 100644 index 8f7d4d9167..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/color_chooser/ScaleValueSet.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.util.ArrayList; -import java.util.List; - -public class ScaleValueSet -{ - private List _scaleValueSet = new ArrayList(); - - public ScaleValueSet() - { - } - - public ScaleValueSet( List scaleValueSet ) - { - setScaleValueSet( scaleValueSet ); - } - - public ScaleValueSet( ScaleValueSet scaleValueSet ) - { - List scaleValueSetList = scaleValueSet.getScaleValueSet(); - - for ( int i = 0; i < scaleValueSetList.size(); i++ ) - { - _scaleValueSet.add( scaleValueSetList.get( i ) ); - } - } - - public void addScaleValue( double value ) - { - _scaleValueSet.add( value ); - } - - public void addScaleValueAtIndex( double value, int index ) - { - _scaleValueSet.add( index, value ); - } - - public void replaceScaleValueAtIndex( double value, int index ) - { - _scaleValueSet.remove( index ); - _scaleValueSet.add( index, value ); - } - - public void deleteScaleValueAtIndex( int index ) - { - _scaleValueSet.remove( index ); - } - - public void setScaleValueSet( List scaleValueSet ) - { - _scaleValueSet = scaleValueSet; - } - - public List getScaleValueSet() - { - return _scaleValueSet; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/damcrest/README.TXT b/cave/ohd.hseb.common/src/ohd/hseb/damcrest/README.TXT deleted file mode 100644 index a7bb815355..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/damcrest/README.TXT +++ /dev/null @@ -1,3 +0,0 @@ -Damcrest not ported over yet? Some discussion of is it needed ?? - -Frank 08/21/08, (with Eric Babin) pushed to TO-11 minimally. \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/DataServicesGlobals.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/DataServicesGlobals.java deleted file mode 100644 index b6b4c1af96..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/DataServicesGlobals.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.util.ArrayList; - -public class DataServicesGlobals //This is a singleton class -{ - private static int count = 0; - private static DataServicesGlobals dataServicesGlobals = null; - private static String missingRepresentation = "-"; - - public static ArrayList dataServiceObservers = null; - public static ArrayList dataDetermObservers = null; - public static ArrayList dataWatSupObservers = null; - public static ArrayList dataEnsembleObservers = null; - - private DataServicesGlobals() - { - } - - public static synchronized DataServicesGlobals getSingleInstanceOfDataServicesGlobals() - { - if(dataServicesGlobals == null) - { - dataServicesGlobals = new DataServicesGlobals(); - } - - dataServiceObservers = new ArrayList(); - dataDetermObservers = new ArrayList(); - dataWatSupObservers = new ArrayList(); - dataEnsembleObservers = new ArrayList(); - - return dataServicesGlobals; - } - - public String getMissingRepresentation() { - return missingRepresentation; - } - - public void setMissingRepresentation(String missingRepresentation) { - DataServicesGlobals.missingRepresentation = missingRepresentation; - } - - public synchronized void incrementCount() - { - count++; - } - - public synchronized void decrementCount() - { - count--; - } - public synchronized int getCount() - { - return count; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/FcstDataDetermWindow.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/FcstDataDetermWindow.java deleted file mode 100644 index bbf6c925a4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/FcstDataDetermWindow.java +++ /dev/null @@ -1,1276 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.ArrayList; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.text.BadLocationException; -import javax.swing.text.Element; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.FcstPtDetermRecord; -import ohd.hseb.util.gui.DateTextField; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class FcstDataDetermWindow implements Subject -{ - private DataServicesGlobals dataServicesGlobals = null; - private java.util.List lhvmRowDataList = null; - private LhvmDataManager lhvmDataManager = null; - private LhvmLogger lhvmLogger = null; - private JTableManager jtm = null; - private JFrame lhvm = null; - - private FcstPtDetermJTableRowData selectedFcstPtDetermJTableRowData = null; - private ArrayList selectedFcstPtDetermJTableRowsDataList = null; - - private JTextField locationTextField = null; - private JComboBox snowMethodTextField = null; - private JComboBox hydrolTextField = null; - private JComboBox hydraulTextField = null; - private JComboBox issueCriteriaTextField = null; - private JComboBox floodTextField = null; - private JComboBox droughtTextField = null; - private JComboBox horizonTextField = null; - private JTextField qpfTextField = null; - private JTextField qtfTextField = null; - private JTextField qzfTextField = null; - private JComboBox normalTextField = null; - private JTextField upstreamSegTextField = null; - private JComboBox reservoirModelTextField = null; - private JComboBox genMethodTextField = null; - private JTextField consumptiveUseTextField = null; - private JTextField channelLossTextField = null; - private JTextField numElevZonesTextField = null; - - private JButton insertButton = null; - private JButton deleteButton = null; - private JButton clearButton = null; - private JButton closeButton = null; - private JButton refreshButton = null; - - private JTextField stationSearchTextField = null; - - private JScrollPane tableScrollPane = null; - private JPanel tableScrollPanePanel = null; - - private DateTextField implDateTextField = null; - private DateTextField webDateTextField = null; - - private int numRows; - private JLabel numRowsLabel = null; - private JTextArea consoleTextArea = null; - private int origNumRows; - - private java.util.List lhvmRowDataList1 = null; - private java.util.List lhvmRowDataList2 = null; - private java.util.List lhvmRowDataList3 = null; - private java.util.List lhvmRowDataList4 = null; - private java.util.List lhvmRowDataList5 = null; - private java.util.List lhvmRowDataList7 = null; - private java.util.List lhvmRowDataList8 = null; - private java.util.List lhvmRowDataList9 = null; - - private String str1[] = null; - private String str2[] = null; - private String str3[] = null; - private String str4[] = null; - private String str5[] = null; - private String str7[] = null; - private String str8[] = null; - private String str9[] = null; - - private ArrayList observers = null; - - private JButton filterOptionsButton; - - public void addObserver(Observer observer) - { - if(observers != null) - { - observers.add(observer); - } - } - public void removeObserver(Observer observer) - { - if(observers != null) - { - observers.remove(observer); - } - } - - public void letKnowOfChanges() - { - if(observers != null) - { - for(int i=0;i 0 || numElevZonesTextField.getText().length() > 0 || - qpfTextField.getText().length() > 0 || - consumptiveUseTextField.getText().length() > 0 || channelLossTextField.getText().length() > 0 || - qtfTextField.getText().length() > 0 || qzfTextField.getText().length() > 0) - { - activateClearButton(); - } - else - { - deActivateClearButton(); - } - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtDetermJTableRowsDataList != null && selectedFcstPtDetermJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtDetermJTableRowsDataList != null && selectedFcstPtDetermJTableRowsDataList.size() == 1) - { - selectedFcstPtDetermJTableRowData = (FcstPtDetermJTableRowData) selectedFcstPtDetermJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtDetermJTableRowsDataList != null && selectedFcstPtDetermJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtDetermJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtDetermJTableRowsDataList.size() == 1) - { - selectedFcstPtDetermJTableRowData = (FcstPtDetermJTableRowData) selectedFcstPtDetermJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtDetermJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtDetermJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - lhvm.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - String currentLidFromRowsInsideLoop = null; - String currentHydrolMethodFromRowsInsideLoop = null; - String currentHydraulMethodFromRowsInsideLoop = null; - String currentSnowMethodFromRowsInsideLoop = null; - String currentIssueCritFromRowsInsideLoop = null; - String currentUpstreamSegFromRowsInsideLoop = null; - String currentReservoirModelFromRowsInsideLoop = null; - int currentHoursQpfFromRowsInsideLoop; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtDetermRecord record = new FcstPtDetermRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - Object[] options = { "YES", "NO" }; - - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - record.setSnow_method(str4[snowMethodTextField.getSelectedIndex()]); - record.setFrequpd_normal(str5[normalTextField.getSelectedIndex()]); - record.setFrequpd_flood(str5[floodTextField.getSelectedIndex()]); - record.setFrequpd_drought(str5[droughtTextField.getSelectedIndex()]); - record.setUpstream_seg(upstreamSegTextField.getText().toUpperCase()); - record.setReservoir_model(str7[reservoirModelTextField.getSelectedIndex()]); - record.setFcst_gen_method(str8[genMethodTextField.getSelectedIndex()]); - record.setFcst_horizon(str9[horizonTextField.getSelectedIndex()]); - if(consumptiveUseTextField.getText().length() > 0 && !consumptiveUseTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setConsumptive_use(consumptiveUseTextField.getText()); - } - else - { - record.setConsumptive_use("N"); - } - if(channelLossTextField.getText().length() > 0 && !channelLossTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setChannel_loss(channelLossTextField.getText()); - } - else - { - record.setChannel_loss("N"); - } - try - { - if(numElevZonesTextField.getText().length() > 0) - { - if(Short.valueOf(numElevZonesTextField.getText()) > 0) - { - record.setNum_elev_zones(Short.valueOf(numElevZonesTextField.getText())); - } - else - { - JOptionPane.showMessageDialog(null, "'Num Elev Zones' should be '1' or greater. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Elev Zones text box; It must be a number. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - try - { - if(qpfTextField.getText().length() > 0) - { - record.setHours_qpf(Short.valueOf(qpfTextField.getText())); - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the QPF text box; It must be a number. Aborting insert."); - return; - } - try - { - if(qtfTextField.getText().length() > 0 && !qtfTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setHours_qtf(Short.valueOf(qtfTextField.getText())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the QTF text box; It must be a number. Aborting insert."); - return; - } - try - { - if(qzfTextField.getText().length() > 0 && !qzfTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setHours_qzf(Short.valueOf(qzfTextField.getText())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the QZF text box; It must be a number. Aborting insert."); - return; - } - record.setHydrol_method(str2[hydrolTextField.getSelectedIndex()]); - record.setHydraul_method(str3[hydraulTextField.getSelectedIndex()]); - if(record.getHydraul_method().equalsIgnoreCase("None")) - { - if(!record.getLid().equalsIgnoreCase(record.getUpstream_seg()) && !record.getUpstream_seg().equalsIgnoreCase("xxxxx")) - { - JOptionPane.showMessageDialog(null, "Routing Method can be 'None' only if LID and Upstream Segment are the same or Upstream Segment is 'XXXXX'. Aborting insert."); - return; - } - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } - record.setDef_issue_crit(str1[issueCriteriaTextField.getSelectedIndex()]); -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - int success = lhvmDataManager.insertOrUpdateDetermTable(record); - if(success != -1) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtDeterm(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0 || numElevZonesTextField.getText().length() > 0 || - consumptiveUseTextField.getText().length() > 0 || channelLossTextField.getText().length() > 0 || - numMonClimTextField.getText().length() > 0 || numDayHydTextField.getText().length() > 0) - { - activateClearButton(); - } - else - { - deActivateClearButton(); - } - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtEnsembleJTableRowsDataList != null && selectedFcstPtEnsembleJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList != null && selectedFcstPtEnsembleJTableRowsDataList.size() == 1) - { - selectedFcstPtEnsembleJTableRowData = (FcstPtEnsembleJTableRowData) selectedFcstPtEnsembleJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList != null && selectedFcstPtEnsembleJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtEnsembleJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList.size() == 1) - { - selectedFcstPtEnsembleJTableRowData = (FcstPtEnsembleJTableRowData) selectedFcstPtEnsembleJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtEnsembleJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - lhvm.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - String currentLidFromRowsInsideLoop = null; - String currentHydrolMethodFromRowsInsideLoop = null; - String currentHydraulMethodFromRowsInsideLoop = null; - String currentSnowMethodFromRowsInsideLoop = null; - String currentFcstTypeFromRowsInsideLoop = null; - String currentFlowTypeFromRowsInsideLoop = null; - String currentUpstreamSegFromRowsInsideLoop = null; - String currentReservoirModelFromRowsInsideLoop = null; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtESPRecord record = new FcstPtESPRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - Object[] options = { "YES", "NO" }; - - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - if(!externalDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !externalDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setExternal_date(DbTimeHelper.getLongTimeFromDateString(externalDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setExternal_date(Long.MIN_VALUE); - } - record.setFrequpd_normal(str6[normalTextField.getSelectedIndex()]); - record.setFrequpd_flood(str6[floodTextField.getSelectedIndex()]); - record.setFrequpd_drought(str6[droughtTextField.getSelectedIndex()]); - record.setPost_processor(str7[postProcessingTextField.getSelectedIndex()]); - record.setUpstream_seg(upstreamSegTextField.getText().toUpperCase()); - record.setReservoir_model(str9[reservoirModelTextField.getSelectedIndex()]); - record.setFcst_horizon(str10[horizonTextField.getSelectedIndex()]); - if(consumptiveUseTextField.getText().length() > 0 && !consumptiveUseTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setConsumptive_use(consumptiveUseTextField.getText()); - } - else - { - record.setConsumptive_use("N"); - } - if(channelLossTextField.getText().length() > 0 && !channelLossTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setChannel_loss(channelLossTextField.getText()); - } - else - { - record.setChannel_loss("N"); - } - try - { - if(numElevZonesTextField.getText().length() > 0) - { - if(Short.valueOf(numElevZonesTextField.getText()) > 0) - { - record.setNum_elev_zones(Short.valueOf(numElevZonesTextField.getText())); - } - else - { - JOptionPane.showMessageDialog(null, "'Num Elev Zones' should be '1' or greater. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - } - else - { - record.setNum_elev_zones(Short.MIN_VALUE); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Elev Zones text box; It must be a number. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - try - { - if(numMonClimTextField.getText().length() > 0 && !numMonClimTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setNummonclim(Short.valueOf(numMonClimTextField.getText())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Mon Clim text box; It must be a number. Aborting insert."); - return; - } - try - { - if(numDayHydTextField.getText().length() > 0 && !numDayHydTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setNumdayhyd(Short.valueOf(numDayHydTextField.getText())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Day Hyd text box; It must be a number. Aborting insert."); - return; - } - record.setHydrol_method(str4[hydrolTextField.getSelectedIndex()]); - record.setHydraul_method(str5[hydraulTextField.getSelectedIndex()]); - if(record.getHydraul_method().equalsIgnoreCase("None")) - { - if(!record.getLid().equalsIgnoreCase(record.getUpstream_seg()) && !record.getUpstream_seg().equalsIgnoreCase("xxxxx")) - { - JOptionPane.showMessageDialog(null, "Routing Method can be 'None' only if LID and Upstream Segment are the same or Upstream Segment is 'XXXXX'. Aborting insert."); - return; - } - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } - record.setSnow_method(str3[snowMethodTextField.getSelectedIndex()]); - record.setFlowtype(str2[flowTypeTextField.getSelectedIndex()]); - record.setFcsttype(str1[fcstTypeTextField.getSelectedIndex()]); -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - int success = lhvmDataManager.insertOrUpdateEnsembleTable(record); - if(success != -1) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtEnsemble(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtServiceJTableRowsDataList != null && selectedFcstPtServiceJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtServiceJTableRowsDataList != null && selectedFcstPtServiceJTableRowsDataList.size() == 1) - { - selectedFcstPtServiceJTableRowData = (FcstPtServiceJTableRowData) selectedFcstPtServiceJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtServiceJTableRowsDataList != null && selectedFcstPtServiceJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtServiceJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtServiceJTableRowsDataList.size() == 1) - { - selectedFcstPtServiceJTableRowData = (FcstPtServiceJTableRowData) selectedFcstPtServiceJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtServiceJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtServiceJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - lhvm.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - String currentLidFromRowsInsideLoop = null; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtServiceRecord record = new FcstPtServiceRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - record.setService_type(str1[serviceTypeTextField.getSelectedIndex()]); - try - { - if(floodThersholdTextField.getText().length() > 0 && !floodThersholdTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setFlood_thres(Double.parseDouble(floodThersholdTextField.getText())); - } - else - { - record.setFlood_thres(Double.MIN_VALUE); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Flood Threshold text box; It must be a number. Aborting insert."); - return; - } - try - { - if(exceedProbTextField.getText().length() > 0 && !exceedProbTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setExceed_prob(Short.parseShort(exceedProbTextField.getText())); - } - else - { - record.setExceed_prob(Short.MIN_VALUE); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Exceed Probability text box; It must be a number. Aborting insert."); - return; - } - Object[] options = { "YES", "NO" }; - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - if(!startDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !startDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setAnal_start_date(DbTimeHelper.getLongTimeFromDateString(startDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setAnal_start_date(Long.MIN_VALUE); - } - if(!endDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !endDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setAnal_end_date(DbTimeHelper.getLongTimeFromDateString(endDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setAnal_end_date(Long.MIN_VALUE); - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - int success = lhvmDataManager.insertOrUpdateServiceTable(record); - if(success != -1) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtService(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - activateClearButton(); - } - else - { - deActivateClearButton(); - } - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtWatsupJTableRowsDataList != null && selectedFcstPtWatsupJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtWatsupJTableRowsDataList != null && selectedFcstPtWatsupJTableRowsDataList.size() == 1) - { - selectedFcstPtWatsupJTableRowData = (FcstPtWatSupJTableRowData) selectedFcstPtWatsupJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtWatsupJTableRowsDataList != null && selectedFcstPtWatsupJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtWatsupJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtWatsupJTableRowsDataList.size() == 1) - { - selectedFcstPtWatsupJTableRowData = (FcstPtWatSupJTableRowData) selectedFcstPtWatsupJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtWatsupJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtWatsupJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - lhvm.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - String currentLidFromRowsInsideLoop = null; - String currentwatsupMethodFromRowsInsideLoop = null; - String currentwatsupCoordAgencyFromRowsInsideLoop = null; - String currentNormalFromRowsInsideLoop = null; - String currentPeriodReqFromRowsInsideLoop = null; - String currentWatsupCritFromRowsInsideLoop = null; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtWatSupRecord record = new FcstPtWatSupRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - Object[] options = { "YES", "NO" }; - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - if(customerDescTextField.getText().length() > 0 && !customerDescTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setCustomer_desc(customerDescTextField.getText()); - } - else - { - null_or_not = 1; - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } - record.setFrequpd_normal(str4[normalTextField.getSelectedIndex()]); - record.setWatsup_method(str5[watsupMethodTextField.getSelectedIndex()]); - record.setWatsup_coord_agency(str3[watsupCoordAgencyTextField.getSelectedIndex()]); - record.setWatsup_crit(str2[watsupCritTextField.getSelectedIndex()]); - record.setPeriod_req(str1[periodReqTextField.getSelectedIndex()]); - record.setWatsup_resp_agency(str6[respAgencyTextField.getSelectedIndex()]); -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - int success = lhvmDataManager.insertOrUpdateWatsupTable(record); - if(success != -1) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtWatsup(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - selectedServiceTableViewViewJTableRowData = (ServiceTableViewViewJTableRowData) selectedServiceTableViewViewJTableRowsDataList.get(0); - showCurrentRowData(); - } - else if(selectedServiceTableViewViewJTableRowsDataList == null) - { - lhvmRowDataList = lhvmDataManager.readDataFromPtServiceView(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - jtm.refreshDisplay(); - deActivateDeleteButton(); - clearForm(); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - } - } - - private void appendToConsoleMessage(String lid) - { - String valueToBeSet = new String(consoleTextArea.getText() + "\n" + "Exception getting number of entries from database for lid: " + lid + " "); - consoleTextArea.insert("", 0); - consoleTextArea.insert(valueToBeSet, 0); - } - - public LhvmApplicationWindow() - { - lhvmAppWindow = this; - dataServicesGlobals = DataServicesGlobals.getSingleInstanceOfDataServicesGlobals(); - dataServicesGlobals.incrementCount(); - - lhvm = new JFrame("Point Services Database Manager"); - lhvm.setSize(1100, 500); - lhvm.setLocation(20,50); - - //Fix the dimensions of this window i.e. dis-allow window resizing - Dimension d = new Dimension(1135, 790); - new WindowResizingManager(lhvm, d, d); - - lhvm.setResizable(false); - //lhvm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - GridBagLayout gbl = new GridBagLayout(); - lhvm.setLayout(gbl); - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.HORIZONTAL; - - - JMenuBar menuBar = new JMenuBar(); - - JMenu fileMenu = new JMenu("File"); - menuBar.add(fileMenu); - //JMenuItem importItem = new JMenuItem("Import from file"); - //importItem.setEnabled(false); - //JMenuItem exportItem = new JMenuItem("Export to file"); - //exportItem.setEnabled(false); - closeItem = new JMenuItem("Close Application"); - //closeItem.addActionListener(ActionListener); - //fileMenu.add(importItem); - //fileMenu.add(exportItem); - fileMenu.add(closeItem); - closeItem.addActionListener(new MenuSelectActionListener()); - - setupTableMenu = new JMenu("Setup"); - fcstRefTablesItem = new JMenuItem("RefTables"); - fcstRefTablesItem.addActionListener(new MenuSelectActionListener()); - //stationsFilterOptionsItem.addActionListener(ActionListener); - setupTableMenu.add(fcstRefTablesItem); - - JMenu tablesMenu = new JMenu("ServiceTypes"); - menuBar.add(tablesMenu); - menuBar.add(setupTableMenu); - fcstPtServiceItem = new JMenuItem("Data Service"); - fcstPtWatsUpItem = new JMenuItem("Water Supply Forecast"); - fcstPtDetermItem = new JMenuItem("Deterministic Forecast"); - fcstPtESPItem = new JMenuItem("Ensemble Forecast"); - fcstPtServiceItem.addActionListener(new MenuSelectActionListener()); - fcstPtDetermItem.addActionListener(new MenuSelectActionListener()); - fcstPtESPItem.addActionListener(new MenuSelectActionListener()); - fcstPtWatsUpItem.addActionListener(new MenuSelectActionListener()); - //stationsFilterOptionsItem.addActionListener(ActionListener); - tablesMenu.add(fcstPtServiceItem); - tablesMenu.add(fcstPtWatsUpItem); - tablesMenu.add(fcstPtDetermItem); - tablesMenu.add(fcstPtESPItem); - - JMenu aboutMenu = new JMenu("Help"); - menuBar.add(aboutMenu); - aboutItem = new JMenuItem("About Forecast Services"); - aboutMenu.add(aboutItem); - aboutItem.addActionListener(new MenuSelectActionListener()); - - - // Install the menu bar in the frame - lhvm.setJMenuBar(menuBar); - - - - - - JLabel consoleLabel = new JLabel("-----Database Messages-----"); - consoleLabel.setForeground(Color.red); - consoleTextArea = new JTextArea(2,50); - - Font font = new Font("Serif", Font.BOLD, 20); - consoleTextArea.setFont(font); - consoleTextArea.setForeground(Color.green); - consoleTextArea.setBackground(Color.black); - consoleTextArea.setCaretColor(Color.red); - consoleTextArea.setBorder(BorderFactory.createEtchedBorder() ); - consoleTextArea.setLineWrap(true); - - - String[] columnsToBeDisplayed = {"Location ID","Name", "Stream", "State","County","Hsa"}; - lhvmLogger = new LhvmLogger(); - lhvmDataManager = LhvmDataManager.getSingleInstanceOfDataManager(jdbcUrl, lhvmLogger,dataServicesGlobals.getMissingRepresentation()); - java.util.List lhvmColumnDescriptorList = new ArrayList(); - lhvmRowDataList = lhvmDataManager.readDataFromPtServiceView(); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Location ID", true, 150, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Name", true, 250, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Stream", true, 200, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("State", true, 125, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("County", true, 200, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Hsa", true, 125, "center")); - jtm = new ComplexJTableManager(lhvmColumnDescriptorList, lhvmRowDataList); - jtm.setDisplayableColumns(columnsToBeDisplayed, false, true); - jtm.setPreferredSizeForJScrollPane(new Dimension(1100, 500)); - jtm.addTableListener(new ServiceTableViewListSelectListener()); - tableScrollPane = jtm.getJScrollPane(); - //jtm.setTableToolTipText("str"); - tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(tableScrollPane); - - String tempStr = null; - if(LhvmDataManager.displayedMessageLhvmWindow != null) - { - tempStr = new String(LhvmDataManager.displayedMessageLhvmWindow); - } - LhvmDataManager.displayedMessageLhvmWindow = new StringBuffer(); - LhvmDataManager.displayedMessageLhvmWindow.append(LhvmDataManager.databaseMessage); - if(tempStr != null) - { - LhvmDataManager.displayedMessageLhvmWindow.append(tempStr); - } - consoleTextArea.insert(new String(LhvmDataManager.displayedMessageLhvmWindow), 0); - - // Get paragraph element - Element paragraph = consoleTextArea.getDocument().getDefaultRootElement(); - - // Get number of content elements - int contentCount = paragraph.getElementCount(); - - // Get index ranges for each content element. - // Each content element represents one line. - // Each line includes the terminating newline. - for (int i=0; i 1) - { - activateDeleteButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedServiceTableViewViewJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - clearForm(); - } - else if(selectedServiceTableViewViewJTableRowsDataList.size() == 1) - { - selectedServiceTableViewViewJTableRowData = (ServiceTableViewViewJTableRowData) selectedServiceTableViewViewJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - } - else if(selectedServiceTableViewViewJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedServiceTableViewViewJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - lhvm.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class MenuSelectActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - if(e.getSource().equals(fcstPtServiceItem)) - { - FcstDataServiceWindow fcstDataServiceWindow = new FcstDataServiceWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataServiceWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstPtWatsUpItem)) - { - FcstDataWatSupWindow fcstDataWatSupWindow = new FcstDataWatSupWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataWatSupWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstPtDetermItem)) - { - FcstDataDetermWindow fcstDataDetermWindow = new FcstDataDetermWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataDetermWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstPtESPItem)) - { - FcstDataEnsembleWindow fcstDataEnsembleWindow = new FcstDataEnsembleWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataEnsembleWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstRefTablesItem)) - { - new ReferenceTablesWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - } - else if(e.getSource().equals(closeItem)) - { - lhvm.dispose(); -// System.exit(0); - } - else if(e.getSource().equals(aboutItem)) - { - JOptionPane.showMessageDialog(null, "Application: Forecast Services\n\n" + - "Version: Awips Release OB8.3\n\n" + "Date: Jan 2'nd, 2008\n\n" + - "Developed by: National Weather Service,\n Office of Hydrologic development, \n Hydrology Laboratory\n\n", - "Forecast Services", JOptionPane.INFORMATION_MESSAGE); - } - } - } - - private class DeleteActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - } - } - -/* private class RefreshActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - lhvmRowDataList = lhvmDataManager.readDataFromPtServiceView(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - jtm.refreshDisplay(); - deActivateDeleteButton(); - clearForm(); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - } - }*/ - - private class CloseActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - operationCloseWindow(); - } - } - - private class ServiceTableViewListSelectListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent e) - { - buttonsActivateWhenSelected(); - } - } - - private class SearchTextTypedActionListener implements KeyListener - { - String currentLidFromRowsInsideLoop; - int[] rowIndices; - int index; - - public void init() - { - index = -1; - rowIndices = new int[lhvmRowDataList.size()]; - - for(int i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - for(int i=0;i < serviceTableViewInfmList.size(); i++) - { - serviceTableViewRecord = (ServiceTableViewRecord) serviceTableViewInfmList.get(i); - ServiceTableViewViewJTableRowData rowData = new ServiceTableViewViewJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(serviceTableViewRecord.getLid().toString()); - if(serviceTableViewRecord.getState() != null) - { - rowData.setState(serviceTableViewRecord.getState().toString()); - } - else - { - rowData.setState(missingRepresentation); - } - if(serviceTableViewRecord.getCounty() != null) - { - rowData.setCounty(serviceTableViewRecord.getCounty().toString()); - } - else - { - rowData.setCounty(missingRepresentation); - } - if(serviceTableViewRecord.getName() != null) - { - rowData.setLocName(serviceTableViewRecord.getName().toString()); - } - else - { - rowData.setLocName(missingRepresentation); - } - if(serviceTableViewRecord.getStream() != null) - { - rowData.setStream(serviceTableViewRecord.getStream().toString()); - } - else - { - rowData.setStream(missingRepresentation); - } - if(serviceTableViewRecord.getHsa() != null) - { - rowData.setHsa(serviceTableViewRecord.getHsa().toString()); - } - else - { - rowData.setHsa(missingRepresentation); - } - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the Service table view"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the Service table view"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Service table view"; - } - return dataList; - } - - public List readDataFromPtService() - { - List serviceTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtServiceTable serviceTable = new FcstPtServiceTable(db); - FcstPtServiceRecord serviceTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - serviceTableInfmList = serviceTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(serviceTableInfmList != null && serviceTableInfmList.size() >0) - { - for(int i=0;i < serviceTableInfmList.size(); i++) - { - serviceTableRecord = (FcstPtServiceRecord) serviceTableInfmList.get(i); - FcstPtServiceJTableRowData rowData = new FcstPtServiceJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(serviceTableRecord.getLid()); - rowData.setServiceType(serviceTableRecord.getService_type()); - if(serviceTableRecord.getFlood_thres() > Double.MIN_VALUE && serviceTableRecord.getFlood_thres() < Double.MAX_VALUE) - { - Double val = new Double(serviceTableRecord.getFlood_thres()); - rowData.setFloodTher(val); - } - else - { - rowData.setFloodTher(DbTable.getNullDouble()); - } - if(serviceTableRecord.getExceed_prob() >= 0 && serviceTableRecord.getExceed_prob() <= 100) - { - Integer val1 = new Integer(serviceTableRecord.getExceed_prob()); - rowData.setExceedProb(val1); - } - else - { - rowData.setExceedProb(DbTable.getNullInt()); - } - if(DbTable.isNull(serviceTableRecord.getImpl_date()) || serviceTableRecord.getImpl_date() < Long.MIN_VALUE || serviceTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - //rowData.setImplDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getImpl_date())); - rowData.setImplDate(serviceTableRecord.getImpl_date()); - } - if(DbTable.isNull(serviceTableRecord.getWeb_date()) || serviceTableRecord.getWeb_date() < Long.MIN_VALUE || serviceTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - //rowData.setWebDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getWeb_date())); - rowData.setWebDate(serviceTableRecord.getWeb_date()); - } - if(DbTable.isNull(serviceTableRecord.getAnal_start_date()) || serviceTableRecord.getAnal_start_date() < Long.MIN_VALUE || serviceTableRecord.getAnal_start_date() > Long.MAX_VALUE) - { - rowData.setStartDate(DbTable.getNullLong()); - } - else - { - //rowData.setStartDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getAnal_start_date())); - rowData.setStartDate(serviceTableRecord.getAnal_start_date()); - } - if(DbTable.isNull(serviceTableRecord.getAnal_end_date()) || serviceTableRecord.getAnal_end_date() < Long.MIN_VALUE || serviceTableRecord.getAnal_end_date() > Long.MAX_VALUE) - { - rowData.setEndDate(DbTable.getNullLong()); - } - else - { - //rowData.setEndDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getAnal_end_date())); - rowData.setEndDate(serviceTableRecord.getAnal_end_date()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in service table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Service table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Service table"; - } - return dataList; - } - - public List readDataFromPtDeterm() - { - List determTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtDetermTable determTable = new FcstPtDetermTable(db); - FcstPtDetermRecord determTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - determTableInfmList = determTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(determTableInfmList != null && determTableInfmList.size() >0) - { - for(int i=0;i < determTableInfmList.size(); i++) - { - determTableRecord = (FcstPtDetermRecord) determTableInfmList.get(i); - FcstPtDetermJTableRowData rowData = new FcstPtDetermJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(determTableRecord.getLid()); - rowData.setHydraulMethod(determTableRecord.getHydraul_method()); - rowData.setHydrolMethod(determTableRecord.getHydrol_method()); - rowData.setSnowMethod(determTableRecord.getSnow_method()); - rowData.setIssueCriteria(determTableRecord.getDef_issue_crit()); - rowData.setUpstreamSeg(determTableRecord.getUpstream_seg()); - rowData.setReservoirModel(determTableRecord.getReservoir_model()); - rowData.setGenMethod(determTableRecord.getFcst_gen_method()); - if(determTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(determTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(DbTable.getNullString()); - } - if(determTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(determTableRecord.getConsumptive_use().toString()); - } - else - { - rowData.setConsumptiveUse(DbTable.getNullString()); - } - if(determTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(determTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(DbTable.getNullString()); - } - if(determTableRecord.getNum_elev_zones() < Short.MIN_VALUE || determTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setNumElevZones(DbTable.getNullInt()); - } - else - { - rowData.setNumElevZones(determTableRecord.getNum_elev_zones()); - } - if(DbTable.isNull(determTableRecord.getImpl_date()) || determTableRecord.getImpl_date() < Long.MIN_VALUE || determTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(determTableRecord.getImpl_date()); - } - if(DbTable.isNull(determTableRecord.getWeb_date()) || determTableRecord.getWeb_date() < Long.MIN_VALUE || determTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(determTableRecord.getWeb_date()); - } - if(determTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(determTableRecord.getFrequpd_normal()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(determTableRecord.getFrequpd_flood()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(determTableRecord.getFrequpd_drought()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(determTableRecord.getHours_qpf() < Integer.MIN_VALUE || determTableRecord.getHours_qpf() > Integer.MAX_VALUE) - { - rowData.setQpf(DbTable.getNullInt()); - } - else - { - rowData.setQpf(determTableRecord.getHours_qpf()); - } - if(determTableRecord.getHours_qtf() < Integer.MIN_VALUE || determTableRecord.getHours_qtf() > Integer.MAX_VALUE) - { - rowData.setQtf(DbTable.getNullInt()); - } - else - { - rowData.setQtf(determTableRecord.getHours_qtf()); - } - if(determTableRecord.getHours_qzf() < Integer.MIN_VALUE || determTableRecord.getHours_qzf() > Integer.MAX_VALUE) - { - rowData.setQzf(DbTable.getNullInt()); - } - else - { - rowData.setQzf(determTableRecord.getHours_qzf()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in determ table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Determ table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Determ table"; - } - return dataList; - } - - public List readReservoirsFromPtDeterm() - { - List determTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtDetermTable determTable = new FcstPtDetermTable(db); - FcstPtDetermRecord determTableRecord = null; - String whereClause = null; - - try - { - whereClause = "WHERE reservoir_model NOT IN ('None') order by lid"; - determTableInfmList = determTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(determTableInfmList != null && determTableInfmList.size() >0) - { - for(int i=0;i < determTableInfmList.size(); i++) - { - determTableRecord = (FcstPtDetermRecord) determTableInfmList.get(i); - FcstPtDetermJTableRowData rowData = new FcstPtDetermJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(determTableRecord.getLid().toString()); - rowData.setHydraulMethod(determTableRecord.getHydraul_method().toString()); - rowData.setHydrolMethod(determTableRecord.getHydrol_method().toString()); - rowData.setSnowMethod(determTableRecord.getSnow_method().toString()); - rowData.setIssueCriteria(determTableRecord.getDef_issue_crit().toString()); - rowData.setUpstreamSeg(determTableRecord.getUpstream_seg().toString()); - rowData.setReservoirModel(determTableRecord.getReservoir_model().toString()); - rowData.setGenMethod(determTableRecord.getFcst_gen_method().toString()); - if(determTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(determTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(DbTable.getNullString()); - } - if(determTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(determTableRecord.getConsumptive_use().toString()); - } - else - { - rowData.setConsumptiveUse(missingRepresentation); - } - if(determTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(determTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(missingRepresentation); - } - if(determTableRecord.getNum_elev_zones() < Short.MIN_VALUE || determTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setNumElevZones(DbTable.getNullInt()); - } - else - { - rowData.setNumElevZones(determTableRecord.getNum_elev_zones()); - } - if(DbTable.isNull(determTableRecord.getImpl_date()) || determTableRecord.getImpl_date() < Long.MIN_VALUE || determTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(determTableRecord.getImpl_date()); - } - if(DbTable.isNull(determTableRecord.getWeb_date()) || determTableRecord.getWeb_date() < Long.MIN_VALUE || determTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(determTableRecord.getWeb_date()); - } - if(determTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(determTableRecord.getFrequpd_normal()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(determTableRecord.getFrequpd_flood()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(determTableRecord.getFrequpd_drought()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(determTableRecord.getHours_qpf() < Integer.MIN_VALUE || determTableRecord.getHours_qpf() > Integer.MAX_VALUE) - { - rowData.setQpf(DbTable.getNullInt()); - } - else - { - rowData.setQpf(determTableRecord.getHours_qpf()); - } - if(determTableRecord.getHours_qtf() < Integer.MIN_VALUE || determTableRecord.getHours_qtf() > Integer.MAX_VALUE) - { - rowData.setQtf(DbTable.getNullInt()); - } - else - { - rowData.setQtf(determTableRecord.getHours_qtf()); - } - if(determTableRecord.getHours_qzf() < Integer.MIN_VALUE || determTableRecord.getHours_qzf() > Integer.MAX_VALUE) - { - rowData.setQzf(DbTable.getNullInt()); - } - else - { - rowData.setQzf(determTableRecord.getHours_qzf()); - } - dataList.add(rowData); - rowData.addAllCellsToMap(); - } - LhvmDataManager.databaseMessage = "Records found in determ table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Determ table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Determ table"; - } - return dataList; - } - - public List readDataFromPtWatsup() - { - List watsupTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtWatSupTable watsupTable = new FcstPtWatSupTable(db); - FcstPtWatSupRecord watsupTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - watsupTableInfmList = watsupTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupTableInfmList != null && watsupTableInfmList.size() > 0) - { - for(int i=0;i < watsupTableInfmList.size(); i++) - { - watsupTableRecord = (FcstPtWatSupRecord) watsupTableInfmList.get(i); - FcstPtWatSupJTableRowData rowData = new FcstPtWatSupJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(watsupTableRecord.getLid().toString()); - rowData.setNormal(watsupTableRecord.getFrequpd_normal().toString()); - rowData.setWatsupMethod(watsupTableRecord.getWatsup_method().toString()); - rowData.setWatsupCoordAgency(watsupTableRecord.getWatsup_coord_agency().toString()); - rowData.setPeriodReq(watsupTableRecord.getPeriod_req().toString()); - rowData.setWatsupCrit(watsupTableRecord.getWatsup_crit().toString()); - rowData.setRespAgency(watsupTableRecord.getWatsup_resp_agency().toString()); - if(watsupTableRecord.getCustomer_desc() != null) - { - rowData.setCustomerDesc(watsupTableRecord.getCustomer_desc().toString()); - } - else - { - rowData.setCustomerDesc(missingRepresentation); - } - if(DbTable.isNull(watsupTableRecord.getImpl_date()) || watsupTableRecord.getImpl_date() < Long.MIN_VALUE || watsupTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(watsupTableRecord.getImpl_date()); - } - if(DbTable.isNull(watsupTableRecord.getWeb_date()) || watsupTableRecord.getWeb_date() < Long.MIN_VALUE || watsupTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(watsupTableRecord.getWeb_date()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in Watsup table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Watsup table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Watsup table"; - } - return dataList; - } - - public List readDataFromPtEnsemble() - { - List ensembleTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtESPTable ensembleTable = new FcstPtESPTable(db); - FcstPtESPRecord ensembleTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - ensembleTableInfmList = ensembleTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(ensembleTableInfmList != null && ensembleTableInfmList.size() >0) - { - for(int i=0;i < ensembleTableInfmList.size(); i++) - { - ensembleTableRecord = (FcstPtESPRecord) ensembleTableInfmList.get(i); - FcstPtEnsembleJTableRowData rowData = new FcstPtEnsembleJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(ensembleTableRecord.getLid().toString()); - rowData.setHydraulMethod(ensembleTableRecord.getHydraul_method().toString()); - rowData.setHydrolMethod(ensembleTableRecord.getHydrol_method().toString()); - rowData.setSnowMethod(ensembleTableRecord.getSnow_method().toString()); - rowData.setUpstreamSeg(ensembleTableRecord.getUpstream_seg().toString()); - rowData.setReservoirModel(ensembleTableRecord.getReservoir_model().toString()); - if(ensembleTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(ensembleTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(missingRepresentation); - } - if(ensembleTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(ensembleTableRecord.getConsumptive_use().toString()); - } - else - { - rowData.setConsumptiveUse(missingRepresentation); - } - if(ensembleTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(ensembleTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(missingRepresentation); - } - if(ensembleTableRecord.getPost_processor() != null) - { - rowData.setPostProcessing(ensembleTableRecord.getPost_processor().toString()); - } - else - { - rowData.setPostProcessing(missingRepresentation); - } - rowData.setFlowType(ensembleTableRecord.getFlowtype().toString()); - rowData.setFcstType(ensembleTableRecord.getFcsttype().toString()); - if(DbTable.isNull(ensembleTableRecord.getImpl_date()) || ensembleTableRecord.getImpl_date() < Long.MIN_VALUE || ensembleTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(ensembleTableRecord.getImpl_date()); - } - if(DbTable.isNull(ensembleTableRecord.getWeb_date()) || ensembleTableRecord.getWeb_date() < Long.MIN_VALUE || ensembleTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(ensembleTableRecord.getWeb_date()); - } - if(DbTable.isNull(ensembleTableRecord.getExternal_date()) || ensembleTableRecord.getExternal_date() < Long.MIN_VALUE || ensembleTableRecord.getExternal_date() > Long.MAX_VALUE) - { - rowData.setExternalDate(DbTable.getNullLong()); - } - else - { - rowData.setExternalDate(ensembleTableRecord.getExternal_date()); - } - if(ensembleTableRecord.getNum_elev_zones() < 0 || ensembleTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setNumElevZones(ensembleTableRecord.getNum_elev_zones()); - } - if(ensembleTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(ensembleTableRecord.getFrequpd_normal().toString()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(ensembleTableRecord.getFrequpd_flood().toString()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(ensembleTableRecord.getFrequpd_drought().toString()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(ensembleTableRecord.getNummonclim() < Integer.MIN_VALUE || ensembleTableRecord.getNummonclim() > Integer.MAX_VALUE) - { - rowData.setNumMonClim(DbTable.getNullInt()); - } - else - { - rowData.setNumMonClim(ensembleTableRecord.getNummonclim()); - } - if(ensembleTableRecord.getNumdayhyd() < Integer.MIN_VALUE || ensembleTableRecord.getNumdayhyd() > Integer.MAX_VALUE) - { - rowData.setNumDayHyd(DbTable.getNullInt()); - } - else - { - rowData.setNumDayHyd(ensembleTableRecord.getNumdayhyd()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in ensemble table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Ensemble table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Ensemble table"; - } - return dataList; - } - - public List readReservoirsFromPtEnsemble() - { - List ensembleTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtESPTable ensembleTable = new FcstPtESPTable(db); - FcstPtESPRecord ensembleTableRecord = null; - String whereClause = null; - - try - { - whereClause = "WHERE reservoir_model NOT IN ('None') order by lid"; - ensembleTableInfmList = ensembleTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(ensembleTableInfmList != null && ensembleTableInfmList.size() > 0) - { - for(int i=0;i < ensembleTableInfmList.size(); i++) - { - ensembleTableRecord = (FcstPtESPRecord) ensembleTableInfmList.get(i); - FcstPtEnsembleJTableRowData rowData = new FcstPtEnsembleJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(ensembleTableRecord.getLid()); - rowData.setHydraulMethod(ensembleTableRecord.getHydraul_method()); - rowData.setHydrolMethod(ensembleTableRecord.getHydrol_method()); - rowData.setSnowMethod(ensembleTableRecord.getSnow_method()); - rowData.setUpstreamSeg(ensembleTableRecord.getUpstream_seg()); - rowData.setReservoirModel(ensembleTableRecord.getReservoir_model()); - if(ensembleTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(ensembleTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(DbTable.getNullString()); - } - if(ensembleTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(ensembleTableRecord.getConsumptive_use()); - } - else - { - rowData.setConsumptiveUse(DbTable.getNullString()); - } - if(ensembleTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(ensembleTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(DbTable.getNullString()); - } - if(ensembleTableRecord.getPost_processor() != null) - { - rowData.setPostProcessing(ensembleTableRecord.getPost_processor()); - } - else - { - rowData.setPostProcessing(DbTable.getNullString()); - } - rowData.setFlowType(ensembleTableRecord.getFlowtype()); - rowData.setFcstType(ensembleTableRecord.getFcsttype()); - if(DbTable.isNull(ensembleTableRecord.getImpl_date()) || ensembleTableRecord.getImpl_date() < Long.MIN_VALUE || ensembleTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(ensembleTableRecord.getImpl_date()); - } - if(DbTable.isNull(ensembleTableRecord.getWeb_date()) || ensembleTableRecord.getWeb_date() < Long.MIN_VALUE || ensembleTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(ensembleTableRecord.getWeb_date()); - } - if(DbTable.isNull(ensembleTableRecord.getExternal_date()) || ensembleTableRecord.getExternal_date() < Long.MIN_VALUE || ensembleTableRecord.getExternal_date() > Long.MAX_VALUE) - { - rowData.setExternalDate(DbTable.getNullLong()); - } - else - { - rowData.setExternalDate(ensembleTableRecord.getExternal_date()); - } - if(ensembleTableRecord.getNum_elev_zones() < 0 || ensembleTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setNumElevZones(ensembleTableRecord.getNum_elev_zones()); - } - if(ensembleTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(ensembleTableRecord.getFrequpd_normal()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(ensembleTableRecord.getFrequpd_flood()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(ensembleTableRecord.getFrequpd_drought()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(ensembleTableRecord.getNummonclim() < Integer.MIN_VALUE || ensembleTableRecord.getNummonclim() > Integer.MAX_VALUE) - { - rowData.setNumMonClim(DbTable.getNullInt()); - } - else - { - rowData.setNumMonClim(ensembleTableRecord.getNummonclim()); - } - if(ensembleTableRecord.getNumdayhyd() < Integer.MIN_VALUE || ensembleTableRecord.getNumdayhyd() > Integer.MAX_VALUE) - { - rowData.setNumDayHyd(DbTable.getNullInt()); - } - else - { - rowData.setNumDayHyd(ensembleTableRecord.getNumdayhyd()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in ensemble table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Ensemble table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Ensemble table"; - } - return dataList; - } - - public List readDataFromFcstType() - { - List fcstTypeInfmList = null; - List dataList = new ArrayList(); - - FcstTypeTable fcstTypeTable = new FcstTypeTable(db); - FcstTypeRecord fcstTypeJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - fcstTypeInfmList = fcstTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(fcstTypeInfmList != null && fcstTypeInfmList.size() > 0) - { - for(int i=0;i < fcstTypeInfmList.size(); i++) - { - fcstTypeJTableRecord = (FcstTypeRecord) fcstTypeInfmList.get(i); - FcstTypeJTableRowData rowData = new FcstTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFcstType(fcstTypeJTableRecord.getFcsttype().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FcstType table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FcstType table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FcstType table"; - } - return dataList; - } - - public List readDataFromFlowType() - { - List flowTypeInfmList = null; - List dataList = new ArrayList(); - - FlowTypeTable flowTypeTable = new FlowTypeTable(db); - FlowTypeRecord flowTypeJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - flowTypeInfmList = flowTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(flowTypeInfmList != null && flowTypeInfmList.size() > 0) - { - for(int i=0;i < flowTypeInfmList.size(); i++) - { - flowTypeJTableRecord = (FlowTypeRecord) flowTypeInfmList.get(i); - FlowTypeJTableRowData rowData = new FlowTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFlowType(flowTypeJTableRecord.getFlowtype().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FlowType table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FlowType table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FlowType table"; - } - return dataList; - } - - public List readDataFromHydrologicMethod() - { - List hydrologicMethodInfmList = null; - List dataList = new ArrayList(); - - HydrologicMethodTable hydrologicMethodTable = new HydrologicMethodTable(db); - HydrologicMethodRecord hydrologicMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - hydrologicMethodInfmList = hydrologicMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(hydrologicMethodInfmList != null && hydrologicMethodInfmList.size() > 0) - { - for(int i=0;i < hydrologicMethodInfmList.size(); i++) - { - hydrologicMethodJTableRecord = (HydrologicMethodRecord) hydrologicMethodInfmList.get(i); - HydrologicMethodJTableRowData rowData = new HydrologicMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setHydrologicMethod(hydrologicMethodJTableRecord.getHydrol_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the HydrologicMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the HydrologicMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the HydrologicMethod table"; - } - return dataList; - } - - public List readDataFromRoutingMethod() - { - List routingMethodInfmList = null; - List dataList = new ArrayList(); - - RoutingMethodTable routingMethodTable = new RoutingMethodTable(db); - RoutingMethodRecord routingMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - routingMethodInfmList = routingMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(routingMethodInfmList != null && routingMethodInfmList.size() > 0) - { - for(int i=0;i < routingMethodInfmList.size(); i++) - { - routingMethodJTableRecord = (RoutingMethodRecord) routingMethodInfmList.get(i); - RoutingMethodJTableRowData rowData = new RoutingMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setRoutingMethod(routingMethodJTableRecord.getHydraul_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the RoutingMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the RoutingMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the RoutingMethod table"; - } - return dataList; - } - - public List readDataFromIssueCriteria() - { - List issueCriteriaInfmList = null; - List dataList = new ArrayList(); - - DefiningIssueCriteriaTable issueCriteriaTable = new DefiningIssueCriteriaTable(db); - DefiningIssueCriteriaRecord issueCriteriaJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - issueCriteriaInfmList = issueCriteriaTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(issueCriteriaInfmList != null && issueCriteriaInfmList.size() > 0) - { - for(int i=0;i < issueCriteriaInfmList.size(); i++) - { - issueCriteriaJTableRecord = (DefiningIssueCriteriaRecord) issueCriteriaInfmList.get(i); - IssueCriteriaJTableRowData rowData = new IssueCriteriaJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setIssueCriteria(issueCriteriaJTableRecord.getDef_issue_crit().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the IssueCriteria table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the IssueCriteria table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the IssueCriteria table"; - } - return dataList; - } - - public List readDataFromSnowMethod() - { - List snowMethodInfmList = null; - List dataList = new ArrayList(); - - SnowMethodTable snowMethodTable = new SnowMethodTable(db); - SnowMethodRecord snowMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - snowMethodInfmList = snowMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(snowMethodInfmList != null && snowMethodInfmList.size() > 0) - { - for(int i=0;i < snowMethodInfmList.size(); i++) - { - snowMethodJTableRecord = (SnowMethodRecord) snowMethodInfmList.get(i); - SnowMethodJTableRowData rowData = new SnowMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setSnowMethod(snowMethodJTableRecord.getSnow_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the SnowMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the SnowMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the SnowMethod table"; - } - return dataList; - } - - public List readDataFromWatsupCoordAgency() - { - List watsupCoordAgencyInfmList = null; - List dataList = new ArrayList(); - - WatSupCoordAgencyTable watsupCoordAgencyTable = new WatSupCoordAgencyTable(db); - WatSupCoordAgencyRecord watsupCoordAgencyJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - watsupCoordAgencyInfmList = watsupCoordAgencyTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupCoordAgencyInfmList != null && watsupCoordAgencyInfmList.size() > 0) - { - for(int i=0;i < watsupCoordAgencyInfmList.size(); i++) - { - watsupCoordAgencyJTableRecord = (WatSupCoordAgencyRecord) watsupCoordAgencyInfmList.get(i); - WatSupCoordAgencyJTableRowData rowData = new WatSupCoordAgencyJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setWatsupCoordAgency(watsupCoordAgencyJTableRecord.getWatsup_coord_agency().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatsupCoordAgency table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatsupCoordAgency table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatsupCoordAgency table"; - } - return dataList; - } - - public List readDataFromWatsupCriterion() - { - List watsupCriterionInfmList = null; - List dataList = new ArrayList(); - - WatSupCriterionTable watsupCriterionTable = new WatSupCriterionTable(db); - WatSupCriterionRecord watsupCriterionJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - watsupCriterionInfmList = watsupCriterionTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupCriterionInfmList != null && watsupCriterionInfmList.size() > 0) - { - for(int i=0;i < watsupCriterionInfmList.size(); i++) - { - watsupCriterionJTableRecord = (WatSupCriterionRecord) watsupCriterionInfmList.get(i); - WatSupCriterionJTableRowData rowData = new WatSupCriterionJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setWatsupCriterion(watsupCriterionJTableRecord.getWatsup_criterion().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatsupCriterion table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatsupCriterion table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatsupCriterion table"; - } - return dataList; - } - - public List readDataFromWatsupMethod() - { - List watsupMethodInfmList = null; - List dataList = new ArrayList(); - - WatSupMethodTable watsupMethodTable = new WatSupMethodTable(db); - WatSupMethodRecord watsupMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - watsupMethodInfmList = watsupMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupMethodInfmList != null && watsupMethodInfmList.size() > 0) - { - for(int i=0;i < watsupMethodInfmList.size(); i++) - { - watsupMethodJTableRecord = (WatSupMethodRecord) watsupMethodInfmList.get(i); - WatSupMethodJTableRowData rowData = new WatSupMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setWatsupMethod(watsupMethodJTableRecord.getWatsup_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatsupMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatsupMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatsupMethod table"; - } - return dataList; - } - - public List readDataFromFrequencyUpdate() - { - List frequencyUpdateInfmList = null; - List dataList = new ArrayList(); - - FrequencyUpdateTable frequencyUpdateTable = new FrequencyUpdateTable(db); - FrequencyUpdateRecord frequencyUpdateRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - frequencyUpdateInfmList = frequencyUpdateTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(frequencyUpdateInfmList != null && frequencyUpdateInfmList.size() > 0) - { - for(int i=0;i < frequencyUpdateInfmList.size(); i++) - { - frequencyUpdateRecord = (FrequencyUpdateRecord) frequencyUpdateInfmList.get(i); - FrequencyUpdateJTableRowData rowData = new FrequencyUpdateJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFrequencyUpdate(frequencyUpdateRecord.getFrequency_update().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FrequencyUpdate table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FrequencyUpdate table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FrequencyUpdate table"; - } - return dataList; - } - - public List readDataFromRequiredPeriod() - { - List requiredPeriodInfmList = null; - List dataList = new ArrayList(); - - RequiredPeriodTable requiredPeriodTable = new RequiredPeriodTable(db); - RequiredPeriodRecord requiredPeriodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - requiredPeriodInfmList = requiredPeriodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(requiredPeriodInfmList != null && requiredPeriodInfmList.size() > 0) - { - for(int i=0;i < requiredPeriodInfmList.size(); i++) - { - requiredPeriodJTableRecord = (RequiredPeriodRecord) requiredPeriodInfmList.get(i); - RequiredPeriodJTableRowData rowData = new RequiredPeriodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setRequiredPeriod(requiredPeriodJTableRecord.getPeriod_req().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the RequiredPeriod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the RequiredPeriod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the RequiredPeriod table"; - } - return dataList; - } - - public List readDataFromPostProcessing() - { - List postProcessingInfmList = null; - List dataList = new ArrayList(); - - PostProcessorTable postProcessingTable = new PostProcessorTable(db); - PostProcessorRecord postProcessingRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - postProcessingInfmList = postProcessingTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(postProcessingInfmList != null && postProcessingInfmList.size() > 0) - { - for(int i=0;i < postProcessingInfmList.size(); i++) - { - postProcessingRecord = (PostProcessorRecord) postProcessingInfmList.get(i); - PostProcessingJTableRowData rowData = new PostProcessingJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setPostProcessing(postProcessingRecord.getPost_processor().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the PostProcessor table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the PostProcessor table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the PostProcessor table"; - } - return dataList; - } - - public List readDataFromHorizon() - { - List horizonInfmList = null; - List dataList = new ArrayList(); - - FcstHorizonTable horizonTable = new FcstHorizonTable(db); - FcstHorizonRecord horizonRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - horizonInfmList = horizonTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(horizonInfmList != null && horizonInfmList.size() > 0) - { - for(int i=0;i < horizonInfmList.size(); i++) - { - horizonRecord = (FcstHorizonRecord) horizonInfmList.get(i); - FcstHorizonJTableRowData rowData = new FcstHorizonJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFcstHorizon(horizonRecord.getFcst_horizon().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FcstHorizon table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FcstHorizon table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FcstHorizon table"; - } - return dataList; - } - - public List readDataFromGenMethod() - { - List genMethodInfmList = null; - List dataList = new ArrayList(); - - FcstGenMethodTable genMethodTable = new FcstGenMethodTable(db); - FcstGenMethodRecord genMethodRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - genMethodInfmList = genMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(genMethodInfmList != null && genMethodInfmList.size() > 0) - { - for(int i=0;i < genMethodInfmList.size(); i++) - { - genMethodRecord = (FcstGenMethodRecord) genMethodInfmList.get(i); - FcstGenMethodJTableRowData rowData = new FcstGenMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setGenMethod(genMethodRecord.getFcst_gen_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FcstGenMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FcstGenMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FcstGenMethod table"; - } - return dataList; - } - - public List readDataFromReservoirModel() - { - List reservoirModelInfmList = null; - List dataList = new ArrayList(); - - ReservoirModelTable reservoirModelTable = new ReservoirModelTable(db); - ReservoirModelRecord reservoirModelRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - reservoirModelInfmList = reservoirModelTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(reservoirModelInfmList != null && reservoirModelInfmList.size() > 0) - { - for(int i=0;i < reservoirModelInfmList.size(); i++) - { - reservoirModelRecord = (ReservoirModelRecord) reservoirModelInfmList.get(i); - ReservoirModelJTableRowData rowData = new ReservoirModelJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setReservoirModel(reservoirModelRecord.getReservoir_model().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the ReservoirModel table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the ReservoirModel table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the ReservoirModel table"; - } - return dataList; - } - - public List readDataFromServiceType() - { - List serviceTypeInfmList = null; - List dataList = new ArrayList(); - - ServiceTypeTable serviceTypeTable = new ServiceTypeTable(db); - ServiceTypeRecord serviceTypeRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - serviceTypeInfmList = serviceTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(serviceTypeInfmList != null && serviceTypeInfmList.size() > 0) - { - for(int i=0;i < serviceTypeInfmList.size(); i++) - { - serviceTypeRecord = (ServiceTypeRecord) serviceTypeInfmList.get(i); - ServiceTypeJTableRowData rowData = new ServiceTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setServiceType(serviceTypeRecord.getService_type().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the ServiceType table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the ServiceType table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the ServiceType table"; - } - return dataList; - } - - public List readDataFromRespAgency() - { - List respAgencyInfmList = null; - List dataList = new ArrayList(); - - WatSupRespAgencyTable respAgencyTable = new WatSupRespAgencyTable(db); - WatSupRespAgencyRecord respAgencyRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - respAgencyInfmList = respAgencyTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(respAgencyInfmList != null && respAgencyInfmList.size() > 0) - { - for(int i=0;i < respAgencyInfmList.size(); i++) - { - respAgencyRecord = (WatSupRespAgencyRecord) respAgencyInfmList.get(i); - RespAgencyJTableRowData rowData = new RespAgencyJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setRespAgency(respAgencyRecord.getWatsup_resp_agency().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatSupRespAgency table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatSupRespAgency table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatSupRespAgency table"; - } - return dataList; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/LhvmLogger.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/LhvmLogger.java deleted file mode 100644 index 573253c828..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/LhvmLogger.java +++ /dev/null @@ -1,240 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.util.Logger; - -public class LhvmLogger implements Logger -{ - private String _fileName = null; - private OutputStream _outputStream = null; - private PrintWriter _writer = null; - private boolean _usingRealFile = false; - private boolean _fileIsOpen = false; - private int _sessionId; - - private static final String dateFormatString = - "yyyyMMdd"; - private static final SimpleDateFormat _dateFormatter = - new SimpleDateFormat(dateFormatString); - - private static final String timeFormatString = - "HH:mm:ss"; - private static final SimpleDateFormat _timeFormatter = - new SimpleDateFormat(timeFormatString); - - private boolean _appendDateTime = false; - private boolean _keepFileOpen = true; - private String _messageId; - - static - { - _dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - public LhvmLogger(String fileName, boolean keepFileOpen, boolean appendDateTime, String messageId) - { - _keepFileOpen = true; - _appendDateTime = true; - _messageId = messageId; - _fileName = fileName; - } - - public LhvmLogger() - { - } - - public int getSessionId() - { - return _sessionId; - } - - public void log(String message) - { - boolean isCreatedNow = false; - if (!isOpen() || message == null) - { - openFile(_fileName, false); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - else - { - String splitStr[] = _fileName.split("\\."); - String dateTimeStampInFileName = splitStr[2]; - if(!(getDateTimeStamp().equalsIgnoreCase(dateTimeStampInFileName))) - { - openFile(_fileName, true); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - } - - if(isCreatedNow) - { - if(_messageId == null) - _messageId = new Integer(_sessionId).toString(); - _writer.println(_messageId); - _writer.println("**************************************"); - } - - if (_appendDateTime) - { - if(message != null) - _writer.println( getTimeStamp() + ": " + message); - } - else - { - if(message != null) - _writer.println(message); - } - _writer.flush(); - if (!_keepFileOpen) - { - close(); - } - } - - private void determineSessionId(String fileName) - { - int sessionId = -1; - String dirName; - int index = fileName.lastIndexOf("/"); - dirName = fileName.substring(0, index); - File dir = new File(dirName); - int leastPossibleNumber = 1; - if(dir.exists()) - { - if(dir.isDirectory()) - { - String files[] = dir.list(); - if(files != null) - { - if(files.length == 0) - { - sessionId = 1; - } - else - { - int existingIds[] = new int[files.length]; - for(int i=0; i < files.length; i++) - { - String str = files[i]; - String splitStr[] = str.split("\\."); - if(splitStr == null) - continue; - else if(splitStr.length != 3) - continue; - else if(!(splitStr[0].equals("RiverMonitor"))) - continue; - else if(splitStr[2].length() != 8) - continue; - try - { - existingIds[i] = Integer.parseInt(splitStr[1]); - Integer.parseInt(splitStr[2]);// To make sure the last portion is a data (number) - } - catch(Exception e) - { - continue; - } - } - Arrays.sort(existingIds); - while(true) - { - if(Arrays.binarySearch(existingIds, leastPossibleNumber) < 0) - { - sessionId = leastPossibleNumber; - break; - } - else - leastPossibleNumber++; - } - } - } - } - else - { - System.out.println("RiverMonitorLogger:["+dir+"] isn't a directory"); - } - } - else - { - System.out.println("RiverMonitorLogger:Directory ["+dir+"] doesn't exist"); - } - - _sessionId = sessionId; - } - - public PrintWriter getPrintWriter() - { - return _writer; - } - - private String getDateTimeStamp() - { - Date date = new Date(); - return _dateFormatter.format(date); - } - - private String getTimeStamp() - { - Date date = new Date(); - return _timeFormatter.format(date); - } - - private void openFile(String fileName, boolean isExistingSession) - { - try - { - if (fileName != null) - { - if(!isExistingSession) - { - determineSessionId(_fileName); - } - if(_sessionId != -1) - { - _fileName = _fileName +"."+ _sessionId + "."+getDateTimeStamp(); - _outputStream = new FileOutputStream(_fileName, true); - _usingRealFile = true; - _fileIsOpen = true; - } - else - { - _outputStream = System.out; - } - } - else //fileName == null - { - _outputStream = System.out; - } - _writer = new PrintWriter(_outputStream); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - } - } - - public void close() - { - if (isOpen() && _usingRealFile) - { - _fileIsOpen = false; - _writer.close(); - } - } - - private boolean isOpen() - { - return _fileIsOpen; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/LocationJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/LocationJTableRowData.java deleted file mode 100644 index 761916fc54..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/LocationJTableRowData.java +++ /dev/null @@ -1,49 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class LocationJTableRowData extends AbstractJTableRowData -{ - private String locId; - - public LocationJTableRowData() - { - } - - public LocationJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String toString() - { - String str = getLocId(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - LocationJTableRowData riverstatRecord = (LocationJTableRowData) rowData; - if(columnName.equals("Upstream Segment")) - ret = compareStrings(getLocId(), riverstatRecord.getLocId()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Upstream Segment")) - dataValue = getStringValue(getLocId()); - return dataValue; - } - - public String getLocId() { - return locId; - } - - public void setLocId(String locId) { - this.locId = locId; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/Observer.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/Observer.java deleted file mode 100644 index 79daef97c3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/Observer.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.fcstservice; - -public interface Observer //Observer of the observer pattern -{ - //There is no need of pasing the subject as regardless of the subject, all the tables will be read - //Just in case we might need independent subject behaviour in the future, design doesn't have to be changed. - public void update(Subject sub); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/PostProcessingJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/PostProcessingJTableRowData.java deleted file mode 100644 index f2ea2a6c13..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/PostProcessingJTableRowData.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class PostProcessingJTableRowData extends AbstractJTableRowData -{ - private String postProcessing; - private String missingRep = null; - - public PostProcessingJTableRowData() - { - } - - public PostProcessingJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getPostProcessing(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - PostProcessingJTableRowData postProcessingRecord = (PostProcessingJTableRowData) rowData; - if(columnName.equals("Post Processing")) - ret = compareStrings(getPostProcessing(), postProcessingRecord.getPostProcessing()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Post Processing")) - dataValue = getStringValue(getPostProcessing()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Post Processing", CellType.STRING, getPostProcessing(), missingRep)); - } - - public String getPostProcessing() { - return postProcessing; - } - - public void setPostProcessing(String postProcessing) { - this.postProcessing = postProcessing; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ReferenceTablesWindow.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ReferenceTablesWindow.java deleted file mode 100644 index c4266b8f33..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ReferenceTablesWindow.java +++ /dev/null @@ -1,547 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.SpringLayout; - -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ReferenceTablesWindow -{ - private DataServicesGlobals dataServicesGlobals = null; - private java.util.List lhvmRowDataList1 = null; - private java.util.List lhvmRowDataList2 = null; - private java.util.List lhvmRowDataList3 = null; - private java.util.List lhvmRowDataList4 = null; - private java.util.List lhvmRowDataList5 = null; - private java.util.List lhvmRowDataList6 = null; - private java.util.List lhvmRowDataList7 = null; - private java.util.List lhvmRowDataList8 = null; - private java.util.List lhvmRowDataList9 = null; - private java.util.List lhvmRowDataList10 = null; - private java.util.List lhvmRowDataList11 = null; - private java.util.List lhvmRowDataList12 = null; - private java.util.List lhvmRowDataList13 = null; - private java.util.List lhvmRowDataList14 = null; - private java.util.List lhvmRowDataList15 = null; - private java.util.List lhvmRowDataList16 = null; - private java.util.List lhvmRowDataList17 = null; - - private LhvmDataManager lhvmDataManager = null; - private LhvmLogger lhvmLogger = null; - private JFrame lhvm = null; - - private JTableManager jtm1 = null; - private JTableManager jtm2 = null; - private JTableManager jtm3 = null; - private JTableManager jtm4 = null; - private JTableManager jtm5 = null; - private JTableManager jtm6 = null; - private JTableManager jtm7 = null; - private JTableManager jtm8 = null; - private JTableManager jtm9 = null; - private JTableManager jtm10 = null; - private JTableManager jtm11 = null; - private JTableManager jtm12 = null; - private JTableManager jtm13 = null; - private JTableManager jtm14 = null; - private JTableManager jtm15 = null; - private JTableManager jtm16 = null; - private JTableManager jtm17 = null; - - private JScrollPane tableScrollPane1 = null; - private JPanel tableScrollPanePanel1 = null; - private JScrollPane tableScrollPane2 = null; - private JPanel tableScrollPanePanel2 = null; - private JScrollPane tableScrollPane3 = null; - private JPanel tableScrollPanePanel3 = null; - private JScrollPane tableScrollPane4 = null; - private JPanel tableScrollPanePanel4 = null; - private JScrollPane tableScrollPane5 = null; - private JPanel tableScrollPanePanel5 = null; - private JScrollPane tableScrollPane6 = null; - private JPanel tableScrollPanePanel6 = null; - private JScrollPane tableScrollPane7 = null; - private JPanel tableScrollPanePanel7 = null; - private JScrollPane tableScrollPane8 = null; - private JPanel tableScrollPanePanel8 = null; - private JScrollPane tableScrollPane9 = null; - private JPanel tableScrollPanePanel9 = null; - private JScrollPane tableScrollPane10 = null; - private JPanel tableScrollPanePanel10 = null; - private JScrollPane tableScrollPane11 = null; - private JPanel tableScrollPanePanel11 = null; - private JScrollPane tableScrollPane12 = null; - private JPanel tableScrollPanePanel12 = null; - private JScrollPane tableScrollPane13 = null; - private JPanel tableScrollPanePanel13 = null; - private JScrollPane tableScrollPane14 = null; - private JPanel tableScrollPanePanel14 = null; - private JScrollPane tableScrollPane15 = null; - private JPanel tableScrollPanePanel15 = null; - private JScrollPane tableScrollPane16 = null; - private JPanel tableScrollPanePanel16 = null; - private JScrollPane tableScrollPane17 = null; - private JPanel tableScrollPanePanel17 = null; - - private JButton closeButton = null; - - private void setDatabaseMessage() - { - String tempStr = null; - if(LhvmDataManager.displayedMessageReferencesWindow != null) - { - tempStr = new String(LhvmDataManager.displayedMessageReferencesWindow); - } - LhvmDataManager.displayedMessageReferencesWindow = new StringBuffer(); - LhvmDataManager.displayedMessageReferencesWindow.append(LhvmDataManager.databaseMessage); - if(tempStr != null) - { - LhvmDataManager.displayedMessageReferencesWindow.append("\n").append(tempStr); - } - } - - public ReferenceTablesWindow(String jdbcUrl) - { - dataServicesGlobals = DataServicesGlobals.getSingleInstanceOfDataServicesGlobals(); - - lhvm = new JFrame("Point Services Reference Tables"); - lhvm.setSize(1000, 500); - lhvm.setLocation(20,50); - lhvm.setLayout(new SpringLayout()); - - //Fix the dimensions of this window i.e. dis-allow window resizing - Dimension d = new Dimension(980, 850); - new WindowResizingManager(lhvm, d, d); - - lhvm.setResizable(false); - - JLabel consoleLabel = new JLabel("-----Database Messages-----"); - consoleLabel.setForeground(Color.red); - - JLabel separatorLabel1 = new JLabel("=================================================================================================="); - separatorLabel1.setForeground(Color.red); - JLabel separatorLabel2 = new JLabel("=================================================================================================="); - separatorLabel2.setForeground(Color.red); - JLabel separatorLabel3 = new JLabel("=================================================================================================="); - separatorLabel3.setForeground(Color.red); - - closeButton = new JButton("Close Window"); - closeButton.addActionListener(new CloseActionListener()); - closeButton.setEnabled(true); - - JTextArea consoleTextArea = new JTextArea(1,50); - Font font = new Font("Serif", Font.BOLD, 15); - consoleTextArea.setFont(font); - consoleTextArea.setForeground(Color.green); - consoleTextArea.setBackground(Color.black); - consoleTextArea.setCaretColor(Color.red); - consoleTextArea.setBorder(BorderFactory.createEtchedBorder() ); - consoleTextArea.setLineWrap(true); - - String[] columnsToBeDisplayed1 = {"Fcst Type"}; - String[] columnsToBeDisplayed2 = {"Flow Type"}; - String[] columnsToBeDisplayed3 = {"Hydrologic Method"}; - String[] columnsToBeDisplayed4 = {"Def Issue Criteria"}; - String[] columnsToBeDisplayed5 = {"Routing Method"}; - String[] columnsToBeDisplayed6 = {"Snow Method"}; - String[] columnsToBeDisplayed7 = {"Wat Sup Coord Agency"}; - String[] columnsToBeDisplayed8 = {"Wat Sup Criterion"}; - String[] columnsToBeDisplayed9 = {"Wat Sup Method"}; - String[] columnsToBeDisplayed10 = {"Frequency Update"}; - String[] columnsToBeDisplayed11 = {"Required Period"}; - String[] columnsToBeDisplayed12 = {"Post Processing"}; - String[] columnsToBeDisplayed13 = {"Horizon"}; - String[] columnsToBeDisplayed14 = {"Typical Fcst Gen Method"}; - String[] columnsToBeDisplayed15 = {"Reservoir Model"}; - String[] columnsToBeDisplayed16 = {"Wat Sup Resp Agency"}; - String[] columnsToBeDisplayed17 = {"Service Type"}; - - JLabel fcstTypeLabel = new JLabel(" Fcst Type"); - JLabel flowTypeLabel = new JLabel(" Flow Type"); - JLabel hydrologicMethodLabel = new JLabel(" Hydrologic Method"); - JLabel issueCriteriaLabel = new JLabel(" Def Issue Criteria"); - JLabel routingMethodLabel = new JLabel(" Routing Method"); - JLabel snowMethodLabel = new JLabel(" Snow Type"); - JLabel watsupCoordAgencyLabel = new JLabel(" Wat Sup Coord Agency"); - JLabel watsupCriterionLabel = new JLabel(" Wat Sup Criterion"); - JLabel watsupMethodLabel = new JLabel(" Wat Sup Method"); - JLabel frequencyUpdateLabel = new JLabel(" Frequency Update"); - JLabel requiredPeriodLabel = new JLabel(" Required Period"); - JLabel postProcessingLabel = new JLabel(" Post Processing"); - JLabel horizonLabel = new JLabel(" Horizon"); - JLabel genMethodLabel = new JLabel(" Typical Fcst Gen Method"); - JLabel reservoirModelLabel = new JLabel(" Reservoir Model"); - JLabel serviceTypeLabel = new JLabel(" Service Type"); - JLabel respAgencyLabel = new JLabel(" Wat Sup Resp Agency"); - - java.util.List lhvmColumnDescriptorList1 = new ArrayList(); - java.util.List lhvmColumnDescriptorList2 = new ArrayList(); - java.util.List lhvmColumnDescriptorList3 = new ArrayList(); - java.util.List lhvmColumnDescriptorList4 = new ArrayList(); - java.util.List lhvmColumnDescriptorList5 = new ArrayList(); - java.util.List lhvmColumnDescriptorList6 = new ArrayList(); - java.util.List lhvmColumnDescriptorList7 = new ArrayList(); - java.util.List lhvmColumnDescriptorList8 = new ArrayList(); - java.util.List lhvmColumnDescriptorList9 = new ArrayList(); - java.util.List lhvmColumnDescriptorList10 = new ArrayList(); - java.util.List lhvmColumnDescriptorList11 = new ArrayList(); - java.util.List lhvmColumnDescriptorList12 = new ArrayList(); - java.util.List lhvmColumnDescriptorList13 = new ArrayList(); - java.util.List lhvmColumnDescriptorList14 = new ArrayList(); - java.util.List lhvmColumnDescriptorList15 = new ArrayList(); - java.util.List lhvmColumnDescriptorList16 = new ArrayList(); - java.util.List lhvmColumnDescriptorList17 = new ArrayList(); - - lhvmLogger = new LhvmLogger(); - lhvmDataManager = LhvmDataManager.getSingleInstanceOfDataManager(jdbcUrl, lhvmLogger,"-"); - - lhvmRowDataList1 = lhvmDataManager.readDataFromFcstType(); - lhvmColumnDescriptorList1.add(new JTableColumnDescriptor("Fcst Type", true, 150, "center")); - jtm1 = new ComplexJTableManager(lhvmColumnDescriptorList1, lhvmRowDataList1); - jtm1.setDisplayableColumns(columnsToBeDisplayed1, false, true); - jtm1.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane1 = jtm1.getJScrollPane(); - //jtm1.setTableToolTipText("str"); - tableScrollPanePanel1 = new JPanel(); - tableScrollPanePanel1.add(tableScrollPane1); - setDatabaseMessage(); - - lhvmRowDataList2 = lhvmDataManager.readDataFromFlowType(); - lhvmColumnDescriptorList2.add(new JTableColumnDescriptor("Flow Type", true, 150, "center")); - jtm2 = new ComplexJTableManager(lhvmColumnDescriptorList2, lhvmRowDataList2); - jtm2.setDisplayableColumns(columnsToBeDisplayed2, false, true); - jtm2.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane2 = jtm2.getJScrollPane(); - //jtm2.setTableToolTipText("str"); - tableScrollPanePanel2 = new JPanel(); - tableScrollPanePanel2.add(tableScrollPane2); - setDatabaseMessage(); - - lhvmRowDataList3 = lhvmDataManager.readDataFromHydrologicMethod(); - lhvmColumnDescriptorList3.add(new JTableColumnDescriptor("Hydrologic Method", true, 150, "center")); - jtm3 = new ComplexJTableManager(lhvmColumnDescriptorList3, lhvmRowDataList3); - jtm3.setDisplayableColumns(columnsToBeDisplayed3, false, true); - jtm3.setPreferredSizeForJScrollPane(new Dimension(150,125)); - tableScrollPane3 = jtm3.getJScrollPane(); - //jtm3.setTableToolTipText("str"); - tableScrollPanePanel3 = new JPanel(); - tableScrollPanePanel3.add(tableScrollPane3); - setDatabaseMessage(); - - lhvmRowDataList4 = lhvmDataManager.readDataFromIssueCriteria(); - lhvmColumnDescriptorList4.add(new JTableColumnDescriptor("Def Issue Criteria", true, 150, "center")); - jtm4 = new ComplexJTableManager(lhvmColumnDescriptorList4, lhvmRowDataList4); - jtm4.setDisplayableColumns(columnsToBeDisplayed4, false, true); - jtm4.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane4 = jtm4.getJScrollPane(); - //jtm4.setTableToolTipText("str"); - tableScrollPanePanel4 = new JPanel(); - tableScrollPanePanel4.add(tableScrollPane4); - setDatabaseMessage(); - - lhvmRowDataList5 = lhvmDataManager.readDataFromRoutingMethod(); - lhvmColumnDescriptorList5.add(new JTableColumnDescriptor("Routing Method", true, 150, "center")); - jtm5 = new ComplexJTableManager(lhvmColumnDescriptorList5, lhvmRowDataList5); - jtm5.setDisplayableColumns(columnsToBeDisplayed5, false, true); - jtm5.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane5 = jtm5.getJScrollPane(); - //jtm5.setTableToolTipText("str"); - tableScrollPanePanel5 = new JPanel(); - tableScrollPanePanel5.add(tableScrollPane5); - setDatabaseMessage(); - - lhvmRowDataList6 = lhvmDataManager.readDataFromSnowMethod(); - lhvmColumnDescriptorList6.add(new JTableColumnDescriptor("Snow Method", true, 150, "center")); - jtm6 = new ComplexJTableManager(lhvmColumnDescriptorList6, lhvmRowDataList6); - jtm6.setDisplayableColumns(columnsToBeDisplayed6, false, true); - jtm6.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane6 = jtm6.getJScrollPane(); - //jtm6.setTableToolTipText("str"); - tableScrollPanePanel6 = new JPanel(); - tableScrollPanePanel6.add(tableScrollPane6); - setDatabaseMessage(); - - lhvmRowDataList7 = lhvmDataManager.readDataFromWatsupCoordAgency(); - lhvmColumnDescriptorList7.add(new JTableColumnDescriptor("Wat Sup Coord Agency", true, 150, "center")); - jtm7 = new ComplexJTableManager(lhvmColumnDescriptorList7, lhvmRowDataList7); - jtm7.setDisplayableColumns(columnsToBeDisplayed7, false, true); - jtm7.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane7 = jtm7.getJScrollPane(); - //jtm7.setTableToolTipText("str"); - tableScrollPanePanel7 = new JPanel(); - tableScrollPanePanel7.add(tableScrollPane7); - setDatabaseMessage(); - - lhvmRowDataList8 = lhvmDataManager.readDataFromWatsupCriterion(); - lhvmColumnDescriptorList8.add(new JTableColumnDescriptor("Wat Sup Criterion", true, 150, "center")); - jtm8 = new ComplexJTableManager(lhvmColumnDescriptorList8, lhvmRowDataList8); - jtm8.setDisplayableColumns(columnsToBeDisplayed8, false, true); - jtm8.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane8 = jtm8.getJScrollPane(); - //jtm8.setTableToolTipText("str"); - tableScrollPanePanel8 = new JPanel(); - tableScrollPanePanel8.add(tableScrollPane8); - setDatabaseMessage(); - - lhvmRowDataList9 = lhvmDataManager.readDataFromWatsupMethod(); - lhvmColumnDescriptorList9.add(new JTableColumnDescriptor("Wat Sup Method", true, 150, "center")); - jtm9 = new ComplexJTableManager(lhvmColumnDescriptorList9, lhvmRowDataList9); - jtm9.setDisplayableColumns(columnsToBeDisplayed9, false, true); - jtm9.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane9 = jtm9.getJScrollPane(); - //jtm9.setTableToolTipText("str"); - tableScrollPanePanel9 = new JPanel(); - tableScrollPanePanel9.add(tableScrollPane9); - setDatabaseMessage(); - - lhvmRowDataList10 = lhvmDataManager.readDataFromFrequencyUpdate(); - lhvmColumnDescriptorList10.add(new JTableColumnDescriptor("Frequency Update", true, 150, "center")); - jtm10 = new ComplexJTableManager(lhvmColumnDescriptorList10, lhvmRowDataList10); - jtm10.setDisplayableColumns(columnsToBeDisplayed10, false, true); - jtm10.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane10 = jtm10.getJScrollPane(); - //jtm10.setTableToolTipText("str"); - tableScrollPanePanel10 = new JPanel(); - tableScrollPanePanel10.add(tableScrollPane10); - setDatabaseMessage(); - - lhvmRowDataList11 = lhvmDataManager.readDataFromRequiredPeriod(); - lhvmColumnDescriptorList11.add(new JTableColumnDescriptor("Required Period", true, 150, "center")); - jtm11 = new ComplexJTableManager(lhvmColumnDescriptorList11, lhvmRowDataList11); - jtm11.setDisplayableColumns(columnsToBeDisplayed11, false, true); - jtm11.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane11 = jtm11.getJScrollPane(); - //jtm11.setTableToolTipText("str"); - tableScrollPanePanel11 = new JPanel(); - tableScrollPanePanel11.add(tableScrollPane11); - setDatabaseMessage(); - - lhvmRowDataList12 = lhvmDataManager.readDataFromPostProcessing(); - lhvmColumnDescriptorList12.add(new JTableColumnDescriptor("Post Processing", true, 150, "center")); - jtm12 = new ComplexJTableManager(lhvmColumnDescriptorList12, lhvmRowDataList12); - jtm12.setDisplayableColumns(columnsToBeDisplayed12, false, true); - jtm12.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane12 = jtm12.getJScrollPane(); - //jtm12.setTableToolTipText("str"); - tableScrollPanePanel12 = new JPanel(); - tableScrollPanePanel12.add(tableScrollPane12); - setDatabaseMessage(); - - lhvmRowDataList13 = lhvmDataManager.readDataFromHorizon(); - lhvmColumnDescriptorList13.add(new JTableColumnDescriptor("Horizon", true, 150, "center")); - jtm13 = new ComplexJTableManager(lhvmColumnDescriptorList13, lhvmRowDataList13); - jtm13.setDisplayableColumns(columnsToBeDisplayed13, false, true); - jtm13.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane13 = jtm13.getJScrollPane(); - //jtm13.setTableToolTipText("str"); - tableScrollPanePanel13 = new JPanel(); - tableScrollPanePanel13.add(tableScrollPane13); - setDatabaseMessage(); - - lhvmRowDataList14 = lhvmDataManager.readDataFromGenMethod(); - lhvmColumnDescriptorList14.add(new JTableColumnDescriptor("Typical Fcst Gen Method", true, 150, "center")); - jtm14 = new ComplexJTableManager(lhvmColumnDescriptorList14, lhvmRowDataList14); - jtm14.setDisplayableColumns(columnsToBeDisplayed14, false, true); - jtm14.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane14 = jtm14.getJScrollPane(); - //jtm14.setTableToolTipText("str"); - tableScrollPanePanel14 = new JPanel(); - tableScrollPanePanel14.add(tableScrollPane14); - setDatabaseMessage(); - - lhvmRowDataList15 = lhvmDataManager.readDataFromReservoirModel(); - lhvmColumnDescriptorList15.add(new JTableColumnDescriptor("Reservoir Model", true, 150, "center")); - jtm15 = new ComplexJTableManager(lhvmColumnDescriptorList15, lhvmRowDataList15); - jtm15.setDisplayableColumns(columnsToBeDisplayed15, false, true); - jtm15.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane15 = jtm15.getJScrollPane(); - //jtm15.setTableToolTipText("str"); - tableScrollPanePanel15 = new JPanel(); - tableScrollPanePanel15.add(tableScrollPane15); - setDatabaseMessage(); - - lhvmRowDataList16 = lhvmDataManager.readDataFromRespAgency(); - lhvmColumnDescriptorList16.add(new JTableColumnDescriptor("Wat Sup Resp Agency", true, 150, "center")); - jtm16 = new ComplexJTableManager(lhvmColumnDescriptorList16, lhvmRowDataList16); - jtm16.setDisplayableColumns(columnsToBeDisplayed16, false, true); - jtm16.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane16 = jtm16.getJScrollPane(); - //jtm16.setTableToolTipText("str"); - tableScrollPanePanel16 = new JPanel(); - tableScrollPanePanel16.add(tableScrollPane16); - setDatabaseMessage(); - - lhvmRowDataList17 = lhvmDataManager.readDataFromServiceType(); - lhvmColumnDescriptorList17.add(new JTableColumnDescriptor("Service Type", true, 150, "center")); - jtm17 = new ComplexJTableManager(lhvmColumnDescriptorList17, lhvmRowDataList17); - jtm17.setDisplayableColumns(columnsToBeDisplayed17, false, true); - jtm17.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane17 = jtm17.getJScrollPane(); - //jtm17.setTableToolTipText("str"); - tableScrollPanePanel17 = new JPanel(); - tableScrollPanePanel17.add(tableScrollPane17); - setDatabaseMessage(); - - consoleTextArea.insert(new String(LhvmDataManager.displayedMessageReferencesWindow), 0); - JScrollPane scrollableTextAreaForConsole = new JScrollPane(consoleTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - - int numRows1 = lhvmRowDataList1.size(); - JLabel numRowsLabel1 = new JLabel(" " + numRows1 + " Rows"); - int numRows2 = lhvmRowDataList2.size(); - JLabel numRowsLabel2 = new JLabel(" " + numRows2 + " Rows"); - int numRows3 = lhvmRowDataList3.size(); - JLabel numRowsLabel3 = new JLabel(" " + numRows3 + " Rows"); - int numRows4 = lhvmRowDataList4.size(); - JLabel numRowsLabel4 = new JLabel(" " + numRows4 + " Rows"); - int numRows5 = lhvmRowDataList5.size(); - JLabel numRowsLabel5 = new JLabel(" " + numRows5 + " Rows"); - int numRows6 = lhvmRowDataList6.size(); - JLabel numRowsLabel6 = new JLabel(" " + numRows6 + " Rows"); - int numRows7 = lhvmRowDataList7.size(); - JLabel numRowsLabel7 = new JLabel(" " + numRows7 + " Rows"); - int numRows8 = lhvmRowDataList8.size(); - JLabel numRowsLabel8 = new JLabel(" " + numRows8 + " Rows"); - int numRows9 = lhvmRowDataList9.size(); - JLabel numRowsLabel9 = new JLabel(" " + numRows9 + " Rows"); - int numRows10 = lhvmRowDataList10.size(); - JLabel numRowsLabel10 = new JLabel(" " + numRows10 + " Rows"); - int numRows11 = lhvmRowDataList11.size(); - JLabel numRowsLabel11 = new JLabel(" " + numRows11 + " Rows"); - int numRows12 = lhvmRowDataList12.size(); - JLabel numRowsLabel12 = new JLabel(" " + numRows12 + " Rows"); - int numRows13 = lhvmRowDataList13.size(); - JLabel numRowsLabel13 = new JLabel(" " + numRows13 + " Rows"); - int numRows14 = lhvmRowDataList14.size(); - JLabel numRowsLabel14 = new JLabel(" " + numRows14 + " Rows"); - int numRows15 = lhvmRowDataList15.size(); - JLabel numRowsLabel15 = new JLabel(" " + numRows15 + " Rows"); - int numRows16 = lhvmRowDataList16.size(); - JLabel numRowsLabel16 = new JLabel(" " + numRows16 + " Rows"); - int numRows17 = lhvmRowDataList17.size(); - JLabel numRowsLabel17 = new JLabel(" " + numRows17 + " Rows"); - - JFrame tablesPanel = new JFrame(); - tablesPanel.setLayout(new SpringLayout()); - tablesPanel.add(numRowsLabel1); - tablesPanel.add(numRowsLabel2); - tablesPanel.add(numRowsLabel3); - tablesPanel.add(numRowsLabel4); - tablesPanel.add(numRowsLabel5); - tablesPanel.add(fcstTypeLabel); - tablesPanel.add(flowTypeLabel); - tablesPanel.add(hydrologicMethodLabel); - tablesPanel.add(issueCriteriaLabel); - tablesPanel.add(routingMethodLabel); - tablesPanel.add(tableScrollPanePanel1); - tablesPanel.add(tableScrollPanePanel2); - tablesPanel.add(tableScrollPanePanel3); - tablesPanel.add(tableScrollPanePanel4); - tablesPanel.add(tableScrollPanePanel5); - SpringUtilities.makeCompactGrid(tablesPanel.getContentPane(), 3, 5, 0, 0, 0, 0); - - JFrame tablesPanel1 = new JFrame(); - tablesPanel1.setLayout(new SpringLayout()); - tablesPanel1.add(numRowsLabel6); - tablesPanel1.add(numRowsLabel7); - tablesPanel1.add(numRowsLabel8); - tablesPanel1.add(numRowsLabel9); - tablesPanel1.add(numRowsLabel10); - tablesPanel1.add(snowMethodLabel); - tablesPanel1.add(watsupCoordAgencyLabel); - tablesPanel1.add(watsupCriterionLabel); - tablesPanel1.add(watsupMethodLabel); - tablesPanel1.add(frequencyUpdateLabel); - tablesPanel1.add(tableScrollPanePanel6); - tablesPanel1.add(tableScrollPanePanel7); - tablesPanel1.add(tableScrollPanePanel8); - tablesPanel1.add(tableScrollPanePanel9); - tablesPanel1.add(tableScrollPanePanel10); - SpringUtilities.makeCompactGrid(tablesPanel1.getContentPane(), 3, 5, 0, 0, 0, 0); - - JFrame tablesPanel2 = new JFrame(); - tablesPanel2.setLayout(new SpringLayout()); - tablesPanel2.add(numRowsLabel11); - tablesPanel2.add(numRowsLabel12); - tablesPanel2.add(numRowsLabel13); - tablesPanel2.add(numRowsLabel14); - tablesPanel2.add(numRowsLabel15); - tablesPanel2.add(requiredPeriodLabel); - tablesPanel2.add(postProcessingLabel); - tablesPanel2.add(horizonLabel); - tablesPanel2.add(genMethodLabel); - tablesPanel2.add(reservoirModelLabel); - tablesPanel2.add(tableScrollPanePanel11); - tablesPanel2.add(tableScrollPanePanel12); - tablesPanel2.add(tableScrollPanePanel13); - tablesPanel2.add(tableScrollPanePanel14); - tablesPanel2.add(tableScrollPanePanel15); - SpringUtilities.makeCompactGrid(tablesPanel2.getContentPane(), 3, 5, 0, 0, 0, 0); - - JFrame tablesPanel3 = new JFrame(); - tablesPanel3.setLayout(new SpringLayout()); - tablesPanel3.add(numRowsLabel16); - tablesPanel3.add(numRowsLabel17); - tablesPanel3.add(respAgencyLabel); - tablesPanel3.add(serviceTypeLabel); - tablesPanel3.add(tableScrollPanePanel16); - tablesPanel3.add(tableScrollPanePanel17); - - SpringUtilities.makeCompactGrid(tablesPanel3.getContentPane(), 3, 2, 0, 0, 0, 0); - - lhvm.getContentPane().add(tablesPanel.getContentPane()); - lhvm.getContentPane ().add(separatorLabel1); - lhvm.getContentPane().add(tablesPanel1.getContentPane()); - lhvm.getContentPane ().add(separatorLabel2); - lhvm.getContentPane().add(tablesPanel2.getContentPane()); - lhvm.getContentPane ().add(separatorLabel3); - lhvm.getContentPane().add(tablesPanel3.getContentPane()); - lhvm.getContentPane ().add(closeButton); - lhvm.getContentPane().add(consoleLabel); - lhvm.getContentPane().add(scrollableTextAreaForConsole); - SpringUtilities.makeCompactGrid(lhvm.getContentPane(), 10, 1, 0, 0, 6, 6); - - lhvm.addWindowListener(new ServicesDbWindowAdapter()); - - lhvm.pack(); - //Show the JFrame - lhvm.setVisible (true); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - lhvm.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class CloseActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - operationCloseWindow(); - } - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RequiredPeriodJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RequiredPeriodJTableRowData.java deleted file mode 100644 index 304a1f4446..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RequiredPeriodJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class RequiredPeriodJTableRowData extends AbstractJTableRowData -{ - private String requiredPeriod; - private String missingRep = null; - - public RequiredPeriodJTableRowData() - { - } - - public RequiredPeriodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getRequiredPeriod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - RequiredPeriodJTableRowData requiredPeriodMethodRecord = (RequiredPeriodJTableRowData) rowData; - if(columnName.equals("Required Period")) - ret = compareStrings(getRequiredPeriod(), requiredPeriodMethodRecord.getRequiredPeriod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Required Period")) - dataValue = getStringValue(getRequiredPeriod()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Required Period", CellType.STRING, getRequiredPeriod(), missingRep)); - } - - public String getRequiredPeriod() { - return requiredPeriod; - } - - public void setRequiredPeriod(String requiredPeriod) { - this.requiredPeriod = requiredPeriod; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ReservoirModelJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ReservoirModelJTableRowData.java deleted file mode 100644 index a7f5fff797..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ReservoirModelJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class ReservoirModelJTableRowData extends AbstractJTableRowData -{ - private String reservoirModel; - private String missingRep = null; - - public ReservoirModelJTableRowData() - { - } - - public ReservoirModelJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getReservoirModel(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - ReservoirModelJTableRowData reservoirModelRecord = (ReservoirModelJTableRowData) rowData; - if(columnName.equals("Reservoir Model")) - ret = compareStrings(getReservoirModel(), reservoirModelRecord.getReservoirModel()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Reservoir Model")) - dataValue = getStringValue(getReservoirModel()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Reservoir Model", CellType.STRING, getReservoirModel(), missingRep)); - } - - public String getReservoirModel() { - return reservoirModel; - } - - public void setReservoirModel(String reservoirModel) { - this.reservoirModel = reservoirModel; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RespAgencyJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RespAgencyJTableRowData.java deleted file mode 100644 index a62cdbdc62..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RespAgencyJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class RespAgencyJTableRowData extends AbstractJTableRowData -{ - private String respAgency; - private String missingRep = null; - - public RespAgencyJTableRowData() - { - } - - public RespAgencyJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getRespAgency(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - RespAgencyJTableRowData respAgencyRecord = (RespAgencyJTableRowData) rowData; - if(columnName.equals("Wat Sup Resp Agency")) - ret = compareStrings(getRespAgency(), respAgencyRecord.getRespAgency()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Resp Agency")) - dataValue = getStringValue(getRespAgency()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Resp Agency", CellType.STRING, getRespAgency(), missingRep)); - } - - public String getRespAgency() { - return respAgency; - } - - public void setRespAgency(String respAgency) { - this.respAgency = respAgency; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RoutingMethodJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RoutingMethodJTableRowData.java deleted file mode 100644 index e70e9072d1..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/RoutingMethodJTableRowData.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class RoutingMethodJTableRowData extends AbstractJTableRowData -{ - private String routingMethod; - private String missingRep = null; - - public RoutingMethodJTableRowData() - { - } - - public RoutingMethodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getRoutingMethod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - RoutingMethodJTableRowData routingMethodRecord = (RoutingMethodJTableRowData) rowData; - if(columnName.equals("Routing Method")) - ret = compareStrings(getRoutingMethod(), routingMethodRecord.getRoutingMethod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Routing Method")) - dataValue = getStringValue(getRoutingMethod()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Routing Method", CellType.STRING, getRoutingMethod(), missingRep)); - } - - public String getRoutingMethod() { - return routingMethod; - } - - public void setRoutingMethod(String routingMethod) { - this.routingMethod = routingMethod; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServiceTableViewViewJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServiceTableViewViewJTableRowData.java deleted file mode 100644 index 8bb8a0ea78..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServiceTableViewViewJTableRowData.java +++ /dev/null @@ -1,128 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.ihfsdb.generated.ServiceTableViewRecord; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class ServiceTableViewViewJTableRowData extends AbstractJTableRowData -{ - private String lid; - private String state; - private String county; - private String hsa; - private String locName; - private String stream; - - public ServiceTableViewViewJTableRowData() - { - } - - public void setServiceTableViewRecord(ServiceTableViewRecord serviceTableViewRecord) - { - setLid(serviceTableViewRecord.getLid()); - setState(serviceTableViewRecord.getState()); - setCounty(serviceTableViewRecord.getCounty()); - setHsa(serviceTableViewRecord.getHsa()); - setLocName(serviceTableViewRecord.getName()); - setStream(serviceTableViewRecord.getStream()); - } - - public ServiceTableViewViewJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String toString() - { - String str = getLid()+" "+ - getState()+" "+ - getCounty()+" "+ - getHsa(); - return str; - } - - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - ServiceTableViewViewJTableRowData serviceTableViewRecord = (ServiceTableViewViewJTableRowData) rowData; - if(columnName.equals("Location ID")) - ret = compareStrings(getLid(), serviceTableViewRecord.getLid()); - else if(columnName.equals("State")) - ret = compareStrings(getState(), serviceTableViewRecord.getState()); - else if (columnName.equals("County")) - ret = compareStrings(getCounty(), serviceTableViewRecord.getCounty()); - else if (columnName.equals("Hsa")) - ret = compareStrings(getHsa(), serviceTableViewRecord.getHsa()); - else if (columnName.equals("Name")) - ret = compareStrings(getLocName(), serviceTableViewRecord.getLocName()); - else if (columnName.equals("Stream")) - ret = compareStrings(getStream(), serviceTableViewRecord.getStream()); - return ret; - } - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Location ID")) - dataValue = getStringValue(getLid()); - else if (columnName.equals("State")) - dataValue = getStringValue(getState()); - else if (columnName.equals("County")) - dataValue = getStringValue(getCounty()); - else if (columnName.equals("Hsa")) - dataValue = getStringValue(getHsa()); - else if (columnName.equals("Name")) - dataValue = getStringValue(getLocName()); - else if (columnName.equals("Stream")) - dataValue = getStringValue(getStream()); - return dataValue; - } - - public String getCounty() { - return county; - } - - public void setCounty(String county) { - this.county = county; - } - - public String getHsa() { - return hsa; - } - - public void setHsa(String hsa) { - this.hsa = hsa; - } - - public String getLid() { - return lid; - } - - public void setLid(String lid) { - this.lid = lid; - } - - public String getLocName() { - return locName; - } - - public void setLocName(String locName) { - this.locName = locName; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getStream() { - return stream; - } - - public void setStream(String stream) { - this.stream = stream; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServiceTypeJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServiceTypeJTableRowData.java deleted file mode 100644 index c6a8b4cb64..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServiceTypeJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class ServiceTypeJTableRowData extends AbstractJTableRowData -{ - private String serviceType; - private String missingRep = null; - - public ServiceTypeJTableRowData() - { - } - - public ServiceTypeJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getServiceType(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - ServiceTypeJTableRowData serviceTypeRecord = (ServiceTypeJTableRowData) rowData; - if(columnName.equals("Service Type")) - ret = compareStrings(getServiceType(), serviceTypeRecord.getServiceType()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Service Type")) - dataValue = getStringValue(getServiceType()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Service Type", CellType.STRING, getServiceType(), missingRep)); - } - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServicesDbWindowAdapter.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServicesDbWindowAdapter.java deleted file mode 100644 index 39996135f3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/ServicesDbWindowAdapter.java +++ /dev/null @@ -1,38 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JFrame; - -public class ServicesDbWindowAdapter extends WindowAdapter -{ - private JFrame jf = null; - private DataServicesGlobals dataServicesGlobals = null; - - public ServicesDbWindowAdapter() - { - super(); - } - - public void windowClosing(WindowEvent e) - { - jf = (JFrame) e.getSource(); - operationCloseWindow(); - } - - private void operationCloseWindow() - { - dataServicesGlobals = DataServicesGlobals.getSingleInstanceOfDataServicesGlobals(); - if(dataServicesGlobals.getCount() <= 1) - { - jf.dispose(); -// System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - jf.dispose(); - } - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/SnowMethodJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/SnowMethodJTableRowData.java deleted file mode 100644 index 4aa22dca62..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/SnowMethodJTableRowData.java +++ /dev/null @@ -1,58 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class SnowMethodJTableRowData extends AbstractJTableRowData -{ - private String snowMethod; - private String missingRep = null; - - public SnowMethodJTableRowData() - { - } - - public SnowMethodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getSnowMethod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - SnowMethodJTableRowData snowMethodRecord = (SnowMethodJTableRowData) rowData; - if(columnName.equals("Snow Method")) - ret = compareStrings(getSnowMethod(), snowMethodRecord.getSnowMethod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Snow Method")) - dataValue = getStringValue(getSnowMethod()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Snow Method", CellType.STRING, getSnowMethod(), missingRep)); - } - - public String getSnowMethod() { - return snowMethod; - } - - public void setSnowMethod(String snowMethod) { - this.snowMethod = snowMethod; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/SpringUtilities.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/SpringUtilities.java deleted file mode 100644 index d2afee0f51..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/SpringUtilities.java +++ /dev/null @@ -1,195 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.awt.Component; -import java.awt.Container; - -import javax.swing.Spring; -import javax.swing.SpringLayout; - -/** - * A 1.4 file that provides utility methods for - * creating form- or grid-style layouts with SpringLayout. - * These utilities are used by several programs, such as - * SpringBox and SpringCompactGrid. - */ -public class SpringUtilities -{ - /** - * A debugging utility that prints to stdout the component's - * minimum, preferred, and maximum sizes. - */ - public static void printSizes(Component c) { - System.out.println("minimumSize = " + c.getMinimumSize()); - System.out.println("preferredSize = " + c.getPreferredSize()); - System.out.println("maximumSize = " + c.getMaximumSize()); - } - - /** - * Aligns the first rows * cols - * components of parent in - * a grid. Each component is as big as the maximum - * preferred width and height of the components. - * The parent is made just big enough to fit them all. - * - * @param rows number of rows - * @param cols number of columns - * @param initialX x location to start the grid at - * @param initialY y location to start the grid at - * @param xPad x padding between cells - * @param yPad y padding between cells - */ - public static void makeGrid(Container parent, - int rows, int cols, - int initialX, int initialY, - int xPad, int yPad) { - SpringLayout layout; - try { - layout = (SpringLayout)parent.getLayout(); - } catch (ClassCastException exc) { - System.err.println("The first argument to makeGrid must use SpringLayout."); - return; - } - - Spring xPadSpring = Spring.constant(xPad); - Spring yPadSpring = Spring.constant(yPad); - Spring initialXSpring = Spring.constant(initialX); - Spring initialYSpring = Spring.constant(initialY); - int max = rows * cols; - - //Calculate Springs that are the max of the width/height so that all - //cells have the same size. - Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). - getWidth(); - Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). - getWidth(); - for (int i = 1; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - - maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); - maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); - } - - //Apply the new width/height Spring. This forces all the - //components to have the same size. - for (int i = 0; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - - cons.setWidth(maxWidthSpring); - cons.setHeight(maxHeightSpring); - } - - //Then adjust the x/y constraints of all the cells so that they - //are aligned in a grid. - SpringLayout.Constraints lastCons = null; - SpringLayout.Constraints lastRowCons = null; - for (int i = 0; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - if (i % cols == 0) { //start of new row - lastRowCons = lastCons; - cons.setX(initialXSpring); - } else { //x position depends on previous component - cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), - xPadSpring)); - } - - if (i / cols == 0) { //first row - cons.setY(initialYSpring); - } else { //y position depends on previous row - cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), - yPadSpring)); - } - lastCons = cons; - } - - //Set the parent's size. - SpringLayout.Constraints pCons = layout.getConstraints(parent); - pCons.setConstraint(SpringLayout.SOUTH, - Spring.sum( - Spring.constant(yPad), - lastCons.getConstraint(SpringLayout.SOUTH))); - pCons.setConstraint(SpringLayout.EAST, - Spring.sum( - Spring.constant(xPad), - lastCons.getConstraint(SpringLayout.EAST))); - } - - /* Used by makeCompactGrid. */ - private static SpringLayout.Constraints getConstraintsForCell( - int row, int col, - Container parent, - int cols) { - SpringLayout layout = (SpringLayout) parent.getLayout(); - Component c = parent.getComponent(row * cols + col); - return layout.getConstraints(c); - } - - /** - * Aligns the first rows * cols - * components of parent in - * a grid. Each component in a column is as wide as the maximum - * preferred width of the components in that column; - * height is similarly determined for each row. - * The parent is made just big enough to fit them all. - * - * @param rows number of rows - * @param cols number of columns - * @param initialX x location to start the grid at - * @param initialY y location to start the grid at - * @param xPad x padding between cells - * @param yPad y padding between cells - */ - public static void makeCompactGrid(Container parent, - int rows, int cols, - int initialX, int initialY, - int xPad, int yPad) { - SpringLayout layout; - try { - layout = (SpringLayout)parent.getLayout(); - } catch (ClassCastException exc) { - System.err.println("The first argument to makeCompactGrid must use SpringLayout."); - return; - } - - //Align all cells in each column and make them the same width. - Spring x = Spring.constant(initialX); - for (int c = 0; c < cols; c++) { - Spring width = Spring.constant(0); - for (int r = 0; r < rows; r++) { - width = Spring.max(width,getConstraintsForCell(r, c, parent, cols).getWidth()); - } - for (int r = 0; r < rows; r++) { - SpringLayout.Constraints constraints = - getConstraintsForCell(r, c, parent, cols); - constraints.setX(x); - constraints.setWidth(width); - } - x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); - } - - //Align all cells in each row and make them the same height. - Spring y = Spring.constant(initialY); - for (int r = 0; r < rows; r++) { - Spring height = Spring.constant(0); - for (int c = 0; c < cols; c++) { - height = Spring.max(height, - getConstraintsForCell(r, c, parent, cols). - getHeight()); - } - for (int c = 0; c < cols; c++) { - SpringLayout.Constraints constraints = - getConstraintsForCell(r, c, parent, cols); - constraints.setY(y); - constraints.setHeight(height); - } - y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); - } - - //Set the parent's size. - SpringLayout.Constraints pCons = layout.getConstraints(parent); - pCons.setConstraint(SpringLayout.SOUTH, y); - pCons.setConstraint(SpringLayout.EAST, x); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/Subject.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/Subject.java deleted file mode 100644 index b37367bc96..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/Subject.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.fcstservice; - -public interface Subject //Subject of the observer pattern -{ - public void addObserver(Observer observer); - public void removeObserver(Observer observer); - public void letKnowOfChanges(); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupCoordAgencyJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupCoordAgencyJTableRowData.java deleted file mode 100644 index f0d1e29c60..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupCoordAgencyJTableRowData.java +++ /dev/null @@ -1,58 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class WatSupCoordAgencyJTableRowData extends AbstractJTableRowData -{ - private String watsupCoordAgency; - private String missingRep = null; - - public WatSupCoordAgencyJTableRowData() - { - } - - public WatSupCoordAgencyJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getWatsupCoordAgency(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - WatSupCoordAgencyJTableRowData watsupCoordAgencyRecord = (WatSupCoordAgencyJTableRowData) rowData; - if(columnName.equals("Wat Sup Coord Agency")) - ret = compareStrings(getWatsupCoordAgency(), watsupCoordAgencyRecord.getWatsupCoordAgency()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Coord Agency")) - dataValue = getStringValue(getWatsupCoordAgency()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Coord Agency", CellType.STRING, getWatsupCoordAgency(), missingRep)); - } - - public String getWatsupCoordAgency() { - return watsupCoordAgency; - } - - public void setWatsupCoordAgency(String watsupCoordAgency) { - this.watsupCoordAgency = watsupCoordAgency; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupCriterionJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupCriterionJTableRowData.java deleted file mode 100644 index f3cf75fb45..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupCriterionJTableRowData.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class WatSupCriterionJTableRowData extends AbstractJTableRowData -{ - private String watsupCriterion; - private String missingRep = null; - - public WatSupCriterionJTableRowData() - { - } - - public WatSupCriterionJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getWatsupCriterion(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - WatSupCriterionJTableRowData watsupCriterionRecord = (WatSupCriterionJTableRowData) rowData; - if(columnName.equals("Wat Sup Criterion")) - ret = compareStrings(getWatsupCriterion(), watsupCriterionRecord.getWatsupCriterion()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Criterion")) - dataValue = getStringValue(getWatsupCriterion()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Criterion", CellType.STRING, getWatsupCriterion(), missingRep)); - } - - public String getWatsupCriterion() { - return watsupCriterion; - } - - public void setWatsupCriterion(String watsupCriterion) { - this.watsupCriterion = watsupCriterion; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupMethodJTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupMethodJTableRowData.java deleted file mode 100644 index 5710b73cfb..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fcstservice/WatSupMethodJTableRowData.java +++ /dev/null @@ -1,58 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class WatSupMethodJTableRowData extends AbstractJTableRowData -{ - private String watsupMethod; - private String missingRep = null; - - public WatSupMethodJTableRowData() - { - } - - public WatSupMethodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getWatsupMethod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - WatSupMethodJTableRowData watsupMethodRecord = (WatSupMethodJTableRowData) rowData; - if(columnName.equals("Wat Sup Method")) - ret = compareStrings(getWatsupMethod(), watsupMethodRecord.getWatsupMethod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Method")) - dataValue = getStringValue(getWatsupMethod()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Method", CellType.STRING, getWatsupMethod(), missingRep)); - } - - public String getWatsupMethod() { - return watsupMethod; - } - - public void setWatsupMethod(String watsupMethod) { - this.watsupMethod = watsupMethod; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpCurPrevVtec.java b/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpCurPrevVtec.java deleted file mode 100755 index 9f4dbf4019..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpCurPrevVtec.java +++ /dev/null @@ -1,467 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.util.ArrayList; - -public class FpCurPrevVtec -{ - private String _locId; - private String _locName; - private String _locStream; - private String _locPe; - private double _floodStg; - private double _floodFlow; - private long _obsBeginTime; - private long _fcstEndTime; - private double _adjustendhrs; - private String _curAction; - private String _curPhenom; - private String _curSignif; - private String _curSeverity; - private String _curCause; - private String _curRecord; - private int _curEtn; - private double _curCrestValue; - private long _curBeginTime; - private long _curEndTime; - private long _curRiseTime; - private long _curCrestTime; - private long _curFallTime; - private String _prevAction; - private String _prevPhenom; - private String _prevSignif; - private String _prevSeverity; - private String _prevCause; - private String _prevRecord; - private int _prevEtn; - private double _prevCrestValue; - private String _prevRiseType; - private String _prevCrestType; - private String _prevFallType; - private long _prevBeginTime; - private long _prevEndTime; - private long _prevRiseTime; - private long _prevCrestTime; - private long _prevFallTime; - private long _prevProductTime; - private ArrayList _obsValuetTimeList; - private ArrayList _fcstValueTimeList; - - public FpCurPrevVtec() - { - - } - - public String getLocId() - { - return _locId; - } - - public void setLocId(String locId) - { - _locId = locId; - } - public String getLocName() - { - return _locName; - } - - public void setLocName(String locName) - { - _locName = locName; - } - - public String getLocStream() - { - return _locStream; - } - - public void setLocStream(String locStream) - { - _locStream = locStream; - } - - public String getLocPe() - { - return _locPe; - } - - public void setLocPe(String locPe) - { - _locPe = locPe; - } - - public double getFloodStg() - { - return _floodStg; - } - - public void setFloodStg(double floodStg) - { - _floodStg = floodStg; - } - - public double getFloodFlow() - { - return _floodFlow; - } - - public void setFloodFlow(double floodFlow) - { - _floodFlow = floodFlow; - } - - public long getObsBeginTime() - { - return _obsBeginTime; - } - - public void setObsBeginTime(long obsBeginTime) - { - _obsBeginTime = obsBeginTime; - } - - public long getFcstEndTime() - { - return _fcstEndTime; - } - - public void setFcstEndTime(long fcstEndTime) - { - _fcstEndTime = fcstEndTime; - } - - public double getAdjustEndhrs() - { - return _adjustendhrs; - } - - public void setAdjustEndhrs(double adjustendhrs) - { - _adjustendhrs = adjustendhrs; - } - - public String getcurAction() - { - return _curAction; - } - - public void setcurAction(String curAction) - { - _curAction = curAction; - } - - public String getcurPhenom() - { - return _curPhenom; - } - - public void setcurPhenom(String curPhenom) - { - _curPhenom = curPhenom; - } - - public String getcurSignif() - { - return _curSignif; - } - - public void setcurSignif(String curSignif) - { - _curSignif = curSignif; - } - - public String getcurSeverity() - { - return _curSeverity; - } - - public void setcurSeverity(String curSeverity) - { - _curSeverity = curSeverity; - } - - public String getcurCause() - { - return _curCause; - } - - public void setcurCause(String curCause) - { - _curCause = curCause; - } - - public String getcurRecord() - { - return _curRecord; - } - - public void setcurRecord(String curRecord) - { - _curRecord = curRecord; - } - - public int getcurEtn() - { - return _curEtn; - } - - public void setcurEtn(int curEtn) - { - _curEtn = curEtn; - } - - public double getcurCrestValue() - { - return _curCrestValue; - } - - public void setcurCrestValue(double curCrestValue) - { - _curCrestValue = curCrestValue; - } - - public long getcurBeginTime() - { - return _curBeginTime; - } - - public void setcurBeginTime(long curBeginTime) - { - _curBeginTime = curBeginTime; - } - - public long getcurEndTime() - { - return _curEndTime; - } - - public void setcurEndTime(long curEndTime) - { - _curEndTime = curEndTime; - } - - public long getcurRiseTime() - { - return _curRiseTime; - } - - public void setcurRiseTime(long curRiseTime) - { - _curRiseTime = curRiseTime; - } - - public long getcurCrestTime() - { - return _curCrestTime; - } - - public void setcurCrestTime(long curCrestTime) - { - _curCrestTime = curCrestTime; - } - - public long getcurFallTime() - { - return _curFallTime; - } - - public void setcurFallTime(long curFallTime) - { - _curFallTime = curFallTime; - } - - - public String getprevAction() - { - return _prevAction; - } - - public void setprevAction(String prevAction) - { - _prevAction = prevAction; - } - - public String getprevPhenom() - { - return _prevPhenom; - } - - public void setprevPhenom(String prevPhenom) - { - _prevPhenom = prevPhenom; - } - - public String getprevSignif() - { - return _prevSignif; - } - - public void setprevSignif(String prevSignif) - { - _prevSignif = prevSignif; - } - - public String getprevSeverity() - { - return _prevSeverity; - } - - public void setprevSeverity(String prevSeverity) - { - _prevSeverity = prevSeverity; - } - - public String getprevCause() - { - return _prevCause; - } - - public void setprevCause(String prevCause) - { - _prevCause = prevCause; - } - - public String getprevRecord() - { - return _prevRecord; - } - - public void setprevRecord(String prevRecord) - { - _prevRecord = prevRecord; - } - - public int getprevEtn() - { - return _prevEtn; - } - - public void setprevEtn(int prevEtn) - { - _prevEtn = prevEtn; - } - - public double getprevCrestValue() - { - return _prevCrestValue; - } - - public void setprevCrestValue(double prevCrestValue) - { - _prevCrestValue = prevCrestValue; - } - - public String getprevRiseType() - { - return _prevRiseType; - } - - public void setprevRiseType(String prevRiseType) - { - _prevRiseType = prevRiseType; - } - - public String getprevCrestType() - { - return _prevCrestType; - } - - public void setprevCrestType(String prevCrestType) - { - _prevCrestType = prevCrestType; - } - - public String getprevFallType() - { - return _prevFallType; - } - - public void setprevFallType(String prevFallType) - { - _prevFallType = prevFallType; - } - - public long getprevBeginTime() - { - return _prevBeginTime; - } - - public void setprevBeginTime(long prevBeginTime) - { - _prevBeginTime = prevBeginTime; - } - - public long getprevEndTime() - { - return _prevEndTime; - } - - public void setprevEndTime(long prevEndTime) - { - _prevEndTime = prevEndTime; - } - - public long getprevRiseTime() - { - return _prevRiseTime; - } - - public void setprevRiseTime(long prevRiseTime) - { - _prevRiseTime = prevRiseTime; - } - - public long getprevCrestTime() - { - return _prevCrestTime; - } - - public void setprevCrestTime(long prevCrestTime) - { - _prevCrestTime = prevCrestTime; - } - - public long getprevFallTime() - { - return _prevFallTime; - } - - public void setprevFallTime(long prevFallTime) - { - _prevFallTime = prevFallTime; - } - - public long getprevProductTime() - { - return _prevProductTime; - } - - public void setprevProductTime(long prevProductTime) - { - _prevProductTime = prevProductTime; - } - - public String toString() - { - String str = null; - return str; - } - - public ArrayList getObsValuetTimeList() { - return _obsValuetTimeList; - } - - public void setObsValuetTimeList(ArrayList obsValuetTimeList) { - _obsValuetTimeList = obsValuetTimeList; - } - - public ArrayList getFcstValueTimeList() { - return _fcstValueTimeList; - } - - public void setFcstValueTimeList(ArrayList fcstValueTimeList) { - _fcstValueTimeList = fcstValueTimeList; - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfo.java b/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfo.java deleted file mode 100644 index 312fd60143..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfo.java +++ /dev/null @@ -1,1173 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.FlowToStageValueMapper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.timeserieslite.gui.drawing.SignificantLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TsCanvasToolTipListener; -import ohd.hseb.timeserieslite.gui.drawing.TsDataPointPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslBackgroundPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslCanvasPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslTimeLinePainter; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class FpVtecInfo { - private static final long MISSING_INT = -9999; - - private static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - private static final long MILLIS_PER_SECOND = 1000; - - private static final int TOP_MARGIN = 100; - - private int _defaultHoursBackInTime = 120; - - private int _defaultHoursForwardInTime = 336; - - private FpVtecInfoDataManager _dataMgr = null; - - private String _locationId = null; - - private List _paramCodeList = new ArrayList(); - - private String _jdbcConnectionString = null; - - private FpCurPrevVtec _fpCurPrevVtecRecord = null; - - private PDCDataType _dataType = null; - - private List _dataTypeList = new ArrayList(); - - private long _startTime = 0; - - private long _endTime = 0; - - private int HOURS_TO_ROUND = 6; - - private FpVtecInfoFrame _frame = null; - - private TsPaintableCanvas _canvas = null; - - private TimeHolder _curVtecBeginTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecEndTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecRiseTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecCrestTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecFallTimeHolder = new TimeHolder(); - - private static Map _physicalElementMap = new HashMap(); - static { - _physicalElementMap.put("HG", PDCDataType.HEIGHT); - _physicalElementMap.put("HP", PDCDataType.HEIGHT); - _physicalElementMap.put("HT", PDCDataType.HEIGHT); - _physicalElementMap.put("HM", PDCDataType.HEIGHT); - _physicalElementMap.put("HL", PDCDataType.HEIGHT); - _physicalElementMap.put("HZ", PDCDataType.HEIGHT); - _physicalElementMap.put("HK", PDCDataType.HEIGHT); - _physicalElementMap.put("QR", PDCDataType.DISCHARGE); - _physicalElementMap.put("QT", PDCDataType.DISCHARGE); - _physicalElementMap.put("QS", PDCDataType.DISCHARGE); - _physicalElementMap.put("QA", PDCDataType.DISCHARGE); - _physicalElementMap.put("QM", PDCDataType.DISCHARGE); - - } - - // ------------------------------------------------------------------------------------- - - public static void show(String dbConnString, String locationId, - String paramCodeString1, String paramCodeString2) { - - String[] argStringArray = { dbConnString, locationId, paramCodeString1, - paramCodeString2 }; - - FpVtecInfoFrame.setLastUpdateTime(FpVtecInfoFrame.STILL_OPENED); - - for (int i = 0; i < argStringArray.length; i++) { - System.out.println("argStringArray[" + i + "] = " - + argStringArray[i]); - } - - FpVtecInfo app = new FpVtecInfo(); - app.display(argStringArray, true); - - // need to refresh frame in "Update Graph" and "Save Changes" - app.getFrame().setApplication(app); - - } - - // -------------------------------------------------------------------------------------------------- - - public static void main(String[] argStringArray) { - FpVtecInfo app = new FpVtecInfo(); - app.display(argStringArray, true); - - // need to refresh frame in "Update Graph" and "Save Changes" - app.getFrame().setApplication(app); - - } - - // -------------------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) { - - CodeTimer timer = new CodeTimer(); - System.out - .println("Start to display event's timeseries and VTEC information"); - - // retrive the input arguments - handleCommandLineArgs(argStringArray); - - String header = "FpVtecInfo.display()"; - - // read FP, VTEC information from input file - timer.start(); - _dataMgr.readInputFileFormFpCurPrevVtecInfoMap(); - timer.stop(header + " read input file took"); - - // set the timeseries beginTime and endTime based on backhrs and - // forecasthrs - // store FP/VTEC information to _fpCurPrevVtecRecord for location - // _locationId - - _fpCurPrevVtecRecord = setTSBeginEndTimeWindow(_locationId); - - // prepare the JFrame for display window - if (_frame == null) - _frame = new FpVtecInfoFrame(_fpCurPrevVtecRecord, _dataMgr); - - _frame.setExitOnClose(exitOnClose); - - // get canvas from frame - _canvas = _frame.getCanvas(); - - // determine the stage or flow data type - - if (_dataTypeList.size() > 0) { - _dataType = (PDCDataType) _dataTypeList.get(0); - } - - // draw the canvas - timer.start(); - initializeCanvas(_dataType, _paramCodeList, _canvas); - timer.stop(header + " initializeCanvas() took "); - - timer.start(); - _frame.setVisible(true); - timer.stop(header + "setVisible() took "); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void handleCommandLineArgs(String[] argStringArray) { - String header = "FpVtecInfo.handleCommandLineArgs(): "; - - // includes the optional jdbcConnectionString - if (argStringArray.length > 0) { - _jdbcConnectionString = argStringArray[0]; - _dataMgr = new FpVtecInfoDataManager(_jdbcConnectionString); - System.out.println("_jdbcConnection = " + _jdbcConnectionString); - } - - // location id - if (argStringArray.length > 1) { - _locationId = argStringArray[1]; - System.out.println("_locationId = " + _locationId); - } - - // create param code list and dataType list - for (int i = 2; i < argStringArray.length; i++) { - String paramCodeString = argStringArray[i]; - System.out.println(header + "paramCodeString = " + paramCodeString); - - if ((paramCodeString != null) && (paramCodeString.length() == 6)) // valid - // example - // = - // HRIRGZ - { - ParamCode paramCode = new ParamCode(paramCodeString); - - paramCode = expandParamCode(_locationId, paramCode); - - if (paramCode != null) { - _paramCodeList.add(paramCode); - - // String physicalElement = paramCode.substring(0,2); - PDCDataType dataType = getDataTypeFromPhysicalElement(paramCode - .getPe()); - _dataTypeList.add(dataType); - } - } - } - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void initializeCanvas(PDCDataType dataType, List paramCodeList, - TsPaintableCanvas canvas) { - initializeTimeWindow(canvas); - - // make room for the large area required by the text header in the graph - canvas.setTopMargin(TOP_MARGIN); - - if (dataType == PDCDataType.HEIGHT) { - - initForHeight(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DISCHARGE) { - initForDischarge(_locationId, paramCodeList, canvas); - } - - // call this again to make it redraw everything correctly - // it wasn't working without this - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // ----------------------------------------------------------------------- - public void redrawCanvas() { - _canvas.refresh(); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void initializeTimeWindow(TsPaintableCanvas canvas) { - setStartTime(_startTime); - setEndTime(_endTime); - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // ---------------------------------------------------------------------------------------------------- - private FpCurPrevVtec setTSBeginEndTimeWindow(String locationId) { - String header = "FpVtecInfo.setTSBeginEndTime() "; - Map tempMap = new HashMap(); - - // get current time - long currentTime = System.currentTimeMillis(); - long roundedCurrentTime = TimeHelper.truncateTimeInMillisToNearestHour( - currentTime, HOURS_TO_ROUND); - - // set up time window - // get the backhrs and forwardhrs from record for locationId - - tempMap = _dataMgr.getvtecinfoMap(); - - FpCurPrevVtec temp = (FpCurPrevVtec) tempMap.get(locationId); - - if (temp != null) { - long obs_begintime_inmillis = temp.getObsBeginTime() - * MILLIS_PER_SECOND; - long fcst_endtime_inmillis = temp.getFcstEndTime() - * MILLIS_PER_SECOND; - - long rounded_obs_begintime = TimeHelper - .truncateTimeInMillisToNearestHour(obs_begintime_inmillis, - HOURS_TO_ROUND); - long rounded_fcst_endtime = TimeHelper - .truncateTimeInMillisToNearestHour(fcst_endtime_inmillis, - HOURS_TO_ROUND); - - if ((temp.getObsBeginTime() == MISSING_INT) - || (temp.getObsBeginTime() == 0)) - setStartTime(roundedCurrentTime - - (_defaultHoursBackInTime * MILLIS_PER_HOUR)); - else - setStartTime(rounded_obs_begintime); - - if ((temp.getFcstEndTime() == MISSING_INT) - || (temp.getFcstEndTime() == 0)) - setEndTime(roundedCurrentTime - + (_defaultHoursForwardInTime * MILLIS_PER_HOUR)); - else - setEndTime(rounded_fcst_endtime); - - } - - else { - System.out.println(header + "VTEC record not found for " - + locationId); - } - - return temp; - - } - - // -------------------------------------------------------------------------------------------------- - - private boolean isValueAvailable(Measurement measurement, MeasuringUnit unit) { - boolean result = false; - - if (measurement != null) { - if (measurement.getValue(unit) > 0.0) { - result = true; - } - } - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private void addCanvasListeners(TsPaintableCanvas canvas, - ValueMapper valueMapper) { - // Add listener for the tooltip - TsCanvasToolTipListener toolTipMgr = new TsCanvasToolTipListener( - canvas, valueMapper); - canvas.addMouseMotionListener(toolTipMgr); - - // Add listener for the timelines drag - TimeLineAdjustmentListener adjustmentListener = new TimeLineAdjustmentListener( - this, canvas, getCurVtecBeginTimeHolder(), - getCurVtecEndTimeHolder(), getCurVtecRiseTimeHolder(), - getCurVtecCrestTimeHolder(), getCurVtecFallTimeHolder()); - canvas.addMouseListener(adjustmentListener); - - return; - } - - // ------------------------------------------------------------------------------------- - private ParamCode expandParamCode(String locationId, ParamCode paramCode) { - - String header = "FpVtecInfo.expandParamCode(): "; - ParamCode expandedParamCode = new ParamCode(paramCode); - String expandedParamCodeString = null; - - String typeSource = paramCode.getTypeSource(); - String peString = paramCode.getPe(); - - if (typeSource.indexOf('-') == 1) { - if (typeSource.charAt(0) == 'F') { - typeSource = _dataMgr.getPreferredFcstTypeSource(locationId, - peString); - - if (typeSource != null) { - expandedParamCode.setTypeSource(typeSource); - expandedParamCodeString = expandedParamCode.toString(); - } else { - expandedParamCode = null; - expandedParamCodeString = null; - } - } - - } else { - expandedParamCodeString = expandedParamCode.toString(); - } - - System.out.println(header + "original paramCode = " - + paramCode.toString()); - System.out.println(header + "expandedParamCode = " - + expandedParamCodeString); - - return expandedParamCode; - - } - - // ------------------------------------------------------------------------------------- - - PDCDataType getDataTypeFromPhysicalElement(String physicalElement) { - - PDCDataType dataType = (PDCDataType) _physicalElementMap - .get(physicalElement); - if (dataType == null) { - if (stringStartsWith(physicalElement, 'H')) { - dataType = PDCDataType.HEIGHT; - } - if (stringStartsWith(physicalElement, 'Q')) { - dataType = PDCDataType.DISCHARGE; - } - } - - return dataType; - - } - - // ------------------------------------------------------------------------------------- - - private boolean stringStartsWith(String physicalElement, char firstCharacter) { - boolean result = false; - - if ((physicalElement != null) && (physicalElement.length() > 0) - && (physicalElement.charAt(0) == firstCharacter)) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------- - - public void initForHeight(String locationId, List paramCodeList, - TsPaintableCanvas canvas) { - long curvtec_beginTime = 0; - long curvtec_endTime = 0; - long curvtec_riseTime = 0; - long curvtec_crestTime = 0; - long curvtec_fallTime = 0; - - String header = "FpVtecInfo.initForHeight(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - Color outlineColor = Color.WHITE; - Color cur_timeLineColor = Color.WHITE; - Color curvtec_begintimeLineColor = Color.BLUE; - Color curvtec_endtimeLineColor = Color.GREEN; - Color curvtec_risetimeLineColor = Color.ORANGE; - Color curvtec_cresttimeLineColor = Color.RED; - Color curvtec_falltimeLineColor = Color.MAGENTA; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = null; // actually depends on rating curve - // existence - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - // handel the begintime saved as CURRENT time - if (_fpCurPrevVtecRecord.getcurBeginTime() == -1) { - getCurVtecBeginTimeHolder().setTime(currentTime); - } else if (_fpCurPrevVtecRecord.getcurBeginTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecBeginTimeHolder().setTime(MISSING_INT); - } else { - curvtec_beginTime = _fpCurPrevVtecRecord.getcurBeginTime() - * MILLIS_PER_SECOND; - getCurVtecBeginTimeHolder().setTime(curvtec_beginTime); - - } - - // handel the endtime as CURRENT time - if (_fpCurPrevVtecRecord.getcurEndTime() == -1) { - getCurVtecEndTimeHolder().setTime(currentTime); - } else if (_fpCurPrevVtecRecord.getcurEndTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecEndTimeHolder().setTime(MISSING_INT); - } else { - curvtec_endTime = _fpCurPrevVtecRecord.getcurEndTime() - * MILLIS_PER_SECOND; - getCurVtecEndTimeHolder().setTime(curvtec_endTime); - } - - // handle the risetime - if (_fpCurPrevVtecRecord.getcurRiseTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecRiseTimeHolder().setTime(MISSING_INT); - } else { - curvtec_riseTime = _fpCurPrevVtecRecord.getcurRiseTime() - * MILLIS_PER_SECOND; - getCurVtecRiseTimeHolder().setTime(curvtec_riseTime); - } - - // handle the crest time - if (_fpCurPrevVtecRecord.getcurCrestTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecCrestTimeHolder().setTime(MISSING_INT); - } else { - curvtec_crestTime = _fpCurPrevVtecRecord.getcurCrestTime() - * MILLIS_PER_SECOND; - getCurVtecCrestTimeHolder().setTime(curvtec_crestTime); - } - - // handle the falltime - if (_fpCurPrevVtecRecord.getcurFallTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecFallTimeHolder().setTime(MISSING_INT); - } else { - curvtec_fallTime = _fpCurPrevVtecRecord.getcurFallTime() - * MILLIS_PER_SECOND; - getCurVtecFallTimeHolder().setTime(curvtec_fallTime); - } - - // set title and measuring units - - String titleString = "River Stages for " + locationId; - - // read in the observed time series - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - - // read in the forecast time series - - fcstTs = _dataMgr.loadFcstStageTimeSeries(locationId, - paramCode, getEndTime(), _fpCurPrevVtecRecord); - - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } else // observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = _dataMgr.loadObservedStageTimeSeries(locationId, - paramCode, getStartTime(), _fpCurPrevVtecRecord); - - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - } - - // create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - ValueMapper valueMapper = null; - - if (ratingCurve.exists()) { - valueMapper = new StageToFlowValueMapper(ratingCurve); - rightAxisLabelString = "cfs"; - } else { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "feet"; - } - - // the textheader in the TimeSeries/VTEC info window - String[] textHeaderStringArray = null; - - if (_fpCurPrevVtecRecord != null) { - textHeaderStringArray = getTextHeaderStringArray(locationId, - _fpCurPrevVtecRecord, obsParamCodeString.substring(0, 5), - fcstParamCodeString.substring(0, 5), unit.toString()); - - } - - TslBackgroundPainter backgroundPainter = new TslBackgroundPainter( - outlineColor, leftAxisLabelString, rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - // time lines painter - // Current time line - if (currentTimeHolder != null) { - // TslTimeLinePainter timeLinePainter = new - // TslTimeLinePainter(cur_timeLineColor, - // "N", 95, currentTimeHolder); - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter( - cur_timeLineColor, "N", 95, currentTimeHolder); - - assignPainterToCanvas(timeLinePainter, canvas); - } - - // Event begin time line - - TslTimeLinePainter curvtec_begintimeLinePainter = new TslTimeLinePainter( - curvtec_begintimeLineColor, "B", 95, - getCurVtecBeginTimeHolder()); - assignPainterToCanvas(curvtec_begintimeLinePainter, canvas); - - // Event end time line - - TslTimeLinePainter curvtec_endtimeLinePainter = new TslTimeLinePainter( - curvtec_endtimeLineColor, "E", 95, getCurVtecEndTimeHolder()); - - assignPainterToCanvas(curvtec_endtimeLinePainter, canvas); - - // Event Rise time line - - TslTimeLinePainter curvtec_risetimeLinePainter = new TslTimeLinePainter( - curvtec_risetimeLineColor, "R", 95, - getCurVtecRiseTimeHolder()); - - assignPainterToCanvas(curvtec_risetimeLinePainter, canvas); - - // Event Crest time line - - TslTimeLinePainter curvtec_cresttimeLinePainter = new TslTimeLinePainter( - curvtec_cresttimeLineColor, "C", 95, - getCurVtecCrestTimeHolder()); - - assignPainterToCanvas(curvtec_cresttimeLinePainter, canvas); - - - // Event Fall time line - - TslTimeLinePainter curvtec_falltimeLinePainter = new TslTimeLinePainter( - curvtec_falltimeLineColor, "F", 95, - getCurVtecFallTimeHolder()); - - assignPainterToCanvas(curvtec_falltimeLinePainter, canvas); - - - // significant value line painters for floodstage and actionstage - - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - Color actionStageColor = Color.YELLOW; - Color floodStageColor = Color.ORANGE; - Color moderateStageColor = Color.RED; - Color majorStageColor = Color.MAGENTA; - - if (sigRiverLevels != null) { - boolean shouldPaint = false; - - // flood stage - Measurement floodStageMeasurement = new Measurement(sigRiverLevels - .getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = new SignificantLinePainter( - floodStageColor, floodStageMeasurement, unit); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - floodStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(floodStagePainter, canvas); - - // action stage - Measurement actionStageMeasurement = new Measurement(sigRiverLevels - .getActionStage(), unit); - - SignificantLinePainter actionStagePainter = new SignificantLinePainter( - actionStageColor, actionStageMeasurement, unit); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - actionStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(actionStagePainter, canvas); - - // moderate stage - double moderatefs = sigRiverLevels.getModerateFloodStage(); - Measurement moderateStageMeasurement = new Measurement( - sigRiverLevels.getModerateFloodStage(), unit); - - SignificantLinePainter moderateStagePainter = new SignificantLinePainter( - moderateStageColor, moderateStageMeasurement, unit); - - shouldPaint = isValueAvailable(moderateStageMeasurement, unit); - moderateStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(moderateStagePainter, canvas); - - // major stage - Measurement majorStageMeasurement = new Measurement(sigRiverLevels - .getMajorFloodStage(), unit); - - SignificantLinePainter majorStagePainter = new SignificantLinePainter( - majorStageColor, majorStageMeasurement, unit); - - shouldPaint = isValueAvailable(majorStageMeasurement, unit); - majorStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(majorStagePainter, canvas); - - } - - // observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, - obsTsHolder); - obsTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, - fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ------------------------------------------------------------------------------------ - public void initForDischarge(String locationId, List paramCodeList, - TsPaintableCanvas canvas) { - long curvtec_beginTime = 0; - long curvtec_endTime = 0; - long curvtec_riseTime = 0; - long curvtec_crestTime = 0; - long curvtec_fallTime = 0; - - String header = "FpVtecInfo.initForDischarge(): "; - - MeasuringUnit unit = MeasuringUnit.cfs; - - canvas.setDisplayedMeasuringUnit(unit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.WHITE; - Color curvtec_begintimeLineColor = Color.BLUE; - Color curvtec_endtimeLineColor = Color.GREEN; - Color curvtec_risetimeLineColor = Color.ORANGE; - Color curvtec_cresttimeLineColor = Color.RED; - Color curvtec_falltimeLineColor = Color.MAGENTA; - - String leftAxisLabelString = "cfs"; - String rightAxisLabelString = null; // actually depends on rating curve - // existence - - // Set time - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - // handel the begintime saved as CURRENT time - if (_fpCurPrevVtecRecord.getcurBeginTime() == -1) { - // curvtec_beginTimeHolder = new TimeHolder(); - getCurVtecBeginTimeHolder().setTime(currentTime); - } else if (_fpCurPrevVtecRecord.getcurBeginTime() != -9999) { - curvtec_beginTime = _fpCurPrevVtecRecord.getcurBeginTime() - * MILLIS_PER_SECOND; - // curvtec_beginTimeHolder = new TimeHolder(); - getCurVtecBeginTimeHolder().setTime(curvtec_beginTime); - } - if (_fpCurPrevVtecRecord.getcurEndTime() != -9999) { - curvtec_endTime = _fpCurPrevVtecRecord.getcurEndTime() - * MILLIS_PER_SECOND; - // curvtec_endTimeHolder = new TimeHolder(); - getCurVtecEndTimeHolder().setTime(curvtec_endTime); - } - if (_fpCurPrevVtecRecord.getcurRiseTime() != -9999) { - curvtec_riseTime = _fpCurPrevVtecRecord.getcurRiseTime() - * MILLIS_PER_SECOND; - // curvtec_riseTimeHolder = new TimeHolder(); - getCurVtecRiseTimeHolder().setTime(curvtec_riseTime); - } - if (_fpCurPrevVtecRecord.getcurCrestTime() != -9999) { - curvtec_crestTime = _fpCurPrevVtecRecord.getcurCrestTime() - * MILLIS_PER_SECOND; - // curvtec_crestTimeHolder = new TimeHolder(); - getCurVtecCrestTimeHolder().setTime(curvtec_crestTime); - } - if (_fpCurPrevVtecRecord.getcurFallTime() != -9999) { - curvtec_fallTime = _fpCurPrevVtecRecord.getcurFallTime() - * MILLIS_PER_SECOND; - // curvtec_fallTimeHolder = new TimeHolder(); - getCurVtecFallTimeHolder().setTime(curvtec_fallTime); - } - - // set title and measuring units - - String titleString = "River Discharge for " + locationId; - // read in the observed time series - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - // read in the forecast time series - fcstTs = _dataMgr.loadFcstDischargeTimeSeries(locationId, - paramCode, getEndTime(), _fpCurPrevVtecRecord); - - fcstStageTimer - .stop(header + "loadFcstDischargeTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } else // observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = _dataMgr.loadObservedDischargeTimeSeries(locationId, - paramCode, getStartTime(), _fpCurPrevVtecRecord); - stageTimer.stop(header - + "loadObservedDischargeTimeSeries took "); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - } - - // create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - ValueMapper valueMapper = null; - - if (ratingCurve.exists()) { - valueMapper = new FlowToStageValueMapper(ratingCurve); - rightAxisLabelString = "feet"; - } else { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "cfs"; - } - - String[] textHeaderStringArray = null; - - if (_fpCurPrevVtecRecord != null) { - textHeaderStringArray = getTextHeaderStringArray(locationId, - _fpCurPrevVtecRecord, obsParamCodeString.substring(0, 5), - fcstParamCodeString.substring(0, 5), unit.toString()); - } - - TslBackgroundPainter backgroundPainter = new TslBackgroundPainter( - outlineColor, leftAxisLabelString, rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - // time line painter - if (currentTimeHolder != null) { - TslTimeLinePainter nowtimeLinePainter = new TslTimeLinePainter( - timeLineColor, "N", 95, currentTimeHolder); - // nowtimeLineLabelPainter.setTimeType("N"); - assignPainterToCanvas(nowtimeLinePainter, canvas); - } - - if (getCurVtecBeginTimeHolder() != null) { - TslTimeLinePainter curvtec_begintimeLinePainter = new TslTimeLinePainter( - curvtec_begintimeLineColor, "B", 95, - getCurVtecBeginTimeHolder()); - assignPainterToCanvas(curvtec_begintimeLinePainter, canvas); - } - - if (getCurVtecEndTimeHolder() != null) { - TslTimeLinePainter curvtec_endtimeLinePainter = new TslTimeLinePainter( - curvtec_endtimeLineColor, "E", 95, - getCurVtecEndTimeHolder()); - - assignPainterToCanvas(curvtec_endtimeLinePainter, canvas); - } - - if (getCurVtecRiseTimeHolder() != null) { - TslTimeLinePainter curvtec_risetimeLinePainter = new TslTimeLinePainter( - curvtec_risetimeLineColor, "R", 95, - getCurVtecRiseTimeHolder()); - - assignPainterToCanvas(curvtec_risetimeLinePainter, canvas); - } - - if (getCurVtecCrestTimeHolder() != null) { - TslTimeLinePainter curvtec_cresttimeLinePainter = new TslTimeLinePainter( - curvtec_cresttimeLineColor, "C", 95, - getCurVtecCrestTimeHolder()); - - assignPainterToCanvas(curvtec_cresttimeLinePainter, canvas); - } - - if (getCurVtecFallTimeHolder() != null) { - TslTimeLinePainter curvtec_falltimeLinePainter = new TslTimeLinePainter( - curvtec_falltimeLineColor, "F", 95, - getCurVtecFallTimeHolder()); - - assignPainterToCanvas(curvtec_falltimeLinePainter, canvas); - } - - // significant value line painters for floodflow and actionflow - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - Color floodFlowColor = Color.RED; - Color moderateFlowColor = Color.MAGENTA; - Color majorFlowColor = Color.CYAN; - Color actionFlowColor = Color.YELLOW; - - if (sigRiverLevels != null) { - boolean shouldPaint = false; - - // Flood Flow - Measurement floodFlowMeasurement = new Measurement(sigRiverLevels - .getFloodFlow(), unit); - - SignificantLinePainter floodFlowPainter = new SignificantLinePainter( - floodFlowColor, floodFlowMeasurement, unit); - - shouldPaint = isValueAvailable(floodFlowMeasurement, unit); - floodFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(floodFlowPainter, canvas); - - // action flow - Measurement actionFlowMeasurement = new Measurement(sigRiverLevels - .getActionFlow(), unit); - - SignificantLinePainter actionFlowPainter = new SignificantLinePainter( - actionFlowColor, actionFlowMeasurement, unit); - - shouldPaint = isValueAvailable(actionFlowMeasurement, unit); - actionFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(actionFlowPainter, canvas); - - // moderate flow - Measurement moderateFlowMeasurement = new Measurement( - sigRiverLevels.getModerateFloodFlow(), unit); - - SignificantLinePainter moderateFlowPainter = new SignificantLinePainter( - moderateFlowColor, moderateFlowMeasurement, unit); - - shouldPaint = isValueAvailable(moderateFlowMeasurement, unit); - moderateFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(moderateFlowPainter, canvas); - - // major flow - Measurement majorFlowMeasurement = new Measurement(sigRiverLevels - .getMajorFloodFlow(), unit); - - SignificantLinePainter majorFlowPainter = new SignificantLinePainter( - majorFlowColor, majorFlowMeasurement, unit); - - shouldPaint = isValueAvailable(majorFlowMeasurement, unit); - majorFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(majorFlowPainter, canvas); - - } - - // observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, - obsTsHolder); - obsTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, - fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ------------------------------------------------------------------------------------ - - private void assignPainterToCanvas(TslCanvasPainter painter, - TsPaintableCanvas canvas) { - painter.setCanvas(canvas); - canvas.addTsCanvasPainter(painter); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslTimeLinePainter painter, - TsPaintableCanvas canvas) { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void assignPainterToCanvas(TslBackgroundPainter painter, - TsPaintableCanvas canvas) { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private String[] getTextHeaderStringArray(String locationId, - FpCurPrevVtec fpcurprevvtecRecord, String paramCodeString, - String fcstParamCodeString, String unitString) { - String[] textHeaderStringArray = null; - StringBuffer paramCodeStringBuffer = new StringBuffer(paramCodeString); - if (fcstParamCodeString != null) { - paramCodeStringBuffer.append(" " + fcstParamCodeString); - } - - textHeaderStringArray = new String[3]; - - // Lid-Name-FldStg - // if (unitString.equals("feet")) - if (_dataType == PDCDataType.HEIGHT) - textHeaderStringArray[0] = locationId + " - " - + fpcurprevvtecRecord.getLocName() + " - " - + fpcurprevvtecRecord.getLocStream() + " - " - + "Flood Stage: " + fpcurprevvtecRecord.getFloodStg() + " " - + unitString; - else - textHeaderStringArray[0] = locationId + " - " - + fpcurprevvtecRecord.getLocName() + " - " - + fpcurprevvtecRecord.getLocStream() + " - " - + "Flood Flow: " + fpcurprevvtecRecord.getFloodFlow() - + unitString; - - // PE-TS - textHeaderStringArray[1] = "PE/DUR/TS: " - + paramCodeStringBuffer.toString(); - - // Current VTEC phenom, signif and ETN - - textHeaderStringArray[2] = "Proposed VTEC Phenom: " - + fpcurprevvtecRecord.getcurPhenom() + " " + "Signif: " - + fpcurprevvtecRecord.getcurSignif() + " " + "ETN: " - + fpcurprevvtecRecord.getcurEtn(); - - return textHeaderStringArray; - - } - - // -------------------------------------------------------------------------------------------------- - /* - * private String wrapInHTML(String origString) { StringBuffer buffer = new - * StringBuffer("
" + origString + "
"); - * - * return buffer.toString(); } - */ - // ------------------------------------------------------------ - /* - * private String getVerticalText(String origText) { char[] charArray = - * origText.toCharArray(); StringBuffer buffer = new StringBuffer(); - * - * buffer.append(""); for (int i = 0; i < charArray.length; i++) { - * buffer.append(charArray[i]); - * - * //don't do a break for the last one if (i < charArray.length-1) { - * buffer.append("
"); } } buffer.append(""); - * - * String verticalText = buffer.toString(); - * - * return verticalText; } - * // - * -------------------------------------------------------------------------------------------------- - * - * - * /** @param startTime The startTime to set. - */ - public void setStartTime(long startTime) { - _startTime = startTime; - } - - // -------------------------------------------------------------------------------------------------- - - /** - * @return Returns the startTime. - */ - public long getStartTime() { - return _startTime; - } - - // -------------------------------------------------------------------------------------------------- - - /** - * @param endTime - * The endTime to set. - */ - public void setEndTime(long endTime) { - _endTime = endTime; - } - - /** - * @return Returns the endTime. - */ - public long getEndTime() { - return _endTime; - } - - // -------------------------------------------------------------------------------------------------- - /** - * @return _fpCurPrevVtecRecord - */ - public FpCurPrevVtec getFpCurPrevVtecRecord() { - return _fpCurPrevVtecRecord; - } - - public FpVtecInfoFrame getFrame() { - return _frame; - } - - public void setFrame(FpVtecInfoFrame _frame) { - this._frame = _frame; - } - - public FpVtecInfoDataManager get_dataMgr() { - return _dataMgr; - } - - public void set_dataMgr(FpVtecInfoDataManager mgr) { - _dataMgr = mgr; - } - - public TimeHolder getCurVtecBeginTimeHolder() { - return _curVtecBeginTimeHolder; - } - - public TimeHolder getCurVtecEndTimeHolder() { - return _curVtecEndTimeHolder; - } - - public TimeHolder getCurVtecRiseTimeHolder() { - return _curVtecRiseTimeHolder; - } - - public TimeHolder getCurVtecCrestTimeHolder() { - return _curVtecCrestTimeHolder; - } - - public TimeHolder getCurVtecFallTimeHolder() { - return _curVtecFallTimeHolder; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoDataManager.java b/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoDataManager.java deleted file mode 100644 index c2ca1aa7a1..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoDataManager.java +++ /dev/null @@ -1,532 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.FloodcatRecord; -import ohd.hseb.ihfsdb.generated.FloodcatTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class FpVtecInfoDataManager { - - private static final long MILLIS_PER_SECOND = 1000; - - private Database _db = null; - - private Logger _logger = null; - - private String _jdbcConnectionString = null; - - private String _rpfdataFilePath = null; - - private Map _vtecinfoMap = new HashMap(); - - // --------------------------------------------------------------------------------- - - public FpVtecInfoDataManager(String jdbcConnectionString) { - _logger = new FileLogger(true); - - _jdbcConnectionString = jdbcConnectionString; - - _db = new Database(); - - _db.connect(_jdbcConnectionString); - - getAppsDefaults(); - } - - // --------------------------------------------------------------------------------- - - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - - _rpfdataFilePath = ad.getToken("rpf_template_dir") + "/"; - - return; - } - - // ---------------------------------------------------------------------------------- - - public void readInputFileFormFpCurPrevVtecInfoMap() { - // String header = - // "FpVtecInfoDataManager.readInputFileFormCurPrevVtecInfoMap(): "; - String fpvtecinfoFileName = getFpVtecInfoFileName(); - FpVtecInfoFileReader reader = new FpVtecInfoFileReader( - fpvtecinfoFileName); - - _vtecinfoMap = reader.read(); - - return; - } - - // ------------------------------------------------------------------------ - private String getFpVtecInfoFileName() { - String fpvtecinfoFileName = _rpfdataFilePath + "fpvtecinfo.dat"; - System.out.println("FpVtecInfoDataManager: getFpVtecInfoFileName()" - + fpvtecinfoFileName); - - return fpvtecinfoFileName; - } - - // ------------------------------------------------------------------------------------- - private void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId, - ParamCode paramCode, long startTime, - FpCurPrevVtec fpCurPrevVtecRecord) { - final double missingValue = -9999.0; - String header = "FpVtecInfoDataManager.loadObservedStageTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - AbsTimeMeasurement measurement = null; - ArrayList obsValueTimeList = new ArrayList(); - String obsValueTimeRecord = null; - String[] temp = null; - double obsValue = missingValue; - long obsTime = 0; - - try { - obsValueTimeList = fpCurPrevVtecRecord.getObsValuetTimeList(); - - if (obsValueTimeList != null) { - for (int i = 0; i < obsValueTimeList.size(); i++) { - obsValueTimeRecord = obsValueTimeList.get(i).toString(); - - // don't let the missing values be included - - temp = obsValueTimeRecord.split(","); - obsValue = Double.parseDouble(temp[0]); - obsTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(obsValue, obsTime, - unit); - - stageTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch (Exception e) { - System.err.println(header - + "error loading observed data from obsValueTimeList"); - e.printStackTrace(); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedDischargeTimeSeries( - String locationId, ParamCode paramCode, long startTime, - FpCurPrevVtec fpCurPrevVtecRecord) { - final double missingValue = -9999.0; - - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "FpVtecInfoDataManager.loadObservedDischargeTimeSeries(): "; - - AbsTimeMeasurement measurement = null; - ArrayList obsValueTimeList = new ArrayList(); - String obsValueTimeRecord = null; - String[] temp = null; - double obsValue = missingValue; - long obsTime = 0; - - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - try { - obsValueTimeList = fpCurPrevVtecRecord.getObsValuetTimeList(); - - if (obsValueTimeList != null) { - for (int i = 0; i < obsValueTimeList.size(); i++) { - obsValueTimeRecord = obsValueTimeList.get(i).toString(); - - temp = obsValueTimeRecord.split(","); - obsValue = Double.parseDouble(temp[0]); - obsTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(obsValue, obsTime, - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch (Exception e) { - System.err.println(header - + "error loading observed data from obsValueTimeList"); - e.printStackTrace(); - } - - return dischargeTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - ParamCode paramCode, long endTime, FpCurPrevVtec fpCurPrevVtecRecord) { - long originalBasisTime = 0; - final double missingValue = -9999.0; - - MeasuringUnit unit = MeasuringUnit.feet; - AbsTimeMeasurement measurement = null; - String header = "FpVtecInfoDataManager.loadFcstStageTimeSeries(): "; - ArrayList fcstValueTimeList = new ArrayList(); - String fcstValueTimeRecord = null; - String[] temp = null; - double fcstValue = missingValue; - long fcstTime = 0; - - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - try { - fcstValueTimeList = fpCurPrevVtecRecord.getFcstValueTimeList(); - - if (fcstValueTimeList != null) { - for (int i = 0; i < fcstValueTimeList.size(); i++) { - fcstValueTimeRecord = fcstValueTimeList.get(i).toString(); - - temp = fcstValueTimeRecord.split(","); - fcstValue = Double.parseDouble(temp[0]); - fcstTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(fcstValue, fcstTime, - unit); - - stageTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch (Exception e) { - System.err.println(header - + "error loading forecast data from fcstValueTimeList"); - e.printStackTrace(); - } - - return stageTimeSeries; - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - ParamCode paramCode, long endTime, FpCurPrevVtec fpCurPrevVtecRecord) { - long originalBasisTime = 0; - final double missingValue = -9999.0; - - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "FpVtecInfoDataManager.loadFcstDischargeTimeSeries(): "; - - ArrayList fcstValueTimeList = new ArrayList(); - String fcstValueTimeRecord = null; - String[] temp = null; - double fcstValue = missingValue; - long fcstTime = 0; - AbsTimeMeasurement measurement = null; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - try { - fcstValueTimeList = fpCurPrevVtecRecord.getFcstValueTimeList(); - - if (fcstValueTimeList != null) { - for (int i = 0; i < fcstValueTimeList.size(); i++) { - fcstValueTimeRecord = fcstValueTimeList.get(i).toString(); - - temp = fcstValueTimeRecord.split(","); - fcstValue = Double.parseDouble(temp[0]); - fcstTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(fcstValue, fcstTime, - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch (Exception e) { - System.err.println(header - + "error loading forecast data from fcstValueTimeList"); - e.printStackTrace(); - } - - return dischargeTimeSeries; - } - - // ------------------------------------------------------------------------------------ - public RatingCurve loadRatingCurve(String locationId) { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - try { - ratingRecordList = ratingTable.select("WHERE LID = '" + locationId - + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" - + locationId + "' AND active = 'T' ORDER BY date desc", 1); - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId - + "'"); - - // determine total amount of active - // rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList - .get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - } - - // initialize the RatingCurve object with data from the database, - // including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - // done by addRatingPoint - // ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } // end for - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList - .get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord - .getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } catch (SQLException e) { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - // ------------------------------------------------------------------------------ - - public SigRiverLevels loadSigRiverLevels(String locationId) { - String header = "FpVtecInfoDataManager.loadSigRiverLevels(): "; - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (RiverstatRecord) recordList.get(0); - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - // need to change the common lib SigRiverLevels.java - - if (DbTable.isNull(actionStage)) { - System.out.println(header + " actionStage is null for " - + locationId); - } - if (DbTable.isNull(record.getPrimary_pe())) { - System.out.println(header + " primary_pe is null for " - + locationId); - record.setPrimary_pe("HG"); - } - - levels = new SigRiverLevels(locationId, record.getPrimary_pe(), - floodStage, actionStage, floodFlow, actionFlow); - // load moderate and major floods - - loadFloodCategories(levels); - } - } catch (SQLException e) { - logSQLException(e); - } - - return levels; - } - - // -------------------------------------------------------------------------------------------------- - private void loadFloodCategories(SigRiverLevels levels) { - FloodcatTable table = new FloodcatTable(_db); - FloodcatRecord record = null; - - String whereClause = "WHERE lid = '" + levels.getLocationId() + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (FloodcatRecord) recordList.get(0); - - levels.setMinorFloodFlow(record.getMinor_flow()); - levels.setModerateFloodFlow(record.getModerate_flow()); - levels.setMajorFloodFlow(record.getMajor_flow()); - - levels.setMinorFloodStage(record.getMinor_stage()); - levels.setModerateFloodStage(record.getModerate_stage()); - levels.setMajorFloodStage(record.getMajor_stage()); - } - } catch (SQLException e) { - logSQLException(e); - } - - return; - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSource(String lid, String pe) { - String header = "FpVtecInfoDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + "'" + " AND pe = '" + pe - + "'" + " AND dur = 0 " + " AND ts like 'F%' " - + " order by ts_rank ASC"; - - try { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - if (pe.charAt(0) == 'H') { - for (int i = 0; i < recordList.size(); i++) { - record = (IngestFilterRecord) recordList.get(i); - if (fcstHeightRecordExists(record)) { - newTypeSource = record.getTs(); - break; - } - } - - } else // pe is not 'H*', so don't look at fcstHeight to see if - // it exists - { - newTypeSource = record.getTs(); - } - - } - } catch (SQLException e) { - logSQLException(e); - } - - // System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // -------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------- - public boolean fcstHeightRecordExists(IngestFilterRecord ingestRecord) { - boolean result = false; - - String header = "FpVtecInfoDataManager.fcstHeightRecordExists(): "; - - FcstHeightTable table = new FcstHeightTable(_db); - - String whereClause = "WHERE lid = '" + ingestRecord.getLid() + "'" - + " AND pe = '" + ingestRecord.getPe() + "'" + " AND dur = " - + ingestRecord.getDur() + " AND ts = '" + ingestRecord.getTs() - + "'"; - - try { - int recordCount = table.selectCount(whereClause); - - if (recordCount > 0) { - result = true; - } - } catch (SQLException e) { - logSQLException(e); - } - - return result; - } - - public Map getvtecinfoMap() { - return _vtecinfoMap; - } - - public String get_rpfdataFilePath() { - return _rpfdataFilePath; - } - - public void set_rpfdataFilePath(String filePath) { - _rpfdataFilePath = filePath; - } - - public Database get_db() { - return _db; - } - - public void set_db(Database _db) { - this._db = _db; - } - -} // end FpVtecInfoDataManager diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoFileReader.java b/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoFileReader.java deleted file mode 100755 index 683c7765a7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoFileReader.java +++ /dev/null @@ -1,442 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; - -public class FpVtecInfoFileReader -{ - //private List _fpvtecinfoList; - private String _fullFilePath = null; - private boolean _debug = false; - private BufferedReader _reader = null; - private Map _fpcurprevvtecMap = null; - - // ------------------------------------------------------------------------------ - public FpVtecInfoFileReader() - { - - } - // ---------------------------------------------------------------------------------- - public FpVtecInfoFileReader(String fullFilePath) - { - _fullFilePath = fullFilePath; - _fpcurprevvtecMap = new HashMap(); - } - - // ---------------------------------------------------------------------------------- - public Map read() - { - String header = "FpVtecInfoFileReader.read() "; - - try - { - FileReader fileReader = new FileReader(_fullFilePath); - _reader = new BufferedReader(fileReader); - - readFileHeader(); - - boolean done = false; - - while ( ! done ) - { - try - { - FpCurPrevVtec fpvtecinfo = readFpVtecData(); - if (fpvtecinfo != null) - { - _fpcurprevvtecMap.put(fpvtecinfo.getLocId(), fpvtecinfo); - - } - else - { - System.out.println("fpvtecinfo is null"); - debug_logline(header + "fpvtecinfo is null"); - } - - } - catch (EOFException e) - { - done = true; - } - catch (Exception e) - { - System.err.println(header + - "Exception reading file " + _fullFilePath + - " " + e.getMessage()); - e.printStackTrace(); - - done = true; - } - } //end while - - - if (_reader != null) - { - _reader.close(); - _reader = null; - } - - } //end try - catch (FileNotFoundException e) - { - System.err.println("Unable to open" + _fullFilePath); - - } - catch (IOException e) - { - System.err.println("Unable to open" + _fullFilePath); - } - - return _fpcurprevvtecMap; - } - - // ---------------------------------------------------------------------------------- - private void readFileHeader() throws IOException - { - String header = "FpVtecInfoFileReader.readFileHeader(): "; - String line = null; - - //ignore the first 4 lines in the fpvtecinfo.dat - line = _reader.readLine(); - debug_logline(header + " line 1 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 2 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 3 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 4 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 5 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 6 = " + line); - - } - - // ---------------------------------------------------------------------------------- - - private FpCurPrevVtec readFpVtecData() throws IOException - { - String header = "FpVtecInfoFileReader.readFpVtecData(): "; - StringTokenizer fpLineTokenizer = null; - StringTokenizer curVtecLineTokenizer = null; - StringTokenizer prevVtecLineTokenizer = null; - StringTokenizer observedTSLineTokenizer = null; - StringTokenizer fcstTSLineTokenizer = null; - ArrayList obsValueTimeList = new ArrayList(); - ArrayList fcstValueTimeList = new ArrayList(); - - // The first line includes fp information for specific location - - String stationFpDataLine = _reader.readLine(); - - if (stationFpDataLine == null) - { - throw new EOFException(); - } - else - fpLineTokenizer = new StringTokenizer(stationFpDataLine, ","); - - // The second line includes current VTEC information for specific location - - String stationCurVtecDataLine = _reader.readLine(); - if (stationCurVtecDataLine == null) - { - throw new EOFException(); - } - else - curVtecLineTokenizer = new StringTokenizer(stationCurVtecDataLine, ","); - - - // The third line includes previous VTEC information for specific location - - String stationPrevVtecDataLine = _reader.readLine(); - - if (stationPrevVtecDataLine == null) - { - throw new EOFException(); - } - else if (stationPrevVtecDataLine.equals("MSG")) - { - //no previous event exist - System.out.println("No previous event exist."); - } - else - { - prevVtecLineTokenizer = new StringTokenizer(stationPrevVtecDataLine, ","); - } - - // The fourth line includes observed timesreis data - String stationObservedTSLine = _reader.readLine(); - - if (stationObservedTSLine == null) - { - throw new EOFException(); - } - else if (stationObservedTSLine.equals("MSG")) - { - //no observed TS exists - System.out.println("No Observed TimeSeries data exists."); - } - else - { - observedTSLineTokenizer = new StringTokenizer(stationObservedTSLine, ";"); - } - - // The fifth line includes forecast timesreis data - String stationForecastTSLine = _reader.readLine(); - - if (stationForecastTSLine == null) - { - throw new EOFException(); - } - else if (stationForecastTSLine.equals("MSG")) - { - //no forecast TS exists - System.out.println("No Forecast TimeSeries data exists."); - } - else - { - fcstTSLineTokenizer = new StringTokenizer(stationForecastTSLine, ";"); - } - - FpCurPrevVtec descriptor = new FpCurPrevVtec(); - - // parse out the first line FP information - - String lid = fpLineTokenizer.nextToken(); - descriptor.setLocId(lid.trim()); - - - String name = fpLineTokenizer.nextToken(); - descriptor.setLocName(name.trim()); - - - String stream = fpLineTokenizer.nextToken(); - descriptor.setLocStream(stream.trim()); - - - String pe = fpLineTokenizer.nextToken(); - descriptor.setLocPe(pe.trim()); - - - double fs = Double.parseDouble(fpLineTokenizer.nextToken()); - descriptor.setFloodStg(fs); - - - double fq = Double.parseDouble(fpLineTokenizer.nextToken()); - descriptor.setFloodFlow(fq); - - - long obs_begintime = Long.parseLong(fpLineTokenizer.nextToken()); - descriptor.setObsBeginTime(obs_begintime); - - long fcst_endtime = Long.parseLong(fpLineTokenizer.nextToken()); - descriptor.setFcstEndTime(fcst_endtime); - - double adjustendhrs = Double.parseDouble(fpLineTokenizer.nextToken()); - descriptor.setAdjustEndhrs(adjustendhrs); - - - debug_logline(header + "lid = " + lid + " " + - "name = " + name + " " + - "stream = " + stream); - - - // parse out second line current VTEC information - - String cur_action = curVtecLineTokenizer.nextToken(); - descriptor.setcurAction(cur_action.trim()); - - String cur_phenom = curVtecLineTokenizer.nextToken(); - descriptor.setcurPhenom(cur_phenom.trim()); - - String cur_signif = curVtecLineTokenizer.nextToken(); - descriptor.setcurSignif(cur_signif.trim()); - - String cur_severity = curVtecLineTokenizer.nextToken(); - descriptor.setcurSeverity(cur_severity.trim()); - - String cur_cause = curVtecLineTokenizer.nextToken(); - descriptor.setcurCause(cur_cause.trim()); - - String cur_record = curVtecLineTokenizer.nextToken(); - descriptor.setcurRecord(cur_record.trim()); - - int cur_etn = Integer.parseInt(curVtecLineTokenizer.nextToken()); - descriptor.setcurEtn(cur_etn); - - double cur_crest_value = Double.parseDouble(curVtecLineTokenizer.nextToken()); - descriptor.setcurCrestValue(cur_crest_value); - - long cur_begintime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurBeginTime(cur_begintime); - - long cur_endtime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurEndTime(cur_endtime); - - long cur_risetime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurRiseTime(cur_risetime); - - long cur_cresttime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurCrestTime(cur_cresttime); - - long cur_falltime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurFallTime(cur_falltime); - - debug_logline(header + "cur_action = " + cur_action + " " + - "cur_phenom = " + cur_phenom + " " + - "cur_signif = " + cur_signif + " " + - "cur_severity = " + cur_severity + " " + - "cur_cause = " + cur_cause + " " + - "cur_record = " + cur_record + " " + - "cur_etn = " + cur_etn + " " + - "cur_crest_value = " + cur_crest_value); - - // parse out third line previous VTEC information - - if (prevVtecLineTokenizer != null) - { - String prev_action = prevVtecLineTokenizer.nextToken(); - descriptor.setprevAction(prev_action); - - String prev_phenom = prevVtecLineTokenizer.nextToken(); - descriptor.setprevPhenom(prev_phenom); - - String prev_signif = prevVtecLineTokenizer.nextToken(); - descriptor.setprevSignif(prev_signif); - - String prev_severity = prevVtecLineTokenizer.nextToken(); - descriptor.setprevSeverity(prev_severity); - - String prev_cause = prevVtecLineTokenizer.nextToken(); - descriptor.setprevCause(prev_cause); - - String prev_record = prevVtecLineTokenizer.nextToken(); - descriptor.setprevRecord(prev_record); - - - int prev_etn = Integer.parseInt(prevVtecLineTokenizer.nextToken()); - descriptor.setprevEtn(prev_etn); - - double prev_crest_value = Double.parseDouble(prevVtecLineTokenizer.nextToken()); - descriptor.setprevCrestValue(prev_crest_value); - - String prev_rise_ts = prevVtecLineTokenizer.nextToken(); - descriptor.setprevRiseType(prev_rise_ts); - - String prev_crest_ts = prevVtecLineTokenizer.nextToken(); - descriptor.setprevCrestType(prev_crest_ts); - - String prev_fall_ts = prevVtecLineTokenizer.nextToken(); - descriptor.setprevFallType(prev_fall_ts); - - long prev_begintime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevBeginTime(prev_begintime); - - long prev_endtime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevEndTime(prev_endtime); - - long prev_risetime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevRiseTime(prev_risetime); - - long prev_cresttime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevCrestTime(prev_cresttime); - - long prev_falltime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevFallTime(prev_falltime); - - long prev_producttime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevProductTime(prev_producttime); - - debug_logline(header + "prev_action = " + prev_action + " " + - "prev_phenom = " + prev_phenom + " " + - "prev_signif = " + prev_signif + " " + - "prev_severity = " + prev_severity + " " + - "prev_cause = " + prev_cause + " " + - "prev_record = " + prev_record + " " + - "prev_etn = " + prev_etn + " " + - "prev_crest_value = " + prev_crest_value + " " + - "prev_rise_ts = " + prev_rise_ts + " " + - "prev_crest_ts = " + prev_crest_ts + " " + - "prev_fall_ts = " + prev_fall_ts); - } - - // parse out the observed time series data - - if (observedTSLineTokenizer != null) - { - while (observedTSLineTokenizer.hasMoreTokens()) { - obsValueTimeList.add(observedTSLineTokenizer.nextToken()); - } - - descriptor.setObsValuetTimeList(obsValueTimeList); - } - - // pase out the forecast time series data - - if (fcstTSLineTokenizer != null) - { - while (fcstTSLineTokenizer.hasMoreTokens()) { - fcstValueTimeList.add(fcstTSLineTokenizer.nextToken()); - } - - descriptor.setFcstValueTimeList(fcstValueTimeList); - } - - return descriptor; - } - - //--------------------------------------------------------- - public void setDebug(boolean debug) - { - this._debug = debug; - } - - //--------------------------------------------------------------------------------- - - public boolean getDebug() - { - return _debug; - } - - // ---------------------------------------------------------------------------------- - private void debug_logline(String message) - { - debug_log(message + '\n'); - - return; - } - // ---------------------------------------------------------------------------------- - - private void debug_log(String message) - { - if (getDebug()) - { - System.out.print(message); - } - - return; - } - // ---------------------------------------------------------------------------------- - - public Map getFpCurPrevVtecMap() - { - return _fpcurprevvtecMap; - } - - // --------------------------------------------------------------------------------- -} - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoFrame.java b/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoFrame.java deleted file mode 100644 index c7dc9bdc4a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/FpVtecInfoFrame.java +++ /dev/null @@ -1,2256 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; - -import javax.swing.AbstractButton; -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSeparator; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.border.Border; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.gui.util.ScreenCaptureActionListener; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - - -//------------------------------------------------------------------------------ - -public class FpVtecInfoFrame extends JFrame -{ - //------------------------------------------------------------------------------ - //private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - private static final int MILLIS_PER_SECOND = 1000; - //private static final int HOURS_TO_ROUND = 6; - private static final long MISSING_INT = -9999; - private static final String MISSING_STR = "MSG"; - private Dimension _minSize = new Dimension(250, 250); - private Dimension _maxSize = new Dimension(1000,1000); - - protected static final int STILL_OPENED = 0; - protected static final int CLOSED_BUT_NOT_SAVED = -1; - - private OutputStream _outputStream = null; - //private boolean _fileIsOpen = false; - private PrintWriter _writer = null; - private static long _lastUpdateTime = STILL_OPENED; - private long _currentTime = 0; - - //window sizing variables - - private Dimension _initialSize = new Dimension(1250, 550); - - private JMenuBar _menuBar = null; - private JPanel _mainPanel = null; - private JPanel _tslPanel = null; - private JPanel _curvtecPanel = null; - private JPanel _prevvtecPanel = null; - private JPanel _windowButtonPanel = null; - private JPanel _buttonPanel = null; - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - - // in _curvtecPanel - private JLabel _curvtecPanelLabel = null; - private JLabel _curvtecActionComboBoxLabel = null; - - private String[] _curvtecActionComboBoxString = {"CAN", "CON", "COR", "EXP", "EXT", - "NEW", "ROU"}; - - private JComboBox _curvtecActionComboBox = new JComboBox(_curvtecActionComboBoxString); - private JLabel _curvtecPhenomComboBoxLabel = null; - private String[] _curvtecPhenomComboBoxString = {"FL", "HY"}; - private JComboBox _curvtecPhenomComboBox = new JComboBox(_curvtecPhenomComboBoxString); - private JLabel _curvtecSignifComboBoxLabel = null; - private String[] _curvtecSignifComboBoxString = {"A (wAtch)", "S (Statement)", - "W (Warning)", "Y (advisorY)" }; - private JComboBox _curvtecSignifComboBox = new JComboBox(_curvtecSignifComboBoxString); - private JLabel _curvtecSeverityComboBoxLabel = null; - private String[] _curvtecSeverityComboBoxString = {"0 (N/A)", "1 (Minor)", "2 (Moderate)", - "3 (Major)", "N (None)", "U (Unknown)" }; - private JComboBox _curvtecSeverityComboBox = new JComboBox(_curvtecSeverityComboBoxString); - - private JLabel _curvtecICComboBoxLabel = null; - - private String[] _curvtecICComboBoxString = {"DM (Dam Fail)","DR (Dam Rel)", - "ER (Exc Rain)", "ET (Flow Tidal)", - "FS (Surge)", "FT (Fld/Tide)", - "GO (Glacial)", "IC (Ice Mix)","IJ (Ice Jam)", - "MC (Multiple)", "OT (Other)", - "RS (Rain/Snow)", "SM (Snow Melt)", - "UU (Unknown)","WT (Wind/Tidal)"}; - - private JComboBox _curvtecICComboBox = new JComboBox(_curvtecICComboBoxString); - private JLabel _curvtecRecordComboBoxLabel = null; - private String[] _curvtecRecordComboBoxString = {"NO (NotExp)", "NR (Near)", - "OO (N/A)", "UU (None)"}; - private JComboBox _curvtecRecordComboBox = new JComboBox(_curvtecRecordComboBoxString); - - private JLabel _curvtecBeginTimeLabel = null; - private DateTimeTextField _curvtecBeginTimeTextField = null; - private JRadioButton _curvtecBeginTimeSetMissingRadioButton = null; - private JRadioButton _curvtecBeginTimeSetCurrentRadioButton = null; - private JRadioButton _curvtecBeginTimeRadioButton = null; - - private JLabel _curvtecEndTimeLabel = null; - private DateTimeTextField _curvtecEndTimeTextField = null; - private JRadioButton _curvtecEndTimeSetMissingRadioButton = null; - private JRadioButton _curvtecEndTimeSetCurrentRadioButton = null; - private JRadioButton _curvtecEndTimeRadioButton = null; - - private JLabel _curvtecRiseTimeLabel = null; - private DateTimeTextField _curvtecRiseTimeTextField = null; - private JCheckBox _curvtecRiseTimeSetMissingCheckBox = null; - private JLabel _curvtecCrestTimeLabel = null; - private DateTimeTextField _curvtecCrestTimeTextField = null; - private JCheckBox _curvtecCrestTimeSetMissingCheckBox = null; - private JLabel _curvtecCrestValueLabel = null; - private JTextField _curvtecCrestValueTextField = null; - private String _curCrestValueStr = null; - private JLabel _curvtecFallTimeLabel = null; - private DateTimeTextField _curvtecFallTimeTextField = null; - private JCheckBox _curvtecFallTimeSetMissingCheckBox = null; - // private JButton _curvtecUpdateGraphButton = null; - private JButton _curvtecSaveChangesButton = null; - private JButton _curvtecResetButton = null; - - // in _prevvtecPanel - private JLabel _prevvtecpanelLabel = null; - private JLabel _prevvtecActionLabel = null; - private JTextField _prevvtecActionTextField = null; - private JLabel _prevvtecPhenomLabel = null; - private JTextField _prevvtecPhenomTextField = null; - private JLabel _prevvtecSignifLabel = null; - private JTextField _prevvtecSignifTextField = null; - private JLabel _prevvtecSeverityLabel = null; - private JTextField _prevvtecSeverityTextField = null; - private JLabel _prevvtecICLabel = null; - private JTextField _prevvtecICTextField = null; - private JLabel _prevvtecRecordLabel = null; - private JTextField _prevvtecRecordTextField = null; - private JLabel _prevvtecBeginTimeLabel = null; - private JTextField _prevvtecBeginTimeTextField = null; - private JLabel _prevvtecEndTimeLabel = null; - private JTextField _prevvtecEndTimeTextField = null; - private JLabel _prevvtecRiseTimeLabel = null; - private JTextField _prevvtecRiseTimeTextField = null; - private JLabel _prevvtecRiseTypeLabel = null; - private JTextField _prevvtecRiseTypeTextField = null; - private JLabel _prevvtecCrestTimeLabel = null; - private JTextField _prevvtecCrestTimeTextField = null; - private JLabel _prevvtecCrestValueLabel = null; - private JTextField _prevvtecCrestValueTextField = null; - private JLabel _prevvtecCrestTypeLabel = null; - private JTextField _prevvtecCrestTypeTextField = null; - private JLabel _prevvtecFallTimeLabel = null; - private JTextField _prevvtecFallTimeTextField = null; - private JLabel _prevvtecFallTypeLabel = null; - private JTextField _prevvtecFallTypeTextField = null; - private JLabel _prevvtecProductTimeLabel = null; - private JTextField _prevvtecProductTimeTextField = null; - - // Booleans related to check boxes and radio button - private boolean _forceSetRiseTimeMissing = false; - private boolean _forceSetCrestTimeMissing = false; - private boolean _forceSetFallTimeMissing = false; - private boolean _forceSetBeginTimeMissing = false; - private boolean _forceSetBeginTimeCurrent = false; - private boolean _forceSetBeginTime = false; - private boolean _forceSetEndTimeMissing = false; - private boolean _forceSetEndTimeCurrent = false; - private boolean _forceSetEndTime = false; - - // in _initWindowButtonPanel - private JButton _closeButton = null; - - private FpCurPrevVtec _fpCurPrevVtecData = null; - - // for canvas - private TsPaintableCanvas _canvas = null; - //private ValueMapper _rightAxisValueMapper = null; - - private boolean _exitOnClose = false; - private FpVtecInfoDataManager _dataMgr = null; - - //define object for FpVtecInfo - private FpVtecInfo _application; - - // keep the original proposed VTEC information - private String _selected_curAction = null; - private String _selected_curPhenom = null; - private String _selected_curSignif_str = null; - private String _selected_curSeverity_str = null; - private String _selected_curCause_str = null; - private String _selected_curRecord_str = null; - private String _selected_curCrestValue_str = null; - private long _selected_curBeginTime = 0; - private long _selected_curEndTime = 0; - private long _selected_curRiseTime = 0; - private long _selected_curCrestTime = 0; - private long _selected_curFallTime = 0; - - private boolean _graphicalChange = false; - - //------------------------------------------------------------------------------ - - public FpVtecInfoFrame(FpCurPrevVtec fpCurPrevVtecRecord, - FpVtecInfoDataManager dataMgr) - { - // get the Fp/vtec information from fpcurprevvtecrecord - - _fpCurPrevVtecData = fpCurPrevVtecRecord; - _dataMgr = dataMgr; - - initGui(); - - return; - } - - // --------------------------------------------------------------------------------- - - public void setTimeWindow(long startTime, long endTime) - { - _canvas.setTimeWindow(startTime, endTime); - - return; - } - - //------------------------------------------------------------------------------ - public TsPaintableCanvas getCanvas() - { - - return _canvas; - - } - - //------------------------------------------------------------------------------ - - public void setExitOnClose(boolean exitOnClose) - { - _exitOnClose = exitOnClose; - - return; - } - //------------------------------------------------------------------------------ - - private void initGui() - { - //setAlwaysOnTop(true); - - - // canvas needs to be initialized before the menu bar, - // because of the screen capturer - initCanvas(0, 0, - _initialSize.width, - _initialSize.height); - - String dbName = _dataMgr.get_db().getDatabaseName(); - String windowTitle = "TimeSeries/Valid Time Event Code Information Window on " + dbName; - - this.setTitle(windowTitle); - - initMenuBar(); - - //limit the range of the resizing - // this object can be local because it remains in memory as a listener - //WindowResizingManager manager = new WindowResizingManager(this, _minSize, _maxSize); - - _tslPanel = new JPanel(); - _tslPanel.setBackground(Color.white); - - settslPanelLayout(); - - addtslPanelListeners(); - - // init curvtec info Panel - initCurVtecPanel(); - - // init prevvtec info Panel - initPrevVtecPanel(); - - // create window control button - initWindowButtonPanel(); - - // create the _buttonPanel including _curvtecPanel, _prevvtecPanel and - // _windowButtonPanel - _buttonPanel = new JPanel(); - - GridBagConstraints buttonGbc = new GridBagConstraints(); - buttonGbc.fill = GridBagConstraints.BOTH; - - buttonGbc.insets = new Insets(2,2,2,2); - buttonGbc.anchor = GridBagConstraints.NORTHWEST; - buttonGbc.weightx = 1; - buttonGbc.weighty = 1; - _buttonPanel.setPreferredSize(new Dimension(1200,280)); - - _buttonPanel.setLayout(new GridBagLayout()); - - addComponent(_buttonPanel, _curvtecPanel, buttonGbc, 0, 0, 1, 3, 1, 0); - addComponent(_buttonPanel, _prevvtecPanel, buttonGbc, 1, 0, 1, 3, 3, 0); - addComponent(_buttonPanel, _windowButtonPanel, buttonGbc, 0, 10, 5, 1, 1, 1); - - //create main panel including _tslPanel(canvas) and _buttonPanel - _mainPanel = new JPanel(); - - GridBagLayout layoutMgr = new GridBagLayout(); - - GridBagConstraints mainGbc = new GridBagConstraints(); - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - //set size for the _mainPanel including the _tslPanel and _buttonPanel - _mainPanel.setPreferredSize(new Dimension(1200,920)); - - _mainPanel.setLayout(layoutMgr); - - // add components to the main panel - - //setJMenuBar(_menuBar); - addComponent(_mainPanel, _tslPanel, mainGbc, 0, 0, 3, 9, 1, 1); - addComponent(_mainPanel, _buttonPanel, mainGbc, 0, 10, 3, 3, 1, 0); - - //add the _mainPanel to the Frame and initialize the frame - this.getContentPane().add(_mainPanel); - - // pack the two panels to a prefererred size and layouts - this.pack(); - - return; - } - - //--------------------------------------------------------------------- - private void initCurVtecPanel() - { - String toolTipText = null; - String selected_curSignif = null; - String selected_curSeverity = null; - String selected_curCause = null; - String selected_curRecord = null; - - Dimension panelDimension = new Dimension(500, 250); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - // get _currentTime; - - _currentTime = System.currentTimeMillis(); - - _curvtecPanel = new JPanel(); - _curvtecPanel.setPreferredSize(panelDimension); - - JPanel panel = _curvtecPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - _curvtecPanelLabel = new JLabel("Proposed VTEC Information:"); - - // init Action ComboBoxapplication - _curvtecActionComboBoxLabel = new JLabel("Action:"); - _selected_curAction = _fpCurPrevVtecData.getcurAction(); - _curvtecActionComboBox.setSelectedItem(_selected_curAction); - - // init Phenom ComboBoxapplication - _curvtecPhenomComboBoxLabel = new JLabel("Phenom:"); - _selected_curPhenom = _fpCurPrevVtecData.getcurPhenom(); - _curvtecPhenomComboBox.setSelectedItem(_selected_curPhenom); - - // init Signif ComboBoxapplication - _curvtecSignifComboBoxLabel = new JLabel(" Signif:"); - selected_curSignif = _fpCurPrevVtecData.getcurSignif(); - if (selected_curSignif.equals("A")) - _selected_curSignif_str = "A (wAtch)"; - else if (selected_curSignif.equals("S")) - _selected_curSignif_str = "S (Statement)"; - else if (selected_curSignif.equals("W")) - _selected_curSignif_str = "W (Warning)"; - else if (selected_curSignif.equals("Y")) - _selected_curSignif_str = "Y (advisorY)"; - - _curvtecSignifComboBox.setSelectedItem(_selected_curSignif_str); - - // init Severity ComboBoxapplication - _curvtecSeverityComboBoxLabel = new JLabel("Severity:"); - selected_curSeverity = _fpCurPrevVtecData.getcurSeverity(); - if (selected_curSeverity.equals("0")) - _selected_curSeverity_str = "0 (N/A)"; - else if (selected_curSeverity.equals("1")) - _selected_curSeverity_str = "1 (Minor)"; - else if (selected_curSeverity.equals("2")) - _selected_curSeverity_str = "2 (Moderate)"; - else if (selected_curSeverity.equals("3")) - _selected_curSeverity_str = "3 (Major)"; - else if (selected_curSeverity.equals("N")) - _selected_curSeverity_str = "N (None)"; - else if (selected_curSeverity.equals("U")) - _selected_curSeverity_str = "U (Unknown)"; - - _curvtecSeverityComboBox.setSelectedItem(_selected_curSeverity_str); - - // init Immediate Cause ComboBox - _curvtecICComboBoxLabel = new JLabel("Cause:"); - selected_curCause = _fpCurPrevVtecData.getcurCause(); - - if (selected_curCause.equals("DM")) - _selected_curCause_str = "DM (Dam Fail)"; - if (selected_curCause.equals("DR")) - _selected_curCause_str = "DR (Dam Rel)"; - if (selected_curCause.equals("ER")) - _selected_curCause_str = "ER (Exc Rain)"; - if (selected_curCause.equals("ET")) - _selected_curCause_str = "ET (Flow Tidal)"; - if (selected_curCause.equals("FS")) - _selected_curCause_str = "FS (Surge)"; - if (selected_curCause.equals("FT")) - _selected_curCause_str = "FT (Fld/Tide)"; - if (selected_curCause.equals("GO")) - _selected_curCause_str = "GO (Glacial)"; - if (selected_curCause.equals("IC")) - _selected_curCause_str = "IC (Ice Mix)"; - if (selected_curCause.equals("IJ")) - _selected_curCause_str = "IJ (Ice Jam)"; - if (selected_curCause.equals("MC")) - _selected_curCause_str = "MC (Multiple)"; - if (selected_curCause.equals("OT")) - _selected_curCause_str = "OT (Other)"; - if (selected_curCause.equals("RS")) - _selected_curCause_str = "RS (Rain/Snow)"; - if (selected_curCause.equals("SM")) - _selected_curCause_str = "SM (Snow Melt)"; - if (selected_curCause.equals("UU")) - _selected_curCause_str = "UU (Unknown)"; - if (selected_curCause.equals("WT")) - _selected_curCause_str = "WT (Wind/Tidal)"; - - _curvtecICComboBox.setSelectedItem(_selected_curCause_str); - - // init Record ComboBoxapplication - _curvtecRecordComboBoxLabel = new JLabel(" Record:"); - selected_curRecord = _fpCurPrevVtecData.getcurRecord(); - if (selected_curRecord.equals("NO")) - _selected_curRecord_str = "NO (NotExp)"; - else if (selected_curRecord.equals("NR")) - _selected_curRecord_str = "NR (Near)"; - else if (selected_curRecord.equals("OO")) - _selected_curRecord_str = "OO (N/A)"; - else if (selected_curRecord.equals("UU")) - _selected_curRecord_str = "UU (None)"; - - _curvtecRecordComboBox.setSelectedItem(_selected_curRecord_str); - - // init Current VTEC BeginTime textfield - toolTipText = "Proposed VTEC Event Begin Time. Click on Text Box to edit."; - _curvtecBeginTimeLabel = new JLabel("Begin Time:"); - _curvtecBeginTimeLabel.setToolTipText(toolTipText); - // this constructor to get the date/time in minute. - _curvtecBeginTimeTextField = new DateTimeTextField(getCurVtecBeginTime(), this, - "Begin", 30, true); - _selected_curBeginTime = getCurVtecBeginTime(); - if (_forceSetBeginTimeMissing == true) - { - _curvtecBeginTimeTextField.setText("MSG"); - - } - else if (_forceSetBeginTimeCurrent == true) - { - _curvtecBeginTimeTextField.setText("CURRENT"); - - } - - _curvtecBeginTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - - - // init radio button for set begintime as missing - _curvtecBeginTimeSetMissingRadioButton = new JRadioButton("Set MSG", - _forceSetBeginTimeMissing); - _curvtecBeginTimeSetMissingRadioButton.addActionListener(new SelectBeginTimeMissingRadioButtonListener()); - - // init radio button for set begintime as current - _curvtecBeginTimeSetCurrentRadioButton = new JRadioButton("Set CURRENT", - _forceSetBeginTimeCurrent); - - _curvtecBeginTimeSetCurrentRadioButton.addActionListener(new SelectBeginTimeCurrentRadioButtonListener()); - - // init radio button for set begintime as regular - _curvtecBeginTimeRadioButton = new JRadioButton("Set Date/Time", - _forceSetBeginTime); - _curvtecBeginTimeRadioButton.addActionListener(new SelectBeginTimeRadioButtonListener()); - - // create ButtonGroup - ButtonGroup curvtecBeginTimeButtonGroup = new ButtonGroup(); - curvtecBeginTimeButtonGroup.add(_curvtecBeginTimeSetMissingRadioButton); - curvtecBeginTimeButtonGroup.add(_curvtecBeginTimeSetCurrentRadioButton); - curvtecBeginTimeButtonGroup.add(_curvtecBeginTimeRadioButton); - - // init Current VTEC EndTime textfield - toolTipText = "Proposed VTEC Event End Time. Click on Text Box to edit."; - _curvtecEndTimeLabel = new JLabel("End Time:"); - _curvtecEndTimeLabel.setToolTipText(toolTipText); - _curvtecEndTimeTextField = new DateTimeTextField(getCurVtecEndTime(), this, - "End", 30, true); - _selected_curEndTime = getCurVtecEndTime(); - - if (_forceSetEndTimeMissing == true) - { - _curvtecEndTimeTextField.setText("MSG"); - } - else if (_forceSetEndTimeCurrent == true) - { - _curvtecEndTimeTextField.setText("CURRENT"); - - } - - _curvtecEndTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - - - // init radio button for set end time as missing - _curvtecEndTimeSetMissingRadioButton = new JRadioButton("Set MSG", - _forceSetEndTimeMissing); - _curvtecEndTimeSetMissingRadioButton.addActionListener(new SelectEndTimeMissingRadioButtonListener()); - - // init radio button for set end time as current - _curvtecEndTimeSetCurrentRadioButton = new JRadioButton("Set CURRENT", - _forceSetEndTimeCurrent); - _curvtecEndTimeSetCurrentRadioButton.addActionListener(new SelectEndTimeCurrentRadioButtonListener()); - - // init radio button for set end time as regular - _curvtecEndTimeRadioButton = new JRadioButton("Set Date/Time", - _forceSetEndTime); - - _curvtecEndTimeRadioButton.addActionListener(new SelectEndTimeRadioButtonListener()); - - - // create ButtonGroup - ButtonGroup curvtecEndTimeButtonGroup = new ButtonGroup(); - curvtecEndTimeButtonGroup.add(_curvtecEndTimeSetMissingRadioButton); - curvtecEndTimeButtonGroup.add(_curvtecEndTimeSetCurrentRadioButton); - curvtecEndTimeButtonGroup.add(_curvtecEndTimeRadioButton); - - // init Current VTEC event rise above fs time - toolTipText = "Proposed VTEC Event Rise Above Flood Stage Time. Click on Text Box to edit."; - _curvtecRiseTimeLabel = new JLabel("AbvFld Time:"); - _curvtecRiseTimeLabel.setToolTipText(toolTipText); - _curvtecRiseTimeTextField = new DateTimeTextField(getCurVtecRiseTime(), this, - "AbvFld", - 30, true); - _selected_curRiseTime = getCurVtecRiseTime(); - if (_forceSetRiseTimeMissing == true) - { - _curvtecRiseTimeTextField.setText("MSG"); - } - - _curvtecRiseTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - // init checkbox for set risetime as missing - _curvtecRiseTimeSetMissingCheckBox = new JCheckBox("Set MSG", - _forceSetRiseTimeMissing); - - _curvtecRiseTimeSetMissingCheckBox.addActionListener(new ChangeRiseTimeMissingCheckBoxListener()); - - // init Current VTEC event crest time - toolTipText = "Proposed VTEC Event Crest Time. Click on Text Box to edit."; - _curvtecCrestTimeLabel = new JLabel("Crest Time:"); - _curvtecCrestTimeLabel.setToolTipText(toolTipText); - _curvtecCrestTimeTextField = new DateTimeTextField(getCurVtecCrestTime(), this, - "Crest", - 30, true); - _selected_curCrestTime = getCurVtecCrestTime(); - if (_forceSetCrestTimeMissing == true) - { - _curvtecCrestTimeTextField.setText("MSG"); - } - _curvtecCrestTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - // init checkbox for set cresttime as missing - _curvtecCrestTimeSetMissingCheckBox = new JCheckBox("Set MSG", - _forceSetCrestTimeMissing); - - _curvtecCrestTimeSetMissingCheckBox.addActionListener(new ChangeCrestTimeMissingCheckBoxListener()); - - // init Crest Value textfield - toolTipText = "Proposed VTEC Crest Value. Click on Text Box to edit. Record and Severity" + - " fields may automatically change if crest value is changed"; - _curvtecCrestValueLabel = new JLabel("Crest Value:"); - _curvtecCrestValueLabel.setToolTipText(toolTipText); - _curvtecCrestValueTextField = new JTextField(getCurVtecCrestValue()); - _curCrestValueStr = getCurVtecCrestValue().trim(); - _selected_curCrestValue_str = _curCrestValueStr; - - // init Current VTEC event fall time - toolTipText = "Proposed VTEC Event Fall Below Flood Stage Time. Click on Text Box to edit."; - _curvtecFallTimeLabel = new JLabel("BlwFld Time:"); - _curvtecFallTimeLabel.setToolTipText(toolTipText); - _curvtecFallTimeTextField = new DateTimeTextField(getCurVtecFallTime(), this, - "BlwFld", - 40, true); - _selected_curFallTime = getCurVtecFallTime(); - if (_forceSetFallTimeMissing == true) - { - _curvtecFallTimeTextField.setText("MSG"); - } - _curvtecFallTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - // init checkbox for set falltime as missing - _curvtecFallTimeSetMissingCheckBox = new JCheckBox("Set MSG", - _forceSetFallTimeMissing); - - _curvtecFallTimeSetMissingCheckBox.addActionListener(new ChangeFallTimeMissingCheckBoxListener()); - - //JButton _curvtecSaveChangesButton - _curvtecSaveChangesButton = new JButton("Save Changes"); - _curvtecSaveChangesButton.setEnabled(true); - _curvtecSaveChangesButton.addActionListener( new SaveChangeListener()); - - //JButton _curvtecResetButton - _curvtecResetButton = new JButton("Reset"); - _curvtecResetButton.setEnabled(true); - _curvtecResetButton.addActionListener( new ResetListener()); - - // Separate - JSeparator separator = new JSeparator(JSeparator.HORIZONTAL); - - // add all component to panel - // col, row numCols numRows Wcol wrow - - addComponent(panel, _curvtecPanelLabel, gbc, 0, 0, 2, 1, 1, 0); - addComponent(panel, _curvtecActionComboBoxLabel, gbc, 0, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecActionComboBox, gbc, 1, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecPhenomComboBoxLabel, gbc, 2, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecPhenomComboBox, gbc, 3, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecSignifComboBoxLabel, gbc, 4, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecSignifComboBox, gbc, 5, 1, 1, 1, 1, 0); - - - addComponent(panel, _curvtecSeverityComboBoxLabel,gbc, 0, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecSeverityComboBox, gbc, 1, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecICComboBoxLabel, gbc, 2, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecICComboBox, gbc, 3, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecRecordComboBoxLabel, gbc, 4, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecRecordComboBox, gbc, 5, 2, 1, 1, 1, 0); - - addComponent(panel, _curvtecBeginTimeLabel, gbc, 0, 3, 1, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeTextField, gbc, 1, 3, 2, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeSetMissingRadioButton,gbc,3,3,1, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeSetCurrentRadioButton,gbc,4,3,1, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeRadioButton, gbc, 5, 3, 1, 1, 1, 0); - - addComponent(panel, _curvtecEndTimeLabel, gbc, 0, 4, 1, 1, 1, 0); - addComponent(panel, _curvtecEndTimeTextField, gbc, 1, 4, 2, 1, 1, 0); - addComponent(panel, _curvtecEndTimeSetMissingRadioButton,gbc,3,4, 1, 1, 1, 0); - addComponent(panel, _curvtecEndTimeSetCurrentRadioButton,gbc,4,4, 1, 1, 1, 0); - addComponent(panel, _curvtecEndTimeRadioButton, gbc, 5, 4, 1, 1, 1, 0); - - addComponent(panel, _curvtecRiseTimeLabel, gbc, 0, 5, 1, 1, 1, 0); - addComponent(panel, _curvtecRiseTimeTextField, gbc, 1, 5, 2, 1, 1, 0); - addComponent(panel, _curvtecRiseTimeSetMissingCheckBox, gbc, 3, 5, 1, 1, 1, 0); - - addComponent(panel, _curvtecCrestTimeLabel, gbc, 0, 6, 1, 1, 1, 0); - addComponent(panel, _curvtecCrestTimeTextField, gbc, 1, 6, 2, 1, 1, 0); - addComponent(panel, _curvtecCrestTimeSetMissingCheckBox, gbc, 3, 6,1, 1, 1, 0); - - addComponent(panel, _curvtecCrestValueLabel, gbc, 4, 6, 1, 1, 1, 0); - addComponent(panel, _curvtecCrestValueTextField, gbc, 5, 6, 1, 1, 1, 0); - - addComponent(panel, _curvtecFallTimeLabel, gbc, 0, 7, 1, 1, 1, 0); - addComponent(panel, _curvtecFallTimeTextField, gbc, 1, 7, 2, 1, 1, 0); - addComponent(panel, _curvtecFallTimeSetMissingCheckBox, gbc, 3, 7, 1, 1, 1, 0); - addComponent(panel, separator, gbc, 0, 8, 6, 1, 1, 0); - //addComponent(panel, _curvtecUpdateGraphButton, gbc, 0, 9, 2, 1, 1, 0); - addComponent(panel, _curvtecResetButton, gbc, 1, 9, 2, 1, 1, 0); - addComponent(panel, _curvtecSaveChangesButton, gbc, 3, 9, 2, 1, 1, 0); - - return; - - } - - //--------------------------------------------------------------------- - private void initPrevVtecPanel() - { - Dimension panelDimension = new Dimension(550, 250); - - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(4, 4, 4, 4); - gbc.weightx = 1; - gbc.weighty = 1; - - _prevvtecPanel = new JPanel(); - _prevvtecPanel.setPreferredSize(panelDimension); - - JPanel panel = _prevvtecPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - // Just display previous event's VTEC info, not allow customize - _prevvtecpanelLabel = new JLabel("Previous VTEC Information:"); - - _prevvtecActionLabel = new JLabel("Action:"); - _prevvtecActionTextField = new JTextField(getPrevVtecAction()); - _prevvtecActionTextField.setEditable(false); - - _prevvtecICLabel = new JLabel("Cause:"); - _prevvtecICTextField = new JTextField(getPrevVtecIC()); - _prevvtecICTextField.setEditable(false); - - _prevvtecRecordLabel = new JLabel("Record:"); - _prevvtecRecordTextField = new JTextField(getPrevVtecRecord()); - _prevvtecRecordTextField.setEditable(false); - - _prevvtecPhenomLabel = new JLabel("Phenom:"); - _prevvtecPhenomTextField = new JTextField(getPrevVtecPhenom()); - _prevvtecPhenomTextField.setEditable(false); - - _prevvtecSignifLabel = new JLabel("Signif:"); - _prevvtecSignifTextField = new JTextField(getPrevVtecSignif()); - _prevvtecSignifTextField.setEditable(false); - - _prevvtecSeverityLabel = new JLabel("Severity:"); - _prevvtecSeverityTextField = new JTextField(getPrevVtecSeverity()); - _prevvtecSeverityTextField.setEditable(false); - - // init previous VTEC BeginTime textfield - _prevvtecBeginTimeLabel = new JLabel("Begin Time:"); - _prevvtecBeginTimeTextField = new JTextField(getPrevVtecBeginTime()); - _prevvtecBeginTimeTextField.setEditable(false); - - // init previous VTEC EndTime textfield - _prevvtecEndTimeLabel = new JLabel("End Time:"); - _prevvtecEndTimeTextField = new JTextField(getPrevVtecEndTime()); - _prevvtecEndTimeTextField.setEditable(false); - - // init pervious VTEC event rise above fs time - _prevvtecRiseTimeLabel = new JLabel("AbvFld Time:"); - _prevvtecRiseTimeTextField = new JTextField(getPrevVtecRiseTime()); - _prevvtecRiseTimeTextField.setEditable(false); - - // init previous VTEC event rise type - _prevvtecRiseTypeLabel = new JLabel("AbvFld Type:"); - _prevvtecRiseTypeTextField = new JTextField(getPrevVtecRiseType()); - _prevvtecRiseTypeTextField.setEditable(false); - - // init previous VTEC event crest time - _prevvtecCrestTimeLabel = new JLabel("Crest Time:"); - _prevvtecCrestTimeTextField = new JTextField(getPrevVtecCrestTime()); - _prevvtecCrestTimeTextField.setEditable(false); - - // init previous VTEC event crest value - _prevvtecCrestValueLabel = new JLabel("Crest Value:"); - _prevvtecCrestValueTextField = new JTextField(getPrevVtecCrestValue()); - _prevvtecCrestValueTextField.setEditable(false); - - // init previous VTEC event crest type - _prevvtecCrestTypeLabel = new JLabel("Crest Type:"); - _prevvtecCrestTypeTextField = new JTextField(getPrevVtecCrestType()); - _prevvtecCrestTypeTextField.setEditable(false); - - // init previous VTEC event fall time - _prevvtecFallTimeLabel = new JLabel("BlwFld Time:"); - _prevvtecFallTimeTextField = new JTextField(getPrevVtecFallTime()); - _prevvtecFallTimeTextField.setEditable(false); - - // init previous VTEC event fall type - _prevvtecFallTypeLabel = new JLabel("BlwFld Type:"); - _prevvtecFallTypeTextField = new JTextField(getPrevVtecFallType()); - _prevvtecFallTypeTextField.setEditable(false); - - //init previous VTEC event product time - _prevvtecProductTimeLabel = new JLabel("Product Time:"); - _prevvtecProductTimeTextField = new JTextField(getPrevVtecProductTime()); - _prevvtecProductTimeTextField.setEditable(false); - - - // add components into panel - // col, row numCols numRows Wcol wrow - addComponent(panel, _prevvtecpanelLabel, gbc, 0, 0, 2, 1, 1, 0); - addComponent(panel, _prevvtecActionLabel, gbc, 0, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecActionTextField, gbc, 1, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecPhenomLabel, gbc, 2, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecPhenomTextField, gbc, 3, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecSignifLabel, gbc, 4, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecSignifTextField, gbc, 5, 1, 1, 1, 1, 0); - - addComponent(panel, _prevvtecSeverityLabel, gbc, 0, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecSeverityTextField, gbc, 1, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecICLabel, gbc, 2, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecICTextField, gbc, 3, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecRecordLabel, gbc, 4, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecRecordTextField, gbc, 5, 2, 1, 1, 1, 0); - - - addComponent(panel, _prevvtecBeginTimeLabel, gbc, 0, 3, 1, 1, 1, 0); - addComponent(panel, _prevvtecBeginTimeTextField, gbc, 1, 3, 3, 1, 1, 0); - addComponent(panel, _prevvtecEndTimeLabel, gbc, 0, 4, 1, 1, 1, 0); - addComponent(panel, _prevvtecEndTimeTextField, gbc, 1, 4, 3, 1, 1, 0); - addComponent(panel, _prevvtecRiseTimeLabel, gbc, 0, 5, 1, 1, 1, 0); - addComponent(panel, _prevvtecRiseTimeTextField, gbc, 1, 5, 3, 1, 1, 0); - addComponent(panel, _prevvtecRiseTypeLabel, gbc, 4, 5, 1, 1, 1, 0); - addComponent(panel, _prevvtecRiseTypeTextField, gbc, 5, 5, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestTimeLabel, gbc, 0, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestTimeTextField, gbc, 1, 6, 3, 1, 1, 0); - addComponent(panel, _prevvtecCrestTypeLabel, gbc, 4, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestTypeTextField,gbc, 5, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestValueLabel, gbc, 6, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestValueTextField, gbc, 7, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecFallTimeLabel, gbc, 0, 7, 1, 1, 1, 0); - addComponent(panel, _prevvtecFallTimeTextField, gbc, 1, 7, 3, 1, 1, 0); - addComponent(panel, _prevvtecFallTypeLabel, gbc, 4, 7, 1, 1, 1, 0); - addComponent(panel, _prevvtecFallTypeTextField, gbc, 5, 7, 1, 1, 1, 0); - addComponent(panel, _prevvtecProductTimeLabel, gbc, 0, 8, 1, 1, 1, 0); - addComponent(panel, _prevvtecProductTimeTextField,gbc, 1, 8, 3, 1, 1, 0); - - return; - - } - - //--------------------------------------------------------------------- - private void initWindowButtonPanel() - { - Dimension panelDimension = new Dimension(980, 100); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - _windowButtonPanel = new JPanel(); - _windowButtonPanel.setPreferredSize(panelDimension); - - JPanel panel = _windowButtonPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - _closeButton = new JButton("Close"); - _closeButton.addActionListener(new CloseListener()); - - // add components into panel - // col, row numCols numRows Wcol wrow - addComponent(panel, _closeButton, gbc, 0, 0, 0, 0, 0, 0); - - return; - - } - //----------------------------------------------------------------- - private void settslPanelLayout() - { - _tslPanel.setLayout(new GridBagLayout()); - GridBagConstraints mainPanelGbc = new GridBagConstraints(); - mainPanelGbc.fill = GridBagConstraints.BOTH; - - if (_canvas == null) - { - System.out.println("Canvas is null"); - } - - // add components into panel - // col, row numCols numRows Wcol wrow - addComponent(_tslPanel, _canvas, mainPanelGbc, 0, 0, 1, 1, 1, 1); - - return; - } - - //----------------------------------------------------------------- - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - //----------------------------------------------------------------- - - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - // for screencapture button - ScreenCaptureActionListener screenCaptureActionListener = - new ScreenCaptureActionListener(this, FpVtecInfoFrame.this); - - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new CloseListener()); - menu.add(menuItem); - - - // create a button directly on the menuBar - - Color menuBarColor = _menuBar.getBackground(); - Border invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - JButton saveButton = new JButton(" Save Screen "); - saveButton.addActionListener(screenCaptureActionListener); - saveButton.setBorder(invisibleBorder); - saveButton.setSize(60, 30); - String saveButtonTooltipText = "Capture the screen to a file."; - saveButton.setToolTipText(saveButtonTooltipText); - _menuBar.add(saveButton); - - - HelpActionListener helpActionListener = new HelpActionListener(); - JButton helpButton = new JButton("Help"); - helpButton.addActionListener(helpActionListener); - helpButton.setBorder(invisibleBorder); - helpButton.setSize(60, 30); - _menuBar.add(helpButton); - - - //add to the Frame - setJMenuBar(_menuBar); - - return; - } - - //----------------------------------------------------------------- - - private void addtslPanelListeners() - { - - //allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - } - //-----------------------------------------------------------------\ - - private void close() - { - if (_exitOnClose) - { - FpVtecInfoFrame.this.setVisible(false); - - dispose(); - - //System.exit(0); comment out, just close the SeriesTime/VTEC window, not - // main application - } - } - - private void closeWithoutSaving() - { - - _lastUpdateTime = CLOSED_BUT_NOT_SAVED; - - if (_exitOnClose) - { - FpVtecInfoFrame.this.setVisible(false); - dispose(); - - //System.exit(0); comment out, just close the SeriesTime/VTEC window, not - // main application - } - } - - //----------------------------------------------------------------- - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - closeWithoutSaving(); - } - } - - //----------------------------------------------------------------- - - - private class FrameCloseWindowListener extends WindowAdapter - { - public void windowClosing(WindowEvent evt) - { - closeWithoutSaving(); - } - - } - - public void showMessage() - { - long obsCutOffTime = _application.getStartTime(); - long fcstCutOffTime = _application.getEndTime(); - String obsCutOffTimeString = ""; - String fcstCutOffTimeString = ""; - - if (obsCutOffTime > 0 && fcstCutOffTime > 0) - { - obsCutOffTimeString = DbTimeHelper.getDateTimeStringFromLongTime(obsCutOffTime); - fcstCutOffTimeString = DbTimeHelper.getDateTimeStringFromLongTime(fcstCutOffTime); - } - - String message = "The YELLOW time series is observed data.\n" + - "The GREEN time series is forecast data. \n" + - "The vertical WHITE line with 'N' is current time.\n" + - "The vertical BLUE line with 'B' is proposed vtec event's begin time.\n" + - "The vertical GREEN line with 'E' is proposed vtec event's end time. \n" + - "The vertical ORANGE line with 'R' is proposed vtec event's rise above flood level time.\n" + - "The vertical RED line with 'C' is proposed vtec event's crest time.\n" + - "The vertical MEGENTA line with 'F' is proposed vtec event's fall below flood level time.\n" + - "The horizontal YELLOW line is action level.\n" + - "The horizontal ORANGE line is flood level.\n" + - "The horizontal RED line is moderate flood level. \n" + - "The horizontal MEGENTA line is major flood level. \n" + - "The timeseries window starts from " + obsCutOffTimeString + "Z to " + - fcstCutOffTimeString + "Z"; - - DialogHelper.displayMessageDialog(this, message, "TimeSeries/VTEC Help"); - } - // ------------------------------------------------------------------------------------ - - private class HelpActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - showMessage(); - } - - } - - // ------------------------------------------------------------------------------------- - // action for the button "Update " - /*private class UpdateGraphListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - updateGraph(); - return; - } - } */ - // ------------------------------------------------------------------------------------ - public void updateGraph() - { - // get the time from time text fields, set them to - //_fpCurPrevVtecData, and TimeHolder - - long currentTime = System.currentTimeMillis(); - - // for the begintime - if (_curvtecBeginTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurBeginTime(MISSING_INT); - _application.getCurVtecBeginTimeHolder().setTime(MISSING_INT); - } - else if (_curvtecBeginTimeTextField.getText().equals("CURRENT")) - { - _fpCurPrevVtecData.setcurBeginTime(-1); - _application.getCurVtecBeginTimeHolder().setTime(currentTime); - } - else - { - _fpCurPrevVtecData.setcurBeginTime(_curvtecBeginTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecBeginTimeHolder().setTime(_curvtecBeginTimeTextField.getTime()); - } - - - // for the end time - if (_curvtecEndTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurEndTime(MISSING_INT); - _application.getCurVtecEndTimeHolder().setTime(MISSING_INT); - } - else if (_curvtecEndTimeTextField.getText().equals("CURRENT")) - { - _fpCurPrevVtecData.setcurEndTime(-1); - _application.getCurVtecEndTimeHolder().setTime(currentTime); - } - else - { - _fpCurPrevVtecData.setcurEndTime(_curvtecEndTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecEndTimeHolder().setTime(_curvtecEndTimeTextField.getTime()); - } - - // for the rise time - if (_curvtecRiseTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurRiseTime(MISSING_INT); - _application.getCurVtecRiseTimeHolder().setTime(MISSING_INT); - } - else - { - _fpCurPrevVtecData.setcurRiseTime(_curvtecRiseTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecRiseTimeHolder().setTime(_curvtecRiseTimeTextField.getTime()); - } - - // for the crest time - if (_curvtecCrestTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurCrestTime(MISSING_INT); - _application.getCurVtecCrestTimeHolder().setTime(MISSING_INT); - } - else - { - _fpCurPrevVtecData.setcurCrestTime(_curvtecCrestTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecCrestTimeHolder().setTime(_curvtecCrestTimeTextField.getTime()); - } - - // for the fall time - if (_curvtecFallTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurFallTime(MISSING_INT); - _application.getCurVtecFallTimeHolder().setTime(MISSING_INT); - } - else - { - _fpCurPrevVtecData.setcurFallTime(_curvtecFallTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecFallTimeHolder().setTime(_curvtecFallTimeTextField.getTime()); - } - - // repaint the canvas - _application.redrawCanvas(); - - } - - - // ----------------------------------------------------------------------- - public void updateCurDateTimeTextField() - { - long new_curVTECBeginTime = 0; - long new_curVTECEndTime = 0; - long new_curVTECRiseTime = 0; - long new_curVTECCrestTime = 0; - long new_curVTECFallTime = 0; - - _graphicalChange = true; - - new_curVTECBeginTime = (_application.getCurVtecBeginTimeHolder()).getTime(); - _curvtecBeginTimeTextField.setTime(new_curVTECBeginTime); - - - new_curVTECEndTime = (_application.getCurVtecEndTimeHolder()).getTime(); - _curvtecEndTimeTextField.setTime(new_curVTECEndTime); - - - new_curVTECRiseTime = (_application.getCurVtecRiseTimeHolder()).getTime(); - _curvtecRiseTimeTextField.setTime(new_curVTECRiseTime); - - new_curVTECCrestTime = (_application.getCurVtecCrestTimeHolder()).getTime(); - _curvtecCrestTimeTextField.setTime(new_curVTECCrestTime); - - new_curVTECFallTime = (_application.getCurVtecFallTimeHolder()).getTime(); - _curvtecFallTimeTextField.setTime(new_curVTECFallTime); - - _graphicalChange = false; - } - - public void resetCurVtecPanel() - { - _curvtecActionComboBox.setSelectedItem(_selected_curAction); - _curvtecPhenomComboBox.setSelectedItem(_selected_curPhenom); - _curvtecSignifComboBox.setSelectedItem(_selected_curSignif_str); - _curvtecSeverityComboBox.setSelectedItem(_selected_curSeverity_str); - _curvtecICComboBox.setSelectedItem(_selected_curCause_str); - _curvtecRecordComboBox.setSelectedItem(_selected_curRecord_str); - - // reset to original event begin time - - if (_selected_curBeginTime == MISSING_INT) - { - _curvtecBeginTimeSetMissingRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setText("MSG"); - } - else if (_selected_curBeginTime == -1) - { - _curvtecBeginTimeSetCurrentRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setText("CURRENT"); - } - else - { - _curvtecBeginTimeRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setTime(_selected_curBeginTime); - } - - // reset to original event end time - - if (_selected_curEndTime == MISSING_INT) - { - _curvtecEndTimeSetMissingRadioButton.setSelected(true); - _curvtecEndTimeTextField.setText("MSG"); - } - else if (_selected_curEndTime == -1) - { - _curvtecEndTimeSetCurrentRadioButton.setSelected(true); - _curvtecEndTimeTextField.setText("CURRENT"); - } - else - { - _curvtecEndTimeRadioButton.setSelected(true); - _curvtecEndTimeTextField.setTime(_selected_curEndTime); - } - - // reset to original event rise above flood level time - - if (_selected_curRiseTime == MISSING_INT) - { - _curvtecRiseTimeSetMissingCheckBox.setSelected(true); - _curvtecRiseTimeTextField.setText("MSG"); - } - else - { - _curvtecRiseTimeSetMissingCheckBox.setSelected(false); - _curvtecRiseTimeTextField.setTime(_selected_curRiseTime); - } - - // reset to original event crest above flood level time - - if (_selected_curCrestTime == MISSING_INT) - { - _curvtecCrestTimeSetMissingCheckBox.setSelected(true); - _curvtecCrestTimeTextField.setText("MSG"); - } - else - { - _curvtecCrestTimeSetMissingCheckBox.setSelected(false); - _curvtecCrestTimeTextField.setTime(_selected_curCrestTime); - } - - // reset to original event fall below flood level time - - if (_selected_curFallTime == MISSING_INT) - { - _curvtecFallTimeSetMissingCheckBox.setSelected(true); - _curvtecFallTimeTextField.setText("MSG"); - } - else - { - _curvtecFallTimeSetMissingCheckBox.setSelected(false); - _curvtecFallTimeTextField.setTime(_selected_curFallTime); - } - // reset to original crest value - _curvtecCrestValueTextField.setText(_selected_curCrestValue_str); - - - updateGraph(); - - } - // ---------------------------------------------------------------------------------------- - private class ResetListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - FpVtecInfoFrame.this.resetCurVtecPanel(); - } - } - // ----------------------------------------------------------------------------------------- - private class SaveChangeListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String header = "SaveChangeListener.actionPerformed():"; - Double curCrestValue = -9999.0; - Boolean curCrestValueEdit = false; - StringBuffer outputStringBuffer = new StringBuffer(); - - if ( DialogHelper.displayConfirmDialog( FpVtecInfoFrame.this, "Are you sure you want to save the edits (will update the VTEC Settings window), " + - "and close the TimeSeries/VTEC window?", "Save Changes and Close" ) ) - { - // update file curvteceditfile.dat - String outputfilePath = FpVtecInfoFrame.this.get_dataMgr().get_rpfdataFilePath(); - - String fpvtecinfoOutputFileName = outputfilePath + "curvteceditsaved.dat" ; - - openOutputFile( fpvtecinfoOutputFileName); - - long curTime = System.currentTimeMillis(); - outputStringBuffer.append( "The output file with edits for proposed VTEC information is created on:" - + DbTimeHelper.getDateTimeStringFromLongTime(curTime) + "\n" ); - outputStringBuffer.append("###lid,locname,action,phenom,signif,severity,cause,record,etn,crest_value," + - "begintime,endtime,risetime,cresttime,falltime###" + "\n"); - - String lid = _fpCurPrevVtecData.getLocId(); - String locName = _fpCurPrevVtecData.getLocName(); - String curAction = (String) _curvtecActionComboBox.getSelectedItem(); - - String curPhenom = (String) _curvtecPhenomComboBox.getSelectedItem(); - - String curSignif = (String) _curvtecSignifComboBox.getSelectedItem(); - String sub_curSignif = curSignif.substring(0, 1); - - String curSeverity = (String) _curvtecSeverityComboBox.getSelectedItem(); - String sub_curSeverity = curSeverity.substring(0, 1); - - - String curCause = (String)_curvtecICComboBox.getSelectedItem(); - String sub_curCause = curCause.substring(0, 2); - - String curRecord = (String)_curvtecRecordComboBox.getSelectedItem(); - String sub_curRecord = curRecord.substring(0, 2); - - int curEtn = _fpCurPrevVtecData.getcurEtn(); - String curCrestString = _curvtecCrestValueTextField.getText().trim(); - - if (curCrestString.equals(_curCrestValueStr)) - curCrestValueEdit = false; - else - curCrestValueEdit = true; - - _curCrestValueStr = curCrestString; - - if (curCrestString == null || curCrestString.equals("")) - { - DialogHelper.displayErrorDialog( FpVtecInfoFrame.this, "No crest value entered", "Unable to save" ); - } - else - curCrestValue = Double.valueOf(curCrestString); - - String curBeginTime = _curvtecBeginTimeTextField.getText().trim(); - String curEndTime = _curvtecEndTimeTextField.getText().trim(); - String curRiseTime = _curvtecRiseTimeTextField.getText().trim(); - String curCrestTime = _curvtecCrestTimeTextField.getText().trim(); - String curFallTime = _curvtecFallTimeTextField.getText().trim(); - - /*String curBeginTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecBeginTimeHolder().getTime()).trim(); - String curEndTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecEndTimeHolder().getTime()).trim(); - String curRiseTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecRiseTimeHolder().getTime()).trim(); - String curCrestTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecCrestTimeHolder().getTime()).trim(); - String curFallTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecFallTimeHolder().getTime()).trim(); - */ - - - if (curBeginTime == null || curEndTime == null || curRiseTime == null - || curCrestTime == null || curFallTime == null) - { - DialogHelper.displayErrorDialog( FpVtecInfoFrame.this, "No time entered", "Unable to save" ); - } - - - outputStringBuffer.append(lid + "," + locName + "," + curAction + "," + - curPhenom + "," + sub_curSignif + "," + sub_curSeverity + - "," + sub_curCause + "," + sub_curRecord + "," + curEtn + - "," + curCrestValue + "," + curCrestValueEdit + "," + curBeginTime + "," + - curEndTime +"," + curRiseTime +"," + curCrestTime + - "," + curFallTime); - - _writer.println( outputStringBuffer); - _writer.flush(); - - // update the outputfile timestamp - setLastUpdateTimeToCurrentTime(); - System.out.println(header + "_lastUpdateTime = " + FpVtecInfoFrame.getLastUpdateTime()); - - // close the current TimeSeries/VTEC window - - close(); - - } - - } - } -// ---------------------------------------------------------------- - private static void setLastUpdateTimeToCurrentTime() - { - //return the time in seconds, so divide by 1000 - _lastUpdateTime = System.currentTimeMillis()/1000; - - return; - } - - protected static void setLastUpdateTime(long lastUpdateTimeInSeconds) - { - //return the time in seconds, so divide by 1000 - _lastUpdateTime = lastUpdateTimeInSeconds; - - return; - } - // --------------------------------------------------------------- - public static long getLastUpdateTime() - { - return _lastUpdateTime; - } - -// ------------------------------------------------------------------------ - - private void openOutputFile(String fileName) - { - try - { - if (fileName != null) - { - _outputStream = new BufferedOutputStream( new FileOutputStream(fileName, false) ); - - // _fileIsOpen = true; - } - else //fileName == null - { - _outputStream = System.out; - } - - _writer = new PrintWriter( _outputStream ); - } - catch (java.io.IOException e) - { - System.out.println( e ); - - } - } - - // ------------------------------------------------------------------------------------ - private void initCanvas(int x, int y, - int width, int height) - - { - MeasuringUnit measuringUnit = MeasuringUnit.feet; - - _canvas = new TsPaintableCanvas( - measuringUnit, - x, y, - width, height); - - _canvas.setPreferredSize(_initialSize); - // _canvas.setMinimumSize(_minSize); - - return; - - } //end initCanvas - - - // --------------------------------------------------------------------------------- - /* - * get the current event's begin time for the specified locationId - */ - private long getCurVtecBeginTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurBeginTime() == MISSING_INT) - { - _forceSetBeginTimeMissing = true; - time = MISSING_INT; - } - else if (_fpCurPrevVtecData.getcurBeginTime() == -1) - { - _forceSetBeginTimeCurrent = true; - time = -1; - } - else - { - _forceSetBeginTime = true; - - time = _fpCurPrevVtecData.getcurBeginTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecBeginTime():" + "begintime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's end time for the specified locationId - */ - private long getCurVtecEndTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurEndTime() == MISSING_INT) - { - _forceSetEndTimeMissing = true; - time = MISSING_INT; - } - else if (_fpCurPrevVtecData.getcurEndTime() == -1) - { - _forceSetEndTimeCurrent = true; - time = -1; - } - else - { - _forceSetEndTime = true; - time = _fpCurPrevVtecData.getcurEndTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecEndTime():" + "endtime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's rise above flood stage time for the specified locationId - */ - private long getCurVtecRiseTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurRiseTime() == MISSING_INT) - { - _forceSetRiseTimeMissing = true; - time = MISSING_INT; - } - else - { - _forceSetRiseTimeMissing = false; - time = _fpCurPrevVtecData.getcurRiseTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecRiseTime():" + "risetime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's crest time for the specified locationId - */ - private long getCurVtecCrestTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurCrestTime() == MISSING_INT) - { - _forceSetCrestTimeMissing = true; - time = MISSING_INT; - } - else - { - _forceSetCrestTimeMissing = false; - time = _fpCurPrevVtecData.getcurCrestTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecCrestTime():" + "cresttime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's crest value for the specified locationId - */ - private String getCurVtecCrestValue() - { - double value = -9999.0; - String valuestring = null; - - try - { - value = _fpCurPrevVtecData.getcurCrestValue(); - valuestring = Double.toString(value); - - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecCrestValue():" + "crest value =" + value); - } - return valuestring; - } - // --------------------------------------------------------------------------------- - /* - * get the current event's fall below of flood stage time for the specified locationId - */ - private long getCurVtecFallTime() - { - long time = -2; - - try - { - if ( _fpCurPrevVtecData.getcurFallTime() == MISSING_INT) - { - _forceSetFallTimeMissing = true; - time = MISSING_INT; - } - else - { - _forceSetFallTimeMissing = false; - time = _fpCurPrevVtecData.getcurFallTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecFallTime():" + "falltime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's action code for the specified locationId - */ - private String getPrevVtecAction() - { - String prevVtecAction = ""; - - try - { - prevVtecAction = _fpCurPrevVtecData.getprevAction(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecAction():" + "Action =" + prevVtecAction); - } - return prevVtecAction; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's Record for the specified locationId - */ - private String getPrevVtecRecord() - { - String prevVtecRecord = ""; - - try - { - prevVtecRecord = _fpCurPrevVtecData.getprevRecord(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecRecord():" + "Record =" + prevVtecRecord); - } - return prevVtecRecord; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's rise type for the specified locationId - */ - private String getPrevVtecRiseType() - { - String prevVtecRiseType = ""; - - try - { - prevVtecRiseType = _fpCurPrevVtecData.getprevRiseType(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecRiseType():" + "Rise Type =" + prevVtecRiseType); - } - return prevVtecRiseType; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's crest type for the specified locationId - */ - private String getPrevVtecCrestType() - { - String prevVtecCrestType = ""; - - try - { - prevVtecCrestType = _fpCurPrevVtecData.getprevCrestType(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecCrestType():" + "Crest Type =" + prevVtecCrestType); - } - return prevVtecCrestType; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's fall type for the specified locationId - */ - private String getPrevVtecFallType() - { - String prevVtecFallType = ""; - - try - { - prevVtecFallType = _fpCurPrevVtecData.getprevFallType(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecFallType():" + "Fall Type =" + prevVtecFallType); - } - return prevVtecFallType; - } - // --------------------------------------------------------------------------------- - /* - * get the previous event's action code for the specified locationId - */ - private String getPrevVtecIC() - { - String prevVtecIC = ""; - - - try - { - prevVtecIC = _fpCurPrevVtecData.getprevCause(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecIC():" + "Immediate Cause =" + prevVtecIC); - } - return prevVtecIC; - } - -// --------------------------------------------------------------------------------- - /* - * get the previous event's phenom code for the specified locationId - */ - private String getPrevVtecPhenom() - { - String prevVtecPhenom = ""; - - try - { - prevVtecPhenom = _fpCurPrevVtecData.getprevPhenom(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecPhenom():" + "Phenom =" + prevVtecPhenom); - } - return prevVtecPhenom; - } - -// --------------------------------------------------------------------------------- - /* - * get the previous event's Signif code for the specified locationId - */ - private String getPrevVtecSignif() - { - String prevVtecSignif = ""; - - try - { - prevVtecSignif = _fpCurPrevVtecData.getprevSignif(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecSignif():" + "Signif =" + prevVtecSignif); - } - return prevVtecSignif; - } - -// --------------------------------------------------------------------------------- - /* - * get the previous event's severity code for the specified locationId - */ - private String getPrevVtecSeverity() - { - String prevVtecSeverity = ""; - - try - { - prevVtecSeverity = _fpCurPrevVtecData.getprevSeverity(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecSeverity():" + "Severity =" + prevVtecSeverity); - } - return prevVtecSeverity; - } - // --------------------------------------------------------------------------------- - /* - * get the previous event's Begin Time for the specified locationId - */ - private String getPrevVtecBeginTime() - { - long time = -1; - String timestring = ""; - - try - { - - - time = _fpCurPrevVtecData.getprevBeginTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecBeginTime():" + "begintime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's end time for the specified locationId - */ - private String getPrevVtecEndTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevEndTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecEndTime():" + "endtime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's rise abpve flood stage time for the specified locationId - */ - private String getPrevVtecRiseTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevRiseTime(); - if (time == MISSING_INT ) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecRiseTime():" + "risetime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's crest time for the specified locationId - */ - private String getPrevVtecCrestTime() - { - long time = -1; - String timestring = ""; - try - { - time = _fpCurPrevVtecData.getprevCrestTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecCrestTime():" + "cresttime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's crest value for the specified locationId - */ - private String getPrevVtecCrestValue() - { - double value = -9999.0; - String valuestring = null; - - try - { - value = _fpCurPrevVtecData.getprevCrestValue(); - if (value != 0.0) - valuestring = Double.toString(value); - - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecCrestValue():" + "crest value =" + value); - } - - return valuestring; - } - - - - // --------------------------------------------------------------------------------- - /* - * get the previous event's fall time for the specified locationId - */ - private String getPrevVtecFallTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevFallTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if ( time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecFallTime():" + "falltime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's product time for the specified locationId - */ - private String getPrevVtecProductTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevProductTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if ( time != 0) - { - time = time * MILLIS_PER_SECOND; - timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecProductTime():" + "producttime =" + time); - } - return timestring; - } - - // ------------------------------------------------------------------------------ - public FpVtecInfo getApplication() { - return _application; - } - - // -------------------------------------------------------------------------------- - - public void setApplication(FpVtecInfo application) { - this._application = application; - } - - //---------------------------------------------------------------------------------- - private class UpdateVtecTimeDocumentListener implements DocumentListener - { - - public void insertUpdate(DocumentEvent arg0) - { - - if (! _graphicalChange) - { - System.out.println("UpdateVtecTimeDocumentListener.insertUpdate() event used."); - updateGraph(); - } - else - { - System.out.println("UpdateVtecTimeDocumentListener.insertUpdate() event ignored."); - - } - - } - - public void removeUpdate(DocumentEvent arg0) - { - - } - - public void changedUpdate(DocumentEvent arg0) - { - - } - - } - - public FpVtecInfoDataManager get_dataMgr() { - return _dataMgr; - } - - public void set_dataMgr(FpVtecInfoDataManager mgr) { - _dataMgr = mgr; - } - - // action for check box _curvtecRiseTimeSetMissingCheckBox - private class ChangeRiseTimeMissingCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecRiseTimeTextField.setText("MSG"); - } - else - { - _curvtecRiseTimeTextField.setTime(_currentTime); - - } - - updateGraph(); - - } - } - - // action for check box _curvtecCrestTimeSetMissingCheckBox - private class ChangeCrestTimeMissingCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecCrestTimeTextField.setText("MSG"); - - } - else - { - _curvtecCrestTimeTextField.setTime(_currentTime); - - } - - updateGraph(); - - } - } - - // action for check box _curvtecFallTimeSetMissingCheckBox - private class ChangeFallTimeMissingCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecFallTimeTextField.setText("MSG"); - - } - else - { - _curvtecFallTimeTextField.setTime(_currentTime); - - } - - updateGraph(); - - } - - } - - // action for radio button _curvtecBeginTimeSetMissingRadioButton - private class SelectBeginTimeMissingRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecBeginTimeTextField.setText("MSG"); - updateGraph(); - - } - - } - } - - - // action for radio button _curvtecBeginTimeSetCurrentRadioButton - private class SelectBeginTimeCurrentRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecBeginTimeTextField.setText("CURRENT"); - updateGraph(); - } - - } - } - - // action for radio button _curvtecBeginTimeRadioButton - private class SelectBeginTimeRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecBeginTimeTextField.setTime(_currentTime); - updateGraph(); - - } - - } - } - -// action for radio button _curvtecEndTimeSetMissingRadioButton - private class SelectEndTimeMissingRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecEndTimeTextField.setText("MSG"); - updateGraph(); - - } - - } - } - - - // action for radio button _curvtecEndTimeSetCurrentRadioButton - private class SelectEndTimeCurrentRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecEndTimeTextField.setText("CURRENT"); - updateGraph(); - - } - - } - } - - // action for radio button _curvtecEndTimeRadioButton - private class SelectEndTimeRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecEndTimeTextField.setTime(_currentTime); - updateGraph(); - - } - - } - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/TimeLineAdjustmentListener.java b/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/TimeLineAdjustmentListener.java deleted file mode 100644 index bd668c59fc..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/fp_vtec_info/TimeLineAdjustmentListener.java +++ /dev/null @@ -1,233 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.awt.Point; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class TimeLineAdjustmentListener extends MouseAdapter implements MouseMotionListener -{ - - private boolean _button1Down = false; - private boolean _tipShownOnce = false; - - //variables related to keyboard commands - private boolean _hasFocus = false; - private Point _mousePosition = null; - private TimeHolder _beginTimeHolder = null; - private TimeHolder _endTimeHolder = null; - private TimeHolder _riseTimeHolder = null; - private TimeHolder _crestTimeHolder = null; - private TimeHolder _fallTimeHolder = null; - - private TimeHolder[] _timeHolderArray = null; - private TimeHolder _selectedTimeHolder = null; - - //List _pointList = new ArrayList(); - private TsPaintableCanvas _canvas = null; - private FpVtecInfo _worker = null; - - - // constructor - public TimeLineAdjustmentListener(FpVtecInfo worker, - TsPaintableCanvas canvas, - TimeHolder beginTimeHolder, - TimeHolder endTimeHolder, - TimeHolder riseTimeHolder, - TimeHolder crestTimeHolder, - TimeHolder fallTimeHolder) - { - _beginTimeHolder = beginTimeHolder; - _endTimeHolder = endTimeHolder; - _riseTimeHolder = riseTimeHolder; - _crestTimeHolder = crestTimeHolder; - _fallTimeHolder = fallTimeHolder; - - _timeHolderArray = new TimeHolder[] {beginTimeHolder, - endTimeHolder, - riseTimeHolder, - crestTimeHolder, - fallTimeHolder}; - - - _canvas = canvas; - _worker = worker; - } - - public void mouseDragged(MouseEvent event) - { - String header = "TimeLineAdjustmentListener.mouseDragged(): "; - System.out.println(header + "activated "); - - if (_button1Down) - { - Point point = event.getPoint(); - //System.out.println("activated mouseDragged, button = " + button ); - //adjustTimeLine(point); - } - - } - - public void mouseMoved(MouseEvent event) - { - _mousePosition = event.getPoint(); - //do nothing - } - - public void mousePressed(MouseEvent event) - { - String header = "TimeLineAdjustmentListener.mousePressed(): "; - System.out.println(header); - - int button = event.getButton(); - if (button == MouseEvent.BUTTON1) - { - _button1Down = true; - _selectedTimeHolder = findClosestTimeHolder(event.getPoint()); - } - else - { - - } - - return; - - } - - - public void mouseReleased(MouseEvent event) - { - System.out.println("Precip adjust listener: mouseReleased()"); - int button = event.getButton(); - - if (button == MouseEvent.BUTTON1) - { - _button1Down = false; - - adjustTimeLine(event.getPoint()); - _selectedTimeHolder = null; - } - - } - - public void mouseEntered(MouseEvent event) - { - //get the focus on this canvas, so that the keyboard commands will work on it - //AnalysisWindow.this._precipCanvas.requestFocusInWindow(); - // System.out.println("mouseEntered():" + " requested focus "); - _hasFocus = true; - } - - public void mouseExited(MouseEvent event) - { - _hasFocus = false; - } - - public void keyPressed(KeyEvent e) - { - - } - - public void keyReleased(KeyEvent e) - { - - } - - public void keyTyped(KeyEvent e) - { - - } -// ---------------------------------------------------------------------------------- - private TimeHolder findClosestTimeHolder(Point point) - { - long timeInMillis = getTimeFromPoint(point); - - long timeWindowInHours = 3; - final long timeWindowInMillis = timeWindowInHours * TimeHelper.MILLIS_PER_HOUR; - - long timeDiffInMillis = 0; - long bigTimeInMillis = timeWindowInMillis + 1; - long minDiffInMillis = bigTimeInMillis; - - TimeHolder closestTimeHolder = null; - - for (int i = 0; i < _timeHolderArray.length; i++) - { - TimeHolder timeHolder = _timeHolderArray[i]; - long timefromtimeholder = timeHolder.getTime(); - - timeDiffInMillis = Math.abs(timeHolder.getTime() - timeInMillis); - - if (timeDiffInMillis < minDiffInMillis) - { - minDiffInMillis = timeDiffInMillis; - closestTimeHolder = timeHolder; - } - } - - //make sure that the closest one is within the time window - if (minDiffInMillis > timeWindowInMillis) - { - closestTimeHolder = null; - } - - return closestTimeHolder; - } -// ---------------------------------------------------------------------------------- - - private long getTimeFromPoint(Point point) - { - DataPoint dataPoint = _canvas.getViewport().getDataPoint(point); - - long newTime = (long) Math.floor(dataPoint.getX()); - - newTime /= TimeHelper.MILLIS_PER_HALF_HOUR; - newTime *= TimeHelper.MILLIS_PER_HALF_HOUR; - - return newTime; - } - - private void adjustTimeLine(Point point) - { - String header = "TimeLineAdjustment.adjustTimeLine(): "; - - - TimeHolder timeHolder = _selectedTimeHolder; - System.out.println(header + "_selectedTimeHolder = " + _selectedTimeHolder); - if (timeHolder == null) - { - return; - } - - long newTime = getTimeFromPoint(point); - - long oldTime = timeHolder.getTime(); - - System.out.println(header + DbTimeHelper.getDateTimeStringFromLongTime(oldTime) + - " new time = " + DbTimeHelper.getDateTimeStringFromLongTime(newTime) ); - - timeHolder.setTime(newTime); - - System.out.println(header + "time line moved to " + - DbTimeHelper.getDateTimeStringFromLongTime(newTime)); - - - _worker.getFrame().updateCurDateTimeTextField(); - _worker.getFrame().updateGraph(); - - - } //end adjustTimeLine - - -} //end TimeLineAdjustmentListener - -//-------------------------------------------------------------------- - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/ContourGrid.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/ContourGrid.java deleted file mode 100644 index 224abbb440..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/ContourGrid.java +++ /dev/null @@ -1,19 +0,0 @@ -package ohd.hseb.geomap.contour; - -/** - * - * @author cgobs - * This is an interface for a 2-D (row * col) non-jagged array that contains doubles. - */ -public interface ContourGrid -{ - - double getValue(int row, int col); - void setValue(int row, int col, double value); - - double[][] getValuesArray(); - - int getRowCount(); - int getColCount(); - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/Interpolator.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/Interpolator.java deleted file mode 100644 index 7de2651e56..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/Interpolator.java +++ /dev/null @@ -1,23 +0,0 @@ -package ohd.hseb.geomap.contour; - -public class Interpolator -{ -// ----------------------------------------------------------------------------------------- - public Interpolator() - { - - } -// ----------------------------------------------------------------------------------------- - public double interpolate(double targetX, double x1, double y1, double x2, double y2) - { - double slope = (y2 - y1) / (x2 - x1); - double intercept = (y1) - (slope*x1); - - double y = (slope*targetX) + intercept; - - return y; - } - - // ----------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/RowColToLatLonTranslator.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/RowColToLatLonTranslator.java deleted file mode 100644 index beffac740a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/RowColToLatLonTranslator.java +++ /dev/null @@ -1,15 +0,0 @@ -package ohd.hseb.geomap.contour; - -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.RowColumnPoint; - -public interface RowColToLatLonTranslator -{ - - LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint); - LatLonPoint getLatLonPoint(double row, double col); - -// RowColumnPoint getRowColumnPoint(double lat, double lon); - RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint); - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/RowToLatLonContourer.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/RowToLatLonContourer.java deleted file mode 100644 index 2df7fcc4d7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/contour/RowToLatLonContourer.java +++ /dev/null @@ -1,254 +0,0 @@ -package ohd.hseb.geomap.contour; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.model.RowColumnPoint; -import ohd.hseb.util.Range; - -public class RowToLatLonContourer -{ - private double[][] _valueArray; - private int _rowCount = 0; - private int _colCount = 0; - - private RowColToLatLonTranslator _positionTranslator = null; - - // -------------------------------------------------------------------------------------------- - public RowToLatLonContourer(short [][] valueArray, RowColToLatLonTranslator translator ) - { - this (getDoubleArrayFromShortArray(valueArray), translator); - } - // -------------------------------------------------------------------------------------------- - public RowToLatLonContourer(ContourGrid grid, RowColToLatLonTranslator translator) - { - this (grid.getValuesArray(), translator); - } - - // -------------------------------------------------------------------------------------------- - - - public RowToLatLonContourer(double [][] valueArray, RowColToLatLonTranslator translator) - { - setValueArray(valueArray); - - _rowCount = valueArray.length; - if (_rowCount > 0) - { - _colCount = valueArray[0].length; - } - - _positionTranslator = translator; - - } - - - // -------------------------------------------------------------------------------------------- - private static double[][] getDoubleArrayFromShortArray(short[][] shortArray) - { - int rowCount = shortArray.length; - int colCount = 0; - if (rowCount > 0) - { - colCount = shortArray[0].length; - } - - double[][] doubleArray = new double[rowCount][colCount]; - for (int row = 0; row < rowCount; row ++) - { - for (int col = 0; col < colCount; col++) - { - doubleArray[row][col] = shortArray[row][col]; - } - } - - return doubleArray; - } - // -------------------------------------------------------------------------------------------- - - public void setValueArray(double[][] valueArray) - { - _valueArray = valueArray; - } - - // -------------------------------------------------------------------------------------------- - - public double[][] getValueArray() - { - return _valueArray; - } - - // -------------------------------------------------------------------------------------------- - - public double getValue(int row, int col) - { - // System.out.println("row = " + row + " col = " + col); - return _valueArray[row][col]; - } - - // -------------------------------------------------------------------------------------------- - public List< List > contour(double[] levelArray) - { - List< List > listOfLatLonPolylineLists = new ArrayList >(); - - for (int i = 0; i < levelArray.length; i++) - { - List polylineList = contourOneLevel(levelArray[i]); - listOfLatLonPolylineLists.add(polylineList); - } - - return listOfLatLonPolylineLists; - } - - // -------------------------------------------------------------------------------------------- - - public List contourOneLevel(double level) - { - List polylineList = new ArrayList(); - - LatLonPoint previousPoint = null; - - for (int row = 0; row < _rowCount; row++) - { - for (int col = 0; col < _colCount; col++) - { - - List pointList = getPointsFromFourCells(level, row, col); //eliminate duplicate points - if (pointList.size() > 0) - { - LatLonPolyline polyline = new LatLonPolyline(pointList); - polylineList.add(polyline); - } - } - } - - return polylineList; - } - // -------------------------------------------------------------------------------------------- - private List getPointsFromFourCells(double level, int row, int col) - { - String header = "RowToLatLonContourer.getPointsFromFourCells(): "; - List latLonPointList = new ArrayList (); - LatLonPoint point = null; - - if (col < _colCount - 1) - { - point = getCrossOverLatLonPoint(level, row, col, row, col+1); - addPointToListIfNotNull(latLonPointList, point); - - if (row < _rowCount - 1) - { - point = getCrossOverLatLonPoint(level, row, col+1, row+1, col+1); - addPointToListIfNotNull(latLonPointList, point); - - - point = getCrossOverLatLonPoint(level, row+1, col+1, row+1, col); - addPointToListIfNotNull(latLonPointList, point); - - } - - } - if (row < _rowCount - 1) - { - point = getCrossOverLatLonPoint(level, row+1, col, row, col); - addPointToListIfNotNull(latLonPointList, point); - - } - if (latLonPointList.size() == 1) - { - latLonPointList.clear(); - System.out.println(header + "clearing list of its single point"); - } - return latLonPointList; - } - // -------------------------------------------------------------------------------------------- - private LatLonPoint getCrossOverLatLonPoint(double level, - int row1, int col1, - int row2, int col2) - { - LatLonPoint point = null; - - double value1 = getValue(row1, col1); - double value2 = getValue(row2, col2); - Range range = new Range(value1, value2); - - if (range.isBetweenInclusive(level)) - { - if (value1 == value2) //ignore it, this is counterintuitive, but needed - { - //do nothing - } - else //there is a distinct boundary and value1 != value2 - { - LatLonPoint latLonPoint1 = getLatLonPoint(row1, col1); - LatLonPoint latLonPoint2 = getLatLonPoint(row2, col2); - - LatLonPoint interpolatedPoint = interpolate(level, latLonPoint1, value1, latLonPoint2, value2); - point = interpolatedPoint; - } - - } - return point; - } - - // -------------------------------------------------------------------------------------------- - private LatLonPoint interpolate(double targetValue, - LatLonPoint point1, double value1, - LatLonPoint point2, double value2) - { - // String header = "RowToLatLonContourer.interpolate(): "; - - Interpolator interpolator = new Interpolator(); - - double lat1 = point1.getLat(); - double lat2 = point2.getLat(); - - double lon1 = point1.getLon(); - double lon2 = point2.getLon(); - - -// these are switched from the usual order, since we are seeking lat and lon instead of value - double interpolatedLat = interpolator.interpolate(targetValue, value1, lat1, value2, lat2); - double interpolatedLon = interpolator.interpolate(targetValue, value1, lon1, value2, lon2); - - LatLonPoint newPoint = new LatLonPoint(interpolatedLat, interpolatedLon); - - RowColumnPoint rcPoint = getRowColumnPoint(newPoint); - // System.out.println(header + rcPoint ); - - return newPoint; - } - - // -------------------------------------------------------------------------------------------- - - private LatLonPoint getLatLonPoint(int row, int col) - { - - LatLonPoint point = _positionTranslator.getLatLonPoint(new RowColumnPoint(row, col)); - - return point; - } - - // -------------------------------------------------------------------------------------------- - private RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - RowColumnPoint point = _positionTranslator.getRowColumnPoint(latLonPoint); - - return point; - } - - // -------------------------------------------------------------------------------------------- - private void addPointToListIfNotNull(List pointList, LatLonPoint point) - { - if (point != null) - { - pointList.add(point); - } - - return; - } - // -------------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/DrawableShape.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/DrawableShape.java deleted file mode 100644 index 41fd568515..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/DrawableShape.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.geomap.model; - -public interface DrawableShape -{ - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/ElevationMap.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/ElevationMap.java deleted file mode 100644 index 727f64106a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/ElevationMap.java +++ /dev/null @@ -1,228 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; - -public class ElevationMap implements RowColToLatLonTranslator -{ - private LatLonBounds _latLonBounds = null; - private double _latResInDegrees = 0; - private double _lonResInDegrees = 0; - - private short[][] _valueArray = null; - private int _rowCount = 0; - private int _colCount = 0; - // ---------------------------------------------------------------------------------------------------------------------- - public ElevationMap(LatLonBounds latLonBounds, double latResInDegrees, double lonResInDegrees) - { - _latLonBounds = new LatLonBounds(latLonBounds); - setLatResInDegrees(latResInDegrees); - setLonResInDegrees(lonResInDegrees); - - _rowCount = (int) Math.ceil(latLonBounds.getLatDifference() / latResInDegrees); - _colCount = (int) Math.ceil(latLonBounds.getLonDifference() / lonResInDegrees); - - _valueArray = new short[getRowCount()][getColCount()]; - } - // ------------------------------------------------------------------------------ - public void setLatLonBounds(LatLonBounds latLonBounds) - { - _latLonBounds = latLonBounds; - } - // ------------------------------------------------------------------------------ - - public LatLonBounds getLatLonBounds() - { - return _latLonBounds; - } - // ------------------------------------------------------------------------------ - - public List getLatLonPointList() - { - return new ArrayList(); - } - // ------------------------------------------------------------------------------ - - public void setLatResInDegrees(double latResInDegrees) - { - _latResInDegrees = latResInDegrees; - } - - public double getLatResInDegrees() - { - return _latResInDegrees; - } - - public void setLonResInDegrees(double lonResInDegrees) - { - _lonResInDegrees = lonResInDegrees; - } - - public double getLonResInDegrees() - { - return _lonResInDegrees; - } - // ------------------------------------------------------------------------------ - public RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - double row = getRow(latLonPoint.getLat()); - double col = getCol(latLonPoint.getLon()); - - return new RowColumnPoint(row, col); - } - // ------------------------------------------------------------------------------ - public LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint) - { - double lat = getLat((int) rowColumnPoint.getRow()); - double lon = getLon((int) rowColumnPoint.getCol()); - - return new LatLonPoint(lat, lon); - } - // ------------------------------------------------------------------------------ - public LatLonPoint getLatLonPoint(double row, double col) - { - double lat = getLat((int) row); - double lon = getLon((int) col); - - return new LatLonPoint(lat, lon); - } - - // ------------------------------------------------------------------------------ - - public int getRow(double lat) - { - int row = -1; - - double latDiff = _latLonBounds.getNorthLat() - lat; - row = (int) Math.ceil(latDiff / getLatResInDegrees()); - - return row; - } - // ------------------------------------------------------------------------------ - public int getCol(double lon) - { - int col = -1; - - double lonDiff = lon - _latLonBounds.getWestLon(); - col = (int) Math.ceil(lonDiff / getLonResInDegrees()); - - return col; - } - // ------------------------------------------------------------------------------ - public double getLat(int row) - { - double lat = _latLonBounds.getNorthLat() - (row * getLatResInDegrees()); - - return lat; - } - // ------------------------------------------------------------------------------ - public double getLon(int col) - { - double lon = _latLonBounds.getWestLon() + (col * getLonResInDegrees()); - - return lon; - } - // ------------------------------------------------------------------------------ - - - public void setValueByLatLon(double lat, double lon, short value) - { - - setValue(getRow(lat), getCol(lon), value); - } - - // ------------------------------------------------------------------------------ - public void setValue(int row, int col, short value) - { - - _valueArray[row][col] = value; - } - - // ------------------------------------------------------------------------------ - public short[][] getValueArray() - { - return _valueArray; - } - // ------------------------------------------------------------------------------ - public short getValue(int row, int col) - { - short value = 0; - - if (isInRange(row, col)) - { - value = _valueArray[row][col]; - } - return value; - } - - private boolean isInRange(int row, int col) - { - boolean result = false; - if ((row >-1) && - (row < getRowCount()) && - (col >-1) && - (col < getColCount()) ) - { - result = true; - } - - return result; - } - - public short getValueByLatLon(double lat, double lon) - { - int row = getRow(lat); - int col = getCol(lon); - - return getValue(row, col); - } - - // ------------------------------------------------------------------------------ - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getLatLonBounds() + "lat res = " + getLatResInDegrees() + " lon res = " + getLonResInDegrees()); - - int rowCount = getRowCount(); - int colCount = getColCount(); - - for (int row = 0; row < rowCount; row++) - { - for (int col = 0; col < colCount; col++) - { - buffer.append(_valueArray[row][col] + " "); - } - buffer.append("\n"); - } - - return buffer.toString(); - } - - // ------------------------------------------------------------------------------ - - - public void setRowCount(int rowCount) - { - _rowCount = rowCount; - } - public int getRowCount() - { - return _rowCount; - } - public void setColCount(int colCount) - { - _colCount = colCount; - } - public int getColCount() - { - return _colCount; - } - - - // ------------------------------------------------------------------------------ - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/HrapRowColToLatLonConverter.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/HrapRowColToLatLonConverter.java deleted file mode 100644 index 18c777b083..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/HrapRowColToLatLonConverter.java +++ /dev/null @@ -1,207 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; - -public class HrapRowColToLatLonConverter implements RowColToLatLonTranslator -{ - - private static double RADIANS_PER_DEGREE = 0.017453293; - private static double DEGREES_PER_RADIAN = 57.29577951; - private static double EARTH_RADIUS = 6371.2; - private static double MESH_LEN = 4.7625; - private static double STDLAT = 60; - private static double STDLON = 105; - - // public static int LOCAL_HRAP_ROWS = 131; - // public static int LOCAL_HRAP_COLS = 131; - - private int _baseNationalRow = 0; - private int _baseNationalColumn = 0; - - private Map _latLonCache = new HashMap(); - - // ------------------------------------------------------------------------------------------------- - /** - * This class translates between local Hrap grid locations and Lat-Lon corrdinates. - * It uses the baseNationalRow and the baseNationalColumn for this - */ - - public HrapRowColToLatLonConverter(int baseNationalRow, int baseNationalColumn) - { - _baseNationalRow = baseNationalRow; - _baseNationalColumn = baseNationalColumn; - } - // ------------------------------------------------------------------------------------------------- - - public RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - return getRowColumnPoint(latLonPoint.getLat(), latLonPoint.getLon()); - } - - // ------------------------------------------------------------------------------------------------- - - public RowColumnPoint getRowColumnPoint(double lat, double lon) - { - - double tlat, re; - double latrad, lonrad; - double r; - double x, y; - - tlat = STDLAT * RADIANS_PER_DEGREE; - - re = (EARTH_RADIUS * (1. + Math.sin(tlat))) / MESH_LEN; - latrad = lat * RADIANS_PER_DEGREE; - lonrad = (lon + 180. - STDLON) * RADIANS_PER_DEGREE; - - r = re * Math.cos(latrad) / (1. + Math.sin(latrad)); - x = r * Math.sin(lonrad); - y = r * Math.cos(lonrad); - - double col = x + 401.; - double row = y + 1601.; - - col -= getBaseNationalColumn(); - row -= getBaseNationalRow(); - - return new RowColumnPoint(row, col); - - } - // ------------------------------------------------------------------------------------------------- - public static RowColumnPoint getNationalRowColumnPoint(LatLonPoint latLonPoint) - { - return getNationalRowColumnPoint(latLonPoint.getLat(), latLonPoint.getLon()); - } - - // ------------------------------------------------------------------------------------------------- - - public static RowColumnPoint getNationalRowColumnPoint(double lat, double lon) - { - - double tlat, re; - double latrad, lonrad; - double r; - double x, y; - - tlat = STDLAT * RADIANS_PER_DEGREE; - - re = (EARTH_RADIUS * (1. + Math.sin(tlat))) / MESH_LEN; - latrad = lat * RADIANS_PER_DEGREE; - lonrad = (lon + 180. - STDLON) * RADIANS_PER_DEGREE; - - r = re * Math.cos(latrad) / (1. + Math.sin(latrad)); - x = r * Math.sin(lonrad); - y = r * Math.cos(lonrad); - - double col = x + 401.; - double row = y + 1601.; - - return new RowColumnPoint(row, col); - - } - // ------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint) - { - - return getLatLonPoint(rowColumnPoint.getRow(), rowColumnPoint.getCol()); - } - - // ------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPointOld(double row, double col) - { - - RowColumnPoint rowColumnPoint = new RowColumnPoint(row, col); - LatLonPoint latLonPoint = _latLonCache.get(rowColumnPoint); - - if (latLonPoint == null ) - { - latLonPoint = calculateLatLonPoint(row, col); - _latLonCache.put(rowColumnPoint, latLonPoint); - } - - return latLonPoint; - } - - // ------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPoint(double row, double col) - { - - return calculateLatLonPoint(row, col); - } - // ------------------------------------------------------------------------------------------------- - - public LatLonPoint calculateLatLonPoint(double row, double col) - { - - row = row + getBaseNationalRow(); - col = col + getBaseNationalColumn(); - - - double x, y; - double rr, gi; - double ang, tlat; - - double lat = 0; - double lon = 0; - - tlat = 60.0 / DEGREES_PER_RADIAN; - - x = col - 401.; - y = row - 1601.; - - rr = (x * x) + (y * y); - gi = ((EARTH_RADIUS * (1 + Math.sin(tlat)))/MESH_LEN); - gi = gi * gi; - - lat = Math.asin((gi - rr) / (gi + rr)) * DEGREES_PER_RADIAN; - - ang = Math.atan2(y, x) * DEGREES_PER_RADIAN; - - if (ang < 0) - ang=ang + 360.; - - lon = 270 + STDLON - ang; - - if (lon < 0) - lon += 360.; - - if (lon > 360) - lon -= 360.; - - lon *= -1.0; - - - return new LatLonPoint(lat, lon); - } - // ------------------------------------------------------------------------------------------------- - - private void setBaseNationalRow(int baseNationalRow) - { - _baseNationalRow = baseNationalRow; - } - // ------------------------------------------------------------------------------------------------- - - private int getBaseNationalRow() - { - return _baseNationalRow; - } - // ------------------------------------------------------------------------------------------------- - - private void setBaseNationalColumn(int baseNationalColumn) - { - _baseNationalColumn = baseNationalColumn; - } - // ------------------------------------------------------------------------------------------------- - - private int getBaseNationalColumn() - { - return _baseNationalColumn; - } - - // ------------------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonBounds.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonBounds.java deleted file mode 100644 index dd37ee69a7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonBounds.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.geomap.model; - -public class LatLonBounds -{ - private double _northLat = 0; - private double _southLat = 0; - private double _westLon = 0; - private double _eastLon = 0; - - // ----------------------------------------------------------------------------------------------------------- - - public LatLonBounds(double northLat, double southLat, double westLon, double eastLon) - { - setNorthLat(northLat); - setSouthLat(southLat); - setWestLon(westLon); - setEastLon(eastLon); - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - public LatLonBounds(LatLonPoint northWestLatLong, LatLonPoint southEastLatLong) - { - setNorthLat(northWestLatLong.getLat()); - setSouthLat(southEastLatLong.getLat()); - setWestLon(northWestLatLong.getLon()); - setEastLon(southEastLatLong.getLon()); - } - // ----------------------------------------------------------------------------------------------------------- - - public LatLonBounds(LatLonBounds origBounds) - { - setNorthLat(origBounds.getNorthLat()); - setSouthLat(origBounds.getSouthLat()); - setWestLon(origBounds.getWestLon()); - setEastLon(origBounds.getEastLon()); - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setNorthLat(double northLat) - { - _northLat = northLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getNorthLat() - { - return _northLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeNorthLat(double changeAmount) - { - _northLat += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setSouthLat(double southLat) - { - _southLat = southLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getSouthLat() - { - return _southLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeSouthLat(double changeAmount) - { - _southLat += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setWestLon(double westLon) - { - _westLon = westLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getWestLon() - { - return _westLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeWestLon(double changeAmount) - { - _westLon += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setEastLon(double eastLon) - { - _eastLon = eastLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getEastLon() - { - return _eastLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeEastLon(double changeAmount) - { - _eastLon += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getLatDifference() - { - return getNorthLat() - getSouthLat(); - } - - // ----------------------------------------------------------------------------------------------------------- - public double getLonDifference() - { - return getEastLon() - getWestLon(); - } - - // ----------------------------------------------------------------------------------------------------------- - - - public void updateLatLonBounds(float lat1, float lat2, - float lon1, float lon2) - { - updateLatitude(lat1); - updateLatitude(lat2); - - updateLongitude(lon1); - updateLongitude(lon2); - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - private void updateLatitude(float lat) - { - if (lat > getNorthLat()) - { - setNorthLat(lat); - } - if (lat < getSouthLat()) - { - setSouthLat(lat); - } - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - private void updateLongitude(float lon) - { - if (lon < getWestLon()) - { - setWestLon(lon); - } - if (lon > getEastLon()) - { - setEastLon(lon); - } - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - public boolean equals(Object object) - { - boolean result = false; - - LatLonBounds otherBounds = (LatLonBounds) object; - if ( - (getNorthLat() == otherBounds.getNorthLat() ) && - (getSouthLat() == otherBounds.getSouthLat() ) && - (getEastLon() == otherBounds.getEastLon()) && - (getWestLon() == otherBounds.getWestLon() ) - ) - { - result = true; - } - - return result; - } - // ----------------------------------------------------------------------------------------------------------- - - public String toString() - { - String string = getNorthLat() + "," + getWestLon() + " to " + getSouthLat() + ", " + getEastLon(); - return string; - - } - // ----------------------------------------------------------------------------------------------------------- - -} //end class LatLonBounds diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonPoint.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonPoint.java deleted file mode 100644 index 36bd83347c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonPoint.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.geomap.model; - -public class LatLonPoint implements DrawableShape -{ - private double _lat; - private double _lon; - - - public LatLonPoint(double lat, double lon) - { - setLat(lat); - setLon(lon); - } - - public void setLat(double lat) - { - _lat = lat; - } - - public double getLat() - { - return _lat; - } - - public void changeLat(double changeAmount) - { - _lat += changeAmount; - - } - - public void setLon(double lon) - { - _lon = lon; - } - - public double getLon() - { - return _lon; - } - - public void changeLon(double changeAmount) - { - _lon += changeAmount; - } - - public boolean equals(LatLonPoint point) - { - double tolerance = 0.000000001; - - boolean result = false; - - double latDiff = Math.abs(getLat() - point.getLat()); - double lonDiff = Math.abs(getLon() - point.getLon()); - - if ( (latDiff < tolerance) && (lonDiff < tolerance)) - { - result = true; - } - - return result; - } - - public String toString() - { - - return String.format("lat = %5.2f , lon = %5.2f ", _lat, _lon); - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonPolyline.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonPolyline.java deleted file mode 100644 index 0098fea749..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/LatLonPolyline.java +++ /dev/null @@ -1,73 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.ArrayList; -import java.util.List; - - -public class LatLonPolyline implements DrawableShape -{ - List _pointList = null; - - - public LatLonPolyline() - { - _pointList = new ArrayList(); - } - - public LatLonPolyline(List pointList) - { - _pointList = pointList; - } - - public void addPoint(LatLonPoint point) - { - _pointList.add(point); - } - - public void addPointList(List pointList) - { - _pointList.addAll(pointList); - } - - public List getPointList() - { - return _pointList; - } - - public boolean equals(LatLonPolyline line) - { - boolean result = false; - - if (_pointList.size() == line.getPointList().size()) - { - result = true; - for (int i = 0; i < _pointList.size(); i++) - { - LatLonPoint point1 = _pointList.get(i); - LatLonPoint point2 = line.getPointList().get(i); - if (! point1.equals(point2) ) - { - result = false; - break; - } - } - } - - - return result; - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - for (LatLonPoint point: _pointList) - { - buffer.append(point.toString()); - } - - return buffer.toString(); - - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/Polygon.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/Polygon.java deleted file mode 100644 index 03877d597f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/Polygon.java +++ /dev/null @@ -1,19 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.ArrayList; -import java.util.List; - -public class Polygon implements DrawableShape -{ - List _pointList = new ArrayList(); - - public Polygon(List pointList) - { - _pointList = pointList; - } - - public List getPointList() - { - return _pointList; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/RowColumnPoint.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/RowColumnPoint.java deleted file mode 100644 index 84b8ffa6da..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/model/RowColumnPoint.java +++ /dev/null @@ -1,51 +0,0 @@ -package ohd.hseb.geomap.model; - -public class RowColumnPoint -{ - private double _row = 0; - private double _column = 0; - - // ----------------------------------------------------------------------------------------- - public RowColumnPoint(double row, double column) - { - setRow(row); - setColumn(column); - } - - // ----------------------------------------------------------------------------------------- - - public void setRow(double row) - { - _row = row; - } - - // ----------------------------------------------------------------------------------------- - - public double getRow() - { - return _row; - } - - // ----------------------------------------------------------------------------------------- - - public void setColumn(double column) - { - _column = column; - } - - // ----------------------------------------------------------------------------------------- - - public double getCol() - { - return _column; - } - - // ----------------------------------------------------------------------------------------- - - public String toString() - { - return "row = " + getRow() + " col = " + getCol(); - } - // ----------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/BaseMapProjection.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/BaseMapProjection.java deleted file mode 100644 index 55445355d8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/BaseMapProjection.java +++ /dev/null @@ -1,377 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; - - -public abstract class BaseMapProjection implements MapProjection -{ - protected static double RADIANS_PER_DEGREE = 0.017453292519943295 ; - protected static double DEGREES_PER_RADIAN = 1.0/RADIANS_PER_DEGREE ; - protected static double NAUTICAL_MILES_PER_DEGREE = 60; - - - private int _mapWidth = 0; - private int _mapHeight = 0; - - - private LatLonBounds _latLonBounds = null; - private double _mapScaleFactor = 90; //degrees per/ pixel - private LatLonPoint _centerLatLon = null; - - // ----------------------------------------------------------------------------------- - - protected int getOffsetX() - { - return getMapWidth() / 2; - } - - protected int getOffsetY() - { - return getMapHeight() / 2; - } - - /* - - -float zoom_multiple = 1.0 ; -float original_zoom_multiple = 1.0 ; -long orig_scale_factor; -long init_scale_factor; -long map_scale_factor; -static int MAXX = 0 ; -static int MAXY = 0 ; -int offsetx,offsety; -int polar_offsety = 0 ; // Used for keeping track of the y-offset of the - // HRAP and Polar Stereographic map projection. -int polar_offsetx = 0 ; // Used for keeping track of the x-offset of the - // HRAP projection. -int projection=M_FLAT; -int prev_projection=M_FLAT; -static int XOR = 0 ; -static int YOR = 0 ; -int zoom_scale = 1; - -float map_center_lat=33.0; -float map_center_lon=-114.0; -float original_center_lat ; -float original_center_lon ; -float top_lat,left_lon; -float width_in_nmi = 0.0 ; -float dtr = 0.017453292519943295 ; -float init_top_lat , init_width ; -int init_offsetx , init_zoom ; -float region_llat = -999.0 , - region_llon = -999.0 , - region_rlat = -999.0 , - region_rlon = -999.0 ; - -static MotifCallback pan_routine = NULL ; -static MotifCallback zoom_routine = NULL ; - - - */ - - abstract public LatLonPoint getLatLonPoint(Point screenPoint); - abstract public LatLonPoint getLatLonPoint(int x, int y); - - - abstract public Point getScreenPoint(LatLonPoint latlonPoint); - abstract public Point getScreenPoint(double lat, double lon); - - public boolean isInRange(double lat, double lon) - { - String header = "BaseMapProjection.isInRange()"; - boolean result = false; - LatLonBounds bounds = getLatLonBounds(); - - if (bounds.getNorthLat() == bounds.getSouthLat()) - { - System.out.println(header + " north and sound bounds are the same."); - } - - if ( - - (lat <= bounds.getNorthLat()) && - (lat >= bounds.getSouthLat()) && - (lon >= bounds.getEastLon()) && - (lon <= bounds.getWestLon()) - ) - { - result = true; - System.out.println(header + "finally, something is in range to be drawn"); - } - - return result; - } - - - // ---------------------------------------------------------------- - - public List getLatLonPointList(List screenCoordList) - { - List latLonPointList = new ArrayList(); - - for (Point screenPoint : screenCoordList) - { - LatLonPoint latLonPoint = getLatLonPoint(screenPoint); - latLonPointList.add(latLonPoint); - } - - return null; - } - - // ---------------------------------------------------------------- - - public List getScreenPointList(List latLongCoordinateList) - { - List screenPointList = new ArrayList(); - - for (LatLonPoint latLonPoint : latLongCoordinateList) - { - Point screenPoint = getScreenPoint(latLonPoint); - screenPointList.add(screenPoint); - } - - return screenPointList; - } - - //------------------------------------------------------------------------------------------------- - - - - protected void init(float displayWidthInNauticalMiles) - { - double degreesLongitude ; - - int offsetx = getOffsetX(); - int offsety = getOffsetY(); - - double mapCenterLat = getCenterLatLon().getLat(); - - degreesLongitude = displayWidthInNauticalMiles / - ( NAUTICAL_MILES_PER_DEGREE * Math.cos ( mapCenterLat * RADIANS_PER_DEGREE ) ) ; - - double map_scale_factor = ( long ) ( 2.0 * ( float ) getOffsetX() / degreesLongitude ) ; - - //Compute the top latitude and the left longitude. - LatLonPoint northWestLatLong = getLatLonPoint(new Point(0,0)); - _latLonBounds.setNorthLat(northWestLatLong.getLat()); - _latLonBounds.setWestLon(northWestLatLong.getLon()); - - /* - init_scale_factor = map_scale_factor ; - orig_scale_factor = init_scale_factor ; - init_top_lat = top_lat ; - init_width = width_in_nmi ; - init_offsetx = offsetx ; - */ - } - - // ---------------------------------------------------------------- - /* - - void _init_map_variables ( float nmi ) - { - float degrees_lon ; - projection = M_FLAT ; - width_in_nmi = nmi ; - - offsetx = _get_map_width ( 0 ) / 2 ; - offsety = _get_map_height ( 0 ) / 2 ; - - // New logic added by Bryon Lawrence on January 15, 2002. This is an - // attempt to incorporate an initial measurement in nautical miles into - // the initial computation of the scale factor. - degrees_lon = width_in_nmi / - ( ( float ) NUM_NMI_PER_DEGREE * cos ( map_center_lat * dtr ) ) ; - map_scale_factor = ( long ) ( 2.0 * ( float ) offsetx / degrees_lon ) ; - - //Compute the top latitude and the left longitude. - - mConvertXY2LatLon(0,0,&top_lat,&left_lon) ; - init_scale_factor = map_scale_factor ; - orig_scale_factor = init_scale_factor ; - init_top_lat = top_lat ; - init_width = width_in_nmi ; - init_offsetx = offsetx ; - } - - */ - - // ---------------------------------------------------------------- - - public void setLatLonBounds(LatLonBounds latLonBounds) - { - String header = "BaseMapProjection.setLatLonBounds(): "; - System.out.println(header); - - _latLonBounds = new LatLonBounds(latLonBounds); - - setCenterInternally(); - } - - private void setCenterInternally() - { - String header = "BaseMapProjection.setCenterInternally(): "; - System.out.println(header); - LatLonBounds bounds = getLatLonBounds(); - - double lat = (bounds.getNorthLat() + bounds.getSouthLat())/2.0 ; - double lon = (bounds.getEastLon() + bounds.getWestLon())/2.0 ; - - _centerLatLon = new LatLonPoint(lat, lon); - } - - private void setLatLonBoundsInternally() - { - String header = "BaseMapProjection.setLatLonBoundsInternally(): "; - - LatLonPoint centerPoint = getCenterLatLon(); - double pixelsPerDegree = getMapScaleFactor(); - - double latOffset = getOffsetY() / pixelsPerDegree; - double lonOffset = getOffsetX() / pixelsPerDegree; - - System.out.println(header + " latOffset = " + latOffset); - System.out.println(header + " lonOffset = " + lonOffset); - - double northLat = centerPoint.getLat() + latOffset; - double southLat = centerPoint.getLat() - latOffset; - - double westLat = centerPoint.getLon() - lonOffset; - double eastLat = centerPoint.getLon() + lonOffset; - - _latLonBounds = new LatLonBounds(northLat,southLat, westLat, eastLat); - - System.out.println(header + " latLonBounds = " + _latLonBounds); - - } - - // ---------------------------------------------------------------- - public LatLonBounds getLatLonBounds() - { - return _latLonBounds; - } - // ---------------------------------------------------------------- - - public void setMapHeight(int mapHeight) - { - _mapHeight = mapHeight; - setLatLonBoundsInternally(); - } - // ---------------------------------------------------------------- - - public int getMapHeight() - { - return _mapHeight; - - } - - //------------------------------------------------------------------------------------------------- - - public void panProportionally(double northSouthPanProportion, double eastWestPanProportion) - { - String header = "BaseMapProjection.panProportionally(): "; - // System.out.println(header + "northSouthPanProportion = " + northSouthPanProportion + - // " eastWestPanProportion = " + eastWestPanProportion); - - LatLonBounds latLonBounds = getLatLonBounds(); - double panLatAmount = northSouthPanProportion * latLonBounds.getLatDifference(); - double panLonAmount = eastWestPanProportion * latLonBounds.getLonDifference(); - - System.out.println(header + "latLonBounds.getLatDifference() = " + latLonBounds.getLatDifference() + - " latLonBounds.getLonDifference() = " + latLonBounds.getLonDifference()); - - - changeCenter(panLatAmount, panLonAmount); - - return; - } - - //------------------------------------------------------------------------------------------------- - - public void changeCenter(double changeLatAmount, double changeLonAmount) - { - - String header = "BaseMapProjection.changeCenter(): "; - System.out.println(header + "changeLatAmount " + changeLatAmount); - System.out.println(header + "changeLonAmount " + changeLonAmount); - - _centerLatLon.changeLat(changeLatAmount); - _centerLatLon.changeLon(changeLonAmount); - - System.out.println(header + "new center = " + _centerLatLon); - System.out.println(header + "mapScaleFactor = " + getMapScaleFactor()); - - - setLatLonBoundsInternally(); - } - //------------------------------------------------------------------------------------------------- - - public LatLonPoint getCenterLatLon() - { - return _centerLatLon; - } - - //------------------------------------------------------------------------------------------------- - - public void setCenterLatLon(LatLonPoint newCenter) - { - String header = "BaseMapProjection.setCenterLatLon(): "; - - LatLonPoint oldCenter = getCenterLatLon(); - - _centerLatLon = newCenter; - - System.out.println(header + "oldCenter = " + oldCenter + " newCenter = " + newCenter); - System.out.println(header + "width " + getMapWidth() + " height = " + getMapHeight()); - - - setLatLonBoundsInternally(); - - return; - } - - // ---------------------------------------------------------------- - - public void setMapScaleFactor(double mapScaleFactor) - { - _mapScaleFactor = mapScaleFactor; - } - // ---------------------------------------------------------------- - - public double getMapScaleFactor() - { - return _mapScaleFactor; - } - - // ---------------------------------------------------------------- - public void setMapWidthAndHeight(int mapWidth, int mapHeight) - { - _mapWidth = mapWidth; - _mapHeight = mapHeight; - setLatLonBoundsInternally(); - } - - public void setMapWidth(int mapWidth) - { - _mapWidth = mapWidth; - setLatLonBoundsInternally(); - } - - // ---------------------------------------------------------------- - - public int getMapWidth() - { - return _mapWidth; - } - - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/FlatMapProjection.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/FlatMapProjection.java deleted file mode 100644 index cc6048a945..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/FlatMapProjection.java +++ /dev/null @@ -1,84 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; - -import ohd.hseb.geomap.model.LatLonPoint; - -// ------------------------------------------------------------------------------------------ -public class FlatMapProjection extends BaseMapProjection -{ - -// ------------------------------------------------------------------------------------------ - - - public FlatMapProjection (LatLonPoint centerLatLonPoint) - { - setCenterLatLon(centerLatLonPoint); - } - - - public LatLonPoint getLatLonPoint(int x, int y) - { - double lat = 0.0; - double lon = 0.0; - - double mapCenterLon = getCenterLatLon().getLon(); - double mapCenterLat = getCenterLatLon().getLat(); - - lon = ( ( ( double ) (x - getOffsetX()) / getMapScaleFactor() ) + mapCenterLon) ; - lat = mapCenterLat - ( ( double ) ( y - getOffsetY() ) / getMapScaleFactor() ) ; - - LatLonPoint point = new LatLonPoint(lat, lon); - - return point; - } - - - //------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPoint(Point screenPoint) - { - - int x = screenPoint.x; - int y = screenPoint.y; - - return getLatLonPoint(x, y); - } - //------------------------------------------------------------------------------------------------- - - public Point getScreenPoint(LatLonPoint latLonPoint) - { - - double lat = latLonPoint.getLat(); - double lon = latLonPoint.getLon(); - - return getScreenPoint(lat, lon); - - } - -// ------------------------------------------------------------------------------------------------- - - public Point getScreenPoint(double lat, double lon) - { - - double mapCenterLat = getCenterLatLon().getLat(); - double mapCenterLon = getCenterLatLon().getLon(); - - if (mapCenterLon > 0 && lon < 0) - lon = lon + 360; - - if (mapCenterLon < 0 && lon > 0) - lon = lon - 360; - - int x = (int) ((lon - mapCenterLon) * getMapScaleFactor() ) + getOffsetX(); - int y = (int) ( getOffsetY() - ((lat - mapCenterLat) * getMapScaleFactor() ) ); - - - - return new Point(x,y); - } - - //------------------------------------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/MapProjection.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/MapProjection.java deleted file mode 100644 index cbb269b6a2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/MapProjection.java +++ /dev/null @@ -1,43 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; - -public interface MapProjection -{ - void setMapScaleFactor(double mapScaleFactor); - double getMapScaleFactor(); - - int getMapWidth(); - void setMapWidth(int mapWidth); - - int getMapHeight(); - void setMapHeight(int mapHeight); - - //configuration methods - void setLatLonBounds(LatLonBounds latLonBounds); - LatLonBounds getLatLonBounds(); - - void panProportionally(double northSouthPanProportion, double eastWestPanProportion); - - void setCenterLatLon(LatLonPoint centerLatLong); - LatLonPoint getCenterLatLon(); - - //useful methods - - boolean isInRange(double lat, double lon); - - LatLonPoint getLatLonPoint(Point screenPoint); - LatLonPoint getLatLonPoint(int x, int y); - List getLatLonPointList(List screenCoordList); - - Point getScreenPoint(LatLonPoint latlonPoint); - Point getScreenPoint(double lat, double lon); - - List getScreenPointList(List latLonPointList); - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/PolarProjection.java b/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/PolarProjection.java deleted file mode 100644 index 821873aa03..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/geomap/projection/PolarProjection.java +++ /dev/null @@ -1,95 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; - -import ohd.hseb.geomap.model.LatLonPoint; - -public class PolarProjection extends BaseMapProjection -{ - - - public PolarProjection(LatLonPoint centerLatLonPoint, double mapScaleFactor) - { - setCenterLatLon(centerLatLonPoint); - setMapScaleFactor(mapScaleFactor); - } - - @Override - public LatLonPoint getLatLonPoint(Point screenPoint) - { - return getLatLonPoint(screenPoint.x, screenPoint.y); - } - - @Override - public LatLonPoint getLatLonPoint(int x, int y) - { - - double c; - double py; - double px; - double p; - - /* Be sure to take into account any panning/recentering effects. */ - x = x - getOffsetX(); - y = (-1 * y) + getOffsetY(); - - py = (double)y; - px = (double)x; - - double lon = ((getCenterLatLon().getLon() * RADIANS_PER_DEGREE) + Math.atan2(py,px)) * DEGREES_PER_RADIAN + 90.0; - - p = Math.pow(((px*px) + (py*py)),0.5); - c = 2.0 * Math.atan(p/(2.0 * ( double ) getMapScaleFactor())); - - double lat = Math.asin(Math.cos(c) * Math.sin((90.0 *RADIANS_PER_DEGREE)) + - (py * Math.sin(c) * Math.cos((90.0 * RADIANS_PER_DEGREE))/p)) * DEGREES_PER_RADIAN; - - - - - return new LatLonPoint(lat, lon); - } - - @Override - public Point getScreenPoint(LatLonPoint latLonPoint) - { - return getScreenPoint(latLonPoint.getLat(), latLonPoint.getLon()); - } - - @Override - public Point getScreenPoint(double lat, double lon) - { - double k; - double temp; - double centerLon; - - int x = 0; - int y = 0; - - lat = lat * RADIANS_PER_DEGREE; - lon = lon * RADIANS_PER_DEGREE; - centerLon = getCenterLatLon().getLon() * RADIANS_PER_DEGREE; - - temp = 1 + Math.sin(lat); - - if (temp == 0.0) - { - System.out.println("Error\n"); - } - else - { - k = getMapScaleFactor(); - - double tangentTerm = 2.0 * k * Math.tan((Math.PI /4.0) - (lat / 2.0)) ; - - temp = tangentTerm * Math.sin(lon - centerLon); - x = (int)temp + getOffsetX(); - - temp = -tangentTerm * Math.cos(lon - centerLon); - y = getOffsetY() - (int)temp; - } - - return new Point(x, y); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/grid/XmrgGrid.java b/cave/ohd.hseb.common/src/ohd/hseb/grid/XmrgGrid.java deleted file mode 100644 index 97d041e531..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/grid/XmrgGrid.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Created on May 24, 2004 - * - * - */ -package ohd.hseb.grid; - - -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; - -/** - * @author GobsC - * - * - */ -public class XmrgGrid -{ - public static final double OFF_GRID_VALUE = -8888.0; - private double _missingValue = -999.0; - - private long _time = 0; - -// old way of storing grid - private Map _valueMap = null; - // private List _valueList = null; - - -//new way of storing grid - private double[][] _gridValuesArray = null; - - private boolean _isValid = true; - - - private int _rowCount = 0; - private int _colCount = 0; - - private int _baseRow = 0; //southern row - private int _baseCol = 0; // western col - - - // private boolean _newWay = true; - - -// ----------------------------------------------------------------------------------- - private XmrgGrid() - { - _isValid = true; - } - -// ----------------------------------------------------------------------------------- - public static XmrgGrid getInvalidGrid(long time) - { - XmrgGrid grid = new XmrgGrid(time); - - grid.setIsValid(false); - - return grid; - } - - -// ----------------------------------------------------------------------------------- - - public XmrgGrid(long time) - { - _time = time; - _valueMap = new HashMap(); - // _valueList = new ArrayList(); - - } - - // ----------------------------------------------------------------------------------- - - public XmrgGrid(long time, int southernRowIndex, int westernColIndex, - int rowCount, int colCount) - { - - _time = time; - - // new way - _rowCount = rowCount; - _colCount = colCount; - - _baseRow = southernRowIndex; - _baseCol = westernColIndex; - - _gridValuesArray = new double[_rowCount][_colCount]; - - return; - } - -// ----------------------------------------------------------------------------------- - - public void setValue(int hrapRow, int hrapCol, double value) - { - int rowIndex = hrapRow - _baseRow; - int colIndex = hrapCol - _baseCol; - - _gridValuesArray[rowIndex][colIndex] = value; - - return; - } -// ----------------------------------------------------------------------------------- - - public double[][] getValuesArray() - { - return _gridValuesArray; - } - -// ----------------------------------------------------------------------------------- - - public double getValue(int hrapRow, int hrapCol) - { - int rowIndex = hrapRow - _baseRow; - int colIndex = hrapCol - _baseCol; - - double value = OFF_GRID_VALUE; - - //Chip CHANGE 8/23/05 - if ( - (rowIndex > -1) && (rowIndex < _rowCount) && - (colIndex > -1) && (colIndex < _colCount) - ) - { - value = _gridValuesArray[rowIndex][colIndex]; - } - else - { - - // System.out.println("XmrgGrid.getValue(): attempting to access " + - // "rowIndex = " + rowIndex + " colIndex = " + colIndex); - - // System.out.print(" Row Values should be >= 0 < " + _rowCount); - // System.out.println(" and column values should be >= 0 < " + _colCount); - - } - return value; - } - // ----------------------------------------------------------------------------------- - - public void setTime(long time) - { - _time = time; - } -// ----------------------------------------------------------------------------------- - - public long getTime() - { - return _time; - } - -// ----------------------------------------------------------------------------------- - private Object getKey(int hrapRow, int hrapCol) - { - Long key = new Long(hrapRow*10000 + hrapCol); - - return key; - } - -// ----------------------------------------------------------------------------------- - public String toString() - { - StringBuffer buffer = new StringBuffer(); - // String outString = null; - double value = 0; - - - buffer.append("time = " + DbTimeHelper.getDateTimeStringFromLongTime(_time) + "\n"); - /* - for (int i = 0; i < _valueList.size(); i++) - { - String keyValue = (String) _valueList.get(i); - StringTokenizer tokenizer = new StringTokenizer(keyValue, "|"); - - - while (tokenizer.hasMoreTokens()) - { - String hrapRow = tokenizer.nextToken(); - String hrapCol = tokenizer.nextToken(); - String valueString = tokenizer.nextToken(); - value = Double.parseDouble(valueString); - - if (value > 0.0) - { - buffer.append("hrapRow = " + hrapRow + " hrapCol = " + hrapCol + " value = " + value + "\n"); - } - - } - - } - */ - return buffer.toString(); - - } -// ----------------------------------------------------------------------------------- - - public void setIsValid(boolean isValid) - { - _isValid = isValid; - } -// ----------------------------------------------------------------------------------- - - public boolean isValid() - { - return _isValid; - } - - private void setBaseRow(int baseRow) - { - _baseRow = baseRow; - } - - public int getBaseRow() - { - return _baseRow; - } - - private void setBaseCol(int baseCol) - { - _baseCol = baseCol; - } - - public int getBaseCol() - { - return _baseCol; - } - - public int getRowCount() - { - return _rowCount; - } - - public int getColCount() - { - return _colCount; - } - -// ----------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/gui/util/ScreenCaptureActionListener.java b/cave/ohd.hseb.common/src/ohd/hseb/gui/util/ScreenCaptureActionListener.java deleted file mode 100644 index 6c6f70912e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/gui/util/ScreenCaptureActionListener.java +++ /dev/null @@ -1,181 +0,0 @@ -package ohd.hseb.gui.util; - -import java.awt.AWTException; -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Robot; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.imageio.stream.FileImageOutputStream; -import javax.imageio.stream.ImageOutputStream; -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileFilter; - -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class ScreenCaptureActionListener implements ActionListener { - - private JFileChooser _imageFileChooser = null; - - private Window _baseWindow = null; - - private Component _componentToCapture = null; - - // ------------------------------------------------------------------------------------- - - public ScreenCaptureActionListener(Window componentToCapture) { - _componentToCapture = componentToCapture; - _baseWindow = componentToCapture; - - return; - } - - // ------------------------------------------------------------------------------------- - - public ScreenCaptureActionListener(Window baseWindow, - Component componentToCapture) { - _baseWindow = baseWindow; - _componentToCapture = componentToCapture; - - return; - } - - // ------------------------------------------------------------------------------------- - - public void actionPerformed(ActionEvent event) { - this.displayCaptureScreenFileChooser(); - - } // end actionPerformed - - // ------------------------------------------------------------------------------------- - - private void displayCaptureScreenFileChooser() { - BufferedImage image = captureScreenToImage(); - - if (_imageFileChooser == null) { - AppsDefaults ad = AppsDefaults.getInstance(); - - String defaultDirectory = ad.getToken("whfs_image_dir"); - _imageFileChooser = new JFileChooser(defaultDirectory); - } - - // add a FileFilter for JPG files - List filterList = new ArrayList(); - - filterList.add("JPEG"); - filterList.add("JPG"); - FileFilter fileFilter = new ExtensionFileFilter(filterList, - "JPEG Image Files (*.jpg, *.JPG) "); - - // set the file filter - _imageFileChooser.setFileFilter(fileFilter); - // _imageFileChooser.set - - // open the dialog - int returnVal = _imageFileChooser.showSaveDialog(_baseWindow); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = _imageFileChooser.getSelectedFile(); - - // ensure ends in ".jpg" - if ((!file.getName().endsWith(".jpg")) - && (!file.getName().endsWith(".JPG"))) { - String newFilePath = file.getPath() + ".jpg"; - file = new File(newFilePath); - } - - writeImageToFile(image, file); - } - - else { - DialogHelper.displayMessageDialog(_baseWindow, - "Image file not saved."); - } - - return; - } - - // ----------------------------------------------------------------- - - private BufferedImage captureScreenToImage() { - - String header = "ScreenCaptureActionListener.captureScreenToImage(): "; - - BufferedImage bufferedImage = null; - try { - - Robot robot = new Robot(); - Rectangle boundsRectangle = null; - - if (_componentToCapture != _baseWindow) { - - Point origin = getOriginRelativeToScreen(_componentToCapture); - // _componentToCapture.get - Rectangle componentBounds = _componentToCapture.getBounds(); - boundsRectangle = new Rectangle(origin.x, origin.y, - componentBounds.width, componentBounds.height); - - } else { - boundsRectangle = _baseWindow.getBounds(); - } - - bufferedImage = robot.createScreenCapture(boundsRectangle); - - } // end try - - catch (AWTException e) { - e.printStackTrace(); - } - - return bufferedImage; - } - - // ----------------------------------------------------------------- - private Point getOriginRelativeToScreen(Component component) { - - int x = 0; - int y = 0; - - Component parent = component; - - while (parent != null) { - x += parent.getX(); - y += parent.getY(); - - parent = parent.getParent(); - } - - return new Point(x, y); - - } - - // ----------------------------------------------------------------- - - private void writeImageToFile(BufferedImage image, File file) { - try { - ImageOutputStream imageOutputStream = new FileImageOutputStream( - file); - ImageIO.write(image, "JPG", imageOutputStream); - imageOutputStream.close(); - } - - catch (java.io.IOException e) { - e.printStackTrace(); - } - - return; - } - // ----------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/AbsTimeMeasurement.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/AbsTimeMeasurement.java deleted file mode 100644 index bf858479a8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/AbsTimeMeasurement.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Created on Aug 25, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.measurement; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -/** - * @author GobsC - * - * - */ -public class AbsTimeMeasurement extends Measurement -{ - private long _time; // the time the measurement was taken - - // ***************************************************************************** - public AbsTimeMeasurement(Measurement measurement, long timeInMillis) - { - super(measurement); - _time = timeInMillis; - - return; - } - -// ***************************************************************************** - - public AbsTimeMeasurement(double value, long timeInMillis, MeasuringUnit unit) - { - super(value, unit); - _time = timeInMillis; - - return; - } - - // ***************************************************************************** - - public AbsTimeMeasurement(AbsTimeMeasurement measurement) - { - super(measurement.getValue(), measurement.getUnit()); - _time = measurement.getTime(); - - return; - } - //--------------------------------------------------------------- - - public long getTime() - { - return _time; - } - - public void setTime(long timeInMillis) - { - _time = timeInMillis; - } - //--------------------------------------------------------------- - - private String formatTime(long time) - { - - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); - formatter.setTimeZone(TimeZone.getTimeZone("UTC")); - return formatter.format(new Date(time)) + " UTC"; - } - - - //--------------------------------------------------------------- - public static AbsTimeMeasurement getConvertedCopy(AbsTimeMeasurement origMeasurement, - MeasuringUnit toUnit) - { - - AbsTimeMeasurement newMeasurement = new AbsTimeMeasurement(origMeasurement); - - newMeasurement.convert(toUnit); - - return newMeasurement; - } - -// --------------------------------------------------------------- - - public static AbsTimeMeasurement interpolate(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long desiredTime) - { - long t1 = m1.getTime(); - long t2 = m2.getTime(); - - double value1 = m1.getValue(); - double value2 = m2.getValue(); - - double slope = (value2 - value1) / (t2 - t1); - double intercept = (value1) - (slope*t1); - - - double value = (slope*desiredTime) + intercept; - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, desiredTime, m1.getUnit()); - - measurement.setIsInterpolated(true); - - return measurement; - } - - //--------------------------------------------------------------- - - - public boolean equals(Object object) - { - boolean result = false; - - if (object instanceof AbsTimeMeasurement) - { - AbsTimeMeasurement m = (AbsTimeMeasurement) object; - result = equals(m); - } - - return result; - - } - - //--------------------------------------------------------------- - - - public boolean equals(AbsTimeMeasurement measurement) - { - boolean result = false; - - if (this.getUnit() != measurement.getUnit()) - { - measurement = AbsTimeMeasurement.getConvertedCopy(measurement, this.getUnit()); - } - - - if ( - (this.getValue() == measurement.getValue()) && - (this.getTime() == measurement.getTime()) - ) - { - result = true; - } - - return result; - - } - - // --------------------------------------------------------------- - public int hashCode() - { - int value = 0; - - MeasuringUnit standardUnit = MeasuringUnit.getStandardUnitForUnit(this.getUnit()); - value = (int) ( this.getTime() + - this.getValue(standardUnit)); - - return value; - } - // --------------------------------------------------------------- - - public String toString() - { - return getValue() + " in " + getUnit().getName() + " at " + formatTime(_time); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/AbsTimeMeasurementPair.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/AbsTimeMeasurementPair.java deleted file mode 100644 index b38f2b2072..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/AbsTimeMeasurementPair.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.measurement; - - -/** - * @author Chip Gobs - * - * Contains a pair of Measurements - */ -public class AbsTimeMeasurementPair -{ - private AbsTimeMeasurement _measurement1; - private AbsTimeMeasurement _measurement2; - - // ---------------------------------------------------------------------------------------------- - - public AbsTimeMeasurementPair(AbsTimeMeasurement measurement1, AbsTimeMeasurement measurement2) - { - setMeasurement1(measurement1); - setMeasurement1(measurement2); - - return; - } - - /** - * @param measurement1 The measurement1 to set. - */ - public void setMeasurement1(AbsTimeMeasurement measurement1) - { - _measurement1 = new AbsTimeMeasurement(measurement1); - } - - /** - * @return Returns the measurement1. - */ - public AbsTimeMeasurement getMeasurement1() - { - return _measurement1; - } - - /** - * @param measurement2 The measurement2 to set. - */ - public void setMeasurement2(AbsTimeMeasurement measurement2) - { - _measurement2 = new AbsTimeMeasurement(measurement2); - } - - /** - * @return Returns the measurement2. - */ - public AbsTimeMeasurement getMeasurement2() - { - return _measurement2; - } - - // ---------------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/IrregularTimeSeries.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/IrregularTimeSeries.java deleted file mode 100644 index 49b55b0bfd..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/IrregularTimeSeries.java +++ /dev/null @@ -1,661 +0,0 @@ -/* - * Created on Sep 26, 2003 - * - * - */ -package ohd.hseb.measurement; - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.model.ForecastAdjuster; -import ohd.hseb.model.ForecastAdjusterParams; -import ohd.hseb.model.ForecastInterpolationMethod; - -/** - * @author Chip Gobs - * - * - */ -public class IrregularTimeSeries -{ - - private static final double _missingValue = -999.0; - private static final double _otherMissingValue = -9999.0; - private List _measurementList = new ArrayList(); - private MeasuringUnit _measuringUnit = null; - private String _name = null; - - //--------------------------------------------------------------------- - - //--------------------------------------------------------------------- - - public IrregularTimeSeries(MeasuringUnit unit) - { - _measuringUnit = unit; - } - -// --------------------------------------------------------------------- - - - /** - * - * @param newTimeSeries - * This add method perfoms mathematical addition, - * not insertion to the set of values. See insertXXX methods for insertion. - */ - - public static IrregularTimeSeries add(IrregularTimeSeries ts1, IrregularTimeSeries ts2) - { - //algorithm - - //1. find out all the times for which either time series has a measurement. - // store these times in an array - //2. iterate over the list to drive the addition of the 2 time series. - // There is a getMeasurementByTime method that allows for filling in zeroes - // and for interpolation adn for exact Measurement retrieval. - - MeasuringUnit unit1 = ts1.getMeasuringUnit(); - MeasuringUnit unit2 = ts2.getMeasuringUnit(); - - IrregularTimeSeries combinedTs = new IrregularTimeSeries(unit1); - IrregularTimeSeries newTs = new IrregularTimeSeries(unit1); - - // make sure that ts2 contains the same units; - // this might create an unpleasant side effect, so I convert it back at the end - - if (unit1 != unit2) - { - ts2.convert(unit1); - } - - // insert all of the measurements into the combined time series - combinedTs.insertTimeSeries(ts1); - // System.out.println("combined with ts1 \n " + combinedTs); - - combinedTs.insertTimeSeries(ts2); - // System.out.println("combined with ts1 and ts2 \n" + combinedTs); - - // get the array out of the time series - AbsTimeMeasurement[] combinedArray = combinedTs.getMeasurementArray(); - - - //for now, assume that any values out of range for a particular time series - // = 0.0; - - - boolean allowInterpolation = true; - boolean fillInEndsWithZero = true; - - long desiredTime = -1; - long previousTime = -2; - - for (int i = 0 ; i < combinedArray.length; i++ ) - { - AbsTimeMeasurement currentMeasurement = combinedArray[i]; - - desiredTime = currentMeasurement.getTime(); - - if (desiredTime != previousTime) //don't want duplicate entries, so checking - { - - AbsTimeMeasurement m1 = ts1.getAbsTimeMeasurementByTime(desiredTime, - allowInterpolation, - fillInEndsWithZero); - - AbsTimeMeasurement m2 = ts2.getAbsTimeMeasurementByTime(desiredTime, - allowInterpolation, - fillInEndsWithZero); - double value = m1.getValue() + m2.getValue(); - AbsTimeMeasurement newM = new AbsTimeMeasurement(value, desiredTime, unit1); - newTs.insertMeasurement(newM); - } - - previousTime = desiredTime; - - } //end for i - - - //convert back - might be needed - ts2.convert(unit2); - - return newTs; - - } // end add - - - //--------------------------------------------------------------------- - public void convert(MeasuringUnit newUnit) - { - String header = "TimeSeries.convert(): "; - // System.out.println(header + "is being called for ts = " + _name ); - - // trace(); - - List newMeasurementList = new ArrayList(); - - if (_measuringUnit != newUnit) - { - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement origMeasurement = (Measurement) _measurementList.get(i); - Measurement convertedMeasurement = - Measurement.getConvertedCopy(origMeasurement, newUnit); - - newMeasurementList.add(convertedMeasurement); - - } - - _measuringUnit = newUnit; - _measurementList = newMeasurementList; - } - - } - - //--------------------------------------------------------------------- - - public long getEndTime() - { - long endTime = -1; - if (_measurementList.size() > 0) - { - endTime = getAbsTimeMeasurementByIndex(_measurementList.size() - 1).getTime(); - } - return endTime; - } - - //--------------------------------------------------------------------- - public AbsTimeMeasurement findClosestMeasurementByTime(long targetTime) - { - AbsTimeMeasurement curMeasurement = null; - - AbsTimeMeasurement closestMeasurement = null; - long smallestTimeDiff = -1; - - long previousTimeDiff = -1; - long timeDiff = 0; - - boolean done = false; - - for (int i = 0; !done && i < _measurementList.size(); i++) - { - curMeasurement = (AbsTimeMeasurement) _measurementList.get(i); - - timeDiff = Math.abs( curMeasurement.getTime() - targetTime); - - if ( closestMeasurement == null) //first time - { - smallestTimeDiff = timeDiff; - closestMeasurement = curMeasurement; - } - else //not first time - { - if (timeDiff < smallestTimeDiff) - { - smallestTimeDiff = timeDiff; - closestMeasurement = curMeasurement; - } - else if (timeDiff > previousTimeDiff) //gone too far - { - done = true; - } - } - - previousTimeDiff = timeDiff; - - } - - - return closestMeasurement; - } - - // --------------------------------------------------------------------- - public AbsTimeMeasurement getMinMeasurement(long startTime, long endTime) - { - //could keep track of this internally when items are added or deleted from the list, but then it would have to - // be called everytime something is deleted, or else set a boolean marker to note that something would have to be recalculated in this - // method the next time it is called - AbsTimeMeasurement measurement = null; - - AbsTimeMeasurement minMeasurement = null; - - //String header = "IrregularTimeSeries.getMinMeasurement(): "; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = (AbsTimeMeasurement) _measurementList.get(i); - long time = measurement.getTime(); - - if ( (time >= startTime) && (time <= endTime) ) - { - - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - - ( (minMeasurement == null) || - (measurement.getValue() < minMeasurement.getValue()) - ) - ) - { - minMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - - } //end for i - - return minMeasurement; - - } - - // --------------------------------------------------------------------- - - public AbsTimeMeasurement getMinMeasurement() - { - - return getMinMeasurement(getStartTime(), getEndTime()); - - } - - //--------------------------------------------------------------------- - public AbsTimeMeasurement getMaxMeasurement(long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement maxMeasurement = null; - - double value = 0; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = (AbsTimeMeasurement) _measurementList.get(i); - long time = measurement.getTime(); - - - if ( (time >= startTime) && (time <= endTime) ) - { - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - ( (maxMeasurement == null) || - (measurement.getValue() > maxMeasurement.getValue()) - ) - ) - { - maxMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - } //end for - - - return maxMeasurement; - } - - //--------------------------------------------------------------------- - - public AbsTimeMeasurement getMaxMeasurement() - { - return getMaxMeasurement(getStartTime(), getEndTime()); - } - - //--------------------------------------------------------------------- - - public AbsTimeMeasurement[] getMeasurementArray() - { - AbsTimeMeasurement[] measurementArray = - new AbsTimeMeasurement[_measurementList.size()]; - - for (int index = 0; index < _measurementList.size(); index++) - { - measurementArray[index] = getAbsTimeMeasurementByIndex(index); - } - return measurementArray; - - } //getMeasurementArray - //--------------------------------------------------------------------- - - - public AbsTimeMeasurement getAbsTimeMeasurementByIndex(int index) - { - AbsTimeMeasurement measurement = null; - - measurement = (AbsTimeMeasurement) _measurementList.get(index); - - return measurement; - - } //getMeasurement - - //--------------------------------------------------------------------- - - - public AbsTimeMeasurement getAbsTimeMeasurementByTime(long desiredTime, - boolean interpolate, - boolean fillEndsWithZero) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement curMeasurement = null; - - AbsTimeMeasurement previousMeasurement = null; - AbsTimeMeasurement nextMeasurement = null; - - if ((desiredTime < this.getStartTime()) - || (desiredTime > this.getEndTime())) - { - if (fillEndsWithZero) - { - measurement = new AbsTimeMeasurement(0.0, desiredTime, - this._measuringUnit); - measurement.setIsDefaulted(true); - } - } - - else - // the desired time is in the range of the measurements contained in the - // TimeSeries - { - for (int i = 0; i < _measurementList.size(); i++) - { - curMeasurement = getAbsTimeMeasurementByIndex(i); - if (curMeasurement.getTime() == desiredTime) - { - //found it exactly - measurement = curMeasurement; - break; - } - else if (curMeasurement.getTime() < desiredTime) - { - previousMeasurement = curMeasurement; - //don't break, keep looking - } - else - //curMeasurement.getTime() > time) - { - nextMeasurement = curMeasurement; - - if (interpolate) - { - measurement = AbsTimeMeasurement.interpolate( - previousMeasurement, nextMeasurement, - desiredTime); - } - - break; // it is not in here, since we are past where it - // should be - } - } //end for - - } //end else - - - return measurement; - - } //getMeasurement - - //--------------------------------------------------------------------- - - - public int getMeasurementCount() - { - return _measurementList.size(); - } - - //--------------------------------------------------------------------- - - - public double[] getMeasurementValueArray() throws Exception - { - return getMeasurementValueArray(_measuringUnit); - } //end getMeasurementValueArray - - //--------------------------------------------------------------------- - - public double[] getMeasurementValueArray(MeasuringUnit unit) throws Exception - { - double[] valueArray = new double[_measurementList.size()]; - - if (_measuringUnit != unit) - { - convert(unit); - - } - - for (int index = 0; index < _measurementList.size(); index++) - { - - valueArray[index] = getAbsTimeMeasurementByIndex(index).getValue(); - } - - return valueArray; - - } //end getMeasurementValueArray - - //--------------------------------------------------------------------- - - public MeasuringUnit getMeasuringUnit() - { - return _measuringUnit; - } - - //--------------------------------------------------------------------- - - - public long getStartTime() - { - long startTime = -1; - if (_measurementList.size() > 0) - { - startTime = getAbsTimeMeasurementByIndex(0).getTime(); - } - return startTime; - } - - //--------------------------------------------------------------------- - - - - public void insertMeasurement(AbsTimeMeasurement newMeasurement) - { - //insert the measurement in the list in ascending order of time - boolean inserted = false; - - - //convert to the units of the TimeSeries - //try - { - AbsTimeMeasurement convertedMeasurement = - AbsTimeMeasurement.getConvertedCopy(newMeasurement, - _measuringUnit); - } - //catch (MeasuringUnitConversionException e) - //{ - // e.printStackTrace(); - // throw new Error (e.getMessage()); - //} - - // if the first measurement in the list - if (_measurementList.size() == 0) - { - _measurementList.add(0, newMeasurement); - inserted = true; - } - else if (newMeasurement.getTime() >= this.getEndTime()) - { - - _measurementList.add(newMeasurement); - inserted = true; - } - - - - // if the proper location was not found - if (!inserted) - { - //find the location to insert the measurement within the list - // and insert it - for (int i = 0; i < _measurementList.size() && ( !inserted); i++) - { - AbsTimeMeasurement currentMeasurement = - (AbsTimeMeasurement) _measurementList.get(i); - if (newMeasurement.getTime() < currentMeasurement.getTime() ) - { - _measurementList.add(i, newMeasurement); - inserted = true; - } - } //end for i - } - - return; - - } //insertMeasurement - - //--------------------------------------------------------------------- - - - public void insertTimeSeries(IrregularTimeSeries ts) - { - if (ts != null) - { - try - { - for (int i = 0; i < ts._measurementList.size(); i++) - { - this.insertMeasurement((ts.getAbsTimeMeasurementByIndex(i))); - } - } - catch (Exception e) - { - //can't really happen, since the TimeSeries can't - //hold a measurement of the wrong type - throw new Error("woh! somehow a bad measurement got in here "); - - } - } - } //end insertTimeSeries -// --------------------------------------------------------------------- - public IrregularTimeSeries getSubTimeSeries(long startTime, long endTime) - { - /** - * Return the time series that is within this time window, inclusively. - */ - IrregularTimeSeries newTs = new IrregularTimeSeries(this._measuringUnit); - - for (int i= 0; i < this.getMeasurementCount(); i++) - { - AbsTimeMeasurement m = this.getAbsTimeMeasurementByIndex(i); - long mTime = m.getTime(); - if ( (mTime >= startTime) && (mTime <= endTime) ) - { - newTs.insertMeasurement(m); - } - } - - return newTs; - - } -//--------------------------------------------------------------------- - - - public void setName(String name) - { - _name = name; - } -// --------------------------------------------------------------------- - - public String getName() - { - return _name; - } - //--------------------------------------------------------------------- - - - - public String toString() - { - - StringBuffer buffer = new StringBuffer(); - - if (getName() != null) - { - buffer.append("Name = " + getName() + " "); - } - - buffer.append("Units: " + _measuringUnit + " "); - - - - NumberFormat f = new DecimalFormat("###.##"); - - for (int i = 0; i < _measurementList.size(); i++) - { - double value = getAbsTimeMeasurementByIndex(i).getValue(); - String valueString = f.format(value); - buffer.append(valueString + " "); - } - - - - return buffer.toString(); - } - -// --------------------------------------------------------------------- - public static void main(String[] argStringArray) - { - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - ForecastAdjusterParams params = new ForecastAdjusterParams(); - params.setBlendingHours(5); - params.setBlendingMethod(ForecastInterpolationMethod.DIFFERENCE); - params.setShouldDoAdjustment(true); - - ForecastAdjuster adjuster = new ForecastAdjuster(params); - - long fcstStartTime = System.currentTimeMillis(); - - final long MILLIS_PER_HOUR = 1000 * 3600; - - long obsStartTime = fcstStartTime - (3 * 24 * MILLIS_PER_HOUR); //3 days before fcst start - long obsEndTime = fcstStartTime + (7 * MILLIS_PER_HOUR); // 7 hours after fcst start - - IrregularTimeSeries observedTs = new IrregularTimeSeries(dischargeUnit); - - double[] obsMeasurementValueArray = {18, 19, 20, 22, 24, 28, 33, 28, 39, 40, 41, 43, 53, 57, 41, 29, 29, 28, 27, 26, 26, 24, 28 }; - - int index = 0; - - - - - // load up the observed time series - index = 0; - for (long time = obsStartTime; time <= obsEndTime; time+= MILLIS_PER_HOUR) - { - AbsTimeMeasurement m = new AbsTimeMeasurement(obsMeasurementValueArray[index], time, dischargeUnit); - - observedTs.insertMeasurement(m); - - index++; - if (index == obsMeasurementValueArray.length) - { - index = 0; - } - } - - long subStartTime = obsStartTime + (2 * MILLIS_PER_HOUR); - long subEndTime = obsEndTime - (2 * MILLIS_PER_HOUR); - - IrregularTimeSeries subTimeSeries = observedTs.getSubTimeSeries(subStartTime, subEndTime); - - System.out.println("origObsTimeSeries = " + observedTs); - System.out.println("subObsTimeSeries = " + subTimeSeries); - - - - } - -} //end class TimeSeries diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/IrregularTimeSeriesHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/IrregularTimeSeriesHolder.java deleted file mode 100644 index 29b0af43db..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/IrregularTimeSeriesHolder.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Created on Oct 14, 2003 - * - * - * */ -package ohd.hseb.measurement; - -/** - * @author Chip Gobs - * - * This is a simple Holder class for an IrregularTimeSeries object - */ -public class IrregularTimeSeriesHolder -{ - private IrregularTimeSeries _timeSeries; - - public void setTimeSeries(IrregularTimeSeries timeSeries) - { - _timeSeries = timeSeries; - } - - public IrregularTimeSeries getTimeSeries() - { - return _timeSeries; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/Measurement.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/Measurement.java deleted file mode 100644 index 9980243692..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/Measurement.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * This class is a fundamental class to be used as the basis - * for time series and other measurements. - */ - -package ohd.hseb.measurement; - -//import java.text.*; -import java.util.Date; - -/** - * @author Chip Gobs - * - * - */ -public class Measurement -{ - - - private MeasuringUnit _unit; - private double _value; - - private boolean _interpolated = false; - private boolean _extrapolated = false; - private boolean _defaulted = false; - - private boolean _isMissing = false; - - private double _missingValue = -999.0; - - //conversion for degrees fahrenheit and celsius - private static final double _f_to_c_factor = 5.0/9.0; - private static final double _c_to_f_factor = 9.0/5.0; - - - //consider a separate valid time class - - - //--------------------------------------------------------------- - - public Measurement(double value, MeasuringUnit unit) - { - _value = value; - _unit = unit; - - _isMissing = false; - - if (_unit == null) - { - throw new Error("ERROR: Measurement.Measurement() MeasuringUnit may not be null"); - } - - return; - } - - //--------------------------------------------------------------- - - public Measurement(Measurement measurement) - { - _value = measurement.getValue(); - _unit = measurement.getUnit(); - - _isMissing = measurement.isMissing(); - - return; - } - - - //--------------------------------------------------------------- - public boolean equals(Object object) - { - boolean result = false; - - if (object instanceof Measurement) - { - Measurement m = (Measurement) object; - result = this.equals(m); - } - - return result; - - } - //--------------------------------------------------------------- - - public boolean equals(Measurement measurement) - { - boolean result = false; - - if (this._unit != measurement.getUnit()) - { - measurement = this.getCopy(this._unit); - } - - if (this.getValue() == measurement.getValue()) - { - result = true; - } - - return result; - - } - - //--------------------------------------------------------------- - public static Measurement getConvertedCopy(Measurement origMeasurement, MeasuringUnit toUnit) - { - Measurement newMeasurement = null; - - if (origMeasurement != null) - { - newMeasurement = new Measurement(origMeasurement); - newMeasurement.convert(toUnit); - } - return newMeasurement; - } - - //--------------------------------------------------------------- - - public Measurement getCopy() - { - return getCopy(_unit); - } - //--------------------------------------------------------------- - - public Measurement getCopy(MeasuringUnit unit) - { - return Measurement.getConvertedCopy(this, unit); - } - //--------------------------------------------------------------- - - public MeasuringUnit getUnit() - { - return _unit; - } - - //--------------------------------------------------------------- - - public double getValue() - { - if (_isMissing) - { - _value = _missingValue; - } - - return _value; - } - - //--------------------------------------------------------------- - public double getValue(MeasuringUnit unit) - { - double value = _value; - - if (_isMissing) - { - _value = _missingValue; - value = _value; - } - - else if (_unit != unit) - { - double factor = MeasuringUnit.getConversionFactor(_unit, unit); - value = _value * factor; - } - - return value; - - } - - //--------------------------------------------------------------- - public void setValue(double value) - { - _value = value; - } - - //--------------------------------------------------------------- - public void addMeasurement(Measurement measurement) - { - measurement.convert(_unit); - - this.setValue(this.getValue() + measurement.getValue()); - - } - - //--------------------------------------------------------------- - - - protected void setUnit(MeasuringUnit unit) - { - _unit = unit; - } - - - //--------------------------------------------------------------- - - - // public void convert(MeasuringUnit toUnit) throws - // MeasuringUnitConversionException - protected void convert(MeasuringUnit toUnit) - { - String header = "Measurement.convert(): "; - - MeasuringUnit fromUnit = this.getUnit(); - if (fromUnit.getType() == toUnit.getType()) - { - if (fromUnit == toUnit) //do nothing - { - // no conversion needed - } - else if (fromUnit.getType() == MeasuringUnitType.temperature) - { - if (fromUnit.equals(MeasuringUnit.degreesFahrenheit) && - (toUnit.equals(MeasuringUnit.degreesCelsius) ) ) - { - _value = fahrenHeightToCelsius(_value); - _unit = toUnit; - } - else if (fromUnit.equals(MeasuringUnit.degreesCelsius) && - (toUnit.equals(MeasuringUnit.degreesFahrenheit) ) ) - { - _value = celsiusToFahrenheit(_value); - _unit = toUnit; - } - } - else // multiplicative conversion - { - double factor = MeasuringUnit.getConversionFactor(fromUnit, toUnit); - - // System.out.println(header + " from " + _value + " in " + fromUnit + - // " to " + (_value * factor) + " in " + toUnit ); - - - _value = _value * factor; - _unit = toUnit; - - } - } - else //can't convert these types - { - //throw new MeasuringUnitConversionException(fromUnit, toUnit); - throw new Error("Bogus Unit conversion attempt from " + - fromUnit.getName() + - " to " + toUnit.getName() ); - } - } //end convert - - //--------------------------------------------------------------- - private double fahrenHeightToCelsius(double origValue) - { - double newValue = _f_to_c_factor * ( origValue - 32); - - return newValue; - } - - private double celsiusToFahrenheit(double origValue) - { - double newValue = (_c_to_f_factor * origValue) + 32; - - return newValue; - } - - //--------------------------------------------------------------- - - - public String toString() - { - String string = null; - - if (! _isMissing) - { - string = _value + " in " + _unit.getName(); - } - else - { - string = "MISSING"; - } - - return string; - } - - - //--------------------------------------------------------------- - - public void setIsInterpolated(boolean interpolated) { - this._interpolated = interpolated; - } - //--------------------------------------------------------------- - - public boolean isInterpolated() - { - return _interpolated; - } - - //--------------------------------------------------------------- - - public void setIsExtrapolated(boolean extrapolated) - { - this._extrapolated = extrapolated; - } - - //--------------------------------------------------------------- - - public boolean isExtrapolated() - { - return _extrapolated; - } - - //--------------------------------------------------------------- - - public void setIsDefaulted(boolean defaulted) - { - this._defaulted = defaulted; - } - - //--------------------------------------------------------------- - - public boolean isDefaulted() - { - return _defaulted; - } - - //--------------------------------------------------------------- - - public void setIsMissing(boolean isMissing) - { - _isMissing = isMissing; - - _value = _missingValue; - } - - //--------------------------------------------------------------- - public boolean isMissing() - { - return _isMissing; - } - - //--------------------------------------------------------------- - - public int hashCode() - { - int value = 0; - - MeasuringUnit standardUnit = MeasuringUnit.getStandardUnitForUnit(this.getUnit()); - value = (int) ( this.getValue(standardUnit)); - - return value; - } - //--------------------------------------------------------------- - - public static void main (String[] args) throws Exception - { - AbsTimeMeasurement m1 = new AbsTimeMeasurement(3.0, - new Date().getTime(), - MeasuringUnit.feet); - - System.out.println(m1); - - AbsTimeMeasurement m2 = AbsTimeMeasurement.getConvertedCopy(m1, MeasuringUnit.inches); - - System.out.println(m2); - - } //end main - - -} //end class Measurement diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementHolder.java deleted file mode 100644 index 95c6436fc7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementHolder.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on Feb 9, 2004 - * - * - */ -package ohd.hseb.measurement; - - -/** - * @author GobsC - * - * This is a holder class for Measurement objects. - */ -public class MeasurementHolder -{ - - private Measurement _measurement; - - - public Measurement getMeasurement() - { - return _measurement; - } - - - public void setMeasurement(Measurement measurement) - { - _measurement = measurement; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPoint.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPoint.java deleted file mode 100644 index 7f1e72d396..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPoint.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Created on Jul 13, 2004 - * - * - */ -package ohd.hseb.measurement; - -/** - * @author GobsC - * - * - */ -public class MeasurementPoint -{ - private Measurement _xMeasurement; - private Measurement _yMeasurement; - - - public MeasurementPoint(Measurement measurement1, Measurement measurement2) - { - _xMeasurement = measurement1; - _yMeasurement = measurement2; - } - -// ------------------------------------------------------------------------------- - - public MeasurementPoint(MeasurementPoint point, MeasuringUnit unit1, MeasuringUnit unit2) - { - _xMeasurement = point.getXMeasurement().getCopy(unit1); - _yMeasurement = point.getYMeasurement().getCopy(unit2); - } - -// ------------------------------------------------------------------------------- - public void setXMeasurement(Measurement xMeasurement) - { - _xMeasurement = xMeasurement; - } -// ------------------------------------------------------------------------------- - - public Measurement getXMeasurement() - { - return _xMeasurement; - } -// ------------------------------------------------------------------------------- - - public void setYMeasurement(Measurement yMeasurement) - { - _yMeasurement = yMeasurement; - } -// ------------------------------------------------------------------------------- - - public Measurement getYMeasurement() - { - return _yMeasurement; - } -// ------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPointComparator.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPointComparator.java deleted file mode 100644 index 7e19b937b0..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPointComparator.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Created on Jul 15, 2004 - * - * - */ -package ohd.hseb.measurement; - -import java.util.Comparator; - -/** - * @author GobsC - * - * - */ -public class MeasurementPointComparator implements Comparator -{ - - private boolean _compareX = false; - private boolean _ascendingOrder = true; - - public MeasurementPointComparator(boolean compareX, boolean ascendingOrder ) - { - _compareX = compareX; - _ascendingOrder = ascendingOrder; - } - - public int compare(Object uhg1, Object uhg2) - { - int result = 0; - - MeasurementPoint point1 = (MeasurementPoint) uhg1; - MeasurementPoint point2= (MeasurementPoint) uhg2; - - Measurement m1 = null; - Measurement m2 = null; - - if (_compareX) - { - m1 = point1.getXMeasurement(); - m2 = point2.getXMeasurement(); - } - else - { - m1 = point1.getYMeasurement(); - m2 = point2.getYMeasurement(); - } - - //pick a standard unit - MeasuringUnit unit = m1.getUnit(); - - - double value1 = m1.getValue(unit); - double value2 = m2.getValue(unit); - - if (value1 < value2) - { - result = -1; - } - else if (value1 == value2) - { - result = 0; - } - else // value1 > value2 - { - result = 1; - } - - if (! _ascendingOrder) - { - result *= -1; - } - - return result; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPointSeries.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPointSeries.java deleted file mode 100644 index 46df936d49..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasurementPointSeries.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Created on Jul 14, 2004 - * - * - */ -package ohd.hseb.measurement; - - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -/** - * @author Chip Gobs - * - * This class contains a collection of MeasurementPoint objects and can - * operate on the collection. - */ -public class MeasurementPointSeries -{ - // ------------------------------------------------------------------------ - - private List _measurementPointList = null; - - private MeasuringUnit _xMeasuringUnit = null; - private MeasuringUnit _yMeasuringUnit = null; - - private Comparator _comparator; - - // ------------------------------------------------------------------------ - - public MeasurementPointSeries(MeasuringUnit xMeasuringUnit, MeasuringUnit yMeasuringUnit, Comparator comparator) - { - _xMeasuringUnit = xMeasuringUnit; - _yMeasuringUnit = yMeasuringUnit; - - _comparator = comparator; - - _measurementPointList = new ArrayList(); - } - - // ------------------------------------------------------------------------ - - public void setComparator(Comparator comparator) - { - _comparator = comparator; - } - - // ------------------------------------------------------------------------ - - public Comparator getComparator() - { - return _comparator; - } - - // ------------------------------------------------------------------------ - - // ------------------------------------------------------------------------ - public void addPoint(MeasurementPoint newPoint) - { - newPoint = new MeasurementPoint(newPoint, _xMeasuringUnit, _yMeasuringUnit); - - boolean added = false; - for (int i = 0; i < _measurementPointList.size() && !added; i++) - { - MeasurementPoint existingPoint = (MeasurementPoint) _measurementPointList.get(i); - - int result = _comparator.compare(newPoint, existingPoint); - - if ((result == -1) || (result == 0)) - { - _measurementPointList.add(i, newPoint); - added = true; - } - } - - if (! added) - { - _measurementPointList.add(newPoint); - } - - return; - } - // ------------------------------------------------------------------------ - public void removePoint(MeasurementPoint point) - { - _measurementPointList.remove(point); - } - - // ------------------------------------------------------------------------ - public void clear() - { - _measurementPointList.clear(); - } - - // ------------------------------------------------------------------------ - - public int size() - { - int result = 0; - - if (_measurementPointList != null) - { - result = _measurementPointList.size(); - } - - return result; - } - // ------------------------------------------------------------------------ - - public MeasurementPoint getPoint(int index) - { - return (MeasurementPoint) _measurementPointList.get(index); - } - // ------------------------------------------------------------------------ - - public Measurement getMaxXMeasurement() - { - return getMaxMeasurement(true); - } - - // ------------------------------------------------------------------------ - - public Measurement getMinXMeasurement() - { - return getMinMeasurement(true); - } - - // ------------------------------------------------------------------------ - - - public Measurement getMaxYMeasurement() - { - return getMaxMeasurement(false); - - } - - // ------------------------------------------------------------------------ - - public Measurement getMinYMeasurement() - { - return getMinMeasurement(false); - } - - // ------------------------------------------------------------------------ - - public Measurement getMaxMeasurement(boolean isXOrdinate) - { - Measurement maxMeasurement = null; - Measurement pointMeasurement = null; - - MeasuringUnit unit = null; - - // determine which units we are dealing with - if (isXOrdinate) - { - unit = _xMeasuringUnit; - } - else - { - unit = _yMeasuringUnit; - } - - - - // look at each measurement point to determine the max - for (int i = 0; i < size(); i++) - { - MeasurementPoint point = (MeasurementPoint) _measurementPointList.get(i); - - if (isXOrdinate) - { - pointMeasurement = point.getXMeasurement(); - } - else - { - pointMeasurement = point.getYMeasurement(); - } - - if (maxMeasurement == null) - { - maxMeasurement = pointMeasurement; - } - else //maxMeasurement != null - { - if (pointMeasurement != null) - { - if (pointMeasurement.getValue(unit) > maxMeasurement.getValue(unit)) - { - maxMeasurement = pointMeasurement; - } - } - } - - } - - return maxMeasurement; - - } - - - - // ------------------------------------------------------------------------ - public Measurement getMinMeasurement(boolean isXOrdinate) - { - Measurement minMeasurement = null; - Measurement pointMeasurement = null; - - MeasuringUnit unit = null; - - // determine which units we are dealing with - if (isXOrdinate) - { - unit = _xMeasuringUnit; - } - else - { - unit = _yMeasuringUnit; - } - - - - // look at each measurement point to determine the max - for (int i = 0; i < size(); i++) - { - MeasurementPoint point = (MeasurementPoint) _measurementPointList.get(i); - - - - if (isXOrdinate) - { - pointMeasurement = point.getXMeasurement(); - } - else - { - pointMeasurement = point.getYMeasurement(); - } - - if (minMeasurement == null) - { - minMeasurement = pointMeasurement; - } - else //minMeasurement != null - { - if (pointMeasurement != null) - { - if (pointMeasurement.getValue(unit) < minMeasurement.getValue(unit)) - { - minMeasurement = pointMeasurement; - } - } - } - - } - - return minMeasurement; - - } - // ------------------------------------------------------------------------ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0 ; i < size(); i++) - { - MeasurementPoint point = getPoint(i); - - Measurement xMeasurement = point.getXMeasurement(); - Measurement yMeasurement = point.getYMeasurement(); - - buffer.append("x = " + xMeasurement + " y = " + yMeasurement + "\n"); - - } - - return buffer.toString(); - - } - - // ------------------------------------------------------------------------ - public static void main(String[] argStringArray) - { - MeasuringUnit xUnit = MeasuringUnit.hours; - MeasuringUnit yUnit = MeasuringUnit.cfs; - - boolean compareXValues = true; - boolean ascendingOrder = true; - - Comparator comparator = new MeasurementPointComparator(compareXValues, ascendingOrder); - - MeasurementPointSeries measurementPointSeries = new MeasurementPointSeries(xUnit, yUnit, comparator); - - int measurementCount = 10; - - for (int i = 0 ; i < measurementCount; i++) - { - Measurement m1 = new Measurement(measurementCount - i - 1, xUnit); - Measurement m2 = new Measurement(2*i, yUnit); - - MeasurementPoint point = new MeasurementPoint(m1, m2); - - measurementPointSeries.addPoint(point); - } - - - - for (int i = 0 ; i < measurementPointSeries.size(); i++) - { - MeasurementPoint point = measurementPointSeries.getPoint(i); - - Measurement xMeasurement = point.getXMeasurement(); - Measurement yMeasurement = point.getYMeasurement(); - - System.out.println("x = " + xMeasurement + " y = " + yMeasurement); - } - - Measurement minXMeasurement = measurementPointSeries.getMinXMeasurement(); - Measurement minYMeasurement = measurementPointSeries.getMinYMeasurement(); - - Measurement maxXMeasurement = measurementPointSeries.getMaxXMeasurement(); - Measurement maxYMeasurement = measurementPointSeries.getMaxYMeasurement(); - - System.out.println("minX = " + minXMeasurement + " minY = " + minYMeasurement); - System.out.println("maxX = " + maxXMeasurement + " maxY = " + maxYMeasurement); - } - // ------------------------------------------------------------------------ - -} //end MeasurementPointSeries diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnit.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnit.java deleted file mode 100644 index bc535c3cdf..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnit.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * To change the template for this generated file go to - * - */ -package ohd.hseb.measurement; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author gobsc - * - * This is basically an enum of all possible units of measure, but it is also - * smart enough to help handle unit conversions. - */ -public class MeasuringUnit -{ - - //conversion factor map - private static Map _conversionFactorMap = new HashMap(); - - - //conversion standard map - private static Map _conversionStandardMap= new HashMap(); - - // Note: the standard unit for a particular MeasuringUnitType, MUST be the first - //one of that type created here. Otherwise, a circular lookup dependency will be created when - //when the code tries to set up Maps used to convert first to the standard unit (which wouldn't exist yet) - // and then to the desired unit. - // In the private constructor, having a conversion factor of 1.0 is used to identify the unit - // as the standard of that MeasuringUnitType. - - - //discharge types - public static final MeasuringUnit cfs = new MeasuringUnit("cfs", MeasuringUnitType.discharge, 1.0); - public static final MeasuringUnit kcfs = new MeasuringUnit("kcfs", MeasuringUnitType.discharge, 1000.0); - public static final MeasuringUnit cms = new MeasuringUnit("cms", MeasuringUnitType.discharge, 35.314666572 ); - - //length types - public static final MeasuringUnit meters = new MeasuringUnit("meters", MeasuringUnitType.length, 1.0); - public static final MeasuringUnit cm = new MeasuringUnit("cm", MeasuringUnitType.length, 0.01); - public static final MeasuringUnit mm = new MeasuringUnit("mm", MeasuringUnitType.length, 0.001); - public static final MeasuringUnit inches = new MeasuringUnit("inches", MeasuringUnitType.length, 0.0254); - public static final MeasuringUnit feet = new MeasuringUnit("feet", MeasuringUnitType.length, 0.3048); - - //relative time types - public static final MeasuringUnit hours = new MeasuringUnit("hours", MeasuringUnitType.elapsedTime, 1.0); - public static final MeasuringUnit days = new MeasuringUnit("days", MeasuringUnitType.elapsedTime, 24.0); - - //temperature types - // This implementation does NOT work right for Fahrenheit to/from Celsius conversion because - // one needs to add or subtract 32 to convert. Address this later, when needed. - // Consider adding a larger, unit conversion class - public static final MeasuringUnit degreesFahrenheit = new MeasuringUnit("degrees F", MeasuringUnitType.temperature, 1.0); - public static final MeasuringUnit degreesCelsius = - new MeasuringUnit("degrees C", MeasuringUnitType.temperature, 0); - - - //speed types - public static final MeasuringUnit mph = new MeasuringUnit("mph", MeasuringUnitType.speed, 1.0); - public static final MeasuringUnit knots = new MeasuringUnit("knots", MeasuringUnitType.speed, 1.150779448 ); - public static final MeasuringUnit kph = new MeasuringUnit("kph", MeasuringUnitType.speed, 0.621371192); - - //direction - public static final MeasuringUnit degrees = new MeasuringUnit("degrees", MeasuringUnitType.elapsedTime, 1.0); - - - - //unitless - public static final MeasuringUnit unitless = - new MeasuringUnit("unitless", MeasuringUnitType.unitless, 1.0); - - - // member variables - private MeasuringUnitType _type; - private String _name; - - //note, we simply need to convert to a standard and convert from the standard, - // so that we don't have (N*N) -N conversions, just 2*N conversions - - // -------------------------------------------------------------------- - private MeasuringUnit(String unitName, - MeasuringUnitType type, - double conversionFactor) - { - _name = unitName; - _type = type; - - - String toStandardKey = null; - String fromStandardKey = null; - - if (conversionFactor == 1.0) - { - // this is the standard unit - _conversionStandardMap.put(type, this); - - toStandardKey = getConversionKey(unitName,unitName); - fromStandardKey = getConversionKey(unitName, unitName); - - addConversionFactor(toStandardKey, conversionFactor); - addConversionFactor(fromStandardKey, 1.0/conversionFactor); - } - else - { - MeasuringUnit standardUnit = getStandardUnitForType(type); - toStandardKey = getConversionKey(unitName,standardUnit.getName()); - fromStandardKey = getConversionKey(standardUnit.getName(), unitName); - - - addConversionFactor(toStandardKey, conversionFactor); - addConversionFactor(fromStandardKey, 1.0/conversionFactor); - } - - } //end constructor - - - public String getName() - { - return _name; - } - - public MeasuringUnitType getType() - { - return _type; - } - - public String toString() - { - return _name; - } - - public static double getConversionFactor(MeasuringUnit fromUnit, - MeasuringUnit toUnit) - { - MeasuringUnit standardUnit = getStandardUnitForType(fromUnit.getType()); - double conversionFactor = 1.0; - - if (fromUnit == toUnit) - { - conversionFactor = 1.0; - } - else - { - - String conversionKey1 = getConversionKey(fromUnit, standardUnit); - Double conversionFactor1 = (Double)_conversionFactorMap.get(conversionKey1); - - String conversionKey2 = getConversionKey(standardUnit, toUnit); - Double conversionFactor2 = (Double)_conversionFactorMap.get(conversionKey2); - conversionFactor = conversionFactor1.doubleValue() * - conversionFactor2.doubleValue(); - - } - - return conversionFactor; - } //end getConversionFactor - - protected static MeasuringUnit getStandardUnitForType(MeasuringUnitType type) - { - MeasuringUnit unit = (MeasuringUnit) _conversionStandardMap.get(type); - - return unit; - - } //end getStandardUnitForType - - protected static MeasuringUnit getStandardUnitForUnit(MeasuringUnit unit) - { - MeasuringUnitType type = unit.getType(); - MeasuringUnit standardUnit = (MeasuringUnit) _conversionStandardMap.get(type); - - return standardUnit; - - } //end getStandardUnitForType - - - /* - private static void addConversionFactor(MeasuringUnit fromUnit, - MeasuringUnit toUnit, - double conversionFactor) - { - String conversionKey = getConversionKey(fromUnit, toUnit); - addConversionFactor(conversionKey, conversionFactor); - - return; - } - */ - - private static void addConversionFactor(String conversionKey, double conversionFactor) - { - _conversionFactorMap.put(conversionKey, new Double(conversionFactor)); - - return; - } - - - private static String getConversionKey(MeasuringUnit fromUnit, MeasuringUnit toUnit) - { - return getConversionKey(fromUnit.getName(), toUnit.getName()); - } - - private static String getConversionKey(String fromUnitName, String toUnitName) - { - return fromUnitName + "|" + toUnitName; - } - -} //end MeasuringUnit diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnitConversionException.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnitConversionException.java deleted file mode 100644 index 80eab5edfa..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnitConversionException.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.measurement; -/** - * @author gobsc - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class MeasuringUnitConversionException extends Exception -{ - public MeasuringUnitConversionException(MeasuringUnit fromUnit, MeasuringUnit toUnit) - { - super("Unable to convert " + fromUnit.getName() + " to " + toUnit.getName()); - - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnitType.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnitType.java deleted file mode 100644 index b66486ace0..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/MeasuringUnitType.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * - */ -package ohd.hseb.measurement; -/** - * @author gobsc - * - * This class is basically an enum for the possible types of - * MeasuringUnits. distance, volume, flow - */ -public class MeasuringUnitType -{ - - public static final MeasuringUnitType length = new MeasuringUnitType("length"); - public static final MeasuringUnitType discharge = new MeasuringUnitType("discharge"); - public static final MeasuringUnitType volume = new MeasuringUnitType("volume"); - public static final MeasuringUnitType elapsedTime = new MeasuringUnitType("elapsedTime"); - public static final MeasuringUnitType temperature = new MeasuringUnitType("temperature"); - public static final MeasuringUnitType speed = new MeasuringUnitType("speed"); - public static final MeasuringUnitType direction = new MeasuringUnitType("direction"); - - public static final MeasuringUnitType unitless = new MeasuringUnitType("unitless"); - - - private String _name = null; - - //private constructor - private MeasuringUnitType(String typeName) - { - _name = typeName; - } - - public String getName() - { - return _name; - } - - public String toString() - { - return _name; - - } //toString - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/RegularTimeSeries.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/RegularTimeSeries.java deleted file mode 100644 index 53304a9c7f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/RegularTimeSeries.java +++ /dev/null @@ -1,1145 +0,0 @@ -/* - * Created on Oct 15, 2003 - * - * - * - */ -package ohd.hseb.measurement; - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.TimeHelper; - -/** - * @author Chip Gobs - * - * - */ -public class RegularTimeSeries -{ - private static final double _missingValue = -999.0; - private static final double _otherMissingValue = -9999.0; - private static final long _millisPerHour = 1000 * 60 * 60; - - private static final String _missingString = "MSG"; - - private String _name = null; - private long _startTime = 0; - private long _endTime = 0; - private int _intervalInHours = 1; - private long _shiftedTimeInMillis = 0; - private long _intervalInMillis = _intervalInHours * _millisPerHour; - private List _measurementList = new ArrayList(); - private MeasuringUnit _measuringUnit = null; - - - -// ----------------------------------------------------------------------------- - - public RegularTimeSeries(RegularTimeSeries originalTimeSeries) - { - - this(originalTimeSeries._startTime, - originalTimeSeries._endTime, - originalTimeSeries._intervalInHours, - originalTimeSeries._measuringUnit, -1.0); - - _shiftedTimeInMillis = originalTimeSeries._shiftedTimeInMillis; - - List origMeasurementList = originalTimeSeries._measurementList; - - for (int i = 0; i < origMeasurementList.size(); i++) - { - Measurement origMeasurement = (Measurement) originalTimeSeries._measurementList.get(i); - Measurement measurement = new Measurement(origMeasurement); - - setMeasurementByIndex(measurement, i); - } - - return; - } - -// ----------------------------------------------------------------------------- - - public RegularTimeSeries(long startTime, - long endTime, - int intervalInHours, - MeasuringUnit unit) - { - - // defaults to initialValue = 0.0; - this(startTime, endTime, intervalInHours, unit, 0.0); - - } - -// ----------------------------------------------------------------------------- - - public RegularTimeSeries(long startTime, - long endTime, - int intervalInHours, - MeasuringUnit unit, - double initialValue) - { - //System.out.println("RegularTimeSeries c-tor"); - _intervalInHours = intervalInHours; - _intervalInMillis = _intervalInHours * _millisPerHour; - - _startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, - _intervalInHours); - - _endTime = TimeHelper.truncateTimeInMillisToNearestHour(endTime, - _intervalInHours); - - - // System.out.println( "RegularTimeSeries ctor _startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_startTime)); - // System.out.println( "RegularTimeSeries ctor _endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_endTime)); - - - - _measuringUnit = unit; - - long numberOfIntervals = (_endTime - _startTime) / _intervalInMillis; - numberOfIntervals++; //if endTime == startTime, that is 1 interval - - //long currentTime = startTime; - for (int i = 0; i < numberOfIntervals; i++) - { - Measurement newMeasurement = new Measurement(initialValue, unit); - _measurementList.add(i, newMeasurement); - } - - } //end RegularTimeSeries() - -// --------------------------------------------------------------------------- - public void shiftStartEndTimeHours(int hoursShift) - { - - long timeDiff = hoursShift * _millisPerHour; - - _startTime += timeDiff; - _endTime += timeDiff; - - _shiftedTimeInMillis = timeDiff; - - return; - } - -// --------------------------------------------------------------------------- - - public static RegularTimeSeries add(RegularTimeSeries ts1, RegularTimeSeries ts2) - { - long startTime1 = ts1.getStartTime(); - long startTime2 = ts2.getStartTime(); - - long endTime1 = ts1.getEndTime(); - long endTime2 = ts2.getEndTime(); - - int intervalInHours = ts1.getIntervalInHours(); - long intervalInMillis = intervalInHours * _millisPerHour; - - MeasuringUnit unit = ts1.getMeasuringUnit(); - ts2.convert(unit); - - long startTime = Math.min(startTime1, startTime2); - long endTime = Math.max(endTime1, endTime2); - - // fit the 2 time series to each other - ts1.stretchTimeSeries(startTime, endTime, 0); - ts2.stretchTimeSeries(startTime, endTime, 0); - - - //create the new time series - RegularTimeSeries newTs = new RegularTimeSeries(startTime, endTime, - intervalInHours, - unit); - - - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement m1 = ts1.getMeasurementByTime(time); - Measurement m2 = ts2.getMeasurementByTime(time); - - double value1 = m1.getValue(); - double value2 = m2.getValue(); - - if ( (! m1.isMissing()) && (!m2.isMissing()) ) - { - double value = value1 + value2; - Measurement newMeasurement = new Measurement (value, unit); - newTs.setMeasurementByTime(newMeasurement, time); - } - else - { - Measurement newMeasurement = new Measurement (0.0, unit); - newMeasurement.setIsMissing(true); - newTs.setMeasurementByTime(newMeasurement, time); - } - } - - return newTs; - } -// --------------------------------------------------------------------------- - public RegularTimeSeries copy() - { - RegularTimeSeries newTs = - new RegularTimeSeries(this.getStartTime(), - this.getEndTime(), - this.getIntervalInHours(), - this.getMeasuringUnit()); - - for (int i=0; i < this._measurementList.size(); i++) - { - Measurement m = (Measurement) this._measurementList.get(i); - newTs.setMeasurementByIndex( m, i); - - } - - return newTs; - - } - -// --------------------------------------------------------------------------- - - - public void convert(MeasuringUnit newUnit) - { - String header = "RegularTimeSeries.convert(): "; - // System.out.println(header + " ts name = " + _name); - // trace(); - - List newMeasurementList = new ArrayList(); - - if (_measuringUnit != newUnit) - { - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement origMeasurement = (Measurement) _measurementList.get(i); - Measurement convertedMeasurement = - Measurement.getConvertedCopy(origMeasurement, newUnit); - - newMeasurementList.add(convertedMeasurement); - - } - - _measuringUnit = newUnit; - _measurementList = newMeasurementList; - } - - } -// ----------------------------------------------------------------------------- - public void stretchTimeSeries(long newStartTime, long endStartTime, double fillInValue) - { - prependTimeSeries(newStartTime, fillInValue); - extendTimeSeries(endStartTime, fillInValue); - - return; - } - -// ----------------------------------------------------------------------------- - public void trimTimeSeriesAtStart(long newStartTime) - { - // round off the newEndTime to the nearest hour - // if it is not already rounded, then add an hour to the rounded result - long newRoundedStartTime = TimeHelper.truncateTimeInMillisToNearestHour(newStartTime, 1); - - if (newRoundedStartTime != newStartTime) - { - newRoundedStartTime += _millisPerHour; - } - - - // remove measurements from the beginning of the list - if (newRoundedStartTime > _startTime) - { - long hoursDiff = (newRoundedStartTime - _startTime) / _millisPerHour; - for (int i = 0; i < hoursDiff; i++) - { - //remove from the beginning of the list - _measurementList.remove(0); - } - - _startTime = newRoundedStartTime; - } - - return; - } - -// ----------------------------------------------------------------------------- - public void prependTimeSeries(long newStartTime) - { - prependTimeSeries(newStartTime, 0.0); - - } - - public void prependTimeSeries(long newStartTime, double fillInValue) - { - // round off the newEndTime to the nearest hour - // if it is not already rounded, then add an hour to the rounded result - long roundedStartTime = TimeHelper.truncateTimeInMillisToNearestHour(newStartTime, 1); - - if (roundedStartTime != newStartTime) - { - roundedStartTime += _millisPerHour; - } - - - // add measurements to the beginning of the list - if (roundedStartTime < _startTime) - { - long hoursDiff = (_startTime - roundedStartTime) / _millisPerHour; - for (int i = 0; i < hoursDiff; i++) - { - Measurement newMeasurement = new Measurement(fillInValue, _measuringUnit); - - //add to the beginning of the list - _measurementList.add(0, newMeasurement); - } - - _startTime = roundedStartTime; - } - - } //end prependTimeSeries() - -// --------------------------------------------------------------------------- - public void extendTimeSeries(long newEndTime) - { - extendTimeSeries(newEndTime, 0.0); - } - - public void extendTimeSeries(long newEndTime, double fillInValue) - { - - // round off the newEndTime to the nearest hour - // if it is not already rounded, then add an hour to the rounded result - long roundedEndTime = TimeHelper.truncateTimeInMillisToNearestHour(newEndTime, 1); - - if (roundedEndTime != newEndTime) - { - roundedEndTime+= _millisPerHour; - } - - - // add measurements to the end of the list - if (roundedEndTime > _endTime) - { - long hoursDiff = (roundedEndTime - _endTime) / _millisPerHour; - for (int i = 0; i < hoursDiff; i++) - { - Measurement newMeasurement = new Measurement(fillInValue, _measuringUnit); - - //add to the end of the list - _measurementList.add(newMeasurement); - } - - _endTime = roundedEndTime; - } - - - - } //end extendTimeSeries() -// --------------------------------------------------------------------------- - public void setName(String name) - { - _name = name; - } -// --------------------------------------------------------------------------- - - public String getName() - { - return _name; - } -// --------------------------------------------------------------------------- - - public int getMeasurementCount() - { - return _measurementList.size(); - } - -// -------------------------------------------------------- - - public Measurement getMeasurementByIndex(int index) - { - /* - if (index >= _measurementList.size()) - { - - } - */ - - return (Measurement)_measurementList.get(index); - } -// -------------------------------------------------------- - - public double getMeasurementValueByIndex(int index, MeasuringUnit unit) - { - double value = _missingValue; - - Measurement m = getMeasurementByIndex(index); - if (m != null) - { - m = m.getCopy(unit); - value = m.getValue(); - } - else - { - System.err.println("RegularTimeSeries.getMeasurementValueByIndex(): no measurement for index = " + index); - } - - return value; - } - -// -------------------------------------------------------- - public double getMeasurementValueByTime(long time, MeasuringUnit unit) - { - double value = _missingValue; - - Measurement m = getMeasurementByTime(time); - - if (m != null) - { - m = m.getCopy(unit); - value = m.getValue(); - } - else - { - System.err.println("RegularTimeSeries.getMeasurementValueByTime(): no measurement for time = " + - DbTimeHelper.getDateTimeStringFromLongTime(time)); - } - return value; - } - -// -------------------------------------------------------- - - public long getMeasurementTimeByIndex(int index) - { - long newTime = _startTime + (index * _intervalInMillis); - - return newTime; - } - -// -------------------------------------------------------- - - private int getMeasurementIndexByTime(long time) - { - int index = -1; - - String header = "RegularTimeSeries.getMeasurementIndexByTime()"; - - - //System.out.println(header + "time 1 = " + time); - - //System.out.println(header + "orig time = " + DbTimeHelper.getDateTimeStringFromLongTime(time)); - - time = TimeHelper.truncateTimeInMillisToNearestHour(time, _intervalInHours) + _shiftedTimeInMillis; - - //System.out.println(header + "adjusted time = " + DbTimeHelper.getDateTimeStringFromLongTime(time)); - - //System.out.println(header + "startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_startTime)); - //System.out.println(header + "endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_endTime)); - // - if ( (time >= _startTime) && - (time <= _endTime) ) - { - long intervalsDifference = (time - _startTime) / _intervalInMillis; - index = (int) intervalsDifference; - - /* - if (index >= _measurementList.size()) - { - System.out.println("Problem is here"); - System.out.println("Time Series name = " + getName()); - } - */ - - } - - //System.out.println(header + "index = " + index); - - return index; - } - -// -------------------------------------------------------- - - private void setMeasurementByIndex(Measurement measurement, int index) - { - Measurement newMeasurement = - Measurement.getConvertedCopy(measurement, - _measuringUnit); - _measurementList.remove(index); - _measurementList.add(index, newMeasurement); - - return; - } - -// -------------------------------------------------------- - - public void setMeasurementByTime(Measurement measurement, long time) - { - - if (time > _endTime) - { - // System.out.println("RegularTimeSeries.setMeasurementByTime(): Extending the timeSeries"); - extendTimeSeries(time); - } - else if (time < _startTime) - { - // System.out.println("RegularTimeSeries.setMeasurementByTime(): Prepending the timeSeries"); - prependTimeSeries(time); - } - - int index = getMeasurementIndexByTime(time); - - // System.out.println("RegularTimeSeries.setMeasurementByTime(): time = " + - // DbTimeHelper.getDateTimeStringFromLongTime(time) + " index = " + index); - - if (index != -1) - { - setMeasurementByIndex(measurement, index); - } - - return; - } -// -------------------------------------------------------- - /* - private void setMeasurementValueByIndex(double value, int index) - { - // System.out.println(" ** RegularTimeSeries.setMeasurementValueByIndex()"); - - Measurement measurement = getMeasurementByIndex(index); - measurement.setValue(value); - } - */ -// -------------------------------------------------------- - /* - private void setMeasurementValueByTime(double value, long time) - { - // System.out.println(" ** RegularTimeSeries.setMeasurementValueByTime()"); - Measurement measurement = getMeasurementByTime(time); - measurement.setValue(value); - } - */ -// -------------------------------------------------------- - - public Measurement getMeasurementByTime(long time) - { - Measurement measurement = null; - int index = -1; - - index = getMeasurementIndexByTime(time); - - if (index != -1) - { - measurement = getMeasurementByIndex(index); - } - - return measurement; - } - - public AbsTimeMeasurement getAbsTimeMeasurementByTime(long time) - { - Measurement measurement = null; - AbsTimeMeasurement absTimeMeasurement = null; - - - measurement = getMeasurementByTime(time); - if (measurement != null) - { - absTimeMeasurement = new AbsTimeMeasurement(measurement, time); - } - - return absTimeMeasurement; - } - -// -------------------------------------------------------- - - public AbsTimeMeasurement getAbsTimeMeasurementByIndex(int index) - { - Measurement measurement = (Measurement)_measurementList.get(index); - long time = getMeasurementTimeByIndex(index); - - AbsTimeMeasurement absTimeMeasurement = new AbsTimeMeasurement(measurement, time); - - return absTimeMeasurement; - - } - -// -------------------------------------------------------- - - public RegularTimeSeries getSubTimeSeries(long startTime, long endTime) - { - /** - * Return the time series that is within this time window, inclusively. - */ - RegularTimeSeries newTs = null; - - newTs = new RegularTimeSeries(startTime, - endTime, - this.getIntervalInHours(), - this.getMeasuringUnit() ); - - boolean firstTime = true; - for (int i= 0; i < this.getMeasurementCount(); i++) - { - AbsTimeMeasurement m = this.getAbsTimeMeasurementByIndex(i); - - //nulls are not possible, so don't check for them - - long mTime = m.getTime(); - if ( (mTime >= startTime) && (mTime <= endTime) ) - { - if (firstTime) - { - newTs = new RegularTimeSeries(mTime, - mTime, - this.getIntervalInHours(), - this.getMeasuringUnit() ); - firstTime = false; - - } - newTs.setMeasurementByTime(m, mTime); - } - } - - return newTs; - - } -// -------------------------------------------------------- -/* - private void setStartTime(long startTime) - { - _startTime = startTime; - } -*/ -//---------------------------------------------------------- - - public long getStartTime() - { - return _startTime; - } -//-------------------------------------------------------- -/* - private void setEndTime(long endTime) - { - _endTime = endTime; - } -*/ -//-------------------------------------------------------- - - public long getEndTime() - { - return _endTime; - } - -// -------------------------------------------------------- - - - public MeasuringUnit getMeasuringUnit() - { - return _measuringUnit; - } - -// -------------------------------------------------------- - -/* - public Measurement getMinMeasurement() - { - Measurement measurement = null; - Measurement minMeasurement = null; - - if (_measurementList.size() > 0) - { - minMeasurement = (Measurement) _measurementList.get(0); - } - - for (int i = 1; i < _measurementList.size(); i++) - { - measurement = (Measurement) _measurementList.get(i); - - if (measurement.getValue() < minMeasurement.getValue()) - { - minMeasurement = measurement; - } - } - - if (minMeasurement != null) - { - minMeasurement = new Measurement(minMeasurement); - } - - return minMeasurement; - } - -//--------------------------------------------------------------------- - - public Measurement getMaxMeasurement() - { - String header = "RegularTimeSeries.getMaxMeasurement(): " + - "where name = " + _name; - - // System.out.println(header + "current time series is " + this._name); - - - Measurement measurement = null; - Measurement maxMeasurement = null; - - MeasuringUnit checkingUnit = this.getMeasuringUnit(); - - double value = 0; - - if (_measurementList.size() > 0) - { - maxMeasurement = (Measurement) _measurementList.get(0); - } - - - for (int i = 1; i < _measurementList.size(); i++) - { - - - measurement = (Measurement) _measurementList.get(i); - value = measurement.getValue(); - - if (! measurement.getUnit().getName().equals(checkingUnit.getName())) - - { - System.out.println(header + " ******* HEY, the expected unit was " + checkingUnit + - " and the received unit was " + measurement.getUnit() + " and the value was " + value); - } - - - if (value > maxMeasurement.getValue()) - { - //System.out.println(header + "value for maxMeasurement so far = " + value); - maxMeasurement = measurement; - } - } //end for - - if (maxMeasurement != null) - { - maxMeasurement = new Measurement(maxMeasurement); - } - - return maxMeasurement; - } - */ - -//--------------------------------------------------------------------- - - public AbsTimeMeasurement getMinMeasurement(long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - - AbsTimeMeasurement minMeasurement = null; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = getAbsTimeMeasurementByIndex(i); - long time = measurement.getTime(); - - if ( (time >= startTime) && (time <= endTime) ) - { - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - - ( (minMeasurement == null) || - (measurement.getValue() < minMeasurement.getValue()) - ) - ) - { - minMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - } //end for i - - // System.out.println("RegularTimeSeries.getMinMeasurement(): result = " + minMeasurement); - - return minMeasurement; - - } - - // --------------------------------------------------------------------- - - public AbsTimeMeasurement getMinMeasurement() - { - - return getMinMeasurement(getStartTime(), getEndTime()); - - } - - //--------------------------------------------------------------------- - public AbsTimeMeasurement getMaxMeasurement(long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement maxMeasurement = null; - - double value = 0; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = getAbsTimeMeasurementByIndex(i); - long time = measurement.getTime(); - - if ( (time >= startTime) && (time <= endTime) ) - { - - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - - - ( (maxMeasurement == null) || - (measurement.getValue() > maxMeasurement.getValue()) - ) - ) - { - maxMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - } //end for - - // System.out.println("RegularTimeSeries.getMaxMeasurement(): result = " + maxMeasurement); - - - return maxMeasurement; - } - - //--------------------------------------------------------------------- - - public AbsTimeMeasurement getMaxMeasurement() - { - return getMaxMeasurement(getStartTime(), getEndTime()); - } - - //--------------------------------------------------------------------- - - public static RegularTimeSeries concatenate( RegularTimeSeries ts1, - RegularTimeSeries ts2) - { - String header = "RegularTimeSeries.concatenate(): "; - - long startTime = Math.min(ts1.getStartTime(), ts2.getStartTime()); - long endTime = Math.max(ts1.getEndTime(), ts2.getEndTime()); - - - RegularTimeSeries newTs = - new RegularTimeSeries(startTime, - endTime, - ts1.getIntervalInHours(), - ts1.getMeasuringUnit()); - - long intervalInMillis = ts1.getIntervalInHours() * _millisPerHour; - - // note: the ts1 timeseries takes precedence during overlapping periods - - // insert the ts2 data - for (int i = 0; i < ts2.getMeasurementCount(); i++) - { - Measurement measurement = ts2.getMeasurementByIndex(i); - long time = ts2.getMeasurementTimeByIndex(i); - - - // System.out.println(header + "ts2 " + " time = " + DbTimeHelper.getDateTimeStringFromLongTime(time) + " value = " + measurement.getValue()); - newTs.setMeasurementByTime(measurement, time); - } //end for - - - // insert the ts1 data - for (int i = 0; i < ts1.getMeasurementCount(); i++) - { - Measurement measurement = ts1.getMeasurementByIndex(i); - - long time = ts1.getMeasurementTimeByIndex(i); - - // System.out.println(header + "ts1 " + " time = " + DbTimeHelper.getDateTimeStringFromLongTime(time) + " value = " + measurement.getValue() ); - newTs.setMeasurementByTime(measurement, time); - } //end for - - - return newTs; - } - -// -------------------------------------------------------- - - public void setIntervalInHours(int intervalInHours) - { - _intervalInHours = intervalInHours; - } - - //-------------------------------------------------------- - - public int getIntervalInHours() - { - return _intervalInHours; - } - -// -------------------------------------------------------- - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - if (_name != null) - { - buffer.append("Name: " + getName()); - } - - buffer.append(" Units: " + _measuringUnit + " "); - buffer.append(" Measurement Count = " + getMeasurementCount()); - - buffer.append(" Start Time = " + DbTimeHelper.getDateTimeStringFromLongTime(_startTime)); - buffer.append(" End Time = " + DbTimeHelper.getDateTimeStringFromLongTime(_endTime)); - - buffer.append(" "); - - NumberFormat f = new DecimalFormat("##0.00"); - - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement measurement = getMeasurementByIndex(i); - - //long time = getMeasurementTimeByIndex(i); - //String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - if (! measurement.isMissing() ) - { - double value = measurement.getValue(); - String valueString = f.format(value); - - // buffer.append(timeString + "->"); - buffer.append(valueString + " "); - } - else // it is missing - { - // buffer.append(timeString + "->"); - buffer.append(_missingString + " "); - } - } - return buffer.toString(); - - } - - -// -------------------------------------------------------- - - private static void originalTests() - { - final long millisPerHour = 1000 * 60 * 60; - int hoursCount = 6; - int hoursPerDay = 24; - long startTime = System.currentTimeMillis(); - startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, 1); - - long endTime = startTime + (millisPerHour * hoursCount); - long shift = millisPerHour * hoursCount; - - int hoursPerInterval = 1; - - RegularTimeSeries ts1 = new RegularTimeSeries(startTime, endTime, - hoursPerInterval, MeasuringUnit.mm); - - - long startTime2 = endTime - (3 * millisPerHour); - long endTime2 = startTime2 + (millisPerHour * hoursCount); - RegularTimeSeries ts2 = new RegularTimeSeries(startTime2, endTime2, - hoursPerInterval, - MeasuringUnit.mm); - - - long m1Time = startTime; - long m2Time = startTime2; - for (int i = 0; i <= hoursCount; i++) - { - Measurement measurement = new Measurement(13.0 + i, MeasuringUnit.mm); - ts1.setMeasurementByTime(measurement, m1Time); - - Measurement measurement2 = new Measurement(47.0 + i, MeasuringUnit.mm); - ts2.setMeasurementByTime(measurement2, m2Time); - - m1Time += millisPerHour; - m2Time += millisPerHour; - } - - System.out.println("ts1 = " + ts1); - System.out.println("ts2 = " + ts2); - - - - // test out sub time series - RegularTimeSeries subTimeSeries = ts1.getSubTimeSeries(startTime2, endTime2); - - System.out.println("new start time = " + DbTimeHelper.getDateTimeStringFromLongTime(startTime2) + - " new end time = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime2)); - System.out.println("subTimeSeries = " + subTimeSeries); - - - - - // test out adding measurements that occur before and after the way the time series - // is currently set up - Measurement measurement = new Measurement(999.0, MeasuringUnit.mm); - ts1.setMeasurementByTime(measurement, ts1.getStartTime() - millisPerHour); - - Measurement measurement2 = new Measurement(1000.0, MeasuringUnit.mm); - ts1.setMeasurementByTime(measurement2, ts1.getEndTime() + millisPerHour); - - System.out.println("altered ts1 = " + ts1); - - - // test out adding measurements before and after the current start and end times - // of a RegularTimeSeries - - long newStartTime = ts1.getStartTime()- (5 * millisPerHour); - long newEndTime = ts1.getEndTime() + (5 * millisPerHour); - - ts1.stretchTimeSeries(newStartTime, newEndTime, -99999); - - System.out.println("stretched ts1 = " + ts1); - - - newStartTime += (10 * millisPerHour); - ts1.trimTimeSeriesAtStart(newStartTime); - System.out.println("trimmed ts1 = " + ts1); - - - /* // index testing section - int index = ts1.getMeasurementIndexByTime(startTime); - long time = ts1.getMeasurementTimeByIndex(index); - - int index2 = ts1.getMeasurementIndexByTime(time); - long time2 = ts1.getMeasurementTimeByIndex(index2); - System.out.println("ts1 index = " + index); - System.out.println("ts1 time = " + time); - System.out.println("ts1 index = " + index2); - System.out.println("ts1 time2 = " + time2); - */ - - - - RegularTimeSeries concatTs = RegularTimeSeries.concatenate(ts1, ts2); - - System.out.println("concat Ts = " + concatTs); - } -// -------------------------------------------------------- - private static void testShifting() - { - String header = "RegularTimeSeries.testShifting(): "; - final long MILLIS_PER_HOUR = _millisPerHour; - - int shiftInHours = 12; - - int intervalInHours = 24; - long intervalInMillis = intervalInHours * MILLIS_PER_HOUR; - - long startTime = System.currentTimeMillis(); - startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, intervalInHours); - long endTime = startTime + 3 * 24 * _millisPerHour; - MeasuringUnit unit = MeasuringUnit.inches; - - - - RegularTimeSeries ts1 = new RegularTimeSeries(startTime, endTime, - intervalInHours, unit); - - ts1.shiftStartEndTimeHours(shiftInHours); - startTime = ts1.getStartTime(); - - StringBuffer inBuffer = new StringBuffer(); - StringBuffer outBuffer = new StringBuffer(); - - - //initialize test values - double value = 0.0; - String valueTimeString = null; - - for (long t = startTime; t <= endTime; t+= intervalInMillis ) - { - value += 1.0; - Measurement m = new Measurement(value, unit); - ts1.setMeasurementByTime(m, t); - - valueTimeString = getValueTimeString(t, value); - - inBuffer.append(valueTimeString); - - System.out.println(header + "IN " + valueTimeString); - } - - for (long t = startTime; t <= endTime; t+= intervalInMillis) - { - Measurement m = ts1.getMeasurementByTime(t); - - if (m != null) - { - value = m.getValue(); - } - else - { - value = _missingValue; - } - valueTimeString = getValueTimeString(t, value); - - outBuffer.append(valueTimeString); - - System.out.println(header + "OUT " + valueTimeString); - } - - //verify that what went in is what comes out - if (inBuffer.toString().equals(outBuffer.toString())) - { - System.out.println(header + "The buffers are the same. "); - } - else - { - System.out.println(header + "The buffers are different. "); - } - - } -// -------------------------------------------------------- - static String getValueTimeString(long time, double value) - { - return "Value = " + value + " time = " + - DbTimeHelper.getDateTimeStringFromLongTime(time); - } -// -------------------------------------------------------- - - public static void main(String[] args) - { - - //originalTests(); - - testShifting(); - - } - -// -------------------------------------------------------- - -/* - private void trace() - { - try - { - throw new Exception("trace"); - } - catch(Exception e) - { - e.printStackTrace(); - } - - } -*/ -// -------------------------------------------------------- - - -} //end RegularTimeSeries diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/RegularTimeSeriesHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/RegularTimeSeriesHolder.java deleted file mode 100644 index 5d7ed559bf..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/RegularTimeSeriesHolder.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Created on Oct 14, 2003 - * - * - * */ -package ohd.hseb.measurement; - -import java.util.ArrayList; - -/** - * @author Chip Gobs - * - * This is a simple Holder class for a TimeSeries object - * It will forward TimeSeriesEvents to the listeners. - * It won't notify the listener with the same Receiver as the Event's source. - */ -public class RegularTimeSeriesHolder -{ - private RegularTimeSeries _timeSeries; - private java.util.List _listenerList = new ArrayList(); - - private long _eventCount = 0; - - - public void setTimeSeries(RegularTimeSeries timeSeries) - { - _timeSeries = timeSeries; - } - - public void forwardEvent(TimeSeriesEvent event) - { - event.setEventId(_eventCount); - - notifyListeners(event); - - _eventCount++; - } - - - public RegularTimeSeries getTimeSeries() - { - return _timeSeries; - } - - - - public void addListener(TimeSeriesListener listener) - { - _listenerList.add(listener); - } - - - public void removeListener(TimeSeriesListener listener) - { - _listenerList.remove(listener); - } - - - private void notifyListeners(TimeSeriesEvent event) - { - for (int i = 0 ; i < _listenerList.size(); i++) - { - TimeSeriesListener listener = (TimeSeriesListener) _listenerList.get(i); - - if (listener.getReceiver() != event.getSource()) - { - listener.handleTimeSeriesEvent(event); - } - } - } - - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/RelTimeMeasurement.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/RelTimeMeasurement.java deleted file mode 100644 index 5e2ffc1ec8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/RelTimeMeasurement.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Created on Aug 25, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.measurement; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * This class represents a Measurement at a time relative to some - * externally defined time. - */ -public class RelTimeMeasurement extends Measurement -{ - private long _relTimeInMillis; //time after or before another base time, defined elsewhere - - //--------------------------------------------------------------- - - public RelTimeMeasurement(double value, long relTimeInMillis, MeasuringUnit unit) - { - super(value, unit); - _relTimeInMillis = relTimeInMillis; - } - - //--------------------------------------------------------------- - - public RelTimeMeasurement(RelTimeMeasurement measurement) - { - super(measurement.getValue(), measurement.getUnit()); - _relTimeInMillis = measurement.getRelativeTime(); - } - - //--------------------------------------------------------------- - public Measurement getConvertedCopy(MeasuringUnit toUnit) - { - - RelTimeMeasurement newMeasurement = new RelTimeMeasurement(this); - - newMeasurement.convert(toUnit); - - return newMeasurement; - } - // --------------------------------------------------------------- - - public long getRelativeTime() - { - return _relTimeInMillis; - } - - //--------------------------------------------------------------- - private String formatTime(long time) - { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); - return formatter.format(new Date(time)); - } - //--------------------------------------------------------------- - - public String toString() - { - return getValue() + " in " + getUnit().getName() + " at " + formatTime(_relTimeInMillis); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeIntervalMeasurement.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeIntervalMeasurement.java deleted file mode 100644 index 01182699e7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeIntervalMeasurement.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Created on Sep 26, 2003 - * - * - */ -package ohd.hseb.measurement; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author Chip Gobs - * - * This class handles the abstraction of - * a measurement that is taken over a period of time, - * such as 1-hour precipitation totals. - * - */ -public class TimeIntervalMeasurement extends AbsTimeMeasurement -{ - - private static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - private int _intervalInHours = -1; - - - //--------------------------------------------------------------------- - - public TimeIntervalMeasurement(double value, - long endTimeInMillis, - int intervalInHours, - MeasuringUnit unit) - { - super(value, endTimeInMillis, unit); - - setIntervalInHours(intervalInHours); - - return; - } - - //--------------------------------------------------------------------- - - public TimeIntervalMeasurement(TimeIntervalMeasurement measurement) - { - super(measurement.getValue(), - measurement.getTime(), - measurement.getUnit()); - - setIntervalInHours(measurement.getIntervalInHours()); - return; - } - //--------------------------------------------------------------- - public static TimeIntervalMeasurement getConvertedCopy( - TimeIntervalMeasurement origMeasurement, - MeasuringUnit toUnit) - { - TimeIntervalMeasurement newMeasurement = - new TimeIntervalMeasurement(origMeasurement); - - newMeasurement.convert(toUnit); - - return newMeasurement; - } - //--------------------------------------------------------------- - - // --------------------------------------------------------------- - - public long getStartTime() - { - return getTime() - (_intervalInHours * MILLIS_PER_HOUR); - } - - //--------------------------------------------------------------- - - private void setIntervalInHours(int intervalInHours) - { - _intervalInHours = intervalInHours; - } - -// --------------------------------------------------------------- - - public long getEndTime() - { - return getTime(); - } - //--------------------------------------------------------------- -/* - private void setEndTime(long endTime) - { - setTime(endTime); - } -*/ - //--------------------------------------------------------------- - - public int getIntervalInHours() - { - return _intervalInHours; - } - //--------------------------------------------------------------- - - private String formatTime(long time) - { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); - return formatter.format(new Date(time)); - } - - - //--------------------------------------------------------------- - - public String toString() - { - - String outString = getValue() + " in " + getUnit().getName() + " ending at " + - formatTime(getEndTime()) + - " over " + _intervalInHours + " hours. "; - - return outString; - } - //--------------------------------------------------------------------- - -} //end class TimeIntervalMeasurement - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesEvent.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesEvent.java deleted file mode 100644 index 67a44d30b8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesEvent.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Created on Apr 23, 2004 - * - * - */ -package ohd.hseb.measurement; - -/** - * @author GobsC - * - * - */ -public class TimeSeriesEvent -{ - - private String _message = null; - private Object _source = null; - private long _eventId = 0; - - public TimeSeriesEvent(String message, Object source) - { - _message = message; - _source = source; - - } - - public void setMessage(String message) - { - _message = message; - } - - public String getMessage() - { - return _message; - } - - public void setSource(Object source) - { - _source = source; - } - - public Object getSource() - { - return _source; - } - - public void setEventId(long eventId) - { - _eventId = eventId; - } - - public long getEventId() - { - return _eventId; - } - - public String toString() - { - String outString = "Event #" + this.getEventId() + ": " + this.getMessage() ; - - return outString; - - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesListener.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesListener.java deleted file mode 100644 index ef9c78a727..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesListener.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Created on Apr 23, 2004 - * - * - */ -package ohd.hseb.measurement; - -/** - * @author GobsC - * - * Listener for TimeSeriesEvent objects - */ -public interface TimeSeriesListener -{ - - void handleTimeSeriesEvent(TimeSeriesEvent event); - Object getReceiver(); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesTotaller.java b/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesTotaller.java deleted file mode 100644 index 0180de66ea..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/measurement/TimeSeriesTotaller.java +++ /dev/null @@ -1,170 +0,0 @@ -package ohd.hseb.measurement; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.TimeHelper; - -public class TimeSeriesTotaller -{ - public final static long MILLIS_PER_HOUR = 1000 * 60 * 60; - - // -------------------------------------------------------------------------------- - public static RegularTimeSeries - getRegularTimeSeries(int newIntervalInHours, - int shiftHours, - RegularTimeSeries origTimeSeries) - { - - String header = "TimeSeriesTotaller.getRegularTimeSeries(): "; - - long intervalInMillis = newIntervalInHours * MILLIS_PER_HOUR; - - long startTime = determineStartTime(origTimeSeries.getStartTime(), - newIntervalInHours, - shiftHours); - - long endTime = determineEndTime(origTimeSeries.getEndTime(), - newIntervalInHours, - shiftHours); - - // System.out.println(header + - // "startTime = " + getTimeString(startTime) + - // " endTime = " + getTimeString(endTime)); - - MeasuringUnit unit = origTimeSeries.getMeasuringUnit(); - - RegularTimeSeries newTs = new RegularTimeSeries(startTime, - endTime, - newIntervalInHours, - unit ); - newTs.shiftStartEndTimeHours(shiftHours); - - //start at end of period that we want to calculate - long scanStartTime = newTs.getStartTime(); - - long lookBackTimeInMillis = intervalInMillis - MILLIS_PER_HOUR; - - //calculate the totals - for (long newTime = scanStartTime; - newTime <= endTime; - newTime += intervalInMillis) - { - double totalValue = 0.0; - - // System.out.println("-begin -----newTime = " + getTimeString(newTime)); - - //for each original interval - for (long origTime = newTime - lookBackTimeInMillis; - origTime <= newTime; - origTime+= MILLIS_PER_HOUR) - { - // System.out.println("origTime = " + getTimeString(origTime)); - Measurement m = origTimeSeries.getMeasurementByTime(origTime); - if (m != null) - { - totalValue += m.getValue(); - } - } - // System.out.println("-end -----newTime = " + getTimeString(newTime) + - // " totalValue = " + totalValue); - - Measurement m = new Measurement(totalValue, unit); - - newTs.setMeasurementByTime(m, newTime); - - } - - - return newTs; - } - - // -------------------------------------------------------------------------------- - private static String getTimeString(long time) - { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } - - // -------------------------------------------------------------------------------- - - public static long determineStartTime(long origHourlyStartTime, int intervalInHours, int shiftHours) - { - - long newStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - origHourlyStartTime, intervalInHours); - - newStartTime += intervalInHours * MILLIS_PER_HOUR; - - // newStartTime += shiftHours; - - return newStartTime; - } - // -------------------------------------------------------------------------------- - public static long determineEndTime(long origHourlyEndTime, int intervalInHours, int shiftHours) - { - - long endStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - origHourlyEndTime, intervalInHours); - - endStartTime += intervalInHours * MILLIS_PER_HOUR; - - // endStartTime += shiftHours; - - return endStartTime; - } - // -------------------------------------------------------------------------------- - - public static RegularTimeSeries - getRegularTimeSeries(int intervalInHours, - RegularTimeSeries origTimeSeries) - { - - return getRegularTimeSeries(intervalInHours, 0, origTimeSeries ); - } - - // -------------------------------------------------------------------------------- - - public static void main(String[] stringArgs) - { - long startTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 24); - long endTime = startTime + (3 * 24*MILLIS_PER_HOUR); - MeasuringUnit unit = MeasuringUnit.inches; - - RegularTimeSeries origTimeSeries = new RegularTimeSeries(startTime, - endTime, - 1, - unit); - int intervalInHours = 6; - int shiftInHours = 0; - RegularTimeSeries totalledTimeSeries = null; - - //initialize test values - double value = 0.0; - for (long t = startTime; t <= endTime; t+= MILLIS_PER_HOUR) - { - Measurement m = new Measurement(value, unit); - value += 1.0; - origTimeSeries.setMeasurementByTime(m, t); - } - - //calculate 6 hour values - - intervalInHours = 3; - shiftInHours = 2; - totalledTimeSeries = - TimeSeriesTotaller.getRegularTimeSeries( - intervalInHours, - shiftInHours, - origTimeSeries); - - - - System.out.println("original time series = \n" + origTimeSeries); - - System.out.println("for every " + intervalInHours + - " hours : \n " + totalledTimeSeries); - - return; - } - - // -------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/DurationCode.java b/cave/ohd.hseb.common/src/ohd/hseb/model/DurationCode.java deleted file mode 100644 index 0d8f30d1bd..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/DurationCode.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Created on Aug 20, 2004 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * - */ -public class DurationCode -{ - public static int getHoursFromCode(int durationCode) - { - int hours = 0; - if ((durationCode >= 1000) && (durationCode < 2000)) - { - hours = durationCode - 1000; - } - else if (durationCode >= 2000 && (durationCode < 3000)) - { - int days = durationCode - 2000; - hours = days * 24; - } - - - return hours; - } - - - public static int getCodeFromHours(int hours) - { - int durationCode = 0; - - if (hours <= 999) - { - durationCode = 1000 + hours; - } - - return durationCode; - } - - public static int getCodeFromHoursString(String hoursString) - { - int hours = Integer.parseInt(hoursString); - int durationCode = getCodeFromHours(hours); - - return durationCode; - - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/FlowToStageValueMapper.java b/cave/ohd.hseb.common/src/ohd/hseb/model/FlowToStageValueMapper.java deleted file mode 100644 index 7f3182d956..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/FlowToStageValueMapper.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Created on Oct 22, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.ValueMapper; - -/** - * @author GobsC - * - * This implementation of ValueMapper maps river stages to discharge. - */ -public class FlowToStageValueMapper implements ValueMapper -{ - private MeasuringUnit _inputMeasuringUnit = MeasuringUnit.cfs; - private MeasuringUnit _outputMeasuringUnit = MeasuringUnit.feet; - - - private RatingCurve _ratingCurve = null; - - //-------------------------------------------------------- - - public FlowToStageValueMapper(RatingCurve ratingCurve) - { - _ratingCurve = ratingCurve; - } - //-------------------------------------------------------- - - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement resultMeasurement = null; - - double keyValue = inputMeasurement.getValue(_inputMeasuringUnit); - - double resultValue = 0; - if (_ratingCurve != null) - { - resultValue = _ratingCurve.getStageFromDischarge(keyValue); - resultMeasurement = new Measurement(resultValue, - _outputMeasuringUnit); - } - - return resultMeasurement; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - //-------------------------------------------------------- - -} // StageToFlowValueMapper diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjuster.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjuster.java deleted file mode 100644 index 4b89aae964..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjuster.java +++ /dev/null @@ -1,924 +0,0 @@ -/* - * Created on Aug 27, 2004 - * - * - */ -package ohd.hseb.model; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -//import ohd.hseb.util.CodeTimer; - -/** - * @author Chip Gobs - * - * The job of this class is to manage the blending of observed and forecast data such - * that the forecast time series is adjusted to match better with the observed data. - */ -public class ForecastAdjuster -{ - private static final long MILLIS_PER_MINUTE = 60 * 1000; - private static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - - private ForecastAdjusterParams _params = null; - private List _observedForecastPairList = null; - private Map _observedForecastMap = null; - private long _lastObservedTimeToUseAsInput = 0; - - private final static boolean _debug = false; - - // ---------------------------------------------------------------------------------- - - public ForecastAdjuster(ForecastAdjusterParams params) - { - // String header = "ForecastAdjuster()" ; - - // System.out.println("inside " + header); - - _params = params; - - _observedForecastPairList = new ArrayList(); - _observedForecastMap = new HashMap(); - } - - - // ---------------------------------------------------------------------------------- - public RegularTimeSeries getAdjustedTimeSeries(IrregularTimeSeries observedTs, - RegularTimeSeries origFcstTs ) - { - RegularTimeSeries adjustedFcstTs = null; - - ObservedForecastMeasurementPair previousPair = null; - ObservedForecastMeasurementPair nextPair = null; - - AbsTimeMeasurement origFcstMeasurement = null; - AbsTimeMeasurement adjustedMeasurement = null; - - - //trim the observedTimeSeries as needed - IrregularTimeSeries trimmedObsTs = observedTs.getSubTimeSeries(observedTs.getStartTime(), - getLastObservedTimeToUseAsInput()); - - int allowableBlendingHours = _params.getBlendingHours(); - - ForecastBlender forwardBlender = new ForecastBlender(allowableBlendingHours); - ForecastBlender backwardBlender = new ForecastBlender(allowableBlendingHours); - - - if ( _params.shouldDoAdjustment()) - { - // System.out.println(header + "Actually doing the adjustment"); - //create the data structure for helping go from a forecast point to its matching - //observed point (if any) - - buildObsAndForecastPairList( trimmedObsTs, - origFcstTs, - _params.getPairingTimeMinutes() * MILLIS_PER_MINUTE); - - // create new forecast time series - adjustedFcstTs = new RegularTimeSeries(origFcstTs.getStartTime(), origFcstTs.getEndTime(), - origFcstTs.getIntervalInHours(), - origFcstTs.getMeasuringUnit()); - - //for each forecast value - for (long time = origFcstTs.getStartTime(); time <= origFcstTs.getEndTime(); time += MILLIS_PER_HOUR ) - { - origFcstMeasurement = origFcstTs.getAbsTimeMeasurementByTime(time); - - //used for debugging/printing purposes - String fcstTimeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - adjustedMeasurement = new AbsTimeMeasurement(origFcstMeasurement); - - //try to find the origFcstMeasurement in the hashMap - AbsTimeMeasurement matchingObsMeasurement = - (AbsTimeMeasurement) _observedForecastMap.get(origFcstMeasurement); - - - if (matchingObsMeasurement != null) //there is a matching observedMeasurement, use direct adjustment - { - - performMatchingAdjustment(matchingObsMeasurement, - adjustedMeasurement, - forwardBlender, - backwardBlender, - fcstTimeString); - - - } - else // can't do direct adjustment, try interpolation and blending - { - previousPair = findBestPreviousPairByTime(time); - nextPair = findBestNextPairByTime(time); - - boolean doBlending = performInterpolation(origFcstMeasurement, - adjustedMeasurement, - previousPair, - nextPair, - forwardBlender, - backwardBlender, - fcstTimeString); - - if (doBlending) //pairs not close enough to each other, or at least - // one pair is missing, so try to use blending - { - performBlending(origFcstMeasurement, - adjustedMeasurement, - previousPair, - nextPair, - forwardBlender, - backwardBlender, - fcstTimeString); - } - - } //end else for unmatched fcst measurements - - if (adjustedMeasurement.getValue() < 0.0) - { - adjustedMeasurement.setValue(0.0); - } - - adjustedFcstTs.setMeasurementByTime(adjustedMeasurement, time); - - } //end for each forecast value - - } - else //don't adjust anything - { - if (_debug) - { - System.out.println("Not doing the adjustment"); - } - adjustedFcstTs = origFcstTs; - } - - return adjustedFcstTs; - - } - // ------------------------------------------------------------------------------------------------- - private void performMatchingAdjustment(AbsTimeMeasurement matchingObsMeasurement, - AbsTimeMeasurement adjustedMeasurement, - ForecastBlender forwardBlender, - ForecastBlender backwardBlender, - String fcstTimeString) - { - - if (_debug) - { - double amount = matchingObsMeasurement.getValue() - adjustedMeasurement.getValue(); - System.out.println(fcstTimeString + " using direct correction by pairing. Adjusting by " + amount); - } - //set value to current pairing observed value - //adjustedMeasurement = new AbsTimeMeasurement(origFcstMeasurement); - adjustedMeasurement.setValue(matchingObsMeasurement.getValue()); - - forwardBlender.clearBlender(); - backwardBlender.clearBlender(); - - } - - - // ------------------------------------------------------------------------------------------------- - - private boolean performInterpolation(AbsTimeMeasurement origFcstMeasurement, - AbsTimeMeasurement adjustedMeasurement, - ObservedForecastMeasurementPair previousPair, - ObservedForecastMeasurementPair nextPair, - ForecastBlender forwardBlender, - ForecastBlender backwardBlender, - String fcstTimeString) - { - AbsTimeMeasurement previousObs = null; - AbsTimeMeasurement nextObs = null; - - boolean doBlending = false; - - if ((previousPair != null) && (nextPair != null)) // - { - - previousObs = previousPair.getObservedMeasurement(); - nextObs = nextPair.getObservedMeasurement(); - - long prevTime = previousObs.getTime(); - long nextTime = nextObs.getTime(); - - //consider adding a method to AbsTimeMeasurement to - // allow for time window comparisons - - long timeDiff = nextTime - prevTime; - - // if can do interpolation - if (timeDiff <= _params.getInterpolationHours() * MILLIS_PER_HOUR) - { - - if (_debug) - { - System.out.print(fcstTimeString + " using interpolation by"); - } - adjustByInterpolation(origFcstMeasurement, - adjustedMeasurement, - previousPair, - nextPair); - - forwardBlender.clearBlender(); - backwardBlender.clearBlender(); - doBlending = false; - } - else //can't do interpolation, need to try blending - { - doBlending = true; - } - } //end if previousPair and nextPair not null - - else //can't do interpolation, need to try blending - { - doBlending = true; - } - - - return doBlending; - } - // ------------------------------------------------------------------------------------------------- - - private AbsTimeMeasurement performBlending(AbsTimeMeasurement origFcstMeasurement, - AbsTimeMeasurement adjustedMeasurement, - ObservedForecastMeasurementPair previousPair, - ObservedForecastMeasurementPair nextPair, - ForecastBlender forwardBlender, - ForecastBlender backwardBlender, - String fcstTimeString) - { - AbsTimeMeasurement forwardAdjustment = forwardBlender.getBlendAdjustment(previousPair, origFcstMeasurement); - AbsTimeMeasurement backwardAdjustment = backwardBlender.getBlendAdjustment(nextPair, origFcstMeasurement); - - AbsTimeMeasurement blendingAdjustment = combineBlendingAdjustments(forwardAdjustment, - backwardAdjustment); - adjustedMeasurement.addMeasurement(blendingAdjustment); - - if (blendingAdjustment.getValue() != 0.0) - { - if (_debug) - { - System.out.println(fcstTimeString + " Total blending adjustment = " + blendingAdjustment.getValue() + - " original value = " + origFcstMeasurement.getValue() + - " new value = " + adjustedMeasurement.getValue()); - } - } - else - { - if (_debug) - { - System.out.println(fcstTimeString + " No adjustment."); - } - } - - return adjustedMeasurement; - } - - // ------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement combineBlendingAdjustments(AbsTimeMeasurement forwardBlendAdjustment, - AbsTimeMeasurement backwardBlendAdjustment) - { - - double forwardValue = forwardBlendAdjustment.getValue(); - double backwardValue = backwardBlendAdjustment.getValue(); - - double adjustmentValue = forwardValue + backwardValue; - - int notEqualsZeroCount = 0; - - //count the non-zero adjustments - if (forwardValue != 0.0) - { - notEqualsZeroCount ++; - - } - if (backwardValue != 0.0) - { - notEqualsZeroCount ++; - - } - - if (notEqualsZeroCount > 0) - { - adjustmentValue /= (double) notEqualsZeroCount; - } - else - { - adjustmentValue = 0.0; - } - - - if (_debug) - { - System.out.println("forward blending Adjustment = " + forwardValue + - " backward blending adjustment = " + backwardValue); - } - - AbsTimeMeasurement blendingAdjustment = new AbsTimeMeasurement(forwardBlendAdjustment); //sets the time, will change the value - blendingAdjustment.setValue(adjustmentValue); - - return blendingAdjustment; - - - } - - // ---------------------------------------------------------------------------------- - private void adjustByInterpolation(AbsTimeMeasurement origFcstMeasurement, - AbsTimeMeasurement adjustedFcstMeasurement, - ObservedForecastMeasurementPair prevPair, - ObservedForecastMeasurementPair nextPair) - { - - ForecastInterpolationMethod blendingMethod = _params.getBlendingMethod(); - - AbsTimeMeasurement prevObs = prevPair.getObservedMeasurement(); - AbsTimeMeasurement prevFcst = prevPair.getForecastMeasurement(); - - AbsTimeMeasurement nextObs = nextPair.getObservedMeasurement(); - AbsTimeMeasurement nextFcst = nextPair.getForecastMeasurement(); - - long origFcstTime = origFcstMeasurement.getTime(); - - if ( (blendingMethod != null ) && - (blendingMethod.equals(ForecastInterpolationMethod.RATIO) )) - { - double ratio1 = prevObs.getValue() / prevFcst.getValue(); - double ratio2 = nextObs.getValue() / nextFcst.getValue(); - - double ratioDiff = Math.abs(ratio1 - ratio2); - - //if out of sanity range, then do DIFFERENCES anyway - if ( (ratio1 > 5.0) || (ratio2 > 5.0) || (ratioDiff > 2.0) ) - { - System.out.println(" differences "); - double adjustment = getAdjustmentUsingDifferences(origFcstTime, prevPair, nextPair); - double oldValue = adjustedFcstMeasurement.getValue(); - adjustedFcstMeasurement.setValue(oldValue + adjustment); - } - else // it is OK to use ratio method - { - System.out.println(" ratios "); - double adjustment = getAdjustmentUsingRatios(origFcstTime, prevPair, nextPair); - double oldValue = adjustedFcstMeasurement.getValue(); - adjustedFcstMeasurement.setValue(oldValue * adjustment); - } - } - else //use differences - { - System.out.println(" differences "); - double adjustment = getAdjustmentUsingDifferences(origFcstTime, prevPair, nextPair); - double oldValue = adjustedFcstMeasurement.getValue(); - adjustedFcstMeasurement.setValue(oldValue + adjustment); - - } - return; - } - - // ---------------------------------------------------------------------------------- - private double getAdjustmentUsingDifferences(long origFcstTime, - ObservedForecastMeasurementPair prevPair, - ObservedForecastMeasurementPair nextPair) - { - AbsTimeMeasurement prevObs = prevPair.getObservedMeasurement(); - AbsTimeMeasurement prevFcst = prevPair.getForecastMeasurement(); - - AbsTimeMeasurement nextObs = nextPair.getObservedMeasurement(); - AbsTimeMeasurement nextFcst = nextPair.getForecastMeasurement(); - - - double diff1 = prevObs.getValue() - prevFcst.getValue(); - double diff2 = nextObs.getValue() - nextFcst.getValue(); - - AbsTimeMeasurement diff1Measurement = - new AbsTimeMeasurement(diff1, prevObs.getTime(), prevObs.getUnit()); - - AbsTimeMeasurement diff2Measurement = - new AbsTimeMeasurement(diff2, nextObs.getTime(), nextObs.getUnit()); - - - AbsTimeMeasurement adjustmentMeasurement = - interpolate(diff1Measurement, diff2Measurement, origFcstTime); - - - double adjustmentValue = adjustmentMeasurement.getValue(); - - return adjustmentValue; - - } - - // ---------------------------------------------------------------------------------- - - - private double getAdjustmentUsingRatios(long origFcstTime, - ObservedForecastMeasurementPair prevPair, - ObservedForecastMeasurementPair nextPair) - { - AbsTimeMeasurement prevObs = prevPair.getObservedMeasurement(); - AbsTimeMeasurement prevFcst = prevPair.getForecastMeasurement(); - - AbsTimeMeasurement nextObs = nextPair.getObservedMeasurement(); - AbsTimeMeasurement nextFcst = nextPair.getForecastMeasurement(); - - - double ratio1 = prevObs.getValue() / prevFcst.getValue(); - double ratio2 = nextObs.getValue() / nextFcst.getValue(); - - AbsTimeMeasurement ratio1Measurement = - new AbsTimeMeasurement(ratio1, prevObs.getTime(), prevObs.getUnit()); - - AbsTimeMeasurement ratio2Measurement = - new AbsTimeMeasurement(ratio2, nextObs.getTime(), nextObs.getUnit()); - - AbsTimeMeasurement adjustmentMeasurement = - AbsTimeMeasurement.interpolate(ratio1Measurement, ratio2Measurement, origFcstTime); - - double adjustmentValue = adjustmentMeasurement.getValue(); - - return adjustmentValue; - } - - // ---------------------------------------------------------------------------------- - - private void buildObsAndForecastPairList(IrregularTimeSeries observedTs, - RegularTimeSeries forecastTs, - long maxTimeDifferenceForPairing) - - { - // String header = "ForecastAdjuster.buildObsAndForecastPairList(): "; - - //initialize the internal structures - _observedForecastPairList = new ArrayList(); - _observedForecastMap = new HashMap(); - - - // for each forecast value - for (int fcstIndex = 0; fcstIndex < forecastTs.getMeasurementCount(); fcstIndex++) - { - - AbsTimeMeasurement forecastMeasurement = - forecastTs.getAbsTimeMeasurementByIndex(fcstIndex); - - findObsAndForecastPairAndAddtoList(forecastMeasurement, observedTs, maxTimeDifferenceForPairing); - - - } //end for each forecast value - - return; - - } // buildObsAndForecastPairList - // ----------------------------------------------------------------------------------------------- - private void findObsAndForecastPairAndAddtoList(AbsTimeMeasurement forecastMeasurement, - IrregularTimeSeries observedTs, - long maxTimeDifferenceForPairing) - { - - long forecastTime = 0; - long obsTime = 0; - long timeDiff = 0; - - int startingObsIndex = 0; - - forecastTime = forecastMeasurement.getTime(); - - //set up inner loop variables - boolean foundFirstLegalMatch = false; - long smallestTimeDifference = -1; - AbsTimeMeasurement bestObsMeasurement = null; - boolean done = false; - - // System.out.println(header + "forecastMeasurement = " + forecastMeasurement); - -// look at each observed to find the best match (if any) for this forecast value - - - for (int obsIndex = startingObsIndex; - (!done && (obsIndex < observedTs.getMeasurementCount())); - obsIndex++) - { - AbsTimeMeasurement obsMeasurement = - observedTs.getAbsTimeMeasurementByIndex(obsIndex); - - obsTime = obsMeasurement.getTime(); - - - timeDiff = Math.abs(forecastTime - obsTime); - - // observed is in valid range for pairing - if (timeDiff <= maxTimeDifferenceForPairing) - { - if (! foundFirstLegalMatch) - { - foundFirstLegalMatch = true; - smallestTimeDifference = timeDiff; - bestObsMeasurement = obsMeasurement; - } - else //have already found a valid match for this forecast point - { - if (timeDiff < smallestTimeDifference) - { - smallestTimeDifference = timeDiff; - bestObsMeasurement = obsMeasurement; - } - else //we have gone past the best-matching observed - //we have already found smallest time difference - //(list is sorted in ascending order by time) - { - done = true; - startingObsIndex = obsIndex; //next time we do the inner loop, start here - - } - } - } - else // observed is not within valid range for pairing - { - if (foundFirstLegalMatch) // we now know the best match - { - done = true; - startingObsIndex = obsIndex; //next time we do the inner loop, start here - - } - else // (! foundFirstLegalMatch) - { - if (obsTime > forecastTime) - { - // there is no match for this forecast measurement, - // since we have passed the forecastTime and - // are out of the time window - done = true; - startingObsIndex = obsIndex; - } - else // obsTime <= forecastTime, actually, if it were =, the time window would match - { - //System.out.println("obsTime < forecastTime"); - // we need to keep looking, because we have not - // yet gotten in range - } - } //end else ! foundFirstLegalMatch - - } //end else observed not within valid range for printing - - - } //end for each observed - - - //check to see if any matches were found - // if so, then add the pair of points to the list and map - if (foundFirstLegalMatch) - { - ObservedForecastMeasurementPair pair = new ObservedForecastMeasurementPair( - bestObsMeasurement, forecastMeasurement); - - _observedForecastPairList.add(pair); - _observedForecastMap.put(forecastMeasurement, bestObsMeasurement); - - if (_debug) - { - System.out.println("pair = " + pair); - } - } - else - { - - //System.out.println("did not find a pair for " + forecastMeasurement); - } - - - } // end findObsAndForecastPairAndAddtoList - - // ----------------------------------------------------------------------------------------------- - - - private ObservedForecastMeasurementPair findBestNextPairByTime(long targetTime) - { - ObservedForecastMeasurementPair nextPair = null; - ObservedForecastMeasurementPair currentPair = null; - boolean done = false; - - for (int i = 0; !done && i < _observedForecastPairList.size(); i++) - { - currentPair = (ObservedForecastMeasurementPair) _observedForecastPairList.get(i); - if (currentPair.getForecastMeasurement().getTime() > targetTime) - { - nextPair = currentPair; - done = true; - } - } - - return nextPair; - } -// ----------------------------------------------------------------------------------------------- - private ObservedForecastMeasurementPair findBestPreviousPairByTime(long targetTime) - { - ObservedForecastMeasurementPair previousPair = null; - ObservedForecastMeasurementPair currentPair = null; - boolean done = false; - - for (int i = 0; !done && i < _observedForecastPairList.size(); i++) - { - currentPair = (ObservedForecastMeasurementPair) _observedForecastPairList.get(i); - if (currentPair.getForecastMeasurement().getTime() < targetTime) - { - previousPair = currentPair; - } - else // m.time >= targetTime - { - done = true; - } - } - - return previousPair; - } -// ----------------------------------------------------------------------------------------------- - - private ObservedForecastMeasurementPair oldFindBestNextPairByTime( - IrregularTimeSeries observedTs, - RegularTimeSeries forecastTs, - long targetTime, - long maxTimeDifferenceForPairing) - { - ObservedForecastMeasurementPair pair = null; - - IrregularTimeSeries choppedObservedTs = observedTs.getSubTimeSeries( - targetTime, observedTs.getEndTime()); - - AbsTimeMeasurement currentObsMeasurement = null; - AbsTimeMeasurement forecastMeasurement = null; - - boolean done = false; - long obsTime = 0; - // the measurements returned from getAbsTimeMeasurementByIndex(index) - // are in ascending order - // from earliest to latest in time - - // start near or at targetTime and work forward in time - for (int i = 0; (!done && i < choppedObservedTs.getMeasurementCount()); i++) - { - currentObsMeasurement = choppedObservedTs.getAbsTimeMeasurementByIndex(i); - obsTime = currentObsMeasurement.getTime(); - - forecastMeasurement = - findClosestForecastByObsTimeAtOrAfterTargetTime(forecastTs, - obsTime, - targetTime); - - if (areMeasurementsCloseEnoughInTime(forecastMeasurement, - currentObsMeasurement, maxTimeDifferenceForPairing)) - { - - pair = new ObservedForecastMeasurementPair( - currentObsMeasurement, forecastMeasurement); - - done = true; - } - - else - //keep looking - { - - } - } //end for - - - return pair; - - } - - // --------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement findClosestForecastByObsTimeAtOrAfterTargetTime(RegularTimeSeries forecastTs, - long obsTime, long targetTime) - { - //find the closest forecast (by time) to the obstime. - //The forecast found must be at or after the targetTime - - boolean done = false; - boolean firstTime = true; - long smallestTimeDiff = 0; - long timeDiff = 0; - AbsTimeMeasurement bestFcstMeasurement = null; - - - for (int i = 0; !done && i < forecastTs.getMeasurementCount(); i++) - { - - AbsTimeMeasurement fcstMeasurement = forecastTs.getAbsTimeMeasurementByIndex(i); - long fcstTime = fcstMeasurement.getTime(); - - if (fcstTime >= targetTime) - { - if ( firstTime ) //first time, do some initialization - { - smallestTimeDiff = Math.abs(obsTime - fcstTime); - bestFcstMeasurement = fcstMeasurement; - firstTime = false; - } - else //not the first iteration - { - timeDiff = Math.abs(obsTime - fcstTime); - - if (timeDiff < smallestTimeDiff) - { - smallestTimeDiff = timeDiff; - bestFcstMeasurement = fcstMeasurement; - } - else //we are getting farther from the obsTime, so stop - { - done = true; - } - } - - } - else //fcstTime < targetTime, so we need to just keep iterating - { - // do nothing - } - - } - - return bestFcstMeasurement; - } - - // ----------------------------------------------------------------------------------------------- - - private boolean areMeasurementsCloseEnoughInTime(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long maxMillisForCloseness) - { - boolean result = false; - - if ((m1 != null) && (m2 != null)) - { - long timeDiff = m1.getTime() - m2.getTime(); - - if (Math.abs(timeDiff) <= maxMillisForCloseness) - { - result = true; - } - } - - return result; - } - // ---------------------------------------------------------------------------------- - public static AbsTimeMeasurement interpolate(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long desiredTime) - { - long t1 = m1.getTime(); - long t2 = m2.getTime(); - - double value1 = m1.getValue(); - double value2 = m2.getValue(); - - double slope = (value2 - value1) / (t2 - t1); - double intercept = (value1) - (slope * t1); - - double value = (slope * desiredTime) + intercept; - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, - desiredTime, m1.getUnit()); - - measurement.setIsInterpolated(true); - - return measurement; - } - - // ---------------------------------------------------------------------------------- - - - public ForecastAdjusterParams getParams() - { - return _params; - } - - // ---------------------------------------------------------------------------------- - - public void setParams(ForecastAdjusterParams params) - { - _params = params; - } - - // ---------------------------------------------------------------------------------- - public static void main(String[] argStringArray) - { - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - ForecastAdjusterParams params = new ForecastAdjusterParams(); - params.setBlendingHours(5); - params.setBlendingMethod(ForecastInterpolationMethod.DIFFERENCE); - params.setShouldDoAdjustment(true); - - ForecastAdjuster adjuster = new ForecastAdjuster(params); - - long fcstStartTime = System.currentTimeMillis(); - long fcstEndTime = fcstStartTime + (7 * 24 * MILLIS_PER_HOUR); //7 days - - long obsStartTime = fcstStartTime - (3 * 24 * MILLIS_PER_HOUR); //3 days before fcst start - long obsEndTime = fcstStartTime + (7 * MILLIS_PER_HOUR); // 7 hours after fcst start - - IrregularTimeSeries observedTs = new IrregularTimeSeries(dischargeUnit); - RegularTimeSeries forecastTs = - new RegularTimeSeries(fcstStartTime, fcstEndTime, 1, dischargeUnit); - - - - // load up the forecast time series - double[] fcstMeasurementValueArray = {20, 21, 22, 24, 26, 30, 35, 40, 41, 42, 43, 45, 55, 67, 43, 32, 31, 30, 29, 28, 27, 26, 25 }; - - int index = 0; - - for (long time = fcstStartTime; time <= fcstEndTime; time+= MILLIS_PER_HOUR) - { - Measurement m = new Measurement(fcstMeasurementValueArray[index], dischargeUnit); - forecastTs.setMeasurementByTime(m, time); - - index++; - if (index == fcstMeasurementValueArray.length) - { - index = 0; - } - } - - - // load up the observed time series - index = 0; - double[] obsMeasurementValueArray = {18, 19, 20, 22, 24, 28, 33, 28, 39, 40, 41, 43, 53, 57, 41, 29, 29, 28, 27, 26, 26, 24, 28 }; - - long MILLIS_PER_MINUTE = 1000 * 60; - for (long time = obsStartTime; time <= obsEndTime; time+= 11 * MILLIS_PER_MINUTE) - { - AbsTimeMeasurement m = new AbsTimeMeasurement(obsMeasurementValueArray[index], time, dischargeUnit); - - observedTs.insertMeasurement(m); - - index++; - if (index == obsMeasurementValueArray.length) - { - index = 0; - } - } - - - RegularTimeSeries adjustedForecastTs = null; - - adjustedForecastTs = adjuster.getAdjustedTimeSeries(observedTs, forecastTs); - - - //print results - System.out.println("observedTs = " + observedTs + "\n"); - - System.out.println("original forecast Ts = " + forecastTs + "\n"); - System.out.println("adjusted forecast Ts = " + adjustedForecastTs); - - } - - // ---------------------------------------------------------------------------------- - - /** - * @param lastObservedTimeToUseAsInput The lastObservedTimeToUseAsInput to set. - */ - public void setLastObservedTimeToUseAsInput(long lastObservedTimeToUseAsInput) - { - // String header = " ForecastAdjuster.setLastObservedTimeToUseAsInput()"; - // System.out.println(header + "lastObservedTimeToUseAsInput = " + - // DbTimeHelper.getDateTimeStringFromLongTime(lastObservedTimeToUseAsInput)); - _lastObservedTimeToUseAsInput = lastObservedTimeToUseAsInput; - } - - // ---------------------------------------------------------------------------------- - - /** - * @return Returns the lastObservedTimeToUseAsInput. - */ - public long getLastObservedTimeToUseAsInput() - { - // String header = " ForecastAdjuster.getLastObservedTimeToUseAsInput()"; - // System.out.println(header + "lastObservedTimeToUseAsInput = " + - // DbTimeHelper.getDateTimeStringFromLongTime(_lastObservedTimeToUseAsInput)); - return _lastObservedTimeToUseAsInput; - } - // ---------------------------------------------------------------------------------- - - - private class BlendingData - { - - boolean _usedBlend = false; - int _blendHoursCount = 0; - double _blendAmount = 0.0; - - - - - } - // ---------------------------------------------------------------------------------- - - -} //end ForecastAdjuster diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjusterParams.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjusterParams.java deleted file mode 100644 index ff7a1a90d2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjusterParams.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Created on Aug 27, 2004 - * - */ -package ohd.hseb.model; - -/** - * @author Chip Gobs - * - * This class is holds the blending parameters for ForecastAdjuster - */ - -public class ForecastAdjusterParams -{ - - private boolean _shouldDoAdjustment = false; - private int _pairingTimeMinutes = 0; - private int _interpolationHours = 0; - private int _blendingHours = 0; - private int _maxBlendingHours = 500; - private ForecastInterpolationMethod _blendingMethod = ForecastInterpolationMethod.DIFFERENCE; - - - // ------------------------------------------------------------------------------- - /** - * @param useBlending The useBlending to set. - */ - public void setShouldDoAdjustment(boolean shouldDoAdjustment) - { - // String header = "ForecastAdjusterParams.setShouldDoAdjustment():"; - // System.out.println(header + "shouldDoAdjustment now = " + shouldDoAdjustment); - this._shouldDoAdjustment = shouldDoAdjustment; - } -// ------------------------------------------------------------------------------- - - /** - * @return Returns whether blending is on or off. - */ - public boolean shouldDoAdjustment() - { - return _shouldDoAdjustment; - } -// ------------------------------------------------------------------------------- - - /** - * @param blendingHours The blendingHours to set. - */ - public void setBlendingHours(int blendingHours) - { - _blendingHours = blendingHours; - } - -// ------------------------------------------------------------------------------- - - /** - * @return Returns the blendingHours. - */ - public int getBlendingHours() - { - return _blendingHours; - } - -// ------------------------------------------------------------------------------- - - /** - * @param blendMethod The blendMethod to set. - */ - public void setBlendingMethod(ForecastInterpolationMethod blendMethod) - { - _blendingMethod = blendMethod; - } -// ------------------------------------------------------------------------------- - - /** - * @return Returns the blendMethod. - */ - public ForecastInterpolationMethod getBlendingMethod() - { - return _blendingMethod; - } -// ------------------------------------------------------------------------------- - /** - * @param interpolationHours The interpolationHours to set. - */ - public void setInterpolationHours(int interpolationHours) - { - _interpolationHours = interpolationHours; - } - /** - * @return Returns the interpolationHours. - */ - public int getInterpolationHours() - { - return _interpolationHours; - } - /** - * @param pairingTimeMinutes The pairingTimeMinutes to set. - */ - public void setPairingTimeMinutes(int pairingTimeMinutes) - { - _pairingTimeMinutes = pairingTimeMinutes; - } - /** - * @return Returns the pairingTimeMinutes. - */ - public int getPairingTimeMinutes() - { - return _pairingTimeMinutes; - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjustmentTest.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjustmentTest.java deleted file mode 100644 index e3d2572cfc..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastAdjustmentTest.java +++ /dev/null @@ -1,451 +0,0 @@ -package ohd.hseb.model; - -import junit.framework.TestCase; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -public class ForecastAdjustmentTest extends TestCase -{ - - protected static final long MILLIS_PER_HOUR = 3600 * 1000; - protected static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; - - - // -------------------------------------------------------------------------------------------------------- - - public ForecastAdjustmentTest(String name) - { - super(name); - } - - // -------------------------------------------------------------------------------------------------------- - - protected void setUp() throws Exception - { - super.setUp(); - - } - - // -------------------------------------------------------------------------------------------------------- - - - protected void tearDown() throws Exception - { - super.tearDown(); - } - - // -------------------------------------------------------------------------------------------------------- - - private DateValuePair dvp(String dateTimeString, double value) - { - return new DateValuePair(dateTimeString, value); - - } - - // -------------------------------------------------------------------------------------------------------- - - - private class DateValuePair - { - private String dateString = null; - private double value = 0.0; - - public DateValuePair(String dateTimeString, double value) - { - setDateString(dateTimeString); - setValue(value); - } - - public void setDateString(String dateString) - { - this.dateString = dateString; - } - public String getDateString() - { - return dateString; - } - public void setValue(double value) - { - this.value = value; - } - public double getValue() - { - return value; - } - } - - // -------------------------------------------------------------------------------------------------------- - - private RegularTimeSeries getForecastTimeSeries() - { - - DateValuePair fcstMeasurementValueArray[] = - - { - dvp("2007-03-01 13:00:00", .25), - dvp("2007-03-01 14:00:00", .10), - dvp("2007-03-01 15:00:00", .15), - dvp("2007-03-01 16:00:00", .50), - dvp("2007-03-01 17:00:00", .80), - dvp("2007-03-01 18:00:00", 1.2), - dvp("2007-03-01 19:00:00", 1.5), - dvp("2007-03-01 20:00:00", 1.9), - dvp("2007-03-01 21:00:00", 2.1), - dvp("2007-03-01 22:00:00", 2.5), - dvp("2007-03-01 23:00:00", 2.9), - dvp("2007-03-02 00:00:00", 3.2), - dvp("2007-03-02 01:00:00", 3.6), - dvp("2007-03-02 02:00:00", 4.0), - dvp("2007-03-02 03:00:00", 4.9), - dvp("2007-03-02 04:00:00", 6.1), - dvp("2007-03-02 05:00:00", 7.9), - dvp("2007-03-02 06:00:00", 10.0), - dvp("2007-03-02 07:00:00", 12.0), - dvp("2007-03-02 08:00:00", 14.1), - dvp("2007-03-02 09:00:00", 16.0), - dvp("2007-03-02 10:00:00", 17.0), - dvp("2007-03-02 11:00:00", 17.5), - dvp("2007-03-02 12:00:00", 17.8), - dvp("2007-03-02 13:00:00", 17.6), - dvp("2007-03-02 14:00:00", 17.3), - dvp("2007-03-02 15:00:00", 16.8), - dvp("2007-03-02 16:00:00", 16.0), - dvp("2007-03-02 17:00:00", 14.7), - dvp("2007-03-02 18:00:00", 13.6), - dvp("2007-03-02 19:00:00", 12.7), - dvp("2007-03-02 20:00:00", 11.9), - dvp("2007-03-02 21:00:00", 12.0), - dvp("2007-03-02 22:00:00", 12.0), - dvp("2007-03-02 23:00:00", 12.0), - dvp("2007-03-03 00:00:00", 12.0) - }; - - String dateTimeString = "2007-03-06 01:00:00"; - long fcstStartTime = DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - - long fcstEndTime = getTime("2007-03-03 06:00:00"); - - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - RegularTimeSeries forecastTs = - new RegularTimeSeries(fcstStartTime, fcstEndTime, 1, dischargeUnit); - - for (int i = 0; i < fcstMeasurementValueArray.length; i++) - { - DateValuePair dvp = fcstMeasurementValueArray[i]; - - double value = dvp.getValue(); - long time = DbTimeHelper.getLongTimeFromDateTimeString(dvp.getDateString()); - - Measurement m = new Measurement(value , dischargeUnit); - forecastTs.setMeasurementByTime(m, time); - } - - - return forecastTs; - - } - - // -------------------------------------------------------------------------------- - - private IrregularTimeSeries getObservedTimeSeries() - { - - DateValuePair obsMeasurementValueArray[] = - - { - dvp("2007-03-01 13:00:00", 4), - dvp("2007-03-01 14:00:00", 4), - dvp("2007-03-01 15:00:00", 4), - dvp("2007-03-01 16:00:00", 4), - dvp("2007-03-01 17:00:00", 4), - dvp("2007-03-01 18:00:00", 4), - dvp("2007-03-01 19:00:00", 4), - dvp("2007-03-01 20:00:00", 4), - dvp("2007-03-01 21:00:00", 4), - dvp("2007-03-01 22:00:00", 4), - dvp("2007-03-01 23:00:00", 4), - dvp("2007-03-02 00:00:00", 4), - dvp("2007-03-02 01:00:00", 4.2), - dvp("2007-03-02 02:00:00", 4.4), - - dvp("2007-03-02 03:00:00", 4.5), - dvp("2007-03-02 04:00:00", 4.8), - // dvp("2007-03-02 03:00:00", -9999), - // dvp("2007-03-02 04:00:00", -9999), - - dvp("2007-03-02 05:00:00", 5.0), - dvp("2007-03-02 06:00:00", 5.2), - dvp("2007-03-02 07:00:00", 5.4), - - dvp("2007-03-02 08:00:00", 10.1), - dvp("2007-03-02 09:00:00", 10.5), - // dvp("2007-03-02 08:00:00", -9999), - // dvp("2007-03-02 09:00:00", -9999), - - // test the big gap - dvp("2007-03-02 10:00:00", 10.8), //17 - //fcst at 11:00 is 17.5 - // dvp("2007-03-02 15:50:00", 11.8), - //fcst at 13:00 is 17.6 - - //fcst at 15 is 16.8 - dvp("2007-03-02 16:00:00", 11.8), //16 - - - //test a small gap (the size for interpolation) - dvp("2007-03-02 20:00:00", 10), - dvp("2007-03-02 23:00:00", 10) - - }; - - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - IrregularTimeSeries observedTs = new IrregularTimeSeries(dischargeUnit); - - for (int i = 0; i < obsMeasurementValueArray.length; i++) - { - DateValuePair dvp = obsMeasurementValueArray[i]; - - double value = dvp.getValue(); - long time = DbTimeHelper.getLongTimeFromDateTimeString(dvp.getDateString()); - - AbsTimeMeasurement m = new AbsTimeMeasurement(value, time, dischargeUnit); - observedTs.insertMeasurement(m); - } - - return observedTs; - - } - - // -------------------------------------------------------------------------------- - - public void testPairing() - { - RegularTimeSeries fcstTimeSeries = getForecastTimeSeries(); - IrregularTimeSeries obsTimeSeries = getObservedTimeSeries(); - - long lastObsTime = obsTimeSeries.getEndTime(); - - ForecastAdjuster adjuster = getForecastAdjuster(lastObsTime); - - RegularTimeSeries adjustedForecastTs = adjuster.getAdjustedTimeSeries(obsTimeSeries, fcstTimeSeries); - - MeasuringUnit unit = adjustedForecastTs.getMeasuringUnit(); - - double value = 0; - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 00:00:00"), unit); - assertEquals(4.0, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 05:00:00"), unit); - assertEquals(5.0, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 9:00:00"), unit); - assertEquals(10.5, value); - - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 10:00:00"), unit); - assertEquals(10.8, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 11:00:00"), unit); - assertEquals(10.8, value); - - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 15:00:00"), unit); - assertEquals(11.8, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 16:00:00"), unit); - assertEquals("after gap ", 11.8, value); - - - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 20:00:00"), unit); - assertEquals("before small gap ", 10.0, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 23:00:00"), unit); - assertEquals("after small gap ", 10.0, value); - - - // System.out.println("observedTs = " + obsTimeSeries + "\n"); - // - // System.out.println("original forecast Ts = " + fcstTimeSeries + "\n"); - // System.out.println("adjusted forecast Ts = " + adjustedForecastTs); - - } - - // ---------------------------------------------------------------- - - public void testInterpolation() - { - RegularTimeSeries fcstTimeSeries = getForecastTimeSeries(); - IrregularTimeSeries obsTimeSeries = getObservedTimeSeries(); - - long lastObsTime = obsTimeSeries.getEndTime(); - - ForecastAdjuster adjuster = getForecastAdjuster(lastObsTime); - - - RegularTimeSeries adjustedForecastTs = adjuster.getAdjustedTimeSeries(obsTimeSeries, fcstTimeSeries); - - MeasuringUnit unit = adjustedForecastTs.getMeasuringUnit(); - - double value = 0; - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 19:00:00"), unit); - assertEquals(10.0, value); - } - - // -------------------------------------------------------------------------------------------------------- - private double getDesiredDoubleMatchedBlendedValue(ForecastAdjuster adjuster, - RegularTimeSeries fcstTimeSeries, - IrregularTimeSeries obsTimeSeries, - String prevForecastTimeString, String prevObsTimeString, - String nextForecastTimeString, String nextObsTimeString, - String targetForecastTimeString, - int targetHoursFromPrevAdjustment, - int targetHoursFromNextAdjustment) - { - - String header = "ForecastAdjustmentTest.getDesiredBlendedValue(): "; - MeasuringUnit unit = fcstTimeSeries.getMeasuringUnit(); - - double fcstValue = fcstTimeSeries.getMeasurementValueByTime(getTime(targetForecastTimeString), unit); - - - //setup of previous pair - AbsTimeMeasurement prevObsMeasurement = obsTimeSeries.findClosestMeasurementByTime(getTime(prevObsTimeString)); - double prevObsValue = prevObsMeasurement.getValue(unit); - double prevFcstValue = fcstTimeSeries.getMeasurementValueByTime(getTime(prevForecastTimeString), unit); - double prevAdjustment = prevObsValue - prevFcstValue; - - - //setup of next pair - AbsTimeMeasurement nextObsMeasurement = obsTimeSeries.findClosestMeasurementByTime(getTime(nextObsTimeString)); - double nextObsValue = nextObsMeasurement.getValue(unit); - double nextFcstValue = fcstTimeSeries.getMeasurementValueByTime(getTime(nextForecastTimeString), unit); - double nextAdjustment = nextObsValue - nextFcstValue; - - - // calculate the blend - double blendingHours = adjuster.getParams().getBlendingHours(); - - double forwardFadeFactor = (blendingHours-targetHoursFromPrevAdjustment)/(blendingHours); - double forwardBlend = prevAdjustment * forwardFadeFactor; - - double backwardFadeFactor = (blendingHours-targetHoursFromNextAdjustment)/(blendingHours); - double backwardBlend = nextAdjustment * backwardFadeFactor ; - - double totalBlend = (forwardBlend + backwardBlend) / 2; - - // add the blend shift of the original forecast value - double newDesiredValue = fcstValue + totalBlend; - - - System.out.println(header + "forwardBlend " + forwardBlend + - " backwardBlend = " + backwardBlend + - " totalBlend = " + totalBlend + - " newDesired Value = " + newDesiredValue); - - - return newDesiredValue; - } - // -------------------------------------------------------------------------------------------------------- - - - public void testBlending() - { - - String header = "ForecastAdjustmentTest.testBlending(): "; - - RegularTimeSeries fcstTimeSeries = getForecastTimeSeries(); - IrregularTimeSeries obsTimeSeries = getObservedTimeSeries(); - - long lastObsTime = obsTimeSeries.getEndTime(); - - ForecastAdjuster adjuster = getForecastAdjuster(lastObsTime); - - - RegularTimeSeries adjustedForecastTs = adjuster.getAdjustedTimeSeries(obsTimeSeries, fcstTimeSeries); - - MeasuringUnit unit = adjustedForecastTs.getMeasuringUnit(); - - String targetTimeString = "2007-03-02 13:00:00"; - double value = adjustedForecastTs.getMeasurementValueByTime(getTime(targetTimeString), unit); - - double newDesiredValue = getDesiredDoubleMatchedBlendedValue( - adjuster, fcstTimeSeries, obsTimeSeries, - "2007-03-02 11:00:00", "2007-03-02 10:00:00", //fcst can match an obs up to 70 minutes away - "2007-03-02 15:00:00", "2007-03-02 16:00:00", //fcst can match an obs up to 70 minutes away - targetTimeString, //target time - 2, - 2); - - System.out.println(header + "newDesiredValue = " + newDesiredValue); - - - assertEquals(newDesiredValue, value); - - - targetTimeString = "2007-03-02 14:00:00"; - value = adjustedForecastTs.getMeasurementValueByTime(getTime(targetTimeString), unit); - - newDesiredValue = getDesiredDoubleMatchedBlendedValue( - adjuster, fcstTimeSeries, obsTimeSeries, - "2007-03-02 11:00:00", "2007-03-02 10:00:00", //fcst can match an obs up to 70 minutes away - "2007-03-02 15:00:00", "2007-03-02 16:00:00", //fcst can match an obs up to 70 minutes away - targetTimeString, //target time - 3, - 1); - - System.out.println(header + "newDesiredValue = " + newDesiredValue); - - - assertEquals(newDesiredValue, value); - - return; - - - } - - // -------------------------------------------------------------------------------------------------------- - - private long getTime(String dateTimeString) - { - return DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - } - - // -------------------------------------------------------------------------------------------------------- - - private ForecastAdjuster getForecastAdjuster(long lastObsTime) - { - - ForecastAdjusterParams params = new ForecastAdjusterParams(); - - int pairingTimeMinutes = 70; - int interpolationHours = 3; - - - params.setBlendingHours(100); - params.setBlendingMethod(ForecastInterpolationMethod.DIFFERENCE); - params.setShouldDoAdjustment(true); - params.setPairingTimeMinutes(pairingTimeMinutes); - params.setInterpolationHours(interpolationHours); - System.out.println("pairing minutes hours = " + params.getPairingTimeMinutes()); - System.out.println("Interpolation hours = " + params.getInterpolationHours()); - - - ForecastAdjuster adjuster = new ForecastAdjuster(params); - - adjuster.setLastObservedTimeToUseAsInput(lastObsTime); - - - return adjuster; - } - - // -------------------------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastBlender.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastBlender.java deleted file mode 100644 index 0cbc652e5e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastBlender.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Created on Sep 23, 2004 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; - -/** - * @author Chip Gobs - * - * Forecast Blender - */ -public class ForecastBlender -{ - - private int _blendHoursCount = 0; - private double _baseBlendAmount = 0; - private boolean _usedBlend = false; - - private int _allowableBlendingHours = 0; - - private long _allowableTimeWindow = 0; - - private static final long MILLIS_PER_MINUTE = 60 * 1000; - private static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - - private static boolean _debug = false; - - // ----------------------------------------------------------------------------------------- - public ForecastBlender(int allowableBlendingHours) - { - - _blendHoursCount = 0; - _baseBlendAmount= 0; - _usedBlend = false; - - _allowableTimeWindow = allowableBlendingHours * MILLIS_PER_HOUR; - _allowableBlendingHours = allowableBlendingHours; - } - - // ----------------------------------------------------------------------------------------- - public void clearBlender() - { - _blendHoursCount = 0; - _baseBlendAmount = 0; - _usedBlend = false; - - } - // ---------------------------------------------------------------------------------- - - /** - * @param _blendHoursCount The _blendHoursCount to set. - */ - private void setBlendHoursCount(int blendHoursCount) - { - this._blendHoursCount = blendHoursCount; - } - - // ----------------------------------------------------------------------------------------- - /** - * @return Returns the _blendHoursCount. - */ - private int getBlendHoursCount() - { - return _blendHoursCount; - } - // ----------------------------------------------------------------------------------------- - /** - * @param _baseBlendAmount The _blendAmount to set. - */ - private void setBlendAmount(double blendAmount) - { - this._baseBlendAmount = blendAmount; - } - // ----------------------------------------------------------------------------------------- - /** - * @return Returns the _blendAmount. - */ - private double getBlendAmount() - { - return _baseBlendAmount; - } - // ----------------------------------------------------------------------------------------- - /** - * @param _usedBlendForward The _usedBlendForward to set. - */ - public void setUsedBlend(boolean usedBlend) - { - this._usedBlend = usedBlend; - } - // ----------------------------------------------------------------------------------------- - /** - * @return Returns the _usedBlendForward. - */ - public boolean usedBlend() - { - return _usedBlend; - } - // ----------------------------------------------------------------------------------------- - - private boolean areMeasurementsCloseEnoughInTime(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long maxMillisForCloseness) - { - boolean result = false; - - if ((m1 != null) && (m2 != null)) - { - long timeDiff = m1.getTime() - m2.getTime(); - - if (Math.abs(timeDiff) <= maxMillisForCloseness) - { - result = true; - } - } - - return result; - } - // ---------------------------------------------------------------------------------- - public AbsTimeMeasurement getBlendAdjustment(ObservedForecastMeasurementPair obsFcstPair, - AbsTimeMeasurement origFcstMeasurement) - { - String header = "ForecastBlender.getBlendAdjustment(): "; - - AbsTimeMeasurement adjustmentMeasurement = null; - AbsTimeMeasurement observedMeasurement = null; - AbsTimeMeasurement pairedFcstMeasurement = null; - - long fcstTime = origFcstMeasurement.getTime(); - - - if (obsFcstPair != null) - { - observedMeasurement = obsFcstPair.getObservedMeasurement(); - pairedFcstMeasurement = obsFcstPair.getForecastMeasurement(); - - if (areMeasurementsCloseEnoughInTime(observedMeasurement, - origFcstMeasurement, - _allowableTimeWindow)) - { - - - //first time for forward blending of this group of - // forecast values - if (! _usedBlend) - { - _usedBlend = true; - - long pairFcstTime = obsFcstPair.getForecastMeasurement().getTime(); - long timeDiff = fcstTime - pairFcstTime; - - _blendHoursCount = (int) (timeDiff / MILLIS_PER_HOUR); - _baseBlendAmount = observedMeasurement.getValue() - pairedFcstMeasurement.getValue(); - - } - - // have already usedBlendForward - else - { - _blendHoursCount ++; - } - - double absBlendHoursCount = Math.abs(_blendHoursCount); - - double fadeFactor = ((double) _allowableBlendingHours - (double) absBlendHoursCount) / - (double) (_allowableBlendingHours); - - double adjustmentValue = (_baseBlendAmount * fadeFactor); - - adjustmentMeasurement = new AbsTimeMeasurement(origFcstMeasurement); //conveniently copies units and time - adjustmentMeasurement.setValue(adjustmentValue); - - - if (_debug) - { - if (_blendHoursCount > 0) - { - System.out.print(header + "Forward blend for " + - DbTimeHelper.getDateTimeStringFromLongTime(origFcstMeasurement.getTime()) + " "); - } - else - { - System.out.print(header + "Backward blend for " + - DbTimeHelper.getDateTimeStringFromLongTime(origFcstMeasurement.getTime()) + " "); - } - - System.out.println("blending adjustment value = " + adjustmentValue); - - System.out.println(header + "raw blendAmount = " + _baseBlendAmount + - " fadeFactor = " + fadeFactor + - " blendHoursCount = " + _blendHoursCount + "\n"); - - } - - } //end if measurements are close in time - } //end if previous pair != null - - - //make sure that there are no null adjustments, - // if they are null at this point, make it a 0.0 adjustment - if (adjustmentMeasurement == null) - { - adjustmentMeasurement = new AbsTimeMeasurement(origFcstMeasurement); - adjustmentMeasurement.setValue(0.0); - } - - return adjustmentMeasurement; - - } //end getBlendAdjustment() - // ----------------------------------------------------------------------------------------- - -} //end class ForecastBlender diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastInterpolationMethod.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastInterpolationMethod.java deleted file mode 100644 index 7be27de389..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ForecastInterpolationMethod.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Created on Sep 3, 2004 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * This follows the java enum pattern with private constructors and public static final instances. - */ -public class ForecastInterpolationMethod -{ - private String _methodName = null; - - public static final ForecastInterpolationMethod DIFFERENCE = new ForecastInterpolationMethod("DIFFERENCE"); - public static final ForecastInterpolationMethod RATIO = new ForecastInterpolationMethod("RATIO"); - - - private static String[] _methodNameArray = { "DIFF", "DIFFERENCE", "RATIO" }; - - private static ForecastInterpolationMethod[] _methodArray = { DIFFERENCE, DIFFERENCE, RATIO }; - - // ------------------------------------------------------------------------------------- - - private ForecastInterpolationMethod(String methodName) - { - _methodName = methodName; - - return; - } - - // ------------------------------------------------------------------------------------- - public static ForecastInterpolationMethod getMethodByName(String methodName) - { - ForecastInterpolationMethod method = DIFFERENCE; //this is the default - - for (int i = 0; i < _methodNameArray.length; i++ ) - { - if (_methodNameArray[i].equalsIgnoreCase(methodName)) - { - method = _methodArray[i]; - break; - } - } - - return method; - } - // ------------------------------------------------------------------------------------- - - public String getName() - { - return _methodName; - - } - // ------------------------------------------------------------------------------------- - public String toString() - { - String outString = null; - - outString = "methodName = " + getName(); - - return outString; - - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/LocationDescriptor.java b/cave/ohd.hseb.common/src/ohd/hseb/model/LocationDescriptor.java deleted file mode 100644 index 1a1d917467..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/LocationDescriptor.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Created on Oct 8, 2004 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * - */ -public class LocationDescriptor -{ - private String _id; - private String _locationName; - private String _streamName; - private String _basinId; - private String _hsa; - private String _modelPreference; - // ------------------------------------------------------------------------------------------------ - /** - * @param id The id to set. - */ - public void setId(String id) - { - _id = id; - } - /** - * @return Returns the id. - */ - public String getId() - { - return _id; - } -// ------------------------------------------------------------------------------------------------ - - /** - * @param name The name to set. - */ - public void setLocationName(String locationName) - { - _locationName = locationName; - } - /** - * @return Returns the name. - */ - public String getLocationName() - { - return _locationName; - } -// ------------------------------------------------------------------------------------------------ - - /** - * @param streamName The streamName to set. - */ - public void setStreamName(String streamName) - { - _streamName = streamName; - } - /** - * @return Returns the streamName. - */ - public String getStreamName() - { - return _streamName; - } -// ------------------------------------------------------------------------------------------------ - - /** - * @param basinName The basinName to set. - */ - public void setBasinId(String basinId) - { - _basinId = basinId; - } - /** - * @return Returns the basinName. - */ - public String getBasinId() - { - return _basinId; - } -// ------------------------------------------------------------------------------------------------ - public void setHsa(String hsa) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } -// ------------------------------------------------------------------------------------------------ - public void setModelPreference(String modelPreference) - { - _modelPreference = modelPreference; - } - public String getModelPreference() - { - return _modelPreference; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/MonthlyValues.java b/cave/ohd.hseb.common/src/ohd/hseb/model/MonthlyValues.java deleted file mode 100644 index 313465e9b8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/MonthlyValues.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Created on Jan 20, 2004 - * - * - */ -package ohd.hseb.model; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; - -import ohd.hseb.db.DbTimeHelper; - -/** - * @author GobsC - * - * This class encapsulates the double precision floating point values - * that are stored for each month. - */ -public class MonthlyValues -{ - private String _basinId = null; - private String _pe = null; - private short _dur = 0; - private String _ts = null; - private String _extremum = null; - private boolean _adjustment = false; - private long _postingTime = 0; - private double[] _valueArray = new double[12]; - private int _monthsInYear = 12; - - - // ------------------------------------------------------------ - - public MonthlyValues() - { - } //MonthlyValues() - - // ------------------------------------------------------------ - public MonthlyValues(double[] valueArray) - { - setValues(valueArray); - } //MonthlyValues() - - // ------------------------------------------------------------ - public void setValues(double[] valueArray) - { - for (int i = 0 ; i < valueArray.length && - i < _monthsInYear ; i++) - { - _valueArray[i] = valueArray[i]; - } - - } //setValues() - // ------------------------------------------------------------ - - // ------------------------------------------------------------ - - public double getValue(long time) - { - double value = 0.0; - //this method returns an interpolated daily value - - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(new Date(time)); - - - // extract needed info based on the current time - int monthIndex = cal.get(Calendar.MONTH); - int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); - int year = cal.get(Calendar.YEAR); - - int year1 = year; - int year2 = year; - - - int currentMonth = monthIndex; - - double month1Value = 0; - double month2Value = 0; - - double weight1 = 0; - double weight2 = 0; - - double monthToMonthDayDistance = 0.0; - double month1ToDayDistance = 0.0; - double month2ToDayDistance = 0.0; - - - //determine which months to interpolate against - if (dayOfMonth == 16) - { - value = _valueArray[currentMonth]; - - month1Value = _valueArray[currentMonth]; - month2Value = 0; - - monthToMonthDayDistance = 1; - - month1ToDayDistance = 0; - month2ToDayDistance = 1; - } - else if (dayOfMonth < 16) - { - int previousMonth = monthIndex-1; - if (previousMonth < Calendar.JANUARY) - { - previousMonth = Calendar.DECEMBER; - year1 = year - 1; - } - - month1Value = _valueArray[previousMonth]; - month2Value = _valueArray[currentMonth]; - - monthToMonthDayDistance = getDayDistance(year1, previousMonth, 16, year2, currentMonth, 16); - - month1ToDayDistance = getDayDistance(year1, previousMonth, 16, year2, currentMonth, dayOfMonth); - month2ToDayDistance = getDayDistance(year2, currentMonth, dayOfMonth, year2, currentMonth, 16); - - } - - else //dayOfMonth > 16 - { - - int nextMonth = currentMonth + 1; - if (nextMonth > Calendar.DECEMBER) - { - nextMonth = Calendar.JANUARY; - year2 = year + 1; - } - - month1Value = _valueArray[currentMonth]; - month2Value = _valueArray[nextMonth]; - - monthToMonthDayDistance = getDayDistance(year1, currentMonth, 16, year2, nextMonth, 16); - - month1ToDayDistance = getDayDistance(year1, currentMonth, 16, year1, currentMonth, dayOfMonth); - month2ToDayDistance = getDayDistance(year1, currentMonth, dayOfMonth, year2, nextMonth, 16); - - } - - - weight1 = (1.0 - (month1ToDayDistance/monthToMonthDayDistance)); - weight2 = (1.0 - (month2ToDayDistance/monthToMonthDayDistance)); - - - value = (weight1 * month1Value) + (weight2 * month2Value); - - return value; - } - - // ------------------------------------------------------------ - - private double getDayDistance(int year1, int month1, int day1, - int year2, int month2, int day2) - { - int daysInYear1 = 365; - - if (isLeapYear(year1)) - { - daysInYear1 = 366; - } - - GregorianCalendar cal1 = new GregorianCalendar(year1, month1, day1); - int dayOfYear1 = cal1.get(Calendar.DAY_OF_YEAR); - - GregorianCalendar cal2 = new GregorianCalendar(year2, month2, day2); - int dayOfYear2 = cal2.get(Calendar.DAY_OF_YEAR); - - //if there is a year change, make the first day of the second year - // start at 366 or 367 - - if (year2 != year1) - { - dayOfYear2 += daysInYear1; - } - - int dayDistance = dayOfYear2 - dayOfYear1; - - - return dayDistance; - - } //end getDayDistance() - - // ------------------------------------------------------------ - - private boolean isLeapYear(int year) - { - boolean isLeap = false; - - if ((year % 4) == 0) - { - if ((year % 100) == 0) - { - if ((year % 400) == 0 ) //2000 is a leap year, 1900 and 2100 are not - { - isLeap = true; - } - else - { - isLeap = false; - } - } - else - { - isLeap = true; - } - } - else - { - isLeap = false; - } - - return isLeap; - } //end isLeapYear() - - // ------------------------------------------------------------ - public static void main (String[] args) - { - - double[] valuesArray = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, - - 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 }; - - MonthlyValues values = new MonthlyValues(valuesArray); - - final long millisPerDay = 1000 * 60 * 60 * 24; - long currentTime = System.currentTimeMillis(); - long todayTime = (currentTime / millisPerDay) * millisPerDay; - - todayTime += 1000 * 3600 *12; //add 12 hours - - long loopTime = todayTime; - int daysInYear = 365; - - for (int i = 0; i < daysInYear; i++) - { - String dateString = DbTimeHelper.getDateStringFromLongTime(loopTime); - - String dateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(loopTime); - - double value = values.getValue(loopTime); - System.out.println("On " + dateString + " at " + dateTimeString + ", the value is " + value); - - - loopTime += millisPerDay; - } - - - } - - public String getBasinId() - { - return _basinId; - } - - public long getPostingTime() - { - return _postingTime; - } - - public void setBasinId( String basinId) - { - _basinId = basinId; - } - - public void setPostingTime( long postingTime ) - { - _postingTime = postingTime; - } - - public double[] getValueArray() - { - double[] valueArray = new double[ _valueArray.length ]; - - for ( int i = 0; i < _valueArray.length; i++ ) - { - valueArray[ i ] = _valueArray[ i ]; - } - return valueArray; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( short dur ) - { - _dur = dur; - } - - public short getDur() - { - return _dur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setAdjustment( boolean adjustment ) - { - _adjustment = adjustment; - } - - public boolean isAdjustment() - { - return _adjustment; - } - - // ------------------------------------------------------------ - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ObservedForecastMeasurementPair.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ObservedForecastMeasurementPair.java deleted file mode 100644 index 75ef17d9c5..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ObservedForecastMeasurementPair.java +++ /dev/null @@ -1,64 +0,0 @@ -package ohd.hseb.model; - -import ohd.hseb.measurement.AbsTimeMeasurement; - - -/** - * @author Chip Gobs - * - * Contains a pair of Measurements - */ -public class ObservedForecastMeasurementPair -{ - private AbsTimeMeasurement _observedMeasurement; - private AbsTimeMeasurement _forecastMeasurement; - - // ---------------------------------------------------------------------------------------------- - - public ObservedForecastMeasurementPair(AbsTimeMeasurement observedMeasurement, - AbsTimeMeasurement forecastMeasurement) - { - setObservedMeasurement(observedMeasurement); - setForecastMeasurement(forecastMeasurement); - - return; - } - - public void setObservedMeasurement(AbsTimeMeasurement observedMeasurement) - { - _observedMeasurement = new AbsTimeMeasurement(observedMeasurement); - } - - public AbsTimeMeasurement getObservedMeasurement() - { - return _observedMeasurement; - } - - public void setForecastMeasurement(AbsTimeMeasurement forecastMeasurement) - { - _forecastMeasurement = new AbsTimeMeasurement(forecastMeasurement); - } - - public AbsTimeMeasurement getForecastMeasurement() - { - return _forecastMeasurement; - } - - public int hashCode() - { - return _observedMeasurement.hashCode() + _forecastMeasurement.hashCode(); - } - - public String toString() - { - String outString = "Observed: " + _observedMeasurement.toString() + - " Forecast: " + _forecastMeasurement.toString(); - - - return outString; - } - - // ---------------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/ParamCode.java b/cave/ohd.hseb.common/src/ohd/hseb/model/ParamCode.java deleted file mode 100644 index 97366722da..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/ParamCode.java +++ /dev/null @@ -1,266 +0,0 @@ -package ohd.hseb.model; - -import java.util.HashMap; -import java.util.Map; - -public class ParamCode -{ - private String _paramCodeString = null; - - private static final Map _shefDurCodeToIhfsDurCodeMap = new HashMap(); - private static final Map _ihfsDurCodeToShefDurCodeMap = new HashMap(); - - private String _pe = null; - private String _typeSource = null; - private int _ihfsDur = 0; - private String _shefDur = null; - private String _extremum = null; - - static - { - initDurationCodeMaps(); - } - - // ------------------------------------------------------------------------------- - public ParamCode(String paramCodeString) - { - _paramCodeString = paramCodeString; - parse(paramCodeString); - - return; - } - // ------------------------------------------------------------------------------- - - public ParamCode(ParamCode paramCode) - { - _pe = paramCode.getPe(); - _typeSource = paramCode.getTypeSource(); - _ihfsDur = paramCode.getIhfsDur(); - _shefDur = paramCode.getShefDur(); - _extremum = paramCode.getExtremum(); - _paramCodeString = paramCode._paramCodeString; - - - return; - } - // ------------------------------------------------------------------------------- - // ------------------------------------------------------------------------------- - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getPe() + - getShefDur() + - getTypeSource() + - getExtremum() ); - - return buffer.toString(); - - - } - - // ------------------------------------------------------------------------------- - - public String toStringVerbose() - { - StringBuffer buffer = new StringBuffer(); - - - buffer.append("pe = " + getPe() + - " dur = " + getIhfsDur() + - " ts = " + getTypeSource() + - " extremum = " + getExtremum() ); - - return buffer.toString(); - - } - // ------------------------------------------------------------------------------- - - private void parse(String paramCodeString) - { - - setPe(paramCodeString.substring(0,2)); - _shefDur = paramCodeString.substring(2,3); - - _ihfsDur = getIhfsDurationCode(_shefDur); - - setTypeSource(paramCodeString.substring(3,5)); - setExtremum(paramCodeString.substring(5,6)); - - return; - } - // ------------------------------------------------------------------------------- - private static void initDurationCodeMaps() - { - - /* - 0 | I | Instantaneous - 1 | U | 1 Minute - 15 | C | 15 Minutes - 30 | J | 30 Minutes - 1001 | H | 1 Hour - 1002 | B | 2 Hour - 1003 | T | 3 Hour - 1004 | F | 4 Hour - 1006 | Q | 6 Hour - 1008 | A | 8 Hour - 1012 | K | 12 Hour - 1018 | L | 18 Hour - 2001 | D | 1 Day - 2007 | W | 1 Week - 3001 | M | 1 Month - 4001 | Y | 1 Year - 5000 | Z | Unspecified - 5001 | S | Seasonal - 5002 | R | Period of Record - 5004 | P | Total Since 7 AM - 5005 | X | Unknown - - */ - - - String code = "?"; - - String charCodeString = "IUCJHBTFQAKLDWMYZSRPX"; - - int intCodeArray[] = { 0, 1, 15, 30, - 1001, 1002, 1003, 1004, 1006, 1008, 1012, 1018, - 2001, 2007, - 3001, - 4001, - 5000, 5001, 5002, 5004, 5005 }; - - - - int i = 0; - - for (i = 0; i < charCodeString.length(); i++) - { - String shefCode = charCodeString.substring(i, i+1); - Integer intCode = new Integer(intCodeArray[i]); - - _shefDurCodeToIhfsDurCodeMap.put(shefCode, intCode); - _ihfsDurCodeToShefDurCodeMap.put(intCode, shefCode); - } - - return; - - } - // ------------------------------------------------------------------------------- - public static int getIhfsDurationCode(String shefDurationCode) - { - int ihfsCode = -1; - Integer ihfsCodeInteger = (Integer) _shefDurCodeToIhfsDurCodeMap.get(shefDurationCode); - - if (ihfsCodeInteger != null) - { - ihfsCode = ihfsCodeInteger.intValue(); - } - - return ihfsCode; - } - // ------------------------------------------------------------------------------- - public static String getShefDurationCode(int ihfsDurationCode) - { - String shefDurationCode = "?"; - - Integer ihfsDurationCodeInteger = new Integer(ihfsDurationCode); - - String shefDurationCodeFromMap = - (String) _ihfsDurCodeToShefDurCodeMap.get(ihfsDurationCodeInteger); - - if (shefDurationCodeFromMap != null) - { - shefDurationCode = shefDurationCodeFromMap; - } - - return shefDurationCode; - } - /** - * @param pe The pe to set. - */ - public void setPe(String pe) - { - _pe = pe; - } - /** - * @return Returns the pe. - */ - public String getPe() - { - return _pe; - } - /** - * @param typeSource The typeSource to set. - */ - public void setTypeSource(String typeSource) - { - _typeSource = typeSource; - } - /** - * @return Returns the typeSource. - */ - public String getTypeSource() - { - return _typeSource; - } - /** - * @param ihfsDur The ihfsDur to set. - */ - public void setIhfsDur(int ihfsDur) - { - _ihfsDur = ihfsDur; - } - /** - * @return Returns the ihfsDur. - */ - public int getIhfsDur() - { - return _ihfsDur; - } - /** - * @param shefDur The shefDur to set. - */ - public void setShefDur(String shefDur) - { - _shefDur = shefDur; - } - /** - * @return Returns the shefDur. - */ - public String getShefDur() - { - return _shefDur; - } - /** - * @param extremum The extremum to set. - */ - public void setExtremum(String extremum) - { - _extremum = extremum; - } - /** - * @return Returns the extremum. - */ - public String getExtremum() - { - return _extremum; - } - - // ------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - ParamCode code = null; - - code = new ParamCode("HGIRGZ"); - System.out.println("code = " + code.toString()); - - - code = new ParamCode("HPIRZX"); - System.out.println("code = " + code.toString()); - - } - - // ------------------------------------------------------------------------------- - -} //end ParamCode diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/PrecipPPAndPCValueMapper.java b/cave/ohd.hseb.common/src/ohd/hseb/model/PrecipPPAndPCValueMapper.java deleted file mode 100644 index 8ad071a110..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/PrecipPPAndPCValueMapper.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.ValueMapper; - -/** - * @author GobsC - * - * - */ -public class PrecipPPAndPCValueMapper implements ValueMapper -{ - - private MeasuringUnit _inputMeasuringUnit = null; - private MeasuringUnit _outputMeasuringUnit = null; - private double _difference = 0; - - // -------------------------------------------------------------------------- - - public PrecipPPAndPCValueMapper(double minValue1, - double minValue2, - MeasuringUnit unit) - { - _difference = minValue2 - minValue1; - - _inputMeasuringUnit = unit; - _outputMeasuringUnit = unit; - - return; - } - - // -------------------------------------------------------------------------- - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement convertedMeasurement = inputMeasurement.getCopy(); - double value = convertedMeasurement.getValue(); - value += _difference; - - convertedMeasurement.setValue(value); - - return convertedMeasurement; - - } - - // -------------------------------------------------------------------------- - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - // -------------------------------------------------------------------------- - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - // -------------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallRunoffModel.java b/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallRunoffModel.java deleted file mode 100644 index 31ed7ccc44..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallRunoffModel.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Created on Nov 4, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.RegularTimeSeries; - -/** - * @author Chip Gobs - * - * This interface is made to be implemented by various - * specific rainfall-runoff models - * - **/ -public interface RainfallRunoffModel -{ - public RegularTimeSeries calculateRunoff(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries - ); - - public RainfallRunoffModelType getModelType(); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallRunoffModelType.java b/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallRunoffModelType.java deleted file mode 100644 index f79eb5a8f2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallRunoffModelType.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Created on Nov 5, 2003 - * - */ - -package ohd.hseb.model; - -/** - * @author Chip Gobs - */ -public class RainfallRunoffModelType -{ - - public static RainfallRunoffModelType SAC_SMA = new RainfallRunoffModelType("SAC-SMA"); - public static RainfallRunoffModelType API_MKC = new RainfallRunoffModelType("API-MKC"); - - private static final RainfallRunoffModelType[] _modelTypeArray = { API_MKC, SAC_SMA }; - - private String _name; - - private RainfallRunoffModelType(String name) - { - _name = name; - } - - /** - * This method returns a RainfallRunoffModelType, based on a name lookup. If no match is found, then the passed in - * default type is returned. The default type can be null if desired. - * @param name The name of the RainfallRunoffModelType - * @return - */ - public static RainfallRunoffModelType getRainfallRunoffModelTypeByName(String name, RainfallRunoffModelType defaultType) - { - RainfallRunoffModelType returnType = defaultType; - - for (RainfallRunoffModelType type : _modelTypeArray) - { - if (name.equalsIgnoreCase(type.getName())) - { - returnType = type; - } - } - - return returnType; - } - - /** - * This method returns a RainfallRunoffModelType, based on a name lookup. If no match is found, then the - * default type of API_MKC is returned. - * @param name The name of the RainfallRunoffModelType - * @return - */ - public static RainfallRunoffModelType getRainfallRunoffModelTypeByName(String name) - { - return getRainfallRunoffModelTypeByName(name, RainfallRunoffModelType.API_MKC); - } - - - - public static RainfallRunoffModelType[] getModelTypeArray() - { - return _modelTypeArray; - } - - public String getName() - { - return _name; - } - - public String toString() - { - return _name; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallToStageModel.java b/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallToStageModel.java deleted file mode 100644 index 7e2565535c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/RainfallToStageModel.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; - -/** - * @author Chip Gobs - * - * This class combines the RainfallRunoffModel - * with a UnitHydrograph and a Rating Curve to output a TimeSeries object. - */ -public interface RainfallToStageModel -{ - - -// ------------------------------------------------------------- - - - public RegularTimeSeries calculateStageTimeSeries(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries, - RegularTimeSeriesHolder runOffTimeSeriesHolder); - - - -} //end interface RainfallToStageModel \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/RatingCurve.java b/cave/ohd.hseb.common/src/ohd/hseb/model/RatingCurve.java deleted file mode 100644 index b36b270141..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/RatingCurve.java +++ /dev/null @@ -1,573 +0,0 @@ -/* - * Created on Jul 7, 2003 - * - * Conversion routines modified from code by Russ Erb. - */ -package ohd.hseb.model; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -/** - * @author Chip Gobs - * - * This class contains all the data associated with - * a RatingCurve and allows for conversion to and from discharge and stage. - * It is not aware of the database. - * The RatingShift still needs to be accounted for; this could be done - * with the code that loads the RatingCurve in the first place. - */ -public class RatingCurve -{ - private String _locationId = null; - - private double _shiftAmount = 0.0; - - private String _usgsRatingNumber = null; - private long _ratingDate = 0; - - private List _ratingPointList = new ArrayList(); - - private int _millisPerHour = 60 * 60 * 1000; - - private MeasuringUnit _stageUnit = MeasuringUnit.feet; - private MeasuringUnit _dischargeUnit = MeasuringUnit.cfs; - - //--------------------------------------------------------------------- - public RatingCurve(String locationId) - { - setLocationId(locationId); - } - - public static RatingCurve getTestRatingCurve(String testLocationId) - { - RatingCurve rc = new RatingCurve(testLocationId); - double[] flowArray = {0.0, 5, 20, 30, 50, 100, 250, 400, 600, 800, 1000 }; - double[] stageArray = {0.0, .1, 1, 2, 5, 8, 9, 12.5, 15, 17, 19}; - - for (int i = 0; i < flowArray.length; i++) - { - RatingPoint point = new RatingPoint(); - point.setDischarge(flowArray[i]); - point.setUnshiftedStage(stageArray[i]); - - rc.addRatingPoint(point); - } - - return rc; - } - - public void setLocationId(String locationId) - { - _locationId = locationId; - } - - public String getLocationId() - { - return _locationId; - } - - public void setUsgsRatingNumber(String usgsRatingNumber) - { - _usgsRatingNumber = usgsRatingNumber; - } - - public String getUsgsRatingNumber() - { - return _usgsRatingNumber; - } - - public void setRatingDate(long ratingDate) - { - _ratingDate = ratingDate; - } - - public long getRatingDate() - { - return _ratingDate; - } - // --------------------------------------------------------------------- - - public void setShiftAmount(double shiftAmount) - { - _shiftAmount = shiftAmount; - - //update all of the associated ratingPoints - for (int i = 0; i < _ratingPointList.size(); i++) - { - RatingPoint ratingPoint = (RatingPoint) _ratingPointList.get(i); - ratingPoint.setShiftAmount(_shiftAmount); - } - } - - // --------------------------------------------------------------------- - - - public double getShiftAmount() - { - return _shiftAmount; - } - // --------------------------------------------------------------------- - - public boolean exists() - { - boolean result = false; - - if (_ratingPointList.size() > 1) - { - result = true; - } - - return result; - } - // --------------------------------------------------------------------- - - public void addRatingShift() - { - - } - // --------------------------------------------------------------------- - public List getRatingPointList() - { - List newList = new ArrayList(); - for (int i = 0; i < _ratingPointList.size(); i++) - { - RatingPoint point = (RatingPoint) _ratingPointList.get(i); - newList.add(point); - } - - return newList; - } - - // --------------------------------------------------------------------- - - public int getRatingPointCount() - { - return _ratingPointList.size(); - } - - public RatingPoint getRatingPoint(int index) - { - RatingPoint point = null; - - if ((index >= 0) && (index <= _ratingPointList.size() ) ) - point = (RatingPoint) _ratingPointList.get(index); - - return point; - } -// --------------------------------------------------------------------- - public RatingPoint getFirstRatingPoint() - { - RatingPoint point = null; - - point = getRatingPoint(0); - - return point; - } -// --------------------------------------------------------------------- - public RatingPoint getSecondRatingPoint() - { - RatingPoint point = null; - point = getRatingPoint(1); - - return point; - } -// --------------------------------------------------------------------- - public RatingPoint getLastRatingPoint() - { - RatingPoint point = null; - - point = getRatingPoint(_ratingPointList.size() - 1); - - return point; - } -// --------------------------------------------------------------------- - - public RatingPoint getNextToLastRatingPoint() - { - RatingPoint point = null; - - point = getRatingPoint(_ratingPointList.size() - 2); - - return point; - } -// --------------------------------------------------------------------- - public void addRatingPoint(RatingPoint newPoint) - { - //insert the RatingPoint at the correct point - // in order to keep the list in ascending sorted order by stage - - newPoint.setShiftAmount(_shiftAmount); - - double stage = newPoint.getShiftedStage(); - boolean inserted = false; - - - if (_ratingPointList.size() == 0) - { - _ratingPointList.add(newPoint); - inserted = true; - } - else - { - for (int i = 0; i < _ratingPointList.size() && !inserted; i++) - { - RatingPoint curPoint = (RatingPoint) _ratingPointList.get(i); - if (stage < curPoint.getShiftedStage()) - { - _ratingPointList.add(i, newPoint); - inserted = true; - } - else if (stage == curPoint.getShiftedStage()) - { - _ratingPointList.add(i, newPoint); - inserted = true; - removeRatingPoint(curPoint); - } - - } - if (!inserted) - { - //need to add to the end of the list - _ratingPointList.add(newPoint); - } - } //end else - - return; - } -// --------------------------------------------------------------------- - public boolean removeRatingPoint(RatingPoint ratingPoint) - { - //remove the RatingPoint if a match exists in the list - // - boolean removed = false; - - for (int i = 0; i < _ratingPointList.size() && ! removed ; i++) - { - RatingPoint curPoint = (RatingPoint) _ratingPointList.get(i); - if (curPoint.equals(ratingPoint)) - { - _ratingPointList.remove(ratingPoint); - removed = true; - } - } - - return removed; - } -// --------------------------------------------------------------------- - - public IrregularTimeSeries getStageTimeSeries(IrregularTimeSeries flowTimeSeries) - { - //includes the shift - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(MeasuringUnit.feet); - - for (int i = 0; i < flowTimeSeries.getMeasurementCount(); i++) - { - AbsTimeMeasurement flowMeasurement = flowTimeSeries.getAbsTimeMeasurementByIndex(i); - - double stageValue = getStageFromDischarge(flowMeasurement.getValue()); - AbsTimeMeasurement stageMeasurement = new AbsTimeMeasurement(stageValue, - flowMeasurement.getTime(), - MeasuringUnit.feet); - - stageTimeSeries.insertMeasurement(stageMeasurement); - - } //end for - - return stageTimeSeries; - } - -// --------------------------------------------------------------------- - public IrregularTimeSeries getDischargeIrregularTimeSeries(IrregularTimeSeries stageTimeSeries) - { - //ensure input units are correct - stageTimeSeries.convert(_stageUnit); - - - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(_dischargeUnit); - - for (int i = 0; i < stageTimeSeries.getMeasurementCount(); i++) - { - AbsTimeMeasurement stageMeasurement = stageTimeSeries.getAbsTimeMeasurementByIndex(i); - - double dischargeValue = getDischargeFromStage(stageMeasurement.getValue()); - long time = stageMeasurement.getTime(); - AbsTimeMeasurement dischargeMeasurement = - new AbsTimeMeasurement(dischargeValue, time, _dischargeUnit); - - dischargeTimeSeries.insertMeasurement(dischargeMeasurement); - - } //end for - - return dischargeTimeSeries; - - - - } - -// --------------------------------------------------------------------- - - public RegularTimeSeries getStageRegularTimeSeries(RegularTimeSeries flowTimeSeries) - { - - //ensure units are correct - flowTimeSeries.convert(_dischargeUnit); - - - // get info about flowTimeSeries - long startTime = flowTimeSeries.getStartTime(); - long endTime = flowTimeSeries.getEndTime(); - int intervalInHours = flowTimeSeries.getIntervalInHours(); - int intervalInMillis = intervalInHours * _millisPerHour; - - - RegularTimeSeries stageTimeSeries = new RegularTimeSeries(startTime, endTime, - intervalInHours, _stageUnit); - - - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement flowMeasurement = flowTimeSeries.getMeasurementByTime(time); - - double stageValue = getStageFromDischarge(flowMeasurement.getValue()); - Measurement stageMeasurement = new Measurement(stageValue, - _stageUnit); - - stageTimeSeries.setMeasurementByTime(stageMeasurement, time); - - } //end for - - return stageTimeSeries; - - } //end getStageRegularTimeSeries -// --------------------------------------------------------------------- - - public RegularTimeSeries getDischargeRegularTimeSeries(RegularTimeSeries stageTimeSeries) - { - - //ensure input units are correct - stageTimeSeries.convert(_stageUnit); - - - // get info about flowTimeSeries - long startTime = stageTimeSeries.getStartTime(); - long endTime = stageTimeSeries.getEndTime(); - int intervalInHours = stageTimeSeries.getIntervalInHours(); - int intervalInMillis = intervalInHours * _millisPerHour; - - - RegularTimeSeries flowTimeSeries = new RegularTimeSeries(startTime, endTime, - intervalInHours, _dischargeUnit); - - - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement stageMeasurement = stageTimeSeries.getMeasurementByTime(time); - - double flowValue = getDischargeFromStage(stageMeasurement.getValue()); - Measurement flowMeasurement = new Measurement(flowValue, - _dischargeUnit); - - flowTimeSeries.setMeasurementByTime(flowMeasurement, time); - - } //end for - - return flowTimeSeries; - - } //end getFlowRegularTimeSeries - - -// --------------------------------------------------------------------- - -// ***************************************************************************** -// taken from Russ Erb's code -// stageToDischarge() - this method is called with a stage value and returns -// the corresponding discharge -// ***************************************************************************** - public double getDischargeFromStage(double stage) - { - - RatingPoint firstStage = new RatingPoint(); - RatingPoint lastStage = new RatingPoint(); - RatingPoint lowerStage = new RatingPoint(); - RatingPoint higherStage = new RatingPoint(); - - double discharge=0.0; - double diff_discharge=0.0; - double diff_stage=0.0; - - // if the rating curve doesn't exist then return -999 - if (! this.exists()) - return(-999.0); - - // if the stage value passed in is less then the lowest stage in the - // rating table then extrapolate the discharge - firstStage = getFirstRatingPoint(); - if (stage < firstStage.getShiftedStage()) - { - higherStage = getSecondRatingPoint(); - diff_discharge = higherStage.getDischarge() - firstStage.getDischarge(); - diff_stage = higherStage.getShiftedStage() - firstStage.getShiftedStage(); - if (diff_stage == 0.0) - discharge = firstStage.getDischarge(); - else - discharge = firstStage.getDischarge() - ((diff_discharge/diff_stage) * (firstStage.getShiftedStage() - stage)); - } - - // if the stage value passed in is greater then the highest stage in the - // rating table then extrapolate the discharge - lastStage = getLastRatingPoint(); - if (stage > lastStage.getShiftedStage()) - { - lowerStage = getNextToLastRatingPoint(); - diff_discharge = lastStage.getDischarge() - lowerStage.getDischarge(); - diff_stage = lastStage.getShiftedStage() - lowerStage.getShiftedStage(); - if (diff_stage == 0.0) - discharge = lastStage.getDischarge(); - else - discharge = lastStage.getDischarge() + ((diff_discharge/diff_stage) * (stage - lastStage.getShiftedStage())); - } - - // if the stage value passed in is between the lowest and highest stage - // in the rating table then interpolate the discharge - if ( (stage >= firstStage.getShiftedStage()) && (stage <= lastStage.getShiftedStage()) ) - { - for (int ctr=0; ctr< _ratingPointList.size()-1; ctr++) - { - lowerStage = getRatingPoint(ctr); - higherStage = getRatingPoint(ctr+1); - if ( (stage >= lowerStage.getShiftedStage()) && (stage <= higherStage.getShiftedStage()) ) - { - diff_discharge = higherStage.getDischarge() - lowerStage.getDischarge(); - diff_stage = higherStage.getShiftedStage() - lowerStage.getShiftedStage(); - - if (diff_stage == 0.0) - discharge = lowerStage.getDischarge(); - else - discharge = lowerStage.getDischarge() + ((diff_discharge/diff_stage) * (stage - lowerStage.getShiftedStage())); - - break; - } - } //end for - } //end if - - // for some reason the discharge is less than zero then return zero - if (discharge < 0.0) - return(0.0); - else - return(discharge); - - } // end of stageToDischarge method - - -// ***************************************************************************** -// taken from Russ Erb's code -// dischargeToStage() - this method is called with a discharge value and returns -// the corresponding stage -// ***************************************************************************** - public double getStageFromDischarge(double discharge) - { - - RatingPoint firstDischarge = new RatingPoint(); - RatingPoint lastDischarge = new RatingPoint(); - RatingPoint lowerDischarge = new RatingPoint(); - RatingPoint higherDischarge = new RatingPoint(); - - double stage=0.0; - double diff_discharge=0.0; - double diff_stage=0.0; - - // if the rating curve doesn't exist then return -999 - if (! this.exists()) - return(-999.0); - - // if the discharge value passed in is less then the lowest discharge in the - // rating table then extrapolate the stage - firstDischarge = getFirstRatingPoint(); - if (discharge < firstDischarge.getDischarge()) - { - higherDischarge = getSecondRatingPoint(); - diff_discharge = higherDischarge.getDischarge() - firstDischarge.getDischarge(); - diff_stage = higherDischarge.getShiftedStage() - firstDischarge.getShiftedStage(); - if (diff_discharge == 0.0) - stage = firstDischarge.getShiftedStage(); - else - stage = firstDischarge.getShiftedStage() - ((diff_stage/diff_discharge) * (firstDischarge.getDischarge() - discharge)); - } - - // if the discharge value passed in is greater then the highest discharge in the - // rating table then extrapolate the stage - lastDischarge = getLastRatingPoint(); - if (discharge > lastDischarge.getDischarge()) - { - lowerDischarge = getNextToLastRatingPoint(); - diff_discharge = lastDischarge.getDischarge() - lowerDischarge.getDischarge(); - diff_stage = lastDischarge.getShiftedStage() - lowerDischarge.getShiftedStage(); - if (diff_discharge == 0.0) - stage = lastDischarge.getShiftedStage(); - else - stage = lastDischarge.getShiftedStage() + ((diff_stage/diff_discharge) * (discharge - lastDischarge.getDischarge())); - } - - // if the discharge value passed in is between the lowest and highest discharge - // in the rating table then interpolate the stage - if ( (discharge >= firstDischarge.getDischarge()) && (discharge <= lastDischarge.getDischarge()) ) - { - for (int ctr=0; ctr< _ratingPointList.size()-1; ctr++) - { - lowerDischarge = getRatingPoint(ctr); - higherDischarge = getRatingPoint(ctr+1); - if ( (discharge >= lowerDischarge.getDischarge()) && (discharge <= higherDischarge.getDischarge()) ) - { - diff_discharge = higherDischarge.getDischarge() - lowerDischarge.getDischarge(); - diff_stage = higherDischarge.getShiftedStage() - lowerDischarge.getShiftedStage(); - - if (diff_discharge == 0.0) - stage = lowerDischarge.getShiftedStage(); - else - stage = lowerDischarge.getShiftedStage() + ((diff_stage/diff_discharge) * (discharge - lowerDischarge.getDischarge())); - - break; - } - } //end for - } //end if - - // System.out.println("discharge = " + discharge + " stage = " + stage); - - return(stage); - - } // end of dischargeToStage method - - - - -// ***************************************************************************** - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getLocationId()); - - for (int i = 0; i < getRatingPointCount() ; i++) - { - RatingPoint point = (RatingPoint) this.getRatingPoint(i); - buffer.append(point + "\n"); - } - - return buffer.toString(); - - } //end toString - - - - - -} //end class RatingCurve diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/RatingPoint.java b/cave/ohd.hseb.common/src/ohd/hseb/model/RatingPoint.java deleted file mode 100644 index 3155da9e8e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/RatingPoint.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Created on Jul 7, 2003 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * - */ -public class RatingPoint -{ - private double _shiftAmount; - private double _unshiftedStage; - private double _discharge; - -// ------------------------------------------------------------------------------------------ - public void setUnshiftedStage(double stage) - { - this._unshiftedStage = stage; - } -// ------------------------------------------------------------------------------------------ - - public double getUnshiftedStage() - { - return _unshiftedStage; - } -// ------------------------------------------------------------------------------------------ - - public void setShiftAmount(double shiftAmount) - { - _shiftAmount = shiftAmount; - } -// ------------------------------------------------------------------------------------------ - - public double getShiftedStage() - { - return _unshiftedStage + _shiftAmount; - } -// ------------------------------------------------------------------------------------------ - public void setDischarge(double discharge) - { - this._discharge = discharge; - } -// ------------------------------------------------------------------------------------------ - - public double getDischarge() - { - return _discharge; - } -// ------------------------------------------------------------------------------------------ - public boolean equals(RatingPoint point2) - { - boolean result = false; - - if ( - (this._unshiftedStage == point2._unshiftedStage) && - (this._shiftAmount == point2._shiftAmount) && - (this._discharge == point2._discharge ) - ) - { - result = true; - } - - return result; - - } -// ------------------------------------------------------------------------------------------ - - public String toString() - { - String outString = " stage = " + getUnshiftedStage() + - " discharge = " + getDischarge(); - - return outString; - } -// ------------------------------------------------------------------------------------------ - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/RatingShift.java b/cave/ohd.hseb.common/src/ohd/hseb/model/RatingShift.java deleted file mode 100644 index a486172f54..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/RatingShift.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Created on Jun 9, 2004 - * - * Filename : RatingShiftEntry.java - * Author : Gautam Sood - * Last Revision Date : Jun 9, 2004 - * - */ -/** - * @author Gautam Sood -*/ - -package ohd.hseb.model; - -public class RatingShift -{ - private String _lid = null; - - private long _date = 0; - - private double _shiftAmount = 0.0; - - private boolean _active = false; - - public RatingShift() - { - } - - public RatingShift( RatingShift ratingShift ) - { - setLid( ratingShift.getLid() ); - setDate( ratingShift.getDate() ); - setShiftAmount( ratingShift.getShiftAmount() ); - setActive( ratingShift.isActive() ); - } - - public void setLid(String lid) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - - public boolean equals( RatingShift entry ) - { - boolean isEqual = false; - - if ( ( _lid.equalsIgnoreCase( entry.getLid() ) ) && - ( _date == entry.getDate() ) ) - { - isEqual = true; - } - return isEqual; - } - - public void setDate( long date ) - { - _date = date; - } - - public long getDate() - { - return _date; - } - - public void setShiftAmount( double shiftAmount ) - { - _shiftAmount = shiftAmount; - } - - public double getShiftAmount() - { - return _shiftAmount; - } - - public void setActive( boolean active ) - { - _active = active; - } - - public boolean isActive() - { - return _active; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/SigRiverLevels.java b/cave/ohd.hseb.common/src/ohd/hseb/model/SigRiverLevels.java deleted file mode 100644 index d3ca9873fb..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/SigRiverLevels.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Created on Oct 3, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.db.DbTable; - -/** - * @author Chip Gobs - * - * - */ -public class SigRiverLevels -{ - private String _locationId = null; - - private int MISSING_VALUE = -999; - - private boolean _useStage = true; - private String _primaryPe = null; - - //stages - private double _floodStage = MISSING_VALUE; - private double _actionStage = MISSING_VALUE; - private double _minorFloodStage = MISSING_VALUE; - private double _moderateFloodStage = MISSING_VALUE; - private double _majorFloodStage = MISSING_VALUE; - - //flows - private double _floodFlow = MISSING_VALUE; - private double _actionFlow = MISSING_VALUE; - private double _minorFloodFlow = MISSING_VALUE; - private double _moderateFloodFlow = MISSING_VALUE; - private double _majorFloodFlow = MISSING_VALUE; - - //------------------------------------------------------- - - public SigRiverLevels() - { - - } - - //-------------------------------------------------------------------------------- - - public SigRiverLevels(String locationId, String primaryPe, - double floodStage, double actionStage, - double floodFlow, double actionFlow) - { - _locationId = locationId; - - _primaryPe = primaryPe; - if (_primaryPe.substring(0,1).equalsIgnoreCase("Q")) - { - _useStage = false; - } - - _floodStage = checkMissing(floodStage); - _actionStage = checkMissing(actionStage); - - _floodFlow = checkMissing(floodFlow); - _actionFlow = checkMissing(actionFlow); - - return; - } - - // ------------------------------------------------------------------------------ - private double checkMissing(double value) - { - double resultingValue = value; - - if (value == 0.0) - { - resultingValue = MISSING_VALUE; - } - - return resultingValue; - } - - //-------------------------------------------------------------------------------- - - - public void setLocationId(String locationId) - { - _locationId = locationId; - } - - //-------------------------------------------------------------------------------- - - - public String getLocationId() - { - return _locationId; - } - - //-------------------------------------------------------------------------------- - - - public void setFloodStage(double floodStage) - { - _floodStage = floodStage; - } - - //-------------------------------------------------------------------------------- - - - public double getFloodStage() - { - return _floodStage; - } - -// -------------------------------------------------------------------------------- - - private boolean hasValue(double value) - { - boolean result = true; - - if ((value == MISSING_VALUE) || (DbTable.isNull(value))) - { - result = false; - } - - return result; - } - -// -------------------------------------------------------------------------------- - - - public boolean hasFloodStage() - { - return hasValue(_floodStage); - } - -// -------------------------------------------------------------------------------- - - public boolean hasActionStage() - { - return hasValue(_actionStage); - } - -// -------------------------------------------------------------------------------- - public boolean hasMinorFloodStage() - { - return hasValue(_minorFloodStage); - } -// -------------------------------------------------------------------------------- - public boolean hasModerateFloodStage() - { - return hasValue(_moderateFloodStage); - } -// -------------------------------------------------------------------------------- - public boolean hasMajorFloodStage() - { - return hasValue(_majorFloodStage); - } - -// -------------------------------------------------------------------------------- - - public boolean hasFloodFlow() - { - return hasValue(_floodFlow); - } - -// -------------------------------------------------------------------------------- - - public boolean hasActionFlow() - { - return hasValue(_actionFlow); - } - -// -------------------------------------------------------------------------------- - public boolean hasMinorFloodFlow() - { - return hasValue(_minorFloodFlow); - } -// -------------------------------------------------------------------------------- - public boolean hasModerateFloodFlow() - { - return hasValue(_moderateFloodFlow); - } -// -------------------------------------------------------------------------------- - public boolean hasMajorFloodFlow() - { - return hasValue(_majorFloodFlow); - } - -// -------------------------------------------------------------------------------- - - public void setActionStage(double actionStage) - { - _actionStage = actionStage; - } - -// -------------------------------------------------------------------------------- - - public double getActionStage() - { - return _actionStage; - } - -// -------------------------------------------------------------------------------- - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(_locationId + "with primary pe = " + _primaryPe); - - if (hasFloodStage()) - { - buffer.append("Flood Stage = " + _floodStage + " "); - } - else - { - buffer.append("No flood stage set."); - } - - - if (hasActionStage()) - { - buffer.append("Action Stage = " + _actionStage + "\n"); - - } - else - { - buffer.append("No action stage set."); - } - - - - if (hasFloodFlow()) - { - buffer.append("Flood Flow = " + _floodFlow + " "); - } - else - { - buffer.append("No flood flow set."); - } - - - - if (hasActionFlow()) - { - buffer.append("Action Flow = " + _actionFlow + "\n"); - - } - else - { - buffer.append("No action flow set."); - } - - - String outString = buffer.toString(); - - return outString; - - } -// -------------------------------------------------------------------------------- - - - public void setPrimaryPe(String primaryPe) - { - _primaryPe = primaryPe; - } - -// -------------------------------------------------------------------------------- - - public String getPrimaryPe() - { - return _primaryPe; - } -// -------------------------------------------------------------------------------- - - public void setFloodFlow(double floodFlow) - { - _floodFlow = floodFlow; - } -// -------------------------------------------------------------------------------- - - public double getFloodFlow() - { - return _floodFlow; - } -// -------------------------------------------------------------------------------- - - - public void setActionFlow(double actionFlow) - { - _actionFlow = actionFlow; - } - -// -------------------------------------------------------------------------------- - - public double getActionFlow() - { - return _actionFlow; - } - -// -------------------------------------------------------------------------------- - - public void setUseStage(boolean useStage) - { - _useStage = useStage; - } - -// -------------------------------------------------------------------------------- - - - public boolean useStage() - { - return _useStage; - } - - public void setMinorFloodStage(double minorFloodStage) - { - _minorFloodStage = minorFloodStage; - } - - public double getMinorFloodStage() - { - return _minorFloodStage; - } - - /** - * @param moderateFloodStage The moderateFloodStage to set. - */ - public void setModerateFloodStage(double moderateFloodStage) - { - _moderateFloodStage = moderateFloodStage; - } - - /** - * @return Returns the moderateFloodStage. - */ - public double getModerateFloodStage() - { - return _moderateFloodStage; - } - - /** - * @param majorFloodStage The majorFloodStage to set. - */ - public void setMajorFloodStage(double majorFloodStage) - { - _majorFloodStage = majorFloodStage; - } - - /** - * @return Returns the majorFloodStage. - */ - public double getMajorFloodStage() - { - return _majorFloodStage; - } - - public void setMinorFloodFlow(double minorFloodFlow) - { - _minorFloodFlow = minorFloodFlow; - } - - public double getMinorFloodFlow() - { - return _minorFloodFlow; - } - - public void setModerateFloodFlow(double moderateFloodFlow) - { - _moderateFloodFlow = moderateFloodFlow; - } - - public double getModerateFloodFlow() - { - return _moderateFloodFlow; - } - - public void setMajorFloodFlow(double majorFloodFlow) - { - _majorFloodFlow = majorFloodFlow; - } - - public double getMajorFloodFlow() - { - return _majorFloodFlow; - } - -// -------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/StageToFlowValueMapper.java b/cave/ohd.hseb.common/src/ohd/hseb/model/StageToFlowValueMapper.java deleted file mode 100644 index ce3c4a0ac9..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/StageToFlowValueMapper.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Created on Oct 22, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.ValueMapper; - -/** - * @author GobsC - * - * This implementation of ValueMapper maps river stages to discharge. - */ -public class StageToFlowValueMapper implements ValueMapper -{ - private MeasuringUnit _inputMeasuringUnit = MeasuringUnit.feet; - private MeasuringUnit _outputMeasuringUnit = MeasuringUnit.cfs; - - - private RatingCurve _ratingCurve = null; - - //-------------------------------------------------------- - - public StageToFlowValueMapper(RatingCurve ratingCurve) - { - _ratingCurve = ratingCurve; - } - //-------------------------------------------------------- - - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement resultMeasurement = null; - - Measurement convertedMeasurement = - Measurement.getConvertedCopy(inputMeasurement, - _inputMeasuringUnit); - double keyValue = convertedMeasurement.getValue(); - - double resultValue = 0; - if (_ratingCurve != null) - { - resultValue = _ratingCurve.getDischargeFromStage(keyValue); - resultMeasurement = new Measurement(resultValue, - _outputMeasuringUnit); - } - - return resultMeasurement; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - //-------------------------------------------------------- - -} // StageToFlowValueMapper diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrograph.java b/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrograph.java deleted file mode 100644 index 4e4912b7a2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrograph.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Created on Jun 25, 2003 - * - * This class is designed to compute the flow from runoff. - */ -package ohd.hseb.model; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RelTimeMeasurement; - - -/** - * @author Chip Gobs - * - * The UnitHydrograph class maps runoff to the amount of marginal flow - * generated by that runoff. - * It returns a RegularTimeSeries object that contains flow measurements. - */ - - - -public class UnitHydrograph -{ - - - //input: inches of runoff - //a starting time - //output: a time series of flow in CFS - - private static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - private MeasuringUnit _measuringUnit = MeasuringUnit.cfs; - - private String _locationId = null; - private String _areaId = null; - private String _rainfallRunoffModelTypeName = null; - - private int _interval = -1; // in hours - - private List _measurementList = new ArrayList(); - - //---------------------------------------------------------------------- - - - public UnitHydrograph(MeasuringUnit measuringUnit, int intervalInHours) - { - _measuringUnit = measuringUnit; - _interval = intervalInHours; - } - - //---------------------------------------------------------------------- - - - public void setMeasuringUnit(MeasuringUnit measuringUnit) - { - _measuringUnit = measuringUnit; - } - //---------------------------------------------------------------------- - - public MeasuringUnit getMeasuringUnit() - { - return _measuringUnit; - } - //---------------------------------------------------------------------- - - public void setLocationId(String locationId) - { - _locationId = locationId; - } - //---------------------------------------------------------------------- - - public String getLocationId() - { - return _locationId; - } - //---------------------------------------------------------------------- - - public void setAreaId(String areaId) - { - _areaId = areaId; - } - //---------------------------------------------------------------------- - - public String getAreaId() - { - return _areaId; - } - //---------------------------------------------------------------------- - - public int getOrdinateCount() - { - return _measurementList.size(); - } - //---------------------------------------------------------------------- - - public List getMeasurementList() - { - return _measurementList; - } - - //---------------------------------------------------------------------- - - public void addMeasurement(RelTimeMeasurement origMeasurement) - { - RelTimeMeasurement newMeasurement = - (RelTimeMeasurement) origMeasurement.getConvertedCopy(_measuringUnit); - - _measurementList.add(newMeasurement); - - return; - } - - // ---------------------------------------------------------------------- - - public void setInterval(int interval) - { - _interval = interval; - } - - //---------------------------------------------------------------------- - - public int getIntervalInHours() - { - return _interval; - } - - //---------------------------------------------------------------------- - - public static UnitHydrograph getTestUnitHydrograph() - { - double[] valueArray = { 100.0, 200.0, 350.0, 500.0, - 300.0, 250.0, 200.0, 150.0, - 100.0, 50.0, 25.0, 10}; - - UnitHydrograph uhg = new UnitHydrograph(MeasuringUnit.cfs, 1); - - - for (int i = 0; i < valueArray.length; i++) - { - RelTimeMeasurement measurement = new RelTimeMeasurement(valueArray[i], i, MeasuringUnit.cfs); - uhg.addMeasurement(measurement); - } - - return uhg; - - } - - //---------------------------------------------------------------------- - public UnitHydrograph getScaledUnitHydrograph(double newTotalDischarge) - { - - UnitHydrograph uhg = new UnitHydrograph(this.getMeasuringUnit(), this.getIntervalInHours()); - - double totalDischarge = this.getTotalDischarge(); - double scalingFactor = newTotalDischarge/totalDischarge; - - for (int i = 0; i < _measurementList.size(); i++) - { - RelTimeMeasurement measurement = (RelTimeMeasurement) _measurementList.get(i); - - double value = measurement.getValue() * scalingFactor; - - RelTimeMeasurement newMeasurement = new RelTimeMeasurement(measurement); - newMeasurement.setValue(value); - - uhg.addMeasurement(newMeasurement); - } - - - return uhg; - - } - - //---------------------------------------------------------------------- - - public RelTimeMeasurement getPeakFlowMeasurement() - { - RelTimeMeasurement peak = null; - - for (int i = 0; i < _measurementList.size() ; i++) - { - RelTimeMeasurement measurement = (RelTimeMeasurement) _measurementList.get(i); - if ( (peak == null) || - (measurement.getValue() > peak.getValue()) - ) - { - peak = measurement; - } - } - - return peak; - } - - //---------------------------------------------------------------------- - - public IrregularTimeSeries getFlowTimeSeries(AbsTimeMeasurement runoffMeasurement) - { - MeasuringUnit runoffUnit = MeasuringUnit.inches; - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - - //convert to inches - AbsTimeMeasurement convertedRunoffMeasurement = - AbsTimeMeasurement.getConvertedCopy(runoffMeasurement, runoffUnit); - - double scaleFactor = convertedRunoffMeasurement.getValue(); - - - IrregularTimeSeries ts = new IrregularTimeSeries(MeasuringUnit.cfs); - - long startTime = runoffMeasurement.getTime(); - long measurementTime = 0; - double discharge = 0.0; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurementTime = startTime + (i)*(MILLIS_PER_HOUR); - - Measurement unitGraphValue = - (Measurement) _measurementList.get(i); - - discharge = scaleFactor * unitGraphValue.getValue(); - AbsTimeMeasurement newMeasurement = new AbsTimeMeasurement(discharge, - measurementTime, - dischargeUnit); - ts.insertMeasurement(newMeasurement); - } - - return ts; - } - - //---------------------------------------------------------------------- - - public RegularTimeSeries getFlowRegularTimeSeries(AbsTimeMeasurement runoffMeasurement) - { - MeasuringUnit runoffUnit = MeasuringUnit.inches; - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - - //convert to inches - AbsTimeMeasurement convertedRunoffMeasurement = - AbsTimeMeasurement.getConvertedCopy(runoffMeasurement, runoffUnit); - - double scaleFactor = convertedRunoffMeasurement.getValue(); - - int hourCount = _measurementList.size(); - int intervalInHours = 1; - - long intervalInMillis = intervalInHours * MILLIS_PER_HOUR; - - long startTime = runoffMeasurement.getTime(); - long endTime = startTime + ((hourCount-1) * MILLIS_PER_HOUR); - - RegularTimeSeries ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, dischargeUnit); - - - double discharge = 0.0; - - int i = 0; - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - - Measurement unitgraphValue = - (Measurement) _measurementList.get(i); - - discharge = scaleFactor * unitgraphValue.getValue(); - - Measurement newMeasurement = new Measurement(discharge, - dischargeUnit); - - ts.setMeasurementByTime(newMeasurement, time); - - i++; - } - - return ts; - - } //end getFlowRegularTimeSeries - - //---------------------------------------------------------------------- - - - public String toString() - { - String outString = null; - - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement m = (Measurement) _measurementList.get(i); - buffer.append ("ordinal " + i + " = " + m.getValue() + "\n"); - } - - outString = buffer.toString(); - - return outString; - } - - //------------------------------------------------------------------------ - public double getTotalDischarge() - { - double total = 0.0; - - for(int i = 0; i < _measurementList.size(); i++) - { - RelTimeMeasurement measurement = (RelTimeMeasurement) _measurementList.get(i); - total += measurement.getValue(); - } - - return total; - } - //------------------------------------------------------------------------ - - public RegularTimeSeries calculateTotalDischargeTs(String status, - RegularTimeSeries interimFlowTimeSeries, - RegularTimeSeries runoffTs, - long startTime, - long endTime, - long intervalInMillis) - - - { - - //String header = "UnitHydrograph.calculateTotalDischargeTs(): " + status; - - // System.out.println(header); - - RegularTimeSeries unitgraphFlowTimeSeries = null; - RegularTimeSeries totalFlowTimeSeries = interimFlowTimeSeries.copy(); - - // convert the runoff to discharge through the unithydrograph - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement runoffMeasurement = null; - - if (runoffTs != null) - { - runoffMeasurement = runoffTs.getMeasurementByTime(time); - } - else - { - //System.out.println(header + " runoffTs is null"); - } - - if (runoffMeasurement == null) - { - // System.out.println(header + " runoffMeasurement is null when time = " + - // DbTimeHelper.getDateTimeStringFromLongTime(time)); - } - - else - { - - AbsTimeMeasurement absTimeRunoffMeasurement = - new AbsTimeMeasurement(runoffMeasurement, time); - - unitgraphFlowTimeSeries = - this.getFlowRegularTimeSeries(absTimeRunoffMeasurement); - - - if ( (totalFlowTimeSeries != null) && - (unitgraphFlowTimeSeries != null) - ) - { - totalFlowTimeSeries = - RegularTimeSeries.add(totalFlowTimeSeries, - unitgraphFlowTimeSeries); - - // System.out.println(header + "unitgraphFlowTimeSeries is not null"); - // System.out.println(header + "interimFlowTimeSeries is not null\n"); - } - else if (unitgraphFlowTimeSeries != null) - { - totalFlowTimeSeries = unitgraphFlowTimeSeries.copy(); - // System.out.println(header + "unitgraphFlowTimeSeries is not null"); - // System.out.println(header + "interimFlowTimeSeries is null\n"); - } - - } - } //end for - - return totalFlowTimeSeries; - } -// --------------------------------------------------------------------- - - public static void main(String[] args) throws Exception - { - UnitHydrograph uhg = UnitHydrograph.getTestUnitHydrograph(); - AbsTimeMeasurement runoff = null; - IrregularTimeSeries ts1 = null; - IrregularTimeSeries ts2 = null; - IrregularTimeSeries ts3 = null; - - long desiredTime = new Date().getTime() ; - long roundingFactor = 1000 * 60 * 60; - desiredTime /= roundingFactor; - desiredTime *= roundingFactor; - - - - runoff = new AbsTimeMeasurement(1.0, desiredTime, MeasuringUnit.inches); - ts1 = uhg.getFlowTimeSeries(runoff); - System.out.println("ts1 = " + ts1); - - runoff = new AbsTimeMeasurement(1.0, desiredTime + (1000 * 60 * 60), MeasuringUnit.inches); - ts2 = uhg.getFlowTimeSeries(runoff); - System.out.println("ts2 = " + ts2); - - ts3 = IrregularTimeSeries.add(ts1, ts2); - System.out.println("ts3 = " + ts3); - - } //main - - /** - * @param rainfallRunoffModel The rainfallRunoffModel to set. - */ - public void setRainfallRunoffModel(String rainfallRunoffModelTypeName) - { - _rainfallRunoffModelTypeName = rainfallRunoffModelTypeName; - } - - /** - * @return Returns the rainfallRunoffModel. - */ - public String getRainfallRunoffModelTypeName() - { - return _rainfallRunoffModelTypeName; - } - - - -} //end UnitHydrograph diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographDescriptor.java b/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographDescriptor.java deleted file mode 100644 index 7838a4e1f8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographDescriptor.java +++ /dev/null @@ -1,202 +0,0 @@ -package ohd.hseb.model; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -/** - * @author GobsC - * This class describes a particular unit hydrograph, by location, basin, model, and duration. - * - */ -public class UnitHydrographDescriptor -{ - private String _locationId = null; - private String _basinId = null; - private String _model = null; - private int _duration = 0; - // ------------------------------------------------------------------------------ - public UnitHydrographDescriptor(String locationId, String basinId, - String model, int duration) - { - _locationId = locationId; - _basinId = basinId; - _model = model; - _duration = duration; - return; - } - - - // ------------------------------------------------------------------------------ - public static List createUnitHydrographDescriptorList( - List unitHydrographEntryList) - { - String header = "UnitHydrographDescriptor.createUnitHydrographDescriptorList(): "; - List descriptorList = new ArrayList(); - UnitHydrographEntry entry = null; - UnitHydrographDescriptor descriptor = null; - - HashSet descriptorSet = new HashSet(); - - boolean addToDescriptorList = false; - - for (int i = 0; i < unitHydrographEntryList.size(); i++) - { - entry = (UnitHydrographEntry) unitHydrographEntryList.get(i); - - descriptor = UnitHydrographDescriptor.createUnitHydrographDescriptorFromEntry(entry); - - - if (! descriptorSet.contains(descriptor)) - { - descriptorSet.add(descriptor); - } - } - - - - //convert the Set to a List - descriptorList = new ArrayList(descriptorSet); - - //print it all out - -/* - System.out.println(header + " UHG Descriptor List"); - for (int i = 0; i < descriptorList.size(); i++) - { - UnitHydrographDescriptor desc = (UnitHydrographDescriptor) descriptorList.get(i); - System.out.println(desc); - } -*/ - - return descriptorList; - - } - //------------------------------------------------------------------------------ - public static UnitHydrographDescriptor createUnitHydrographDescriptorFromEntry(UnitHydrographEntry entry) - { - UnitHydrographDescriptor descriptor = - new UnitHydrographDescriptor(entry.getLocationId(), - entry.getAreaId(), - entry.getModel(), - entry.getDur()); - - - - return descriptor; - } - //------------------------------------------------------------------------------ - public boolean isMatchingEntry(UnitHydrographEntry entry) - { - boolean result = false; - - if ((_locationId.equals(entry.getLocationId())) - && (_basinId.equals(entry.getAreaId())) - && (_model.equals(entry.getModel())) - && (_duration == entry.getDur())) - { - result = true; - } - - return result; - } - //------------------------------------------------------------------------------ - - /** - * @return Returns the locationId. - */ - public String getLocationId() - { - return _locationId; - } - //------------------------------------------------------------------------------ - - /** - * @return Returns the basinId. - */ - public String getBasinId() - { - return _basinId; - } - - //------------------------------------------------------------------------------ - - - /** - * @return Returns the model. - */ - public String getModel() - { - return _model; - } - //------------------------------------------------------------------------------ - - - /** - * @return Returns the duration. - */ - public int getDuration() - { - return _duration; - } - //------------------------------------------------------------------------------ - public boolean equals(Object object) - { - boolean result = false; - - if (object instanceof UnitHydrographDescriptor) - { - result = equals((UnitHydrographDescriptor) object); - } - else - { - result = false; - } - - return result; - } - - //------------------------------------------------------------------------------ - public int hashCode() - { - - String hashString = _locationId + "|" + _basinId + "|" + _model + "|" +_duration; - - int hashValue = hashString.hashCode(); - - return hashValue; - } - - //------------------------------------------------------------------------------ - - public boolean equals(UnitHydrographDescriptor desc) - { - - boolean result = false; - - if ( (_locationId.equals(desc.getLocationId())) && - (_basinId.equals(desc.getBasinId())) && - (_model.equals(desc.getModel())) && - (_duration == desc.getDuration()) - ) - { - result = true; - } - - return result; - } - //------------------------------------------------------------------------------ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("location = " + _locationId + " " + - "basin = " + _basinId + " " + - "model = " + _model + " " + - "duration = " + _duration); - - return buffer.toString(); - } - //------------------------------------------------------------------------------ - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographEntry.java b/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographEntry.java deleted file mode 100644 index f713bfb4f3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographEntry.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Created on Jun 9, 2004 - * - * Filename : UnitHydrographEntry.java - * Author : Gautam Sood - * Last Revision Date : Jun 9, 2004 - * - */ -/** - * @author Gautam Sood -*/ - -package ohd.hseb.model; - - -public class UnitHydrographEntry -{ - private String _locationId = null; - - private String _areaId = null; - - private String _model = null; - - private int _dur = 0; - - private int _ordinal = 0; - - private double _discharge = 0.0; -// ------------------------------------------------------------------------------ - - public UnitHydrographEntry() - { - } -// ------------------------------------------------------------------------------ - - public UnitHydrographEntry( UnitHydrographEntry uhgEntry ) - { - setLocationId( uhgEntry.getLocationId() ); - setAreaId( uhgEntry.getAreaId() ); - setDur( uhgEntry.getDur() ); - setOrdinal( uhgEntry.getOrdinal() ); - setDischarge( uhgEntry.getDischarge() ); - } -// ------------------------------------------------------------------------------ - - public void setLocationId(String locationId) - { - _locationId = locationId; - } -// ------------------------------------------------------------------------------ - - public String getLocationId() - { - return _locationId; - } -// ------------------------------------------------------------------------------ - - public void setAreaId(String areaId) - { - _areaId = areaId; - } -// ------------------------------------------------------------------------------ - - public String getAreaId() - { - return _areaId; - } -// ------------------------------------------------------------------------------ - - public void setDur(int dur) - { - _dur = dur; - } -// ------------------------------------------------------------------------------ - - public int getDur() - { - return _dur; - } -// ------------------------------------------------------------------------------ - - public void setOrdinal(int ordinal) - { - _ordinal = ordinal; - } -// ------------------------------------------------------------------------------ - - public int getOrdinal() - { - return _ordinal; - } -// ------------------------------------------------------------------------------ - - public void setDischarge(double discharge) - { - _discharge = discharge; - } -// ------------------------------------------------------------------------------ - - public double getDischarge() - { - return _discharge; - } -// ------------------------------------------------------------------------------ - - public boolean hasEqualKey( UnitHydrographEntry entry ) - { - boolean isEqual = false; - - if ( - ( _locationId.equalsIgnoreCase( entry.getLocationId() ) ) && - ( _areaId.equalsIgnoreCase( entry.getAreaId() ) ) && - ( _model.equalsIgnoreCase( entry.getModel() ) ) && - ( _dur == entry.getDur() ) && - ( _ordinal == entry.getOrdinal() ) - ) - { - isEqual = true; - } - return isEqual; - } -// ------------------------------------------------------------------------------ - - public boolean equals( Object object ) - { - UnitHydrographEntry entry = (UnitHydrographEntry) object; - boolean isEqual = false; - - if ( - ( _locationId.equalsIgnoreCase( entry.getLocationId() ) ) && - ( _areaId.equalsIgnoreCase( entry.getAreaId() ) ) && - ( _model.equalsIgnoreCase( entry.getModel() ) ) && - ( _dur == entry.getDur() ) && - ( _ordinal == entry.getOrdinal() ) && - ( _discharge == entry.getDischarge()) - ) - { - isEqual = true; - } - return isEqual; - } -// ------------------------------------------------------------------------------ - - public int hashCode() - { - String hashString = _locationId.toLowerCase() + "|" + _areaId.toLowerCase() + - "|" + _model.toLowerCase() + "|" + _dur + "|" + _ordinal + "|" + - _discharge; - - int hashValue = hashString.hashCode(); - - return hashValue; - } -// ------------------------------------------------------------------------------ - - /** - * @param model The model to set. - */ - public void setModel(String model) - { - _model = model; - } -// ------------------------------------------------------------------------------ - - /** - * @return Returns the model. - */ - public String getModel() - { - return _model; - } -// ------------------------------------------------------------------------------ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("location = " + _locationId + " " + - "area = " + _areaId + " " + - "model = " + _model + " " + - "duration = " + DurationCode.getHoursFromCode(_dur) + " " + - "ordinal = " +_ordinal + " " + - "discharge = " + _discharge); - - return buffer.toString(); - } - //------------------------------------------------------------------------------ - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographHolder.java deleted file mode 100644 index 15d2ad502d..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographHolder.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Created on Jul 13, 2004 - * - * - */ -package ohd.hseb.model; - - -/** - * @author GobsC - * - * - */ -public class UnitHydrographHolder -{ - private UnitHydrograph _unitHydrograph = null; - - // --------------------------------------------------------------------------------- - - public UnitHydrographHolder(UnitHydrograph unitHydrograph) - { - _unitHydrograph = unitHydrograph; - } - - // --------------------------------------------------------------------------------- - - public void setUnitHydrograph(UnitHydrograph unitHydrograph) - { - _unitHydrograph = unitHydrograph; - } - - // --------------------------------------------------------------------------------- - - - public UnitHydrograph getUnitHydrograph() - { - return _unitHydrograph; - } - - // --------------------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographTest.java b/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographTest.java deleted file mode 100644 index 0af42314c0..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/UnitHydrographTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package ohd.hseb.model; - -import junit.framework.TestCase; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RelTimeMeasurement; - -public class UnitHydrographTest extends TestCase -{ - - - public void testScalingAll() - { - - UnitHydrograph origUhg = getTestUnitHydrograph(); - - testScaling(origUhg.getTotalDischarge()); - testScaling(origUhg.getTotalDischarge() * 2); - testScaling(origUhg.getTotalDischarge()/2); - testScaling(100); - - - } - - public void testScaling(double desiredTotalDischarge) - { - UnitHydrograph origUhg = getTestUnitHydrograph(); - - UnitHydrograph scaledUhg = origUhg.getScaledUnitHydrograph(desiredTotalDischarge); - assertEquals(desiredTotalDischarge, scaledUhg.getTotalDischarge(), 0.0001 ); - } - - public static UnitHydrograph getTestUnitHydrograph() - { - double[] valueArray = { 100.0, 200.0, 350.0, 500.0, - 300.0, 250.0, 200.0, 150.0, - 100.0, 50.0, 25.0, 10}; - - UnitHydrograph uhg = new UnitHydrograph(MeasuringUnit.cfs, 1); - - - for (int i = 0; i < valueArray.length; i++) - { - RelTimeMeasurement measurement = new RelTimeMeasurement(valueArray[i], i, MeasuringUnit.cfs); - uhg.addMeasurement(measurement); - } - - return uhg; - - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/mkcapi/KcApiRainfallRunoffModel.java b/cave/ohd.hseb.common/src/ohd/hseb/model/mkcapi/KcApiRainfallRunoffModel.java deleted file mode 100644 index 8f3be405f9..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/mkcapi/KcApiRainfallRunoffModel.java +++ /dev/null @@ -1,449 +0,0 @@ -// -// filename: KcApiRainfallRunoffModel.java -// author : Chip Gobs - -// description: This class is used to encapsulate the MKC-API -// - -package ohd.hseb.model.mkcapi; - -//import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RainfallRunoffModel; -import ohd.hseb.model.RainfallRunoffModelType; - -public class KcApiRainfallRunoffModel implements RainfallRunoffModel -{ - - //debugging variable from 5/27/04 - // private boolean _oldWay = false; - -//***************************************************************************** -// Private data -//***************************************************************************** - private boolean _success = true; - - private double _thresholdRunoff; - private double _ffhValue; - - private double _soilMoistureIndex; - - private long _startTime = 0; //starting time of the model states - private long _tsStartTime = 0; // starting time of the output = startTime + 1hour - private long _endTime = 0; - - private RegularTimeSeries _hourlyMapTs = null; - private RegularTimeSeries _accumMapTs = null; - - private RegularTimeSeries _accumRunoffTs = null; - private RegularTimeSeries _hourlyRunoffTs = null; - - // the output dischard time series - private RegularTimeSeries _hourlyDischargeTs = null; - - private static final MeasuringUnit _precipUnit = MeasuringUnit.inches; - private static final MeasuringUnit _runoffUnit = MeasuringUnit.inches; - private static final int _millisPerHour = 60 * 60 * 1000; - - private double _missingValue = -999.0; - -//***************************************************************************** -// KcApiModel() - constructor has the Threshold Runoff, 1-hour FFH, hourly MAPs, -// and unit-hydrograph passed in and then..... -// -//***************************************************************************** - public KcApiRainfallRunoffModel(double tro, double ffh) - { - _thresholdRunoff = tro; - _ffhValue = ffh; - - - } // end of constructor - - - public void setFfhValue(double ffhValue) - { - _ffhValue = ffhValue; - } - - - public double getFfhValue() - { - return _ffhValue; - } -// ***************************************************************************** -// calcSMI() - method which calculates the Soil Moisture Index -// ***************************************************************************** - - public RegularTimeSeries calculateRunoff( long startTime, - long endTime, - RegularTimeSeries hourlyMapTimeSeries) - { - - - - _startTime = startTime; - _endTime = endTime; - - int intervalInMillis = 1 * _millisPerHour; - _tsStartTime = _startTime + intervalInMillis; - - // the time series start time is one hour after the startTime, - // which represents the last saved model state time - - - - String header = "KcApiModel.calculateRunoff():"; - /* System.out.println(header + "running the KcApiModel with startTime = " - + DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - " endTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - */ - - //note: not doing anything with the evaporationTimeSeries - // find a better way to package the specific input requirements for - // the various models - - _success = true; - - _hourlyMapTs = hourlyMapTimeSeries; - - _hourlyMapTs.convert(_precipUnit); - - - // System.out.println(header + " before stretch _hourlyMapTs = " + _hourlyMapTs); - - _hourlyMapTs.stretchTimeSeries(_tsStartTime, _endTime, 0.0); - - //System.out.println(header + " after stretch _hourlyMapTs = " + _hourlyMapTs); - - - // System.out.println(header + " _thresholdRunoff = " + _thresholdRunoff); - - // System.out.println(header + " _ffhValue = " + _ffhValue); - - - - if (_thresholdRunoff < 0.0) - _success = false; - // else if (_latestFFH < 0.0) - // _success = false; - else if (_hourlyMapTs.getMeasurementCount() < 1) - _success = false; - - if (_success) - _success = calcSMI(); - - if (_success) - _success = calcAccumMap(); - - if (_success) - _success = calcAccumRO(); - - if (_success) - _success = calcHourlyRO(); - - - return _hourlyRunoffTs; - } // end of calculateRunoff() - - -// ***************************************************************************** -// computed() - method which checks if a Discharge TS was computed or not -// ***************************************************************************** - public boolean computedSuccessfully() - { - return _success; - - } // end of computed method - - -// ***************************************************************************** -// getSMI() - method which returns the Soil Moisture Index -// ***************************************************************************** - public double getSMI() - { - return _soilMoistureIndex; - } // end of getSMI method - - -// ***************************************************************************** -// getDischargeTS() - method which returns an array which contains the hourly -// discharge values computed using the MBRFC SMI method -// ***************************************************************************** - public RegularTimeSeries getDischargeTS() - { - if (computedSuccessfully()) - return _hourlyDischargeTs; - else - return null; - - } - - public void setThresholdRunoff(double thresholdRunoff) - { - _thresholdRunoff = thresholdRunoff; - } - - public double getThresholdRunoff() - { - return _thresholdRunoff; - } - - -//***************************************************************************** -// calcSMI() - method which calculates the Soil Moisture Index -//***************************************************************************** - private boolean calcSMI() - { - String header = "KcApiRainfallRunoffModel.calcSMI(): "; - double tryThisSMI = 0.18; - double runoff = 0.0; - - // System.out.println(header + "_ffhValue = " + _ffhValue ); - // System.out.println(header + "_thresholdRunoff = " + _thresholdRunoff ); - - - runoff = _thresholdRunoff; - while (runoff >= _thresholdRunoff) - { - tryThisSMI = tryThisSMI + 0.01; - runoff = runMBRFC_API(tryThisSMI, _ffhValue); - } - - _soilMoistureIndex = tryThisSMI; - - - - // System.out.println(header + "_soilMoistureIndex = " + _soilMoistureIndex ); - - - - return true; - - } // end of calcSMI method - -//***************************************************************************** -// runMBRFC_API() - method which returns the Runoff given the SMI and precip -//***************************************************************************** - private double runMBRFC_API(double s, double p) - { - double smi = s; - double precip = p; - - double en = 0.0; - double d = 0.0; - double runoff = 0.0; - - en = 0.89 + (0.63 * smi); - d = 0.306 * Math.pow(smi, 1.865); - runoff = Math.pow( ( Math.pow(precip, en) + Math.pow(d, en) ) , (1.0/en) ) - d; - - return runoff; - - } // end of calcSMI method - -//***************************************************************************** -// calcAccumMap() - method which takes the individual hourly MAPs and -// calculates the accumulated MAPs for each hour -//***************************************************************************** - private boolean calcAccumMap() - { - String header = "KcApiModel.calcAccumMap()"; - - // long startTime = _tsStartTime; - // long endTime = _endTime; - - // old way fixed 5/27/04 - - long startTime = _tsStartTime; - long endTime = _endTime; - - - MeasuringUnit hourlyMapTsUnit = _hourlyMapTs.getMeasuringUnit(); - - _accumMapTs = new RegularTimeSeries(startTime, endTime, 1, hourlyMapTsUnit); - - Measurement accumMeasurement = null; - - - //initialize the first accumulated value to the first hourly value - - Measurement firstHourlyMeasurement = _hourlyMapTs.getMeasurementByTime(startTime); - Measurement firstAccumMeasurement = new Measurement(firstHourlyMeasurement); - - _accumMapTs.setMeasurementByTime(firstAccumMeasurement, startTime); - - double hourlyValue = 0.0; - double previousAccumValue = 0.0; - - final long millisPerHour = 1000 * 60 * 60; - - // load the time series with accumulated precip values - for (long time=startTime+millisPerHour ; time <= endTime; time+= millisPerHour) - { - - - hourlyValue = _hourlyMapTs.getMeasurementValueByTime(time, _precipUnit); - previousAccumValue = _accumMapTs.getMeasurementValueByTime(time-millisPerHour, _precipUnit); - - double newValue = 0.0; - - if (hourlyValue > 0.0) - { - newValue = previousAccumValue + hourlyValue; - } - else - { - newValue = previousAccumValue; - } - - - // This was just a coding error. It did not cause a problem since the - // values were the same anyway - INCHES - // REPLACED 5/27/04 Measurement newMeasurement = new Measurement(newValue, _hourlyMapTsUnit); - Measurement newMeasurement = new Measurement(newValue, _precipUnit); - - _accumMapTs.setMeasurementByTime(newMeasurement, time); - - } //end accum for loop - - return true; - } // end of calcAccumMap method - - -//***************************************************************************** -// calcAccumRO() - method which -//***************************************************************************** - private boolean calcAccumRO() - { - String header = "KcApiRainfallRunoffModel.calcAccumRO(): "; - - -// this block commented out 5/27/04 from KcApiRainfallRunoffModel.calcAccumRO() - //long startTime = _accumMapTs.getStartTime(); - // long endTime = _accumMapTs.getEndTime(); - - // this block added 5/27/04 to KcApiRainfallRunoffModel.calcAccumRO() - long startTime = _tsStartTime; - long endTime = _endTime; - - - - - double accumRunoffValue = 0.0; - long intervalInMillis = _millisPerHour; - - _accumRunoffTs = new RegularTimeSeries(startTime, endTime, 1, _runoffUnit); - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - //double accumMapValue = getMeasurementValueByIndex(_accumMapTs, i, _precipUnit); - double accumMapValue = _accumMapTs.getMeasurementValueByTime(time, _precipUnit); - - if (accumMapValue < 0.0) - { - accumMapValue = 0.0; - } - - accumRunoffValue = runMBRFC_API(_soilMoistureIndex, accumMapValue); - Measurement accumRunoffMeasurement = new Measurement(accumRunoffValue, _runoffUnit); - _accumRunoffTs.setMeasurementByTime(accumRunoffMeasurement, time); - } - - - - return true; - - } // end of calcAccumRO method - - -//***************************************************************************** -// calcHourlyRO() - method which -//***************************************************************************** - private boolean calcHourlyRO() - { - String header = "KcApiModel.calcHourlyRO(): "; - - long startTime = _accumRunoffTs.getStartTime(); - long endTime = _accumRunoffTs.getEndTime(); - - _hourlyRunoffTs = new RegularTimeSeries(startTime, endTime, 1, _runoffUnit); - - - - double accumValue = _accumRunoffTs.getMeasurementValueByTime( startTime, _runoffUnit); - Measurement accumMeasurement = new Measurement(accumValue, _accumRunoffTs.getMeasuringUnit()); - _hourlyRunoffTs.setMeasurementByTime(accumMeasurement, startTime); - - - for (int i=1; i<_accumRunoffTs.getMeasurementCount(); i++) - { - double currentAccumValue = getMeasurementValueByIndex(_accumRunoffTs, i, _runoffUnit); - double previousAccumValue = getMeasurementValueByIndex(_accumRunoffTs, i-1, _runoffUnit); - - double runoffValue = currentAccumValue - previousAccumValue; - - // System.out.println(header + " _accumRunoffTs.getMeasuringUnit() = " + _accumRunoffTs.getMeasuringUnit()); - - - Measurement runoffMeasurement = new Measurement(runoffValue, - _accumRunoffTs.getMeasuringUnit()); - - long time = _hourlyRunoffTs.getMeasurementTimeByIndex(i); - _hourlyRunoffTs.setMeasurementByTime(runoffMeasurement, time); - //String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - /* - if (runoffValue != 0.0) - { - System.out.println(header + " runoffMeasurement = " + - runoffMeasurement + " at " + timeString); - } - */ - } - - //System.out.println(header + "bug version = " + _oldWay); - // System.out.println(header + "_accumMapTs = " + _accumMapTs); - // System.out.println(header + "_accumRunoffTs = " + _accumRunoffTs); - // System.out.println(header + "_hourlyRunoffTs = " + _hourlyRunoffTs); - // System.out.println(header + " _accumRunoffTs = " + _accumRunoffTs); - - - return true; - - } // end of calcHourlyRO method - - // --------------------------------------------------------------------------- - private double getMeasurementValueByIndex(RegularTimeSeries ts, int index, MeasuringUnit unit) - { - double value = _missingValue; - - Measurement m = ts.getMeasurementByIndex(index); - - if (m != null) - { - if (! m.isMissing() ) - { - m = m.getCopy(unit); - value = m.getValue(); - } - else - { - value = _missingValue; //set this class's version of a missing value - } - } - - return value; - } - - - public RainfallRunoffModelType getModelType() - { - return RainfallRunoffModelType.API_MKC; - } - - -} // end of KcApi class diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/mkcapi/KcApiRainfallToStageModel.java b/cave/ohd.hseb.common/src/ohd/hseb/model/mkcapi/KcApiRainfallToStageModel.java deleted file mode 100644 index 60121a130f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/mkcapi/KcApiRainfallToStageModel.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.model.mkcapi; - -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementHolder; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.model.ForecastAdjuster; -import ohd.hseb.model.RainfallRunoffModel; -import ohd.hseb.model.RainfallToStageModel; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.UnitHydrograph; -/** - * @author Chip Gobs - * - * This class combines the RainfallRunoffModel - * with a UnitHydrograph and a Rating Curve to output a TimeSeries object. - */ -public class KcApiRainfallToStageModel implements RainfallToStageModel -{ - private RainfallRunoffModel _rainfallRunoffModel = null; - private ForecastAdjuster _forecastAdjuster = null; - - private RatingCurve _ratingCurve = null; - private UnitHydrograph _unitgraph = null; - - private final static long _millisPerHour = 60 * 60 * 1000; - - private MeasurementHolder _baseStageMeasurementHolder = null; - private IrregularTimeSeriesHolder _observedStageTimeSeriesHolder = null; - private RegularTimeSeriesHolder _simulatedDischargeTimeSeriesHolder = null; - - - private final static MeasuringUnit _stageUnit = MeasuringUnit.feet; - private final static MeasuringUnit _dischargeUnit = MeasuringUnit.cfs; - -// ------------------------------------------------------------- - - public KcApiRainfallToStageModel(RainfallRunoffModel rainfallRunoffModel, - UnitHydrograph unitgraph, - RatingCurve ratingCurve, - MeasurementHolder baseStageMeasurementHolder, - IrregularTimeSeriesHolder observedStageTimeSeriesHolder, - ForecastAdjuster forecastAdjuster, - RegularTimeSeriesHolder simulatedDischargeTimeSeriesHolder) - { - - _rainfallRunoffModel = rainfallRunoffModel; - - _ratingCurve = ratingCurve; - _unitgraph = unitgraph; - - _baseStageMeasurementHolder = baseStageMeasurementHolder; - - _observedStageTimeSeriesHolder = observedStageTimeSeriesHolder; - - _forecastAdjuster = forecastAdjuster; - _simulatedDischargeTimeSeriesHolder = simulatedDischargeTimeSeriesHolder; - - } //end RainfallToStageModel() - - // ------------------------------------------------------------- - - public RegularTimeSeries calculateStageTimeSeries(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries, - RegularTimeSeriesHolder runoffTimeSeriesHolder) - - - { - - - Measurement baseflowMeasurement = null; - - //get the baseflow measurement - if (_ratingCurve != null) - { - double stageValue = _baseStageMeasurementHolder.getMeasurement().getValue(_stageUnit); - double dischargeValue = _ratingCurve.getDischargeFromStage(stageValue); - baseflowMeasurement = new Measurement(dischargeValue, _dischargeUnit); - } - String header = "KcApiRainfallToStageModel.calculateStageTimeSeries():"; - - int intervalInHours = 1; - long intervalInMillis = _millisPerHour * intervalInHours; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - long tsStartTime = startTime + intervalInMillis; - - - /* - System.out.println(header + "startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - " endTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - */ - - // System.out.println(header + "precipTimeSeries = " + precipTimeSeries); - // System.out.println(header + "evap TimeSeries = " + potentialEvapTimeSeries); - - - - - RegularTimeSeries runoffTs = - _rainfallRunoffModel.calculateRunoff(startTime, - endTime, - precipTimeSeries); - - runoffTimeSeriesHolder.setTimeSeries(runoffTs); - - //System.out.println(header + "--------------------------------"); - // System.out.println(header + "runoffTs = " + runoffTs); - - - RegularTimeSeries totalFlowTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, - intervalInHours, MeasuringUnit.cfs); - - - - // System.out.println(header + "after unithydrograph, prior total flow time series " + totalFlowTimeSeries); - - //use newly calculated runoff - totalFlowTimeSeries = - _unitgraph.calculateTotalDischargeTs("new ", - totalFlowTimeSeries, - runoffTs, - tsStartTime, - endTime, - intervalInMillis); - - - - //System.out.println(header + "after unithydrograph, new total flow time series " + totalFlowTimeSeries); - - // create a test baseFlow time series - RegularTimeSeries baseFlowTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, - intervalInHours, - MeasuringUnit.cfs, - baseflowMeasurement.getValue() - ); - - // System.out.println(header + "base flow time series " + baseFlowTimeSeries); - - - // add the baseflow to the current total flow - totalFlowTimeSeries = RegularTimeSeries.add(totalFlowTimeSeries, baseFlowTimeSeries); - - - - // System.out.println(header + "after addition of baseflow, new total flow time series " + totalFlowTimeSeries); - - - //store the simulation results - _simulatedDischargeTimeSeriesHolder.setTimeSeries(totalFlowTimeSeries); - - // forecast adjustment - if (_forecastAdjuster.getParams().shouldDoAdjustment()) - { - // CodeTimer timer = new CodeTimer(); - //timer.start(); - IrregularTimeSeries observedStageTimeSeries = _observedStageTimeSeriesHolder.getTimeSeries(); - IrregularTimeSeries observedDischargeTimeSeries = _ratingCurve.getDischargeIrregularTimeSeries(observedStageTimeSeries); - totalFlowTimeSeries = _forecastAdjuster.getAdjustedTimeSeries(observedDischargeTimeSeries, totalFlowTimeSeries); - // timer.stop(" the forecast adjustment took "); - } - - - - RegularTimeSeries stageTimeSeries = - _ratingCurve.getStageRegularTimeSeries(totalFlowTimeSeries); - - return stageTimeSeries; - - } //end getStageTimeSeries - -// --------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacRainfallToStageModel.java b/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacRainfallToStageModel.java deleted file mode 100644 index 852c80f13d..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacRainfallToStageModel.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.model.sacsma; - -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.model.ForecastAdjuster; -import ohd.hseb.model.RainfallRunoffModel; -import ohd.hseb.model.RainfallToStageModel; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.UnitHydrograph; - -/** - * @author Chip Gobs - * - * This class combines the RainfallRunoffModel - * with a UnitHydrograph and a Rating Curve to output a TimeSeries object. - */ -public class SacRainfallToStageModel implements RainfallToStageModel -{ - private RainfallRunoffModel _rainfallRunoffModel = null; - private ForecastAdjuster _forecastAdjuster = null; - - private RatingCurve _ratingCurve = null; - private UnitHydrograph _unitgraph = null; - - private RegularTimeSeriesHolder _priorRunoffTimeSeriesHolder = null; - private IrregularTimeSeriesHolder _observedStageTimeSeriesHolder = null; - private RegularTimeSeriesHolder _simulatedDischargeTimeSeriesHolder = null; - - private final static long _millisPerHour = 60 * 60 * 1000; - -// ------------------------------------------------------------- - - public SacRainfallToStageModel(RainfallRunoffModel rainfallRunoffModel, - UnitHydrograph unitgraph, - RatingCurve ratingCurve, - RegularTimeSeriesHolder priorRunoffTimeSeriesHolder, - IrregularTimeSeriesHolder observedStageTimeSeriesHolder, - ForecastAdjuster forecastAdjuster, - RegularTimeSeriesHolder simulatedDischargeTimeSeriesHolder) - { - - _rainfallRunoffModel = rainfallRunoffModel; - - _ratingCurve = ratingCurve; - _unitgraph = unitgraph; - - _priorRunoffTimeSeriesHolder = priorRunoffTimeSeriesHolder; - - - // forecast adjustment variables - _observedStageTimeSeriesHolder = observedStageTimeSeriesHolder; - _forecastAdjuster = forecastAdjuster; - _simulatedDischargeTimeSeriesHolder = simulatedDischargeTimeSeriesHolder; - - - } //end RainfallToStageModel() - - // ------------------------------------------------------------- - - public RegularTimeSeries calculateStageTimeSeries(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries, - RegularTimeSeriesHolder runoffTimeSeriesHolder - ) - - { - - String header = "SacRainfallToStageModel.calculateStageTimeSeries():"; - - - RegularTimeSeries priorRunoffTimeSeries = _priorRunoffTimeSeriesHolder.getTimeSeries(); - - int intervalInHours = 1; - long intervalInMillis = _millisPerHour * intervalInHours; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - long tsStartTime = startTime + intervalInMillis; - - - - - RegularTimeSeries runoffTs = - _rainfallRunoffModel.calculateRunoff(startTime, - endTime, - precipTimeSeries); - - runoffTimeSeriesHolder.setTimeSeries(runoffTs); - - - RegularTimeSeries totalFlowTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, - intervalInHours, MeasuringUnit.cfs); - - - //note: the previous totalFlowTimeSeries will be ADDED(math) to the flow output - // from the unit hydrograph - - //use prior runoff - - long priorRunoffStartTime = startTime - - (_unitgraph.getOrdinateCount() * _millisPerHour); - - long priorRunoffEndTime = startTime; - totalFlowTimeSeries = - _unitgraph.calculateTotalDischargeTs("prior ", - totalFlowTimeSeries, - priorRunoffTimeSeries, - priorRunoffStartTime, - priorRunoffEndTime, - intervalInMillis); - - - // System.out.println(header + "after _unitgraph.calculateTotalDischargeTs(), prior total flow time series\n " + totalFlowTimeSeries); - - //use newly calculated runoff - totalFlowTimeSeries = - _unitgraph.calculateTotalDischargeTs("new ", - totalFlowTimeSeries, - runoffTs, - tsStartTime, - endTime, - intervalInMillis); - - - - - // System.out.println(header + "after _unitgraph.calculateTotalDischargeTs(), new total flow time series\n " + totalFlowTimeSeries); - - //lop off the hours at the beginning that are before the model run start time - totalFlowTimeSeries.trimTimeSeriesAtStart(tsStartTime); - - - //store the simulation results - _simulatedDischargeTimeSeriesHolder.setTimeSeries(totalFlowTimeSeries); - - // forecast adjustment - if (_forecastAdjuster.getParams().shouldDoAdjustment()) - { - // CodeTimer timer = new CodeTimer(); - //timer.start(); - IrregularTimeSeries observedStageTimeSeries = _observedStageTimeSeriesHolder.getTimeSeries(); - IrregularTimeSeries observedDischargeTimeSeries = _ratingCurve.getDischargeIrregularTimeSeries(observedStageTimeSeries); - totalFlowTimeSeries = _forecastAdjuster.getAdjustedTimeSeries(observedDischargeTimeSeries, totalFlowTimeSeries); - // timer.stop(" the forecast adjustment took "); - } - - - // System.out.println(header + "after totalFlowTimeSeries.trimTimeSeriesAtStart(), new total flow time series\n " + totalFlowTimeSeries); - - - // put through the rating curve to get the stages - RegularTimeSeries stageTimeSeries = - _ratingCurve.getStageRegularTimeSeries(totalFlowTimeSeries); - - return stageTimeSeries; - - } //end getStageTimeSeries - -// --------------------------------------------------------------------- - - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaParameters.java b/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaParameters.java deleted file mode 100644 index f6208b841a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaParameters.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Created on Jun 20, 2003 - * - * - */ -package ohd.hseb.model.sacsma; -import java.text.DecimalFormat; -import java.text.NumberFormat; - -/** - * @author gobsc - * - * - */ -public class SacSmaParameters -{ - - private String _basinId; - private String _source; - private long _validTime; - private long _postingTime; - - - // these were common block parameter variables in the FORTRAN code - private double _uztwm = 0.0; - private double _uzfwm = 0.0; - private double _uzk = 0.0; - private double _pctim = 0.0; - private double _adimp = 0.0; - private double _riva = 0.0; - private double _zperc = 0.0; - private double _rexp = 0.0; - - private double _lztwm = 0.0; - private double _lzfsm = 0.0; - private double _lzfpm = 0.0; - private double _lzsk = 0.0; - private double _lzpk = 0.0; - - private double _pfree = 0.0; - - //these 2 are calculated - //SAVED = RSERV * (LZFPM + LZFSM) - // private double _saved = 0.0; //aka rserv? - //PAREA = 1.0 - PCTIM - ADIMP - // private double _parea = 0.0; - - private double _rserv = 0.0; - - private double _side = 0.0; - - //other sac params - not soil related - - private double _peadj = 0.0; - private double _pxadj = 0.0; - private double _efc = 0.0; - - - - - - public SacSmaParameters() - { - } - - public SacSmaParameters(SacSmaParameters params) - { - //copy constructor - - setBasinId(params.getBasinId()); - setSource(params.getSource()); - setValidTime(params.getValidTime()); - setPostingTime(params.getPostingTime()); - - - setUztwm(params.getUztwm()); - setUzfwm(params.getUzfwm()); - setUzk(params.getUzk()); - setPctim(params.getPctim()); - setAdimp(params.getAdimp()); - setRiva(params.getRiva()); - setZperc(params.getZperc()); - setRexp(params.getRexp()); - - setLztwm(params.getLztwm()); - setLzfsm(params.getLzfsm()); - setLzfpm(params.getLzfpm()); - setLzsk(params.getLzsk()); - setLzpk(params.getLzpk()); - - - setPfree(params.getPfree()); - setRserv(params.getRserv()); - setSide(params.getSide()); - - return; - } - - /** - * - * @param paramArray - * The parameters are doubles in this order: - * UZTWM, UZFWM, UZK, PCTIM, ADIMP, RIVA, ZPERC, REXP,LZTWM, LZFSM, LZFPM, LZSK, LZPK, PFREE, RSERV, SIDE - */ - public SacSmaParameters(double[] paramArray) - { - int i = 0; - setUztwm(paramArray[i++]); - setUzfwm(paramArray[i++]); - setUzk(paramArray[i++]); - setPctim(paramArray[i++]); - setAdimp(paramArray[i++]); - setRiva(paramArray[i++]); - setZperc(paramArray[i++]); - setRexp(paramArray[i++]); - setLztwm(paramArray[i++]); - setLzfsm(paramArray[i++]); - - setLzfpm(paramArray[i++]); - setLzsk(paramArray[i++]); - setLzpk(paramArray[i++]); - setPfree(paramArray[i++]); - - setRserv(paramArray[i++]); - setSide(paramArray[i++]); - - } - - public boolean equals(SacSmaParameters params) - { - boolean result = false; - - if ( - (getBasinId().equalsIgnoreCase(params.getBasinId())) && - (getSource().equalsIgnoreCase(params.getSource())) && - (getValidTime() == params.getValidTime()) && - (getPostingTime() == params.getPostingTime()) && - (getUztwm() == params.getUztwm()) && - (getUzfwm() == params.getUzfwm()) && - (getUzk() == params.getUzk()) && - (getPctim() == params.getPctim()) && - (getAdimp() == params.getAdimp()) && - (getRiva() == params.getRiva()) && - (getZperc() == params.getZperc()) && - (getRexp() == params.getRexp()) && - (getLztwm() == params.getLztwm()) && - (getLzfsm() == params.getLzfsm()) && - (getLzfpm() == params.getLzfpm()) && - (getLzsk() == params.getLzsk()) && - (getLzpk() == params.getLzpk()) && - (getPfree() == params.getPfree()) && - (getRserv() == params.getRserv()) && - (getSide() == params.getSide()) && - (getPeadj() == params.getPeadj()) && - (getPxadj() == params.getPxadj()) && - (getEfc() == params.getEfc()) - ) - - { - result = true; - } - - return result; - } - - - public boolean equalsValues(SacSmaParameters params) - { - boolean result = false; - - if ( - // (getBasinId().equalsIgnoreCase(params.getBasinId())) && - //(getSource().equalsIgnoreCase(params.getSource())) && - // (getValidTime() == params.getValidTime()) && - // (getPostingTime() == params.getPostingTime()) && - (getUztwm() == params.getUztwm()) && - (getUzfwm() == params.getUzfwm()) && - (getUzk() == params.getUzk()) && - (getPctim() == params.getPctim()) && - (getAdimp() == params.getAdimp()) && - (getRiva() == params.getRiva()) && - (getZperc() == params.getZperc()) && - (getRexp() == params.getRexp()) && - (getLztwm() == params.getLztwm()) && - (getLzfsm() == params.getLzfsm()) && - (getLzfpm() == params.getLzfpm()) && - (getLzsk() == params.getLzsk()) && - (getLzpk() == params.getLzpk()) && - (getPfree() == params.getPfree()) && - (getRserv() == params.getRserv()) && - (getSide() == params.getSide()) && - (getPeadj() == params.getPeadj()) && - (getPxadj() == params.getPxadj()) && - (getEfc() == params.getEfc()) - ) - - { - result = true; - } - - return result; - } - - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat f = new DecimalFormat(formatString); - - String outString = "Params = " + - " uztwm = " + f.format(_uztwm) + - " uzfwm = " + f.format(_uzfwm) + - " uzk = " + f.format(_uzk) + - " pctim = " + f.format(_pctim) + "\n" + - " adimp = " + f.format(_adimp) + - " riva = " + f.format(_riva) + - " zperc = " + f.format(_zperc) + - - " rexp = " + f.format(_rexp) + "\n" + - " lztwm = " + f.format(_lztwm) + - " lzfsm = " + f.format(_lzfsm) + - - " lzfpm = " + f.format(_lzfpm) + - - " lzsk = " + f.format(_lzsk) + "\n" + - " lzpk = " + f.format(_lzpk) + - " pfree = " + f.format(_pfree) + - " rserv = " + f.format(_rserv) + - " side = " + f.format(_side) + "\n" + - " parea = " + f.format(getParea()) + "\n"; - - return outString; - - } - - public void setBasinId(String basinId) - { - _basinId = basinId; - } - - public String getBasinId() - { - return _basinId; - } - - public void setSource(String source) - { - _source = source; - } - - public String getSource() - { - return _source; - } - - public void setValidTime(long validTime) - { - _validTime = validTime; - } - - public long getValidTime() - { - return _validTime; - } - - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - - public long getPostingTime() - { - return _postingTime; - } - -// accessors - - public void setUztwm(double uztwm) { - this._uztwm = uztwm; - } - - public double getUztwm() { - return _uztwm; - } - - public void setUzfwm(double uzfwm) { - this._uzfwm = uzfwm; - } - - public double getUzfwm() { - return _uzfwm; - } - - public void setUzk(double uzk) { - this._uzk = uzk; - } - - public double getUzk() { - return _uzk; - } - - public void setPctim(double pctim) { - this._pctim = pctim; - } - - public double getPctim() { - return _pctim; - } - - public void setAdimp(double adimp) { - this._adimp = adimp; - } - - public double getAdimp() { - return _adimp; - } - - public void setRiva(double riva) { - this._riva = riva; - } - - public double getRiva() { - return _riva; - } - - public void setZperc(double zperc) { - this._zperc = zperc; - } - - public double getZperc() { - return _zperc; - } - - public void setRexp(double rexp) { - this._rexp = rexp; - } - - public double getRexp() { - return _rexp; - } - - public void setLztwm(double lztwm) { - this._lztwm = lztwm; - } - - public double getLztwm() { - return _lztwm; - } - - public void setLzfsm(double lzfsm) { - this._lzfsm = lzfsm; - } - - public double getLzfsm() { - return _lzfsm; - } - - public void setLzfpm(double lzfpm) { - this._lzfpm = lzfpm; - } - - public double getLzfpm() { - return _lzfpm; - } - - public void setLzsk(double lzsk) { - this._lzsk = lzsk; - } - - public double getLzsk() { - return _lzsk; - } - - public void setLzpk(double lzpk) { - this._lzpk = lzpk; - } - - public double getLzpk() { - return _lzpk; - } - - public void setPfree(double pfree) { - this._pfree = pfree; - } - - public double getPfree() { - return _pfree; - } - - public void setSide(double side) { - this._side = side; - } - - public double getSide() { - return _side; - } - - - public double getSaved() - { //calculated parameter - // - return (_rserv * (_lzfpm + _lzfsm)); - //return _saved; - } - - //public void setParea(double parea) { - // this._parea = parea; - //} - - public double getParea() - { //calculated parameter - return (1.0 - _pctim - _adimp); - //return _parea; - } - - public void setRserv(double rserv) - { - this._rserv = rserv; - } - - public double getRserv() - { - return _rserv; - } - - - public double getPeadj() - { - return _peadj; - } - - - public void setPeadj(double peadj) - { - _peadj = peadj; - } - - - public double getPxadj() - { - return _pxadj; - } - - public void setPxadj(double pxadj) - { - _pxadj = pxadj; - } - - public void setEfc(double efc) - { - _efc = efc; - } - - public double getEfc() - { - return _efc; - } - - - - -} //end SacSmaParameters diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaRainfallRunoffModel.java b/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaRainfallRunoffModel.java deleted file mode 100644 index e374049926..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaRainfallRunoffModel.java +++ /dev/null @@ -1,1175 +0,0 @@ -package ohd.hseb.model.sacsma; - - -import java.text.DecimalFormat; -import java.text.NumberFormat; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.RainfallRunoffModel; -import ohd.hseb.model.RainfallRunoffModelType; - - -/** - * - * - * @author Chip Gobs - * @version 0.5 - */ -public class SacSmaRainfallRunoffModel implements RainfallRunoffModel -{ - private static final int _millisPerHour = 60 * 60 * 1000; - private SacSmaParameters _params; - private SacSmaState _state; - - private boolean _useStaticMape = false; - private MonthlyValues _monthlyMapeAdjustmentValues = null; - - private RegularTimeSeriesHolder _potentialEvapTimeSeriesHolder = null; - - private MonthlyValues _monthlyMapeValues = null; - - private double _peAdjust = 1.0; - private double _pxAdjust = 1.0; - - - // calculated, during the initial setting of params from SacSmaParameters to - // this object's variables - //private double _saved = 0.0; - // private double _parea = 0.0; - - - //private double[] _fgco = new double[6]; //unused - private double[] _rsum = new double[7]; - - // private double _ppe = 0.0; - //private double _psc = 0.0; -// private double _pta = 0.0; -// private double _pwe = 0.0; - - // common block sums - private double _srot = 0.0; - private double _simpvt = 0.0; - private double _srodt = 0.0; - private double _srost = 0.0; - private double _sintft = 0.0; - private double _sgwfp = 0.0; - private double _sgwfs = 0.0; - private double _srecht = 0.0; - private double _sett = 0.0; - - private double _se1 = 0.0; -// private double _se2 = 0.0; - private double _se3 = 0.0; - private double _se4 = 0.0; - private double _se5 = 0.0; - - - - //variables that are initialized in the main section of code - //that I need to pass to the doIncrements section - - private double _dlzp = 0.0; - private double _dlzs = 0.0; - private double _duz = 0.0; - - private double _sbf = 0.0; - private double _ssur = 0.0; - private double _sif = 0.0; - private double _sperc = 0.0; - private double _sdro = 0.0; - private double _spbf = 0.0; - - private double _pinc = 0.0; - - - //variables that could have been local, but belong to the - // object so that results of the operation can be verified - private double _bfp = 0.0; - private double _bfs = 0.0; - private double _roimp = 0.0; - private double _tci = 0.0; - - //private PrintWriter _runoffWriter = null; - //private PrintWriter _internalsWriter = null; - - private MeasuringUnit _precipUnit = MeasuringUnit.mm; - private MeasuringUnit _runoffUnit = MeasuringUnit.mm; - - -//-------------------------------------------------------------------------- - /** - * Constructor for objects of class SacSmaModel - */ - public SacSmaRainfallRunoffModel(SacSmaState state, - SacSmaParameters params, - double peAdjust, - double pxAdjust, - boolean useStaticMape, - MonthlyValues monthlyValues, - RegularTimeSeriesHolder potentialEvapTimeSeriesHolder) - { - - // _basinId = params.getBasinId(); - // _paramsSource = params.getSource(); - // _stateSource = state.getSource(); - - // says whether using MAPE time series or static monthly MAPE values - _useStaticMape = useStaticMape; - - if (_useStaticMape) - { - _monthlyMapeValues = monthlyValues; - } - else - { - _monthlyMapeAdjustmentValues = monthlyValues; - } - - // can be null - _potentialEvapTimeSeriesHolder = potentialEvapTimeSeriesHolder; - - setParameters(params); - - setState(state); - - _peAdjust = peAdjust; - _pxAdjust = pxAdjust; - - } -// -------------------------------------------------------------------------- - - private static String getStateString(SacSmaState state) - { - String formatString = "#####.#####"; - NumberFormat format = new DecimalFormat(formatString); - - String string = " uztwc = " + format.format(state.getUztwc()) + - " uzfwc = " + format.format(state.getUzfwc()) + - " lztwc = " + format.format(state.getLztwc()) + "\n" + - " lzfsc = " + format.format(state.getLzfsc()) + - " lzfpc = " + format.format(state.getLzfpc()) + - " adimc = " + format.format(state.getAdimc()) + "\n"; - - - //" rsum = " + state.getRsumString() + "\n"; - - - return string; - } //end getStateString - - -// -------------------------------------------------------------------------- - - public RegularTimeSeries calculateRunoff( long startTime, - long endTime, - RegularTimeSeries precipTimeSeries) - - - { - - String header = "SacSmaModel.calculateRunoff(): "; - - - final double hoursPerDay = 24; - int hoursPerInterval = 1; - - // the time series start time is one hour after the startTime, - // which represents the last saved model state time - long tsStartTime = startTime + (hoursPerInterval * _millisPerHour); - - - double intervalPortionOfDay = hoursPerInterval/hoursPerDay; - - RegularTimeSeries runoffTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, 1, _runoffUnit); - - - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - String formatString = "#####.#####"; - NumberFormat formatter = new DecimalFormat(formatString); - - // System.out.println("Java version of SacSma:"); - - - //setupTestLogFiles(); - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(getState()) + - getParameters().toString(); - - //System.out.println(internalsMessage); - - // _internalsWriter.println(internalsMessage); - - - long millisPerHour = 60 * 60 * 1000; - - RegularTimeSeries potentialEvapTimeSeries = _potentialEvapTimeSeriesHolder.getTimeSeries(); - - - int hoursCount = Math.min(precipTimeSeries.getMeasurementCount(), - potentialEvapTimeSeries.getMeasurementCount()); - - - //for each piece of input data - - //fill in the time series out to the length of the model run - precipTimeSeries.stretchTimeSeries(tsStartTime, endTime, 0.0); - - - if (! _useStaticMape) //using time series - { - potentialEvapTimeSeries.stretchTimeSeries(tsStartTime, endTime, 0.0); - } - - - // at the start of the calculation, reset the basis time for the state - _state.setBasisTime(System.currentTimeMillis()); - - - for (long time = tsStartTime; time <= endTime; time += millisPerHour) - { - Measurement precipMeasurement = precipTimeSeries.getMeasurementByTime(time); - - if ((precipMeasurement != null) && (! precipMeasurement.isMissing())) - { - precipMeasurement = precipMeasurement.getCopy(_precipUnit); - - precipAmount = precipMeasurement.getValue(); - - if (precipAmount < 0.0) - { - precipAmount = 0.0; - } - else - { - precipAmount *= _pxAdjust; - } - } - else - { - precipAmount = 0.0; - } - - - if (_useStaticMape) - { - double dailyEvaporationAmount = _monthlyMapeValues.getValue(time); - evaporationAmount = dailyEvaporationAmount * intervalPortionOfDay; - - evaporationAmount *= _peAdjust; - - } - else //using time series - { - Measurement evapMeasurement = potentialEvapTimeSeries.getMeasurementByTime(time); - - if (evapMeasurement != null) - { - evapMeasurement = evapMeasurement.getCopy(_precipUnit); - evaporationAmount = evapMeasurement.getValue(); - - double adjustmentFactor = _monthlyMapeAdjustmentValues.getValue(time); - evaporationAmount *= adjustmentFactor; - - evaporationAmount *= _peAdjust; - } - else //evapMeasurement == null - { - evaporationAmount = 0.0; - } - } - - - double totalChannelInflow = - calculate(intervalPortionOfDay, - precipAmount, - evaporationAmount); - - // reset the valid time - _state.setValidTime(time); - - - - /* - System.out.println(header + "runoff = " + totalChannelInflow + - " precip = " + precipAmount + - " poten. evap = " + evaporationAmount); - */ - - Measurement totalChannelInflowMeasurement = - new Measurement(totalChannelInflow, _runoffUnit); - - runoffTimeSeries.setMeasurementByTime(totalChannelInflowMeasurement, time); - - } - return runoffTimeSeries; - } -// -------------------------------------------------------------------------- - - private void setParameters(SacSmaParameters params) - { - - _params = new SacSmaParameters(params); - - //_uztwm = params.getUztwm(); - //_uzfwm = params.getUzfwm(); - //_uzk = params.getUzk(); - - //_pctim = params.getPctim(); - //_adimp = params.getAdimp(); - //_riva = params.getRiva(); - //_zperc = params.getZperc(); - //_rexp = params.getRexp(); - //_lztwm = params.getLztwm(); - //_lzfsm = params.getLzfsm(); - //_lzfpm = params.getLzfpm(); - //_lzsk = params.getLzsk(); - //_lzpk = params.getLzpk(); - - //_pfree = params.getPfree(); - //_rserv = params.getRserv(); - //_side = params.getSide(); - - - } //end setParameters - -// -------------------------------------------------------------------------- - - - public SacSmaParameters getParameters() - { - SacSmaParameters params = new SacSmaParameters(); - - - /* - - params.setBasinId(_basinId); - params.setSource(_stateSource); - - - params.setUztwm( _uztwm ); - params.setUzfwm( _uzfwm ); - params.setUzk( _uzk ); - - params.setPctim(_pctim ); - params.setAdimp( _adimp ); - params.setRiva(_riva ); - params.setZperc(_zperc ); - params.setRexp(_rexp ); - params.setLztwm(_lztwm ); - params.setLzfsm(_lzfsm ); - params.setLzfpm(_lzfpm ); - params.setLzsk(_lzsk ); - params.setLzpk(_lzpk ); - - params.setPfree( _pfree ); - params.setSide(_side ); - - params.setRserv(_rserv); - */ - - params = new SacSmaParameters(_params); - - return params; - - } //end getParameters - -// -------------------------------------------------------------------------- - - public void setState(SacSmaState state) - { - - _state = new SacSmaState(state); - - //_uztwc = state.getUztwc(); - //_uzfwc = state.getUzfwc(); - - //_lztwc = state.getLztwc(); - - //_lzfsc = state.getLzfsc(); - //_lzfpc = state.getLzfpc(); - - //_adimc = state.getAdimc(); - - //private double[] _fgco = new double[6]; - // _rsum = new double[ state.getRsum().length ]; - // for (int i = 0; i < state.getRsum().length; i++) - // { - // _rsum[i] = state.getRsum()[i]; - // } - - - // _ppe = state.getPpe(); -// _psc = state.getPsc(); -// _pta = state.getPta(); -// _pwe = state.getPwe(); - - } - -//-------------------------------------------- - public SacSmaState getState() - { - SacSmaState state = new SacSmaState(_state); - - - //private double[] _fgco = new double[6]; - //double[] localRsum = new double[_rsum.length]; - //for (int i = 0; i < _rsum.length; i++) - //{ - // localRsum[i] = _rsum[i]; - //} - //state.setRsum(localRsum); - - - // _ppe = state.getPpe(); - //state.setPsc(_psc ); - //state.setPta(_pta ); - //state.setPwe(_pwe ); - - return state; - } - -// -------------------------------------------------------------------------- - - public double getSaved() - { //calculated parameter - // - return (_params.getRserv() * (_params.getLzfpm() + _params.getLzfsm())); - //return _saved; - } - - //public void setParea(double parea) { - // this._parea = parea; - //} - -// -------------------------------------------------------------------------- - - - public double getParea() - { //calculated parameter - return (1.0 - _params.getPctim() - _params.getAdimp()); - //return _parea; - } -//-------------------------------------------- - /** - * calculate() - * - * @param timeInterval a sample parameter for a method - * @return void - */ - - /* - * Translation Notes: - * dt = timeInterval in fraction of a day (for example, 1 hour = 1/24.0) - * pxv = ranfallPlusMelt - * ep = evaporation - * tci = totalChannelInflowMinusRunoffDepth - */ - - public double calculate(double dt /*dt */, - double rainfallPlusMelt /*pxv */, - double evaporation /* ep*/) - { - double evapTransDemand = evaporation; - - double e1; - double e2; - double e3; - - double residualEvapTransDemand = 0.0; - - //later put this in the object itself - boolean useFrozenGroundCalcs = false; - - - // old code does this: - //evapTransDemand = evaporation * evaporationDistribution(Kint) - - // compute et from upper zone - - e1 = evapTransDemand * (_state.getUztwc() / _params.getUztwm() ); - - residualEvapTransDemand = evapTransDemand - e1; - - //subtract off e1 - _state.setUztwc(_state.getUztwc() - e1); - - // introduce e2 - e2 = 0.0; - - boolean perform220Check = false; - - if (_state.getUztwc() < 0.0) - { - e1 += _state.getUztwc(); - _state.setUztwc(0.0); - residualEvapTransDemand = evapTransDemand - e1; - - if (_state.getUzfwc() < residualEvapTransDemand) - { - //e2 is evap from UZFWC - e2 = _state.getUzfwc(); - //trace("setting _uzfwc to 0.0"); - _state.setUzfwc(0.0); - - residualEvapTransDemand -= e2; - perform220Check = false; //simulates goto 225 - } - else //_state.getUzfwc() >= residualEvapTransDemand //simulates 221 - { - //trace("221"); - e2 = residualEvapTransDemand; - - _state.setUzfwc(_state.getUzfwc() - e2); - - //trace("near 221, _uzfwc = " + _uzfwc); - residualEvapTransDemand = 0.0; - - perform220Check = true; - } - - } - else //(state.getUztwc() >= 0.0) //simulates goto 220 - { - perform220Check = true; - } - - - if (perform220Check) - { - //trace("220"); - if (( _state.getUztwc() / _params.getUztwm() ) < (_state.getUzfwc() / _params.getUzfwm())) - { - // upper zone free water ratio exceeds upper zone tension - // water ratio, this transfer free water to tension - - double uzrat = ( (_state.getUztwc() + _state.getUzfwc()) / ( _params.getUztwm() + _params.getUzfwm()) ); - - _state.setUztwc(( _params.getUztwm() * uzrat)); - - _state.setUzfwc((_params.getUzfwm() * uzrat)); - //trace("near 220, _uzfwc = " + _uzfwc); - } - } - - // line 225 equiv - //trace("225"); - if (_state.getUztwc() < 0.00001) - { - _state.setUztwc(0.0); - } - - if ( _state.getUzfwc() < 0.00001) - { - - _state.setUzfwc(0.0); - //trace("near 225, _uzfwc set to 0.0"); - } - - // compute et from the lower zone - // compute et from LZTWC (E3) - - e3 = residualEvapTransDemand * (_state.getLztwc() / - ( _params.getUztwm() + - _params.getLztwm()) ); - - _state.setLztwc(_state.getLztwc() - e3); - - if (_state.getLztwc() < 0.0 ) //simulates the goto 226 stuff - { - // e3 cannot exceed lztwc - e3 += _state.getLztwc(); - - _state.setLztwc(0.0); - } - - //trace("226"); - - //simulates line 226 - double ratlzt = _state.getLztwc() / _params.getLztwm(); - double ratlz = (_state.getLztwc() + _state.getLzfpc() + _state.getLzfsc() - getSaved()) / - (_params.getLztwm() + _params.getLzfpm() + _params.getLzfsm() - getSaved()); - - if (ratlzt < ratlz) - { - // resupply lower zone tension water from lower - // zone free water if more water available there - - double del = (ratlz -ratlzt) * _params.getLztwm(); - - // transfer from lzfwc to lztwc - - - _state.setLztwc(_state.getLztwc() + del); - _state.setLzfsc(_state.getLzfsc() - del); - - - if (_state.getLzfsc() < 0.0) - { - //if transfer exceeds lzfsc then remainder - // comes from lzfpc - _state.setLzfpc(_state.getLzfpc() + _state.getLzfsc()); - _state.setLzfsc(0.0); - } - } - - - //line 230 stuff - //trace("230"); - if (_state.getLztwc() < 0.00001) - { - _state.setLztwc(0.0); - } - - // compute et from _adimp area - e5 - double e5 = e1 + (residualEvapTransDemand + e2) * - ((_state.getAdimc() -e1 - _state.getUztwc())/(_params.getUztwm() + _params.getLztwm())); - - //adjust adminc, additional impervious area storage, for evaporation - - - _state.setAdimc(_state.getAdimc() - e5); - - if (_state.getAdimc() < 0.0) - { - // e5 cannot exceed adminc - e5 += _state.getAdimc(); - - _state.setAdimc(0.0); - } - - //simulates line 231 - //trace("231"); - e5 *= _params.getAdimp(); - // e5 is et from the area _adimp - - //-------------------------- - // compute percolation and runoff amounts - - double twx = rainfallPlusMelt + _state.getUztwc() - _params.getUztwm(); - // twx is the time interval available moisture in excess of - // uztw requirements - - if (twx < 0.0) - { - //all moisture held in uztw - no excess - _state.setUztwc(_state.getUztwc() + rainfallPlusMelt); - twx = 0.0; - - } - else //(twc >= 0.0) //simulates line 232 - { - _state.setUztwc(_params.getUztwm()); - } - - //line 233 - //trace("233"); - - _state.setAdimc(_state.getAdimc() + ( rainfallPlusMelt - twx) ); - - //compute impervious area runoff - _roimp = rainfallPlusMelt * _params.getPctim(); - // roimp is runoff from the minimum impervious area - - _simpvt += _roimp; - - //initialize time interval sums - - _sbf = 0.0; - _ssur = 0.0; - _sif = 0.0; - _sperc = 0.0; - _sdro = 0.0; - _spbf = 0.0; - - //determine computational time increments for the basic time interval - - //make sure that the rounding here is done the same way that fortran does - // it - //incrementCount = ninc - long ninc = (long) Math.floor(1.0 + (0.2 * ( _state.getUzfwc() + twx))); - - //ninc = number of time increments that the time interval is - // is divided into for further soil-moisture accounting. no one increment - // will exceed 5.0 mm of uzfwc + pav - - //dinc = incrementLength - double dinc = (1.0 / ninc) * dt; - - //trace("dinc RESULT = " + dinc + "with inputs:"); - //trace("ninc = " + ninc); - //trace("timeInterval = " + dt); - //trace("END dinc block"); - - - // dinc = length of each increment in days - - - //_pinc = _moisturePerIncrement - _pinc = twx / ninc; - // moisturePerIncrement = amount of available moisture per increment - // compute free water depletion fractions for the time increment being use - // basic depletions are for one day - - _duz = 1.0 - Math.pow((1.0 - _params.getUzk()), dinc); - _dlzp = 1.0 - Math.pow((1.0 - _params.getLzpk()), dinc); - _dlzs = 1.0 - Math.pow((1.0 - _params.getLzsk()), dinc); - - //trace("_dlzp result = " + _dlzp + " with inputs"); - //trace("_lzpk = " + _lzpk); - //trace("dinc = " + dinc); - - //trace("_dlzs result = " + _dlzs + " with inputs"); - //trace("_lzsk = " + _lzsk); - //trace("dinc = " + dinc); - - - // start incremental do loop for the time interval - - for (int i = 0; i < ninc; i++) - { - //trace("doIncrements loop, iteration # " + i); - doIncrements(); - } - - - //compute sums and adjust runoff amounts by the area over - // which they are generated - - double eUsed = e1 + e2 + e3; - //eUsed is the et from pArea which is 1.0-_adimp-pctim - _sif *= getParea(); - - //separate channel component of baseflow - //from the non-channel component - - double tbf = _sbf * getParea(); - //tbf is toal baseflow - - double bfcc = tbf * (1.0/ (1.0 + _params.getSide()) ); - //bfcc is baseflow, channel component - - _bfp= _spbf* getParea()/(1.0 + _params.getSide()); - - // error #2, had _bfs = bfcc = bfp; - _bfs = bfcc - _bfp; - - if (_bfs < 0.0) - { - _bfs = 0.0; - } - - double bfncc = tbf - bfcc; - // bfncc is baseflow, non-channel component - - //add to monthly sums - _sintft += _sif; - _sgwfp += _bfp; - _sgwfs += _bfs; - _srecht += bfncc; - _srost += _ssur; - _srodt += _sdro; - - //compute total channel inflow for the time interval - _tci = _roimp + _sdro + _ssur +_sif + bfcc; - - //compute e4-et from riparian vegetarian - double e4 = (evapTransDemand - eUsed) * _params.getRiva(); - - //subtract e4 from channel inflow - _tci = _tci - e4; - - if (_tci < 0.0) - { - e4 += _tci; - _tci = 0.0; - } - - //trace("250"); - _srot += _tci; - - //compute total evapotranspiration - tet - eUsed *= getParea(); - double tet = eUsed + e5 + e4; - - _sett += tet; - - _se1 += e1* getParea(); - _se3 += e3 * getParea(); - - _se4 += e4; - _se5 += e5; - - //check that adimc is >= uztwc - if ( _state.getAdimc() < _state.getUztwc()) - { - _state.setAdimc( _state.getUztwc()); - } - - // add to sums of runoff components - _rsum[0] += _tci; - _rsum[1] += _roimp; - _rsum[2] += _sdro; - _rsum[3] += _ssur; - _rsum[4] += _sif; - _rsum[5] += _bfs; - _rsum[6] += _bfp; - - return _tci; - } //end calculate - - //--------------------------------------------------------------------- - - private void doIncrements() - { - //put in lines from pages 2b to 3b - double adsur = 0.0; - - //compute direct runoff (from _adimp area) - double ratio = ( _state.getAdimc() - _state.getUztwc()) / _params.getLztwm(); - - if (ratio < 0.0) - { - ratio = 0.0; - } - - double addro = _pinc * Math.pow(ratio, 2); - //addro is the amount of direct runoff from the area _adimp - - //compute baseflow and keep track of time interval sum - - double bf = _state.getLzfpc() * _dlzp; - - _state.setLzfpc( _state.getLzfpc() - bf); - - - if ( _state.getLzfpc() <= 0.0001) - { - bf += _state.getLzfpc(); - _state.setLzfpc(0.0); - } - - //simulates line 234 - //trace("234"); - _sbf += bf; - _spbf += bf; - bf = _state.getLzfsc() * _dlzs; - - - _state.setLzfsc(_state.getLzfsc()- bf); - if (_state.getLzfsc() <= 0.0001) - { - bf += _state.getLzfsc(); - _state.setLzfsc(0.0); - } - - //line 235 - //trace("235"); - _sbf += bf; - - //computer percolation - if no water available then skip - - if ((_pinc + _state.getUzfwc()) <= 0.01) - { - - _state.setUzfwc( _state.getUzfwc() + _pinc); - //trace("near 235, _uzfwc = " + _uzfwc); - - //skip most of the rest//need to goto 249 - } - else //water available line // 251 equiv - { - //trace("251"); - double percm = (_params.getLzfpm() * _dlzp) + (_params.getLzfsm()* _dlzs); - double perc = percm * ( _state.getUzfwc() / _params.getUzfwm()); - - //trace("result percm = " + percm + " with inputs :"); - //trace("_lzfpm = " + _lzfpm); - //trace("dlzp = " + _dlzp); - //trace("_lzfsm = " + _lzfsm); - //trace("_dlzs = " + _dlzs); - - //trace("result perc = " + perc + " with inputs:" ); - //trace("percm = " + percm); - //trace("_uzfwc = " + _uzfwc); - //trace("_uzfwm = " + _uzfwm); - - - - double defr = 1.0 - ( (_state.getLztwc() + _state.getLzfpc() + _state.getLzfsc()) / (_params.getLztwm() + _params.getLzfpm() + _params.getLzfsm()) ); - //trace ("near 251 defr = " + defr); - - //trace ("_lztwc = " + _lztwc); - //trace ("_lzfpc = " + _lzfpc); - //trace ("_lzfsc = " + _lzfsc); - //trace ("_lztwm = " + _lztwm); - //trace ("_lzfpm = " + _lzfpm); - //trace ("_lzfsm = " + _lzfsm); - //trace ("end of 251 defr block"); - - - //defr is the lower zone moisture deficiency ratio - - double fr = 1.0; - //fr is the change in percolation withdrawal due to frozen ground - - double fi = 1.0; - // fi is the change in interflow withdrawal due to frozen ground - - //if (useFrozenGroundCalc) - //{ - // _uzdefr = 1.0 - ((_uztwc+_uzfwc) / (_uztwm + _uzfwm )); - // frozenGround(); - //} - - //error # 3 - //trace("input perc = " + perc ); - perc = perc * (1.0 + (_params.getZperc() * Math.pow(defr, _params.getRexp()))) * fr; - //trace("before 241, result perc = " + perc); - //trace("_zperc = " + _zperc); - //trace("defr = " + defr); - //trace("_rexp = " + _rexp); - //trace("fr = " + fr); - //trace("end perc print block"); - - - //Note: percolation occurs from uzfwc before pav is added - if (perc >= _state.getUzfwc()) - { - //percolation rate exceeds uzfwc - - perc = _state.getUzfwc(); - } - - //trace("241"); - //error #4 - found 6/30/03 - - - _state.setUzfwc(_state.getUzfwc() - perc); - //trace("near 241, _uzfwc = " + _uzfwc); - - // check to see if percolation exceeds lower zone deficiency - - double check = _state.getLztwc() + _state.getLzfpc() + _state.getLzfsc() + perc - _params.getLztwm() - _params.getLzfpm() -_params.getLzfsm(); - if (check > 0.0) - { - perc -= check; - - _state.setUzfwc(_state.getUzfwc() + check); - //trace("near 241, part 2, _uzfwc = " + _uzfwc); - - } - - //trace("242"); - _sperc += perc; - //sperc is the time interval summation of perc - - //compute interflow and keep track of time interval sum - // note: moisturePerIncrement has not yet been added - - double del = _state.getUzfwc() * _duz * fi; - _sif += del; - - //trace("near 242, _uzfwc = " + _uzfwc); - _state.setUzfwc(_state.getUzfwc() - del); - - //distribute percolated water into the lower zones - //tension water must be filled first except for the pfree area - //perct is percolation to tension water and perfc is percolation - //going to free water - double percf = 0.0; - - double perct = perc * (1.0 - _params.getPfree()); - if ((perct + _state.getLztwc()) <= _params.getLztwm()) - { - _state.setLztwc(_state.getLztwc() + perct); - percf = 0.0; - } - else // (perct + _lztwc) > _lztwm) // simulates line 234 - { - //trace("234"); - percf = perct + _state.getLztwc() - _params.getLztwm(); - - _state.setLztwc(_params.getLztwm()); - } - - //distribute percolation in excess tension requirements - //among the free water storages - - - //line 244 equiv - //trace("244"); - percf += (perc * _params.getPfree()); - - if (percf != 0.0) // may have problem with exact equivalence - { - double hpl = _params.getLzfpm() / (_params.getLzfpm() + _params.getLzfsm()); - //hpl is the relative size of the primary storage - //as compared with toal lower zone free water storage - - double ratlp = _state.getLzfpc() / _params.getLzfpm(); - double ratls = _state.getLzfsc() / _params.getLzfsm(); - //ratlp and ratls are content to capacity rations, or - //in other words, the realtive fullness of each storage - - double fracp = (hpl*2.0 * (1.0 - ratlp)) / - (( 1.0 - ratlp) + (1.0 - ratls)); - - //fracp is the fraction going to primary - if (fracp > 1.0) - { - fracp = 1.0; - } - - double percp = percf * fracp; - double percs = percf - percp; - - //percp and percs are the amount of the excess - //percolation going to primary and supplemental - //storages, respectively - - _state.setLzfsc(_state.getLzfsc() + percs); - - if (_state.getLzfsc() > _params.getLzfsm()) - { - percs = percs - _state.getLzfsc() + _params.getLzfsm(); - _state.setLzfsc(_params.getLzfsm()); - } - - - //line 246 equiv - //trace("246"); - - _state.setLzfpc( _state.getLzfpc() + (percf-percs)); - - //check to make sure _lzfpc does not exceed _lzfpm - - if (_state.getLzfpc() > _params.getLzfpm()) - { - double excess = _state.getLzfpc() - _params.getLzfpm(); - - _state.setLztwc(_state.getLztwc() + excess); - - _state.setLzfpc(_params.getLzfpm()); - - } - } - - //line 245 equiv - //trace("245"); - //distribute moisturePerIncrement between _uzfwc and surface runoff - if (_pinc != 0.0) - { - //check if moisturePerIncrement exceeds _uzfwm - - if ((_pinc + _state.getUzfwc()) <= _params.getUzfwm()) - { - //no surface runoff - _state.setUzfwc(_state.getUzfwc() + _pinc); - //trace("near 245, _uzfwc = " + _uzfwc); - //simulate goto 249 - it will flow through correctly as is - } - else - { - //simulate line 248 - //trace("248"); - //compute surface runoff (sur) and keep track of time - // interval sum - double sur = _pinc + _state.getUzfwc() - _params.getUzfwm(); - - - _state.setUzfwc(_params.getUzfwm()); - //trace("near 248, _uzfwc = " + _uzfwc); - - _ssur += (sur* getParea()); - adsur = sur*(1.0 - (addro/_pinc) ); - //adsur is the amount of surface runoff which comes - //from that portion of _adimp which is not - //currently generating direct runoff. addro/moisturePerIncrement - // is the fraction of _adimp currently generating - // direct runoff - - _ssur += (adsur*_params.getAdimp()); - - - } - } - } - - //line 249 equiv - //trace("249"); - - _state.setAdimc(_state.getAdimc() + ((_pinc) - addro) - adsur ); - if (_state.getAdimc() > _params.getUztwm() + _params.getLztwm()) - { - addro += (_state.getAdimc()) - (_params.getUztwm() + _params.getLztwm()); - - _state.setAdimc(_params.getUztwm() + _params.getLztwm()); - - } - - //trace("247"); - _sdro += (addro*_params.getAdimp()); - if (_state.getAdimc() < 0.00001) - { - _state.setAdimc(0.0); - } - - - } //end doIncrements - - // -------------------------------------------------------------------------- - - - public String toString() - { - String stateString = getState().toString(); - String paramString = getParameters().toString(); - String modelString = stateString + " " + paramString; - - return modelString; - } - - // -------------------------------------------------------------------------- - - -/* - public void setupTestLogFiles() - { - try - { - _runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - _internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - } -*/ - // -------------------------------------------------------------------------- - - - public RainfallRunoffModelType getModelType() - { - return RainfallRunoffModelType.SAC_SMA; - } - - // -------------------------------------------------------------------------- - -} //end class SacSmaModel diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaState.java b/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaState.java deleted file mode 100644 index 37dd5d8bf5..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaState.java +++ /dev/null @@ -1,347 +0,0 @@ - -/** - * Write a description of class SacSmaState here. - * - * @author Chip Gobs - * @version 6/20/03 - */ -package ohd.hseb.model.sacsma; -import java.text.DecimalFormat; -import java.text.NumberFormat; - -import ohd.hseb.db.DbTimeHelper; - -public class SacSmaState -{ - private String _basinId = null; - private String _source = null; - private long _validTime = 0; - private long _basisTime = 0; - private long _postingTime = 0; - - - private double _uztwc = 0.0; - private double _uzfwc = 0.0; - private double _lztwc = 0.0; - private double _lzfsc = 0.0; - private double _lzfpc = 0.0; - private double _adimc = 0.0; - - //private double[] _fgco = new double[6]; - //private double[] _rsum = new double[7]; - - //private double _ppe = 0.0; - //private double _psc = 0.0; - //private double _pta = 0.0; - //private double _pwe = 0.0; - - /** - * Constructor for objects of class SacSmaState - */ - public SacSmaState() - { - - } - - public SacSmaState(SacSmaState state) - { - - setBasinId(state.getBasinId()); - setSource(state.getSource()); - setValidTime(state.getValidTime()); - setBasisTime(state.getBasisTime()); - setPostingTime(state.getPostingTime()); - - - setUztwc(state.getUztwc()); - setUzfwc(state.getUzfwc()); - setLztwc(state.getLztwc()); - setLzfsc(state.getLzfsc()); - setLzfpc(state.getLzfpc()); - setAdimc(state.getAdimc()); - - return; - - } - - public SacSmaState(double[] stateArray) - { - int i = 0; - - setUztwc(stateArray[i++]); - setUzfwc(stateArray[i++]); - setLztwc(stateArray[i++]); - setLzfsc(stateArray[i++]); - setLzfpc(stateArray[i++]); - setAdimc(stateArray[i++]); - - //consider setting - //fpcoArray - //rsumArray - - //setPpe(stateArray[i++]); - //setPsc(stateArray[i++]); - //setPta(stateArray[i++]); - //setPwe(stateArray[i++]); - - - - } - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat format = new DecimalFormat(formatString); - - - - - String string = "Basin Id = " + _basinId + - " data source = " + _source + - " valid time = " + DbTimeHelper.getDateTimeStringFromLongTime(_validTime) + - " basis time = " + DbTimeHelper.getDateTimeStringFromLongTime(_basisTime) + - " posting time = " + DbTimeHelper.getDateTimeStringFromLongTime(_postingTime) + - "\n" + - " uztwc = " + format.format(_uztwc) + - " uzfwc = " + format.format(_uzfwc) + - " lztwc = " + format.format(_lztwc) + - " lzfsc = " + format.format(_lzfsc) + - " lzfpc = " + format.format(_lzfpc) + - " adimc = " + format.format(_adimc); - //" rsum = " + getRsumString() + "\n"; - - //"ppe = " + _ppe + "\n" + - //"pse = " + _psc + - //"pta = " + _pta + - //"pwe = " + _pwe + "\n"; - - return string; - } - - public void setBasinId(String basinId) - { - _basinId = basinId; - } - - public String getBasinId() - { - return _basinId; - } - - public void setSource(String source) - { - _source = source; - } - - public String getSource() - { - return _source; - } - - public void setValidTime(long validTime) - { - _validTime = validTime; - } - - public long getValidTime() - { - return _validTime; - } - - public void setBasisTime(long basisTime) - { - _basisTime = basisTime; - } - - public long getBasisTime() - { - return _basisTime; - } - - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - - public long getPostingTime() - { - return _postingTime; - } - - public boolean equals(SacSmaState state) - { - boolean result = false; - - - - if ( - (getBasinId().equalsIgnoreCase(state.getBasinId())) && - (getSource().equalsIgnoreCase(state.getSource())) && - (getValidTime() == state.getValidTime()) && - (getBasisTime() == state.getBasisTime()) && - (getPostingTime() == state.getPostingTime()) && - (getUztwc() == state.getUztwc()) && - (getUzfwc() == state.getUzfwc()) && - (getLztwc() == state.getLztwc()) && - (getLzfsc() == state.getLzfsc()) && - (getLzfpc() == state.getLzfpc()) && - (getAdimc() == state.getAdimc())) - { - result = true; - } - - return result; - } - - - - public boolean equalsValues(SacSmaState state) - { - boolean result = false; - - - - if ( - //(getBasinId().equalsIgnoreCase(state.getBasinId())) && - //(getSource().equalsIgnoreCase(state.getSource())) && - // (getValidTime() == state.getValidTime()) && - // (getBasisTime() == state.getBasisTime()) && - // (getPostingTime() == state.getPostingTime()) && - (getUztwc() == state.getUztwc()) && - (getUzfwc() == state.getUzfwc()) && - (getLztwc() == state.getLztwc()) && - (getLzfsc() == state.getLzfsc()) && - (getLzfpc() == state.getLzfpc()) && - (getAdimc() == state.getAdimc())) - { - result = true; - } - - return result; - } - - /* - public String getRsumString() - { - String formatString = "#####.###"; - NumberFormat format = new DecimalFormat(formatString); - - StringBuffer rsumStringBuffer = new StringBuffer(); - - for (int i = 0 ; i < _rsum.length; i++) - { - rsumStringBuffer.append(format.format(_rsum[i]) + " "); - } - - return rsumStringBuffer.toString(); - } - */ - - - public void setUztwc(double uztwc) { - this._uztwc = uztwc; - } - - public double getUztwc() - { - return _uztwc; - } - - public void setUzfwc(double uzfwc) { - this._uzfwc = uzfwc; - } - - public double getUzfwc() { - return _uzfwc; - } - - public void setLztwc(double lztwc) { - this._lztwc = lztwc; - } - - public double getLztwc() { - return _lztwc; - } - - public void setLzfsc(double lzfsc) { - this._lzfsc = lzfsc; - } - - public double getLzfsc() { - return _lzfsc; - } - - public void setLzfpc(double lzfpc) { - this._lzfpc = lzfpc; - } - - public double getLzfpc() { - return _lzfpc; - } - - public void setAdimc(double adimc) { - this._adimc = adimc; - } - - public double getAdimc() { - return _adimc; - } - -/* - public void setRsum(double[] rsum) - { - this._rsum = rsum; - } -*/ -/* - public double[] getRsum() - { - return _rsum; - } -*/ - /* - public void setPpe(double ppe) - { - this._ppe = ppe; - } - - - public double getPpe() - { - return _ppe; - } - - - public void setPwe(double pwe) - { - this._pwe = pwe; - } - - public double getPwe() - { - return _pwe; - } - - public void setPsc(double psc) - { - this._psc = psc; - } - - - public double getPsc() - { - return _psc; - } - - public void setPta(double _pta) { - this._pta = _pta; - } - - public double getPta() { - return _pta; - } -*/ - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaTest.java b/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaTest.java deleted file mode 100644 index 4620d634f6..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/model/sacsma/SacSmaTest.java +++ /dev/null @@ -1,898 +0,0 @@ -/* - * Created on Jun 23, 2003 - * - * - */ -package ohd.hseb.model.sacsma; -import java.io.BufferedReader; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.PrintWriter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.UnitHydrograph; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -/** - * @author Chip Gobs - * - * - */ -public class SacSmaTest -{ - - private static boolean _newTest = true; - - -//---------------------------------------------- - public static void main(String[] args) throws Exception - { - Logger logger = new FileLogger("D:/Data/code/SiteSpecific/output/SacSmaTiming.out"); - - logger.log("log this"); - - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - testModel(); - - timer.stop("Done with 1 iteration of testModel"); - - // testAll(); - - } //end main - - //--------------------------------------------------------------------------- - - //--------------------------------------------------------------------------- - - - //----------------------------------------------------------------------- - /* - * - * - * - - PXADJ = 1.000 - PEADJ = 1.000 - UZTWM = 60.000 - UZFWM = 25.000 - UZK = 0.350 - PCTIM = 0.000 - ADIMP = 0.000 - RIVA = 0.003 - ZPERC = 210.000 - REXP = 1.40 - LZTWM = 120.000 - LZFSM = 25.000 - LZFPM = 150.000 - LZSK = 0.080 - LZPK = 0.004 - PFREE = 0.250 - RSERV = 0.300 - SIDE = 0.000 - IOPTET=0 //we don't have this one, so ignore it - EFC = 0.50 - - - use these as the starting states (put them in the database) - - UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC - 31.02 0.009 31.94 0.060 74.74 62.04 - */ - - // ----------------------------------------------------------------------- - - public static void testModel() - { - - SacSmaParameters params = null; - SacSmaState state = null; - SacSmaRainfallRunoffModel model = null; - - RegularTimeSeriesHolder evapTimeSeriesHolder = new RegularTimeSeriesHolder(); - - int hoursPerInterval = 1; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - double[] precipArray = null; - double[] evaporationArray = null; - - String dataDir = null; - - try - { - - if (_newTest) //test against data provided by Mike Smith - { - - dataDir = "D:/Data/code/SiteSpecific/input/States_params/"; - - params = getTestParams(); - state = getTestState(); - - - precipArray = readPrecipArray(dataDir + "precip.in.txt"); - evaporationArray = readEvapArray(dataDir + "et_demand.txt"); - //evaporationArray = readEvapArray(dataDir + "actual_et.txt"); - } - else //test against the data provided by LMRFC - { - dataDir = "D:/Data/code/exampleCode/sacsma/"; - double[] parameterArray = readParameterArray(dataDir + "parmsandco"); - double[] stateArray = readStateArray(dataDir + "parmsandco"); - - params = new SacSmaParameters(parameterArray); - state = new SacSmaState(stateArray); - - precipArray = readPrecipArray(dataDir + "rainfile"); - evaporationArray = readEvapArray(dataDir + "evapfile"); - } - - - RegularTimeSeries evapTimeSeries = getEvapTimeSeries(evaporationArray); - evapTimeSeriesHolder.setTimeSeries(evapTimeSeries); - - boolean useMapeTimeSeries = true; - - double[] values = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; - MonthlyValues mapeAdjustmentValues = new MonthlyValues(values); - - double peAdjust = 1.0; - double pxAdjust = 1.0; - - model = new SacSmaRainfallRunoffModel(state, - params, - peAdjust, - pxAdjust, - useMapeTimeSeries, - mapeAdjustmentValues, - evapTimeSeriesHolder); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - int length = Math.min(precipArray.length, evaporationArray.length); - - String formatString = "#####.000"; - NumberFormat formatter = new DecimalFormat(formatString); - - System.out.println("Java version of SacSma:"); - - PrintWriter runoffWriter = null; - PrintWriter internalsWriter = null; - - try - { - runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(model.getState()) + - model.getParameters().toString(); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - internalsWriter.println("DAY HR UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC RAIN+MELT ACT-ET TOT-RO "); - - - int day = 1; - int hour = 1; - - //for each piece of input data - for (int i = 0 ; i < length; i++) - { - - precipAmount = precipArray[i]; - evaporationAmount = evaporationArray[i]; - - double totalChannelInflow = - model.calculate(hoursPerInterval/ 24.0, - precipAmount, - evaporationAmount); - - - if (_newTest ) - { - - runoffMessage = "day = " + day + - " hour = " + hour + - " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + formatter.format(totalChannelInflow); - } - else //old test with LMRFC's data - { - runoffMessage = "i = " + i + - " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + formatter.format(totalChannelInflow); - } - - - - System.out.println(runoffMessage); - runoffWriter.println(runoffMessage); - //System.out.println(model); - - - - internalsMessage = day + " " + hour + - " " + getStateString(model.getState()) + " " + - precipAmount + " " + - evaporationAmount + " " + - formatter.format(totalChannelInflow); - - // System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - hour++; - if (hour > 24) - { - hour = 1; - day++; - } - - - } //end for - - runoffWriter.close(); - internalsWriter.close(); - - } //end testModel - - - //----------------------------------------------------------------------- - private static SacSmaParameters getTestParams() - { - //uses sept93 data for ELDO2) - /* - PXADJ = 1.000 - PEADJ = 1.000 - UZTWM = 60.000 - UZFWM = 25.000 - UZK = 0.350 - PCTIM = 0.000 - ADIMP = 0.000 - RIVA = 0.003 - ZPERC = 210.000 - REXP = 1.40 - LZTWM = 120.000 - LZFSM = 25.000 - LZFPM = 150.000 - LZSK = 0.080 - LZPK = 0.004 - PFREE = 0.250 - RSERV = 0.300 - SIDE = 0.000 - IOPTET=0 //we don't have this one, so ignore it - EFC = 0.50 - */ - - SacSmaParameters params = new SacSmaParameters(); - - params.setPxadj(1.0); - params.setPeadj(1.0); - params.setUztwm(60.0); - params.setUzfwm(25.0); - params.setUzk(0.35); - params.setPctim(0.000); - params.setAdimp(0.000); - params.setRiva(0.003); - params.setZperc(210.000); - params.setRexp(1.40); - params.setLztwm(120.000); - params.setLzfsm(25.0); - params.setLzfpm(150.000); - params.setLzsk(0.080); - params.setLzpk(0.004); - params.setPfree(0.250); - params.setRserv(0.300); - params.setSide(0.000); - params.setEfc(.50); - - return params; - } - - // ----------------------------------------------------------------------- - private static SacSmaState getTestState() - { - /* - use these as the starting states (put them in the database) - - UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC - 31.02 0.009 31.94 0.060 74.74 62.04 - */ - /* - - Since the sac93_states test data does not explicitly give initial conditions, - I have reconstructed the initial conditions by using the 0+1 states and - using numeric analysis approximated the previous state (0) - - The xxxxxDiff variables show the approximate change in the state variables per iteration - for a particular - calibration when there is no precip (which is the case for the first 10 or so intervals). - - */ - - double uztwcDiff = -0.103; - double uzfwcDiff = 0; - double lztwcDiff = -0.02; - double lzfscDiff = -0.0002; - double lzfpcDiff = -0.0133; - double adimcDiff = -0.12; - - SacSmaState state = new SacSmaState(); - - // started with state 1, go back to the approximate state 0 - state.setUztwc(31.02 - uztwcDiff ); - state.setUzfwc(0.009 - uzfwcDiff ); - state.setLztwc(31.94 - lztwcDiff); - state.setLzfsc(0.060 - lzfscDiff); - state.setLzfpc(74.74 - lzfpcDiff ); - state.setAdimc(62.04 - adimcDiff); - - return state; - - } - // ----------------------------------------------------------------------- - public static void testAll() throws Exception - { - - double[] stateArray = null; - double[] parameterArray = null; - - SacSmaParameters params = null; - SacSmaState state = null; - SacSmaRainfallRunoffModel model = null; - - RegularTimeSeriesHolder evapTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - - int hoursPerInterval = 1; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - double[] precipArray = null; - double[] evaporationArray = null; - - UnitHydrograph ugh = UnitHydrograph.getTestUnitHydrograph(); - IrregularTimeSeries currentTimeSeries = null; - IrregularTimeSeries totalTimeSeries = - new IrregularTimeSeries(MeasuringUnit.cfs); - - - try - { - parameterArray = readParameterArray("D:/Data/exampleCode/sacsma/parmsandco"); - stateArray = readStateArray("D:/Data/exampleCode/sacsma/parmsandco"); - - params = new SacSmaParameters(parameterArray); - state = new SacSmaState(stateArray); - - - precipArray = readPrecipArray("D:/Data/exampleCode/sacsma/rainfile"); - evaporationArray = readEvapArray("D:/Data/exampleCode/sacsma/evapfile"); - - RegularTimeSeries evapTimeSeries = getEvapTimeSeries(evaporationArray); - evapTimeSeriesHolder.setTimeSeries(evapTimeSeries); - - - boolean useMapeTimeSeries = true; - - double[] values = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; - MonthlyValues mapeAdjustmentValues = new MonthlyValues(values); - - double peAdjust = 1.0; - double pxAdjust = 1.0; - - - model = new SacSmaRainfallRunoffModel(state, - params, - peAdjust, - pxAdjust, - useMapeTimeSeries, - mapeAdjustmentValues, - evapTimeSeriesHolder); - - } - catch (java.io.IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - int length = Math.min(precipArray.length, evaporationArray.length); - - String formatString = "#####.000"; - NumberFormat formatter = new DecimalFormat(formatString); - - System.out.println("Java version of SacSma:"); - - PrintWriter runoffWriter = null; - PrintWriter internalsWriter = null; - - try - { - runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(model.getState()) + - model.getParameters().toString(); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - long time = System.currentTimeMillis(); - - //for each piece of input data - for (int i = 0 ; i < length; i++) - { - - precipAmount = precipArray[i]; - evaporationAmount = evaporationArray[i]; - - double totalChannelInflow = - model.calculate(hoursPerInterval/ 24.0, - precipAmount, - evaporationAmount); - - - AbsTimeMeasurement runoff = new AbsTimeMeasurement(totalChannelInflow, time, MeasuringUnit.mm); - time += 60 *60 * 1000; //add an hour - currentTimeSeries = ugh.getFlowTimeSeries(runoff); - - totalTimeSeries = IrregularTimeSeries.add(totalTimeSeries, currentTimeSeries); - - runoffMessage = "i = " + i + " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + - formatter.format(totalChannelInflow); - - - - System.out.println(runoffMessage); - runoffWriter.println(runoffMessage); - //System.out.println(model); - - internalsMessage = getStateString(model.getState()); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - } //end for - - runoffWriter.close(); - internalsWriter.close(); - - } //end testAll - - - // ------------------------------------------------------------- - -// ------------------------------------------------------------- -/* - private static String getStateStringVerbose(SacSmaState state) - { - String formatString = "#####.000"; - NumberFormat format = new DecimalFormat(formatString); - - String string = " uztwc = " + format.format(state.getUztwc()) + - " uzfwc = " + format.format(state.getUzfwc()) + - " lztwc = " + format.format(state.getLztwc()) + "\n" + - " lzfsc = " + format.format(state.getLzfsc()) + - " lzfpc = " + format.format(state.getLzfpc()) + - " adimc = " + format.format(state.getAdimc()) + "\n"; - - - //" rsum = " + state.getRsumString() + "\n"; - - - return string; - } -*/ -// ---------------------------------------------- -private static String getStateString(SacSmaState state) -{ - -/* UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC */ - - String formatString = "###.000"; - NumberFormat format = new DecimalFormat(formatString); - - String string = format.format(state.getUztwc()) + - " " + format.format(state.getUzfwc()) + - " " + format.format(state.getLztwc()) + - " " + format.format(state.getLzfsc()) + - " " + format.format(state.getLzfpc()) + - " " + format.format(state.getAdimc()); - - return string; -} - -//---------------------------------------------- -/* -private static String getStateLabelString() -{ - return "UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC "; -} -*/ -// ---------------------------------------------- - - private static boolean isWhiteSpace(char c) - { - boolean result = false; - - if ( (c == ' ') || (c== '\t') ) - { - result = true; - - } - return result; - } - -// ---------------------------------------------- - private static boolean isPartOfANumber(char c) - { - boolean result = false; - - if ( ((c >= '0') && (c <= '9')) || - (c =='-') || (c == '.') - ) - { - result = true; - } - - return result; - } //end isPartOfANumber - -// ---------------------------------------------- - private static double[] readDoubleArray(String fileName, boolean skipFirstLine) throws java.io.IOException - { - // System.out.println("----------opening file = " + fileName); - List doubleList = new ArrayList(); - - FileReader fileReader = new FileReader(fileName); - BufferedReader bufferedReader = new BufferedReader(fileReader); - //FileReader reader = new FileReader(fileName); - - String line = null; - int lineCount = 0; - - - line = ""; - - while( line != null) - { - line = bufferedReader.readLine(); - if (line == null) - { - break; - } - lineCount++; - // System.out.println(fileName + ": line " + lineCount + " = " + line); - - if ((skipFirstLine) && (lineCount == 1) ) - { - continue; // skip this line entirely - } - - int lastPos = 0; - StringBuffer numberBuffer = new StringBuffer(); - boolean success = false; - boolean foundNumberPart = false; - String numberString = null; - - // assemble the number string from the line - for (int i = 0; i < line.length() ; i++) - { - char c = line.charAt(i); - if ( isPartOfANumber(c) || - ( isWhiteSpace(c) && (foundNumberPart == false ) ) - ) - { - if (isWhiteSpace(c)) - { - //System.out.println("I found whitespace at character " + i); - } - else - { - foundNumberPart = true; - numberBuffer.append(c); - // System.out.println("numberBuffer = " + numberBuffer + " i = " + i); - success = true; - } - } - else //we are done with looking for the number - { - numberString = numberBuffer.toString(); - //System.out.println("numberString = " + numberString); - break; - } - } //end for - - if ((success) && (numberString == null) ) - { - numberString = numberBuffer.toString(); - } - - if (success) - { - double number = -9999.9999; - number = Double.parseDouble(numberString); - doubleList.add(new Double(number)); - } - } //end while - - bufferedReader.close(); - fileReader.close(); - - //copy the list contents to the array of doubles - double[] doubleArray = new double[doubleList.size()]; - for (int i = 0; i < doubleList.size(); i++) - { - - Double doubleVar = (Double) doubleList.get(i); - doubleArray[i] = doubleVar.doubleValue(); - } - - // System.out.println("SacSmaTest.readDoubleArray size = " + - // doubleList.size()); - return doubleArray; - } - -// ---------------------------------------------- - - private static double[] readStateArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[6]; - - int skipAmount = 16; - - //skip the first 16 parameters in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i + skipAmount]; - } - - return sizedArray; - } - -// ---------------------------------------------- - - - private static double[] readParameterArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[16]; - -// skip the last 6 state/carryover variables in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i]; - } - - return sizedArray; - - } - -// ---------------------------------------------- - - private static double[] readPrecipArray(String fileName) throws java.io.IOException - { - - return readDoubleArray(fileName, true); - } - -// ---------------------------------------------- - - private static double[] readEvapArray(String fileName) throws java.io.IOException - { - - return readDoubleArray(fileName, false); - } - - -// ---------------------------------------------- - private static RegularTimeSeries getEvapTimeSeries(double[] evapArray) - { - - long endTime = System.currentTimeMillis(); - endTime = TimeHelper.truncateTimeInMillisToNearestHour(endTime, 1); - - final long millisPerHour = 60 * 60 * 1000; - long startTime = endTime - (millisPerHour * (evapArray.length -1)); - - int intervalInHours = 1; - - RegularTimeSeries ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, - MeasuringUnit.mm); - - return ts; - } - -// ---------------------------------------------- - public static void oldTestModel() - { - - double[] stateArray = null; - double[] parameterArray = null; - - SacSmaParameters params = null; - SacSmaState state = null; - SacSmaRainfallRunoffModel model = null; - - RegularTimeSeriesHolder evapTimeSeriesHolder = new RegularTimeSeriesHolder(); - - int hoursPerInterval = 1; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - double[] precipArray = null; - double[] evaporationArray = null; - - - try - { - parameterArray = readParameterArray("D:/Data/exampleCode/sacsma/parmsandco"); - - - - stateArray = readStateArray("D:/Data/exampleCode/sacsma/parmsandco"); - - params = new SacSmaParameters(parameterArray); - state = new SacSmaState(stateArray); - - - - precipArray = readPrecipArray("D:/Data/exampleCode/sacsma/rainfile"); - evaporationArray = readEvapArray("D:/Data/exampleCode/sacsma/evapfile"); - - RegularTimeSeries evapTimeSeries = getEvapTimeSeries(evaporationArray); - evapTimeSeriesHolder.setTimeSeries(evapTimeSeries); - - boolean useMapeTimeSeries = true; - - double[] values = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; - MonthlyValues mapeAdjustmentValues = new MonthlyValues(values); - - double peAdjust = 1.0; - double pxAdjust = 1.0; - - model = new SacSmaRainfallRunoffModel(state, - params, - peAdjust, - pxAdjust, - useMapeTimeSeries, - mapeAdjustmentValues, - evapTimeSeriesHolder); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - int length = Math.min(precipArray.length, evaporationArray.length); - - String formatString = "#####.000"; - NumberFormat formatter = new DecimalFormat(formatString); - - System.out.println("Java version of SacSma:"); - - PrintWriter runoffWriter = null; - PrintWriter internalsWriter = null; - - try - { - runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(model.getState()) + - model.getParameters().toString(); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - - //for each piece of input data - for (int i = 0 ; i < length; i++) - { - - precipAmount = precipArray[i]; - evaporationAmount = evaporationArray[i]; - - double totalChannelInflow = - model.calculate(hoursPerInterval/ 24.0, - precipAmount, - evaporationAmount); - - runoffMessage = "i = " + i + " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + - formatter.format(totalChannelInflow); - - - - System.out.println(runoffMessage); - runoffWriter.println(runoffMessage); - //System.out.println(model); - - internalsMessage = getStateString(model.getState()); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - - - } //end for - - runoffWriter.close(); - internalsWriter.close(); - - } //end oldTestModel - -} - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/DailyTimeSlotPolicy.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/DailyTimeSlotPolicy.java deleted file mode 100755 index e6d6aecb47..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/DailyTimeSlotPolicy.java +++ /dev/null @@ -1,54 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Map; - -public class DailyTimeSlotPolicy implements TimeSlotPolicy -{ - public Long getSlotDateTimeInMillis( long originalDateTimeInMillis ) - { - - originalDateTimeInMillis = truncateTimeInMillisToDay( originalDateTimeInMillis ); - originalDateTimeInMillis += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; - - return new Long( originalDateTimeInMillis ); - } - - public void insertTimeValuePairIfBetterMatch( Map timeValuePairHashMap, TimeValuePair newTimeValuePair ) - { - long newTopOfTheHourDateTime = truncateTimeInMillisToDay( newTimeValuePair.getDateTime() ); - newTopOfTheHourDateTime += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; - - long newObsDateTimeDiff = 0; - long oldObsDateTimeDiff = 0; - Long topOfHourKey = new Long( newTopOfTheHourDateTime ); - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairHashMap.get( topOfHourKey ); - - newObsDateTimeDiff = Math.abs( newTimeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( timeValuePair == null ) - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - } - else - { - oldObsDateTimeDiff = Math.abs( timeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( oldObsDateTimeDiff > newObsDateTimeDiff ) // if new valuepair is closer to top of the hour - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - } - } - } - - private long truncateTimeInMillisToDay( long dateTime ) - { - long dateTimeReturnValue = dateTime; - - dateTimeReturnValue /= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - dateTimeReturnValue *= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - - return dateTimeReturnValue; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/HourlyTimeSlotPolicy.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/HourlyTimeSlotPolicy.java deleted file mode 100755 index a08a0f9ac4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/HourlyTimeSlotPolicy.java +++ /dev/null @@ -1,75 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Map; - -import ohd.hseb.util.TimeHelper; - -public class HourlyTimeSlotPolicy implements TimeSlotPolicy -{ - private long _minutesBeforeTopOfHour = PDCPreprocessorDataMgr._minutesBeforeTopOfHour; - private long _minutesAfterTopOfHour = PDCPreprocessorDataMgr._minutesAfterTopOfHour; - - public Long getSlotDateTimeInMillis( long originalDateTimeInMillis ) - { - return new Long( TimeHelper.roundTimeInMillisToNearestHour( originalDateTimeInMillis ) ); - } - - private boolean obsDateTimeInRange( long dateTime, long newTopOfTheHourDateTime ) - { - long lowerWindowMinutes = newTopOfTheHourDateTime - ( _minutesBeforeTopOfHour * 60 * 1000 ); - long upperWindowMinutes = newTopOfTheHourDateTime + ( _minutesAfterTopOfHour * 60 * 1000 ); - boolean inRange = false; - - if ( ( dateTime >= lowerWindowMinutes ) && ( dateTime <= upperWindowMinutes ) ) - { - inRange = true; - } - - return inRange; - } - - public void insertTimeValuePairIfBetterMatch( Map timeValuePairHashMap, TimeValuePair newTimeValuePair ) - { - - String header = "HourlyTimeSlotPolicy.insertTimeValuePairIfBetterMatch() "; - - long newTopOfTheHourDateTime = TimeHelper.roundTimeInMillisToNearestHour( newTimeValuePair.getDateTime() ); - long newObsDateTimeDiff = 0; - long oldObsDateTimeDiff = 0; - Long topOfHourKey = new Long( newTopOfTheHourDateTime ); - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairHashMap.get( topOfHourKey ); - - newObsDateTimeDiff = Math.abs( newTimeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( timeValuePair == null ) - { - if ( obsDateTimeInRange( newTimeValuePair.getDateTime(), newTopOfTheHourDateTime ) ) - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - // System.out.println(header + "null previous value, so put " + newTimeValuePair + " into the map"); - } - else - { - // System.out.println(header + " " + timeValuePair + " is out of the time range, so won't insert into the map"); - } - - } - else - { - oldObsDateTimeDiff = Math.abs( timeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( oldObsDateTimeDiff > newObsDateTimeDiff ) // if new valuepair is closer to top of the hour - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - // System.out.println(header + "closer than previous value, so put " + newTimeValuePair + " into the map"); - } - else - { - - // System.out.println(header + " " + newTimeValuePair + " is not closer in time than " + - // timeValuePair + " so won't insert into the map"); - } - } - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/IrregularObsTimeSeries.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/IrregularObsTimeSeries.java deleted file mode 100755 index fc8e2b6833..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/IrregularObsTimeSeries.java +++ /dev/null @@ -1,174 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Gautam Sood - * - */ -public class IrregularObsTimeSeries -{ - private RegularObsTimeSeriesDescriptor _obsTimeSeriesDescriptor; - private Map _timeValuePairMap = new HashMap(); - private boolean _valuePairListNeedsRefreshing = true; - private List _timeValuePairList = new ArrayList(); - private List _dateTimeList = new ArrayList(); - private long _timeStepIntervalInMillis = 0; - -/** - * @param descriptor - RegularObsTimeSeriesDescriptor - * @param timeStepIntervalInHours - Time step duration in hours. e.g. hourly timeseries, 6 hourly timeseries, etc - * @param timeSlotPolicy - Hourly or Daily time slot policy - */ - public IrregularObsTimeSeries( RegularObsTimeSeriesDescriptor descriptor, long timeStepIntervalInHours ) - { - _obsTimeSeriesDescriptor = descriptor; - _timeStepIntervalInMillis = timeStepIntervalInHours * PDCPreprocessorDataMgr.MILLIS_PER_HOUR; - } - - public IrregularObsTimeSeries( IrregularObsTimeSeries obsTimeSeries, long timeStepDurationInHours ) - { - setObsTimeSeriesDescriptor( obsTimeSeries.getDescriptor() ); - setTopOfTheHourTimeValuePairMap( obsTimeSeries.getTopOfTheHourTimeValuePairMap() ); - setDateTimeList( obsTimeSeries.getDateTimeList() ); - _timeStepIntervalInMillis = timeStepDurationInHours * PDCPreprocessorDataMgr.MILLIS_PER_HOUR; - } - - public String toString() - { - updateTimeValuePairList(); - - StringBuffer stringBuffer = new StringBuffer(); - - for ( int i = 0; i < _timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) _timeValuePairList.get( i ); - stringBuffer.append(timeValuePair); - } - return stringBuffer.toString(); - } - - public List getTimeValuePairList( boolean forceRefresh ) - { - if ( ( _valuePairListNeedsRefreshing ) || ( forceRefresh ) ) - { - updateTimeValuePairList(); - } - - return _timeValuePairList; - } - - private void setDateTimeList( List dateTimeList ) - { - _dateTimeList = dateTimeList; - } - - private List getDateTimeList() - { - return _dateTimeList; - } - - - private void updateTimeValuePairList() - { - _timeValuePairList.clear(); - - for ( int i = 0; i < _dateTimeList.size(); i++ ) - { - Long dateTimeLong = (Long) _dateTimeList.get( i ); - TimeValuePair timeValuePair = (TimeValuePair) _timeValuePairMap.get( dateTimeLong ); - _timeValuePairList.add( timeValuePair ); - } - - _valuePairListNeedsRefreshing = false; - return; - } - - public void addTimeValuePairIfBetterMatch( TimeValuePair newTimeValuePair ) - { - _valuePairListNeedsRefreshing = true; - - Long dateTimeLong = new Long( newTimeValuePair.getDateTime() ); - - _timeValuePairMap.put( dateTimeLong, newTimeValuePair ); - addDateTimeToDateTimeList( dateTimeLong ); - } - - private void addDateTimeToDateTimeList( Long dateTimeLong ) - { - int index = -1; - boolean found = false; - - for ( int i = 0; i < _dateTimeList.size(); i++ ) - { - Long dateTime = (Long) _dateTimeList.get( i ); - - - if ( dateTimeLong.longValue() < dateTime.longValue() ) - { - index = i; - found = true; - break; - } - } - - if ( found ) //descriptor inserted at index - { - _dateTimeList.add( index, dateTimeLong ); - } - else // descriptorlist is either empty or descriptor belongs at the end of the list - { - index = 0; - _dateTimeList.add( dateTimeLong ); - } - } - - - public void setObsTimeSeriesDescriptor( RegularObsTimeSeriesDescriptor obsTimeSeriesDescriptor ) - { - _obsTimeSeriesDescriptor = obsTimeSeriesDescriptor; - } - - public RegularObsTimeSeriesDescriptor getDescriptor() - { - return _obsTimeSeriesDescriptor; - } - - public void setTimeValuePairList( List timeValueList ) - { - _timeValuePairList.addAll( timeValueList ); - } - - public void addTimeValuePairList( List timeValueList ) - { - _valuePairListNeedsRefreshing = true; - for ( int i = 0; i < timeValueList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValueList.get( i ); - addTimeValuePairIfBetterMatch( timeValuePair ); - } - } - - public void setTopOfTheHourTimeValuePairMap( Map topOfTheHourTimeValuePairMap ) - { - _timeValuePairMap = topOfTheHourTimeValuePairMap; - } - - public Map getTopOfTheHourTimeValuePairMap() - { - return _timeValuePairMap; - } - - - /** - * @return Returns the timeStepDurationInMillis. - */ - public long getTimeStepIntervalInMillis() - { - return _timeStepIntervalInMillis; - } -} \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/Location.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/Location.java deleted file mode 100755 index 826732d551..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/Location.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.pdc_pp; - -import ohd.hseb.model.RatingCurve; - -public class Location -{ - private String _lid = null; - private double _lat = 0; - private double _lon = 0; - private double _elevation = 0; - private String _locationName = null; - private boolean _isRiverStation = false; - private boolean _isFcstPoint = false; - private String _hsa = null; - private double _floodStage = 0; - private double _floodFlow = 0; - private RatingCurve _ratingCurve = null; - private boolean _isDCP = false; - private boolean _isObserver = false; - private String _telemType = null; - - public Location() - { - } - - public Location( Location location ) - { - _lid = location.getLid(); - _hsa = location.getHsa(); - _lat = location.getLat(); - _lon = location.getLon(); - _elevation = location.getElevation(); - _locationName = location.getLocationName(); - _isRiverStation = location.isRiverStation(); - _floodStage = location.getFloodStage(); - _floodFlow = location.getFloodFlow(); - _ratingCurve = location.getRatingCurve(); - _isDCP = location.isDCP(); - _isObserver = location.isObserver(); - _telemType = location.getTelemType(); - } - - public String toString() - { - String string = null; - - string = "LID = " + _lid + - " HSA = " + _hsa + - " Lat = " + _lat + - " Lon = " + _lon + - " Elev = " + _elevation + - " Location Name = " + _locationName + - " RiverStation = " + _isRiverStation + - " Flood Stage = " + _floodStage + - " Flood Flow = " + _floodFlow + - " DCP = " + _isDCP + - " Observer = " + _isObserver + - " Telem Type = " + _telemType; - - return string; - } - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setLat( double lat ) - { - _lat = lat; - } - public double getLat() - { - return _lat; - } - public void setLon( double lon ) - { - _lon = lon; - } - public double getLon() - { - return _lon; - } - public void setElevation( double elevation ) - { - _elevation = elevation; - } - public double getElevation() - { - return _elevation; - } - public void setLocationName( String locationName ) - { - _locationName = locationName; - } - public String getLocationName() - { - return _locationName; - } - - public void setRiverStation( boolean isRiverStation ) - { - _isRiverStation = isRiverStation; - } - - public boolean isRiverStation() - { - return _isRiverStation; - } - - public void setFloodStage( double floodStage ) - { - _floodStage = floodStage; - } - - public double getFloodStage() - { - return _floodStage; - } - - public void setHsa( String hsa ) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } - - public void setFcstPoint( boolean isFcstPoint ) - { - _isFcstPoint = isFcstPoint; - } - - public String isFcstPoint() - { - String result = "F"; - - if ( _isFcstPoint ) - { - result = "T"; - } - - return result; - } - - public void setFloodFlow( double floodFlow ) - { - _floodFlow = floodFlow; - } - - public double getFloodFlow() - { - return _floodFlow; - } - - public void setRatingCurve( RatingCurve ratingCurve ) - { - _ratingCurve = ratingCurve; - } - - public RatingCurve getRatingCurve() - { - return _ratingCurve; - } - - public void setDCP( boolean isDCP ) - { - _isDCP = isDCP; - } - - public boolean isDCP() - { - return _isDCP; - } - - public void setObserver( boolean isObserver ) - { - _isObserver = isObserver; - } - - public boolean isObserver() - { - return _isObserver; - } - - public void setTelemType( String telemType ) - { - _telemType = telemType; - } - - public String getTelemType() - { - return _telemType; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/NonPrecipObsTableManager.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/NonPrecipObsTableManager.java deleted file mode 100755 index ac01c9887e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/NonPrecipObsTableManager.java +++ /dev/null @@ -1,257 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; - - - -public class NonPrecipObsTableManager extends DbTable -{ - public static final int DECIMAL_PLACES = 2; - - public NonPrecipObsTableManager(Database database, String tableName ) - { - //Constructor calls DbTable's constructor - super(database); - setTableName( tableName ); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a Vector of ObservedData objects - //----------------------------------------------------------------- - public List select( String tableName, int numHoursToProcess, long endTime ) throws SQLException - { - String header = "NonPrecipObsTableManager.select: "; - - CodeTimer nonPrecipObsTableTimer = new CodeTimer(); - if ( PDCPreprocessorDataMgr._DEBUG ) - { - nonPrecipObsTableTimer.start(); - } - RegularObsTimeSeriesDescriptor obsTimeSeriesDescriptor = - new RegularObsTimeSeriesDescriptor(); - RegularObsTimeSeries obsTimeSeries = null; - double value = 0.0; - long obsTime = 0; - TimeValuePair timeValuePair = null; - - long hourlyEndTime = TimeHelper.roundTimeInMillisToNearestHour( endTime ); - long hourlyStartTime = hourlyEndTime - - ( ( numHoursToProcess - 1) * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - - long dailyEndTime = truncateTimeInMillisToDay( endTime ); - dailyEndTime += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; //12z to 12z - long dailyStartTime = dailyEndTime - - ( ( numHoursToProcess ) * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - - String pe = null; - String extremum = null; - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - DailyTimeSlotPolicy dailyTimeSlotPolicy = new DailyTimeSlotPolicy(); - CodeTimer queryTimer = new CodeTimer(); - - List obsTimeSeriesList = new ArrayList(); - int recordsFound = 0; - - String tabbedheader = " " + header; - - Map obsTimeSeriesMap = new HashMap(); - - // create a List to hold Height Records - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = - "Select lid, pe, dur, extremum, ts, value, obstime from " + - tableName + " WHERE obstime >= '" + - DbTimeHelper.getDateTimeStringFromLongTime( hourlyStartTime ) + "'"; - - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery( selectStatement ); - - // loop through the result set - boolean rsNext = rs.next(); - - // Setting the start and end time for the timeseries - - while ( rsNext ) - { - obsTimeSeriesDescriptor.setLid( getTrimmedString( rs.getString( 1 ) ) ); - pe = getTrimmedString( rs.getString( 2 ) ); - obsTimeSeriesDescriptor.setPe( pe ); - obsTimeSeriesDescriptor.setDur( rs.getShort( 3 ) ); - extremum = getTrimmedString( rs.getString( 4 ) ); - obsTimeSeriesDescriptor.setExtremum( extremum ); - obsTimeSeriesDescriptor.setTs( getTrimmedString( rs.getString( 5 ) ) ); - value = MathHelper.roundToNDecimalPlaces(rs.getDouble( 6 ), DECIMAL_PLACES) ; - obsTime = getLongTime( rs.getString( 7 ) ); - - timeValuePair = new TimeValuePair( obsTime, value ); - - obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesMap.get( obsTimeSeriesDescriptor ); - - if ( obsTimeSeries == null ) - { - // Check for Air Temperature Daily MAX and MIN - if ( (pe.equalsIgnoreCase("TA")) && - ((extremum.equalsIgnoreCase("X")) || (extremum.equalsIgnoreCase("N"))) ) - { - obsTimeSeriesDescriptor.setEndTime( dailyEndTime ); - obsTimeSeriesDescriptor.setStartTime( dailyStartTime ); - - //System.out.println(header + "dailyEndTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(dailyEndTime)); - - RegularObsTimeSeriesDescriptor newDescriptor = - new RegularObsTimeSeriesDescriptor( obsTimeSeriesDescriptor ); - - obsTimeSeries = - new RegularObsTimeSeries( newDescriptor, 24, - dailyTimeSlotPolicy ); // 24 hour data - } - else - { - obsTimeSeriesDescriptor.setEndTime( hourlyEndTime ); - obsTimeSeriesDescriptor.setStartTime( hourlyStartTime ); - RegularObsTimeSeriesDescriptor newDescriptor = - new RegularObsTimeSeriesDescriptor( obsTimeSeriesDescriptor ); - - obsTimeSeries = new RegularObsTimeSeries( newDescriptor, 1, - hourlyTimeSlotPolicy ); // hourly data - } - - addTimeSeriesToOrderedList( obsTimeSeriesList, obsTimeSeries ); - - obsTimeSeriesMap.put( obsTimeSeries.getDescriptor(), obsTimeSeries ); - } - - - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - - // increment the number of records found - recordsFound++; - rsNext = rs.next(); - } - - System.out.println(header + "table = " + tableName + - " raw recordsFound = " + recordsFound); - - // Close the result set - rs.close(); - - - return obsTimeSeriesList; - } // end of select method - - -// ------------------------------------------------------------------------- - -/** - * - * @param dateTime - date/time in milliseconds - * @return - the date/time truncated to the day. e.g. 10-30-2005 5:00pm becomes 10-30-2005 12:00am - */ - private long truncateTimeInMillisToDay( long dateTime ) - { - long dateTimeReturnValue = dateTime; - - dateTimeReturnValue /= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - dateTimeReturnValue *= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - - return dateTimeReturnValue; - } - - - // -------------------------------------------------------------------------------------------- - public void addTimeSeriesToOrderedList(List obsTimeSeriesList, RegularObsTimeSeries newTimeSeries ) - { - String header = "NonPrecipobsTableManager.addTimeSeriesToOrderedList(): "; - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - Comparator comparator = new RegularObsTimeSeriesComparator(); - - index = Collections.binarySearch(obsTimeSeriesList, newTimeSeries, comparator); // -4 - - // Add the non-existent item to the list - if (index < 0) - { - obsTimeSeriesList.add(-index-1, newTimeSeries); - } - else if (index == 0) - { - obsTimeSeriesList.add(index, newTimeSeries); - System.out.println(header + "Item added at 0 index in the list"); - } - - else - { - System.out.println(header + "Item aleady in the list"); - } - } - - // -------------------------------------------------------------------------------------------- - - - public void addTimeSeriesToOrderedList_old( List obsTimeSeriesList, - RegularObsTimeSeries newTimeSeries ) - { - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( i ); - - if ( newLid.compareToIgnoreCase( obsTimeSeries.getDescriptor().getLid() ) < 0 ) - { - index = i; - found = true; - break; - } - } - - if ( found ) //descriptor inserted at index - { - obsTimeSeriesList.add( index, newTimeSeries ); - } - else // descriptorlist is either empty or descriptor belongs at the end of the list - { - index = 0; - obsTimeSeriesList.add( newTimeSeries ); - } - } - - public long getLongTime( String timeString ) - { - long longTime = 0; - - longTime = getLongTimeFromDateTimeString( timeString ); - return longTime; - } - - public List select( String arg0 ) throws SQLException - { - throw new Error( "NonPrecipObsTable.select(String) should not be used" ); - } -} // end of HeightTable class diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileReader.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileReader.java deleted file mode 100755 index 88e8c6013c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileReader.java +++ /dev/null @@ -1,496 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.InputMismatchException; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - - -public class PDCFileReader -{ - private List _obsTimeSeriesList; - private String _fullFilePath = null; - - private int _numberOfValues = 0; - private long _startTimeInSeconds = 0; - private int _timeIntervalInSeconds = 0; - private Map _durCodetoDurMap = null; - private boolean _debug = false; - - private BufferedReader _reader = null; - - private static final int SECONDS_PER_HOUR = 3600; - - - // ---------------------------------------------------------------------------------- - public PDCFileReader(String fullFilePath) - { - this(fullFilePath, PDCFileReader.getDurCodeToDurMap()); - } - - // ---------------------------------------------------------------------------------- - public PDCFileReader(String fullFilePath, Map durCodeToDurMap) - { - _fullFilePath = fullFilePath; - _durCodetoDurMap = durCodeToDurMap; - _obsTimeSeriesList = new ArrayList(); - } - - public void resetObsTimeSeriesList() - { - if(_obsTimeSeriesList == null) - _obsTimeSeriesList = new ArrayList(); - else - _obsTimeSeriesList.clear(); - - Runtime.getRuntime().gc(); - } - // ---------------------------------------------------------------------------------- - public List read() - { - String header = "PDCFileReader.read() "; - // boolean done = false; - - - try - { - FileReader fileReader = new FileReader(_fullFilePath); - _reader = new BufferedReader(fileReader); - - readFileHeader(); - - - String line = "DUMMY"; - - boolean done = false; - - while ( ! done ) - { - try - { - RegularObsTimeSeries timeSeries = readRegularStationData(); - if (timeSeries != null) - { - // debug_logline(header + - // " adding timeSeries to _obsTimeSeriesList " + - // timeSeries.getDescriptor() + - // " value pair list size() = " + - // timeSeries.getTimeValuePairList(true).size()); - - _obsTimeSeriesList.add(timeSeries); - - } - else - { - debug_logline(header + "timeSeries is null"); - } - - } - catch (EOFException e) - { - done = true; - } - catch (Exception e) - { - System.err.println(header + - "Exception reading file " + _fullFilePath + - " " + e.getMessage()); - e.printStackTrace(); - - done = true; - } - } //end while - - // System.out.println(header + "_obsTimeSeriesList contains " + - // _obsTimeSeriesList.size() + " time series. "); - - - if (_reader != null) - { - _reader.close(); - _reader = null; - } - - } //end try - catch (FileNotFoundException e) - { - System.err.println("Unable to open" + _fullFilePath); - _obsTimeSeriesList = null; - } - catch (IOException e) - { - System.err.println("Unable to open" + _fullFilePath); - _obsTimeSeriesList = null; - } - - return _obsTimeSeriesList; - } - - // ---------------------------------------------------------------------------------- - private void readFileHeader() throws IOException - { - String header = "PDCFileReader.readFileHeader(): "; - String line = null; - - //ignore the first 6 lines - line = _reader.readLine(); - debug_logline(header + " line 1 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 2 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 3 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 4 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 5 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 6 = " + line); - - String fileHeaderString = _reader.readLine(); - - StringTokenizer tokenizer = new StringTokenizer(fileHeaderString); - - _numberOfValues = Integer.parseInt(tokenizer.nextToken()); - - _startTimeInSeconds = Long.parseLong(tokenizer.nextToken()); - - _timeIntervalInSeconds = Integer.parseInt(tokenizer.nextToken()); - - - debug_logline("_numberOfHours = " + _numberOfValues + - " _startTimeInSeconds = " + _startTimeInSeconds + - " _timeIntervalInSeconds = " + _timeIntervalInSeconds ); - - } - // ---------------------------------------------------------------------------------- - private RegularObsTimeSeries readRegularStationData() throws Exception - { - - String header = "PDCFileReader.readRegularStationData() "; - RegularObsTimeSeriesDescriptor descriptor = readStationHeader(); - - debug_log(header + "descriptor = " + descriptor + "\n"); - - TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - - long timeIntervalInHours = _timeIntervalInSeconds/SECONDS_PER_HOUR ; - - RegularObsTimeSeries timeSeries = new RegularObsTimeSeries(descriptor, - timeIntervalInHours, - timeSlotPolicy); - - try - { - readValues(timeSeries); - } - catch (Exception e) - { - System.err.println(header + - "Error when reading values for descriptor = " + - descriptor); - e.printStackTrace(); - } - - // System.out.println(header + "returning timeSeries = " + timeSeries); - return timeSeries; - } - - - // ---------------------------------------------------------------------------------- - - private RegularObsTimeSeriesDescriptor readStationHeader() throws IOException - { - String header = "PDCFileReader.readStationHeader(): "; - - - String stationHeaderLine = _reader.readLine(); - - - - StringTokenizer headerTokenizer = new StringTokenizer(stationHeaderLine); - // Scanner headerScanner = new Scanner(stationHeaderLine); - - String deviceLine = _reader.readLine(); - - if ( (stationHeaderLine == null) || (deviceLine == null) ) - { - throw new EOFException(); - } - - StringTokenizer deviceLineTokenizer = new StringTokenizer(deviceLine); - - // Scanner deviceScanner = new Scanner(deviceLine); - - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - - long startTimeInMillis = _startTimeInSeconds * 1000; - long timeIntervalInMillis = _timeIntervalInSeconds * 1000; - long endTimeInMillis = startTimeInMillis + ((_numberOfValues-1) * timeIntervalInMillis); - - descriptor.setStartTime(startTimeInMillis); - descriptor.setEndTime(endTimeInMillis) ; - - String lid = headerTokenizer.nextToken(); - descriptor.setLid(lid); - - String hsa = headerTokenizer.nextToken(); - String paramCode = headerTokenizer.nextToken(); - - debug_logline("lid = " + lid + - " hsa = " + hsa + - " paramCode = " + paramCode); - - - //Work on the ParamCode. It is in multiple parts - setPedtse(descriptor, paramCode); - - double elevation = Double.parseDouble(headerTokenizer.nextToken()); - double lat = Double.parseDouble(headerTokenizer.nextToken()); - double lon = Double.parseDouble(headerTokenizer.nextToken()); - String fcst_pointString = headerTokenizer.nextToken(); - String name = restOfLine(headerTokenizer); - name = name.trim(); - - debug_logline(header + "name = :" + name + ":"); - - - // parse out the device line - String dcpString = deviceLineTokenizer.nextToken(); - String observerString = deviceLineTokenizer.nextToken(); - String telemTypes = restOfLine(deviceLineTokenizer); - - debug_logline(""); - debug_logline("dcpString = " + dcpString + - " observerString = " + observerString + - " telemTypes String = " + telemTypes); - - // descriptor.setHsa // can't do it easily, but don't need it anyway - - // System.out.println(header + " descriptor = " + descriptor); - - return descriptor; - } - - // ---------------------------------------------------------------------------------- - String restOfLine(StringTokenizer tokenizer) - { - String header = "PDCFileReader.restOfLine(): "; - - StringBuffer buffer = new StringBuffer(); - - int count = 0; - - while (tokenizer.hasMoreTokens()) - { - buffer.append(tokenizer.nextToken() + " "); - count++; - } - - //get rid of extra " " at the end - if (count > 0) - { - int spaceIndex = buffer.lastIndexOf(" "); - buffer.delete(spaceIndex, spaceIndex+1); - } - - String restOfLineString = buffer.toString(); - - // debug_log(header + " restofLine = " + restOfLineString + "\n"); - - return restOfLineString; - } - - // ---------------------------------------------------------------------------------- - private void setPedtse(RegularObsTimeSeriesDescriptor descriptor, String paramCode) - { - - int length = paramCode.length(); - - try - { - descriptor.setPe(paramCode.substring(0, 2)); - - String durCodeString = paramCode.substring(2, 3); - String durString = (String) _durCodetoDurMap.get(durCodeString); - short dur = 0; - - if (durString != null) - { - dur = Short.parseShort(durString); - } - - descriptor.setDur(dur); - - String typeSource = paramCode.substring(3, 5); - descriptor.setTs(typeSource); - - String extremum = paramCode.substring(5, 6); - - descriptor.setExtremum(extremum); - } - catch (Error e) - { - - } - - return; - } - // ---------------------------------------------------------------------------------- - - private void readValues(RegularObsTimeSeries timeSeries) throws IOException - { - String header = "PDCFileReader.readValues(): "; - long time = _startTimeInSeconds * 1000; - long incrementTime = timeSeries.getTimeStepIntervalInMillis(); - - RegularObsTimeSeriesDescriptor desc = timeSeries.getDescriptor(); - - double value = 0.0; - - List pairList = new ArrayList(); - - debug_logline(header + "attempting to read " + _numberOfValues + " values."); - - String valueLine = _reader.readLine(); - StringTokenizer tokenizer = new StringTokenizer(valueLine); - boolean isMissing = false; - - - if (valueLine.indexOf("MISSING") > -1) - { - System.out.println(header + " time series " + desc.toString() + " is SET to MISSING!"); - desc.setMissing(true); - isMissing = true; - } - - - for (int i = 0; i < _numberOfValues; i++) - { - try - { - if (isMissing) - { - value = PDCFileWriter.MISSING; - } - else - { - value = Double.parseDouble(tokenizer.nextToken()); - } - - debug_log("value[" + i +"] = " + value); - } - catch (InputMismatchException e1) - { - debug_log("when i = " + i); - debug_logline("read in a bad value from line = " + valueLine); - - throw (new InputMismatchException("bad read at entry # " + - i + " (starts at 0)" + - " value line = " + valueLine + - " TS Descriptor = " + desc )); - } - - TimeValuePair pair = new TimeValuePair(time, value); - pairList.add(pair); - - time += incrementTime; - } - - debug_logline(""); - - timeSeries.addTimeValuePairList(pairList); - - // int size = timeSeries.getTimeValuePairList(true).size(); - - // System.out.println(header + "timeSeries.getTimeValuePairList(true).size() = " + size ); - - - return; - } - - // ---------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - String fileName = "/fs/hseb/ob72/wfo_rfc/whfs/local/data/pdc_pp/keep/cachedWind.dat"; - - Map durCodeToDurMap = getDurCodeToDurMap(); - - PDCFileReader reader = new PDCFileReader (fileName, durCodeToDurMap); - reader.setDebug(true); - - reader.read(); - - - } - // ---------------------------------------------------------------------------------- - private static Map getDurCodeToDurMap() - { - // used just for testing. Real code uses database to access - //shefdur table. - Map durCodeToDurMap = new HashMap(); - - addCodeToMap(durCodeToDurMap, "I", 0); - addCodeToMap(durCodeToDurMap, "H", 1001); - addCodeToMap(durCodeToDurMap, "B", 1002); - addCodeToMap(durCodeToDurMap, "T", 1003); - addCodeToMap(durCodeToDurMap, "F", 1004); - addCodeToMap(durCodeToDurMap, "Q", 1006); - addCodeToMap(durCodeToDurMap, "D", 2001); - addCodeToMap(durCodeToDurMap, "Z", 5000); - - - return durCodeToDurMap; - } - - private static void addCodeToMap(Map durCodeToDurMap, String durCode, int duration) - { - durCodeToDurMap.put(durCode, duration + ""); - } - /** - * @param debug The debug to set. - */ - public void setDebug(boolean debug) - { - this._debug = debug; - } - /** - * @return Returns the debug. - */ - public boolean getDebug() - { - return _debug; - } - - // ---------------------------------------------------------------------------------- - private void debug_logline(String message) - { - debug_log(message + '\n'); - - return; - } - // ---------------------------------------------------------------------------------- - private void debug_log(String message) - { - if (getDebug()) - { - System.out.print(message); - } - - return; - } - // ---------------------------------------------------------------------------------- -} - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileReaderSlow.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileReaderSlow.java deleted file mode 100755 index ad3d5de40e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileReaderSlow.java +++ /dev/null @@ -1,422 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.InputMismatchException; -import java.util.List; -import java.util.Map; -import java.util.Scanner; - - -public class PDCFileReaderSlow -{ - private List _obsTimeSeriesList; - private String _fullFilePath = null; - private Scanner _scanner = null; - - private int _numberOfValues = 0; - private long _startTimeInSeconds = 0; - private int _timeIntervalInSeconds = 0; - private Map _durCodetoDurMap = null; - private boolean _debug = false; - - - - private static final int SECONDS_PER_HOUR = 3600; - - - // ---------------------------------------------------------------------------------- - public PDCFileReaderSlow(String fullFilePath) - { - this(fullFilePath, PDCFileReaderSlow.getDurCodeToDurMap()); - } - - // ---------------------------------------------------------------------------------- - public PDCFileReaderSlow(String fullFilePath, Map durCodeToDurMap) - { - _fullFilePath = fullFilePath; - _durCodetoDurMap = durCodeToDurMap; - - _obsTimeSeriesList = new ArrayList(); - } - // ---------------------------------------------------------------------------------- - public List read() - { - String header = "PDCFileReaderSlow.read() "; - // boolean done = false; - - try - { - FileReader fileReader = new FileReader(_fullFilePath); - BufferedReader reader = new BufferedReader(fileReader); - _scanner = new Scanner ( reader ); - - readFileHeader(); - - while ( _scanner.hasNext() ) - { - try - { - RegularObsTimeSeries timeSeries = readRegularStationData(); - if (timeSeries != null) - { - // debug_logline(header + - // " adding timeSeries to _obsTimeSeriesList " + - // timeSeries.getDescriptor() + - // " value pair list size() = " + - // timeSeries.getTimeValuePairList(true).size()); - - _obsTimeSeriesList.add(timeSeries); - - } - else - { - debug_logline(header + "timeSeries is null"); - } - - } - catch (Exception e) - { - System.err.println(header + - "Exception reading file " + _fullFilePath + - " " + e.getMessage()); - e.printStackTrace(); - // done = true; - } - } - - // System.out.println(header + "_obsTimeSeriesList contains " + - // _obsTimeSeriesList.size() + " time series. "); - - - } - catch (FileNotFoundException e) - { - System.err.println("Unable to open" + _fullFilePath); - _obsTimeSeriesList = null; - } - - if (_scanner != null) - { - _scanner.close(); - } - - return _obsTimeSeriesList; - } - - // ---------------------------------------------------------------------------------- - private void readFileHeader() - { - String header = "PDCFileReaderSlow.readFileHeader(): "; - String line = null; - - //ignore the first 6 lines - line = _scanner.nextLine(); - debug_logline(header + " line 1 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 2 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 3 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 4 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 5 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 6 = " + line); - - String fileHeaderString = _scanner.nextLine(); - Scanner fileHeaderScanner = new Scanner(fileHeaderString); - - - _numberOfValues = fileHeaderScanner.nextInt(); - - _startTimeInSeconds = fileHeaderScanner.nextLong(); - - _timeIntervalInSeconds = fileHeaderScanner.nextInt(); - - - debug_logline("_numberOfHours = " + _numberOfValues + - " _startTimeInSeconds = " + _startTimeInSeconds + - " _timeIntervalInSeconds = " + _timeIntervalInSeconds ); - - } - // ---------------------------------------------------------------------------------- - private RegularObsTimeSeries readRegularStationData() throws Exception - { - - String header = "PDCFileReaderSlow.readRegularStationData() "; - RegularObsTimeSeriesDescriptor descriptor = readStationHeader(); - - debug_log(header + "descriptor = " + descriptor); - - TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - - long timeIntervalInHours = _timeIntervalInSeconds/SECONDS_PER_HOUR ; - - RegularObsTimeSeries timeSeries = new RegularObsTimeSeries(descriptor, - timeIntervalInHours, - timeSlotPolicy); - - try - { - readValues(timeSeries); - } - catch (Exception e) - { - System.err.println(header + - "Error when reading values for descriptor = " + - descriptor); - e.printStackTrace(); - } - - // System.out.println(header + "returning timeSeries = " + timeSeries); - return timeSeries; - } - - - // ---------------------------------------------------------------------------------- - - private RegularObsTimeSeriesDescriptor readStationHeader() - { - - String stationHeaderLine = _scanner.nextLine(); - Scanner headerScanner = new Scanner(stationHeaderLine); - - String deviceLine = _scanner.nextLine(); - Scanner deviceScanner = new Scanner(deviceLine); - - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - String header = "PDCFileReaderSlow.readStationHeader(): "; - long startTimeInMillis = _startTimeInSeconds * 1000; - long timeIntervalInMillis = _timeIntervalInSeconds * 1000; - long endTimeInMillis = startTimeInMillis + ((_numberOfValues-1) * timeIntervalInMillis); - - descriptor.setStartTime(startTimeInMillis); - descriptor.setEndTime(endTimeInMillis) ; - - String lid = headerScanner.next(); - descriptor.setLid(lid); - - String hsa = headerScanner.next(); - String paramCode = headerScanner.next(); - - //Work on the ParamCode. It is in multiple parts - setPedtse(descriptor, paramCode); - - double elevation = headerScanner.nextDouble(); - double lat = headerScanner.nextDouble(); - double lon = headerScanner.nextDouble(); - String fcst_pointString = headerScanner.next(); - String name = headerScanner.nextLine(); - name = name.trim(); - - debug_logline(header + "name = :" + name + ":"); - - - // parse out the device line - String dcpString = deviceScanner.next(); - String observerString = deviceScanner.next(); - String telemTypes = deviceScanner.nextLine(); - - debug_logline(""); - debug_logline("dcpString = " + dcpString + - " observerString = " + observerString + - " telemTypes String = " + telemTypes); - - // descriptor.setHsa // can't do it easily, but don't need it anyway - - // System.out.println(header + " descriptor = " + descriptor); - - return descriptor; - } - - // ---------------------------------------------------------------------------------- - private void setPedtse(RegularObsTimeSeriesDescriptor descriptor, String paramCode) - { - - int length = paramCode.length(); - - try - { - descriptor.setPe(paramCode.substring(0, 2)); - - String durCodeString = paramCode.substring(2, 3); - String durString = (String) _durCodetoDurMap.get(durCodeString); - short dur = 0; - - if (durString != null) - { - dur = Short.parseShort(durString); - } - - descriptor.setDur(dur); - - String typeSource = paramCode.substring(3, 5); - descriptor.setTs(typeSource); - - String extremum = paramCode.substring(5, 6); - - descriptor.setExtremum(extremum); - } - catch (Error e) - { - - } - - return; - } - // ---------------------------------------------------------------------------------- - - private void readValues(RegularObsTimeSeries timeSeries) - { - String header = "PDCFileReaderSlow.readValues(): "; - long time = _startTimeInSeconds * 1000; - long incrementTime = timeSeries.getTimeStepIntervalInMillis(); - - RegularObsTimeSeriesDescriptor desc = timeSeries.getDescriptor(); - - double value = 0.0; - - List pairList = new ArrayList(); - - debug_logline(header + "attempting to read " + _numberOfValues + " values."); - - String valueLine = _scanner.nextLine(); - Scanner valueScanner = new Scanner(valueLine); - boolean isMissing = false; - - - if (valueLine.indexOf("MISSING") > -1) - { - System.out.println(header + " time series " + desc.toString() + " is SET to MISSING!"); - desc.setMissing(true); - isMissing = true; - } - - - for (int i = 0; i < _numberOfValues; i++) - { - try - { - if (isMissing) - { - value = PDCFileWriter.MISSING; - } - else - { - value = valueScanner.nextDouble(); - } - - // debug_log("value[" + i +"] = " + value); - } - catch (InputMismatchException e1) - { - debug_log("when i = " + i); - debug_logline("read in a bad value from line = " + valueLine); - - throw (new InputMismatchException("bad read at entry # " + - i + " (starts at 0)" + - " value line = " + valueLine + - " TS Descriptor = " + desc )); - } - - TimeValuePair pair = new TimeValuePair(time, value); - pairList.add(pair); - - time += incrementTime; - } - - debug_logline(""); - - timeSeries.addTimeValuePairList(pairList); - - // int size = timeSeries.getTimeValuePairList(true).size(); - - // System.out.println(header + "timeSeries.getTimeValuePairList(true).size() = " + size ); - - - return; - } - - // ---------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - String fileName = "/fs/hseb/ob72/wfo_rfc/whfs/local/data/pdc_pp/keep/cachedWind.dat"; - - Map durCodeToDurMap = getDurCodeToDurMap(); - - PDCFileReaderSlow reader = new PDCFileReaderSlow (fileName, durCodeToDurMap); - reader.setDebug(true); - - reader.read(); - - - } - // ---------------------------------------------------------------------------------- - private static Map getDurCodeToDurMap() - { - // used just for testing. Real code uses database to access - //shefdur table. - Map durCodeToDurMap = new HashMap(); - - addCodeToMap(durCodeToDurMap, "I", 0); - addCodeToMap(durCodeToDurMap, "H", 1001); - addCodeToMap(durCodeToDurMap, "B", 1002); - addCodeToMap(durCodeToDurMap, "T", 1003); - addCodeToMap(durCodeToDurMap, "F", 1004); - addCodeToMap(durCodeToDurMap, "Q", 1006); - addCodeToMap(durCodeToDurMap, "D", 2001); - addCodeToMap(durCodeToDurMap, "Z", 5000); - - - return durCodeToDurMap; - } - - private static void addCodeToMap(Map durCodeToDurMap, String durCode, int duration) - { - durCodeToDurMap.put(durCode, duration + ""); - } - /** - * @param debug The debug to set. - */ - public void setDebug(boolean debug) - { - this._debug = debug; - } - /** - * @return Returns the debug. - */ - public boolean getDebug() - { - return _debug; - } - - // ---------------------------------------------------------------------------------- - private void debug_logline(String message) - { - debug_log(message + '\n'); - - return; - } - // ---------------------------------------------------------------------------------- - private void debug_log(String message) - { - if (getDebug()) - { - System.out.print(message); - } - - return; - } - // ---------------------------------------------------------------------------------- -} - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileWriter.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileWriter.java deleted file mode 100755 index 9b9888ce70..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCFileWriter.java +++ /dev/null @@ -1,688 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.DecimalFormat; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; - -public class PDCFileWriter -{ - public static final int MISSING = -9999; - private static final double MISSING_DOUBLE = MISSING; - - - private String _preprocessedFilePath = null; - private boolean _fileIsOpen = false; - private boolean _keepPreprocessedFileOpen = false; - private OutputStream _outputStream = null; - private PrintWriter _writer = null; - - private Map _locationHashMap = null; - private Map _shefDurMap = null; - // private Map _shefDurToDurcodeMap = null; - - - private boolean _DEBUG = false; - - CodeTimer _timeSeriesOutputStringTimer = null; - - private long _startTime = 0; - private long _endTime = 0; - - - //this will change during the processing - //it exists solely for monitor different parts of the processing - private int _timeSeriesValueCount = 0; - - - // ------------------------------------------------------------------------------ - - public PDCFileWriter(Map locationHashMap, - Map shefDurMap, - Map shefDurToDurcodeMap, - String preprocessedFilePath) - { - _locationHashMap = locationHashMap; - _shefDurMap = shefDurMap; - // _shefDurToDurcodeMap = shefDurToDurcodeMap; - _preprocessedFilePath = preprocessedFilePath; - - return; - } - // ---------------------------------------------------------------------------------- - - public void writeIrregularObsDataToFile( List obsTimeSeriesList, String fileName ) - { - - _timeSeriesOutputStringTimer = new CodeTimer(); - //_decimalFormatTimer = new CodeTimer(); - - if ( ( obsTimeSeriesList != null ) && (! obsTimeSeriesList.isEmpty() ) ) - { - StringBuffer outputStringBuffer = new StringBuffer(); - String finalPreProcessedFileName = _preprocessedFilePath + fileName + ".dat"; - String preProcessedWorkFileName = finalPreProcessedFileName + ".work"; - - - //open if needed - if (!isPreprocessedFileOpen()) - { - // System.out.println("writeIrregularObsDataToFile() : Opening " + fileName); - openPreProcessedFile( preProcessedWorkFileName ); - // _writer = new PrintWriter( _outputStream ); - } - - // write out the message, pre-pending date time stamp if required - if ( _DEBUG ) - { - System.out.println( "Writing out to file: " + _preprocessedFilePath + fileName + ".dat" ); - System.out.flush(); - } - - long curTime = System.currentTimeMillis(); - outputStringBuffer.append( "Created on: " + - DbTimeHelper.getDateTimeStringFromLongTime( curTime ) + "\n" ); - - outputStringBuffer.append( "####(file header)NUM_OF_VALUES START_TIME TIME_INTERVAL_BETWEEN_VALUES_IN_SECONDS\n" ); - outputStringBuffer.append( "####LID HSA PEDSTE ELEV LAT LON FCST_PNT(T/F) STATION_NAME\n" ); - outputStringBuffer.append( "####DCP_FLAG OBSERVER_FLAG TELEM_TYPE_STRINGS \n" ); - outputStringBuffer.append( "####VALUES\n" ); - if ( obsTimeSeriesList != null ) - { - IrregularObsTimeSeries firstObsTimeSeries = (IrregularObsTimeSeries) obsTimeSeriesList.get( 0 ); - int num_of_values = firstObsTimeSeries.getTimeValuePairList( true ).size(); - long start_time = firstObsTimeSeries.getDescriptor().getStartTime(); - long timeStepIntervalInMillis = firstObsTimeSeries.getTimeStepIntervalInMillis(); - long timeStepIntervalInSeconds = timeStepIntervalInMillis / 1000; - - long end_time = firstObsTimeSeries.getDescriptor().getEndTime(); - - // long end_time = start_time + ( (num_of_values - 1) * timeStepIntervalInMillis ); - - - /* - * long start_time = firstObsTimeSeries.getDescriptor().getStartTime(); - long end_time = firstObsTimeSeries.getDescriptor().getEndTime(); - * - */ - - outputStringBuffer.append("#### start time = " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " end time = " + - DbTimeHelper.getDateTimeStringFromLongTime(end_time) + '\n'); - - - - if ( _DEBUG ) - { - outputStringBuffer.append( num_of_values + " " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " " + timeStepIntervalInSeconds + "\n" ); - } - else - { - outputStringBuffer.append( num_of_values + " " + start_time/1000 + - " " + timeStepIntervalInSeconds + "\n" ); - } - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - IrregularObsTimeSeries obsTimeSeries = (IrregularObsTimeSeries) obsTimeSeriesList.get( i ); - if ( obsTimeSeries != null ) - { - outputStringBuffer.append( getOutputStringFromLocationAndIrregularObsTimeSeries( obsTimeSeries ) ); - } - } - } - else - { - outputStringBuffer.append("#### start time = UNKNOWN " + - " end time = UNKNOWN \n"); - - } - - _writer.println( outputStringBuffer ); - _writer.flush(); - - //close if supposed to do so - if (! _keepPreprocessedFileOpen ) - { - // System.out.println("writeIrregularObsDataToFile() closing the file"); - closePreprocessedFile(); - File workFile = new File( preProcessedWorkFileName ); - File finalFile = new File ( finalPreProcessedFileName ); - finalFile.delete(); - workFile.renameTo( new File( finalPreProcessedFileName ) ); - } - } - } - -// ------------------------------------------------------------------------ - - private String getOutputStringFromLocationAndIrregularObsTimeSeries( IrregularObsTimeSeries obsTimeSeries ) - { - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - String lid = descriptor.getLid(); - String shef_param_code = null; - Location location = (Location) _locationHashMap.get( lid ); - StringBuffer outputString = new StringBuffer(); - - shef_param_code = descriptor.getPe() + _shefDurMap.get( "" + descriptor.getDur() ) + - descriptor.getTs() + descriptor.getExtremum(); - descriptor.setShef_param_code( shef_param_code ); - outputString.append( location.getLid() + " " + location.getHsa() + " " + - descriptor.getShef_param_code() + " " + location.getElevation() + " " + - location.getLat() + " " + location.getLon() + " " + location.isFcstPoint() + " " + - location.getLocationName() + "\n" ); - - if ( location.isDCP() ) - { - outputString.append( "T " ); - } - else - { - outputString.append( "F " ); - } - - if ( location.isObserver() ) - { - outputString.append( "T " ); - } - else - { - outputString.append( "F " ); - } - - if ( ( location.getTelemType() == null ) || (location.getTelemType().length() == 0) ) - { - outputString.append( "NO_TELEM_TYPE" ); - } - else - { - outputString.append( location.getTelemType() ); - } - outputString.append( "\n" + getIrregularObsTimeSeriesOutputString( obsTimeSeries ) + "\n" ); - - - return outputString.toString(); - } - -// ------------------------------------------------------------------------ - private String getIrregularObsTimeSeriesOutputString( IrregularObsTimeSeries obsTimeSeries ) - { - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String missingDoubleString = getFormattedNumber(MISSING_DOUBLE, decimalFormat) + ""; - - StringBuffer outputStringBuffer = new StringBuffer(); - - String dateTimeString = null; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - - dateTimeString = DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime()); - // formattedNumber = getFormattedNumber(timeValuePair.getValue(), decimalFormat ); - outputStringBuffer.append( dateTimeString + "|" + - timeValuePair.getValue() + "\n"); - - - } - else - { - outputStringBuffer.append(timeValuePair.getValue() + " "); - } - } - else - { - if ( _DEBUG ) - { - outputStringBuffer.append(missingDoubleString + "\n"); - } - else - { - outputStringBuffer.append(missingDoubleString + " "); - } - - } - } - return outputStringBuffer.toString(); - } - - - // ------------------------------------------------------------------------ - public void writeRegularObsDataToFile( List obsTimeSeriesList, String fileName ) - { - _timeSeriesOutputStringTimer = new CodeTimer(); - // _decimalFormatTimer = new CodeTimer(); - - - if ( ( obsTimeSeriesList != null ) && (! obsTimeSeriesList.isEmpty() ) ) - { - - StringBuffer outputStringBuffer = new StringBuffer(); - String finalPreProcessedFileName = _preprocessedFilePath + fileName + ".dat"; - String preProcessedWorkFileName = finalPreProcessedFileName + ".work"; - - //open if needed - if (!isPreprocessedFileOpen()) - { - openPreProcessedFile( preProcessedWorkFileName ); - // _writer = new PrintWriter(_outputStream); - } - - if ( _DEBUG ) - { - System.out.println( "Writing out to file: " + _preprocessedFilePath + fileName + ".dat" ); - System.out.flush(); - } - - long curTime = System.currentTimeMillis(); - // write out the message, pre-pending date time stamp if required - if ( _DEBUG ) - { - - outputStringBuffer.append( "DEBUGGABLE OUTPUT FILE Created on: " + - DbTimeHelper.getDateTimeStringFromLongTime( curTime ) + "\n" ); - } - else - { - outputStringBuffer.append( "Created on: " + - DbTimeHelper.getDateTimeStringFromLongTime( curTime ) + "\n" ); - } - - outputStringBuffer.append( "####(file header)NUM_OF_VALUES START_TIME TIME_INTERVAL_BETWEEN_VALUES_IN_SECONDS\n" ); - outputStringBuffer.append( "####LID HSA PEDSTE ELEV LAT LON FCST_PNT(T/F) STATION_NAME\n" ); - outputStringBuffer.append( "####DCP_FLAG OBSERVER_FLAG TELEM_TYPE_STRINGS \n" ); - outputStringBuffer.append( "####VALUES\n" ); - if ( ( obsTimeSeriesList != null ) && (obsTimeSeriesList.size() > 0) ) - { - RegularObsTimeSeries firstObsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( 0 ); - int num_of_values = firstObsTimeSeries.getTimeValuePairList( true ).size(); - - _timeSeriesValueCount = num_of_values; - - long start_time = firstObsTimeSeries.getDescriptor().getStartTime(); - long timeStepIntervalInMillis = firstObsTimeSeries.getTimeStepIntervalInMillis(); - long timeStepIntervalInSeconds = timeStepIntervalInMillis / 1000; - long end_time = start_time + ( (num_of_values - 1) * timeStepIntervalInMillis ); - - _startTime = start_time; - _endTime = end_time; - - outputStringBuffer.append("#### start time = " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " end time = " + - DbTimeHelper.getDateTimeStringFromLongTime(end_time) + '\n'); - - if ( _DEBUG ) - { - outputStringBuffer.append( num_of_values + " " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " " + timeStepIntervalInSeconds + "\n" ); - } - else - { - outputStringBuffer.append( num_of_values + " " + start_time/1000 + - " " + timeStepIntervalInSeconds + "\n" ); - } - - - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( i ); - if ( obsTimeSeries != null ) - { - outputStringBuffer.append( - getRegularObsTimeSeriesOutputStringWhenMergedWithLocation( obsTimeSeries ) ); - - } - } - } - else - { - outputStringBuffer.append("#### start time = UNKNOWN" + - " end time = UNKNOWN \n"); - - return; - } - - - - //System.out.println(header + - // "creating the output string from each obsTimeSeries and its location entry took a total of " + - // outputStringTimer.getElapsedTime() + " millis."); - - // System.out.println(header + - // "creating the output string from each obsTimeSeries alone took a total of " + - // _timeSeriesOutputStringTimer.getElapsedTime() + " millis."); - - - - // fileTimer.start(); - _writer.println( outputStringBuffer ); - // fileTimer.stop(header + "writing the outputStringBuffer to the file took"); - _writer.flush(); - - // close if supposed to do so - if (!_keepPreprocessedFileOpen) - { - closePreprocessedFile(); - File workFile = new File(preProcessedWorkFileName); - File finalFile = new File(finalPreProcessedFileName); - finalFile.delete(); - workFile.renameTo(new File(finalPreProcessedFileName)); - } - } - } - -// ------------------------------------------------------------------------ - - private StringBuffer getRegularObsTimeSeriesOutputStringWhenMergedWithLocation( RegularObsTimeSeries obsTimeSeries ) - { - StringBuffer outputStringBuffer = new StringBuffer(); - - String header = "PDCFileWriter.getRegularObsTimeSeriesOutputStringWhenMergedWithLocation(): "; - - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - - if (descriptor == null) - { - System.out.println(header + " ***************** the time series descriptor is null"); - return outputStringBuffer; - } - - - String lid = descriptor.getLid(); - String shef_param_code = null; - Location location = (Location) _locationHashMap.get( lid ); - - if (location == null) - { - System.out.println(header + " ***************** the location object is null for lid = " + lid); - return outputStringBuffer; - } - - - //Make sure that a pe of PC ends up with a duration of 0, - //even though within the preprocessor, before writing, it has a different duration - //, matching the calculated accumulations it applies to. The "I" duration in this case - //indicates the source of the data, not the period for which accumulations were computed - if (descriptor.getPe().equals("PC")) - { - descriptor.setDur((short)0); - } - String durationString = (String) _shefDurMap.get( "" + descriptor.getDur() ); - - shef_param_code = descriptor.getPe() + durationString + - descriptor.getTs() + descriptor.getExtremum(); - descriptor.setShef_param_code( shef_param_code ); - - outputStringBuffer.append(location.getLid() + " " + location.getHsa() + " " + - descriptor.getShef_param_code() + " " + location.getElevation() + " " + - location.getLat() + " " + location.getLon() + " " + location.isFcstPoint() + " " + - location.getLocationName() + "\n" ); - - if ( location.isDCP() ) - { - outputStringBuffer.append( "T " ); - } - else - { - outputStringBuffer.append( "F " ); - } - - if ( location.isObserver() ) - { - outputStringBuffer.append( "T " ); - } - else - { - outputStringBuffer.append( "F " ); - } - - if ( ( location.getTelemType() == null ) || (location.getTelemType().length() == 0) ) - { - outputStringBuffer.append( "NO_TELEM_TYPE" ); - } - else - { - outputStringBuffer.append( location.getTelemType() ); - } - - - // _timeSeriesOutputStringTimer.restart(); - - outputStringBuffer.append( "\n" + getRegularObsTimeSeriesTimeValuePairListOutputString( obsTimeSeries ) + "\n" ); - // _timeSeriesOutputStringTimer.stop(); - - return outputStringBuffer; - } - -private String getRegularObsTimeSeriesTimeValuePairListOutputString( RegularObsTimeSeries obsTimeSeries ) - { - String header = "PDCFileWriter.getRegularObsTimeSeriesTimeValuePairListOutputString(): "; - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - //Map timeValuePairMap = ob - - - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String missingDoubleString = getFormattedNumber(MISSING_DOUBLE, decimalFormat) + ""; - - StringBuffer outputStringBuffer = new StringBuffer(); - - //double formattedNumber = 0.0; - String dateTimeString = null; - - if (timeValuePairList.size() > _timeSeriesValueCount) - { - // System.out.println(header + "\nFor " + obsTimeSeries.getDescriptor().toString() + - // " timeValuePairList.size() = " + timeValuePairList.size() + - // "> intended _timeSeriesValueCount = " + _timeSeriesValueCount); - } - else if (timeValuePairList.size() < _timeSeriesValueCount) - { - System.out.println(header + "\n *******For " + obsTimeSeries.getDescriptor().toString() + - " timeValuePairList.size() = " + timeValuePairList.size() + - " < intended _timeSeriesValueCount = " + _timeSeriesValueCount); - - } - else - { - //System.out.println(header + "\nFor " + obsTimeSeries.getDescriptor().toString() + - // " timeValuePairList.size() = intended _timeSeriesValueCount"); - } - - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - - if ( - (descriptor.getStartTime() > _startTime) || - (descriptor.getEndTime() < _endTime) - ) - { - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(descriptor.getStartTime()); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(descriptor.getEndTime()); - System.out.println(header + descriptor.toString() + " goes from " + - startTimeString + " to " + endTimeString ); - - - String origStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_startTime); - String origEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_endTime); - - System.out.println(header + " and should have gone from " + - origStartTimeString + " to " + origEndTimeString ); - - System.out.println(header + " merger string = " + obsTimeSeries.getMergerString() + '\n'); - - - } - - if (! descriptor.isMissing() ) //NOT MISSING - { - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - dateTimeString = DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime()); - // formattedNumber = getFormattedNumber(timeValuePair.getValue(), decimalFormat ); - outputStringBuffer.append( dateTimeString + "|" + - timeValuePair.getValue() + "\n"); - } - else - { - // formattedNumber = getFormattedNumber(timeValuePair.getValue(), decimalFormat ); - outputStringBuffer.append(timeValuePair.getValue() + " "); - } - } - else - { - if ( _DEBUG ) - { - outputStringBuffer.append(missingDoubleString + "\n"); - } - else - { - outputStringBuffer.append(missingDoubleString + " "); - } - - } - } - - } - else //the time series is missing - { - outputStringBuffer.append("MISSING"); - /* - for ( long indexTime = descriptor.getStartTime(); - indexTime < descriptor.getEndTime(); - indexTime += PDCPreprocessorDataMgr.MILLIS_PER_HOUR ) - { - outputStringBuffer.append(missingDoubleString + " "); - } - */ - - } - - - return outputStringBuffer.toString(); - } -// ------------------------------------------------------------------------- - public double getFormattedNumber(double value, DecimalFormat decimalFormat) - { - // _decimalFormatTimer.restart(); - - // value = roundToPlaces(value, 2); - - // String numberString = decimalFormat.format(value); - - // _decimalFormatTimer.stop(); - - return value; - } - - - // ------------------------------------------------------------------------- - - public String getFormattedNumber_old(double value, DecimalFormat decimalFormat) - { - //_decimalFormatTimer.restart(); - - return value + ""; - } -// ------------------------------------------------------------------------- - - public double getFormattedNumberWithRounding(double value, DecimalFormat decimalFormat) - { - // _decimalFormatTimer.restart(); - - value = MathHelper.roundToNDecimalPlaces(value, 2); - - // String numberString = decimalFormat.format(value); - - // _decimalFormatTimer.stop(); - - return value; - } - - -// ------------------------------------------------------------------------- - - private boolean isPreprocessedFileOpen() - { - return _fileIsOpen; - } - -// ------------------------------------------------------------------------ - - public void closePreprocessedFile() - { - if (isPreprocessedFileOpen() ) - { - _fileIsOpen = false; - _writer.close(); - } - } - -// ------------------------------------------------------------------------ - - public void closePreprocessedFile( PrintWriter writer ) - { - if (isPreprocessedFileOpen() ) - { - _fileIsOpen = false; - writer.close(); - } - } - -// ------------------------------------------------------------------------ - - private void openPreProcessedFile(String fileName) - { - try - { - if (fileName != null) - { - _outputStream = new BufferedOutputStream( new FileOutputStream(fileName, false) ); - - _fileIsOpen = true; - } - else //fileName == null - { - _outputStream = System.out; - } - - _writer = new PrintWriter( _outputStream ); - } - catch (java.io.IOException e) - { - System.out.println( e ); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - } - - // ------------------------------------------------------------------------ - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCPreprocessor.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCPreprocessor.java deleted file mode 100755 index 947a0f2933..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCPreprocessor.java +++ /dev/null @@ -1,1230 +0,0 @@ -/* - * Created on Jun 13, 2005 - * - * - * - */ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -/** - * @author Gautam Sood Chip Gobs - */ -public class PDCPreprocessor { - private static final String _versionString = "OB8.1"; - - private static final String _dateString = "March 27, 2007"; - - private static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - private static final Runtime _runtime = Runtime.getRuntime(); - - private PDCPreprocessorDataMgr _dataMgr = null; - - private boolean _debug = false; - - private String _preprocessedFilePath = null; // directory where the - // processed files are placed - // in - - private String _logDirName = null; // directory where the log will be placed - // in - - private Logger _logger = null; - - private Set _completeLidSet = null; - - private Set _completeRiverStationLidSet = null; - - private long _endTime = 0; - - private long _endTimeLastHour = 0; - - // private long _endTimeNextHour = 0; - - private List _heightTimeSeriesList = null; - - private List _stagePoolTimeSeriesList = new ArrayList(); - - private List _percentFloodFlowTimeSeriesList = new ArrayList(); - - private List _lakeTimeSeriesList = null; - - private List _dischargeTimeSeriesList = null; - - private List _heightDerivedDischargeTimeSeriesList = new ArrayList(); - - private List _flowStorageTimeSeriesList = new ArrayList(); - - private List _temperatureTimeSeriesList = null; - - private List _tempTimeSeriesList = new ArrayList(); - - private List _maxTempTimeSeriesList = new ArrayList(); - - private List _minTempTimeSeriesList = new ArrayList(); - - private List _dewPointTimeSeriesList = new ArrayList(); - - private List _deltaDewPointTimeSeriesList = new ArrayList(); - - private List _deltaTempTimeSeriesList = new ArrayList(); - - private List _windTimeSeriesList = null; - - private List _windSpeedTimeSeriesList = new ArrayList(); - - private List _windDirectionTimeSeriesList = new ArrayList(); - - private List _snowTimeSeriesList = null; - - private List _snowWaterTimeSeriesList = new ArrayList(); - - private List _depthAboveFloodStageTimeSeriesList = new ArrayList(); - - private List _deltaSnowWaterTimeSeriesList = new ArrayList(); - - private List _weatherTimeSeriesList = null; - - private List _relativeHumidityTimeSeriesList = new ArrayList(); - - private List _instantPrecipTimeSeriesList = new ArrayList(); - - private List _hourlyPrecipTimeSeriesList = new ArrayList(); - - private List _threeHourPrecipTimeSeriesList = new ArrayList(); - - private List _sixHourPrecipTimeSeriesList = new ArrayList(); - - private List _twentyFourHourPrecipTimeSeriesList = new ArrayList(); - - private int _heightHours = 0; - - private int _temperatureHours = 0; - - private int _snowHours = 0; - - private int _windHours = 0; - - private int _weatherHours = 0; - - private int _precipHours = 0; - - private int _lowerWindow = 0; - - private int _upperWindow = 0; - - public PDCPreprocessor() { - } - - /** - * initialize( String[] args ) - Used to process the command line arguments - * and set appropriate variables. - * - * @param args - * - Command line arguments - */ - private void initialize(String[] args) { - String header = "PDCPreprocessor.initialize(): "; - StringBuffer baseConnectionStringBuffer = new StringBuffer(); // gotten - // from - // the - // command - // line - String logFileName = null; - - getAppsDefaults(); - - for (int i = 0; i < args.length; i++) { - System.out.println("args[" + i + "] = " + args[i]); - } - - processCommandLineArguments(baseConnectionStringBuffer, args); - - logFileName = _logDirName + "/PDCPreprocessor.log"; - - _logger = new FileLogger(logFileName, true, true); - - _logger - .log("----------------------------------------------------------------------------------------- "); - _logger.log("version = " + _versionString + " date = " + _dateString); - - _logger.log("Starting PDC Preprocessor - " - + DbTimeHelper.getDateTimeStringFromLongTime(System - .currentTimeMillis())); - - _logger.log(header + "JDBC connection string = " - + baseConnectionStringBuffer.toString()); - - _dataMgr = new PDCPreprocessorDataMgr(baseConnectionStringBuffer - .toString(), _logger, _preprocessedFilePath, _lowerWindow, - _upperWindow, _debug); - - _endTime = System.currentTimeMillis(); - _endTimeLastHour = _endTime; - _endTimeLastHour /= MILLIS_PER_HOUR; - _endTimeLastHour *= MILLIS_PER_HOUR; - - // _endTimeNextHour = _endTimeLastHour + MILLIS_PER_HOUR; - - } - - // ----------------------------------------------------------------------------------------- - - private void disconnect() { - _dataMgr.disconnect(); - return; - } - - // ----------------------------------------------------------------------------------------- - - private long getNonPrecipEndTime() { - - return _endTimeLastHour; - } - - private long getNonPrecipDailyEndTime() { - String header = "PDCPreprocessor.getNonPrecipDailyEndTime(): "; - - long dailyEndTime = _endTimeLastHour; - dailyEndTime /= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - dailyEndTime *= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - - dailyEndTime += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; - - System.out.println(header + "dailyEndTime = " - + DbTimeHelper.getDateTimeStringFromLongTime(dailyEndTime)); - - return dailyEndTime; - - } - - // ----------------------------------------------------------------------------------------- - - private long getPrecipEndTime() { - - return _endTime; - } - - // ----------------------------------------------------------------------------------------- - - /** - * processObsData() - Processes the Observed data and calls appropriate - * methods from the Data Manager to write the data out to the .dat files. - */ - public void processObsData() { - String header = "PDCPreprocessor.processObsData(): "; - - CodeTimer precipTimer = new CodeTimer(); - - _dataMgr.createLidMap(); - _dataMgr.createShefDurMap(); - _completeLidSet = _dataMgr.getCompleteLidSet(); - - _completeRiverStationLidSet = _dataMgr.getRiverStationLidSet(); - - _dataMgr.handleCacheAging(); - - printFreeMemory("Before handleHeightData"); - handleHeightData(); - printFreeMemory("After handleHeightData"); - - handleFlowAndStorageData(); - printFreeMemory("After handleFlowAndStorageData"); - - handleTemperatureData(); - printFreeMemory("After handleTemperatureData"); - - handleWindData(); - printFreeMemory("After handleWindData"); - - handleSnowData(); - printFreeMemory("After handleSnowData"); - - handleWeatherData(); - printFreeMemory("After handleWeatherData"); - - // handle precip data - precipTimer.start(); - // processPrecipData(); - processPrecipDataWithCaching(_precipHours); - precipTimer.stop("Reading and processing the Precip Data took "); - - CodeTimer writePrecipDataFileTimer = new CodeTimer(); - writePrecipDataFileTimer.start(); - _dataMgr.writeIrregularObsDataToFile(_instantPrecipTimeSeriesList, - "PrecipInstant"); - - _dataMgr.writeRegularObsDataToFile(_hourlyPrecipTimeSeriesList, - "Precip1Hour"); - _dataMgr.writeRegularObsDataToFile(_threeHourPrecipTimeSeriesList, - "Precip3Hour"); - _dataMgr.writeRegularObsDataToFile(_sixHourPrecipTimeSeriesList, - "Precip6Hour"); - _dataMgr.writeRegularObsDataToFile(_twentyFourHourPrecipTimeSeriesList, - "Precip24Hour"); - - writePrecipDataFileTimer - .stop("Writing all of the precip data files took"); - } - - static public void printFreeMemory() { - printFreeMemory(null); - } - - static public void printFreeMemory(String message) { - long freeMemory = _runtime.freeMemory(); - long maxMemory = _runtime.maxMemory(); - if (message == null) { - message = ""; - } - - System.out.println(message + " Free memory = " + freeMemory - + " Max memory = " + maxMemory); - - } - - private void handleHeightData() { - String header = "PDCPreprocessor.handleHeightData(): "; - - CodeTimer heightDbTimer = new CodeTimer(); - CodeTimer heightCacheTimer = new CodeTimer(); - - heightCacheTimer.start(); - _heightTimeSeriesList = _dataMgr - .getNonPrecipObsTimeSeriesListUsingCache("Height", - getNonPrecipEndTime(), _heightHours); - heightCacheTimer.stop(header + "height cache usage took"); - - addMissingRiverTimeSeries(_heightTimeSeriesList, - getRegularObsTimeSeriesDescriptor("HG", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _heightHours, true), true); - - processHeightTimeSeriesList(); - - _heightTimeSeriesList = null; - System.gc(); - - _dataMgr.writeRegularObsDataToFile(_stagePoolTimeSeriesList, "Height"); - _dataMgr.writeRegularObsDataToFile(_depthAboveFloodStageTimeSeriesList, - "HeightAboveFloodStage"); - - _stagePoolTimeSeriesList = null; - _depthAboveFloodStageTimeSeriesList = null; - - System.gc(); - - } - - // -------------------------------------------------------------------------------------------- - private void handleFlowAndStorageData() { - _lakeTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( - "Lake", getNonPrecipEndTime(), _heightHours); - _dischargeTimeSeriesList = _dataMgr - .getNonPrecipObsTimeSeriesListUsingCache("Discharge", - getNonPrecipEndTime(), _heightHours); - // addMissingTimeSeries( _lakeTimeSeriesList, - // getRegularObsTimeSeriesDescriptor( "LS", "RZ", "Z", (short) 0, - // getNonPrecipEndTime(), _heightHours ), true ); - - // adds discharge data that was derived from height data, as needed (if - // there was no data for it) - incorporateConvertedHeightData(_heightDerivedDischargeTimeSeriesList, - _dischargeTimeSeriesList); - - addMissingTimeSeries(_dischargeTimeSeriesList, - getRegularObsTimeSeriesDescriptor("QR", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _heightHours, true), true); - // addMissingTimeSeries( _dischargeTimeSeriesList, - // getRegularObsTimeSeriesDescriptor( "QT", "RZ", "Z", (short) 0, - // getNonPrecipEndTime(), _heightHours, true ), true ); - - printFreeMemory("handleFlowAndStorageData() before processFlowStorageTimeSeriesList()"); - - processFlowStorageTimeSeriesList(); - - printFreeMemory("handleFlowAndStorageData() after processFlowStorageTimeSeriesList()"); - - _lakeTimeSeriesList = null; - _dischargeTimeSeriesList = null; - _heightDerivedDischargeTimeSeriesList = null; - System.gc(); - - printFreeMemory("handleFlowAndStorageData() before processFloodFlowPercentageTimeSeriesList()"); - - processFloodFlowPercentageTimeSeriesList(); - printFreeMemory("handleFlowAndStorageData() after processFloodFlowPercentageTimeSeriesList()"); - - printFreeMemory("handleFlowAndStorageData() before writeRegularObsDataToFile() #1"); - _dataMgr.writeRegularObsDataToFile(_flowStorageTimeSeriesList, - "FlowStorage"); - printFreeMemory("handleFlowAndStorageData() after writeRegularObsDataToFile() #1"); - - printFreeMemory("handleFlowAndStorageData() before writeRegularObsDataToFile() #2"); - _dataMgr.writeRegularObsDataToFile(_percentFloodFlowTimeSeriesList, - "PercentFloodFlow"); - printFreeMemory("handleFlowAndStorageData() after writeRegularObsDataToFile() #2"); - - } - - // -------------------------------------------------------------------------------------------- - - private void incorporateConvertedHeightData( - List derivedDischargeTimeSeriesList, List dischargeTimeSeriesList) { - - // if there are any derived time series that - // are not present in the regular discharge time series, then add them - - List timeSeriesToAddList = new ArrayList(); - - int lastFoundIndex = 0; - - for (int i = 0; i < derivedDischargeTimeSeriesList.size(); i++) { - RegularObsTimeSeries derivedDischargeTimeSeries = (RegularObsTimeSeries) derivedDischargeTimeSeriesList - .get(i); - - RegularObsTimeSeriesDescriptor derivedDescriptor = derivedDischargeTimeSeries - .getDescriptor(); - - String derivedLid = derivedDescriptor.getLid(); - - boolean foundMatch = false; - for (int j = lastFoundIndex; !foundMatch - && j < dischargeTimeSeriesList.size(); j++) { - RegularObsTimeSeries dischargeTimeSeries = (RegularObsTimeSeries) dischargeTimeSeriesList - .get(j); - - RegularObsTimeSeriesDescriptor descriptor = dischargeTimeSeries - .getDescriptor(); - - if (derivedLid.equalsIgnoreCase(descriptor.getLid())) { - foundMatch = true; - lastFoundIndex = j; - } - - } - - if (!foundMatch) // it wasn't in the list, so add it to the list to - // add later - // we don't want to screw up the iteration through the - // dischargeTimeSeriesList - { - timeSeriesToAddList.add(derivedDischargeTimeSeries); - } - - } - - // add all of the needed converted time series - for (int i = 0; i < timeSeriesToAddList.size(); i++) { - RegularObsTimeSeries timeSeries = (RegularObsTimeSeries) timeSeriesToAddList - .get(i); - - addTimeSeriesToOrderedList(dischargeTimeSeriesList, timeSeries); - } - - } - - // -------------------------------------------------------------------------------------------- - - private void handleTemperatureData() { - - // Note: Temperature data does NOT use caching. - // It was found to be too complicated. - // Your mileage may vary. - String header = "PDCPreprocessor.handleTemperatureData(): "; - CodeTimer timer = new CodeTimer(); - - CodeTimer dbTimer = new CodeTimer(); - CodeTimer addMissingTimer = new CodeTimer(); - CodeTimer processTimer = new CodeTimer(); - CodeTimer fileWriterTimer = new CodeTimer(); - timer.start(); - - dbTimer.start(); - _temperatureTimeSeriesList = _dataMgr - .getNonPrecipObsTimeSeriesListFromDb("Temperature", - getNonPrecipEndTime(), _temperatureHours); - dbTimer.stop(header + " reading from the db took "); - - addMissingTimer.start(); - - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TA", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _temperatureHours, true), true); - - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TA", "RZ", "X", (short) 0, - getNonPrecipDailyEndTime(), _temperatureHours, false), - false); - - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TA", "RZ", "N", (short) 0, - getNonPrecipDailyEndTime(), _temperatureHours, false), - false); - - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TD", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _temperatureHours, true), true); - - addMissingTimer.stop(header + "4 addMissingTimeSeries() calls took "); - - processTimer.start(); - - printFreeMemory(header + "before processTemperatureTimeSeriesList"); - - processTemperatureTimeSeriesList(); - processTimer.stop(header + " processing Temperature data took "); - printFreeMemory(header + "after processTemperatureTimeSeriesList"); - - _temperatureTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _temperatureTimeSeriesList = null"); - - fileWriterTimer.start(); - _dataMgr.writeRegularObsDataToFile(_tempTimeSeriesList, "Temperature"); - _tempTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _tempTimeSeriesList = null"); - - _dataMgr.writeRegularObsDataToFile(_minTempTimeSeriesList, - "TemperatureMin"); - _minTempTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _minTempTimeSeriesList = null"); - - _dataMgr.writeRegularObsDataToFile(_maxTempTimeSeriesList, - "TemperatureMax"); - _maxTempTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _maxTempTimeSeriesList = null"); - - _dataMgr.writeRegularObsDataToFile(_dewPointTimeSeriesList, "DewPoint"); - _dataMgr.writeRegularObsDataToFile(_deltaTempTimeSeriesList, - "TemperatureDelta"); - _dataMgr.writeRegularObsDataToFile(_deltaDewPointTimeSeriesList, - "DewPointDelta"); - fileWriterTimer.stop(header + " all the 6 file writes took "); - - _tempTimeSeriesList = null; - _minTempTimeSeriesList = null; - _maxTempTimeSeriesList = null; - _dewPointTimeSeriesList = null; - _deltaTempTimeSeriesList = null; - _deltaDewPointTimeSeriesList = null; - - System.gc(); - - timer.stop(header + " took "); - } - - // -------------------------------------------------------------------------------------------- - private void handleWindData() { - - String header = "PDCPreprocessor.handleWindData(): "; - - CodeTimer windTimer = new CodeTimer(); - windTimer.start(); - _windTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( - "Wind", getNonPrecipEndTime(), _windHours); - - windTimer.stop(header + "wind cache usage took "); - addMissingTimeSeries(_windTimeSeriesList, - getRegularObsTimeSeriesDescriptor("UD", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _windHours, true), true); - addMissingTimeSeries(_windTimeSeriesList, - getRegularObsTimeSeriesDescriptor("US", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _windHours, true), true); - - processWindTimeSeriesList(); - _windTimeSeriesList = null; - System.gc(); - - _dataMgr.writeRegularObsDataToFile(_windSpeedTimeSeriesList, - "WindSpeed"); - _dataMgr.writeRegularObsDataToFile(_windDirectionTimeSeriesList, - "WindDirection"); - - _windSpeedTimeSeriesList = null; - _windDirectionTimeSeriesList = null; - - System.gc(); - } - - // ---------------------------------------------------------------------------------------------- - - private void handleSnowData() { - String header = "PDCPreprocessor.handleSnowData(): "; - - CodeTimer snowTimer = new CodeTimer(); - snowTimer.start(); - _snowTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( - "Snow", getNonPrecipEndTime(), _snowHours); - snowTimer.stop(header + "snow cache usage took "); - - addMissingTimeSeries(_snowTimeSeriesList, - getRegularObsTimeSeriesDescriptor("SW", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _snowHours, true), true); - processSnowTimeSeriesList(); - _snowTimeSeriesList = null; - System.gc(); - - _dataMgr.writeRegularObsDataToFile(_snowWaterTimeSeriesList, - "SnowWaterEquivalent"); - _dataMgr.writeRegularObsDataToFile(_deltaSnowWaterTimeSeriesList, - "SnowWaterEquivalentDelta"); - - } - - private void handleWeatherData() { - _weatherTimeSeriesList = _dataMgr - .getNonPrecipObsTimeSeriesListUsingCache("Weather", - getNonPrecipEndTime(), _weatherHours); - - addMissingTimeSeries(_weatherTimeSeriesList, - getRegularObsTimeSeriesDescriptor("XR", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _weatherHours, true), true); - processWeatherTimeSeriesList(); - _weatherTimeSeriesList = null; - System.gc(); - - _dataMgr.writeRegularObsDataToFile(_relativeHumidityTimeSeriesList, - "RelativeHumidity"); - _relativeHumidityTimeSeriesList = null; - System.gc(); - - } - - // -------------------------------------------------------------------------------------------- - private void addAllMissingTimeSeries() { - addMissingTimeSeries(_heightTimeSeriesList, - getRegularObsTimeSeriesDescriptor("HG", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _heightHours, - true), true); - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TA", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), - _temperatureHours, true), true); - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TA", "RZ", "X", Short - .parseShort("0"), getNonPrecipEndTime(), - _temperatureHours, false), false); - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TA", "RZ", "N", Short - .parseShort("0"), getNonPrecipEndTime(), - _temperatureHours, false), false); - addMissingTimeSeries(_temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor("TD", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), - _temperatureHours, true), true); - addMissingTimeSeries(_windTimeSeriesList, - getRegularObsTimeSeriesDescriptor("UD", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _windHours, - true), true); - addMissingTimeSeries(_windTimeSeriesList, - getRegularObsTimeSeriesDescriptor("US", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _windHours, - true), true); - addMissingTimeSeries(_snowTimeSeriesList, - getRegularObsTimeSeriesDescriptor("SW", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _snowHours, - true), true); - addMissingTimeSeries(_weatherTimeSeriesList, - getRegularObsTimeSeriesDescriptor("XR", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _weatherHours, - true), true); - addMissingTimeSeries(_lakeTimeSeriesList, - getRegularObsTimeSeriesDescriptor("LS", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _heightHours, - true), true); - addMissingTimeSeries(_dischargeTimeSeriesList, - getRegularObsTimeSeriesDescriptor("QR", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _heightHours, - true), true); - addMissingTimeSeries(_dischargeTimeSeriesList, - getRegularObsTimeSeriesDescriptor("QT", "RZ", "Z", Short - .parseShort("0"), getNonPrecipEndTime(), _heightHours, - true), true); - } - - // -------------------------------------------------------------------------------------------- - - private void addMissingTimeSeries(List obsTimeSeriesList, - RegularObsTimeSeriesDescriptor descriptor, boolean isHourly, - Set lidSet) { - String header = "PDCPreprocessor.addMissingTimeSeries(): "; - CodeTimer methodTimer = new CodeTimer(); - methodTimer.start(); - - CodeTimer getLidSetTimer = new CodeTimer(); - CodeTimer createMissingTimer = new CodeTimer(); - CodeTimer addToOrderListTimer = new CodeTimer(); - - Set partialLidSet = null; - Set missingLidSet = new HashSet(lidSet); - List missingLidList = null; - String lid = null; - - descriptor.setMissing(true); - - if ((descriptor.isMissing() == true) - && (descriptor.getExtremum().equals("X"))) { - System.out.println(header + "descriptor = " + descriptor); - } - - getLidSetTimer.start(); - partialLidSet = getLidSetFromObsTimeSeriesList(obsTimeSeriesList, - descriptor.getPe(), descriptor.getExtremum()); - - getLidSetTimer.stop(header + " getLidSetFromObsTimeSeriesList() took"); - - missingLidSet.removeAll(partialLidSet); - - missingLidList = new ArrayList(missingLidSet); - - for (int i = 0; i < missingLidList.size(); i++) { - lid = (String) missingLidList.get(i); - createMissingTimer.restart(); - RegularObsTimeSeries obsTimeSeries = createMissingTimeSeries(lid, - new RegularObsTimeSeriesDescriptor(descriptor), isHourly); - createMissingTimer.stop(); - - addToOrderListTimer.restart(); - addTimeSeriesToOrderedList(obsTimeSeriesList, obsTimeSeries); - addToOrderListTimer.stop(); - } - - System.out.println(header - + "total elapsed time for createMissingTimeSeries calls = " - + createMissingTimer.getElapsedTime() + " millis."); - - System.out.println(header - + "total elapsed time for addToOrderListTimer calls = " - + addToOrderListTimer.getElapsedTime() + " millis."); - - methodTimer.stop(header + "took"); - } - - private void addMissingTimeSeries(List obsTimeSeriesList, - RegularObsTimeSeriesDescriptor descriptor, boolean isHourly) { - addMissingTimeSeries(obsTimeSeriesList, descriptor, isHourly, - _completeLidSet); - - return; - } - - private void addMissingRiverTimeSeries(List obsTimeSeriesList, - RegularObsTimeSeriesDescriptor descriptor, boolean isHourly) { - addMissingTimeSeries(obsTimeSeriesList, descriptor, isHourly, - _completeRiverStationLidSet); - - return; - } - - // -------------------------------------------------------------------------------------------- - private RegularObsTimeSeries createMissingTimeSeries(String lid, - RegularObsTimeSeriesDescriptor descriptor, boolean isHourly) { - RegularObsTimeSeries obsTimeSeries = null; - - descriptor.setLid(lid); - - descriptor.setMissing(true); - - if (isHourly) { - obsTimeSeries = new RegularObsTimeSeries(descriptor, 1, - new HourlyTimeSlotPolicy()); - } else { - obsTimeSeries = new RegularObsTimeSeries(descriptor, 24, - new DailyTimeSlotPolicy()); - } - - /* - * - * for ( long indexTime = descriptor.getStartTime(); indexTime < - * descriptor.getEndTime(); indexTime += - * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ) { TimeValuePair - * timeValuePair = new TimeValuePair( indexTime, - * PDCPreprocessorDataMgr.MISSING ); - * obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); } - */ - - return obsTimeSeries; - } - - // -------------------------------------------------------------------------------------------- - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor( - String pe, String ts, String extremum, short duration, - long endTime, int hoursToProcess, boolean adjustByOneHour) { - - int hoursBack = hoursToProcess; - - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - - descriptor.setPe(pe); - descriptor.setTs(ts); - descriptor.setExtremum(extremum); - descriptor.setDur(duration); - descriptor.setEndTime(TimeHelper - .roundTimeInMillisToNearestHour(endTime)); - - if (adjustByOneHour) // for normal descriptors, not for TA X or TA N - { - hoursBack -= 1; - } - - descriptor.setStartTime(descriptor.getEndTime() - - ((hoursBack) * PDCPreprocessorDataMgr.MILLIS_PER_HOUR)); - - return descriptor; - } - - // -------------------------------------------------------------------------------------------- - public void addTimeSeriesToOrderedList(List obsTimeSeriesList, - RegularObsTimeSeries newTimeSeries) { - String header = "PDCPreprocessor.addTimeSeriesToOrderedList(): "; - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - Comparator comparator = new RegularObsTimeSeriesComparator(); - - index = Collections.binarySearch(obsTimeSeriesList, newTimeSeries, - comparator); // -4 - - // Add the non-existent item to the list - if (index < 0) { - obsTimeSeriesList.add(-index - 1, newTimeSeries); - } - - else if (index == 0) { - obsTimeSeriesList.add(index, newTimeSeries); - System.out.println(header + "Item added at 0 index in the list"); - } - - else { - System.out.println(header + "Item aleady in the list"); - } - } - - // -------------------------------------------------------------------------------------------- - public void addTimeSeriesToOrderedList_orig(List obsTimeSeriesList, - RegularObsTimeSeries newTimeSeries) { - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - for (int i = 0; i < obsTimeSeriesList.size(); i++) { - obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get(i); - - if (newLid.compareToIgnoreCase(obsTimeSeries.getDescriptor() - .getLid()) < 0) { - index = i; - found = true; - break; - } - } - - if (found) // descriptor inserted at index - { - obsTimeSeriesList.add(index, newTimeSeries); - } else // descriptorlist is either empty or descriptor belongs at the - // end of the list - { - index = 0; - obsTimeSeriesList.add(newTimeSeries); - } - } - - /** - * - * @param obsTimeSeriesList - * - list of ObsTimeSeries objects - * @return Set of lids in the obsTimeSeriesList - */ - private Set getLidSetFromObsTimeSeriesList(List obsTimeSeriesList, - String pe, String extremum) { - Set lidSet = new HashSet(); - - for (int i = 0; i < obsTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList - .get(i); - if ((obsTimeSeries.getDescriptor().getPe().equalsIgnoreCase(pe)) - && (obsTimeSeries.getDescriptor().getExtremum() - .equalsIgnoreCase(extremum))) { - lidSet.add(obsTimeSeries.getDescriptor().getLid()); - } - } - return lidSet; - } - - /** - * Takes the temperature Timeseries List and extracts 24 hour min/max, Air - * temperature, and Dewpoint timeseries - * - */ - private void processTemperatureTimeSeriesList() { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if (_temperatureTimeSeriesList != null) { - for (int i = 0; i < _temperatureTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _temperatureTimeSeriesList - .get(i); - - descriptor = obsTimeSeries.getDescriptor(); - long startTime = descriptor.getStartTime(); - - pe = descriptor.getPe(); - if ((pe.equalsIgnoreCase("TA")) - && (descriptor.getExtremum().equalsIgnoreCase("X"))) { - // descriptor.setStartTime( startTime + 24 * - // PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - obsTimeSeries.setObsTimeSeriesDescriptor(descriptor); - _maxTempTimeSeriesList.add(obsTimeSeries); - } else if ((pe.equalsIgnoreCase("TA")) - && (descriptor.getExtremum().equalsIgnoreCase("N"))) { - // descriptor.setStartTime( startTime + 24 * - // PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - obsTimeSeries.setObsTimeSeriesDescriptor(descriptor); - - _minTempTimeSeriesList.add(obsTimeSeries); - } else if ((pe.equalsIgnoreCase("TA")) - && (descriptor.getExtremum().equalsIgnoreCase("Z"))) { - _tempTimeSeriesList.add(obsTimeSeries); - _deltaTempTimeSeriesList.add(_dataMgr - .getDeltaTimeSeries(obsTimeSeries)); - - } else if (pe.equalsIgnoreCase("TD")) { - _deltaDewPointTimeSeriesList.add(_dataMgr - .getDeltaTimeSeries(obsTimeSeries)); - - // descriptor.setStartTime( startTime + 24 * - // PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - _dewPointTimeSeriesList.add(obsTimeSeries); - - } - } - } - } - - /** - * takes the Snow Timeseries list and extracts all Timeseries with a PE of - * "SW" - * - */ - private void processSnowTimeSeriesList() { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if (_snowTimeSeriesList != null) { - for (int i = 0; i < _snowTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _snowTimeSeriesList - .get(i); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if (pe.equalsIgnoreCase("SW")) // Snow Water equivalent - { - _snowWaterTimeSeriesList.add(obsTimeSeries); - _deltaSnowWaterTimeSeriesList.add(_dataMgr - .getDeltaTimeSeries(obsTimeSeries)); - } - } - } - } - - /** - * processFlowStorageTimeSeriesList() - Processes the - * dischargeTimeSeriesList and retrieves the valid flowStorage timeseries - * - */ - private void processFlowStorageTimeSeriesList() { - String pe = null; - - RegularObsTimeSeriesDescriptor descriptor = null; - - if (_dischargeTimeSeriesList != null) { - for (int i = 0; i < _dischargeTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _dischargeTimeSeriesList - .get(i); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if ((pe.equalsIgnoreCase("QR")) || (pe.equalsIgnoreCase("QT"))) { - addTimeSeriesToOrderedList(_flowStorageTimeSeriesList, - obsTimeSeries); - // _flowStorageTimeSeriesList.add ( obsTimeSeries ); - } - } - } - - if (_lakeTimeSeriesList != null) { - for (int i = 0; i < _lakeTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _lakeTimeSeriesList - .get(i); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if (pe.equalsIgnoreCase("LS")) { - addTimeSeriesToOrderedList(_flowStorageTimeSeriesList, - obsTimeSeries); - // _flowStorageTimeSeriesList.add ( obsTimeSeries ); - } - } - } - } - - /** - * takes the Weather Timeseries list and extracts all Timeseries with a PE - * of "XR" (Relative Humidity) - * - */ - private void processWeatherTimeSeriesList() { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if (_weatherTimeSeriesList != null) { - for (int i = 0; i < _weatherTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _weatherTimeSeriesList - .get(i); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if (pe.equalsIgnoreCase("XR")) // Relative Humidity - { - _relativeHumidityTimeSeriesList.add(obsTimeSeries); - } - } - } - } - - /** - * Takes the Wind Timeseries and extracts the Wind Speed and Wind Direction - * Time Series - * - */ - private void processWindTimeSeriesList() { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if (_windTimeSeriesList != null) { - for (int i = 0; i < _windTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _windTimeSeriesList - .get(i); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if (pe.equalsIgnoreCase("US")) // Wind speed - { - _windSpeedTimeSeriesList.add(obsTimeSeries); - } else if (pe.equalsIgnoreCase("UD")) // Wind direction - { - _windDirectionTimeSeriesList.add(obsTimeSeries); - } - } - } - - } - - /** - * Takes all of the Height Timeseries and divides it into the stage/pool and - * depth_above_flood_stage timeserieslist. Also creates a flowstorage - * timeseries list - * - */ - private void processHeightTimeSeriesList() { - String header = "PDCPreprocessor.processHeightTimeSeriesList(): "; - - String pe = null; - RegularObsTimeSeries derivedDischargeTimeSeries = null; - - if (_heightTimeSeriesList != null) { - for (int i = 0; i < _heightTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _heightTimeSeriesList - .get(i); - pe = obsTimeSeries.getDescriptor().getPe(); - - if (pe.equalsIgnoreCase("HG") || pe.equalsIgnoreCase("HP") - || pe.equalsIgnoreCase("HT")) { - _stagePoolTimeSeriesList.add(obsTimeSeries); - _depthAboveFloodStageTimeSeriesList.add(_dataMgr - .getDepthAboveFSTimeSeries(obsTimeSeries)); - derivedDischargeTimeSeries = _dataMgr - .getDischargeTimeSeriesFromHeightTimeSeries(obsTimeSeries); - if (derivedDischargeTimeSeries != null) { - _heightDerivedDischargeTimeSeriesList - .add(derivedDischargeTimeSeries); - } - } - } - } - } - - /** - * Takes the floodStorageTimeSeriesList and creates the - * percentFloodFlowTimeSeriesList - * - */ - private void processFloodFlowPercentageTimeSeriesList() { - String pe = null; - - if (_flowStorageTimeSeriesList != null) { - for (int i = 0; i < _flowStorageTimeSeriesList.size(); i++) { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _flowStorageTimeSeriesList - .get(i); - if (obsTimeSeries != null) { - // pe = obsTimeSeries.getDescriptor().getPe(); - - RegularObsTimeSeries percentFloodFlowTimeSeries = _dataMgr - .getPercentFloodFlowTimeSeriesListFromFlowStorageTimeSeries(obsTimeSeries); - if (percentFloodFlowTimeSeries != null) { - _percentFloodFlowTimeSeriesList - .add(percentFloodFlowTimeSeries); - } - - } - } - } - } - - /** - * Runs the PDC Precip Preprocessor (C code) and then takes the generated C - * code and creates the instant/six hour/24 hour precip timeseries lists. - * - */ - private void processPrecipData() { - if (_precipHours > 0) { - _dataMgr.executePDCPrecipPP(getPrecipEndTime(), _precipHours); - _instantPrecipTimeSeriesList = _dataMgr - .getInstantaneousPrecipTimeSeriesList(getPrecipEndTime()); - - _hourlyPrecipTimeSeriesList = _dataMgr - .get1HourPrecipTimeSeriesListFromCFile(); - _threeHourPrecipTimeSeriesList = _dataMgr - .get3HourPrecipTimeSeriesListFromCFile(); - _sixHourPrecipTimeSeriesList = _dataMgr - .get6HourPrecipTimeSeriesListFromCFile(); - _twentyFourHourPrecipTimeSeriesList = _dataMgr - .get24HourPrecipTimeSeriesListFromCFile(); - } - } - - private void processPrecipDataWithCaching(int numHoursToPreprocess) { - PrecipListHolder holder = _dataMgr.processPrecipDataWithCaching( - getPrecipEndTime(), numHoursToPreprocess); - - _instantPrecipTimeSeriesList = holder.getInstantPrecipTimeSeriesList(); - _hourlyPrecipTimeSeriesList = holder.getOneHourPrecipTimeSeriesList(); - _threeHourPrecipTimeSeriesList = holder - .getThreeHourPrecipTimeSeriesList(); - _sixHourPrecipTimeSeriesList = holder.getSixHourPrecipTimeSeriesList(); - _twentyFourHourPrecipTimeSeriesList = holder - .getTwentyFourHourPrecipTimeSeriesList(); - } - - /** - * - * @param baseConnectionStringBuffer - * - Postgres database connection string - * @param logDirName - * - Directory where the log file will be created - * @param args - * - Command line arguments - */ - private void processCommandLineArguments( - StringBuffer baseConnectionStringBuffer, String[] args) { - if (args.length < 1) { - System.err - .println("Usage: ohd.hseb.PDCPreprocessor.PDCPreprocessor connection_string logFileDir "); - System.exit(0); - } - - baseConnectionStringBuffer.append(args[0]); - - if (args.length >= 2) { - if (args[1].equalsIgnoreCase("true")) { - _debug = true; - } - } - } - - /** - * Get's token values from .Apps_defaults - * - */ - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - // String OS = System.getProperty("os.name").toLowerCase(); - - _temperatureHours = ad.getInt("pdc_temperature_hours", 168) + 24; - _heightHours = ad.getInt("pdc_height_hours", 168); - _snowHours = ad.getInt("pdc_snow_hours", 168) + 24; - _windHours = ad.getInt("pdc_wind_hours", 168); - _weatherHours = ad.getInt("pdc_weather_hours", 168); - _precipHours = ad.getInt("pdc_precip_hours", 168); - _lowerWindow = ad.getInt("pdc_lower_window", 2); - _upperWindow = ad.getInt("pdc_upper_window", 2); - - // if ( (OS.indexOf("nt") > -1) - // || (OS.indexOf("windows 2000") > -1) - // || (OS.indexOf("windows xp") > -1) ) - // { - // _preprocessedFilePath = "D:\\data\\PDCPreprocessor\\data\\"; - // _logDirName = "D:\\data\\PDCPreprocessor\\log\\"; - // } - // else // assume it's unix - // { - _preprocessedFilePath = ad.getToken("pdc_pp_dir") + "/"; - _logDirName = ad.getToken("pdc_pp_log_dir") + "/"; - - // } - } - - public void testPDCFiles() { - _dataMgr.testPDCFiles(); - - } - - public static void main(String[] args) { - - CodeTimer programTimer = new CodeTimer(); - programTimer.start(); - - PDCPreprocessor pdcPreprocessor = new PDCPreprocessor(); - boolean debug = false; - - pdcPreprocessor.initialize(args); - - pdcPreprocessor.processObsData(); - - pdcPreprocessor.disconnect(); - - programTimer.stop("Finished PDCProcessor in"); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCPreprocessorDataMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCPreprocessorDataMgr.java deleted file mode 100755 index 6554babc78..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PDCPreprocessorDataMgr.java +++ /dev/null @@ -1,1683 +0,0 @@ -/* - * Created on September 10, 2005 - */ -package ohd.hseb.pdc_pp; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.LocPDCRecord; -import ohd.hseb.ihfsdb.generated.LocPDCView; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.ShefDurRecord; -import ohd.hseb.ihfsdb.generated.ShefDurTable; -import ohd.hseb.ihfsdb.generated.StnClassRecord; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.EnvHelper; -import ohd.hseb.util.IntegerHolder; -import ohd.hseb.util.Logger; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.StringParser; -import ohd.hseb.util.TimeHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PDCPreprocessorDataMgr { - public static final int MISSING = -9999; - - // private static final double MISSING_DOUBLE = MISSING; - private static String OS = System.getProperty("os.name").toLowerCase(); - - public static final long MILLIS_PER_HALF_HOUR = 30 * 60 * 1000; - - public static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; - - public static final long MILLIS_PER_12_HOURS = MILLIS_PER_HOUR * 12; - - public static final long MILLIS_PER_MINUTE = 60 * 1000; - - public static long _minutesBeforeTopOfHour; - - public static long _minutesAfterTopOfHour; - - public static boolean _DEBUG = false; - - // Variables used for the preprocessed file - private String _preprocessedFilePath = null; - - // private long _endTime = System.currentTimeMillis(); - - private Database _db = null; - - private Logger _logger = null; - - private Map _locationHashMap = null; - - private Map _shefDurMap = null; - - private Map _shefDurToDurcodeMap = null; - - private int _nonPrecipHoursToReadWhenCaching = 24; - - private int _precipHoursToReadWhenCaching = 48; // currently, must be a - - // multiple of 24 hours - - private long _cacheRefreshAgeMaxInMillis = 60 * 60 * 1000; - - // private String _dataDir = null; - private String _refreshIndicatorBaseFileName = "CacheRefreshIndicator.dat"; - - // ------------------------------------------------------------------------ - - public PDCPreprocessorDataMgr(String baseConnectionString, Logger logger, - String preprocessedFilePath, long minutesBeforeTopOfHour, - long minutesAfterTopOfHour, boolean debug) { - super(); - - _db = new Database(); - _logger = logger; - _DEBUG = debug; - _preprocessedFilePath = preprocessedFilePath; - _minutesBeforeTopOfHour = minutesBeforeTopOfHour; - _minutesAfterTopOfHour = minutesAfterTopOfHour; - - getAppsDefaults(); - - if (baseConnectionString == null) { - baseConnectionString = getBaseConnectionString(); - } - _db.connectWithDriverSearch(baseConnectionString); - } - - // ------------------------------------------------------------------------------------ - - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - - _preprocessedFilePath = ad.getToken("pdc_pp_dir") + "/"; - - int cacheRefreshAgeInMinutes = ad.getInt("pdc_clean_cache_minutes", 59); - _cacheRefreshAgeMaxInMillis = cacheRefreshAgeInMinutes - * MILLIS_PER_MINUTE; - - System.out.println("_cacheRefreshAgeMax = " - + _cacheRefreshAgeMaxInMillis); - - return; - } - - // ------------------------------------------------------------------------ - - public String getDatabaseName() { - String dbName = _db.getDatabaseName(); - return dbName; - } - - // ------------------------------------------------------------------------ - - private String getBaseConnectionString() { - // this is used in testing mode, not the production mode - String connectionURLPart = "jdbc:postgresql://dx1-nhdr:5432/hd_ob6ounx?user=oper"; - return connectionURLPart; - } - - // ------------------------------------------------------------------------ - - /** - * createLidMap() - Creates a Hashmap of Location objects. Used for the - * RegularObsTimeSeriesDescriptor objects - */ - public void createLidMap() { - DecimalFormat decimalFormat = new DecimalFormat("0.00"); - - CodeTimer lidHashMapTimer = new CodeTimer(); - CodeTimer locPDCViewTimer = new CodeTimer(); - CodeTimer riverStatTableTimer = new CodeTimer(); - CodeTimer putHashMapTimer = new CodeTimer(); - CodeTimer parseTimer = new CodeTimer(); - CodeTimer ratingCurveTimer = new CodeTimer(); - - Location location = null; - String whereClause = ""; - - LocPDCView locPDCView = new LocPDCView(_db); - RiverstatTable riverStatTable = new RiverstatTable(_db); - StnClassTable stationClassTable = new StnClassTable(_db); - - List locPDCViewList = null; - List riverStatRecordList = null; - List stationClassList = null; - - if (_DEBUG) { - lidHashMapTimer.start(); - } - - try { - if (_DEBUG) { - locPDCViewTimer.start(); - } - locPDCViewList = locPDCView.select(whereClause); - if (_DEBUG) { - locPDCViewTimer.stop("Finished LocPDCView query in "); - } - - if (_DEBUG) { - riverStatTableTimer.start(); - } - riverStatRecordList = riverStatTable.select(whereClause); - if (_DEBUG) { - riverStatTableTimer.stop("Finished RiverStatTable query in "); - } - - stationClassList = stationClassTable.select(whereClause); - - } catch (SQLException e) { - logSQLException(e); - e.printStackTrace(); - } - - if (_locationHashMap == null) { - _locationHashMap = new HashMap(); - } - if (_DEBUG) { - System.out - .println("Size of recordslist = " + locPDCViewList.size()); - System.out.flush(); - } - - for (int i = 0; i < locPDCViewList.size(); i++) { - LocPDCRecord locPDCRecord = (LocPDCRecord) locPDCViewList.get(i); - location = new Location(); - location.setLid(locPDCRecord.getLid().trim()); - location.setHsa(locPDCRecord.getHsa().trim()); - - if (_DEBUG) { - parseTimer.restart(); - } - - double formattedLat = getFormattedDouble(locPDCRecord.getLat(), 2, - DbTable.getNullDouble(), 0.0); - location.setLat(formattedLat); - - double formattedLon = getFormattedDouble(locPDCRecord.getLon(), 2, - DbTable.getNullDouble(), 0.0); - location.setLon(formattedLon); - - if (_DEBUG) { - parseTimer.stop(); - } - - location.setElevation(locPDCRecord.getElev()); - location.setLocationName(locPDCRecord.getName()); - location.setRiverStation(false); - - double fq = locPDCRecord.getFq(); - double fs = locPDCRecord.getFs(); - - if (locPDCRecord.getLid().equals("ESFO2")) { - System.out.println("fs = " + fs); - } - - if ((fq == 0) || (DbTable.isNull(fq)))// missing value - { - location.setFloodFlow(MISSING); - } else { - location.setFloodFlow(fq); - } - - if ((fs == 0) || (DbTable.isNull(fs)))// missing value - { - location.setFloodStage(MISSING); - } else { - location.setFloodStage(fs); - } - - if ((fq == MISSING) && (fs != MISSING) - && (location.getRatingCurve() != null)) { - location.setFloodFlow(location.getRatingCurve() - .getDischargeFromStage(fs)); - } - - String dispClass = locPDCRecord.getDisp_class(); - - if ((dispClass.indexOf("F")) != -1) { - location.setFcstPoint(true); - } else { - location.setFcstPoint(false); - } - - String dcp = locPDCRecord.getIs_dcp(); - - if ((dcp.indexOf("T")) != -1) { - location.setDCP(true); - } else { - location.setDCP(false); - } - - String observer = locPDCRecord.getIs_observer(); - - if ((observer.indexOf("T")) != -1) { - location.setObserver(true); - } else { - location.setObserver(false); - } - - location.setTelemType(locPDCRecord.getTelem_type()); - if (_DEBUG) { - putHashMapTimer.restart(); - } - _locationHashMap.put(location.getLid(), location); - if (_DEBUG) { - putHashMapTimer.stop(); - } - } - - /* - * for ( int i = 0; i < riverStatRecordList.size(); i++ ) { - * RiverstatRecord riverStatRecord = (RiverstatRecord) - * riverStatRecordList.get( i ); - * - * Location selectedLoc = (Location) _locationHashMap.get( - * riverStatRecord.getLid() ); - * - * if ( ( selectedLoc != null ) && ( riverStatRecord != null ) ) { - * selectedLoc.setRiverStation( true ); } } - */ - - // For each stationClassRecord, match it up to a location record. - // if there is a match, set the river station indicator to true if - // stnClassRecord's display class contains F, D, or R. - for (int i = 0; i < stationClassList.size(); i++) { - StnClassRecord stnClassRecord = (StnClassRecord) stationClassList - .get(i); - - Location selectedLoc = (Location) _locationHashMap - .get(stnClassRecord.getLid()); - - if ((selectedLoc != null) && (stnClassRecord != null)) { - String displayClassString = stnClassRecord.getDisp_class(); - if ((displayClassString.contains("R")) - || (displayClassString.contains("D")) - || (displayClassString.contains("F"))) { - selectedLoc.setRiverStation(true); - } - - } - } - - if (_DEBUG) { - ratingCurveTimer.restart(); - } - - loadRatingCurves(); - if (_DEBUG) { - ratingCurveTimer.stop(); - } - - if (_DEBUG) { - System.out.println("push HashMap finished in " - + putHashMapTimer.getElapsedTime() + " millis"); - System.out.println("parseTimer finished in " - + parseTimer.getElapsedTime() + " millis"); - System.out.println("ratingCurveTimer finished in " - + ratingCurveTimer.getElapsedTime() + " millis"); - lidHashMapTimer.stop("Finished creating Lid HashMap in "); - } - } - - // -------------------------------------------------------------------------------- - - private double getFormattedDouble(double originalValue, - int decimalPlacesToMaintain, double missingValue, - double missingValueReplacement) { - double value = missingValueReplacement; - - if (originalValue == missingValue) { - originalValue = missingValueReplacement; - } else { - value = MathHelper.roundToNDecimalPlaces(originalValue, - decimalPlacesToMaintain); - } - - return value; - } - - // ------------------------------------------------------------------------ - - public Set getCompleteLidSet() { - Set completeLidSet = _locationHashMap.keySet(); - - return completeLidSet; - } - - public Set getRiverStationLidSet() { - List locationKeyList = new ArrayList(_locationHashMap.keySet()); - - Set completeRiverStationLidSet = new HashSet(); - - // find all river stations and add their lids to the lid set. - for (int i = 0; i < locationKeyList.size(); i++) { - String lid = (String) locationKeyList.get(i); - Location location = (Location) _locationHashMap.get(lid); - - if (location == null) { - System.err.println("no location found for " + lid - + " in getRiverStationLidSet"); - continue; - } - - if (location.isRiverStation()) { - completeRiverStationLidSet.add(lid); - } - } - - return completeRiverStationLidSet; - } - - // ------------------------------------------------------------------------ - - public RegularObsTimeSeries getDischargeTimeSeriesFromHeightTimeSeries( - RegularObsTimeSeries obsTimeSeries) { - RegularObsTimeSeries newTimeSeries = null; - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor( - obsTimeSeries.getDescriptor()); - - Location location = (Location) _locationHashMap - .get(descriptor.getLid()); - - if (location == null) { - System.err.println("no location found for " + descriptor.getLid() - + " in getDischargeTimeSeriesFromHeightTimeSeries"); - return newTimeSeries; - } - - // DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - String dischargeString = null; - RatingCurve ratingCurve = location.getRatingCurve(); - boolean wrongPe = false; - - // change the descriptor and check for a nonconvertable PE - if (descriptor.getPe().equalsIgnoreCase("HG")) { - descriptor.setPe("QR"); - } else if (descriptor.getPe().equalsIgnoreCase("HT")) { - descriptor.setPe("QT"); - } else { - wrongPe = true; - } - - if (!wrongPe && ratingCurve != null && ratingCurve.exists()) { - - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - newTimeSeries = new RegularObsTimeSeries(descriptor, 1, - hourlyTimeSlotPolicy); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - double dischargeValue = 0.0; - - for (int i = 0; i < timeValuePairList.size(); i++) { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList - .get(i); - if (timeValuePair != null) { - TimeValuePair newTimeValuePair = new TimeValuePair( - timeValuePair.getDateTime()); - - dischargeValue = ratingCurve - .getDischargeFromStage(timeValuePair.getValue()); - dischargeValue = MathHelper.roundToNDecimalPlaces( - dischargeValue, 2); - newTimeValuePair.setValue(dischargeValue); - - // dischargeString = decimalFormat.format( - // ratingCurve.getDischargeFromStage( - // timeValuePair.getValue() ) ); - // newTimeValuePair.setValue( Double.parseDouble( - // dischargeString ) ); - - newTimeSeries - .addTimeValuePairIfBetterMatch(newTimeValuePair); - } - } - } - - return newTimeSeries; - } - - // ------------------------------------------------------------------------ - - public RegularObsTimeSeries getPercentFloodFlowTimeSeriesListFromFlowStorageTimeSeries( - RegularObsTimeSeries obsTimeSeries) { - RegularObsTimeSeries newTimeSeries = null; - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries - .getDescriptor(); - Location location = (Location) _locationHashMap - .get(descriptor.getLid()); - // DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - if (location == null) { - System.err - .println("no location found for " - + descriptor.getLid() - + " in getPercentFloodFlowTimeSeriesListFromFlowStorageTimeSeries"); - return newTimeSeries; - } - - if (location.getFloodFlow() > 0.0) { - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - newTimeSeries = new RegularObsTimeSeries(descriptor, 1, - hourlyTimeSlotPolicy); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - double percentFloodFlow = 0.0; - - for (int i = 0; i < timeValuePairList.size(); i++) { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList - .get(i); - if (timeValuePair != null) { - TimeValuePair newTimeValuePair = new TimeValuePair( - timeValuePair.getDateTime()); - - if (!timeValuePair.isMissingValue()) { - percentFloodFlow = timeValuePair.getValue() - / location.getFloodFlow(); - percentFloodFlow = 100.0 * MathHelper - .roundToNDecimalPlaces(percentFloodFlow, 2); - - // String valueString = decimalFormat.format( - // timeValuePair.getValue() / location.getFloodFlow() ); - // newTimeValuePair.setValue( Double.parseDouble( - // valueString ) ); - - if ((percentFloodFlow >= 0.0) - && (percentFloodFlow <= 100.0)) { - newTimeValuePair.setValue(percentFloodFlow); - newTimeSeries - .addTimeValuePairIfBetterMatch(newTimeValuePair); - } - } - } - } - } - return newTimeSeries; - } - - // ------------------------------------------------------------------------ - - public void loadRatingCurves() { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List allRatingRecordList = null; - List singleStationRatingRecordList = new ArrayList(); - - List allRatingShiftRecordList = null; - List singleStationShiftList = null; - - List allRiverstatRecordList = null; - RiverstatRecord riverStatRecord = null; - - String prevLid = null; - - int riverStatIndex = 0; - int ratingShiftIndex = 0; - IntegerHolder ratingShiftIndexHolder = new IntegerHolder( - ratingShiftIndex); - IntegerHolder riverStatIndexHolder = new IntegerHolder(riverStatIndex); - - try { - allRatingRecordList = ratingTable.select("ORDER BY lid, stage"); - allRatingShiftRecordList = ratingShiftTable - .select("WHERE active = 'T' ORDER BY lid, date desc"); - allRiverstatRecordList = riverstatTable.select("ORDER BY lid"); - - for (int i = 0; i < allRatingRecordList.size(); i++) { - RatingRecord ratingRecord = (RatingRecord) allRatingRecordList - .get(i); - // you have at least one rating curve that you have dealt with - // and you are still going - if ((prevLid != null) - && (!ratingRecord.getLid().equalsIgnoreCase(prevLid))) { - singleStationShiftList = getStationRatingShiftRecordListFromRatingShiftRecordList( - prevLid, allRatingShiftRecordList, - ratingShiftIndexHolder); - riverStatRecord = getRiverStatRecordFromRiverStatRecordList( - prevLid, allRiverstatRecordList, - riverStatIndexHolder); - // process old - loadRatingCurveByRecordList(singleStationRatingRecordList, - singleStationShiftList, riverStatRecord, prevLid); - - singleStationRatingRecordList.clear(); - } - - singleStationRatingRecordList.add(ratingRecord); - prevLid = ratingRecord.getLid(); - } - - } catch (SQLException e) { - logSQLException(e); - ratingCurve = null; - } - } - - // ------------------------------------------------------------------------ - - private void loadRatingCurveByRecordList(List ratingRecordList, - List ratingShiftList, RiverstatRecord riverStatRecord, - String locationId) { - String header = "loadRatingCurveByRecordList(): "; - - RatingCurve ratingCurve = null; - - // determine total amount of active - // rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList - .get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - // System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - // initialize the RatingCurve object with data from the database, - // including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - // done by addRatingPoint - // ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } // end for - - // set the USGS fields in the rating curve - if (riverStatRecord != null) { - ratingCurve.setUsgsRatingNumber(riverStatRecord.getUsgs_ratenum()); - ratingCurve.setRatingDate(riverStatRecord.getRatedat()); - } - - Location location = (Location) _locationHashMap.get(locationId); - - if (location != null) { - location.setRatingCurve(ratingCurve); - } else { - System.out - .println(header - + " Station classification missing ERROR for locationId = " - + locationId - + " + Run set_stnclass.LX to update station classifications."); - } - - } - - // ------------------------------------------------------------------------ - - /** - * @param lid - * - location id - * @param allRatingShiftRecordList - * - Complete list of ratingShiftRecords sorted by lid - * @param ratingShiftIndexHolder - * - Index holder for the current ratingShift Index - * @return Single station ratingShiftRecordList - */ - private List getStationRatingShiftRecordListFromRatingShiftRecordList( - String lid, List allRatingShiftRecordList, - IntegerHolder ratingShiftIndexHolder) { - List ratingShiftRecordList = new ArrayList(); - RatingShiftRecord record = null; - - boolean found = false; - boolean done = false; - - for (int i = ratingShiftIndexHolder.getValue(); i < allRatingShiftRecordList - .size() && !done; i++) { - record = (RatingShiftRecord) allRatingShiftRecordList.get(i); - if (record.getLid().equalsIgnoreCase(lid)) { - ratingShiftRecordList.add(record); - found = true; - ratingShiftIndexHolder.setValue(i); - } else if (found) // prevlid does not match current lid and lid has - // already been found so we've found all the - // ratingshifts for the lid - { - done = true; - } - } - return ratingShiftRecordList; - } - - // ------------------------------------------------------------------------ - - /** - * Get's the matching riverstatrecord for the passed in lid - * - * @param lid - * - location id - * @param allRiverStatRecordList - * - Complete list of RiverstatRecords - * @param riverStatIndexHolder - * - Index holder for the current riverstat Index - */ - private RiverstatRecord getRiverStatRecordFromRiverStatRecordList( - String lid, List allRiverStatRecordList, - IntegerHolder riverStatIndexHolder) { - RiverstatRecord record = null; - - boolean found = false; - - for (int i = riverStatIndexHolder.getValue(); i < allRiverStatRecordList - .size() && !found; i++) { - record = (RiverstatRecord) allRiverStatRecordList.get(i); - if (record.getLid().equalsIgnoreCase(lid)) { - found = true; - riverStatIndexHolder.setValue(i); - } - } - return record; - } - - // ------------------------------------------------------------------------ - - /** - * createShefDurMap() - Creates a Hashmap of Shef durations. Used for - * creating PEDTSEPs when writing out the data to .DAT files - */ - public Map getShefDurCodeToDurMap() { - return _shefDurToDurcodeMap; - } - - public void createShefDurMap() { - CodeTimer timer1 = new CodeTimer(); - - if (_DEBUG) { - timer1.start(); - } - - ShefDurTable table = new ShefDurTable(_db); - List shefDurRecordList = null; - - try { - shefDurRecordList = table.select(""); - } catch (SQLException e) { - logSQLException(e); - } - - if (_shefDurMap == null) { - _shefDurMap = new HashMap(); - _shefDurToDurcodeMap = new HashMap(); - } - - for (int i = 0; i < shefDurRecordList.size(); i++) { - ShefDurRecord record = (ShefDurRecord) shefDurRecordList.get(i); - _shefDurMap.put("" + record.getDur(), record.getDurcode()); - _shefDurToDurcodeMap.put(record.getDurcode(), "" + record.getDur()); - } - - if (_DEBUG) { - timer1.stop("Finished creating ShefDurMap in "); - } - } - - // ------------------------------------------------------------------------ - - /** - * getCachedNonPrecipObsTimeSeriesList - Queries the database and returns a - * List of Observed Time Series. - * - * @param tableName - * - Name of the table to query. - * @param numHoursToPreProcess - * - The number of hours of data to preprocess. - * - * @return obsTimeSeriesList - List of RegularObsTimeSeries objects - */ - private List readNonPrecipObsTimeSeriesListFromCachedFile( - String fullFilePath) { - - PDCFileReader reader = new PDCFileReader(fullFilePath, - _shefDurToDurcodeMap); - - List obsTimeSeriesList = reader.read(); - - return obsTimeSeriesList; - } - - // ------------------------------------------------------------------------ - - private List readPrecipObsTimeSeriesListFromCachedFile(String fullFilePath) { - - PDCFileReader reader = new PDCFileReader(fullFilePath, - _shefDurToDurcodeMap); - - List obsTimeSeriesList = reader.read(); - - return obsTimeSeriesList; - } - - // ------------------------------------------------------------------------ - public List getNonPrecipObsTimeSeriesListUsingCache(String tableName, - long endTime, int numHoursToPreprocess) { - String header = "PDCPreprocessorDataMgr.getNonPrecipObsTimeSeriesListUsingCache(): "; - List resultantTimeSeriesList = null; - List fileTimeSeriesList = null; - List dbTimeSeriesList = null; - CodeTimer dbTimer = new CodeTimer(); - CodeTimer writeTimer = new CodeTimer(); - - int numHoursToRetrieveFromDb = 0; - - String fullFilePath = _preprocessedFilePath + "/cached" + tableName - + ".dat"; - - fileTimeSeriesList = readNonPrecipObsTimeSeriesListFromCachedFile(fullFilePath); - - if (isCachedDataCurrentEnough(fileTimeSeriesList, - _nonPrecipHoursToReadWhenCaching)) - - { - numHoursToRetrieveFromDb = _nonPrecipHoursToReadWhenCaching; - } else // re-retrieve everything from the db - { - numHoursToRetrieveFromDb = numHoursToPreprocess; - } - - System.out.println(header + "for table = " + tableName - + ", numHoursToRetrieveFromDb = " + numHoursToRetrieveFromDb); - - dbTimer.start(); - dbTimeSeriesList = getNonPrecipObsTimeSeriesListFromDb(tableName, - endTime, numHoursToRetrieveFromDb); - dbTimer.stop(header + "db read within cache read took "); - - long newStartTime = getNewStartTime(endTime, 1, numHoursToPreprocess); - - resultantTimeSeriesList = TimeSeriesListMgr.mergeTimeSeriesLists( - dbTimeSeriesList, fileTimeSeriesList, newStartTime, endTime); - - // for the next time this program is run, write out the newly cached - // data - // I don't want the missing data to be saved - - writeTimer.start(); - writeRegularObsDataToFile(resultantTimeSeriesList, "cached" + tableName); - writeTimer - .stop(header + "writing to data file within cache read took "); - - return resultantTimeSeriesList; - } - - // -------------------------------------------------------------------------------------------- - public List getPrecipObsTimeSeriesListFromCache(int timeStepIntervalInHours) { - List cachedDataTimeSeriesList = null; - - String fullFilePath = _preprocessedFilePath + "/cached" - + timeStepIntervalInHours + "HourPrecip.dat"; - - cachedDataTimeSeriesList = readPrecipObsTimeSeriesListFromCachedFile(fullFilePath); - - return cachedDataTimeSeriesList; - } - - // -------------------------------------------------------------------------------------------- - - public void handleCacheAging() { - if (!isCacheNewEnough()) { - deleteOldCacheFiles(); - updateCacheRefreshIndicator(); - } - } - - // -------------------------------------------------------------------------------------------- - - private boolean isCacheNewEnough() { - boolean result = false; - - File file = new File(getCacheRefreshIndicatorFileName()); - if (file.exists()) { - long fileCreationTime = file.lastModified(); - long currentTime = System.currentTimeMillis(); - - long ageInMillis = currentTime - fileCreationTime; - if (ageInMillis < _cacheRefreshAgeMaxInMillis) { - result = true; - } else { - result = false; - } - } - - return result; - } - - // -------------------------------------------------------------------------------------------- - - private void deleteOldCacheFiles() { - File directory = new File(_preprocessedFilePath); - - File fileArray[] = directory.listFiles(); - - if (fileArray != null) { - - for (int i = 0; i < fileArray.length; i++) { - File file = fileArray[i]; - String fileName = file.getName(); - if (fileName.startsWith("cached") && fileName.endsWith(".dat")) { - file.delete(); - } - - } - } - - } - - // -------------------------------------------------------------------------------------------- - - private void updateCacheRefreshIndicator() { - File file = new File(getCacheRefreshIndicatorFileName()); - try { - if (file.exists()) { - file.delete(); - } - - file.createNewFile(); - } catch (IOException e) { - System.out.println(e.getMessage()); - } - } - - // -------------------------------------------------------------------------------------------- - - private String getCacheRefreshIndicatorFileName() { - return _preprocessedFilePath + "/" + _refreshIndicatorBaseFileName; - } - - // -------------------------------------------------------------------------------------------- - - private boolean isCachedDataCurrentEnough(List fileTimeSeriesList, - int cacheHours) { - /* - * This examines the times of the data in the cache. - * shouldCacheBeAccepted() examines the last time that the cache itself - * was completely recreated from scratch. - */ - String header = "PDCPreprocessorDataMgr.isCachedDataCurrentEnough() :"; - boolean result = false; - - if (fileTimeSeriesList != null) // if there is no file, then it is not - // current enough - { - RegularObsTimeSeries firstFileTs = (RegularObsTimeSeries) fileTimeSeriesList - .get(0); - - // System.out.println(header + " firstFileTs = " + firstFileTs); - - long lastFileObsTime = firstFileTs.getLatestTimeValue(0); - - long currentTime = System.currentTimeMillis(); - - // System.out.println(header + " lastFileObsTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(lastFileObsTime) + - // " currentTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(currentTime) ); - - long stalenessTime = currentTime - lastFileObsTime; - - if (stalenessTime < cacheHours * MILLIS_PER_HOUR) { - result = true; - } - } else { - System.out - .println(header - + "fileTimeSeriesList is null, so need to read more data from db"); - } - - return result; - } - - // -------------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------- - - // ------------------------------------------------------------------------- - /** - * getNonPrecipObsTimeSeriesListFromDb - Queries the database and returns a - * List of Observed data. - * - * @param tableName - * - Name of the table to query. - * @param numHoursToPreProcess - * - The number of hours of data to preprocess. - * - * @return obsTimeSeriesList - List of RegularObsTimeSeries data - */ - public List getNonPrecipObsTimeSeriesListFromDb(String tableName, - long endTime, int numHoursToPreProcess) { - String header = "PDCPreprocessorDataMgr.getNonPrecipObsTimeSeriesListFromDb(): "; - NonPrecipObsTableManager table = new NonPrecipObsTableManager(_db, - tableName); - List obsTimeSeriesList = null; - - if (numHoursToPreProcess > 0) { - try { - obsTimeSeriesList = table.select(tableName, - numHoursToPreProcess, endTime); - } catch (SQLException e) { - logSQLException(e); - } - } - - System.out.println(header + "for table = " + tableName - + ", records retrieved = " + obsTimeSeriesList.size()); - - return obsTimeSeriesList; - } - - // ------------------------------------------------------------------------ - - public RegularObsTimeSeries getDepthAboveFSTimeSeries( - RegularObsTimeSeries obsTimeSeries) { - RegularObsTimeSeries newTimeSeries = null; - Location location = (Location) _locationHashMap.get(obsTimeSeries - .getDescriptor().getLid()); - double floodStage = MISSING; - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - if (location == null) { - System.out.println("Pause"); - return newTimeSeries; - } - if (location.isRiverStation()) { - newTimeSeries = new RegularObsTimeSeries( - obsTimeSeries.getDescriptor(), 1, hourlyTimeSlotPolicy); - floodStage = location.getFloodStage(); - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - for (int i = 0; i < timeValuePairList.size(); i++) { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList - .get(i); - if (timeValuePair != null) { - TimeValuePair newTimeValuePair = new TimeValuePair( - timeValuePair.getDateTime()); - if ((floodStage == MISSING) - || (timeValuePair.getValue() == MISSING)) { - newTimeValuePair.setValue(MISSING); - } else { - newTimeValuePair.setValue(timeValuePair.getValue() - - floodStage); - } - newTimeSeries - .addTimeValuePairIfBetterMatch(newTimeValuePair); - } - } - } else { - newTimeSeries = new RegularObsTimeSeries( - obsTimeSeries.getDescriptor(), 1, hourlyTimeSlotPolicy); - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - for (int i = 0; i < timeValuePairList.size(); i++) { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList - .get(i); - TimeValuePair newTimeValuePair = null; - if (timeValuePair != null) { - newTimeValuePair = new TimeValuePair( - timeValuePair.getDateTime(), MISSING); - newTimeSeries - .addTimeValuePairIfBetterMatch(newTimeValuePair); - } - } - } - return newTimeSeries; - } - - // ------------------------------------------------------------------------ - - public RegularObsTimeSeries getDeltaTimeSeries( - RegularObsTimeSeries obsTimeSeries) { - DecimalFormat decimalFormat = new DecimalFormat("0.00"); - - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries - .getDescriptor(); - long previousDayTime = descriptor.getStartTime(); - - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - RegularObsTimeSeries newTimeSeries = new RegularObsTimeSeries( - obsTimeSeries.getDescriptor(), 1, hourlyTimeSlotPolicy); - - descriptor.setStartTime(previousDayTime + (MILLIS_PER_DAY)); - - Map timeValuePairMap = obsTimeSeries.getTopOfTheHourTimeValuePairMap(); - - for (long indexTime = descriptor.getStartTime(); indexTime <= descriptor - .getEndTime(); indexTime += MILLIS_PER_HOUR) { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairMap - .get(new Long(indexTime)); - if (timeValuePair != null) { - TimeValuePair newTimeValuePair = new TimeValuePair( - timeValuePair.getDateTime()); - TimeValuePair previousTimeValuePair = (TimeValuePair) timeValuePairMap - .get(new Long(previousDayTime)); - - if ((timeValuePair == null) || (previousTimeValuePair == null) - || (previousTimeValuePair.getValue() == MISSING) - || (timeValuePair.getValue() == MISSING)) { - - } else { - double newValue = timeValuePair.getValue() - - previousTimeValuePair.getValue(); - - newTimeValuePair.setValue(Double.parseDouble(decimalFormat - .format(newValue))); - newTimeSeries - .addTimeValuePairIfBetterMatch(newTimeValuePair); - } - - previousDayTime += MILLIS_PER_HOUR; - } - - } - - return newTimeSeries; - } - - // ------------------------------------------------------------------------ - - public void executePDCPrecipPP(long endTime, int precipHoursToReadFromDB) { - CodeTimer executePDCPrecipPPTimer = new CodeTimer(); - - if (_DEBUG) { - executePDCPrecipPPTimer.start(); - } - - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - String commandString = dirString + "/run_pdc_precip_pp" + " " - + (endTime / 1000) + " " + precipHoursToReadFromDB; - - if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1)) // Checking to see if - // running on Linux or - // Windows - { - } else { - Process process = null; - try { - System.out.println("Command string = :" + commandString + ":"); - process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } catch (IOException e) { - logException(e); - if (_DEBUG) { - e.printStackTrace(); - } - } - - catch (InterruptedException e) { - logException(e); - if (_DEBUG) { - e.printStackTrace(); - } - } - - finally { - // DR#10955 - if (process != null) { - process.destroy(); - } - } - } - if (_DEBUG) { - executePDCPrecipPPTimer.stop("Completed call of PDCPrecipPP in "); - } - } - - public List getInstantaneousPrecipTimeSeriesList(long endTime) { - List instantPrecipTimeSeriesList = new ArrayList(); - String instantPrecipInputFileName = null; - - if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1)) { - instantPrecipInputFileName = "D:/data/pdcpreprocessor/geninstantprecip.out"; - } else // assume it's unix - { - instantPrecipInputFileName = _preprocessedFilePath - + "/geninstantprecip.out"; - } - - try { - File instantPrecipFile = new File(instantPrecipInputFileName); - - BufferedReader _reader = new BufferedReader(new FileReader( - instantPrecipFile)); - String line = _reader.readLine(); // discard the first line - line = _reader.readLine(); // discard the second line - line = _reader.readLine(); // discard the third line - line = _reader.readLine(); - - while ((line = _reader.readLine()) != null) // reads the next line - // and checks if it's - // null - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - String[] tokenizedLine = StringParser.tokenize(line); - - descriptor.setLid(tokenizedLine[0]); - descriptor.setPe(tokenizedLine[1]); - descriptor.setDur((short) 1001); - descriptor.setExtremum("Z"); - descriptor.setTs(tokenizedLine[2]); - descriptor.setStartTime(endTime - MILLIS_PER_DAY); - descriptor.setEndTime(endTime); - - line = _reader.readLine(); - tokenizedLine = StringParser.tokenize(line); - - IrregularObsTimeSeries obsTimeSeries = new IrregularObsTimeSeries( - descriptor, 1); - - long startTime = endTime - MILLIS_PER_DAY; - int counter = 0; - - // add all of the regular hours for the last 24 hours, 1..24 - for (long indexTime = startTime; indexTime < endTime; indexTime += MILLIS_PER_HOUR) { - TimeValuePair timeValuePair = new TimeValuePair(indexTime); - timeValuePair.setValue(Double - .parseDouble(tokenizedLine[counter++])); - obsTimeSeries.addTimeValuePairIfBetterMatch(timeValuePair); - } - - // add the special entry that is for the last half hour - TimeValuePair timeValuePair = new TimeValuePair(endTime - - (MILLIS_PER_HALF_HOUR)); - timeValuePair.setValue(Double - .parseDouble(tokenizedLine[counter++])); - obsTimeSeries.addTimeValuePairIfBetterMatch(timeValuePair); - - instantPrecipTimeSeriesList.add(obsTimeSeries); - } - } catch (FileNotFoundException e) { - logException(e); - if (_DEBUG) { - e.printStackTrace(); - } - } catch (IOException e) { - logException(e); - if (_DEBUG) { - e.printStackTrace(); - } - } - return instantPrecipTimeSeriesList; - } - - // ------------------------------------------------------------------------ - - // ------------------------------------------------------------------------ - public List get1HourPrecipTimeSeriesListFromCFile() { - return readPrecipTimeSeriesListFromCGeneratedFile(1, 1001); - } - - // ------------------------------------------------------------------------ - public List get3HourPrecipTimeSeriesListFromCFile() { - return readPrecipTimeSeriesListFromCGeneratedFile(3, 1003); - } - - // ------------------------------------------------------------------------ - public List get6HourPrecipTimeSeriesListFromCFile() { - return readPrecipTimeSeriesListFromCGeneratedFile(6, 1006); - } - - // ------------------------------------------------------------------------ - public List get24HourPrecipTimeSeriesListFromCFile() { - return readPrecipTimeSeriesListFromCGeneratedFile(24, 2001); - } - - // ------------------------------------------------------------------------ - - public List readPrecipTimeSeriesListFromCGeneratedFile( - int timeStepIntervalInHours, int durationCode) { - List precipTimeSeriesList = new ArrayList(); - - String fileName = "gen" + timeStepIntervalInHours + "hourprecip.out"; - - String precipInputFileName = null; - String[] tokenizedLine = null; - - if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1)) { - precipInputFileName = "D:/data/pdcpreprocessor/" + fileName; - } else // assume it's unix - { - precipInputFileName = _preprocessedFilePath + "/" + fileName; - } - - try { - File precipInputFile = new File(precipInputFileName); - - BufferedReader _reader = new BufferedReader(new FileReader( - precipInputFile)); - String line = _reader.readLine(); // discard the first line - line = _reader.readLine(); // discard the second line - line = _reader.readLine(); // discard the third line - line = _reader.readLine(); // discard the fourth line - line = _reader.readLine(); - tokenizedLine = StringParser.tokenize(line); - - long startTime = Long.parseLong(tokenizedLine[0]) * 1000; - long endTime = Long.parseLong(tokenizedLine[1]) * 1000; - - while ((line = _reader.readLine()) != null) // reads the next line - // and checks if it's - // null - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - tokenizedLine = StringParser.tokenize(line); - - descriptor.setLid(tokenizedLine[0]); - // descriptor.setPe( "PP" ); //added 5/16/06 - - descriptor.setPe(tokenizedLine[1]); // commented out because I - // want acumm. precip to - // display as PP - descriptor.setDur((short) durationCode); - descriptor.setExtremum("Z"); - descriptor.setTs(tokenizedLine[2]); - descriptor.setStartTime(startTime); - descriptor.setEndTime(endTime); - - line = _reader.readLine(); - tokenizedLine = StringParser.tokenize(line); - - TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - - RegularObsTimeSeries obsTimeSeries = new RegularObsTimeSeries( - descriptor, timeStepIntervalInHours, timeSlotPolicy); - - int counter = 0; - - // System.out.println( ( _endTime - startTime ) / ( 1000 * 60 ) - // ); - - long indexTime = startTime; - - // add in all the TimeValuePairs for the complete periods - for (int i = 0; i < tokenizedLine.length - 1; i++) { - TimeValuePair timeValuePair = new TimeValuePair(indexTime); - timeValuePair.setValue(Double - .parseDouble(tokenizedLine[counter++])); - obsTimeSeries.addTimeValuePairIfBetterMatch(timeValuePair); - indexTime += timeStepIntervalInHours * MILLIS_PER_HOUR; - } - - // add in the tvp for the last (possibly) incomplete period - TimeValuePair timeValuePair = new TimeValuePair(endTime); - timeValuePair.setValue(Double - .parseDouble(tokenizedLine[counter++])); - obsTimeSeries.addTimeValuePairIfBetterMatch(timeValuePair); - - precipTimeSeriesList.add(obsTimeSeries); - } - } catch (FileNotFoundException e) { - logException(e); - if (_DEBUG) { - e.printStackTrace(); - } - } catch (IOException e) { - logException(e); - if (_DEBUG) { - e.printStackTrace(); - } - } - - return precipTimeSeriesList; - } - - // ------------------------------------------------------------------------ - - private void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - // ------------------------------------------------------------------------ - - private void logException(Exception exception) { - _logger.log("ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - } - - // ------------------------------------------------------------------------ - public PrecipListHolder processPrecipDataWithCaching(long endTime, - int numHoursToPreprocess) { - CodeTimer cCodeTimer = new CodeTimer(); - CodeTimer cacheReadTimer = new CodeTimer(); - CodeTimer processingTimer = new CodeTimer(); - CodeTimer instTimer = new CodeTimer(); - CodeTimer mergingTimer = new CodeTimer(); - - PrecipListHolder precipListHolder = new PrecipListHolder(); - - String header = "PDCPreprocessor.processPrecipDataWithCaching(): "; - int hoursToReadWhenCaching = _precipHoursToReadWhenCaching; // Note, - // MUST be a - // multiple - // of 24 - // hours - int numHoursToRetrieveUsingCRoutines = 0; - // read in cached Precip Data into all 4 Lists of RegularObsTimeSeries - // objects - // adjust the number of hours to read for the C program, - // based on how much I read in from the cache and how current it is - - // call the c program - // read some the list of observed time series data from the c file - - // merge the c file data and the cached file data - // save the merged data into the cache - - // write out the merged data - - cacheReadTimer.start(); - - List cached1HourPrecipTimeSeriesList = getPrecipObsTimeSeriesListFromCache(1); - - List cached3HourPrecipTimeSeriesList = getPrecipObsTimeSeriesListFromCache(3); - - List cached6HourPrecipTimeSeriesList = getPrecipObsTimeSeriesListFromCache(6); - - List cached24HourPrecipTimeSeriesList = getPrecipObsTimeSeriesListFromCache(24); - - cacheReadTimer.stop(header + "reading the cache took "); - - List instantPrecipTimeSeriesList = null; - List oneHourPrecipTimeSeriesList = null; - List threeHourPrecipTimeSeriesList = null; - List sixHourPrecipTimeSeriesList = null; - List twentyFourHourPrecipTimeSeriesList = null; - - // determine how many hours to retrieve fresh from the database - if ((isCachedDataCurrentEnough(cached1HourPrecipTimeSeriesList, - hoursToReadWhenCaching)) - && (isCachedDataCurrentEnough(cached3HourPrecipTimeSeriesList, - hoursToReadWhenCaching)) - && (isCachedDataCurrentEnough(cached6HourPrecipTimeSeriesList, - hoursToReadWhenCaching)) - && (isCachedDataCurrentEnough(cached24HourPrecipTimeSeriesList, - hoursToReadWhenCaching))) { - numHoursToRetrieveUsingCRoutines = hoursToReadWhenCaching; - } else // re-retrieve everything from the db - { - numHoursToRetrieveUsingCRoutines = numHoursToPreprocess; - } - - // retrieve fresh data and merge it with the data previously retrieved - // from the cache. - if (numHoursToPreprocess > 0) { - System.out.println(header + " asking for " - + numHoursToRetrieveUsingCRoutines + " from C code"); - - cCodeTimer.start(); - - executePDCPrecipPP(endTime, numHoursToRetrieveUsingCRoutines); - - cCodeTimer.stop(header - + "Running the C Precip preprocessor alone took"); - - instTimer.start(); - instantPrecipTimeSeriesList = getInstantaneousPrecipTimeSeriesList(endTime); - precipListHolder - .setInstantPrecipTimeSeriesList(instantPrecipTimeSeriesList); - instTimer.stop(header + " calculating Instantaneous Precip took "); - - mergingTimer.start(); - - // Merge all the time series (plural) - long newStartTime = 0; - oneHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList( - endTime, 1, numHoursToPreprocess, 1001, - cached1HourPrecipTimeSeriesList); - precipListHolder - .setOneHourPrecipTimeSeriesList(oneHourPrecipTimeSeriesList); - - threeHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList( - endTime, 3, numHoursToPreprocess, 1003, - cached3HourPrecipTimeSeriesList); - precipListHolder - .setThreeHourPrecipTimeSeriesList(threeHourPrecipTimeSeriesList); - - sixHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList( - endTime, 6, numHoursToPreprocess, 1006, - cached6HourPrecipTimeSeriesList); - precipListHolder - .setSixHourPrecipTimeSeriesList(sixHourPrecipTimeSeriesList); - - twentyFourHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList( - endTime, 24, numHoursToPreprocess, 2001, - cached24HourPrecipTimeSeriesList); - precipListHolder - .setTwentyForHourPrecipTimeSeriesList(twentyFourHourPrecipTimeSeriesList); - - mergingTimer.stop(header - + "merging the 1,3,6, and 24 hour time series took"); - - } - - return precipListHolder; - } - - // ------------------------------------------------------------------------ - private List getMergedPrecipTimeSeriesList(long endTime, - int timeStepInHours, int numHoursToPreprocess, int durationCode, - List cachedPrecipTimeSeriesList) { - String header = "PDCPreprocessorDataMgr.getMergedPrecipTimeSeriesList() "; - List mergedDataList = null; - List freshDataList = null; - long newStartTime = 0; - - String cachedDataFileName = "cached" + timeStepInHours + "HourPrecip"; - - freshDataList = readPrecipTimeSeriesListFromCGeneratedFile( - timeStepInHours, durationCode); - - newStartTime = getNewStartTime(endTime, timeStepInHours, - numHoursToPreprocess); - long newEndTime = getNewEndTime(endTime, timeStepInHours); - - TimeSeriesListMgr.setNewStartTime(freshDataList, newStartTime); - - String newStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(newStartTime); - String newEndTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(newEndTime); - - System.out.println(header + " " + timeStepInHours - + "-hour timestep, newStartTime = " + newStartTimeString - + " newEndTime = " + newEndTimeString); - - mergedDataList = TimeSeriesListMgr.mergeTimeSeriesLists(freshDataList, - cachedPrecipTimeSeriesList, newStartTime, newEndTime); - - // copy to the cache for the next run - writeRegularObsDataToFile(mergedDataList, cachedDataFileName); - - return mergedDataList; - - } - - // ------------------------------------------------------------------------ - long getNewStartTime(long endTime, int timeStepIntervalInHours, - int numHoursToPreprocess) { - long newStartTime = 0; - long hoursBack = 0; - - // ----examine this section for simplification and correction- - // long numPeriods = numHoursToPreprocess / timeStepIntervalInHours; - // long millisBackInTime = numPeriods * timeStepIntervalInHours * - // MILLIS_PER_HOUR; - - if (timeStepIntervalInHours == 1) { - hoursBack = numHoursToPreprocess - 1; - } else { - hoursBack = numHoursToPreprocess - 1; - } - - long timeStepIntervalInMillis = timeStepIntervalInHours - * MILLIS_PER_HOUR; - long millisBackInTime = hoursBack * MILLIS_PER_HOUR; - - newStartTime = endTime - millisBackInTime; - newStartTime /= timeStepIntervalInMillis; - newStartTime *= timeStepIntervalInMillis; - // ---------------- - - if (timeStepIntervalInHours == 24) { - newStartTime += MILLIS_PER_12_HOURS; // 12z is used instead of 0z - } - - return newStartTime; - - } - - // ------------------------------------------------------------------------ - - long getNewEndTime(long origEndTime, int timeStepIntervalInHours) { - String header = "PDCPreprocessor.getNewEndTime(): "; - long endTime = 0; - - if (timeStepIntervalInHours != 24) { - // System.out.println(header + "orig end time was " + - // DbTimeHelper.getDateTimeStringFromLongTime(origEndTime)); - endTime = TimeHelper.truncateTimeInMillisToNearestHour(origEndTime, - timeStepIntervalInHours); - endTime += timeStepIntervalInHours * MILLIS_PER_HOUR; - } - - // System.out.println(header + "new time is " + - // DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - else // if (timeStepIntervalInHours == 24) - { - long twelveHourEndTime = TimeHelper - .truncateTimeInMillisToNearestHour(origEndTime, 12); - long twentyFourHourEndTime = TimeHelper - .truncateTimeInMillisToNearestHour(origEndTime, 24); - - if (twelveHourEndTime == twentyFourHourEndTime) // before 12 Z - { - endTime = twelveHourEndTime + MILLIS_PER_12_HOURS; - - } else // after 12Z - { - endTime = twelveHourEndTime + MILLIS_PER_DAY; - } - - } - - return endTime; - } - - // ------------------------------------------------------------------------ - - /** - * disconnect() - Closes the active connection to the database - */ - public void disconnect() { - _db.disconnect(); - } - - // ------------------------------------------------------------------------ - - @Override - public void finalize() { - disconnect(); - } - - // ------------------------------------------------------------------------ - - // ------------------------------------------------------------------------- - public void writeIrregularObsDataToFile(List obsTimeSeriesList, - String fileName) { - PDCFileWriter writer = new PDCFileWriter(_locationHashMap, _shefDurMap, - _shefDurToDurcodeMap, _preprocessedFilePath); - writer.writeIrregularObsDataToFile(obsTimeSeriesList, fileName); - } - - public void writeRegularObsDataToFile(List obsTimeSeriesList, - String fileName) { - PDCFileWriter writer = new PDCFileWriter(_locationHashMap, _shefDurMap, - _shefDurToDurcodeMap, _preprocessedFilePath); - writer.writeRegularObsDataToFile(obsTimeSeriesList, fileName); - } - - public void setPreprocessedFilePath(String preprocessedFilePath) { - _preprocessedFilePath = preprocessedFilePath; - } - - // ------------------------------------------------------------------------ - public void testPDCFiles() { - String fullFilePath = _preprocessedFilePath + "/cachedHeight.dat"; - - PDCFileReaderSlow reader = new PDCFileReaderSlow(fullFilePath, - _shefDurToDurcodeMap); - - List obsTimeSeriesList = reader.read(); - - PDCFileWriter writer = new PDCFileWriter(_locationHashMap, _shefDurMap, - _shefDurToDurcodeMap, _preprocessedFilePath); - - writer.writeRegularObsDataToFile(obsTimeSeriesList, "cachedHeight2"); - } - - // ------------------------------------------------------------------------ - - /** - * @return Returns whether in debug mode or not. - */ -} \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PdcMergeTest.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PdcMergeTest.java deleted file mode 100644 index 4579893837..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PdcMergeTest.java +++ /dev/null @@ -1,509 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PdcMergeTest extends TestCase { - public static final long MILLIS_PER_HALF_HOUR = 30 * 60 * 1000; - - public static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; - - public static final long MILLIS_PER_12_HOURS = MILLIS_PER_HOUR * 12; - - public static final long MILLIS_PER_MINUTE = 60 * 1000; - - private String pdc_pp_dirValue = "./pdctest/"; - - private RegularObsTimeSeries _cached3HourTimeSeries = null; - - private RegularObsTimeSeries _fresh3HourTimeSeries = null; - - private RegularObsTimeSeries _expectedMerged3HourTimeSeries = null; - - private RegularObsTimeSeries _cached24HourTimeSeries = null; - - private RegularObsTimeSeries _fresh24HourTimeSeries = null; - - private RegularObsTimeSeries _expectedMerged24HourTimeSeries = null; - - private PDCPreprocessorDataMgr _dataMgr = null; - - // 3 hour variables - private long _3HourStartTime = _3HourCachedTimeValuePairArray[0] - .getDateTime(); - - private String _3HourStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(_3HourStartTime); - - private String _3HourEndTimeString = "2007-01-02 05:15:00"; - - private long _3HourEndTime = DbTimeHelper - .getLongTimeFromDateTimeString(_3HourEndTimeString); - - private int _3HourLookBackWindow = 24; - - // 24 hour variables - private long _24HourStartTime = _24HourCachedTimeValuePairArray[0] - .getDateTime(); - - private String _24HourStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(_24HourStartTime); - - private String _24HourEndTimeString = "2007-01-11 03:07:00"; - - private long _24HourEndTime = DbTimeHelper - .getLongTimeFromDateTimeString(_24HourEndTimeString); - - private int _24HourLookBackWindow = 240; - - private static TimeValuePair[] _3HourCachedTimeValuePairArray = { - tvp("2007-01-01 00:00:00", 1.0), tvp("2007-01-01 03:00:00", 2.0), - tvp("2007-01-01 06:00:00", 3.0), tvp("2007-01-01 09:00:00", 4.0), - tvp("2007-01-01 12:00:00", 5.0), tvp("2007-01-01 15:00:00", 6.0), - tvp("2007-01-01 18:00:00", 7.0), tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), tvp("2007-01-02 03:00:00", 10.0) }; - - private static TimeValuePair[] _3HourFreshTimeValuePairArray = { - // tvp("2007-01-01 00:00:00", 1.0), - // tvp("2007-01-01 03:00:00", 2.0), - // tvp("2007-01-01 06:00:00", 3.0), - // tvp("2007-01-01 09:00:00", 4.0), - // tvp("2007-01-01 12:00:00", 5.0), - // tvp("2007-01-01 15:00:00", 6.0), - // tvp("2007-01-01 18:00:00", 7.0), - tvp("2007-01-01 21:00:00", 8.0), tvp("2007-01-02 00:00:00", 9.0), - tvp("2007-01-02 03:00:00", 11.0), tvp("2007-01-02 06:00:00", 5.5) }; - - private static TimeValuePair[] _3HourExpectedMergedTimeValuePairArray = { - // tvp("2007-01-01 00:00:00", 1.0), - // tvp("2007-01-01 03:00:00", 2.0), - tvp("2007-01-01 06:00:00", 3.0), tvp("2007-01-01 09:00:00", 4.0), - tvp("2007-01-01 12:00:00", 5.0), tvp("2007-01-01 15:00:00", 6.0), - tvp("2007-01-01 18:00:00", 7.0), tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), tvp("2007-01-02 03:00:00", 11.0), - tvp("2007-01-02 06:00:00", 5.5) }; - - private static TimeValuePair[] _24HourCachedTimeValuePairArray = { - tvp("2007-01-01 12:00:00", 1.0), tvp("2007-01-02 12:00:00", 2.0), - tvp("2007-01-03 12:00:00", 3.0), tvp("2007-01-04 12:00:00", 4.0), - tvp("2007-01-05 12:00:00", 5.0), tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), tvp("2007-01-08 12:00:00", 8.0), - // tvp("2007-01-09 12:00:00", 9.0), - // tvp("2007-01-10 12:00:00", 10.0) - }; - - private static TimeValuePair[] _24HourFreshTimeValuePairArray = { - // tvp("2007-01-01 12:00:00", 1.0), - // tvp("2007-01-02 12:00:00", 2.0), - // tvp("2007-01-03 12:00:00", 3.0), - // tvp("2007-01-04 12:00:00", 4.0), - // tvp("2007-01-05 12:00:00", 5.0), - tvp("2007-01-06 12:00:00", 6.0), tvp("2007-01-07 12:00:00", 7.0), - tvp("2007-01-08 12:00:00", 8.0), tvp("2007-01-09 12:00:00", 9.0), - tvp("2007-01-10 12:00:00", 11.0), tvp("2007-01-11 12:00:00", 5.5) }; - - private static TimeValuePair[] _24HourExpectedMergedTimeValuePairArray = { - tvp("2007-01-01 12:00:00", 1.0), tvp("2007-01-02 12:00:00", 2.0), - tvp("2007-01-03 12:00:00", 3.0), tvp("2007-01-04 12:00:00", 4.0), - tvp("2007-01-05 12:00:00", 5.0), tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), tvp("2007-01-08 12:00:00", 8.0), - tvp("2007-01-09 12:00:00", 9.0), tvp("2007-01-10 12:00:00", 11.0), - tvp("2007-01-11 12:00:00", 5.5) }; - - // -------------------------------------------------------------------------------------------------------- - - public PdcMergeTest() { - AppsDefaults ad = AppsDefaults.getInstance(); - - String preprocessedFilePath = ad.getToken("pdc_pp_dir") + "/"; - String logDirName = ad.getToken("pdc_pp_log_dir") + "/"; - - Logger logger = new FileLogger(logDirName + "PdcMergeTest.log"); - - String connectionString = "jdbc:postgresql://dx1-nhdr:5432/hd_ob81fwr?user=pguser"; - - _dataMgr = new PDCPreprocessorDataMgr(connectionString, logger, - preprocessedFilePath, 5, 5, true); - - return; - } - - // -------------------------------------------------------------------------------------------------------- - @Override - protected void setUp() throws Exception { - super.setUp(); - - createCachedTimeSeries(); - createFreshTimeSeries(); - createExpectedMergedTimeSeries(); - - } - - // -------------------------------------------------------------------------------------------------------- - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - // -------------------------------------------------------------------------------------------------------- - - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor( - String lid, String startTimeString, String endTimeString) { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - descriptor.setLid(lid); - descriptor.setPe("PP"); - descriptor.setDur((short) 1001); - descriptor.setTs("RG"); - descriptor.setExtremum("Z"); - - long startTime = DbTimeHelper - .getLongTimeFromDateTimeString(startTimeString); - descriptor.setStartTime(startTime); - - long endTime = DbTimeHelper - .getLongTimeFromDateTimeString(endTimeString); - descriptor.setEndTime(endTime); - - return descriptor; - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor( - String lid, long startTime, long endTime) { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - descriptor.setLid(lid); - descriptor.setPe("PP"); - descriptor.setDur((short) 1001); - descriptor.setTs("RG"); - descriptor.setExtremum("Z"); - - descriptor.setStartTime(startTime); - descriptor.setEndTime(endTime); - - return descriptor; - } - - // -------------------------------------------------------------------------------------------------------- - - private void addPairs(TimeValuePair[] timeValuePairArray, - RegularObsTimeSeries regularObsTimeSeries) { - String header = "PdcMergeTest.addPairs(): "; - for (int i = 0; i < timeValuePairArray.length; i++) { - TimeValuePair tvp = timeValuePairArray[i]; - if (tvp != null) { - regularObsTimeSeries.addTimeValuePairIfBetterMatch(tvp); - } else { - System.out.println(header + "tvp is null"); - } - } - - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeries createTimeSeries(String lid, - int durationInHours, TimeValuePair[] timeValuePairArray) { - // TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - TimeSlotPolicy timeSlotPolicy = null; - - TimeValuePair firstPair = timeValuePairArray[0]; - TimeValuePair lastPair = timeValuePairArray[timeValuePairArray.length - 1]; - - long startTime = firstPair.getDateTime(); - long endTime = lastPair.getDateTime(); - - if (durationInHours == 3) { - timeSlotPolicy = new HourlyTimeSlotPolicy(); - } else if (durationInHours == 24) { - timeSlotPolicy = new DailyTimeSlotPolicy(); - } - - RegularObsTimeSeriesDescriptor descriptor = getRegularObsTimeSeriesDescriptor( - lid, startTime, endTime); - - RegularObsTimeSeries timeSeries = new RegularObsTimeSeries(descriptor, - durationInHours, timeSlotPolicy); - - addPairs(timeValuePairArray, timeSeries); - - return timeSeries; - - } - - // -------------------------------------------------------------------------------------------------------- - - private void createCachedTimeSeries() { - _cached3HourTimeSeries = createTimeSeries("TEST1", 3, - _3HourCachedTimeValuePairArray); - _cached24HourTimeSeries = createTimeSeries("TEST1", 24, - _24HourCachedTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - private void createFreshTimeSeries() { - _fresh3HourTimeSeries = createTimeSeries("TEST1", 3, - _3HourFreshTimeValuePairArray); - _fresh24HourTimeSeries = createTimeSeries("TEST1", 24, - _24HourFreshTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - private void createExpectedMergedTimeSeries() { - _expectedMerged3HourTimeSeries = createTimeSeries("TEST1", 3, - _3HourExpectedMergedTimeValuePairArray); - _expectedMerged24HourTimeSeries = createTimeSeries("TEST1", 24, - _24HourExpectedMergedTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - public void innerTestMerge(final long endTime, int timeStepInHours, - int numHoursToPreprocess, RegularObsTimeSeries cachedTimeSeries, - RegularObsTimeSeries freshTimeSeries, - RegularObsTimeSeries expectedMergedTimeSeries) { - - String header = "PdcMergeTest.innerTestMerge(): "; - - // The current PDC merge way - long newStartTime = _dataMgr.getNewStartTime(endTime, timeStepInHours, - numHoursToPreprocess); - long newEndTime = _dataMgr.getNewEndTime(endTime, timeStepInHours); - - // long newStartTime = getNewStartTime(endTime, timeStepInHours, - // numHoursToPreprocess); - // long newEndTime = getNewEndTime(endTime, timeStepInHours); - - String originalEndTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(endTime); - - String newStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(newStartTime); - String newEndTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(newEndTime); - - System.out.println(header + "original end time = " - + originalEndTimeString); - System.out.println(header + " " + timeStepInHours - + "-hour timestep, newStartTime = " + newStartTimeString - + " newEndTime = " + newEndTimeString); - - // These lists of time series (plural) will have only 1 time series each - List freshList = new ArrayList(); - freshList.add(freshTimeSeries); - - List cachedList = new ArrayList(); - cachedList.add(cachedTimeSeries); - - List mergedList = TimeSeriesListMgr.mergeTimeSeriesLists(freshList, - cachedList, newStartTime, newEndTime); - RegularObsTimeSeries mergedTs = null; - - // get out the 1 merged time series that we are expecting - for (int i = 0; i < mergedList.size(); i++) { - mergedTs = (RegularObsTimeSeries) mergedList.get(i); - } - - // check that the merged list still has only 1 time series - assertEquals(1, mergedList.size()); - - // verify that the name of the time series is correct - String lid = mergedTs.getDescriptor().getLid(); - assertEquals("TEST1", lid); - - // verify that there are contents each time series - - boolean biggerThanZero = false; - - // fresh - biggerThanZero = freshTimeSeries.getTimeValuePairList(true).size() > 0; - assertEquals(true, biggerThanZero); - - // cached - biggerThanZero = cachedTimeSeries.getTimeValuePairList(true).size() > 0; - assertEquals(true, biggerThanZero); - - // merged - biggerThanZero = mergedTs.getTimeValuePairList(true).size() > 0; - assertEquals(true, biggerThanZero); - - // verify that the fresh and cached are not equal - boolean freshTsAndCachedEqual = regularTimeSeriesEqual(freshTimeSeries, - cachedTimeSeries); - assertEquals(false, freshTsAndCachedEqual); - - // verify that the fresh and mergedTs are equal, since mergeTs really IS - // freshTs - boolean mergeTsAndFreshEqual = regularTimeSeriesEqual(mergedTs, - freshTimeSeries); - assertEquals(true, mergeTsAndFreshEqual); - - // verify that the cached and mergeTs are not equal - boolean mergeTsAndCachedEqual = regularTimeSeriesEqual(mergedTs, - cachedTimeSeries); - assertEquals(false, mergeTsAndCachedEqual); - - // verify that the mergedTs is equal to the expectedMergedTimeSeries - - boolean mergedTsAndExpectedMergedTsEqual = regularTimeSeriesEqual( - mergedTs, expectedMergedTimeSeries); - if (!mergedTsAndExpectedMergedTsEqual) { - System.out.println(" mergedTs = "); - System.out.println(mergedTs); - - System.out.println("expected mergedTs = "); - System.out.println(expectedMergedTimeSeries + "\n"); - } - assertEquals(true, mergedTsAndExpectedMergedTsEqual); - - } - - // -------------------------------------------------------------------------------------------------------- - - public void test3HourMerge() { - innerTestMerge(_3HourEndTime, 3, _3HourLookBackWindow, - _cached3HourTimeSeries, _fresh3HourTimeSeries, - _expectedMerged3HourTimeSeries); - - long lastValue = _fresh3HourTimeSeries.getLatestTimeValue(-9999); - long expectedLastValue = DbTimeHelper - .getLongTimeFromDateTimeString("2007-01-02 06:00:00"); - assertEquals(expectedLastValue, lastValue); - } - - // -------------------------------------------------------------------------------------------------------- - - public void testGetNewEndTime() { - innerTestGetNewEndTime("2007-01-01 12:00:00", "2007-01-01 00:00:00", 24); - innerTestGetNewEndTime("2007-01-01 12:00:00", "2007-01-01 03:00:00", 24); - innerTestGetNewEndTime("2007-01-01 12:00:00", "2007-01-01 11:00:00", 24); - innerTestGetNewEndTime("2007-01-02 12:00:00", "2007-01-01 12:00:00", 24); - innerTestGetNewEndTime("2007-01-02 12:00:00", "2007-01-01 13:00:00", 24); - innerTestGetNewEndTime("2007-01-02 12:00:00", "2007-01-01 16:00:00", 24); - } - - // -------------------------------------------------------------------------------------------------------- - - public void innerTestGetNewEndTime(String expectedDateTimeString, - String originalDateTimeString, int timeStepInHours) { - - String header = "PdcMergeTest.innerTestGenNewEndTime(): "; - - long origEndTime = DbTimeHelper - .getLongTimeFromDateTimeString(originalDateTimeString); - long expectedEndTime = DbTimeHelper - .getLongTimeFromDateTimeString(expectedDateTimeString); - - long newEndTime = _dataMgr.getNewEndTime(origEndTime, timeStepInHours); - String newEndDateTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(newEndTime); - - if (expectedEndTime != newEndTime) { - System.out.println(header + "originalDateTimeString = " - + originalDateTimeString + "\n expectedEndTime = " - + expectedDateTimeString + " while the " - + "\n actual new end time is " + newEndDateTimeString); - } - - assertEquals(expectedEndTime, newEndTime); - - } - - public void test24HourMerge() { - innerTestMerge(_24HourEndTime, 24, _24HourLookBackWindow, - _cached24HourTimeSeries, _fresh24HourTimeSeries, - _expectedMerged24HourTimeSeries); - - long lastValue = _fresh24HourTimeSeries.getLatestTimeValue(-9999); - System.out.println("24 hour last value = " - + DbTimeHelper.getDateTimeStringFromLongTime(lastValue)); - long expectedLastValue = DbTimeHelper - .getLongTimeFromDateTimeString("2007-01-11 12:00:00"); - assertEquals(expectedLastValue, lastValue); - } - - // -------------------------------------------------------------------------------------------------------- - - private boolean regularTimeSeriesEqual(RegularObsTimeSeries rts1, - RegularObsTimeSeries rts2) { - boolean result = true; - - List tvpList1 = rts1.getTimeValuePairList(true); - List tvpList2 = rts2.getTimeValuePairList(true); - - // System.out.println("tvpList1.size() = " + tvpList1.size()); - // System.out.println("tvpList2.size() = " + tvpList2.size()); - - // check the sizes - if (tvpList1.size() != tvpList2.size()) { - result = false; - } - - // if that passed, check the individual parts - for (int i = 0; result && i < tvpList1.size(); i++) { - TimeValuePair tvp1 = (TimeValuePair) tvpList1.get(i); - TimeValuePair tvp2 = (TimeValuePair) tvpList2.get(i); - - if (mismatchedNullness(tvp1, tvp2)) { - result = false; - } - - else if ((tvp1 == null) && (tvp2 == null)) { - // System.out.println("tvp 1 and tvp2 are both null "); - ; // do nothing - } - - else if (tvp1 == null) { - // System.out.println("tvp1 is null "); - ; // do nothing - } - - else if (tvp2 == null) { - // System.out.println("tvp2 is null "); - ; // do nothing - } - - else if ((tvp1.getValue() != tvp2.getValue())) { - // System.out.println("tvp 1 = " + tvp1 + " tvp2 = " + tvp2); - result = false; - } - - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - private boolean mismatchedNullness(TimeValuePair tvp1, TimeValuePair tvp2) { - boolean result = false; - - if ((tvp1 == null) && (tvp2 != null)) { - result = true; - } else if ((tvp2 != null) && (tvp2 == null)) { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - - private static TimeValuePair tvp(String dateTimeString, double value) { - long time = DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - return new TimeValuePair(time, value); - - } - - // -------------------------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PdcReadTest.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PdcReadTest.java deleted file mode 100644 index 9bcbf21b2a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PdcReadTest.java +++ /dev/null @@ -1,366 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.List; - -import junit.framework.TestCase; -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PdcReadTest extends TestCase { - Database _db = null; - - private RegularObsTimeSeries _correct3HourTimeSeries = null; - - private RegularObsTimeSeries _correct24HourTimeSeries = null; - - private PDCPreprocessorDataMgr _dataMgr = null; - - private static TimeValuePair[] _3HourCorrectTimeValuePairArray = { - tvp("2007-01-01 00:00:00", 1.0), tvp("2007-01-01 03:00:00", 2.0), - tvp("2007-01-01 06:00:00", 3.0), tvp("2007-01-01 09:00:00", 4.0), - tvp("2007-01-01 12:00:00", 5.0), tvp("2007-01-01 15:00:00", 6.0), - tvp("2007-01-01 18:00:00", 7.0), tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), tvp("2007-01-02 03:00:00", 11.0) }; - - private static TimeValuePair[] _24HourCorrectTimeValuePairArray = { - tvp("2007-01-01 12:00:00", 1.0), tvp("2007-01-02 12:00:00", 2.0), - tvp("2007-01-03 12:00:00", 3.0), tvp("2007-01-04 12:00:00", 4.0), - tvp("2007-01-05 12:00:00", 5.0), tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), tvp("2007-01-08 12:00:00", 8.0), - tvp("2007-01-09 12:00:00", 9.0), tvp("2007-01-10 12:00:00", 10.0) }; - - // 3 hour variables - private long _3HourStartTime = _3HourCorrectTimeValuePairArray[0] - .getDateTime(); - - private String _3HourStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(_3HourStartTime); - - private long _3HourEndTime = _3HourCorrectTimeValuePairArray[9] - .getDateTime(); - - private String _3HourEndTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(_3HourEndTime); - - // 24 hour variables - private long _24HourStartTime = _24HourCorrectTimeValuePairArray[0] - .getDateTime(); - - private String _24HourStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(_24HourStartTime); - - private long _24HourEndTime = _24HourCorrectTimeValuePairArray[9] - .getDateTime(); - - private String _24HourEndTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(_24HourEndTime); - - public PdcReadTest() { - - AppsDefaults ad = AppsDefaults.getInstance(); - - String preprocessedFilePath = ad.getToken("pdc_pp_dir") + "/"; - String logDirName = ad.getToken("pdc_pp_log_dir") + "/"; - - Logger logger = new FileLogger(logDirName + "PdcReadTest.log"); - - String connectionString = "jdbc:postgresql://dx1-nhdr:5432/hd_ob81fwr?user=pguser"; - - _dataMgr = new PDCPreprocessorDataMgr(connectionString, logger, - preprocessedFilePath, 5, 5, true); - - long time = DbTimeHelper - .getLongTimeFromDateTimeString("2007-01-01 12:00:00"); - System.out.println("time = " + time); - - time = DbTimeHelper - .getLongTimeFromDateTimeString(" 2007-01-10 12:00:00"); - System.out.println("time = " + time); - - } - - // -------------------------------------------------------------------------------------------------------- - @Override - protected void setUp() throws Exception { - super.setUp(); - - createCorrectTimeSeries(); - - } - - // -------------------------------------------------------------------------------------------------------- - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor( - String lid, String startTimeString, String endTimeString) { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - descriptor.setLid(lid); - descriptor.setPe("PP"); - descriptor.setDur((short) 1001); - descriptor.setTs("RG"); - descriptor.setExtremum("Z"); - - long startTime = DbTimeHelper - .getLongTimeFromDateTimeString(startTimeString); - descriptor.setStartTime(startTime); - - long endTime = DbTimeHelper - .getLongTimeFromDateTimeString(endTimeString); - descriptor.setEndTime(endTime); - - return descriptor; - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeries createTimeSeries(String lid, - int durationInHours, TimeValuePair[] timeValuePairArray) { - // TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - TimeSlotPolicy timeSlotPolicy = null; - - String startTimeString = null; - String endTimeString = null; - - if (durationInHours == 3) { - startTimeString = _3HourStartTimeString; - endTimeString = _3HourEndTimeString; - } else if (durationInHours == 24) { - startTimeString = _24HourStartTimeString; - endTimeString = _24HourEndTimeString; - } - - RegularObsTimeSeriesDescriptor descriptor = getRegularObsTimeSeriesDescriptor( - lid, startTimeString, endTimeString); - - RegularObsTimeSeries timeSeries = new RegularObsTimeSeries(descriptor, - durationInHours, timeSlotPolicy); - - addPairs(timeValuePairArray, timeSeries); - - return timeSeries; - - } - - // -------------------------------------------------------------------------------------------------------- - - private void addPairs(TimeValuePair[] timeValuePairArray, - RegularObsTimeSeries regularObsTimeSeries) { - for (int i = 0; i < timeValuePairArray.length; i++) { - TimeValuePair tvp = timeValuePairArray[i]; - if (tvp != null) { - regularObsTimeSeries.addTimeValuePairIfBetterMatch(tvp); - } - } - - } - - // -------------------------------------------------------------------------------------------------------- - - private void createCorrectTimeSeries() { - _correct3HourTimeSeries = createTimeSeries("TEST1", 3, - _3HourCorrectTimeValuePairArray); - _correct24HourTimeSeries = createTimeSeries("TEST1", 24, - _24HourCorrectTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - public void innerCFileRead(int timeStepIntervalInHours, int durationCode, - RegularObsTimeSeries correctTimeSeries) { - - long newStartTime = correctTimeSeries.getDescriptor().getStartTime(); - long endTime = correctTimeSeries.getDescriptor().getEndTime(); - - // These lists of time series (plural) will have only 1 time series each - - List readTsList = _dataMgr.readPrecipTimeSeriesListFromCGeneratedFile( - timeStepIntervalInHours, durationCode); - - RegularObsTimeSeries readTs = null; - - for (int i = 0; i < readTsList.size(); i++) { - readTs = (RegularObsTimeSeries) readTsList.get(i); - } - - String lid = readTs.getDescriptor().getLid(); - assertEquals("TEST1", lid); - - boolean readAndCorrectTimeSeriesEqual = regularTimeSeriesEqual(readTs, - correctTimeSeries); - assertEquals(true, readAndCorrectTimeSeriesEqual); - - } - - // -------------------------------------------------------------------------------------------------------- - - public void test3HourRead() { - innerCFileRead(3, 1003, _correct3HourTimeSeries); - } - - // -------------------------------------------------------------------------------------------------------- - - public void test24HourRead() { - innerCFileRead(24, 2001, _correct24HourTimeSeries); - } - - // -------------------------------------------------------------------------------------------------------- - public void testPDCFileRead() { - CodeTimer timer1 = new CodeTimer(); - CodeTimer timer2 = new CodeTimer(); - - String fileName = "/awips/hydroapps/ob82/whfs/local/data/pdc_pp/cached1HourPrecip.dat"; - - timer1.start(); - PDCFileReaderSlow reader1 = new PDCFileReaderSlow(fileName); - List list1 = reader1.read(); - timer1.stop("old PDCFileReaderSlow took"); - - timer2.start(); - PDCFileReader reader2 = new PDCFileReader(fileName); - // reader2.setDebug(true); - List list2 = reader2.read(); - timer2.stop("new PDCFileReaderSlow took"); - - boolean actualResult = listOfRegularTimeSeriesEqual(list1, list2); - - assertEquals(true, actualResult); - - } - - // -------------------------------------------------------------------------------------------------------- - private boolean atLeastOneIsNull(Object object1, Object object2) { - boolean result = false; - - if ((object1 == null) || (object2 == null)) { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - - private boolean bothAreNull(Object object1, Object object2) { - boolean result = false; - - if ((object1 == null) && (object2 == null)) { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - - private boolean listOfRegularTimeSeriesEqual(List list1, List list2) { - boolean result = true; - - if (atLeastOneIsNull(list1, list2)) { - if (bothAreNull(list1, list2)) { - result = true; - } else // they are different - { - result = false; - } - } - - else if (list1.size() != list2.size()) // neither is null - { - result = false; // size is different, the lists are not the same - } - - else // size is same, need to check some more - { - result = true; // assume they are the same. change if proved false - - for (int i = 0; i < list1.size(); i++) { - RegularObsTimeSeries ts1 = (RegularObsTimeSeries) list1.get(i); - RegularObsTimeSeries ts2 = (RegularObsTimeSeries) list2.get(i); - - if (!regularTimeSeriesEqual(ts1, ts2)) { - result = false; // something is different, so the lists are - // not the same - break; - - } - } - - } - - return result; - - } - - // -------------------------------------------------------------------------------------------------------- - - private boolean regularTimeSeriesEqual(RegularObsTimeSeries rts1, - RegularObsTimeSeries rts2) { - boolean result = true; - - List tvpList1 = rts1.getTimeValuePairList(true); - List tvpList2 = rts2.getTimeValuePairList(true); - - // System.out.println("tvpList1.size() = " + tvpList1.size()); - - // check the sizes - if (tvpList1.size() != tvpList2.size()) { - result = false; - } - - // if that passed, check the individual parts - for (int i = 0; result && i < tvpList1.size(); i++) { - TimeValuePair tvp1 = (TimeValuePair) tvpList1.get(i); - TimeValuePair tvp2 = (TimeValuePair) tvpList2.get(i); - - if (mismatchedNullness(tvp1, tvp2)) { - result = false; - } - - else if (tvp1 == null) { - // System.out.print("tvp 1 and tvp2 are both null "); - ; // do nothing - } - - else if ((tvp1.getValue() != tvp2.getValue())) { - // System.out.println("tvp 1 = " + tvp1 + " tvp2 = " + tvp2); - result = false; - } - - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - private boolean mismatchedNullness(TimeValuePair tvp1, TimeValuePair tvp2) { - boolean result = false; - - if ((tvp1 == null) && (tvp2 != null)) { - result = true; - } else if ((tvp2 != null) && (tvp2 == null)) { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - - private static TimeValuePair tvp(String dateTimeString, double value) { - long time = DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - return new TimeValuePair(time, value); - - } - - // -------------------------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PrecipListHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PrecipListHolder.java deleted file mode 100755 index f674749b72..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/PrecipListHolder.java +++ /dev/null @@ -1,85 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.List; - -public class PrecipListHolder -{ - private List _instantPrecipTimeSeriesList; - private List _oneHourPrecipTimeSeriesList; - private List _threeHourPrecipTimeSeriesList; - private List _sixHourPrecipTimeSeriesList; - private List _twentyForHourPrecipTimeSeriesList; - - // -------------------------------------------------------------------------------------- - /** - * @param instantPrecipTimeSeriesList The instantPrecipTimeSeriesList to set. - */ - public void setInstantPrecipTimeSeriesList(List instantPrecipTimeSeriesList) - { - this._instantPrecipTimeSeriesList = instantPrecipTimeSeriesList; - } - /** - * @return Returns the instantPrecipTimeSeriesList. - */ - public List getInstantPrecipTimeSeriesList() - { - return _instantPrecipTimeSeriesList; - } - /** - * @param oneHourPrecipTimeSeriesList The oneHourPrecipTimeSeriesList to set. - */ - public void setOneHourPrecipTimeSeriesList(List oneHourPrecipTimeSeriesList) - { - this._oneHourPrecipTimeSeriesList = oneHourPrecipTimeSeriesList; - } - /** - * @return Returns the oneHourPrecipTimeSeriesList. - */ - public List getOneHourPrecipTimeSeriesList() - { - return _oneHourPrecipTimeSeriesList; - } - /** - * @param threeHourPrecipTimeSeriesList The threeHourPrecipTimeSeriesList to set. - */ - public void setThreeHourPrecipTimeSeriesList(List threeHourPrecipTimeSeriesList) - { - this._threeHourPrecipTimeSeriesList = threeHourPrecipTimeSeriesList; - } - /** - * @return Returns the _3hourPrecipTimeSeriesList. - */ - public List getThreeHourPrecipTimeSeriesList() - { - return _threeHourPrecipTimeSeriesList; - } - /** - * @param sixHourPrecipTimeSeriesList The sixHourPrecipTimeSeriesList to set. - */ - public void setSixHourPrecipTimeSeriesList(List sixHourPrecipTimeSeriesList) - { - this._sixHourPrecipTimeSeriesList = sixHourPrecipTimeSeriesList; - } - /** - * @return Returns the sixHourPrecipTimeSeriesList. - */ - public List getSixHourPrecipTimeSeriesList() - { - return _sixHourPrecipTimeSeriesList; - } - /** - * @param twentyForHourPrecipTimeSeriesList The twentyForHourPrecipTimeSeriesList to set. - */ - public void setTwentyForHourPrecipTimeSeriesList(List twentyForHourPrecipTimeSeriesList) - { - this._twentyForHourPrecipTimeSeriesList = twentyForHourPrecipTimeSeriesList; - } - /** - * @return Returns the twentyForHourPrecipTimeSeriesList. - */ - public List getTwentyFourHourPrecipTimeSeriesList() - { - return _twentyForHourPrecipTimeSeriesList; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeries.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeries.java deleted file mode 100755 index 5cc620b10e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeries.java +++ /dev/null @@ -1,442 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * - * @author Gautam Sood - * - */ -public class RegularObsTimeSeries -{ - - private String _mergerString = null; - - private TimeSlotPolicy _timeSlotPolicy = null; - private RegularObsTimeSeriesDescriptor _obsTimeSeriesDescriptor; - private Map _topOfTheHourTimeValuePairMap = new HashMap(); - private boolean _valuePairListNeedsRefreshing = true; - private List _timeValuePairList = new ArrayList(); -// private List _dateTimeList = new ArrayList(); - private long _timeStepDurationInMillis = 0; //Time in millis between each value - - private static final int MILLIS_PER_HOUR = 60 * 60 * 1000; - -/** - * @param descriptor - RegularObsTimeSeriesDescriptor - * @param timeStepDurationInHours - Time step duration in hours. e.g. hourly timeseries, 6 hourly timeseries, etc - * @param timeSlotPolicy - Hourly or Daily time slot policy - */ - public RegularObsTimeSeries( RegularObsTimeSeriesDescriptor descriptor, long timeStepDurationInHours, TimeSlotPolicy timeSlotPolicy ) - { - _obsTimeSeriesDescriptor = descriptor; - _timeStepDurationInMillis = timeStepDurationInHours * PDCPreprocessorDataMgr.MILLIS_PER_HOUR; - _timeSlotPolicy = timeSlotPolicy; - - setMergerString("UNTOUCHED"); - } - - public RegularObsTimeSeries( RegularObsTimeSeries origTimeSeries) - { - //Note: This is a deep copy, not a shallow one - setObsTimeSeriesDescriptor(new RegularObsTimeSeriesDescriptor(origTimeSeries.getDescriptor()) ); - - _timeSlotPolicy = origTimeSeries._timeSlotPolicy; //immutable object - - Map copiedMap = copyTimeOfTheHourTimeValuePairMap(origTimeSeries.getTopOfTheHourTimeValuePairMap()); - setTopOfTheHourTimeValuePairMap( copiedMap ); - - // setDateTimeList( origTimeSeries.getDateTimeList() ); - _timeStepDurationInMillis = origTimeSeries.getTimeStepIntervalInMillis(); - - setMergerString(origTimeSeries.getMergerString()); - } - - private Map copyTimeOfTheHourTimeValuePairMap(Map origMap) - { - Map map = new HashMap(); - - TimeValuePair origPair = null; - TimeValuePair newPair = null; - - Collection valuesCollection = origMap.values(); - - List valueList = new ArrayList(valuesCollection); - - for (int i = 0; i < valueList.size(); i++) - { - origPair = (TimeValuePair) valueList.get(i); - - newPair = new TimeValuePair(origPair); - map.put( new Long(newPair.getDateTime()), newPair); - - } - return map; - } - - - public String toString() - { - updateTimeValuePairList(); - - StringBuffer stringBuffer = new StringBuffer(); - - stringBuffer.append("Time step = " + _timeStepDurationInMillis/MILLIS_PER_HOUR + " hours: "); - - for ( int i = 0; i < _timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) _timeValuePairList.get( i ); - if (timeValuePair != null) - { - stringBuffer.append(timeValuePair.toString() + '|'); - } - } - return stringBuffer.toString(); - } - - public List getTimeValuePairList( boolean forceRefresh ) - { - if ( ( _valuePairListNeedsRefreshing ) || ( forceRefresh ) ) - { - updateTimeValuePairList(); - } - - return _timeValuePairList; - } - - private void updateTimeValuePairList() - { - String header = "RegularObsTimeSeries.updateTimeValuePairList(): "; - _timeValuePairList.clear(); - long endTime = _obsTimeSeriesDescriptor.getEndTime(); - long startTime = _obsTimeSeriesDescriptor.getStartTime(); - - // System.out.println(header + "startTime = " + startTime + " endTime = " + endTime ); - - for ( long time = startTime; time <= endTime; time+=_timeStepDurationInMillis ) - { - Long dateTimeLong = new Long( time ); - TimeValuePair timeValuePair = (TimeValuePair) _topOfTheHourTimeValuePairMap.get( dateTimeLong ); - - /* - if (timeValuePair == null) - { - System.out.println(header + " value being added is null for desc = " + _obsTimeSeriesDescriptor); - } - */ - - _timeValuePairList.add( timeValuePair ); - - } - - _valuePairListNeedsRefreshing = false; - return; - } - - public void addTimeValuePairIfBetterMatch( TimeValuePair newTimeValuePair ) - { - _valuePairListNeedsRefreshing = true; - - if (_timeSlotPolicy == null) //null is, in effect, a permissive policy, letting everything in - { - Long key = new Long(newTimeValuePair.getDateTime()); - _topOfTheHourTimeValuePairMap.put(key, newTimeValuePair); - } - - else //when you have a real policy - { - Long topOfTheHourKey = _timeSlotPolicy.getSlotDateTimeInMillis(newTimeValuePair.getDateTime()); - - if (topOfTheHourKey != null) - { - _timeSlotPolicy.insertTimeValuePairIfBetterMatch(_topOfTheHourTimeValuePairMap, newTimeValuePair); - } - } - } - - /** - * @param otherTimeSeries - * This method takes the argument's time value pairs and uses them to - * update the current object's _topOfTheHourTimeValuePairMap. - * - */ - public void replaceMatchingTimeValuePairs(RegularObsTimeSeries otherTimeSeries) - { - String header = "RegularObsTimeSeries.replaceMatchingTimeValuePairs(): "; - boolean done = false; - - this._valuePairListNeedsRefreshing = true; - - List otherTimeValuePairList = otherTimeSeries.getTimeValuePairList(true); - if (otherTimeValuePairList == null) - { - System.err.println(header + " ERROR - otherTimeValuePairList is null. "); - done = true; - } - - for (int i = 0; ( !done && (i < otherTimeValuePairList.size()) ); i++) - { - TimeValuePair newTimeValuePair = (TimeValuePair) otherTimeValuePairList.get(i); - Long key = null; - - if (newTimeValuePair != null) - { - key = new Long(newTimeValuePair.getDateTime()); - if (key != null) - { - //if there is a value already here, then replace it - if (this._topOfTheHourTimeValuePairMap.get(key) != null) - { - this._topOfTheHourTimeValuePairMap.put(key, newTimeValuePair); - } - else //value not already present, so leave it alone - { - - } - } - else - { - throw new Error(header + "key is not allowed to be null"); - } - } - - } - - return; - } - - // --------------------------------------------------------------------------------------- - public void replaceNonMatchingTimeValuePairs(RegularObsTimeSeries anotherTimeSeries) - { - String header = "RegularObsTimeSeries.replaceNonMatchingTimeValuePairs(): "; - boolean done = false; - - this._valuePairListNeedsRefreshing = true; - - List otherTimeValuePairList = anotherTimeSeries.getTimeValuePairList(true); - if (otherTimeValuePairList == null) - { - System.err.println(header + " ERROR - otherTimeValuePairList is null. "); - done = true; - } - - for (int i = 0; ( !done && (i < otherTimeValuePairList.size()) ); i++) - { - TimeValuePair newTimeValuePair = (TimeValuePair) otherTimeValuePairList.get(i); - Long key = null; - - if (newTimeValuePair != null) - { - key = new Long(newTimeValuePair.getDateTime()); - if (key != null) - { - //if there is no value already here, then put one in - if (this._topOfTheHourTimeValuePairMap.get(key) == null) - { - this._topOfTheHourTimeValuePairMap.put(key, newTimeValuePair); - } - else //value already present, so leave it alone - { - - } - } - else - { - throw new Error(header + "key is not allowed to be null"); - } - } - - } - - return; - } - - // --------------------------------------------------------------------------------------- - - public void removeTimeValuePairsBefore(long startTime) - { - List keyList = new ArrayList(_topOfTheHourTimeValuePairMap.keySet()); - - //remove any excess Hours from the front of the list. - for (int i = 0; i < keyList.size() ; i++) - { - Object objectKey = keyList.get(i); - - if (objectKey != null) - { - Long key = (Long) objectKey; - - if (key.longValue() < startTime) - { - _topOfTheHourTimeValuePairMap.remove(key); - } - } - - } - _valuePairListNeedsRefreshing = true; - } - - // --------------------------------------------------------------------------------------- - - public void removeTimeValuePairsAfter(long endTime) - { - List keyList = new ArrayList(_topOfTheHourTimeValuePairMap.keySet()); - - //remove any excess Hours from the front of the list. - for (int i = 0; i < keyList.size() ; i++) - { - Object objectKey = keyList.get(i); - - if (objectKey != null) - { - Long key = (Long) objectKey; - - if (key.longValue() > endTime) - { - _topOfTheHourTimeValuePairMap.remove(key); - } - } - - } - _valuePairListNeedsRefreshing = true; - } - - // --------------------------------------------------------------------------------------- - - public long getLatestTimeValue(long badValue) - { - String header = "RegularObsTimeSeries.getLatestTimeValue(): "; - long latestTimeValue = badValue; - List timeValuePairList = getTimeValuePairList(false); - - if (timeValuePairList != null) - { - - if (timeValuePairList.size() > 0) - { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(timeValuePairList.size() - 1); - if (pair != null) - { - latestTimeValue = pair.getDateTime(); - // System.out.println(header + "latestTimeValue = " - // + latestTimeValue); - } - else - { - // System.out.println(header + "latest TimeValuePair is null "); - } - } - else - { - // System.out.println(header + "timeValuePairList.size() == 0 "); - } - } - else - { - // System.out.println(header + "timeValuePairList is null"); - } - - return latestTimeValue; - } - - // --------------------------------------------------------------------------------------- - - public void setObsTimeSeriesDescriptor( RegularObsTimeSeriesDescriptor obsTimeSeriesDescriptor ) - { - _obsTimeSeriesDescriptor = obsTimeSeriesDescriptor; - _valuePairListNeedsRefreshing = true; - } - // --------------------------------------------------------------------------------------- - - public RegularObsTimeSeriesDescriptor getDescriptor() - { - return _obsTimeSeriesDescriptor; - } - // --------------------------------------------------------------------------------------- - public void setStartTime(long startTime) - { - getDescriptor().setStartTime(startTime); - - _valuePairListNeedsRefreshing = true; - - } - // --------------------------------------------------------------------------------------- - - public void setEndTime(long endTime) - { - getDescriptor().setEndTime(endTime); - - _valuePairListNeedsRefreshing = true; - - } - // --------------------------------------------------------------------------------------- - public void setTimeValuePairList( List timeValueList ) - { - _timeValuePairList.addAll( timeValueList ); - } - // --------------------------------------------------------------------------------------- - - public void addTimeValuePairList( List timeValueList ) - { - String header = "RegularObsTimeSeries.addTimeValuePairList(): "; - _valuePairListNeedsRefreshing = true; - for ( int i = 0; i < timeValueList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValueList.get( i ); - // System.out.println(header + " attempting to add timeValuePair = " + timeValuePair ); - addTimeValuePairIfBetterMatch( timeValuePair ); - } - } - // --------------------------------------------------------------------------------------- - - public void setTopOfTheHourTimeValuePairMap( Map topOfTheHourTimeValuePairMap ) - { - _topOfTheHourTimeValuePairMap = topOfTheHourTimeValuePairMap; - } - // --------------------------------------------------------------------------------------- - - public Map getTopOfTheHourTimeValuePairMap() - { - return _topOfTheHourTimeValuePairMap; - } - // --------------------------------------------------------------------------------------- - - // public void setDateTimeList( List dateTimeList ) - // { - // _dateTimeList = dateTimeList; - // } - - // public List getDateTimeList() - // { - // return _dateTimeList; - // } - - /** - * @return Returns the timeStepDurationInMillis. - */ - public long getTimeStepIntervalInMillis() - { - return _timeStepDurationInMillis; - } - - /** - * @param mergerString The mergerString to set. - */ - public void setMergerString(String mergerString) - { - _mergerString = mergerString; - } - - /** - * @return Returns the mergerString. - */ - public String getMergerString() - { - return _mergerString; - } -} \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java deleted file mode 100755 index 872262e228..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java +++ /dev/null @@ -1,23 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Comparator; - -public class RegularObsTimeSeriesComparator implements Comparator -{ - - public int compare(Object object1, Object object2) - { - RegularObsTimeSeries ts1 = (RegularObsTimeSeries) object1; - RegularObsTimeSeries ts2 = (RegularObsTimeSeries) object2; - - RegularObsTimeSeriesDescriptor desc1 = ts1.getDescriptor(); - RegularObsTimeSeriesDescriptor desc2 = ts2.getDescriptor(); - - int returnValue = desc1.toString().compareTo(desc2.toString()); - - return returnValue; - } - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java.new b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java.new deleted file mode 100644 index 701cd81854..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java.new +++ /dev/null @@ -1,63 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Comparator; - -public class RegularObsTimeSeriesComparator implements Comparator -{ - - public int compare(Object object1, Object object2) - { - RegularObsTimeSeries ts1 = (RegularObsTimeSeries) object1; - RegularObsTimeSeries ts2 = (RegularObsTimeSeries) object2; - - RegularObsTimeSeriesDescriptor desc1 = ts1.getDescriptor(); - RegularObsTimeSeriesDescriptor desc2 = ts2.getDescriptor(); - RegularObsTimeSeriesDescriptor first = null; - RegularObsTimeSeriesDescriptor second = null; - - String header = "RegularObsTimeSeriesComparator.compare(): "; - - - int returnValue = desc1.toString().compareTo(desc2.toString()); - - - - if ( - (desc1.getLid().equals("WETO2") || desc1.getLid().equals("ALXO2")) && - (desc2.getLid().equals(desc1.getLid()) ) - ) - { - //System.out.println(header + "desc1 = :" + desc1.toString() + ":"); - //System.out.println(header + "desc2 = :" + desc2.toString() + ":\n"); - - - if (returnValue < 0) - { - first = desc1; - second = desc2; - // System.out.println(header + first.toString() + " comes before " + second.toString()); - } - else if (returnValue > 0) - { - first = desc2; - second = desc1; - // System.out.println(header + first.toString() + " comes before " + second.toString()); - } - else - { - System.out.println(header + " equals " ); - } - - System.out.println(header + "first = :" + first.toString() + ":"); - System.out.println(header + "second = :" + second.toString() + ":\n"); - - - - } - - return returnValue; - } - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesDescriptor.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesDescriptor.java deleted file mode 100755 index db2b253ae2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesDescriptor.java +++ /dev/null @@ -1,252 +0,0 @@ -package ohd.hseb.pdc_pp; - -import ohd.hseb.model.ParamCode; -import ohd.hseb.util.TimeHelper; - -public class RegularObsTimeSeriesDescriptor -{ - private String _lid; - private String _shefParamCodeString; - private ParamCode _paramCode; - private String _pe; - private short _dur; - private String _extremum; - private String _ts; - private long _endTime = 0; - private long _startTime = 0; - private String _outputString = null; - private String _identityString = null; - private int _hashCode = 0; - private boolean _missing = false; - - private boolean _identityChanged = true; // is used to determine whether to recalculate the tostring - - public RegularObsTimeSeriesDescriptor() {} - - public RegularObsTimeSeriesDescriptor( RegularObsTimeSeriesDescriptor descriptor ) - { - _lid = descriptor.getLid(); - _pe = descriptor.getPe(); - _dur = descriptor.getDur(); - _extremum = descriptor.getExtremum(); - _ts = descriptor.getTs(); - _endTime = descriptor.getEndTime(); - _startTime = descriptor.getStartTime(); - - _missing = descriptor._missing; - - - getIdentity(); - - // _identityChanged = descriptor.hasIdentityChanged(); - - // _outputString = descriptor.getOutputString(); - // _hashCode = descriptor._hashCode; - - - } - - - private void getIdentity() - { - if ( _identityChanged ) - { -// computeToString(); -// computeHashCode(); - - _outputString = "lid = " + _lid + - " pe = " + _pe + - " dur = " + _dur + - " extremum = " + _extremum + - " ts = " + _ts; - - _hashCode = _outputString.hashCode(); - - _shefParamCodeString = getPe() + ParamCode.getShefDurationCode(getDur()) + - getTs() + getExtremum(); - - _identityChanged = false; - } - } - - private void getIdentityString() - { - _identityString = _lid + "|" + _pe + "|" + _shefParamCodeString + "|" + _dur + "|" + _extremum + "|" + _ts; - } - - public String toString() - { - getIdentity(); - - return _outputString; - } - - public int hashCode() - { - getIdentity(); - - return _hashCode; - } - -/* - private void computeToString() - { - _outputString = "lid = " + _lid + - " pe = " + _pe + - " shef_param_code = " + _shef_param_code + - " dur = " + _dur + - " extremum = " + _extremum + - " ts = " + _ts; - } - - private void computeHashCode() - { - _hashCode = _outputString.hashCode(); - } - -*/ - public boolean equals( Object object ) - { - RegularObsTimeSeriesDescriptor descriptor = (RegularObsTimeSeriesDescriptor) object; - boolean returnValue = false; - - // if ( this.toString().equals( descriptor.toString() ) ) - if ( _hashCode == descriptor.hashCode()) - { - returnValue = true; - } - else - { - returnValue = false; - } - - return returnValue; - } - - - public String getLid() - { - return _lid; - } - - public String getPe() - { - return _pe; - } - - public short getDur() - { - return _dur; - } - - public String getTs() - { - return _ts; - } - - public String getExtremum() - { - return _extremum; - } - - public String getShef_param_code() - { - getIdentity(); - - return _shefParamCodeString; - } - - public void setLid( String lid ) - { - _lid = lid; - setIdentityChanged( true ); - } - - public void setPe( String pe ) - { - _pe = pe; - setIdentityChanged( true ); - } - - public void setShef_param_code( String shef_param_code ) - { - _shefParamCodeString = shef_param_code; - setIdentityChanged( true ); - } - - public void setDur( short dur ) - { - _dur = dur; - setIdentityChanged( true ); - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - setIdentityChanged( true ); - } - - public void setTs( String ts ) - { - _ts = ts; - setIdentityChanged( true ); - } - - public void setIdentityChanged( boolean valueChanged ) - { - _identityChanged = valueChanged; - } - - public boolean hasIdentityChanged() - { - return _identityChanged; - } - - public void setOutputString( String outputString ) - { - _outputString = outputString; - setIdentityChanged( true ); - } - - public String getOutputString() - { - return _outputString; - } - - public void setEndTime( long endTime ) - { - _endTime = TimeHelper.roundTimeInMillisToNearestHour( endTime ); - } - - public long getEndTime() - { - return _endTime; - } - - public void setStartTime( long startTime ) - { - _startTime = TimeHelper.roundTimeInMillisToNearestHour( startTime ); - } - - public long getStartTime() - { - return _startTime; - } - - /** - * @param missing The missing to set. - */ - public void setMissing(boolean missing) - { - _missing = missing; - } - - /** - * @return Returns the missing. - */ - public boolean isMissing() - { - return _missing; - } -} - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeSeriesListMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeSeriesListMgr.java deleted file mode 100755 index 032509b0ef..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeSeriesListMgr.java +++ /dev/null @@ -1,377 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -//import ohd.hseb.util.CodeTimer; - -public class TimeSeriesListMgr -{ - - final static String INITIAL_MATCH= "NO MATCH"; - final static String REGULAR_MATCH= "Fresh and Cached"; - final static String REGULAR_MATCH_PE_SWITCH= "Fresh and Cached WITH PE swap"; - final static String CACHE_ONLY = "Cache Only"; - final static String FRESH_ONLY = "Fresh Only"; - - - /**The purpose of this class is to group all the methods for handling the List of RegularObsTimeSeries - * It is intended to be called by the PDCPreprocessorDataManager */ -// ------------------------------------------------------------------------- - - public static void setNewStartTime(List timeSeriesList, long newStartTime) - { - - RegularObsTimeSeries timeSeries = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if (timeSeriesList == null) - { - return; - } - - for (int i = 0; i < timeSeriesList.size(); i++) - { - timeSeries = (RegularObsTimeSeries) timeSeriesList.get(i); - - descriptor = timeSeries.getDescriptor(); - descriptor.setStartTime(newStartTime); - - //consider combining this with the setting of the descriptor's starttime, since if they are - // not atomic, bugs could be introduced - timeSeries.removeTimeValuePairsBefore(newStartTime); - } - } - -// ------------------------------------------------------------------------- - - public static List mergeTimeSeriesLists(List freshTimeSeriesList, - List cachedTimeSeriesList, - long newStartTime, - long endTime) - - { - // CodeTimer addTimer = new CodeTimer(); - - String header = "TimeSeriesListMgr.mergeTimeSeriesLists() :"; - List mergedTimeSeriesList = new ArrayList(); - - RegularObsTimeSeries freshTs = null; - RegularObsTimeSeries cachedTs = null; - RegularObsTimeSeries mergedTs = null; - - RegularObsTimeSeriesDescriptor freshTsDesc = null; - - // System.out.println(header + "newStartTime = " + newStartTime); - - if ((freshTimeSeriesList != null) && (cachedTimeSeriesList != null)) - { - //build a map to be used for searching for the matching time series - Map cachedTimeSeriesMap = createTimeSeriesMap(cachedTimeSeriesList); - List unmatchedCachedTimeSeriesDescriptorList = createUnmatchedTimeSeriesDescriptorList(cachedTimeSeriesList); - - // for each time series in list 1, find the matching time series - for (int i = 0; i < freshTimeSeriesList.size(); i++) - { - - freshTs = (RegularObsTimeSeries) freshTimeSeriesList.get(i); - freshTsDesc = freshTs.getDescriptor(); - - // add in the cachedTs data - // mergedTs = copyTimeSeriesWithAdjustedStartTime(freshTs, newStartTime); - mergedTs = freshTs; - mergedTs.setStartTime(newStartTime); - mergedTs.setEndTime(endTime); - - mergedTs.setMergerString(INITIAL_MATCH); - - cachedTs = findMatchingTimeSeries(freshTs, cachedTimeSeriesMap); - - //removed this section, since I won't merge different PE's or TS's - /* - //make a second attempt at retrieving the cached data since the - // pe might have changed from PC to PP or vice versa. - if (cachedTs == null) - { - - String origPe = freshTs.getDescriptor().getPe(); - String newPe = null; - if (origPe.equals("PC")) - { - newPe = "PP"; - } - else if (origPe.equals("PP")) - { - newPe = "PC"; - } - - if (newPe != null) //if performed a swap - { - // System.out.println(header - // + "Swapping PEs for cache search for \nfreshTs Descriptor = " - // + " from " + origPe + " to " + newPe); - freshTs.getDescriptor().setPe(newPe); - cachedTs = findMatchingTimeSeries(freshTs, cachedTimeSeriesMap); - } - } - */ - - // if found matching cached data - if (cachedTs != null) //foundMatching TS - { - mergedTs.setMergerString(REGULAR_MATCH); - - //This cachedTs has been matched with a freshTs, so remove it from the unmatched list - unmatchedCachedTimeSeriesDescriptorList.remove(cachedTs.getDescriptor()); - - mergedTs.replaceNonMatchingTimeValuePairs(cachedTs); - } - else //cachedTs == null //did not find a match - { - - mergedTs.setMergerString(FRESH_ONLY); - - - System.out.println(header - + "ERROR - Could not find a match for the \nfreshTs Descriptor = " - + freshTsDesc); - - } - - // add the merged time series to the list - mergedTimeSeriesList.add(mergedTs); - - - } //end for each freshTimeSeriesList - - - // For each time series that was in the cachedTimeSeriesList, but not in the fresh data time series List, - // trim the times neatly and then let that be the merged list, since there - // really is no merger possible - - RegularObsTimeSeries unmatchedCachedTs = null; - RegularObsTimeSeriesDescriptor unmatchedCachedTsDesc = null; - - // System.out.println(header + "before unmatched ts loop"); - - int matchedIndex = -1; - int size = unmatchedCachedTimeSeriesDescriptorList.size(); - // System.out.println(header + " preparing to loop " + size + " times. "); - - for (int i = 0; i < size ; i++) - { - unmatchedCachedTsDesc = (RegularObsTimeSeriesDescriptor) - unmatchedCachedTimeSeriesDescriptorList.get(i); - unmatchedCachedTs = (RegularObsTimeSeries) cachedTimeSeriesMap.get(unmatchedCachedTsDesc); - - - if (unmatchedCachedTs != null) - { - unmatchedCachedTs.setStartTime(newStartTime); - unmatchedCachedTs.setEndTime(endTime); - unmatchedCachedTs.setMergerString(CACHE_ONLY); - - matchedIndex = addToOrderedMergedTimeSeriesList(unmatchedCachedTs, - mergedTimeSeriesList, - matchedIndex+1); - } - else - { - System.err.println(header + "ERROR unexpectedly null time series"); - } - - } // end for each unmatchedTimeSeries - - } //end if - - else //missing either time series - { - // there is no cached list to merge, so the freshTimeSeries List is expected to contain - // maxHours worth of data . Normally, it will contain less data. - //System.out.println(header + ""); - mergedTimeSeriesList = freshTimeSeriesList; - - } - - return mergedTimeSeriesList; - } - -// ------------------------------------------------------------------------- - private static int addToOrderedMergedTimeSeriesList(RegularObsTimeSeries timeSeries, - List mergedTimeSeriesList, - int startingIndex) - { - String header = "TimeSeriesListMgr.addToOrderedMergedTimeSeriesList(): "; - int matchingIndex = -1; - RegularObsTimeSeries curTs = null; - RegularObsTimeSeriesDescriptor curTsDesc = null; - - RegularObsTimeSeriesDescriptor tsDesc = timeSeries.getDescriptor(); - - boolean inserted = false; - - for (int i = startingIndex; i < mergedTimeSeriesList.size(); i++) - { - curTs = (RegularObsTimeSeries) mergedTimeSeriesList.get(i); - curTsDesc = curTs.getDescriptor(); - - int compareValue = tsDesc.toString().compareTo(curTsDesc.toString()); - - if (compareValue < 0) - { - mergedTimeSeriesList.add(i, timeSeries); - matchingIndex = i; - inserted = true; - break; - } - else if (compareValue == 0) - { - System.out.println(header + "ERROR, the compare value equals 0. Not expected. "); - break; - } - } - - if (! inserted) //either only item in list, or multiple items and it is last - { - mergedTimeSeriesList.add(timeSeries); - matchingIndex = mergedTimeSeriesList.size() - 1; - } - - return matchingIndex; - - } - -// ------------------------------------------------------------------------- - - - private static List createUnmatchedTimeSeriesDescriptorList(List regularObsTimeSeriesList) - { - List newList = new ArrayList(); - - for (int i = 0; (regularObsTimeSeriesList != null ) && i < regularObsTimeSeriesList.size(); i++) - { - RegularObsTimeSeries ts = (RegularObsTimeSeries) regularObsTimeSeriesList.get(i); - RegularObsTimeSeriesDescriptor desc = ts.getDescriptor(); - newList.add(desc); - } - - return newList; - } -// ------------------------------------------------------------------------- - - private static Map createTimeSeriesMap(List regularObsTimeSeriesList) - { - Map newMap = new HashMap(); - - for (int i = 0; (regularObsTimeSeriesList != null ) && i < regularObsTimeSeriesList.size(); i++) - { - RegularObsTimeSeries ts = (RegularObsTimeSeries) regularObsTimeSeriesList.get(i); - newMap.put(ts.getDescriptor(), ts); - } - - return newMap; - } -// ------------------------------------------------------------------------- - private static RegularObsTimeSeries findMatchingTimeSeries(RegularObsTimeSeries tsToFindMatchFor, Map timeSeriesMap) - { - RegularObsTimeSeries foundTs = null; - RegularObsTimeSeriesDescriptor descriptor = null; - RegularObsTimeSeriesDescriptor alteredDescriptorCopy = null; - boolean changedDuration = false; - short previousDuration = -1; - - if (timeSeriesMap != null) - { - descriptor = tsToFindMatchFor.getDescriptor(); - - Object key = null; - - if ( descriptor.getPe().equals("PC")) //need to change the duration to 0 - { - previousDuration = descriptor.getDur(); - changedDuration = true; - descriptor.setDur( (short) 0); - key = descriptor; - - // alteredDescriptorCopy = new RegularObsTimeSeriesDescriptor(descriptor); - // alteredDescriptorCopy.setDur((short)0); - // key = alteredDescriptorCopy; - } - else //everything is normal, no changes needed - { - key = descriptor; - } - - foundTs = (RegularObsTimeSeries) timeSeriesMap.get(key); - - if (changedDuration) - { - descriptor.setDur(previousDuration); - } - } - - return foundTs; - } - -// ------------------------------------------------------------------------- - - private static RegularObsTimeSeries copyTimeSeriesWithAdjustedStartTime(RegularObsTimeSeries origTs, - long newStartTime) - { - String header = "PDCPreprocessorDataMgr.copyTimeSeriesWithAdjustedStartTime(): "; - RegularObsTimeSeries newTs = null; - RegularObsTimeSeriesDescriptor newTsDesc = null; - RegularObsTimeSeriesDescriptor origTsDesc = null; - - origTsDesc = origTs.getDescriptor(); - - - newTs = new RegularObsTimeSeries(origTs); - - /* - if (origTsDesc.getLid().equals("KERO2") - && origTsDesc.getPe().equals("PC")) - { - System.out.println("***************************************"); - System.out.println(header + "after copying \n" - + "\n origTimeSeries = " + origTs + "\n newTimeSeries = " - + newTs); - } - */ - // adjust the start time of the mergedTs so that it goes back as far as - // we want it to - long endTime = origTsDesc.getEndTime(); - - - newTsDesc = newTs.getDescriptor(); - newTsDesc.setStartTime(newStartTime); - newTsDesc.setEndTime(endTime); - - /* - if (origTsDesc.getLid().equals("KERO2") - && origTsDesc.getPe().equals("PC")) - { - System.out.println(header + "after changing start and end times \n" - + "\n origTimeSeries = " + origTs + "\n newTimeSeries = " - + newTs); - - System.out.println(header + "\nold startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(origTsDesc.getStartTime()) + - "\nold EndTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(origTsDesc.getEndTime()) + - "\nnew startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(newStartTime) + - "\nnew endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - System.out.println("***************************************"); - - } -*/ - - return newTs; - } - -// ------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeSlotPolicy.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeSlotPolicy.java deleted file mode 100755 index 3b2a1b11cd..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeSlotPolicy.java +++ /dev/null @@ -1,12 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Map; - -public interface TimeSlotPolicy -{ - - public Long getSlotDateTimeInMillis( long originalDateTimeInMillis ); - - public void insertTimeValuePairIfBetterMatch( Map timeValuePairHashMap, TimeValuePair timeValuePair ); - -} \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeValuePair.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeValuePair.java deleted file mode 100755 index a7962da642..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/TimeValuePair.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.pdc_pp; - -import ohd.hseb.db.DbTimeHelper; - -public class TimeValuePair -{ - private long _dateTime = 0; - private double _value = 0.0; - private boolean _isMissing = true; - - public TimeValuePair( long dateTime, double value ) - { - _dateTime = dateTime; - _value = value; - _isMissing = false; - } - - public TimeValuePair( long dateTime ) - { - _dateTime = dateTime; - _isMissing = true; - } - - public TimeValuePair( TimeValuePair timeValuePair ) - { - this(timeValuePair.getDateTime(), timeValuePair.getValue() ); - // _dateTime = timeValuePair.getDateTime(); - // _value = timeValuePair.getValue(); - } - - public String toString() - { - String string = DbTimeHelper.getDateTimeStringFromLongTime( _dateTime ) + "," + _value; -// String string = _value + " "; - - return string; - } - - public boolean isMissingValue() - { - boolean returnValue = false; - - if ( _value == PDCPreprocessorDataMgr.MISSING ) - { - returnValue = true; - } - - return returnValue; - } - - public void setDateTime( long dateTime ) - { - _dateTime = dateTime; - } - - public long getDateTime() - { - return _dateTime; - } - - public void setValue( double value ) - { - _value = value; - } - - public double getValue() - { - return _value; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/sample_data_set/CreateSampleDataSet.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/sample_data_set/CreateSampleDataSet.java deleted file mode 100644 index b3bd77edad..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/sample_data_set/CreateSampleDataSet.java +++ /dev/null @@ -1,84 +0,0 @@ -package ohd.hseb.pdc_pp.sample_data_set; - -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -public class CreateSampleDataSet -{ - private SampleDataSetCreatorDataMgr _dataMgr = null; - private boolean _createData = true; - - public CreateSampleDataSet() - { - - } - - /** - * initialize( String[] args ) - Used to process the command line arguments and set appropriate variables. - * @param args - Command line arguments - */ - private void initialize( String[] args ) - { - StringBuffer baseConnectionStringBuffer = new StringBuffer(); //gotten from the command line - StringBuffer logDirName = new StringBuffer(); - String logFileName = null; - Logger logger = null; - - processCommandLineArguments( baseConnectionStringBuffer, logDirName, args ); - - logFileName = logDirName + "/SampleDataSetCreator.log"; - - logger = new FileLogger(logFileName, true, true); - - _dataMgr = new SampleDataSetCreatorDataMgr(baseConnectionStringBuffer.toString(), logger ); - if ( _createData ) - { - _dataMgr.create_test_location(); - _dataMgr.create_test_data(); - } - else - { - _dataMgr.removeAllData(); - } - } - - /** - * - * @param baseConnectionStringBuffer - Postgres database connection string - * @param logDirName - Directory where the log file will be created - * @param args - Command line arguments - */ - private void processCommandLineArguments( StringBuffer baseConnectionStringBuffer, - StringBuffer logDirName, String[] args ) - { - if ( args.length < 2 ) - { - System.err.println("Usage: ohd.hseb.PDCPreprocessor.sample_data_set.CreateSampleDataSet connection_string logFileDir "); - System.exit(0); - } - - if ( args.length == 3 ) - { - if ( args[2].equalsIgnoreCase( "true" ) ) - { - _createData = true; - } - else - { - _createData = false; - } - } - - baseConnectionStringBuffer.append( args[0] ); - logDirName.append( args[1] ); - } - - public static void main( String[] args ) - { - CreateSampleDataSet dataCreator = new CreateSampleDataSet(); - - dataCreator.initialize( args ); - - - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/sample_data_set/SampleDataSetCreatorDataMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/sample_data_set/SampleDataSetCreatorDataMgr.java deleted file mode 100644 index 0aebdc8b10..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/pdc_pp/sample_data_set/SampleDataSetCreatorDataMgr.java +++ /dev/null @@ -1,871 +0,0 @@ -package ohd.hseb.pdc_pp.sample_data_set; - -import java.sql.SQLException; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.CurPCRecord; -import ohd.hseb.ihfsdb.generated.CurPCTable; -import ohd.hseb.ihfsdb.generated.CurPPRecord; -import ohd.hseb.ihfsdb.generated.CurPPTable; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.LakeRecord; -import ohd.hseb.ihfsdb.generated.LakeTable; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.SnowRecord; -import ohd.hseb.ihfsdb.generated.SnowTable; -import ohd.hseb.ihfsdb.generated.StnClassRecord; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.ihfsdb.generated.TemperatureRecord; -import ohd.hseb.ihfsdb.generated.TemperatureTable; -import ohd.hseb.ihfsdb.generated.WeatherRecord; -import ohd.hseb.ihfsdb.generated.WeatherTable; -import ohd.hseb.ihfsdb.generated.WindRecord; -import ohd.hseb.ihfsdb.generated.WindTable; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -public class SampleDataSetCreatorDataMgr -{ - private Database _db = null; - private Logger _logger = null; - private static String OS = System.getProperty("os.name").toLowerCase(); - private String _connectionString = null; - private long _endTime = System.currentTimeMillis(); - private long _TOTHEndTime = TimeHelper.roundTimeInMillisToNearestHour( _endTime ); - private long _startTime = _TOTHEndTime - ( 24 * TimeHelper.MILLIS_PER_HOUR ); - private String _lid1 = "1PDC1"; - private String _lid2 = "1PDC2"; - - public SampleDataSetCreatorDataMgr( String baseConnectionString, Logger logger ) - { - super(); - - _db = new Database(); - _logger = logger; - - if ( baseConnectionString == null ) - { - baseConnectionString = getBaseConnectionString(); - } - _connectionString = baseConnectionString; - _db.connectWithDriverSearch( _connectionString ); - } - - public void create_test_location() - { - LocationRecord locationRecord1 = new LocationRecord(); - LocationRecord locationRecord2 = new LocationRecord(); - StnClassRecord stnClassRecord1 = new StnClassRecord(); - StnClassRecord stnClassRecord2 = new StnClassRecord(); - RiverstatRecord riverStatRecord1 = new RiverstatRecord(); - RiverstatRecord riverStatRecord2 = new RiverstatRecord(); - RatingRecord ratingRecord1 = new RatingRecord(); - RatingRecord ratingRecord2 = new RatingRecord(); - RatingTable ratingTable = new RatingTable( _db ); - LocationTable locationTable = new LocationTable( _db ); - StnClassTable stnClassTable = new StnClassTable( _db ); - RiverstatTable riverstatTable = new RiverstatTable( _db ); - List recordList = null; - - locationRecord1.setLid( _lid1 ); - locationRecord1.setCounty( "BRYAN" ); - locationRecord1.setDetail( "1 W" ); - locationRecord1.setElev( 503 ); - locationRecord1.setHsa( "OUN" ); - locationRecord1.setLat( 32.34343456 ); - locationRecord1.setLon( 97.232341123 ); - locationRecord1.setLremark( "US HWY 70 NR LT BANK ON DS SIDE OF BRIDGE OVER BLUE RIVER, 1 MI. W OF BLUE, OK AND 8 MI. E OF DURANT, OKDURANT/BRYAN COUNTY CEMA IS BACKUP OBSERVER TO DCP" ); - locationRecord1.setLrevise( System.currentTimeMillis() ); - locationRecord1.setName( "PDC Test Site 1" ); - locationRecord1.setNetwork( "B" ); - locationRecord1.setRb( "RED 3" ); - locationRecord1.setRfc( "ABRFC" ); - locationRecord1.setState( "OK" ); - locationRecord1.setWfo( "OUN" ); - locationRecord1.setTzone( "MST7" ); - stnClassRecord1.setLid( _lid1 ); - stnClassRecord1.setDisp_class( "RPTO" ); - stnClassRecord1.setDcp( "T" ); - stnClassRecord1.setObserver( "T" ); - stnClassRecord1.setTelem_type( "NONE" ); - riverStatRecord1.setLid( _lid1 ); - riverStatRecord1.setFq( 42000 ); - riverStatRecord1.setFs( 22 ); - ratingRecord1.setLid( _lid1 ); - - - locationRecord2.setLid( _lid2 ); - locationRecord2.setCounty( "BRYAN" ); - locationRecord2.setDetail( "1 W" ); - locationRecord2.setElev( 503 ); - locationRecord2.setHsa( "OUN" ); - locationRecord2.setLat( 30.34343456 ); - locationRecord2.setLon( 99.232341123 ); - locationRecord2.setLremark( "US HWY 70 NR LT BANK ON DS SIDE OF BRIDGE OVER BLUE RIVER, 1 MI. W OF BLUE, OK AND 8 MI. E OF DURANT, OKDURANT/BRYAN COUNTY CEMA IS BACKUP OBSERVER TO DCP" ); - locationRecord2.setLrevise( System.currentTimeMillis() ); - locationRecord2.setName( "PDC Test Site 2" ); - locationRecord2.setNetwork( "B" ); - locationRecord2.setRb( "RED 3" ); - locationRecord2.setRfc( "ABRFC" ); - locationRecord2.setState( "OK" ); - locationRecord2.setWfo( "OUN" ); - locationRecord2.setTzone( "MST7" ); - stnClassRecord2.setLid( _lid2 ); - stnClassRecord2.setDisp_class( "RPTO" ); - stnClassRecord2.setDcp( "T" ); - stnClassRecord2.setObserver( "T" ); - stnClassRecord2.setTelem_type( "NONE" ); - riverStatRecord2.setLid( _lid2 ); - riverStatRecord2.setFq( 5750 ); - riverStatRecord2.setFs( 25 ); - ratingRecord2.setLid( _lid2 ); - - - try - { - recordList = locationTable.select( "WHERE LID = '" + _lid1 + "' or LID = '" + _lid2 + "' " ); - - if ( recordList.size() == 0 ) - { - System.out.println( "Inserting Location/StnClass/Riverstat/Rating records for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - locationTable.insert( locationRecord1 ); - locationTable.insert( locationRecord2 ); - stnClassTable.insert( stnClassRecord1 ); - stnClassTable.insert( stnClassRecord2 ); - riverstatTable.insert( riverStatRecord1 ); - riverstatTable.insert( riverStatRecord2 ); - for ( double i = 0; i < 5.0; i+=0.1 ) - { - ratingRecord1.setStage( i ); - ratingRecord1.setDischarge( i*1.5 ); - ratingTable.insert( ratingRecord1 ); - } - - for ( double i = 0; i < 5.0; i+=0.2 ) - { - ratingRecord2.setStage( i ); - ratingRecord2.setDischarge( i*2.5 ); - ratingTable.insert( ratingRecord2 ); - } - } - else - { - System.out.println( "Test locations already exist in the Location/StnClass/Riverstat/Rating tables...\n" + - "Removing and reinserting Location/StnClass/Riverstat/Rating records for locations " + - "\"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - ratingTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - riverstatTable.delete( riverStatRecord1 ); - riverstatTable.delete( riverStatRecord2 ); - stnClassTable.delete( stnClassRecord1 ); - stnClassTable.delete( stnClassRecord2 ); - locationTable.delete( locationRecord1 ); - locationTable.delete( locationRecord2 ); - locationTable.insert( locationRecord1 ); - locationTable.insert( locationRecord2 ); - stnClassTable.insert( stnClassRecord1 ); - stnClassTable.insert( stnClassRecord2 ); - riverstatTable.insert( riverStatRecord1 ); - riverstatTable.insert( riverStatRecord2 ); - for ( double i = 0; i < 5.0; i+=0.1 ) - { - ratingRecord1.setStage( i ); - ratingRecord1.setDischarge( i*1.5 ); - ratingTable.insert( ratingRecord1 ); - } - - for ( double i = 0; i < 5.0; i+=0.2 ) - { - ratingRecord2.setStage( i ); - ratingRecord2.setDischarge( i*2.5 ); - ratingTable.insert( ratingRecord2 ); - } - } - } - catch (SQLException e ) - { - e.printStackTrace(); - } - } - - public void create_test_data() - { - deleteTestData(); - createHeightData(); - createTemperatureData(); - createWindData(); - createSnowData(); - createWeatherData(); - createLakeData(); - createDischargeData(); - createPCData(); - createPPData(); - } - - public void removeAllData() - { - RatingTable ratingTable = new RatingTable( _db ); - LocationTable locationTable = new LocationTable( _db ); - StnClassTable stnClassTable = new StnClassTable( _db ); - RiverstatTable riverstatTable = new RiverstatTable( _db ); - - System.out.println( "Deleting data from the Location/Riverstat/StnClass/Rating tables" ); - deleteTestData(); - try - { - ratingTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - stnClassTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - riverstatTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - locationTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - } - catch (SQLException e ) - { - e.printStackTrace(); - } - } - private void deleteTestData() - { - HeightTable heightTable = new HeightTable( _db ); - TemperatureTable tempTable = new TemperatureTable( _db ); - WindTable windTable = new WindTable( _db ); - SnowTable snowTable = new SnowTable( _db ); - WeatherTable weatherTable = new WeatherTable( _db ); - LakeTable lakeTable = new LakeTable( _db ); - DischargeTable dischargeTable = new DischargeTable( _db ); - CurPCTable curPCTable = new CurPCTable( _db ); - CurPPTable curPPTable = new CurPPTable( _db ); - System.out.println( "Clearing out old test data" ); - try - { - heightTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - tempTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - windTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - snowTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - weatherTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - lakeTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - dischargeTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - curPCTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - curPPTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - } - - private void createHeightData() - { - System.out.println( "Inserting test Height data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - HeightRecord record = new HeightRecord(); - HeightTable heightTable = new HeightTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "HG" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "HG" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - heightTable.insert( record ); - record.setPe( "HP" ); - record.setValue( value*1000 ); - heightTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "HG" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - heightTable.insert( record ); - record.setPe( "HP" ); - record.setValue( value*1000 ); - heightTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createTemperatureData() - { - System.out.println( "Inserting test Temperature data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - TemperatureRecord record = new TemperatureRecord(); - TemperatureTable temperatureTable = new TemperatureTable( _db ); - short dur = 1001; - short revision = 0; - double value = 50.0; - - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "TA" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = ( _startTime - 24 * TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setExtremum( "Z" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - temperatureTable.insert( record ); - if ( indexTime == _startTime ) - { - record.setExtremum( "N" ); - temperatureTable.insert( record ); - } - if ( indexTime == _TOTHEndTime ) - { - record.setExtremum( "X" ); - temperatureTable.insert( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 1; - } - - value = 2; - - record.setPe( "TD" ); - - for ( long indexTime = _startTime-(24*TimeHelper.MILLIS_PER_HOUR); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setValue( value ); - try - { - record.setObstime( indexTime ); - temperatureTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value++; - } - - record.setPe( "TA" ); - record.setLid( _lid2 ); - value = 60; - - for ( long indexTime = ( _startTime - 24 * TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setExtremum( "Z" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - temperatureTable.insert( record ); - if ( indexTime == _startTime ) - { - record.setExtremum( "N" ); - temperatureTable.insert( record ); - } - if ( indexTime == _TOTHEndTime ) - { - record.setExtremum( "X" ); - temperatureTable.insert( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 2; - } - - value = 2; - - record.setPe( "TD" ); - for ( long indexTime = _startTime-(24*TimeHelper.MILLIS_PER_HOUR); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setValue( value ); - record.setObstime( indexTime ); - try - { - temperatureTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 2; - } - - } - - private void createWindData() - { - System.out.println( "Inserting test Wind data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - WindRecord record = new WindRecord(); - WindTable windTable = new WindTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "US" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "US" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - record.setPe( "UD" ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "US" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - record.setPe( "UD" ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createSnowData() - { - System.out.println( "Inserting test Snow data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - SnowRecord record = new SnowRecord(); - SnowTable snowTable = new SnowTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "SW" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = ( _startTime - 24*TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - snowTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = ( _startTime - 24*TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - snowTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createWeatherData() - { - System.out.println( "Inserting test Weather data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - WeatherRecord record = new WeatherRecord(); - WeatherTable weatherTable = new WeatherTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "XR" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - weatherTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - weatherTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createLakeData() - { - System.out.println( "Inserting test Lake data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - LakeRecord record = new LakeRecord(); - LakeTable lakeTable = new LakeTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "LS" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - lakeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - lakeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createDischargeData() - { - System.out.println( "Inserting test Discharge data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - DischargeRecord record = new DischargeRecord(); - DischargeTable dischargeTable = new DischargeTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "QR" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "QR" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - dischargeTable.insert( record ); - record.setPe( "QT" ); - dischargeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "QR" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - dischargeTable.insert( record ); - record.setPe( "QT" ); - dischargeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createPCData() - { - System.out.println( "Inserting test PC data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - CurPCRecord record = new CurPCRecord(); - CurPCTable curPCTable = new CurPCTable( _db ); - short dur = 0; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "PC" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPCTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPCTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createPPData() - { - System.out.println( "Inserting test PP data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - CurPPRecord record = new CurPPRecord(); - CurPPTable curPPTable = new CurPPTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "PP" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPPTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPPTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - } - } - - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - private void logException( Exception exception ) - { - _logger.log( "ERROR = " + - exception.getMessage() ); - exception.printStackTrace( _logger.getPrintWriter() ); - - _logger.log( "End of stack trace" ); - } - - private String getBaseConnectionString() - { - //this is used in testing mode, not the production mode - String connectionURLPart = "jdbc:postgresql://dx1-nhdr:5432/hd_ob7ounx?user=pguser"; - return connectionURLPart; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/prism/Converter.java b/cave/ohd.hseb.common/src/ohd/hseb/prism/Converter.java deleted file mode 100644 index 5d58dc236a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/prism/Converter.java +++ /dev/null @@ -1,47 +0,0 @@ -package ohd.hseb.prism; - -// import ohd.hseb.prism.*; - -public class Converter implements MPEConstants -{ - static public class HrapPoint - { - private double hrap_row; - private double hrap_col; - - public double getHrapRow ( ) - { - return hrap_row; - } - - public double getHrapCol ( ) - { - return hrap_col; - } - } - - static public HrapPoint convertLatLonToHrap ( double longitude, - double latitude ) - { - double r; - HrapPoint hrap_point = new HrapPoint ( ); - - latitude *= D2RAD; - longitude = ( longitude + 180.0 - REF_LON ) * D2RAD; - r = RE * Math.cos (latitude)/(1.0 + Math.sin(latitude)); - hrap_point.hrap_col = r * Math.sin(longitude); - hrap_point.hrap_row = r * Math.cos(longitude); - hrap_point.hrap_col += HRAP_BASE_COL; - hrap_point.hrap_row += HRAP_BASE_ROW; - - return hrap_point; - } - - static public void main ( String args [ ] ) - { - HrapPoint hrap = convertLatLonToHrap ( 100.63, 33.48 ); - - System.out.println ( "Row: " + hrap.hrap_row ); - System.out.println ( "Col: " + hrap.hrap_col ); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/prism/GeoData.java b/cave/ohd.hseb.common/src/ohd/hseb/prism/GeoData.java deleted file mode 100644 index 2b2160cdd3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/prism/GeoData.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Created on August 25, 2005 - * - */ - -/** - * @author Bryon Lawrence - * - * This retrieves the contents of the coord_xxxx.dat file. - * For a RFC, xxxx is the name of the office. For a WFO, - * xxxx is 'host'. - */ -package ohd.hseb.prism; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class GeoData { - - static private String _filepath; - - private int _southwest_column = -1; - - private int _southwest_row = -1; - - private int _number_of_columns = -1; - - private int _number_of_rows = -1; - - // Static initializer - static { - build_filepath(); - } - - static private void build_filepath() { - String office_name = ""; - String geo_data_dir = ""; - AppsDefaults apps_defaults = AppsDefaults.getInstance(); - - office_name = apps_defaults.getToken("st3_rfc"); - geo_data_dir = apps_defaults.getToken("geo_data"); - - _filepath = geo_data_dir + "/" + office_name + "/ascii/coord_" - + office_name + ".dat"; - } - - private void read_geo_data() throws IOException { - BufferedReader _reader = new BufferedReader(new FileReader(_filepath)); - _southwest_column = Integer.parseInt(_reader.readLine()); - _southwest_row = Integer.parseInt(_reader.readLine()); - _number_of_columns = Integer.parseInt(_reader.readLine()); - _number_of_rows = Integer.parseInt(_reader.readLine()); - - } - - public int getSouthwestColumn() { - return _southwest_column; - } - - public int getSouthwestRow() { - return _southwest_row; - } - - public int getNumColumns() { - return _number_of_columns; - } - - public int getNumRows() { - return _number_of_rows; - } - - static public String getFilePath() { - return _filepath; - } - - GeoData() throws IOException { - read_geo_data(); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/prism/MPEClimo.java b/cave/ohd.hseb.common/src/ohd/hseb/prism/MPEClimo.java deleted file mode 100644 index 2bea85fee7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/prism/MPEClimo.java +++ /dev/null @@ -1,397 +0,0 @@ -package ohd.hseb.prism; - -import java.io.IOException; - -import ohd.hseb.util.CodeTimer; - -/** - * @author Bryon Lawrence - * March 8, 2006 - * - * This program crops a national PRISM file to the size of an office's MPE area. - * It stores this cropped PRISM product as an XMRG file which can be read and - * displayed by MPE Editor. This program replaces the create_prism program. - * - * The arguments to this program are: - * - * "prefix_of_input_prism_file" "prefix_of_output_prism_file" - * - * The input prism files are assumed to have a suffix of _MM where MM is the - * two digit month number. - * - * 01 January - * 02 February - * 03 March - * 04 April - * 05 May - * 06 June - * 07 July - * 08 August - * 09 September - * 10 October - * 11 November - * 12 December - * - * A suffix of _MMM is placed on each output XMRG PRISM file. The MMM is the 3 - * character month abbreviation: - * - * jan January - * feb February - * mar March - * apr April - * may May - * jun June - * jul July - * aug August - * sep September - * oct October - * nov November - * dec December - * - * An optional third argument indicates whether a precipitation or temperature - * prism file is being. "p" indicates a precipitation file. "t" indicates a - * temperature file. If this argument is omitted, then a precipitation file is - * assumed. - * - * The tokens input_prism_dir and output_prism_dir define the directories - * of the input PRISM files and the output cropped XMRG files. If these are not - * set, then this program will look for the prism files in the current working - * directory. - * - * This program expects there to be 13 raw prism files in the directory specified by - * input_prism_dir. These include 12 monthly files and 1 annual prism file. - * This program will produce 13 XMRG files corresponding to the 13 input files. - * - * Example of usage: - * - * export prism_input_dir=/fs/hseb/whfs/site_data/mpe_data/PRISM - * export prism_output_dir=/awips/hydroapps/precip_proc/local/data/app/mpe/prism - * - * java MPEClimo us_tmin prism_min_temp_ounx t - * - * This will look for raw prism files in the /fs/hseb/whfs/site_data/mpe_data/PRISM - * directory for the following files: - * - * us_tmin_01 us_tmin_04 us_tmin_07 us_tmin_10 us_tmin_14 - * us_tmin_02 us_tmin_05 us_tmin_08 us_tmin_11 - * us_tmin_03 us_tmin_06 us_tmin_09 us_tmin_12 - * - * It will create the following output files in the - * /awips/hydroapps/precip_proc/local/data/app/mpe/PRISM directory: - * - * prism_min_temp_ounx_jan prism_min_temp_ounx_aug - * prism_min_temp_ounx_feb prism_min_temp_ounx_sep - * prism_min_temp_ounx_mar prism_min_temp_ounx_oct - * prism_min_temp_ounx_apr prism_min_temp_ounx_nov - * prism_min_temp_ounx_may prism_min_temp_ounx_dec - * prism_min_temp_ounx_jun prism_min_temp_ounx_ann - * prism_min_temp_ounx_jul - * - * The "t" argument specifies this is by default - */ - -public class MPEClimo implements MPEConstants -{ - - static private boolean temperature_prism_flag = false; - static private double scale_factor = 1.0; - - static public double[][] cropPrismToHrapGrid ( Prism prism, - int southwest_column, - int southwest_row, - int number_columns, - int number_rows ) - { - double latitude_upper_left; - double col_longitude; - double row_latitude ; - double cellsize = prism.getCellSize ( ); - double latitude_lower_left = prism.getSouthWestLat ( ); - double longitude_lower_left = prism.getSouthWestLong ( ); - double precip[][] = new double [ number_columns ] [ number_rows ]; - Converter.HrapPoint hrap_point; - int count [][] = new int [ number_columns ] [ number_rows ]; - int hrap_row; - int hrap_col; - int num_prism_cols = prism.getNumColumns ( ); - int num_prism_rows = prism.getNumRows ( ); - int prism_data [ ][ ] = prism.getPrism ( ); - int prism_nodata = prism.getNoDataVal ( ); - - // Initialize the count and precipitation arrays to 0. - for ( int col = 0; col < number_columns; ++ col ) - { - for ( int row =0; row < number_rows; ++ row ) - { - count [ col ] [ row ] = 0; - precip [ col ] [ row ] = 0.0; - } - } - - // Get the latitude of the upperleft corner. - latitude_upper_left = latitude_lower_left + cellsize * num_prism_rows; - - // Process data row by row. - for ( int row = 0; row < num_prism_rows; ++row ) - { - row_latitude = latitude_upper_left - ( ( row - 0.5 ) * cellsize ); - - for ( int col = 0; col < num_prism_cols; ++col ) - { - if ( prism_data [ row ][ col ] != -9999 ) - { - col_longitude = longitude_lower_left + - ( ( col - 0.5 ) * cellsize ); - col_longitude = - col_longitude; - - hrap_point = Converter.convertLatLonToHrap ( col_longitude, - row_latitude ); - hrap_row = (int)hrap_point.getHrapRow ( ); - hrap_col = (int)hrap_point.getHrapCol ( ); - - hrap_row -= southwest_row; - hrap_col -= southwest_column; - - if ( ( hrap_row >= 0 ) && - ( hrap_row < number_rows ) && - ( hrap_col >= 0 ) && - ( hrap_col < number_columns ) ) - { - count [ hrap_col ] [ hrap_row ] ++; - precip [ hrap_col ][ hrap_row ] += prism_data [ row ] [ col ]; - } - } - } - } - - /* Compute the average. */ - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - if ( count [ col ][ row ] == 0 ) - { - precip [ col ] [ row ] = MISSING; - } - else - { - precip [ col ] [ row ] = precip [ col ] [ row ]/ - count [ col ] [ row ]; - } - } - } - - // Fill in any holes in the data. - double sum; - int col_begin = 0; - int col_end = 0; - int num = 0; - int row_begin = 0; - int row_end = 0; - - for ( int row = 0; row < number_rows; ++ row ) - { - row_begin = row - 1 ; - - if ( row_begin < 0 ) row_begin = 0; - - row_end = row + 1; - - if ( row_end == number_rows ) row_end = row; - - for ( int col = 0; col < number_columns; ++ col ) - { - if ( count [ col ] [ row ] == 0 ) - { - col_begin = col - 1; - if ( col_begin < 0 ) col_begin = 0; - - col_end = col + 1; - - if ( col_end == number_columns ) col_end = col; - - num = 0; - sum = 0.0; - - for ( int row_fill = row_begin; row_fill <= row_end; - ++row_fill ) - { - for ( int col_fill = col_begin; col_fill <= col_end; - ++ col_fill ) - { - if ( count [ col_fill ] [ row_fill ] > 0 ) - { - ++num; - sum += precip [ col_fill ] [ row_fill ]; - } - } - } - - if ( num == 0 ) - { - precip [ col ] [ row ] = MISSING; - } - else - { - precip [ col ] [ row ] = sum / num; - } - } - } - - } - - // If processing temperature data, convert them from Celcius to - // Fahrenheit. - if ( temperature_prism_flag ) - { - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - if ( precip [ col ] [ row ] != MISSING ) - { - precip [ col ] [ row ] /= 100.0 ; - - // Convert from Celcius to Fahrenheit - precip [col][row] = ( precip [col][row] * 1.8 ) + 32; - } - } - } - } - else - { - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - precip [ col ] [ row ] /= 100.0 ; - } - } - } - - return precip; - } - - /* - * The Main Routine for MPE Climo. - */ - static public void main ( String args [ ] ) - { - double precip [ ][ ]; - GeoData geo_data; - final String month_array [ ] = new String [ ] { "01", "02", "03", "04", - "05", "06", "07", "08", "09", "10", - "11", "12", "14" }; - final String month_name_array [ ] = new String [ ] {"jan", "feb", "mar", - "apr", "may", "jun", - "jul", "aug", "sep", - "oct", "nov", "dec", - "ann" }; - int southwest_column; - int southwest_row; - int number_columns; - int number_rows; - - Prism prism; - String prism_output_path = Prism.getOutputFilePath ( ); - String file; - - // The user must supply the prefix of the national prism file. The - // national prism file is assumed to end with the month number. For example - // 01 like us_tmin_01 - // The user must also supply the file name prefix of the cropped, output - // Prism file. - - if (args.length < 2 ) - { - System.out.println( "Must provide the prefix of the input prism file"); - System.out.println( "and the cropped, output prism file."); - System.out.print ( "Usage: MPEclimo input_prism_file_prefix "); - System.out.println ("output_prism_file_prefix "); - System.exit(1); - } - - // The user may suppy a flag indicating whether temperature or - // precipitation PRISM xmrg files are to be created. - if ( args.length == 3 ) - { - if ( args [ 2 ].charAt(0) == 't' || args [ 1 ].charAt(0) == 'T') - { - temperature_prism_flag = true; - - // The scale factor for precipitation data is 1.0. - // The scale factor for temperature data is 10.0. - scale_factor = 10.0; - } - } - - // Read the coordinates of the MPE forecast area the - // PRISM data will be cropped to. - try - { - geo_data = new GeoData ( ); - southwest_column = geo_data.getSouthwestColumn ( ); - southwest_row = geo_data.getSouthwestRow ( ); - number_columns = geo_data.getNumColumns ( ); - number_rows = geo_data.getNumRows ( ); - - System.out.println ( "South West Column: " + southwest_column ); - System.out.println ( "South West Row: " + southwest_row ); - System.out.println ( "Number of Columns: " + number_columns ); - System.out.println ( "Number of Rows: " + number_rows ); - - prism = new Prism ( ); - - /* Start a timer. This will show how much time is spent - * reading the prism data. - */ - CodeTimer totalTime = new CodeTimer (); - totalTime.start(); - - for ( int month = 0; month < month_array.length; ++ month ) - { - - // Construct the input PRISM file name - file = args[0]+ "_" + month_array [ month ]; - prism.readPrism (file); - System.out.println ( "Processing file: " + Prism.getInputFilePath () - + "/" + file ); - System.out.println ( prism ); - - // Crop the PRISM data to the forecast area. - precip = cropPrismToHrapGrid ( prism, southwest_column, - southwest_row, - number_columns, - number_rows ); - - // Write the prism data to an XMRG file. - file = prism_output_path + "/" + args[1] + "_"+ month_name_array [ month ]; - System.out.println( "Writing PRISM data to " + file ); - - XMRG.writeXMRG ( file, - "lawrence", - "HP", - "PRISM", - "xxxxxx", - "xxxxxx", - precip, - scale_factor, - southwest_column, - southwest_row, - number_columns, - number_rows, - 9998, - 1, - false ); - } - - totalTime.stop("Total read time for Scanner "); - System.exit ( 0 ); - } - catch ( IOException e ) - { - System.out.println ( e.toString ( ) ); - System.exit ( 1 ); - } - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/prism/MPEConstants.java b/cave/ohd.hseb.common/src/ohd/hseb/prism/MPEConstants.java deleted file mode 100644 index ad58b6f958..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/prism/MPEConstants.java +++ /dev/null @@ -1,16 +0,0 @@ -package ohd.hseb.prism; - -public interface MPEConstants -{ - double PI=3.141592654; - double D2RAD=PI/180.0; - double EARTHR=6371.2; - double REF_LAT=60.0; - double REF_LON=105.0; - double RMESH=4.7625; - double TLAT=REF_LAT*D2RAD; - double RE=(EARTHR * ( 1.0 + Math.sin(TLAT)))/RMESH; - double HRAP_BASE_COL=401.0; - double HRAP_BASE_ROW=1601.0; - double MISSING=-999.0; -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/prism/Prism.java b/cave/ohd.hseb.common/src/ohd/hseb/prism/Prism.java deleted file mode 100644 index 5c42f45808..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/prism/Prism.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Created on August 25, 2005 - */ - -/** - * @ author Bryon Lawrence - * - * This is the Java version of the create_prism - * program. - */ -package ohd.hseb.prism; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Scanner; -import java.util.StringTokenizer; - -import ohd.hseb.util.CodeTimer; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class Prism { - static private String _prism_input_path; - - static private String _prism_output_path; - - private double _cellsize; - - private double _latitude_southwest_corner; - - private double _longitude_southwest_corner; - - private int _nodata_value; - - private int _num_rows; - - private int _num_cols; - - private int[][] _prism_data; - - // Static initializer for prism input path and - // prism output path. - static { - AppsDefaults apps_defaults = AppsDefaults.getInstance(); - _prism_input_path = apps_defaults.getToken("prism_input_dir"); - _prism_output_path = apps_defaults.getToken("prism_output_dir"); - } - - public void readPrism(String prism_filename) throws IOException { - - String prism_filepath; - String token; - - // Build the input filepath. - prism_filepath = _prism_input_path + "/" + prism_filename; - FileInputStream fileInputStream = new FileInputStream(prism_filepath); - BufferedInputStream bufferedInputStream = new BufferedInputStream( - fileInputStream); - - Scanner scanner = new Scanner(bufferedInputStream); - - // Do we need to read the string? - token = scanner.next(); - _num_cols = scanner.nextInt(); - - token = scanner.next(); - _num_rows = scanner.nextInt(); - - token = scanner.next(); - _longitude_southwest_corner = scanner.nextDouble(); - - token = scanner.next(); - _latitude_southwest_corner = scanner.nextDouble(); - - token = scanner.next(); - _cellsize = scanner.nextDouble(); - - token = scanner.next(); - _nodata_value = scanner.nextInt(); - - _prism_data = new int[_num_rows][_num_cols]; - - CodeTimer outerTimer = new CodeTimer(); - CodeTimer innerTimer = new CodeTimer(); - outerTimer.start(); - - for (int row = 0; row < _num_rows; ++row) { - for (int col = 0; col < _num_cols; ++col) { - innerTimer.restart(); - _prism_data[row][col] = scanner.nextInt(); - innerTimer.stop(); - } - - } - - outerTimer.stop("The nested for loops took "); - - System.out.println("Parse Token Elapsed Time = " - + innerTimer.getElapsedTime()); - scanner.close(); - - } - - /* - * This method is not used. It represents a faster way of reading and - * Processing PRISM data. But the code is trickier. Code readability has - * been chosen over performance. - */ - public void readPrismOld(String prism_filename) throws IOException { - String line; - String prism_filepath; - String token; - StringTokenizer token_string; - - // Build the input filepath. - prism_filepath = _prism_input_path + "/" + prism_filename; - - FileInputStream fileInputStream = new FileInputStream(prism_filepath); - InputStreamReader inputStreamReader = new InputStreamReader( - fileInputStream); - BufferedReader reader = new BufferedReader(inputStreamReader); - - // DataInputStream reader = new DataInputStream (new BufferedReader ( - // new FileReader ( _prism_filepath ) )); - - // Read the number of columns - line = reader.readLine(); - - token_string = new StringTokenizer(line); - token = token_string.nextToken(); - token = token_string.nextToken(); - - // Do we need to read the string? - _num_cols = Integer.parseInt(token); - - // Read the number of rows - line = reader.readLine(); - token_string = new StringTokenizer(line); - token = token_string.nextToken(); - token = token_string.nextToken(); - _num_rows = Integer.parseInt(token); - - // Read the longitude of the lowerleft corner - line = reader.readLine(); - token_string = new StringTokenizer(line); - token = token_string.nextToken(); - token = token_string.nextToken(); - _longitude_southwest_corner = Double.parseDouble(token); - - // Read the latitude of the lowerleft corner - line = reader.readLine(); - token_string = new StringTokenizer(line); - token = token_string.nextToken(); - token = token_string.nextToken(); - _latitude_southwest_corner = Double.parseDouble(token); - - // Read the cell size - line = reader.readLine(); - token_string = new StringTokenizer(line); - token = token_string.nextToken(); - token = token_string.nextToken(); - _cellsize = Double.parseDouble(token); - - // Read the nodata value. - line = reader.readLine(); - token_string = new StringTokenizer(line); - token = token_string.nextToken(); - token = token_string.nextToken(); - _nodata_value = Integer.parseInt(token); - - _prism_data = new int[_num_rows][_num_cols]; - - CodeTimer outerTimer = new CodeTimer(); - CodeTimer innerTimer = new CodeTimer(); - outerTimer.start(); - - for (int row = 0; row < _num_rows; ++row) { - line = reader.readLine(); - token_string = new StringTokenizer(line); - - for (int col = 0; col < _num_cols; ++col) { - innerTimer.restart(); - token = token_string.nextToken(); - _prism_data[row][col] = Integer.parseInt(token); - innerTimer.stop(); - } - } - - outerTimer.stop("The nested for loops took "); - - System.out.println("Parse Token Elapsed Time = " - + innerTimer.getElapsedTime()); - reader.close(); - - } - - public int getNumColumns() { - return _num_cols; - } - - public int getNumRows() { - return _num_rows; - } - - public double getSouthWestLong() { - return _longitude_southwest_corner; - } - - public double getSouthWestLat() { - return _latitude_southwest_corner; - } - - public double getCellSize() { - return _cellsize; - } - - public int getNoDataVal() { - return _nodata_value; - } - - public int[][] getPrism() { - return _prism_data; - } - - @Override - public String toString() { - return new String("num_rows: " + _num_rows + " num_cols: " + _num_cols - + " southwest longitude: " + _longitude_southwest_corner - + " southwest latitude: " + _latitude_southwest_corner); - } - - static public String getInputFilePath() { - return _prism_input_path; - } - - static public String getOutputFilePath() { - return _prism_output_path; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/prism/XMRG.java b/cave/ohd.hseb.common/src/ohd/hseb/prism/XMRG.java deleted file mode 100644 index 7916f044f8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/prism/XMRG.java +++ /dev/null @@ -1,117 +0,0 @@ -package ohd.hseb.prism; - -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - - -public class XMRG -{ - static public void writeXMRG ( String filePath, - String user, - String OS, - String process, - String datetimes, - String datetimev, - double [ ] [ ] data_matrix, - double conversion_factor, - int southwest_column, - int southwest_row, - int number_columns, - int number_rows, - int maxval, - int version_number, - boolean replace_missing ) throws IOException - { - byte [ ] byte_array; - byte [ ] boperuser = new byte [ 10 ]; - byte [ ] bdatev = new byte [ 20 ]; - byte [ ] bdates = new byte [ 20 ]; - byte [ ] bproc_flag = new byte [ 8 ]; - - DataOutputStream file; - int record_length; - short mosaic [][] = new short [ number_columns ] [ number_rows ]; - - // This method writes XMRG files. - String operuser = OS + user; - byte_array = operuser.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - boperuser [ i ] = byte_array [ i ]; - } - - byte_array = process.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - bproc_flag [ i ] = byte_array [ i ]; - } - - byte_array = datetimes.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - bdates [ i ] = byte_array [ i ]; - } - - byte_array = datetimev.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - bdatev [ i ] = byte_array [ i ]; - } - - - for ( int col = 0; col < number_columns; ++ col ) - { - for ( int row = 0; row < number_rows; ++ row ) - { - mosaic [ col ][ row ] = ( short ) ( data_matrix [ col ] [ row ] * - conversion_factor ); - } - } - - - // Open the output file. - // Write the xmrg header information. - file = new DataOutputStream ( new FileOutputStream ( - new File ( filePath ) ) ); - - // Write the first record of the header. - file.writeInt ( 16 ); - file.writeInt ( southwest_column ); - file.writeInt ( southwest_row ); - file.writeInt ( number_columns ); - file.writeInt ( number_rows ); - file.writeInt ( 16 ); - - // Write the second record of the header. - file.writeInt ( 66 ); - file.write ( boperuser, 0, boperuser.length ); - file.write ( bdates, 0, bdates.length ); - file.write ( bproc_flag, 0, bproc_flag.length ); - file.write ( bdatev, 0, bdatev.length ); - file.writeInt ( maxval ); - file.writeInt ( version_number ); - file.writeInt ( 66 ); - - // Compute the data record length in bytes. - record_length = number_columns * 2; - - // Write the data records. - for ( int row = 0; row < number_rows; ++ row ) - { - file.writeInt ( record_length ); - - for ( int col = 0; col < number_columns; ++ col ) - { - file.writeShort ( mosaic [ col ] [ row ] ); - } - - file.writeInt ( record_length ); - } - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/Location.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/Location.java deleted file mode 100644 index 3024bc7c44..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/Location.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.timeserieslite; - -import ohd.hseb.model.RatingCurve; - -public class Location -{ - private String _lid = null; - private double _lat = 0; - private double _lon = 0; - private double _elevation = 0; - private String _locationName = null; - private boolean _isRiverStation = false; - private boolean _isFcstPoint = false; - private String _hsa = null; - private double _floodStage = 0; - private double _floodFlow = 0; - private RatingCurve _ratingCurve = null; - private boolean _isDCP = false; - private boolean _isObserver = false; - private String _telemType = null; - - public Location() - { - } - - public Location( Location location ) - { - _lid = location.getLid(); - _hsa = location.getHsa(); - _lat = location.getLat(); - _lon = location.getLon(); - _elevation = location.getElevation(); - _locationName = location.getLocationName(); - _isRiverStation = location.isRiverStation(); - _floodStage = location.getFloodStage(); - _floodFlow = location.getFloodFlow(); - _ratingCurve = location.getRatingCurve(); - _isDCP = location.isDCP(); - _isObserver = location.isObserver(); - _telemType = location.getTelemType(); - } - - public String toString() - { - String string = null; - - string = "LID = " + _lid + - " HSA = " + _hsa + - " Lat = " + _lat + - " Lon = " + _lon + - " Elev = " + _elevation + - " Location Name = " + _locationName + - " RiverStation = " + _isRiverStation + - " Flood Stage = " + _floodStage + - " Flood Flow = " + _floodFlow + - " DCP = " + _isDCP + - " Observer = " + _isObserver + - " Telem Type = " + _telemType; - - return string; - } - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setLat( double lat ) - { - _lat = lat; - } - public double getLat() - { - return _lat; - } - public void setLon( double lon ) - { - _lon = lon; - } - public double getLon() - { - return _lon; - } - public void setElevation( double elevation ) - { - _elevation = elevation; - } - public double getElevation() - { - return _elevation; - } - public void setLocationName( String locationName ) - { - _locationName = locationName; - } - public String getLocationName() - { - return _locationName; - } - - public void setRiverStation( boolean isRiverStation ) - { - _isRiverStation = isRiverStation; - } - - public boolean isRiverStation() - { - return _isRiverStation; - } - - public void setFloodStage( double floodStage ) - { - _floodStage = floodStage; - } - - public double getFloodStage() - { - return _floodStage; - } - - public void setHsa( String hsa ) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } - - public void setFcstPoint( boolean isFcstPoint ) - { - _isFcstPoint = isFcstPoint; - } - - public String isFcstPoint() - { - if ( _isFcstPoint ) - { - return "T"; - } - else - { - return "F"; - } - } - - public void setFloodFlow( double floodFlow ) - { - _floodFlow = floodFlow; - } - - public double getFloodFlow() - { - return _floodFlow; - } - - public void setRatingCurve( RatingCurve ratingCurve ) - { - _ratingCurve = ratingCurve; - } - - public RatingCurve getRatingCurve() - { - return _ratingCurve; - } - - public void setDCP( boolean isDCP ) - { - _isDCP = isDCP; - } - - public boolean isDCP() - { - return _isDCP; - } - - public void setObserver( boolean isObserver ) - { - _isObserver = isObserver; - } - - public boolean isObserver() - { - return _isObserver; - } - - public void setTelemType( String telemType ) - { - _telemType = telemType; - } - - public String getTelemType() - { - return _telemType; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/PDCDataType.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/PDCDataType.java deleted file mode 100644 index 7d15ab8536..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/PDCDataType.java +++ /dev/null @@ -1,80 +0,0 @@ -package ohd.hseb.timeserieslite; - - -import java.util.HashMap; -import java.util.Map; - -public class PDCDataType -{ - private static Map _dataTypeMap = new HashMap(); - - - public final static PDCDataType HEIGHT = new PDCDataType("Height"); - public final static PDCDataType DISCHARGE = new PDCDataType("Discharge"); - public final static PDCDataType LAKE_STORAGE = new PDCDataType("Lake Storage"); - - public final static PDCDataType PRECIP_TOTAL = new PDCDataType("Precip Totals"); - public final static PDCDataType PRECIP_PC = new PDCDataType("Precip PC"); - - public final static PDCDataType SNOW_DEPTH = new PDCDataType("Snow Depth"); - public final static PDCDataType SNOW_WATER_EQUIVALENT = new PDCDataType("Snow Water Equivalent"); - - public final static PDCDataType TEMPERATURE = new PDCDataType("Temperature"); - public final static PDCDataType DEWPOINT = new PDCDataType("Dewpoint"); - - public final static PDCDataType RELATIVE_HUMIDITY = new PDCDataType("Relative Humidity"); - - public final static PDCDataType WIND_SPEED = new PDCDataType("Wind Speed"); - public final static PDCDataType WIND_DIRECTION = new PDCDataType("Wind Direction"); - - - //---------------------------------------------------------------------------- - - private String _name; - - //---------------------------------------------------------------------------- - private PDCDataType() - { - - } - - //---------------------------------------------------------------------------- - private PDCDataType(String name) - { - _name = name; - - if (_dataTypeMap == null) - { - _dataTypeMap = new HashMap(); - } - - _dataTypeMap.put(name.toLowerCase(), this); - - return; - } - //---------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - - //---------------------------------------------------------------------------- - - - public static PDCDataType getDataTypeFromString(String name) - { - PDCDataType dataType = (PDCDataType) _dataTypeMap.get(name.toLowerCase()); - - return dataType; - } - - // ---------------------------------------------------------------------------- - - - public String toString() - { - return _name; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/ParamCode.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/ParamCode.java deleted file mode 100644 index dd402bdb58..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/ParamCode.java +++ /dev/null @@ -1,264 +0,0 @@ -package ohd.hseb.timeserieslite; - -import java.util.HashMap; -import java.util.Map; - -public class ParamCode -{ - private String _paramCodeString = null; - - private static final Map _shefDurCodeToIhfsDurCodeMap = new HashMap(); - private static final Map _ihfsDurCodeToShefDurCodeMap = new HashMap(); - - private String _pe = null; - private String _typeSource = null; - private int _ihfsDur = 0; - private String _shefDur = null; - private String _extremum = null; - - static - { - initDurationCodeMaps(); - } - - // ------------------------------------------------------------------------------- - public ParamCode(String paramCodeString) - { - _paramCodeString = paramCodeString; - parse(paramCodeString); - - return; - } - // ------------------------------------------------------------------------------- - - public ParamCode(ParamCode paramCode) - { - _pe = paramCode.getPe(); - _typeSource = paramCode.getTypeSource(); - _ihfsDur = paramCode.getIhfsDur(); - _shefDur = paramCode.getShefDur(); - _extremum = paramCode.getExtremum(); - _paramCodeString = paramCode._paramCodeString; - - - return; - } - // ------------------------------------------------------------------------------- - // ------------------------------------------------------------------------------- - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getPe() + - getShefDur() + - getTypeSource() + - getExtremum() ); - - return buffer.toString(); - } - - // ------------------------------------------------------------------------------- - - public String toStringVerbose() - { - StringBuffer buffer = new StringBuffer(); - - - buffer.append("pe = " + getPe() + - " dur = " + getIhfsDur() + - " ts = " + getTypeSource() + - " extremum = " + getExtremum() ); - - return buffer.toString(); - - } - // ------------------------------------------------------------------------------- - - private void parse(String paramCodeString) - { - - setPe(paramCodeString.substring(0,2)); - _shefDur = paramCodeString.substring(2,3); - - _ihfsDur = getIhfsDurationCode(_shefDur); - - setTypeSource(paramCodeString.substring(3,5)); - setExtremum(paramCodeString.substring(5,6)); - - return; - } - // ------------------------------------------------------------------------------- - private static void initDurationCodeMaps() - { - - /* - 0 | I | Instantaneous - 1 | U | 1 Minute - 15 | C | 15 Minutes - 30 | J | 30 Minutes - 1001 | H | 1 Hour - 1002 | B | 2 Hour - 1003 | T | 3 Hour - 1004 | F | 4 Hour - 1006 | Q | 6 Hour - 1008 | A | 8 Hour - 1012 | K | 12 Hour - 1018 | L | 18 Hour - 2001 | D | 1 Day - 2007 | W | 1 Week - 3001 | M | 1 Month - 4001 | Y | 1 Year - 5000 | Z | Unspecified - 5001 | S | Seasonal - 5002 | R | Period of Record - 5004 | P | Total Since 7 AM - 5005 | X | Unknown - - */ - - - String code = "?"; - - String charCodeString = "IUCJHBTFQAKLDWMYZSRPX"; - - int intCodeArray[] = { 0, 1, 15, 30, - 1001, 1002, 1003, 1004, 1006, 1008, 1012, 1018, - 2001, 2007, - 3001, - 4001, - 5000, 5001, 5002, 5004, 5005 }; - - - - int i = 0; - - for (i = 0; i < charCodeString.length(); i++) - { - String shefCode = charCodeString.substring(i, i+1); - Integer intCode = new Integer(intCodeArray[i]); - - _shefDurCodeToIhfsDurCodeMap.put(shefCode, intCode); - _ihfsDurCodeToShefDurCodeMap.put(intCode, shefCode); - } - - return; - - } - // ------------------------------------------------------------------------------- - public static int getIhfsDurationCode(String shefDurationCode) - { - int ihfsCode = -1; - Integer ihfsCodeInteger = (Integer) _shefDurCodeToIhfsDurCodeMap.get(shefDurationCode); - - if (ihfsCodeInteger != null) - { - ihfsCode = ihfsCodeInteger.intValue(); - } - - return ihfsCode; - } - // ------------------------------------------------------------------------------- - public static String getShefDurationCode(int ihfsDurationCode) - { - String shefDurationCode = "?"; - - Integer ihfsDurationCodeInteger = new Integer(ihfsDurationCode); - - String shefDurationCodeFromMap = - (String) _ihfsDurCodeToShefDurCodeMap.get(ihfsDurationCodeInteger); - - if (shefDurationCodeFromMap != null) - { - shefDurationCode = shefDurationCodeFromMap; - } - - return shefDurationCode; - } - /** - * @param pe The pe to set. - */ - public void setPe(String pe) - { - _pe = pe; - } - /** - * @return Returns the pe. - */ - public String getPe() - { - return _pe; - } - /** - * @param typeSource The typeSource to set. - */ - public void setTypeSource(String typeSource) - { - _typeSource = typeSource; - } - /** - * @return Returns the typeSource. - */ - public String getTypeSource() - { - return _typeSource; - } - /** - * @param ihfsDur The ihfsDur to set. - */ - public void setIhfsDur(int ihfsDur) - { - _ihfsDur = ihfsDur; - } - /** - * @return Returns the ihfsDur. - */ - public int getIhfsDur() - { - return _ihfsDur; - } - /** - * @param shefDur The shefDur to set. - */ - public void setShefDur(String shefDur) - { - _shefDur = shefDur; - } - /** - * @return Returns the shefDur. - */ - public String getShefDur() - { - return _shefDur; - } - /** - * @param extremum The extremum to set. - */ - public void setExtremum(String extremum) - { - _extremum = extremum; - } - /** - * @return Returns the extremum. - */ - public String getExtremum() - { - return _extremum; - } - - // ------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - ParamCode code = null; - - code = new ParamCode("HGIRGZ"); - System.out.println("code = " + code.toString()); - - - code = new ParamCode("HPIRZX"); - System.out.println("code = " + code.toString()); - - } - - // ------------------------------------------------------------------------------- - -} //end ParamCode diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TSLDrawingMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TSLDrawingMgr.java deleted file mode 100644 index 456ddd6cc2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TSLDrawingMgr.java +++ /dev/null @@ -1,13 +0,0 @@ -package ohd.hseb.timeserieslite; - -//import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public interface TSLDrawingMgr -{ - - public void display(String[] argStringArray, boolean exitOnClose); - - - // public MeasuringUnit getMeasuringUnit(); - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TSLFrame.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TSLFrame.java deleted file mode 100644 index 1c88fee23b..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TSLFrame.java +++ /dev/null @@ -1,302 +0,0 @@ -package ohd.hseb.timeserieslite; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.KeyStroke; -import javax.swing.border.Border; - -import ohd.hseb.gui.util.ScreenCaptureActionListener; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - - -public class TSLFrame extends JFrame -{ - //------------------------------------------------------------------------------ - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - private static final int HOURS_TO_ROUND = 6; - - //window sizing variables - private Dimension _minSize = new Dimension(250, 250); - private Dimension _maxSize = new Dimension(1000, 1000); - private Dimension _initialSize = new Dimension(500, 500); - - - private JMenuBar _menuBar = null; - private JPanel _mainPanel = null; - - private TsPaintableCanvas _canvas = null; - private ValueMapper _rightAxisValueMapper = null; - - private boolean _exitOnClose = false; - - //------------------------------------------------------------------------------ - - public TSLFrame() - { - initGui(); - - return; - } - - // --------------------------------------------------------------------------------- - - public void setTimeWindow(long startTime, long endTime) - { - _canvas.setTimeWindow(startTime, endTime); - - return; - } - - //------------------------------------------------------------------------------ - public TsPaintableCanvas getCanvas() - { - - return _canvas; - - } - - //------------------------------------------------------------------------------ - - public void setExitOnClose(boolean exitOnClose) - { - _exitOnClose = exitOnClose; - - return; - } - //------------------------------------------------------------------------------ - - private void initGui() - { - setAlwaysOnTop(true); - - // canvas needs to be initialized before the menu bar, - // because of the screen capturer - initCanvas(0, 0, - _initialSize.width, - _initialSize.height); - - - this.setTitle("TimeSeriesLite"); - - initMenuBar(); - - //limit the range of the resizing - // this object can be local because it remains in memory as a listener - WindowResizingManager manager = new WindowResizingManager(this, _minSize, _maxSize); - - _mainPanel = new JPanel(); - _mainPanel.setBackground(Color.red); - - setLayout(); - - addListeners(); - - this.getContentPane().add(_mainPanel); - this.pack(); - - } - - //----------------------------------------------------------------- - private void setLayout() - { - _mainPanel.setLayout(new GridBagLayout()); - GridBagConstraints mainPanelGbc = new GridBagConstraints(); - mainPanelGbc.fill = GridBagConstraints.BOTH; - -// col, row numCols numRows Wcol wrow - - if (_canvas == null) - { - System.out.println("Canvas is null"); - } - addComponent(_mainPanel, _canvas, mainPanelGbc, 0, 0, 1, 1, 1, 1); - - return; - } - - //----------------------------------------------------------------- - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - //----------------------------------------------------------------- - - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - ScreenCaptureActionListener screenCaptureActionListener = - new ScreenCaptureActionListener(this, _canvas); - - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new CloseListener()); - menu.add(menuItem); - - - // create a button directly on the menuBar - - Color menuBarColor = _menuBar.getBackground(); - Border invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - JButton saveButton = new JButton(" Save Screen "); - saveButton.addActionListener(screenCaptureActionListener); - saveButton.setBorder(invisibleBorder); - saveButton.setSize(60, 30); - String saveButtonTooltipText = "Capture the screen to a file."; - saveButton.setToolTipText(saveButtonTooltipText); - _menuBar.add(saveButton); - - - HelpActionListener helpActionListener = new HelpActionListener(); - JButton helpButton = new JButton("Help"); - helpButton.addActionListener(helpActionListener); - helpButton.setBorder(invisibleBorder); - helpButton.setSize(60, 30); - _menuBar.add(helpButton); - - - - //add to the Frame - setJMenuBar(_menuBar); - } - - //----------------------------------------------------------------- - - private void addListeners() - { - - //allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - } - //-----------------------------------------------------------------\ - - private void close() - { - dispose(); - - if (_exitOnClose) - { - // System.exit(0); - } - } - - //----------------------------------------------------------------- - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - close(); - } - } - - //----------------------------------------------------------------- - - - private class FrameCloseWindowListener extends WindowAdapter - { - public void windowClosing(WindowEvent evt) - { - close(); - } - - } - // ------------------------------------------------------------------------------------ - - private class HelpActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String message = "The yellow time series is observed.\n" + - "The green time series is forecast. \n" + - "The vertical yellow line is current time.\n" + - "The horizontal yellow and red lines are action and flood levels,\n" + - "respectively (if applicable)."; - - DialogHelper.displayMessageDialog(TSLFrame.this, message, "TimeSeriesLite Help"); - } - - } - // ------------------------------------------------------------------------------------ - private void initCanvas(int x, int y, - int width, int height) - - { - - MeasuringUnit measuringUnit = MeasuringUnit.feet; - - _canvas = new TsPaintableCanvas( - measuringUnit, - x, y, - width, height); - - _canvas.setPreferredSize(_initialSize); - _canvas.setMinimumSize(_minSize); - - } //end initCanvas - - - // --------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TimeSeriesLite.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TimeSeriesLite.java deleted file mode 100644 index ef2a87f4f2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/TimeSeriesLite.java +++ /dev/null @@ -1,219 +0,0 @@ -package ohd.hseb.timeserieslite; - -import ohd.hseb.util.CodeTimer; - - -public class TimeSeriesLite -{ -// ------------------------------------------------------------------------------------- - - //accepted as command-line arguments - //private String _locationId = null; - private String _drawingManagerClassName = null; - - //internal variables - private TSLDrawingMgr _drawingMgr = null; - - // ------------------------------------------------------------------------------------- - - private void readCommandLineArgs(String[] argStringArray) - { - if (argStringArray.length > 1) - { - //_locationId = argStringArray[0]; - _drawingManagerClassName = argStringArray[0]; - } - else - { - System.out.println("usage: java " + - this.getClass().getName() + - "dataManagerClassName "); - } - - return; - } - -// ------------------------------------------------------------------------------------- - - private void loadDrawingManager(String[] argumentStringArray) - { - String header = "TimeSeriesList.loadDataManager(): "; - - try - { - Class drawingManagerClass = Class.forName(_drawingManagerClassName); - - _drawingMgr = (TSLDrawingMgr) drawingManagerClass.newInstance(); - //_drawingMgr.handleCommandLineArgs(argumentStringArray); - - System.out.println(header + "_drawingMgr's class name = " + - _drawingMgr.getClass().getName()); - - - } - catch (ClassNotFoundException e) - { - e.printStackTrace(); - } - catch (IllegalAccessException e) - { - e.printStackTrace(); - } - catch (InstantiationException e) - { - e.printStackTrace(); - } - - return; - } -// ------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) - { - CodeTimer timer = new CodeTimer(); - String header = "TimeSeriesLite.display(): "; - - readCommandLineArgs(argStringArray); - - timer.start(); - loadDrawingManager(argStringArray); - timer.stop("loadDrawingManager() took "); - - if (_drawingMgr != null) - { - _drawingMgr.display(argStringArray, exitOnClose); - - } - - else - { - System.out.println(header + "_drawingMgr == null"); - } - - return; - - } - -// ------------------------------------------------------------------------------------- - /* - public void display_old(String[] argStringArray, boolean exitOnClose) - { - - CodeTimer timer = new CodeTimer(); - String header = "TimeSeriesLite.display(): "; - - readCommandLineArgs(argStringArray); - - timer.start(); - loadDrawingManager(argStringArray); - timer.stop("loadDrawingManager() took "); - - if (_drawingMgr != null) - { - TSLFrame frame = new TSLFrame(); - - frame.setExitOnClose(exitOnClose); - - System.out.println(header + "after TSLFrame()"); - - TsPaintableCanvas canvas = frame.getCanvas(); - - timer.start(); - _drawingMgr.initializeCanvas(canvas); - timer.stop("initializeCanvas() took "); - - // System.out.println(header + "after _drawingMgr.initialize(canvas);"); - - - timer.start(); - frame.setVisible(true); - timer.stop("setVisible() took "); - - // System.out.println(header + "after frame.setVisible(true)"); - - } - - else - { - System.out.println(header + "_drawingMgr == null"); - } - - return; - } - */ -// ------------------------------------------------------------------------------------- - - public static void show(String nameOfDrawingMgr, - String dbConnString, - String locationId, - String paramCodeString1, - String paramCodeString2) - { - String header = "TimeSeriesLite.show(): "; - - String[] argStringArray = - { - nameOfDrawingMgr, - dbConnString, - locationId, - paramCodeString1, - paramCodeString2 - }; - - for (int i = 0; i < argStringArray.length; i++) - { - System.out.println("argStringArray[" + - i + "] = " + argStringArray[i]); - } - - TimeSeriesLite app = new TimeSeriesLite(); - app.display(argStringArray, true); - - } - - public static void main(String[] argStringArray) - { - TimeSeriesLite app = new TimeSeriesLite(); - app.display(argStringArray, true); - - //test(); - - return; - } -// ------------------------------------------------------------------------------------- -// ------------------------------------------------------------------------------------- - - public static void test() - { - - String[] argStringArray = {"ohd.hseb.timeserieslite.pdc.PDCDrawingMgr", - "jdbc:postgresql://140.90.91.111:5432/hd_ob72ounx?user=pguser", - "BLUO2", - "HGIRGZ", - "HGIFZZ" - }; - - TimeSeriesLite app = new TimeSeriesLite(); - app.display(argStringArray, true); - - - /* - argStringArray[3] = "HGIRGZ"; - app.display(argStringArray, true); - - - argStringArray[3] = "TAIRGZ"; - app.display(argStringArray, true); - - - argStringArray[3] = "USIRGZ"; - app.display(argStringArray, true); - - argStringArray[3] = "UDIRGZ"; - app.display(argStringArray, true); - */ - - return; - } -// ------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/SignificantLinePainter.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/SignificantLinePainter.java deleted file mode 100644 index f5fe5c6599..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/SignificantLinePainter.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of a significant data lines on a TsPaintableCanvas - */ -public class SignificantLinePainter implements TslCanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private Measurement _measurement = null; - - private boolean _shouldPaint = false; -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - - - // --------------------------------------------------------- - public SignificantLinePainter(Color lineColor, - Measurement measurement, - MeasuringUnit displayedMeasuringUnit) - { - - _lineColor = lineColor; - - _measurement = Measurement.getConvertedCopy(measurement, - displayedMeasuringUnit); - - - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - MeasuringUnit unit = _canvas.getDisplayedMeasuringUnit(); - // convert again just in case the _canvas has had its units changed, - // even though this feature is not available at this time - if (_measurement.getUnit() != unit) - { - _measurement = - Measurement.getConvertedCopy(_measurement, unit); - - } - double value = _measurement.getValue(); - long minTime = (long) _canvas.getViewport().getMinDataPoint().getX(); - long maxTime = (long) _canvas.getViewport().getMaxDataPoint().getX(); - - DataPoint dp1 = new DataPoint(minTime, value); - DataPoint dp2 = new DataPoint(maxTime, value); - - if (getViewport().isViewable(dp1)) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - - } - - //--------------------------------------------------------------- - - - //--------------------------------------------------------------- - - - public Measurement getMaxMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _measurement; - } - - return measurement; - } - - - public Measurement getMinMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _measurement; - } - - return measurement; - } - - -/** - * @param canvas The canvas to set. - */ -public void setCanvas(TsPaintableCanvas canvas) -{ - _canvas = canvas; -} - - -/** - * @return Returns the canvas. - */ -public TsPaintableCanvas getCanvas() -{ - return _canvas; -} - -//---------------------------------------------------- - - -} //end of SignficantLinePainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsBarPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsBarPainter.java deleted file mode 100644 index 2f0f1f1c5a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsBarPainter.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of precipitation data on a PaintableCanvas - */ -public class TsBarPainter implements TslCanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _barColor = null; - private Color _outlineColor = null; - - private RegularTimeSeriesHolder _precipTimeSeriesHolder = null; - private TsPaintableCanvas _canvas = null; - - private boolean _shouldDrawBars = true; - - private boolean _shouldPaint = true; - - private static final double VERY_SMALL_NUMBER = 0.0000000000000001; - - // --------------------------------------------------------- - public TsBarPainter(Color barColor, - Color outlineColor, - RegularTimeSeriesHolder timeSeriesHolder - ) - { - - _precipTimeSeriesHolder = timeSeriesHolder; - _canvas = getCanvas(); - - _barColor = barColor; - _outlineColor = outlineColor; - - } - -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - - //System.out.println("PrecipPainter.paint(): precip ts = " + getTimeSeries()); - if (_shouldPaint) - { - drawDataBars(g); - } - } - -// ---------------------------------------------------- - private void drawDataBars( Graphics g ) - { - // String header = "TsBarPainter.drawDataBars(): "; - // System.out.println(header + "-------------------------"); - int x1; - int y1; - int x2; - int y2; - g.setColor(_barColor); - - long millisPerInterval = MILLIS_PER_HOUR; - - RegularTimeSeries timeSeries = getTimeSeries(); - - if (timeSeries != null) - { - millisPerInterval = timeSeries.getIntervalInHours() * MILLIS_PER_HOUR; - } - - //draw each data bar - for ( int i = 0; (timeSeries != null) && - ( i < timeSeries.getMeasurementCount()); i++) - { - - Measurement measurement = (Measurement) - timeSeries.getMeasurementByIndex(i); - - Measurement convertedMeasurement = Measurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double value = convertedMeasurement.getValue(); - - - if (value > VERY_SMALL_NUMBER) - - { - - long endTime = timeSeries.getMeasurementTimeByIndex(i); - long startTime = endTime - millisPerInterval; - - /* - if (!_shouldDrawBars) - { - String timeString = CanvasHelper.getDateTimeStringFromLongTime(endTime); - System.out.println("Time = " + timeString + " value = " + value); - } - */ - - DataPoint dp1 = new DataPoint(startTime, 0); - DataPoint dp2 = new DataPoint(endTime, value); - - - if ( (getViewport().isViewable(dp1)) && - (getViewport().isViewable(dp2)) - ) - { - - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - - int barHeight = Math.abs(p1.y - p2.y); - int barWidth = Math.abs(p1.x - p2.x); - - if (_shouldDrawBars) - { - g.setColor(_barColor); - g.fillRect(p1.x, p2.y, barWidth, barHeight); - - g.setColor(_outlineColor); - g.drawRect(p1.x, p2.y, barWidth, barHeight); - } - else //draw Lines - { - g.setColor(_barColor); - g.drawLine(p1.x, p2.y, p1.x + barWidth, p2.y); - - } - } - - }//end if value > 0.0 - - } // for loop - - - } // end of drawDataBars method -// ---------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - private RegularTimeSeries getTimeSeries() - { - return _precipTimeSeriesHolder.getTimeSeries(); - } - -//--------------------------------------------------------- - public Measurement getMinMeasurement() - { - //force this method to return 0.0 always, since - //I always want 0 shown, regardless of the actual measurements - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - /* - - Measurement minMeasurement = null; - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - if (minMeasurement != null) - { - minMeasurement = new Measurement(minMeasurement); - } - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - - */ - return minMeasurement; - } -//---------------------------------------------------- - - public Measurement getMaxMeasurement() - { - - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - - String header = "PrecipPainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - if (maxMeasurement != null) - { - maxMeasurement = new Measurement(maxMeasurement); - - if ( maxMeasurement.getValue(_canvas.getDisplayedMeasuringUnit()) < 1.0) - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - //System.out.println(header + " time series was null, setting max measurement to 1.0 "); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - - - //System.out.println(header + " max measurement is " + maxMeasurement); - - return maxMeasurement; - } - -// ---------------------------------------------------- - - public void setShouldDrawBars(boolean shouldDrawBars) - { - _shouldDrawBars = shouldDrawBars; - } - -// ---------------------------------------------------- - - - public boolean shouldDrawBars() - { - return _shouldDrawBars; - } - - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsCanvasToolTipListener.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsCanvasToolTipListener.java deleted file mode 100644 index 927b303896..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsCanvasToolTipListener.java +++ /dev/null @@ -1,119 +0,0 @@ -package ohd.hseb.timeserieslite.gui.drawing; - -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class TsCanvasToolTipListener extends MouseMotionAdapter -{ - private TsPaintableCanvas _canvas = null; - private ValueMapper _valueMapper = null; - - // --------------------------------------------------------------------------------- - - - public TsCanvasToolTipListener(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - _canvas = canvas; - _valueMapper = valueMapper; - } - // --------------------------------------------------------------------------------- - - public void mouseMoved(MouseEvent event) - { - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas.getViewport().getDataPoint(screenPoint); - - - if (_canvas.getViewport().isViewable(dataPoint)) - { - updateDataPointText(dataPoint, _valueMapper, _canvas); - } - } - - - - // --------------------------------------------------------------------------------- - - public void updateDataPointText(DataPoint dataPoint, - ValueMapper valueMapper, - TsPaintableCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String leftUnitString = canvas.getDisplayedMeasuringUnit().toString(); - String rightUnitString = valueMapper.getOutputMeasuringUnit().toString(); - - String message = getDataPointString(dataPoint, valueMapper, leftUnitString, rightUnitString); - - //textField.setText(message); - - canvas.setToolTipText(message); - - return; - } - - // --------------------------------------------------------------------------------- - - private String getDataPointString(DataPoint dataPoint, - ValueMapper valueMapper, - String leftUnitString, - String rightUnitString) - { - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(dataPoint.getY()); - - String mappedValueString = ""; - - if (valueMapper != null) - { - MeasuringUnit inputUnit = valueMapper.getInputMeasuringUnit(); - Measurement inputMeasurement = new Measurement(dataPoint.getY(), inputUnit); - - Measurement mappedMeasurement = valueMapper.getResultMeasurement(inputMeasurement); - - double mappedValue = mappedMeasurement.getValue(); - - mappedValueString = nf.format(mappedValue); - } - - long time = (long) Math.floor( dataPoint.getX()); - - String timeString = getDateTimeStringToMinutes(time); - - String dataPointString = timeString + ", " + - valueString + " " + leftUnitString + ", " + - mappedValueString + " " + rightUnitString; - - return dataPointString; - } - - //---------------------------------------------------------------------- - - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + " Z"; - - return timeString; - } - - //---------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsDataPointPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsDataPointPainter.java deleted file mode 100644 index 8f83b5c2b5..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TsDataPointPainter.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of an irregular time series on a TsPaintableCanvas - */ -public class TsDataPointPainter implements TslCanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _pointColor = null; - - private IrregularTimeSeriesHolder _timeSeriesHolder = null; - private RegularTimeSeriesHolder _regularTimeSeriesHolder = null; - - private TsPaintableCanvas _canvas = null; - - private boolean _isRegular = false; // distinguishes between the kind of time series - - private boolean _drawLinesBetweenPoints = false; - private boolean _shouldPaint = true; - - // --------------------------------------------------------- - public TsDataPointPainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder, - boolean drawLinesBetweenPoints) - { - - _isRegular = true; - - _regularTimeSeriesHolder = regularTimeSeriesHolder; - - _pointColor = pointColor; - - _drawLinesBetweenPoints = drawLinesBetweenPoints; - - } - // --------------------------------------------------------- - - public TsDataPointPainter(Color pointColor, - IrregularTimeSeriesHolder timeSeriesHolder) - { - - _isRegular = false; - - _timeSeriesHolder = timeSeriesHolder; - - _drawLinesBetweenPoints = false; - - _pointColor = pointColor; - } - - // --------------------------------------------------------- - public TsDataPointPainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder) - { - this (pointColor, regularTimeSeriesHolder, false); - - } -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - //String header = "StagePainter.paint(): "; - - if (_shouldPaint) - { - drawDataPoints(g); - } - } - -// ---------------------------------------------------------- - private void drawDataPoints( Graphics g ) - { - if (_isRegular) - { - drawRegularDataPoints(g); - } - else - { - drawIrregularDataPoints(g); - } - } -// ---------------------------------------------------------- - private void drawRegularDataPoints( Graphics g ) - { - String header = "TsDataPointPainter.drawRegularDataPoints():"; - - - if (getRegularTimeSeries() == null ) - { - //System.out.println(header + " time series is null"); - return; - } - - long startTime = getRegularTimeSeries().getStartTime(); - long endTime = getRegularTimeSeries().getEndTime(); - - - g.setColor(_pointColor); - - - long hoursPerInterval = 1; - long millisPerInterval = MILLIS_PER_HOUR * hoursPerInterval; - - DataPoint previousDataPoint = null; - - //draw each data point - for ( long time = startTime; time <= endTime; time += millisPerInterval) - { - - Measurement measurement = getRegularTimeSeries().getMeasurementByTime(time); - - measurement = measurement.getCopy(getDisplayedMeasuringUnit()); - - - double value = measurement.getValue(); - - DataPoint dp1 = new DataPoint(time, value); - - drawDataPoint(dp1, g); - - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - - } // for loop - - } // end of drawRegularDataPoints() method - - -// ---------------------------------------------------------- - - private void drawIrregularDataPoints( Graphics g ) - { - - DataPoint previousDataPoint = null; - - String header = "StagePainter.drawIrregularDataPoints():"; - //System.out.println(header + " at beginning"); - - if (getTimeSeries() == null) - { - //System.out.println(header + " time series is null"); - } - - g.setColor(_pointColor); - - //System.out.println(header + "time series = " + getTimeSeries()); - - //draw each data point - for ( int i = 0; (getTimeSeries() != null) && - i < getTimeSeries().getMeasurementCount(); i++) - { - - AbsTimeMeasurement measurement = (AbsTimeMeasurement) - getTimeSeries().getAbsTimeMeasurementByIndex(i); - - - - AbsTimeMeasurement convertedMeasurement = - AbsTimeMeasurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double convertedValue = convertedMeasurement.getValue(); - long time = measurement.getTime(); - - DataPoint dp1 = new DataPoint(time, convertedValue); - - drawDataPoint(dp1, g); - - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - - - - } // for loop - - } // end of drawIrregularDataPoints() method - -// --------------------------------------------------------- - private void drawSegment(DataPoint dp1, DataPoint dp2, Graphics g) - { - - Viewport viewport = getViewport(); - -// if it is viewable, then draw it - if ( (getViewport().isViewable(dp1)) && (getViewport().isViewable(dp2)) ) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - else - { - //System.out.println("StagePainter.drawSegment(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } - -// --------------------------------------------------------- - - private void drawDataPoint(DataPoint dp, Graphics g) - { - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } -// -------------------------------------------------------- - private IrregularTimeSeries getTimeSeries() - { - IrregularTimeSeries ts = null; - - if (_timeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _timeSeriesHolder.getTimeSeries(); - } - return ts; - } - -// --------------------------------------------------------- - - private RegularTimeSeries getRegularTimeSeries() - { - RegularTimeSeries ts = null; - - - if (_regularTimeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _regularTimeSeriesHolder.getTimeSeries(); - } - - return ts; - } -// --------------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - - public Measurement getMinMeasurement() - { - String header = "StagePainter.getMinMeasurement()"; - - Measurement minMeasurement = null; - - //extremes don't count unless displayed - if (_shouldPaint) - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - minMeasurement = getRegularTimeSeries().getMinMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - } - // System.out.println(header + "minMeasurement = " + minMeasurement); - - - return minMeasurement; - } - -// ---------------------------------------------------- - -// ---------------------------------------------------- - public Measurement getMaxMeasurement() - { - String header = "StagePainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - - if (_shouldPaint) //extremes don't count unless displayed - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - maxMeasurement = getRegularTimeSeries().getMaxMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - } - else - { - //System.out.println(header + "No time series found!!!!"); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - } - - return maxMeasurement; - } - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - /** - * @param drawLinesBetweenPoints The drawLinesBetweenPoints to set. - */ - public void setDrawLinesBetweenPoints(boolean drawLinesBetweenPoints) - { - _drawLinesBetweenPoints = drawLinesBetweenPoints; - } - /** - * @return Returns the drawLinesBetweenPoints. - */ - public boolean getDrawLinesBetweenPoints() - { - return _drawLinesBetweenPoints; - } - - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslBackgroundPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslBackgroundPainter.java deleted file mode 100644 index a6faa3c20f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslBackgroundPainter.java +++ /dev/null @@ -1,622 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Point; -import java.awt.Rectangle; -import java.text.NumberFormat; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.util.BooleanHolder; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.CanvasHelper; -import ohd.hseb.util.gui.drawing.CanvasPainter; -import ohd.hseb.util.gui.drawing.ScalingHelper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author Chip Gobs - * - * This class implements CanvasPainter and encapsulates the - * drawing of the X and Y axes and all the tick marks - */ -public class TslBackgroundPainter implements CanvasPainter -{ - - // width distinctions for drawing labeling - private static final int WIDE_WIDTH = 600; - private static final int NARROW_WIDTH = 400; - private static final int TINY_WIDTH = 0; - - // various colors - private static final Color _backgroundColor = Color.black; - - private static final Color _gridColor = Color.GRAY; - private Color _outlineColor = Color.WHITE; - private static final Color _labelColor = Color.WHITE; - private static final Color _currentTimeColor = Color.YELLOW; - - //time constant - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - //number formatter - private NumberFormat _numberFormat = NumberFormat.getInstance(); - - //unit labels - private String _leftUnitLabelString = null; - private String _rightUnitLabelString = null; - - //fonts - private Font _titleFont = null; - private Font _labelFont = null; - - //FontHelper - custom class - private FontHelper _titleFontHelper = null; - private FontHelper _labelFontHelper = null; - - // margins and shifts - private final static int _titleYShift = - 20; - - private final static int _headerYShift = 0; - private int _leftLabelShift = 30; - private int _rightLabelShift = 10; - - private double _smallRoundingError = 0.000000001; - - // canvas and value mapper(which controls the values on the right axis) - private TsPaintableCanvas _canvas = null; - private ValueMapper _rightLabelValueMapper = null; - - // graphing hours - private int _hoursPerMajorXTick = 6; - private int _hoursPerMinorXTick = 1; - - private boolean _showMinorTicks = true; - - private String[] _textHeaderStringArray = null; - private String _title = null; - - - // --------------------------------------------------------- - public TslBackgroundPainter(Color outlineColor, - String leftUnitLabelString, - String rightUnitLabelString) - { - _outlineColor = outlineColor; - // _canvas = canvas; - - _leftUnitLabelString = leftUnitLabelString; - _rightUnitLabelString = rightUnitLabelString; - - _numberFormat.setMaximumFractionDigits(2); - - _titleFont = new Font("TimesRoman", Font.BOLD, 14); - _labelFont = new Font("Helvetica", Font.PLAIN, 9); - - _titleFontHelper = new FontHelper(_titleFont); - _labelFontHelper = new FontHelper(_labelFont); - - _showMinorTicks = true; - - } //tsBackgroundPainter() - -// --------------------------------------------------------- - public void setShowMinorTicks(boolean showMinorTicks) - { - _showMinorTicks = showMinorTicks; - } -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawBackground(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// ---------------------------------------------------- - - public void setRightLabelValueMapper(ValueMapper rightLabelValueMapper) - { - _rightLabelValueMapper = rightLabelValueMapper; - } -// ---------------------------------------------------- - - public ValueMapper getRightLabelValueMapper() - { - return _rightLabelValueMapper; - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - public void drawBackground(Graphics g) - { - - Rectangle r = _canvas.getBounds(); - - //set the normal font to use - g.setFont( _labelFont ); - - //clear the image - g.setColor(_backgroundColor); - g.fillRect(0, 0, r.width, r.height); - - //draw the axis labels, ticks, and dotted lines - drawHorizontalLines( g ); - drawVerticalLines( g ); - - //draw the Title - // drawTitle(g); - - drawTextHeader(g); - - int x = 0; - int y = 0; - - x = 10; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_leftUnitLabelString, g, x, y); - - x = _canvas.getViewport().getMaxScreenPoint().x + 0; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_rightUnitLabelString, g, x, y); - - return; - } -//---------------------------------------------------- - private void drawTitle(Graphics g) - { - // String header = "TslTsBackgroundPainter().drawTitle(): "; - - - String titleString = _canvas.getTitle(); - - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, titleString) / 2; - - int x = middleX - totalLeftShift; - int y = (_canvas.getTopMargin() + _titleYShift); - - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(titleString, x, y); - - return; - } //drawTitle - -// ---------------------------------------------------- - private void drawTextHeader(Graphics g) - { - String header = "TslTsBackgroundPainter().drawHeaderText(): "; - - g.setFont(_titleFont); - g.setColor(_labelColor); - - String headerString = ""; - - if (_textHeaderStringArray != null) - { - headerString = _textHeaderStringArray[0]; - } - - // System.out.println(header + "headerString = " + headerString); - - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, headerString) / 2; - int fontHeight = _titleFontHelper.getHeight(g); - - int x = middleX - totalLeftShift; - int y = 20; - - - - // draw each of the strings for the header - for (int i = 0; i < _textHeaderStringArray.length; i++) - { - if (_textHeaderStringArray[i] != null) - { - g.drawString(_textHeaderStringArray[i], x, y); - y += fontHeight; - } - } - return; - } //drawTitle - -// ---------------------------------------------------- - - private void drawUnitLabel(String unitLabel, Graphics g, int x, int y) - { - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(unitLabel, x, y); - - return; - } //drawTitle - -// -------------------------------------------------------------------------- - - private void drawVerticalLines(Graphics g) - { - // determine the min and max data values to chart - String header = "TslTsBackgroundPainter.drawVerticalLines(): "; - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - Point point1 = null; - Point point2 = null; - - - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - // draw each tick line - int minorTickHours = _hoursPerMinorXTick; - int majorTickHours = _hoursPerMajorXTick; - - for (double tickValue = minXValue; - tickValue <= maxXValue; - tickValue += minorTickHours * MILLIS_PER_HOUR) - { - point1 = getViewport().getScreenPoint(new DataPoint(tickValue, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(tickValue, maxYValue)); - - //if on a majorTick - if (isOnATick((long)tickValue, majorTickHours)) - { - - // System.out.println(header + "on a tick -> tickValue = " + - // DbTimeHelper.getDateTimeStringFromLongTime((long)tickValue)); - - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on graph boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else //not on a graph boundary - { - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - } - - //draw the major tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+6, point2.x, point1.y); - - //draw a major tick - //build the labels - BooleanHolder atZeroHour = new BooleanHolder(false); - String hourLabelString = getHourLabelString((long) tickValue, atZeroHour); - - - String dateLabelString = CanvasHelper.getDateString((long)tickValue); - - // draw the labels - g.setColor(_labelColor); - g.drawString(hourLabelString, point1.x-5, point1.y + 15); - - //only draw the date string at 00Z - if (atZeroHour.getValue() == true) - { - g.drawString(dateLabelString, point1.x-5, point1.y + 30); - } - } - else //on a minor tick - { - - // System.out.println(header + "on a minor tick -> tickValue = " + - // DbTimeHelper.getDateTimeStringFromLongTime((long)tickValue)); - - - - //draw a minor tick - //draw the minor tick extension - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+2, point2.x, point1.y); - - } - } //end for i - - - // if applicable, draw current time line - long currentTime = System.currentTimeMillis(); - if ( (currentTime >= minXValue) && (currentTime <=maxXValue)) - { - point1 = getViewport().getScreenPoint(new DataPoint(currentTime, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(currentTime, maxYValue)); - - g.setColor(_currentTimeColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - } //end drawXAxis - -// -------------------------------------------------------------------------- - private String getHourLabelString(long timeValue, BooleanHolder atZeroHour) - { - String hourLabelString = null; - String hourLabelBaseString = CanvasHelper.getHourString((long)timeValue); - - if (hourLabelBaseString.equals("00")) - { - atZeroHour.setValue(true); - } - - - if (_canvas.getWidth() >= WIDE_WIDTH) - { - hourLabelString = hourLabelBaseString + 'Z'; - } - else if (_canvas.getWidth() >= NARROW_WIDTH) - { - if (atZeroHour.getValue() == true) - { - hourLabelString = "0Z"; - } - else - { - hourLabelString = hourLabelBaseString; - } - } - else //TINY WIDTH - { - //00 and 06 become 0 and 6 to make more space - if (hourLabelBaseString.charAt(0) == '0') - { - hourLabelString = " " + hourLabelBaseString.substring(1,2); - } - else - { - hourLabelString = hourLabelBaseString; - } - } - - return hourLabelString; - } - -// -------------------------------------------------------------------------- - private boolean isOnATick(long timeValue, int hoursPerTick) - { - boolean result = false; - - long roundedTime = TimeHelper.truncateTimeInMillisToNearestHour((long)timeValue, hoursPerTick); - - // String timeValueString = DbTimeHelper.getDateTimeStringFromLongTime(timeValue); - // String roundedTimeString = DbTimeHelper.getDateTimeStringFromLongTime(roundedTime); - - if ( ( timeValue == roundedTime ) || - ( timeValue == roundedTime + (hoursPerTick*MILLIS_PER_HOUR)) - ) - { - result = true; - } - return result; - } //end isOnATick - - -// ------------------------------------------------------------------------------------------- - - private void drawHorizontalLines(Graphics g) - { - //determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - //String header = "TsBackgroundPainter.drawHorizontalLines(): "; - - //System.out.println(header + "minDataPoint = " + minDataPoint); - //System.out.println(header + "maxDataPoint = " + maxDataPoint); - - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - ScalingHelper scalingHelper = new ScalingHelper(minYValue, maxYValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - // int totalTickCount = majorTickCountMax * minorTickCount; - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minYValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_labelFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxYValue + _smallRoundingError); - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minYValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(minXValue, majorTickValue)); - point2 = getViewport().getScreenPoint(new DataPoint(maxXValue, majorTickValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not working due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - //CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - - } - - - //draw the left side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x-5, point1.y, point1.x, point2.y); - - // draw the label - String numberLabelString = _numberFormat.format(majorTickValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point1.x - _leftLabelShift , point1.y + 3); - - - - - //draw the right side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point2.x+5, point2.y, point2.x, point2.y); - - // draw the label - ValueMapper valueMapper = getRightLabelValueMapper(); - - double newValue = majorTickValue; - if (valueMapper != null) - { - Measurement m = new Measurement(majorTickValue, valueMapper.getInputMeasuringUnit()); - newValue = valueMapper.getResultMeasurement(m).getValue(); - } - - numberLabelString = _numberFormat.format(newValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point2.x + _rightLabelShift , point2.y + 3); - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minXValue, minorTickValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(maxXValue, minorTickValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, minorPoint1.x, minorPoint1.y, minorPoint2.x, minorPoint2.y); - - } - } - - } //end if _showMinorTicks - - } - - } //end drawYAxis - - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - - /** - * @param textHeaderStringArray The textHeaderStringArray to set. - */ - public void setTextHeaderStringArray(String[] textHeaderStringArray) - { - _textHeaderStringArray = textHeaderStringArray; - } - - /** - * @return Returns the textHeaderStringArray. - */ - public String[] getTextHeaderStringArray() - { - return _textHeaderStringArray; - } - - /** - * @param title The title to set. - */ - public void setTitle(String title) - { - _title = title; - } - - /** - * @return Returns the title. - */ - public String getTitle() - { - return _title; - } - -// ------------------------------------------------------------------------------ - - - - -} //end of SigStageLinePainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslCanvasPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslCanvasPainter.java deleted file mode 100644 index e0eebebcf7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslCanvasPainter.java +++ /dev/null @@ -1,10 +0,0 @@ -package ohd.hseb.timeserieslite.gui.drawing; - -import ohd.hseb.util.gui.drawing.TsCanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public interface TslCanvasPainter extends TsCanvasPainter -{ - - public void setCanvas(TsPaintableCanvas canvas); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslTimeLinePainter.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslTimeLinePainter.java deleted file mode 100644 index 4e1791d3e7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/gui/drawing/TslTimeLinePainter.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.gui.drawing.CanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of the vertical time line indicator on a TsPaintableCanvas - */ -public class TslTimeLinePainter implements CanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private TimeHolder _timeHolder = null; - - private String _labelString = null; - private int _labelYPosition = -1; - - // --------------------------------------------------------- - public TslTimeLinePainter(Color lineColor, - TimeHolder timeHolder) - { - - _lineColor = lineColor; - _timeHolder = timeHolder; - } - - // --------------------------------------------------------- - - public TslTimeLinePainter(Color lineColor, - String labelString, - int labelYPosition, - TimeHolder timeHolder) - { - - _lineColor = lineColor; - _timeHolder = timeHolder; - _labelString = labelString; - _labelYPosition = labelYPosition; - } - -//--------------------------------------------------------- - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - - double dataX = _timeHolder.getTime(); - double maxDataY = getViewport().getMaxDataPoint().getY(); - double minDataY = getViewport().getMinDataPoint().getY(); - - DataPoint dp1 = new DataPoint(dataX, maxDataY); - DataPoint dp2 = new DataPoint(dataX, minDataY); - - if (getViewport().isViewable(dp1)) - { - - Point p1 = _canvas.getViewport().getScreenPoint(dp1); - Point p2 = _canvas.getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - //draw a label if the _labelString is set - if (_labelString != null) - { - g.drawString(_labelString, p1.x, _labelYPosition); - } - - } - - } // end of drawDataLine() - - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - -//---------------------------------------------------- - - -} //end of TimeLinePainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/pdc/PDCDrawingMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/pdc/PDCDrawingMgr.java deleted file mode 100644 index e2589a916b..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/pdc/PDCDrawingMgr.java +++ /dev/null @@ -1,2321 +0,0 @@ -package ohd.hseb.timeserieslite.pdc; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.model.FlowToStageValueMapper; -import ohd.hseb.model.PrecipPPAndPCValueMapper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.timeserieslite.TSLDrawingMgr; -import ohd.hseb.timeserieslite.TSLFrame; -import ohd.hseb.timeserieslite.gui.drawing.SignificantLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TsBarPainter; -import ohd.hseb.timeserieslite.gui.drawing.TsCanvasToolTipListener; -import ohd.hseb.timeserieslite.gui.drawing.TsDataPointPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslBackgroundPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslCanvasPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslTimeLinePainter; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class PDCDrawingMgr implements TSLDrawingMgr -{ - private static final long MILLIS_PER_HOUR = 60*60*1000; - private static final int TOP_MARGIN = 100; - private int _hoursBackInTime = 120; - private int _hoursForwardInTime = 168; - - private PdcTslDataManager _dataMgr = null; - private String _locationId = null; - private List _paramCodeList = new ArrayList(); - private String _jdbcConnectionString = null; - - // private PDCDataType _dataType = null; - private List _dataTypeList = new ArrayList(); - - private long _startTime = 0; - private long _endTime = 0; - - private int HOURS_TO_ROUND = 6; - - - private static Map _physicalElementMap = new HashMap(); - static - { - _physicalElementMap.put("HG", PDCDataType.HEIGHT); - _physicalElementMap.put("HP", PDCDataType.HEIGHT); - _physicalElementMap.put("HT", PDCDataType.HEIGHT); - _physicalElementMap.put("QR", PDCDataType.DISCHARGE); - _physicalElementMap.put("QT", PDCDataType.DISCHARGE); - _physicalElementMap.put("LS", PDCDataType.LAKE_STORAGE); - _physicalElementMap.put("PP", PDCDataType.PRECIP_TOTAL); - _physicalElementMap.put("PC", PDCDataType.PRECIP_PC); - _physicalElementMap.put("SW", PDCDataType.SNOW_WATER_EQUIVALENT); - _physicalElementMap.put("SD", PDCDataType.SNOW_DEPTH); - - _physicalElementMap.put("TA", PDCDataType.TEMPERATURE); - _physicalElementMap.put("TD", PDCDataType.DEWPOINT); - - _physicalElementMap.put("WS", PDCDataType.WIND_SPEED); - _physicalElementMap.put("WD", PDCDataType.WIND_DIRECTION); - - _physicalElementMap.put("XR", PDCDataType.RELATIVE_HUMIDITY); - - } - - - // -------------------------------------------------------------------------------------------------- - - public PDCDrawingMgr() - { - - } - // -------------------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) - { - - handleCommandLineArgs(argStringArray); - - String header = "PDCDrawingMgr.display()"; - - TSLFrame frame = new TSLFrame(); - - frame.setExitOnClose(exitOnClose); - - // System.out.println(header + "after TSLFrame()"); - - TsPaintableCanvas canvas = frame.getCanvas(); - - - PDCDataType dataType = null; - - if ( _dataTypeList.size() > 0 ) - { - dataType = (PDCDataType) _dataTypeList.get(0); - } - - // System.out.println(header + " before initializeCanvas() "); - initializeCanvas(dataType, _paramCodeList, canvas); - // System.out.println(header + " after initializeCanvas() "); - - frame.setVisible(true); - } - - // -------------------------------------------------------------------------------------------------- - - private void initializeCanvas(PDCDataType dataType, - List paramCodeList, - TsPaintableCanvas canvas) - { - - String header = "initializeCanvas(): "; - initializeTimeWindow(canvas); - - //make room for the large area required by the text header in the graph - canvas.setTopMargin(TOP_MARGIN); - - - if (dataType == PDCDataType.HEIGHT) - { - initForHeight(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DISCHARGE) - { - initForDischarge(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.LAKE_STORAGE) - { - // initForLakeStorage(_locationId, canvas); - } - - - else if (dataType == PDCDataType.PRECIP_TOTAL) - { - System.out.println(header + "before initForPrecipDualMode() "); - initForPrecipDualMode(_locationId, paramCodeList, canvas); - System.out.println(header + "after initForPrecipDualMode() "); - } - - else if (dataType == PDCDataType.PRECIP_PC) - { - System.out.println(header + "before initForPrecipPC() "); - initForPrecipPC(_locationId, paramCodeList, canvas); - System.out.println(header + "after initForPrecipPC() "); - } - - else if (dataType == PDCDataType.SNOW_WATER_EQUIVALENT) - { - initForSnow(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.SNOW_DEPTH) - { - initForSnow(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.TEMPERATURE) - { - initForTemperature(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DEWPOINT) - { - initForDewpoint(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.WIND_DIRECTION) - { - initForWindDirection(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.WIND_SPEED) - { - initForWindSpeed(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.RELATIVE_HUMIDITY) - { - initForHumidity(_locationId, paramCodeList, canvas); - } - - - - //call this again to make it redraw everything correctly - // it wasn't working without this - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void initializeTimeWindow(TsPaintableCanvas canvas) - { - //set up time window - long currentTime = System.currentTimeMillis(); - long roundedCurrentTime = - TimeHelper.truncateTimeInMillisToNearestHour(currentTime, HOURS_TO_ROUND); - - setStartTime(roundedCurrentTime - (_hoursBackInTime * MILLIS_PER_HOUR)); - setEndTime(getStartTime() + (_hoursForwardInTime * MILLIS_PER_HOUR)); - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private boolean isValueAvailable(Measurement measurement, MeasuringUnit unit) - { - boolean result = false; - - if (measurement != null) - { - if (measurement.getValue(unit) > 0.0) - { - result = true; - } - } - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private void addCanvasListeners(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - //Add listener for the tooltip - TsCanvasToolTipListener toolTipMgr = new TsCanvasToolTipListener(canvas, valueMapper); - canvas.addMouseMotionListener(toolTipMgr); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void handleCommandLineArgs(String[] argStringArray) - { - String header = "PdcDrawingManager.handleCommandLineArgs(): "; - - //includes the optional jdbcConnectionString - if (argStringArray.length > 1) - { - _jdbcConnectionString = argStringArray[1]; - _dataMgr = new PdcTslDataManager(_jdbcConnectionString); - } - - //location id - if (argStringArray.length > 2) - { - _locationId = argStringArray[2]; - } - - -// create param code list and dataType list - for (int i = 3; i < argStringArray.length; i++) - { - String paramCodeString = argStringArray[i]; - System.out.println(header + "paramCodeString = " + paramCodeString); - - ParamCode paramCode = new ParamCode(paramCodeString); - - paramCode = expandParamCode(_locationId, paramCode); - - if (paramCode != null) - { - _paramCodeList.add(paramCode); - - // String physicalElement = paramCode.substring(0,2); - PDCDataType dataType = getDataTypeFromPhysicalElement(paramCode.getPe()); - _dataTypeList.add(dataType); - } - } - - return; - } - // ------------------------------------------------------------------------------------- - private ParamCode expandParamCode(String locationId, ParamCode paramCode) - { - - String header = "PDCDrawingMgr.expandParamCode(): "; - ParamCode expandedParamCode = new ParamCode(paramCode); - String expandedParamCodeString = null; - - String typeSource = paramCode.getTypeSource(); - String peString = paramCode.getPe(); - - if (typeSource.indexOf('-') == 1) - { - if (typeSource.charAt(0) == 'F') - { - typeSource = _dataMgr.getPreferredFcstTypeSource(locationId, peString); - - if (typeSource != null) - { - expandedParamCode.setTypeSource(typeSource); - expandedParamCodeString = expandedParamCode.toString(); - } - else - { - expandedParamCode = null; - expandedParamCodeString = null; - } - } - - } - else - { - expandedParamCodeString = expandedParamCode.toString(); - } - - System.out.println(header + "original paramCode = " + paramCode.toString() ); - System.out.println(header + "expandedParamCode = " + expandedParamCodeString ); - - return expandedParamCode; - - } - - // ------------------------------------------------------------------------------------- - - private ParamCode getParamCode(List paramCodeList) - { - ParamCode paramCode = null; - - - if ( (paramCodeList != null) && (paramCodeList.size() > 0) ) - { - paramCode = (ParamCode) paramCodeList.get(0); - } - - return paramCode; - } - - - // ------------------------------------------------------------------------------------- - private PDCDataType getDataTypeFromPhysicalElement(String physicalElement) - { - - PDCDataType dataType = (PDCDataType) _physicalElementMap.get(physicalElement); - if (dataType == null) - { - if (stringStartsWith(physicalElement, 'H')) - { - dataType = PDCDataType.HEIGHT; - } - if (stringStartsWith(physicalElement, 'Q')) - { - dataType = PDCDataType.DISCHARGE; - } - } - - return dataType; - - } - // ------------------------------------------------------------------------------------- - private boolean stringStartsWith(String physicalElement, char firstCharacter) - { - boolean result = false; - - if ( (physicalElement!= null) && - (physicalElement.length() > 0) && - (physicalElement.charAt(0) == firstCharacter) - ) - { - result = true; - } - - return result; - } - // ------------------------------------------------------------------------------------- - - public void initForHeight(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "PDCDrawingMgr.initForHeight(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = null; //actually depends on rating curve existence - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new StageToFlowValueMapper(ratingCurve); - rightAxisLabelString = "cfs"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "feet"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - - //observed data painter - if (obsTs != null) - { - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - } - - // forecast data painters - if (fcstTs != null) - { - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - } - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForHeightWithLists(String locationId, - List paramCodeList, - TsPaintableCanvas canvas) - { - - String header = "PDCDrawingMgr.initForHeightWithLists(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = "cfs"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - - List obsTsList = new ArrayList(); - List fcstTsList = new ArrayList(); - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstTsList.add(fcstTs); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - - CodeTimer stageTimer = new CodeTimer(); - - stageTimer.start(); - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsTsList.add(obsTs); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - ValueMapper valueMapper = new StageToFlowValueMapper(ratingCurve); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - boolean shouldPaint = true; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - // observed data painter - for (int i = 0; i < obsTsList.size(); i++) - { - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - } - - - - // forecast data painters - for (int i = 0; i < fcstTsList.size(); i++) - { - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - } - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForDischarge(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "PDCDrawingMgr.initForDischarge(): "; - - MeasuringUnit unit = MeasuringUnit.cfs; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "cfs"; - String rightAxisLabelString = null; //actually depends on rating curve existence - - //Set time - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - - String titleString = "River Discharge for " + locationId; - //read in the observed time series - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstDischargeTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstDischargeTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedDischargeTimeSeries(locationId, - paramCode, - getStartTime()); - stageTimer.stop(header + "loadObservedDischargeTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new FlowToStageValueMapper(ratingCurve); - rightAxisLabelString = "feet"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "cfs"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - -/* - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - */ - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - - - //------------------------------------------------------------------------------------ - - public void initForTemperature(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.degreesFahrenheit; - MeasuringUnit rightUnit = MeasuringUnit.degreesCelsius; - - canvas.setDisplayedMeasuringUnit(leftUnit); - // canvas.setLeftMargin(30); - // canvas.setRightMargin(30); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Deg. F"; - String rightAxisLabelString = "Deg. C"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Air Temperature for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedTemperatureTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - //-------------------------------------------------------------------------------------- - - public void initForWindSpeed(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.knots; - MeasuringUnit rightUnit = leftUnit; - - canvas.setDisplayedMeasuringUnit(leftUnit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Knots"; - String rightAxisLabelString = "Knots"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Wind Speed for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedWindTimeSeries(locationId, paramCode, leftUnit); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - //-------------------------------------------------------------------------------------- - - public void initForWindDirection(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.degrees; - MeasuringUnit rightUnit = leftUnit; - - canvas.setDisplayedMeasuringUnit(leftUnit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Degrees"; - String rightAxisLabelString = "Degrees"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Wind Direction for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedWindTimeSeries(locationId, paramCode, leftUnit); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - public void initForSnow(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.inches; - MeasuringUnit rightUnit = MeasuringUnit.mm; - - canvas.setDisplayedMeasuringUnit(leftUnit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Inches"; - String rightAxisLabelString = "mm"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Snow Depth for " + locationId; - - - ParamCode paramCode = getParamCode(paramCodeList); - - - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedSnowTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - public void initForDewpoint(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.degreesFahrenheit; - MeasuringUnit rightUnit = MeasuringUnit.degreesCelsius; - - - canvas.setDisplayedMeasuringUnit(leftUnit); - // canvas.setLeftMargin(30); - // canvas.setRightMargin(30); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Deg. F"; - String rightAxisLabelString = "Deg. C"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "DewPoint for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - //read in the observed time series - //dewpoint comes from the temperature table - IrregularTimeSeries obsTs = - _dataMgr.loadObservedTemperatureTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - // -------------------------------------------------------------------------------------------------- - - public void initForHumidity(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.unitless; - MeasuringUnit rightUnit = MeasuringUnit.unitless; - - - canvas.setDisplayedMeasuringUnit(leftUnit); - // canvas.setLeftMargin(30); - // canvas.setRightMargin(30); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Percent"; - String rightAxisLabelString = "Percent"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - ParamCode paramCode = getParamCode(paramCodeList); - - // set title and measuring units - - String titleString = "Relative Humidity for " + locationId; - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadRelativeHumidityTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - - String unitString = "%"; - - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString(), - unitString); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - // -------------------------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslCanvasPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addTsCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslTimeLinePainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - private void assignPainterToCanvas(TslBackgroundPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - public void initForPrecipTotal(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - MeasuringUnit measuringUnit = MeasuringUnit.inches; - canvas.setDisplayedMeasuringUnit(measuringUnit); - - - String leftAxisLabelString = measuringUnit.toString(); - String rightAxisLabelString = "mm"; - - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Hourly Precip totals for " + locationId; - //setCanvasTitle("Precip for " + locationId); - - // observed data painters - - ParamCode paramCode = getParamCode(paramCodeList); - - int durationInHours = getDurationInHours(paramCode.getIhfsDur()); - - RegularTimeSeries precipTimeSeries = - _dataMgr.loadPrecipData(locationId, durationInHours); - - IrregularTimeSeries irregularPrecipTimeSeries = - getIrregularTimeSeries(precipTimeSeries); - - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - irregularPrecipTimeSeries, - paramCode.toString()); - - //background painter - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - ValueMapper valueMapper = new UnitValueMapper(MeasuringUnit.inches, - MeasuringUnit.mm); - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - // observed data painters - - RegularTimeSeriesHolder precipTsHolder = new RegularTimeSeriesHolder(); - precipTsHolder.setTimeSeries(precipTimeSeries); - - - Color barColor = Color.BLUE; - TsBarPainter precipPainter = new TsBarPainter(barColor, - outlineColor, - precipTsHolder); - - assignPainterToCanvas(precipPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - - return; - } - - // ---------------------------------------------------------------------------------- - public void initForPrecipDualMode(String locationId, - List paramCodeList, - TsPaintableCanvas canvas) - { - - // String header = "initForPrecipDualMode(): "; - - //set up the measuring unit for this method and the canvas - MeasuringUnit unit = MeasuringUnit.inches; - canvas.setDisplayedMeasuringUnit(unit); - - ParamCode pcParamCode = null; - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "PP in."; - String rightAxisLabelString = "mm"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - ParamCode paramCode = getParamCode(paramCodeList); - - String titleString = "Precip PC and PP for " + locationId; - - //read in the observed PC time series - - CodeTimer pcTimer = new CodeTimer(); - pcTimer.start(); - IrregularTimeSeries obsTs = - _dataMgr.loadObservedPrecipPcTimeSeries(locationId, - paramCode, - getStartTime()); - - pcTimer.stop("db retrieval took"); - - //read in the preprocessed PP time series - // that comes from PDC's preprocessed files - int durationInHours = getDurationInHours(paramCode.getIhfsDur()); - - CodeTimer pdcPrecipTimer = new CodeTimer(); - pdcPrecipTimer.start(); - - RegularTimeSeries precipTotalsTimeSeries = - _dataMgr.loadPrecipData(locationId, durationInHours); - - pdcPrecipTimer.stop("PDC data retrieval took"); - - //convert to irregular time series - IrregularTimeSeries irregularPrecipTotalTimeSeries = - getIrregularTimeSeries(precipTotalsTimeSeries); - - //background painter with its ValueMapper - //create the valueMapper - double minPPValue = 0.0; - - ValueMapper valueMapper = null; - - IrregularTimeSeries normalizedObsTs = null; - - - //set up the appropriate value mapper - if (obsTs.getMeasurementCount() > 0) - { - - rightAxisLabelString = "PC in."; - - Measurement minPCMeasurement = obsTs.getMinMeasurement(); - - double minPCValue = minPPValue; - - if (minPCMeasurement != null) - { - minPCValue = minPCMeasurement.getValue(unit); - } - - valueMapper = new PrecipPPAndPCValueMapper(minPPValue, - minPCValue, - unit); - - //This simply subtracts off the minPCValue from all entries, - // so that the resulting timeseries starts at 0.0. This will - //enable it to be drawn on the same graph as the PP routines. - normalizedObsTs = scaleIrregularTimeSeriesByAddition(obsTs, - minPCValue); - - //set up the secondary paramcode - pcParamCode = new ParamCode(paramCode); - if (paramCode.getPe().equals("PP")) - { - pcParamCode.setPe("PC"); - pcParamCode.setIhfsDur(0); - pcParamCode.setShefDur("I"); - pcParamCode.setExtremum("Z"); - pcParamCode.setTypeSource(paramCode.getTypeSource()); - } - - } - else - { - rightAxisLabelString = "mm"; - normalizedObsTs = obsTs; - valueMapper = new UnitValueMapper(unit, MeasuringUnit.mm); - } - - String[] textHeaderStringArray = null; - - if (pcParamCode != null) //there is pc data - { - textHeaderStringArray = getTextHeaderStringArray(locationId, - irregularPrecipTotalTimeSeries, - paramCode.toString(), - obsTs, - pcParamCode.toString(), - irregularPrecipTotalTimeSeries.getMeasuringUnit().toString() - ); - } - else //there is no pc data - { - - textHeaderStringArray = - getTextHeaderStringArray(locationId, - irregularPrecipTotalTimeSeries, - paramCode.toString()); - } - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - // time line painter - TslTimeLinePainter timeLinePainter = - new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - - assignPainterToCanvas(timeLinePainter, canvas); - - - // observed PP data painters - RegularTimeSeriesHolder precipTsHolder = new RegularTimeSeriesHolder(); - precipTsHolder.setTimeSeries(precipTotalsTimeSeries); - - Color barColor = Color.BLUE; - TsBarPainter precipPainter = new TsBarPainter(barColor, - outlineColor, - precipTsHolder); - - assignPainterToCanvas(precipPainter, canvas); - - - //observed PC data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(normalizedObsTs); - - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - //tooltip listener - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ---------------------------------------------------------------------------------- - public IrregularTimeSeries scaleIrregularTimeSeriesByAddition(IrregularTimeSeries origTs, - double additive) - { - String header = "PDCDrawingMgr.scaleIrregularTimeSeriesByAddition(): "; - IrregularTimeSeries newTs = new IrregularTimeSeries(origTs.getMeasuringUnit()); - - AbsTimeMeasurement valueArray[] = origTs.getMeasurementArray(); - double value = 0; - - for (int i = 0 ; i < valueArray.length; i++) - { - AbsTimeMeasurement newMeasurement = new AbsTimeMeasurement(valueArray[i]); - value = newMeasurement.getValue() - additive; - - newMeasurement.setValue(value); - - newTs.insertMeasurement(newMeasurement); - } - - // System.out.println(header + "origTs = " + origTs); - // System.out.println(header + "newTs = " + newTs); - - return newTs; - } - - // ---------------------------------------------------------------------------------- - - public void initForPrecipPC(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - //set up the measuring unit for this method and the canvas - MeasuringUnit unit = MeasuringUnit.inches; - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "inches"; - String rightAxisLabelString = "mm"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - // set title and measuring units - - ParamCode paramCode = getParamCode(paramCodeList); - - - String titleString = "Precip PC for " + locationId; - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedPrecipPcTimeSeries(locationId, paramCode, getStartTime()); - - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(unit, MeasuringUnit.mm); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - //tooltip listener - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ---------------------------------------------------------------------------------- - - private int getDurationInHours(int ihfsDurationCode) - { - int durationInHours = 0; - - if ( (ihfsDurationCode >= 1000) && (ihfsDurationCode < 2000) ) - { - durationInHours = ihfsDurationCode - 1000; - } - if (ihfsDurationCode == 2001) - { - durationInHours = 24; - } - - return durationInHours; - } - // ---------------------------------------------------------------------------------- - - private IrregularTimeSeries getIrregularTimeSeries(RegularTimeSeries origTs) - { - MeasuringUnit unit = origTs.getMeasuringUnit(); - IrregularTimeSeries irregularTimeSeries = new IrregularTimeSeries(unit); - - int count = origTs.getMeasurementCount(); - - AbsTimeMeasurement measurement = null; - - for (int i = 0; i < count; i++) - { - measurement = origTs.getAbsTimeMeasurementByIndex(i); - irregularTimeSeries.insertMeasurement(measurement); - } - - return irregularTimeSeries; - } - - - // ------------------------------------------------------------------------------------- - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode - ) - - { - MeasuringUnit unit = obsTs.getMeasuringUnit(); - String unitString = unit.getName(); - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode, - String unitString - ) - - { - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCodeString, - IrregularTimeSeries fcstTs, - String otherParamCodeString, - String unitString - ) - - { - - String header = "getTextHeadStringArray()[6-args] : "; - - String[] textHeaderStringArray = null; - IrregularTimeSeries maxMinTs = null; - - if (paramCodeString == null) - { - paramCodeString = ""; - } - StringBuffer paramCodeStringBuffer = new StringBuffer(paramCodeString); - - - Location location = _dataMgr.getLocationInfo(locationId); - if (location == null) - { - location = new Location(); - location.setLid(locationId); - location.setLocationName("Unknown location"); - location.setElevation(0); - - } - - //determine units and the max, min, and last values - MeasuringUnit unit = determineUnit(obsTs, fcstTs); - - long startTime = getStartTime(); - long endTime = getEndTime(); - - - System.out.println(header + "before get max and min and last measurements "); - - AbsTimeMeasurement max = getMaxTsMeasurement(obsTs, fcstTs, unit, startTime, endTime); - System.out.println(header + "after get max "); - - AbsTimeMeasurement min = getMinTsMeasurement(obsTs, fcstTs, unit, startTime, endTime); - System.out.println(header + "after get min "); - - - AbsTimeMeasurement last = getLastMeasurement(obsTs, fcstTs, unit, startTime, endTime); - System.out.println(header + "after get last "); - - - System.out.println(header + "after get max and min and last measurements "); - - - //append to the param code string - if (otherParamCodeString != null) - { - paramCodeStringBuffer.append(" " + otherParamCodeString); - } - - // assign values to the textHeaderStringArray - textHeaderStringArray = new String[5]; - textHeaderStringArray[0] = locationId + " - " + - location.getLocationName() + " - " + - "Elevation: " + location.getElevation() + " feet"; - - textHeaderStringArray[1] = paramCodeStringBuffer.toString(); - textHeaderStringArray[2] = "Max = " + getMeasurementString(max, unitString); - textHeaderStringArray[3] = "Min = " + getMeasurementString(min, unitString); - textHeaderStringArray[4] = "Last = " + getMeasurementString(last, unitString); - - return textHeaderStringArray; - } - // -------------------------------------------------------------------------------------------------- - private MeasuringUnit determineUnit(IrregularTimeSeries ts1, IrregularTimeSeries ts2) - { - MeasuringUnit unit = MeasuringUnit.feet; - IrregularTimeSeries notNullTs = null; - - // pick an available time series to use for calculation max and min and last values - if (ts1 != null) - { - notNullTs = ts1; - } - else if (ts2 != null) - { - notNullTs = ts2; - } - else - { - notNullTs = null; - } - - if (notNullTs != null) - { - unit = notNullTs.getMeasuringUnit(); - } - - return unit; - } - - // -------------------------------------------------------------------------------------------------- - - private AbsTimeMeasurement getLastMeasurement(IrregularTimeSeries ts1, - IrregularTimeSeries ts2, - MeasuringUnit unit, - long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement m1 = null; - AbsTimeMeasurement m2 = null; - - m1 = getLastMeasurement(ts1, unit, startTime, endTime); - m2 = getLastMeasurement(ts2, unit, startTime, endTime); - - - if ((m1 != null) && (m2 != null)) - { - if (m1.getTime() > m2.getTime()) - { - measurement = m1; - } - else - { - measurement = m2; - } - } - else if (m1 != null) - { - measurement = m1; - } - else if (m2 != null) - { - measurement = m2; - } - - return measurement; - } - - // -------------------------------------------------------------------------------------------------- - - - private AbsTimeMeasurement getLastMeasurement(IrregularTimeSeries timeSeries, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement measurement = null; - - if (timeSeries != null) - { - int count = timeSeries.getMeasurementCount(); - - for (int i = count - 1; i >= 0; i--) - { - measurement = timeSeries.getAbsTimeMeasurementByIndex(i); - if (measurement != null) - { - long time = measurement.getTime(); - - if ((time <= endTime) && (time >= startTime)) - { - break; // quit, I found the measurement that I want. - } - } - } - } - - measurement = getMeasurementByUnit(measurement, unit); - - return measurement; - - } - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getMaxTsMeasurement(IrregularTimeSeries ts1, - IrregularTimeSeries ts2, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement returnMeasurement = null; - - AbsTimeMeasurement m1 = null; - AbsTimeMeasurement m2 = null; - int notNullCount = 0; - - if (ts1 != null) - { - m1 = ts1.getMaxMeasurement(startTime, endTime); - if (m1 != null) - { - returnMeasurement = m1; - notNullCount++; - } - } - if (ts2 != null) - { - m2 = ts2.getMaxMeasurement(startTime, endTime); - if (m2 != null) - { - notNullCount++; - if (notNullCount == 1) // ts1 was null - { - returnMeasurement = m2; - } - else - // notNullCount == 2, so ts1 was not null, need to compare - { - if (m2.getValue(unit) > m1.getValue(unit)) - { - returnMeasurement = m2; - } - } - } - } - - returnMeasurement = getMeasurementByUnit(returnMeasurement, unit); - - return returnMeasurement; - } - - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getMinTsMeasurement(IrregularTimeSeries ts1, - IrregularTimeSeries ts2, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement returnMeasurement = null; - - AbsTimeMeasurement m1 = null; - AbsTimeMeasurement m2 = null; - int notNullCount = 0; - - if (ts1 != null) - { - m1 = ts1.getMinMeasurement(startTime, endTime); - if (m1 != null) - { - returnMeasurement = m1; - notNullCount++; - } - } - if (ts2 != null) - { - m2 = ts2.getMinMeasurement(startTime, endTime); - if (m2 != null) - { - notNullCount++; - if (notNullCount == 1) // ts1 was null - { - returnMeasurement = m2; - } - else - // notNullCount == 2, so ts1 was not null, need to compare - { - if (m2.getValue(unit) < m1.getValue(unit)) - { - returnMeasurement = m2; - } - } - } - } - - returnMeasurement = getMeasurementByUnit(returnMeasurement, unit); - - return returnMeasurement; - } - - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getMeasurementByUnit(AbsTimeMeasurement origMeasurement, - MeasuringUnit unit) - { - AbsTimeMeasurement measurement = origMeasurement; - - if ( (origMeasurement != null) && (origMeasurement.getUnit() != unit)) - { - measurement = AbsTimeMeasurement.getConvertedCopy(origMeasurement, unit); - } - - return measurement; - } - - // -------------------------------------------------------------------------------------------------- - - - private String getMeasurementString(AbsTimeMeasurement measurement, String unitString) - { - String measurementString = null; - - if (measurement != null) - { - String timeString = - DbTimeHelper.getDateTimeStringFromLongTime(measurement.getTime()); - - //get rid of the seconds - timeString = timeString.substring(0, timeString.length()-3); - - double value = MathHelper.roundToNDecimalPlaces(measurement.getValue(), 2); - - measurementString = - value + " " + - unitString + - " at " + timeString + "Z"; - - } - else - { - measurementString = "Not Available"; - } - - return measurementString; - } - - // -------------------------------------------------------------------------------------------------- - private String wrapInHTML(String origString) - { - StringBuffer buffer = new StringBuffer("
" + origString + "
"); - - return buffer.toString(); - } -// ------------------------------------------------------------ - private String getVerticalText(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - buffer.append(charArray[i]); - - //don't do a break for the last one - if (i < charArray.length-1) - { - buffer.append("
"); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } -// ------------------------------------------------------------ - private String getVerticalTextFromNewLines(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - char c = charArray[i]; - if (c == '\n') - { - buffer.append("
"); - } - else - { - buffer.append(c); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } - // -------------------------------------------------------------------------------------------------- - - - /** - * @param startTime The startTime to set. - */ - public void setStartTime(long startTime) - { - _startTime = startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @return Returns the startTime. - */ - public long getStartTime() - { - return _startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @param endTime The endTime to set. - */ - public void setEndTime(long endTime) - { - _endTime = endTime; - } - /** - * @return Returns the endTime. - */ - public long getEndTime() - { - return _endTime; - } - - // -------------------------------------------------------------------------------------------------- - - - - - // -------------------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/pdc/PdcTslDataManager.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/pdc/PdcTslDataManager.java deleted file mode 100644 index 6476a1bbe3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/pdc/PdcTslDataManager.java +++ /dev/null @@ -1,1305 +0,0 @@ -package ohd.hseb.timeserieslite.pdc; - -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LocPDCRecord; -import ohd.hseb.ihfsdb.generated.LocPDCView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RawPCRecord; -import ohd.hseb.ihfsdb.generated.RawPCTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.SnowRecord; -import ohd.hseb.ihfsdb.generated.SnowTable; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.ihfsdb.generated.TemperatureRecord; -import ohd.hseb.ihfsdb.generated.TemperatureTable; -import ohd.hseb.ihfsdb.generated.WeatherRecord; -import ohd.hseb.ihfsdb.generated.WeatherTable; -import ohd.hseb.ihfsdb.generated.WindRecord; -import ohd.hseb.ihfsdb.generated.WindTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.pdc_pp.PDCFileReader; -import ohd.hseb.pdc_pp.RegularObsTimeSeries; -import ohd.hseb.pdc_pp.TimeValuePair; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PdcTslDataManager { - - // -------------------------------------------------------------------------------------------- - - public static final double MISSING = -999.0; - - private static final int _defaultQualityCode = 1879048191; - - private static final int _questionable_bad_threshold = 1073741824; - - private static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - private static final long MILLIS_PER_YEAR = (365L * 24L * 60L * 60L * 1000L); - - private Database _db = null; - - private Logger _logger = null; - - private String _jdbcConnectionString = null; - - private PDCDataType _dataType = null; - - private String _physicalElement = null; - - private String _preprocessedFilePath = null; - - private double MAX_REASONABLE_PRECIP = 30; // inches per hour - - // --------------------------------------------------------------------------------- - - public PdcTslDataManager(String jdbcConnectionString) { - _logger = new FileLogger(true); - - _jdbcConnectionString = jdbcConnectionString; - - _db = new Database(); - - _db.connect(_jdbcConnectionString); - - getAppsDefaults(); - } - - // --------------------------------------------------------------------------------- - - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - - _preprocessedFilePath = ad.getToken("pdc_pp_dir") + "/"; - } - - // ------------------------------------------------------------------------------------- - - private void connect(String connectionString) { - _db.connectWithDriverSearch(connectionString); - } - - // ------------------------------------------------------------------------------------- - - public void disconnect() { - _db.disconnect(); - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSource(String lid, String pe) { - String header = "PdcTslDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + "'" + " AND pe = '" + pe - + "'" + " AND dur = 0 " + " AND ts like 'F%' " - + " order by ts_rank ASC"; - - try { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - if (pe.charAt(0) == 'H') { - for (int i = 0; i < recordList.size(); i++) { - record = (IngestFilterRecord) recordList.get(i); - if (fcstHeightRecordExists(record)) { - newTypeSource = record.getTs(); - break; - } - } - - } else // pe is not 'H*', so don't look at fcstHeight to see if - // it exists - { - newTypeSource = record.getTs(); - } - - } - } catch (SQLException e) { - logSQLException(e); - } - - // System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // ---------------------------------------------------------------------------------- - public boolean fcstHeightRecordExists(IngestFilterRecord ingestRecord) { - boolean result = false; - - String header = "PdcTslDataManager.fcstHeightRecordExists(): "; - - FcstHeightTable table = new FcstHeightTable(_db); - - String whereClause = "WHERE lid = '" + ingestRecord.getLid() + "'" - + " AND pe = '" + ingestRecord.getPe() + "'" + " AND dur = " - + ingestRecord.getDur() + " AND ts = '" + ingestRecord.getTs() - + "'"; - - try { - int recordCount = table.selectCount(whereClause); - - if (recordCount > 0) { - result = true; - } - } catch (SQLException e) { - logSQLException(e); - } - - return result; - } - - // ---------------------------------------------------------------------------------- - /* - * public String getPreferredFcstTypeSourceByIngestFilter(String lid, - * ParamCode paramCode) { String header = - * "PdcTslDataManager.getPreferredFcstTypeSourceByIngestFilter(): "; - * - * String newTypeSource = null; - * - * IngestFilterTable table = new IngestFilterTable(_db); - * - * IngestFilterRecord record = null; - * - * String whereClause = "WHERE lid = '" + lid + "' AND pe = '" + - * paramCode.getPe() + "'" + "AND dur = 0 " + "AND ts like 'F%' " + - * " order by ts_rank ASC" ; - * - * try { List recordList = table.select(whereClause); if (recordList.size() - * > 0) { int i = 0; //for (int i = 0; i < recordList.size(); i++) { record - * = (IngestFilterRecord) recordList.get(i); newTypeSource = record.getTs(); - * } } } catch(SQLException e) { logSQLException(e); } - * - * System.out.println(header + " newTypeSource = " + newTypeSource); - * - * return newTypeSource; } - * - * // - * ------------------------------------------------------------------------ - * ------------- public String getPreferredFcstTypeSourceByFcstHeight(String - * lid, ParamCode paramCode) { String header = - * "PdcTslDataManager.getPreferredFcstTypeSource(): "; - * - * String newTypeSource = null; - * - * FcstHeightTable table = new FcstHeightTable(_db); - * - * FcstHeightRecord record = null; - * - * String whereClause = "WHERE lid = '" + lid + "' AND pe = '" + - * paramCode.getPe() + "'" + "AND dur = 0 " + - * " order by basistime DESC, validtime ASC" ; - * - * try { List recordList = table.selectNRecords(whereClause,1); if - * (recordList.size() > 0) { int i = 0; //for (int i = 0; i < - * recordList.size(); i++) { record = (FcstHeightRecord) recordList.get(i); - * newTypeSource = record.getTs(); } } } catch(SQLException e) { - * logSQLException(e); } - * - * System.out.println(header + " newTypeSource = " + newTypeSource); - * - * return newTypeSource; } - */ - // ------------------------------------------------------------------------------------- - public SigRiverLevels loadSigRiverLevels(String locationId) { - String header = "PdcTslDataManager.loadSigRiverLevels(): "; - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (RiverstatRecord) recordList.get(0); - - String primaryPe = record.getPrimary_pe(); - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - - if (DbTable.isNull(actionStage)) { - System.out.println(header + " actionStage is null for " - + locationId); - } - if (DbTable.isNull(record.getPrimary_pe())) { - System.out.println(header + " primary_pe is null for " - + locationId); - record.setPrimary_pe(" "); - } - - levels = new SigRiverLevels(locationId, record.getPrimary_pe(), - floodStage, actionStage, floodFlow, actionFlow); - - } - } catch (SQLException e) { - logSQLException(e); - } - - return levels; - } - - // -------------------------------------------------------------------------------------------------- - - public RatingCurve loadRatingCurve(String locationId) { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - try { - ratingRecordList = ratingTable.select("WHERE LID = '" + locationId - + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" - + locationId + "' AND active = 'T' ORDER BY date desc", 1); - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId - + "'"); - - // determine total amount of active - // rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList - .get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - // System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - // initialize the RatingCurve object with data from the database, - // including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - // done by addRatingPoint - // ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } // end for - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList - .get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord - .getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } catch (SQLException e) { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - // ------------------------------------------------------------------------------------- - - public RegularTimeSeries loadPrecipData(String locationId, - int durationInHours) { - String header = "PdcTslDataManager.loadPrecipData(): "; - RegularTimeSeries timeSeries = null; - - if (locationId.equalsIgnoreCase("MAX")) { - timeSeries = loadPrecipDataForMaximumInArea(locationId, - durationInHours); - } else if (locationId.equalsIgnoreCase("AVG")) { - timeSeries = loadPrecipDataForAverageInArea(locationId, - durationInHours); - } else { - timeSeries = loadPrecipDataForRealLocation(locationId, - durationInHours); - } - - return timeSeries; - - } - - // ------------------------------------------------------------------------------------- - public RegularTimeSeries loadPrecipDataForRealLocation(String locationId, - int durationInHours) { - - // String header = "PdcTslDataManager.loadPrecipDataRealLocation(): "; - RegularTimeSeries timeSeries = null; - String precipFileName = getPrecipFileName(durationInHours); - - List list = readPrecipObsTimeSeriesListFromCachedFile(precipFileName); - - // iterate through the list to find the matching locationId - // once found, translate the RegularObsTimeSeries to a RegularTimeSeries - - for (int i = 0; i < list.size(); i++) { - RegularObsTimeSeries regularObsTimeSeries = (RegularObsTimeSeries) list - .get(i); - - String lid = regularObsTimeSeries.getDescriptor().getLid(); - - if (lid.equals(locationId)) { - timeSeries = getRegularTimeSeries(regularObsTimeSeries); - break; - } - - } - - return timeSeries; - } - - // ------------------------------------------------------------------------------------- - public RegularTimeSeries loadPrecipDataForMaximumInArea(String locationId, - int durationInHours) { - String header = "PdcTslDataManager.loadPrecipDataForMaximumInArea(): "; - RegularTimeSeries timeSeries = null; - String precipFileName = getPrecipFileName(durationInHours); - - List regularObsTimeSeriesList = readPrecipObsTimeSeriesListFromCachedFile(precipFileName); - - RegularObsTimeSeries maxRegularObsTimeSeries = null; - - RegularObsTimeSeries regularObsTimeSeries = null; - - // let the first obstimeseries initialize the max time series - if (regularObsTimeSeriesList.size() > 0) { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList - .get(0); - maxRegularObsTimeSeries = regularObsTimeSeries; - } - - List maxTimeValuePairList = maxRegularObsTimeSeries - .getTimeValuePairList(true); - - // iterate through the list of RegularObsTimeSeries to set the maximums - - for (int i = 1; i < regularObsTimeSeriesList.size(); i++) { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList - .get(i); - List timeValuePairList = regularObsTimeSeries - .getTimeValuePairList(true); - - for (int j = 0; j < timeValuePairList.size(); j++) { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(j); - long time = pair.getDateTime(); - double value = pair.getValue(); - - TimeValuePair maxPair = (TimeValuePair) maxTimeValuePairList - .get(j); - double maxValue = maxPair.getValue(); - - if (value < MAX_REASONABLE_PRECIP) { - if (value > maxValue) { - String timeString = DbTimeHelper - .getDateTimeStringFromLongTime(time); - - System.out.println(header + " new max = " + value - + " at " - + regularObsTimeSeries.getDescriptor().getLid() - + " for 1- hour ending at " + timeString); - - maxPair.setValue(value); - } - } - } - } - - // just to be sure - maxRegularObsTimeSeries.setTimeValuePairList(maxTimeValuePairList); - - // translate to a normal - timeSeries = getRegularTimeSeries(maxRegularObsTimeSeries); - - return timeSeries; - - } - - // ------------------------------------------------------------------------------------- - - public RegularTimeSeries loadPrecipDataForAverageInArea(String locationId, - int durationInHours) { - // String header = - // "PdcTslDataManager.loadPrecipDataForAverageInArea(): "; - RegularTimeSeries timeSeries = null; - - String precipFileName = getPrecipFileName(durationInHours); - - List regularObsTimeSeriesList = readPrecipObsTimeSeriesListFromCachedFile(precipFileName); - - RegularObsTimeSeries averageRegularObsTimeSeries = null; - RegularObsTimeSeries regularObsTimeSeries = null; - List averageTimeValuePairList = null; - - if ((regularObsTimeSeriesList != null) - && (regularObsTimeSeriesList.size() > 0)) { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList - .get(0); - averageRegularObsTimeSeries = new RegularObsTimeSeries( - regularObsTimeSeries); - - averageTimeValuePairList = averageRegularObsTimeSeries - .getTimeValuePairList(true); - } else { - return timeSeries; - } - - // iterate through the list of RegularObsTimeSeries to set the totals - - for (int i = 0; i < regularObsTimeSeriesList.size(); i++) { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList - .get(i); - List timeValuePairList = regularObsTimeSeries - .getTimeValuePairList(true); - - for (int j = 0; j < timeValuePairList.size(); j++) { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(j); - long time = pair.getDateTime(); - double value = pair.getValue(); - double totalValue = 0; - double previousValue = 0; - - if ((value < MAX_REASONABLE_PRECIP) && (value >= 0.0)) { - TimeValuePair totalPair = (TimeValuePair) averageTimeValuePairList - .get(j); - if (i == 0) // first iteration only, init the previous - // totals to Zero - { - previousValue = 0; - } else { - previousValue = totalPair.getValue(); - } - - totalValue = previousValue + value; - - totalPair.setValue(totalValue); - } - } - } - - // determine the number of time series to divide by - double count = regularObsTimeSeriesList.size(); - - // take the totals and convert to averages - for (int i = 0; i < averageTimeValuePairList.size(); i++) { - TimeValuePair pair = (TimeValuePair) averageTimeValuePairList - .get(i); - long time = pair.getDateTime(); - double value = pair.getValue() / count; - - pair.setValue(value); - - } - - // just to be sure - averageRegularObsTimeSeries - .setTimeValuePairList(averageTimeValuePairList); - - // translate to a normal - timeSeries = getRegularTimeSeries(averageRegularObsTimeSeries); - - return timeSeries; - - } - - // ------------------------------------------------------------------------------------- - - public RegularTimeSeries getRegularTimeSeries( - RegularObsTimeSeries obsTimeSeries) { - - long startTime = obsTimeSeries.getDescriptor().getStartTime(); - long endTime = obsTimeSeries.getDescriptor().getEndTime(); - long timeStepIntervalInMillis = obsTimeSeries - .getTimeStepIntervalInMillis(); - long timeStepIntervalInHours = timeStepIntervalInMillis - / MILLIS_PER_HOUR; - MeasuringUnit unit = MeasuringUnit.inches; - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - String endTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(endTime); - - RegularTimeSeries regularTimeSeries = new RegularTimeSeries(startTime, - endTime, (int) timeStepIntervalInHours, unit); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - for (int i = 0; i < timeValuePairList.size(); i++) { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(i); - long time = pair.getDateTime(); - double value = pair.getValue(); - - Measurement measurement = new Measurement(value, unit); - - regularTimeSeries.setMeasurementByTime(measurement, time); - } - - // Days go from 12Z to 12Z, not 0Z to 0Z, - // so shift the time serires by 12 hours - if (timeStepIntervalInHours == 24) { - regularTimeSeries.shiftStartEndTimeHours(12); - } - - return regularTimeSeries; - } - - // ------------------------------------------------------------------------------------- - - public List readPrecipObsTimeSeriesListFromCachedFile(String fullFilePath) { - String header = "PdcTslDataManager.readPrecipObsTimeSeriesListFromCachedFile(): "; - - PDCFileReader reader = new PDCFileReader(fullFilePath); - - CodeTimer readerTimer = new CodeTimer(); - - readerTimer.start(); - List obsTimeSeriesList = reader.read(); - readerTimer.stop(header + "reader.read() took"); - - return obsTimeSeriesList; - } - - // ------------------------------------------------------------------------------------- - private void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - // ------------------------------------------------------- - public String getLocationName(String locationId) { - return loadLocationName(locationId); - } - - // ------------------------------------------------------- - private String loadLocationName(String locationId) { - - String locationName = null; - - LocationRecord record = null; - LocationTable table = new LocationTable(_db); - - try { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (LocationRecord) recordList.get(0); - locationName = record.getName(); - } - } catch (SQLException e) { - logSQLException(e); - } - - return locationName; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId, - ParamCode paramCode, long startTime) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - // ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (HeightRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedDischargeTimeSeries( - String locationId, ParamCode paramCode, long startTime) { - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "PdcTslDataManager.loadObservedDischargeTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - // ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (DischargeRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedPrecipPcTimeSeries( - String locationId, ParamCode paramCode, long startTime) { - - MeasuringUnit unit = MeasuringUnit.inches; - - String header = "PdcTslDataManager.loadObservedPrecipPcTimeSeries(): "; - IrregularTimeSeries timeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - RawPCTable table = new RawPCTable(_db); - RawPCRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - long currentTime = System.currentTimeMillis(); - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = 'PC' " + " AND ts = '" + paramCode.getTypeSource() - + "'" + " AND dur = 0 " + " AND quality_code >= " - + _questionable_bad_threshold + " AND obstime >= '" - + startTimeString + "'"; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (RawPCRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - timeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return timeSeries; - - } - - // ------------------------------------------------------------------------ - public IrregularTimeSeries loadObservedTemperatureTimeSeries( - String locationId, ParamCode paramCode) { - String header = "PdcTslDataManager.loadTemperatureTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.degreesFahrenheit; - - IrregularTimeSeries timeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - TemperatureTable table = new TemperatureTable(_db); - TemperatureRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (TemperatureRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - timeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return timeSeries; - - } - - // ----------------------------------------------------------------------------------- - public IrregularTimeSeries loadRelativeHumidityTimeSeries( - String locationId, ParamCode paramCode) { - String header = "PdcTslDataManager.loadRelativeHumidityTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.unitless; - - IrregularTimeSeries timeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - WeatherTable table = new WeatherTable(_db); - WeatherRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (WeatherRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - timeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return timeSeries; - - } - - // ----------------------------------------------------------------------------------- - public IrregularTimeSeries loadObservedWindTimeSeries(String locationId, - ParamCode paramCode, MeasuringUnit measuringUnit) { - String header = "PdcTslDataManager.loadObservedWindSpeedTimeSeries(): "; - - MeasuringUnit unit = measuringUnit; - - IrregularTimeSeries timeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - WindTable table = new WindTable(_db); - WindRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (WindRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - timeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return timeSeries; - - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadObservedSnowTimeSeries(String locationId, - ParamCode paramCode) { - String header = "PdcTslDataManager.loadObservedSnowTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.inches; - - IrregularTimeSeries timeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - SnowTable table = new SnowTable(_db); - SnowRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (SnowRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - timeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return timeSeries; - - } - - // ----------------------------------------------------------------------------------- - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadObservedDewpointTimeSeries( - String locationId, ParamCode paramCode) { - String header = "PdcTslDataManager.loadObservedDewpointTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.inches; - - IrregularTimeSeries timeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - TemperatureTable table = new TemperatureTable(_db); - TemperatureRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (TemperatureRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - timeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return timeSeries; - - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - ParamCode paramCode) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - long originalBasisTime = 0; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (FcstHeightRecord) recordList.get(i); - - if (i == 0) { - originalBasisTime = record.getBasistime(); - } else { - if (record.getBasistime() != originalBasisTime) { - break; - } - } - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + - // measurement); - - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - ParamCode paramCode) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstDischargeTimeSeries(): "; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - long originalBasisTime = 0; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (FcstDischargeRecord) recordList.get(i); - - if (i == 0) { - originalBasisTime = record.getBasistime(); - } else { - if (record.getBasistime() != originalBasisTime) { - break; - } - } - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + - // measurement); - - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return dischargeTimeSeries; - } - - // ----------------------------------------------------------------------------------- - - public Location getLocationInfo(String locationId) { - DecimalFormat decimalFormat = new DecimalFormat("0.00"); - - Location location = null; - String whereClause = " WHERE lid = '" + locationId + "'"; - - LocPDCView locPDCView = new LocPDCView(_db); - RiverstatTable riverStatTable = new RiverstatTable(_db); - StnClassTable stationClassTable = new StnClassTable(_db); - - List locPDCViewList = null; - List riverStatRecordList = null; - List stationClassList = null; - - try { - locPDCViewList = locPDCView.select(whereClause); - riverStatRecordList = riverStatTable.select(whereClause); - - stationClassList = stationClassTable.select(whereClause); - - } catch (SQLException e) { - logSQLException(e); - e.printStackTrace(); - } - - for (int i = 0; i < locPDCViewList.size(); i++) { - LocPDCRecord locPDCRecord = (LocPDCRecord) locPDCViewList.get(i); - location = new Location(); - location.setLid(locPDCRecord.getLid().trim()); - location.setHsa(locPDCRecord.getHsa().trim()); - - location.setLat(Double.parseDouble(decimalFormat - .format(locPDCRecord.getLat()))); - location.setLon(Double.parseDouble(decimalFormat - .format(locPDCRecord.getLon()))); - - location.setElevation(locPDCRecord.getElev()); - location.setLocationName(locPDCRecord.getName()); - location.setRiverStation(false); - - double fq = locPDCRecord.getFq(); - double fs = locPDCRecord.getFs(); - - if (fq == 0) // missing value - { - location.setFloodFlow(MISSING); - } else { - location.setFloodFlow(fq); - } - - if (fs == 0) // missing value - { - location.setFloodStage(MISSING); - } else { - location.setFloodStage(fs); - } - - if ((fq == 0.0) && (fs != 0.0) - && (location.getRatingCurve() != null)) { - location.setFloodFlow(location.getRatingCurve() - .getDischargeFromStage(fs)); - } - - String dispClass = locPDCRecord.getDisp_class(); - - if ((dispClass.indexOf("F")) != -1) { - location.setFcstPoint(true); - } else { - location.setFcstPoint(false); - } - - String dcp = locPDCRecord.getIs_dcp(); - - if ((dcp.indexOf("T")) != -1) { - location.setDCP(true); - } else { - location.setDCP(false); - } - - String observer = locPDCRecord.getIs_observer(); - - if ((observer.indexOf("T")) != -1) { - location.setObserver(true); - } else { - location.setObserver(false); - } - - location.setTelemType(locPDCRecord.getTelem_type()); - - } - - return location; - } - - // ------------------------------------------------------------------------ - private String getPrecipFileName(int durationInHours) { - String precipFileName = _preprocessedFilePath + "/Precip" - + durationInHours + "Hour.dat"; - return precipFileName; - } - - // ------------------------------------------------------------------------ - - public long getLatestHourTime() { - return TimeHelper.truncateTimeInMillisToNearestHour(System - .currentTimeMillis(), 1); - } - // ----------------------------------------------------------------------------------- - -} // end PdcTslDataManager diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/rivermon/RiverMonDrawingMgr.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/rivermon/RiverMonDrawingMgr.java deleted file mode 100644 index dc13413f16..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/rivermon/RiverMonDrawingMgr.java +++ /dev/null @@ -1,1233 +0,0 @@ -package ohd.hseb.timeserieslite.rivermon; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.FlowToStageValueMapper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.timeserieslite.TSLDrawingMgr; -import ohd.hseb.timeserieslite.TSLFrame; -import ohd.hseb.timeserieslite.gui.drawing.SignificantLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TsCanvasToolTipListener; -import ohd.hseb.timeserieslite.gui.drawing.TsDataPointPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslBackgroundPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslCanvasPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslTimeLinePainter; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class RiverMonDrawingMgr implements TSLDrawingMgr -{ - private static final long MILLIS_PER_HOUR = 60*60*1000; - private static final int TOP_MARGIN = 100; - private int _hoursBackInTime = 120; - private int _hoursForwardInTime = 168; - - private RiverMonTslDataManager _dataMgr = null; - private String _locationId = null; - private List _paramCodeList = new ArrayList(); - private String _jdbcConnectionString = null; - - // private PDCDataType _dataType = null; - private List _dataTypeList = new ArrayList(); - - private long _startTime = 0; - private long _endTime = 0; - - private int HOURS_TO_ROUND = 6; - - - private static Map _physicalElementMap = new HashMap(); - static - { - _physicalElementMap.put("HG", PDCDataType.HEIGHT); - _physicalElementMap.put("HP", PDCDataType.HEIGHT); - _physicalElementMap.put("HT", PDCDataType.HEIGHT); - _physicalElementMap.put("QR", PDCDataType.DISCHARGE); - _physicalElementMap.put("QT", PDCDataType.DISCHARGE); - _physicalElementMap.put("LS", PDCDataType.LAKE_STORAGE); - - } - - - // -------------------------------------------------------------------------------------------------- - - public RiverMonDrawingMgr() - { - - } - // -------------------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) - { - - CodeTimer timer = new CodeTimer(); - - handleCommandLineArgs(argStringArray); - - String header = "PDCDrawingMgr.display()"; - - - TSLFrame frame = new TSLFrame(); - - frame.setExitOnClose(exitOnClose); - - System.out.println(header + "after TSLFrame()"); - - TsPaintableCanvas canvas = frame.getCanvas(); - - - PDCDataType dataType = null; - - if ( _dataTypeList.size() > 0 ) - { - dataType = (PDCDataType) _dataTypeList.get(0); - } - - initializeCanvas(dataType, _paramCodeList, canvas); - - timer.start(); - frame.setVisible(true); - timer.stop("setVisible() took "); - - } - - // -------------------------------------------------------------------------------------------------- - - private void initializeCanvas(PDCDataType dataType, - List paramCodeList, - TsPaintableCanvas canvas) - { - initializeTimeWindow(canvas); - - //make room for the large area required by the text header in the graph - canvas.setTopMargin(TOP_MARGIN); - - - if (dataType == PDCDataType.HEIGHT) - { - initForHeight(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DISCHARGE) - { - initForDischarge(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.LAKE_STORAGE) - { - // initForLakeStorage(_locationId, canvas); - } - - - - //call this again to make it redraw everything correctly - // it wasn't working without this - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void initializeTimeWindow(TsPaintableCanvas canvas) - { - //set up time window - long currentTime = System.currentTimeMillis(); - long roundedCurrentTime = - TimeHelper.truncateTimeInMillisToNearestHour(currentTime, HOURS_TO_ROUND); - - setStartTime(roundedCurrentTime - (_hoursBackInTime * MILLIS_PER_HOUR)); - setEndTime(getStartTime() + (_hoursForwardInTime * MILLIS_PER_HOUR)); - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private boolean isValueAvailable(Measurement measurement, MeasuringUnit unit) - { - boolean result = false; - - if (measurement != null) - { - if (measurement.getValue(unit) > 0.0) - { - result = true; - } - } - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private void addCanvasListeners(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - //Add listener for the tooltip - TsCanvasToolTipListener toolTipMgr = new TsCanvasToolTipListener(canvas, valueMapper); - canvas.addMouseMotionListener(toolTipMgr); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void handleCommandLineArgs(String[] argStringArray) - { - String header = "PdcDrawingManager.handleCommandLineArgs(): "; - - //includes the optional jdbcConnectionString - if (argStringArray.length > 1) - { - _jdbcConnectionString = argStringArray[1]; - _dataMgr = new RiverMonTslDataManager(_jdbcConnectionString); - } - - //location id - if (argStringArray.length > 2) - { - _locationId = argStringArray[2]; - } - - -// create param code list and dataType list - for (int i = 3; i < argStringArray.length; i++) - { - String paramCodeString = argStringArray[i]; - System.out.println(header + "paramCodeString = " + paramCodeString); - - if ((paramCodeString != null) && (paramCodeString.length() == 6)) //valid example = HRIRGZ - { - ParamCode paramCode = new ParamCode(paramCodeString); - - paramCode = expandParamCode(_locationId, paramCode); - - if (paramCode != null) - { - _paramCodeList.add(paramCode); - - // String physicalElement = paramCode.substring(0,2); - PDCDataType dataType = getDataTypeFromPhysicalElement(paramCode.getPe()); - _dataTypeList.add(dataType); - } - } - } - - return; - } - // ------------------------------------------------------------------------------------- - private ParamCode expandParamCode(String locationId, ParamCode paramCode) - { - - String header = "RiverMonDrawingMgr.expandParamCode(): "; - ParamCode expandedParamCode = new ParamCode(paramCode); - String expandedParamCodeString = null; - - String typeSource = paramCode.getTypeSource(); - String peString = paramCode.getPe(); - - if (typeSource.indexOf('-') == 1) - { - if (typeSource.charAt(0) == 'F') - { - typeSource = _dataMgr.getPreferredFcstTypeSource(locationId, peString); - - if (typeSource != null) - { - expandedParamCode.setTypeSource(typeSource); - expandedParamCodeString = expandedParamCode.toString(); - } - else - { - expandedParamCode = null; - expandedParamCodeString = null; - } - } - - } - else - { - expandedParamCodeString = expandedParamCode.toString(); - } - - System.out.println(header + "original paramCode = " + paramCode.toString() ); - System.out.println(header + "expandedParamCode = " + expandedParamCodeString ); - - return expandedParamCode; - - } - - // ------------------------------------------------------------------------------------- - - ParamCode getParamCode(List paramCodeList) - { - ParamCode paramCode = null; - - - if ( (paramCodeList != null) && (paramCodeList.size() > 0) ) - { - paramCode = (ParamCode) paramCodeList.get(0); - } - - return paramCode; - } - - - // ------------------------------------------------------------------------------------- - - PDCDataType getDataTypeFromPhysicalElement(String physicalElement) - { - - PDCDataType dataType = (PDCDataType) _physicalElementMap.get(physicalElement); - if (dataType == null) - { - if (stringStartsWith(physicalElement, 'H')) - { - dataType = PDCDataType.HEIGHT; - } - if (stringStartsWith(physicalElement, 'Q')) - { - dataType = PDCDataType.DISCHARGE; - } - } - - return dataType; - - } - - // ------------------------------------------------------------------------------------- - - private boolean stringStartsWith(String physicalElement, char firstCharacter) - { - boolean result = false; - - if ( (physicalElement!= null) && - (physicalElement.length() > 0) && - (physicalElement.charAt(0) == firstCharacter) - ) - { - result = true; - } - - return result; - } - // ------------------------------------------------------------------------------------- - - public void initForHeight(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "RiverMonDrawingMgr.initForHeight(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = null; //actually depends on rating curve existence - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = ""; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new StageToFlowValueMapper(ratingCurve); - rightAxisLabelString = "cfs"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "feet"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForHeightWithLists(String locationId, - List paramCodeList, - TsPaintableCanvas canvas) - { - - String header = "RiverMonDrawingMgr.initForHeightWithLists(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = "cfs"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - - List obsTsList = new ArrayList(); - List fcstTsList = new ArrayList(); - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstTsList.add(fcstTs); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - - CodeTimer stageTimer = new CodeTimer(); - - stageTimer.start(); - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsTsList.add(obsTs); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - ValueMapper valueMapper = new StageToFlowValueMapper(ratingCurve); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - boolean shouldPaint = true; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - // observed data painter - for (int i = 0; i < obsTsList.size(); i++) - { - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - } - - - - // forecast data painters - for (int i = 0; i < fcstTsList.size(); i++) - { - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - } - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForDischarge(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "RiverMonDrawingMgr.initForDischarge(): "; - - MeasuringUnit unit = MeasuringUnit.cfs; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "cfs"; - String rightAxisLabelString = null; //actually depends on rating curve existence - - //Set time - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - - String titleString = "River Discharge for " + locationId; - //read in the observed time series - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstDischargeTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstDischargeTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedDischargeTimeSeries(locationId, - paramCode, - getStartTime()); - stageTimer.stop(header + "loadObservedDischargeTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new FlowToStageValueMapper(ratingCurve); - rightAxisLabelString = "feet"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "cfs"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - -/* - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - */ - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - //------------------------------------------------------------------------------------ - - private void assignPainterToCanvas(TslCanvasPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addTsCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslTimeLinePainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - private void assignPainterToCanvas(TslBackgroundPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - private int getDurationInHours(int ihfsDurationCode) - { - int durationInHours = 0; - - if ( (ihfsDurationCode >= 1000) && (ihfsDurationCode < 2000) ) - { - durationInHours = ihfsDurationCode - 1000; - } - if (ihfsDurationCode == 2001) - { - durationInHours = 24; - } - - return durationInHours; - } - // ---------------------------------------------------------------------------------- - - private IrregularTimeSeries getIrregularTimeSeries(RegularTimeSeries origTs) - { - MeasuringUnit unit = origTs.getMeasuringUnit(); - IrregularTimeSeries irregularTimeSeries = new IrregularTimeSeries(unit); - - int count = origTs.getMeasurementCount(); - - AbsTimeMeasurement measurement = null; - - for (int i = 0; i < count; i++) - { - measurement = origTs.getAbsTimeMeasurementByIndex(i); - irregularTimeSeries.insertMeasurement(measurement); - } - - return irregularTimeSeries; - } - - - // ------------------------------------------------------------------------------------- - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode - ) - - { - MeasuringUnit unit = obsTs.getMeasuringUnit(); - String unitString = unit.getName(); - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode, - String unitString - ) - - { - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCodeString, - IrregularTimeSeries fcstTs, - String fcstParamCodeString, - String unitString - ) - - { - AbsTimeMeasurement max = null; - AbsTimeMeasurement min = null; - AbsTimeMeasurement last = null; - - String[] textHeaderStringArray = null; - StringBuffer paramCodeStringBuffer = new StringBuffer(paramCodeString); - - Location location = _dataMgr.getLocationInfo(locationId); - if (location == null) - { - location = new Location(); - location.setLid(locationId); - location.setLocationName("Unknown location"); - location.setElevation(0); - - } - - - if (obsTs != null) - { - long startTime = getStartTime(); - long endTime = getEndTime(); - - max = obsTs.getMaxMeasurement(startTime, endTime); - min = obsTs.getMinMeasurement(startTime, endTime); - last = getLastMeasurement(obsTs, startTime, endTime); - } - - if (fcstParamCodeString != null) - { - paramCodeStringBuffer.append(" " + fcstParamCodeString); - } -// - - textHeaderStringArray = new String[5]; - textHeaderStringArray[0] = locationId + " - " + - location.getLocationName() + " - " + - "Elevation: " + location.getElevation() + " feet"; - - // textHeaderStringArray[1] = "Elevation: " + location.getElevation() + " feet"; - textHeaderStringArray[1] = paramCodeStringBuffer.toString(); - - - textHeaderStringArray[2] = "Max Obs = " + getMeasurementString(max, unitString); - textHeaderStringArray[3] = "Min Obs = " + getMeasurementString(min, unitString); - textHeaderStringArray[4] = "Last Obs = " + getMeasurementString(last, unitString); - - return textHeaderStringArray; - } - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getLastMeasurement(IrregularTimeSeries timeSeries, - long startTime, - long endTime) - { - AbsTimeMeasurement measurement = null; - - int count = timeSeries.getMeasurementCount(); - - for (int i = count - 1; i >= 0; i--) - { - measurement = timeSeries.getAbsTimeMeasurementByIndex(i); - if (measurement != null) - { - long time = measurement.getTime(); - - if ((time <= endTime) && (time >= startTime)) - { - break; //quit, I found the measurement that I want. - } - } - } - - return measurement; - - } - // -------------------------------------------------------------------------------------------------- - - private String getMeasurementString(AbsTimeMeasurement measurement, String unitString) - { - String measurementString = null; - - if (measurement != null) - { - String timeString = - DbTimeHelper.getDateTimeStringFromLongTime(measurement.getTime()); - - //get rid of the seconds - timeString = timeString.substring(0, timeString.length()-3); - - double value = MathHelper.roundToNDecimalPlaces(measurement.getValue(), 2); - - measurementString = - value + " " + - unitString + - " at " + timeString + "Z"; - - } - else - { - measurementString = "Not Available"; - } - - return measurementString; - } - - // -------------------------------------------------------------------------------------------------- - private String wrapInHTML(String origString) - { - StringBuffer buffer = new StringBuffer("
" + origString + "
"); - - return buffer.toString(); - } -// ------------------------------------------------------------ - private String getVerticalText(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - buffer.append(charArray[i]); - - //don't do a break for the last one - if (i < charArray.length-1) - { - buffer.append("
"); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } -// ------------------------------------------------------------ - private String getVerticalTextFromNewLines(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - char c = charArray[i]; - if (c == '\n') - { - buffer.append("
"); - } - else - { - buffer.append(c); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } - // -------------------------------------------------------------------------------------------------- - - - /** - * @param startTime The startTime to set. - */ - public void setStartTime(long startTime) - { - _startTime = startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @return Returns the startTime. - */ - public long getStartTime() - { - return _startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @param endTime The endTime to set. - */ - public void setEndTime(long endTime) - { - _endTime = endTime; - } - /** - * @return Returns the endTime. - */ - public long getEndTime() - { - return _endTime; - } - - // -------------------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/rivermon/RiverMonTslDataManager.java b/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/rivermon/RiverMonTslDataManager.java deleted file mode 100644 index 60463231d7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/timeserieslite/rivermon/RiverMonTslDataManager.java +++ /dev/null @@ -1,762 +0,0 @@ -package ohd.hseb.timeserieslite.rivermon; - -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LocPDCRecord; -import ohd.hseb.ihfsdb.generated.LocPDCView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.pdc_pp.RegularObsTimeSeries; -import ohd.hseb.pdc_pp.TimeValuePair; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class RiverMonTslDataManager { - - // -------------------------------------------------------------------------------------------- - - public static final double MISSING = -999.0; - - private static final int _defaultQualityCode = 1879048191; - - private static final int _questionable_bad_threshold = 1073741824; - - private static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - private static final long MILLIS_PER_YEAR = (365L * 24L * 60L * 60L * 1000L); - - private Database _db = null; - - private Logger _logger = null; - - private String _jdbcConnectionString = null; - - private PDCDataType _dataType = null; - - private String _physicalElement = null; - - private String _preprocessedFilePath = null; - - private double MAX_REASONABLE_PRECIP = 30; // inches per hour - - // --------------------------------------------------------------------------------- - - public RiverMonTslDataManager(String jdbcConnectionString) { - _logger = new FileLogger(true); - - _jdbcConnectionString = jdbcConnectionString; - - _db = new Database(); - - _db.connect(_jdbcConnectionString); - - getAppsDefaults(); - } - - // --------------------------------------------------------------------------------- - - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - - _preprocessedFilePath = ad.getToken("pdc_pp_dir") + "/"; - } - - // ------------------------------------------------------------------------------------- - - private void connect(String connectionString) { - _db.connectWithDriverSearch(connectionString); - } - - // ------------------------------------------------------------------------------------- - - public void disconnect() { - _db.disconnect(); - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSource(String lid, String pe) { - String header = "PdcTslDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + "'" + " AND pe = '" + pe - + "'" + " AND dur = 0 " + " AND ts like 'F%' " - + " order by ts_rank ASC"; - - try { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - if (pe.charAt(0) == 'H') { - for (int i = 0; i < recordList.size(); i++) { - record = (IngestFilterRecord) recordList.get(i); - if (fcstHeightRecordExists(record)) { - newTypeSource = record.getTs(); - break; - } - } - - } else // pe is not 'H*', so don't look at fcstHeight to see if - // it exists - { - newTypeSource = record.getTs(); - } - - } - } catch (SQLException e) { - logSQLException(e); - } - - // System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // ---------------------------------------------------------------------------------- - public boolean fcstHeightRecordExists(IngestFilterRecord ingestRecord) { - boolean result = false; - - String header = "PdcTslDataManager.fcstHeightRecordExists(): "; - - FcstHeightTable table = new FcstHeightTable(_db); - - String whereClause = "WHERE lid = '" + ingestRecord.getLid() + "'" - + " AND pe = '" + ingestRecord.getPe() + "'" + " AND dur = " - + ingestRecord.getDur() + " AND ts = '" + ingestRecord.getTs() - + "'"; - - try { - int recordCount = table.selectCount(whereClause); - - if (recordCount > 0) { - result = true; - } - } catch (SQLException e) { - logSQLException(e); - } - - return result; - } - - // ---------------------------------------------------------------------------------- - /* - * public String getPreferredFcstTypeSourceByIngestFilter(String lid, - * ParamCode paramCode) { String header = - * "PdcTslDataManager.getPreferredFcstTypeSourceByIngestFilter(): "; - * - * String newTypeSource = null; - * - * IngestFilterTable table = new IngestFilterTable(_db); - * - * IngestFilterRecord record = null; - * - * String whereClause = "WHERE lid = '" + lid + "' AND pe = '" + - * paramCode.getPe() + "'" + "AND dur = 0 " + "AND ts like 'F%' " + - * " order by ts_rank ASC" ; - * - * try { List recordList = table.select(whereClause); if (recordList.size() - * > 0) { int i = 0; //for (int i = 0; i < recordList.size(); i++) { record - * = (IngestFilterRecord) recordList.get(i); newTypeSource = record.getTs(); - * } } } catch(SQLException e) { logSQLException(e); } - * - * System.out.println(header + " newTypeSource = " + newTypeSource); - * - * return newTypeSource; } - * - * // - * ------------------------------------------------------------------------ - * ------------- public String getPreferredFcstTypeSourceByFcstHeight(String - * lid, ParamCode paramCode) { String header = - * "PdcTslDataManager.getPreferredFcstTypeSource(): "; - * - * String newTypeSource = null; - * - * FcstHeightTable table = new FcstHeightTable(_db); - * - * FcstHeightRecord record = null; - * - * String whereClause = "WHERE lid = '" + lid + "' AND pe = '" + - * paramCode.getPe() + "'" + "AND dur = 0 " + - * " order by basistime DESC, validtime ASC" ; - * - * try { List recordList = table.selectNRecords(whereClause,1); if - * (recordList.size() > 0) { int i = 0; //for (int i = 0; i < - * recordList.size(); i++) { record = (FcstHeightRecord) recordList.get(i); - * newTypeSource = record.getTs(); } } } catch(SQLException e) { - * logSQLException(e); } - * - * System.out.println(header + " newTypeSource = " + newTypeSource); - * - * return newTypeSource; } - */ - // ------------------------------------------------------------------------------------- - public SigRiverLevels loadSigRiverLevels(String locationId) { - String header = "PdcTslDataManager.loadSigRiverLevels(): "; - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (RiverstatRecord) recordList.get(0); - - String primaryPe = record.getPrimary_pe(); - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - - if (DbTable.isNull(actionStage)) { - System.out.println(header + " actionStage is null for " - + locationId); - } - if (DbTable.isNull(record.getPrimary_pe())) { - System.out.println(header + " primary_pe is null for " - + locationId); - record.setPrimary_pe(" "); - } - - levels = new SigRiverLevels(locationId, record.getPrimary_pe(), - floodStage, actionStage, floodFlow, actionFlow); - - } - } catch (SQLException e) { - logSQLException(e); - } - - return levels; - } - - // -------------------------------------------------------------------------------------------------- - - public RatingCurve loadRatingCurve(String locationId) { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - try { - ratingRecordList = ratingTable.select("WHERE LID = '" + locationId - + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" - + locationId + "' AND active = 'T' ORDER BY date desc", 1); - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId - + "'"); - - // determine total amount of active - // rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList - .get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - // System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - // initialize the RatingCurve object with data from the database, - // including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - // done by addRatingPoint - // ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } // end for - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList - .get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord - .getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } catch (SQLException e) { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - // ------------------------------------------------------------------------------------- - - public RegularTimeSeries getRegularTimeSeries( - RegularObsTimeSeries obsTimeSeries) { - - long startTime = obsTimeSeries.getDescriptor().getStartTime(); - long endTime = obsTimeSeries.getDescriptor().getEndTime(); - long timeStepIntervalInMillis = obsTimeSeries - .getTimeStepIntervalInMillis(); - long timeStepIntervalInHours = timeStepIntervalInMillis - / MILLIS_PER_HOUR; - MeasuringUnit unit = MeasuringUnit.inches; - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - String endTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(endTime); - - RegularTimeSeries regularTimeSeries = new RegularTimeSeries(startTime, - endTime, (int) timeStepIntervalInHours, unit); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - for (int i = 0; i < timeValuePairList.size(); i++) { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(i); - long time = pair.getDateTime(); - double value = pair.getValue(); - - Measurement measurement = new Measurement(value, unit); - - regularTimeSeries.setMeasurementByTime(measurement, time); - } - - regularTimeSeries.shiftStartEndTimeHours(12); - - return regularTimeSeries; - } - - // ------------------------------------------------------------------------------------- - - private void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - // ------------------------------------------------------- - public String getLocationName(String locationId) { - return loadLocationName(locationId); - } - - // ------------------------------------------------------- - private String loadLocationName(String locationId) { - - String locationName = null; - - LocationRecord record = null; - LocationTable table = new LocationTable(_db); - - try { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (LocationRecord) recordList.get(0); - locationName = record.getName(); - } - } catch (SQLException e) { - logSQLException(e); - } - - return locationName; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId, - ParamCode paramCode, long startTime) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - // ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (HeightRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedDischargeTimeSeries( - String locationId, ParamCode paramCode, long startTime) { - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "PdcTslDataManager.loadObservedDischargeTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - // ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - System.out.println(header + "whereClause = " + whereClause); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (DischargeRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - ParamCode paramCode) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - long originalBasisTime = 0; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (FcstHeightRecord) recordList.get(i); - - if (i == 0) { - originalBasisTime = record.getBasistime(); - } else { - if (record.getBasistime() != originalBasisTime) { - break; - } - } - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + - // measurement); - - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - ParamCode paramCode) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstDischargeTimeSeries(): "; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + paramCode.getPe() + "'" + " AND ts = '" - + paramCode.getTypeSource() + "'" + " AND dur = " - + paramCode.getIhfsDur() + " AND extremum = '" - + paramCode.getExtremum() + "'" + " AND quality_code >= " - + _questionable_bad_threshold + " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - long originalBasisTime = 0; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (FcstDischargeRecord) recordList.get(i); - - if (i == 0) { - originalBasisTime = record.getBasistime(); - } else { - if (record.getBasistime() != originalBasisTime) { - break; - } - } - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + - // measurement); - - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return dischargeTimeSeries; - } - - // ----------------------------------------------------------------------------------- - - public Location getLocationInfo(String locationId) { - DecimalFormat decimalFormat = new DecimalFormat("0.00"); - - Location location = null; - String whereClause = " WHERE lid = '" + locationId + "'"; - - LocPDCView locPDCView = new LocPDCView(_db); - RiverstatTable riverStatTable = new RiverstatTable(_db); - StnClassTable stationClassTable = new StnClassTable(_db); - - List locPDCViewList = null; - List riverStatRecordList = null; - List stationClassList = null; - - try { - locPDCViewList = locPDCView.select(whereClause); - riverStatRecordList = riverStatTable.select(whereClause); - - stationClassList = stationClassTable.select(whereClause); - - } catch (SQLException e) { - logSQLException(e); - e.printStackTrace(); - } - - for (int i = 0; i < locPDCViewList.size(); i++) { - LocPDCRecord locPDCRecord = (LocPDCRecord) locPDCViewList.get(i); - location = new Location(); - location.setLid(locPDCRecord.getLid().trim()); - location.setHsa(locPDCRecord.getHsa().trim()); - - location.setLat(Double.parseDouble(decimalFormat - .format(locPDCRecord.getLat()))); - location.setLon(Double.parseDouble(decimalFormat - .format(locPDCRecord.getLon()))); - - location.setElevation(locPDCRecord.getElev()); - location.setLocationName(locPDCRecord.getName()); - location.setRiverStation(false); - - double fq = locPDCRecord.getFq(); - double fs = locPDCRecord.getFs(); - - if (fq == 0) // missing value - { - location.setFloodFlow(MISSING); - } else { - location.setFloodFlow(fq); - } - - if (fs == 0) // missing value - { - location.setFloodStage(MISSING); - } else { - location.setFloodStage(fs); - } - - if ((fq == 0.0) && (fs != 0.0) - && (location.getRatingCurve() != null)) { - location.setFloodFlow(location.getRatingCurve() - .getDischargeFromStage(fs)); - } - - String dispClass = locPDCRecord.getDisp_class(); - - if ((dispClass.indexOf("F")) != -1) { - location.setFcstPoint(true); - } else { - location.setFcstPoint(false); - } - - String dcp = locPDCRecord.getIs_dcp(); - - if ((dcp.indexOf("T")) != -1) { - location.setDCP(true); - } else { - location.setDCP(false); - } - - String observer = locPDCRecord.getIs_observer(); - - if ((observer.indexOf("T")) != -1) { - location.setObserver(true); - } else { - location.setObserver(false); - } - - location.setTelemType(locPDCRecord.getTelem_type()); - - } - - return location; - } - - // ------------------------------------------------------------------------ - private String getPrecipFileName(int durationInHours) { - String precipFileName = _preprocessedFilePath + "/Precip" - + durationInHours + "Hour.dat"; - return precipFileName; - } - - // ------------------------------------------------------------------------ - - public long getLatestHourTime() { - return TimeHelper.truncateTimeInMillisToNearestHour(System - .currentTimeMillis(), 1); - } - // ----------------------------------------------------------------------------------- - -} // end PdcTslDataManager diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/BooleanHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/util/BooleanHolder.java deleted file mode 100644 index 5ae6dbe1ec..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/BooleanHolder.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on May 14, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * - */ -public class BooleanHolder -{ - private boolean _value; - - public BooleanHolder(boolean value) - { - setValue(value); - } - - public void setValue(boolean value) - { - _value = value; - } - - public boolean getValue() - { - return _value; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/CodeTimer.java b/cave/ohd.hseb.common/src/ohd/hseb/util/CodeTimer.java deleted file mode 100644 index b59a83b58b..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/CodeTimer.java +++ /dev/null @@ -1,110 +0,0 @@ -package ohd.hseb.util; - -// create a Logger class. Give to Gautam for java practice purposes. - -public class CodeTimer -{ - - private boolean _isRunning = false; - private long _startTime = 0; - private long _endTime = 0; - private long _elapsedTime = 0; - private Logger _logger = null; - - //----------------------------------------------- - - public CodeTimer() - { - - - } - //----------------------------------------------- - - public CodeTimer(Logger logger) - { - _logger = logger; - } - - //----------------------------------------------- - - public void start() - { - _isRunning = true; - _startTime = System.currentTimeMillis(); - _elapsedTime = 0; - - return; - } - - //----------------------------------------------- - - public long stop() - { - return this.stop(""); - } - - //----------------------------------------------- - - public long stop(String message) - { - _endTime = System.currentTimeMillis(); - _elapsedTime += (_endTime - _startTime); - - _isRunning = false; - - if ( (message != null) && (message.length() > 0) ) - { - log(message + " " + _elapsedTime + " millis."); - } - - if (_logger != null) - { - _logger.close(); - } - - return _elapsedTime; - } - - //----------------------------------------------- - - public void restart() - { - _isRunning = true; - _startTime = System.currentTimeMillis(); - } - - //----------------------------------------------- - - // reset all the state variables - public void clear() - { - _isRunning = false; - _startTime = 0; - _endTime = 0; - _elapsedTime = 0; - } - - //----------------------------------------------- - - private void log(String message) - { - if (_logger != null) - { - _logger.log(message); - } - else - { - System.out.println(message); - } - return; - } - - //----------------------------------------------- - - public long getElapsedTime() - { - return _elapsedTime; - } - - -} //end class CodeTimer diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/CodeTracer.java b/cave/ohd.hseb.common/src/ohd/hseb/util/CodeTracer.java deleted file mode 100644 index 0ada6b3f16..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/CodeTracer.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Created on Jul 28, 2004 - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * - */ -public class CodeTracer -{ - private Logger _logger = null; - - // ------------------------------------------------------------- - // nobody can call this - public CodeTracer() - { - - } - - public CodeTracer(Logger logger) - { - _logger = logger; - - } - // ------------------------------------------------------------- - public void trace(String message) - { - - // calls trace with a prepended message - if (_logger != null) - { - _logger.log(message); - trace(); - } - else - { - System.out.println(message); - trace(); - } - } - // ------------------------------------------------------------- - public void trace() - { - try - { - throw new Exception("Just Tracing, not an actual error"); - } - catch (Exception e) - { - if (_logger != null) - { - e.printStackTrace(_logger.getPrintWriter()); - } - else - { - e.printStackTrace(); - } - } - - } //end trace() - // ------------------------------------------------------------- -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/Cryptor.java b/cave/ohd.hseb.common/src/ohd/hseb/util/Cryptor.java deleted file mode 100644 index 4bce8443a2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/Cryptor.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Created on Aug 28, 2003 - * - * - */ -package ohd.hseb.util; - -import java.util.Random; - - - -public class Cryptor -{ - - private String _key = "adlfkjaldfkjaldkjf"; - private static long _seed = 5234234234L; - private static int _range = 17; - - // ---------------------------------------------------------- - public static String decrypt(String encryptedString) - { - StringBuffer buffer = new StringBuffer(encryptedString); - - Random random = new Random(_seed); - for (int i = 0; i < buffer.length(); i++) - { - char c = buffer.charAt(i); - c -= getNextShift(random); - buffer.setCharAt(i,c); - } - - // System.out.println(""); - - return buffer.toString(); - } - - // ---------------------------------------------------------- - - public static String encrypt(String encryptedString) - { - StringBuffer buffer = new StringBuffer(encryptedString); - - Random random = new Random(_seed); - for (int i = 0; i < buffer.length(); i++) - { - char c = buffer.charAt(i); - c += getNextShift(random); - buffer.setCharAt(i,c); - } - - // System.out.println(""); - - return buffer.toString(); - } - - // --------------------------------------------------- - private static int getNextShift(Random random) - { - int shift = random.nextInt(2 * _range) - _range; - // System.out.print("shift = " + shift + " "); - return shift; - } - - // ---------------------------------------------------------- - - public static void main(String[] args) - { - String message = ""; - String encMessage = ""; - - String decMessage = ""; - - encMessage = encrypt(message); - decMessage = decrypt(encMessage); - - - // System.out.println("message = " + message); - System.out.println("encMessage = " + encMessage); - //System.out.println("decMessage = " + decMessage); - - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/DataPoint.java b/cave/ohd.hseb.common/src/ohd/hseb/util/DataPoint.java deleted file mode 100644 index 0742c1a39c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/DataPoint.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Created on Jul 16, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author gobsc - * - * - */ -public class DataPoint -{ - private double _x; - private double _y; - - public DataPoint() - { - - } - - public DataPoint(double x, double y) - { - setX(x); - setY(y); - } - - public void setX(double x) - { - this._x = x; - } - - public double getX() - { - return _x; - } - - public void setY(double y) - { - this._y = y; - } - - public double getY() - { - return _y; - } - - public String toString() - { - String outString = "( " + _x + ", " + _y + ")"; - return outString; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/DoubleHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/util/DoubleHolder.java deleted file mode 100644 index f2c6937e1c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/DoubleHolder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * Holds a double value This is needed because Double is immutable and primitives are passed by - * value to methods. - */ -public class DoubleHolder -{ - private double _value; - - public DoubleHolder(double value) - { - _value = value; - } - - public void setValue(double value) - { - _value = value; - } - - public double getValue() - { - return _value; - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/EndianConverter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/EndianConverter.java deleted file mode 100644 index 0eb102fd51..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/EndianConverter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Created on Oct 31, 2003 - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - */ -public class EndianConverter -{ - - public static int convert(int origEndianInt) - { - - int newEndianInt = - (( origEndianInt & 0x000000ff )<< 24) | - (( origEndianInt & 0x0000ff00) << 8) | - (( origEndianInt & 0x00ff0000) >>> 8) | - (( origEndianInt & 0xff000000) >>> 24); - /* - System.out.println("MAP.convertEndian(int): original int was " + origEndianInt + - " new one is newEndianInt " + - newEndianInt); - */ - - return newEndianInt; - - } -// ---------------------------------------------------- - - public static short convert(short origEndianShort) - { - short newEndianShort = - (short)( (( origEndianShort & 0x000000ff )<< 8) | - (( origEndianShort & 0x0000ff00) >>> 8) - ); - - - return newEndianShort; - - } //end convertEndian for shorts - -// ---------------------------------------------------------- - - public static float convert(float origEndianFloat) - { - - int intBits = Float.floatToIntBits(origEndianFloat); - - - int flippedInt = - (( intBits & 0x000000ff )<< 24) | - (( intBits & 0x0000ff00) << 8) | - (( intBits & 0x00ff0000) >>> 8) | - (( intBits & 0xff000000) >>> 24); - - float newEndianFloat = Float.intBitsToFloat(flippedInt); - - - return newEndianFloat; - - } -// ---------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/EnvHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/EnvHelper.java deleted file mode 100644 index e744efacf8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/EnvHelper.java +++ /dev/null @@ -1,130 +0,0 @@ -package ohd.hseb.util; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Properties; - -public class EnvHelper { - private Properties _props = null; - - // -------------------------------------------------------------- - // Note, this version of EnvHelper uses the returned System.getenv() method. - // It was unavailable for a few java versions (1.3.x to 1.4.x ?) - // Code timings on a Linux box reveal an improvement with the old code - // taking - // 54 milliseconds and the new code taking only 5 millis in SSHP. - // -------------------------------------------------------------- - - public Properties getProperties() { - - if (_props == null) { - _props = new Properties(); - - _props.putAll(System.getenv()); - - } // end if - - return _props; - } - - // -------------------------------------------------------------- - - private Properties getProperties_old() { - - if (_props == null) { - _props = new Properties(); - - Process process = null; - - String commandString = this.getEnvCommandString(); - - try { - - process = Runtime.getRuntime().exec(commandString); - - InputStream inStream = process.getInputStream(); - - BufferedReader br = new BufferedReader(new InputStreamReader( - inStream)); - String line; - while ((line = br.readLine()) != null) { - int index = line.indexOf('='); - if (index < 0) { - // something is wrong with the line, - // ignore it and read the next line - continue; - } - - String key = line.substring(0, index); - String value = line.substring(index + 1); - - // works in java >= 1.2 - // _props.setProperty( key, value ); - - // works in java < 1.2, and later, but is not prefered. - _props.put(key, value); - - // System.out.println( key + " = " + value ); - } - } catch (java.io.IOException e) { - e.printStackTrace(); - return _props; - } finally { - // DR#10955 - if (process != null) { - process.destroy(); - } - } - } // end if - - return _props; - } - - // -------------------------------------------------------------- - private String getEnvCommandString() { - String OS = System.getProperty("os.name").toLowerCase(); - String commandString = ""; - - if (OS.indexOf("windows 9") > -1) { - commandString = "command.com /c set "; - } else if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1)) { - // thanks to JuanFran for the xp fix! - commandString = "cmd.exe /c set "; - } else // assume unix - { - commandString = "env"; - } - - return commandString; - } - - // -------------------------------------------------------------- - public String getProperty(String key) { - Properties props = this.getProperties(); - - return props.getProperty(key); - } - - // -------------------------------------------------------------- - public static void main(String[] args) { - EnvHelper envHelper = new EnvHelper(); - - Properties env = envHelper.getProperties(); - - if (env == null) { - System.out.println("dude, env is null"); - } else { - System.out.println("------------------"); - env.list(System.out); - } - - String tempVar = envHelper.getProperty("TEMP"); - - System.out.println("TEMP = " + tempVar); - - return; - } - -} \ No newline at end of file diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/FileLogger.java b/cave/ohd.hseb.common/src/ohd/hseb/util/FileLogger.java deleted file mode 100644 index c33119d6ce..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/FileLogger.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Created on Jul 9, 2003 - * - * - */ -package ohd.hseb.util; - -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -/** - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- -------------------------------------
- * May 13, 2011  8079       jnjanga     added custom printStackTrace method
- * 
- * 
- * - * @author gobsc - */ -public class FileLogger implements Logger { - - // private vars - private String _fileName = null; - - private OutputStream _outputStream = null; - - private PrintWriter _writer = null; - - private boolean _usingRealFile = false; - - private boolean _fileIsOpen = false; - - private static final String dateFormatString = "yyyy/MM/dd HH:mm:ss.SSS"; - - private static final SimpleDateFormat _dateFormatter = new SimpleDateFormat( - dateFormatString); - - static { - _dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - // options - private boolean _appendDateTime = false; - - private boolean _keepFileOpen = true; - - // --------------------------------------------------------------------- - - public FileLogger(boolean appendDateTime) { - - _appendDateTime = appendDateTime; - - } - - /* - */ - public FileLogger(String fileName) { - // default is to keep the file open until closed - // and to append the date and time to each line - // of text - - this(fileName, true, true); - } - - // --------------------------------------------------------------------- - - public FileLogger(String fileName, boolean keepFileOpen, - boolean appendDateTime) { - _keepFileOpen = keepFileOpen; - _appendDateTime = appendDateTime; - - _fileName = fileName; - - } - - // --------------------------------------------------------------------- - - public void log(String message) { - - // open if needed - if (!isOpen()) { - openFile(_fileName); - _writer = new PrintWriter(_outputStream); - } - - // write out the message, pre-pending date time stamp if required - if (_appendDateTime) { - _writer.println(getDateTimeStamp() + ": " + message); - } else { - _writer.println(message); - } - - _writer.flush(); - - // close if supposed to do so - if (!_keepFileOpen) { - close(); - } - } - - /** - * logs a stack trace - * - * @param aThrowable - * a thrown exception - */ - public void printStackTrace(Throwable aThrowable) { - // add the class name and any message passed to constructor - final String SPACE = " "; - final StringBuilder result = new StringBuilder(SPACE); - result.append(aThrowable.toString()); - final String NEW_LINE = System.getProperty("line.separator"); - result.append(NEW_LINE); - - // add each element of the stack trace - for (StackTraceElement element : aThrowable.getStackTrace()) { - result.append(NEW_LINE); - for (int i = 0; i < 25; i++) - result.append(SPACE); - result.append(element); - } - log(result.toString()); - } - - // --------------------------------------------------------------------- - public PrintWriter getPrintWriter() { - return _writer; - } - - // --------------------------------------------------------------------- - - private String getDateTimeStamp() { - Date date = new Date(); - - return _dateFormatter.format(date); - } - - // --------------------------------------------------------------------- - - private void openFile(String fileName) { - try { - if (fileName != null) { - _outputStream = new FileOutputStream(fileName, true); - _usingRealFile = true; - _fileIsOpen = true; - } else // fileName == null - { - _outputStream = System.out; - - } - - _writer = new PrintWriter(_outputStream); - - } catch (java.io.IOException e) { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - public void close() { - // try - { - if (isOpen() && _usingRealFile) { - _fileIsOpen = false; - _writer.close(); - } - } - // catch(java.io.IOException e) - { - // e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - private boolean isOpen() { - return _fileIsOpen; - } - - // --------------------------------------------------------------------- - -} // FileLogger diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/Grid.java b/cave/ohd.hseb.common/src/ohd/hseb/util/Grid.java deleted file mode 100644 index c78a687871..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/Grid.java +++ /dev/null @@ -1,7 +0,0 @@ -package ohd.hseb.util; - - -public interface Grid -{ - double getValue(int row, int col); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/IntegerHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/util/IntegerHolder.java deleted file mode 100644 index 98b06e5162..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/IntegerHolder.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * Holds an int value. This is needed because Integer is immutable and int is passed by value to - * methods. - */ -public class IntegerHolder -{ - private int _value; - - public IntegerHolder(int value) - { - _value = value; - } - - public void setValue(int value) - { - _value = value; - } - - public int getValue() - { - return _value; - } - - public void change(int amount) - { - _value += amount; - } - - public void increment() - { - change(1); - } - - public void decrement() - { - change(-1); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/Logger.java b/cave/ohd.hseb.common/src/ohd/hseb/util/Logger.java deleted file mode 100644 index cb82744421..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/Logger.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Created on Jul 9, 2003 - * - * - */ -package ohd.hseb.util; - -import java.io.PrintWriter; - -/** - * @author Chip Gobs - * - * - */ -public interface Logger -{ - public void log(String message); - public void close(); - public PrintWriter getPrintWriter(); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/LongHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/util/LongHolder.java deleted file mode 100644 index 713db5aba4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/LongHolder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * Holds a LongValue. This is needed because Long is immutable. - */ -public class LongHolder -{ - private long _value; - - public LongHolder(long value) - { - _value = value; - } - - public void setValue(long value) - { - _value = value; - } - - public long getValue() - { - return _value; - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/MathHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/MathHelper.java deleted file mode 100644 index ba63306d21..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/MathHelper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Created on Nov 14, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - * - * This class consolidates some common math functions. - */ -public class MathHelper -{ - /* public static double roundToNDecimalPlaces(double origValue, int decimalPlaces) - { - double factor = Math.pow(10, decimalPlaces); - long intValue = (long) (origValue * factor); - double newValue = intValue / factor; - - return newValue; - } //end roundToNDecimalPlaces - */ - - public static double roundToNDecimalPlaces(double numberToRound, int decimalPlacesToMaintain) - { - - long roundingFactor = 1; - long temporaryHolder; - long roundingFactorArray[] = { 1, 10, 100, 1000, 10000, 100000, - 1000000, 10000000, 100000000, 1000000000 }; - - if (decimalPlacesToMaintain < 0) - { - decimalPlacesToMaintain = 0; - } - else if (decimalPlacesToMaintain > 9) - { - decimalPlacesToMaintain = 9; - } - - - // I could have used pow(), but this is faster - roundingFactor = roundingFactorArray[decimalPlacesToMaintain]; - - temporaryHolder = (long) Math.floor((numberToRound * roundingFactor) + 0.5); - - numberToRound = (double) temporaryHolder / roundingFactor; - - return numberToRound; - - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/MaxMinData.java b/cave/ohd.hseb.common/src/ohd/hseb/util/MaxMinData.java deleted file mode 100644 index 517f0047c9..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/MaxMinData.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on Jul 15, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * - */ -public class MaxMinData -{ - private double _maxValue; - private double _minValue; -// --------------------------------------------------------------- - public MaxMinData(double maxValue, double minValue) - { - _maxValue = maxValue; - _minValue = minValue; - } -// --------------------------------------------------------------- - public void setMaxValue(double maxValue) - { - _maxValue = maxValue; - } -// --------------------------------------------------------------- - - public double getMaxValue() - { - return _maxValue; - } -// --------------------------------------------------------------- - - public void setMinValue(double minValue) - { - _minValue = minValue; - } -// --------------------------------------------------------------- - - public double getMinValue() - { - return _minValue; - } -// --------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/MemoryLogger.java b/cave/ohd.hseb.common/src/ohd/hseb/util/MemoryLogger.java deleted file mode 100644 index 45c400da60..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/MemoryLogger.java +++ /dev/null @@ -1,24 +0,0 @@ -package ohd.hseb.util; - -public class MemoryLogger -{ - - private static SessionLogger _logger = null; - - public static void setLogger(Logger logger) - { - _logger = (SessionLogger) logger; - - System.out.println("MemoryLogger.setLogger(): _logger.getSessionId() = " + _logger.getSessionId()); - } - - public static void log(String message) - { - Runtime runtime = Runtime.getRuntime(); - String text = null; - - text = message + "Free:" + runtime.freeMemory() + " Max:"+ runtime.maxMemory()+ " total:"+ runtime.totalMemory(); - _logger.log(text); - - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/NameValuePair.java b/cave/ohd.hseb.common/src/ohd/hseb/util/NameValuePair.java deleted file mode 100644 index a0e8820c8f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/NameValuePair.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Created on Jul 11, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.util; - -/** - * @author gobsc - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class NameValuePair -{ - private String _name; - private String _value; - - public NameValuePair() - { - - } - - public NameValuePair(String name, String value) - { - setName(name); - setValue(value); - } - - public void setName(String name) - { - this._name = name; - } - - public String getName() - { - return _name; - } - - public void setValue(String value) - { - this._value = value; - } - - public String getValue() - { - return _value; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/PrecipUtils.java b/cave/ohd.hseb.common/src/ohd/hseb/util/PrecipUtils.java deleted file mode 100644 index 7a24c3168c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/PrecipUtils.java +++ /dev/null @@ -1,13 +0,0 @@ -package ohd.hseb.util; - -public class PrecipUtils -{ - - - public double get_total_hourly_PC() - { - double totalHourlyPC = 0; - - return totalHourlyPC; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/Range.java b/cave/ohd.hseb.common/src/ohd/hseb/util/Range.java deleted file mode 100644 index 384d855fa5..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/Range.java +++ /dev/null @@ -1,60 +0,0 @@ -package ohd.hseb.util; - -public class Range -{ - private double _min = 0; - private double _max = 0; - // --------------------------------------------------------------------------- - - public Range(double value1, double value2) - { - double min = Math.min(value1, value2); - double max = Math.max(value1, value2); - - setMin(min); - setMax(max); - } - // --------------------------------------------------------------------------- - public boolean isBetweenInclusive(double value) - { - boolean result = false; - - if ((value >= getMin()) && (value <= getMax() )) - { - result = true; - } - - return result; - } - - // --------------------------------------------------------------------------- - - public void setMin(double min) - { - _min = min; - } - - // --------------------------------------------------------------------------- - - public double getMin() - { - return _min; - } - - // --------------------------------------------------------------------------- - - public void setMax(double max) - { - _max = max; - } - - // --------------------------------------------------------------------------- - - public double getMax() - { - return _max; - } - - // --------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/SessionLogger.java b/cave/ohd.hseb.common/src/ohd/hseb/util/SessionLogger.java deleted file mode 100644 index 41489e23d2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/SessionLogger.java +++ /dev/null @@ -1,240 +0,0 @@ -package ohd.hseb.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.TimeZone; - - -public class SessionLogger implements Logger -{ - private String _currentFileName = null; - private OutputStream _outputStream = null; - private PrintWriter _writer = null; - private boolean _usingRealFile = false; - private boolean _fileIsOpen = false; - private int _sessionId; - - private static final String dateFormatString = - "yyyyMMdd"; - private static final SimpleDateFormat _dateFormatter = - new SimpleDateFormat(dateFormatString); - - private static final String timeFormatString = - "HH:mm:ss"; - private static final SimpleDateFormat _timeFormatter = - new SimpleDateFormat(timeFormatString); - - private boolean _appendDateTime = false; - private boolean _keepFileOpen = true; - private String _messageId; - private String _baseFileName; - private String _appName; - - static - { - _dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - _timeFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - public SessionLogger(String appName, String baseFileName, - boolean keepFileOpen, boolean appendDateTime, String messageId) - { - _keepFileOpen = true; - _appendDateTime = true; - _messageId = messageId; - _baseFileName = baseFileName; - _appName = appName; - } - - public int getSessionId() - { - return _sessionId; - } - - public void log(String message) - { - boolean isCreatedNow = false; - if (!isOpen() || message == null) - { - openFile(_baseFileName, false); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - else - { - String splitStr[] = _currentFileName.split("\\."); - String dateTimeStampInFileName = splitStr[2]; - if(!(getCurrentDate().equalsIgnoreCase(dateTimeStampInFileName))) - { - openFile(_currentFileName, true); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - } - - if(isCreatedNow) - { - if(_messageId == null) - _messageId = new Integer(_sessionId).toString(); - _writer.println(_messageId); - _writer.println("**************************************"); - } - - if (_appendDateTime) - { - if(message != null) - _writer.println( getCurrentTime() + ": " + message); - } - else - { - if(message != null) - _writer.println(message); - } - _writer.flush(); - if (!_keepFileOpen) - { - close(); - } - } - - private void determineSessionId(String fileName) - { - int sessionId = -1; - String dirName; - int index = fileName.lastIndexOf("/"); - dirName = fileName.substring(0, index); - File dir = new File(dirName); - int leastPossibleNumber = 1; - if(dir.exists()) - { - if(dir.isDirectory()) - { - String files[] = dir.list(); - if(files != null) - { - if(files.length == 0) - { - sessionId = 1; - } - else - { - int existingIds[] = new int[files.length]; - for(int i=0; i < files.length; i++) - { - String str = files[i]; - String splitStr[] = str.split("\\."); - if(splitStr == null) - continue; - else if(splitStr.length != 3) - continue; - else if(!(splitStr[0].compareTo(_appName) == 0)) - continue; - else if(splitStr[2].length() != 8) - continue; - try - { - existingIds[i] = Integer.parseInt(splitStr[1]); - Integer.parseInt(splitStr[2]);// To make sure the last portion is a data (number) - } - catch(Exception e) - { - continue; - } - } - Arrays.sort(existingIds); - while(true) - { - if(Arrays.binarySearch(existingIds, leastPossibleNumber) < 0) - { - sessionId = leastPossibleNumber; - break; - } - else - leastPossibleNumber++; - } - } - } - } - else - { - System.out.println(_appName + ":["+dir+"] isn't a directory"); - } - } - else - { - System.out.println(_appName + ":Directory ["+dir+"] doesn't exist"); - } - - _sessionId = sessionId; - } - - public PrintWriter getPrintWriter() - { - return _writer; - } - - private String getCurrentDate() - { - Date date = new Date(); - return _dateFormatter.format(date); - } - - private String getCurrentTime() - { - Date date = new Date(); - return _timeFormatter.format(date); - } - - private void openFile(String fileName, boolean isExistingSession) - { - try - { - if (fileName != null) - { - if(!isExistingSession) - { - determineSessionId(_baseFileName); - } - if(_sessionId != -1) // !=-1 means able to get a session id that is valid - { - _currentFileName = _baseFileName +"."+ _sessionId + "."+getCurrentDate(); - _outputStream = new FileOutputStream(_currentFileName, true); - _usingRealFile = true; - _fileIsOpen = true; - } - else // unable to get a session id so log to console - { - _outputStream = System.out; - } - } - else //fileName == null - { - _outputStream = System.out; - } - _writer = new PrintWriter(_outputStream); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - } - } - - public void close() - { - if (isOpen() && _usingRealFile) - { - _fileIsOpen = false; - _writer.close(); - } - } - - private boolean isOpen() - { - return _fileIsOpen; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/StringDataConverter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/StringDataConverter.java deleted file mode 100644 index a1b33c39bb..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/StringDataConverter.java +++ /dev/null @@ -1,204 +0,0 @@ -package ohd.hseb.util; - -import java.text.DecimalFormat; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; - -public class StringDataConverter -{ - private static final String latlonFormatString = "0.00"; - private static final DecimalFormat _latlonFormatter = new DecimalFormat(latlonFormatString); - - public StringDataConverter() - { - } - - public String getFormattedDoubleValue( double doubleValue ) - { - String returnString = ""; - if ( doubleValue != DbTable.getNullDouble() ) - { - returnString = _latlonFormatter.format( doubleValue ); - } - - return ( returnString ); - } - - public double getDoubleValue( String valueString ) - { - double value = DbTable.getNullDouble(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Double.parseDouble( valueString ); - } - - return value; - } - - public long getLongDateValue( String dateString ) - { - long value = DbTable.getNullLong(); - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - value = DbTimeHelper.getLongTimeFromDateString( dateString ); - } - - return value; - } - - public long getLongDateTimeValue( String dateTimeString ) - { - long value = DbTable.getNullLong(); - - if ( ! dateTimeString.equalsIgnoreCase( "" ) ) - { - value = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - } - - return value; - } - - public long getLongValue( String valueString ) - { - long value = DbTable.getNullLong(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Long.parseLong( valueString ); - } - return value; - } - - public String getFormattedFloatValue( float floatValue ) - { - String returnString = ""; - if ( floatValue != DbTable.getNullFloat() ) - { - returnString = _latlonFormatter.format( floatValue ); - } - - return ( returnString ); - } - - public float getFloatValue( String valueString ) - { - float value = DbTable.getNullFloat(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Float.parseFloat( valueString ); - } - return value; - } - - public int getIntValue( String valueString ) - { - int value = DbTable.getNullInt(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Integer.parseInt( valueString ); - } - - return value; - } - - public short getShortValue( String valueString ) - { - short value = DbTable.getNullShort(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Short.parseShort( valueString ); - } - - return value; - } - - public String getStringFromDouble( double value ) - { - String valueString = ""; - - if ( value != DbTable.getNullDouble() ) - { - valueString = Double.toString( value ); - } - - return valueString; - } - - public String getStringFromInt( int value ) - { - String valueString = ""; - - if ( value != DbTable.getNullInt() ) - { - valueString = Integer.toString( value ); - } - - return valueString; - } - - public String getStringFromLong( long value ) - { - String valueString = ""; - - if ( value != DbTable.getNullLong() ) - { - valueString = Long.toString( value ); - } - - return valueString; - } - - public String getStringFromShort( short value ) - { - String valueString = ""; - - if ( value != DbTable.getNullShort() ) - { - valueString = Short.toString( value ); - } - - return valueString; - } - - public String getDateStringFromDateLong( long dateLong ) - { - String dateString = ""; - - if ( dateLong != DbTable.getNullLong() ) - { - dateString = DbTimeHelper.getDateStringFromLongTime( dateLong ); - } - - return dateString; - } - - public String getString( String string ) - { - String returnString = null; - - if ( ! string.equalsIgnoreCase( "" ) ) - { - returnString = string; - } - - return returnString; - } - - public String getDateTimeStringFromDateTimeLong( long dateTimeLong ) - { - String dateString = ""; - - if ( dateTimeLong != DbTable.getNullLong() ) - { - dateString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeLong ); - } - - return dateString; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/StringHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/StringHelper.java deleted file mode 100644 index 33d25e2bc7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/StringHelper.java +++ /dev/null @@ -1,93 +0,0 @@ -package ohd.hseb.util; - -public class StringHelper -{ - public static int areArraysEqual(String[] array1, String[] array2) - { - int result = 0; - - if(array1 == null && array2 != null) - result = -1; - else if(array2 == null && array1 != null) - result = -1; - else if(array1 == null && array2 == null) - result = 0; - else if(array1.length != array2.length) - { - result = -1 ; - } - else - { - for(int i=0 ; i < array1.length; i++) - { - if(array1[i].compareTo(array2[i]) != 0) - { - result = -1; - break; - } - } - } - return result; - } - - - public static String capitalizeFirstLetterOfWords(String text) - { - String result = null; - if(text != null) - { - String tempText = text.toLowerCase(); - String splitWords[] = tempText.split("\\s+"); - - if(splitWords != null) - { - String newConvertedWords[] = new String[splitWords.length]; - - for(int i=0; i < splitWords.length; i++) - { - boolean newWordFormed = false; - String newWord = null; - String orgWord = splitWords[i]; - if(orgWord.length() != 0) - { - char begChar = orgWord.charAt(0); - if(Character.isLetter(begChar)) - { - if(Character.isLowerCase(begChar)) - { - char newBegChar = Character.toUpperCase(begChar); - newWord = newBegChar + orgWord.substring(1, orgWord.length()); - newWordFormed = true; - } - } - } - if (newWordFormed) - { - newConvertedWords[i] = newWord; - } - else - { - newConvertedWords[i] = orgWord; - } - } - - result = ""; - - for(int i=0; i < newConvertedWords.length; i++) - { - if(i == 0 ) - { - result = newConvertedWords[i]; - } - else - { - result = result + " " + newConvertedWords[i]; - } - } - } - } - - return result; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/StringParser.java b/cave/ohd.hseb.common/src/ohd/hseb/util/StringParser.java deleted file mode 100644 index 57fda49c4e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/StringParser.java +++ /dev/null @@ -1,46 +0,0 @@ -package ohd.hseb.util; - - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -public class StringParser -{ - public StringParser() - { - } - - public static String[] tokenize( String stringToTokenize ) - { - StringTokenizer tokens = new StringTokenizer( stringToTokenize ); - List tokenList = new ArrayList(); - - while ( tokens.hasMoreTokens() ) - { - tokenList.add( tokens.nextToken() ); - } - - String[] stringArray = new String[ tokenList.size() ]; - - for ( int i = 0; i < tokenList.size(); i++ ) - { - stringArray[ i ] = (String) tokenList.get( i ); - } - - return stringArray; - } - - public String toString( List tokenList ) - { - StringBuffer output = new StringBuffer(); - String token = null; - - for ( int i = 0; i < tokenList.size(); i++ ) - { - token = (String) tokenList.get( i ); - output.append( token + " " ); - } - return output.toString(); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/TimeHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/TimeHelper.java deleted file mode 100644 index dd517422ef..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/TimeHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Created on Oct 8, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - */ - -public class TimeHelper -{ - - public static final long MILLIS_PER_MINUTE = 60 * 1000; - public static final long MILLIS_PER_HALF_HOUR = 30 * MILLIS_PER_MINUTE; - public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - public static final long MILLIS_PER_12_HOURS = MILLIS_PER_HOUR * 12; - public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; - -// -------------------------------------------------------------------------- - - public static long truncateTimeInMillisToNearestHour(long timeInMillis, - int hoursToTruncate) - { - long roundingAmount = hoursToTruncate * MILLIS_PER_HOUR; - long roundedTime = timeInMillis; - roundedTime /= roundingAmount; - roundedTime *= roundingAmount; - - return roundedTime; - } -// -------------------------------------------------------------------------- - public static long roundTimeInMillisToNearestHour(long timeInMillis) - { - long roundingAmount = MILLIS_PER_HOUR; - long halfHourInMillis = MILLIS_PER_HOUR/2; - long roundedTime = truncateTimeInMillisToNearestHour(timeInMillis + halfHourInMillis, 1); - - return roundedTime; - } -// -------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/TimeHolder.java b/cave/ohd.hseb.common/src/ohd/hseb/util/TimeHolder.java deleted file mode 100644 index 544cafce9d..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/TimeHolder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Created on Oct 31, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - * - * This class is intended to be used as a way for - * other objects to point to something that is always used - * to maintain a time. Multiple objects may wish to set - * or get the time contained herein. They can do this to - * remain in synch about a particular time concept. - Example: various objects need to know what the model run time is - without explicitly know who is maintaining it, so they just have a reference - to the same timeholder, which they can access. - **/ -public class TimeHolder -{ - private long _time = 0; - - public void setTime(long time) - { - _time = time; - } - - public long getTime() - { - return _time; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/TimeSeriesFileManager.java b/cave/ohd.hseb.common/src/ohd/hseb/util/TimeSeriesFileManager.java deleted file mode 100644 index 38397059d0..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/TimeSeriesFileManager.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Created on Oct 2, 2003 - * - * - */ -package ohd.hseb.util; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -/** - * author: Chip Gobs - */ -public class TimeSeriesFileManager -{ - - public static double[] readPrecipArray(String fileName) throws java.io.IOException - { - - return readDoubleArray(fileName, true); - } - -// ------------------------------------------------------- - - public static double[] readEvapArray(String fileName) throws java.io.IOException - { - return readDoubleArray(fileName, false); - } -// ------------------------------------------------------- - - public static double[] readDoubleArray(String fileName, boolean skipFirstLine) throws java.io.IOException - { - // System.out.println("----------opening file = " + fileName); - List doubleList = new ArrayList(); - - FileReader fileReader = new FileReader(fileName); - BufferedReader bufferedReader = new BufferedReader(fileReader); - //FileReader reader = new FileReader(fileName); - - String line = null; - int lineCount = 0; - - - line = ""; - - while( line != null) - { - line = bufferedReader.readLine(); - if (line == null) - { - break; - } - lineCount++; - // System.out.println(fileName + ": line " + lineCount + " = " + line); - - if ((skipFirstLine) && (lineCount == 1) ) - { - continue; // skip this line entirely - } - - StringBuffer numberBuffer = new StringBuffer(); - boolean success = false; - boolean foundNumberPart = false; - String numberString = null; - - // assemble the number string from the line - for (int i = 0; i < line.length() ; i++) - { - char c = line.charAt(i); - if ( isPartOfANumber(c) || - ( isWhiteSpace(c) && (foundNumberPart == false ) ) - ) - { - if (isWhiteSpace(c)) - { - //System.out.println("I found whitespace at character " + i); - } - else - { - foundNumberPart = true; - numberBuffer.append(c); - // System.out.println("numberBuffer = " + numberBuffer + " i = " + i); - success = true; - } - } - else //we are done with looking for the number - { - numberString = numberBuffer.toString(); - //System.out.println("numberString = " + numberString); - break; - } - } //end for - - if ((success) && (numberString == null) ) - { - numberString = numberBuffer.toString(); - } - - if (success) - { - double number = -9999.9999; - number = Double.parseDouble(numberString); - doubleList.add(new Double(number)); - } - } //end while - - bufferedReader.close(); - fileReader.close(); - - //copy the list contents to the array of doubles - double[] doubleArray = new double[doubleList.size()]; - for (int i = 0; i < doubleList.size(); i++) - { - - Double doubleVar = (Double) doubleList.get(i); - doubleArray[i] = doubleVar.doubleValue(); - } - - // System.out.println("SacSmaTest.readDoubleArray size = " + - // doubleList.size()); - return doubleArray; - } -// ------------------------------------------------------- - - public static double[] readStateArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[6]; - - int skipAmount = 16; - - //skip the first 16 parameters in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i + skipAmount]; - } - - return sizedArray; - } -// ------------------------------------------------------- - - public static double[] readParameterArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[16]; - - // skip the last 6 state/carryover variables in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i]; - } - - return sizedArray; - } - -// ---------------------------------------------- - private static boolean isWhiteSpace(char c) - { - boolean result = false; - - if ( (c == ' ') || (c== '\t') ) - { - result = true; - - } - return result; - } - -// ---------------------------------------------- - private static boolean isPartOfANumber(char c) - { - boolean result = false; - - if ( ((c >= '0') && (c <= '9')) || - (c =='-') || (c == '.') - ) - { - result = true; - } - - return result; - - } //end isPartOfANumber - -// ---------------------------------------------------------------------------------------------- - - public void saveRegularTimeSeries(RegularTimeSeries rts, String filePath) - { - saveRegularTimeSeries(rts, filePath, null); - } - -// ---------------------------------------------------------------------------------------------- - - public void saveRegularTimeSeries(RegularTimeSeries rts, String filePath, MeasuringUnit unit) - { - - if (unit == null) - { - unit = rts.getMeasuringUnit(); - } - - PrintWriter outputStream = null; - try - { - outputStream = new PrintWriter(new FileOutputStream(filePath)); - } - catch(FileNotFoundException e) - { - System.out.println("Error opening the file " + filePath); - } - - outputStream.println(DbTimeHelper.getDateTimeStringFromLongTime(rts.getStartTime())); //1st line in the file - outputStream.println(DbTimeHelper.getDateTimeStringFromLongTime(rts.getEndTime())); //2nd line in the file - outputStream.println(rts.getIntervalInHours()); //3rd line in the file - - //outputs the values of RTS to the file, starting from index = 0 - for (int i = 0; i < rts.getMeasurementCount(); i++) - { - outputStream.println(rts.getMeasurementValueByIndex(i, unit)); - } - - outputStream.close(); - - } //end of saveRegularTimeSeries() - - - /**************************************************************************** - * reading from a file, fileNameStr, returns an object of RegularTimeSeries - * or null. User needs to check the returned is null or not. - ****************************************************************************/ - public RegularTimeSeries readRegularTimeSeries(String filePath, MeasuringUnit unit) - { - RegularTimeSeries retrievedRTS = null; - - //This is where a real application would open the file. - //System.out.println("Opening: " + filePath + "."); - - BufferedReader inputStream = null; - String startTimeStr = null; - String endTimeStr = null; - int intervalInHours = 0; - - /*-------open the file and get start time & end time & intervalInHours --------*/ - try - { - inputStream = new BufferedReader(new FileReader(filePath)); - startTimeStr = inputStream.readLine().trim(); //get 1st line - endTimeStr = inputStream.readLine().trim(); //get 2nd line - intervalInHours = Integer.parseInt(inputStream.readLine().trim()); //get 3rd line - - /* retrievedRTS = new RegularTimeSeries(DbTimeHelper.getLongTimeFromDateTimeString(startTimeStr), - DbTimeHelper.getLongTimeFromDateTimeString(endTimeStr), - intervalInHours, - unit); - */ - /*-------------read the file from 4th line to end to retrieve all the values-------*/ - int count = 0; - String valueLine = null; - - while ((valueLine = inputStream.readLine()) != null) //start reading from 4th line - { - if(retrievedRTS == null) - { - retrievedRTS = new RegularTimeSeries(DbTimeHelper.getLongTimeFromDateTimeString(startTimeStr), - DbTimeHelper.getLongTimeFromDateTimeString(endTimeStr), - intervalInHours, - unit); - } - Measurement measurement = new Measurement(Double.parseDouble(valueLine.trim()), unit); - long time = (retrievedRTS.getStartTime() + count * intervalInHours * TimeHelper.MILLIS_PER_HOUR ); - retrievedRTS.setMeasurementByTime(measurement, time); - // System.out.println("count = " + count + ": " + Double.parseDouble(valueLine.trim())); - - count++; - } - inputStream.close(); - - } - catch (FileNotFoundException e) - { - System.out.println("File " + filePath + " was not found"); - } - catch (Exception e) - { - System.out.println("Error reading from file " + filePath); - } - - return retrievedRTS; //maybe an object, maybe null. user needs to check the returned. - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/UnitValueMapper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/UnitValueMapper.java deleted file mode 100644 index 90d2496be4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/UnitValueMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * - */ -package ohd.hseb.util; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; - -/** - * @author GobsC - * - * - */ -public class UnitValueMapper implements ValueMapper -{ - - private MeasuringUnit _inputMeasuringUnit = null; - private MeasuringUnit _outputMeasuringUnit = null; - - public UnitValueMapper(MeasuringUnit fromUnit, MeasuringUnit toUnit) - { - _inputMeasuringUnit = fromUnit; - _outputMeasuringUnit = toUnit; - } - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement convertedMeasurement = - Measurement.getConvertedCopy(inputMeasurement, - _inputMeasuringUnit); - double keyValue = convertedMeasurement.getValue(); - - Measurement measurement = new Measurement(keyValue, _inputMeasuringUnit); - Measurement convertedOutputMeasurement = Measurement.getConvertedCopy(measurement, _outputMeasuringUnit); - - return convertedOutputMeasurement; - - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - //-------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/ValueMapper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/ValueMapper.java deleted file mode 100644 index eae614c07a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/ValueMapper.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Created on Oct 22, 2003 - * - * - */ -package ohd.hseb.util; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; - -/** - * @author GobsC - * - * This interface is meant to be used by the TsBackgroundPainter in - * order to determine how to label the right label in the - * TsPaintableCanvas. For example, an implementor of this interface - * could provide the information needed to map between inches to mm - * or from stage to discharge. - * - */ -public interface ValueMapper -{ - public Measurement getResultMeasurement(Measurement measurement); - public MeasuringUnit getInputMeasuringUnit(); - public MeasuringUnit getOutputMeasuringUnit(); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ComponentHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ComponentHelper.java deleted file mode 100644 index 0b493ec9dd..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ComponentHelper.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Created on Oct 21, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 21, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.Component; -import java.awt.Container; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; - -import javax.swing.JPanel; - -public class ComponentHelper -{ - - public static void addPanelComponent( JPanel panel, Component component, int column, int row, int width, int height, int fill ) - { - addComponent( panel, component, column, row, width, height, 0, 0, fill ); - } - - public static void addPanelComponent( JPanel panel, Component component, int column, int row, int width, int height, double weightx, double weighty, int fill ) - { - addComponent( panel, component, column, row, width, height, weightx, weighty, fill ); - } - - public static void addPanelComponent( JPanel panel, Component component, GridBagConstraints gbc, int column, int row, int width, int height, int fill ) - { - addComponent( panel, component, gbc, column, row, width, height, fill ); - } - - public static void addFrameComponent( Container frameContentPane, Component component, int column, int row, int width, int height, int fill ) - { - addComponent( frameContentPane, component, column, row, width, height, 0, 0, fill ); - } - - public static void addFrameComponent( Container frameContentPane, Component component, int column, int row, int width, int height, double weightx, double weighty, int fill ) - { - addComponent( frameContentPane, component, column, row, width, height, weightx, weighty, fill ); - } - - private static void addComponent( Container container, Component component, int column, int row, int width, int height, double weightx, double weighty, int fill) - { - GridBagConstraints gbConstraints = new GridBagConstraints(); - gbConstraints.fill = fill; - - setConstraints( gbConstraints, column, row, width, height, weightx, weighty ); - - GridBagLayout layoutMgr = (GridBagLayout) container.getLayout(); - layoutMgr.setConstraints( component, gbConstraints ); - - container.add( component ); - } - - private static void addComponent( Container container, Component component, GridBagConstraints constraints, int column, int row, int width, int height, int fill) - { - GridBagConstraints gbConstraints = constraints; - gbConstraints.fill = fill; - - double weightx = gbConstraints.weightx; - double weighty = gbConstraints.weighty; - setConstraints( gbConstraints, column, row, width, height, weightx, weighty); - - GridBagLayout layoutMgr = (GridBagLayout) container.getLayout(); - layoutMgr.setConstraints( component, gbConstraints ); - - container.add( component ); - } - - private static void setConstraints( GridBagConstraints gbConstraints, int column, int row, int width, int height, double weightx, double weighty ) - { - gbConstraints.gridx = column; - gbConstraints.gridy = row; - gbConstraints.gridwidth = width; - gbConstraints.gridheight = height; - gbConstraints.weightx = weightx; - gbConstraints.weighty = weighty; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DatePanel.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DatePanel.java deleted file mode 100644 index f81c3f09d0..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DatePanel.java +++ /dev/null @@ -1,622 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 30, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import ohd.hseb.db.DbTimeHelper; - -public class DatePanel extends JPanel -{ - private TimePanel _timePanel = null; - - private int _month = 0; - private int _day = 0; - private int _year = 0; - private long _dateTimeLong = 0; - private boolean _leapYear = false; - - private JButton _upMonthButton = new JButton(); - private JButton _upDayButton = new JButton(); - private JButton _upYearButton = new JButton(); - - private JButton _downMonthButton = new JButton(); - private JButton _downDayButton = new JButton(); - private JButton _downYearButton = new JButton(); - - private JTextField _monthTextField = new JTextField( 6 ); - private JTextField _dayTextField = new JTextField( 3 ); - private JTextField _yearTextField = new JTextField( 4 ); - - private static Map _monthNamesMap = new HashMap(); - private static Map _dayMaxMap = new HashMap(); - - public DatePanel() - /******************** - Purpose: Empty Constructor - *********************/ - { - this( new Date().getTime() ); - } - - public DatePanel( long dateLong ) - /******************** - Purpose: Constructor with a long date value - *********************/ - { - int month, day, year; - - _dateTimeLong = dateLong; - - setupMonthNamesMap(); - - String date = DbTimeHelper.getDateStringFromLongTime( dateLong ); - - year = Integer.parseInt( date.substring( 0, 4 ) ); - month = Integer.parseInt( date.substring( 5, 7 ) ); - day = Integer.parseInt( date.substring( 8, 10 ) ); - - initDate( month, day, year ); - execute(); - } - - private void execute() - /******************** - Purpose: Main execution of the program - *********************/ - { - this.setLayout( new GridBagLayout() ); - - setupDayMaxMap(); - - initDateDisplay(); - - addListeners(); - setSize( 240, 150 ); - } - - private void initDateDisplay() - /******************** - Purpose: Initializes the GUI - *********************/ - { - _upYearButton.setIcon( getUpIcon() ); - _upMonthButton.setIcon( getUpIcon() ); - _upDayButton.setIcon( getUpIcon() ); - _downYearButton.setIcon( getDownIcon() ); - _downMonthButton.setIcon( getDownIcon() ); - _downDayButton.setIcon( getDownIcon() ); - - - - _upYearButton.setBackground( Color.WHITE ); - _upMonthButton.setBackground( Color.WHITE ); - _upDayButton.setBackground( Color.WHITE ); - _downYearButton.setBackground( Color.WHITE ); - _downMonthButton.setBackground( Color.WHITE ); - _downDayButton.setBackground( Color.WHITE ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _upYearButton, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upMonthButton, 10, 0, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upDayButton, 20, 0, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _yearTextField, 0, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _monthTextField, 10, 10, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _dayTextField, 20, 10, 5, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _downYearButton, 0, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downMonthButton, 10, 20, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downDayButton, 20, 20, 1, 1, GridBagConstraints.BOTH ); - } - - - private void initDate( int month, int day, int year ) - /******************** - Purpose: Initializes the date text fields and the month, day, year member variables - *********************/ - { - String dateTimeString = null; - - _monthTextField.setText( "" + _monthNamesMap.get( new Integer( month ) ) ); - _dayTextField.setText( "" + day ); - _yearTextField.setText( "" + year ); - _month = month; - _year = year; - _day = day; - if ( _timePanel != null ) - { - dateTimeString = _year + "-" + _month + "-" + _day + " " + _timePanel.getTimeString(); - _dateTimeLong = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - } - } - - public String getDateString() - { - return _year + "-" + _month + "-" + _day; - } - - - private void updateDate() - /******************** - Purpose: Updates the date/display by calling initDate - *********************/ - { - initDate( _month, _day, _year ); - if ( _timePanel != null ) - { - setDate( _dateTimeLong ); - } - } - - - private ImageIcon getUpIcon() - /******************** - Purpose: Returns the Up Arrow icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.UP_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - private ImageIcon getDownIcon() - /******************** - Purpose: Returns the Down Arrow icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.DOWN_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - private void addListeners() - /******************** - Purpose: Adds all of the listeners - *********************/ - { - // Listeners for the 6 buttons for the date - _upYearButton.addActionListener( new UpYearListener() ); - _upMonthButton.addActionListener( new UpMonthListener() ); - _upDayButton.addActionListener( new UpDayListener() ); - _downYearButton.addActionListener( new DownYearListener() ); - _downMonthButton.addActionListener( new DownMonthListener() ); - _downDayButton.addActionListener( new DownDayListener() ); - - // Listeners for the 3 date Text Fields - _yearTextField.addFocusListener( new YearTextFieldFocusListener() ); - _monthTextField.addFocusListener( new MonthTextFieldFocusListener() ); - _dayTextField.addFocusListener( new DayTextFieldFocusListener() ); - _yearTextField.addActionListener( new YearTextFieldListener() ); - _monthTextField.addActionListener( new MonthTextFieldListener() ); - _dayTextField.addActionListener( new DayTextFieldListener() ); - } - - private void updateDayTextField() - { - int inputDay = 0; - int maxDay = getDayMax(); - - validateLeapYear(); - - try - { - inputDay = Integer.parseInt( _dayTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputDay <= maxDay ) && ( inputDay > 0 ) ) - { - _day = inputDay; - } - updateDate(); - } - - private void updateYearTextField() - { - try - { - _year = Integer.parseInt( _yearTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - validateLeapYear(); // Sets _leapYear to true if it's a leapyear - validateDayValue(); - updateDate(); - } - - private void updateMonthTextField() - { - int inputMonth = 0; - - try - { - inputMonth = Integer.parseInt( _monthTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputMonth >= 1 ) && ( inputMonth <= 12 ) ) - { - _month = inputMonth; - validateLeapYear(); - validateDayValue(); - } - updateDate(); - } - - private class DayTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - public void focusLost(FocusEvent arg0) - { - updateDayTextField(); - } - } - - private class YearTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateYearTextField(); - } - } - - private class MonthTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateMonthTextField(); - } - - } - private class YearTextFieldListener implements ActionListener - /******************** - Purpose: Year text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateYearTextField(); - } - } - - private class MonthTextFieldListener implements ActionListener - /******************** - Purpose: Month text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateMonthTextField(); - } - } - - private class DayTextFieldListener implements ActionListener - /******************** - Purpose: Day text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateDayTextField(); - } - } - - - - - private class UpYearListener implements ActionListener - /******************** - Purpose: Up year button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - _year++; - - validateLeapYear(); // Sets _leapYear to true if it's a leapyear - validateDayValue(); - updateDate(); - } - } - - private class UpMonthListener implements ActionListener - /******************** - Purpose: Up month button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _month < 12 ) - { - _month++; - } - else - { - _month = 1; - } - validateDayValue(); - updateDate(); - } - } - - private class UpDayListener implements ActionListener - /******************** - Purpose: Up day button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _day < getDayMax() ) - { - _day++; - } - else - { - _day = 1; - } - updateDate(); - } - } - - private class DownYearListener implements ActionListener - /******************** - Purpose: Down year button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - // Need to make sure the year is still A.D. - if ( _year >= 1 ) - { - _year--; - } - validateLeapYear(); - validateDayValue(); - updateDate(); - } - } - - private class DownMonthListener implements ActionListener - /******************** - Purpose: Down month button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _month > 1 ) // Checks to see if the month is greater than 1 - { - _month--; - } - else - { - _month = 12; - } - validateDayValue(); - updateDate(); - } - } - - private class DownDayListener implements ActionListener - /******************** - Purpose: Down day button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _day > 1 ) - { - _day--; - } - else - { - _day = getDayMax(); - } - updateDate(); - } - } - - private int getDayMax() - /******************** - Purpose: returns the maximum # of days for the particular month/year - *********************/ - { - String dayMaxString = null; - int dayMax = 0; - - dayMaxString = "" + _dayMaxMap.get( new Integer( _month ) ); - dayMax = Integer.parseInt( dayMaxString ); - - if ( _month == 2 ) - { - if ( _leapYear ) - { - dayMax++; // Adds 1 to the max day which is 28 - } - } - return dayMax; - } - - private void validateDayValue() - /******************** - Purpose: Sets a valid day value when the month is changed - *********************/ - { - int dayMax = getDayMax(); - - if ( _day > dayMax ) - { - _day = dayMax; - } - } - - private void validateLeapYear() - /******************** - Purpose: Determines if _year is a leap year - *********************/ - { - if ( _year % 4 == 0 ) // Checks if the year is divisible by 4 - { - _leapYear = true; - if ( _year % 400 == 0 ) // Checks if the year is divisible by 400 - { - _leapYear = true; - } - if ( ( _year % 100 == 0 ) && ( _year % 400 != 0 ) ) // Checks if the year is divisible by 100 - { // and not by 400. If true, then it is NOT a leap year - _leapYear = false; - } - } - else - { - _leapYear = false; - } - } - - private void setupMonthNamesMap() - /******************** - Purpose: Initialize _monthNamesMap - *********************/ - { - String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", - "September", "October", "November", "December" }; - - for ( int i = 1; i <= 12; i++ ) - { - _monthNamesMap.put( new Integer( i ), months[ i - 1 ] ); - } - } - - private void setupDayMaxMap() - /******************** - Purpose: Initialize _dayMaxMap - *********************/ - { - int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - - for ( int i = 1; i <= 12; i++ ) - { - _dayMaxMap.put( new Integer( i ), new Integer( days[ i - 1 ] ) ); - } - } - - protected long getDateLong() - /******************** - Purpose: Return a long value for the date - *********************/ - { - long dateTimeLong = 0; - String dateString = null; - String dateTimeString = null; - - dateString = _year + "-" + _month + "-" + _day; - - dateTimeString = dateString; - - dateTimeLong = DbTimeHelper.getLongTimeFromDateString( dateTimeString ); - - return dateTimeLong; - } - - public long getDateTimeLong() - /******************** - Purpose: Returns a long value for the date/time by calling getDateTimeLong from TimePanel - *********************/ - { - return _dateTimeLong; - } - - private long getInternalDateTimeLong() - { - return _dateTimeLong; - } - - - public void linkDateTime( TimePanel timePanel ) - /******************** - Purpose: Links the Date object with the Time object - *********************/ - { - _timePanel = timePanel; - if ( _timePanel.getDatePanel() != this ) - { - _timePanel.setTime( _dateTimeLong ); - _timePanel.linkDateTime( this ); - } - } - - public TimePanel getTimePanel() - /******************** - Purpose: returns the Time object - *********************/ - { - return _timePanel; - } - - public void setDate( long dateTimeLong, boolean recurse ) - { - int month, day, year; - - _dateTimeLong = dateTimeLong; - - setupMonthNamesMap(); - - String date = DbTimeHelper.getDateStringFromLongTime( dateTimeLong ); - - year = Integer.parseInt( date.substring( 0, 4 ) ); - month = Integer.parseInt( date.substring( 5, 7 ) ); - day = Integer.parseInt( date.substring( 8, 10 ) ); - - initDate( month, day, year ); - - if ( ( _timePanel != null ) && ( recurse ) ) - { - _timePanel.setTime( dateTimeLong ); - } - } - - public void setDate( long dateTimeLong ) - { - setDate( dateTimeLong, true ); - } - - public static void main( String[] args ) - { - Date date = new Date(); - DatePanel datetimeGUI = new DatePanel( date.getTime() ); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTextField.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTextField.java deleted file mode 100644 index 5930c9c835..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTextField.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Created on Nov 06, 2006 - * - * - */ -package ohd.hseb.util.gui; - - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Date; - -import javax.swing.JFrame; -import javax.swing.JTextField; - -import ohd.hseb.db.DbTimeHelper; - -/** - * @author VarmaR - * - * - */ -public class DateTextField extends JTextField -{ - private JFrame _parent = null; - private String _dialogTitle = null; - private boolean _allowOnlyEvenHours = false; - private String _missingRepresentation = null; - - // ---------------------------------------------------------------------------------------- - public DateTextField(long initialTime, JFrame parent, String dialogTitle, int columns, String missingRepresentation) - { - super(columns); - // this.setColumns(columns); - _parent = parent; - _dialogTitle = dialogTitle; - - setTime(initialTime); - - java.awt.Color backgroundColor = getBackground(); - - setEditable(false); - - setBackground(backgroundColor); - - addListeners(); - - _missingRepresentation = missingRepresentation; - } - // ---------------------------------------------------------------------------------------- - - public long getTime() - { - long time = DbTimeHelper.getLongTimeFromDateTimeString( this.getText() ); - return time; - } - // ---------------------------------------------------------------------------------------- - - public void setTime(long time) - { - if(time != 0) - { - String timeString = DbTimeHelper.getDateStringFromLongTime(time ); - this.setText(timeString); - } - else - { - this.setText("yyyy-mm-dd"); - } - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - - } - - - // ---------------------------------------------------------------------------------------- - private void addListeners() - { - this.addMouseListener(new TimeTextFieldListener()); - - } - - // ---------------------------------------------------------------------------------------- - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if (_missingRepresentation != null && ! _missingRepresentation.equals("") && !textField.getText().equals( "yyyy-mm-dd" ) && !textField.getText().equals( _missingRepresentation )) - { - dateTime = DbTimeHelper.getLongTimeFromDateString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - - DateTimeDialog dateTimeGUI = new DateTimeDialog( _parent, dateTime, _dialogTitle ); - dateTimeGUI.setDateOnly(); - dateTimeGUI.setAllowOnlyEvenHours(_allowOnlyEvenHours); - - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.setVisible(true); - } - } - - // ---------------------------------------------------------------------------------------- - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } - // ---------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeDialog.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeDialog.java deleted file mode 100644 index 917d749f87..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeDialog.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Created on Oct 29, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 29, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.Container; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JPanel; - -public class DateTimeDialog extends JDialog -{ - private Container _frameContentPane = getContentPane(); - private JButton _setTimeButton = new JButton( "Apply" ); - private JButton _cancelButton = new JButton( "Cancel" ); - private TimePanel _timePanel = null; - private DatePanel _datePanel = null; - private List _dateTimeListenerList = new ArrayList(); - private JPanel _buttonPanel = new JPanel(); - - private boolean _allowOnlyEvenHours = false; - - private boolean _dateOnly = false; - - - public DateTimeDialog( JDialog owner, String frameTitle ) - { - this( owner, new Date().getTime(), frameTitle ); - } - - public DateTimeDialog( JDialog owner ) - { - this( owner, new Date().getTime(), "" ); - } - - - public DateTimeDialog( JDialog owner, long dateTimeLong, String frameTitle ) - { - super( owner, true ); - this.setTitle( "Date/Time Display - " + frameTitle ); - _datePanel = new DatePanel(); - _timePanel = new TimePanel(); - setupGUI(); - _datePanel.setDate( dateTimeLong ); - } - - public DateTimeDialog( Frame owner, String frameTitle ) - { - this( owner, new Date().getTime(), frameTitle ); - } - - public DateTimeDialog( Frame owner ) - { - this( owner, new Date().getTime(), "" ); - } - - public DateTimeDialog( Frame owner, long dateTimeLong, String frameTitle ) - { - super( owner, true ); - this.setTitle( "Date/Time Display - " + frameTitle ); - _datePanel = new DatePanel(); - _timePanel = new TimePanel(); - setupGUI(); - _datePanel.setDate( dateTimeLong ); - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - _timePanel.setAllowOnlyEvenHours(_allowOnlyEvenHours); - } - - public void setDateOnly() - { - _timePanel.setVisible( false ); - } - - private void setupGUI() - { - JPanel horizontalSeparatorPanel = new JPanel(); - - _frameContentPane.setLayout( new GridBagLayout() ); - _buttonPanel.setLayout( new GridBagLayout() ); - - _datePanel.linkDateTime( _timePanel ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _datePanel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _timePanel, 0, 2, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _buttonPanel, _setTimeButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _cancelButton, 2, 0, 2, 2, GridBagConstraints.BOTH ); - - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 3, 4, 2, GridBagConstraints.BOTH ); - - setSize( 270, 250 ); - - addListener(); - } - - public void addDateTimeEventListener( DateTimeEventListener dateTimeEventListener ) - { - _dateTimeListenerList.add( dateTimeEventListener ); - } - - private void notifyListeners( DateTimeEvent dateTimeEvent ) - { - for ( int i = 0; i < _dateTimeListenerList.size(); i++ ) - { - DateTimeEventListener listener = (DateTimeEventListener) _dateTimeListenerList.get( i ); - listener.dateTimeEntered( dateTimeEvent ); - } - } - - - private void addListener() - { - _setTimeButton.addActionListener( new SetTimeListener() ); - _cancelButton.addActionListener( new CancelListener() ); - } - - private class SetTimeListener implements ActionListener - /******************** - Purpose: - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - long dateTime = _datePanel.getDateTimeLong(); - - DateTimeEvent dateTimeEvent = new DateTimeEvent( dateTime, true ); - notifyListeners( dateTimeEvent ); - close(); - } - } - - private class CancelListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - long dateTime = _datePanel.getDateTimeLong(); - - DateTimeEvent dateTimeEvent = new DateTimeEvent( dateTime, false ); - notifyListeners( dateTimeEvent ); - close(); - } - } - - private void close() - { - this.dispose(); - } - - - public static void main(String[] args) - { - DateTimeDialog dateTimeGUI = new DateTimeDialog( new Frame(), new Date().getTime(), "Testing" ); - dateTimeGUI.show(); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeEvent.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeEvent.java deleted file mode 100644 index 3d7f05abf7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on Nov 6, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Nov 6, 2003 - * - */ -package ohd.hseb.util.gui; - -/** - * @author SoodG -*/ -public class DateTimeEvent -{ - private boolean _isGoodDate = false; - private long _dateTimeLong = 0; - - public DateTimeEvent() - { - } - - public DateTimeEvent( long dateTimeLong, boolean isGoodDate ) - { - _dateTimeLong = dateTimeLong; - _isGoodDate = isGoodDate; - } - - public void setGoodDate( boolean isGoodDate ) - { - _isGoodDate = isGoodDate; - } - - public boolean isGoodDate() - { - return _isGoodDate; - } - - public void setDateTimeLong( long dateTimeLong ) - { - _dateTimeLong = dateTimeLong; - } - - public long getDateTimeLong() - { - return _dateTimeLong; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeEventListener.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeEventListener.java deleted file mode 100644 index cdecd5dd1e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeEventListener.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Created on Nov 6, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Nov 6, 2003 - * - */ -package ohd.hseb.util.gui; - -public interface DateTimeEventListener -{ - void dateTimeEntered( DateTimeEvent event ); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeTextField.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeTextField.java deleted file mode 100644 index dae6716298..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DateTimeTextField.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Created on Apr 27, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Date; - -import javax.swing.JFrame; -import javax.swing.JTextField; - -import ohd.hseb.db.DbTimeHelper; - -/** - * @author GobsC - * - * - */ -public class DateTimeTextField extends JTextField -{ - private JFrame _parent = null; - private String _dialogTitle = null; - private boolean _allowOnlyEvenHours = false; - private boolean _limitTimeToMinutes = false; //defaults to seconds - - // ---------------------------------------------------------------------------------------- - public DateTimeTextField(long initialTime, JFrame parent, String dialogTitle, int columns) - { - this(initialTime, parent, dialogTitle, columns, false); - } - - public DateTimeTextField(long initialTime, JFrame parent, String dialogTitle, int columns, boolean limitTimeToMinutes) - { - super(columns); - // this.setColumns(columns); - _parent = parent; - _dialogTitle = dialogTitle; - - java.awt.Color backgroundColor = getBackground(); - - setEditable(false); - - setBackground(backgroundColor); - - setLimitTimeToMinutes(limitTimeToMinutes); - - setTime(initialTime); - - addListeners(); - } - - public void setLimitTimeToMinutes(boolean limitTimeToMinutes) - { - _limitTimeToMinutes = limitTimeToMinutes; - } - // ---------------------------------------------------------------------------------------- - - public long getTime() - { - long time = 0; - - if (_limitTimeToMinutes) - { - time = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(this.getText() ); - } - else - { - time = DbTimeHelper.getLongTimeFromDateTimeString( this.getText() ); - } - return time; - } - // ---------------------------------------------------------------------------------------- - - public void setTime(long time) - { - String timeString = null; - - if (_limitTimeToMinutes) //date time string limited to minutes - { - timeString = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - } - else //normal date time string - { - timeString = DbTimeHelper.getDateTimeStringFromLongTime(time ); - } - this.setText(timeString); - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - - } - - - // ---------------------------------------------------------------------------------------- - private void addListeners() - { - this.addMouseListener(new TimeTextFieldListener()); - - } - - // ---------------------------------------------------------------------------------------- - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - String text = textField.getText(); - - if ( ! text.equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - if ( _limitTimeToMinutes) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(text); - } - else - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString(text); - } - } - else - { - dateTime = new Date().getTime(); - } - - DateTimeDialog dateTimeGUI = new DateTimeDialog( _parent, dateTime, _dialogTitle ); - dateTimeGUI.setAllowOnlyEvenHours(_allowOnlyEvenHours); - - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.setVisible(true); - } - } - - // ---------------------------------------------------------------------------------------- - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = null; - - if (_limitTimeToMinutes) - { - timeString = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(dateTimeEvent.getDateTimeLong() ); - } - else //normal, full Year to seconds string - { - timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - - } - - _timeTextField.setText( timeString ); - } - } - } - // ---------------------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DialogHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DialogHelper.java deleted file mode 100644 index 7f958f9157..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/DialogHelper.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Created on Mar 16, 2004 - * - * - */ -package ohd.hseb.util.gui; - - - -import java.awt.Container; -import java.awt.Cursor; -import java.awt.Window; - -import javax.swing.JFrame; -import javax.swing.JOptionPane; - -/** - * @author GobsC - * - * This is a simple class with static methods to make it - * easy to display error and message dialogs. - */ -public class DialogHelper -{ - - - // ----------------------------------------------------------------------------------------- - - - public static boolean displayConfirmDialog(Window parent, String message, String dialogTitle) - { - int choice = 0; - boolean confirm = false; - - choice = JOptionPane.showConfirmDialog( parent, message, dialogTitle, - JOptionPane.YES_NO_OPTION, - JOptionPane.WARNING_MESSAGE ); - - if ( choice == JOptionPane.YES_OPTION ) - { - confirm = true; - } - - return confirm; - } - - // ----------------------------------------------------------------------------------------- - - public static void displayErrorDialog(Window parent, String message, String dialogTitle) - { - - int dialogType = JOptionPane.ERROR_MESSAGE; - - JOptionPane.showMessageDialog(parent, message, dialogTitle, dialogType); - } - - // ----------------------------------------------------------------------------------------- - - public static void displayMessageDialog(Window parent, String message, String dialogTitle) - { - - int dialogType = JOptionPane.INFORMATION_MESSAGE; - - JOptionPane.showMessageDialog(parent, message, dialogTitle, dialogType); - } - - // ----------------------------------------------------------------------------------------- - - public static void displayMessageDialog(Window parent, String message) - { - - JOptionPane.showMessageDialog(parent, message); - } - - // ----------------------------------------------------------------------------------------- - - public static void setWaitCursor(JFrame frame) - { - Container c = frame.getContentPane(); // get the window's content pane - setWaitCursor(c); - //c.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - - } - - public static void setDefaultCursor(JFrame frame) - { - Container c = frame.getContentPane(); // get the window's content pane - setDefaultCursor(c); - // c.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - - } - - public static void setWaitCursor(Container container) - { - container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - - } - - public static void setDefaultCursor(Container container) - { - container.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - -} //end class DialogHelper diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ExtensionFileFilter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ExtensionFileFilter.java deleted file mode 100644 index 2d4981c1c8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ExtensionFileFilter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Created on Jun 16, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 16, 2004 - * - */ -package ohd.hseb.util.gui; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.filechooser.FileFilter; - -/** - * @author SoodG -*/ -public class ExtensionFileFilter extends FileFilter -{ - private List _extensionList = new ArrayList(); - private String _extensionDescription = null; - - public ExtensionFileFilter( List extList, String extensionDescription ) - { - _extensionList = extList; - _extensionDescription = extensionDescription; - } - - public boolean accept( File f ) - { - boolean returnValue = false; - - if ( f.isDirectory() ) - { - returnValue = true; - } - else - { - String extension = getExtension( f ); - - if ( extension != null ) - { - if ( extensionValid( extension ) ) - { - returnValue = true; - } - else - { - returnValue = false; - } - } - } - return returnValue; - } - - private boolean extensionValid( String extension ) - { - boolean isEquals = false; - - for ( int i = 0; i < _extensionList.size(); i++ ) - { - String ext = (String) _extensionList.get( i ); - if( ext.equalsIgnoreCase( extension ) ) - { - isEquals = true; - } - } - return isEquals; - } - - public static String getExtension( File f ) - { - String ext = null; - if ( f != null ) - { - String s = f.getName(); - int i = s.lastIndexOf('.'); - - if (i > 0 && i < s.length() - 1) - { - ext = s.substring(i+1).toLowerCase(); - } - } - return ext; - } - - - public String getDescription() - { - return _extensionDescription; - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/FontHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/FontHelper.java deleted file mode 100644 index 043127c106..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/FontHelper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Created on Jul 20, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.awt.Font; -import java.awt.Graphics; - -/** - * @author GobsC - * - * - */ -public class FontHelper -{ - Font _font = null; - - public FontHelper(Font font) - { - - _font = font; - } - - public int getWidth(Graphics g, String textString) - { - int totalWidth = g.getFontMetrics(_font).stringWidth(textString); - - return totalWidth; - } - - public int getHeight(Graphics g) - { - int height = g.getFontMetrics(_font).getHeight(); - - return height; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/FrameCloseWindowListener.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/FrameCloseWindowListener.java deleted file mode 100644 index b110b46332..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/FrameCloseWindowListener.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JFrame; - - -public class FrameCloseWindowListener extends WindowAdapter -{ - - - - private JFrame _frame = null; - - public FrameCloseWindowListener(JFrame frame) - { - _frame = frame; - } - - public void windowClosing(WindowEvent evt) - { - _frame.dispose(); - } - - public static void addFrameCloseWindowListener(JFrame frame) - { - FrameCloseWindowListener listener = new FrameCloseWindowListener(frame); - - frame.addWindowListener(listener); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ItemsSelectionDialog.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ItemsSelectionDialog.java deleted file mode 100755 index 4c2cca5fd2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/ItemsSelectionDialog.java +++ /dev/null @@ -1,779 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.swing.DefaultListSelectionModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - - -/** - * @author RajaramV - * @modifiedBy CGobs - */ -public class ItemsSelectionDialog extends JDialog -{ - private String _selectedItems[]; - private String _allowedItems[]; - private String _orgSelectedItems[]; - private boolean _isSelectionCancelled = false; - private JList _allowedItemsJList; - private JList _selectedItemsJList; - private Container _container; - private JButton _addButton; - private JButton _removeButton ; - private JButton _applyButton ; - private JButton _moveUpButton; - private JButton _moveDownButton; - private JButton _closeButton; - private JLabel _allowedColLabel ; - private JLabel _selectedColLabel ; - private String _stringForPrototypeCellValue; - private String[] _newItemsAfterAdditionOrRemoval; - private boolean _isAnyItemSelectedForMovedUpOrDown = false; - - - //------------------------------------------------------------------------------------------------------------ - - public ItemsSelectionDialog(JFrame owner,String title, String[] itemsAllowed, - String[] itemsToBePresentInSelectedList) - { - super(owner, true); - _allowedItems=itemsAllowed; - Arrays.sort(_allowedItems, 0, _allowedItems.length); - - _selectedItems = itemsToBePresentInSelectedList; - _orgSelectedItems = _selectedItems; - setStringForPrototypeCellValue(); - if(title == null) - this.setTitle("Items Selection Dialog"); - else - this.setTitle(title); - initGui(); - } - - //------------------------------------------------------------------------------------------------------------ - - private void setStringForPrototypeCellValue() - { - String string = null; - if( _allowedItems.length > 0 ) - { - string = _allowedItems[0]; - for(int i = 1; i < _allowedItems.length; i++) - { - if ( _allowedItems[i].length() > string.length()) - string = _allowedItems[i]; - } - } - _stringForPrototypeCellValue = string; - } - - //------------------------------------------------------------------------------------------------------------ - - private void initGui() - { - - _container = getContentPane(); - _container.setLayout(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - _container.setPreferredSize(new Dimension(490, 490)); - - //create the top part of the gui - JPanel mainPanel = initMainPanel(); - - //add bottom button panel - _applyButton = new JButton("Apply"); - _closeButton = new JButton("Close"); - - JPanel buttonPanel = new JPanel(); - buttonPanel.add(_applyButton); - buttonPanel.add(_closeButton); - - /* col, row, width, height, weightx weighty fill(opt) */ - addComponent(_container, mainPanel, gbc, 0, 0, 4, 10, 1, 1, 1); - addComponent(_container, buttonPanel, gbc, 0, 10, 4, 1, 0, 0); - - - if(_isAnyItemSelectedForMovedUpOrDown) - { - _selectedItemsJList.clearSelection(); - _isAnyItemSelectedForMovedUpOrDown = false; - } - - // mainPanel.addComponentListener(new WindowResizeListener(mainPanel)); - - addListeners(); - - _newItemsAfterAdditionOrRemoval = new String[_selectedItems.length]; - System.arraycopy(_selectedItems, 0, _newItemsAfterAdditionOrRemoval, 0, _selectedItems.length); - this.pack(); - this.setVisible(true); - } - - //------------------------------------------------------------------------------------------------------------ - private JButton initArrowButton(String iconType) - { - Dimension dimension = new Dimension(15, 20); - - Color buttonColor = this.getBackground(); - Color imageColor = Color.BLUE; - - ImageIcon arrowIcon = StandardImageIcons.getImageIcon(iconType, - imageColor, buttonColor, dimension); - - - JButton button = new JButton(arrowIcon); - - button.setPreferredSize(dimension); - - return button; - - } - - //------------------------------------------------------------------------------------------------------------ - - private JPanel initMainPanel() - { - final int visibleRowCount = 30; - - JPanel mainPanel = new JPanel(); - mainPanel.setLayout(new GridBagLayout()); - //mainPanel.setBackground(Color.RED); - - GridBagConstraints gbc = new GridBagConstraints(); - - _addButton = new JButton("Add >>"); - _removeButton = new JButton("Remove <<"); - - _moveUpButton = initArrowButton(StandardImageIcons.UP_ARROW); - _moveDownButton = initArrowButton(StandardImageIcons.DOWN_ARROW); - - //set tooltips - _moveUpButton.setToolTipText("Move selected items up in the list."); - _moveDownButton.setToolTipText("Move selected items down in the list."); - - - // _moveUpButton = new JButton("^"); - // _moveDownButton = new JButton("v"); - - _allowedColLabel = new JLabel("Allowed Items"); - _selectedColLabel = new JLabel("Selected Items"); - - _allowedItemsJList = new JList(_allowedItems); - _allowedItemsJList.setVisibleRowCount(visibleRowCount); - _allowedItemsJList.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - if(_stringForPrototypeCellValue.length() < ("Allowed Items").length()) - { - _allowedItemsJList.setPrototypeCellValue(("Allowed Items")); - } - _allowedItemsJList.setAutoscrolls(true); - - JPanel allowedListPanel = new JPanel(); - JScrollPane allowedScrollPane = new JScrollPane(_allowedItemsJList); - allowedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - allowedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - allowedListPanel.setLayout(new GridLayout(1,1)); - allowedListPanel.add(allowedScrollPane); - - - if(_selectedItems !=null) - _selectedItemsJList = new JList(_selectedItems); - else - _selectedItemsJList = new JList(); - - _selectedItemsJList.setVisibleRowCount(visibleRowCount); - _selectedItemsJList.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - if(_stringForPrototypeCellValue.length() < ("Selected Items").length()) - { - _selectedItemsJList.setPrototypeCellValue(("Selected Items")); - } - _selectedItemsJList.setAutoscrolls(true); - - JPanel selectedListPanel = new JPanel(); - JScrollPane selectedScrollPane = new JScrollPane(_selectedItemsJList); - selectedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - selectedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - selectedListPanel.setLayout(new GridLayout(1,1)); - selectedListPanel.add(selectedScrollPane); - - - JPanel addAndRemoveButtonPanel = new JPanel(); - // addandRemoveButtonsPanel.setLayout(new GridLayout(2,1,15,15)); - - // addAndRemoveButtonPanel.setBackground(Color.PINK); - addAndRemoveButtonPanel.setLayout(new GridLayout(2, 1, 0, 15)); - addAndRemoveButtonPanel.add(_addButton); - addAndRemoveButtonPanel.add(_removeButton); - - JPanel moveButtonsPanel = new JPanel(); - moveButtonsPanel.setLayout(new GridLayout(2, 1, 0, 15)); - moveButtonsPanel.add(_moveUpButton); - moveButtonsPanel.add(_moveDownButton); - - JPanel verticalFillerPanel = new JPanel(); - verticalFillerPanel.setPreferredSize(new Dimension(50, 50)); - // verticalFillerPanel.setBackground(Color.BLUE); - - JPanel verticalFillerPanel2 = new JPanel(); - verticalFillerPanel2.setPreferredSize(new Dimension(50, 50)); - // verticalFillerPanel2.setBackground(Color.GREEN); - - gbc.insets = new Insets(5,5,5,5); - /* col, row, width, height, weightx weighty fill(opt) */ - - addComponent(mainPanel, _allowedColLabel, gbc, 1, 0, 1, 1, 0, 0); - addComponent(mainPanel, allowedListPanel, gbc, 1, 1, 1, 5, 1, 1, 1); - addComponent(mainPanel, addAndRemoveButtonPanel, gbc, - 2, 3, 1, 1, 0, 0); - - addComponent(mainPanel, verticalFillerPanel, gbc, 2, 0, 1, 2, 0, 1, 1); - addComponent(mainPanel, verticalFillerPanel2, gbc, 2, 3, 1, 2, 0, 1, 1); - - - addComponent(mainPanel, _selectedColLabel, gbc, 3, 0, 1, 1, 0, 0); - addComponent(mainPanel, selectedListPanel, gbc, 3, 1, 1, 5, 1, 1, 1); - - addComponent(mainPanel, moveButtonsPanel, gbc, 4, 3, 1, 1, 0, 0); - - - return mainPanel; - - } - - //------------------------------------------------------------------------------------------------------------ - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - addComponent(container, component, gbc, column, row, columnCells, rowCells, weightX, weightY, 0); - } - - //------------------------------------------------------------------------------------------------------------ - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY, int fill) - { - -// how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - -// what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - -// the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - gbc.fill = fill; - - container.add(component, gbc); - - return; - } - - //------------------------------------------------------------------------------------------------------------ - - - private void addListeners() - { - _addButton.addActionListener( new AddButtonListener()); - _removeButton.addActionListener(new RemoveButtonListener()); - _closeButton.addActionListener(new CloseButtonListener()); - _moveUpButton.addActionListener(new MoveUpButtonListener()); - _moveDownButton.addActionListener(new MoveDownButtonListener()); - - _applyButton.addActionListener(new ConfirmSelectionButtonListener()); - - //allows user to remove items with the delete or backspace keys - _selectedItemsJList.addKeyListener(new SelectedListKeyListener()); - _selectedItemsJList.addMouseListener(new DoubleClickOnSelectedListener()); - - _allowedItemsJList.addKeyListener(new AllowedListKeyListener()); - _allowedItemsJList.addMouseListener(new DoubleClickOnAllowedListener()); - return; - } - - // ------------------------------------------------------------------------------------------------------------ - public String[] getSelectedItems() - { - String [] returnedSelectedItems = null ; - if(!_isSelectionCancelled) - { - if(_selectedItems != null) - { - returnedSelectedItems = new String[_selectedItems.length]; - - System.arraycopy(_selectedItems, 0, - returnedSelectedItems, 0, - _selectedItems.length ); - } - } - else - { - returnedSelectedItems = _orgSelectedItems; - } - return returnedSelectedItems; - } - - // ------------------------------------------------------------------------------------------------------------ - private class DoubleClickOnAllowedListener extends MouseAdapter - { - public void mouseClicked(MouseEvent e) - { - if( e.getClickCount() == 2) - { - addSelectedItems(); - } - - } - - } - - // ------------------------------------------------------------------------------------------------------------ - - private class DoubleClickOnSelectedListener extends MouseAdapter - { - public void mouseClicked(MouseEvent e) - { - if( e.getClickCount() == 2) - { - removeSelectedItems(); - } - - } - - } - - private class AddButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - addSelectedItems(); - } - } - // ------------------------------------------------------------------------------------------------------------ - - private class CloseButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _isSelectionCancelled = true; - closeItemsSelectionDialog(); - } - } - // ------------------------------------------------------------------------------------------------------------ - private void addSelectedItems() - { - int[] indicesOfNewItemsSelectedFromAllowedList =_allowedItemsJList.getSelectedIndices(); - int numOfNewItemsSelectedFromAllowedList = indicesOfNewItemsSelectedFromAllowedList.length; - int numOfExistingItemsInNewList = _selectedItemsJList.getModel().getSize(); - - // All the items in allowed list are already present in new List - if(numOfExistingItemsInNewList == _allowedItemsJList.getModel().getSize()) - { - - } - //New List is empty, so add all the item selected from allowed list - else if (numOfExistingItemsInNewList == 0) - { - _selectedItemsJList.setListData(_allowedItemsJList.getSelectedValues()); - } - else //Compare existing new list and items newly selected from allowed list for any match then add - { - int cntOfSameItems=0; - for(int i =0; i< numOfNewItemsSelectedFromAllowedList; i++) - { - int index = indicesOfNewItemsSelectedFromAllowedList[i]; - String itemFromAllowed = _allowedItemsJList.getModel().getElementAt(index).toString(); - for(int j = 0; j < numOfExistingItemsInNewList; j++) - { - String itemFromExistingNewList = _selectedItemsJList.getModel().getElementAt(j).toString(); - if(itemFromExistingNewList.compareTo(itemFromAllowed) == 0) - { - cntOfSameItems++; - } - } - } - - - int numOfFinalItemsAfterAddition = (numOfNewItemsSelectedFromAllowedList + - numOfExistingItemsInNewList) - cntOfSameItems; - - _newItemsAfterAdditionOrRemoval = new String[numOfFinalItemsAfterAddition]; - - int cnt=0; - for(cnt=0; cnt=0; j--) - { - int indexInBlock = new Integer(blockList.get(j).toString()).intValue(); - String temp = finalSelectedItems[indexInBlock+1] ; - finalSelectedItems[indexInBlock+1] = finalSelectedItems[indexInBlock]; - finalSelectedItems[indexInBlock] = temp; - } - } - } - System.arraycopy(finalSelectedItems, 0, _newItemsAfterAdditionOrRemoval, 0, _newItemsAfterAdditionOrRemoval.length); - System.arraycopy(finalSelectedItems, 0, _selectedItems, 0, _selectedItems.length); - - _selectedItemsJList.setListData(_selectedItems); - - } - // ------------------------------------------------------------------------------------------------------------ - - private void closeItemsSelectionDialog() - { - this.dispose(); - } - - // ------------------------------------------------------------------------------------------------------------ - - private class ConfirmSelectionButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - setFinalSelectedItemsArray(); - closeItemsSelectionDialog(); - } - } - // ------------------------------------------------------------------------------------------------------------ - - private class SelectedListKeyListener implements KeyListener - { - public void keyPressed(KeyEvent e) - { - int keyCode = e.getKeyCode(); - - if ( ( keyCode == KeyEvent.VK_DELETE) || (keyCode == KeyEvent.VK_BACK_SPACE) ) - { - removeSelectedItems(); - } - - } - - public void keyReleased(KeyEvent e) - { - - } - - public void keyTyped(KeyEvent e) - { - - - } - } - - - // ------------------------------------------------------------------------------------------------------------ - private class AllowedListKeyListener implements KeyListener - { - public void keyPressed(KeyEvent e) - { - int keyCode = e.getKeyCode(); - - if (keyCode == KeyEvent.VK_ENTER) - { - addSelectedItems(); - } - } - - public void keyReleased(KeyEvent e) - { - - } - - public void keyTyped(KeyEvent e) - { - - } - } - - - // ------------------------------------------------------------------------------------------------------------ - - private static String[] initBigItemsArray(int count) - { - String [] itemStringArray = new String[count]; - - for (int i = 0; i < count; i++) - { - itemStringArray[i] = "Item" + i; - } - - return itemStringArray; - } - // ------------------------------------------------------------------------------------------------------------ - - public static void main(String[] args) - { - JFrame frame = new JFrame(); - - frame.setSize(new Dimension(250, 250)); - frame.setVisible(true); - - FrameCloseWindowListener.addFrameCloseWindowListener(frame); - - String titleString = "Test ColumnSelection"; - - String[] initialSelectedList = {"Item2", "Item4"}; - - String[] bigItemsAllowed = initBigItemsArray(100); - - new ItemsSelectionDialog(frame, titleString, bigItemsAllowed, initialSelectedList); - - frame.dispose(); - - } -} - -// ------------------------------------------------------------------------------------ - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledComboBox.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledComboBox.java deleted file mode 100644 index c486681b71..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledComboBox.java +++ /dev/null @@ -1,234 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionListener; -import java.awt.event.MouseWheelListener; -import java.util.List; - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -public class LabeledComboBox extends JPanel -{ - private JLabel _label = new JLabel(); - private JComboBox _comboBox = new JComboBox(); - private GridBagConstraints _gbLabelConstraints = new GridBagConstraints(); - private GridBagConstraints _gbTFConstraints = new GridBagConstraints(); - - public LabeledComboBox() - { - setupConstraints(); - setupComponents(); - } - - public LabeledComboBox( String labelText ) - { - this(); - setLabel( labelText ); - } - - public LabeledComboBox( String labelText, String[] comboBoxStringArray ) - { - this(); - setLabel( labelText ); - setComboBox( comboBoxStringArray ); - } - - public LabeledComboBox( String labelText, String tooltip ) - { - this(); - setLabel( labelText ); - _comboBox.setToolTipText( tooltip ); - } - - public LabeledComboBox( String labelText, List comboBoxStringList ) - { - this(); - setLabel( labelText ); - setComboBox( comboBoxStringList ); - } - - public LabeledComboBox( String labelText, String[] comboBoxStringArray, String toolTipText ) - { - this( labelText, comboBoxStringArray ); - setToolTipText( toolTipText ); - } - - public LabeledComboBox( String labelText, List comboBoxStringList, String toolTipText ) - { - this( labelText, comboBoxStringList ); - setToolTipText( toolTipText ); - } - - private void setupComponents() - { - this.setLayout( new GridBagLayout() ); -// _label.setPreferredSize( new Dimension( 150, 15 ) ); -// _comboBox.setPreferredSize( new Dimension( 150, 15 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _label, _gbLabelConstraints, 0, 0, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addPanelComponent( this, _comboBox, _gbTFConstraints, 1, 0, 1, 1, GridBagConstraints.VERTICAL ); - } - - public String toString() - { - return "Label = " + _label.getText() + " | ComboBox = " + (String) _comboBox.getSelectedItem(); - } - - private void setupConstraints() - { - _gbLabelConstraints.anchor = GridBagConstraints.EAST; - _gbLabelConstraints.weightx = 1; - _gbLabelConstraints.weighty = 1; - - _gbTFConstraints.anchor = GridBagConstraints.WEST; - _gbTFConstraints.weightx = 1; - _gbTFConstraints.weighty = 1; - } - - public void setLabelPreferredSize( Dimension dimension ) - { - _label.setPreferredSize( dimension ); - } - - public void setComboBoxPreferredSize( Dimension dimension ) - { - _comboBox.setPreferredSize( dimension ); - } - - public void setLabel( String labelString ) - { - _label.setText( labelString ); - } - - public String getLabel() - { - return _label.getText(); - } - - public void setComboBox( JComboBox comboBox ) - { - _comboBox = comboBox; - } - - public void setComboBoxFromStringArray( Object[] comboBoxStringArray ) - { - String comboBoxString = null; - - for ( int i = 0; i < comboBoxStringArray.length;i++ ) - { - comboBoxString = (String) comboBoxStringArray[ i ]; - _comboBox.addItem( comboBoxString ); - } - } - - public void setComboBox( String[] comboBoxStringArray ) - { - for ( int i = 0; i < comboBoxStringArray.length; i++ ) - { - _comboBox.addItem( comboBoxStringArray[ i ] ); - } - } - - public void setComboBox( List comboBoxStringList ) - { - String comboBoxString = null; - _comboBox.removeAllItems(); - - for ( int i = 0; i < comboBoxStringList.size(); i++ ) - { - comboBoxString = (String) comboBoxStringList.get( i ); - _comboBox.addItem( comboBoxString ); - } - } - - public JComboBox getComboBox() - { - return _comboBox; - } - - public String getSelectedCBItem() - { - return ( (String) _comboBox.getSelectedItem() ); - } - - public void setToolTip( String toolTipText ) - { - _label.setToolTipText( toolTipText ); - } - - public void enableComboBox( boolean enable ) - { - _comboBox.setEnabled( enable ); - } - - public void enableLabel( boolean enable ) - { - _label.setEnabled( enable ); - } - - public void setEditComboBox( boolean editable ) - { - _comboBox.setEditable( editable ); - } - - public void setSelectedItem( Object object ) - { - _comboBox.setSelectedItem( object ); - } - - public void setSelectedIndex( int index ) - { - _comboBox.setSelectedIndex( index ); - } - - public int getSelectedIndex() - { - return _comboBox.getSelectedIndex(); - } - - public int getItemCount() - { - return _comboBox.getItemCount(); - } - - public Object getSelectedItem() - { - return _comboBox.getSelectedItem(); - } - - public void enableLabeledTextField( boolean enable ) - { - enableComboBox( enable ); - enableLabel( enable ); - } - - public void setLabelFont( Font font ) - { - _label.setFont( font ); - } - - public void setComboBoxFont( Font font ) - { - _comboBox.setFont( font ); - } - - public void addComboBoxActionListener( ActionListener actionListener ) - { - _comboBox.addActionListener( actionListener ); - } - - public void addComboBoxWheelListener( MouseWheelListener wheelListener ) - { - _comboBox.addMouseWheelListener( wheelListener ); - } - - public void removeComboBoxActionListener( ActionListener actionListener ) - { - _comboBox.removeActionListener( actionListener ); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledSlider.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledSlider.java deleted file mode 100644 index a72bbbea53..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledSlider.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Created on Nov 16, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.text.DecimalFormat; -import java.text.NumberFormat; - -import javax.swing.BoundedRangeModel; -import javax.swing.DefaultBoundedRangeModel; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeListener; - -import ohd.hseb.util.MathHelper; - -/** - * @author GobsC - * - * - */ -public class LabeledSlider extends JPanel -{ - - private JSlider _slider = null; - private JLabel _label = null; - private JLabel _valueLabel = null; - - - private double _initialModelValue = 0.0; - private double _minModelValue = 0.0; - private double _maxModelValue = 1.0; - - private int _sliderMin = 0; - private int _sliderMax = 100; - - private NumberFormat _numberFormat = new DecimalFormat("###.00"); - - -// ---------------------------------------------------------------------------- - - public LabeledSlider(String labelString, - double initialModelValue, - double minModelValue, - double maxModelValue, - int width, - int height) - { - - //set the private data member variables - - _label = new JLabel(labelString); - - _initialModelValue = initialModelValue; - _minModelValue = minModelValue; - _maxModelValue = maxModelValue; - - - //initialize the private gui variables - - int initialSliderValue = getSliderValueFromModelValue(initialModelValue); - _valueLabel = new JLabel(getSliderValueLabelString(initialModelValue)); - - BoundedRangeModel boundedRangeModel = new DefaultBoundedRangeModel(); - boundedRangeModel.setMinimum(_sliderMin); - boundedRangeModel.setMaximum(_sliderMax); - boundedRangeModel.setValue(initialSliderValue); - _slider = new JSlider(boundedRangeModel); - - //add gui elements - this.add(_label); - this.add(_slider); - this.add(_valueLabel); - - this.setSize(width, height); - - - } - - // ---------------------------------------------------------------------------- - public double getModelValue() - { - return getModelValueFromSliderValue(_slider.getValue()); - } - // ---------------------------------------------------------------------------- - - public void setModelValue(double modelValue) - { - int sliderValue = getSliderValueFromModelValue(modelValue); - - _slider.setValue(sliderValue); - - updateValueLabel(); - - } - - -// ---------------------------------------------------------------------------- - public void addChangeListener(ChangeListener listener) - { - - _slider.addChangeListener(listener); - - return; - } -// ---------------------------------------------------------------------------- - - - private int getSliderValueFromModelValue(double modelValue) - { - double modelRange = _maxModelValue - _minModelValue; - double sliderRange = _sliderMax - _sliderMin; - - double modelDiff = modelValue - _minModelValue; - double modelFraction = modelDiff / modelRange; - - double sliderDoubleValue = _sliderMin + (modelFraction * sliderRange); - - return (int) Math.round(sliderDoubleValue); - } - -// ---------------------------------------------------------------------------- - - - private double getModelValueFromSliderValue(int sliderValue) - { - - double modelRange = _maxModelValue - _minModelValue; - double sliderRange = _sliderMax - _sliderMin; - - double sliderDiff = sliderValue - _sliderMin; - double sliderFraction = sliderDiff / sliderRange; - - double modelValue = _minModelValue + (sliderFraction * modelRange); - - modelValue = MathHelper.roundToNDecimalPlaces(modelValue, 2); - - return modelValue; - } - // ---------------------------------------------------------------------------- - - private String getSliderValueLabelString(double modelValue) - { - String modelValueString = _numberFormat.format(modelValue); - modelValueString = padToNChars(modelValueString, 6); - - String maxModelValueString = _numberFormat.format(_maxModelValue); - maxModelValueString = padToNChars(maxModelValueString, 6); - - String stringValue = modelValueString + "| max = " + maxModelValueString; - return stringValue; - } - - // ---------------------------------------------------------------------------- - - private String padToNChars(String originalString, int charCount) - { - String newString = originalString; - int length = originalString.length() ; - if (length < charCount) - { - int diff = charCount - length; - StringBuffer buffer = new StringBuffer(originalString); - for (int i = 0; i < diff; i++) - { - buffer.insert(0, ' '); - } - newString = buffer.toString(); - } - - return newString; - } - // ---------------------------------------------------------------------------- - /** - * @param slider The slider to set. - */ - private void setSlider(JSlider slider) - { - _slider = slider; - } - -// ---------------------------------------------------------------------------- - - /** - * @return Returns the slider. - */ - private JSlider getSlider() - { - return _slider; - } - -// ---------------------------------------------------------------------------- - - /** - * @param sliderLabel The sliderLabel to set. - */ - private void setLabel(JLabel label) - { - _label = label; - } - -// ---------------------------------------------------------------------------- - - /** - * @return Returns the sliderLabel. - */ - private JLabel getLabel() - { - return _label; - } - -// ---------------------------------------------------------------------------- - - /** - * @param sliderValueLabel The sliderValueLabel to set. - */ - private void setValueLabel(JLabel valueLabel) - { - _valueLabel = valueLabel; - } -// ---------------------------------------------------------------------------- - private void updateValueLabel() - { - String labelString = getSliderValueLabelString(getModelValue()); - _valueLabel.setText(labelString); - } -// ---------------------------------------------------------------------------- - - /** - * @return Returns the sliderValueLabel. - */ - private JLabel getValueLabel() - { - return _valueLabel; - } -// ---------------------------------------------------------------------------- - - - - /* - private class LabeledSliderChangeListener implements ChangeListener - { - public void stateChanged(ChangeEvent e) - { - double newValue = getModelValueFromSliderValue(getSlider().getValue()); - _valueLabel.setText(getSliderValueLabelString(newValue)); - - _streamModel.setLztwc(newValue); - notifyListeners("LZTWC changed"); - } - } - */ -// ---------------------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledTextField.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledTextField.java deleted file mode 100644 index 13bfc53808..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/LabeledTextField.java +++ /dev/null @@ -1,212 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.KeyListener; -import java.awt.event.MouseListener; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; - -public class LabeledTextField extends JPanel -{ - private JLabel _label = new JLabel(); - private JTextField _textField = new JTextField(); - private GridBagConstraints _gbLabelConstraints = new GridBagConstraints(); - private GridBagConstraints _gbTFConstraints = new GridBagConstraints(); - - public LabeledTextField() - { -// setPreferredSize( new Dimension( 240, 15 ) ); - setupConstraints(); - setupComponents(); -// this.setBackground( Color.YELLOW ); - } - - public LabeledTextField( String labelText, String textFieldText, int textFieldWidthInColumns ) - { - this(); - setLabel( labelText ); - setTextField( textFieldText ); - setTextFieldWidth( textFieldWidthInColumns ); - } - - public LabeledTextField( String labelText, String textFieldText, String toolTipText, int textFieldWidthInColumns ) - { - this(); - setLabel( labelText ); - setTextField( textFieldText ); - setTextFieldWidth( textFieldWidthInColumns ); - setToolTipText( toolTipText ); - _label.setToolTipText( toolTipText ); - _textField.setToolTipText( toolTipText); - } - - private void setupComponents() - { -// this.setLayout( new FlowLayout( FlowLayout.LEFT ) ); - setLayout( new GridBagLayout() );; -// _label.setPreferredSize( new Dimension( 120, 15 ) ); -// _label.setMaximumSize( new Dimension( 100, 15 ) ); -// _textField.setPreferredSize( new Dimension( 120, 15 ) ); -// _textField.setMaximumSize( new Dimension( 100, 15 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _label, _gbLabelConstraints, 0, 0, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addPanelComponent( this, _textField, _gbTFConstraints, 1, 0, 1, 1, GridBagConstraints.VERTICAL ); -// this.add( _label ); -// this.add( _textField ); - - } - - public String toString() - { - return "Label = " + _label.getText() + " | TextField = " + _textField.getText(); - } - - private void setupConstraints() - { - _gbLabelConstraints.anchor = GridBagConstraints.EAST; - _gbLabelConstraints.weightx = 1; - _gbLabelConstraints.weighty = 0; - - _gbTFConstraints.anchor = GridBagConstraints.WEST; - _gbTFConstraints.weightx = 1; - _gbTFConstraints.weighty = 0; - } - - public void setLabel( String labelString ) - { - _label.setText( labelString ); - } - - public String getLabelText() - { - return _label.getText(); - } - - public void setTextField( String textFieldText ) - { - _textField.setText( textFieldText ); - } - - public void setTextField( double textFieldNumber ) - { - setNumberField( textFieldNumber ); - } - - public void setTextField( int textFieldNumber ) - { - setNumberField( textFieldNumber ); - } - - public void setTextField( short textFieldNumber ) - { - setNumberField( textFieldNumber ); - } - - public void setTextFieldDate( long dateString ) - { - _textField.setText( DbTimeHelper.getDateStringFromLongTime( dateString ) ); - } - - private void setNumberField( double doubleValue ) - { - if ( DbTable.isNull( doubleValue ) ) - { - _textField.setText( "" ); - } - else - { - _textField.setText( Double.toString( doubleValue ) ); - } - } - - private void setNumberField( short shortValue ) - { - if ( DbTable.isNull( shortValue ) ) - { - _textField.setText( "" ); - } - else - { - _textField.setText( Short.toString( shortValue ) ); - } - } - - private void setNumberField( int doubleValue ) - { - if ( DbTable.isNull( doubleValue ) ) - { - _textField.setText( "" ); - } - else - { - _textField.setText( Integer.toString( doubleValue ) ); - } - } - - - public String getTextFieldText() - { - return _textField.getText(); - } - - public void setTextFieldWidth( int columns ) - { - _textField.setColumns( columns ); - } - - public void setToolTip( String toolTipText ) - { - _label.setToolTipText( toolTipText ); - _textField.setToolTipText( toolTipText ); - } - - public void enableTextField( boolean enable ) - { - _textField.setEnabled( enable ); - } - - public void enableLabel( boolean enable ) - { - _label.setEnabled( enable ); - } - - public void setEditTextField( boolean editable ) - { - _textField.setEditable( editable ); - } - - public void enableLabeledTextField( boolean enable ) - { - enableTextField( enable ); - enableLabel( enable ); - } - - public void addTextFieldKeyListener( KeyListener keyListener ) - { - _textField.addKeyListener( keyListener ); - } - - public void addTextFieldMouseListener( MouseListener mouseListener ) - { - _textField.addMouseListener( mouseListener ); - } - - public void setLabelPreferredSize( Dimension dimension ) - { - _label.setPreferredSize( dimension ); - } - - public void setTextFieldPreferredSize( Dimension dimension ) - { - _textField.setPreferredSize( dimension ); - } - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/OptionSelectionDialog.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/OptionSelectionDialog.java deleted file mode 100644 index ea3cc38581..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/OptionSelectionDialog.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Created on Aug 10, 2005 - * - * - */ -package ohd.hseb.util.gui; - -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JOptionPane; - - -/** - * @author Chip Gobs - * - * - */ -public class OptionSelectionDialog -{ - - private String _itemString = null; - - //--------------------------------------------------- - - public OptionSelectionDialog() - { - - } - //--------------------------------------------------- - - private void setItemString(String itemString) - { - this._itemString = itemString; - } - - public String getItemString() - { - return _itemString; - } - - // --------------------------------------------------- - - public boolean requestItemByDialog(String dialogTitleString, - String textMessage, - String comboBoxLabelString, - String[] optionArray) - { - String password = null; - JComboBox comboBox = new JComboBox(); - - - for (int i = 0; i < optionArray.length; i++) - { - comboBox.addItem(optionArray[i]); - } - - Object[] messageObjectArray = - { textMessage, - comboBoxLabelString, comboBox, - }; - - //_userName = JOptionPane.showInputDialog(null, messageObjectArray); - - - JOptionPane optionPane = new JOptionPane(); - - optionPane.setMessage( messageObjectArray ); - - optionPane.setMessageType( JOptionPane.QUESTION_MESSAGE ); - - JDialog dialog = optionPane.createDialog( null, dialogTitleString); - - dialog.show(); - - dialog.dispose(); - - - _itemString = (String) comboBox.getSelectedItem(); - - - return true; - } - - - - //--------------------------------------------------- - - public static void main(String[] args) - { - - OptionSelectionDialog dialog = new OptionSelectionDialog(); - - String title = "Rainfall-Runoff Model Selection"; - String message = "Please enter the rainfall-runoff model\n" + - " for which this unit hydrograph is appropriate.\n" + - " " ; - String comboBoxLabelString = "Rainfall-Runoff Model:"; - String[] optionArray = { "ANY ", - "API-MKC", - "SAC-SMA" }; - - dialog.requestItemByDialog(title, message, comboBoxLabelString, optionArray ); - - System.out.println("model = " + dialog.getItemString()); - - } - //--------------------------------------------------- -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/PasswordDialog.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/PasswordDialog.java deleted file mode 100644 index 90ea5b4231..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/PasswordDialog.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Created on Aug 29, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.util.gui; - -import javax.swing.JDialog; -import javax.swing.JOptionPane; -import javax.swing.JPasswordField; -import javax.swing.JTextField; - - -/** - * @author Chip Gobs - * - * This class lets the user request a password and obscures it - * as it is being typed in. - */ -public class PasswordDialog -{ - - private String _userName = null; - private String _password = null; - - //--------------------------------------------------- - - public PasswordDialog() - { - - } - //--------------------------------------------------- - - public void setUserName(String userName) - { - _userName = userName; - } - - public String getUserName() - { - return _userName; - } - - public void setPassword(String password) - { - _password = password; - } - - public String getPassword() - { - return _password; - } - - //--------------------------------------------------- - - - public boolean requestPasswordByDialog(String textMessage) - { - String password = null; - JTextField userNameField = new JTextField(""); - JPasswordField passwordField = new JPasswordField(""); - - Object[] messageObjectArray = - { textMessage, - "User Name:", userNameField, - "Password:", passwordField - }; - - //_userName = JOptionPane.showInputDialog(null, messageObjectArray); - - - JOptionPane optionPane = new JOptionPane(); - - optionPane.setMessage( messageObjectArray ); - - optionPane.setMessageType( JOptionPane.QUESTION_MESSAGE ); - - JDialog dialog = optionPane.createDialog( null, "Password" ); - - dialog.show(); - - dialog.dispose(); - - - _userName = new String(userNameField.getText()); - _password = new String(passwordField.getPassword()); - - - - return true; - } - - - - //--------------------------------------------------- - public static void main(String[] args) - { - - PasswordDialog dialog = new PasswordDialog(); - - dialog.requestPasswordByDialog("Please enter your username and password, dude!"); - - System.out.println("username = " + dialog.getUserName()); - System.out.println("password = " + dialog.getPassword()); - - } - - - // --------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/StandardImageIcons.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/StandardImageIcons.java deleted file mode 100644 index 42d44f41ac..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/StandardImageIcons.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Created on Dec 15, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.ImageIcon; - - -/** - * @author GobsC - * - * This class makes some standard image icons available to the application. - */ -public class StandardImageIcons -{ - - public static final String UP_ARROW = "UpArrow"; - public static final String DOWN_ARROW = "DownArrow"; - - public static final String RIGHT_ARROW = "RightArrow"; - public static final String LEFT_ARROW = "LeftArrow"; - - public static final String DOUBLE_RIGHT_ARROW = "DoubleRightArrow"; - public static final String DOUBLE_LEFT_ARROW = "DoubleLeftArrow"; - - public static final String CIRCLE = "Circle"; - - private static Map _imageMap = new HashMap(); - - - private static int _verticalSpacing = 3; - private static int _horizontalSpacing = 3; - - - //---------------------------------------------------------- - - //---------------------------------------------------------- - - - public static ImageIcon getImageIcon(String imageName, Color foreground, Color background, - Dimension dimension) - { - - String key = imageName + "|" + - foreground.toString() + "|" + - background.toString() + "|" + - dimension.getWidth() + "|" + dimension.getHeight(); - - BufferedImage image = (BufferedImage)_imageMap.get(key); - Image scaledImage = null; - - if (image == null) - { - image = initBufferedImage(imageName, foreground, background, dimension); - - scaledImage = image.getScaledInstance(dimension.width, dimension.height, Image.SCALE_FAST); - - _imageMap.put(imageName, image); - } - - ImageIcon imageIcon = new ImageIcon(scaledImage); - - return imageIcon; - } - - //---------------------------------------------------------- - - - private static BufferedImage initBufferedImage(String imageName, - Color foregroundColor, - Color backgroundColor, - Dimension dimension) - { - BufferedImage image = null; - String header = "BufferedCanvas.initBufferedImage()"; - - //TYPE_INT_ARGB allows for transparent background - image = new BufferedImage(dimension.width, - dimension.height, - BufferedImage.TYPE_INT_ARGB); - - Graphics2D graphics = (Graphics2D) image.createGraphics(); - - //make the icon background transparent - for (int col = 0; col < dimension.width; col++) { - for (int row = 0; row < dimension.height; row++) { - image.setRGB(col, row, 0x0); - } - } - - //make the icons smoother looking - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - //old way required a backgroundColor, the new transparent background - // way does not. - // fillBackground(graphics, backgroundColor, dimension); - - if (imageName.equals(UP_ARROW)) - { - drawUpArrow(graphics, foregroundColor, dimension); - - } - else if (imageName.equals(DOWN_ARROW)) - { - drawDownArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(LEFT_ARROW)) - { - drawLeftArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(RIGHT_ARROW)) - { - drawRightArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(DOUBLE_LEFT_ARROW)) - { - drawDoubleLeftArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(DOUBLE_RIGHT_ARROW)) - { - drawDoubleRightArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(CIRCLE)) - { - drawCircle(graphics, foregroundColor, dimension); - } - - - return image; - } - - //---------------------------------------------------------- - - private static void fillBackground(Graphics g, Color backgroundColor, - Dimension dimension) - { - g.setColor(backgroundColor); - g.fillRect(0, 0, dimension.width, dimension.height); - } - - //---------------------------------------------------------- - private static void drawCircle(Graphics g, Color foregroundColor, Dimension dimension) - { - - int middleX = dimension.width/2; - int middleY = dimension.height/2; - int x = 0; - int y = 0; - - g.setColor(foregroundColor); - - g.fillOval(x, y, dimension.width, dimension.height); - } - - //---------------------------------------------------------- - - private static void drawUpArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - - int[] xPoints = { middleX, left, right}; - int[] yPoints = { top, bottom, bottom}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - - - private static void drawDownArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - - int[] xPoints = { left, middleX, right}; - int[] yPoints = {top, bottom, top}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - -//---------------------------------------------------------- - - private static void drawLeftArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - - int[] xPoints = { left, right, right}; - int[] yPoints = { middleY, top, bottom}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - - - private static void drawRightArrow(Graphics g, - Color foregroundColor, - Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - int[] xPoints = { right, left, left}; - int[] yPoints = { middleY, top, bottom}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - private static void drawDoubleLeftArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width/2 - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - int[] xPoints = { left, right, right}; - int[] yPoints = { middleY, top, bottom}; - - int shiftAmount = right; - int[] shiftedXPoints = shiftPointsHorizontally(xPoints, shiftAmount); - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - g.fillPolygon(shiftedXPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - - private static void drawDoubleRightArrow(Graphics g, - Color foregroundColor, - Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width/2 - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - int[] xPoints = { right, left, left}; - int[] yPoints = { middleY, top, bottom}; - - int shiftAmount = right; - int[] shiftedXPoints = shiftPointsHorizontally(xPoints, shiftAmount); - - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - g.fillPolygon(shiftedXPoints, yPoints, 3); - - - return; - } - //---------------------------------------------------------- - private static int[] shiftPointsHorizontally(int[] origPointsArray, int shiftAmount) - { - int[] shiftedXPoints = new int[origPointsArray.length]; - for (int i = 0; i < origPointsArray.length; i++) - { - shiftedXPoints[i] = origPointsArray[i] + shiftAmount; - } - - return shiftedXPoints; - - } - - //---------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableColumnComparator.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableColumnComparator.java deleted file mode 100644 index abe719c40a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableColumnComparator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Created on Jun 24, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 24, 2004 - * - */ - -/** - * @author SoodG -*/ -package ohd.hseb.util.gui; - -import java.util.Comparator; - -public abstract class TableColumnComparator implements Comparator -{ - protected String _columnName = null; - protected boolean _ascOrder = true; -// ------------------------------------------------------------------------------- - public abstract int compare(Object arg0, Object arg1); -// ------------------------------------------------------------------------------- - public void initColumnInfo( String columnName, boolean ascOrder ) - { - _columnName = columnName; - _ascOrder = ascOrder; - } -// ------------------------------------------------------------------------------- - public int compareNumbers( double value1, double value2 ) - { - int returnValue = 0; - - if ( value1 < value2 ) - { - returnValue = -1; - } - else if ( value1 == value2 ) - { - returnValue = 0; - } - else // value1 > value2 - { - returnValue = 1; - } - - return returnValue; - } -// ------------------------------------------------------------------------------- - public int compareStrings( String string1, String string2 ) - { - int returnValue = 0; - - returnValue = string1.compareTo(string2); - - return returnValue; - } - - //------------------------------------------------------------------------------- -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableHelper.java deleted file mode 100644 index 12397a798b..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableHelper.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Created on Feb 24, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Feb 24, 2004 - * - */ -package ohd.hseb.util.gui; - -import java.util.LinkedList; - -public class TableHelper -{ - private String[] _dbColumnNameArray = null; - private LinkedList _sortColumnOrderList = new LinkedList(); - private boolean[] _sortOrderArray = null; - private int _columnCount = 0; - - - public TableHelper( String[] dbColumnNameArray ) - { - _dbColumnNameArray = dbColumnNameArray; - _columnCount = _dbColumnNameArray.length; - _sortOrderArray = new boolean[ _columnCount ]; - initialize(); - } - - private void initialize() - { - initLinkedListAndOrderArray(); - } - - public String getOrderByClause() - { - StringBuffer clauseBuffer = new StringBuffer(); - - clauseBuffer.append( " ORDER BY" ); - - for( int i = 0; i < _columnCount; i++ ) - { - String orderString = null; - - int column = Integer.parseInt( _sortColumnOrderList.get( i ).toString() ); - - if ( _sortOrderArray[ column ] == true ) - { - orderString = " asc"; - } - else - { - orderString = " desc"; - } - clauseBuffer.append( " " + _dbColumnNameArray[ column ] + orderString + "," ); - } - clauseBuffer.replace( clauseBuffer.length() - 1, clauseBuffer.length(), " " ); /* Replaces the last comma - with a space */ - return clauseBuffer.toString(); - } - - public void setOrderByClause( int column ) - { - // If true, sets it false and vice versa - setColumnOrderList( column ); -// System.out.println( _sortColumnOrderList ); - _sortOrderArray[ column ] = !( _sortOrderArray[ column ] ); - } - - private void setColumnOrderList( int column ) - { - int index = -1; - - for( int i = 0; i < _sortColumnOrderList.size(); i++ ) - { - Integer valueInteger = (Integer) _sortColumnOrderList.get( i ); - int value = valueInteger.intValue(); - if ( column == value ) - { - index = i; - } - } - if ( index != -1 ) - { - Object columnValueObject = _sortColumnOrderList.remove( index ); - _sortColumnOrderList.addFirst( columnValueObject ); - } - } - - private void initLinkedListAndOrderArray() - { - for ( int i = 0; i < _columnCount; i++ ) - { - _sortOrderArray[ i ] = false; - _sortColumnOrderList.add( i, new Integer( i ) ); - } - } - - public static void main( String args[] ) - { - String[] columnNames = { "Basin ID", "PE", "DUR", "TS", "Extremum", "Adjustment" }; - TableHelper tbhelper = new TableHelper( columnNames ); - System.out.println( tbhelper.getOrderByClause() ); - tbhelper.setOrderByClause( 4 ); - System.out.println( tbhelper.getOrderByClause() ); - tbhelper.setOrderByClause( 2 ); - System.out.println( tbhelper.getOrderByClause() ); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableHelper2.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableHelper2.java deleted file mode 100644 index da8e32255d..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TableHelper2.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Created on June 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : June 14, 2004 - * - */ -package ohd.hseb.util.gui; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - - -public class TableHelper2 -{ - private String[] _columnNameArray = null; - private LinkedList _sortColumnOrderList = new LinkedList(); - private boolean[] _sortOrderArray = null; - private int _columnCount = 0; - private TableColumnComparator _listComparator = null; - private int _lastSortedColumn = 0; - - - public TableHelper2( TableColumnComparator listComparator, String[] columnNameArray ) - { - _columnNameArray = columnNameArray; - _columnCount = _columnNameArray.length; - _sortOrderArray = new boolean[ _columnCount ]; - _listComparator = listComparator; - initialize(); - } - - private void initialize() - { - initLinkedListAndOrderArray(); - } - - public void sortList( List listToSort, int column, boolean flipOrder ) - { - String columnName = _columnNameArray[ column ]; - boolean sortAscOrder = _sortOrderArray[ column ]; - - _listComparator.initColumnInfo( columnName, sortAscOrder ); - Collections.sort( listToSort, _listComparator ); - - if (flipOrder) - { - _sortOrderArray[ column ] = ! _sortOrderArray[ column ]; - } - - _lastSortedColumn = column; - } - - - public void sortWithoutMemory( List listToSort, int column, boolean isAscendingOrder ) - { - String columnName = _columnNameArray[ column ]; - boolean sortAscOrder = isAscendingOrder; - - _listComparator.initColumnInfo( columnName, sortAscOrder ); - Collections.sort( listToSort, _listComparator ); - } - - /* - public void resortList( List listToSort, int column ) - { - _sortOrderArray[ column ] = true; - sortList( listToSort, column ); - sortList( listToSort, column ); - } - */ - - public void resortList( List listToSort) - { - sortList( listToSort, _lastSortedColumn, false); - } - - private void initLinkedListAndOrderArray() - { - for ( int i = 0; i < _columnCount; i++ ) - { - _sortOrderArray[ i ] = false; - _sortColumnOrderList.add( i, new Integer( i ) ); - } - } - - public static void main( String args[] ) - { - String[] columnNames = { "Basin ID", "PE", "DUR", "TS", "Extremum", "Adjustment" }; -// TableHelper2 tbhelper = new TableHelper2( columnNames ); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TimePanel.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TimePanel.java deleted file mode 100644 index 09c10b2a83..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/TimePanel.java +++ /dev/null @@ -1,554 +0,0 @@ -/* - * Created on Oct 28, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 28, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.util.Date; - -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import ohd.hseb.db.DbTimeHelper; - - -public class TimePanel extends JPanel -{ - private DatePanel _datePanel = null; - - private int _hours = 0; - private int _minutes = 0; - private int _seconds = 0; - private long _dateTimeLong = 0; - - private JButton _upHourButton = new JButton(); - private JButton _upMinuteButton = new JButton(); - private JButton _upSecondButton = new JButton(); - - private JButton _downHourButton = new JButton(); - private JButton _downMinuteButton = new JButton(); - private JButton _downSecondButton = new JButton(); - - private JTextField _hoursTextField = new JTextField( 3 ); - private JTextField _minutesTextField = new JTextField( 3 ); - private JTextField _secondsTextField = new JTextField( 3 ); - - private boolean _allowOnlyEvenHours = false; - - public TimePanel() - /******************** - Purpose: Empty Constructor - *********************/ - { - this( 0 ); - } - - public TimePanel( long dateTimeLong ) - /******************** - Purpose: Constructor with a date/time long value - *********************/ - { - int hours = 0, - minutes = 0, - seconds = 0; - - String time = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeLong ); - - hours = Integer.parseInt( time.substring( 11, 13 ) ); - minutes = Integer.parseInt( time.substring( 14, 16 ) ); - seconds = Integer.parseInt( time.substring( 17, 19 ) ); - - initTime( hours, minutes, seconds ); - - initialize(); - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - - if (_allowOnlyEvenHours) - { - setEnableMinutesAndSeconds(false); - } - } - - private void setEnableMinutesAndSeconds(boolean enable) - { - - _minutesTextField.setEditable(enable); - _secondsTextField.setEditable(enable); - - _upMinuteButton.setEnabled(enable); - _downMinuteButton.setEnabled(enable); - - _upSecondButton.setEnabled(enable); - _downSecondButton.setEnabled(enable); - - return; - } - - - private void initialize() - /******************** - Purpose: Initializes the layout and adds the listeners - *********************/ - { - this.setLayout( new GridBagLayout() ); - - initTimeDisplay(); - - addListeners(); - - setSize( 240, 150 ); - } - - private void initTimeDisplay() - /******************** - Purpose: Initializes the Panel - *********************/ - { - _upHourButton.setIcon( getUpIcon() ); - _upMinuteButton.setIcon( getUpIcon() ); - _upSecondButton.setIcon( getUpIcon() ); - _downHourButton.setIcon( getDownIcon() ); - _downMinuteButton.setIcon( getDownIcon() ); - _downSecondButton.setIcon( getDownIcon() ); - - _upHourButton.setBackground( Color.WHITE ); - _upMinuteButton.setBackground( Color.WHITE ); - _upSecondButton.setBackground( Color.WHITE ); - _downHourButton.setBackground( Color.WHITE ); - _downMinuteButton.setBackground( Color.WHITE ); - _downSecondButton.setBackground( Color.WHITE ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _upHourButton, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upMinuteButton, 10, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upSecondButton, 20, 0, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _hoursTextField, 0, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _minutesTextField, 10, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _secondsTextField, 20, 10, 5, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _downHourButton, 0, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downMinuteButton, 10, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downSecondButton, 20, 20, 1, 1, GridBagConstraints.BOTH ); - } - - - private void addListeners() - /******************** - Purpose: Adds the listeners to the buttons and text fields - *********************/ - { - // Listeners for the 6 buttons for the date - _upHourButton.addActionListener( new UpHourListener() ); - _upMinuteButton.addActionListener( new UpMinuteListener() ); - _upSecondButton.addActionListener( new UpSecondListener() ); - _downHourButton.addActionListener( new DownHourListener() ); - _downMinuteButton.addActionListener( new DownMinuteListener() ); - _downSecondButton.addActionListener( new DownSecondListener() ); - - // Listeners for the 3 date Text Fields - _hoursTextField.addFocusListener( new HoursTextFieldFocusListener() ); - _minutesTextField.addFocusListener( new MinutesTextFieldFocusListener() ); - _secondsTextField.addFocusListener( new SecondsTextFieldFocusListener() ); - _hoursTextField.addActionListener( new HoursTextFieldListener() ); - _minutesTextField.addActionListener( new MinutesTextFieldListener() ); - _secondsTextField.addActionListener( new SecondsTextFieldListener() ); - } - - private void updateHoursTextField() - { - int inputHours = -1; - - try - { - inputHours = Integer.parseInt( _hoursTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputHours >= 0 ) && ( inputHours <= 23 ) ) - { - _hours = inputHours; - } - - updateTime(); - } - - private void updateMinutesTextField() - { - int inputMinutes = -1; - - try - { - inputMinutes = Integer.parseInt( _minutesTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputMinutes >= 0 ) && ( inputMinutes < 60 ) ) - { - _minutes = inputMinutes; - } - - updateTime(); - } - - private void updateSecondsTextField() - { - int inputSeconds = -1; - - try - { - inputSeconds = Integer.parseInt( _secondsTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputSeconds >= 0 ) && ( inputSeconds < 60 ) ) - { - _seconds = inputSeconds; - } - - updateTime(); - } - - private class HoursTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateHoursTextField(); - } - } - - private class MinutesTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateMinutesTextField(); - } - } - - private class SecondsTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateSecondsTextField(); - } - } - private class HoursTextFieldListener implements ActionListener - /******************** - Purpose: Hours text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateHoursTextField(); - } - } - - private class MinutesTextFieldListener implements ActionListener - /******************** - Purpose: Minutes text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateMinutesTextField(); - } - } - - private class SecondsTextFieldListener implements ActionListener - /******************** - Purpose: Seconds text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateSecondsTextField(); - } - } - - private class UpHourListener implements ActionListener - /******************** - Purpose: Up hour button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _hours < 23 ) - { - _hours++; - } - else - { - _hours = 0; - } - - updateTime(); - } - } - - private class UpMinuteListener implements ActionListener - /******************** - Purpose: Up minute button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _minutes < 59 ) - { - _minutes++; - } - else - { - _minutes = 0; - } - - updateTime(); - } - } - - private class UpSecondListener implements ActionListener - /******************** - Purpose: Up second button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _seconds < 59 ) - { - _seconds++; - } - else - { - _seconds = 0; - } - - updateTime(); - } - } - - private class DownHourListener implements ActionListener - /******************** - Purpose: Down hour button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _hours > 0 ) - { - _hours--; - } - else - { - _hours = 23; - } - updateTime(); - } - } - - private class DownMinuteListener implements ActionListener - /******************** - Purpose: Down minute button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _minutes > 0 ) - { - _minutes--; - } - else - { - _minutes = 59; - } - updateTime(); - - } - } - - private class DownSecondListener implements ActionListener - /******************** - Purpose: Down second button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _seconds > 0 ) - { - _seconds--; - } - else - { - _seconds = 59; - } - updateTime(); - } - } - - - private Icon getUpIcon() - /******************** - Purpose: Returns the up Icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.UP_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - private Icon getDownIcon() - /******************** - Purpose: Returns the down Icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.DOWN_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - - private void updateTime() - /******************** - Purpose: Updates the time/Panel - *********************/ - { - initTime( _hours, _minutes, _seconds ); - if ( _datePanel != null ) - { - setTime( _dateTimeLong ); - } - } - - public long getDateTimeLong() - /******************** - Purpose: Return a long value for the date/time - *********************/ - { - long dateTimeLong = 0; - long dateLong = 0; - StringBuffer dateTimeBuffer = new StringBuffer(); - String dateTimeString = null; - - dateLong = _datePanel.getDateLong(); - - dateTimeBuffer.append( DbTimeHelper.getDateStringFromLongTime( dateLong ) + " " ); - dateTimeBuffer.append( _hours + ":" + _minutes + ":" + _seconds ); - dateTimeString = dateTimeBuffer.toString(); - dateTimeLong = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - - return dateTimeLong; - } - - public String getTimeString() - { - return _hours + ":" + _minutes + ":" + _seconds; - } - - - public DatePanel getDatePanel() - /******************** - Purpose: Returns the datePanel object - *********************/ - { - return _datePanel; - } - - public void linkDateTime( DatePanel datePanel ) - /******************** - Purpose: links the date/time objects - *********************/ - { - _datePanel = datePanel; - if ( _datePanel.getTimePanel() != this ) - { - _datePanel.linkDateTime( this ); - } - } - - public void setTime( long dateTimeLong, boolean recurse ) - /******************** - Purpose: - *********************/ - { - int hours = 0, - minutes = 0, - seconds = 0; - - String time = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeLong ); - - hours = Integer.parseInt( time.substring( 11, 13 ) ); - minutes = Integer.parseInt( time.substring( 14, 16 ) ); - seconds = Integer.parseInt( time.substring( 17, 19 ) ); - - initTime( hours, minutes, seconds ); - - if ( ( _datePanel != null ) && ( recurse ) ) - { - _datePanel.setDate( dateTimeLong, false ); - } - } - - public void setTime( long dateTimeLong ) - /******************** - Purpose: - *********************/ - { - setTime( dateTimeLong, true ); - } - - private void initTime( int hours, int minutes, int seconds ) - /******************** - Purpose: Initializes the time values/Textfields - *********************/ - { - String dateTimeString = null; - - _hoursTextField.setText( "" + hours ); - _minutesTextField.setText( "" + minutes ); - _secondsTextField.setText( "" + seconds ); - _hours = hours; - _minutes = minutes; - _seconds = seconds; - - if ( _datePanel != null ) - { - dateTimeString = _datePanel.getDateString(); - - dateTimeString += " " + _hours + ":" + _minutes + ":" + _seconds; - - _dateTimeLong = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - } - -// setTime( _dateTimeLong ); - } - - public static void main(String[] args) - { - Date date = new Date(); - TimePanel TimePanel = new TimePanel( date.getTime() ); - } -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/WindowResizingManager.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/WindowResizingManager.java deleted file mode 100644 index 3ba0cb4329..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/WindowResizingManager.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Created on Apr 28, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.awt.Dimension; -import java.awt.Window; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; - -/** - * @author GobsC - * - * This class manages the permissable max and min sizes of a window - */ -public class WindowResizingManager extends ComponentAdapter -{ - private Dimension _minDimension = null; - private Dimension _maxDimension = null; - - private Window _window = null; - - public WindowResizingManager(Window managedComponent, - Dimension minDimension, - Dimension maxDimension) - { - - _window = managedComponent; - - _minDimension = minDimension; - _maxDimension = maxDimension; - - - _window.addComponentListener(this); - - } - - public void componentResized( ComponentEvent e ) - { - - int height = _window.getHeight(); - int width = _window.getWidth(); - //System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - int minWidth = _minDimension.width; - int maxWidth = _maxDimension.width; - int minHeight = _minDimension.height; - int maxHeight = _maxDimension.height; - - if ( width < minWidth ) - { - _window.setSize( new Dimension( minWidth, height ) ); - } - if ( width > maxWidth ) - { - _window.setSize( new Dimension( maxWidth, height ) ); - } - if ( height < minHeight ) - { - _window.setSize( new Dimension( width, minHeight ) ); - } - if ( height > maxHeight ) - { - _window.setSize( new Dimension( width, maxHeight) ); - } - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/BufferedCanvas.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/BufferedCanvas.java deleted file mode 100644 index f4b63b4ff5..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/BufferedCanvas.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Created on Jul 28, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.image.BufferedImage; - -import javax.swing.JPanel; -/** - * @author Chip Gobs - * - * This class acts as the abstract base class for the family of pre-defined - * custom "Canvas" classes. - */ -//public abstract class BufferedCanvas extends java.awt.Canvas -public abstract class BufferedCanvas extends JPanel -{ - private BufferedImage _bufferedImage = null; - private Graphics _bufferedImageGraphics = null; - - private boolean _needsToRedraw = true; - - //--------------------------------------------------------------------- - - public BufferedCanvas() - { - - } - - public BufferedCanvas(int x, int y, int width, int height) - { - Rectangle boundsRectangle = new Rectangle(x, y, width, height); - this.setBounds(boundsRectangle); - } - - // --------------------------------------------------------------------- - - public void setNeedsToRedraw(boolean needsToRedraw) - { - _needsToRedraw = needsToRedraw; - } - - // --------------------------------------------------------------------- - - public void paint(Graphics g) - { - //System.out.println("BufferedCanvas.paint()"); - //make sure that the bufferedImage - //is the same size as the Canvas - - if ( _bufferedImage == null)// don't have a _bufferedImage - { - - // System.out.println("BufferedCanvas.paint() _bufferedImage is null"); - initBufferedImage(); - _needsToRedraw = true; - } - - else if (!sizeSame(_bufferedImage, this) ) - { - //System.out.println("BufferedCanvas.paint() size not same"); - - resizeByVisibleArea(); - - initBufferedImage(); - _needsToRedraw = true; - } - - - // if the image needs to be redrawn to the imageBuffer, - // do it - if (_needsToRedraw) - { - _needsToRedraw = false; - - //System.out.println("BufferedCanvas.paint() size not same"); - - draw(getBufferedImageGraphics()); - } - - copyBufferedImage(g); - } //end paint() -//--------------------------------------------------------- - public void resizeByVisibleArea() - { - int width = this.getVisibleRect().width; - int height = this.getVisibleRect().height; - - this.setSize(width, height); - } -// --------------------------------------------------------- - - public void update(Graphics g) - { - paint(g); - } -//--------------------------------------------------------- - // This method must be overloaded by the subclass - public abstract void draw(Graphics g); - - public void repaint() - { - //System.out.println("BufferedCanvas.repaint()"); - setNeedsToRedraw(true); - super.repaint(); - } -//--------------------------------------------------------- - private void copyBufferedImage(Graphics canvasGraphics) - { - // Toolkit toolkit = Toolkit.getDefaultToolkit(); - - //System.out.println("BufferedCanvas.copyBufferedImage()"); - - - canvasGraphics.drawImage(_bufferedImage, 0, 0, this); - - return; - } //copyBufferedImage -//----------------------------------------------------------------- - private boolean sizeSame(BufferedImage bufferedImage, - BufferedCanvas canvas) - { - boolean result = false; - if ((bufferedImage.getWidth() == canvas.getWidth()) && - ( bufferedImage.getHeight() == canvas.getHeight()) - ) - { - result = true; - } - - return result; - } //end sizeSame -//----------------------------------------------------------------- - public BufferedImage getBufferedImage() - { - return _bufferedImage; - } - -//----------------------------------------------------------------- - protected Graphics getBufferedImageGraphics() - { - if (_bufferedImageGraphics == null) - { - if (_bufferedImage == null) - { - initBufferedImage(); - } - _bufferedImageGraphics = _bufferedImage.createGraphics(); - } - - return _bufferedImageGraphics; - } - -//----------------------------------------------------------------- - -private void initBufferedImage() -{ - - // String header = "BufferedCanvas.initBufferedImage()"; - // Rectangle visibleRectangle = getVisibleRect(); - int width = this.getWidth(); - int height = this.getHeight(); - - - // System.out.println(header + "width = " + width + " height = " + height); - - _bufferedImage = new BufferedImage(width, - height, - BufferedImage.TYPE_INT_RGB); - - _bufferedImageGraphics = _bufferedImage.createGraphics(); -} - -/* - public boolean imageUpdate(Image img, - int infoflags, - int x, - int y, - int w, - int h) - { - System.out.println("BufferedCanvas.imageUpdate(): infoflangs = " + infoflags ); - boolean result = true; - if ( (infoflags & ImageObserver.ALLBITS) == ImageObserver.ALLBITS) - { - result = false; - } - - return result; - } //imageUpdate() -*/ - -} //end BufferedCanvas diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/CanvasHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/CanvasHelper.java deleted file mode 100644 index 0fbe170cc2..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/CanvasHelper.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Created on Sep 26, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - - -import java.awt.BasicStroke; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -/** - * @author GobsC - * - * - */ -public class CanvasHelper -{ - - public static Stroke createDashedStroke() - { - float[] fArray = {4.0f, 4.0f}; - return new BasicStroke(1.0f, BasicStroke.CAP_ROUND, - BasicStroke.JOIN_ROUND, 5.0f, fArray, 0.0f); - } - -// -------------------------------------------------------------------------- - public static void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2) - { - Graphics2D g2 = (Graphics2D) g; - Stroke origStroke = g2.getStroke(); - Stroke stroke = createDashedStroke(); - - g2.setStroke(stroke); - g2.drawLine(x1, y1, x2, y2); - g2.setStroke(origStroke); - - return; - } //end drawDashedLine - -// -------------------------------------------------------------------------- - - public static String getDateString(long timeInMillis) - { - SimpleDateFormat sdf = new SimpleDateFormat("MM/dd"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(timeInMillis)); - - return timeString; - } -// -------------------------------------------------------------------------- - - public static String getHourString(long timeInMillis) - { - SimpleDateFormat sdf = new SimpleDateFormat("HH"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(timeInMillis)); - - return timeString; - } -// -------------------------------------------------------------------------- - public static String getDateTimeStringFromLongTime(long time) - { - String timeString = null; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(new java.util.Date(time)); - - return timeString; - } - -// -------------------------------------------------------------------------- - -} //end CanvasHelper diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/CanvasPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/CanvasPainter.java deleted file mode 100644 index a9f667ef29..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/CanvasPainter.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - - -import java.awt.Graphics; - -/** - * @author GobsC - * - * This interface is used in conjunction with the - * PaintableCanvas class. - * - * Implementations of this interface will paint to the - * canvas of the PaintableCanvas. - */ -public interface CanvasPainter -{ - public void paint(Graphics g); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataCurvePainter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataCurvePainter.java deleted file mode 100644 index 2f68574fc5..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataCurvePainter.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Created on Jul 12, 2004 - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasurementPointSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; - - -/** - * @author GobsC - * - */ - -public class DataCurvePainter implements DataPointCanvasPainter -{ - - private MeasurementPointSeries _measurementPointSeries = null; - private DataPointCanvas _canvas = null; - private boolean _shouldPaint = true; - private Color _curveColor = null; -// ---------------------------------------------------------------------------------------- - - public DataCurvePainter (MeasurementPointSeries series, - DataPointCanvas canvas, - Color curveColor) - { - _measurementPointSeries = series; - - _canvas = canvas; - - _curveColor = curveColor; - } - - -// ---------------------------------------------------------------------------------------- - - public Measurement getMaxYMeasurement() - { - return _measurementPointSeries.getMaxYMeasurement(); - - } - -// ---------------------------------------------------------------------------------------- - - public Measurement getMinYMeasurement() - { - return _measurementPointSeries.getMinYMeasurement(); - - } - -// ---------------------------------------------------------------------------------------- - public Measurement getMaxXMeasurement() - { - return _measurementPointSeries.getMaxXMeasurement(); - } - -// ---------------------------------------------------------------------------------------- - - public Measurement getMinXMeasurement() - { - return _measurementPointSeries.getMinXMeasurement(); - } - -// ---------------------------------------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// ---------------------------------------------------------------------------------------- - public void paint(Graphics g) - { - - if (_shouldPaint) - { - drawDataPoints(g); - } - - } //end paint() - -// -------------------------------------------------------------------------- - private void drawDataPoints(Graphics g) - { - int count = _measurementPointSeries.size(); - - g.setColor(_curveColor); - - MeasuringUnit yUnit = _canvas.getDisplayedYMeasuringUnit(); - MeasuringUnit xUnit = _canvas.getDisplayedXMeasuringUnit(); - - Measurement xMeasurement = null; - Measurement yMeasurement = null; - - DataPoint oldDataPoint = null; - - for (int i = 0; i < count; i++) - { - MeasurementPoint point = _measurementPointSeries.getPoint(i); - - yMeasurement = point.getYMeasurement(); - double discharge = yMeasurement.getValue(yUnit); - - xMeasurement = point.getXMeasurement(); - double hour = xMeasurement.getValue(xUnit); - - DataPoint dp = new DataPoint(hour, discharge); - - drawDataPoint(dp, g); - - if (oldDataPoint != null) - { - drawSegment(oldDataPoint, dp, g); - } - - oldDataPoint = dp; - } - } -// -------------------------------------------------------------------------- - - private void drawSegment(DataPoint dp1, DataPoint dp2, Graphics g) - { - Viewport viewport = getViewport(); - -// if it is viewable, then draw it - if ( (getViewport().isViewable(dp1)) && (getViewport().isViewable(dp2)) ) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - else - { - //System.out.println("StagePainter.drawSegment(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } - -// -------------------------------------------------------------------------- - - private void drawDataPoint(DataPoint dp, Graphics g) - { - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } -// ---------------------------------------------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// ---------------------------------------------------------------------------------------- - - public void setMeasurementPointSeries(MeasurementPointSeries measurementPointSeries) - { - _measurementPointSeries = measurementPointSeries; - } -// ---------------------------------------------------------------------------------------- - - public MeasurementPointSeries getMeasurementPointSeries() - { - return _measurementPointSeries; - } -// ---------------------------------------------------------------------------------------- - -} //end class DataCurvePainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvas.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvas.java deleted file mode 100644 index 64909c20b4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvas.java +++ /dev/null @@ -1,444 +0,0 @@ -/* - * Created on Jul 12, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Graphics; -import java.awt.Point; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.MaxMinData; - - -/** - * @author GobsC - * - * This class is at the same hierarchical level as TsPaintableCanvas, - * but is more flexible with what kind of data is on the X axis. - * - * Unlike the TsPaintableCanvas, it assumes that all the X axis will be - * painted. - */ -public class DataPointCanvas extends PaintableCanvas -{ - - private String _className = "DataPointCanvas"; - - private MeasuringUnit _displayedYMeasuringUnit = null; - private MeasuringUnit _displayedXMeasuringUnit = null; - - private Viewport _viewport = null; - private ScalingHelper _horizontalScalingHelper = null; - private ScalingHelper _verticalScalingHelper = null; - - - private List _dataPointCanvasPainterList = new ArrayList(); - - private int _leftMargin = 50; - private int _rightMargin = 50; - private int _topMargin = 40; - private int _bottomMargin = 50; - - - private String _title = null; - - -// ---constructor------------------------------------------------ - - public DataPointCanvas(MeasuringUnit displayedXMeasuringUnit, - MeasuringUnit displayedYMeasuringUnit, - int x, int y, - int width, int height, - ScalingHelper horizontalScalingHelper, - ScalingHelper verticalScalingHelper ) - { - super(x, y, width, height); - - _displayedXMeasuringUnit = displayedXMeasuringUnit; - _displayedYMeasuringUnit = displayedYMeasuringUnit; - - _horizontalScalingHelper = horizontalScalingHelper; - _verticalScalingHelper = verticalScalingHelper; - - addListeners(); - - setVisible(true); - - - repaint(); - - } //DataPointCanvas - -// -------------------------------------------------------- - - - public void addDataPointCanvasPainter(DataPointCanvasPainter painter) - { - _dataPointCanvasPainterList.add(painter); - - addCanvasPainter(painter); - - return; - } - - public void removeAllDataPointCanvasPainters() - { - _dataPointCanvasPainterList.clear(); - return; - } - -// -------------------------------------------------------- - - public void setTitle(String graphTitleText) - { - _title = graphTitleText; - return; - } - -// -------------------------------------------------------- - - public int getLeftMargin() - { - return _leftMargin; - } - -// -------------------------------------------------------- - public int getRightMargin() - { - return _rightMargin; - } -// -------------------------------------------------------- - public int getTopMargin() - { - return _topMargin; - } -// -------------------------------------------------------- - - public int getBottomMargin() - { - return _bottomMargin; - } -// ----------------------------------------------------------------- - - public String getTitle() - { - return _title; - } - -// -------------------------------------------------------- - - public void draw(Graphics g) - { - //System.out.println("TsPaintableCanvas.draw()"); - - //drawBackground(g); - - //draw the stuff from all the custom painters - super.draw(g); - } - -// -------------------------------------------------------- - - public void setDisplayedMeasuringUnit(MeasuringUnit measuringUnit) - { - String header = "TsPaintableCanvas.setDisplayedMeasuringUnit()"; - - //System.out.println("displayed Measuring Unit is changing from " + - // _displayedMeasuringUnit + " to " + measuringUnit); - - _displayedYMeasuringUnit = measuringUnit; - - } -// -------------------------------------------------------- - - public MeasuringUnit getDisplayedYMeasuringUnit() - { - return _displayedYMeasuringUnit; - } - -// ------------------------------------------------------- - public MeasuringUnit getDisplayedXMeasuringUnit() - { - return _displayedXMeasuringUnit; - } - -// ------------------------------------------------------- - - public Viewport getViewport() - { - return _viewport; - } - - -// ------------------------------------------------------------------------ - - private void addListeners() - { - - //the resize listener - addComponentListener - ( - new ComponentAdapter() - { - public void componentResized(ComponentEvent event) - { - resize(); - } - } - ); - - - - } //end addListeners() - -// ------------------------------------------------------------------------------ - - - public void refresh() - { - adjustViewport(); - } -// ------------------------------------------------------------------------------ - - private MaxMinData getMaxAndMinCoordinateValues(boolean isXOrdinate) - { - String header = "DataPointCanvas.getMaxAndMinCoordinateValues(): "; - - Measurement minMeasurement = null; - Measurement maxMeasurement = null; - - - minMeasurement = getMinMeasurementForPainters(isXOrdinate); - maxMeasurement = getMaxMeasurementForPainters(isXOrdinate); - - - double minValue = 0.0; - double maxValue = 1.0; - - ScalingHelper scalingHelper = null; - - if (isXOrdinate) - { - scalingHelper = _horizontalScalingHelper; - } - else - { - scalingHelper = _verticalScalingHelper; - } - - - if (minMeasurement != null) - { - minValue = minMeasurement.getValue(); - } - else - { - minValue = 0.0; - } - - - if (maxMeasurement != null) - { - maxValue = maxMeasurement.getValue(); - } - - if (maxValue <= 0.0) - { - maxValue = 1.0; - } - - - scalingHelper.setMinDataValue(minValue); - scalingHelper.setMaxDataValue(maxValue); - - // System.out.println(header + "orig minValue = " + minValue + " orig maxValue = " + maxValue); - - minValue = scalingHelper.getMinScaleValue(); - maxValue = scalingHelper.getMaxScaleValue(); - -// System.out.println(header + "new minValue = " + minValue + " new maxValue = " + maxValue); - - MaxMinData maxMinData = new MaxMinData(maxValue, minValue); - - return maxMinData; - } - -// ------------------------------------------------------------------------------ - - private void adjustViewport() - { - //String header = "TsPaintableCanvas.adjustViewport(): "; - //System.out.println(header); - - int minUseableX = 0 + _leftMargin; - int minUseableY = 0 + _topMargin; - - int maxUseableX = getWidth() - _rightMargin; - int maxUseableY = getHeight() - _bottomMargin; - - Point minScreenPoint = new Point(minUseableX, minUseableY); - Point maxScreenPoint = new Point(maxUseableX, maxUseableY); - - // determine the max and min data values for the Y-axis - MaxMinData maxMinYValue = getMaxAndMinCoordinateValues(false); - - double minYValue = maxMinYValue.getMinValue(); - double maxYValue = maxMinYValue.getMaxValue(); - - - // determine the max and min data values for the X-axis - MaxMinData maxMinXValue = getMaxAndMinCoordinateValues(true); - - double minXValue = maxMinXValue.getMinValue(); - double maxXValue = maxMinXValue.getMaxValue(); - - - DataPoint minDataPoint = new DataPoint(minXValue, minYValue); - DataPoint maxDataPoint = new DataPoint(maxXValue, maxYValue); - - if (_viewport == null) - { - _viewport = new Viewport(minScreenPoint, maxScreenPoint, - minDataPoint, maxDataPoint); - _viewport.setFlipYOrientation(true); - } - - else //_viewport != null - { - _viewport.setMinScreenPoint(minScreenPoint); - _viewport.setMaxScreenPoint(maxScreenPoint); - _viewport.setMinDataPoint(minDataPoint); - _viewport.setMaxDataPoint(maxDataPoint); - - _viewport.setFlipYOrientation(true); - - } - - repaint(); - - } //end adjustViewport - -// end getMaxMeasurementForPainters() -// ----------------------------------------------------------------- - private Measurement getMinMeasurementForPainters(boolean isXOrdinate) - { - Measurement minMeasurement = null; - Measurement painterMinMeasurement = null; - MeasuringUnit unit = null; - - - if (isXOrdinate) - { - unit = getDisplayedXMeasuringUnit(); - } - else - { - unit = getDisplayedYMeasuringUnit(); - } - - // check each DataPointCanvasPainter for its min - for (int i = 0 ; _dataPointCanvasPainterList != null && i <_dataPointCanvasPainterList.size() ; i++) - { - - DataPointCanvasPainter painter = (DataPointCanvasPainter) _dataPointCanvasPainterList.get(i); - - - if (isXOrdinate) - { - painterMinMeasurement = painter.getMinXMeasurement(); - } - else - { - painterMinMeasurement = painter.getMinYMeasurement(); - } - - Measurement tempMin = Measurement.getConvertedCopy(painterMinMeasurement, unit) ; - - if (tempMin != null) - { - - if ( (minMeasurement == null) || - (tempMin.getValue() < minMeasurement.getValue()) - ) - { - minMeasurement = tempMin; - } - - } - - } //end for - - return minMeasurement; - } -// ----------------------------------------------------------------- - private Measurement getMaxMeasurementForPainters( boolean isXOrdinate) - { - Measurement maxMeasurement = null; - Measurement painterMaxMeasurement = null; - MeasuringUnit unit = null; - - if (isXOrdinate) - { - unit = getDisplayedXMeasuringUnit(); - } - else - { - unit = getDisplayedYMeasuringUnit(); - } - - // check each DataPointCanvasPainter for its max - for (int i = 0 ; _dataPointCanvasPainterList != null && i < _dataPointCanvasPainterList.size() ; i++) - { - DataPointCanvasPainter painter = (DataPointCanvasPainter) _dataPointCanvasPainterList.get(i); - - if (isXOrdinate) - { - painterMaxMeasurement = painter.getMaxXMeasurement(); - } - else - { - painterMaxMeasurement = painter.getMaxYMeasurement(); - } - - - Measurement tempMax = Measurement.getConvertedCopy( painterMaxMeasurement, unit); - - if (tempMax != null) - { - - if ( (maxMeasurement == null) || - (tempMax.getValue() > maxMeasurement.getValue()) - ) - { - maxMeasurement = tempMax; - } - - } - - } //end for - - return maxMeasurement; - - } // end getMaxMeasurementForPainters() -// ----------------------------------------------------------------- - - private void resize() - { - adjustViewport(); - } //end resize() - - - -// -------------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasAdapter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasAdapter.java deleted file mode 100644 index 76bf1c5407..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasAdapter.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Created on Jul 19, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -/** - * @author Chip Gobs - * This interface provides a facade for working with the DataPointCanvas and its - * other associated classes, such as Painters. It helps ensure that the implementation - * classes are providing all of the needed functionality. - */ -public interface DataPointCanvasAdapter -{ - public DataPointCanvas initCanvas(Object initializationObject); - public void refreshCanvas(Object dataObject); - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasBackgroundPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasBackgroundPainter.java deleted file mode 100644 index 1f65c6d0de..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasBackgroundPainter.java +++ /dev/null @@ -1,537 +0,0 @@ -/* - * Created on July 14, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.text.NumberFormat; - -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.FontHelper; - -/** - * @author Chip Gobs - * - * This class implements CanvasPainter and encapsulates the - * drawing of the X and Y axes and all the tick marks - */ -public class DataPointCanvasBackgroundPainter implements CanvasPainter -{ - private String _className = "DataPointCanvasBackgroundPainter"; - - private DataPointCanvas _canvas = null; - - - //number formatter - private NumberFormat _numberFormat = NumberFormat.getInstance(); - - // various colors - private static final Color _backgroundColor = Color.black; - - - // NOTE: future changes: - // will want to have multiple time series, so there needs - // to be a way to have different colors for timeseries - - private static final Color _gridColor = Color.GRAY; - private Color _outlineColor = Color.WHITE; - private static final Color _labelColor = Color.WHITE; - private static final Color _numberColor = Color.WHITE; - - - //unit labels - private String _xUnitLabelString = null; - private String _yUnitLabelString = null; - - -// fonts - private Font _titleFont = null; - private Font _labelFont = null; - private Font _numberFont = null; - - // margins and shifts - private final static int _titleYShift = - 20; - private int _leftUnitLabelShift = 10; - private final static int _constantYAxisNumberLabelSpacing = 0; - - private int _lowerNumberLabelShift = 15; - - //FontHelper - custom class - private FontHelper _labelFontHelper = null; - private FontHelper _titleFontHelper = null; - - private double _smallRoundingError = 0.000000001; - - - private boolean _showMinorVerticalTicks = true; - private boolean _showMinorVerticalLabels = true; - private boolean _showMinorHorizontalTicks = true; - - private ScalingHelper _verticalScalingHelper = null; - private ScalingHelper _horizontalScalingHelper = null; - // --------------------------------------------------------- - public DataPointCanvasBackgroundPainter(Color lineColor, - DataPointCanvas canvas, - String xUnitLabelString, - String yUnitLabelString, - ScalingHelper horizontalScalingHelper, - ScalingHelper verticalScalingHelper) - { - _outlineColor = lineColor; - _canvas = canvas; - - - _xUnitLabelString = xUnitLabelString; - _yUnitLabelString = yUnitLabelString; - - _numberFormat.setMaximumFractionDigits(2); - - _titleFont = new Font("TimesRoman",Font.BOLD,20); - _labelFont= new Font("TimesRoman",Font.BOLD,14); - _numberFont = new Font("Helvetica",Font.PLAIN,10); - - _labelFontHelper = new FontHelper(_labelFont); - _titleFontHelper = new FontHelper(_titleFont); - - _showMinorVerticalTicks = false; - _showMinorHorizontalTicks = false; - - _horizontalScalingHelper = horizontalScalingHelper; - _verticalScalingHelper = verticalScalingHelper; - - } //tsBackgroundPainter() - -// --------------------------------------------------------- - public void setShowMinorVerticalTicks(boolean showMinorVerticalTicks) - { - _showMinorVerticalTicks = showMinorVerticalTicks; - } -// --------------------------------------------------------- - public void setShowMinorHorizontalTicks(boolean showMinorHorizontalTicks) - { - _showMinorHorizontalTicks = showMinorHorizontalTicks; - } -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawBackground(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - public void drawBackground(Graphics g) - { - - Rectangle r = _canvas.getBounds(); - - //clear the image - g.setColor(_backgroundColor); - g.fillRect(0, 0, r.width, r.height); - - //draw the axis labels, ticks, and dotted lines - drawHorizontalLines( g ); - drawVerticalLines( g ); - - // draw the title of the graph - - drawTitle(g); - - int x = 0; - int y = 0; - - //draw x axis label - int labelWidth = _labelFontHelper.getWidth(g, _xUnitLabelString); - x = (int) ((r.width * .5) - (.5 * labelWidth)); - - int labelShift = (int) (-.4 * _canvas.getBottomMargin()); - - y = (r.height) + labelShift; - drawLabel(_xUnitLabelString, g, x, y); - - - //draw y axis label - x = _leftUnitLabelShift; - y = (r.height * 4/9); - int verticalSpacing = _labelFontHelper.getHeight(g); - drawVerticalLabel(_yUnitLabelString, g, x, y, verticalSpacing); - - - } - -//---------------------------------------------------- - private void drawTitle(Graphics g) - { - String titleString = _canvas.getTitle(); - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, titleString) / 2; - - int x = middleX - totalLeftShift; - int y = (_canvas.getTopMargin() + _titleYShift); - - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(titleString, x, y); - - return; - } //drawTitle - -// -------------------------------------------------------------------------- - private void drawLabel(String labelString, Graphics g, int x, int y) - { - g.setFont(_labelFont); - g.setColor(_labelColor); - g.drawString(labelString, x, y); - - return; - } //drawUnitLabel -// -------------------------------------------------------------------------- - private void drawVerticalLabel(String labelString, Graphics g, int x, int y, int verticalSpacing) - { - Graphics2D g2 = (Graphics2D) g; - - g2.setFont(_labelFont); - g2.setColor(_labelColor); - - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < labelString.length(); i++) - { - char c = labelString.charAt(i); - String newString = Character.toString(c); - g2.drawString(newString, x, y); - y += verticalSpacing; - } - - - return; - } //drawVerticalUnitLabel -// -------------------------------------------------------------------------------------------------- - private void drawXAxisNumberLabel(Graphics g, int x, int y, double value) - { - String header = _className + ".drawXAxisNumberLabel(): "; - String numberLabelString =_numberFormat.format(value); - - g.setColor(_numberColor); - g.setFont(_numberFont); - - int totalLeftShift = _labelFontHelper.getWidth(g, numberLabelString) / 2; - g.drawString(numberLabelString, x - totalLeftShift, y + _lowerNumberLabelShift); - - - } -// -------------------------------------------------------------------------------------------------- - private void drawYAxisNumberLabel(Graphics g, int x, int y, double value) - { - String header = _className + "drawYAxisNumberLabel(): "; - String numberLabelString =_numberFormat.format(value); - - g.setColor(_numberColor); - g.setFont(_numberFont); - - int totalYShift = _labelFontHelper.getHeight(g) / 4; - int stringWidth = _labelFontHelper.getWidth(g, numberLabelString); - int totalLeftShift = -(stringWidth + _constantYAxisNumberLabelSpacing); - // System.out.println(header + "_labelFontHelper says that stringWidth of = " + - // numberLabelString + " = " + stringWidth); - - int newX = x + totalLeftShift; - if (newX < 0) - { - newX = 0; - } - - int newY = y + totalYShift; - - g.drawString(numberLabelString, newX, newY); - - - } -// -------------------------------------------------------------------------- - - private void drawVerticalLines(Graphics g) - { - String header = _className + ".drawVerticalLines(): "; - //determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - // this is correct. To draw a series of vertical lines, I need to know - // how far left and right things are, so I need to scale horizontally. - ScalingHelper scalingHelper = _horizontalScalingHelper; - - scalingHelper.setMinDataValue(minXValue); - scalingHelper.setMaxDataValue(maxXValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minXValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_numberFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxXValue + _smallRoundingError); - - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minXValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(majorTickValue, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(majorTickValue, maxYValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not working due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - - //draw the lower tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+5, point1.x, point2.y); - - // draw the label - drawXAxisNumberLabel(g, point1.x, point1.y, majorTickValue); - - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorVerticalTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minorTickValue, minYValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(minorTickValue, maxYValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, - minorPoint1.x, minorPoint1.y, - minorPoint2.x, minorPoint2.y); - - // draw the label - if (_showMinorVerticalLabels) - { - drawXAxisNumberLabel(g, minorPoint1.x, minorPoint1.y, minorTickValue); - } - - } - } - - } //end if _showMinorTicks - - } //end for - - } //end drawYAxis -// -------------------------------------------------------------------------- - - /* - private boolean isOnATick(long timeValue, int hoursPerTick) - { - boolean result = false; - - if ((timeValue % hoursPerTick) == 0 ) - { - result = true; - } - return result; - } //end isOnATick - */ - -// ------------------------------------------------------------------------------------------- - - private void drawHorizontalLines(Graphics g) - { - //determine the min and max data values to chart - - String header = "DataBackgroundPainter.drawHorizontalLines(): "; - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - // ScalingHelper scalingHelper = new ScalingHelper(minYValue, maxYValue); - - // this is correct. To draw a series of horizontal lines, I need to know - // how far up and down things are, so I need to scale vertically - ScalingHelper scalingHelper = _verticalScalingHelper; - scalingHelper.setMinDataValue(minYValue); - scalingHelper.setMaxDataValue(maxYValue); - - //scalingHelper = new ScalingHelper(minYValue, maxYValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minYValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_numberFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxYValue + _smallRoundingError); - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minYValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(minXValue, majorTickValue)); - point2 = getViewport().getScreenPoint(new DataPoint(maxXValue, majorTickValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not work due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - //CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - - } - - - //draw the left side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x-5, point1.y, point1.x, point2.y); - - // draw the label - drawYAxisNumberLabel(g, point1.x, point1.y, majorTickValue); - - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorHorizontalTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minXValue, minorTickValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(maxXValue, minorTickValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, minorPoint1.x, - minorPoint1.y, - minorPoint2.x, - minorPoint2.y); - - } - } - - } //end if _showMinorTicks - - } - - } //end drawYAxis - - - public void setShowMinorVerticalLabels(boolean showMinorVerticalLabels) - { - _showMinorVerticalLabels = showMinorVerticalLabels; - } - - - public boolean showMinorVerticalLabels() - { - return _showMinorVerticalLabels; - } - -// ------------------------------------------------------------------------------ - - -} //end of DataPointCanvasBackgroundPainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasPainter.java deleted file mode 100644 index 6d484b47b6..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasPainter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Created on Jul 15, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import ohd.hseb.measurement.Measurement; - -/** - * @author GobsC - * - * - */ -public interface DataPointCanvasPainter extends CanvasPainter -{ - public Measurement getMaxXMeasurement(); - public Measurement getMinXMeasurement(); - - public Measurement getMaxYMeasurement(); - public Measurement getMinYMeasurement(); - - public void setShouldPaint(boolean shouldPaint); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/PaintableCanvas.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/PaintableCanvas.java deleted file mode 100644 index e78ab705d7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/PaintableCanvas.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Graphics; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Chip Gobs - * - * This class provides a BufferedCanvas and accepts - * multiple layers of painters, each of which knows how - * to draw on it. Each painter has access to this object's - * Viewport in order to make scaling decisions. - */ -public class PaintableCanvas extends BufferedCanvas -{ - - private List _canvasPainterList = new ArrayList(); - -// ------------------------------------------------------------------ - - public PaintableCanvas(int x, int y, int width, int height) - { - super(x, y, width, height); - - return; - } - -// ------------------------------------------------------------------ - - public void draw(Graphics g) - { - //System.out.println("PaintableCanvas.draw()"); - for (int i = 0 ; i < _canvasPainterList.size(); i++) - { - CanvasPainter painter = (CanvasPainter) _canvasPainterList.get(i); - painter.paint(g); - } - } -// ------------------------------------------------------------------ - public void addCanvasPainter(CanvasPainter painter) - { - _canvasPainterList.add(painter); - return; - } -// ------------------------------------------------------------------ - - public void addCanvasPainter(int index, CanvasPainter painter) - { - _canvasPainterList.add(index, painter); - - return; - } -// ------------------------------------------------------------------ - public void removeCanvasPainter(CanvasPainter painter) - { - _canvasPainterList.remove(painter); - return; - } -// -------------------------------------------------------------------- - - public CanvasPainter removeCanvasPainter(int index) - { - CanvasPainter painter = null; - - painter = (CanvasPainter)_canvasPainterList.remove(index); - - return painter; - } - - -// ------------------------------------------------------------------ - protected int getCanvasPainterCount() - { - return _canvasPainterList.size(); - } -// ------------------------------------------------------------------ - protected CanvasPainter getCanvasPainterByIndex(int index) - { - return (CanvasPainter) _canvasPainterList.get(index); - } - - -// ------------------------------------------------------------------ - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/ScalingHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/ScalingHelper.java deleted file mode 100644 index 7527ff02c4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/ScalingHelper.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Created on Apr 7, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -/** - * @author GobsC - * - * - */ -public class ScalingHelper -{ - - //includes the first and last ticks - // private final static int _minMajorTickCount = 4; - private final static int _maxMajorTickCount = 6; - - - private final static double _niceLowerNumberFactor = 5.0; - - private double[] _niceMajorIncrementArray = {1.0, 2.0, 5.0}; - private double[] _niceMinorIncrementArray = {.2, .5, 1}; - private double _baseFactorStartingPoint = .01; -// ------------------------------------------------------------------------- - private double _minDataValue; - private double _maxDataValue; - - private double _minScaleValue; - private double _maxScaleValue; - - private int _majorTickCount; - private int _minorTickCount; - - private double _majorTickIncrement; - private double _minorTickIncrement; - - - -// ------------------------------------------------------------------------- - - public ScalingHelper(double minDataValue, double maxDataValue) - { - _minDataValue = minDataValue; - _maxDataValue = maxDataValue; - - rescale(); - } - -// -------------------------------------------------------------------- - - public void setMaxDataValue(double maxDataValue) - { - _maxDataValue = maxDataValue; - - rescale(); - } - -// -------------------------------------------------------------------- - - public double getMaxDataValue() - { - return _maxDataValue; - - } - -// -------------------------------------------------------------------- - - public void setMinDataValue(double minDataValue) - { - _minDataValue = minDataValue; - rescale(); - } - -// -------------------------------------------------------------------- - - public double getMinDataValue() - { - return _minDataValue; - } - -// -------------------------------------------------------------------- - public int getMajorTickCount() - { - return _majorTickCount; - } - - public double getMajorTickIncrement() - { - return _majorTickIncrement; - } - -// -------------------------------------------------------------------- - - public double getMaxScaleValue() - { - return _maxScaleValue; - } - -// -------------------------------------------------------------------- - - - public int getMinorTickCount() - { - return _minorTickCount; - } - - // -------------------------------------------------------------------- - - public double getMinorTickIncrement() - { - return _minorTickIncrement; - } -// -------------------------------------------------------------------- - - public double getMinScaleValue() - { - return _minScaleValue; - } - -// -------------------------------------------------------------------- - - public void setNiceMajorIncrementArray(double[] niceMajorIncrementArray) - { - _niceMajorIncrementArray = niceMajorIncrementArray; - rescale(); - } - -// -------------------------------------------------------------------- - - public double[] getNiceMajorIncrementArray() - { - return _niceMajorIncrementArray; - } - -// -------------------------------------------------------------------- - - public void setNiceMinorIncrementArray(double[] niceMinorIncrementArray) - { - _niceMinorIncrementArray = niceMinorIncrementArray; - rescale(); - } - -// -------------------------------------------------------------------- - - public double[] getNiceMinorIncrementArray() - { - return _niceMinorIncrementArray; - } - -// -------------------------------------------------------------------- - private void rescale() - { - - - int multipleCount = (int) Math.floor(_minDataValue/ _niceLowerNumberFactor); - _minScaleValue = multipleCount * _niceLowerNumberFactor; - - - double baseFactor = _baseFactorStartingPoint; - - // find the right nice increment - - boolean done = false; - int i = 0; - - - double range = _maxDataValue - _minScaleValue; - - - //ensure that range is a sane value - - if (range < 1.0) - { - range = 1.0; - } - - - while (!done ) - { - double testIncrement = _niceMajorIncrementArray[i] * ( baseFactor); - - int testTickCount = (int) Math.ceil(range/testIncrement + 1); - - - //if there are a reasonable number of tickCounts, then stop - // if ((testTickCount >= _minMajorTickCount) && - // (testTickCount <= _maxMajorTickCount)) - if (testTickCount <= _maxMajorTickCount) - { - - _majorTickCount = testTickCount; - - _majorTickIncrement = testIncrement; - - _minorTickIncrement = _niceMinorIncrementArray[i] * baseFactor; - _minorTickCount = (int) (_niceMajorIncrementArray[i]/ _niceMinorIncrementArray[i]) - 1; - - //first tick counts as a tick, so subtract 1 - _maxScaleValue = _minScaleValue + ( (_majorTickCount-1) * _majorTickIncrement); - - done = true; - } - - i++; - - if ((i >= _niceMajorIncrementArray.length) || - (i >= _niceMinorIncrementArray.length)) - { - i = 0; - baseFactor *= 10.0; - } - - } //end while !done - - - - return; - } - -// -------------------------------------------------------------------- - public String toString() - { - String outString = " minDataValue = " + getMinDataValue() + - " maxDataValue = " + getMaxDataValue() + "\n" + - " minScaleValue = " + getMinScaleValue() + - " maxScaleValue = " + getMaxScaleValue() + "\n" + - " majorTickCount = " + getMajorTickCount() + - " minorTickCount = " + getMinorTickCount() + "\n" + - " majorTickIncrement = " + getMajorTickIncrement() + - " minorTickIncrement = " + getMinorTickIncrement(); - - return outString; - } - - -// -------------------------------------------------------------------- - public static void main(String[] argArray) - { - double minValue = 87.6; - double maxValue = 123.5; - ScalingHelper scaler = new ScalingHelper(minValue, maxValue); - - System.out.println(scaler.toString()); - - } - - /** - * @param baseFactorStartingPoint The baseFactorStartingPoint to set. - */ - public void setBaseFactorStartingPoint(double baseFactorStartingPoint) - { - _baseFactorStartingPoint = baseFactorStartingPoint; - } - - /** - * @return Returns the baseFactorStartingPoint. - */ - public double getBaseFactorStartingPoint() - { - return _baseFactorStartingPoint; - } - - -// -------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasEvent.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasEvent.java deleted file mode 100644 index 6a35860b81..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Created on Oct 7, 2003 - * - * This class is for events related to clicking on - * a TimeSeriesCanvas - */ - -package ohd.hseb.util.gui.drawing; - - -import ohd.hseb.measurement.AbsTimeMeasurement; - -/** - * @author Chip Gobs - * - * - */ -public class TsCanvasEvent -{ - - private AbsTimeMeasurement _measurement = null; - -// ----------------------------------------------------------------------- - public TsCanvasEvent(TsCanvasEvent event) - { - this(event._measurement); - - return; - } -// ----------------------------------------------------------------------- - - public TsCanvasEvent(AbsTimeMeasurement measurement) - { - _measurement = new AbsTimeMeasurement(measurement); - - return; - } - -//----------------------------------------------------------------------- - - public AbsTimeMeasurement getMeasurement() - { - return _measurement; - } -// ----------------------------------------------------------------------- - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasEventListener.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasEventListener.java deleted file mode 100644 index 6f1256c0b4..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasEventListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Created on Oct 7, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -/** - * @author GobsC - * - * - */ -public interface TsCanvasEventListener -{ - - public void handleTsCanvasEvent(TsCanvasEvent event); - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasPainter.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasPainter.java deleted file mode 100644 index b9df696cc8..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsCanvasPainter.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -//import ohd.hseb.util.gui.*; -import ohd.hseb.measurement.Measurement; - -/** - * @author GobsC - * - * This interface is an extension of CanvasPainter - * and specializes the CanvasPainter in that it deals with - * the maximum and minimum measurements, which - * usually come from TimeSeries - * - **/ -public interface TsCanvasPainter extends CanvasPainter -{ - - public Measurement getMaxMeasurement(); - public Measurement getMinMeasurement(); - public void setShouldPaint(boolean shouldPaint); - - -} //end of TsCanvasPainter diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsPaintableCanvas.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsPaintableCanvas.java deleted file mode 100644 index 8a21fe1b8b..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/TsPaintableCanvas.java +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Created on Oct 7, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Graphics; -import java.awt.Point; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; - -/** - * @author Chip Gobs - * - * - */ -public class TsPaintableCanvas extends PaintableCanvas -{ - - private MeasuringUnit _displayedMeasuringUnit = null; - private Viewport _viewport = null; - - - private List _tsCanvasPainterList = new ArrayList(); - private List _eventListeners = new ArrayList(); - - private int _intervalInHours = 1; - - private int _leftMargin = 50; - private int _rightMargin = 50; - private int _topMargin = 40; - private int _bottomMargin = 50; - - //time constant - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - - // the default viewing window for the timeSeries - //private long _defaultTimeWindowInHours = 72; - private long _defaultTimeWindowInHours = 72; - - private long _startTime = (System.currentTimeMillis()/MILLIS_PER_HOUR)*MILLIS_PER_HOUR; - private long _endTime = _startTime + - (_defaultTimeWindowInHours * MILLIS_PER_HOUR); - - - - private String _title = null; - - //testing only - private int _showCount = 0; - -//---constructor------------------------------------------------ - - public TsPaintableCanvas(MeasuringUnit displayedMeasuringUnit, - int x, int y, - int width, int height) - { - super(x, y, width, height); - - _displayedMeasuringUnit = displayedMeasuringUnit; - - addListeners(); - - setVisible(true); - - - repaint(); - - } //TsPaintableCanvas - -// -------------------------------------------------------- - public void addTsCanvasPainterAfter(TsCanvasPainter painterToAdd, TsCanvasPainter painterToAddAfter) - { - int index = -1; - - index = _tsCanvasPainterList.indexOf(painterToAddAfter); - - if (index != -1) - { - addTsCanvasPainter(painterToAdd, index + 1); - } - else - { - throw (new Error("Error: Attempted to add after a painter that does not exist")); - } - - return; - } -// -------------------------------------------------------- - - public void addTsCanvasPainter(TsCanvasPainter painter, int index) - { - // String header = "TsPaintableCanvas.addTsCanvasPainter(2 arg): "; - - _tsCanvasPainterList.add(index, painter); - addCanvasPainter(index, painter); - - // System.out.println(header + " _tsCanvasPainterList has " + _tsCanvasPainterList.size() + " elements."); - - return; - } - - public void addTsCanvasPainter(TsCanvasPainter painter) - { - // String header = "TsPaintableCanvas.addTsCanvasPainter(1 arg): "; - _tsCanvasPainterList.add(painter); - addCanvasPainter(painter); - - // System.out.println(header + " _tsCanvasPainterList has " + _tsCanvasPainterList.size() + " elements."); - - return; - } - -// -------------------------------------------------------- - public void removeTsCanvasPaintersBetweenExclusive(TsCanvasPainter firstPainter, TsCanvasPainter lastPainter) - { - // String header = "TsPaintableCanvas.removeTsCanvasPaintersBetweenExclusive() "; - boolean haveFoundFirst = false; - boolean done = false; - - List paintersToRemoveList = new ArrayList(); - - //determine which painters to remove - for (int i = 0; i < _tsCanvasPainterList.size(); i++) - { - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - // System.out.println(header + "at top of loop, painter = " + painter); - - - if (haveFoundFirst) - { - if (painter != lastPainter) - { - //System.out.println(header + "adding painter to the removal list."); - paintersToRemoveList.add(painter); - } - else //we are done - { - // System.out.println(header + "found last painter."); - done = true; - break; - } - } - else if (painter == firstPainter) //keep looking for the first painter - { - haveFoundFirst = true; - // System.out.println(header + "found first painter."); - } - } //end for - - // System.out.println(header + "removing " + paintersToRemoveList.size() + " painters."); - //actually remove the painters - for (TsCanvasPainter painter : paintersToRemoveList) - { - removeTsCanvasPainter(painter); - } - } - -// -------------------------------------------------------- - public void removeTsCanvasPaintersBetweenInclusive(TsCanvasPainter firstPainter, TsCanvasPainter lastPainter) - { - String header = "TsPaintableCanvas.removeTsCanvasPaintersBetweenInclusive() "; - boolean haveFoundFirst = false; - boolean done = false; - - List paintersToRemoveList = new ArrayList(); - - //determine which painters to remove - for (int i = 0; i < _tsCanvasPainterList.size(); i++) - { - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - // System.out.println(header + "at top of loop, painter = " + painter); - - - if (haveFoundFirst) - { - if (painter != lastPainter) - { - //System.out.println(header + "adding painter to the removal list."); - paintersToRemoveList.add(painter); - } - else //we are done - { - paintersToRemoveList.add(painter); - // System.out.println(header + "found last painter."); - done = true; - break; - } - } - else if (painter == firstPainter) //keep looking for the first painter - { - haveFoundFirst = true; - paintersToRemoveList.add(painter); - // System.out.println(header + "found first painter."); - } - } //end for - - System.out.println(header + "removing " + paintersToRemoveList.size() + " painters."); - //actually remove the painters - for (TsCanvasPainter painter : paintersToRemoveList) - { - removeTsCanvasPainter(painter); - } - } - -// -------------------------------------------------------- - - - - public void removeTsCanvasPainter(TsCanvasPainter painter) - { - _tsCanvasPainterList.remove(painter); - removeCanvasPainter(painter); - return; - } -// -------------------------------------------------------- - public void setTitle(String graphTitleText) - { - _title = graphTitleText; - return; - } - -// -------------------------------------------------------- - - public long getStartTime() - { - return _startTime; - } - -// -------------------------------------------------------- - public long getEndTime() - { - return _endTime; - } - -// -------------------------------------------------------- - - public int getLeftMargin() - { - return _leftMargin; - } - -// -------------------------------------------------------- - - public void setLeftMargin(int leftMargin) - { - _leftMargin = leftMargin; - adjustViewport(); - } - -// -------------------------------------------------------- - public int getRightMargin() - { - return _rightMargin; - } -// -------------------------------------------------------- - public void setRightMargin(int rightMargin) - { - _rightMargin = rightMargin; - adjustViewport(); - } -// -------------------------------------------------------- - public int getTopMargin() - { - return _topMargin; - } -// -------------------------------------------------------- - public void setTopMargin(int topMargin) - { - _topMargin = topMargin; - adjustViewport(); - } -// -------------------------------------------------------- - - public String getTitle() - { - return _title; - } - -// -------------------------------------------------------- - public void setTimeWindow(long startTime, long endTime) - { - _startTime = startTime; - _endTime = endTime; - - adjustViewport(); - - } - -// -------------------------------------------------------- - - - public void slideTimeWindow(int hoursToShift) - { - - long millisToShift = hoursToShift * MILLIS_PER_HOUR; - - setTimeWindow(_startTime + millisToShift, - _endTime + millisToShift); - } - -// -------------------------------------------------------- - - public void draw(Graphics g) - { - //System.out.println("TsPaintableCanvas.draw()"); - - //drawBackground(g); - - //draw the stuff from all the custom painters - super.draw(g); - - - } - -// -------------------------------------------------------- - - - -// -------------------------------------------------------- - - public void setDisplayedMeasuringUnit(MeasuringUnit measuringUnit) - { - String header = "TsPaintableCanvas.setDisplayedMeasuringUnit()"; - - //System.out.println("displayed Measuring Unit is changing from " + - // _displayedMeasuringUnit + " to " + measuringUnit); - - _displayedMeasuringUnit = measuringUnit; - - - } - -// -------------------------------------------------------- - - public MeasuringUnit getDisplayedMeasuringUnit() - { - return _displayedMeasuringUnit; - } - -// ------------------------------------------------------- - - public Viewport getViewport() - { - return _viewport; - } - -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------ - - private void addListeners() - { - - //the resize listener - addComponentListener - ( - new ComponentAdapter() - { - public void componentResized(ComponentEvent event) - { - resize(); - } - } - ); - - - } //end addListeners() - -// ------------------------------------------------------------------------------ - - public AbsTimeMeasurement getAbsTimeMeasurementByTruncation(Point point) - { - - DataPoint dataPoint = _viewport.getDataPoint(point); - MeasuringUnit unit = getDisplayedMeasuringUnit(); - - //System.out.println("TsPaintableCanvas.mouseListener() unit = " + unit); - - double clickedValue = dataPoint.getY(); - double value = MathHelper.roundToNDecimalPlaces(clickedValue, 2); - - - - long clickedTime = (long)dataPoint.getX(); - long time = TimeHelper.truncateTimeInMillisToNearestHour(clickedTime, - _intervalInHours); - - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, time, unit); - - return measurement; - } - -// ------------------------------------------------------------------------------ - - public AbsTimeMeasurement getAbsTimeMeasurementByRounding(Point point) - { - - DataPoint dataPoint = _viewport.getDataPoint(point); - MeasuringUnit unit = getDisplayedMeasuringUnit(); - - //System.out.println("TsPaintableCanvas.mouseListener() unit = " + unit); - - double clickedValue = dataPoint.getY(); - double value = MathHelper.roundToNDecimalPlaces(clickedValue, 2); - - - long clickedTime = (long)dataPoint.getX(); - long time = TimeHelper.roundTimeInMillisToNearestHour(clickedTime); - - - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, time, unit); - - return measurement; - } -// ------------------------------------------------------------------------------ - public void refresh() - { - // String header = "TsPaintableCanvas.refresh(): "; - - // System.out.println(header); - adjustViewport(); - } -// ------------------------------------------------------------------------------ - - private void adjustViewport() - { - //String header = "TsPaintableCanvas.adjustViewport(): "; - //System.out.println(header); - - int minUseableX = 0 + _leftMargin; - int minUseableY = 0 + _topMargin; - - int maxUseableX = getWidth() - _rightMargin; - int maxUseableY = getHeight() - _bottomMargin; - - Point minScreenPoint = new Point(minUseableX, minUseableY); - Point maxScreenPoint = new Point(maxUseableX, maxUseableY); - - long minTime = _startTime; - long maxTime = _endTime; - - Measurement minMeasurement = getMinMeasurementForPainters(); - Measurement maxMeasurement = getMaxMeasurementForPainters(); - - double minValue = 0.0; - double maxValue = 1.0; - - if (minMeasurement != null) - { - minValue = minMeasurement.getValue(); - } - else - { - minValue = 0.0; - } - - - if (maxMeasurement != null) - { - maxValue = maxMeasurement.getValue(); - } - - if (maxValue <= 0.0) - { - maxValue = 1.0; - } - - ScalingHelper scalingHelper = new ScalingHelper(minValue, maxValue); - - minValue = scalingHelper.getMinScaleValue(); - maxValue = scalingHelper.getMaxScaleValue(); - - //System.out.println(header + "minValue = " + minValue); - // System.out.println(header + "maxValue = " + maxValue); - - DataPoint minDataPoint = new DataPoint(minTime, minValue); - DataPoint maxDataPoint = new DataPoint(maxTime, maxValue); - - if (_viewport == null) - { - _viewport = new Viewport(minScreenPoint, - maxScreenPoint, - minDataPoint, - maxDataPoint); - _viewport.setFlipYOrientation(true); - } - - else //_viewport != null - { - _viewport.setMinScreenPoint(minScreenPoint); - _viewport.setMaxScreenPoint(maxScreenPoint); - _viewport.setMinDataPoint(minDataPoint); - _viewport.setMaxDataPoint(maxDataPoint); - - _viewport.setFlipYOrientation(true); - } - - - repaint(); - - } //end adjustViewport - -//----------------------------------------------------------------- - private Measurement getMinMeasurementForPainters() - { - Measurement minMeasurement = null; - - - // check each TsCanvasPainter for its max and min - for (int i = 0 ; _tsCanvasPainterList != null && i <_tsCanvasPainterList.size() ; i++) - { - - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - MeasuringUnit unit = getDisplayedMeasuringUnit(); - Measurement tempMin = Measurement.getConvertedCopy(painter.getMinMeasurement(), unit) ; - - if (tempMin != null) - { - - if ( (minMeasurement == null) || - (tempMin.getValue() < minMeasurement.getValue()) - ) - { - minMeasurement = tempMin; - } - - //System.out.println("TsPaintableCanvas.getMinMeasurement(): tempMin is NOT null"); - } - - } //end for - - //System.out.println("TsPaintableCanvas.getMinMeasurement(): minMeasurement = " + minMeasurement); - - - return minMeasurement; - } -// ----------------------------------------------------------------- - private Measurement getMaxMeasurementForPainters() - { - Measurement maxMeasurement = null; - - // check each TsCanvasPainter for its max and min - for (int i = 0 ; _tsCanvasPainterList != null && i < _tsCanvasPainterList.size() ; i++) - { - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - MeasuringUnit unit = getDisplayedMeasuringUnit(); - Measurement tempMax = Measurement.getConvertedCopy(painter.getMaxMeasurement(), unit); - - if (tempMax != null) - { - - if ( (maxMeasurement == null) || - (tempMax.getValue() > maxMeasurement.getValue()) - ) - { - maxMeasurement = tempMax; - } - - //System.out.println("TsPaintableCanvas.getMaxMeasurement(): tempMax is NOT null"); - } - - } //end for - - //System.out.println("TsPaintableCanvas.getMaxMeasurement(): maxMeasurement = " + maxMeasurement); - - return maxMeasurement; - } // end getMaxMeasurementForPainters() -//----------------------------------------------------------------- - - private void resize() - { - adjustViewport(); - } //end resize() -//-------------------------------------------------------------------------- - -} //end TsPaintableCanvas - - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/Viewport.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/Viewport.java deleted file mode 100644 index b0eac6e7c1..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/drawing/Viewport.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Created on Jul 16, 2003 - * - * Viewport provides the tools for translating between - * data coordinates and screen coordinates. - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Point; - -import ohd.hseb.util.DataPoint; - -/** - * @author Chip Gobs - * - * This class provides a mapping between screen coordinates and - * data coordinates. - */ -public class Viewport -{ - private Point _minScreenPoint = null; - private Point _maxScreenPoint = null; - - private DataPoint _minDataPoint = null; - private DataPoint _maxDataPoint = null; - - private boolean _flipYOrientation = false; - private boolean _flipXOrientation = false; - -// ---------------------------------------------------------------------------- - public Viewport(Point minScreenPoint, - Point maxScreenPoint, - DataPoint minDataPoint, - DataPoint maxDataPoint) - { - _minScreenPoint = minScreenPoint; - _maxScreenPoint = maxScreenPoint; - - _minDataPoint = minDataPoint; - _maxDataPoint = maxDataPoint; - - return; - } - - // ---------------------------------------------------------------------------- - - - public Viewport(Viewport viewport) - { - _minScreenPoint = viewport.getMinScreenPoint(); - _maxScreenPoint = viewport.getMaxScreenPoint(); - - _minDataPoint = viewport.getMinDataPoint(); - _maxDataPoint = viewport.getMaxDataPoint(); - - _flipXOrientation = viewport._flipXOrientation; - _flipYOrientation = viewport._flipYOrientation; - - return; - - } - - // ---------------------------------------------------------------------------- - - public boolean isViewable(DataPoint dataPoint) - { - boolean result = false; - - if ( - (dataPoint.getX() >= _minDataPoint.getX()) && - (dataPoint.getX() <= _maxDataPoint.getX()) && - (dataPoint.getY() >= _minDataPoint.getY()) && - (dataPoint.getY() <= _maxDataPoint.getY()) - ) - { - result = true; - } - - return result; - - } - - // ---------------------------------------------------------------------------- - - public void setFlipYOrientation(boolean flip) - { - _flipYOrientation = flip; - } - - // ---------------------------------------------------------------------------- - - public void setFlipXOrientation(boolean flip) - { - _flipXOrientation = flip; - } - - // ---------------------------------------------------------------------------- - - public DataPoint getDataPoint(Point screenPoint) - { - DataPoint dataPoint = new DataPoint(); - - - double x = calcDataCoord(screenPoint.x, - _minScreenPoint.x, - _maxScreenPoint.x, - _minDataPoint.getX(), - _maxDataPoint.getX(), - _flipXOrientation); - - double y = calcDataCoord(screenPoint.y, - _minScreenPoint.y, - _maxScreenPoint.y, - _minDataPoint.getY(), - _maxDataPoint.getY(), - _flipYOrientation); - - dataPoint.setX(x); - dataPoint.setY(y); - - return dataPoint; - } - - // ---------------------------------------------------------------------------- - - public Point getScreenPoint(DataPoint dataPoint) - { - Point screenPoint = new Point(); - - int x = calcScreenCoord(dataPoint.getX(), - _minScreenPoint.x, - _maxScreenPoint.x, - _minDataPoint.getX(), - _maxDataPoint.getX(), - _flipXOrientation); - - int y = calcScreenCoord(dataPoint.getY(), - _minScreenPoint.y, - _maxScreenPoint.y, - _minDataPoint.getY(), - _maxDataPoint.getY(), - _flipYOrientation); - - screenPoint.x = x; - screenPoint.y = y; - - return screenPoint; - } - - //---------------------------------------------------------------------------- - - private double calcDataCoord(int screenCoord, - int minScreenCoord, - int maxScreenCoord, - double minDataCoord, - double maxDataCoord, - boolean flipOrientation) - { - double dataCoord = 0.0; - int lengthDrawn = 0; - - int useableScreenLength = Math.abs(maxScreenCoord - minScreenCoord); - double maxDataDiff = maxDataCoord - minDataCoord; - - double fractionalDistance = 0.0; - - /* - * avoid possible divide by 0 - */ - if (useableScreenLength == 0) - { - return 0.0; - } - - // determine how far from the appropriate edge the coordinate is - if (flipOrientation) - { - //lengthDrawn = Math.abs(screenCoord - maxScreenCoord); - lengthDrawn = maxScreenCoord - screenCoord; - } - else - { - lengthDrawn = screenCoord - minScreenCoord; - //lengthDrawn = Math.abs(screenCoord - minScreenCoord); - } - - //figure out the proportion of the screen distance the coordinate is - fractionalDistance = (double) lengthDrawn/ - (double) useableScreenLength; - - // get the dataCoord from the fractionalDistance - dataCoord = (fractionalDistance * maxDataDiff) + minDataCoord; - - return dataCoord; - } - // ---------------------------------------------------------------------------- - - private int calcScreenCoord(double dataCoord, - int minScreenCoord, - int maxScreenCoord, - double minDataCoord, - double maxDataCoord, - boolean flipOrientation) - { - int screenCoord = 0; - - int useableScreenLength = Math.abs(maxScreenCoord - minScreenCoord); - double maxDataDiff = maxDataCoord - minDataCoord; - - double curDataDiff = dataCoord - minDataCoord; - - - // avoid possible divided by 0 - if (maxDataDiff == 0) - { - return 0; - } - - - // Rounding - double fractionDrawn = ((double)curDataDiff /(double) maxDataDiff); - int lengthDrawn = (int) Math.round(fractionDrawn * useableScreenLength); - - if (flipOrientation) - { - screenCoord = maxScreenCoord - lengthDrawn; - } - else - { - screenCoord = minScreenCoord + lengthDrawn; - } - - return screenCoord; - - } //end calcScreenCoord - - // ---------------------------------------------------------------------------- - - - public void setMinScreenPoint(Point minScreenPoint) - { - _minScreenPoint = minScreenPoint; - } - - // ---------------------------------------------------------------------------- - - public Point getMinScreenPoint() - { - return _minScreenPoint; - } - - // ---------------------------------------------------------------------------- - - - public void setMaxScreenPoint(Point maxScreenPoint) - { - _maxScreenPoint = maxScreenPoint; - } - - // ---------------------------------------------------------------------------- - - - public Point getMaxScreenPoint() - { - return _maxScreenPoint; - } - - // ---------------------------------------------------------------------------- - - - public void setMinDataPoint(DataPoint minDataPoint) - { - _minDataPoint = minDataPoint; - } - // ---------------------------------------------------------------------------- - - public DataPoint getMinDataPoint() - { - return _minDataPoint; - } - // ---------------------------------------------------------------------------- - - public void setMaxDataPoint(DataPoint maxDataPoint) - { - _maxDataPoint = maxDataPoint; - } - // ---------------------------------------------------------------------------- - - public DataPoint getMaxDataPoint() - { - return _maxDataPoint; - } - -// ---------------------------------------------------------------------------- - -// ---------------------------------------------------------------------------- - - public static void main(String[] args) - { - Point minScreenPoint = new Point(0,0); - Point maxScreenPoint = new Point(500, 500); - - DataPoint minDataPoint = new DataPoint(0.0, 0.0); - DataPoint maxDataPoint = new DataPoint(100, 100); - - Viewport vp = new Viewport(minScreenPoint, - maxScreenPoint, - minDataPoint, - maxDataPoint); - - for (int i = 0; i <= 500; i+=100) - { - for (int j = 0; j <= 500; j+=100) - { - Viewport.test(vp, i, j); - } - } - - - } //end main - - // ---------------------------------------------------------------------------- - - public static void test(Viewport viewport, int x, int y) - { - Point screenPoint = new Point(x, y); - DataPoint currentDataPoint = null; - Point newPoint = null; - - currentDataPoint = viewport.getDataPoint(screenPoint); - - newPoint = viewport.getScreenPoint(currentDataPoint); - - System.out.println("orig screenPoint = " + screenPoint); - System.out.println("data Point = " + currentDataPoint); - System.out.println("converted point " + newPoint); - - return; - } //end test - -} //end class ViewPort diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeCellRenderer.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeCellRenderer.java deleted file mode 100755 index 0b0c0936dc..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeCellRenderer.java +++ /dev/null @@ -1,256 +0,0 @@ -package ohd.hseb.util.gui.jchecktree; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; - -import javax.swing.AbstractAction; -import javax.swing.ActionMap; -import javax.swing.ButtonGroup; -import javax.swing.ButtonModel; -import javax.swing.Icon; -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.ActionMapUIResource; -import javax.swing.tree.TreeCellRenderer; -import javax.swing.tree.TreePath; - -public class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer -{ - /** This is a type-safe enumerated type */ - public static class State { private State() { } } - public static final State NOT_SELECTED = new State(); - public static final State SELECTED = new State(); - public static final State DONT_CARE = new State(); - - private CheckTreeSelectionModel selectionModel; - private TreeCellRenderer delegate; - private TristateCheckBox checkBox = new TristateCheckBox(); - - public CheckTreeCellRenderer(TreeCellRenderer delegate, CheckTreeSelectionModel selectionModel) - { - this.delegate = delegate; - this.selectionModel = selectionModel; - setLayout(new BorderLayout()); - setOpaque(false); - checkBox.setOpaque(false); - } - - - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) - { - Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); - TreePath path = tree.getPathForRow(row); - - if(path!=null) - { - if(selectionModel.isPathSelected(path, true)) - { - //checkBox.setState(Boolean.TRUE); - checkBox.setState(SELECTED); - } - else - { - // checkBox.setState(selectionModel.isPartiallySelected(path) ? null : Boolean.FALSE); - checkBox.setState(selectionModel.isPartiallySelected(path) ? null : NOT_SELECTED); - } - } - removeAll(); - add(checkBox, BorderLayout.WEST); - add(renderer, BorderLayout.CENTER); - return this; - } - - - /** - * Maintenance tip - There were some tricks to getting this code - * working: - * - * 1. You have to overwite addMouseListener() to do nothing - * 2. You have to add a mouse event on mousePressed by calling - * super.addMouseListener() - * 3. You have to replace the UIActionMap for the keyboard event - * "pressed" with your own one. - * 4. You have to remove the UIActionMap for the keyboard event - * "released". - * 5. You have to grab focus when the next state is entered, - * otherwise clicking on the component won't get the focus. - * 6. You have to make a TristateDecorator as a button model that - * wraps the original button model and does state management. - */ - public class TristateCheckBox extends JCheckBox { - - private final TristateDecorator model; - - public TristateCheckBox(String text, Icon icon, State initial){ - super(text, icon); - // Add a listener for when the mouse is pressed - super.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e) { - grabFocus(); - model.nextState(); - } - }); - // Reset the keyboard action map - ActionMap map = new ActionMapUIResource(); - map.put("pressed", new AbstractAction() { - public void actionPerformed(ActionEvent e) { - grabFocus(); - model.nextState(); - } - }); - map.put("released", null); - SwingUtilities.replaceUIActionMap(this, map); - // set the model to the adapted model - model = new TristateDecorator(getModel()); - setModel(model); - setState(initial); - } - public TristateCheckBox(String text, State initial) { - this(text, null, initial); - } - public TristateCheckBox(String text) { - this(text, DONT_CARE); - } - public TristateCheckBox() { - this(null); - } - - /** No one may add mouse listeners, not even Swing! */ - public void addMouseListener(MouseListener l) { } - /** - * Set the new state to either SELECTED, NOT_SELECTED or - * DONT_CARE. If state == null, it is treated as DONT_CARE. - */ - public void setState(State state) { model.setState(state); } - /** Return the current state, which is determined by the - * selection status of the model. */ - public State getState() { return model.getState(); } - public void setSelected(boolean b) { - if (b) { - setState(SELECTED); - } else { - setState(NOT_SELECTED); - } - } - /** - * Exactly which Design Pattern is this? Is it an Adapter, - * a Proxy or a Decorator? In this case, my vote lies with the - * Decorator, because we are extending functionality and - * "decorating" the original model with a more powerful model. - */ - private class TristateDecorator implements ButtonModel { - private final ButtonModel other; - private TristateDecorator(ButtonModel other) { - this.other = other; - } - private void setState(State state) { - if (state == NOT_SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(false); - } else if (state == SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(true); - } else { // either "null" or DONT_CARE - other.setArmed(true); - setPressed(true); - setSelected(true); - } - } - /** - * The current state is embedded in the selection / armed - * state of the model. - * - * We return the SELECTED state when the checkbox is selected - * but not armed, DONT_CARE state when the checkbox is - * selected and armed (grey) and NOT_SELECTED when the - * checkbox is deselected. - */ - private State getState() { - if (isSelected() && !isArmed()) { - // normal black tick - return SELECTED; - } else if (isSelected() && isArmed()) { - // don't care grey tick - return DONT_CARE; - } else { - // normal deselected - return NOT_SELECTED; - } - } - /** We rotate between NOT_SELECTED, SELECTED and DONT_CARE.*/ - private void nextState() { - State current = getState(); - if (current == NOT_SELECTED) { - setState(SELECTED); - } else if (current == SELECTED) { - setState(DONT_CARE); - } else if (current == DONT_CARE) { - setState(NOT_SELECTED); - } - } - /** Filter: No one may change the armed status except us. */ - public void setArmed(boolean b) { - } - /** We disable focusing on the component when it is not - * enabled. */ - public void setEnabled(boolean b) { - setFocusable(b); - other.setEnabled(b); - } - /** All these methods simply delegate to the "other" model - * that is being decorated. */ - public boolean isArmed() { return other.isArmed(); } - public boolean isSelected() { return other.isSelected(); } - public boolean isEnabled() { return other.isEnabled(); } - public boolean isPressed() { return other.isPressed(); } - public boolean isRollover() { return other.isRollover(); } - public void setSelected(boolean b) { other.setSelected(b); } - public void setPressed(boolean b) { other.setPressed(b); } - public void setRollover(boolean b) { other.setRollover(b); } - public void setMnemonic(int key) { other.setMnemonic(key); } - public int getMnemonic() { return other.getMnemonic(); } - public void setActionCommand(String s) { - other.setActionCommand(s); - } - public String getActionCommand() { - return other.getActionCommand(); - } - public void setGroup(ButtonGroup group) { - other.setGroup(group); - } - public void addActionListener(ActionListener l) { - other.addActionListener(l); - } - public void removeActionListener(ActionListener l) { - other.removeActionListener(l); - } - public void addItemListener(ItemListener l) { - other.addItemListener(l); - } - public void removeItemListener(ItemListener l) { - other.removeItemListener(l); - } - public void addChangeListener(ChangeListener l) { - other.addChangeListener(l); - } - public void removeChangeListener(ChangeListener l) { - other.removeChangeListener(l); - } - public Object[] getSelectedObjects() { - return other.getSelectedObjects(); - } - } - } -} - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeManager.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeManager.java deleted file mode 100755 index 7100296f56..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeManager.java +++ /dev/null @@ -1,62 +0,0 @@ -package ohd.hseb.util.gui.jchecktree; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.JCheckBox; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreePath; - -public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener -{ - private CheckTreeSelectionModel selectionModel; - private JTree tree = new JTree(); - int hotspot = new JCheckBox().getPreferredSize().width; - - public CheckTreeManager(JTree tree) - { - this.tree = tree; - selectionModel = new CheckTreeSelectionModel(tree.getModel()); - tree.setCellRenderer(new CheckTreeCellRenderer(tree.getCellRenderer(), selectionModel)); - tree.addMouseListener(this); - selectionModel.addTreeSelectionListener(this); - } - - public void mouseClicked(MouseEvent me) - { - TreePath path = tree.getPathForLocation(me.getX(), me.getY()); - if(path==null) - return; - if(me.getX()>tree.getPathBounds(path).x+hotspot) - return; - - boolean selected = selectionModel.isPathSelected(path, true); - selectionModel.removeTreeSelectionListener(this); - - try - { - if(selected) - selectionModel.removeSelectionPath(path); - else - selectionModel.addSelectionPath(path); - } - finally - { - selectionModel.addTreeSelectionListener(this); - tree.treeDidChange(); - } - } - - public CheckTreeSelectionModel getSelectionModel() - { - return selectionModel; - } - - public void valueChanged(TreeSelectionEvent e) - { - // TODO Auto-generated method stub - } -} - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeSelectionModel.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeSelectionModel.java deleted file mode 100755 index 6e7ee2d06f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeSelectionModel.java +++ /dev/null @@ -1,185 +0,0 @@ -package ohd.hseb.util.gui.jchecktree; - -import java.util.ArrayList; -import java.util.Stack; - -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -public class CheckTreeSelectionModel extends DefaultTreeSelectionModel -{ - private TreeModel model; - - public CheckTreeSelectionModel(TreeModel model) - { - this.model = model; - setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - } - - // tests whether there is any unselected node in the subtree of given path - public boolean isPartiallySelected(TreePath path) - { - if(isPathSelected(path, true)) - return false; - TreePath[] selectionPaths = getSelectionPaths(); - if(selectionPaths==null) - return false; - for(int j = 0; j _allRowDataList = null; - private JTableSortHelper _sortHelper; - private JTableColumnDescriptorManager _columnDescriptorManager; - private ScrollableJTable _scrollableJTable = null; - - private Dimension _columnHeaderPreferredSize = null; - - - public ComplexJTableManager(List columnDescriptorList, List rowDataList, Dimension columnHeaderPreferredSize) - { - - _columnHeaderPreferredSize = columnHeaderPreferredSize; - - _allRowDataList = rowDataList; - _columnDescriptorManager = new JTableColumnDescriptorManager( - columnDescriptorList); - _scrollableJTable = new ScrollableJTable(this, _columnHeaderPreferredSize); - String columnNamesToDisplay[] = getColumnNamesThatAreCurrentlyDisplayed(); - if(columnNamesToDisplay != null) - { - setDisplayableColumns(getColumnNamesThatAreCurrentlyDisplayed(), true, true); - } - - } - - public ComplexJTableManager(List columnDescriptorList, List rowDataList) - { - this (columnDescriptorList, rowDataList, null); - } - - public ComplexJTableManager(List columnDescriptorList, List rowDataList, int tableRowSelectionMode) - { - _allRowDataList = rowDataList; - _columnDescriptorManager = new JTableColumnDescriptorManager( - columnDescriptorList); - _scrollableJTable = new ScrollableJTable(this, tableRowSelectionMode); - } - - public void setColumnHeaderPreferredSize(Dimension columnHeaderPreferredSize) - { - _columnHeaderPreferredSize = columnHeaderPreferredSize; - if (_scrollableJTable != null) - { - _scrollableJTable.setColumnHeaderPreferredSize(columnHeaderPreferredSize); - } - } - - public void resetSortHelper() - { - _sortHelper = null; - } - - public void setChangedAllRowDataList(List allRowDataList) - { - _allRowDataList = allRowDataList; - } - - public List getAllRowDataList() - { - return _allRowDataList; - } - - public void setColumnsForDisplay(String columnNamesSelected[]) - { - _columnDescriptorManager.setDisplayableColumns(columnNamesSelected); - } - - public void setDisplayableColumns(String columnNamesSelected[], - boolean changeSortOrder,boolean firstDraw) - { - _columnDescriptorManager.setDisplayableColumns(columnNamesSelected); - - boolean columnSortOrderArray[] = null; - - if(changeSortOrder) - { - columnSortOrderArray = _columnDescriptorManager.getSortOrderOfAllColumns(); - } - - String[] allColumnNamesInColumnDescriptorManager = _columnDescriptorManager.getAllColumnNamesInColumnDescriptorManager(); - _sortHelper = new JTableSortHelper(allColumnNamesInColumnDescriptorManager); - if(columnSortOrderArray != null) - { - _sortHelper.setChangedSortOrderArray(columnSortOrderArray); - } - _scrollableJTable.createTable(firstDraw); - } - - public String[] getColumnNamesThatAreCurrentlyDisplayed() - { - String columnNames[] = _columnDescriptorManager. - getColumnNamesThatAreCurrentlyDisplayed(); - return columnNames; - } - - public void swapColumns(String columnName1, String columnName2) - { - _columnDescriptorManager.swapColumnsInList(columnName1, columnName2); - } - - public String[][] getDisplayRowDataArray() - { - // CodeTimer timer = new CodeTimer(); - // timer.start(); - List columnDescriptorList = _columnDescriptorManager.getColumnDescriptor(); - String colNamesSelected[] = _columnDescriptorManager.getColumnNamesThatAreCurrentlyDisplayed(); - - _rowDataForCurrentDisplayedRows = new String[_allRowDataList.size()] - [colNamesSelected.length]; - _cellBackgroundColorsForCurrentDisplayedRows = new Color[_allRowDataList.size()] - [colNamesSelected.length]; - _cellForegroundColorsForCurrentDisplayedRows = new Color[_allRowDataList.size()] - [colNamesSelected.length]; - int col = 0; - - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - for(int row=0; row < _allRowDataList.size(); row++) - { - JTableRowData infoRecord = (JTableRowData) _allRowDataList.get(row); - col = 0; - for(int j =0; j =0; i--) - { - boolean isAscending = _columnDescriptorManager.getSortDirectionForColumn(columnNamesForSortingToBeDone[i]); - // System.out.println("ComplexJTableManager.sort(): "+ columnNamesForSortingToBeDone[i]+"|"+ isAscending); - sort(columnNamesForSortingToBeDone[i], isAUserClick, isAscending); - } - } - } - - public void sort(String columnName, boolean isAUserClick, boolean isAscending) - { - // System.out.println("ComplexJTableManager.sort(,,):" + columnName); - _sortHelper.sortList(_allRowDataList, columnName, isAUserClick, isAscending); - } - - public boolean isColumnAsc(String columnName) - { - return _sortHelper.isColumnAsc(columnName); - } - - public JTableRowData getRowData(int rowIndex) - { - JTableRowData rowData = (JTableRowData) _allRowDataList.get(rowIndex); - return rowData; - } - - public Color getCellBackgroundColor(int row, int column) - { - Color newBackgroundColor = _cellBackgroundColorsForCurrentDisplayedRows[row][column]; - return newBackgroundColor; - } - - public Color getCellForegroundColor(int row, int column) - { - Color newForegroundColor = _cellForegroundColorsForCurrentDisplayedRows[row][column]; - return newForegroundColor; - } - - public void setSortInfoNotBasedOnUserClicks(String columnNamesToSort[], boolean columnSortOrder[], int columnSortNumber[]) - { - _columnDescriptorManager.setSortInfoNotBasedOnUserClicks(columnNamesToSort, columnSortOrder, columnSortNumber); - _scrollableJTable.sort(); - } - - public void clearSort() - { - _columnDescriptorManager.clearSort(); - _scrollableJTable.sort(); - } - - public String[] getColumnNamesForSortToBeDone() - { - String columnNamesForSorting[] = _columnDescriptorManager.getColumnNamesForSortToBeDone(); - - return columnNamesForSorting; - } - - public int[] getSortOrderForSortedColumnNames() - { - int sortOrderForSortedColumns[] = _columnDescriptorManager.getSortOrderForSortedColumnNames(); - - return sortOrderForSortedColumns; - } - - public int[] getWidthOfDisplayedColumns() - { - int columnWidths[] = _columnDescriptorManager.getWidthOfDisplayedColumns(); - return columnWidths; - } - - public String[] getAlignmentOfDisplayedColumns() - { - String columnAligments[] = _columnDescriptorManager.getAlignmentOfDisplayedColumns(); - return columnAligments; - } - - public void setWidthOfDisplayedColumns(int columnWidths[]) - { - _columnDescriptorManager.setWidthOfDisplayedColumns(columnWidths); - } - - public void setAlignmentOfDisplayedColumns(String columnAlignments[]) - { - _columnDescriptorManager.setAlignmentOfDisplayedColumns(columnAlignments); - } - - public void selectColumnForSorting(String columnName) - { - boolean isAscending = _columnDescriptorManager.getSortDirectionForColumn(columnName); - _columnDescriptorManager.selectColumnForSorting(columnName, isAscending, -1, true); - } - - public JTableColumnDisplaySettings getTableSettings() - { - JTableColumnDisplaySettings columnDisplaySettings = _columnDescriptorManager.getTableColumnSettings(); - return columnDisplaySettings; - } - - public void addTableListener(EventListener eventListener) - { - _scrollableJTable.addTableListeners(eventListener); - } - - public void removeTableListener(EventListener eventListener) - { - _scrollableJTable.removeTableListener(eventListener); - } - - public JScrollPane getJScrollPane() - { - return(_scrollableJTable.getJScrollPane()); - } - - public void setPreferredSizeForJScrollPane(Dimension dimension) - { - _scrollableJTable.setPreferredSizeForJScrollPane(dimension); - } - - public int[] getSelectedRowIndices() - { - int selectedRowIndices[] =_scrollableJTable.getSelectedRowIndices(); - - return selectedRowIndices; - } - - public List getSelectedRowsData() - { - int selectedRowIndices[] = getSelectedRowIndices(); - List selectedRowDataList = new ArrayList(); - for(int loopCnt=0; loopCnt _columnDescriptorList = null; - private Map _columnDescriptorMap = null; - private List _columnDescriptorForSortInfoList = null; - private static final int _totalSortToRecord = 4; - private Map _columnSettingMap = null; - - public JTableColumnDescriptorManager(List columnDescriptorList) - { - _columnDescriptorList = columnDescriptorList; - _columnDescriptorMap = new HashMap(); - for(int i =0 ; i < _columnDescriptorList.size(); i++) - { - JTableColumnDescriptor columnDescription = (JTableColumnDescriptor) - _columnDescriptorList.get(i); - _columnDescriptorMap.put(columnDescription.getColumnName(), - columnDescription); - } - - _columnDescriptorForSortInfoList = new ArrayList(_totalSortToRecord); - - } - - public String getSettingsString() - { - String columnDisplaySetting[] = getDisplayedColumnSettings(); - String columnSortSetting[] = getColumnSortSettings(); - String settings = null; - - settings = "#COLUMN:Column Name|Column Width".concat("\n"); - if(columnDisplaySetting != null) - { - for(int i=0 ; i < columnDisplaySetting.length; i++) - { - settings = settings.concat(columnDisplaySetting[i]).concat("\n"); - } - } - settings = settings.concat("\n").concat("#SORT:Column Name|IsAscending|Sort Order").concat("\n"); - if(columnSortSetting != null) - { - for(int i=0; i < columnSortSetting.length; i++) - { - settings = settings.concat(columnSortSetting[i]).concat("\n"); - } - } - return settings; - } - - public List getSettingsListFromSettingsString(String settings) - { - List returnList = new ArrayList(); - int begIndex = 0; - while(settings != null) - { - int indexOfNewLine = settings.indexOf("\n"); - if(indexOfNewLine != -1) - { - String line = settings.subSequence(begIndex, indexOfNewLine).toString(); - returnList.add(line); - settings = settings.subSequence(indexOfNewLine+1, settings.length()).toString(); - } - else - { - break; - } - } - - return returnList; - } - - public List getTableSettingsForTokenMentioned(List settingsList, String tokenName) - { - List settingsListForTokenMentioned = new ArrayList (); - if(settingsList != null) - { - for(int i=0; i < settingsList.size(); i++) - { - String tempStr = settingsList.get(i).toString(); - if(!(tempStr.equals(""))) - { - String str = tempStr.subSequence(0,tokenName.length()).toString(); - if(str.compareTo(tokenName) == 0) - { - settingsListForTokenMentioned.add(settingsList.get(i)); - } - } - } - - } - return settingsListForTokenMentioned; - } - - public void setSettingsFromString(String settings) - { - String header = "JTableColumnDescriptorManager.setSettingsFromString(): "; - - if(settings != null) - { - _columnDescriptorForSortInfoList.clear(); //make the list empty - - List settingsList = getSettingsListFromSettingsString(settings); - - boolean isColumnDisplayTokenReadAndSet = readColumnDisplayToken(settingsList); - if(isColumnDisplayTokenReadAndSet) - { - readColumnSortToken(settingsList); - } - } - } - - private void readColumnSortToken(List settingsList) - { - String columnSortToken = "SORT:"; - String str; - - List columnNamesToSortList = new ArrayList(); - List columnSortDirectionList = new ArrayList(); - List columnSortOrderList = new ArrayList(); - - List stringListForSortToken = getTableSettingsForTokenMentioned(settingsList, columnSortToken); - - if(stringListForSortToken != null) - { - for(int i =0; i < stringListForSortToken.size(); i++) - { - str = stringListForSortToken.get(i).toString(); - str = str.substring(columnSortToken.length(), str.length()).trim(); - - String[] splitStr = str.split("\\|"); - if(splitStr != null && splitStr.length == 3) - { - if(isValidColumn(splitStr[0])) - { - columnNamesToSortList.add(splitStr[0]); - - boolean columnSortAsc = Boolean.parseBoolean(splitStr[1]); - columnSortDirectionList.add(columnSortAsc); - - columnSortOrderList.add(Integer.parseInt(splitStr[2])); - } - } - } - - for(int i=0; i < columnNamesToSortList.size(); i++) - { - selectColumnForSorting(columnNamesToSortList.get(i), columnSortDirectionList.get(i), - i, false); - } - } - } - - private boolean readColumnDisplayToken(List settingsList) - { - String columnDisplayToken = "COLUMN:"; - String str; - boolean isColumnDisplayTokenReadAndSet = false; - - List columnNamesToDisplayList = new ArrayList(); - List columnWidthList = new ArrayList(); - - String columnNamesToDisplay[] = null; - int columnWidths[] = null; - - List stringListForColumnDisplayToken = getTableSettingsForTokenMentioned(settingsList, columnDisplayToken); - - if(stringListForColumnDisplayToken != null) - { - for(int i =0; i < stringListForColumnDisplayToken.size(); i++) - { - str = stringListForColumnDisplayToken.get(i).toString(); - str = str.substring(columnDisplayToken.length(), str.length()).trim(); - String[] splitStr = str.split("\\|"); - if(splitStr != null && splitStr.length == 2) - { - if(isValidColumn(splitStr[0])) - { - columnNamesToDisplayList.add(splitStr[0]); - int columnWidth = Integer.parseInt(splitStr[1]); - columnWidthList.add(columnWidth); - } - } - } - columnNamesToDisplay = new String[columnNamesToDisplayList.size()]; - columnWidths = new int[columnNamesToDisplayList.size()]; - - for(int i=0; i < columnNamesToDisplayList.size(); i++) - { - columnNamesToDisplay[i] = columnNamesToDisplayList.get(i); - columnWidths[i] = columnWidthList.get(i); - } - } - - if(columnNamesToDisplay!= null ) - { - setDisplayableColumns(columnNamesToDisplay); - setWidthOfDisplayedColumns(columnWidths); - isColumnDisplayTokenReadAndSet = true; - } - - return isColumnDisplayTokenReadAndSet; - } - - protected boolean isValidColumn(String columnName) - { - boolean isValidColumn = false; - Set validColumnNamesSet = getSetOfValidColumnNames(); - - if( validColumnNamesSet.contains(columnName) ) - { - isValidColumn = true; - } - - if( ! isValidColumn) - { - System.out.println("Invalid column name ["+ columnName +"] in settings file"); - System.out.println("Check the settings file..."); - } - return isValidColumn; - } - - protected String[] getAllowedColumnNamesArray() - { - String[] allowedColNames = new String[_columnDescriptorList.size()]; - - for(int i = 0; i < allowedColNames.length ; i++) - { - JTableColumnDescriptor columnDescriptor; - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - allowedColNames[i] = columnDescriptor.getColumnName(); - } - - return allowedColNames; - } - - protected Set getSetOfValidColumnNames() - { - // String header = "JTableColumnDescriptorManager.getSetOfValidColumnNames(): "; - Set validColumnNamesSet = new HashSet(); - - JTableColumnDescriptor columnDescription = null; - for(int j=0; j < _columnDescriptorList.size() ;j++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(j); - validColumnNamesSet.add(columnDescription.getColumnName()); - // System.out.println(header + "columnName[" + j +"] = " + columnDescription.getColumnName()); - } - return validColumnNamesSet; - } - - protected void setDisplayableColumns(String columnNamesSelected[]) - { - for(int i=0;i < _columnDescriptorList.size(); i++) - { - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - columnDescription.setDisplay(false); - for(int j=0; j < columnNamesSelected.length ;j++) - { - if( columnDescription.getColumnName().compareTo(columnNamesSelected[j]) == 0 ) - { - columnDescription.setDisplay(true); - } - } - } - - //Rearrange the list in such a way that the descriptor of selected column names - //Appear in the top of the list, and they are added in the same order as - //the selected column names - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - - for(int i = 0 ; i < columnNamesSelected.length; i++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorMap. - get(columnNamesSelected[i]); - if(columnDescription != null) - { - _columnDescriptorList.remove(columnDescription); - _columnDescriptorList.add(i, columnDescription); - } - } - } - - protected List getColumnDescriptor() - { - return _columnDescriptorList; - } - - protected String[] getAllColumnNamesInColumnDescriptorManager() - { - String columnNames[] = new String[_columnDescriptorList.size()]; - if(_columnDescriptorList.size() > 0) - { - columnNames = new String[_columnDescriptorList.size()]; - for(int i=0;i < _columnDescriptorList.size(); i++) - { - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - columnNames[i] = columnDescription.getColumnName(); - } - } - - return columnNames; - } - - protected String[] getColumnNamesThatAreCurrentlyDisplayed() - { - String columnNames[] = null; - int cnt=0; - JTableColumnDescriptor columnDescription; - - for(int i=0;i < _columnDescriptorList.size(); i++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - if ( columnDescription.getDisplay()) - cnt++; - } - if(cnt > 0) - { - columnNames = new String[cnt]; - int j=0; - for(int i=0;i < _columnDescriptorList.size(); i++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - if ( columnDescription.getDisplay()) - { - columnNames[j++] = columnDescription.getColumnName(); - - } - } - } - return columnNames; - } - - protected void swapColumnsInList(String columnName1, String columnName2) - { - JTableColumnDescriptor columnDescriptor1, columnDescriptor2; - columnDescriptor1 = (JTableColumnDescriptor) _columnDescriptorMap. - get(columnName1); - columnDescriptor2 = (JTableColumnDescriptor) _columnDescriptorMap. - get(columnName2); - - int index1 = _columnDescriptorList.indexOf(columnDescriptor1); - int index2 = _columnDescriptorList.indexOf(columnDescriptor2); - - _columnDescriptorList.set(index1, columnDescriptor2); - _columnDescriptorList.set(index2, columnDescriptor1); - - } - - protected JTableColumnDisplaySettings getTableColumnSettings() - { - return this; - } - - protected void clearSort() - { - String header = "JTableColumnDescriptorManager.clearSort(): "; - if(_columnDescriptorForSortInfoList != null) - { - _columnDescriptorForSortInfoList.clear(); - } - } - - protected void setSortInfoNotBasedOnUserClicks(String columnNamesToSort[], boolean columnSortOrder[], int columnSortNumber[]) - { - setSortOrderOfColumns(columnSortOrder, columnNamesToSort, columnSortNumber); - - for(int i=0; i < columnSortNumber.length; i++) - { - if(columnSortNumber[i] != -1) - { - selectColumnForSorting(columnNamesToSort[i], columnSortOrder[i], - columnSortNumber[i], false); - } - } - - } - - protected String[] getDisplayedColumnSettings() - { - String columnNamesInDisplay[] = getColumnNamesThatAreCurrentlyDisplayed(); - - String columnSetting[] = new String[columnNamesInDisplay.length]; - - JTableColumnDescriptor columnDescriptor; - int cnt=0; - for(int i=0 ; i < _columnDescriptorList.size(); i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - if(columnDescriptor.getDisplay()) - { - String columnName = columnDescriptor.getColumnName(); - int columnWidth = columnDescriptor.getWidth(); - columnSetting[cnt++] = "COLUMN:"+columnName+"|"+columnWidth; - } - } - - return columnSetting; - } - - protected int[] getWidthOfDisplayedColumns() - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - int columnWidths[] = new int[columnsDisplayed.length]; - - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnWidths[i] = columnDescriptor.getWidth(); - } - - return columnWidths; - } - - protected String[] getAlignmentOfDisplayedColumns() - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - String columnAlignments[] = new String[columnsDisplayed.length]; - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnAlignments[i] = columnDescriptor.getAlignment(); - } - - return columnAlignments; - } - - protected boolean[] getSortOrderOfAllColumns() - { - String allColumns[] = getAllColumnNamesInColumnDescriptorManager(); - - boolean columnsAscOrDescArray[] = new boolean[allColumns.length]; - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < allColumns.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(allColumns[i]); - columnsAscOrDescArray[i] = columnDescriptor.getSortAsc(); - } - return columnsAscOrDescArray; - } - - protected int getSortOrderNumberForColumn(String columnName) - { - int columnSortOrder = -1; - - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnName); - columnSortOrder = columnDescriptor.getSortOrder(); - return columnSortOrder; - } - - protected boolean getSortDirectionForColumn(String columnName) - { - boolean isAscending = false; - - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) _columnDescriptorMap.get(columnName); - isAscending = columnDescriptor.getSortAsc(); - - return isAscending; - } - - protected void setWidthOfDisplayedColumns(int columnWidths[]) - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnDescriptor.setWidth(columnWidths[i]); - } - } - - protected void setAlignmentOfDisplayedColumns(String columnAlignments[]) - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnDescriptor.setAlignment(columnAlignments[i]); - } - } - - - // ----------------------------------------------------------------------------------------------------------------------- - protected void selectColumnForSorting(String columnName, boolean isAscending, int positionToInsert, - boolean shouldReverseAscOrDescOrder) - { - // String header = "JTableColumnDescriptorManager.selectColumnForSorting() [new]: "; - - //printColumnsToSortBy("before " + header); - - JTableColumnDescriptor columnDescription = (JTableColumnDescriptor) _columnDescriptorMap.get(columnName); - - if(shouldReverseAscOrDescOrder) //flip the sort order of this column - { - isAscending = columnDescription.getSortAsc(); // get prev sort direction (asc or desc) - columnDescription.setSortAsc( ! isAscending ); // reverse the prev asc to desc or vice versa - } - else - { - columnDescription.setSortAsc( isAscending );// set the sort direction passed as argument to this method - } - - columnDescription.setSortOrder(positionToInsert); - - //put in the correct order relative to other columns - int index = 0; - - index = _columnDescriptorForSortInfoList.indexOf(columnDescription); - - if(index != -1) //the column is already in the list - { - _columnDescriptorForSortInfoList.remove(index); // remove it - _columnDescriptorForSortInfoList.add(0, columnDescription); //add it to the front of the list - } - else //it is not already in the list - { - if (_columnDescriptorForSortInfoList.size() >= _totalSortToRecord) //if we need to dump a sort column, because we have too many - { - int lastIndex = _columnDescriptorForSortInfoList.size()-1; - _columnDescriptorForSortInfoList.remove(lastIndex); - } - - if( positionToInsert == -1) //we just want it at the front - { - _columnDescriptorForSortInfoList.add(0, columnDescription); - } - else //we want it at a specific position - { - _columnDescriptorForSortInfoList.add(positionToInsert, columnDescription); - } - - } //end of else it is not already in the list - - //reset the sort order integer value for the descriptors - for (int i = 0; i < _columnDescriptorForSortInfoList.size(); i++) - { - JTableColumnDescriptor desc = (JTableColumnDescriptor) _columnDescriptorForSortInfoList.get(i); - desc.setSortOrder(i); - } - - // printColumnsToSortBy("after " + header); - - } //end of selectColumnForSorting - - // ------------------------------------------------------------------------------------------------------ - - private void printColumnsToSortBy(String message) - { - String header = "JTableColumnDescriptorList.printColumnstoSortBy() "; - - System.out.println(message); - - for (int i = 0; i < _columnDescriptorForSortInfoList.size() ; i++) - { - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) _columnDescriptorForSortInfoList.get(i); - if (columnDescriptor != null) - { - String direction = "ASC"; - - if (! columnDescriptor.getSortAsc()) - { - direction = "DESC"; - } - System.out.println(i + " " + columnDescriptor.getColumnName() + - " " + columnDescriptor.getSortOrder() + " " + direction); - } - else - { - System.out.println(header + " column at index " + i + " is null"); - } - } - - System.out.println(); - - } - - // ------------------------------------------------------------------------------------------------------ - protected String[] getColumnNamesForSortToBeDone() - { - - String columnNamesForSorting[] = new String[_columnDescriptorForSortInfoList.size()]; - - for(int i=0; i < columnNamesForSorting.length; i++) - { - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorForSortInfoList.get(i); - columnNamesForSorting[i] = columnDescriptor.getColumnName(); - } - return columnNamesForSorting; - - } - - // ------------------------------------------------------------------------------------------------------ - protected int[] getSortOrderForSortedColumnNames() - { - - int sortOrderForSortedColumns[] = new int[_columnDescriptorForSortInfoList.size()]; - - for(int i=0; i < sortOrderForSortedColumns.length; i++) - { - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorForSortInfoList.get(i); - sortOrderForSortedColumns[i] = columnDescriptor.getSortOrder(); - } - return sortOrderForSortedColumns; - - } - -// ------------------------------------------------------------------------------------------------------ - - private String[] getColumnSortSettings() - { - String columnSortSetting[] = null; - JTableColumnDescriptor columnDescriptor; - - String header = "JTableColumnDescriptorManager.getColumnSortSettings(): "; - if (_columnDescriptorForSortInfoList.size() > 0) - { - int j=0; - columnSortSetting = new String[_columnDescriptorForSortInfoList.size()]; - _columnSettingMap = new HashMap(); - for(int i=0 ; i < _columnDescriptorList.size(); i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - - String columnName = columnDescriptor.getColumnName(); - boolean isAscending = columnDescriptor.getSortAsc(); - - int columnSortOrder = -1; - int index = _columnDescriptorForSortInfoList.indexOf(columnDescriptor); - columnSortOrder = index; - - - if(columnSortOrder != -1) //if this column is to be sorted by - { - _columnSettingMap.put(new Integer(columnSortOrder).toString() , columnDescriptor); - columnSortSetting[j++] = "SORT:"+columnName+"|"+ isAscending+"|"+columnSortOrder; - } - } - } - String finalSortSetting[]= null; - if(columnSortSetting != null) - { - if(columnSortSetting.length > _totalSortToRecord) - finalSortSetting = new String[_totalSortToRecord]; - else - finalSortSetting = new String[columnSortSetting.length]; - for(int i=0; i < finalSortSetting.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnSettingMap.get(new Integer(i).toString()); - finalSortSetting[i] = "SORT:"+columnDescriptor.getColumnName()+"|"+ columnDescriptor.getSortAsc()+"|"+i; - } - } - return finalSortSetting; - } - - private void setSortOrderOfColumns(boolean columnSortOrders[], String columnNamesToSort[], int columnSortOrderNumber[]) - { - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < _columnDescriptorList.size(); i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - for(int j=0; j< columnNamesToSort.length ; j++) - { - //check if the column name is chosen for sort and then set the sort info - if(columnDescriptor.getColumnName().compareTo(columnNamesToSort[j]) == 0) - { - columnDescriptor.setSortAsc(columnSortOrders[j]); - columnDescriptor.setSortOrder(columnSortOrderNumber[j]); - } - } - } - } - -} //end of JTableColumnDescriptor diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableColumnDisplaySettings.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableColumnDisplaySettings.java deleted file mode 100755 index 3c669a904e..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableColumnDisplaySettings.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -public interface JTableColumnDisplaySettings -{ - String getSettingsString(); - - void setSettingsFromString(String settings); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableHeaderRenderer.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableHeaderRenderer.java deleted file mode 100644 index 6e5962035a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableHeaderRenderer.java +++ /dev/null @@ -1,92 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Component; -import java.awt.Dimension; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.JTable; -import javax.swing.SwingConstants; -import javax.swing.UIManager; - -public class JTableHeaderRenderer extends JTableCellRenderer -{ - private JTableManager _tableManager = null; - private Map _sortedColumnsAndTheirOrdersMap = null; - - public JTableHeaderRenderer(JTableManager tableManager, Dimension columnHeaderPreferredSize) - { - _tableManager = tableManager; - determineColumnSortDetails(); - setHorizontalAlignment(SwingConstants.CENTER); - setVerticalAlignment(SwingConstants.TOP); - - if (columnHeaderPreferredSize != null) - { - setPreferredSize(columnHeaderPreferredSize); - } - - setOpaque(true); - - // This call is needed because DefaultTableCellRenderer calls setBorder() - // in its constructor, which is executed after updateUI() - setBorder(UIManager.getBorder("TableHeader.cellBorder")); - } - - public void setTableManager(JTableManager manager) - { - _tableManager = manager; - determineColumnSortDetails(); - } - - public void determineColumnSortDetails() - { - _sortedColumnsAndTheirOrdersMap = new HashMap(); - String[] columnNamesForSortToBeDone = _tableManager.getColumnNamesForSortToBeDone(); - int[] sortOrderForSortedColumns = _tableManager.getSortOrderForSortedColumnNames(); - for(int i=0; i < columnNamesForSortToBeDone.length; i++) - { - _sortedColumnsAndTheirOrdersMap.put(columnNamesForSortToBeDone[i], sortOrderForSortedColumns[i]); - } - } - - public void updateUI() - { - super.updateUI(); - } - - public Component getTableCellRendererComponent(JTable table, Object value, - boolean selected, boolean focused, int row, int column) - { - - // String header = "JTableHeaderRenderer.getTableCellRendererComponent()"; - // System.out.println(header + "called."); - - final String upArrowString = "\u25BC"; //upArrow unicode for Times New Roman font - final String downArrowString = "\u25B2";//downArrow unicode for Times New Roman font - String arrowString = downArrowString; - - String str = value.toString(); - String columnHeaderString = value.toString(); - Integer columnSortOrder = (Integer) _sortedColumnsAndTheirOrdersMap.get(columnHeaderString); - if(columnSortOrder != null) - { - // System.out.println(columnHeaderString + "|"+ columnSortOrder); - if ( _tableManager.isColumnAsc(columnHeaderString) ) - { - arrowString = upArrowString; - } - - str = "" + value + " " + arrowString + "" + - (columnSortOrder.intValue() + 1) +""; - - } - else - { - str = "" + value +""; - } - setValue(str); - return this; - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableManager.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableManager.java deleted file mode 100755 index 1fd89e986f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableManager.java +++ /dev/null @@ -1,124 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.util.EventListener; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; - -public interface JTableManager -{ - - void sort(String columnName, boolean isAUserClick, boolean isAscending); - - void sort(boolean isAUserClick); - - String[][] getDisplayRowDataArray(); - - JTableRowData getRowData(int i); - - String[] getColumnNamesThatAreCurrentlyDisplayed(); - - Color getCellBackgroundColor(int row, int column); - - Color getCellForegroundColor(int row, int column); - - Dimension getSizeForJScrollPane(); - - void swapColumns(String columnName1, String columnName2); - - int[] getWidthOfDisplayedColumns(); - - String[] getAlignmentOfDisplayedColumns(); - - void setWidthOfDisplayedColumns(int columnWidths[]); - - void setAlignmentOfDisplayedColumns(String columnAlignments[]); - - void setColumnsForDisplay(String columnNamesSelected[]); - - void setDisplayableColumns(String columnNamesSelected[], - boolean changeSortOrder, boolean firstDraw); - - void selectColumnForSorting(String columnName); - - String[] getColumnNamesForSortToBeDone(); - - public int[] getSortOrderForSortedColumnNames(); - - void setChangedAllRowDataList(List allRowDataList); - - void resetSortHelper(); - - void setSortInfoNotBasedOnUserClicks(String columnNamesToSort[], boolean columnSortOrder[], int columnSortNumber[]); - - void clearSort(); - - JTableColumnDisplaySettings getTableSettings(); - - public void addTableListener(EventListener eventListener); - - public void removeTableListener(EventListener eventListener); - - public JScrollPane getJScrollPane(); - - public void setPreferredSizeForJScrollPane(Dimension dimension); - - public int[] getSelectedRowIndices(); - - public List getSelectedRowsData(); - - public int getMousePointedRowIndex(Point p); - - public int getMousePointedColumnIndex(Point p); - - public String getColumnNameAtIndex(int columnIndex) ; - - public JTableRowData getSelectedRowData(int rowIndex); - - public void setRowToolTipText(String str); - - public void refreshDisplay(); - - public List getAllRowDataList(); - - public String[] getAllowedColumnNamesArray(); - - /** - * Find the index of the first row containing the value - * @param uniqueValueForRow - * @return index - */ - public int getTheRowIndexToHighLightBasedOnValue(String uniqueValueForRow); - - /** - * Find the index of the first row containing the value - * in the columnName specified - * @param uniqueValueForRow - * @param columnName - * @return index - */ - public int getTheRowIndexToHighLightBasedOnValue(String uniqueValueForRow, String columnName); - - public void selectRows(int initialRowToSelect, int finalRowToSelect); - - public void selectRows(int rowIndices[]); - - public void deselectRows(int rowIndices[]); - - public void deselectRows(int initialRowToRemoveSelection, int finalRowToRemoveSelection); - - public void setVerifyInputWhenFocusTarget(boolean verify); - - public String getAlignment(String columnName); - - public String getColumnHeaderToolTipText(String columnName); - - public boolean isColumnAsc(String columnName); - - public void invokeColumnSelector(JFrame frame); - - } diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableModel.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableModel.java deleted file mode 100755 index 5b5ae6c634..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableModel.java +++ /dev/null @@ -1,123 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import javax.swing.table.DefaultTableModel; - -public class JTableModel extends DefaultTableModel -{ - private String[] _columnNames = null; - - private Object[][] _data = null; - private int[] _columnWidths = null; - private String[] _columnAlignments = null; - - - public JTableModel( String[] colNames, String[][] dataStringArray, - int[] columnWidth, String[] columnAlignment) - { - _columnNames = colNames; - _data = dataStringArray; - _columnWidths = columnWidth; - _columnAlignments = columnAlignment; - } - - public void setChangedColumnNames(String colNames[]) - { - _columnNames = colNames; - } - - public void setChangedColumnWidths(int columnWidths[]) - { - _columnWidths = columnWidths; - } - - public void setChangedColumnAlignments(String columnAlignments[]) - { - _columnAlignments = columnAlignments; - } - - public void updateData( String[][] dataStringArray ) - { - _data = dataStringArray; - } - - public int getColumnCount() - { - return _columnNames.length; - } - - public int getRowCount() - { - if ( _data != null ) - { - return _data.length; - } - else - { - return 0; - } - } - - public String getColumnName(int col) - { - return _columnNames[col]; - } - - public int getColumnNumber(String columnName) - { - int index = -1; - for(int i=0; i < _columnNames.length; i++) - { - if(_columnNames[i].equals(columnName)) - { - index =i; - break; - } - } - return index; - } - - public String getColumnAlignment(String columnName) - { - String alignment = null; - int index = -1; - for(int i=0; i <_columnNames.length; i++) - { - if(_columnNames[i].equals(columnName)) - { - index =i; - break; - } - } - - alignment = _columnAlignments[index]; - return alignment; - } - - public int getColumnWidth(String columnName) - { - int width = -1; - int index = -1; - for(int i=0; i <_columnNames.length; i++) - { - if(_columnNames[i].equals(columnName)) - { - index =i; - break; - } - } - - width = _columnWidths[index]; - return width; - } - - public Object getValueAt(int row, int col) - { - return _data[row][col]; - } - - public boolean isCellEditable(int row, int col) - { - return false; - } -} - diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableRowData.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableRowData.java deleted file mode 100755 index d0aa71b48f..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableRowData.java +++ /dev/null @@ -1,18 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; - -public interface JTableRowData -{ - int compare(String columnName, JTableRowData object); - - String getDataValue(String ColumnName); - - Color getCellBackgroundColor(String columnName); - - Color getCellForegroundColor(String columnName); - - void addCell(BaseTableCell cell); - - BaseTableCell getCell(String columnName); -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableSortHelper.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableSortHelper.java deleted file mode 100755 index 18f44323d7..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/JTableSortHelper.java +++ /dev/null @@ -1,120 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class JTableSortHelper -{ - private String[] _columnNameArray = null; - private List _sortColumnOrderList = new ArrayList(); - private boolean[] _isSortAscOrDescArray = null; - private int _columnCount = 0; - private JTableColumnComparator _columnComparator = new JTableColumnComparator(); - - public JTableSortHelper(String[] columnNameArray ) - { - _columnNameArray = columnNameArray; - _columnCount = _columnNameArray.length; - _isSortAscOrDescArray = new boolean[ _columnCount ]; - initialize(); - } - - public void setChangedColumns(String[] columnNameArray) - { - _columnNameArray = columnNameArray; - _columnCount = _columnNameArray.length; - } - - public void setChangedSortOrderArray(boolean sortOrderArray[]) - { - _isSortAscOrDescArray = sortOrderArray; - } - - public boolean[] getsortOrderArray() - { - return _isSortAscOrDescArray; - } - - private void initialize() - { - initLinkedListAndOrderArray(); - } - - public void sortList( List listToSort, String columnName, boolean isAUserClick , boolean isAscending) - { - int index = -1; - for(int i=0; i < _columnNameArray.length; i++) - { - if(_columnNameArray[i].compareTo(columnName) == 0 ) - { - index = i; - break; - } - } - _columnComparator.initColumnInfo( columnName, isAscending ); - - Collections.sort( listToSort, _columnComparator ); - - if (isAUserClick) - { - _isSortAscOrDescArray[ index ] = ! isAscending; - } - - } - - public boolean determineAscOrDescForColumnName(String columnName) - { - boolean result; - int matchIndex = findIndexOfColumnNameInColumnNamesArray(columnName); - if(matchIndex != -1) - result = _isSortAscOrDescArray[matchIndex]; - else - result = false; //default is desc - - return result; - } - - public boolean isColumnAsc(String columnName) - { - boolean result = false;//default is desc - int matchIndex = findIndexOfColumnNameInColumnNamesArray(columnName); - if(matchIndex != -1) - result = _isSortAscOrDescArray[matchIndex]; - - return result; - } - - private int findIndexOfColumnNameInColumnNamesArray(String columnName) - { - int matchIndex = -1; - for(int i=0; i < _columnNameArray.length; i++) - { - if(_columnNameArray[i].equals(columnName)) - { - matchIndex = i; - break; - } - } - return matchIndex; - } - - public void sortWithoutMemory( List listToSort, int column, boolean isAscendingOrder ) - { - String columnName = _columnNameArray[ column ]; - boolean sortAscOrder = isAscendingOrder; - - _columnComparator.initColumnInfo( columnName, sortAscOrder ); - Collections.sort( listToSort, _columnComparator ); - } - - private void initLinkedListAndOrderArray() - { - for ( int i = 0; i < _columnCount; i++ ) - { - _isSortAscOrDescArray[ i ] = true; - _sortColumnOrderList.add( i, new Integer( i ) ); - } - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/ScrollableJTable.java b/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/ScrollableJTable.java deleted file mode 100644 index 9562cafa3a..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/gui/jtable/ScrollableJTable.java +++ /dev/null @@ -1,618 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionAdapter; -import java.awt.event.MouseMotionListener; -import java.util.ArrayList; -import java.util.EventListener; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TableColumnModelEvent; -import javax.swing.event.TableColumnModelListener; -import javax.swing.table.TableColumn; - -/** - * @author RajaramV - * - */ - -public class ScrollableJTable -{ - private JTable _table; - private JTableManager _tableManager; - private JTableModel _tableModel; - private JTableCellRenderer _cellRenderer = null; - private JScrollPane _tableScrollPane = null; - private boolean _sortFlag = false; - private boolean _moveFlag = false; - private boolean _firstDraw = false; - - private Dimension _columnHeaderPreferredSize = null; - - private Set _listenerSet = new HashSet(); - private int _tableRowSelectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION; - - /* - public ScrollableJTable(JTableManager tableManager) - { - _tableManager = tableManager; - _cellRenderer = new JTableCellRenderer(); - _cellRenderer.setTableManager(_tableManager); - } - */ - - public ScrollableJTable(JTableManager tableManager, Dimension columnHeaderPreferredSize) - { - _columnHeaderPreferredSize = columnHeaderPreferredSize; - - _tableManager = tableManager; - _cellRenderer = new JTableCellRenderer(); - _cellRenderer.setTableManager(_tableManager); - } - - public ScrollableJTable(JTableManager tableManager, int tableRowSelectionMode) - { - _tableManager = tableManager; - _cellRenderer = new JTableCellRenderer(); - _cellRenderer.setTableManager(_tableManager); - _tableRowSelectionMode = tableRowSelectionMode; - } - - - public JScrollPane getJScrollPane() - { - return _tableScrollPane; - } - - protected void setPreferredSizeForJScrollPane(Dimension dimension) - { - _tableScrollPane.setPreferredSize(dimension); - } - - protected Dimension getSizeForJScrollPane() - { - return _tableScrollPane.getSize(); - } - - protected void createTable(boolean firstDraw) - { - _firstDraw = firstDraw; - _tableModel = null; - Container scrollPaneContainer = null; - JScrollPane oldTableScrollPane = _tableScrollPane; - Dimension oldPreferredSizeForTableScrollPane = null; - Point oldPosition = null; - if(_tableScrollPane != null) - { - oldPreferredSizeForTableScrollPane = _tableScrollPane.getPreferredSize(); - oldPosition = _tableScrollPane.getViewport().getViewPosition(); - } - - String columnNamesToBeDisplayed[] = _tableManager.getColumnNamesThatAreCurrentlyDisplayed(); - - String rowData[][] = _tableManager.getDisplayRowDataArray(); - - int widthOfColumnsDisplayed[] = _tableManager.getWidthOfDisplayedColumns(); - - String[] alignmentOfColumnsDisplayed = _tableManager.getAlignmentOfDisplayedColumns(); - - _tableModel = new JTableModel(columnNamesToBeDisplayed, rowData, - widthOfColumnsDisplayed, alignmentOfColumnsDisplayed); - - _table = new JTable(_tableModel); - _table.setSelectionMode(_tableRowSelectionMode); - - int cnt=0; - Iterator it = _listenerSet.iterator(); - while(it.hasNext() && cnt++ < _listenerSet.size()) - { - addTableListeners((EventListener)it.next()); - } - - _table.setOpaque(false); - _table.setDefaultRenderer(Object.class, _cellRenderer); - - _table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - - setColumnListeners(); - - _tableScrollPane = new JScrollPane(_table); - - if(oldTableScrollPane !=null) - { - scrollPaneContainer = oldTableScrollPane.getParent(); - } - - if (scrollPaneContainer != null) - { - scrollPaneContainer.setVisible(false); - scrollPaneContainer.remove(oldTableScrollPane); - _tableScrollPane.setPreferredSize(oldPreferredSizeForTableScrollPane); - _tableScrollPane.getViewport().setViewPosition(oldPosition); - scrollPaneContainer.add(_tableScrollPane); - scrollPaneContainer.setVisible(true); - } - - sort(); - - for(int i=0; i < columnNamesToBeDisplayed.length; i++) - { - setWidth(columnNamesToBeDisplayed[i], widthOfColumnsDisplayed[i]); - } - } - //------------------------------------------------------------------------------ - protected void sort() - { - _tableManager.sort(true); - refreshAfterSort(); - } - //------------------------------------------------------------------------------ - - protected void setVerifyInputWhenFocusTarget(boolean verify) - { - _table.setVerifyInputWhenFocusTarget(verify); - } - - //------------------------------------------------------------------------------ - /** - * Select the rows that are passed in as argument and - * set the view port to the first selected row if setViewPort is true - */ - protected void selectRows(int rowIndices[], boolean setViewPort) - { - Color highLightBackGroundColor = Color.BLUE; - Color highLightForeGroundColor = Color.YELLOW; - for(int i=0; i < rowIndices.length; i++) - { - _table.getSelectionModel().addSelectionInterval(rowIndices[i], rowIndices[i]); - _table.setSelectionBackground(highLightBackGroundColor); - _table.setSelectionForeground(highLightForeGroundColor); - if(setViewPort) - { - Rectangle rect = _table.getCellRect(rowIndices[0], 0, true); - _tableScrollPane.getViewport().setViewPosition(rect.getLocation()); - } - } - } - - //------------------------------------------------------------------------------ - /** - * Select the rows that are passed in as argument and set the view port to the first selected row - */ - protected void selectRows(int rowIndices[]) - { - selectRows(rowIndices, true); - } - - //------------------------------------------------------------------------------ - /** - * Deselect the rows that are passed in as argument - */ - protected void deselectRows(int rowIndices[]) - { - for(int i=0; i < rowIndices.length; i++) - { - _table.getSelectionModel().removeSelectionInterval(rowIndices[i], rowIndices[i]); - } - } - - //------------------------------------------------------------------------------ - /** - * Deselect the previously selected rows - */ - protected void deselectRows(int initialRowToRemoveSelection, int finalRowToRemoveSelection) - { - _table.getSelectionModel().removeSelectionInterval(initialRowToRemoveSelection, finalRowToRemoveSelection); - } - - //------------------------------------------------------------------------------ - /** - * Select the rows from initialRowToSelect till finalRowToSelect - * that are passed in as argument and set the view port to the first selected row - */ - protected void selectRows(int initialRowToSelect, int finalRowToSelect) - { - selectRows( initialRowToSelect, finalRowToSelect, true); - } - - //------------------------------------------------------------------------------ - /** - * Select the rows from initialRowToSelect till finalRowToSelect - * that are passed in as argument and set the view port to the first selected row if setViewPort is true - */ - protected void selectRows(int initialRowToSelect, int finalRowToSelect, boolean setViewPort) - { - Color highLightBackGroundColor = Color.BLUE; - Color highLightForeGroundColor = Color.YELLOW; - _table.setRowSelectionInterval(initialRowToSelect, finalRowToSelect); - _table.setSelectionBackground(highLightBackGroundColor); - _table.setSelectionForeground(highLightForeGroundColor); - if(setViewPort) - { - Rectangle rect = _table.getCellRect(initialRowToSelect, 0, true); - _tableScrollPane.getViewport().setViewPosition(rect.getLocation()); - } - } - //------------------------------------------------------------------------------ - private void setColumnWidths() - { - //String header = "ScrollableJTable.setColumnWidths(); "; - //System.out.println(header + "called." ); - - if(_table!=null) - { - int numOfCols = _table.getColumnCount(); - for(int i=0; i < numOfCols; i++) - { - String columnName = _tableModel.getColumnName(i); - int columnWidth = _tableModel.getColumnWidth(columnName); - int columnIndex = _tableModel.getColumnNumber(columnName); - - TableColumn column = _table.getColumnModel().getColumn(columnIndex); - int prevWidth = column.getWidth(); - if(prevWidth != columnWidth) - { - column.setWidth(columnWidth); - } - } - } - } - - private void setWidth(String columnName, int columnWidth) - { - int columnIndex = _tableModel.getColumnNumber(columnName); - TableColumn column = _table.getColumnModel().getColumn(columnIndex); - _table.getColumnModel().getColumn(columnIndex).setHeaderRenderer(new JTableHeaderRenderer(_tableManager, _columnHeaderPreferredSize)); - column.setWidth(columnWidth); - column.setPreferredWidth(columnWidth); - } - - public void setColumnHeaderPreferredSize(Dimension columnHeaderPreferredSize) - { - _columnHeaderPreferredSize = columnHeaderPreferredSize; - } - - protected void addTableListeners(EventListener eventListener) - { - if(eventListener != null) - { - _listenerSet.add(eventListener); - Class[] classArray = eventListener.getClass().getInterfaces(); - - for(int i=0; i < classArray.length; i++) - { - String splitStr[] = classArray[i].toString().split(" "); - String className = splitStr[1]; - if(className.equals("javax.swing.event.ListSelectionListener")) - { - _table.getSelectionModel().addListSelectionListener((ListSelectionListener)eventListener); - } - else if(className.equals("java.awt.event.MouseListener")) - { - _table.addMouseListener((MouseListener)eventListener); - } - else if(className.equals("java.awt.event.MouseMotionListener")) - { - _table.addMouseMotionListener((MouseMotionListener)eventListener); - } - } - } - } - - protected void removeTableListener(EventListener eventListener) - { - if(eventListener != null) - { - Class[] classArray = eventListener.getClass().getInterfaces(); - for(int i=0; i < classArray.length; i++) - { - String splitStr[] = classArray[i].toString().split(" "); - String className = splitStr[1]; - if(className.equals("javax.swing.event.ListSelectionListener")) - { - _table.getSelectionModel().removeListSelectionListener((ListSelectionListener)eventListener); - } - else if(className.equals("java.awt.event.MouseListener")) - { - _table.removeMouseListener((MouseListener)eventListener); - } - else if(className.equals("java.awt.event.MouseMotionListener")) - { - _table.removeMouseMotionListener((MouseMotionListener)eventListener); - } - } - } - } - - protected int[] getSelectedRowIndices() - { - java.util.List rowsSelectedList = new ArrayList(); - ListSelectionModel jtableListSelectionModel = _table.getSelectionModel(); - int firstIndex = jtableListSelectionModel.getMinSelectionIndex(); - int lastIndex = jtableListSelectionModel.getMaxSelectionIndex(); - for(int i=firstIndex ; i<=lastIndex ; i++) - { - if(jtableListSelectionModel.isSelectedIndex(i)) - { - rowsSelectedList.add(new Integer(i).toString()); - } - } - int rowsSelected[] = new int[rowsSelectedList.size()]; - for(int i=0; i read(String rgbColorFilePath ) - { - String header = "RGBTextFileReader(). read() "; - - File rgbColorFile = null; - BufferedReader reader = null; - String line = null; - String[] tokenizedString = null; - String colorName = null; - rgbColorFile = new File( rgbColorFilePath ); - Map colorMap = new HashMap(); - - try - { - reader = new BufferedReader( new FileReader( rgbColorFile ) ); - line = reader.readLine(); //discard the first line - line = reader.readLine(); - while ( line != null ) - { - tokenizedString = StringParser.tokenize( line ); - colorName = getRGBColorName( tokenizedString ); - -// if the read in RGB color name exists in the ColorName table, then add to the _rgbColorMap - - Color color = new Color(Integer.parseInt( tokenizedString[ 0 ] ), - Integer.parseInt( tokenizedString[ 1 ] ), - Integer.parseInt( tokenizedString[ 2 ] ) ); - - - - colorMap.put( colorName.toUpperCase(), color ); - - // System.out.println(header + "colorName = " + colorName + " color = " + color); - - line = reader.readLine(); - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - - return colorMap; - } - // --------------------------------------------------------------------------------------------------- - - private String getRGBColorName( String[] tokenizedName ) - { - StringBuffer rgbColorName = new StringBuffer(); - - for ( int i = 3; i < tokenizedName.length;i++ ) - { - rgbColorName.append( tokenizedName[ i ] ); - - if ( i != ( tokenizedName.length - 1 ) ) - { - rgbColorName.append( " " ); - } - } - - return rgbColorName.toString(); - } - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/test/EnvTest.java b/cave/ohd.hseb.common/src/ohd/hseb/util/test/EnvTest.java deleted file mode 100644 index 3420a997eb..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/test/EnvTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package ohd.hseb.util.test; - -import java.util.Properties; - -import ohd.hseb.util.CodeTimer; - - -public class EnvTest -{ - - private long _envTotal = 0; - - - public static void main(String[] args) - { - EnvTest test = new EnvTest(); - CodeTimer timer = new CodeTimer(); - - - int iterationCount = 10; - long pureJavaTotalTime = 0; - - - timer.start(); - test.envTest(iterationCount); - timer.stop("intTest time for " + iterationCount + " iterations "); - - return; - - } - - - public void envTest(int iterationCount) - { - - Properties props = System.getProperties(); - - props.list(System.out); - } - - - - -} //end class EnvTest diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/test/JniTest.java b/cave/ohd.hseb.common/src/ohd/hseb/util/test/JniTest.java deleted file mode 100644 index 5025910f93..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/test/JniTest.java +++ /dev/null @@ -1,97 +0,0 @@ - -package ohd.hseb.util.test; - - -public class JniTest -{ - - static - { - try - { - System.loadLibrary("JniTest"); - } - catch(Throwable t) - { - System.out.println("Unable to loadLibrary."); - } - } - - public static void main(String[] args) - { - JniTest test = new JniTest(); - System.out.println("I am calling jniMethod from java"); - test.jniMethod("Chip", 10); - - int iterationCount = 10000; - long nativeTotalTime = 0; - long pureJavaTotalTime = 0; - - pureJavaTotalTime = test.jTest("Chip", 10, iterationCount); - - nativeTotalTime = test.nativeTest("Chip", 10, iterationCount); - - System.out.println("Java calling C native time = " + nativeTotalTime + " millis. for " + iterationCount + " iterations"); - System.out.println("Pure Java time = " + pureJavaTotalTime + " millis. for " + iterationCount + " iterations"); - - return; - - - } - - public long jTest(String name, int age, int iterationCount) - { - - - long totalTime = 0; - long time1 = 0; - long time2 = 0; - - time1 = System.currentTimeMillis(); - for (int i = 0; i < iterationCount; i++) - { - - jMethod(name, age); - - - } - time2 = System.currentTimeMillis(); - totalTime = (time2 - time1); - - return totalTime; - - } - - public long nativeTest(String name, int age, int iterationCount) - { - - - long totalTime = 0; - long time1 = 0; - long time2 = 0; - - time1 = System.currentTimeMillis(); - for (int i = 0; i < iterationCount; i++) - { - - jniMethod(name, age); - - - } - time2 = System.currentTimeMillis(); - totalTime = (time2 - time1); - - return totalTime; - - } - - public void jMethod(String name, int age) - { - System.out.println("My name = " + name + " and my age = " + age + "."); - } - - - public native void jniMethod(String name, int age); - - -} //end class Test diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/test/TimeTest.java b/cave/ohd.hseb.common/src/ohd/hseb/util/test/TimeTest.java deleted file mode 100644 index 516cf0617c..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/test/TimeTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.util.test; - -import junit.framework.TestCase; -import ohd.hseb.db.DbTimeHelper; - -public class TimeTest extends TestCase -{ - - - public void testTime() - { - long timeLong = 0; - String resultDateTimeString = null; - - String epochDateTimeString = "1970-01-01 00:00:00"; - String epochDateTimeToMinutesString = "1970-01-01 00:00"; - - String epochDateTimePlusOneMinuteString = "1970-01-01 00:01:00"; - - String epochDateTimeToMinutesPlusOneMinuteString = "1970-01-01 00:01"; - - - //first moment in epoch to seconds - timeLong = DbTimeHelper.getLongTimeFromDateTimeString(epochDateTimeString); - assertEquals(0, timeLong); - - resultDateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(0); - assertEquals(epochDateTimeString, resultDateTimeString); - - - //first moment in epoch to minutes - timeLong = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(epochDateTimeToMinutesString); - assertEquals(0, timeLong); - - - resultDateTimeString = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(timeLong); - assertEquals(epochDateTimeToMinutesString, resultDateTimeString); - - //one minute after the epoch, to seconds - timeLong = DbTimeHelper.getLongTimeFromDateTimeString(epochDateTimePlusOneMinuteString); - assertEquals(60000, timeLong); - - - //one minute after the epoch, in minutes - timeLong = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(epochDateTimeToMinutesPlusOneMinuteString); - assertEquals(60000, timeLong); - - - - return; - - - } - - - -} diff --git a/cave/ohd.hseb.common/src/ohd/hseb/util/test/TimingTest.java b/cave/ohd.hseb.common/src/ohd/hseb/util/test/TimingTest.java deleted file mode 100644 index d0025e9aa3..0000000000 --- a/cave/ohd.hseb.common/src/ohd/hseb/util/test/TimingTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package ohd.hseb.util.test; - -import ohd.hseb.util.CodeTimer; - -public class TimingTest -{ - - private long _longTotal = 0; - private double _doubleTotal = 0.0; - - - public static void main(String[] args) - { - TimingTest test = new TimingTest(); - CodeTimer timer = new CodeTimer(); - - int iterationCount = 1000000; - long pureJavaTotalTime = 0; - - //timer.start(); - //test.outputTest("Chip", 10, iterationCount); - // timer.stop("Pure Java output time for " + iterationCount + " iterations "); - - timer.start(); - test.intTest(iterationCount); - timer.stop("intTest time for " + iterationCount + " iterations "); - - - timer.start(); - test.floatTest(iterationCount); - timer.stop("floatTest time for " + iterationCount + " iterations "); - - - test.showResults(); - - return; - - - } - - public void showResults() - { - System.out.println("longTotal = " + _longTotal); - System.out.println("doubleTotal = " + _doubleTotal); - } - - - //--------test loop methods --------------------------------------------------------- - - //------------------------------------------------------------------- - - public void outputTest(String name, int age, int iterationCount) - { - - for (int i = 0; i < iterationCount; i++) - { - - outputMethod(name, age); - - } - - return; - - } - - //------------------------------------------------------------------- - - public void intTest(int iterationCount) - { - - int j = 0; - int k = 0; - - - for (int i = 0; i < iterationCount; i++) - { - j = i + 2; - - k = intComputeMethod(i, j); - _longTotal += k; - - } - - - - - return; - - } - - //------------------------------------------------------------------- - - public void floatTest(int iterationCount) - { - - - long totalTime = 0; - int j; - float k = 0f; - - - for (int i = 0; i < iterationCount; i++) - { - j = i + 2; - - k = floatComputeMethod( (float)i, (float)j ); - - _doubleTotal += k; - } - - - return; - - } - - - //------work methods -------------------------------------------- - - public void outputMethod(String name, int age) - { - System.out.println("My name = " + name + " and my age = " + age + "."); - } - - - public int intComputeMethod(int i, int j) - { - return i + j; - } - - - public float floatComputeMethod(float i, float j) - { - return i + j; - } - - -} //end class TimingTest diff --git a/cave/ohd.hseb.fcstservice/.classpath b/cave/ohd.hseb.fcstservice/.classpath deleted file mode 100644 index 1fa3e6803d..0000000000 --- a/cave/ohd.hseb.fcstservice/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/cave/ohd.hseb.fcstservice/.project b/cave/ohd.hseb.fcstservice/.project deleted file mode 100644 index 2e8fb09207..0000000000 --- a/cave/ohd.hseb.fcstservice/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.hseb.fcstservce - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/cave/ohd.hseb.fcstservice/.settings/org.eclipse.jdt.core.prefs b/cave/ohd.hseb.fcstservice/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 94981887a8..0000000000 --- a/cave/ohd.hseb.fcstservice/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -#Thu Mar 26 11:32:56 CDT 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cave/ohd.hseb.fcstservice/META-INF/MANIFEST.MF b/cave/ohd.hseb.fcstservice/META-INF/MANIFEST.MF deleted file mode 100644 index 236c80c6c5..0000000000 --- a/cave/ohd.hseb.fcstservice/META-INF/MANIFEST.MF +++ /dev/null @@ -1,16 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Forecast Service Plug-in -Bundle-SymbolicName: ohd.hseb.fcstservice;singleton:=true -Bundle-Version: 1.0.0.qualifier -Bundle-Activator: com.raytheon.fcstservice.activator.Activator -Require-Bundle: ohd.hseb.ihfsdb, - ohd.hseb.common, - org.eclipse.ui, - org.eclipse.core.runtime, - org.postgres, - com.raytheon.viz.core, - ohd.hseb.monitor -Bundle-ActivationPolicy: lazy -Bundle-Vendor: Raytheon -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/cave/ohd.hseb.fcstservice/build.properties b/cave/ohd.hseb.fcstservice/build.properties deleted file mode 100644 index 6e2f847b66..0000000000 --- a/cave/ohd.hseb.fcstservice/build.properties +++ /dev/null @@ -1,6 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - localization/ diff --git a/cave/ohd.hseb.fcstservice/localization/menus/fcstservice/baseFcstService.xml b/cave/ohd.hseb.fcstservice/localization/menus/fcstservice/baseFcstService.xml deleted file mode 100644 index 26314a19cd..0000000000 --- a/cave/ohd.hseb.fcstservice/localization/menus/fcstservice/baseFcstService.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/cave/ohd.hseb.fcstservice/localization/menus/fcstservice/index.xml b/cave/ohd.hseb.fcstservice/localization/menus/fcstservice/index.xml deleted file mode 100644 index 6b0ddac279..0000000000 --- a/cave/ohd.hseb.fcstservice/localization/menus/fcstservice/index.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - \ No newline at end of file diff --git a/cave/ohd.hseb.fcstservice/ohd.hseb.fcstservice.ecl b/cave/ohd.hseb.fcstservice/ohd.hseb.fcstservice.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cave/ohd.hseb.fcstservice/plugin.xml b/cave/ohd.hseb.fcstservice/plugin.xml deleted file mode 100644 index 6ecf5c603a..0000000000 --- a/cave/ohd.hseb.fcstservice/plugin.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - diff --git a/cave/ohd.hseb.fcstservice/scripts/start_fcstservice b/cave/ohd.hseb.fcstservice/scripts/start_fcstservice deleted file mode 100755 index d936e86157..0000000000 --- a/cave/ohd.hseb.fcstservice/scripts/start_fcstservice +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/ksh - -# File name: start_fcstservice -# Author : Ram Varma - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS -. $RUN_FROM_DIR/../../set_hydro_env - -#LHVM_LOG=$LHVM_LOG_DIR/fcstservice - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/fcstservice.jar - -#Execute Lhvm -xterm -T "fcstservice" -iconic \ --e $SYS_JAVA_DIR/bin/java ohd.hseb.fcstservice.LhvmApplicationWindow $JDBCURL & diff --git a/cave/ohd.hseb.fcstservice/src/com/raytheon/fcstservice/action/OpenFcstService.java b/cave/ohd.hseb.fcstservice/src/com/raytheon/fcstservice/action/OpenFcstService.java deleted file mode 100644 index 60621ae361..0000000000 --- a/cave/ohd.hseb.fcstservice/src/com/raytheon/fcstservice/action/OpenFcstService.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.fcstservice.action; - -import ohd.hseb.fcstservice.LhvmApplicationWindow; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPersistentPreferenceStore; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -import com.raytheon.monitor.activator.Activator; -import com.raytheon.monitor.preferences.PreferenceConstants; - -/** - * Performs actions needed to open the Forecast Services application. - * - *
- *
- * SOFTWARE HISTORY
- *
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * 	
- * 
- * 
- * - * @author mfegan - * @version 1.0 - */ - -public class OpenFcstService extends AbstractHandler { - - /** - * - */ - public OpenFcstService() { - super(); - } - - /* (non-Javadoc) - * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) - */ - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); - IPersistentPreferenceStore store = Activator.getDefault().getPreferenceStore(); - String databaseConnectionString = store.getString(PreferenceConstants.JDBC_URL); - - if (databaseConnectionString == null || databaseConnectionString.equals("")) { - MessageDialog.openError(shell, "Error Starting Forecast Services", "Database connection string not set, or incorrect, please verify River Apps settings on preference page."); - } else { - String[] args = {databaseConnectionString}; - LhvmApplicationWindow.main(args); -// MessageDialog.openInformation(shell, null, "Open Forecast Service is not yet implemented."); - } - return null; - } - -} diff --git a/cave/ohd.hseb.fcstservice/src/com/raytheon/fcstservice/activator/Activator.java b/cave/ohd.hseb.fcstservice/src/com/raytheon/fcstservice/activator/Activator.java deleted file mode 100644 index be9336027e..0000000000 --- a/cave/ohd.hseb.fcstservice/src/com/raytheon/fcstservice/activator/Activator.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.fcstservice.activator; - -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -/** - * The activator class controls the plug-in life cycle - * - *
- *
- * SOFTWARE HISTORY
- *
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * 	
- * 
- * 
- * - * @author mfegan - * @version 1.0 - */ - -public class Activator extends AbstractUIPlugin { - - // The plug-in ID - public static final String PLUGIN_ID = "ohd.hseb.sshp"; - - // The shared instance - private static Activator plugin; - - /** - * The constructor - */ - public Activator() { - super(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); - } - - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } -} diff --git a/cave/ohd.hseb.ihfsdb/.classpath b/cave/ohd.hseb.ihfsdb/.classpath deleted file mode 100644 index 35de0c16be..0000000000 --- a/cave/ohd.hseb.ihfsdb/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/cave/ohd.hseb.ihfsdb/.project b/cave/ohd.hseb.ihfsdb/.project deleted file mode 100644 index 687e9281df..0000000000 --- a/cave/ohd.hseb.ihfsdb/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - ohd.hseb.ihfsdb - - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.pde.PluginNature - - diff --git a/cave/ohd.hseb.ihfsdb/.settings/org.eclipse.jdt.core.prefs b/cave/ohd.hseb.ihfsdb/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 0a81398afd..0000000000 --- a/cave/ohd.hseb.ihfsdb/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -#Thu Mar 26 11:32:39 CDT 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cave/ohd.hseb.ihfsdb/META-INF/MANIFEST.MF b/cave/ohd.hseb.ihfsdb/META-INF/MANIFEST.MF deleted file mode 100644 index 75854cbbb7..0000000000 --- a/cave/ohd.hseb.ihfsdb/META-INF/MANIFEST.MF +++ /dev/null @@ -1,12 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: IHFSDB Plug-in -Bundle-SymbolicName: ohd.hseb.ihfsdb -Bundle-Version: 1.0.0.qualifier -Bundle-Vendor: Raytheon -Export-Package: ohd.hseb.db, - ohd.hseb.ihfsdb.generated -Bundle-ClassPath: dist/ihfsdb.jar, - . -Require-Bundle: org.postgres -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/cave/ohd.hseb.ihfsdb/PreferredTableNames.txt b/cave/ohd.hseb.ihfsdb/PreferredTableNames.txt deleted file mode 100644 index 689dd6844a..0000000000 --- a/cave/ohd.hseb.ihfsdb/PreferredTableNames.txt +++ /dev/null @@ -1,195 +0,0 @@ -AdjustFactor -Admin -Agricultural -AlertAlarmVal -ArealFcst -ArealObs -Benchmark -City -ColorName -ColorOverlay -ColorValue -CommentValue -Contacts -ContingencyValue -CoopComms -CoopRecip -CoopSpons -Counties -CountyTransmit -Countynum -Crest -CurPC -CurPP -DPARadar -DailyPP -DamTypes -DataLimits -Datum -Dcp -DcpOwner -Descrip -DefiningIssueCriteria -Discharge -DpaAdapt -Eligzon -Evaporation -FcstDischarge -FcstGenMethod -FcstHeight -FcstHorizon -FcstOther -FcstPrecip -FcstPtDeterm -FcstPtESP -FcstPtService -FcstTemperature -FcstPtWatSup -FcstType -FishCount -Flood -FloodTs -Floodcat -Floodstmt -FlowType -FpPrevProd -FpPrevProdPractice -FrequencyUpdate -Gage -GageMaint -GageOwner -GageType -GateDam -GeoArea -Ground -Height -HgStation -HourlyPC -HourlyPP -Hsa -HydrologicMethod -Ice -IngestFilter -LWstmt -Lake -LatestObsValue -Lightning -LineSegs -LocArea -LocDataLimits -LocExtAgency -LocImage -Location -Lowwater -Moisture -MonthlyValues -NWRTransmitter -Network -OFSDataTrans -OFSStnTrans -Observer -OfficeNotes -PairedValue -PerfLog -PointDataPresets -PostProcessor -Power -Pressure -ProcValue -ProductLink -Proximity -PseudoGageVal -Pub -PurgeDynData -PurgeProduct -RequiredPeriod -RWBiasDyn -RWBiasStat -RWParams -RWPrefs -RWRadarResult -RWResult -RadarLoc -RadarResp -Radiation -Rating -RatingShift -RawPC -RawPP -RawPother -Refer -RejectedData -ResOwner -Rescap -Reservoir -ReservoirModel -Rfc -RiverMonGroup -RiverMonLocation -RiverStatus -Riverstat -RoutingMethod -RpfFcstGroup -RpfFcstPoint -RpfParams -S3PostAnalParams -S3PostAnalPrefs -SacSmaParams -SacSmaState -ServiceTableView -ServiceType -ShefDur -ShefEx -ShefPETrans -ShefPe -ShefProb -ShefQc -ShefTs -Snow -SnowMethod -SshpConfig -State -StnClass -Telem -TelmOwner -TelmPayor -TelmType -Temperature -TextProduct -TimeZone -UnitGraph -UnkStn -UnkStnValue -UserPrefs -VTECaction -VTECcause -VTECevent -VTECphenom -VTECpractice -VTECrecord -VTECsever -VTECsignif -WaterQuality -WatSupCoordAgency -WatSupMethod -WatSupCriterion -WatSupRespAgency -Weather -Wind -YUnique -Zonenum -AgencyOfficeUnique -CountyInfo -FpInfo -HvStation -HwStages -LocClass -LocPDC -LocRiverMon -LocTransmit -LocView -LocWfo -PrevProd -StatProf -StationList -ZoneInfo diff --git a/cave/ohd.hseb.ihfsdb/PreferredTableNames.txt.temp b/cave/ohd.hseb.ihfsdb/PreferredTableNames.txt.temp deleted file mode 100644 index c5b38fc5bd..0000000000 --- a/cave/ohd.hseb.ihfsdb/PreferredTableNames.txt.temp +++ /dev/null @@ -1,179 +0,0 @@ -/fs/hseb/ob81/ohd/whfs/schema/IHFS/tables: -AdjustFactor.t -Admin.t -Agricultural.t -AlertAlarmVal.t -ArealFcst.t -ArealObs.t -Benchmark.t -City.t -ColorName.t -ColorOverlay.t -ColorValue.t -CommentValue.t -Contacts.t -ContingencyValue.t -CoopComms.t -CoopRecip.t -CoopSpons.t -Counties.t -CountyTransmit.t -Countynum.t -Crest.t -CurPC.t -CurPP.t -DPARadar.t -DailyPP.t -DamTypes.t -DataLimits.t -Datum.t -Dcp.t -DcpOwner.t -Descrip.t -Discharge.t -DpaAdapt.t -Eligzon.t -Evaporation.t -FcstDischarge.t -FcstHeight.t -FcstOther.t -FcstPrecip.t -FcstTemperature.t -FishCount.t -Flood.t -FloodTs.t -Floodcat.t -Floodstmt.t -FpPrevProd.t -FpPrevProdPractice.t -Gage.t -GageMaint.t -GageOwner.t -GageType.t -GateDam.t -GeoArea.t -Ground.t -Height.t -HgStation.t -HourlyPC.t -HourlyPP.t -Hsa.t -Ice.t -IngestFilter.t -LWstmt.t -Lake.t -LatestObsValue.t -Lightning.t -LineSegs.t -LocArea.t -LocDataLimits.t -LocExtAgency.t -LocImage.t -Location.t -Lowwater.t -Moisture.t -MonthlyValues.t -NWRTransmitter.t -Network.t -OFSDataTrans.t -OFSStnTrans.t -Observer.t -OfficeNotes.t -PairedValue.t -PerfLog.t -PointDataPresets.t -Power.t -Pressure.t -ProcValue.t -ProductLink.t -Proximity.t -PseudoGageVal.t -Pub.t -PurgeDynData.t -PurgeProduct.t -RCS -RWBiasDyn.t -RWBiasStat.t -RWParams.t -RWPrefs.t -RWRadarResult.t -RWResult.t -RadarLoc.t -RadarResp.t -Radiation.t -Rating.t -RatingShift.t -RawPC.t -RawPP.t -RawPother.t -Refer.t -RejectedData.t -ResOwner.t -Rescap.t -Reservoir.t -Rfc.t -RiverMonGroup.t -RiverMonLocation.t -RiverStatus.t -Riverstat.t -RpfFcstGroup.t -RpfFcstPoint.t -RpfParams.t -S3PostAnalParams.t -S3PostAnalPrefs.t -SacSmaParams.t -SacSmaState.t -ShefDur.t -ShefEx.t -ShefPETrans.t -ShefPe.t -ShefProb.t -ShefQc.t -ShefTs.t -Snow.t -SshpConfig.t -State.t -StnClass.t -Telem.t -TelmOwner.t -TelmPayor.t -TelmType.t -Temperature.t -TextProduct.t -TimeZone.t -UnitGraph.t -UnkStn.t -UnkStnValue.t -UserPrefs.t -VTECaction.t -VTECcause.t -VTECevent.t -VTECphenom.t -VTECpractice.t -VTECrecord.t -VTECsever.t -VTECsignif.t -WaterQuality.t -Weather.t -Wfo.t -Wind.t -YUnique.t -Zonenum.t - -/fs/hseb/ob81/ohd/whfs/schema/IHFS/views: -AgencyOfficeUnique.t -CountyInfo.t -FpInfo.t -HvStation.t -HwStages.t -LocClass.t -LocPDC.t -LocRiverMon.t -LocTransmit.t -LocView.t -LocWfo.t -PrevProd.t -RCS -StatProf.t -StationList.t -ZoneInfo.t diff --git a/cave/ohd.hseb.ihfsdb/REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar b/cave/ohd.hseb.ihfsdb/REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar deleted file mode 100644 index a9156e958b..0000000000 Binary files a/cave/ohd.hseb.ihfsdb/REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar and /dev/null differ diff --git a/cave/ohd.hseb.ihfsdb/build.properties b/cave/ohd.hseb.ihfsdb/build.properties deleted file mode 100644 index b7a1edcd31..0000000000 --- a/cave/ohd.hseb.ihfsdb/build.properties +++ /dev/null @@ -1,5 +0,0 @@ -source.. = src/ -bin.includes = META-INF/,\ - .,\ - dist/ihfsdb.jar,\ - REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar diff --git a/cave/ohd.hseb.ihfsdb/build.xml b/cave/ohd.hseb.ihfsdb/build.xml deleted file mode 100644 index 2cf757138c..0000000000 --- a/cave/ohd.hseb.ihfsdb/build.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cave/ohd.hseb.ihfsdb/dist/ihfsdb.jar b/cave/ohd.hseb.ihfsdb/dist/ihfsdb.jar deleted file mode 100644 index c5bb671143..0000000000 Binary files a/cave/ohd.hseb.ihfsdb/dist/ihfsdb.jar and /dev/null differ diff --git a/cave/ohd.hseb.ihfsdb/ohd.hseb.ihfsdb.ecl b/cave/ohd.hseb.ihfsdb/ohd.hseb.ihfsdb.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/Database.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/Database.java deleted file mode 100755 index 0f10f9a860..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/Database.java +++ /dev/null @@ -1,251 +0,0 @@ -package ohd.hseb.db; - -import java.sql.*; - -/** - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 13, 2000             R. Erb     Original Creation
- * Aug 06, 2003             C. Gobs    Class Overhaul
- * May 13, 2011  8079       jnjanga    added method newStmtForScrollableRset()
- * 
- * 
- * - * @author R. Erb - */ - -public class Database { - // ***************************************************************************** - // Private data - // ***************************************************************************** - - // the jdbc url is passed in through the connectTo method - private String _urlConnectionString = null; - - // define data types to be used to connect to the database - // and store the SQL statement - private Connection _conn = null; - - private Statement _stmt = null; - - private String _defaultDriverClassName = "org.postgresql.Driver"; - - private String _driverClassName = _defaultDriverClassName; - - // private String[] _driverNameArray = {"org.postgresql.Driver", - // "com.informix.jdbc.IfxDriver" }; - private String[] _driverNameArray = { "org.postgresql.Driver" }; - - private DbType _dbType = DbType.PostgreSQL; - - // private DbType _dbType = DbType.Informix; - - // ***************************************************************************** - // IhfsDatabase() - No argument constructor to initialize data - // ***************************************************************************** - public Database() { - - } - - // ***************************************************************************** - - public Database(String connectionString) { - connect(connectionString); - } - - // ***************************************************************************** - - public void setDriverClassName(String driverClassName) { - _driverClassName = driverClassName; - - if (_driverClassName.indexOf("informix") > 0) { - setDbType(DbType.Informix); - } else if (_driverClassName.indexOf("postgresql") > 0) { - setDbType(DbType.PostgreSQL); - } - return; - } - - // ***************************************************************************** - - public String getDriverClassName() { - return _driverClassName; - } - - // ***************************************************************************** - - public void setDbType(DbType dbType) { - _dbType = dbType; - } - - // ***************************************************************************** - - public DbType getDbType() { - return _dbType; - } - - // --------------------------------------------------------------------------------- - - private void loadDbDriver(String driverClassName) { - // Load the JDBC driver - try { - Class.forName(driverClassName); - } catch (Exception e) { - e.printStackTrace(System.err); - System.err.println("ERROR: failed to load JDBC driver named " - + driverClassName + "\n Shutting down."); - System.exit(1); - } - - } - - // --------------------------------------------------------------------------------- - - // --------------------------------------------------------------------------------- - - public void connect(String connectionString) { - _urlConnectionString = connectionString; - - loadDbDriver(getDriverClassName()); - - // Establish a connection to the database and create a statement - try { - _conn = DriverManager.getConnection(_urlConnectionString); - _stmt = _conn.createStatement(); - } catch (SQLException e) { - e.printStackTrace(); - System.err.println("ERROR: failed to connect!"); - System.err.println("ERROR: " + e.getMessage()); - // chip change - System.err.println("ERROR: error code = " + e.getErrorCode()); - System.err.println("ERROR: SQL STATE = " + e.getSQLState()); - - System.exit(1); - } - - } // end of method connectTo - - // ***************************************************************************** - - public void connectWithDriverSearch(String connectionString) { - _urlConnectionString = connectionString; - - try { - connectWithDriverAttempts(0); - } catch (SQLException e) { - e.printStackTrace(); - System.err.println("ERROR: failed to connect!"); - System.err.println("ERROR: " + e.getMessage()); - System.err.println("ERROR: error code = " + e.getErrorCode()); - System.err.println("ERROR: SQL STATE = " + e.getSQLState()); - - System.exit(1); - } - - return; - - } - - // ***************************************************************************** - - private void connectWithDriverAttempts(int attemptCount) - throws SQLException { - - try { - String driverClassName = _driverNameArray[attemptCount]; - setDriverClassName(driverClassName); - loadDbDriver(driverClassName); - - // System.out.println("attempting to load driver " + - // driverClassName); - attemptCount++; // this must occur after the use of attempCount - // above - - _conn = DriverManager.getConnection(_urlConnectionString); - _stmt = _conn.createStatement(); - } catch (SQLException e) { - if (attemptCount < _driverNameArray.length) { - connectWithDriverAttempts(attemptCount); - } else { - throw e; - } - } - - return; - } - - // ***************************************************************************** - // getConnection() - // ***************************************************************************** - public Connection getConnection() { - - return _conn; - } - - // ***************************************************************************** - // getStatement() - // ***************************************************************************** - public Statement getStatement() { - return _stmt; - } - - public Statement newStmtForScrollableRset() throws SQLException { - return getConnection().createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - } - - // ***************************************************************************** - // getDatabaseName() - // ***************************************************************************** - public String getDatabaseName() { - int lastSlashIndex = _urlConnectionString.lastIndexOf("/"); - - String dbName = "Unknown"; - - if (lastSlashIndex > -1) { - String slashSubString = _urlConnectionString - .substring(lastSlashIndex); - int colonIndex = slashSubString.indexOf(":"); - - if (colonIndex > -1) { - dbName = slashSubString.substring(1, colonIndex); - } else { - int qIndex = slashSubString.indexOf("?"); - if (qIndex > -1) { - dbName = slashSubString.substring(1, qIndex); - } - } - - } - - return dbName; - - } // end of method getDatabaseName - - // ***************************************************************************** - // disconnectFrom() - // ***************************************************************************** - public void disconnect() { - // Close the statement and connection to the database - try { - _stmt.close(); - _conn.close(); - - } catch (SQLException e) { - System.err.println("ERROR: failed to close the connection!"); - System.err.println("ERROR: " + e.getMessage()); - System.err.println("ERROR: error code = " + e.getErrorCode()); - e.printStackTrace(); - System.err.println("Shutting Down."); - System.exit(1); - } catch (NullPointerException e) { - System.err.println("ERROR: " + e.getMessage()); - e.printStackTrace(); - } - } // end of method disconnect - -} // end of class Database diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbArrayColumn.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbArrayColumn.java deleted file mode 100644 index 5389ccbdd3..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbArrayColumn.java +++ /dev/null @@ -1,86 +0,0 @@ -package ohd.hseb.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; - -public class DbArrayColumn implements java.sql.Array { - - private String _arrayString = null; - - private double[][] _array = null; - - public DbArrayColumn(String arrayString) { - _arrayString = arrayString; - double[][] newArray = { { 1.0, 2.0 }, { 2.0, 8.0 }, { 3.0, 27.0 } }; - _array = newArray; - } - - public Object getArray() throws SQLException { - - return _array; - - } - - public Object getArray(Map> arg0) throws SQLException { - return _array; - } - - public Object getArray(long index, int count) throws SQLException { - return _array[(int) index][0]; - } - - public Object getArray(long arg0, int arg1, Map> arg2) - throws SQLException { - return _array; - - } - - public int getBaseType() throws SQLException { - - return java.sql.Types.DOUBLE; - } - - public String getBaseTypeName() throws SQLException { - return "double[]"; - } - - @Override - public String toString() { - return _arrayString; - } - - public ResultSet getResultSet() throws SQLException { - // TODO Auto-generated method stub - return null; - } - - public ResultSet getResultSet(Map> arg0) - throws SQLException { - // TODO Auto-generated method stub - return null; - } - - public ResultSet getResultSet(long index, int count) throws SQLException { - // TODO Auto-generated method stub - return null; - } - - public ResultSet getResultSet(long arg0, int arg1, - Map> arg2) throws SQLException { - // TODO Auto-generated method stub - return null; - } - - /* - * (non-Javadoc) - * - * @see java.sql.Array#free() - */ - @Override - public void free() throws SQLException { - // TODO Auto-generated method stub - - } - -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbConnectionHelper.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbConnectionHelper.java deleted file mode 100755 index 3b65f6d3e5..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbConnectionHelper.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Created on Oct 8, 2003 - * - * - */ -package ohd.hseb.db; - - -/** - * @author Chip Gobs - * - * - */ -public class DbConnectionHelper -{ - String _baseConnectionString = null; - String _propertiesFilePath = null; - -// ------------------------------------------------------------------------ - - public DbConnectionHelper(String baseConnectionString) - { - _baseConnectionString = baseConnectionString; - } - -// ------------------------------------------------------------------------ - - public DbConnectionHelper(String baseConnectionString, String propertiesFilePath) - { - _baseConnectionString = baseConnectionString; - _propertiesFilePath = propertiesFilePath; - } -// ------------------------------------------------------------------------ - public String getConnectionString() - { - String connectionString = _baseConnectionString; - - - return connectionString; - } //end getConnectionString - - // ------------------------------------------------------------------------ -/* private String getConnectionStringByGui() - { - String connectionStringBase = _baseConnectionString; - - String connectionString = null; - - - PasswordDialog dialog = new PasswordDialog(); - - String message = "Enter your user name and password for the HP"; - boolean success = dialog.requestPasswordByDialog(message); - - String userName = dialog.getUserName(); - String password = dialog.getPassword(); - - connectionString = connectionStringBase + - "user="+ userName + - ";password=" + password +";"; - - - return connectionString; - } //end getConnectionStringByGui - - // ------------------------------------------------------------------------ - - private String getDecryptedConnectionString() - { - // - //String url ="jdbc:informix-sqli:" + "//ds1:" + - // "1530/hd_ob3ounx:" + "informixserver=ONLINE"; - - String connectionURLPart = _baseConnectionString; - String connectionString = null; - - String encryptedUserName = null; - String encryptedPassword = null; - - String userName = null; - String password = null; - - Properties props = new Properties(); - try - { - props.load(new FileInputStream(_propertiesFilePath)); - encryptedUserName = props.getProperty("un"); - encryptedPassword = props.getProperty("pw"); - - userName = Cryptor.decrypt(encryptedUserName); - password = Cryptor.decrypt(encryptedPassword); - - connectionString = connectionURLPart + - "user="+ userName + - ";password=" + password +";"; - - } - catch (FileNotFoundException e) - { - //System.err.println("You need a properties file named Data.props"); - //e.printStackTrace(); - } - catch(IOException e) - { - //e.printStackTrace(); - } - - return connectionString; - } //end getDecryptedConnectionString() -*/ - -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbRecord.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbRecord.java deleted file mode 100755 index 404f1d78e3..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Created on Aug 6, 2003 - * - * - */ -package ohd.hseb.db; - -import java.sql.*; - -/** - * @author Chip Gobs - * - * This class is the abstract superclass of all of the xxxRecord classes. - * xxx represents the name of the table or view. This class - * provides some utility methods and acts as a nice way of unifying all of the - * subclasses under one umbrella. - */ -public abstract class DbRecord -{ - public abstract String toString(); - - //------------------------------------------------------- - - public Timestamp copyTimestamp(Timestamp origTimestamp) - { - Timestamp newTimestamp = new Timestamp(origTimestamp.getTime()); - return newTimestamp; - } - - // ------------------------------------------------------- - - public java.sql.Date copyDate(java.sql.Date origDate) - { - java.sql.Date newDate = new java.sql.Date(origDate.getTime()); - return newDate; - } - - // ------------------------------------------------------- - - public String getStringFromTimestamp(Timestamp timestamp) - { - return DbTimeHelper.getStringFromTimestamp(timestamp); - } -// ------------------------------------------------------- - - public String getStringFromDate(java.sql.Date date) - { - - return DbTimeHelper.getStringFromDate(date); - } - //--------------------------------------------------------- - public long getLongTimeFromDateTimeString(String timeString) - { - return DbTimeHelper.getLongTimeFromDateTimeString(timeString); - } - //------------------------------------------------------- - - public String getDateTimeStringFromLongTime(long time) - { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } -//------------------------------------------------------- - - public String getDateStringFromLongTime(long time) - { - return DbTimeHelper.getDateStringFromLongTime(time); - - } - //------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbTable.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbTable.java deleted file mode 100755 index 18d4667a4f..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbTable.java +++ /dev/null @@ -1,716 +0,0 @@ -/* - * Created on Aug 6, 2003 - * Chip Gobs - */ -package ohd.hseb.db; - -import java.sql.*; -import java.util.*; -import java.util.Date; - -/** - * This class is the abstract super class of all generated subclasses. It - * provides some common methods that do not need to be implemented by each - * generated class - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------------------------
- * May 13, 2011  8079       jnjanga    added method executeQuery(Statement,String)
- *                                     for running arbitrary SQL queries.
- * 
- * 
- * - * @author Chip Gobs - */ -public abstract class DbTable { - private String _tableName; - - private Database _database; - - public abstract List select(String where) throws SQLException; - - protected DbTable(Database database) { - _database = database; - } - - protected Database getDatabase() { - return _database; - } - - protected Statement getStatement() { - return _database.getStatement(); - } - - protected Connection getConnection() { - return _database.getConnection(); - } - - protected void setDatabase(Database database) { - _database = database; - } - - public String getTableName() { - return _tableName; - } - - public void setTableName(String tableName) { - _tableName = tableName; - } - - // ***************************************************************************** - // printRecordList() - this method is called with a List of CurPrecipRecord - // objects and prints them to standard out - // ***************************************************************************** - - public void printRecordList(List recordList) { - DbRecord record = null; - - for (int ctr = 0; ctr < recordList.size(); ctr++) { - record = (DbRecord) recordList.get(ctr); - System.out.println(record.toString()); - } - - System.out.println(recordList.size() - + " record(s) returned from printRecord. "); - - } // end of printRecordList method - - // --------------------------------------------------------- - public String getStringFromDate(java.sql.Date date) { - return DbTimeHelper.getStringFromDate(date); - } - - // ------------------------------------------------------- - public long getLongTimeFromDateTimeString(String timeString) { - return DbTimeHelper.getLongTimeFromDateTimeString(timeString); - } - - // --------------------------------------------------------- - public long getLongTimeFromDateString(String timeString) { - return DbTimeHelper.getLongTimeFromDateString(timeString); - } - - // -------------------------------------------------------- - public long getLongTimeFromTimeToSecondsString(String timeString) { - return DbTimeHelper.getLongTimeFromTimeToSecondsString(timeString); - } - - // --------------------------------------------------------- - - public String getDateTimeStringFromLongTime(long time) { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } - - // --------------------------------------------------------- - public String getDateStringFromLongTime(long time) { - return DbTimeHelper.getDateStringFromLongTime(time); - } - - // --------------------------------------------------------- - - public String getStringFromTimestamp(Timestamp timestamp) { - return DbTimeHelper.getStringFromTimestamp(timestamp); - } - - // --------------------------------------------------------- - - public String getTrimmedString(String string) { - if (string != null) { - string = string.trim(); - } - - return string; - } - - // ***************************************************************************** - // getTimeStampFromString() is used to convert DateTime year to sec - // variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the - // database - // already stores it as. - // ***************************************************************************** - public Date getDateTimeFromString(String timeString) { - return DbTimeHelper.getDateTimeFromString(timeString); - } - - // ***************************************************************************** - // getDateFromString() is used to convert Date year to day variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the - // database - // already stores it as. - // ***************************************************************************** - public Date getDateFromString(String timeString) { - return DbTimeHelper.getDateFromString(timeString); - } - - // ***************************************************************************** - // selectCount returns the count of records in the database - // that meet the select criteria in the where clause. - // ***************************************************************************** - - public int selectCount(String where) throws SQLException { - int recordCount = -1; - - // Create the SQL statement and issue it - - // construct the select statment - String selectStatement = "SELECT count(*) FROM " + getTableName() + " " - + where; - - // get the result set back from the query to the database - ResultSet rs = _database.getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) { - // store the recordCount - recordCount = rs.getInt(1); - } - // Close the result set - rs.close(); - - // return a List which holds the CurPrecipRecord objects - return recordCount; - - } // end of selectCount method - - // ------------------------------------------------------------------------------------------- - - public String getString(ResultSet rs, int index) throws SQLException { - String value = getTrimmedString(rs.getString(index)); - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public long getDate(ResultSet rs, int index) throws SQLException { - long date = getNullDate(); - String stringValue = rs.getString(index); - - if (!rs.wasNull()) { - date = getLongTimeFromDateString(stringValue); - } else { - date = getNullDate(); - } - - return date; - } - - // ------------------------------------------------------------------------------------------- - - public long getTimeStamp(ResultSet rs, int index) throws SQLException { - long datetime = getNullTimeStamp(); - String value = rs.getString(index); - - if (!rs.wasNull()) { - datetime = getLongTimeFromDateTimeString(value); - } - - return datetime; - } - - // ------------------------------------------------------------------------------------------- - - public long getTime(ResultSet rs, int index) throws SQLException { - long time = getNullTime(); - String value = rs.getString(index); - - if (!rs.wasNull()) { - time = getLongTimeFromTimeToSecondsString(value); - } - - return time; - } - - // ------------------------------------------------------------------------------------------- - - public double getDouble(ResultSet rs, int index) throws SQLException { - double value = rs.getDouble(index); - - if (rs.wasNull()) { - value = getNullDouble(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public float getFloat(ResultSet rs, int index) throws SQLException { - float value = rs.getFloat(index); - - if (rs.wasNull()) { - value = getNullFloat(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public float getReal(ResultSet rs, int index) throws SQLException { - float value = rs.getFloat(index); - - if (rs.wasNull()) { - value = getNullReal(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public int getInt(ResultSet rs, int index) throws SQLException { - int value = rs.getInt(index); - - if (rs.wasNull()) { - value = getNullInt(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - public long getLong(ResultSet rs, int index) throws SQLException { - long value = rs.getLong(index); - - if (rs.wasNull()) { - value = getNullLong(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - public short getShort(ResultSet rs, int index) throws SQLException { - short value = rs.getShort(index); - - if (rs.wasNull()) { - value = getNullShort(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public byte[] getBytes(ResultSet rs, int index) throws SQLException { - byte[] value = rs.getBytes(index); - - if (rs.wasNull()) { - value = getNullBytes(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - public void setDateOld(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.DATE); - } else { - statement.setString(index, getDateStringFromLongTime(value)); - } - - return; - } - - public void setDate(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.DATE); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - cal.setTimeInMillis(value); - statement.setDate(index, new java.sql.Date(value), cal); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setTimeStamp(PreparedStatement statement, int index, long value) - throws SQLException { - - // passes unit test - // setTimeStampByString(statement, index, value); - - // passes unit test - // setTimeStampByValueWithCalendar(statement, index, value); - - // passes unit test - setTimeStampByValueWithCalendarButWithoutSettingCalendarTime(statement, - index, value); - - // Bad one below fails JUnit test - - // setTimeStampByValueWithoutCalendar(statement, index, value); - } - - private void setTimeStampByString(PreparedStatement statement, int index, - long value) throws SQLException { - String header = "DbTable.setTimeStampByString(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - String dateTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(value); - Timestamp timestamp = Timestamp.valueOf(dateTimeString); - - System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp); - } - - return; - } - - private void setTimeStampByValueWithoutCalendar( - PreparedStatement statement, int index, long value) - throws SQLException { - String header = "DbTable.setTimeStampByValueWithoutCalendar(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - Timestamp timestamp = new Timestamp(value); - System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp); - } - - return; - } - - private void setTimeStampByValueWithCalendar(PreparedStatement statement, - int index, long value) throws SQLException { - String header = "DbTable.setTimeStampByValueWithCalendar(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - cal.setTimeInMillis(value); - Timestamp timestamp = new Timestamp(value); - - // System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp, cal); - - } - - return; - } - - private void setTimeStampByValueWithCalendarButWithoutSettingCalendarTime( - PreparedStatement statement, int index, long value) - throws SQLException { - String header = "DbTable.setTimeStampByValueWithCalendarButWithoutSettingCalendarTime(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - Timestamp timestamp = new Timestamp(value); - - // System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp, cal); - - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setTime(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.TIME); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - - cal.setTimeInMillis(value); - - java.sql.Time time = new java.sql.Time(value); - - statement.setTime(index, time, cal); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setString(PreparedStatement statement, int index, String value) - throws SQLException { - statement.setString(index, value); - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setArray(PreparedStatement statement, int index, String value) - throws SQLException { - // statement.setString(index, value); - - DbArrayColumn arrayColumn = new DbArrayColumn(stripSingleQuotes(value)); - - statement.setArray(index, arrayColumn); - return; - } - - private String stripSingleQuotes(String origString) { - int length = origString.length(); - int indexNotToInclude = length - 1; - - String newString = origString.substring(1, indexNotToInclude); - - return newString; - } - - // ------------------------------------------------------------------------------------------- - - public void setBytes(PreparedStatement statement, int index, byte[] value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.LONGVARBINARY); - } else { - statement.setBytes(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setInt(PreparedStatement statement, int index, int value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.INTEGER); - } else { - statement.setInt(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - public void setLong(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.BIGINT); - } else { - statement.setLong(index, value); - } - return; - } - - // ------------------------------------------------------------------------------------------- - public void setShort(PreparedStatement statement, int index, short value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.SMALLINT); - } else { - statement.setShort(index, value); - } - return; - } - - // ------------------------------------------------------------------------------------------- - public void setDouble(PreparedStatement statement, int index, double value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.DOUBLE); - } else { - statement.setDouble(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - public void setFloat(PreparedStatement statement, int index, float value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.FLOAT); - } else { - statement.setFloat(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - public void setReal(PreparedStatement statement, int index, float value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.REAL); - } else { - statement.setFloat(index, value); // intentionally set to setFloat, - // since setReal does not exist - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(String value) { - boolean result = false; - - if (value == null) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(byte[] value) { - boolean result = false; - - if (value == null) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - public static boolean isNull(long value) { - boolean result = false; - - if (value == getNullLong()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - public static boolean isNull(int value) { - boolean result = false; - - if (value == getNullInt()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(short value) { - boolean result = false; - - if (value == getNullShort()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(double value) { - boolean result = false; - - if (value == getNullDouble()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(float value) { - boolean result = false; - - if (value == getNullFloat()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------------- - - public static int getNullInt() { - return Integer.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static long getNullLong() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - public static short getNullShort() { - return Short.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static float getNullFloat() { - return -Float.MAX_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static float getNullReal() { - return -Float.MAX_VALUE; // real maps to float - } - - // ------------------------------------------------------------------------------------------- - - public static double getNullDouble() { - return -Double.MAX_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static String getNullString() { - return null; - } - - // ------------------------------------------------------------------------------------------- - - public static long getNullDate() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - public static long getNullTimeStamp() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static long getNullTime() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - public static byte[] getNullBytes() { - return null; - - } - - public ResultSet executeQuery(Statement stmt, String sql) - throws SQLException { - return stmt.executeQuery(sql); - } - -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbTimeHelper.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbTimeHelper.java deleted file mode 100755 index 3f58bfe6f3..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbTimeHelper.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Created on Sep 16, 2003 - * - * - */ -package ohd.hseb.db; - -import java.util.*; -import java.util.Date; -import java.text.*; -import java.sql.*; - -/** - * @author GobsC - * - * - */ -public class DbTimeHelper -{ -// --------------------------------------------------------- - - public static String getStringFromDate(java.sql.Date date) - { - String dateString = null; - - if (date != null) - { - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - - dateString = utcSdf2.format(date); - } - return dateString; - } -// --------------------------------------------------------- - - // ***************************************************************************** - // getTimeStampFromString() is used to convert DateTime year to sec variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getDateTimeFromString(String timeString) - { - Date shiftedDate = null; - - if (timeString != null) - { - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedDate = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - } - - return shiftedDate; - } - - // ***************************************************************************** - // getTimeFromString() is used to convert DateTime year to sec variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getTimeToSecondsFromString(String timeString) - { - Date shiftedTime = null; - - if (timeString != null) - { - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedTime = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - } - - return shiftedTime; - } - - // ***************************************************************************** - - // ***************************************************************************** - // getTimeStampFromString() is used to convert DateTime year to sec variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getDateTimeToMinutesFromString(String timeString) - { - Date shiftedDate = null; - - if (timeString != null) - { - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedDate = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - } - - return shiftedDate; - } - - // getDateFromString() is used to convert Date year to day variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getDateFromString(String timeString) - { - Date shiftedDate = null; - - if (timeString == null) - return shiftedDate; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedDate = new Date(utcSdf2.parse(timeString).getTime()); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - return shiftedDate; - } -// ------------------------------------------------------- - public static long getLongTimeFromDateTimeString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getDateTimeFromString(timeString); - - time = date.getTime(); - } - return time; - } -// ------------------------------------------------------- - public static long getLongTimeFromDateTimeToMinutesString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getDateTimeToMinutesFromString(timeString); - - time = date.getTime(); - } - return time; - } - -// ------------------------------------------------------- - - public static long getLongTimeFromDateString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getDateFromString(timeString); - - time = date.getTime(); - } - return time; - } - -// ------------------------------------------------------- - - public static long getLongTimeFromTimeToSecondsString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getTimeToSecondsFromString(timeString); - - time = date.getTime(); - } - return time; - } -// ------------------------------------------------------- - -// ------------------------------------------------------- - public static String getStringFromTimestamp(Timestamp timestamp) - { - String timeString = null; - - if (timestamp != null) - { - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(timestamp); - } - - //System.out.println("timeString = !" + timeString + "!"); - - return timeString; - } -// ------------------------------------------------------- - public static String getTimeToSecondsStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "HH:mm:ss"); - - return timeString; - } - //------------------------------------------------------- - - public static String getDateTimeStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy-MM-dd HH:mm:ss"); - - return timeString; - } - - //------------------------------------------------------- - - public static String getDateTimeToMinutesStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy-MM-dd HH:mm"); - - return timeString; - } - - // ------------------------------------------------------- - - - - public static String getDateStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy-MM-dd"); - - return timeString; - } - - //------------------------------------------------------- - - public static String getStringFromLongTime(long time, String dateFormat) - { - String timeString = null; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat(dateFormat); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(new java.util.Date(time)); - - return timeString; - } - - - - -// ------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbType.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbType.java deleted file mode 100755 index 1091d41132..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/db/DbType.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Created on Sep 17, 2004 - * - * - */ -package ohd.hseb.db; - -/** - * @author GobsC - * - * - */ -public class DbType -{ - public static final DbType Informix = new DbType("Informix"); - public static final DbType PostgreSQL = new DbType("PostgreSQL"); - - private static final DbType[] DBTypeArray = { Informix, PostgreSQL }; - - private String _name = null; - // ----------------------------------------------------------------------- - private DbType(String name) - { - _name = name; - - return; - - } - -// ----------------------------------------------------------------------- - public boolean equals(Object object) - { - boolean result = false; - - DbType type = (DbType) object; - - if (this._name.equals(type._name)) - { - result = true; - } - - return result; - } - -// ----------------------------------------------------------------------- - - public String toString() - { - return _name; - } -// ----------------------------------------------------------------------- -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/CDbGen.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/CDbGen.java deleted file mode 100755 index 8f11822e79..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/CDbGen.java +++ /dev/null @@ -1,2553 +0,0 @@ -// -// // File: CDbGen.java -//Orig Author: Chip Gobs 10/6/04 -//Spawned from JDbGen - -//This is a rewrite of dbgen in Java. It generates -//PostgreSQL-compatible esqlc code. - -package ohd.hseb.dbgen; - -//import ohd.hseb.util.*; - -import java.util.*; // needed for List and Map classes and others -import java.util.Date; // needed for Date class, resolves ambiguity with - // java.sql.Date -import java.io.*; // needed for file I/O -import java.sql.*; - -import ohd.hseb.db.Database; - - -public class CDbGen -{ - private static final boolean _usingNewDateCode = true; - private static final boolean _usingNewDateAndTimeCode = false; - private static final boolean _usingIndicators = true; - - - // --------------------------------------------------------------- - // private data - //--------------------------------------------------------------- - - private Map _cDataTypeIntegerMap = null; //maps from sqlType integer to cDataType String - private Map _sqlTypeToNullTypeMap = null; - private Map _keywordMap = null; - - private String _targetDirName = null; - - private DataOutputStream _dos = null; - - private List _tableDescriptorList = null; - - - private CodeIndenter _indenter = null; - - private final String _indentString = " "; - - private static final String _sectionSeparator = - "\n/* ------------------------------------------------------------------------- */\n"; - - - // ----------------------------------------------------------------------- - public CDbGen() - { - initCDataTypeIntegerMap(); - initSqlTypeToNullTypeMap(); - initKeywordMap(); - - } - // ------------------------------------------------------------------------------------- - private void initKeywordMap() - { - _keywordMap = new HashMap(); - - _keywordMap.put("value", "\\\"value\\\""); - _keywordMap.put("reference", "\\\"reference\\\""); - } - - // ------------------------------------------------------------------------------------- - - private void addCDataTypeIntegerMapEntry(int sqlType, String cType) - { - _cDataTypeIntegerMap.put(new Integer(sqlType), cType); - } - - // ------------------------------------------------------------------------------------- - private void initCDataTypeIntegerMap() - { - - _cDataTypeIntegerMap = new HashMap(); - - //special code handles the difference between internal and external structures - //for the DATE type, see getCDataTypeByInt() - addCDataTypeIntegerMapEntry(Types.DATE, "date"); - - - if (_usingNewDateAndTimeCode) - { - addCDataTypeIntegerMapEntry(Types.TIMESTAMP, "time_t"); - } - else - { - addCDataTypeIntegerMapEntry(Types.TIMESTAMP, "dtime_t"); - } - addCDataTypeIntegerMapEntry(Types.REAL, "float"); - addCDataTypeIntegerMapEntry(Types.FLOAT, "double"); - addCDataTypeIntegerMapEntry(Types.DOUBLE, "double"); - addCDataTypeIntegerMapEntry(Types.SMALLINT, "short"); - addCDataTypeIntegerMapEntry(Types.INTEGER, "long"); - addCDataTypeIntegerMapEntry(Types.BIGINT, "long"); - addCDataTypeIntegerMapEntry(Types.LONGVARBINARY, "char *"); - addCDataTypeIntegerMapEntry(Types.LONGVARCHAR, "char *"); // ? instead of byte[] - addCDataTypeIntegerMapEntry(Types.VARCHAR, "char"); - addCDataTypeIntegerMapEntry(Types.CHAR, "char"); - - - } - // ------------------------------------------------------------------------------------- - private String wrapInQuotesIfNeeded(String colName, boolean needsEscapes) - { - String newColName = colName; - - String value = (String) _keywordMap.get(colName); - - if (value != null) - { - if (needsEscapes) - { - newColName = "\\\"" + colName + "\\\""; - } - else - { - newColName = "\"" + colName + "\""; - } - } - - return newColName; - } - - // ------------------------------------------------------------------------------------- - - private String getCDataTypeByInt(int sqlType, boolean isPublicType) - { - String cDataType = null; - - cDataType = (String) _cDataTypeIntegerMap.get(new Integer(sqlType)); - - //one of few cases in which the public type differs from the internal type - if (_usingNewDateCode) - { - if ( (sqlType == Types.DATE) && (isPublicType) ) - { - cDataType = "date_t"; - } - } - - if (cDataType == null) - { - cDataType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return cDataType; - } - - // ------------------------------------------------------------------------------------- - - private void addSqlTypeToNullTypeMapEntry(int sqlType, String cType) - { - _sqlTypeToNullTypeMap.put(new Integer(sqlType), cType); - } - - // ------------------------------------------------------------------------------------- - private void initSqlTypeToNullTypeMap() - { - _sqlTypeToNullTypeMap = new HashMap(); - - addSqlTypeToNullTypeMapEntry(Types.CHAR, "CHAR"); - addSqlTypeToNullTypeMapEntry(Types.FLOAT, "FLOAT"); - addSqlTypeToNullTypeMapEntry(Types.REAL, "FLOAT"); - addSqlTypeToNullTypeMapEntry(Types.SMALLINT, "SHORT"); - addSqlTypeToNullTypeMapEntry(Types.INTEGER, "INT"); - addSqlTypeToNullTypeMapEntry(Types.BIGINT, "LONG"); - addSqlTypeToNullTypeMapEntry(Types.DOUBLE , "DOUBLE"); - addSqlTypeToNullTypeMapEntry(Types.DATE, "INT"); //not DATE because our public struct is a long - addSqlTypeToNullTypeMapEntry(Types.TIMESTAMP, "DATETIME"); - addSqlTypeToNullTypeMapEntry(Types.VARCHAR, "CHAR"); - addSqlTypeToNullTypeMapEntry(Types.LONGVARCHAR, "CHAR"); - } - - //------------------------------------------------------------------------------------- - - private String getNullTypeByInt(int sqlType) - { - String nullType = null; - - nullType = (String) _sqlTypeToNullTypeMap.get(new Integer(sqlType)); - - - if (nullType == null) - { - nullType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return nullType; - } - - // --------------------------------------------------------------------------------- - - private void write(String line, boolean useIndentation) throws IOException - { - //--------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - - if (useIndentation) - { - String totalIndentString = _indenter.getTotalIndentString(); - - _dos.writeBytes(totalIndentString + line); - } - else - { - _dos.writeBytes(line); - } - } - - // ----------------------------------------------------------------- - private void write(String line) throws IOException - { -// --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - write(line, false); //by default, do not use indentation - - return; - } - - // ----------------------------------------------------------------- - - private void writeLine(String line) throws IOException - { -// --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - boolean useIndentation = true; - write(line + "\n", useIndentation); - - return; - } - - // ----------------------------------------------------------------- - - private void writeNewLine() throws IOException - { -// --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - boolean useIndentation = false; - write("\n", useIndentation); - - return; - } - // ----------------------------------------------------------------- - - private void logError(IOException e) - { - System.err.println("Error trying to write to "); - e.printStackTrace(); - - return; - } - - - // -------------------------------------------------------------------------- - // read the list of preferred table names from a text file with the - // preferred name of the Tables and Views , 1 per line, no spaces in the - // name - // -------------------------------------------------------------------------- - private Map getMapOfPreferredTableNames(String filePath) - { - Map tableNameMap = new HashMap(); - - try - { - - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - String line = null; - - line = reader.readLine(); - - while (line != null) - { - // System.out.println("line = " + line + ":"); - - String preferredTableName = line.trim(); - String lowercaseTableName = preferredTableName.toLowerCase(); - - tableNameMap.put(lowercaseTableName, preferredTableName); - - System.out.println("CDbGen.getMapOfPreferredTableNames(): " - + lowercaseTableName + " -> " + preferredTableName); - - line = reader.readLine(); - } //end while - - reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - - return tableNameMap; - } - - // ----------------------------------------------------------------- - private void buildHeaderSrcFiles(String dbName) - { - try - { - // Strings to hold Table name and File name - String tableName = new String(); - String fileName = new String(); - - // loop through all the table names and build source files - for (int ctr = 0; ctr < _tableDescriptorList.size(); ctr++) - { - TableDescriptor tableDesc = (TableDescriptor) _tableDescriptorList - .get(ctr); - tableName = tableDesc.getName(); - - fileName = tableName + ".h"; - - System.out.println("building source code for " + fileName); - - - FileOutputStream fos = new FileOutputStream(_targetDirName - + "/" + fileName); - _dos = new DataOutputStream(fos); - - createHeaderFile(tableName, fileName, dbName, tableDesc); - - if ((!tableDesc.isView()) && (tableDesc.hasPrimaryKey())) - { - // createRecordGetWhereString(tableDesc); - } - - _indenter.setLevel(0); - - _dos.close(); - } - } - catch (IOException e) - { - logError(e); - } - - } // end of buildRecordSrcFiles method - - - //----------------------------------------------------------------- - private void createHeaderFile(String tableName, String fileName, - String dbName, TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - if (tableDesc.isView()) - { - writeLine("// This is a view record !"); - } - - writeLine("/*"); - _indenter.incLevel(); - writeLine("File: " + fileName); - writeLine("Author : CDBGEN"); - writeLine("Created : " + currentTime + " using database " + dbName); - writeLine("Description: This header file is associated with its .pgc file "); - _indenter.incLevel(2); - writeLine("and defines functions and the table's record structure."); - _indenter.decLevel(2); - _indenter.decLevel(); - writeLine("*/"); - - - writeLine("#ifndef " + tableName + "_h"); - writeLine("#define " + tableName + "_h"); - write("\n\n"); - - - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include \"DbmsAccess.h\""); - writeLine("#include \"DbmsUtils.h\""); - writeLine("#include \"List.h\""); - writeLine("#include \"GeneralUtil.h\""); - writeLine("#include \"dbmserrs.h\""); - writeLine("#include \"datetime.h\""); - writeLine("#include \"time_convert.h\""); - - writeNewLine(); - - - write("\n\n"); - - writeLine("typedef struct _" + tableName); - writeLine("{"); - _indenter.incLevel(); - - writeLine("Node\t\tnode;"); - - createStructureContents(tableName, tableDesc, true); - - writeLine("List\t\tlist;"); - _indenter.decLevel(); - writeLine("} " + tableName + ";"); - - - writeLine("/*"); - _indenter.incLevel(); - writeLine("Function Prototypes"); - _indenter.decLevel(); - writeLine("*/"); - - _indenter.incLevel(); - writeLine(tableName + "* Get" + tableName + "(const char * where);"); - writeLine(tableName + "* Select" + tableName + "(const char * where);"); - writeLine("int Select" + tableName + "Count(const char * where);"); - - if (!tableDesc.isView()) - { - writeLine("int Put" + tableName + "(const " + tableName - + " * structPtr);"); - writeLine("int Insert" + tableName + "(const " + tableName - + " * structPtr);"); - - writeLine("int Update" + tableName + "(const " + tableName + - "* structPtr, const char *where);"); - writeLine("int Delete" + tableName + "(const char *where);"); - - - if (tableDesc.hasPrimaryKey()) - { - writeLine("int Update" + tableName + "ByRecord (const " + tableName + - " * newStructPtr, const " + tableName + " * oldStructPtr);"); - - writeLine("int InsertOrUpdate" + tableName + "(const " + tableName + " * structPtr);"); - - writeLine("int InsertIfUnique" + tableName + "(const " + tableName + " * structPtr, bool *isUnique);"); - writeLine("bool " + tableName +"Exists(const " + tableName + " * structPtr);"); - - writeLine("int Delete" + tableName + "ByRecord(const " + tableName + " * structPtr);"); - - writeLine("void Get" + tableName + "PrimaryKeyWhereString " + - "(const " + tableName + " * structPtr, char returnWhereString[] );"); - - } - } - writeLine("void Free" + tableName + "(" + tableName - + " * structPtr);"); - - writeLine("DbStatus * Get" + tableName + "DbStatus();"); - writeLine("void Set" + tableName +"ErrorLogging(int value);"); - - - _indenter.decLevel(); - writeLine("#endif"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createRecordFileBanner method - - //---------------------------------------------------------------------------------------- - - private void buildEsqlCSourceFiles(String dbName) - { - try - { - // Strings to hold Table name and File name - String tableName = new String(); - String fileName = new String(); - String cursorName = "tcur"; - - // loop through all the table names and build source files - for (int ctr = 0; ctr < _tableDescriptorList.size(); ctr++) - { - TableDescriptor tableDesc = - (TableDescriptor) _tableDescriptorList.get(ctr); - - tableName = tableDesc.getName(); - - fileName = tableName + ".pgc"; - - System.out.println("building source code for " + fileName); - - FileOutputStream fos = - new FileOutputStream(_targetDirName + "/" + fileName); - _dos = new DataOutputStream(fos); - - createEsqlCCommentSection(tableName, fileName, dbName,tableDesc); - createEsqlCIncludeSection(tableName, fileName, dbName); - createStructSection(tableName, tableDesc); - - createMiscDeclarations(tableName); - writeLine(_sectionSeparator); - - - createSelectFunction("Get", tableName, tableDesc, cursorName+"1"); - writeLine(_sectionSeparator); - - createSelectFunction("Select", tableName, tableDesc, cursorName+"2"); - writeLine(_sectionSeparator); - - createSelectCountFunction("Select", tableName, tableDesc, cursorName+"3"); - writeLine(_sectionSeparator); - - if (!tableDesc.isView()) - { - createInsertFunction("Put", tableName, tableDesc); - writeLine(_sectionSeparator); - - createInsertFunction("Insert", tableName, tableDesc); - writeLine(_sectionSeparator); - - createUpdateFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createDeleteFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - - if (tableDesc.hasPrimaryKey()) - { - createUpdateByRecordFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createInsertOrUpdateFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createInsertIfUniqueFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createDeleteByRecordFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createExistsFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createGetPrimaryWhereString(tableName, tableDesc); - writeLine(_sectionSeparator); - } - - } - - - - createFreeFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createGetDbStatusFunction(tableName); - writeLine(_sectionSeparator); - - createSetErrorLogging(tableName); - writeLine(_sectionSeparator); - - _indenter.setLevel(0); - - _dos.close(); - } - } - catch (IOException e) - { - logError(e); - - } - - } // end of buildRecordSrcFiles method - //------------------------------------------------------------------------------------ - - private void createEsqlCCommentSection(String tableName, String fileName, - String dbName, - TableDescriptor tableDesc) - { - - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - if (tableDesc.isView()) - { - writeLine("/* This is a view record ! */"); - } - - writeLine("/*"); - _indenter.incLevel(); - writeLine("File: " + fileName); - writeLine("Author : CDBGEN"); - writeLine("Created : " + currentTime + " using database " + dbName); - writeLine("Description: This .pgc file has an associated header file. "); - _indenter.incLevel(2); - writeLine("and defines all functions and the table's INTERNAL record structure."); - _indenter.decLevel(2); - _indenter.decLevel(); - writeLine("*/"); - writeNewLine(); - } - catch (java.io.IOException e) - { - logError(e); - } - - } - - //---------------------------------------------------------------------------------------- - - private void createEsqlCIncludeSection(String tableName, String fileName, - String dbName) - { - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - writeLine("#include \"" + tableName + ".h\""); - - /* - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include \"DbmsAccess.h\""); - writeLine("#include \"dbmserrs.h\""); - writeLine("#include \"List.h\""); - */ - writeNewLine(); - writeLine("EXEC SQL include sqlda;"); - writeLine("EXEC SQL include sqltypes;"); - writeLine("EXEC SQL include sql3types;"); - writeLine("EXEC SQL include pgtypes_timestamp;"); - writeLine("EXEC SQL include pgtypes_date;"); - writeLine("EXEC SQL include pgtypes_interval;"); - writeLine("EXEC SQL include pgtypes_numeric;"); - writeNewLine(); - - } - catch (java.io.IOException e) - { - logError(e); - } - - - } - - //--------------------------------------------------------------------------------------- - private void createStructSection(String tableName, TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeLine("struct " + tableName + "_t"); - writeLine("{"); - _indenter.incLevel(); - createStructureContents(tableName, tableDesc, false); - _indenter.decLevel(); - writeLine("} " + tableName + "_rec;"); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - } - catch (java.io.IOException e) - { - logError(e); - } - } - //---------------------------------------------------------------------------------------- - - - private void createMiscDeclarations(String tableName) - { - try - { - _indenter.setLevel(0); - - writeLine("#define QUERY_LEN 9999"); - writeLine("static int errorLoggingOn = 1;"); - writeNewLine(); - writeLine("static DbStatus dbStatus;"); - writeNewLine(); - - } - catch (java.io.IOException e) - { - logError(e); - } - } -// ---------------------------------------------------------------------------------------- - - - private void createSetErrorLogging(String tableName) - { - - try - { - _indenter.setLevel(0); - - writeLine("void Set" + tableName +"ErrorLogging(int value)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("errorLoggingOn = value;"); - writeLine("return;"); - - _indenter.decLevel(); - writeLine("}"); - - - writeNewLine(); - - } - catch (java.io.IOException e) - { - logError(e); - } - } -//---------------------------------------------------------------------------------------- - - private void createStructureContents(String tableName, - TableDescriptor tableDesc, - boolean isPublicStructure) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - - String columnName = colDesc.getName(); - int sqlTypeInt = colDesc.getSqlTypeInt(); - String cType = getCDataTypeByInt(sqlTypeInt, isPublicStructure); - - String firstChar = String.valueOf(columnName.charAt(0)); - // String newName = firstChar.toUpperCase() - // + columnName.substring(1); - - - - if ((sqlTypeInt == Types.CHAR) || (sqlTypeInt == Types.VARCHAR) ) - { - int size = colDesc.getSize() + 1; - writeLine(cType + "\t\t" + columnName + "[" + size + "];"); - } - else - //non-character type - { - writeLine(cType + "\t\t" + columnName + ";"); - } - } //end for each column - - - if ((_usingIndicators) && (! isPublicStructure) ) // declare indicator variables - { - writeNewLine(); - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.isNullable()) - { - String columnName = colDesc.getName(); - writeLine("int" +"\t\t" + getIndicatorColumnName(columnName) +";"); - } - - } //end for each column - - } - } - catch (IOException e) - { - logError(e); - } - - } // end of createRecordCopyConstructor method - //------------------------------------------------------------------------------------------- - private String getIndicatorColumnName(String columnName) - { - return "ind_" + columnName; - } - //------------------------------------------------------------------------------------------- - private void createSelectFunction(String functionPrefix, - String tableName, - TableDescriptor tableDesc, - String cursorName) - { - - try - { - _indenter.setLevel(0); - writeLine(tableName + " * " + functionPrefix + tableName + "(const char * where)"); - writeLine("{"); - _indenter.incLevel(); - - writeNewLine(); - writeLine(tableName + " * listPtr = NULL;"); - writeLine(tableName + " * structPtr = NULL;"); - writeLine("char selectStatement[] = \"SELECT * FROM " + tableName + " \";"); - writeNewLine(); - - writeLine("int rowCount = 0;"); - writeLine("int first = 1;"); - writeNewLine(); - - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("struct " + tableName + "_t dbs;"); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, SELECT);"); - writeNewLine(); - - writeLine("strcpy(queryBuffer, selectStatement);"); - writeNewLine(); - - writeLine("if ( ( where != NULL ) && ( * where != '\\0' ) ) "); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("strcat(queryBuffer, where);"); - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("EXEC SQL PREPARE tid FROM :queryBuffer;"); - createErrorChecking(tableName, functionPrefix, "Prepare section", "return (NULL);"); - writeNewLine(); - - writeLine("EXEC SQL DECLARE " + cursorName + " CURSOR WITH HOLD FOR tid;"); - createErrorChecking(tableName, functionPrefix, "Declare cursor section", "return (NULL);"); - writeNewLine(); - - writeLine("EXEC SQL OPEN " + cursorName + ";"); - createErrorChecking(tableName, functionPrefix, "Open cursor section", "return (NULL);"); - writeNewLine(); - - writeLine("listPtr = NULL;"); - writeLine("memset(&dbs, '\\0', sizeof(dbs));"); - writeNewLine(); - - if (_usingIndicators) - { - createFetch(tableDesc, cursorName); - } - else - { - writeLine("EXEC SQL FETCH " + cursorName + " INTO :dbs;"); - } - createErrorChecking(tableName, functionPrefix, "Initial FETCH section", "return (NULL);"); - writeNewLine(); - - writeLine("while (SQLCODE == 0) "); - writeLine("{"); - _indenter.incLevel(); - - writeLine("rowCount++;"); - - writeLine("if ((structPtr = (" + tableName + " *) malloc(sizeof(" + tableName +"))) != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeNewLine(); - createCopyDbStructToCStruct(tableName, tableDesc); - writeNewLine(); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - writeLine("break;"); - _indenter.decLevel(); - writeLine("}"); - - writeNewLine(); - - writeLine("if (first)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("listPtr = structPtr;"); - writeLine("ListInit(&listPtr->list);"); - writeLine("first = 0;"); - - - _indenter.decLevel(); - writeLine("}"); //end of if (first) - writeNewLine(); - - writeLine("ListAdd(&listPtr->list, &structPtr->node);"); - writeLine("memset(&dbs, '\\0', sizeof(dbs));"); - writeNewLine(); - - if (_usingIndicators) - { - createFetch(tableDesc, cursorName); - } - else - { - writeLine("EXEC SQL FETCH " + cursorName + " INTO :dbs;"); - } - createErrorChecking(tableName, functionPrefix, "Nth fetch section", "return (NULL);"); - - - _indenter.decLevel(); - writeLine("}"); //end of while loop - writeNewLine(); - - - writeLine("initDbStatus(&dbStatus);"); - writeLine("setDbStatusRowsAffected(&dbStatus, rowCount);"); - writeNewLine(); - - writeLine("EXEC SQL CLOSE " + cursorName + ";"); - writeLine("return(listPtr);"); - - _indenter.decLevel(); - writeLine("}"); //end of SelectXXX or GetXXX - - } - catch (IOException e) - { - logError(e); - } - - } // end of createSelectFunction() - - // ---------------------------------------------------------------------------------- - private void createSelectCountFunction(String functionPrefix, - String tableName, - TableDescriptor tableDesc, - String cursorName) - { - - try - { - String functionName = functionPrefix + "Count"; - - _indenter.setLevel(0); - writeLine("int " + functionPrefix + tableName + "Count(const char * where)"); - writeLine("{"); - _indenter.incLevel(); - - writeNewLine(); - writeLine("char selectStatement[] = \"SELECT COUNT(*) FROM " + tableName + " \";"); - writeNewLine(); - - - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("int rowCount = 0;"); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, SELECT);"); - writeNewLine(); - - writeLine("strcpy(queryBuffer, selectStatement);"); - writeNewLine(); - - writeLine("if ( ( where != NULL ) && ( * where != '\\0' ) ) "); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("strcat(queryBuffer, where);"); - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("EXEC SQL PREPARE tid FROM :queryBuffer;"); - createErrorChecking(tableName, functionName, "Prepare section", "return (-1);"); - writeNewLine(); - - writeLine("EXEC SQL DECLARE " + cursorName + " CURSOR WITH HOLD FOR tid;"); - createErrorChecking(tableName, functionName, "Declare cursor section", "return (-1);"); - writeNewLine(); - - writeLine("EXEC SQL OPEN " + cursorName + ";"); - createErrorChecking(tableName, functionName, "Open cursor section", "return (-1);"); - writeNewLine(); - - - writeNewLine(); - - writeLine("EXEC SQL FETCH " + cursorName + " INTO :rowCount;"); - - createErrorChecking(tableName, functionName, "Initial FETCH section", "return (-1);"); - writeNewLine(); - - writeLine("initDbStatus(&dbStatus);"); - writeLine("setDbStatusRowsAffected(&dbStatus, rowCount);"); - writeNewLine(); - - writeLine("EXEC SQL CLOSE " + cursorName + ";"); - writeLine("return(rowCount);"); - - _indenter.decLevel(); - writeLine("}"); //end of SelectXXXCount or GetXXXCount - - } - catch (IOException e) - { - logError(e); - } - - } // end of createSelectCountFunction() - - // -------------------------------------------------------------------------------------- - private void createInsertOrUpdateFunction(String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("int InsertOrUpdate" + tableName + "(const " + tableName + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - - writeLine("Update"+ tableName + "ByRecord(structPtr, structPtr);"); - writeLine("setDbStatusSqlCommand(&dbStatus, UPDATE);"); - - writeNewLine(); - - writeLine("if ( (SQLCODE < 0) || (SQLCODE == 100) )"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("Insert" + tableName + "(structPtr);"); - writeLine("setDbStatusSqlCommand(&dbStatus, INSERT);"); - - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("initDbStatus(&dbStatus);"); - - writeLine("return(SQLCODE);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertOrUpdateFunction method - - // ---------------------------------------------------------------------------------- - private void createExistsFunction(String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("bool " + tableName +"Exists(const " + tableName + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("int result = false;"); - writeLine("int rowCount = 0;"); - - writeLine("char whereString[QUERY_LEN];"); - writeNewLine(); - - writeLine("Get" + tableName + "PrimaryKeyWhereString(structPtr, whereString);"); - writeLine("rowCount = Select" + tableName + "Count(whereString);"); - writeNewLine(); - - writeLine("if (rowCount > 0)"); - writeLine("{"); - _indenter.incLevel(); - writeLine("result = true;"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - writeLine("result = false;"); - _indenter.decLevel(); - writeLine("}"); - - writeNewLine(); - writeLine("return(result);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertIfUniqueFunction method - - // ---------------------------------------------------------------------------------- - private void createInsertIfUniqueFunction(String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("int InsertIfUnique" + tableName + "(const " + tableName + " * structPtr, bool *isUnique)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("int resultCode = 0;"); - - writeLine("if (" + tableName + "Exists(structPtr))"); - writeLine("{"); - _indenter.incLevel(); - writeLine("setDbStatusSqlCommand(&dbStatus, SELECT);"); - writeLine("*isUnique = false;"); - writeLine("resultCode = dbStatus.sql_code;"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("resultCode = dbStatus.sql_code;"); - - writeLine("if (resultCode == 0)"); - writeLine("{"); - _indenter.incLevel(); - writeLine("Insert" + tableName + "(structPtr);"); - writeLine("setDbStatusSqlCommand(&dbStatus, INSERT);"); - writeLine("*isUnique = true;"); - writeLine("resultCode = dbStatus.sql_code;"); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - writeLine("*isUnique = false;"); - _indenter.decLevel(); - writeLine("}"); - - - _indenter.decLevel(); - writeLine("}"); - - writeLine("initDbStatus(&dbStatus);"); - writeNewLine(); - writeLine("return(resultCode);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertIfUniqueFunction method - - // ---------------------------------------------------------------------------------- - private void createInsertFunction(String functionPrefix, - String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("int " + functionPrefix + tableName + "(const " + tableName + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("struct " + tableName + "_t dbs;"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, INSERT);"); - writeNewLine(); - - writeLine("if (structPtr == NULL)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("return(ERR_BAD_ARGS);"); - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - - writeLine("memset(&dbs, '\\0', sizeof(dbs));"); - writeNewLine(); - - createCopyCStructToDbStruct(tableName, tableDesc); - writeNewLine(); - - - if (_usingIndicators) - { - createInsertStatement(tableDesc, dbColumnsPerLine); - } - else - { - writeLine("EXEC SQL INSERT INTO " + tableName + " VALUES " + "(:dbs);"); - } - - createFreeTextColumnDbsStructFragment(tableName, tableDesc); - - createErrorChecking(tableName, functionPrefix, "Insert section","return (SQLCODE);"); - writeNewLine(); - - //writeLine("EXEC SQL COMMIT WORK;"); - - writeLine("initDbStatus(&dbStatus);"); - - writeLine("return(ERR_OK);"); - - _indenter.decLevel(); - writeLine("}"); - - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertFunction method - - - // ---------------------------------------------------------------------------------- - private void createUpdateFunction(String tableName, - TableDescriptor tableDesc) - { - - _indenter.setLevel(0); - final int dbColumnsPerLine = 5; - - try - { - writeLine("int Update" + tableName + "(const " + tableName + " *structPtr, const char *where)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("struct " + tableName + "_t dbs;"); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, UPDATE);"); - writeNewLine(); - - createCopyCStructToDbStruct(tableName, tableDesc); - writeNewLine(); - - writeLine("sprintf(queryBuffer, \" UPDATE " + tableName + " SET \" );"); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - int columnCount = columnDescriptorList.size(); - - //write out the query with ? in it - write("strcat(queryBuffer, \"", true); - - //for each column, put in colName = ?, - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String colName = colDesc.getName(); - - colName = wrapInQuotesIfNeeded(colName, true); - - write(colName + " = ? "); - - if (i < columnCount -1) - { - write(", "); - - // only put a number of columns on a line at a time - // so go to a newline and indent - if ((i+1) % dbColumnsPerLine == 0) - { - writeLine("\");"); - write("strcat(queryBuffer, \"", true); - } - } - } - write("\");"); //close the strcat statement - write("\n"); - writeNewLine(); - - //append the where clause to the query - writeLine("if ( (where != NULL) && (*where != '\\0'))"); - writeLine("{"); - _indenter.incLevel(); - writeLine("strcat(queryBuffer, where);"); - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("EXEC SQL PREPARE uid FROM :queryBuffer;"); - createErrorChecking(tableName, "Update", "Prepare section", "return(SQLCODE);"); - writeNewLine(); - - //create the execute statement - -// write out the execute statement - createExecuteUsing(tableDesc, dbColumnsPerLine); - - // free any special TEXT column data - createFreeTextColumnDbsStructFragment(tableName, tableDesc); - - - createErrorChecking(tableName, "Update", "Execute section", "return(SQLCODE);"); - writeNewLine(); - - // writeLine("/* need to verify that this works in postgresql! */"); - // writeLine("num_rows_updated = sqlca.sqlerrd[2];"); - - // writeLine("/* why do we have both lines? */"); - // writeLine("sqlca.sqlerrd[2] = num_rows_updated;"); - - - // writeLine("EXEC SQL COMMIT;"); - writeLine("initDbStatus(&dbStatus);"); - writeLine("return(ERR_OK);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } - - - // ---------------------------------------------------------------------------------- - - private void createUpdateByRecordFunction(String tableName, - TableDescriptor tableDesc) - { - - _indenter.setLevel(0); - final int dbColumnsPerLine = 5; - - try - { - writeLine("int Update" + tableName + "ByRecord (const " + tableName + - " * newStructPtr, const " + tableName + " * oldStructPtr)"); - - _indenter.setLevel(0); - - - writeLine("{"); - _indenter.incLevel(); - - writeLine("char whereClause[BUFSIZ];"); - - writeLine("Get" + tableName + "PrimaryKeyWhereString(oldStructPtr, whereClause);"); - - writeLine("return (Update" + tableName + "(newStructPtr, whereClause));"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - private void createDeleteFunction(String tableName, - TableDescriptor tableDesc) - { - _indenter.setLevel(0); - - try - { - writeLine("int Delete" + tableName + "(const char *where)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("char deleteStatement[] = \"DELETE FROM " + tableName + " \";"); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("strcpy(queryBuffer, deleteStatement);"); - -// append the where clause to the query - writeLine("if ( (where != NULL) && (*where != '\\0'))"); - writeLine("{"); - _indenter.incLevel(); - writeLine("strcat(queryBuffer, where);"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("EXEC SQL EXECUTE IMMEDIATE :queryBuffer;"); - createErrorChecking(tableName, "Delete", "Execute Immediate section", "return(SQLCODE);"); - writeNewLine(); - - writeLine("initDbStatus(&dbStatus);"); - writeLine("return(ERR_OK);"); - - _indenter.decLevel(); - writeLine("}"); - - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - - private void createDeleteByRecordFunction(String tableName, - TableDescriptor tableDesc) - { - - _indenter.setLevel(0); - - try - { - writeLine("int Delete" + tableName + "ByRecord(const " + tableName + " * structPtr)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("char whereClause[BUFSIZ];"); - - writeLine("Get" + tableName + "PrimaryKeyWhereString(structPtr, whereClause);"); - - writeLine("return (Delete" + tableName + "(whereClause));"); - - _indenter.decLevel(); - writeLine("}"); - - - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - private void createFreeTextColumnStructFragment(String tablename, TableDescriptor tableDesc) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - - try - { - - // do a special free for any TEXT fields - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (columnDesc.getSqlTypeInt() == Types.LONGVARCHAR) - { - writeLine("if (structPtr->" + columnDesc.getName() + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("free(structPtr->" + columnDesc.getName() + ");"); - - _indenter.decLevel(); - writeLine("}"); - } - } - - } - catch (IOException e) - { - logError(e); - } - } - - // ---------------------------------------------------------------------------------- - - private void createFreeTextColumnDbsStructFragment(String tablename, TableDescriptor tableDesc) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - // do a special free for any TEXT fields - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (columnDesc.getSqlTypeInt() == Types.LONGVARCHAR) - { - writeLine("if (dbs." + columnDesc.getName() + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("free(dbs." + columnDesc.getName() + ");"); - - _indenter.decLevel(); - writeLine("}"); - } - } - - } - catch (IOException e) - { - logError(e); - } - } - - // ---------------------------------------------------------------------------------- - private void createFreeFunction(String tableName, TableDescriptor tableDesc) - { - _indenter.setLevel(0); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - - - try - { - - writeLine("void Free" + tableName + "( " + tableName - + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine(tableName + "* nextPtr = NULL;"); - writeNewLine(); - - writeLine("while (structPtr != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("nextPtr = ( " + tableName - + " * ) ListNext ( &structPtr->node );"); - - -// do a special free for any TEXT fields - createFreeTextColumnStructFragment(tableName, tableDesc); - - /* - // do a special free for any TEXT fields - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (columnDesc.getSqlTypeInt() == Types.LONGVARCHAR) - { - writeLine("if (structPtr->" + columnDesc.getName() + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("free (structPtr->" + columnDesc.getName() + ");"); - - _indenter.decLevel(); - writeLine("}"); - } - } - */ - writeLine("free (structPtr);"); - writeLine("structPtr = nextPtr;"); - - _indenter.decLevel(); - writeLine("}"); //close the while loop - - writeLine("return;"); - - _indenter.decLevel(); - writeLine("}"); // close the function - - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - private void createGetDbStatusFunction(String tableName) - { - _indenter.setLevel(0); - - try - { - writeLine("DbStatus * Get" + tableName + "DbStatus()"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("return &dbStatus;"); - - _indenter.decLevel(); - writeLine("}"); // close the function - } - - catch (IOException e) - { - logError(e); - } - - } - // ---------------------------------------------------------------------------------- - private List getKeyColumnDescriptorList(TableDescriptor tableDesc) - { - List keyColDescList = new ArrayList(); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - int columnCount = columnDescriptorList.size(); - -// for each key column, check if it is a key column, and, if so, then insert it into the list - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.isKeyColumn()) - { - keyColDescList.add(colDesc); - } - } - - return keyColDescList; - } - // ---------------------------------------------------------------------------------- - private int getDateColumnCount(List columnDescriptorList) - { - - int dateColumnCount = 0; - int columnCount = columnDescriptorList.size(); - - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.getSqlTypeInt() == Types.DATE) - { - dateColumnCount++; - } - } - - return dateColumnCount; - } - - // ---------------------------------------------------------------------------------- - private int getTimeColumnCount(List columnDescriptorList) - { - - int timeColumnCount = 0; - int columnCount = columnDescriptorList.size(); - - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.getSqlTypeInt() == Types.TIMESTAMP) - { - timeColumnCount++; - } - } - - return timeColumnCount; - } - - // ---------------------------------------------------------------------------------- - - - private void createGetPrimaryWhereString(String tableName, TableDescriptor tableDesc) - { - /* - generate the following type of statement - sprintf(returnWhereString, "WHERE lid = '%s' AND pe = '%s' AND dur = %d AND ts = '%s' AND extremum = %d AND obstime = '%s' ", - structPtr->lid, structPtr->pe, structPtr->dur, - structPtr->ts, structPtr->extremum, structPtr->obsTime); - - */ - String header = "CDbGen.createGetPrimaryWhereString(): "; - final int dbColumnsPerLine = 5; - _indenter.setLevel(0); - - int dateColumnCount = 0; - int timeColumnCount = 0; - - try - { - - writeLine("void Get" + tableName + "PrimaryKeyWhereString " + "(const " + tableName + " * structPtr, char returnWhereString[] )"); - writeLine("{"); - _indenter.incLevel(); - - List keyColumnDescriptorList = tableDesc.getKeyColumnDescriptorList(); - int columnCount = keyColumnDescriptorList.size(); - - - dateColumnCount = getDateColumnCount(keyColumnDescriptorList); - timeColumnCount = getTimeColumnCount(keyColumnDescriptorList); - - for (int i = 0; i < dateColumnCount; i++) - { - writeLine("char date_buffer" + i + "[40];"); - } - - - for (int i = 0; i < timeColumnCount; i++) - { - writeLine("char time_buffer" + i + "[40];"); - } - - write("sprintf(returnWhereString, \"WHERE ", true); - -// for each key column, insert the lid = '%s' part of the sprintf statement - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) keyColumnDescriptorList.get(i); - int sqlType = colDesc.getSqlTypeInt(); - - - switch (sqlType) - { - case Types.CHAR: - case Types.VARCHAR: - { - write(colDesc.getName() + " = '%s' " ); - break; - } - case Types.SMALLINT: - { - write(colDesc.getName() + " = %d "); - break; - } - case Types.INTEGER: - { - write(colDesc.getName() + " = %ld "); - break; - } - - case Types.FLOAT: - case Types.REAL: - { - write(colDesc.getName() + " = %f "); - break; - } - - - case Types.DOUBLE: - { - write(colDesc.getName() + " = %lf "); - break; - } - - case Types.DATE: - { - //this case will have a corresponding - //conversion to SQL string from date - - if (_usingNewDateCode) - { - write(colDesc.getName() + " = '%s' "); - } - else - { - write(colDesc.getName() + " = '%ld' "); - } - break; - } - - case Types.TIMESTAMP: - { - - //this case will have a corresponding - //conversion to SQL string from timestamp - write(colDesc.getName() + " = '%s' "); - - break; - } - default: - { - System.out.println(header + "type = " + sqlType); - break; - } - - } - - - //if not the last column - if (i < columnCount - 1) - { - write(" AND "); - } - else //last one before parameter list - { - write("\",\n"); - } - - - } - - - //indent 3 times - write("", true); - write("", true); - write("", true); - - //for each key column, insert the ,sPtr->lid, sPtr->pe - int dateBufferCount = 0; - int timeBufferCount = 0; - - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) keyColumnDescriptorList.get(i); - int sqlType = colDesc.getSqlTypeInt(); - - switch (sqlType) - { - case Types.DATE: - { - //this case will have a corresponding - //conversion to SQL string from timestamp - if (_usingNewDateCode) - { - - write("date_t_to_ansi_date(structPtr->" + colDesc.getName()+ ", date_buffer"+ dateBufferCount + ")"); - dateBufferCount++; - } - else - { - write("structPtr->" + colDesc.getName()); - } - break; - } - case Types.TIMESTAMP: - { - //this case will have a corresponding - //conversion to SQL string from timestamp - if (_usingNewDateAndTimeCode) - { - write("timet_to_ansi(structPtr->" + colDesc.getName() + ", time_buffer" + timeBufferCount + ")"); - timeBufferCount++; - } - else - { - write("dtimet_to_ansi(structPtr->" + colDesc.getName() + ", time_buffer" + timeBufferCount + ")"); - timeBufferCount++; - } - break; - } - default: - { - write("structPtr->" + colDesc.getName()); - break; - } - - } - - - //if not the last column - if (i < columnCount - 1) - { - write(", "); - - if ((i+1) % dbColumnsPerLine == 0) - { - write("\n"); - write("", true); - write("", true); - write("", true); - } - - } - - } - - - write(");\n"); //close sprintf statement - - - _indenter.decLevel(); - writeLine("}"); - - - } - catch (IOException e) - { - logError(e); - } - - } - // ---------------------------------------------------------------------------------- - - private void createCopyDbStructToCStruct(String tableName, TableDescriptor tableDesc) - { - - int columnCount = tableDesc.getColumnDescriptorList().size(); - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - for (int i = 0; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - - int sqlType = colDesc.getSqlTypeInt(); - boolean isNullable = colDesc.isNullable(); - - String indicatorType = getNullTypeByInt(sqlType); - - switch(sqlType) - { - case Types.CHAR: - case Types.VARCHAR: - { - writeLine("strcpy(structPtr->" + colName + - ", dbs." + colName + ");"); - break; - } - case Types.LONGVARCHAR: - { - - //make sure I free any automatically allocated space in the dbs structure - writeLine("if (dbs." + colName + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("structPtr->" + colName + - " = malloc(strlen(dbs." + colName + ") + 1);") ; - writeLine("memset(structPtr->" + colName + ", '\\0', strlen(dbs." + colName + ") +1); "); - writeLine("strcpy(structPtr->" + colName + - ", dbs." + colName + ");"); - - writeLine("free(dbs." + colName +");"); - - _indenter.decLevel(); - writeLine("}"); - - - break; - } - - case Types.DATE: - { - if (_usingNewDateCode) - { - writeLine("structPtr->" + colName + - " = pg_date_to_date_t(dbs." + colName + ");"); - } - else - { - writeLine("structPtr->" + colName + - " = dbs." + colName + ";"); - } - break; - } - - - case Types.TIMESTAMP: - { - if (_usingNewDateAndTimeCode) - { - writeLine("structPtr->" + colName + - " = timestamp_to_timet(dbs." + colName + ");"); - } - else - { - writeLine("structPtr->" + colName + - " = dbs." + colName + ";"); - } - break; - } - - default: - { - writeLine("structPtr->" + colName + - " = dbs." + colName + ";"); - } - - } //end switch - - if (_usingIndicators) - { - String reference = ""; //puts in a "&" if not a string - if (! indicatorType.equals("CHAR")) - { - reference = "&"; - } - - if (isNullable) - { - writeLine("setNullIfIndicated(dbs." + indName + - ", " + indicatorType +", " + reference + "structPtr->" + colName +");"); - } - - //space out the copying so that pairs of setNullIfIndicated and - // data copying are placed together for each column - writeNewLine(); - } - - } //end for - - } //end try - catch (IOException e) - { - logError(e); - } - return; - } - - // ---------------------------------------------------------------------------------- - private void createExecuteUsing(TableDescriptor tableDesc, int dbColumnsPerLine) - { - try - { - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int size = columnDescriptorList.size(); - write("EXEC SQL EXECUTE uid USING ", true); - - //for each column, substitute, - for (int i = 0 ; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - - String indName = getIndicatorColumnName(colName); - - if (_usingIndicators) - { - if (colDesc.isNullable()) - { - write(" :dbs." + colName + ":dbs." + indName); - } - else - { - write(" :dbs." + colName); - - } - } - else - { - write(" :dbs." + colName); - } - - //if not the last column - if (i < size -1) - { - write(","); - - //only put a number of columns on a line at a time - // so go to a newline and indent - if ( (i+1) % dbColumnsPerLine == 0) - { - write("\n"); // newline - write("", true); //indent again - } - } - } - write(";\n"); //close the strcat statement - writeNewLine(); - } - catch (IOException e) - { - logError(e); - } - } - - // ---------------------------------------------------------------------------------- - private void createInsertStatement(TableDescriptor tableDesc, int dbColumnsPerLine) - { - final int numColumnsPerLine = 3; - - try - { - String tableName = tableDesc.getName(); - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int size = columnDescriptorList.size(); - write("EXEC SQL INSERT INTO " + tableName + " (", true); - - _indenter.incLevel(); - - for (int i = 0 ; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - - colName = wrapInQuotesIfNeeded(colName, false); - - write(colName); - - //if not the last column - if (i < size -1) - { - - write(","); - if ( ((i-1) % numColumnsPerLine) == 0) - { - // put in a new line - writeNewLine(); - - // indent - write("", true); - } - } - else //last column - { - //put in the closing parenthesis - writeLine(")"); - } - } - - writeLine("VALUES ("); - - //for each column, substitute, - for (int i = 0 ; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - - if(i == 0) - { - write("", true); //make it indent - } - - if (_usingIndicators) - { - if (colDesc.isNullable()) - { - write(" :dbs." + colName + ":dbs." + indName); - } - else - { - write(" :dbs." + colName); - - } - } - else - { - write(" :dbs." + colName); - } - - //if not the last column - if (i < size -1) - { - write(","); - - //only put a number of columns on a line at a time - // so go to a newline and indent - if ( (i+1) % dbColumnsPerLine == 0) - { - write("\n"); // newline - write("", true); //indent again - } - } - } - write(");\n"); //close VALUES phrase - writeNewLine(); - - - _indenter.decLevel(); - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - - private void createFetch(TableDescriptor tableDesc, String cursorName) - { - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int size = columnDescriptorList.size(); - - try - { - - writeLine("EXEC SQL FETCH " + cursorName + " INTO "); - - for (int i = 0; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - boolean isNullable = colDesc.isNullable(); - - if (i == 0) - { - write("", true); - } - - if (isNullable) - { - write(":dbs." + colName + ":dbs."+indName); - } - else - { - write(":dbs." + colName); - } - - //if not last column - if (i < size - 1) - { - // add comma - write(", ", false); - - // every 2 columns, start using a new line - // and then indent in anticipation of next line - if ( ( (i-1) % 2) == 0) - { - writeNewLine(); - write("", true); - } - } - else //last column - { - writeLine(";"); - writeNewLine(); - } - - } //end for - - } - catch (IOException e) - { - logError(e); - } - - } - // ---------------------------------------------------------------------------------- - private void createCopyCStructToDbStruct(String tableName, TableDescriptor tableDesc) - { - - int columnCount = tableDesc.getColumnDescriptorList().size(); - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - - for (int i = 0; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - int sqlType = colDesc.getSqlTypeInt(); - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - boolean isNullable = colDesc.isNullable(); - - String indicatorType = getNullTypeByInt(sqlType); - - switch(sqlType) - { - case Types.CHAR: - case Types.VARCHAR: - { - writeLine("strcpy(dbs." + colName + - ", structPtr->" + colName + ");"); - - - - break; - } - - //text field - case Types.LONGVARCHAR: - { - - writeLine("dbs." + colName + - " = malloc(strlen(structPtr->" + colName + ") + 1);") ; - writeLine("memset(dbs." + colName + ", '\\0', strlen(structPtr->" + colName + ") +1); "); - writeLine("strcpy(dbs." + colName + - ", structPtr->" + colName + ");"); - - - break; - } - - case Types.DATE: - { - if (_usingNewDateCode) - { - writeLine("dbs." + colName + - " = date_t_to_pg_date(structPtr->" + colName + ");"); - } - else - { - writeLine("dbs." + colName + - " = structPtr->" + colName + ";"); - } - - break; - } - - - case Types.TIMESTAMP: - { - if (_usingNewDateAndTimeCode) - { - writeLine("dbs." + colName + - " = timet_to_timestamp(structPtr->" + colName + ");"); - } - else - { - writeLine("dbs." + colName + - " = structPtr->" + colName + ";"); - } - - - break; - } - - - - default: - { - writeLine("dbs." + colName + - " = structPtr->" + colName + ";"); - break; - } - - } //end switch - - //add the indicator checking - if (_usingIndicators) - { - - String reference = ""; //puts in a "&" if not a string - - if (! indicatorType.equals("CHAR")) - { - reference = "&"; - } - - if (isNullable) - { - writeLine("dbs." + indName + - " = getIndicator(" + - indicatorType + - ", (void *)" + reference + "structPtr->" + colName + ");"); - } - - //space out the copying so that pairs of setNullIfIndicated and - // data copying are placed together for each column - writeNewLine(); - } - - } //end for - - - - } //end try - - catch (IOException e) - { - logError(e); - } - - - - return; - } - // ---------------------------------------------------------------------------------- - private void createErrorChecking(String tableName, String functionName, String functionSection, String returnValueString) - { - try - { - writeLine("if (SQLCODE < 0)"); - writeLine("{"); - _indenter.incLevel(); - - - writeLine("if (errorLoggingOn)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("fprintf(stderr, \"" + functionName + tableName + "() in " + functionSection + " --- ERROR\\n\");"); - writeLine("fprintf(stderr, \"SQLCODE = (%ld) sql state = (%s)\\n\", SQLCODE, sqlca.sqlstate);"); - writeLine("fprintf(stderr, \"Error Message (%s)\\n\", sqlca.sqlerrm.sqlerrmc);"); - writeLine("fflush(stderr);"); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("initDbStatus(&dbStatus);"); - - if (returnValueString != null) - { - writeLine(returnValueString); - } - - _indenter.decLevel(); - writeLine("}"); - - - } - catch(IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - - - public void generate(String connectionURL, String preferredTableNameFilePath, - String dbName, String targetDir, String driverName) - { - - - // define an instance of a the IHFS database class - Database currentDatabase = new Database(); - - if (driverName != null) - { - currentDatabase.setDriverClassName(driverName); - } - - // call the method to connect to the database - currentDatabase.connect(connectionURL); - - - //store the path of the target directory for the generated files - _targetDirName = targetDir; - - //reads a list of Preferred table names from the directory indicated by - //schemaDirName - Map preferredTableNameMap = - getMapOfPreferredTableNames(preferredTableNameFilePath); - - // returns a list of the TableDescriptors which contain metadata about - // the tables and columns. - SchemaDescriber finder = new SchemaDescriber(currentDatabase); - - - _tableDescriptorList = finder.getTableDescriptorList(preferredTableNameMap); - - - _indenter = new CodeIndenter(_indentString); - - //generate all the XXXRecord.java files - buildHeaderSrcFiles(dbName); - - //generate all the XXXTable.jar files - buildEsqlCSourceFiles(dbName); - - // disconnect from the database - currentDatabase.disconnect(); - - } //end generate - - //--------------------------------------------------------------- - // - //--------------------------------------------------------------- - public static void main(String args[]) - { - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - - String connectionURL = null; - String preferredTableNameFilePath = null; - // the database name is passed in as the third command line argument - String dbName = null; - String packageName = null; - String targetDir = null; - String driverName = null; - - - if (args.length < 5) - { - System.err.println("Usage: java CDbGen connectionURL preferredTableNameFilePath dbName targetDir driverClassName"); - } - else - // the argument count looks good - { - connectionURL = args[0]; - preferredTableNameFilePath = args[1]; - - // the database name is passed in as the third command line argument - dbName = args[2]; - - targetDir = args[3]; - - driverName = args[4]; - - // create a JDbGen object named dbgen - CDbGen dbgen = new CDbGen(); - - dbgen.generate(connectionURL, preferredTableNameFilePath, dbName, targetDir, driverName); - - System.out.println("CDBGEN completed!"); - //timer.stop("CDbGen took"); - } - - return; - - } // end of main - -} // end of JDbGen class diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/CodeIndenter.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/CodeIndenter.java deleted file mode 100755 index 47e01d97f4..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/CodeIndenter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Created on Oct 6, 2004 - * - * - */ -package ohd.hseb.dbgen; - -/** - * @author Chip Gobs - * - * This class encapsulates the indentation of code but providing access - * indentation levels and an indentation string based on those levels. - */ -public class CodeIndenter -{ - - private int _indentLevel = 0; - private String _indentString = null; - private String _totalIndentString = null; - - // --------------------------------------------------------------- - - public CodeIndenter(String indentString) - { - _indentString = indentString; - _indentLevel = 0; - } - - // --------------------------------------------------------------- - - public void incLevel() - { - incLevel(1); - } - - - // --------------------------------------------------------------- - - public void incLevel(int amount) - { - _indentLevel += amount; - _totalIndentString = null; - } - - // ---------------------------------------------------------------- - - public void decLevel(int amount) - { - _indentLevel -= amount; - - if (_indentLevel < 0) - { - _indentLevel = 0; - } - - _totalIndentString = null; - } - - // ---------------------------------------------------------------- - - public void decLevel() - { - decLevel(1); - } - - // --------------------------------------------------------------- - - public void setLevel(int level) - { - _indentLevel = level; - _totalIndentString = null; - } - - // --------------------------------------------------------------- - - public String getTotalIndentString() - { - - if (_totalIndentString == null) - { - StringBuffer indentBuffer = new StringBuffer(); - for (int i = 0; i < _indentLevel; i++) - { - indentBuffer.append(_indentString); - } - _totalIndentString = indentBuffer.toString(); - } - return _totalIndentString; - - } - - // --------------------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/ColumnDescriptor.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/ColumnDescriptor.java deleted file mode 100755 index d7b3dbef22..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/ColumnDescriptor.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Created on Aug 13, 2003 - * - * - */ -package ohd.hseb.dbgen; - -/** - * @author Chip Gobs - * - * This class encapsulates information about table columns, for the purpose of - * code generation. - */ -public class ColumnDescriptor -{ - private String _name = null; - - private int _sqlTypeInt = -1; - private String _sqlTypeString = null; - private int _size = 0; //useful for char types - - private boolean _keyColumn = false; - private boolean _nullable = true; - - public void setName(String name) - { - _name = name; - } - - public String getName() - { - return _name; - } - - - public void setSqlTypeString(String sqlTypeString) - { - _sqlTypeString = sqlTypeString; - } - /* - - public String getSqlTypeString() - { - return _sqlTypeString; - } - */ -/* - public void setResultSetType(String resultSetType) - { - _resultSetType = resultSetType; - } - - public String getResultSetType() - { - return _resultSetType; - } - - public void setJavaType(String javaType) - { - _javaType = javaType; - } - - public String getJavaType() - { - return _javaType; - } -*/ - public void setKeyColumn(boolean keyColumn) - { - _keyColumn = keyColumn; - } - - public boolean isKeyColumn() - { - return _keyColumn; - } - - /** - * @param sqlTypeInt The sqlTypeInt to set. - */ - public void setSqlTypeInt(int sqlTypeInt) - { - _sqlTypeInt = sqlTypeInt; - } - - /** - * @return Returns the sqlTypeInt. - */ - public int getSqlTypeInt() - { - return _sqlTypeInt; - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("Name = " + _name + "\n"); - buffer.append("SQL Type (Int) = " + _sqlTypeInt + "\n"); - buffer.append("SQL Type (String) = " + _sqlTypeString + "\n"); - buffer.append("size = " + _size + "\n"); - buffer.append("Is Key Column? = " + _keyColumn + "\n"); - - - return buffer.toString(); - } - - /** - * @param size The size to set. - */ - public void setSize(int size) - { - _size = size; - } - - /** - * @return Returns the size. - */ - public int getSize() - { - return _size; - } - - /** - * @param nullable The nullable to set. - */ - public void setNullable(boolean nullable) - { - _nullable = nullable; - } - - /** - * @return Returns the nullable. - */ - public boolean isNullable() - { - return _nullable; - } - - - - -} //end class ColumnDescriptor diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/JDbGen.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/JDbGen.java deleted file mode 100755 index c0c6d9729f..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/JDbGen.java +++ /dev/null @@ -1,1546 +0,0 @@ -// -// File: JDbGen.java -// Orig Author: Russell Erb 12/18/2000 -// Modified by: Russell Erb 03/30/2001 -// Russell Erb 02/27/2002 - check that lastPeriod is > 0 -// Chip Gobs 08/2003 - a number of changes including: -// using List instead of Vector -// and subclassing from DbTable and DbRecord, -// no-conversion-needed handling of the Timestamp data -// The ability to be expanded for use with other -// database types. -// Chip Gobs 9/2004 - Modified to allow it to work with PostgreSQL or Informix. - -package ohd.hseb.dbgen; - -//import ohd.hseb.util.*; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.sql.Types; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.Database; - -public class JDbGen { - // --------------------------------------------------------------- - // private data - // --------------------------------------------------------------- - - private String _generatedPackageName = null; - - private String _targetDirName = null; - - private DataOutputStream _dos = null; - - private List _tableDescriptorList = null; - - private CodeIndenter _indenter = null; - - private final String _indentString = " "; - - // for Informix mode - // private Map _javaDataTypeStringMap = null; //maps from sqlType String to - // javaDataType - // private Map _rsInterfaceTypeStringMap = null;//maps from sqlTypeString to - // result set dataType - - // for PostgreSQL and other generation modes - private Map _javaDataTypeIntegerMap = null; // maps from sqlType integer to - - // javaDataType String - private Map _rsInterfaceTypeIntegerMap = null; // maps from sqlType - - // integer to result set - // dataType - - // --------------------------------------------------------------------------------- - - public JDbGen() { - initJavaDataTypeIntegerMap(); - initResultSetDataTypeIntegerMap(); - ; - } - - // --------------------------------------------------------------------------------- - - private void addJavaDataTypeIntegerMapEntry(int sqlType, String javaType) { - _javaDataTypeIntegerMap.put(new Integer(sqlType), javaType); - } - - // ------------------------------------------------------------------------------------- - private void initJavaDataTypeIntegerMap() { - - _javaDataTypeIntegerMap = new HashMap(); - - addJavaDataTypeIntegerMapEntry(Types.DATE, "long"); - addJavaDataTypeIntegerMapEntry(Types.TIMESTAMP, "long"); - addJavaDataTypeIntegerMapEntry(Types.TIME, "long");// new one - - addJavaDataTypeIntegerMapEntry(Types.REAL, "float"); - addJavaDataTypeIntegerMapEntry(Types.FLOAT, "float"); // changed from - // double in - // OB7.2 - addJavaDataTypeIntegerMapEntry(Types.DOUBLE, "double"); - - addJavaDataTypeIntegerMapEntry(Types.NUMERIC, "double");// new one - - addJavaDataTypeIntegerMapEntry(Types.SMALLINT, "short"); - addJavaDataTypeIntegerMapEntry(Types.INTEGER, "int"); - addJavaDataTypeIntegerMapEntry(Types.BIGINT, "long"); - - addJavaDataTypeIntegerMapEntry(Types.LONGVARBINARY, "byte[]"); - addJavaDataTypeIntegerMapEntry(Types.LONGVARCHAR, "String"); // ? - // instead - // of - // byte[] - addJavaDataTypeIntegerMapEntry(Types.VARCHAR, "String"); - addJavaDataTypeIntegerMapEntry(Types.CHAR, "String"); - - addJavaDataTypeIntegerMapEntry(Types.ARRAY, "String");// new one - - } - - // ------------------------------------------------------------------------------------- - private void addResultSetTypeIntegerMapEntry(int sqlType, - String resultSetType) { - _rsInterfaceTypeIntegerMap.put(new Integer(sqlType), resultSetType); - } - - // --------------------------STAMP----------------------------------------------------------- - private void initResultSetDataTypeIntegerMap() { - _rsInterfaceTypeIntegerMap = new HashMap(); - - addResultSetTypeIntegerMapEntry(Types.DATE, "Date"); - addResultSetTypeIntegerMapEntry(Types.TIMESTAMP, "TimeStamp"); - addResultSetTypeIntegerMapEntry(Types.TIME, "Time"); // new one - - addResultSetTypeIntegerMapEntry(Types.REAL, "Real"); - addResultSetTypeIntegerMapEntry(Types.FLOAT, "Float"); - addResultSetTypeIntegerMapEntry(Types.DOUBLE, "Double"); - addResultSetTypeIntegerMapEntry(Types.NUMERIC, "Double"); // new one - - addResultSetTypeIntegerMapEntry(Types.SMALLINT, "Short"); - addResultSetTypeIntegerMapEntry(Types.INTEGER, "Int"); - addResultSetTypeIntegerMapEntry(Types.BIGINT, "Long"); - - addResultSetTypeIntegerMapEntry(Types.LONGVARBINARY, "Bytes"); - addResultSetTypeIntegerMapEntry(Types.LONGVARCHAR, "String"); - addResultSetTypeIntegerMapEntry(Types.VARCHAR, "String"); - addResultSetTypeIntegerMapEntry(Types.CHAR, "String"); - - addResultSetTypeIntegerMapEntry(Types.ARRAY, "String"); // new one - } - - // ------------------------------------------------------------------------------------- - - // --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - // --------------------------------------------------------------- - private void write(String line, boolean useIndentation) throws IOException { - if (useIndentation) { - String totalIndentString = _indenter.getTotalIndentString(); - - _dos.writeBytes(totalIndentString + line); - } else { - _dos.writeBytes(line); - } - } - - // ----------------------------------------------------------------- - private void write(String line) throws IOException { - write(line, false); // by default, do not use indentation - - return; - } - - // ----------------------------------------------------------------- - - private void writeLine(String line) throws IOException { - boolean useIndentation = true; - write(line + "\n", useIndentation); - - return; - } - - // -------------------------------------------------------------------------- - // read the list of preferred table names from a text file with the - // preferred name of the Tables and Views , 1 per line, no spaces in the - // name - // -------------------------------------------------------------------------- - private Map getMapOfPreferredTableNames(String filePath) { - Map tableNameMap = new HashMap(); - - try { - - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - String line = null; - - line = reader.readLine(); - - String preferredTableName = null; - String lowercaseTableName = null; - - while (line != null) { - preferredTableName = null; - lowercaseTableName = null; - - // System.out.println("line = " + line + ":"); - int separatorIndex = line.indexOf('='); - - if (separatorIndex > -1) { - lowercaseTableName = line.substring(0, separatorIndex) - .trim().toLowerCase(); - preferredTableName = line.substring(separatorIndex + 1) - .trim(); - } else // only one line item - { - preferredTableName = line.trim(); - lowercaseTableName = preferredTableName.toLowerCase(); - } - - tableNameMap.put(lowercaseTableName, preferredTableName); - - System.out.println("JDbGen.getMapOfPreferredTableNames(): " - + lowercaseTableName + " -> " + preferredTableName); - - line = reader.readLine(); - } // end while - - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - return tableNameMap; - } - - // --------------------------------------------------------------------------------- - private Map getMapOfPreferredTableNames_old(String filePath) { - Map tableNameMap = new HashMap(); - - try { - - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - String line = null; - - line = reader.readLine(); - - while (line != null) { - // System.out.println("line = " + line + ":"); - - String preferredTableName = line.trim(); - String lowercaseTableName = preferredTableName.toLowerCase(); - - tableNameMap.put(lowercaseTableName, preferredTableName); - - System.out.println("JDbGen.getMapOfPreferredTableNames(): " - + lowercaseTableName + " -> " + preferredTableName); - - line = reader.readLine(); - } // end while - - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - return tableNameMap; - } - - // --------------------------------------------------------------------------------- - - private String getJavaDataTypeByInt(int sqlType) { - String javaDataType = null; - - javaDataType = (String) _javaDataTypeIntegerMap - .get(new Integer(sqlType)); - if (javaDataType == null) { - javaDataType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return javaDataType; - } - - // --------------------------------------------------------------------------------- - - private String getRSInterfaceTypeByInt(int sqlType) { - String resultSetDataType = null; - - resultSetDataType = (String) _rsInterfaceTypeIntegerMap - .get(new Integer(sqlType)); - if (resultSetDataType == null) { - resultSetDataType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return resultSetDataType; - - } - - // --------------------------------------------------------------------------------- - // buildRecordSrcFiles - - private void buildRecordSrcFiles(String dbName) { - try { - // Strings to hold Table name and File name - String tableName = null; - String fileName = null; - - // loop through all the table names and build source files - for (int ctr = 0; ctr < _tableDescriptorList.size(); ctr++) { - TableDescriptor tableDesc = (TableDescriptor) _tableDescriptorList - .get(ctr); - tableName = tableDesc.getName(); - - fileName = tableName + "Record.java"; - - FileOutputStream fos = new FileOutputStream(_targetDirName - + "/" + fileName); - _dos = new DataOutputStream(fos); - - createRecordFileBanner(tableName, fileName, dbName, tableDesc); - createRecordPrivateData(tableDesc); - createRecordEmptyConstructor(tableName); - createRecordCopyConstructor(tableName, tableDesc); - createRecordSetGet(tableName, tableDesc); - - if ((!tableDesc.isView()) && (tableDesc.hasPrimaryKey())) { - createRecordGetWhereString(tableDesc); - } - createRecordToString(tableDesc); - - _indenter.setLevel(0); - writeLine("} // end of " + tableName + "Record class\n"); - - _dos.close(); - // fos.close(); - } - } catch (IOException ioe) { - System.err - .println("buildRecordSrcFiles(): Something went wrong trying to write " - + ioe); - } - - } // end of buildRecordSrcFiles method - - // ----------------------------------------------------------------- - // createRecordFileBanner - // ----------------------------------------------------------------- - private void createRecordFileBanner(String tableName, String fileName, - String dbName, TableDescriptor tableDesc) { - try { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - System.out.println("building source code for " + fileName); - - if (tableDesc.isView()) { - writeLine("// This is a view record !"); - } - - writeLine("// filename: " + fileName); - writeLine("// author : DBGEN"); - writeLine("// created : " + currentTime + " using database " - + dbName); - writeLine("// description: This class is used to get data from and put data into a"); - writeLine("// " + tableName + " table record format"); - writeLine("//\n"); - - if (_generatedPackageName.length() > 0) { - writeLine("package " + _generatedPackageName + ";\n"); - } - - writeLine("import ohd.hseb.db.*;\n"); - writeLine("public class " + tableName + "Record extends DbRecord"); - writeLine("{"); - } catch (IOException ioe) { - System.out - .println("createRecordFileBanner(): Something went wrong trying to write " - + ioe); - } - - } // end of createRecordFileBanner method - - // ----------------------------------------------------------------- - // createRecordPrivateData - // ----------------------------------------------------------------- - private void createRecordPrivateData(TableDescriptor tableDesc) { - try { - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - _indenter.setLevel(1); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - String javaDataType = getJavaDataTypeByInt(columnDesc - .getSqlTypeInt()); - String columnName = columnDesc.getName(); - - writeLine("private " + javaDataType + " " + columnName + ";\n"); - } - - } catch (IOException ioe) { - System.err - .println("createRecordPrivateData(): Something went wrong trying to write " - + ioe); - } - - } // end of createRecordPrivateData method - - // --------------------------------------------------------- - // createRecordEmptyConstructor - // -------------------------------------------------------- - private void createRecordEmptyConstructor(String tableName) { - - try { - writeLine("//---------------------------------------------------------------"); - writeLine("// Empty constructor"); - writeLine("//---------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public " + tableName + "Record()"); - writeLine("{"); - writeLine("}\n"); - - } catch (IOException ioe) { - System.err - .println("createRecordEmptyConstructor(): Something went wrong trying to write " - + ioe); - } - - } // end of createRecordEmptyConstructor method - - // --------------------------------------------------------- - // createRecordCopyConstructor - // -------------------------------------------------------- - private void createRecordCopyConstructor(String tableName, - TableDescriptor tableDesc) { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try { - writeLine("//-----------------------------------------------------------------"); - writeLine("// Copy constructor"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public " + tableName + "Record(" + tableName - + "Record origRecord)"); - writeLine("{"); - _indenter.incLevel(); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - - String columnName = colDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - writeLine("set" + newName + "(origRecord.get" + newName - + "());"); - - } // end for each column - - _indenter.decLevel(); - writeLine("}\n"); - - } catch (IOException ioe) { - System.err - .println("createRecordCopyConstructor(): Something went wrong trying to write " - + ioe); - } - - } // end of createRecordCopyConstructor method - - // --------------------------------------------------------------- - // createRecordSetGet - // --------------------------------------------------------------- - private void createRecordSetGet(String tableName, TableDescriptor tableDesc) { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try { - writeLine("//-----------------------------------------------------------------"); - writeLine("// get and set methods for all data items in a " - + tableName + " record\n"); - writeLine("//-----------------------------------------------------------------"); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - String javaDataType = getJavaDataTypeByInt(colDesc - .getSqlTypeInt()); - String columnName = colDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - // create the getter - writeLine("public " + javaDataType + " get" + newName + "()"); - - writeLine("{"); - - _indenter.incLevel(); - writeLine("return " + columnName + ";"); - - _indenter.decLevel(); - writeLine("}\n"); - - // create the setter - writeLine("public void set" + newName + "(" + javaDataType - + " " + columnName + ")"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("this." + columnName + " = " + columnName + " ;"); - - _indenter.decLevel(); - writeLine("}\n"); - - } - - } catch (IOException ioe) { - System.err - .println("createRecordSetGet(): Something went wrong trying to write " - + ioe); - } - - } // end of createRecordSetGet method - - // --------------------------------------------------------------- - // createRecordGetWhereString - // --------------------------------------------------------------- - private void createRecordGetWhereString(TableDescriptor tableDesc) { - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// getWhereString() - this method is called with no arguments"); - writeLine("// and returns a String that contains a valid where clause containing all the"); - writeLine("// primary key fields."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public String getWhereString()"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("String outString = "); - - _indenter.incLevel(); - _indenter.incLevel(); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - write("\"WHERE ", true); - - int keyColumnCount = 0; - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - - // String sqlDataType = columnDesc.getSqlTypeString(); - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - - // String javaDataType = columnDesc.getJavaType(); - String columnName = columnDesc.getName(); - - boolean isKeyColumn = columnDesc.isKeyColumn(); - - // append the pieces to the WHERE clause - if (isKeyColumn) { - keyColumnCount++; - if (keyColumnCount != 1) // not first one - { - write(" + \" AND ", true); - } - - /* - * if (sqlDataType.equalsIgnoreCase("DateTime")) { - * write(columnName + " = '\" + - * getDateTimeStringFromLongTime(" + columnName + ")" + " + - * \"'\" \n"); } else if - * (sqlDataType.equalsIgnoreCase("Date")) { write(columnName + " = - * '\" + getDateStringFromLongTime(" + columnName + ")" + " + - * \"'\" \n"); } - */ - if (sqlDataTypeInt == Types.TIMESTAMP) { - write(columnName - + " = '\" + getDateTimeStringFromLongTime(" - + columnName + ")" + " + \"'\" \n"); - } else if (sqlDataTypeInt == Types.DATE) { - write(columnName - + " = '\" + getDateStringFromLongTime(" - + columnName + ")" + " + \"'\" \n"); - } - - else // the usual - { - write(columnName + " = '\" + " + columnName - + " + \"'\" \n"); - } - - } // end isKeyColumn - - }// end for loop - - writeLine(";"); - - // writeLine("\"\" ;"); - - // get rid of extra indents - _indenter.decLevel(); - _indenter.decLevel(); - - writeLine("return outString;"); - - _indenter.decLevel(); - writeLine("} // end toString()"); - - } catch (IOException ioe) { - System.err - .println("createRecordGetWhereString(): Something went wrong trying to write " - + ioe); - } - - } // end of CreateRecordGetWhereString method - - // --------------------------------------------------------------- - // createRecordToString - // --------------------------------------------------------------- - private void createRecordToString(TableDescriptor tableDesc) { - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// toString() - this method is called with no arguments"); - writeLine("// and returns a String of the internal values"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public String toString()"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("String outString = "); - - _indenter.incLevel(); - _indenter.incLevel(); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - // String sqlDataType = columnDesc.getSqlTypeString(); - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - // String javaDataType = columnDesc.getJavaType(); - String columnName = columnDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - /* - * if (sqlDataType.equalsIgnoreCase("DateTime")) { - * writeLine("getDateTimeStringFromLongTime(get" + newName + - * "()) + \" \" +"); } else if - * (sqlDataType.equalsIgnoreCase("Date")) { - * writeLine("getDateStringFromLongTime(get" + newName + "()) + \" \" - * +"); } - */ - - if (sqlDataTypeInt == Types.TIMESTAMP) { - writeLine("getDateTimeStringFromLongTime(get" + newName - + "()) + \" \" +"); - } else if (sqlDataTypeInt == Types.DATE) { - writeLine("getDateStringFromLongTime(get" + newName - + "()) + \" \" +"); - } else { - writeLine("get" + newName + "() + \" \" +"); - } - } - - writeLine("\"\" ;"); - - // get rid of extra indents - _indenter.decLevel(); - _indenter.decLevel(); - - writeLine("return outString;"); - - _indenter.decLevel(); - writeLine("} // end toString()"); - - } catch (IOException ioe) { - System.err - .println("createRecordToString(): Something went wrong trying to write " - + ioe); - } - - } // end of CreateRecordToString method - - // --------------------------------------------------------------- - // buildTableSrcFiles - // --------------------------------------------------------------- - private void buildTableSrcFiles(String dbName) { - - try { - // Strings to hold Table name and File name - String tableName = null; - String originalTableName = null; - String fileName = null; - - // loop through all the table names and build source files - for (int ctr = 0; ctr < _tableDescriptorList.size(); ctr++) { - TableDescriptor tableDesc = (TableDescriptor) _tableDescriptorList - .get(ctr); - tableName = tableDesc.getName(); - originalTableName = tableDesc.getOriginalCaseTableName(); - - if (tableDesc.isView()) { - fileName = tableName + "View.java"; - } else { - fileName = tableName + "Table.java"; - } - - FileOutputStream fos = new FileOutputStream(_targetDirName - + "/" + fileName); - _dos = new DataOutputStream(fos); - - createTableFileBanner(tableName, fileName, dbName, tableDesc); - createTableData(); - - createTableConstructor(tableName, tableDesc); - createTableSelect(tableName, originalTableName, tableDesc); - createTableSelectNRecords(tableName, originalTableName, - tableDesc); - - if (!tableDesc.isView()) // is a regular table - { - createTableInsert(tableName, tableDesc); - - // all regular tables have this - createTableDelete1(tableName, originalTableName); - createTableUpdate1(tableName, originalTableName, tableDesc); - - // only regular tables with primary keys also have this - if (tableDesc.hasPrimaryKey()) { - createTableDelete2(tableName, originalTableName); - createTableUpdate2(tableName, originalTableName, - tableDesc); - createTableInsertOrUpdate(tableName); - } - - } - - _indenter.setLevel(0); - writeLine("} // end of " + tableName + "Table class"); - - _dos.close(); - // fos.close(); - } - } catch (IOException ioe) { - System.out - .println("buildTableSrcFiles(): Something went wrong trying to write " - + ioe); - } - - } // end of buildTableSrcFiles method - - // --------------------------------------------------------------- - // createTableFileBanner - // --------------------------------------------------------------- - private void createTableFileBanner(String tableName, String fileName, - String dbName, TableDescriptor tableDesc) { - try { - // current time - Date currentTime = new Date(); - - System.out.println("building source code for " + fileName); - - _indenter.setLevel(0); - - writeLine("// filename: " + fileName); - writeLine("// author : DBGEN"); - writeLine("// created : " + currentTime + " using database " - + dbName); - writeLine("// description: This class is used to get data from and put data into the"); - writeLine("// " + tableDesc.getOriginalCaseTableName() - + " table of an IHFS database"); - writeLine("//"); - - if (_generatedPackageName.length() > 0) { - writeLine("package " + _generatedPackageName + ";\n"); - } - - writeLine("import java.sql.*;\n"); - writeLine("import java.util.*;\n"); - writeLine("import ohd.hseb.db.*;\n"); - - if (tableDesc.isView()) { - writeLine("public class " + tableName + "View extends DbTable"); - } else // regular table - { - writeLine("public class " + tableName + "Table extends DbTable"); - } - - writeLine("{"); - } catch (IOException ioe) { - System.out - .println("createTableFileBanner(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableFileBanner method - - // --------------------------------------------------------------- - // createTableConstructors - // --------------------------------------------------------------- - private void createTableData() { - try { - - writeLine("//-----------------------------------------------------------------"); - writeLine("// Private data"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("private int _recordsFound = -1;"); - - } catch (IOException ioe) { - System.err - .println("createTableData(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableData method - - // --------------------------------------------------------------- - // createTableConstructor - // --------------------------------------------------------------- - private void createTableConstructor(String tableName, - TableDescriptor tableDesc) { - - String originalTableName = tableDesc.getOriginalCaseTableName(); - - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// " - + tableName - + "Table() - constructor to set statement variable and initialize"); - writeLine("//\t\tnumber of records found to zero"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - - if (tableDesc.isView()) { - writeLine("public " + tableName + "View(Database database) "); - } else { - writeLine("public " + tableName + "Table(Database database) "); - } - - writeLine("{"); - - _indenter.incLevel(); - writeLine("//Constructor calls DbTable's constructor"); - writeLine("super(database);"); - writeLine("setTableName(\"" + tableDesc.getOriginalCaseTableName() - + "\");"); - - _indenter.decLevel(); - writeLine("}\n\n"); - - } catch (IOException e) { - e.printStackTrace(); - } - } // end createTableConstructor - // --------------------------------------------------------------- - // createTableSelect - // --------------------------------------------------------------- - - private void createTableSelect(String tableName, String originalTableName, - TableDescriptor tableDesc) { - - try { - writeLine("//-----------------------------------------------------------------"); - writeLine("// select() - this method is called with a where clause and returns"); - writeLine("//\t\ta List of " + tableName + "Record objects"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public List select(String where) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine(tableName + "Record record = null;\n"); - writeLine("// create a List to hold " + tableName + " Records"); - writeLine("List recordList = new ArrayList();\n"); - writeLine("// set number of records found to zero"); - writeLine("_recordsFound = 0;\n"); - writeLine("// Create the SQL statement and issue it"); - - writeLine("// construct the select statment"); - writeLine("String selectStatement = \"SELECT * FROM " - + originalTableName + " \" + where;\n"); - writeLine("// get the result set back from the query to the database"); - writeLine("ResultSet rs = getStatement().executeQuery(selectStatement);\n"); - writeLine("// loop through the result set"); - writeLine("while (rs.next())"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("// create an instance of a " + tableName + "Record"); - writeLine("// and store its address in oneRecord"); - writeLine("record = new " + tableName + "Record();\n"); - writeLine("// increment the number of records found"); - writeLine("_recordsFound++;\n"); - writeLine("// assign the data returned to the result set for one"); - writeLine("// record in the database to a " + tableName - + "Record object\n"); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int index = -1; - - for (int i = 0; i < columnDescriptorList.size(); i++) { - index = i + 1; - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - // String sqlDataType = columnDesc.getSqlTypeString(); - - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - - String columnName = columnDesc.getName(); - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - writeLine("record.set" + newName + "(get" + rsInterfaceType - + "(rs, " + index + "));"); - - } // end for - - writeLine(""); - - writeLine("// add this " + tableName + "Record object to the list"); - writeLine("recordList.add(record);"); - - _indenter.decLevel(); - writeLine("}"); - writeLine("// Close the result set"); - writeLine("rs.close();\n"); - - // create the code to return the recordList - writeLine("// return a List which holds the " + tableName - + "Record objects"); - - writeLine("return recordList;\n"); - - _indenter.decLevel(); - writeLine("} // end of select method\n"); - } catch (IOException ioe) { - System.err - .println("createTableSelect(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableSelect method - - // --------------------------------------------------------------- - // createTableSelect - // --------------------------------------------------------------- - private void createTableSelectNRecords(String tableName, - String originalTableName, TableDescriptor tableDesc) { - try { - writeLine("//-----------------------------------------------------------------"); - writeLine("// selectNRecords() - this method is called with a where clause and returns"); - writeLine("//\t\ta List filled with a maximum of maxRecordCount of " - + tableName + "Record objects "); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public List selectNRecords(String where, int maxRecordCount) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine(tableName + "Record record = null;\n"); - writeLine("// create a List to hold " + tableName + " Records"); - writeLine("List recordList = new ArrayList();\n"); - writeLine("// set number of records found to zero"); - writeLine("_recordsFound = 0;\n"); - writeLine("// Create the SQL statement and issue it"); - - writeLine("// construct the select statment"); - writeLine("String selectStatement = \"SELECT * FROM " - + originalTableName + " \" + where;\n"); - writeLine("// get the result set back from the query to the database"); - writeLine("ResultSet rs = getStatement().executeQuery(selectStatement);\n"); - writeLine("// loop through the result set"); - writeLine("while (rs.next())"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("// create an instance of a " + tableName + "Record"); - writeLine("// and store its address in oneRecord"); - writeLine("record = new " + tableName + "Record();\n"); - writeLine("// increment the number of records found"); - writeLine("_recordsFound++;\n"); - writeLine("// assign the data returned to the result set for one"); - writeLine("// record in the database to a " + tableName - + "Record object\n"); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int index = -1; - - for (int i = 0; i < columnDescriptorList.size(); i++) { - index = i + 1; - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - // String sqlDataType = columnDesc.getSqlTypeString(); - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - // String javaDataType = columnDesc.getJavaType(); - String columnName = columnDesc.getName(); - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - writeLine("record.set" + newName + "(get" + rsInterfaceType - + "(rs, " + index + "));"); - - } // end for - - writeLine(""); - - writeLine("// add this " + tableName + "Record object to the list"); - writeLine("recordList.add(record);"); - - writeLine("if (_recordsFound >= maxRecordCount)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("break;"); - - _indenter.decLevel(); - writeLine("}"); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("// Close the result set"); - writeLine("rs.close();\n"); - - // create the code to return the recordList - writeLine("// return a List which holds the " + tableName - + "Record objects"); - - writeLine("return recordList;\n"); - - _indenter.decLevel(); - writeLine("} // end of selectNRecords method\n"); - } catch (IOException ioe) { - System.err - .println("createTableSelectNRecords(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableSelectNRecords method - // --------------------------------------------------------------- - // createTableInsert - // --------------------------------------------------------------- - - private void createTableInsert(String tableName, - TableDescriptor tableDescriptor) { - String originalTableName = tableDescriptor.getOriginalCaseTableName(); - - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// insert() - this method is called with a " - + tableName + "Record object and.."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int insert(" + tableName - + "Record record) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;\n"); - writeLine("// Create a SQL insert statement and issue it"); - - writeLine("// construct the insert statement"); - writeLine("PreparedStatement insertStatement = getConnection().prepareStatement("); - write("\" INSERT INTO " + originalTableName + " VALUES ("); - - List columnDescriptorList = tableDescriptor - .getColumnDescriptorList(); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - if (i == 0) { - write("?"); - } else { - write(", ?"); - } - } - - writeLine(")\");\n"); - - int index = -1; - for (int i = 0; i < columnDescriptorList.size(); i++) { - index = i + 1; - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - - int sqlDataTypeInt = colDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - // String sqlDataType = colDesc.getSqlTypeString(); - - String columnName = colDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - writeLine("set" + rsInterfaceType + "(insertStatement, " - + index + ", record.get" + newName + "());"); - - } - - writeLine(""); - - writeLine("// get the number of records processed by the insert"); - writeLine("returnCode = insertStatement.executeUpdate();\n"); - // writeLine("System.out.println(\"returnCode from putRecord = \" + - // returnCode);"); - - writeLine("return returnCode;\n"); - - _indenter.decLevel(); - writeLine("} // end of insert method\n"); - } catch (IOException ioe) { - System.err - .println("createTableInsert(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableInsert method - - // --------------------------------------------------------------- - // createTableDelete1 - // --------------------------------------------------------------- - private void createTableDelete1(String tableName, String originalTableName) { - - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// delete() - this method is called with a where clause and returns"); - writeLine("// the number of records deleted"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int delete(String where) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;\n"); - writeLine("// Create a SQL delete statement and issue it"); - - writeLine("// construct the delete statement"); - writeLine("String deleteStatement = \"DELETE FROM " - + originalTableName + " \" + where;\n"); - writeLine("// get the number of records processed by the delete"); - writeLine("returnCode = getStatement().executeUpdate(deleteStatement);\n"); - - // writeLine("System.out.println(\"returnCode from delete = \" + - // returnCode);"); - - writeLine("return returnCode;"); - - _indenter.decLevel(); - writeLine("} // end of delete method \n"); - } catch (IOException ioe) { - System.err - .println("createTableDelete1(): Something went wrong trying to write " - + ioe); - } - - } // end of createDelete1 method - - // --------------------------------------------------------------- - // createTableDelete2 - // --------------------------------------------------------------- - private void createTableDelete2(String tableName, String originalTableName) { - - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// delete() - this method is called with a where clause and returns"); - writeLine("// the number of records deleted"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int delete(" + tableName - + "Record record) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;\n"); - writeLine("// Create a SQL delete statement and issue it"); - - writeLine("// construct the delete statement"); - writeLine("String deleteStatement = \"DELETE FROM " - + originalTableName + " \" + record.getWhereString();\n"); - writeLine("// get the number of records processed by the delete"); - writeLine("returnCode = getStatement().executeUpdate(deleteStatement);\n"); - - // writeLine("System.out.println(\"returnCode from delete = \" + - // returnCode);"); - - writeLine("return returnCode;"); - - _indenter.decLevel(); - writeLine("} // end of delete method \n"); - } catch (IOException ioe) { - System.err - .println("createTableDelete2(): Something went wrong trying to write " - + ioe); - } - - } // end of createDelete2 method - - // --------------------------------------------------------------- - // createTableUpdate1 - // --------------------------------------------------------------- - private void createTableUpdate1(String tableName, String originalTableName, - TableDescriptor tableDesc) { - - try { - _indenter.setLevel(0); - - writeLine("//-----------------------------------------------------------------"); - writeLine("// update() - this method is called with a " - + tableName + "Record object and a where clause.."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int update(" + tableName - + "Record record, String where) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;"); - writeLine("// Create a SQL update statement and issue it"); - - writeLine("// construct the update statement"); - writeLine("PreparedStatement updateStatement = getConnection().prepareStatement("); - write("\" UPDATE " + originalTableName + " SET "); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - String columnName = colDesc.getName(); - - if (i == 0) { - write(columnName + " = ?"); - - } else { - write(", " + columnName + " = ?"); - } - - } // end for - - writeLine("\" + where );\n"); - int index = -1; - - for (int i = 0; i < columnDescriptorList.size(); i++) { - index = i + 1; - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - String columnName = colDesc.getName(); - - // String sqlDataType = colDesc.getSqlTypeString(); - int sqlDataTypeInt = colDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - String firstChar = String.valueOf(columnName.charAt(0)); - - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - writeLine("set" + rsInterfaceType + "(updateStatement, " - + index + ", record.get" + newName + "());"); - - } // end for - - writeLine("// get the number of records processed by the update"); - writeLine("returnCode = updateStatement.executeUpdate();\n"); - // writeLine("System.out.println(\"returnCode from updateRecord = \" - // + returnCode);"); - - writeLine("return returnCode;\n"); - - _indenter.decLevel(); - writeLine("} // end of updateRecord method\n"); - } - - catch (IOException ioe) { - System.err - .println("createTableUpdate1(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableUpdate1 method - - // --------------------------------------------------------------- - // createTableUpdate2 - // --------------------------------------------------------------- - private void createTableUpdate2(String tableName, String originalTableName, - TableDescriptor tableDesc) { - - try { - _indenter.setLevel(0); - - writeLine("//-----------------------------------------------------------------"); - writeLine("// update() - this method is called with a " - + tableName + "Record object and a where clause.."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int update(" + tableName + "Record oldRecord, " - + tableName + "Record newRecord) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;"); - writeLine("// Create a SQL update statement and issue it"); - - writeLine("// construct the update statement"); - writeLine("PreparedStatement updateStatement = getConnection().prepareStatement("); - write("\" UPDATE " + originalTableName + " SET "); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - for (int i = 0; i < columnDescriptorList.size(); i++) { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - String columnName = colDesc.getName(); - - if (i == 0) { - write(columnName + " = ?"); - - } else { - write(", " + columnName + " = ?"); - } - - } // end for - - writeLine("\" + oldRecord.getWhereString() );\n"); - int index = -1; - - for (int i = 0; i < columnDescriptorList.size(); i++) { - index = i + 1; - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList - .get(i); - String columnName = colDesc.getName(); - // String sqlDataType = colDesc.getSqlTypeString(); - int sqlDataTypeInt = colDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - String firstChar = String.valueOf(columnName.charAt(0)); - - String newName = firstChar.toUpperCase() - + columnName.substring(1); - - writeLine("set" + rsInterfaceType + "(updateStatement, " - + index + ", newRecord.get" + newName + "());"); - - } // end for - - writeLine("// get the number of records processed by the update"); - writeLine("returnCode = updateStatement.executeUpdate();\n"); - // writeLine("System.out.println(\"returnCode from updateRecord = \" - // + returnCode);"); - - writeLine("return returnCode;\n"); - - _indenter.decLevel(); - writeLine("} // end of updateRecord method\n"); - } - - catch (IOException ioe) { - System.err - .println("createTableUpdate2(): Something went wrong trying to write " - + ioe); - } - - } // end of createTableUpdate2 method - - private void createTableInsertOrUpdate(String tableName) { - - try { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// insertOrUpdate() - this method is call with a " - + tableName + "Record object."); - writeLine("// the number of records inserted or updated"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int insertOrUpdate(" + tableName - + "Record record) throws SQLException"); - writeLine("{"); - _indenter.incLevel(); - writeLine("int returnCode=-999;"); - writeLine("List recordList = select(record.getWhereString());\n"); - - writeLine("if (recordList.size() < 1)"); - writeLine("{"); - _indenter.incLevel(); - writeLine("returnCode = insert(record);"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - - writeLine(tableName + "Record oldRecord = (" + tableName - + "Record) recordList.get(0);"); - writeLine("returnCode = update(oldRecord, record);"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("return returnCode;"); - - _indenter.decLevel(); - writeLine("} // end of insertOrUpdate() "); - } catch (IOException ioe) { - System.err - .println("createTableInsertOrUpdate(): Something went wrong trying to write " - + ioe); - } - } // end of createTableInsertOrUpdate() - - // --------------------------------------------------------------- - // generate - calls all the methods to cause code to be generated - // --------------------------------------------------------------- - - public void generate(String connectionURL, - String preferredTableNameFilePath, String dbName, - String generatedPackageName, String targetDir, String driverName) { - - // define an instance of a the IHFS database class - Database currentDatabase = new Database(); - - if (driverName != null) { - currentDatabase.setDriverClassName(driverName); - } - - // call the method to connect to the database - currentDatabase.connect(connectionURL); - - // store the name of the package to which the generated classes will - // belong - _generatedPackageName = generatedPackageName; - - // store the path of the target directory for the generated files - _targetDirName = targetDir; - - // reads a list of Preferred table names from the directory indicated by - // schemaDirName - Map preferredTableNameMap = getMapOfPreferredTableNames(preferredTableNameFilePath); - - // returns a list of the TableDescriptor which contains metadata about - // the - // tables and columns. This is the method that needs to be overridden - // when - // a database driver requires a custom way of extracting the metadata. - SchemaDescriber finder = new SchemaDescriber(currentDatabase); - - _tableDescriptorList = finder - .getTableDescriptorList(preferredTableNameMap); - - _indenter = new CodeIndenter(_indentString); - - // generate all the XXXRecord.java files - buildRecordSrcFiles(dbName); - - // generate all the XXXTable.jar files - buildTableSrcFiles(dbName); - - // disconnect from the database - currentDatabase.disconnect(); - - } // end generate - - // --------------------------------------------------------------- - - // --------------------------------------------------------------- - public static void main(String args[]) { - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - - String connectionURL = null; - String preferredTableNameFilePath = null; - // the database name is passed in as the third command line argument - String dbName = null; - String packageName = null; - String targetDir = null; - String driverName = null; - - if (args.length < 5) { - System.err - .println("Usage: java JDbGen connectionURL preferredTableNameFilePath dbName packageName targetDir [driverClassName]"); - System.exit(-1); - } else // the argument count looks good - { - connectionURL = args[0]; - preferredTableNameFilePath = args[1]; - - // the database name is passed in as the third command line argument - dbName = args[2]; - - packageName = args[3]; - if (packageName.equals("NONE")) { - packageName = ""; - } - - targetDir = args[4]; - - if (args.length > 5) { - driverName = args[5]; - - } - - // create a JDbGen object named dbgen - JDbGen dbgen = new JDbGen(); - - dbgen.generate(connectionURL, preferredTableNameFilePath, dbName, - packageName, targetDir, driverName); - - System.out.println("JDBGEN completed!"); - // timer.stop("JDbGen took"); - } - - return; - - } // end of main - -} // end of JDbGen class diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/SchemaDescriber.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/SchemaDescriber.java deleted file mode 100755 index d58806e1ee..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/SchemaDescriber.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Created on Sep 16, 2004 - * - * - */ -package ohd.hseb.dbgen; - - -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbType; - -/** - * @author GobsC - * - * This class encapsulates the discovery of the database schema for code generation purposes. - */ -public class SchemaDescriber -{ - - private Database _db; - private DbType _dbType = null; - - - // --------------------------------------------------------------------------------- - - public SchemaDescriber(Database database) - { - _db = database; - _dbType = _db.getDbType(); - } - //------------------------------------------------------------------------------------- - - public List getTableDescriptorList(Map preferredTableNameMap) - { - List descriptorList = null; - - - if (_dbType == DbType.Informix) - { - descriptorList = getInformixTableDescriptorList(preferredTableNameMap); - } - else //use the PostgreSQL way, which we assume to be more standard - { - descriptorList = getPostgreSQLTableDescriptorList(preferredTableNameMap); - } - - return descriptorList; - - } - - - //------------------------------------------------------------------------------------- - - - public List getPostgreSQLTableDescriptorList(Map preferredTableNameMap) - { - String header = "getPostgreSQLTableDescriptorList(): "; - List tdList = new ArrayList(); - - try - { - - // Database Meta Data object - DatabaseMetaData dbmd = _db.getConnection().getMetaData(); - - - //get all the info on regular tables - - boolean isView = false; - - // get the basic info on all the true tables - // added capitalized "TABLE" for postgresql - String[] tableTypesStringArray = { "table", "TABLE" }; - isView = false; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray, tdList); - - // get the basic info on all the views - String[] tableTypesStringArray2 = { "view", "VIEW" }; - // added capitalized "VIEW" for postgresql - isView = true; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray2, tdList); - - - - // create column descriptors for each table or view - for (int i = 0; i < tdList.size(); i++) - { - TableDescriptor tableDesc = (TableDescriptor) tdList.get(i); - String origCaseTableName = tableDesc.getOriginalCaseTableName(); - - // get the column info for all tables and views - // ResultSet rsForColumn = dbmd.getColumns("", "", tableName, - // "%"); - ResultSet rsForColumn = dbmd.getColumns(null, null, - origCaseTableName, "%"); - - // get the primary keys for this particular table - // and store them in a set - // ResultSet rsForKeys = dbmd.getPrimaryKeys("", "", tableName); - ResultSet rsForKeys = dbmd.getPrimaryKeys(null, null, - origCaseTableName); - - Set keySet = new HashSet(); - while (rsForKeys.next()) - { - String keyColumnName = rsForKeys.getString(4); - keySet.add(keyColumnName.toLowerCase()); - } - - if (keySet.size() > 0) - { - tableDesc.setHasPrimaryKey(true); - } - else - { - tableDesc.setHasPrimaryKey(false); - } - - - // for each column, make a corresponding ColumnDescriptor and - // add it to the list contained by the TableDescriptor - while (rsForColumn.next()) - { - String columnName = rsForColumn.getString(4).trim(); - - int sqlTypeInt = rsForColumn.getInt(5); - String sqlTypeString = rsForColumn.getString(6).trim(); - - boolean isNullable = false; - int nullableCode = rsForColumn.getInt(11); - if ( (nullableCode == DatabaseMetaData.columnNullable) || - (nullableCode == DatabaseMetaData.columnNullableUnknown) - ) - { - isNullable = true; - } - else - { - isNullable = false; - - /* - System.out.println("DatabaseMetaData.columnNoNulls = " + - DatabaseMetaData.columnNoNulls); - System.out.println("************ nullablecode = " + - nullableCode + " for " + columnName + - " in " + tableDesc.getName()); - */ - } - - - - //special case for PostgreSQL text field - // needed because it comes out as Types.VARCHAR - if (sqlTypeString.equals("text")) - { - sqlTypeInt = Types.LONGVARCHAR; - } - - int colSize = rsForColumn.getInt(7); - - - ColumnDescriptor colDesc = new ColumnDescriptor(); - colDesc.setName(columnName); - colDesc.setSqlTypeInt(sqlTypeInt); - colDesc.setSqlTypeString(sqlTypeString); - colDesc.setSize(colSize); - colDesc.setNullable(isNullable); - - // set the KeyColumn boolean field as appropriate - if (keySet.contains(columnName.toLowerCase())) - { - colDesc.setKeyColumn(true); - } - else - { - colDesc.setKeyColumn(false); - } - - // add the columnDescriptor to the tableDescriptor's list - tableDesc.getColumnDescriptorList().add(colDesc); - - - } //end while - - //System.out.println(header + "tableDesc = " + tableDesc); - - - } //end for - - - - } - catch (SQLException e) - { - System.out.println(this.getClass().getName() - + ".getTableDescriptorList():" + " Problem with SQL " - + e.getMessage()); - e.printStackTrace(); - } - return tdList; - - } //end getPostgreSQLTableDescriptorList - - //------------------------------------------------------------------------------------- - public List getInformixTableDescriptorList(Map preferredTableNameMap) - { - List tdList = new ArrayList(); - System.out.println("getInformixTableDescriptorList(): begin"); - try - { - - // Database Meta Data object - DatabaseMetaData dbmd = _db.getConnection().getMetaData(); - - - //get all the info on regular tables - - boolean isView = false; - - // get the basic info on all the true tables - String[] tableTypesStringArray = { "table"}; - isView = false; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray, tdList); - - // get the basic info on all the views - String[] tableTypesStringArray2 = { "view"}; - isView = true; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray2, tdList); - - - - // create column descriptors for each table or view - for (int i = 0; i < tdList.size(); i++) - { - TableDescriptor tableDesc = (TableDescriptor) tdList.get(i); - String origCaseTableName = tableDesc.getOriginalCaseTableName(); - - // get the column info for all tables and views - ResultSet rsForColumn = dbmd.getColumns("", "", origCaseTableName, "%"); - - // get the primary keys for this particular table - // and store them in a set - ResultSet rsForKeys = dbmd.getPrimaryKeys("", "", origCaseTableName); - - - Set keySet = new HashSet(); - while (rsForKeys.next()) - { - String keyColumnName = rsForKeys.getString(4); - keySet.add(keyColumnName.toLowerCase()); - } - - if (keySet.size() > 0) - { - tableDesc.setHasPrimaryKey(true); - } - else - { - tableDesc.setHasPrimaryKey(false); - } - - - - // for each column, make a corresponding ColumnDescriptor and - // add it to the list contained by the TableDescriptor - while (rsForColumn.next()) - { - String columnName = rsForColumn.getString(4).trim(); - - String sqlTypeString = rsForColumn.getString(6).trim(); - - int sqlTypeInt = rsForColumn.getInt(5); - - ColumnDescriptor colDesc = new ColumnDescriptor(); - colDesc.setName(columnName); - colDesc.setSqlTypeInt(sqlTypeInt); - colDesc.setSqlTypeString(sqlTypeString); - - - // set the KeyColumn boolean field as appropriate - if (keySet.contains(columnName.toLowerCase())) - { - colDesc.setKeyColumn(true); - } - else - { - colDesc.setKeyColumn(false); - } - - - // add the columnDescriptor to the tableDescriptor's list - tableDesc.getColumnDescriptorList().add(colDesc); - - } //end while - - - - } //end for - - } - catch (SQLException e) - { - System.out.println(this.getClass().getName() - + ".getTableDescriptorList():" + " Problem with SQL " - + e.getMessage()); - e.printStackTrace(); - } - return tdList; - - } //getInformixTableDescriptorList - - //------------------------------------------------------------------------------------- - - - // sub method of getTableDescriptorList - // broken out to reduce duplicate code for tables and views - private void addToRawTableDescriptorList(DatabaseMetaData dbmd, - Map preferredTableNameMap, - boolean isView, - String[] tableTypeNameArray, - List rawTableDescriptorList) - throws SQLException - { - //ResultSet rsForTables = dbmd.getTables("", "", "%", - // tableTypeNameArray ); - ResultSet rsForTables = dbmd.getTables(null, null, "%", - tableTypeNameArray); - - - - while (rsForTables.next()) - { - TableDescriptor tableDesc = new TableDescriptor(); - - String originalCaseName = rsForTables.getString(3); - String lowerCaseName = originalCaseName.toLowerCase(); - String mixedCaseName = (String) preferredTableNameMap.get(lowerCaseName); - if (mixedCaseName == null) - { - mixedCaseName = lowerCaseName; - } - - tableDesc.setOriginalCaseTableName(originalCaseName); - tableDesc.setName(mixedCaseName); - - /* - System.out.println("addToRawTableDescriptorList(): original case of table name = " + - originalCaseName + - " mixed case table name = " + - mixedCaseName); - */ - - tableDesc.setView(isView); - rawTableDescriptorList.add(tableDesc); - } - - rsForTables.close(); - - return; - } - - - - - - -} //end SchemaDescriber diff --git a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/TableDescriptor.java b/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/TableDescriptor.java deleted file mode 100755 index 7afc15a08d..0000000000 --- a/cave/ohd.hseb.ihfsdb/src/ohd/hseb/dbgen/TableDescriptor.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Created on Aug 13, 2003 - * - * This class encapsulates information about a table, including a list - * of column descriptors. - */ -package ohd.hseb.dbgen; - -import java.util.*; - - -/** - * - */ -public class TableDescriptor -{ - private String _name = null; - private String _originalCaseTableName = null; - private boolean _isView = false; - private boolean _hasPrimaryKey = false; - - - private List _columnDescList = new ArrayList(); - private List _keyColumnDescList = null; - - // --------------------------------------------------------------------------------------------- - - public TableDescriptor() - { - - } - - // --------------------------------------------------------------------------------------------- - - public void setName(String name) - { - this._name = name; - } - - // --------------------------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - // --------------------------------------------------------------------------------------------- - - /** - * @param originalTableName The originalTableName to set. - */ - public void setOriginalCaseTableName(String originalTableName) - { - _originalCaseTableName = originalTableName; - } - // --------------------------------------------------------------------------------------------- - - /** - * @return Returns the originalTableName. - */ - public String getOriginalCaseTableName() - { - return _originalCaseTableName; - } - - // --------------------------------------------------------------------------------------------- - - public void setView(boolean isView) - { - this._isView = isView; - } - - // --------------------------------------------------------------------------------------------- - - public boolean isView() - { - return _isView; - } - - // --------------------------------------------------------------------------------------------- - - public void setHasPrimaryKey(boolean hasPrimaryKey) - { - _hasPrimaryKey = hasPrimaryKey; - } - - // --------------------------------------------------------------------------------------------- - - public boolean hasPrimaryKey() - { - return _hasPrimaryKey; - } - - // --------------------------------------------------------------------------------------------- - - - public List getColumnDescriptorList() - { - return _columnDescList; - } - - // --------------------------------------------------------------------------------------------- - - public List getKeyColumnDescriptorList() - { - - if (_keyColumnDescList == null) - { - _keyColumnDescList = new ArrayList(); - - // for each key column, check if it is a key column, and, if so, then insert it into the list - for (int i = 0 ; i < _columnDescList.size() ; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) _columnDescList.get(i); - - if (colDesc.isKeyColumn()) - { - _keyColumnDescList.add(colDesc); - } - } - } - - return _keyColumnDescList; - } - - // --------------------------------------------------------------------------------------------- - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("Name = " + _name); - - buffer.append(" Original Case Table name = " + _originalCaseTableName + "\n"); - buffer.append(" Mixed Case Table name = " + _name + "\n"); - buffer.append(" Is View? = " + _isView + "\n"); - - buffer.append("Columns:\n"); - for (int i = 0; i < _columnDescList.size(); i++) - { - ColumnDescriptor descriptor = (ColumnDescriptor) _columnDescList - .get(i); - - buffer.append("Column " + i + "\n" + - descriptor.toString() + "\n"); - - } - - - return buffer.toString(); - } - - // --------------------------------------------------------------------------------------------- - -} //end class TableDescriptor diff --git a/cave/ohd.hseb.monitor/.classpath b/cave/ohd.hseb.monitor/.classpath deleted file mode 100644 index 1fa3e6803d..0000000000 --- a/cave/ohd.hseb.monitor/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/cave/ohd.hseb.monitor/.project b/cave/ohd.hseb.monitor/.project deleted file mode 100644 index 9f5417f4bc..0000000000 --- a/cave/ohd.hseb.monitor/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.hseb.monitor - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/cave/ohd.hseb.monitor/.settings/org.eclipse.jdt.core.prefs b/cave/ohd.hseb.monitor/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index e31fb0bba0..0000000000 --- a/cave/ohd.hseb.monitor/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -#Thu Mar 26 11:32:22 CDT 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cave/ohd.hseb.monitor/META-INF/MANIFEST.MF b/cave/ohd.hseb.monitor/META-INF/MANIFEST.MF deleted file mode 100644 index 0c4aacd001..0000000000 --- a/cave/ohd.hseb.monitor/META-INF/MANIFEST.MF +++ /dev/null @@ -1,22 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Monitor Plug-in -Bundle-SymbolicName: ohd.hseb.monitor;singleton:=true -Bundle-Version: 1.0.0.qualifier -Bundle-Activator: com.raytheon.monitor.activator.Activator -Require-Bundle: org.eclipse.ui, - org.eclipse.core.runtime, - com.raytheon.viz.core, - ohd.hseb.common, - ohd.hseb.ihfsdb, - org.postgres -Bundle-ActivationPolicy: lazy -Export-Package: com.raytheon.monitor.activator, - com.raytheon.monitor.preferences, - ohd.hseb.monitor -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: com.raytheon.uf.common.mpe.util, - com.raytheon.uf.common.ohd, - com.raytheon.viz.hydrocommon, - com.raytheon.viz.hydrocommon.util, - com.vividsolutions.jts.geom diff --git a/cave/ohd.hseb.monitor/build.properties b/cave/ohd.hseb.monitor/build.properties deleted file mode 100644 index e5eb50c213..0000000000 --- a/cave/ohd.hseb.monitor/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - config.xml,\ - localization/ diff --git a/cave/ohd.hseb.monitor/config.xml b/cave/ohd.hseb.monitor/config.xml deleted file mode 100644 index dc36aacbd4..0000000000 --- a/cave/ohd.hseb.monitor/config.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - jdbc:postgresql://localhost:5432/hd_ob83oax?user=awips&password=awips - /home/awips/hydro/config - /home/awips/hydro/logs - \ No newline at end of file diff --git a/cave/ohd.hseb.monitor/external_jars/postgresql-8.3-603.jdbc3.jar b/cave/ohd.hseb.monitor/external_jars/postgresql-8.3-603.jdbc3.jar deleted file mode 100644 index a9156e958b..0000000000 Binary files a/cave/ohd.hseb.monitor/external_jars/postgresql-8.3-603.jdbc3.jar and /dev/null differ diff --git a/cave/ohd.hseb.monitor/localization/menus/monitor/baseMonitor.xml b/cave/ohd.hseb.monitor/localization/menus/monitor/baseMonitor.xml deleted file mode 100644 index e9011e552e..0000000000 --- a/cave/ohd.hseb.monitor/localization/menus/monitor/baseMonitor.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/cave/ohd.hseb.monitor/localization/menus/monitor/index.xml b/cave/ohd.hseb.monitor/localization/menus/monitor/index.xml deleted file mode 100644 index 33a9d4bac9..0000000000 --- a/cave/ohd.hseb.monitor/localization/menus/monitor/index.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - \ No newline at end of file diff --git a/cave/ohd.hseb.monitor/log/RiverMonitor.1.20080822 b/cave/ohd.hseb.monitor/log/RiverMonitor.1.20080822 deleted file mode 100644 index 9c6aa9e061..0000000000 --- a/cave/ohd.hseb.monitor/log/RiverMonitor.1.20080822 +++ /dev/null @@ -1,38 +0,0 @@ -1 -************************************** -1 -************************************** -16:01:32: RiverMonitor Started -1 -************************************** -16:01:32: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -1 -************************************** -16:01:32: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -1 -************************************** -16:01:33: Derived columns file doesnt exist :[/home/ebabin/workspace/ohd.hseb.river_monitor/config/DerivedColumns.txt] -1 -************************************** -16:01:33: Derived columns file doesnt exist :[/home/ebabin/workspace/ohd.hseb.river_monitor/config/DerivedColumns.txt] -1 -************************************** -16:01:33: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/home/ebabin/workspace/ohd.hseb.river_monitor/config/DefaultRiverMonitorSettings.txt -1 -************************************** -16:01:33: SettingsFileManager.isValidSettingsFile(): [/home/ebabin/workspace/ohd.hseb.river_monitor/config/DefaultRiverMonitorSettings.txt] doesn't exist -1 -************************************** -16:01:33: RiverMonitorDataManager.createRiverMonitorRowDataList(): Memory Info before creating rowdata list:Free:64159664 Max:1023934464 total:65536000 -1 -************************************** -16:01:35: RiverMonitorDataManager.readConfigFileAndFormConfigMap(): ConfigFile [/home/ebabin/workspace/ohd.hseb.river_monitor/config/RiverMonitorPEConfig.txt] doesn't exist -1 -************************************** -16:01:37: RiverMonLocGroupDataManager.initRiverMonGroupMap(): Where Clause:order by ordinal -1 -************************************** -16:01:37: RiverMonitorLocGroupDataManager.initRiverMonLocationMap(): Where Clause:where group_id not like 'DEFAULT' order by ordinal -1 -************************************** -16:01:37: RiverMonitorDataManager.createRiverMonitorRowDataList(): Here 1: Free:150936656 Max:1023934464 total:158793728 diff --git a/cave/ohd.hseb.monitor/logging/PrecipMonitor.1.20080822 b/cave/ohd.hseb.monitor/logging/PrecipMonitor.1.20080822 deleted file mode 100644 index e5da802c04..0000000000 --- a/cave/ohd.hseb.monitor/logging/PrecipMonitor.1.20080822 +++ /dev/null @@ -1,32 +0,0 @@ -1 -************************************** -1 -************************************** -21:10:03: PrecipMonitor Started -1 -************************************** -21:10:03: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -1 -************************************** -21:10:03: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/PrecipDerivedColumns.txt] -1 -************************************** -21:10:03: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/PrecipDerivedColumns.txt] -1 -************************************** -21:10:03: PrecipMonitorSettings.startPrecipMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultPrecipMonitorSettings.txt -1 -************************************** -21:10:03: SettingsFileManager.isValidSettingsFile(): [/awips/hydroapps/whfs/local/data/app/rivermon/DefaultPrecipMonitorSettings.txt] doesn't exist -1 -************************************** -21:10:03: PrecipMonitorDataManager.createPrecipMonitorRowDataList(): Memory Info before creating rowdata list:Free:63957608 Max:1023934464 total:65536000 -1 -************************************** -21:10:09: RiverMonLocGroupDataManager.initRiverMonGroupMap(): Where Clause:order by ordinal -1 -************************************** -21:10:09: RiverMonitorLocGroupDataManager.initRiverMonLocationMap(): Where Clause:where group_id not like 'DEFAULT' order by ordinal -1 -************************************** -21:10:09: PrecipMonitorDataManager.createPrecipMonitorRowDataList(): 1:Free:102711168 Max:1023934464 total:157351936 diff --git a/cave/ohd.hseb.monitor/logging/PrecipMonitor.2.20080822 b/cave/ohd.hseb.monitor/logging/PrecipMonitor.2.20080822 deleted file mode 100644 index 776161a197..0000000000 --- a/cave/ohd.hseb.monitor/logging/PrecipMonitor.2.20080822 +++ /dev/null @@ -1,29 +0,0 @@ -2 -************************************** -2 -************************************** -21:11:15: PrecipMonitor Started -2 -************************************** -21:11:15: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -2 -************************************** -21:11:15: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/PrecipDerivedColumns.txt] -2 -************************************** -21:11:15: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/PrecipDerivedColumns.txt] -2 -************************************** -21:11:15: PrecipMonitorSettings.startPrecipMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultPrecipMonitorSettings.txt -2 -************************************** -21:11:34: RiverMonGroupDataManager.readDataFromRiverMonGroup(): Where Clause:order by group_id -2 -************************************** -21:11:35: RiverMonGroupDataManager.readDataFromRiverMonGroup(): Where Clause:order by group_id -2 -************************************** -21:11:51: PrecipMonitor Application Exiting.... -2 -************************************** -21:11:51: ==================================== diff --git a/cave/ohd.hseb.monitor/logging/PrecipMonitor.3.20080825 b/cave/ohd.hseb.monitor/logging/PrecipMonitor.3.20080825 deleted file mode 100644 index bcb7428167..0000000000 --- a/cave/ohd.hseb.monitor/logging/PrecipMonitor.3.20080825 +++ /dev/null @@ -1,23 +0,0 @@ -3 -************************************** -3 -************************************** -14:56:59: PrecipMonitor Started -3 -************************************** -14:56:59: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -3 -************************************** -14:56:59: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/PrecipDerivedColumns.txt] -3 -************************************** -14:56:59: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/PrecipDerivedColumns.txt] -3 -************************************** -14:56:59: PrecipMonitorSettings.startPrecipMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultPrecipMonitorSettings.txt -3 -************************************** -14:57:14: PrecipMonitor Application Exiting.... -3 -************************************** -14:57:14: ==================================== diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.1.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.1.20080822 deleted file mode 100644 index af2533587c..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.1.20080822 +++ /dev/null @@ -1,23 +0,0 @@ -1 -************************************** -1 -************************************** -20:46:21: RiverMonitor Started -1 -************************************** -20:46:22: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -1 -************************************** -20:46:22: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -1 -************************************** -20:46:22: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -1 -************************************** -20:46:22: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -1 -************************************** -20:46:22: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt -1 -************************************** -20:46:26: Launch PRECIP Monitor [cmd:/home/ebabin/workspace/ohd.hseb.rivermonitor/src/scripts/start_rivermonitor Precip] diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.10.20080825 b/cave/ohd.hseb.monitor/logging/RiverMonitor.10.20080825 deleted file mode 100644 index a2dc582298..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.10.20080825 +++ /dev/null @@ -1,35 +0,0 @@ -10 -************************************** -10 -************************************** -14:55:58: RiverMonitor Started -10 -************************************** -14:55:59: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -10 -************************************** -14:55:59: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -10 -************************************** -14:55:59: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -10 -************************************** -14:55:59: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -10 -************************************** -14:55:59: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt -10 -************************************** -14:56:12: RiverMonitorDataManager.createRiverMonitorRowDataList(): Memory Info before creating rowdata list:Free:64030096 Max:1023934464 total:65536000 -10 -************************************** -14:56:15: RiverMonitorDataManager.readConfigFileAndFormConfigMap(): ConfigFile [awips/hydroapps/whfs/local/data/app/rivermon/RiverMonitorPEConfig.txt] doesn't exist -10 -************************************** -14:56:16: RiverMonLocGroupDataManager.initRiverMonGroupMap(): Where Clause:order by ordinal -10 -************************************** -14:56:16: RiverMonitorLocGroupDataManager.initRiverMonLocationMap(): Where Clause:where group_id not like 'DEFAULT' order by ordinal -10 -************************************** -14:56:16: RiverMonitorDataManager.createRiverMonitorRowDataList(): Here 1: Free:151008992 Max:1023934464 total:158990336 diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.2.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.2.20080822 deleted file mode 100644 index 89d2b2ce51..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.2.20080822 +++ /dev/null @@ -1,26 +0,0 @@ -2 -************************************** -2 -************************************** -20:51:08: RiverMonitor Started -2 -************************************** -20:51:08: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -2 -************************************** -20:51:09: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -2 -************************************** -20:51:09: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -2 -************************************** -20:51:09: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -2 -************************************** -20:51:09: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt -2 -************************************** -20:51:19: Launch PRECIP Monitor [cmd:/home/ebabin/workspace/ohd.hseb.rivermonitor/src/scripts/start_rivermonitor Precip] -2 -************************************** -20:52:27: Launch PRECIP Monitor [cmd:/home/ebabin/workspace/ohd.hseb.rivermonitor/src/scripts/start_rivermonitor Precip] diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.3.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.3.20080822 deleted file mode 100644 index 2cdce49372..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.3.20080822 +++ /dev/null @@ -1,20 +0,0 @@ -3 -************************************** -3 -************************************** -20:58:25: RiverMonitor Started -3 -************************************** -20:58:25: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -3 -************************************** -20:58:26: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -3 -************************************** -20:58:26: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -3 -************************************** -20:58:26: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -3 -************************************** -20:58:26: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.4.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.4.20080822 deleted file mode 100644 index 9bf3a0414b..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.4.20080822 +++ /dev/null @@ -1,20 +0,0 @@ -4 -************************************** -4 -************************************** -21:00:04: RiverMonitor Started -4 -************************************** -21:00:04: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -4 -************************************** -21:00:05: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -4 -************************************** -21:00:05: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -4 -************************************** -21:00:05: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -4 -************************************** -21:00:05: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.5.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.5.20080822 deleted file mode 100644 index 0394887d4a..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.5.20080822 +++ /dev/null @@ -1,20 +0,0 @@ -5 -************************************** -5 -************************************** -21:01:16: RiverMonitor Started -5 -************************************** -21:01:16: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -5 -************************************** -21:01:16: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -5 -************************************** -21:01:17: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -5 -************************************** -21:01:17: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -5 -************************************** -21:01:17: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.6.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.6.20080822 deleted file mode 100644 index c401849a56..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.6.20080822 +++ /dev/null @@ -1,23 +0,0 @@ -6 -************************************** -6 -************************************** -21:02:25: RiverMonitor Started -6 -************************************** -21:02:25: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -6 -************************************** -21:02:25: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -6 -************************************** -21:02:25: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -6 -************************************** -21:02:25: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -6 -************************************** -21:02:26: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt -6 -************************************** -21:02:29: Launch PRECIP Monitor [cmd:/home/ebabin/workspace/ohd.hseb.rivermonitor/src/scripts/start_rivermonitor Precip] diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.7.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.7.20080822 deleted file mode 100644 index 2efccee34c..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.7.20080822 +++ /dev/null @@ -1,38 +0,0 @@ -7 -************************************** -7 -************************************** -21:03:40: RiverMonitor Started -7 -************************************** -21:03:40: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -7 -************************************** -21:03:41: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -7 -************************************** -21:03:41: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -7 -************************************** -21:03:41: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -7 -************************************** -21:03:41: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt -7 -************************************** -21:03:55: Launch PRECIP Monitor [cmd:/home/ebabin/workspace/ohd.hseb.rivermonitor/src/scripts/start_rivermonitor Precip] -7 -************************************** -21:03:56: RiverMonitorDataManager.createRiverMonitorRowDataList(): Memory Info before creating rowdata list:Free:63968112 Max:1023934464 total:65536000 -7 -************************************** -21:04:00: RiverMonitorDataManager.readConfigFileAndFormConfigMap(): ConfigFile [awips/hydroapps/whfs/local/data/app/rivermon/RiverMonitorPEConfig.txt] doesn't exist -7 -************************************** -21:04:01: RiverMonLocGroupDataManager.initRiverMonGroupMap(): Where Clause:order by ordinal -7 -************************************** -21:04:01: RiverMonitorLocGroupDataManager.initRiverMonLocationMap(): Where Clause:where group_id not like 'DEFAULT' order by ordinal -7 -************************************** -21:04:01: RiverMonitorDataManager.createRiverMonitorRowDataList(): Here 1: Free:150952936 Max:1023934464 total:158924800 diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.8.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.8.20080822 deleted file mode 100644 index 5e8fa83759..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.8.20080822 +++ /dev/null @@ -1,20 +0,0 @@ -8 -************************************** -8 -************************************** -21:10:00: RiverMonitor Started -8 -************************************** -21:10:00: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -8 -************************************** -21:10:00: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -8 -************************************** -21:10:00: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -8 -************************************** -21:10:00: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -8 -************************************** -21:10:00: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt diff --git a/cave/ohd.hseb.monitor/logging/RiverMonitor.9.20080822 b/cave/ohd.hseb.monitor/logging/RiverMonitor.9.20080822 deleted file mode 100644 index b8fa443263..0000000000 --- a/cave/ohd.hseb.monitor/logging/RiverMonitor.9.20080822 +++ /dev/null @@ -1,20 +0,0 @@ -9 -************************************** -9 -************************************** -21:11:12: RiverMonitor Started -9 -************************************** -21:11:12: RiverMonitorDataManager.readValidHeightAndDischargePE(): Where Clause:where pe like 'H%' or pe like 'Q%' -9 -************************************** -21:11:12: OfficeNotesDataManager.readDataFromOfficeNotes(): Where Clause:order by topic, id, postingtime -9 -************************************** -21:11:12: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -9 -************************************** -21:11:12: Derived columns file doesnt exist :[/awips/hydroapps/whfs/local/data/app/rivermon/DerivedColumns.txt] -9 -************************************** -21:11:12: RiverMonitorSettings.startRiverMonitor(): Trying to load from file :/awips/hydroapps/whfs/local/data/app/rivermon/DefaultRiverMonitorSettings.txt diff --git a/cave/ohd.hseb.monitor/ohd.hseb.monitor.ecl b/cave/ohd.hseb.monitor/ohd.hseb.monitor.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cave/ohd.hseb.monitor/plugin.xml b/cave/ohd.hseb.monitor/plugin.xml deleted file mode 100644 index eeaf12313a..0000000000 --- a/cave/ohd.hseb.monitor/plugin.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/action/OpenPrecipMonitorAction.java b/cave/ohd.hseb.monitor/src/com/raytheon/monitor/action/OpenPrecipMonitorAction.java deleted file mode 100644 index b0b9b8b475..0000000000 --- a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/action/OpenPrecipMonitorAction.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.monitor.action; - -import ohd.hseb.monitor.Monitor; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPersistentPreferenceStore; - -import com.raytheon.monitor.activator.Activator; - -/** - * TODO Add Description OpenRiverMonitor.java 11 Sept, 2008 - * - *
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- *    10sept2008  #1509     dhladky    Finished Monitor integration.
- * 
- * 
- * - * @author dhladky - * @version 1.0 - */ - -public class OpenPrecipMonitorAction extends AbstractHandler { - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent) - */ - @Override - public Object execute(ExecutionEvent arg0) throws ExecutionException { - IPersistentPreferenceStore store = Activator.getDefault() - .getPreferenceStore(); - String databaseConnectionString = store - .getString(com.raytheon.monitor.preferences.PreferenceConstants.JDBC_URL); - String missingRepresent = store - .getString(com.raytheon.monitor.preferences.PreferenceConstants.MISSING_PRESENTATION); - // connectionString - // missingRepresentation. - // PRECIP, or else, launches RiverMontior... - if (databaseConnectionString == null - || databaseConnectionString.equalsIgnoreCase("")) { - MessageDialog - .openError( - null, - "Error Starting Precip Monitor", - "Database connection string not set, or incorrect, please verify River Apps settings on preference page."); - } else { - String[] args = { databaseConnectionString, missingRepresent, - "Precip" }; - if (!Monitor.precipExists()) { - Monitor.getPrecipInstance().main(args); - } else { - System.out.println("PrecipMonitor...Already running!"); - } - } - return null; - } -} - diff --git a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/action/OpenRiverMonitorAction.java b/cave/ohd.hseb.monitor/src/com/raytheon/monitor/action/OpenRiverMonitorAction.java deleted file mode 100644 index 028f376f89..0000000000 --- a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/action/OpenRiverMonitorAction.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.monitor.action; - -import ohd.hseb.monitor.Monitor; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPersistentPreferenceStore; - -import com.raytheon.monitor.activator.Activator; - -/** - * TODO Add Description OpenRiverMonitor.java Jul 23, 2008 - * - *
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * 	Jul 23, 2008					Eric Babin Initial Creation
- *    10sept2008  #1509     dhladky    Finished integration.
- * 
- * 
- * - * @author ebabin - * @version 1.0 - */ - -public class OpenRiverMonitorAction extends AbstractHandler { - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent) - */ - @Override - public Object execute(ExecutionEvent arg0) throws ExecutionException { - IPersistentPreferenceStore store = Activator.getDefault() - .getPreferenceStore(); - - String databaseConnectionString = store - .getString(com.raytheon.monitor.preferences.PreferenceConstants.JDBC_URL); - String missingRepresent = store - .getString(com.raytheon.monitor.preferences.PreferenceConstants.MISSING_PRESENTATION); - // connectionString - // missingRepresentation. - // PRECIP, or else, launches RiverMontior... - if (databaseConnectionString == null - || databaseConnectionString.equalsIgnoreCase("")) { - MessageDialog - .openError( - null, - "Error Starting River Monitor", - "Database connection string not set, or incorrect, please verify River Apps settings on preference page."); - } else { - String[] args = { databaseConnectionString, missingRepresent, - "River" }; - if (!Monitor.riverExists()) { - Monitor.getRiverInstance().main(args); - } else { - System.out.println("RiverMonitor...Already running!"); - } - } - return null; - } -} diff --git a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/activator/Activator.java b/cave/ohd.hseb.monitor/src/com/raytheon/monitor/activator/Activator.java deleted file mode 100755 index 7a2f34e2e2..0000000000 --- a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/activator/Activator.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.raytheon.monitor.activator; - -import org.eclipse.jface.preference.IPersistentPreferenceStore; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -import com.raytheon.uf.viz.core.localization.HierarchicalPreferenceStore; - -/** - * - * The activator class controls the plug-in life cycle - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Mar 3, 2014  2861       mschenke    Create preference store immediately
- * 
- * 
- * - * @author unknown - * @version 1.0 - */ -public class Activator extends AbstractUIPlugin { - - // The plug-in ID - public static final String PLUGIN_ID = "ohd.hseb.monitor"; - - // The shared instance - private static Activator plugin; - - private IPersistentPreferenceStore prefs = new HierarchicalPreferenceStore( - this); - - /** - * The constructor - */ - public Activator() { - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext - * ) - */ - @Override - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext - * ) - */ - @Override - public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); - } - - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.plugin.AbstractUIPlugin#getPreferenceStore() - */ - @Override - public IPersistentPreferenceStore getPreferenceStore() { - return prefs; - } -} diff --git a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/preferences/MonitorPreferences.java b/cave/ohd.hseb.monitor/src/com/raytheon/monitor/preferences/MonitorPreferences.java deleted file mode 100644 index 4136537085..0000000000 --- a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/preferences/MonitorPreferences.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.monitor.preferences; - -import org.eclipse.jface.preference.FieldEditorPreferencePage; -import org.eclipse.jface.preference.StringFieldEditor; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; - -import com.raytheon.monitor.activator.Activator; - -/** - * OHD monitor preferences page - * - *
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Aug 25, 2008            ebabin     Initial creation
- * Oct, 1, 2008            randerso   Fixed a babinism
- * 16Jan2009    1860       MW Fegan   get defaults from plug-in.
- * 
- * - * @author randerso - * @version 1.0 - */ -public class MonitorPreferences extends FieldEditorPreferencePage implements - IWorkbenchPreferencePage { - - public MonitorPreferences() { - super(GRID); - setPreferenceStore(Activator.getDefault().getPreferenceStore()); - } - - @Override - public void createFieldEditors() { - - addField(new StringFieldEditor( - com.raytheon.monitor.preferences.PreferenceConstants.JDBC_URL, - "&Database Connection String", getFieldEditorParent())); - addField(new StringFieldEditor( - com.raytheon.monitor.preferences.PreferenceConstants.RIVERMON_CONFIG_DIR, - "&Config Directory", getFieldEditorParent())); - addField(new StringFieldEditor( - com.raytheon.monitor.preferences.PreferenceConstants.RIVERMON_LOG_DIR, - "&Log Directory", getFieldEditorParent())); - - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - /* - * intentionally empty -- causes page to be populated using the - * plug-in's config.xml - */ - } -} diff --git a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/preferences/PreferenceConstants.java b/cave/ohd.hseb.monitor/src/com/raytheon/monitor/preferences/PreferenceConstants.java deleted file mode 100644 index d2cf0c8dbd..0000000000 --- a/cave/ohd.hseb.monitor/src/com/raytheon/monitor/preferences/PreferenceConstants.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.monitor.preferences; - -/** - * TODO Add Description PreferenceConstants.java Aug 5, 2008 - * - *
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * 	Aug 5, 2008					Eric Babin Initial Creation
- * 
- * 
- * - * @author ebabin - * @version 1.0 - */ - -public class PreferenceConstants { - - public static final String UNDEFINED = "UNDEFINED"; - - public static final String DATABASE_NAME = "databaseName"; - - public static final String JDBC_URL = "jdbcUrl"; - - public static final String SETTINGS_DIR = "settingsDir"; - - public static final String SETTINGS_FILE = "settingsFile"; - - public static final String DEFAULT_FILE = "defaultFile"; - - public static final String PE_CONFIG_FILE = "peConfigFile"; - - public static final String LOG_FILE = "logFile"; - - public static final String ICONS_DIR = "iconsDir"; - - public static final String DERIVED_COLUMNS_FILE = "derivedColumnsFile"; - - public static final String MISSING_PRESENTATION = "missingPresentation"; - - public static final String GAFF_MOSAIC_DIR = "gaff_mosaic_dir"; - - public static final String GAFF_INPUT_DIR = "gaff_input_dir"; - - public static final String PDC_PP_DIR = "pdc_pp_dir"; - - public static final String RIVERMON_CONFIG_DIR = "rivermon_config_dir"; - - public static final String RIVERMON_LOG_DIR = "rivermon_log_dir"; - - public static final String SSHP_BACKGROUND_FORECAST_OUTPUT_DIR = "sshp_background_forecast_output_dir"; - - public static final String WHFS_BIN_DIR = "whfs_bin_dir"; - - public static final String WHFS_LOCAL_BIN_DIR = "whfs_local_bin_dir"; - - public static final String WHFS_EDITOR = "whfs_editor"; - - public static final String WHFS_REPORT_DIR = "whfs_report_dir"; - - public static final String ST3_RFC = "st3_rfc"; - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmColumns.java deleted file mode 100755 index cb16bc457e..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmColumns.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.alertalarm; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class AlertAlarmColumns -{ - public static String LID = "LocId"; - public static String PE = "PE"; - public static String DUR= "Dur"; - public static String TS = "TS"; - public static String EXT = "Ext"; - public static String PROB = "Prob"; - public static String VALID_TIME = "ValidTime"; - public static String BASIS_TIME = "BasisTime"; - public static String VALUE = "Value"; - public static String SUP_VALUE = "Sup Val"; - public static String SHEF_QUAL_CODE = "SQC"; - public static String QUAL_CODE = "QC"; - public static String REVISION = "Rev"; - public static String PRODUCT_ID = "ProdId"; - public static String PROD_TIME = "ProductTime"; - public static String POSTING_TIME = "PostingTime"; - public static String ACTION_TIME = "ActionTime"; - public static String DESC = "Desc"; - public static String THREAT = "Threat"; - - - /** - * Creates a list of alertalarm columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the alertalarm columns are added to it, - * if not the alertalarm columns are added to the list that is passed as argument. - * The created new list is returned. - * @param officeNotesColumnDescriptorList - * @return - */ - public List getAlertAlarmColumnsList(List alertAlarmColumnDescriptorList) - { - if( alertAlarmColumnDescriptorList == null) - { - alertAlarmColumnDescriptorList = new ArrayList(); - } - - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(LID, true, 50, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PE, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(DUR, true, 25, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(TS, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(EXT, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PROB, true, 35, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(VALID_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(BASIS_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(VALUE, true, 50, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(SUP_VALUE, true, 50, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(SHEF_QUAL_CODE, true, 35, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(QUAL_CODE, true, 40, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(REVISION, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_ID, true, 100, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PROD_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(POSTING_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(ACTION_TIME, true, 70, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(DESC, true, 45, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(THREAT, true, 45, "center")); - - return alertAlarmColumnDescriptorList; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmDataManager.java deleted file mode 100755 index 571d0f64c1..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmDataManager.java +++ /dev/null @@ -1,154 +0,0 @@ -package ohd.hseb.alertalarm; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.AlertAlarmValRecord; -import ohd.hseb.ihfsdb.generated.AlertAlarmValTable; -import ohd.hseb.util.SessionLogger; - -public class AlertAlarmDataManager -{ - private Database _db = null; - private SessionLogger _logger = null; - private String _missingRepresentation; - - public AlertAlarmDataManager(Database dbHandler, SessionLogger logger, String missingRepresentation) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","AlertAlarm Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public List readDataFromAlertAlarmVal() - { - List alertAlarmInfoList = null; - List dataList = null; - String header = "AlertAlarmDataManager.readDataFromAlertAlarmVal(): "; - AlertAlarmValTable alertAlarmValTable = new AlertAlarmValTable(_db); - AlertAlarmValRecord alertAlarmValRecord = null; - String whereClause = null; - try - { - whereClause = "order by lid"; - alertAlarmInfoList = alertAlarmValTable.select(whereClause); - _logger.log(header + " Where clause:"+ whereClause); - if(alertAlarmInfoList != null) - { - dataList = new ArrayList(); - for(int i=0;i < alertAlarmInfoList.size(); i++) - { - - alertAlarmValRecord = (AlertAlarmValRecord) alertAlarmInfoList.get(i); - AlertAlarmJTableRowData rowData = new AlertAlarmJTableRowData(_missingRepresentation); - //rowData.setAlertAlarmRecord(alertAlarmValRecord); - rowData.setLid(alertAlarmValRecord.getLid()); - rowData.setPe(alertAlarmValRecord.getPe()); - rowData.setTs(alertAlarmValRecord.getTs()); - - rowData.setDur(alertAlarmValRecord.getDur()); - - rowData.setExtremum(alertAlarmValRecord.getExtremum()); - - if(alertAlarmValRecord.getProbability() == -1.0) - { - rowData.setProbability(DbTable.getNullFloat()); - } - else - { - rowData.setProbability(alertAlarmValRecord.getProbability()); - } - - rowData.setValidTime(alertAlarmValRecord.getValidtime()); - rowData.setBasisTime(alertAlarmValRecord.getBasistime()); - - rowData.setValue(alertAlarmValRecord.getValue()); - - if(alertAlarmValRecord.getSuppl_value() == -9999.0) - { - rowData.setSupplValue(DbTable.getNullDouble()); - } - else - { - rowData.setSupplValue(alertAlarmValRecord.getSuppl_value()); - } - - rowData.setShefQualCode(alertAlarmValRecord.getShef_qual_code()); - - String result = null; - if(alertAlarmValRecord.getQuality_code() == DbTable.getNullInt()) - result = _missingRepresentation; - else if(alertAlarmValRecord.getQuality_code() >= 1610612736) - result = "Good"; - else if(alertAlarmValRecord.getQuality_code() >= 1073741824) - result = "Quest"; - else - result = "Bad"; - - rowData.setQualityCode(result); - - if(alertAlarmValRecord.getRevision() == DbTable.getNullShort()) - { - result = _missingRepresentation; - } - else if(alertAlarmValRecord.getRevision() == 1) - { - result = "Y"; - } - else - { - result = "N"; - } - rowData.setRevision(result); - - rowData.setProductId(alertAlarmValRecord.getProduct_id()); - - rowData.setProductTime(alertAlarmValRecord.getProducttime()); - - rowData.setPostingTime(alertAlarmValRecord.getPostingtime()); - - rowData.setActionTime(alertAlarmValRecord.getAction_time()); - - rowData.setAaCateg(alertAlarmValRecord.getAa_categ()); - rowData.setAaCheck(alertAlarmValRecord.getAa_check()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" AlertAlarminfo list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmDialog.java deleted file mode 100755 index c60da12f47..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmDialog.java +++ /dev/null @@ -1,115 +0,0 @@ -package ohd.hseb.alertalarm; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; - -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class AlertAlarmDialog extends JDialog -{ - private List _alertAlarmColumnDescriptorList = null; - private JTableManager _alertAlarmTableManager = null; - private AlertAlarmDataManager _alertAlarmDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private SessionLogger _logger = null; - private int _previousRowToHighlight = -1; - private JFrame _mainFrame = null; - private JMenuBar _menuBar; - private JMenu _fileMenu; - private JMenuItem _selectColumnsMenuItem; - - public AlertAlarmDialog(JFrame mainFrame, AlertAlarmDataManager alertAlarmDataMgr, SessionLogger logger) - { - super(mainFrame, true); - _mainFrame = mainFrame; - _logger = logger; - this.setTitle("AlertAlarm"); - this.getContentPane().setLayout(new GridBagLayout()); - _alertAlarmDataMgr = alertAlarmDataMgr; - initialize(); - Dimension dim = new Dimension(1040,560); - new WindowResizingManager(this, dim, dim); - this.pack(); - this.setLocation(25, 25); - } - - public void showAlertAlarmDialog(String lid) - { - _allRowDataList = _alertAlarmDataMgr.readDataFromAlertAlarmVal(); - _alertAlarmTableManager.setChangedAllRowDataList(_allRowDataList); - _alertAlarmTableManager.refreshDisplay(); - - if(lid != null) - { - _alertAlarmTableManager.deselectRows(_previousRowToHighlight, _previousRowToHighlight); - int rowToHighLight = _alertAlarmTableManager.getTheRowIndexToHighLightBasedOnValue(lid); - if(rowToHighLight != -1) - { - System.out.println("Row to highlight:"+ rowToHighLight); - _alertAlarmTableManager.selectRows(rowToHighLight, rowToHighLight); - _previousRowToHighlight = rowToHighLight; - } - } - this.setVisible(true); - } - - private void initialize() - { - _alertAlarmColumnDescriptorList = new AlertAlarmColumns().getAlertAlarmColumnsList(_alertAlarmColumnDescriptorList); - _allRowDataList = _alertAlarmDataMgr.readDataFromAlertAlarmVal(); - _alertAlarmTableManager = new ComplexJTableManager(_alertAlarmColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _alertAlarmTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _alertAlarmTableManager.setDisplayableColumns(columnsSelected, true, true); - _alertAlarmTableManager.setPreferredSizeForJScrollPane(new Dimension(1020, 500)); - _tableScrollPane = _alertAlarmTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(1030,510)); - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - - _menuBar = new JMenuBar(); - this.setJMenuBar(_menuBar); - - _fileMenu = new JMenu("File"); - _selectColumnsMenuItem = new JMenuItem("Select Columns ..."); - _selectColumnsMenuItem.setMnemonic('S'); - _fileMenu.add(_selectColumnsMenuItem); - - _menuBar.add(_fileMenu); - - ChangeColumnsDisplayedMenuListener changeMenuListener = new - ChangeColumnsDisplayedMenuListener(); - _selectColumnsMenuItem.addActionListener(changeMenuListener); - - Container contentPane = this.getContentPane(); - contentPane.add(tablePanel); - } - - private class ChangeColumnsDisplayedMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _alertAlarmTableManager.invokeColumnSelector(_mainFrame); - - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmJTableRowData.java deleted file mode 100755 index 1dce67be70..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/alertalarm/AlertAlarmJTableRowData.java +++ /dev/null @@ -1,221 +0,0 @@ -package ohd.hseb.alertalarm; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class AlertAlarmJTableRowData extends AbstractJTableRowData -{ - private String _lid; - private String _pe; - private short _dur; - private String _ts; - private String _extremum; - private float _probability; - private long _validTime; - private long _basisTime; - private double _value; - private double _supplValue; - private String _shefQualCode; - private String _qualityCode; - private String _revision; - private String _productId; - private long _productTime; - private long _postingTime; - private long _actionTime; - private String _aaCateg; - private String _aaCheck; - - public AlertAlarmJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getAaCateg() - { - return _aaCateg; - } - public void setAaCateg(String aaCateg) - { - _aaCateg = aaCateg; - } - public String getAaCheck() - { - return _aaCheck; - } - public void setAaCheck(String aaCheck) - { - _aaCheck = aaCheck; - } - public long getActionTime() - { - return _actionTime; - } - public void setActionTime(long actionTime) - { - _actionTime = actionTime; - } - public long getBasisTime() - { - return _basisTime; - } - public void setBasisTime(long basisTime) - { - _basisTime = basisTime; - } - public short getDur() - { - return _dur; - } - public void setDur(short dur) - { - this._dur = dur; - } - public String getExtremum() - { - return _extremum; - } - public void setExtremum(String extremum) - { - this._extremum = extremum; - } - public String getLid() - { - return _lid; - } - public void setLid(String lid) - { - this._lid = lid; - } - public String getPe() - { - return _pe; - } - public void setPe(String pe) - { - this._pe = pe; - } - public long getPostingTime() - { - return _postingTime; - } - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - public float getProbability() - { - return _probability; - } - public void setProbability(float probability) - { - this._probability = probability; - } - public String getProductId() - { - return _productId; - } - public void setProductId(String productId) - { - _productId = productId; - } - public long getProductTime() - { - return _productTime; - } - public void setProductTime(long productTime) - { - _productTime = productTime; - } - public String getQualityCode() - { - return _qualityCode; - } - public void setQualityCode(String qualityCode) - { - _qualityCode = qualityCode; - } - public String getRevision() - { - return _revision; - } - public void setRevision(String revision) - { - this._revision = revision; - } - public String getShefQualCode() - { - return _shefQualCode; - } - public void setShefQualCode(String shefQualCode) - { - _shefQualCode = shefQualCode; - } - public double getSupplValue() - { - return _supplValue; - } - public void setSupplValue(double supplValue) - { - _supplValue = supplValue; - } - public String getTs() - { - return _ts; - } - public void setTs(String ts) - { - this._ts = ts; - } - public long getValidTime() - { - return _validTime; - } - public void setValidTime(long validTime) - { - _validTime = validTime; - } - public double getValue() - { - return _value; - } - public void setValue(double value) - { - this._value = value; - } - - // ----------------------------------------------------------------------------------- - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation(), "MM/dd - HH:mm"); - addCell(cell); - - } - - public void addAllCellsToMap() - { - addToCellMap(AlertAlarmColumns.LID, CellType.STRING, getLid()); - addToCellMap(AlertAlarmColumns.PE, CellType.STRING, getPe()); - addToCellMap(AlertAlarmColumns.DUR, CellType.SHORT, getDur()); - addToCellMap(AlertAlarmColumns.TS, CellType.STRING, getTs()); - addToCellMap(AlertAlarmColumns.EXT, CellType.STRING, getExtremum()); - addToCellMap(AlertAlarmColumns.PROB, CellType.FLOAT,getProbability()); - addToCellMap(AlertAlarmColumns.VALID_TIME,CellType.DATE_TIME, getValidTime()); - addToCellMap(AlertAlarmColumns.BASIS_TIME,CellType.DATE_TIME,getBasisTime()); - addToCellMap(AlertAlarmColumns.VALUE,CellType.DOUBLE, getValue()); - addToCellMap(AlertAlarmColumns.SUP_VALUE, CellType.DOUBLE, getSupplValue()); - addToCellMap(AlertAlarmColumns.SHEF_QUAL_CODE, CellType.STRING, getShefQualCode()); - addToCellMap(AlertAlarmColumns.QUAL_CODE,CellType.STRING, getQualityCode()); - addToCellMap(AlertAlarmColumns.REVISION, CellType.STRING, getRevision()); - addToCellMap(AlertAlarmColumns.PRODUCT_ID, CellType.STRING, getProductId()); - addToCellMap(AlertAlarmColumns.PROD_TIME, CellType.DATE_TIME, getProductTime()); - addToCellMap(AlertAlarmColumns.POSTING_TIME, CellType.DATE_TIME, getPostingTime()); - addToCellMap(AlertAlarmColumns.ACTION_TIME, CellType.DATE_TIME, getActionTime()); - addToCellMap(AlertAlarmColumns.DESC, CellType.STRING, getAaCateg()); - addToCellMap(AlertAlarmColumns.THREAT, CellType.STRING,getAaCheck()); - - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/DataFilter.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/DataFilter.java deleted file mode 100755 index d3ee26865b..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/DataFilter.java +++ /dev/null @@ -1,17 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableRowData; - -public interface DataFilter -{ - /** - * Returns the filtered row data list - * @param allRowDataList - * @return - */ - List filter(List allRowDataList); - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/LocationDataFilter.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/LocationDataFilter.java deleted file mode 100755 index 6fe4e96124..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/LocationDataFilter.java +++ /dev/null @@ -1,61 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.util.gui.jtable.JTableRowData; - -public abstract class LocationDataFilter implements DataFilter -{ - protected Map _locationDisplayMap; - - public LocationDataFilter(Map locationDisplayMap) - { - _locationDisplayMap = locationDisplayMap; - } - - public LocationDataFilter() - { - _locationDisplayMap = new HashMap(); - } - - public Map getLocationDisplayMap() - { - return _locationDisplayMap; - } - - /** - * Set this location to be displayed / not - * @param locationId - * @param shouldDisplay - true / false - */ - public void setDisplayStatus(String locationId, Boolean shouldDisplay) - { - _locationDisplayMap.put(locationId, shouldDisplay); - } - - /** - * Reset all locations in the location display map - * - */ - public void blockAllLocations() - { - Set locationIdSet = _locationDisplayMap.keySet(); - - Iterator iterator = locationIdSet.iterator(); - while(iterator.hasNext()) - { - String locationId = iterator.next().toString(); - _locationDisplayMap.put(locationId, false); - } - } - - /** - * Filter the allRowDataList based on the locationDisplayMap - */ - public abstract List filter(List allRowDataList); - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/LocationInfoColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/LocationInfoColumns.java deleted file mode 100755 index 4d9d1d966d..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/LocationInfoColumns.java +++ /dev/null @@ -1,55 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class LocationInfoColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String GROUP_NAME = "Group Name"; - public static final String LOCATION_ID = "Location Id"; - public static final String LOCATION_NAME = "Location Name"; - public static final String HSA = "HSA"; - public static final String GROUP_ORDINAL = "Group Ordinal"; - public static final String LOCATION_ORDINAL = "Location Ordinal"; - public static final String COUNTY = "County"; - public static final String STATE = "State"; - public static final String RIVER_BASIN = "River Basin"; - - - /** - * Creates a list of location info columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the location info columns are added to it, - * if not the location info columns are added to the list that is passed as argument. - * The created new list is returned. - * @param locationInfoColumnDescriptorList - * @return - */ - public List getLocationInfoColumnsList(List locationInfoColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if( locationInfoColumnDescriptorList == null) - { - locationInfoColumnDescriptorList = new ArrayList(); - } - - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ID, textAlignment, "Group Identification")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_NAME, textAlignment, "Group Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ID, textAlignment, "Location Identification")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_NAME, textAlignment, "Location Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(HSA, textAlignment, "Hydrologic Service Area")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ORDINAL, numberAlignment, "Group Ordinal")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ORDINAL, numberAlignment, "Location Ordinal")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(COUNTY, textAlignment, "County Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(STATE, textAlignment, "State Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(RIVER_BASIN, textAlignment, "River Basin")); - - - return locationInfoColumnDescriptorList; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/Monitor.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/Monitor.java deleted file mode 100755 index 85e9016ffa..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/Monitor.java +++ /dev/null @@ -1,117 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.db.Database; -import ohd.hseb.monitor.precip.manager.PrecipMonitorAppManager; -import ohd.hseb.monitor.river.manager.RiverMonitorAppManager; - -public class Monitor -{ - private static Monitor precipInstance = null; - private static Monitor riverInstance = null; - - public Monitor() { - - } - - /** - * Gets the river instance. - * @return Monitor - */ - public static Monitor getRiverInstance() { - if(riverInstance == null) { - riverInstance = new Monitor(); - } - return riverInstance; - } - - /** - * Gets the precip instance. - * @return Monitor - */ - public static Monitor getPrecipInstance() { - if(precipInstance == null) { - precipInstance = new Monitor(); - } - return precipInstance; - } - - /** - * Check to see if river instance exists. - * @return boolean - */ - public static boolean riverExists() { - boolean exists = false; - if(riverInstance != null) { - exists = true; - } - return exists; - } - - /** - * Check to see if river instance exists. - * @return boolean - */ - public static boolean precipExists() { - boolean exists = false; - if(precipInstance != null) { - exists = true; - } - return exists; - } - - /** - * Get rid of river instance. - */ - public static void disposeRiver() { - riverInstance = null; - } - - /** - * Get rid of precip instance. - */ - public static void disposePrecip() { - precipInstance = null; - } - - public void main(String args[]) - { - String connectionString = args[0]; - Database db = createDatabaseConnection(connectionString); - - String missingRepresentation = args[1]; - String version = "OB8.3"; - String versionDate = "Mar 18, 2008"; - - String monitorName = args[2]; - - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager = new MonitorTimeSeriesLiteManager(connectionString); - - if(monitorName.equalsIgnoreCase("PRECIP")) - { - new PrecipMonitorAppManager(db, missingRepresentation, version, versionDate, monitorTimeSeriesLiteManager); - } - else // RIVER - { - new RiverMonitorAppManager(db, missingRepresentation, version, versionDate, monitorTimeSeriesLiteManager); - } - } - - public static String getVersion() - { - return "OB8.3"; - } - - private static Database createDatabaseConnection(String connectionString) - { - Database db; - db = new Database(); - - if (connectionString == null) - { - System.out.println( "RiverMonitor Application.........Database should be provided........"); - - } - db.connectWithDriverSearch(connectionString); - return db; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorCell.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorCell.java deleted file mode 100755 index 44d7a87c9c..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorCell.java +++ /dev/null @@ -1,153 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Color; - -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; -import ohd.hseb.util.gui.jtable.TableCellInterface; - -public class MonitorCell extends BaseTableCell -{ - private ThreatLevel _monitorThreatLevel = ThreatLevel.NO_THREAT; - - private static int defaultDecimalPointsForDisplay = 2; - - // ------------------------------------------------------------------------------------------------------- - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation) - { - super(columnName, cellType, value, missingRepresentation, defaultDecimalPointsForDisplay); - this.setThreatLevel(threatLevel); - } - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, Color cellBackgroundColor, - String missingRepresentation, - int decimalPointsForDisplay) - { - super(columnName, cellType, value, cellBackgroundColor, missingRepresentation,decimalPointsForDisplay); - this.setThreatLevel(threatLevel); - } - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - int decimalPointsForDisplay) - { - super(columnName, cellType, value, missingRepresentation,decimalPointsForDisplay); - this.setThreatLevel(threatLevel); - } - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - String dateFormatString) - { - super(columnName, cellType, value, missingRepresentation, dateFormatString); - this.setThreatLevel(threatLevel); - } - - public ThreatLevel getThreatLevel() - { - return _monitorThreatLevel; - } - - public void setThreatLevel(ThreatLevel rivermonitorThreatLevel) - { - _monitorThreatLevel = rivermonitorThreatLevel; - } - - public Color getCellBackgroundColor() - { - Color color = super.getCellBackgroundColor(); - - if( color == Color.WHITE) - { - ThreatLevel threatLevel = getThreatLevel(); - - switch(threatLevel) - { - case MISSING_DATA: - color = Color.gray; - break; - - case AGED_DATA: - color = Color.gray; - break; - - case CAUTION: - color = Color.yellow; - break; - - case ALERT: - color = Color.red; - break; - - default: - color = Color.white; - } - } - return color; - } - - public Color getCellForegroundColor() - { - Color color = Color.black; - - Color backgroundColor = getCellBackgroundColor(); - - if (backgroundColor.equals(Color.red) || (backgroundColor.equals(Color.gray) ) ) - { - color = Color.yellow; - } - - return color; - } - - public int compare(TableCellInterface otherCell) - { - int result = 0; - - if (getCellType() != CellType.EXTENSION) - { - result = super.compare(otherCell); - } - else - { - result = compareThreat(otherCell); - } - return result; - } - - private int compareThreat(TableCellInterface otherCell) - { - MonitorCell otherThreatCell = (MonitorCell) otherCell; - int result = 0; - result = getThreatLevel().compareTo(otherThreatCell.getThreatLevel()); - if(result == 0) - { - result = compareCells((String) getValue(), (String)otherCell.getValue()); - result *= -1; - } - - return result; - } - - public String getDisplayString() - { - String displayString = null; - - if (getCellType() != CellType.EXTENSION) - { - displayString = super.getDisplayString(); - } - else - { - displayString = getStringValue((String) getValue()); - } - return displayString; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorFrame.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorFrame.java deleted file mode 100755 index 129fa891eb..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorFrame.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Container; -import java.awt.Cursor; - -import javax.swing.JFrame; - -public class MonitorFrame extends JFrame -{ - /** - * - */ - private static final long serialVersionUID = 1145234543265432L; - - public MonitorFrame() - { - super(); - } - - public void setWaitCursor() - { - Container container = this.getContentPane(); // get the window's content pane - container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } - - public void setDefaultCursor() - { - Container container = this.getContentPane(); // get the window's content pane - container.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorMessage.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorMessage.java deleted file mode 100755 index 0aae954095..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorMessage.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.monitor.messaging.Message; -import ohd.hseb.monitor.messaging.MessageType; - -public class MonitorMessage extends Message -{ - private Object _messageData; - - public MonitorMessage(Object source, MessageType messageType, Object messageData) - { - super(source, messageType); - _messageData = messageData; - } - - public MonitorMessage(Object source, MessageType messageType) - { - super(source, messageType); - _messageData = null; - } - - public Object getMessageData() - { - return _messageData; - } - - public void setMessageData(Object messageData) - { - _messageData = messageData; - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorSplitPane.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorSplitPane.java deleted file mode 100755 index 5602781217..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorSplitPane.java +++ /dev/null @@ -1,62 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Component; - -import javax.swing.JSplitPane; - -public class MonitorSplitPane extends JSplitPane -{ - - /** - * - */ - private static final long serialVersionUID = 125315154454l; - - public MonitorSplitPane (int newOrientation, - boolean newContinuousLayout) - { - super(newOrientation, newContinuousLayout); - } - - public void setDividerLocation(int location) - { - int currentDividerLocation = getDividerLocation(); - int adjustedLocation = location; - - - if (location < 30 ) - { - int difference = currentDividerLocation - location; - if (difference > 50) - { - adjustedLocation = currentDividerLocation; - } - } - super.setDividerLocation(adjustedLocation); - } - - public void setRightComponent(Component comp) - { - - int beforeDividerLocation = getDividerLocation(); - - super.setRightComponent(comp); - - setDividerLocation(beforeDividerLocation); - - } - - public void setLeftComponent(Component comp) - { - String header = "MonitorJSplitPane.setLeftComponent() "; - - int beforeDividerLocation = getDividerLocation(); - - super.setLeftComponent(comp); - - setDividerLocation(beforeDividerLocation); - - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorTimeSeriesLiteManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorTimeSeriesLiteManager.java deleted file mode 100755 index 2918dd34dd..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorTimeSeriesLiteManager.java +++ /dev/null @@ -1,132 +0,0 @@ -package ohd.hseb.monitor; - -import javax.swing.JOptionPane; - -import ohd.hseb.model.ParamCode; -import ohd.hseb.monitor.precip.PrecipMonitorJTableRowData; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.timeserieslite.TimeSeriesLite; - -public class MonitorTimeSeriesLiteManager -{ - private String _connectionString; - - public MonitorTimeSeriesLiteManager(String connectionString) - { - _connectionString = connectionString; - } - - public boolean displayTimeSeriesLite(MonitorFrame mainFrame, RiverMonitorJTableRowData rowData) - { - String obsTypeSource = rowData.getObsTypeSource(); - String fcstTypeSource = rowData.getFcstTypeSource(); - String primaryPe = rowData.getPrimaryRiverPe(); - String locationId = rowData.getLid(); - - String obsParamCode = null; - String fcstParamCode = null; - boolean result = false; - - if(obsTypeSource == null && fcstTypeSource == null) - { - result = false; - } - else - { - if(obsTypeSource != null) - obsParamCode = primaryPe+"I"+obsTypeSource+"Z"; - if(fcstTypeSource != null) - fcstParamCode = primaryPe +"I"+fcstTypeSource+"Z"; - - System.out.println("Obs:"+obsParamCode); - System.out.println("Fcst:"+fcstParamCode); - - String tslArgs[]= {"ohd.hseb.timeserieslite.rivermon.RiverMonDrawingMgr", - _connectionString, locationId, obsParamCode, fcstParamCode}; - - TimeSeriesLite tsl = new TimeSeriesLite(); - tsl.display(tslArgs, false); - result = true; - } - - if(!result) - { - String textMsg = "Latestobs and/or MaxFcst is unavailable.
" + - "Unable to display TimeSeriesLite."; - JOptionPane.showMessageDialog(mainFrame, textMsg,"TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - return result; - } - - public boolean displayTimeSeriesLite(MonitorFrame mainFrame, PrecipMonitorJTableRowData rowData, int hour) - { - ParamCode paramCode = null; - switch(hour) - { - case 1: - paramCode = rowData.getPrecipData().getTohPrecip1HrParamCode(); - break; - case 3: - paramCode = rowData.getPrecipData().getTohPrecip3HrParamCode(); - break; - case 6: - paramCode = rowData.getPrecipData().getTohPrecip6HrParamCode(); - break; - case 24: - paramCode = rowData.getPrecipData().getTohPrecip24HrParamCode(); - break; - } - - String obsTypeSource = null; - - String pe = null; - String dur = null; - String extremum = null; - - if(paramCode != null) - { - obsTypeSource = paramCode.getTypeSource(); - pe = "PP"; - dur = "H"; - extremum = paramCode.getExtremum(); - } - - String locationId = rowData.getLid(); - - String obsParamCode = null; - String fcstParamCode = null; - boolean result = false; - - if(paramCode == null) - { - result = false; - } - else - { - if(obsTypeSource != null) - { - obsParamCode = pe+dur+obsTypeSource+extremum; - fcstParamCode = pe + dur + "FF"+ extremum; - } - - System.out.println("Obs:"+obsParamCode); - System.out.println("Fcst:"+fcstParamCode); - - String tslArgs[]= {"ohd.hseb.timeserieslite.pdc.PDCDrawingMgr", - _connectionString, locationId, obsParamCode, fcstParamCode}; - - TimeSeriesLite tsl = new TimeSeriesLite(); - tsl.display(tslArgs, false); - result = true; - } - - if(!result) - { - String textMsg = "Top-of-hour 1 hr Precip data is unavailable.
" + - "Unable to display TimeSeriesLite."; - JOptionPane.showMessageDialog(mainFrame, textMsg,"TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - return result; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorToolBarManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorToolBarManager.java deleted file mode 100755 index c1b4b9bf95..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/MonitorToolBarManager.java +++ /dev/null @@ -1,86 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Image; -import java.awt.Toolkit; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JToolBar; - -import ohd.hseb.officenotes.OfficeNotesDataManager; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class MonitorToolBarManager { - private AppsDefaults _appsDefaults; - - protected JButton _officeNotesButton; - - private Icon _recordedOfficeNotesIcon, _emptyOfficeNotesIcon; - - private JToolBar _toolBar; - - private OfficeNotesDataManager _officeNotesDataMgr; - - public MonitorToolBarManager(JToolBar toolBar, AppsDefaults appsDefaults, - OfficeNotesDataManager officeNotesDataMgr) { - _appsDefaults = appsDefaults; - _toolBar = toolBar; - _officeNotesDataMgr = officeNotesDataMgr; - - addToolBarComponents(); - } - - private void addToolBarComponents() { - createOfficeNotesAccessButton(); - - _toolBar.setFloatable(false); - _toolBar.setRollover(true); - } - - public JButton getOfficeNotesButton() { - return _officeNotesButton; - } - - private void createOfficeNotesAccessButton() { - String iconsDir = _appsDefaults.getToken("rivermon_config_dir", - "/awips/hydroapps/whfs/local/data/app/rivermon"); - - _officeNotesButton = new JButton(); - _recordedOfficeNotesIcon = createIcon(iconsDir + "/OfficeNotes.GIF"); - _emptyOfficeNotesIcon = createIcon(iconsDir + "/EmptyOfficeNotes.GIF"); - - _officeNotesButton.setBorderPainted(false); - _officeNotesButton.setRolloverEnabled(true); - - _toolBar.add(_officeNotesButton); - - setOfficeNotesButtonIcon(_officeNotesDataMgr.getCountOfOfficeNotes()); - } - - public Icon createIcon(String fileName) { - Icon icon = null; - int width = 25; - int height = 25; - Image image = Toolkit.getDefaultToolkit().getImage(fileName); - Image newImage = image.getScaledInstance(width, height, - Image.SCALE_SMOOTH); - icon = new ImageIcon(newImage); - return icon; - } - - public void setOfficeNotesButtonIcon(int numOfOfficeNotesRecs) { - _officeNotesButton.setVisible(false); - if (numOfOfficeNotesRecs > 0) { - _officeNotesButton.setToolTipText("You have " - + numOfOfficeNotesRecs + " OfficeNotes"); - _officeNotesButton.setIcon(_recordedOfficeNotesIcon); - } else { - _officeNotesButton.setToolTipText("OfficeNotes is Empty"); - _officeNotesButton.setIcon(_emptyOfficeNotesIcon); - } - _officeNotesButton.setVisible(true); - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/ThreatLevel.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/ThreatLevel.java deleted file mode 100755 index deff13192e..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/ThreatLevel.java +++ /dev/null @@ -1,35 +0,0 @@ -package ohd.hseb.monitor; - -public enum ThreatLevel -{ - NO_THREAT, - MISSING_DATA, - AGED_DATA, - CAUTION, - ALERT; - - static boolean isDataMissingOrAged(ThreatLevel level) - { - boolean result = false; - - if ((level == ThreatLevel.AGED_DATA) || (level == ThreatLevel.MISSING_DATA) ) - { - result = true; - } - - return result; - } - // ------------------------------------------------------------------------------------- - public boolean isGreater( ThreatLevel otherLevel) - { - boolean result = false; - if (compareTo(otherLevel) > 0) - { - result = true; - } - - return result; - } -} - - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/TreeDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/TreeDataManager.java deleted file mode 100755 index 2ab9e2bb4a..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/TreeDataManager.java +++ /dev/null @@ -1,280 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -public class TreeDataManager -{ - - private Map _nodeMap = new HashMap(); - - public TreeDataManager() - { - - } - - private void addNode(DefaultMutableTreeNode baseNode, TreePath nodePath) - { - String header = "TreeDataManager.addNode(): "; - DefaultMutableTreeNode node = null; - DefaultMutableTreeNode parentNode = null; - - if(isRootPath(baseNode, nodePath)) - { -// is root node, so done - _nodeMap.put(nodePath.toString(), baseNode); - } - else //is not root node - { - //find the parent first - TreePath parentPath = nodePath.getParentPath(); - parentNode = findNode(baseNode, parentPath); - - if (parentNode != null) //found the node, so don't add it - { - //check to make sure this node does not already exist - node = findNode(parentNode, nodePath); //just search under parentNode for the child - - if (node == null) - { - DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodePath.getLastPathComponent()); - parentNode.add(childNode); - - TreePath childNodePath = getTreePathForNode(childNode); - - //System.out.println(header + "Inserting " + childNodePath.toString() + ", " + childNode + " into nodeMap"); - _nodeMap.put(childNodePath.toString(), childNode); - } - } - else //parentNode is null - { - //add the parent node - - // System.out.println(header + "Adding parent node " + parentPath.toString() + ", " + baseNode); - - addNode(baseNode, parentPath); - - //add the child node - - // System.out.println(header + "Adding childt node " + nodePath.toString() + ", " + baseNode); - - addNode(baseNode, nodePath); - } - } - } - - private boolean isRootPath(DefaultMutableTreeNode node, TreePath path) - { - boolean result = false; - - if(path != null) // is valid path - { - int pathCount = path.getPathCount(); - - if(pathCount == 1) - { - if (node.toString().equals(path.getPathComponent(0).toString())) - { - result = true; - } - } - } - - return result; - } - - private DefaultMutableTreeNode oldFindNode(DefaultMutableTreeNode node, TreePath targetPath) - { - DefaultMutableTreeNode resultNode = null; - DefaultMutableTreeNode testNode = null; - - if(node != null) - { - if(isNodeAMatchForPath(node, targetPath)) - { - resultNode = node; - } - else - { - if(isNodeInPath(node, targetPath)) - { - int childCount = node.getChildCount(); - for(int i=0; i < childCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); - - testNode = findNode(childNode, targetPath); - if (testNode != null) - { - resultNode = testNode; - break; - } - } - } - } - } - return (DefaultMutableTreeNode ) resultNode; - } - - private DefaultMutableTreeNode findNode2(DefaultMutableTreeNode node, TreePath targetPath) - { - String header = "TreeDataManager.findNode(): "; - DefaultMutableTreeNode resultNode = null; - DefaultMutableTreeNode testNode = null; - - if(node == null) - { - return null; - } - - if(isNodeInPath(node, targetPath)) - { - - if(isNodeAMatchForPath(node, targetPath)) - { - resultNode = node; - } - else //not a match - { - - int childCount = node.getChildCount(); - for(int i=0; i < childCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); - - if(isNodeInPath(childNode, targetPath)) - { - if(isNodeAMatchForPath(childNode, targetPath)) - { - // System.out.println(header + " childNode = " + - // childNode.toString() + " matches " + targetPath); - - - resultNode = childNode; - break; - } - else //not complete match, so keep looking from here on down - { - // System.out.println(header + " childNode = " + - // childNode.toString() + " is in " + targetPath); - - resultNode = findNode2(childNode, targetPath); - } - break; - } - - else //not a match and not in path - { - // System.out.println(header + " childNode = " + - // childNode.toString() + " is not in " + targetPath); - //do nothing - } - - } //end for - } //end else - - } - - return (DefaultMutableTreeNode ) resultNode; - } - - - private DefaultMutableTreeNode findNode(DefaultMutableTreeNode node, TreePath targetPath) - { - // String header = "TreeDataManager.findNode(): "; - DefaultMutableTreeNode resultNode = _nodeMap.get(targetPath.toString()); - - return resultNode; - } - - - private boolean isNodeInPath(DefaultMutableTreeNode node, TreePath targetPath) - { - boolean isInPath = false; - - TreePath nodePath = getTreePathForNode(node); - isInPath = isPathBeginningOfTargetPath(nodePath, targetPath); - - return isInPath; - } - - private boolean isPathBeginningOfTargetPath(TreePath nodePath, TreePath targetPath) - { - boolean isBeginning = false; - - String nodePathString = nodePath.toString(); - String targetPathString = targetPath.toString(); - - int length = nodePathString.length(); - nodePathString = nodePathString.substring(0, length - 1); - - isBeginning = targetPathString.startsWith(nodePathString); - - return isBeginning; - } - - private boolean isNodeAMatchForPath(DefaultMutableTreeNode node, TreePath targetPath) - { - TreePath nodePath = getTreePathForNode(node); - boolean isTargetNode = false; - - if (targetPath.toString().equals(nodePath.toString())) - { - isTargetNode = true; - } - - return isTargetNode; - } - - private TreePath getTreePathForNode(DefaultMutableTreeNode node) - { - TreePath nodePath = new TreePath(node.getPath()); - return nodePath; - } - - private List createTreePathList(List stringArrayList) - { - List treePathList = new ArrayList(); - - for(int i=0; i < stringArrayList.size(); i++) - { - String[] stringArray = (String[]) stringArrayList.get(i); - DefaultMutableTreeNode[] nodeArray = new DefaultMutableTreeNode[stringArray.length]; - for(int j=0; j < stringArray.length; j++) - { - nodeArray[j] = new DefaultMutableTreeNode(stringArray[j]); - } - TreePath path = new TreePath(nodeArray); - treePathList.add(path); - } - - return treePathList; - } - - public JTree createFilterTreeFromList(DefaultMutableTreeNode rootNode, List stringArrayList) - { - String header = "TreeDataManager.createFilterTreeFromList(): "; - - _nodeMap.clear(); - - List treePathList = createTreePathList(stringArrayList); - - for(int i=0; i < treePathList.size(); i++) - { - TreePath path = treePathList.get(i); - - addNode(rootNode, path); - } - - JTree tree = new JTree(rootNode); - - return tree; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/TreeFilterManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/TreeFilterManager.java deleted file mode 100755 index 4d6639af29..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/TreeFilterManager.java +++ /dev/null @@ -1,80 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.List; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.util.SessionLogger; - -public class TreeFilterManager -{ - private SessionLogger _logger; - private LocationDataFilter _locationDataFilter; - - public TreeFilterManager(SessionLogger logger, LocationDataFilter locationDataFilter) - { - _logger = logger; - _locationDataFilter = locationDataFilter; - } - - public LocationDataFilter getLocationDataFilter() - { - return _locationDataFilter; - } - - public List filter(List allRowDataList) - { - return (_locationDataFilter.filter(allRowDataList)); - } - - public void setDisplayStatus(String location, boolean shouldDisplay) - { - _locationDataFilter.setDisplayStatus(location, shouldDisplay); - } - - public void traversePathsToDisplayLocationSelected(TreePath paths[]) - { - String header = "TreeFilterManager.parsePathsToDisplayLocationSelected()"; - - _locationDataFilter.blockAllLocations(); - - if(paths != null) - { - for(int i=0; i < paths.length; i++) - { - if(paths[i] == null) - { - _logger.log(header + "Invalid path... Check ... "); - } - else - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent(); - setAllLocationsUnderThisNodeToBeDisplayed(node); - } - } - } - } - - public void setAllLocationsUnderThisNodeToBeDisplayed(DefaultMutableTreeNode node) - { - if(node != null) - { - if(node.isLeaf()) - { - setDisplayStatus(node.toString(), true); - } - else - { - int childCount = node.getChildCount(); - for(int i=0; i < childCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); - setAllLocationsUnderThisNodeToBeDisplayed(childNode); - } - } - } - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumn.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumn.java deleted file mode 100755 index ebc031af01..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumn.java +++ /dev/null @@ -1,103 +0,0 @@ -package ohd.hseb.monitor.derivedcolumns; - -import java.awt.Color; -import java.util.HashMap; -import java.util.Map; - -public class DerivedColumn -{ - private String _columnName; - private Color _color; - private String _equationForCellColor; - private String _returnType; - private String _equationForCellValue; - private Object _value; - private static Map _colorMap = new HashMap(); - - static - { - _colorMap.put("black", Color.BLACK); - _colorMap.put("blue", Color.BLUE); - _colorMap.put("cyan", Color.CYAN); - _colorMap.put("darkgray", Color.DARK_GRAY); - _colorMap.put("gray", Color.GRAY); - _colorMap.put("green", Color.GREEN); - _colorMap.put("lightgray", Color.LIGHT_GRAY); - _colorMap.put("magenta", Color.MAGENTA); - _colorMap.put("orange", Color.ORANGE); - _colorMap.put("pink", Color.PINK); - _colorMap.put("red", Color.RED); - _colorMap.put("white", Color.WHITE); - _colorMap.put("yellow", Color.YELLOW); - } - - public String getColumnName() - { - return _columnName; - } - - public void setColumnName(String columnName) - { - _columnName = columnName; - } - - public String getEquationForCellValue() - { - return _equationForCellValue; - } - - public void setEquationForCellValue(String valueEquation) - { - this._equationForCellValue = valueEquation; - } - - public String getEquationForCellColor() - { - return _equationForCellColor; - } - - public void setEquationForCellColor(String cellEquation) - { - this._equationForCellColor = cellEquation; - } - - public String getReturnType() - { - return _returnType; - } - - public void setReturnType(String returnType) - { - _returnType = returnType; - } - - public Object getValue() - { - return _value; - } - - public void setvalue(Object value) - { - _value = value; - } - - public void setCellBackgroundColor(Color color) - { - _color = color; - } - - public Color getCellBackgroundColor() - { - return _color; - } - - public void setCellBackgroundColor(String colorName) - { - Color color = (Color) _colorMap.get(colorName.toLowerCase()); - - if (color != null) - { - setCellBackgroundColor(color); - } - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumnsFileManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumnsFileManager.java deleted file mode 100755 index 73df5c8a26..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumnsFileManager.java +++ /dev/null @@ -1,137 +0,0 @@ -package ohd.hseb.monitor.derivedcolumns; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.util.SessionLogger; - -public class DerivedColumnsFileManager -{ - private String _derivedColumnsFile = null; - private List _derivedColumnsList = null; - private Map _derivedColumnMap = null; - private SessionLogger _logger = null; - - public DerivedColumnsFileManager(String derivedColumnsFile, SessionLogger logger) - { - _derivedColumnsFile = derivedColumnsFile; - _logger = logger; - } - - - private void printFileException(IOException exception) - { - _logger.log("RiverMonitorDerivedColumnsFileManager.printFileException(): ERROR = " + exception.getMessage()); - exception.printStackTrace(); - _logger.log("RiverMonitorDerivedColumnsFileManager.printFileException(): End of stack trace"); - } - - public List getDerivedColumns() - { - if(_derivedColumnsList == null) - _derivedColumnsList = new ArrayList(); - else - _derivedColumnsList.clear(); - - if(_derivedColumnMap == null) - _derivedColumnMap = new HashMap(); - else - _derivedColumnMap.clear(); - - Runtime.getRuntime().gc(); - File fileHandler = new File(_derivedColumnsFile); - - if(fileHandler.exists()) - { - BufferedReader in = null; - String line; - - try - { - in = new BufferedReader(new FileReader(fileHandler)); - while(( line = in.readLine()) != null) - { - String columnName; - String returnType; - String equationForValue; - String equationForColor; - - if(line.length() != 0) - { - line = line.trim(); - if(line.length() != 0 && line.charAt(0) != '#') - { - String splitStr[] = line.split("\\|"); - columnName = splitStr[0]; - returnType = splitStr[1].trim(); - equationForValue = splitStr[2]; - equationForColor = splitStr[3]; - DerivedColumn derivedColumns = new DerivedColumn(); - derivedColumns.setColumnName(columnName); - derivedColumns.setReturnType(returnType); - derivedColumns.setEquationForCellValue(equationForValue); - derivedColumns.setEquationForCellColor(equationForColor); - _derivedColumnsList.add(derivedColumns); - _derivedColumnMap.put(columnName, derivedColumns); - } - } - } - } - catch(IOException exception) - { - printFileException(exception); - } - } - else - { - _logger.log("Derived columns file doesnt exist :[" + fileHandler.getAbsolutePath() + "]"); - } - return _derivedColumnsList; - } - - protected Map getDerivedColumnMap() - { - return _derivedColumnMap; - } - - public String[] getDerivedColumnNames() - { - String derivedColumnNames[] = null; - getDerivedColumns(); - if(_derivedColumnsList.size() != 0) - { - derivedColumnNames = new String[_derivedColumnsList.size()]; - for(int i=0; i < _derivedColumnsList.size(); i++) - { - DerivedColumn derivedColumns = (DerivedColumn) _derivedColumnsList.get(i); - derivedColumnNames[i] = derivedColumns.getColumnName(); - } - } - return derivedColumnNames; - } - - public String[] getAlignmentForDerivedColumns() - { - String alignmentForDerivedColumns[] = null; - if(_derivedColumnsList.size() != 0) - { - alignmentForDerivedColumns = new String[_derivedColumnsList.size()]; - for(int i=0; i < _derivedColumnsList.size(); i++) - { - DerivedColumn derivedColumns = (DerivedColumn) _derivedColumnsList.get(i); - if(derivedColumns.getReturnType().equalsIgnoreCase("string")) - alignmentForDerivedColumns[i] = "center"; - else - alignmentForDerivedColumns[i] = "right"; - } - } - return alignmentForDerivedColumns; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/BaseManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/BaseManager.java deleted file mode 100755 index 8e7104549d..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/BaseManager.java +++ /dev/null @@ -1,45 +0,0 @@ -package ohd.hseb.monitor.manager; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class BaseManager implements Manager -{ - public MessageSystemManager _msgSystemManager; - - public void setMessageSystemManager(MessageSystemManager msgSystemManager) - { - _msgSystemManager = msgSystemManager; - } - - public void send(MonitorMessage message) - { - _msgSystemManager.send(message); - } - - public void send(Manager manager, MessageType messageType) - { - MonitorMessage message = new MonitorMessage(manager, messageType); - System.out.println("Sending..." + message.getMessageType()); - send(message); - } - - public void send(Manager manager, MessageType messageType, JTableRowData selectedRowData) - { - MonitorMessage message = new MonitorMessage(manager, messageType, selectedRowData); - System.out.println("Sending..." + message.getMessageType()); - send(message); - } - - public String toString() - { - String className = this.getClass().toString(); - int lastIndexOfDot = className.lastIndexOf('.'); - String result = className.substring(lastIndexOfDot + 1, className.length()); - - return result; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/Manager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/Manager.java deleted file mode 100755 index 393cf27e5f..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/Manager.java +++ /dev/null @@ -1,13 +0,0 @@ -package ohd.hseb.monitor.manager; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.messaging.MessageSystemManager; - -public interface Manager -{ - public String toString(); - - public void send(MonitorMessage message); - - public void setMessageSystemManager(MessageSystemManager msgSystemManager); -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/MonitorMenuManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/MonitorMenuManager.java deleted file mode 100755 index 7c53b7157c..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/MonitorMenuManager.java +++ /dev/null @@ -1,397 +0,0 @@ -package ohd.hseb.monitor.manager; - -import static ohd.hseb.util.TimeHelper.MILLIS_PER_MINUTE; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; - -import javax.swing.JButton; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.Timer; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipThresholdDialog; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.common.util.RunProcess; - -public abstract class MonitorMenuManager extends BaseManager { - private String _version; - - private String _appName; - - private String _date; - - protected MonitorFrame _mainFrame; - - private JButton _refreshNowButton; - - private JLabel _currentTimeLabel; - - private JLabel _nextRefreshTimeLabel; - - protected JSpinner _refreshTimeSpinner; - - protected JPanel _timeDisplayPanel; - - protected JLabel _dataTimeLabel; - - protected JLabel _rowCountLabel; - - private Timer _refreshDisplayTimer = null; - - protected AppsDefaults _appsDefaults; - - protected SessionLogger _logger; - - public MonitorMenuManager(MessageSystemManager msgSystemManager, - AppsDefaults appsDefaults, SessionLogger logger) { - setMessageSystemManager(msgSystemManager); - _appsDefaults = appsDefaults; - _logger = logger; - } - - protected void setAboutInfo(String version, String date, String appName) { - _version = version; - _date = date; - _appName = appName; - } - - public class AboutListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String aboutText = " Application : " + _appName + "\n" - + " Version : " + _version + "\n" - + " Date : " + _date + "\n" - + " Developed by: \n" - + " National Weather Service\n" - + " Office of Hydrologic Development\n" - + " Hydrology Laboratory"; - DialogHelper.displayMessageDialog(_mainFrame, aboutText, _appName); - } - } - - protected boolean confirmSaveOfficeSettings(String message) { - boolean result = false; - int answer = JOptionPane.showConfirmDialog(_mainFrame, message, - "Save Office Settings", JOptionPane.YES_NO_CANCEL_OPTION); - switch (answer) { - case JOptionPane.YES_OPTION: - result = true; - break; - case JOptionPane.NO_OPTION: - case JOptionPane.CANCEL_OPTION: - case JOptionPane.CLOSED_OPTION: - result = false; - break; - } - return result; - } - - protected void launchTextEditor(String editorTitle, String file, - String appName) { - String editorDir = _appsDefaults.getToken("whfs_local_bin_dir", - "/awips/hydroapps/whfs/local/bin"); - String editor = _appsDefaults.getToken("whfs_editor", "whfs_editor"); - - if (editorDir == null) { - editorDir = "."; - } - if (editor == null) { - editor = "whfs_editor"; - } - String script = editorDir.concat("/").concat(editor); - - // DR#10955 - RunProcess rt = RunProcess.getRunProcess(); - String cmd[] = new String[3]; - cmd[0] = script; - cmd[1] = editorTitle; - cmd[2] = file; - try { - _mainFrame.setWaitCursor(); - rt.exec(cmd); - _logger.log("Launch Text Editor [cmd:" + cmd[0] + " " + cmd[1] - + " " + cmd[2] + "]"); - _mainFrame.setDefaultCursor(); - } catch (IOException ex) { - _mainFrame.setDefaultCursor(); - String str = "Unable to launch text editor:[cmd" + cmd[0] + " " - + cmd[1] + " " + cmd[2] + "] Exception:" + ex; - JOptionPane.showMessageDialog(_mainFrame, str, appName, - JOptionPane.PLAIN_MESSAGE); - } - - } - - protected void createRefreshComponents(int refreshInterval, - JPanel timeDisplayPanel) { - _timeDisplayPanel = timeDisplayPanel; - - JLabel refreshLabel = new JLabel("Update(in mins)"); - int maxValueForRefreshMins = 30; - int minValueForRefreshMins = 1; - int incrValueForRefreshMins = 1; - int initialValueForRefreshMins = refreshInterval; - - SpinnerModel spinnerModel = new SpinnerNumberModel( - initialValueForRefreshMins, minValueForRefreshMins, - maxValueForRefreshMins, incrValueForRefreshMins); - _refreshTimeSpinner = new JSpinner(spinnerModel); - _refreshTimeSpinner.setPreferredSize(new Dimension(35, 20)); - // Disable keyboard edits in the spinner - JFormattedTextField textField = ((JSpinner.DefaultEditor) _refreshTimeSpinner - .getEditor()).getTextField(); - textField.setEditable(false); - _refreshTimeSpinner.addChangeListener(new RefreshTimeSpinBoxListener()); - - _timeDisplayPanel.setLayout(new GridBagLayout()); - _currentTimeLabel = new JLabel(); - _currentTimeLabel.setBackground(Color.RED); - - _nextRefreshTimeLabel = new JLabel(); - _nextRefreshTimeLabel.setBackground(Color.GREEN); - JPanel nextRefreshTimePanel = new JPanel(); - nextRefreshTimePanel.add(_nextRefreshTimeLabel); - - JPanel refreshPanel = new JPanel(); - _refreshNowButton = new JButton("Update Now"); - _refreshNowButton.setPreferredSize(new Dimension(110, 20)); - RefreshButtonListener refreshDisplayTimerListener = new RefreshButtonListener(); - _refreshNowButton.addActionListener(refreshDisplayTimerListener); - refreshPanel.add(refreshLabel); - refreshPanel.add(_refreshTimeSpinner); - refreshPanel.add(_refreshNowButton); - - _dataTimeLabel = new JLabel(); - _dataTimeLabel.setText("DEFAULT TEXT"); - - _rowCountLabel = new JLabel(); - - JPanel dummyPanel1 = new JPanel(); - JPanel dummyPanel1_25 = new JPanel(); - JPanel dummyPanel15 = new JPanel(); - JPanel dummyPanel2 = new JPanel(); - JPanel dummyPanel3 = new JPanel(); - dummyPanel1.setPreferredSize(new Dimension(50, 20)); - dummyPanel1_25.setPreferredSize(new Dimension(50, 20)); - dummyPanel15.setPreferredSize(new Dimension(50, 20)); - dummyPanel2.setPreferredSize(new Dimension(60, 20)); - dummyPanel3.setPreferredSize(new Dimension(50, 20)); - - // col, row, width, height, weightx, weighty, fill - ComponentHelper.addFrameComponent(_timeDisplayPanel, dummyPanel1, 0, 0, - 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, _rowCountLabel, 1, - 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, dummyPanel1_25, 2, - 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, _dataTimeLabel, 3, - 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, dummyPanel15, 4, - 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, _currentTimeLabel, - 5, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, dummyPanel2, 6, 0, - 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - _nextRefreshTimeLabel, 7, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, dummyPanel3, 8, 0, - 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, refreshPanel, 9, - 0, 1, 1, 0, 0, 1); - - } - - public void setInitialRefreshTimeInfo() { - setRefreshTimeSpinnerValue(); - - String curDateTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(System.currentTimeMillis()); - _currentTimeLabel.setText(" Last Update: " + curDateTimeString); - - Integer value = Integer.parseInt(_refreshTimeSpinner.getValue() - .toString()); - int refreshMilliSecs = (int) (value * MILLIS_PER_MINUTE); - System.out.println("Interval :" + value); - - String nextDateTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(System.currentTimeMillis() - + refreshMilliSecs); - String timeString[] = nextDateTimeString.split(" "); - _nextRefreshTimeLabel.setText(" Next Update: " + timeString[1]); - - // time of the PDC file read - _dataTimeLabel.setText("Precip Data Time: N/A"); - - updateRecordCount(); - - } - - protected void updateRecordCount() { - long recordCount = getDisplayedRecordCount(); - _rowCountLabel.setText(recordCount + " Locations"); - } - - private void changeTimeInformationDisplayed(long refreshMilliSecs, - boolean changeLastUpdateTime) { - long currentTime = System.currentTimeMillis(); - - if (changeLastUpdateTime) { - String curDateTimeString = DbTimeHelper - .getTimeToSecondsStringFromLongTime(currentTime); - _currentTimeLabel.setText(" Last Update: " + curDateTimeString); - } - String nextDateTimeString = DbTimeHelper - .getTimeToSecondsStringFromLongTime(currentTime - + refreshMilliSecs); - // String timeString[] = nextDateTimeString.split(" "); - _nextRefreshTimeLabel.setText(" Next Update: " + nextDateTimeString); - - // time of the PDC file read - - long dataUpdateTime = getDataUpdateTime(); - _dataTimeLabel.setText("Precip Data Time: " - + DbTimeHelper - .getTimeToSecondsStringFromLongTime(dataUpdateTime)); - - // updateRecordCount(); - - } - - protected abstract long getDataUpdateTime(); - - protected abstract long getDisplayedRecordCount(); - - public abstract void setMenuSettingsRefreshInterval(int value); - - // Refresh time spin box listener - private class RefreshTimeSpinBoxListener implements ChangeListener { - public void stateChanged(ChangeEvent e) { - Integer value = Integer.parseInt(_refreshTimeSpinner.getValue() - .toString()); - setMenuSettingsRefreshInterval(value); - int refreshMilliSecs = (int) (value * MILLIS_PER_MINUTE); - changeTimeInformationDisplayed(refreshMilliSecs, false); - startTimer(refreshMilliSecs); - } - } - - // Is attached to the update now button - private class RefreshButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - refresh(); - } - } - - protected void startTimer(int delayMilliSecs) { - if (_refreshDisplayTimer == null) { - RefreshButtonListener refreshDisplayTimerListener = new RefreshButtonListener(); - _refreshDisplayTimer = new Timer(delayMilliSecs, - refreshDisplayTimerListener); - } else { - _refreshDisplayTimer.stop(); - // This timer doesn't repeat, hence it always uses setInitialDelay - // and not setDelay - // which is used only if the timer is set to repeat - _refreshDisplayTimer.setInitialDelay(delayMilliSecs); - } - _refreshDisplayTimer.start(); - } - - public abstract void setRefreshTimeSpinnerValue(); - - protected void refreshTimeDisplay() { - Object obj = _refreshTimeSpinner.getValue(); - int refreshMilliSecs = (int) (Integer.parseInt(obj.toString()) * MILLIS_PER_MINUTE); - startTimer(refreshMilliSecs); - - setRefreshTimeSpinnerValue(); - - changeTimeInformationDisplayed(refreshMilliSecs, true); - startTimer(refreshMilliSecs); - } - - protected void refresh() { - String header = "MonitorMenuManager.refresh(): "; - - _mainFrame.setWaitCursor(); - - System.out.print(header); - send(this, MessageType.RELOAD_DATA); - refreshTimeDisplay(); - - _mainFrame.setDefaultCursor(); - } - - protected void sendMissingFilterChanged() { - String header = "MonitorMenuManager.sendMissingFilterChanged(): "; - - System.out.print(header); - send(this, MessageType.REFRESH_DISPLAY); - - } - - protected void menuChange() { - String header = "MonitorMenuManager.menuChange(): "; - - System.out.print(header); - send(this, MessageType.RELOAD_DATA); - refreshTimeDisplay(); - } - - protected class PrecipThresholdListener implements ActionListener { - private PrecipColumnDataSettings _currentMenuSettings; - - public PrecipThresholdListener( - PrecipColumnDataSettings currentMenuSettings) { - String header = "PrecipThresholdListener.PrecipThresholdListener()"; - _currentMenuSettings = currentMenuSettings; - System.out.println(header + "Current Settings: " - + _currentMenuSettings); - } - - public void actionPerformed(ActionEvent e) { - PrecipThresholdDialog precipThresholdDialog = new PrecipThresholdDialog( - _mainFrame, _currentMenuSettings, _logger); - - String header = "PrecipThresholdListener.actionPerformed()"; - // PrecipColumnDataSettings currentMenuSettings = - // _menuSettings.getPrecipSettings(); - - System.out.println(header + "Before show Current Settings: " - + _currentMenuSettings); - - PrecipColumnDataSettings savedPrecipSettings = precipThresholdDialog - .showPrecipThresholdDialog(); - if (savedPrecipSettings != null) { - _currentMenuSettings.setPrecipSettings(savedPrecipSettings); - System.out.println("Im here menu had changed"); - menuChange(); - } else { - System.out.println("Im here menu had not changed"); - } - System.out.println(header + "After show Current Settings: " - + _currentMenuSettings); - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/MonitorRefreshManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/MonitorRefreshManager.java deleted file mode 100755 index e5e32447e1..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/MonitorRefreshManager.java +++ /dev/null @@ -1,94 +0,0 @@ -package ohd.hseb.monitor.manager; - -import javax.swing.JSplitPane; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.SessionLogger; - -public abstract class MonitorRefreshManager extends BaseManager -{ - protected SessionLogger _logger; - protected JSplitPane _splitPane; - - public MonitorRefreshManager(MessageSystemManager msgSystemManager, SessionLogger logger, JSplitPane splitPane) - { - _logger = logger; - _splitPane = splitPane; - - setMessageSystemManager(msgSystemManager); - - MessageType outgoingMessageType = MessageType.REFRESH_DISPLAY; - RefreshReceiver reloadDataReceiver = new RefreshReceiver(outgoingMessageType); - _msgSystemManager.registerReceiver(reloadDataReceiver, MessageType.RELOAD_DATA); - - outgoingMessageType = MessageType.UPDATE_DISPLAY_WITH_SETTINGS; - RefreshReceiver reloadDataWithNewSettingsReceiver = new RefreshReceiver(outgoingMessageType); - _msgSystemManager.registerReceiver(reloadDataWithNewSettingsReceiver, MessageType.RELOAD_DATA_WITH_NEW_SETTINGS); - - } - - protected abstract void reloadData(MonitorMessage incomingMessage, MessageType outgoingMessageType); - - private void setSplitPaneDividerLocation() - { - String header = "MonitorRefreshManager.setSplitPaneDividerLocation(): "; - - int newDividerLocation = _splitPane.getDividerLocation(); - // int lastDividerLocation = _splitPane.getLastDividerLocation(); - - //System.out.println(header + "divider location = " + newDividerLocation); - //System.out.println(header + "last divider location = " + lastDividerLocation); - - _splitPane.setDividerLocation(newDividerLocation); - - //newDividerLocation = _splitPane.getDividerLocation(); - //lastDividerLocation = _splitPane.getLastDividerLocation(); - - // System.out.println(header + "after reset divider location, dividerLocation = " + newDividerLocation); - // System.out.println(header + "after reset divider location, lastDividerLocation = " + lastDividerLocation); - - return; - } - - private class RefreshReceiver implements Receiver - { - private MessageType _outgoingMessageType = null; - - public RefreshReceiver(MessageType outgoingMessageType) - { - _outgoingMessageType = outgoingMessageType; - } - - public void receive(MonitorMessage message) - { - String header = "MonitorRefreshManager.RefreshReceiver.receive(): "; - - //Note: setSplitPaneDividerLocation() is called to prevent the - //inadvertent shrinking of the Filter (left side of SplitPane) when, - //for example, the user maximizes the window while the - //application is refreshing. - //Why setting the divider location BEFORE actually refreshing the - //data and the JTable works is still a mystery to us as of 1/11/08. - //Mysteries are bad! - //Related code is in MonitorSplitPane. In that class, the setting of - //left and right SplitPane components occurs between calls to maintain the - //divider location (again, to avoid having the left side of the JSplitPane shrink.) - //That code is not a mystery. - - setSplitPaneDividerLocation(); - - - CodeTimer reloadTimer = new CodeTimer(); - reloadTimer.start(); - - reloadData(message, _outgoingMessageType); - - reloadTimer.stop(header + "reloadData took: "); - } - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/Receiver.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/Receiver.java deleted file mode 100755 index 3d3a8f5c64..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/manager/Receiver.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.monitor.manager; - -import ohd.hseb.monitor.MonitorMessage; - -public interface Receiver -{ - public void receive(MonitorMessage message); -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/Message.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/Message.java deleted file mode 100755 index 58548c5cff..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/Message.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.monitor.messaging; - -public class Message -{ - private MessageType _messageType; - private Object _source; - - public Message(Object source, MessageType messageType) - { - _source = source; - _messageType = messageType; - } - - public MessageType getMessageType() - { - return _messageType; - } - - public Object getMessageSource() - { - return _source; - } - - public void setMessageType(MessageType messageType) - { - _messageType = messageType; - } - - public void setMessageSource(Object source) - { - _source = source; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/MessageSystemManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/MessageSystemManager.java deleted file mode 100755 index 40002ffdb6..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/MessageSystemManager.java +++ /dev/null @@ -1,63 +0,0 @@ -package ohd.hseb.monitor.messaging; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.Receiver; - -public class MessageSystemManager -{ - private Map> _messageTypeToReceiverListMap; - - public MessageSystemManager() - { - - _messageTypeToReceiverListMap = new HashMap>(); - } - - public void registerReceiver(Receiver receiver, MessageType messageType) - { - String header = "MessageSystemManager.addMeAsListener(): "; - - List receiverList = getReceiverList(messageType); - - receiverList.add(receiver); - } - - public void send(MonitorMessage message) - { - String header = "MessageSystemManager.send(): "; - - List receiverList = getReceiverList(message.getMessageType()); - - if(receiverList != null) - { - for(Receiver receiver : receiverList) - { - receiver.receive(message); - } - } - else - { - System.out.println(header + "ReceiverList is null"); - } - } - - private List getReceiverList(MessageType messageType) - { - String header = "MessageSystemManager.getReceiverList(): "; - - List receiverList = _messageTypeToReceiverListMap.get(messageType); - - if(receiverList == null) - { - receiverList = new ArrayList(); - _messageTypeToReceiverListMap.put(messageType, receiverList); - } - - return receiverList; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/MessageType.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/MessageType.java deleted file mode 100755 index 9ec781b75f..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/messaging/MessageType.java +++ /dev/null @@ -1,42 +0,0 @@ -package ohd.hseb.monitor.messaging; - -public enum MessageType -{ - RELOAD_DATA, // Read data from database. Sent by: lookback time menu filters and refresh/update now button. Received by refresh mgr. - - REFRESH_DISPLAY, // Read filter and menu settings and refresh display. Sent by filter mgr, when the check box is - // clicked and by menu mgr when the missing filter is changed - - RELOAD_DATA_WITH_NEW_SETTINGS, // Sent by settings mgr, when new settings are loaded. Received by Refresh mgr - - UPDATE_DISPLAY_WITH_SETTINGS, // Sent by Refresh mgr, when new settings are loaded. Received by view,menu & filter mgr and they are updated - // based on the settings - - LOAD_SETTINGS, // sent by load settings menu and received by settings mgr - - LOAD_OFFICE_SETTINGS, // sent by load office settings menu and received by settings mgr - - SAVE_SETTINGS,// sent by save settings menu and received by settings mgr - - SAVE_OFFICE_SETTINGS,// sent by save office settings menu and received by settings mgr - - FILTER_SELECT_ITEM, //sent when an location in the filter tree is highlighted; Received by view mgr to highlight the row in table - - VIEW_SELECT_ITEM, // sent by view mgr when a row is selected in the table along with the row data; - // Received by menu mgr to get the corresponding row data - - CREATE_TEXT_FROM_VIEW, // sent by export table to text menu, received by view manager - - UPDATE_SETTINGS, // sent by settings mgr before saving the settings to file, - // received by view mgr to set the current table settings in view settings - - CHANGE_COLUMNS, // sent by column change menu, received by view mgr - - APP_SORT, // sent by hsa-group-location sort menu, received by view mgr - - RIVER_THREAT_SORT, // sent by threat sort menu, received by view mgr - - PRECIP_THREAT_SORT,// sent by precip threat sort menu, received by view mgr - - CLEAR_SORT; // sent by clear sort menu, received by view mgr -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipColumns.java deleted file mode 100755 index b91236a212..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipColumns.java +++ /dev/null @@ -1,94 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -/** - * - * @author rajaramv - * - * The purpose of this class is to provide a consistent set of column names and to provide the - * Descriptor list of Precipitation-related required by the OHD Java Table Framework for the RiverMonitor and PrecipMonitor - * applications. (GobsC) - */ -public class PrecipColumns -{ - public static final String LATEST_30MIN = "Latest 30min Precip"; - public static final String LATEST_1HR = "Latest 1hr Precip"; - public static final String LATEST_3HR = "Latest 3hr Precip"; - public static final String LATEST_6HR = "Latest 6hr Precip"; - public static final String LATEST_12HR = "Latest 12hr Precip"; - public static final String LATEST_18HR = "Latest 18hr Precip"; - public static final String LATEST_24HR = "Latest 24hr Precip"; - - public static final String TOH_PRECIP_1HR = "1hr Precip"; - - public static final String FFG_1HR = "FFG 1hr"; - public static final String FFG_3HR = "FFG 3hr"; - public static final String FFG_6HR = "FFG 6hr"; - - public static final String DIFF_1HR = "Diff 1hr"; - public static final String DIFF_3HR = "Diff 3hr"; - public static final String DIFF_6HR = "Diff 6hr"; - - public static final String RATIO_1HR = "Ratio 1hr %"; - public static final String RATIO_3HR = "Ratio 3hr %"; - public static final String RATIO_6HR = "Ratio 6hr %"; - - public static final String PRECIP_THREAT = "Precip Threat"; - - public static final String LATEST_PRECIP_PARAM_CODE = "Latest Precip Param Code"; - - public static final String TOH_PRECIP_1HR_PARAM_CODE = "1hr Precip Param Code"; - - /** - * Creates a list of precip columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the location info columns & precip data columns are added to it, - * if not the precip data column's list is added to the list that is passed as argument. - * The created new list is returned. - * @param precipMonitorColumnDescriptorList - * @return - */ - public List getPrecipColumnsList(List precipMonitorColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if(precipMonitorColumnDescriptorList == null) - { - precipMonitorColumnDescriptorList = new ArrayList(); - precipMonitorColumnDescriptorList = new LocationInfoColumns().getLocationInfoColumnsList(precipMonitorColumnDescriptorList); - } - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_PRECIP_PARAM_CODE, textAlignment, "Latest Precip Param Code")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.TOH_PRECIP_1HR_PARAM_CODE, textAlignment, "Top-of-Hour 1hr Precip Param Code")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_30MIN, numberAlignment, "Latest 30min Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_1HR, numberAlignment, "Latest 1hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_3HR, numberAlignment, "Latest 3hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_6HR, numberAlignment, "Latest 6hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_12HR, numberAlignment, "Latest 12hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_18HR, numberAlignment, "Latest 18hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_24HR, numberAlignment, "Latest 24hr Precip")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.TOH_PRECIP_1HR, numberAlignment, "Top-of-Hour 1hr Precip")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.FFG_1HR, numberAlignment, "FFG 1hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.FFG_3HR, numberAlignment, "FFG 3hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.FFG_6HR, numberAlignment, "FFG 6hr")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.DIFF_1HR, numberAlignment, "Latest Precip 1hr - FFG 1hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.DIFF_3HR, numberAlignment, "Latest Precip 3hr - FFG 3hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.DIFF_6HR, numberAlignment, "Latest Precip 6hr - FFG 6hr")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.RATIO_1HR, numberAlignment, "(Latest Precip 1hr/FFG 1hr) * 100")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.RATIO_3HR, numberAlignment, "(Latest Precip 3hr/FFG 3hr) * 100")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.RATIO_6HR, numberAlignment, "(Latest Precip 6hr/FFG 6hr) * 100")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.PRECIP_THREAT, textAlignment,"Precip Threat")); - - return precipMonitorColumnDescriptorList; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipData.java deleted file mode 100755 index 3c92f72891..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipData.java +++ /dev/null @@ -1,523 +0,0 @@ -package ohd.hseb.monitor.precip; - -import ohd.hseb.db.DbTable; -import ohd.hseb.model.ParamCode; - -public class PrecipData -{ - private double _ffg1Hr; - private double _ffg3Hr; - private double _ffg6Hr; - - private double _latestPrecip30Min; - private double _latestPrecip1Hr; - private double _latestPrecip3Hr; - private double _latestPrecip6Hr; - private double _latestPrecip12Hr; - private double _latestPrecip18Hr; - private double _latestPrecip24Hr; - - private double _tohPrecip1Hr; - //at the moment, with the synoptic time scales for the PDC preprocessor, - //these columns do not make sense. - // private double _tohPrecip3Hr; - // private double _tohPrecip6Hr; - // private double _tohPrecip24Hr; - - private double _diff1Hr; - private double _diff3Hr; - private double _diff6Hr; - - private int _ratio1Hr; - private int _ratio3Hr; - private int _ratio6Hr; - - private ParamCode _latestPrecipParamCode; - - private ParamCode _tohPrecip1HrParamCode; - private ParamCode _tohPrecip3HrParamCode; - private ParamCode _tohPrecip6HrParamCode; - private ParamCode _tohPrecip24HrParamCode; - - public PrecipData() - { - _ffg1Hr = DbTable.getNullDouble(); - _ffg3Hr = DbTable.getNullDouble(); - _ffg6Hr = DbTable.getNullDouble(); - - _latestPrecip30Min = DbTable.getNullDouble(); - _latestPrecip1Hr = DbTable.getNullDouble(); - _latestPrecip3Hr = DbTable.getNullDouble(); - _latestPrecip6Hr = DbTable.getNullDouble(); - _latestPrecip12Hr = DbTable.getNullDouble(); - _latestPrecip18Hr = DbTable.getNullDouble(); - _latestPrecip24Hr = DbTable.getNullDouble(); - - _tohPrecip1Hr = DbTable.getNullDouble(); - // _tohPrecip3Hr = DbTable.getNullDouble(); - // _tohPrecip6Hr = DbTable.getNullDouble(); - // _tohPrecip24Hr = DbTable.getNullDouble(); - - _diff1Hr = DbTable.getNullDouble(); - _diff3Hr = DbTable.getNullDouble(); - _diff6Hr = DbTable.getNullDouble(); - - _ratio1Hr = DbTable.getNullInt(); - _ratio3Hr = DbTable.getNullInt(); - _ratio6Hr = DbTable.getNullInt(); - } - - public double getFFG1Hr() - { - return _ffg1Hr; - } - - public void setFFG1Hr(double ffg1Hr) - { - _ffg1Hr = ffg1Hr; - } - - public double getFFG3Hr() - { - return _ffg3Hr; - } - - public void setFFG3Hr(double ffg3Hr) - { - _ffg3Hr = ffg3Hr; - } - - public double getFFG6Hr() - { - return _ffg6Hr; - } - - public void setFFG6Hr(double ffg6Hr) - { - _ffg6Hr = ffg6Hr; - } - - public double getTohPrecip1Hr() - { - return _tohPrecip1Hr; - } - - public void setTohPrecip1Hr(double tohPrecip1Hr) - { - _tohPrecip1Hr = tohPrecip1Hr; - } - /* - - public double getTohPrecip3Hr() - { - return _tohPrecip3Hr; - } - - public void setTohPrecip3Hr(double tohPrecip3Hr) - { - _tohPrecip3Hr = tohPrecip3Hr; - } - - public double getTohPrecip6Hr() - { - return _tohPrecip6Hr; - } - - public void setTohPrecip6Hr(double tohPrecip6Hr) - { - _tohPrecip6Hr = tohPrecip6Hr; - } - - public double getTohPrecip24Hr() - { - return _tohPrecip24Hr; - } - - public void setTohPrecip24Hr(double tohPrecip24Hr) - { - _tohPrecip24Hr = tohPrecip24Hr; - } - - */ - - - public double getLatestPrecip30Min() - { - return _latestPrecip30Min; - } - - public void setLatestPrecip30Min(double latestPrecip30Min) - { - _latestPrecip30Min = latestPrecip30Min; - } - - - public double getLatestPrecip1Hr() - { - return _latestPrecip1Hr; - } - - public void setLatestPrecip1Hr(double latestPrecip1Hr) - { - _latestPrecip1Hr = latestPrecip1Hr; - } - - public double getLatestPrecip3Hr() - { - return _latestPrecip3Hr; - } - - public void setLatestPrecip3Hr(double latestPrecip3Hr) - { - _latestPrecip3Hr = latestPrecip3Hr; - } - - public double getLatestPrecip6Hr() - { - return _latestPrecip6Hr; - } - - public void setLatestPrecip6Hr(double latestPrecip6Hr) - { - _latestPrecip6Hr = latestPrecip6Hr; - } - - public double getLatestPrecip12Hr() - { - return _latestPrecip12Hr; - } - - public void setLatestPrecip12Hr(double latestPrecip12Hr) - { - _latestPrecip12Hr = latestPrecip12Hr; - } - - public double getLatestPrecip18Hr() - { - return _latestPrecip18Hr; - } - - public void setLatestPrecip18Hr(double latestPrecip18Hr) - { - _latestPrecip18Hr = latestPrecip18Hr; - } - - public double getLatestPrecip24Hr() - { - return _latestPrecip24Hr; - } - - public void setLatestPrecip24Hr(double latestPrecip24Hr) - { - _latestPrecip24Hr = latestPrecip24Hr; - } - - public int getRatio1Hr() - { - return _ratio1Hr; - } - - public void setRatio1Hr(int ratio1Hr) - { - _ratio1Hr = ratio1Hr; - } - public int getRatio3Hr() - { - return _ratio3Hr; - } - - public void setRatio3Hr(int ratio3Hr) - { - _ratio3Hr = ratio3Hr; - } - public int getRatio6Hr() - { - return _ratio6Hr; - } - - public void setRatio6Hr(int ratio6Hr) - { - _ratio6Hr = ratio6Hr; - } - public double getDiff1Hr() - { - return _diff1Hr; - } - - public void setDiff1Hr(double diff1Hr) - { - _diff1Hr = diff1Hr; - } - public double getDiff3Hr() - { - return _diff3Hr; - } - - public void setDiff3Hr(double diff3Hr) - { - _diff3Hr = diff3Hr; - } - - public double getDiff6Hr() - { - return _diff6Hr; - } - - public void setDiff6Hr(double diff6Hr) - { - _diff6Hr = diff6Hr; - } - - public ParamCode getLatestPrecipParamCode() - { - return _latestPrecipParamCode; - } - - public String getLatestPrecipParamCodeString() - { - if(_latestPrecipParamCode != null) - return _latestPrecipParamCode.toString(); - else - return null; - } - - public void setLatestPrecipParamCode(ParamCode latestPrecipParamCode) - { - _latestPrecipParamCode = latestPrecipParamCode; - } - - public ParamCode getTohPrecip1HrParamCode() - { - return _tohPrecip1HrParamCode; - } - - public String getTohPrecip1HrParamCodeString() - { - if(_tohPrecip1HrParamCode != null) - return _tohPrecip1HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip1HrParamCode(ParamCode tohPrecip1HrParamCode) - { - _tohPrecip1HrParamCode = tohPrecip1HrParamCode; - } - - public ParamCode getTohPrecip3HrParamCode() - { - return _tohPrecip3HrParamCode; - } - - public String getTohPrecip3HrParamCodeString() - { - if(_tohPrecip3HrParamCode != null) - return _tohPrecip3HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip3HrParamCode(ParamCode tohPrecip3HrParamCode) - { - _tohPrecip3HrParamCode = tohPrecip3HrParamCode; - } - - public ParamCode getTohPrecip6HrParamCode() - { - return _tohPrecip6HrParamCode; - } - - public String getTohPrecip6HrParamCodeString() - { - if(_tohPrecip6HrParamCode != null) - return _tohPrecip6HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip6HrParamCode(ParamCode tohPrecip6HrParamCode) - { - _tohPrecip6HrParamCode = tohPrecip6HrParamCode; - } - - public ParamCode getTohPrecip24HrParamCode() - { - return _tohPrecip24HrParamCode; - } - - public String getTohPrecip24HrParamCodeString() - { - if(_tohPrecip24HrParamCode != null) - return _tohPrecip24HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip24HrParamCode(ParamCode tohPrecip24HrParamCode) - { - _tohPrecip24HrParamCode = tohPrecip24HrParamCode; - } - - public boolean isDataAvailable() - { - boolean result = true; - if( - DbTable.isNull(getLatestPrecip30Min()) && - DbTable.isNull(getLatestPrecip1Hr()) && - DbTable.isNull(getLatestPrecip3Hr()) && - DbTable.isNull(getLatestPrecip6Hr()) && - DbTable.isNull(getLatestPrecip12Hr()) && - DbTable.isNull(getLatestPrecip18Hr()) && - DbTable.isNull(getLatestPrecip24Hr()) && - DbTable.isNull(getTohPrecip1Hr()) - - /* - && getTohPrecip3Hr() == DbTable.getNullDouble() && - getTohPrecip6Hr() == DbTable.getNullDouble() && - getTohPrecip24Hr() == DbTable.getNullDouble() - */ - ) - { - result = false; - } - - return result; - } - - public void setTohParamCodeByHour(int hour, ParamCode paramCode) - { - switch(hour) - { - case 1: - setTohPrecip1HrParamCode(paramCode); - break; - case 3: - setTohPrecip3HrParamCode(paramCode); - break; - case 6: - setTohPrecip6HrParamCode(paramCode); - break; - case 24: - setTohPrecip24HrParamCode(paramCode); - break; - } - } - - public void setTohPrecipByHour(int hour, double precipTotal) - { - switch(hour) - { - case 1: - setTohPrecip1Hr(precipTotal); - break; - - /* - case 3: - setTohPrecip3Hr(precipTotal); - break; - case 6: - setTohPrecip6Hr(precipTotal); - break; - case 24: - setTohPrecip24Hr(precipTotal); - break; - */ - } - } - - public double getTohPrecipByHour(int hour) - { - double returnValue = DbTable.getNullDouble(); - switch (hour) - { - case 1: - returnValue = getTohPrecip1Hr(); - break; - /* - case 3: - returnValue = getTohPrecip3Hr(); - break; - case 6: - returnValue = getTohPrecip6Hr(); - break; - case 24: - returnValue = getTohPrecip24Hr(); - break; - */ - } - return returnValue; - } - - public void setLatestPrecipByHour(float hour, double precipTotal) - { - - if (hour == 0.5) - { - setLatestPrecip30Min(precipTotal); - } - else if (hour == 1) - { - setLatestPrecip1Hr(precipTotal); - } - else if (hour == 3) - { - setLatestPrecip3Hr(precipTotal); - } - else if (hour == 6) - { - setLatestPrecip6Hr(precipTotal); - } - else if (hour == 12) - { - setLatestPrecip12Hr(precipTotal); - } - else if (hour == 18) - { - setLatestPrecip18Hr(precipTotal); - } - else if (hour == 24) - { - setLatestPrecip24Hr(precipTotal); - } - - return; - } - - public double getLatestPrecipByHour(float hour) - { - double returnValue = DbTable.getNullDouble(); - - if (hour == 0.5) - { - returnValue = getLatestPrecip30Min(); - } - if (hour == 1) - { - returnValue = getLatestPrecip1Hr(); - } - else if (hour == 3) - { - returnValue = getLatestPrecip3Hr(); - } - else if (hour == 6) - { - returnValue = getLatestPrecip6Hr(); - } - else if (hour == 12) - { - returnValue = getLatestPrecip12Hr(); - } - else if (hour == 18) - { - returnValue = getLatestPrecip18Hr(); - } - else if (hour == 24) - { - returnValue = getLatestPrecip24Hr(); - } - - - return returnValue; - } -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipDataManager.java deleted file mode 100755 index d38a07df58..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipDataManager.java +++ /dev/null @@ -1,964 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.geomap.model.HrapRowColToLatLonConverter; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.RowColumnPoint; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.model.ParamCode; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.pdc_pp.PDCFileReader; -import ohd.hseb.pdc_pp.RegularObsTimeSeries; -import ohd.hseb.pdc_pp.TimeValuePair; -import ohd.hseb.util.MemoryLogger; -import ohd.hseb.util.SessionLogger; -import ucar.ma2.IndexIterator; -import ucar.nc2.NetcdfFile; -import ucar.nc2.Variable; - -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.common.mpe.util.XmrgFile; - - -public class PrecipDataManager { - private AppsDefaults _appsDefaults; - - private double _missingDoubleValue = -9999.0; - - private SessionLogger _logger; - - private Database _db; - - private PDCFileReader _pdcFileReaderForPrecipInstant; - - private PDCFileReader _pdcFileReaderForPrecip1Hour; - - private PDCFileReader _pdcFileReaderForPrecip3Hour; - - private PDCFileReader _pdcFileReaderForPrecip6Hour; - - private PDCFileReader _pdcFileReaderForPrecip24Hour; - - private long _pdcFileUpdateLongTime = 0; // this is the time of file - // creation - - private String _pdcPreprocessorFilesDir; - - private Map> _lidToLatestPrecipMap = null; - - private Map> _lidToTohPrecipMapFor1Hr = null; - - private Map> _lidToTohPrecipMapFor3Hr = null; - - private Map> _lidToTohPrecipMapFor6Hr = null; - - private Map> _lidToTohPrecipMapFor24Hr = null; - - private Map _lidToLatLonPointMap = null; - - private HrapRowColToLatLonConverter _hrapRowColToLatLonConverter = null; - - private int _baseNationalHrapRowSW; - - private int _baseNationalHrapColSW; - - private XmrgGrid _xmrgGridFor1hrFFG = null; - - private XmrgGrid _xmrgGridFor3hrFFG = null; - - private XmrgGrid _xmrgGridFor6hrFFG = null; - - public PrecipDataManager(Database db, AppsDefaults appsDefaults, - String missingRepresentation, SessionLogger logger) { - _logger = logger; - - _db = db; - _appsDefaults = appsDefaults; - _pdcPreprocessorFilesDir = _appsDefaults.getToken("pdc_pp_dir", - "/awips2/awipsShare/hydroapps/whfs/local/data/pdc_pp"); - } - - - // --------------------------------------------------------------------------------------------------- - protected Map getLidToPrecipTotalsMapFromPreprocessorFile( - PDCFileReader pdcFileReader, Map lidToPrecipTotalsMap) { - String header = "PrecipDataManager.getLidToPrecipTotalsMapFromPreprocessorFile(): "; - - // this block of code attempts to help Garbage collection reduce the - // amount of memory required - if (lidToPrecipTotalsMap == null) { - lidToPrecipTotalsMap = new HashMap(); - } else // clear out the map and its contents - { - Set lidSet = lidToPrecipTotalsMap.keySet(); - - // run through each List associated with each - // lid and clear it - for (String lid : lidSet) { - List regularObsTimeSeriesForAllTSList = (List) lidToPrecipTotalsMap - .get(lid); - regularObsTimeSeriesForAllTSList.clear(); - } - - lidToPrecipTotalsMap.clear(); - } - - checkMemoryAndGarbageCollectLog(header - + "G.065 before pdcFileReader.read(), before GC"); - - // read precip data from the PDC file - List regularObsTimeSeriesList = pdcFileReader - .read(); - - checkMemoryAndGarbageCollectLog(header - + "G.07 after pdcFileReader.read(), before GC"); - - // put the list of RegularObsTimeSeries for each lid in the - // lidToPrecipTotalsMap - if (regularObsTimeSeriesList != null) { - List regularObsTimeSeriesForAllTSList = null; - - for (RegularObsTimeSeries regularObsTimeSeries : regularObsTimeSeriesList) { - String lid = regularObsTimeSeries.getDescriptor().getLid(); - - regularObsTimeSeriesForAllTSList = (List) lidToPrecipTotalsMap - .get(lid); - - if (regularObsTimeSeriesForAllTSList == null) { - regularObsTimeSeriesForAllTSList = new ArrayList(); - - lidToPrecipTotalsMap.put(lid, - regularObsTimeSeriesForAllTSList); - } - - regularObsTimeSeriesForAllTSList.add(regularObsTimeSeries); - - } // end for each regularObsTimeSeries - - checkMemoryAndGarbageCollectLog(header + "G.08, after for loop "); - - } - - checkMemoryAndGarbageCollectLog(header + "Here G.09 after if loop "); - - return lidToPrecipTotalsMap; - } - - - private FFGFileInfo getFFGFileInfo(int hour) { - FFGFileInfo ffgFileInfo = null; - String ffgFileName = null; - File[] mosaicFileArray = getGaffMosaicFileArray(hour); - if ((mosaicFileArray != null) && (mosaicFileArray.length > 0)) { - ffgFileName = getNameOfLastModifiedFile(mosaicFileArray); - ffgFileInfo = new FFGFileInfo(ffgFileName, GaffFileFormat.XMRG); - } else // if I didn't find any GAFF output mosaic files, use GAFF input - // files - { - File[] gaffInputFileArray = getGaffInputFileArray(hour); - if ((gaffInputFileArray != null) && (gaffInputFileArray.length > 0)) { - ffgFileName = getNameOfLastModifiedFile(gaffInputFileArray); - ffgFileInfo = new FFGFileInfo(ffgFileName, - GaffFileFormat.NETCDF); - } - } - - return ffgFileInfo; - } - - private enum GaffFileFormat { - NETCDF, XMRG - } - - /* - * Wrapper to store GaffFileName and - * corresponding internal file format - */ - private class FFGFileInfo { - String filename=null; - - GaffFileFormat internalFileformat=null; - - FFGFileInfo(String filename, GaffFileFormat internlFileformat) { - this.filename = filename; - this.internalFileformat = internlFileformat; - } - } - - private String getNameOfLastModifiedFile(File[] fileArray) { - String header = "PrecipDataManager.getNameOfLastModifiedFile(): "; - String nameOfLastModifiedFile = null; - - if (fileArray != null && fileArray.length > 0 - && fileArray[0].length() > 0) { - File lastModifiedFile = findTheLatestModifiedFile(fileArray); - _logger.log(header + " lastmodifiedfile:" + lastModifiedFile); - nameOfLastModifiedFile = lastModifiedFile.toString(); - } else { - _logger.log(header + "No ffg files found."); - } - - return nameOfLastModifiedFile; - } - - // ------------------------------------------------------------------------------------------------------------ - private File[] getGaffMosaicFileArray(int hour) { - String header = "PrecipDataManager.getGaffMosaicFileArray(): "; - File filesForHour[]; - String ffgDirPathname = _appsDefaults.getToken("gaff_mosaic_dir", - "/awips2/awipsShare/hydroapps/whfs/local/data/grid/misc") + "/"; - File ffgDir = new File(ffgDirPathname); - FilenameFilter filter = new NetCdfFileNameFilter(hour); - filesForHour = ffgDir.listFiles(filter); - return filesForHour; - } - - private File[] getGaffInputFileArray(int hour) { - File filesForHour[]; - File dir = null; - String st3RfcToken = _appsDefaults.getToken("st3_rfc"); - String gafInputDir = _appsDefaults.getToken("gaff_input_dir"); - String ffgDir = gafInputDir + "/" - + new String(st3RfcToken.toUpperCase()) + "/" + hour + "hr" - + "/"; - dir = new File(ffgDir); - filesForHour = dir.listFiles(); - return filesForHour; - } - - // ------------------------------------------------------------------------------------------------------------ - - private File findTheLatestModifiedFile(File filesForHrMentioned[]) { - File lastModifiedFile = filesForHrMentioned[0]; - for (int i = 1; i < filesForHrMentioned.length; i++) { - if (filesForHrMentioned[i].lastModified() > lastModifiedFile - .lastModified()) { - lastModifiedFile = filesForHrMentioned[i]; - } - } - return lastModifiedFile; - } - - // ------------------------------------------------------------------------------------------------------------ - - private void readFFGInfoForMentionedHr(int hour) { - final String header = "PrecipDataManager.readFFGInfoForMentionedHr(): "; - FFGFileInfo ffgFileInfo = getFFGFileInfo(hour); - - if (ffgFileInfo != null - && ffgFileInfo.internalFileformat.equals(GaffFileFormat.NETCDF)) { - String ffgFileName = ffgFileInfo.filename; - NetcdfFile netCdfFile = null; - try { - netCdfFile = NetcdfFile.open(ffgFileName); - readNetCdfFileAndCreateXmargGridForMentionedHr(netCdfFile, hour); - } catch (Exception ioe) { - _logger.log(header + "Trying to open netcdf files " - + ffgFileName + " " + ioe); - } finally { - if (null != netCdfFile) { - try { - netCdfFile.close(); - } catch (IOException ioe) { - System.out.println(header - + "Trying to close netcdf files" + ffgFileName - + " " + ioe); - } - } - } - } - - if (ffgFileInfo != null - && ffgFileInfo.internalFileformat.equals(GaffFileFormat.XMRG)) { - String ffgFileName = ffgFileInfo.filename; - XmrgFile xmrgFile = new XmrgFile(ffgFileName); - try { - xmrgFile.load(); - } catch (IOException e) { - _logger.log(header + "-" + e); - } - readXmrgFileAndCreateXmrgGridForMentionedHr(xmrgFile, hour); - } - - } - - // ----------------------------------------------------------------------------------------------- - - private void createLidToLatLongMap() { - if (_lidToLatLonPointMap == null) { - String whereClause = "order by lid"; - LocationTable locationTable = new LocationTable(_db); - LocationRecord locationRecord = new LocationRecord(); - List locationList = null; - try { - locationList = locationTable.select(whereClause); - } catch (SQLException e) { - _logger.log("Error while reading location table for lat/long values:" - + e); - } - - if (locationList != null) { - LatLonPoint latLonPoint; - _lidToLatLonPointMap = new HashMap(); - for (int i = 0; i < locationList.size(); i++) { - locationRecord = (LocationRecord) locationList.get(i); - String lid = locationRecord.getLid(); - double lat = locationRecord.getLat(); - double lon = locationRecord.getLon(); - latLonPoint = new LatLonPoint(lat, lon); - _lidToLatLonPointMap.put(lid, latLonPoint); - } - } - } - } - - // ----------------------------------------------------------------------------------------------- - private void readNetCdfFileAndCreateXmargGridForMentionedHr( - NetcdfFile netCdfFile, int hour) { - createLidToLatLongMap(); - - try { - // read the netcdf file for values of x & y - // ie., the numOfLocalHrapCols & numOfLocalHrapRows - int numOfLocalHrapCols = netCdfFile.findDimension("x").getLength(); - int numOfLocalHrapRows = netCdfFile.findDimension("y").getLength(); - // System.out.println("[y, x] ie., [numOfLocalHrapRows ,numOfLocalHrapCols]:["+numOfLocalHrapRows+","+ - // numOfLocalHrapCols+"]"); - - // read netcdf file for all the ffg values in an array - // ie., read the netcdf file for values of image - ucar.ma2.Array imageArray = (ucar.ma2.Array) netCdfFile.read( - "image", false); - // System.out.println("Array:["+imageArray+"]"); - - // read netcdf file for valid time - Variable validTimeVariable = netCdfFile.findVariable("validTime"); - ucar.ma2.Array validTimeArray = validTimeVariable.read(); - - IndexIterator indexIterator = validTimeArray.getIndexIterator(); - long validTimeLong = indexIterator.getLongNext(); - - // System.out.println("valid time:"+ validTimeArray +" long:"+ - // validTimeLong); - - // read netcdf file for latitude and longitude values of the grid - // area. - // this is the NW point (top left corner) point in the whole grid - // area represented by the netcdf file - ucar.nc2.Attribute lat = (ucar.nc2.Attribute) netCdfFile - .findGlobalAttribute("lat00"); - ucar.nc2.Attribute lon = (ucar.nc2.Attribute) netCdfFile - .findGlobalAttribute("lon00"); - - double latitude = lat.getNumericValue().doubleValue(); - double longitude = lon.getNumericValue().doubleValue(); - - // System.out.println("[latitude,longitude]:["+latitude+","+ - // longitude+"]"); - - createHrapRowColToLatLonConverter(latitude, longitude, - numOfLocalHrapRows); - - createXmrgGridAndSetGridValues(validTimeLong, numOfLocalHrapRows, - numOfLocalHrapCols, imageArray, hour); - } catch (Exception e) { - System.out.println("Error while reading netcdf file:" + e); - e.printStackTrace(); - } - } - - private void readXmrgFileAndCreateXmrgGridForMentionedHr(XmrgFile xmrgFile, - int hour) { - - createLidToLatLongMap(); - - //National HRAP coordinates for the SW corner of this local xmrg grid - _baseNationalHrapRowSW = xmrgFile.getHrapExtent().y; - _baseNationalHrapColSW = xmrgFile.getHrapExtent().x; - - //extract grid data from xmrg file - short[] data = xmrgFile.getData(); - int numOfLocalHrapRows = xmrgFile.getHrapExtent().height; - int numOfLocalHrapCols = xmrgFile.getHrapExtent().width; - long validTime = xmrgFile.getHeader().getValidDate().getTime(); - - //Actually create and populate an xmrg grid object - createXmrgGridAndSetGridValues(validTime, numOfLocalHrapRows, - numOfLocalHrapCols, data, hour); - } - - // ----------------------------------------------------------------------------------------------- - - private void createXmrgGridAndSetGridValues(long validTime, - int numOfLocalHrapRows, int numOfLocalHrapCols, - ucar.ma2.Array array, int hour) { - - XmrgGrid xmrgGrid = new XmrgGrid(validTime, _baseNationalHrapRowSW, - _baseNationalHrapColSW, numOfLocalHrapRows, numOfLocalHrapCols); - - // create a xmrggrid with the given validtime - - switch (hour) { - case 1: - _xmrgGridFor1hrFFG = xmrgGrid; - break; - case 3: - _xmrgGridFor3hrFFG = xmrgGrid; - break; - case 6: - _xmrgGridFor6hrFFG = xmrgGrid; - break; - default: - _xmrgGridFor1hrFFG = xmrgGrid; - } - - // populate the xmrggrid with values read from netcdf file - // note: netcdf values are is read from NW and it is left to right in - // consecutive line ( top to bottom ) ie., usual way - // xmrggrid values are read from SW and it is also left to right in - // consecutive line ( bottom to top) ie., not usual way - int xmrgRowNumber = 0; - IndexIterator indexIterator = array.getIndexIterator(); - - for (int rowIndex = numOfLocalHrapRows - 1; rowIndex >= 0; rowIndex--) { - for (int columnIndex = 0; columnIndex < numOfLocalHrapCols; columnIndex++) { - if (indexIterator.hasNext()) { - - // double value = indexIterator.getDoubleNext(); - int value = indexIterator.getIntNext(); - double convertedValue = convertFfgValue(value); - - // System.out.println("Try to enter:["+ rowIndex+","+ - // columnIndex+"]" + value); - xmrgGrid.setValue(rowIndex + _baseNationalHrapRowSW, - columnIndex + _baseNationalHrapColSW, - convertedValue); - } - } - xmrgRowNumber++; - } - - } - - /* - * overloaded method for use with data array - * read from xmrg file. - */ - private void createXmrgGridAndSetGridValues(long validTime, - int numOfLocalHrapRows, int numOfLocalHrapCols, short[] array, - int hour) { - - XmrgGrid xmrgGrid = new XmrgGrid(validTime, _baseNationalHrapRowSW, - _baseNationalHrapColSW, numOfLocalHrapRows, numOfLocalHrapCols); - switch (hour) { - case 1: - _xmrgGridFor1hrFFG = xmrgGrid; - break; - case 3: - _xmrgGridFor3hrFFG = xmrgGrid; - break; - case 6: - _xmrgGridFor6hrFFG = xmrgGrid; - break; - default: - _xmrgGridFor1hrFFG = xmrgGrid; - } - - // populate the xmrg grid with data array read from Xmrg file - for (int y = numOfLocalHrapRows - 1; y >= 0; y--) { - for (int x = 0; x < numOfLocalHrapCols; x++) { - short value = array[y * numOfLocalHrapCols + x]; - xmrgGrid.setValue(y + _baseNationalHrapRowSW, x - + _baseNationalHrapColSW, value); - } - } - - } - - // ----------------------------------------------------------------------------------------------- - /* - * This method is replicated from ffconv method in ffconv.c - */ - private double convertFfgValue(double originalValue) { - - String header = "PrecipDataManage.convertFfgValue(): "; - - double signFixedValue = originalValue; - double returnValue = 0.0; - final double lowerThreshold = 201; - final double upperThreshold = 253; - final double mFactor = 6; - final double inchPerMM = 0.03937; - - // These are values from image file and they are byte counts. - // These are similar to an enhanced satellite image. - // So normally the values go from 0 to 255 (256 values). - // But, for values beyond 127, they turn negative. - // So value 128 is really 128 - 256 = -128 in the file - // hence you will need to add 256 for negative values to get the actual - // positive value - // This actual value is what is needed. - if (signFixedValue < 0) { - signFixedValue += 256; - } - - // convert the coded value to actual precip amounts in inches - if (signFixedValue == 0) { - returnValue = DbTable.getNullDouble(); - } else if (signFixedValue <= lowerThreshold) { - returnValue = signFixedValue - 1; - returnValue *= inchPerMM; - } else if (signFixedValue <= upperThreshold) { - returnValue = (lowerThreshold - 1) - + ((signFixedValue - 1) - (lowerThreshold - 1)) * mFactor; - returnValue *= inchPerMM; - } else if (signFixedValue >= upperThreshold) { - returnValue = DbTable.getNullDouble(); - } - - return returnValue; - } - - // ----------------------------------------------------------------------------------------------- - private void createHrapRowColToLatLonConverter(double latitude, - double longitude, int numOfLocalHrapRows) { - // with the NW(top left corner) latitude/longitude info - // get the national hrap cordinates for the NW (top left corner) - // TODO examine the negation of longitude - ask Bryon - - RowColumnPoint nationalHrapCoorinatesNW = HrapRowColToLatLonConverter - .getNationalRowColumnPoint(latitude, -longitude); - - // with the national hrap coordinates for the NW (top left corner) - // and the num of local hrap rows and num of local hrap cols info read - // from the netcdf file - // determine the base national hrap row and base national hrap col - // ie., the base national SW point's row number and column number - // which is the bottom left corner's info - _baseNationalHrapRowSW = (int) (nationalHrapCoorinatesNW.getRow() - numOfLocalHrapRows); - _baseNationalHrapColSW = (int) nationalHrapCoorinatesNW.getCol(); - - if (_hrapRowColToLatLonConverter == null) { - _hrapRowColToLatLonConverter = new HrapRowColToLatLonConverter( - _baseNationalHrapRowSW, _baseNationalHrapColSW); - } - // LatLonPoint latLong = - // _hrapRowColToLatLonConverter.getLatLonPoint(numOfLocalHrapRows -1, - // 0); - // System.out.println("lat long:"+ latLong); - } - - // ----------------------------------------------------------------------------------------------- - - public void setTohPrecipDataForThisLidForMentionedHour(String lid, - PrecipData precipData, int hour) { - Map> lidToTohPrecipTimeSeriesMap = null; - - switch (hour) { - case 1: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor1Hr; - break; - case 3: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor3Hr; - break; - case 6: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor6Hr; - break; - case 24: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor24Hr; - break; - } - if (lidToTohPrecipTimeSeriesMap.size() > 0) { - List regularObsTimeSeriesForAllTSList = lidToTohPrecipTimeSeriesMap - .get(lid); - - int count = 0; - if (regularObsTimeSeriesForAllTSList != null) { - for (RegularObsTimeSeries regularObsTimeSeries : regularObsTimeSeriesForAllTSList) { - String paramCodeString = regularObsTimeSeries - .getDescriptor().getShef_param_code(); - ParamCode paramCode = new ParamCode(paramCodeString); - - List timeValuePairsForParticularTSList = regularObsTimeSeries - .getTimeValuePairList(true); - int indexOfLastTimeValuePair = timeValuePairsForParticularTSList - .size() - 1; - - // The last period is a partially-completed period. - // The previous period the most recent complete period. - int indexOfOfLastCompletedPeriod = indexOfLastTimeValuePair - 1; - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfOfLastCompletedPeriod); - double precipTotal = timeValuePair.getValue(); - - boolean checkPrevValue = true; - if (count == 0) { - checkPrevValue = false; - } - - if (precipTotal != _missingDoubleValue) { - if (checkPrevValue) { - if (precipTotal > precipData - .getTohPrecipByHour(hour)) { - precipData - .setTohPrecipByHour(hour, precipTotal); - precipData.setTohParamCodeByHour(hour, - paramCode); - } - } else { - precipData.setTohPrecipByHour(hour, precipTotal); - precipData.setTohParamCodeByHour(hour, paramCode); - } - } else // make sure that the param code is available for - // missing data - { - precipData.setTohParamCodeByHour(hour, paramCode); - } - count++; - }// end of for loop - }// end of if(regularobstimeseriesforallTSlist != null) - } - } - - // ----------------------------------------------------------------------------------------------- - - public void setLatestPrecipDataForThisLid(String lid, PrecipData precipData) { - if (_lidToLatestPrecipMap != null && _lidToLatestPrecipMap.size() > 0) { - List regularObsTimeSeriesForAllTSList = _lidToLatestPrecipMap - .get(lid); - - if (regularObsTimeSeriesForAllTSList != null) { - for (int i = 0; i < regularObsTimeSeriesForAllTSList.size(); i++) { - RegularObsTimeSeries regularObsTimeSeriesForParticularTS = regularObsTimeSeriesForAllTSList - .get(i); - - String paramCodeString = regularObsTimeSeriesForParticularTS - .getDescriptor().getShef_param_code(); - ParamCode paramCode = new ParamCode(paramCodeString); - - precipData.setLatestPrecipParamCode(paramCode); - - List timeValuePairsForParticularTSList = regularObsTimeSeriesForParticularTS - .getTimeValuePairList(true); - - int indexOfLastTimeValuePair = timeValuePairsForParticularTSList - .size() - 1; - boolean checkPrevValue = true; - if (i == 0) { - checkPrevValue = false; - } - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair); - setLatestPrecipForHrMentioned(0.5f, timeValuePair, - precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair - 1); - setLatestPrecipForHrMentioned(1, timeValuePair, precipData, - checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair - 3); - setLatestPrecipForHrMentioned(3, timeValuePair, precipData, - checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair - 6); - setLatestPrecipForHrMentioned(6, timeValuePair, precipData, - checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair - 12); - setLatestPrecipForHrMentioned(12, timeValuePair, - precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair - 18); - setLatestPrecipForHrMentioned(18, timeValuePair, - precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList - .get(indexOfLastTimeValuePair - 24); - setLatestPrecipForHrMentioned(24, timeValuePair, - precipData, checkPrevValue); - - } - } - } - } - - // ------------------------------------------------------------------------------------------------------------ - - public void setFFGDataForThisLid(String lid, PrecipData precipData) { - if (_lidToLatLonPointMap != null) { - LatLonPoint latLon = (LatLonPoint) _lidToLatLonPointMap.get(lid); - if (latLon != null) { - double lat = latLon.getLat(); - double lon = latLon.getLon(); - _logger.log("For lid:"+ lid + " [lat,lon]:"+ lat +","+ lon); - - RowColumnPoint rowColumnPoint = HrapRowColToLatLonConverter - .getNationalRowColumnPoint(lat, lon); - int rowPoint = (int) rowColumnPoint.getRow(); - int colPoint = (int) rowColumnPoint.getCol(); - double value = _xmrgGridFor1hrFFG.getValue(rowPoint, colPoint); - if (value != XmrgGrid.OFF_GRID_VALUE) - precipData.setFFG1Hr(value); - - value = _xmrgGridFor3hrFFG.getValue(rowPoint, colPoint); - if (value != XmrgGrid.OFF_GRID_VALUE) - precipData.setFFG3Hr(value); - - value = _xmrgGridFor6hrFFG.getValue(rowPoint, colPoint); - if (value != XmrgGrid.OFF_GRID_VALUE) - precipData.setFFG6Hr(value); - - if (value == 0.00) { - System.out.println("For lid:" + lid + " value is:" + value); - } - } - - } - } - - // ----------------------------------------------------------------------------------------------- - public void set1Hr3Hr6HrRatio(PrecipData precipData) { - precipData.setRatio1Hr(determinePrecipFFGRatio( - precipData.getLatestPrecip1Hr(), precipData.getFFG1Hr())); - precipData.setRatio3Hr(determinePrecipFFGRatio( - precipData.getLatestPrecip3Hr(), precipData.getFFG3Hr())); - precipData.setRatio6Hr(determinePrecipFFGRatio( - precipData.getLatestPrecip6Hr(), precipData.getFFG6Hr())); - return; - } - - // ----------------------------------------------------------------------------------------------- - - private int determinePrecipFFGRatio(double precip, double ffg) { - int ratio = DbTable.getNullInt(); - - if ((ffg != 0.00 && ffg != DbTable.getNullDouble()) - && precip != DbTable.getNullDouble()) // to avoid divide by 0 - // value - { - ratio = (int) ((precip / ffg) * 100); - } - - return ratio; - } - - // ----------------------------------------------------------------------------------------------- - - public Map> readPrecipFile( - String fileName, PDCFileReader pdcFileReader, - Map> lidToLatestPrecipMap) { - if (pdcFileReader == null) { - pdcFileReader = new PDCFileReader(_pdcPreprocessorFilesDir - + fileName); - } else { - pdcFileReader.resetObsTimeSeriesList(); - } - - lidToLatestPrecipMap = getLidToPrecipTotalsMapFromPreprocessorFile( - pdcFileReader, lidToLatestPrecipMap); - - return lidToLatestPrecipMap; - } - - public void readPDCPreprocessorPrecipFiles() { - String header = "PrecipDataManager.readPDCPreprocessorPrecipFiles(): "; - - // determine the last update time for PDC Precip data - setPdcFileUpdateLongTime(0); - File file = new File(_pdcPreprocessorFilesDir + "/PrecipInstant.dat"); - if (file != null) { - setPdcFileUpdateLongTime(file.lastModified()); - System.out - .println(header - + " the last modified file time = " - + DbTimeHelper - .getDateTimeStringFromLongTime(getPdcFileUpdateLongTime())); - file = null; - } - - // read the - _lidToLatestPrecipMap = readPrecipFile("/PrecipInstant.dat", - _pdcFileReaderForPrecipInstant, _lidToLatestPrecipMap); - checkMemoryAndGarbageCollectLog(header - + "Here after reading precip instant"); - - _lidToTohPrecipMapFor1Hr = readPrecipFile("/Precip1Hour.dat", - _pdcFileReaderForPrecip1Hour, _lidToTohPrecipMapFor1Hr); - checkMemoryAndGarbageCollectLog(header - + "Here after reading precip 1 hour :"); - - _lidToTohPrecipMapFor3Hr = readPrecipFile("/Precip3Hour.dat", - _pdcFileReaderForPrecip3Hour, _lidToTohPrecipMapFor3Hr); - checkMemoryAndGarbageCollectLog(header - + "Here after reading precip 3 hour :"); - - _lidToTohPrecipMapFor6Hr = readPrecipFile("/Precip6Hour.dat", - _pdcFileReaderForPrecip6Hour, _lidToTohPrecipMapFor6Hr); - checkMemoryAndGarbageCollectLog(header - + "Here after reading precip 6 hour :"); - - _lidToTohPrecipMapFor24Hr = readPrecipFile("/Precip24Hour.dat", - _pdcFileReaderForPrecip24Hour, _lidToTohPrecipMapFor24Hr); - checkMemoryAndGarbageCollectLog(header - + "Here after reading precip 24 hour :"); - } - - public void checkMemoryAndGarbageCollectLog(String message) { - Runtime runtime = Runtime.getRuntime(); - String text = null; - - long freeMemory = runtime.freeMemory(); - - final long SMALL_AMOUNT_OF_MEMORY = 30000000; - - if (freeMemory < SMALL_AMOUNT_OF_MEMORY) { - text = message + "Free:" + freeMemory + " Max:" - + runtime.maxMemory() + " total:" + runtime.totalMemory(); - MemoryLogger.log(text); - - runtime.gc(); - } - } - - // ------------------------------------------------------------------------------------------------------------ - - public void readPrecipData(List rowDataList, String tag) { - String header = "PrecipDataManager.readLatestPrecipData(): "; - - System.out.println(header + "Reading precip data"); - - readPDCPreprocessorPrecipFiles(); - - readFFGInfoForMentionedHr(1); - readFFGInfoForMentionedHr(3); - readFFGInfoForMentionedHr(6); - - for (int i = 0; i < rowDataList.size(); i++) { - String lid = null; - PrecipData precipData = new PrecipData(); - if (tag.compareTo("PRECIP") == 0) { - PrecipMonitorJTableRowData precipMonitorRowData = (PrecipMonitorJTableRowData) rowDataList - .get(i); - lid = (String) precipMonitorRowData.getLid(); - precipMonitorRowData.setPrecipData(precipData); - } else { - RiverMonitorJTableRowData riverMonitorRowData = (RiverMonitorJTableRowData) rowDataList - .get(i); - lid = (String) riverMonitorRowData.getLid(); - riverMonitorRowData.setPrecipData(precipData); - } - setLatestPrecipDataForThisLid(lid, precipData); - - setFFGDataForThisLid(lid, precipData); - - setTohPrecipDataForThisLidForMentionedHour(lid, precipData, 1); - setTohPrecipDataForThisLidForMentionedHour(lid, precipData, 3); - setTohPrecipDataForThisLidForMentionedHour(lid, precipData, 6); - setTohPrecipDataForThisLidForMentionedHour(lid, precipData, 24); - - setFfgDifferenceValues(precipData); - - set1Hr3Hr6HrRatio(precipData); - - } // end of for loop - checkMemoryAndGarbageCollectLog(header + "End of read precip method "); - } - - // ------------------------------------------------------------------------------------------------------------ - private void setFfgDifferenceValues(PrecipData precipData) { - precipData.setDiff1Hr(determineFfgDifferenceValue( - precipData.getLatestPrecip1Hr(), precipData.getFFG1Hr())); - precipData.setDiff3Hr(determineFfgDifferenceValue( - precipData.getLatestPrecip3Hr(), precipData.getFFG3Hr())); - precipData.setDiff6Hr(determineFfgDifferenceValue( - precipData.getLatestPrecip6Hr(), precipData.getFFG6Hr())); - } - - // ------------------------------------------------------------------------------------------------------------ - - private double determineFfgDifferenceValue(double precipValue, - double ffgValue) { - - double diffValue = DbTable.getNullDouble(); - - if ((DbTable.isNull(precipValue)) || (DbTable.isNull(ffgValue))) { - // no good - } else { - diffValue = precipValue - ffgValue; - } - - return diffValue; - } - - // ------------------------------------------------------------------------------------------------------------ - - private void setLatestPrecipForHrMentioned(float hour, - TimeValuePair timeValuePair, PrecipData precipData, - boolean checkPrevValue) { - double precipTotal = timeValuePair.getValue(); - - if (precipTotal != _missingDoubleValue) // used since the pdc - // preprocessor represents - // missing as -9999.0 - { - if (checkPrevValue) { - if (precipTotal > precipData.getLatestPrecipByHour(hour)) - precipData.setLatestPrecipByHour(hour, precipTotal); - } else - precipData.setLatestPrecipByHour(hour, precipTotal); - } - } - - public void setPdcFileUpdateLongTime(long pdcFileUpdateLongTime) { - _pdcFileUpdateLongTime = pdcFileUpdateLongTime; - } - - public long getPdcFileUpdateLongTime() { - return _pdcFileUpdateLongTime; - } - - // -------------------------------------------------------------------------------- - class NetCdfFileNameFilter implements FilenameFilter { - - String pattern = "0"; // <---removed the leading underscore "_0" - - public NetCdfFileNameFilter(int hour) { - pattern += hour + ".ffg"; - } - - public boolean accept(String name) { - return name.contains(pattern); - } - - public boolean accept(File arg0, String name) { - return name.contains(pattern); - } - - public String toString() { - return pattern; - } - - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipLocationDataFilter.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipLocationDataFilter.java deleted file mode 100755 index 9ba4df2420..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipLocationDataFilter.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.util.BooleanHolder; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class PrecipLocationDataFilter extends LocationDataFilter -{ - - private BooleanHolder _showMissingBooleanHolder = null; - - public PrecipLocationDataFilter(Map locationDisplayMap, BooleanHolder showMissingBooleanHolder) - { - _locationDisplayMap = locationDisplayMap; - _showMissingBooleanHolder = showMissingBooleanHolder; - } - - /** - * Filter the allRowDataList based on the locationDisplayMap - */ - public List filter(List allRowDataList) - { - boolean showMissing = _showMissingBooleanHolder.getValue(); - List filteredRowDataList = new ArrayList(); - - if (_locationDisplayMap != null) - { - for (int i = 0; i < allRowDataList.size(); i++) - { - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData) allRowDataList.get(i); - String lid = rowData.getLid(); - Boolean shouldDisplay = _locationDisplayMap.get(lid); - if ((shouldDisplay != null) && (shouldDisplay) ) //based on selection in the tree - { - if (showMissing) //based on menu selection - { - filteredRowDataList.add(rowData); - } - else //don't show missing - { - if (rowData.getPrecipData().isDataAvailable()) - { - filteredRowDataList.add(rowData); - } - } - } //end if shouldDisplay - } //end for - } - - - return filteredRowDataList; - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipMonitorDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipMonitorDataManager.java deleted file mode 100755 index a3e2772aaa..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipMonitorDataManager.java +++ /dev/null @@ -1,639 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.awt.Color; -import java.io.FileWriter; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.AdminRecord; -import ohd.hseb.ihfsdb.generated.AdminTable; -import ohd.hseb.ihfsdb.generated.LocRiverMonRecord; -import ohd.hseb.ihfsdb.generated.LocRiverMonView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.monitor.TreeFilterManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.rivermonlocgroup.RiverMonLocGroupDataManager; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; - -import org.apache.bsf.BSFEngine; -import org.apache.bsf.BSFManager; - -import com.raytheon.uf.common.ohd.AppsDefaults; - - -public class PrecipMonitorDataManager { - - private Database _db; - - private AppsDefaults _appsDefaults; - - private SessionLogger _logger; - - private String _defaultHsa; - - private Set _precipLidSet = null; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private List _derivedColumnsList; - - private BSFManager _bsfManager; - - private BSFEngine _beanShellEngine; - - private String _missingRepresentation; - - private List _precipMonitorRowDataList; - - private List _missingPrecipMonitorRowDataList = new ArrayList(); - - private Map _lidDescDetailsMap; - - private Map _lidToRiverBasinMap = new HashMap(); - - private TreeFilterManager _treeFilterManager; - - private String _lidOfCurrentInterest; - - private PrecipMonitorMenuSettings _menuSettings; - - private RiverMonLocGroupDataManager _riverMonLocGroupDataManager; - - private OfficeNotesDataManager _officeNotesDataManager; - - private PrecipDataManager _precipDataManager; - - public PrecipMonitorDataManager(Database db, AppsDefaults appsDefaults, - String missingRepresentation, SessionLogger logger, - PrecipMonitorMenuSettings menuSettings, - DerivedColumnsFileManager derivedColumnsFileManager) { - _appsDefaults = appsDefaults; - _menuSettings = menuSettings; - - _db = db; - _missingRepresentation = missingRepresentation; - _logger = logger; - - _precipDataManager = new PrecipDataManager(_db, _appsDefaults, - _missingRepresentation, _logger); - readAdminTable(); - - _riverMonLocGroupDataManager = new RiverMonLocGroupDataManager(db, - _logger, missingRepresentation, getDefaultHsa()); - - _derivedColumnsFileManager = derivedColumnsFileManager; - - _officeNotesDataManager = new OfficeNotesDataManager(db, _logger, - missingRepresentation); - - try { - initializeBSF(); - } catch (Exception e) { - _logger.log("PrecipMonitorDataManager.PrecipMonitorDataManager(): Error while initialize BSF..." - + e); - } - } - - public RiverMonLocGroupDataManager getRiverMonLocGroupDataManager() { - return _riverMonLocGroupDataManager; - } - - public OfficeNotesDataManager getOfficeNotesDataManager() { - return _officeNotesDataManager; - } - - public TreeFilterManager getTreeFilterManager() { - if (_treeFilterManager == null) { - _treeFilterManager = new TreeFilterManager(_logger, - getLocationDataFilter()); - } - return _treeFilterManager; - } - - public void setLidOfCurrentInterest(String lid) { - _lidOfCurrentInterest = lid; - } - - public String getLidOfCurrentInterest() { - return _lidOfCurrentInterest; - } - - public long getPdcUpdateTime() { - return _precipDataManager.getPdcFileUpdateLongTime(); - } - - public long getDisplayedRecordCount() { - String header = "PrecipMonitorDataManager.getDisplayedRecordCount(): "; - printLocationCounts(header + "_precipMonitorRowDataList "); - - // System.out.println(header + " _precipMonitorRowDataList count = " + - // _precipMonitorRowDataList.size()); - - List selectedRowDataList = getTreeFilterManager().filter( - _precipMonitorRowDataList); - long displayedCount = selectedRowDataList.size(); - - // printLocationCounts(header + " after filter applied "); - - // System.out.println(header + " selectedRowDataList count = " + - // displayedCount); - - return displayedCount; - - } - - public void disconnect() { - _db.disconnect(); - } - - public boolean getShowMissing() { - return _menuSettings.shouldShowMissingPrecip(); - } - - public PrecipColumnDataSettings getPrecipSettings() { - return _menuSettings.getPrecipSettings(); - } - - private void printLocationCounts(String header) { - System.out.println(header + "There are " - + _precipMonitorRowDataList.size() + " displayed with " - + _missingPrecipMonitorRowDataList.size() - + " non-displayed missing locations."); - - writeLidsToFile(); - - } - - private void writeLidsToFile() { - FileWriter writer = null; - - try { - // writer = new - // FileWriter("/awips/hydroapps/ob83_fwr/whfs/bin/PrecipMonitorLocations.txt"); - String whfsBinDir = - this._appsDefaults.getToken("whfs_bin_dir", - "/awips2/awipsShare/hydroapps/whfs/bin"); - - writer = new FileWriter( - whfsBinDir + "/PrecipMonitorLocations.txt"); - for (PrecipMonitorJTableRowData row : _precipMonitorRowDataList) { - writer.write(row.getLid() + "\n"); - } - - writer.close(); - } - - catch (IOException e) { - e.printStackTrace(); - } - - } - - public Map getLidToCriticalColorMap() { - String header = "PrecipMonitorDataManager.getLidToCriticalColorMap(): "; - - Map lidToCriticalColorMap = new HashMap(); - for (PrecipMonitorJTableRowData rowData : _precipMonitorRowDataList) { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - for (PrecipMonitorJTableRowData rowData : _missingPrecipMonitorRowDataList) { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - printLocationCounts(header); - - return lidToCriticalColorMap; - } - - public List getLidList() { - String header = "PrecipMonitorDataManager.getLidList(): "; - List lidList = new ArrayList(); - for (PrecipMonitorJTableRowData rowData : _precipMonitorRowDataList) { - String lid = rowData.getLid(); - lidList.add(lid); - } - - System.out.println(header + "_precipMonitorRowDataList.size() = " - + _precipMonitorRowDataList.size()); - - return lidList; - } - - private List getFullListOfLocationIds() { - List locationIdList = new ArrayList(); - - for (PrecipMonitorJTableRowData rowData : _precipMonitorRowDataList) { - locationIdList.add(rowData.getLid()); - } - - return locationIdList; - - } - - // --------------------------------------------------------------------------------------------------- - - private LocationDataFilter getLocationDataFilter() { - PrecipLocationDataFilter locationDataFilter; - List lidList = getFullListOfLocationIds(); - Map locationDisplayMap = new HashMap(); - - for (String lid : lidList) { - locationDisplayMap.put(lid, false); - } - - locationDataFilter = new PrecipLocationDataFilter(locationDisplayMap, - _menuSettings.getShowMissingPrecipBooleanHolder()); - return locationDataFilter; - } - - private void readAdminTable() { - AdminTable adminTable = new AdminTable(_db); - List adminList = null; - try { - adminList = adminTable.select(""); - } catch (SQLException e) { - logSQLException(e); - } - _defaultHsa = ((AdminRecord) adminList.get(0)).getHsa(); - } - - protected void readCurrentRiverMonTableData() { - /** - * Delegate to the RiverMonLocGroupDataManager the initialization of the - * location and group definitions and ordering. - */ - _riverMonLocGroupDataManager.initializeRiverMonTableData(); - - } - - /** - * Reads the location table and creates the list of - * PrecipMonitorJtableRowdata objects for each location and fills in its - * name, state , county info - * - * @return - */ - private List readPrecipLocationInfo() { - if (_precipLidSet == null) - _precipLidSet = new HashSet(); - else - _precipLidSet.clear(); - - if (_precipMonitorRowDataList != null) { - for (PrecipMonitorJTableRowData precipMonitorRowData : _precipMonitorRowDataList) { - precipMonitorRowData.resetCellMap(); - } - _precipMonitorRowDataList.clear(); - } - - Runtime.getRuntime().gc(); - List precipMonitorRowDataList = new ArrayList(); - - LocationTable locationTable = new LocationTable(_db); - - List locationRecordList; - - loadRiverBasinData(); - - try { - String whereClause = "where lid in (select distinct(lid) from ingestfilter where pe in('PC', 'PP') and ingest='T')"; - locationRecordList = locationTable.select(whereClause); - if (locationRecordList != null) { - for (LocationRecord locationRecord : locationRecordList) { - PrecipMonitorJTableRowData precipMonitorRowData = new PrecipMonitorJTableRowData( - _missingRepresentation, this, _logger); - - precipMonitorRowData.setLid(locationRecord.getLid()); - precipMonitorRowData.setName(locationRecord.getName()); - precipMonitorRowData.setCounty(locationRecord.getCounty()); - precipMonitorRowData.setState(locationRecord.getState()); - - setRiverBasinData(precipMonitorRowData); - - precipMonitorRowDataList.add(precipMonitorRowData); - _precipLidSet.add(locationRecord.getLid()); - } - } - } catch (SQLException e) { - logSQLException(e); - } - return precipMonitorRowDataList; - } - - public List getPrecipMonitorRowDataList() { - return _precipMonitorRowDataList; - } - - private void loadRiverBasinData() { - LocationTable table = new LocationTable(_db); - String whereClause = "order by lid"; - List recordList = null; - - _lidToRiverBasinMap.clear(); - try { - recordList = (List) table.select(whereClause); - for (LocationRecord record : recordList) { - _lidToRiverBasinMap.put(record.getLid(), record.getRb()); - } - } catch (SQLException e) { - - } - - } - - private void setRiverBasinData(PrecipMonitorJTableRowData rowData) { - String riverBasin = _lidToRiverBasinMap.get(rowData.getLid()); - - rowData.setRiverBasin(riverBasin); - - return; - } - - public boolean isPrecipLocation(String lid) { - boolean result = false; - - if (_precipLidSet != null) { - if (_precipLidSet.contains(lid)) { - result = true; - } - } - return result; - } - - public void alterPrecipMonitorRowDataListBasedOnMissingPrecipFilter() { - - _missingPrecipMonitorRowDataList.clear(); - - // _fullPrecipMonitorRowDataList = _precipMonitorRowDataList; - - if (!_menuSettings.shouldShowMissingPrecip()) // show missing precip is - // set to false(ie., skip - // missing precip) - { - System.out.println("Show missing is false"); - List finalPrecipMonitorRowDataList = new ArrayList(); - - for (PrecipMonitorJTableRowData precipMonitorRowData : _precipMonitorRowDataList) { - PrecipData precipData = precipMonitorRowData.getPrecipData(); - - // precip is available add this lid - if (precipData.isDataAvailable()) { - finalPrecipMonitorRowDataList.add(precipMonitorRowData); - } else { - _missingPrecipMonitorRowDataList.add(precipMonitorRowData); - } - } - _precipMonitorRowDataList = finalPrecipMonitorRowDataList; - finalPrecipMonitorRowDataList = null; - Runtime.getRuntime().gc(); - } - } - - public void createPrecipMonitorRowDataList() { - - CodeTimer methodTimer = new CodeTimer(); - methodTimer.start(); - CodeTimer timer = new CodeTimer(); - - String header = "PrecipMonitorDataManager.createPrecipMonitorRowDataList(): "; - - _logger.log(header + " Memory Info before creating rowdata list:" - + printMemoryInfo()); - Runtime.getRuntime().gc(); - - timer.start(); - _precipMonitorRowDataList = readPrecipLocationInfo(); - timer.stop(header + "readPrecipLocationInfo took: "); - - if (_precipMonitorRowDataList != null) { - timer.start(); - readCurrentRiverMonTableData(); - timer.stop(header + "readCurrentRiverMonTableData took: "); - - _logger.log(header + " 1:" + printMemoryInfo()); - Runtime.getRuntime().gc(); - - timer.start(); - _precipDataManager.readPrecipData(_precipMonitorRowDataList, - "PRECIP"); - timer.stop(header + "readPrecipData took: "); - - Runtime.getRuntime().gc(); - _logger.log(header + " 2:" + printMemoryInfo()); - _derivedColumnsList = _derivedColumnsFileManager - .getDerivedColumns(); - - timer.start(); - - for (PrecipMonitorJTableRowData precipMonitorRowData : _precipMonitorRowDataList) { - String groupId = _riverMonLocGroupDataManager - .getGroupId(precipMonitorRowData.getLid()); - String groupName = _riverMonLocGroupDataManager - .getGroupName(groupId); - int groupOrdinal = _riverMonLocGroupDataManager - .getGroupOrdinal(groupId); - String hsa = _riverMonLocGroupDataManager.getHsa(groupId); - int locationOrdinal = _riverMonLocGroupDataManager - .getLocationOrdinal(precipMonitorRowData.getLid()); - - // precipMonitorRowData.setLid(precipMonitorRowData.getLid()); - precipMonitorRowData.setLocationOrdinal(locationOrdinal); - precipMonitorRowData.setHsa(hsa); - precipMonitorRowData.setGroupName(groupName); - precipMonitorRowData.setGroupId(groupId); - precipMonitorRowData.setGroupOrdinal(groupOrdinal); - - /* - * _logger.log(precipMonitorRowData.getLid() + "|" + - * precipMonitorRowData.getName() + "|" + - * precipMonitorRowData.getGroupId() + "|" + - * precipMonitorRowData.getGroupName() + "|" + - * precipMonitorRowData.getLocationOrdinal() + "|" + - * precipMonitorRowData.getGroupOrdinal() ); - */ - - precipMonitorRowData.addAllCellsToMap(); - - getDerivedColumnsInfo(precipMonitorRowData); - - precipMonitorRowData.addDerivedDataToCellMap(); - - } - - int count = _precipMonitorRowDataList.size(); - - timer.stop(header + " for loop with " + count - + " iterations took: "); - - _logger.log(header - + "Before missing precip filter is applied, alllocationinfo list size:" - + _precipMonitorRowDataList.size()); - - // timer.start(); - // alterPrecipMonitorRowDataListBasedOnMissingPrecipFilter(); - // timer.stop(header + - // "alterPrecipMonitorRowDataListBasedOnMissingPrecipFilter took: "); - - _logger.log(header - + "After missing precip filter is applied, alllocationinfo list size:" - + _precipMonitorRowDataList.size()); - } - Runtime.getRuntime().gc(); - _logger.log(header + " Memory Info after creating rowdata list:" - + printMemoryInfo()); - - methodTimer.stop(header + " the whole method took: "); - - } - - // --------------------------------------------------------------------------------------------------- - - public String printMemoryInfo() { - String str = "Free:" + Runtime.getRuntime().freeMemory() + " Max:" - + Runtime.getRuntime().maxMemory() + " total:" - + Runtime.getRuntime().totalMemory(); - return str; - } - - private double roundTo2DecimalPlaces(double number) { - double result = DbTable.getNullDouble(); - if (number != DbTable.getNullDouble()) - result = MathHelper.roundToNDecimalPlaces(number, 2); - - return result; - } - - // --------------------------------------------------------------------------------------------------- - - private void initializeBSF() throws Exception { - _bsfManager = new BSFManager(); - BSFManager.registerScriptingEngine("beanshell", - "bsh.util.BeanShellBSFEngine", null); - _beanShellEngine = _bsfManager.loadScriptingEngine("beanshell"); - } - - // --------------------------------------------------------------------------------------------------- - - protected void getDerivedColumnsInfo( - PrecipMonitorJTableRowData precipMonitorRowData) { - if (_derivedColumnsList != null) { - try { - _bsfManager.declareBean("row", precipMonitorRowData, - PrecipMonitorJTableRowData.class); - _bsfManager.declareBean("precip", - precipMonitorRowData.getPrecipData(), PrecipData.class); - - for (int j = _derivedColumnsList.size() - 1; j >= 0; j--) { - DerivedColumn derivedColumnDesc = (DerivedColumn) _derivedColumnsList - .get(j); - String equationForCellValue = ((String) derivedColumnDesc - .getEquationForCellValue()); - Object returnValueForCell = _beanShellEngine.eval( - "rowtest", 1, 1, equationForCellValue); - if (derivedColumnDesc.getReturnType().equalsIgnoreCase( - "double")) { - double value = roundTo2DecimalPlaces(Double - .parseDouble(returnValueForCell.toString())); - derivedColumnDesc.setvalue(Double.valueOf(value)); - } else - derivedColumnDesc.setvalue(returnValueForCell); - - String equationForCellColor = ((String) derivedColumnDesc - .getEquationForCellColor()); - Object returnColorForCell = _beanShellEngine.eval( - "rowtest", 1, 1, equationForCellColor); - if (returnColorForCell != null) - derivedColumnDesc - .setCellBackgroundColor(returnColorForCell - .toString()); - } - _bsfManager.undeclareBean("row"); - _bsfManager.undeclareBean("precip"); - } catch (Exception e) { - e.printStackTrace(); - } - } - precipMonitorRowData.setDerivedColumnsDetailsList(_derivedColumnsList); - } - - // --------------------------------------------------------------------------------------------------- - public List createStringArrayListOfFilterItems() { - String header = "PrecipMonitorDataManager.createStringArrayListOfFilterItems(): "; - - List locationIdList = getFullListOfLocationIds(); - - List listOfNodePathStringArray = _riverMonLocGroupDataManager - .createStringArrayListOfFilterItems(locationIdList); - - return listOfNodePathStringArray; - } - - // --------------------------------------------------------------------------------------------------- - - public String getDefaultHsa() { - return _defaultHsa; - } - - protected void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public Map getLidDescDetails() { - if (_lidDescDetailsMap == null) { - LocRiverMonView riverMonView = new LocRiverMonView(_db); - try { - List riverMonViewList = (List) riverMonView.select(""); - if (riverMonViewList != null) { - if (riverMonViewList.size() > 0) { - _lidDescDetailsMap = new HashMap(); - for (int i = 0; i < riverMonViewList.size(); i++) { - LocRiverMonRecord record = (LocRiverMonRecord) riverMonViewList - .get(i); - String name = record.getName(); - if (name != null) { - if (name.length() > 0) { - if (name.length() > 50) { - name = name.substring(0, 50); - } - } - } - String desc = name + ";" + record.getState() + ";" - + record.getCounty(); - _lidDescDetailsMap.put(record.getLid(), desc); - } - } - } - } catch (SQLException e) { - logSQLException(e); - } - } - return _lidDescDetailsMap; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipMonitorJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipMonitorJTableRowData.java deleted file mode 100755 index be7876380f..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipMonitorJTableRowData.java +++ /dev/null @@ -1,821 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTable; -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.MonitorCell; -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.CellType; - -public class PrecipMonitorJTableRowData extends AbstractJTableRowData -{ - private int _defaultDecimalPoints = 2; - - private static Map _derivedReturnTypeToCellTypeMap = new HashMap(); - - private String _groupName; - private String _lid; - private String _name; - private String _county; - private String _state; - private String _hsa; - private String _riverBasin; - private String _groupId; - private int _groupOrdinal; - private int _locationOrdinal; - private double _obsFcstMax; - private SessionLogger _logger; - - protected PrecipMonitorDataManager _precipMonitorDataManager; - - private String _toolTipTextForPrecipThreatSummary; - private List _derivedColumnsDetailsList; - - private PrecipData _precipData; - private PrecipColumnDataSettings _precipSettings; - - static - { - _derivedReturnTypeToCellTypeMap.put("boolean", CellType.BOOLEAN); - _derivedReturnTypeToCellTypeMap.put("double", CellType.DOUBLE); - _derivedReturnTypeToCellTypeMap.put("float", CellType.FLOAT); - _derivedReturnTypeToCellTypeMap.put("long", CellType.LONG); - _derivedReturnTypeToCellTypeMap.put("int", CellType.INTEGER); - _derivedReturnTypeToCellTypeMap.put("string", CellType.STRING); - - } - - public PrecipMonitorJTableRowData(String missingRepresentation, PrecipMonitorDataManager precipMonitorDataManager, - SessionLogger logger) - { - setMissingRepresentation(missingRepresentation); - _logger = logger; - _precipMonitorDataManager = precipMonitorDataManager; - } - - public String getLid() - { - return _lid; - } - - public void setLid(String lid) - { - this._lid = lid ; - } - - public String getName() - { - return _name; - } - - public void setName(String name) - { - this._name = name ; - } - - public String getCounty() - { - return _county; - } - - public void setCounty(String county) - { - this._county = county ; - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - this._state = state ; - } - - public String getHsa() - { - return _hsa; - } - - public void setHsa(String hsa) - { - this._hsa = hsa ; - } - - public String getGroupName() - { - return _groupName; - } - - public void setGroupName(String groupName) - { - this._groupName = groupName ; - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - this._groupId = groupId ; - } - - public int getGroupOrdinal() - { - return _groupOrdinal; - } - - public void setGroupOrdinal(int groupOrdinal) - { - this._groupOrdinal = groupOrdinal ; - } - - public int getLocationOrdinal() - { - return _locationOrdinal; - } - - public void setLocationOrdinal(int locationOrdinal) - { - this._locationOrdinal = locationOrdinal ; - } - - public void setObsFcstMax(double obsFcstMax) - { - this._obsFcstMax = obsFcstMax; - } - - public double getObsFcstMax() - { - return _obsFcstMax; - } - - public PrecipData getPrecipData() - { - return _precipData; - } - - public void setPrecipData(PrecipData precipData) - { - _precipData = precipData; - } - - public void setDerivedColumnsDetailsList(List list) - { - _derivedColumnsDetailsList = list; - } - - public List getDerivedColumnsDetailsList() - { - return _derivedColumnsDetailsList; - } - - - public String getStringValue(long value, long missingValue) - { - String result = super.getStringValue(value, missingValue); - if(result != super.getMissingRepresentation()) - { - String tempStr = result.substring(5, result.length()-3); - tempStr = tempStr.replace('-','/'); - tempStr = tempStr.replace(' ', '-'); - result = tempStr; - } - return result; - } - - public String getToolTipTextForPrecipThreatSummary() - { - return _toolTipTextForPrecipThreatSummary; - } - - public void setToolTipTextForPrecipThreatSummary(String toolTipText) - { - _toolTipTextForPrecipThreatSummary = toolTipText; - } - - public void resetCellMap() - { - super.resetCellMap(); - } - - public void addAllCellsToMap() - { - ThreatLevel defaultThreatLevel = ThreatLevel.NO_THREAT; - String header = "RiverMonitorJTableRowData2.addAllCellsToMap(): "; - - String dateTimeFormatString = "MM/dd - HH:mm"; - - _precipSettings = _precipMonitorDataManager.getPrecipSettings(); - - //static data - - addToCellMap(LocationInfoColumns.GROUP_NAME, CellType.STRING, getGroupName() ); - addToCellMap(LocationInfoColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(LocationInfoColumns.GROUP_ORDINAL, CellType.INTEGER, getGroupOrdinal()); - - addToCellMap(LocationInfoColumns.LOCATION_ID, CellType.STRING, getLid() ); - addToCellMap(LocationInfoColumns.LOCATION_NAME, CellType.STRING, getName() ); - addToCellMap(LocationInfoColumns.LOCATION_ORDINAL, CellType.INTEGER, getLocationOrdinal()); - - addToCellMap(LocationInfoColumns.COUNTY, CellType.STRING, getCounty() ); - addToCellMap(LocationInfoColumns.STATE, CellType.STRING, getState() ); - - addToCellMap(LocationInfoColumns.HSA, CellType.STRING, getHsa() ); - - addToCellMap(LocationInfoColumns.RIVER_BASIN, CellType.STRING, getRiverBasin()); - - addToCellMap(PrecipColumns.LATEST_PRECIP_PARAM_CODE, CellType.STRING, getPrecipData().getLatestPrecipParamCodeString() ); - - addToCellMap(PrecipColumns.LATEST_30MIN, CellType.DOUBLE, getPrecipData().getLatestPrecip30Min()); - addToCellMap(PrecipColumns.LATEST_1HR, CellType.DOUBLE, getPrecipData().getLatestPrecip1Hr(), getThreatLevelForPrecipColumn("LATEST", 1)); - addToCellMap(PrecipColumns.LATEST_3HR, CellType.DOUBLE, getPrecipData().getLatestPrecip3Hr(), getThreatLevelForPrecipColumn("LATEST", 3)); - addToCellMap(PrecipColumns.LATEST_6HR, CellType.DOUBLE, getPrecipData().getLatestPrecip6Hr(), getThreatLevelForPrecipColumn("LATEST", 6)); - addToCellMap(PrecipColumns.LATEST_12HR, CellType.DOUBLE, getPrecipData().getLatestPrecip12Hr()); - addToCellMap(PrecipColumns.LATEST_18HR, CellType.DOUBLE, getPrecipData().getLatestPrecip18Hr()); - addToCellMap(PrecipColumns.LATEST_24HR, CellType.DOUBLE, getPrecipData().getLatestPrecip24Hr()); - - addToCellMap(PrecipColumns.TOH_PRECIP_1HR_PARAM_CODE, CellType.STRING, getPrecipData().getTohPrecip1HrParamCodeString() ); - addToCellMap(PrecipColumns.TOH_PRECIP_1HR, CellType.DOUBLE, getPrecipData().getTohPrecip1Hr(), getThreatLevelForPrecipColumn("TOH", 1)); - - addToCellMap(PrecipColumns.FFG_1HR, CellType.DOUBLE, getPrecipData().getFFG1Hr()); - addToCellMap(PrecipColumns.FFG_3HR, CellType.DOUBLE, getPrecipData().getFFG3Hr()); - addToCellMap(PrecipColumns.FFG_6HR, CellType.DOUBLE, getPrecipData().getFFG6Hr()); - - addToCellMap(PrecipColumns.DIFF_1HR, CellType.DOUBLE, getPrecipData().getDiff1Hr(), getThreatLevelForPrecipColumn("DIFF", 1)); - addToCellMap(PrecipColumns.DIFF_3HR, CellType.DOUBLE, getPrecipData().getDiff3Hr(), getThreatLevelForPrecipColumn("DIFF", 3)); - addToCellMap(PrecipColumns.DIFF_6HR, CellType.DOUBLE, getPrecipData().getDiff6Hr(), getThreatLevelForPrecipColumn("DIFF", 6)); - - addToCellMap(PrecipColumns.RATIO_1HR, CellType.INTEGER, getPrecipData().getRatio1Hr(), getThreatLevelForPrecipColumn("RATIO", 1)); - addToCellMap(PrecipColumns.RATIO_3HR, CellType.INTEGER, getPrecipData().getRatio3Hr(), getThreatLevelForPrecipColumn("RATIO", 3)); - addToCellMap(PrecipColumns.RATIO_6HR, CellType.INTEGER, getPrecipData().getRatio6Hr(), getThreatLevelForPrecipColumn("RATIO", 6)); - - ThreatLevel threatLevel = getThreatLevelForPrecipThreatSummary(); - addToCellMap(PrecipColumns.PRECIP_THREAT, CellType.EXTENSION, - getPrecipThreatSummary(), threatLevel, - getMissingRepresentation()); - - } //end addAllCellsToMap - - // ----------------------------------------------------------------------------------- - - public double round(double value, int decimalPlacesToMaintain) - { - return MathHelper.roundToNDecimalPlaces(value, decimalPlacesToMaintain); - } - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value) - { - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, getMissingRepresentation()); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, Color cellBackgroundColor) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, cellBackgroundColor, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } -// ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, missingRepresentation, _defaultDecimalPoints); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel,Color cellBackgroundColor, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, cellBackgroundColor, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - String dateFormatString) - { - - MonitorCell cell = new MonitorCell (columnName, cellType, value, threatLevel, - missingRepresentation, dateFormatString); - - - // addToCellMap(cell); - addCell(cell); - - - return cell; - } - - // ----------------------------------------------------------------------------------- - - protected void addDerivedDataToCellMap() - { - // add all derived columns as well - List derivedColumnsDetailsList = this.getDerivedColumnsDetailsList(); - for(int i=0 ; i < derivedColumnsDetailsList.size(); i++) - { - DerivedColumn desc1 = (DerivedColumn) derivedColumnsDetailsList.get(i); - - CellType cellType = getCellTypeFromReturnType(desc1.getReturnType()); - - addToCellMap(desc1.getColumnName(), cellType, desc1.getValue(), desc1.getCellBackgroundColor()); - } - } - // ----------------------------------------------------------------------------------- - - private CellType getCellTypeFromReturnType(String derivedColumnReturnType) - { - CellType cellType = null; - - cellType = (CellType) _derivedReturnTypeToCellTypeMap.get(derivedColumnReturnType.toLowerCase()); - - return cellType; - } - - - public Color getCellBackgroundColor(String columnName) - { - Color color = Color.white; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellBackgroundColor(); - } - - return color; - } - - // ----------------------------------------------------------------------------------- - - public Color getCellForegroundColor(String columnName) - { - Color color = Color.black; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellForegroundColor(); - } - return color; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getPrecipMonitorThreatLevel() - { - //Find the max threat levels for all cells in this row - ThreatLevel maxCellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = new ArrayList( getCellMap().values()); - maxCellThreatLevel = getMaxRowThreatLevel(cellList); - - ThreatLevel rowThreatLevel = maxCellThreatLevel; - - //If the rowThreatLevel == missing, we want to make sure that ALL of the important columns have missing data. - //If there is any data in these columns, then we want to use NO_THREAT - if (rowThreatLevel == ThreatLevel.MISSING_DATA) - { - if (_precipData.isDataAvailable()) - { - rowThreatLevel = ThreatLevel.NO_THREAT; - } - } - - return rowThreatLevel; - } - // helper methods - - // ----------------------------------------------------------------------------------- - public Color getCriticalColorForThisRow() - { - Color color = Color.WHITE; - ThreatLevel level = getPrecipMonitorThreatLevel(); - if(level == ThreatLevel.ALERT) - { - color = Color.RED; - } - else if(level == ThreatLevel.CAUTION) - { - color = Color.YELLOW; - } - else if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - color = Color.GRAY; - } - - return color; - } - - // ----------------------------------------------------------------------------------- - public ThreatLevel getThreatLevelForPrecipThreatSummary() - { - ThreatLevel level = getPrecipThreatLevelForPrecipThreatSummary(); - - //Threat cell should be color red/yellow/white. So skip threat aged / missing threat level - if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - - return level; - } - -// ----------------------------------------------------------------------------------- - public ThreatLevel getMaxRowThreatLevel(List cellList) - { - //this method assumes that the threat column has not yet been added to the cell map, when this - // method is invoked - ThreatLevel level = ThreatLevel.NO_THREAT; - ThreatLevel maxLevel = ThreatLevel.ALERT; - - //make sure the threat cell's threat level does not get used to calculate row's threat level, so clear it to zero - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - //iterate through each cell, and set the level to the max threat level found - for (int i = 0; i < cellList.size(); i++) - { - - MonitorCell cell = (MonitorCell) cellList.get(i); - - if (cell == null) - { - continue; - } - else - { - cellThreatLevel = cell.getThreatLevel(); - - if (cellThreatLevel.isGreater(level)) - { - level = cellThreatLevel; - if (level == maxLevel) - { - break; //quit looking, because we have determined it is maxed out - } - } - } - } - return level; - } - // ----------------------------------------------------------------------------------- - - - public List getPrecipCells() - { - List cellList = new ArrayList(); - - addCell(cellList, PrecipColumns.LATEST_30MIN); - addCell(cellList, PrecipColumns.LATEST_1HR); - addCell(cellList, PrecipColumns.LATEST_3HR ); - addCell(cellList, PrecipColumns.LATEST_6HR ); - - addCell(cellList, PrecipColumns.TOH_PRECIP_1HR ); - - addCell(cellList, PrecipColumns.DIFF_1HR ); - addCell(cellList, PrecipColumns.DIFF_3HR ); - addCell(cellList, PrecipColumns.DIFF_6HR ); - - addCell(cellList, PrecipColumns.RATIO_1HR ); - addCell(cellList, PrecipColumns.RATIO_3HR ); - addCell(cellList, PrecipColumns.RATIO_6HR ); - - return cellList; - } - - // ----------------------------------------------------------------------------------- - - private void addCell(List cellList, String columnName ) - { - MonitorCell cell = null; - - cell = (MonitorCell) getCellMap().get(columnName); - if(cell != null) - { - cellList.add(cell); - } - - return; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getPrecipThreatLevelForPrecipThreatSummary() - { - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = getPrecipCells(); - cellThreatLevel = getMaxRowThreatLevel(cellList); - - return cellThreatLevel; - } - //-------------------------------------------------------------------------------------- - /* - * Returns true if the data is aged, by checking the time with earliestAcceptableTime - */ - protected boolean isDataAged(long time, long earliestAcceptableTime) - { - boolean result = false; - - if (time < earliestAcceptableTime) - { - result = true; - } - - return result; - } - - private ThreatLevel getPrecipThreatLevel(double value, double alert, double caution) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(! DbTable.isNull(value)) - { - if(value >= alert) - level = ThreatLevel.ALERT; - else if(value >= caution) - level = ThreatLevel.CAUTION; - } - else //value isNull() - { - level = ThreatLevel.MISSING_DATA; - } - - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipValueThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings, String type) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double missing = DbTable.getNullDouble(); - double value; - switch(hour) - { - - case 1: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip1Hr(); - else - value = _precipData.getTohPrecip1Hr(); - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert1Hr(), precipSettings.getPrecipCaution1Hr()); - break; - - case 3: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip3Hr(); - else - // value = _precipData.getTohPrecip3Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert3Hr(), precipSettings.getPrecipCaution3Hr()); - break; - case 6: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip6Hr(); - else - //value = _precipData.getTohPrecip6Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert6Hr(), precipSettings.getPrecipCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipRatioThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - int value; - switch(hour) - { - - case 1: - value = _precipData.getRatio1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert1Hr(), precipSettings.getRatioCaution1Hr()); - break; - case 3: - value = _precipData.getRatio3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert3Hr(), precipSettings.getRatioCaution6Hr()); - break; - case 6: - value = _precipData.getRatio6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert6Hr(), precipSettings.getRatioCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipDiffThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double value; - - switch(hour) - { - case 1: - value = _precipData.getDiff1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert1Hr(), precipSettings.getDiffCaution1Hr()); - break; - case 3: - value = _precipData.getDiff3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert3Hr(), precipSettings.getDiffCaution3Hr()); - break; - case 6: - value = _precipData.getDiff6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert6Hr(), precipSettings.getDiffCaution6Hr()); - break; - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForPrecipColumn(String type, int hour) - { - - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(type.compareTo("LATEST") == 0) // LATEST precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _precipSettings, "LATEST"); - } - else if(type.compareTo("TOH") == 0) // toh precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _precipSettings, "TOH"); - } - else if(type.compareTo("RATIO") == 0) - { - level = getPrecipRatioThreatLevelForHrMentioned(hour, _precipSettings); - } - else //type is DIFF - { - level = getPrecipDiffThreatLevelForHrMentioned(hour, _precipSettings); - } - return level; - } - - -// ------------------------------------------------------------------------------------- - - public ThreatLevel getCellThreatLevelForColumn(String columnName) - { - // String header = "PrecipMonitorJTableRowData.getCellThreatLevelForColumn(): "; - ThreatLevel level; - - MonitorCell cell = (MonitorCell) getCellMap().get(columnName); - - // System.out.println(header + "columnName = " + columnName); - - level = cell.getThreatLevel(); - - return level; - } - -// ------------------------------------------------------------------------------------- - - - public String getPrecipThreatSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - - ThreatLevel level; - ThreatLevel level1Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_1HR); - ThreatLevel level3Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_3HR); - ThreatLevel level6Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("L"); - toolTipStringBuffer.append("L: Latest Precip Exceeded the threshold
"); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_1HR); - // level3Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_3HR); - // level6Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_6HR); - if ( - ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) - /* || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) - */ - ) - { - summaryStringBuffer = summaryStringBuffer.append("T"); - toolTipStringBuffer.append("T: Top Of The Hour Precip Exceeded the threshold
"); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("D"); - toolTipStringBuffer.append("D: Latest Precip - FFG Difference Exceeded the threshold
"); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("R"); - toolTipStringBuffer.append("R: Latest Precip / FFG Ratio Exceeded the threshold
"); - } - - summary = summaryStringBuffer.toString(); - _toolTipTextForPrecipThreatSummary = toolTipStringBuffer.toString(); - return summary; - } -// ------------------------------------------------------------------------------------- - - public void setRiverBasin(String riverBasin) - { - _riverBasin = riverBasin; - } - - public String getRiverBasin() - { - return _riverBasin; - } - -} //end class - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipThresholdDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipThresholdDialog.java deleted file mode 100755 index d980149525..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/PrecipThresholdDialog.java +++ /dev/null @@ -1,392 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTable; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.WindowResizingManager; - -public class PrecipThresholdDialog extends JDialog -{ - private JSpinner _precipAlert1HrSpinBox ; - private JSpinner _precipAlert3HrSpinBox ; - private JSpinner _precipAlert6HrSpinBox ; - - private JSpinner _precipCaution1HrSpinBox ; - private JSpinner _precipCaution3HrSpinBox ; - private JSpinner _precipCaution6HrSpinBox ; - - private JSpinner _ratioAlert1HrSpinBox ; - private JSpinner _ratioAlert3HrSpinBox ; - private JSpinner _ratioAlert6HrSpinBox ; - - private JSpinner _ratioCaution1HrSpinBox ; - private JSpinner _ratioCaution3HrSpinBox ; - private JSpinner _ratioCaution6HrSpinBox ; - - private JSpinner _diffAlert1HrSpinBox ; - private JSpinner _diffAlert3HrSpinBox ; - private JSpinner _diffAlert6HrSpinBox ; - - private JSpinner _diffCaution1HrSpinBox ; - private JSpinner _diffCaution3HrSpinBox ; - private JSpinner _diffCaution6HrSpinBox ; - - private JButton _applyButton; - private JButton _closeButton; - - private SessionLogger _logger; - - private PrecipColumnDataSettings _prevMenuSettings = null; - private PrecipColumnDataSettings _savedMenuSettings = null; - - public PrecipThresholdDialog( JFrame mainFrame, PrecipColumnDataSettings menuSettings, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - _prevMenuSettings = menuSettings; - createPrecipSettingsDialog(); - } - - public void setMenuSettingsForDialog(PrecipColumnDataSettings menuSettings) - { - _prevMenuSettings = menuSettings; - createPrecipSettingsDialog(); - } - - public PrecipColumnDataSettings showPrecipThresholdDialog() - { - _savedMenuSettings = null; - this.setVisible(true); - return _savedMenuSettings; - } - - public void createPrecipSettingsDialog() - { - JPanel precipPanel = new JPanel(new GridBagLayout()); - TitledBorder precipTitledBorder = BorderFactory.createTitledBorder("Precip Threshold"); - precipPanel.setBorder(precipTitledBorder); - precipPanel.setToolTipText("Applied to 1hr, 3hr, 6hr Latest Precip and TOH Precip"); - - if(_prevMenuSettings == null) - { - _prevMenuSettings = new PrecipColumnDataSettings(); - } - - JLabel precip1HrLabel = new JLabel("1 Hr"); - precip1HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel precip3HrLabel = new JLabel("3 Hr"); - precip3HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel precip6HrLabel = new JLabel("6 Hr"); - precip6HrLabel.setPreferredSize(new Dimension(40, 30)); - - JPanel precipLabelPanel = new JPanel(); - precipLabelPanel.setPreferredSize(new Dimension(150, 40)); - precipLabelPanel.add(precip1HrLabel); - precipLabelPanel.add(precip3HrLabel); - precipLabelPanel.add(precip6HrLabel); - - //initial value, min value, max value, incr value - _precipAlert1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipAlert1Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_1HR, 0.01)); - _precipAlert1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipAlert3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipAlert3Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_3HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_3HR, 0.01)); - _precipAlert3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipAlert6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipAlert6Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_6HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_6HR, 0.01)); - _precipAlert6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel precipAlertPanel = new JPanel(); - precipAlertPanel.setPreferredSize(new Dimension(150, 40)); - precipAlertPanel.add(_precipAlert1HrSpinBox); - precipAlertPanel.add(_precipAlert3HrSpinBox); - precipAlertPanel.add(_precipAlert6HrSpinBox); - - _precipCaution1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipCaution1Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_1HR, 0.01)); - _precipCaution1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipCaution3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipCaution3Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_3HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_3HR, 0.01)); - _precipCaution3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipCaution6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipCaution6Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_6HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_6HR, 0.01)); - _precipCaution6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel precipCautionPanel = new JPanel(); - precipCautionPanel.setPreferredSize(new Dimension(150, 40)); - precipCautionPanel.add(_precipCaution1HrSpinBox); - precipCautionPanel.add(_precipCaution3HrSpinBox); - precipCautionPanel.add(_precipCaution6HrSpinBox); - - JPanel precipDummyPanel = new JPanel(); - precipDummyPanel.setPreferredSize(new Dimension(150, 10)); - ComponentHelper.addPanelComponent(precipPanel, precipLabelPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(precipPanel, precipAlertPanel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(precipPanel, precipDummyPanel, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(precipPanel, precipCautionPanel, 0, 3, 1, 1, 1); - - JPanel ratioPanel = new JPanel(new GridBagLayout()); - TitledBorder ratioTitledBorder = BorderFactory.createTitledBorder("Ratio(%) Threshold"); - ratioPanel.setBorder(ratioTitledBorder); - ratioPanel.setToolTipText("Applied to ((Latest Precip / FFG) * 100) columns"); - - JLabel ratio1HrLabel = new JLabel("1 Hr"); - ratio1HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel ratio3HrLabel = new JLabel("3 Hr"); - ratio3HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel ratio6HrLabel = new JLabel("6 Hr"); - ratio6HrLabel.setPreferredSize(new Dimension(40, 30)); - - JPanel ratioLabelPanel = new JPanel(); - ratioLabelPanel.setPreferredSize(new Dimension(150, 40)); - ratioLabelPanel.add(ratio1HrLabel); - ratioLabelPanel.add(ratio3HrLabel); - ratioLabelPanel.add(ratio6HrLabel); - - // initial value, min value, max value, incr value - _ratioAlert1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioAlert1Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioAlert1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioAlert3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioAlert3Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioAlert3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioAlert6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioAlert6Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioAlert6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel ratioAlertPanel = new JPanel(); - ratioAlertPanel.setPreferredSize(new Dimension(150, 40)); - ratioAlertPanel.add(_ratioAlert1HrSpinBox); - ratioAlertPanel.add(_ratioAlert3HrSpinBox); - ratioAlertPanel.add(_ratioAlert6HrSpinBox); - - // initial value, min value, max value, incr value - _ratioCaution1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioCaution1Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioCaution1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioCaution3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioCaution3Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioCaution3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioCaution6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioCaution6Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioCaution6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel ratioCautionPanel = new JPanel(); - ratioCautionPanel.setPreferredSize(new Dimension(150, 40)); - ratioCautionPanel.add(_ratioCaution1HrSpinBox); - ratioCautionPanel.add(_ratioCaution3HrSpinBox); - ratioCautionPanel.add(_ratioCaution6HrSpinBox); - - JPanel ratioDummyPanel = new JPanel(); - ratioDummyPanel.setPreferredSize(new Dimension(150, 10)); - ComponentHelper.addPanelComponent(ratioPanel, ratioLabelPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(ratioPanel, ratioAlertPanel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(ratioPanel, ratioDummyPanel, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(ratioPanel, ratioCautionPanel, 0, 3, 1, 1, 1); - - JPanel diffPanel = new JPanel(new GridBagLayout()); - TitledBorder diffTitledBorder = BorderFactory.createTitledBorder("Diff Threshold"); - diffPanel.setBorder(diffTitledBorder); - diffPanel.setToolTipText("Applied to (Latest Precip - FFG) columns"); - - JLabel diff1HrLabel = new JLabel("1 Hr"); - diff1HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel diff3HrLabel = new JLabel("3 Hr"); - diff3HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel diff6HrLabel = new JLabel("6 Hr"); - diff6HrLabel.setPreferredSize(new Dimension(40, 30)); - - JPanel diffLabelPanel = new JPanel(); - diffLabelPanel.setPreferredSize(new Dimension(150, 40)); - diffLabelPanel.add(diff1HrLabel); - diffLabelPanel.add(diff3HrLabel); - diffLabelPanel.add(diff6HrLabel); - - // initial value, min value, max value, incr value - _diffAlert1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffAlert1Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffAlert1HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffAlert3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffAlert3Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffAlert3HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffAlert6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffAlert6Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffAlert6HrSpinBox.setPreferredSize(new Dimension(55, 30)); - - JPanel diffAlertPanel = new JPanel(); - diffAlertPanel.setPreferredSize(new Dimension(180, 40)); - diffAlertPanel.add(_diffAlert1HrSpinBox); - diffAlertPanel.add(_diffAlert3HrSpinBox); - diffAlertPanel.add(_diffAlert6HrSpinBox); - - _diffCaution1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffCaution1Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffCaution1HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffCaution3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffCaution3Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffCaution3HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffCaution6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffCaution6Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffCaution6HrSpinBox.setPreferredSize(new Dimension(55, 30)); - - JPanel diffCautionPanel = new JPanel(); - diffCautionPanel.setPreferredSize(new Dimension(180, 40)); - diffCautionPanel.add(_diffCaution1HrSpinBox); - diffCautionPanel.add(_diffCaution3HrSpinBox); - diffCautionPanel.add(_diffCaution6HrSpinBox); - - JPanel diffDummyPanel = new JPanel(); - diffDummyPanel.setPreferredSize(new Dimension(180, 10)); - ComponentHelper.addPanelComponent(diffPanel, diffLabelPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(diffPanel, diffAlertPanel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(diffPanel, diffDummyPanel, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(diffPanel, diffCautionPanel, 0, 3, 1, 1, 1); - - JLabel alertLabel = new JLabel("Alert :"); - alertLabel.setOpaque(true); - alertLabel.setBackground(Color.RED); - JLabel cautionLabel = new JLabel("Caution :"); - cautionLabel.setOpaque(true); - cautionLabel.setBackground(Color.YELLOW); - - JPanel alertCautionPanel = new JPanel(new GridBagLayout()); - - JPanel dummyPanel1 = new JPanel(); - dummyPanel1.setPreferredSize(new Dimension(60, 40)); - - alertLabel.setPreferredSize(new Dimension(60, 40)); - - JPanel dummyPanel2 = new JPanel(); - dummyPanel2.setPreferredSize(new Dimension(60, 10)); - - cautionLabel.setPreferredSize(new Dimension(60, 40)); - - ComponentHelper.addPanelComponent(alertCautionPanel, dummyPanel1, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(alertCautionPanel, alertLabel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(alertCautionPanel, dummyPanel2, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(alertCautionPanel, cautionLabel, 0, 3, 1, 1, 1); - - JPanel thresholdPanel = new JPanel(new GridBagLayout()); - ComponentHelper.addPanelComponent(thresholdPanel, alertCautionPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(thresholdPanel, precipPanel, 1, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(thresholdPanel, ratioPanel, 2, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(thresholdPanel, diffPanel, 3, 0, 1, 1, 1); - - JPanel buttonPanel = new JPanel(new GridBagLayout()); - - JPanel dummyPanel3 = new JPanel(); - dummyPanel3.setPreferredSize(new Dimension(20,20)); - - _closeButton = new JButton("Close"); - _applyButton = new JButton ("Apply"); - _applyButton.addActionListener(new ApplyMenuSettingsListener()); - _closeButton.addActionListener(new ClosePrecipSettingsDialogListener()); - - ComponentHelper.addPanelComponent(buttonPanel, _applyButton, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(buttonPanel, dummyPanel3, 1, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(buttonPanel, _closeButton, 2, 0, 1, 1, 1); - - JPanel dummyPanel5 = new JPanel(); - dummyPanel5.setPreferredSize(new Dimension(200,40)); - - JPanel outerPanel = new JPanel(new GridBagLayout()); - ComponentHelper.addPanelComponent(outerPanel, thresholdPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(outerPanel, dummyPanel5, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(outerPanel, buttonPanel, 0, 2, 1, 1, 1); - - this.getContentPane().add(outerPanel); - this.setLocation(25, 25); - Dimension dim = new Dimension(600,450); - new WindowResizingManager(this, dim, dim); - - this.pack(); - this.setTitle("Precip Alert/Caution Threshold Values"); - } - - private void closePrecipSettingsDialog() - { - this.setVisible(false); - this.dispose(); - } - -// --------------------------------------------------------------------------------------------------- - - private double roundTo2DecimalPlaces(double number) - { - double result = DbTable.getNullDouble(); - if (number != DbTable.getNullDouble()) - result = MathHelper.roundToNDecimalPlaces(number, 2); - - return result; - } - - private PrecipColumnDataSettings getPrecipSettingsFromDialog() - { - PrecipColumnDataSettings menuSettings = new PrecipColumnDataSettings(); - - menuSettings.setPrecipAlert1Hr(roundTo2DecimalPlaces((Double)_precipAlert1HrSpinBox.getValue())); - menuSettings.setPrecipAlert3Hr(roundTo2DecimalPlaces((Double)_precipAlert3HrSpinBox.getValue())); - menuSettings.setPrecipAlert6Hr(roundTo2DecimalPlaces((Double)_precipAlert6HrSpinBox.getValue())); - menuSettings.setPrecipCaution1Hr(roundTo2DecimalPlaces((Double)_precipCaution1HrSpinBox.getValue())); - menuSettings.setPrecipCaution3Hr(roundTo2DecimalPlaces((Double)_precipCaution3HrSpinBox.getValue())); - menuSettings.setPrecipCaution6Hr(roundTo2DecimalPlaces((Double)_precipCaution6HrSpinBox.getValue())); - - menuSettings.setRatioAlert1Hr((Integer)_ratioAlert1HrSpinBox.getValue()); - menuSettings.setRatioAlert3Hr((Integer)_ratioAlert3HrSpinBox.getValue()); - menuSettings.setRatioAlert6Hr((Integer)_ratioAlert6HrSpinBox.getValue()); - menuSettings.setRatioCaution1Hr((Integer)_ratioCaution1HrSpinBox.getValue()); - menuSettings.setRatioCaution3Hr((Integer)_ratioCaution3HrSpinBox.getValue()); - menuSettings.setRatioCaution6Hr((Integer)_ratioCaution6HrSpinBox.getValue()); - - menuSettings.setDiffAlert1Hr(roundTo2DecimalPlaces((Double)_diffAlert1HrSpinBox.getValue())); - menuSettings.setDiffAlert3Hr(roundTo2DecimalPlaces((Double)_diffAlert3HrSpinBox.getValue())); - menuSettings.setDiffAlert6Hr(roundTo2DecimalPlaces((Double)_diffAlert6HrSpinBox.getValue())); - menuSettings.setDiffCaution1Hr(roundTo2DecimalPlaces((Double)_diffCaution1HrSpinBox.getValue())); - menuSettings.setDiffCaution3Hr(roundTo2DecimalPlaces((Double)_diffCaution3HrSpinBox.getValue())); - menuSettings.setDiffCaution6Hr(roundTo2DecimalPlaces((Double)_diffCaution6HrSpinBox.getValue())); - - return menuSettings; - } - - private class ApplyMenuSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - PrecipColumnDataSettings currentMenuSettings = getPrecipSettingsFromDialog(); - - if( (_prevMenuSettings.getPrecipAlert1Hr() != currentMenuSettings.getPrecipAlert1Hr()) || - (_prevMenuSettings.getPrecipAlert3Hr() != currentMenuSettings.getPrecipAlert3Hr()) || - (_prevMenuSettings.getPrecipAlert6Hr() != currentMenuSettings.getPrecipAlert6Hr()) || - (_prevMenuSettings.getRatioAlert1Hr() != currentMenuSettings.getRatioAlert1Hr()) || - (_prevMenuSettings.getRatioAlert3Hr() != currentMenuSettings.getRatioAlert3Hr()) || - (_prevMenuSettings.getRatioAlert6Hr() != currentMenuSettings.getRatioAlert6Hr()) || - (_prevMenuSettings.getDiffAlert1Hr() != currentMenuSettings.getDiffAlert1Hr()) || - (_prevMenuSettings.getDiffAlert3Hr() != currentMenuSettings.getDiffAlert3Hr()) || - (_prevMenuSettings.getDiffAlert6Hr() != currentMenuSettings.getDiffAlert6Hr()) || - (_prevMenuSettings.getPrecipCaution1Hr() != currentMenuSettings.getPrecipCaution1Hr()) || - (_prevMenuSettings.getPrecipCaution3Hr() != currentMenuSettings.getPrecipCaution3Hr()) || - (_prevMenuSettings.getPrecipCaution6Hr() != currentMenuSettings.getPrecipCaution6Hr()) || - (_prevMenuSettings.getRatioCaution1Hr() != currentMenuSettings.getRatioCaution1Hr()) || - (_prevMenuSettings.getRatioCaution3Hr() != currentMenuSettings.getRatioCaution3Hr()) || - (_prevMenuSettings.getRatioCaution6Hr() != currentMenuSettings.getRatioCaution6Hr()) || - (_prevMenuSettings.getDiffCaution1Hr() != currentMenuSettings.getDiffCaution1Hr()) || - (_prevMenuSettings.getDiffCaution3Hr() != currentMenuSettings.getDiffCaution3Hr()) || - (_prevMenuSettings.getDiffCaution6Hr() != currentMenuSettings.getDiffCaution6Hr())) - { - _prevMenuSettings = currentMenuSettings; - _savedMenuSettings = currentMenuSettings; - _logger.log("PrecipThresholdDialog.ApplyMenuSettingsListener : New precip settings applied"); - } - } - } - - private class ClosePrecipSettingsDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closePrecipSettingsDialog(); - } - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorAppManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorAppManager.java deleted file mode 100755 index ee02b31240..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorAppManager.java +++ /dev/null @@ -1,227 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Graphics; -import java.awt.GridBagLayout; - -import javax.swing.JPanel; -import javax.swing.JSplitPane; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.db.Database; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorSplitPane; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.util.MemoryLogger; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PrecipMonitorAppManager { - private MessageSystemManager _msgSystemManager; - - private PrecipMonitorDataManager _precipMonitorDataManager; - - private AppsDefaults _appsDefaults; - - public static final String DEFAULT_PRECIP_SETTINGS_FILE = "DefaultPrecipMonitorSettings.txt"; - - public static final String SITE_PRECIP_SETTINGS_FILE = "PrecipMonitorSettings.txt"; - - private SessionLogger _logger; - - private MonitorFrame _mainFrame; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private String _appName = "PrecipMonitor"; - - public static String DERIVED_COLUMNS_FILE = "PrecipDerivedColumns.txt"; - - public PrecipMonitorAppManager(Database db, String missingRepresentation, - String version, String versionDate, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) { - _appsDefaults = AppsDefaults.getInstance(); - - createLogger(); - - ViewSettings viewSettings = new ViewSettings(); - FilterSettings filterSettings = new FilterSettings(); - PrecipMonitorMenuSettings menuSettings = new PrecipMonitorMenuSettings(); - - createFrame(db, version); - - JSplitPane splitPane = new MonitorSplitPane( - JSplitPane.HORIZONTAL_SPLIT, true); - - JPanel timeDisplayPanel = new JPanel(); - JToolBar toolBar = new JToolBar(); - - OfficeNotesDataManager officeNotesDataMgr = new OfficeNotesDataManager( - db, _logger, missingRepresentation); - AlertAlarmDataManager alertAlarmDataMgr = new AlertAlarmDataManager(db, - _logger, missingRepresentation); - - String settingsDir = _appsDefaults.getToken("rivermon_config_dir", - "/awips/hydroapps/whfs/local/data/app/rivermon"); - - _derivedColumnsFileManager = new DerivedColumnsFileManager(settingsDir - + "/" + DERIVED_COLUMNS_FILE, _logger); - - MemoryLogger.setLogger(_logger); - _precipMonitorDataManager = new PrecipMonitorDataManager(db, - _appsDefaults, missingRepresentation, _logger, menuSettings, - _derivedColumnsFileManager); - - _msgSystemManager = new MessageSystemManager(); - - // These objects remain in without a variable, because they register - // listeners to the _msgSystemManager - new PrecipMonitorRefreshManager(_msgSystemManager, _logger, - _precipMonitorDataManager, splitPane); - - new PrecipMonitorFilterManager(_msgSystemManager, _logger, _mainFrame, - _precipMonitorDataManager, splitPane, _appsDefaults, - filterSettings); - - new PrecipMonitorMenuManager(_msgSystemManager, _logger, _mainFrame, - version, versionDate, _appsDefaults, toolBar, - _precipMonitorDataManager, officeNotesDataMgr, - alertAlarmDataMgr, menuSettings, timeDisplayPanel, _appName, - monitorTimeSeriesLiteManager); - - new PrecipMonitorViewManager(_mainFrame, _msgSystemManager, _logger, - _precipMonitorDataManager, splitPane, viewSettings, - _derivedColumnsFileManager, monitorTimeSeriesLiteManager, - _appsDefaults); - - PrecipMonitorSettingsManager settingsManager = new PrecipMonitorSettingsManager( - _msgSystemManager, _appsDefaults, _logger, _mainFrame, - viewSettings, filterSettings, menuSettings); - - settingsManager.startPrecipMonitor(); - - Container frameContentPane = _mainFrame.getContentPane(); - _mainFrame.setLayout(new GridBagLayout()); - - // col, row, width, height, weightx, weighty, fill - ComponentHelper.addFrameComponent(frameContentPane, toolBar, 0, 0, 1, - 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, timeDisplayPanel, - 1, 0, 1, 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, splitPane, 0, 1, 2, - 1, 1, 1, 1); - - _mainFrame.pack(); - _mainFrame.setVisible(true); - } - - private class MonitorJSplitPane extends JSplitPane { - - public MonitorJSplitPane(int newOrientation, boolean newContinuousLayout) { - super(newOrientation, newContinuousLayout); - } - - @Override - public void setDividerLocation(int location) { - int currentDividerLocation = getDividerLocation(); - int adjustedLocation = location; - - if (location < 30) { - int difference = currentDividerLocation - location; - if (difference > 50) { - adjustedLocation = currentDividerLocation; - } - } - super.setDividerLocation(adjustedLocation); - } - - @Override - public void setRightComponent(Component comp) { - String header = "MonitorJSplitPane.setRightComponent() "; - - int beforeDividerLocation = getDividerLocation(); - - // setDividerLocation(beforeDividerLocation); - super.setRightComponent(comp); - - int afterDividerLocation = getDividerLocation(); - - setDividerLocation(beforeDividerLocation); - - System.out.println(header + " before divider location = " - + beforeDividerLocation); - System.out.println(header + " after divider location = " - + afterDividerLocation); - - } - - @Override - public void setLeftComponent(Component comp) { - String header = "MonitorJSplitPane.setLeftComponent() "; - - int beforeDividerLocation = getDividerLocation(); - setDividerLocation(beforeDividerLocation); - - super.setLeftComponent(comp); - - int afterDividerLocation = getDividerLocation(); - - setDividerLocation(beforeDividerLocation); - - System.out.println(header + " before divider location = " - + beforeDividerLocation); - System.out.println(header + " after divider location = " - + afterDividerLocation); - - } - - @Override - public void paint(Graphics g) { - String header = "MonitorJSplitPane.paint() "; - super.paint(g); - - int dividerLocation = getDividerLocation(); - int lastDividerLocation = getLastDividerLocation(); - - System.out.println(header + " divider location = " - + dividerLocation); - System.out.println(header + " last divider location = " - + lastDividerLocation); - - // if (lastDividerLocation > dividerLocation) - // { - // setDividerLocation(lastDividerLocation); - // } - } - } - - private void createLogger() { - String logDir = _appsDefaults.getToken("rivermon_log_dir", - "/awips/hydroapps/whfs/local/data/log/rivermon"); - String logFile = logDir + "/" + _appName; - - _logger = new SessionLogger(_appName, logFile, true, true, null); - _logger.log(null); - _logger.log(_appName + " Started"); - - } - - private void createFrame(Database db, String version) { - _mainFrame = new MonitorFrame(); - String title = _appName + " DbName : " + db.getDatabaseName() - + " Session : " + _logger.getSessionId(); - _mainFrame.setTitle(title); - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorFilterManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorFilterManager.java deleted file mode 100755 index e9d0881a37..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorFilterManager.java +++ /dev/null @@ -1,276 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; -import java.util.Map; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.TreeDataManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeManager; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeSelectionModel; -import ohd.hseb.util.SessionLogger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PrecipMonitorFilterManager extends BaseManager -{ - private SessionLogger _logger; - - private PrecipMonitorDataManager _precipMonitorDataManager; - private FilterSettings _filterSettings; - - private JSplitPane _splitPane; - - private AppsDefaults _appsDefaults; - - private MonitorCheckTreeManager _checkTreeManager; - - private JScrollPane _treeScrollPane; - - private JPopupMenu _popupMenuForTree; - private JMenuItem _expandTreeMenuItem; - private JMenuItem _collapseTreeMenuItem; - - private MonitorFrame _mainFrame; - private String _iconsDir; - - public PrecipMonitorFilterManager(MessageSystemManager msgSystemManager,SessionLogger logger, - MonitorFrame mainFrame, PrecipMonitorDataManager precipMonitorDataManager, JSplitPane splitPane, - AppsDefaults appsDefaults, FilterSettings filterSettings) - { - _precipMonitorDataManager = precipMonitorDataManager; - _splitPane = splitPane; - _appsDefaults = appsDefaults; - _mainFrame = mainFrame; - _filterSettings = filterSettings; - _iconsDir = _appsDefaults.getToken("rivermon_config_dir", "/awips/hydroapps/whfs/local/data/app/rivermon"); - - createPopupMenuForTree(); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), MessageType.REFRESH_DISPLAY); - } - - private void createTreeAndApplySettings(MonitorMessage message) - { - final String header = "PrecipMonitorFilterManager.createTreeAndApplySettings(): "; - System.out.println(header + " thread = " + Thread.currentThread().getId()); - - _mainFrame.setWaitCursor(); - if(message.getMessageSource() != this) - { - System.out.println(header +" Invoked" + "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - List stringArrayListOfFilterItems = _precipMonitorDataManager.createStringArrayListOfFilterItems(); - - TreeDataManager treeDataManager = new TreeDataManager(); - - DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("HSA"); - - JTree tree = treeDataManager.createFilterTreeFromList(rootNode, stringArrayListOfFilterItems); - - tree.setBackground(Color.BLACK); - - TreePath[] preSelectedPaths = _filterSettings.getSelectedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preSelectedPaths :"); - - TreePath[] preExpandedPaths = _filterSettings.getExpandedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preExpandedPaths :"); - - Map lidToCriticalColorMap = _precipMonitorDataManager.getLidToCriticalColorMap(); - - _checkTreeManager = new MonitorCheckTreeManager(tree, preSelectedPaths, preExpandedPaths, lidToCriticalColorMap, _iconsDir); - CheckTreeSelectionListener treeListener = new CheckTreeSelectionListener(); - tree.addMouseListener(treeListener); - - _treeScrollPane = new JScrollPane(tree); - _treeScrollPane.setPreferredSize(new Dimension(300,645)); - - _splitPane.setLeftComponent(_treeScrollPane); - - // printTreePathArray(_checkTreeManager.getSelectionModel().getSelectionPaths(), "Create Tree: "); - - _precipMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(_checkTreeManager.getValidTreePaths(preSelectedPaths)); - - } - _mainFrame.setDefaultCursor(); - } - - private void highlightThisRow() - { - String header = "PrecipMonitorFilterManager.highlightThisRow(): "; - - System.out.print(header ); - send(this, MessageType.FILTER_SELECT_ITEM); - } - - private void sendRefreshDisplayMessage() - { - String header = "PrecipMonitorFilterManager.sendRefreshDisplayMessage(): "; - - System.out.print(header); - send(this, MessageType.REFRESH_DISPLAY); - } - - private void setFilterSettings() - { - String header = "PrecipMonitorFilterManager.setFilterSettings(): "; - System.out.println(header); - - TreePath[] paths = _checkTreeManager.getSelectionModel().getSelectionPaths(); - _filterSettings.setSelectedPaths(paths); - - // printTreePathArray(paths, header + " selected path in "); - - TreePath[] expandedPaths = _checkTreeManager.getAllExpandedPaths(); - _filterSettings.setExpandedPaths(expandedPaths); - - } - - private void createPopupMenuForTree() - { - _popupMenuForTree = new JPopupMenu(); - _expandTreeMenuItem = new JMenuItem("Expand Entire Tree"); - _expandTreeMenuItem.setMnemonic('E'); - _collapseTreeMenuItem = new JMenuItem("Collapse Entire Tree"); - _collapseTreeMenuItem.setMnemonic('C'); - _popupMenuForTree.add(_expandTreeMenuItem); - _popupMenuForTree.add(_collapseTreeMenuItem); - - TreePopupMenuListener treePopupMenuListener = new TreePopupMenuListener(); - _expandTreeMenuItem.addActionListener(treePopupMenuListener); - _collapseTreeMenuItem.addActionListener(treePopupMenuListener); - } - - private void printTreePathArray(TreePath[] treePathArray, String message) - { - if (message != null) - { - System.out.println(message); - } - - if (treePathArray != null) - { - for (TreePath treePath : treePathArray) - { - System.out.println(treePath); - } - } - - return; - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - - private class TreePopupMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - TreePath[] allAvailablePaths = _checkTreeManager.getAllAvailablePaths(); - if(e.getSource().toString().contains("Expand Entire Tree")) - { - _checkTreeManager.expandThesePaths(allAvailablePaths); - } - else //collapse tree - { - _checkTreeManager.collapseEntireTree(); - } - - setFilterSettings(); - } - } - - class CheckTreeSelectionListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - MonitorCheckTreeSelectionModel selectionModel = (MonitorCheckTreeSelectionModel) (_checkTreeManager.getSelectionModel()); - - selectionModel.printInstanceId(); - - TreePath paths[] = selectionModel.getSelectionPaths(); - - // printTreePathArray(paths, "CheckTreeSelectionListener.mouseClicked(): "); - - setFilterSettings(); - - _precipMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(paths); - sendRefreshDisplayMessage(); - - if(SwingUtilities.isLeftMouseButton(e)) - { - JTree tree = (JTree) e.getSource(); - int row = tree.getRowForLocation(e.getX(), e.getY()); - TreePath path = tree.getPathForRow(row); - String itemClickedOnJtree = null; - if(path != null) - { - if(path.getPathCount() == 4) - { - itemClickedOnJtree = path.getLastPathComponent().toString(); - System.out.println("Item of interest:"+ itemClickedOnJtree); - _precipMonitorDataManager.setLidOfCurrentInterest(itemClickedOnJtree); - highlightThisRow(); - } - } - } - } - public void mousePressed(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - - public void mouseReleased(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorMenuManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorMenuManager.java deleted file mode 100755 index 1c94677f9f..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorMenuManager.java +++ /dev/null @@ -1,752 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.alertalarm.AlertAlarmDialog; -import ohd.hseb.monitor.Monitor; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.MonitorToolBarManager; -import ohd.hseb.monitor.manager.MonitorMenuManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.precip.PrecipMonitorJTableRowData; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.officenotes.OfficeNotesDialog; -import ohd.hseb.rivermonlocgroup.RiverMonGroupDialog; -import ohd.hseb.rivermonlocgroup.RiverMonLocationDialog; -import ohd.hseb.util.SessionLogger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PrecipMonitorMenuManager extends MonitorMenuManager { - private JMenuBar _menuBar; - - private JMenu _fileMenu, _displayMenu, _sortMenu, _configMenu, - _detailsMenu, _helpMenu; - - private JMenuItem _selectColumnsMenuItem; - - private JCheckBoxMenuItem _showMissingPrecipMenuItem; - - private JMenuItem _saveColumnSettingsMenuItem; - - private JMenuItem _loadSettingsMenuItem; - - private JMenuItem _loadOfficeSettingsMenuItem; - - private JMenuItem _saveOfficeSettingsMenuItem; - - private JMenuItem _refreshColumnMenuItem; - - private JMenuItem _exportTableToTextMenuItem; - - private JMenuItem _exitApplicationMenuItem; - - private JMenuItem _officeNotesMenuItem; - - private JMenuItem _alertAlarmMenuItem; - - private JMenuItem _timeSeriesLiteMenuItem; - - private JMenuItem _riverMonGroupMenuItem; - - private JMenuItem _riverMonLocationMenuItem; - - private JMenuItem _derivedColumnsMenuItem; - - private JMenuItem _hsagrplocSortMenuItem; - - private JMenuItem _precipThreatSortMenuItem; - - private JMenuItem _clearSortMenuItem; - - private JMenuItem _precipThresholdForThreatColorMenuItem; - - private JMenuItem _aboutMenuItem; - - private RiverMonGroupDialog _riverMonGroupDialog = null; - - private RiverMonLocationDialog _riverMonLocationDialog; - - private AlertAlarmDialog _alertAlarmDialog; - - private AlertAlarmDataManager _alertAlarmDataMgr; - - private PrecipMonitorDataManager _precipMonitorDataManager; - - private PrecipMonitorMenuSettings _menuSettings; - - private OfficeNotesDialog _officeNotesDialog; - - private OfficeNotesDataManager _officeNotesDataMgr; - - private String _settingsDir; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - private PrecipMonitorJTableRowData _selectedRowData; - - private MonitorToolBarManager _toolBarManager; - - public PrecipMonitorMenuManager(MessageSystemManager msgSystemManager, - SessionLogger logger, MonitorFrame mainFrame, String version, - String versionDate, AppsDefaults appsDefaults, JToolBar toolBar, - PrecipMonitorDataManager precipMonitorDataManager, - OfficeNotesDataManager officeNotesDataMgr, - AlertAlarmDataManager alertAlarmDataMgr, - PrecipMonitorMenuSettings menuSettings, JPanel timeDisplayPanel, - String appName, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) { - super(msgSystemManager, appsDefaults, logger); - _appsDefaults = appsDefaults; - - _menuSettings = menuSettings; - - _precipMonitorDataManager = precipMonitorDataManager; - _alertAlarmDataMgr = alertAlarmDataMgr; - - _officeNotesDataMgr = officeNotesDataMgr; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - "/awips/hydroapps/whfs/local/data/app/rivermon"); - - int defaultRefreshInterval = 15; - createRefreshComponents(defaultRefreshInterval, timeDisplayPanel); - - _toolBarManager = new MonitorToolBarManager(toolBar, _appsDefaults, - _officeNotesDataMgr); - _toolBarManager.getOfficeNotesButton().addActionListener( - new OfficeNotesDialogListener()); - - setAboutInfo(version, versionDate, appName); - _mainFrame = mainFrame; - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver( - new UpdateDisplayWithSettingsReceiver(), - MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new ViewSelectItemReceiver(), - MessageType.VIEW_SELECT_ITEM); - - _msgSystemManager.registerReceiver(new UpdateDisplayReceiver(), - MessageType.REFRESH_DISPLAY); - - createMenus(); - - setFrameListener(); - } - - @Override - protected long getDataUpdateTime() { - return _precipMonitorDataManager.getPdcUpdateTime(); - } - - @Override - protected long getDisplayedRecordCount() { - return _precipMonitorDataManager.getDisplayedRecordCount(); - } - - @Override - public void setMenuSettingsRefreshInterval(int value) { - _menuSettings.setRefreshInterval(value); - } - - @Override - public void setRefreshTimeSpinnerValue() { - _refreshTimeSpinner.setValue(_menuSettings.getRefreshInterval()); - } - - private void createMenus() { - _menuBar = new JMenuBar(); - _mainFrame.setJMenuBar(_menuBar); - - _toolBarManager.getOfficeNotesButton().addActionListener( - new OfficeNotesDialogListener()); - - _fileMenu = new JMenu("File"); - _configMenu = new JMenu("Config"); - _displayMenu = new JMenu("Display"); - _sortMenu = new JMenu("Sort"); - _detailsMenu = new JMenu("Details"); - _helpMenu = new JMenu("Help"); - - _fileMenu.setMnemonic('F'); - _configMenu.setMnemonic('C'); - _displayMenu.setMnemonic('D'); - _sortMenu.setMnemonic('S'); - _detailsMenu.setMnemonic('E'); - _helpMenu.setMnemonic('H'); - - // File Menu - _refreshColumnMenuItem = new JMenuItem("Refresh"); - _refreshColumnMenuItem.setMnemonic('R'); - _refreshColumnMenuItem - .setToolTipText("Update screen with latest available data. Same as Update Now"); - _fileMenu.add(_refreshColumnMenuItem); - - _fileMenu.add(new JSeparator()); - - _saveColumnSettingsMenuItem = new JMenuItem("Save Custom Settings ..."); - _saveColumnSettingsMenuItem.setMnemonic('S'); - _fileMenu.add(_saveColumnSettingsMenuItem); - - _saveOfficeSettingsMenuItem = new JMenuItem("Save Office Settings"); - _saveOfficeSettingsMenuItem.setMnemonic('F'); - _saveOfficeSettingsMenuItem - .setToolTipText("Save office settings to PrecipMonitorSettings.txt"); - _fileMenu.add(_saveOfficeSettingsMenuItem); - - _loadSettingsMenuItem = new JMenuItem("Load Custom Settings ..."); - _loadSettingsMenuItem.setMnemonic('L'); - _fileMenu.add(_loadSettingsMenuItem); - - _loadOfficeSettingsMenuItem = new JMenuItem("Load Office Settings"); - _loadOfficeSettingsMenuItem.setMnemonic('O'); - _loadOfficeSettingsMenuItem - .setToolTipText("Load office settings from PrecipMonitorSettings.txt"); - _fileMenu.add(_loadOfficeSettingsMenuItem); - - _fileMenu.add(new JSeparator()); - - _exportTableToTextMenuItem = new JMenuItem( - "Export Data To Text File ..."); - _exportTableToTextMenuItem.setMnemonic('x'); - _fileMenu.add(_exportTableToTextMenuItem); - - _fileMenu.add(new JSeparator()); - - _exitApplicationMenuItem = new JMenuItem("Exit"); - _exitApplicationMenuItem.setMnemonic('E'); - _fileMenu.add(_exitApplicationMenuItem); - - // Display Menu - _selectColumnsMenuItem = new JMenuItem("Select Columns ..."); - _selectColumnsMenuItem.setMnemonic('S'); - _displayMenu.add(_selectColumnsMenuItem); - - _displayMenu.add(new JSeparator()); - - _precipThresholdForThreatColorMenuItem = new JMenuItem( - "Precip Threshold ..."); - _precipThresholdForThreatColorMenuItem.setMnemonic('P'); - _displayMenu.add(_precipThresholdForThreatColorMenuItem); - - _showMissingPrecipMenuItem = new JCheckBoxMenuItem( - "Show Locations with Missing Precip Data"); - _showMissingPrecipMenuItem.setMnemonic('M'); - _displayMenu.add(_showMissingPrecipMenuItem); - - // Config Menu - _riverMonGroupMenuItem = new JMenuItem("Group Definitions ..."); - _riverMonGroupMenuItem.setMnemonic('G'); - _configMenu.add(_riverMonGroupMenuItem); - - _riverMonLocationMenuItem = new JMenuItem( - "Location Grouping/Ordering ..."); - _riverMonLocationMenuItem.setMnemonic('L'); - _configMenu.add(_riverMonLocationMenuItem); - - _configMenu.add(new JSeparator()); - - _derivedColumnsMenuItem = new JMenuItem("Derived Columns ..."); - _derivedColumnsMenuItem.setMnemonic('D'); - _configMenu.add(_derivedColumnsMenuItem); - - // Sort Menu - _clearSortMenuItem = new JMenuItem("Clear Sort"); - _clearSortMenuItem.setMnemonic('C'); - _clearSortMenuItem.setToolTipText("Clear All Sorts"); - _sortMenu.add(_clearSortMenuItem); - - _sortMenu.add(new JSeparator()); - - _hsagrplocSortMenuItem = new JMenuItem( - "Sort by HSA | Group | Location Columns"); - _hsagrplocSortMenuItem.setMnemonic('O'); - _hsagrplocSortMenuItem - .setToolTipText("Sort by HSA, group id, location id"); - _sortMenu.add(_hsagrplocSortMenuItem); - - _precipThreatSortMenuItem = new JMenuItem("PrecipThreat Sort"); - _precipThreatSortMenuItem.setMnemonic('P'); - _precipThreatSortMenuItem.setToolTipText("Sort by PrecipThreat"); - _sortMenu.add(_precipThreatSortMenuItem); - - // Details Memu - _officeNotesMenuItem = new JMenuItem("Office Notes ..."); - _officeNotesMenuItem.setMnemonic('O'); - _detailsMenu.add(_officeNotesMenuItem); - - _alertAlarmMenuItem = new JMenuItem("Alert Alarm ..."); - _alertAlarmMenuItem.setMnemonic('A'); - _detailsMenu.add(_alertAlarmMenuItem); - - _detailsMenu.add(new JSeparator()); - - _timeSeriesLiteMenuItem = new JMenuItem("Time Series Lite..."); - _timeSeriesLiteMenuItem.setMnemonic('T'); - _detailsMenu.add(_timeSeriesLiteMenuItem); - - // Help Menu - _aboutMenuItem = new JMenuItem("About ..."); - _aboutMenuItem.setMnemonic('A'); - _helpMenu.add(_aboutMenuItem); - - setMenuListeners(); - - _menuBar.add(_fileMenu); - _menuBar.add(_displayMenu); - _menuBar.add(_configMenu); - _menuBar.add(_sortMenu); - _menuBar.add(_detailsMenu); - _menuBar.add(_helpMenu); - } - - private void setMenuListeners() { - ChangeColumnsDisplayedMenuListener changeMenuListener = new ChangeColumnsDisplayedMenuListener(); - _selectColumnsMenuItem.addActionListener(changeMenuListener); - - ShowMissingPrecipMenuListener showMissingPrecipMenuListener = new ShowMissingPrecipMenuListener(); - _showMissingPrecipMenuItem - .addItemListener(showMissingPrecipMenuListener); - - SaveSettingsListener saveMenuListener = new SaveSettingsListener(); - _saveColumnSettingsMenuItem.addActionListener(saveMenuListener); - - LoadSettingsListener loadMenuListener = new LoadSettingsListener(); - _loadSettingsMenuItem.addActionListener(loadMenuListener); - - LoadOfficeSettingsListener loadOfficeSettingsListener = new LoadOfficeSettingsListener(); - _loadOfficeSettingsMenuItem - .addActionListener(loadOfficeSettingsListener); - - SaveOfficeSettingsListener saveOfficeSettingsListener = new SaveOfficeSettingsListener(); - _saveOfficeSettingsMenuItem - .addActionListener(saveOfficeSettingsListener); - - ExitApplicationListener exitApplicationListener = new ExitApplicationListener(); - _exitApplicationMenuItem.addActionListener(exitApplicationListener); - - RefreshMenuListener RefreshMenuListener = new RefreshMenuListener(); - _refreshColumnMenuItem.addActionListener(RefreshMenuListener); - - SaveTableListener saveTableListener = new SaveTableListener(); - _exportTableToTextMenuItem.addActionListener(saveTableListener); - - AppSortListener appSortListener = new AppSortListener(); - _hsagrplocSortMenuItem.addActionListener(appSortListener); - - PrecipThreatSortListener precipThreatSortListener = new PrecipThreatSortListener(); - _precipThreatSortMenuItem.addActionListener(precipThreatSortListener); - - ClearSortListener clearSortListener = new ClearSortListener(); - _clearSortMenuItem.addActionListener(clearSortListener); - - AlertAlarmDialogListener alertAlarmDialogListener = new AlertAlarmDialogListener(); - _alertAlarmMenuItem.addActionListener(alertAlarmDialogListener); - - OfficeNotesDialogListener officeNotesDialogListener = new OfficeNotesDialogListener(); - _officeNotesMenuItem.addActionListener(officeNotesDialogListener); - - TimeSeriesLiteMenuItemListener timeSeriesLiteMenuItemListener = new TimeSeriesLiteMenuItemListener(); - _timeSeriesLiteMenuItem - .addActionListener(timeSeriesLiteMenuItemListener); - - RiverMonGroupDialogListener riverMonGroupDialogListener = new RiverMonGroupDialogListener(); - _riverMonGroupMenuItem.addActionListener(riverMonGroupDialogListener); - - RiverMonLocationDialogListener riverMonLocationDialogListener = new RiverMonLocationDialogListener(); - _riverMonLocationMenuItem - .addActionListener(riverMonLocationDialogListener); - - PrecipThresholdListener precipThresholdListener = new PrecipThresholdListener( - _menuSettings.getPrecipSettings()); - _precipThresholdForThreatColorMenuItem - .addActionListener(precipThresholdListener); - - DerivedColumnsEditorListener derivedColumnsEditorListener = new DerivedColumnsEditorListener(); - _derivedColumnsMenuItem.addActionListener(derivedColumnsEditorListener); - - AboutListener aboutListener = new AboutListener(); - _aboutMenuItem.addActionListener(aboutListener); - - } - - private class DerivedColumnsEditorListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String editorTitle = ("\"").concat("Derived Columns").concat("\""); - String file = _settingsDir + "/" - + PrecipMonitorAppManager.DERIVED_COLUMNS_FILE; - launchTextEditor(editorTitle, file, "PrecipMonitor Application"); - } - } - - private void setFrameListener() { - FrameListener frameListener = new FrameListener(); - _mainFrame.addWindowListener(frameListener); - } - - public void closeApplication() { - _logger.log("PrecipMonitor Application Exiting...."); - _logger.log("===================================="); - _precipMonitorDataManager.disconnect(); - _mainFrame.setVisible(false); - _mainFrame.dispose(); - Monitor.disposePrecip(); - } - - private void createOfficeNotesDialog() { - List lidList = _precipMonitorDataManager.getLidList(); - String lids[] = new String[lidList.size()]; - for (int i = 0; i < lidList.size(); i++) { - lids[i] = lidList.get(i).toString(); - } - Arrays.sort(lids); - System.out.println("Create officenotes lids size:" + lidList.size()); - Map lidDescDetailsMap = _precipMonitorDataManager.getLidDescDetails(); - if (_officeNotesDialog == null) - _officeNotesDialog = new OfficeNotesDialog(_mainFrame, - _officeNotesDataMgr, "RIVERMON", lids, lidDescDetailsMap, - _logger); - } - - public void loadSettings() { - String header = "PrecipMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - - private void loadOfficeSettings() { - String header = "PrecipMonitorMenuManager.loadOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_OFFICE_SETTINGS); - } - - public void viewSelectItem(MonitorMessage message) { - String header = "PrecipMonitorMenuManager.viewSelectItem(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - _selectedRowData = (PrecipMonitorJTableRowData) message - .getMessageData(); - } - - public void updateDisplayWithSettings(MonitorMessage message) { - String header = "PrecipMonitorMenuManager.updateDisplayWithSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - refreshTimeDisplay(); - updateMenuWithNewSettings(); - } - - private void updateMenuWithNewSettings() { - if (_menuSettings.shouldShowMissingPrecip()) - _showMissingPrecipMenuItem.setSelected(true); - else - _showMissingPrecipMenuItem.setSelected(false); - } - - public void saveSettings() { - String header = "PrecipMonitorMenuManager.saveSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_SETTINGS); - } - - private void saveOfficeSettings() { - String header = "PrecipMonitorMenuManager.saveOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_OFFICE_SETTINGS); - } - - public void loadSettings(File fileHandler) { - if (fileHandler != null) { - String header = "PrecipMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - } - - public void loadSettingsFromFile(File fileHandler) { - String header = "PrecipMonitorMenuManager.loadSettingsFromFile(): "; - if (fileHandler != null) { - _logger.log(header + "Read settings from " - + fileHandler.getAbsolutePath()); - loadSettings(fileHandler); - } - } - - private void saveTable() { - String header = "PrecipMonitorMenuManager.saveTable(): "; - - System.out.print(header); - send(this, MessageType.CREATE_TEXT_FROM_VIEW); - } - - private void changeColumns() { - String header = "PrecipMonitorMenuManager.changeColumns(): "; - - System.out.print(header); - send(this, MessageType.CHANGE_COLUMNS); - } - - private void precipThreatSort() { - String header = "PrecipMonitorMenuManager.precipThreatSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.PRECIP_THREAT_SORT); - } - - private void appSort() { - String header = "PrecipMonitorMenuManager.appSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.APP_SORT); - } - - private void clearSort() { - String header = "PrecipMonitorMenuManager.clearSort(): "; - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - } - - private void createAlertAlarmDialog() { - if (_alertAlarmDialog == null) - _alertAlarmDialog = new AlertAlarmDialog(_mainFrame, - _alertAlarmDataMgr, _logger); - } - - private void createRiverMonGroupDialog() { - String defaultHsa = _precipMonitorDataManager.getDefaultHsa(); - if (_riverMonGroupDialog == null) - _riverMonGroupDialog = new RiverMonGroupDialog(_mainFrame, - _precipMonitorDataManager.getRiverMonLocGroupDataManager(), - _logger, defaultHsa); - } - - private void createRiverMonLocationDialog() { - if (_riverMonLocationDialog == null) - _riverMonLocationDialog = new RiverMonLocationDialog(_mainFrame, - _precipMonitorDataManager.getRiverMonLocGroupDataManager(), - _logger); - } - - private class ExitApplicationListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - closeApplication(); - } - } - - public class ShowMissingPrecipMenuListener implements ItemListener { - public void itemStateChanged(ItemEvent e) { - String header = "PrecipMonitorMenuManager.ShowMissingPrecipMenuListener.itemStateChanged()"; - - boolean prevValue = _menuSettings.shouldShowMissingPrecip(); - boolean newValue = false; - if (e.getStateChange() == ItemEvent.SELECTED) { - newValue = true; - } - - _menuSettings.setShowMissingPrecip(newValue); - - if (prevValue != newValue) { - sendMissingFilterChanged(); - } - } - } - - public class ChangeColumnsDisplayedMenuListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - changeColumns(); - } - } - - private class ClearSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - clearSort(); - } - } - - private class PrecipThreatSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - precipThreatSort(); - } - } - - private class AppSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - appSort(); - } - } - - private class RiverMonitorListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - //startMonitor("RiverMonitor Application", "RIVER"); - } - } - - private class SaveTableListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - saveTable(); - } - } - - private class RefreshMenuListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - refresh(); - } - } - - private class AlertAlarmDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createAlertAlarmDialog(); - if (_selectedRowData != null) { - _alertAlarmDialog.showAlertAlarmDialog(_selectedRowData - .getLid()); - } else - _alertAlarmDialog.showAlertAlarmDialog(null); - } - } - - private class TimeSeriesLiteMenuItemListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (_selectedRowData != null) { - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, - _selectedRowData, 1); - } else { - String textMsg = " Unable to display TimeSeriesLite
" - + "Please highlight a row... "; - JOptionPane.showMessageDialog(_mainFrame, textMsg, - "TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - } - } - - private class RiverMonGroupDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createRiverMonGroupDialog(); - boolean hasTableChanged = _riverMonGroupDialog - .showRiverMonGroupDialog(); - if (hasTableChanged) { - menuChange(); - } - } - } - - private class RiverMonLocationDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createRiverMonLocationDialog(); - boolean hasTableChanged = _riverMonLocationDialog - .showRiverMonLocationDialog(); - System.out.println("Rivermonlocation table changed:" - + hasTableChanged); - if (hasTableChanged) { - menuChange(); - } - } - } - - private class LoadOfficeSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - loadOfficeSettings(); - } - } - - private class SaveOfficeSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String message = " This will overwrite standard office settings for PrecipMonitor.
" - + "Are you sure ?
"; - if (confirmSaveOfficeSettings(message)) - saveOfficeSettings(); - } - } - - private class LoadSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - loadSettings(); - } - } - - private class FrameListener extends WindowAdapter { - @Override - public void windowClosing(WindowEvent event) { - closeApplication(); - } - } - - private class OfficeNotesDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createOfficeNotesDialog(); - if (_selectedRowData != null) { - _officeNotesDialog.showOfficeNotesDialog(_selectedRowData - .getLid()); - } else - _officeNotesDialog.showOfficeNotesDialog(null); - - _toolBarManager.setOfficeNotesButtonIcon(_officeNotesDataMgr - .getCountOfOfficeNotes()); - } - } - - private class SaveSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - saveSettings(); - } - } - - private class UpdateDisplayReceiver implements Receiver { - public void receive(MonitorMessage message) { - updateRecordCount(); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - setInitialRefreshTimeInfo(); - updateDisplayWithSettings(message); - } - } - - private class ViewSelectItemReceiver implements Receiver { - public void receive(MonitorMessage message) { - viewSelectItem(message); - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorRefreshManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorRefreshManager.java deleted file mode 100755 index e969bebb75..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorRefreshManager.java +++ /dev/null @@ -1,44 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import javax.swing.JSplitPane; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.MonitorRefreshManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.DialogHelper; - -public class PrecipMonitorRefreshManager extends MonitorRefreshManager -{ - private PrecipMonitorDataManager _precipMonitorDataManager; - - public PrecipMonitorRefreshManager(MessageSystemManager msgSystemManager, SessionLogger logger, - PrecipMonitorDataManager precipMonitorDataManager, JSplitPane splitPane) - { - super(msgSystemManager, logger, splitPane); - - _precipMonitorDataManager = precipMonitorDataManager; - } - - protected void reloadData(MonitorMessage incomingMessage, MessageType outgoingMessageType) - { - DialogHelper.setWaitCursor(_splitPane); - - String header = "MonitorRefreshManager.reloadData(): "; - System.out.println(header +" Invoked"+ "...Source:" + incomingMessage.getMessageSource() + - " Type:" + incomingMessage.getMessageType()); - - Runtime.getRuntime().gc(); - _precipMonitorDataManager.createPrecipMonitorRowDataList(); - Runtime.getRuntime().gc(); - - System.out.println(header); - send(this, outgoingMessageType); - - DialogHelper.setDefaultCursor(_splitPane); - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorSettingsManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorSettingsManager.java deleted file mode 100755 index 76fe9238f8..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorSettingsManager.java +++ /dev/null @@ -1,202 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.io.File; - -import javax.swing.JFileChooser; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.monitor.precip.settings.PrecipMonitorSettingsFileManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PrecipMonitorSettingsManager extends BaseManager { - private String _settingsDir; - - private AppsDefaults _appsDefaults; - - private SessionLogger _logger; - - private JFileChooser _fileChooser; - - private MonitorFrame _mainFrame; - - private ViewSettings _viewSettings; - - private FilterSettings _filterSettings; - - private PrecipMonitorMenuSettings _menuSettings; - - private PrecipMonitorSettingsFileManager _precipMonitorSettingsFileManger; - - private String _officeSettingsFile; - - private String _defaultSettingsFile; - - public PrecipMonitorSettingsManager(MessageSystemManager msgSystemManager, - AppsDefaults appsDefaults, SessionLogger logger, - MonitorFrame mainFrame, ViewSettings viewSettings, - FilterSettings filterSettings, - PrecipMonitorMenuSettings menuSettings) { - _appsDefaults = appsDefaults; - _logger = logger; - _viewSettings = viewSettings; - _filterSettings = filterSettings; - _menuSettings = menuSettings; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - "/awips/hydroapps/whfs/local/data/app/rivermon"); - - _precipMonitorSettingsFileManger = new PrecipMonitorSettingsFileManager( - _logger, _viewSettings, _filterSettings, _menuSettings); - - _mainFrame = mainFrame; - - _officeSettingsFile = _settingsDir.concat("/").concat( - PrecipMonitorAppManager.SITE_PRECIP_SETTINGS_FILE); - _defaultSettingsFile = _settingsDir.concat("/").concat( - PrecipMonitorAppManager.DEFAULT_PRECIP_SETTINGS_FILE); - - setMessageSystemManager(msgSystemManager); - - _msgSystemManager.registerReceiver(new LoadSettingsReceiver(), - MessageType.LOAD_SETTINGS); - _msgSystemManager.registerReceiver(new LoadOfficeSettingsReceiver(), - MessageType.LOAD_OFFICE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveSettingsReceiver(), - MessageType.SAVE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveOfficeSettingsReceiver(), - MessageType.SAVE_OFFICE_SETTINGS); - } - - private void saveSettings(MonitorMessage message) { - String header = "PrecipMonitorSettingsManager.saveSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File fileHandler = null; - _fileChooser = new JFileChooser(); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = _fileChooser.showSaveDialog(_mainFrame); - if (result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveOfficeSettings(MonitorMessage message) { - String header = "PrecipMonitorSettingsManager.saveOfficeSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveSettingsToFile(File fileHandler) { - send(this, MessageType.UPDATE_SETTINGS); - - if (fileHandler != null) { - _precipMonitorSettingsFileManger.saveSettingsToFile(fileHandler); - } - } - - private void loadSettings(MonitorMessage message) { - String header = "PrecipMonitorSettingsManager.loadSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - if (message.getMessageSource() != this) { - File fileHandler = null; - _fileChooser = new JFileChooser(); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - int result = _fileChooser.showOpenDialog(_mainFrame); - - if (result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - loadSettings(fileHandler); - } - } - - public void startPrecipMonitor() { - String header = "PrecipMonitorSettings.startPrecipMonitor(): "; - File fileHandler = new File(_officeSettingsFile); - if (fileHandler == null || (!fileHandler.exists())) { - fileHandler = new File(_defaultSettingsFile); - } - - _logger.log(header + "Trying to load from file :" - + fileHandler.getAbsolutePath()); - // loadSettings(fileHandler); - } - - private void loadSettings(File fileHandler) { - String header = "PrecipMonitorSettingsManager.loadSettings(): "; - if (fileHandler != null) { - _precipMonitorSettingsFileManger.setSettingsFromFile(fileHandler); - - System.out.print(header); - send(this, MessageType.RELOAD_DATA_WITH_NEW_SETTINGS); - } - } - - private void loadOfficeSettings(MonitorMessage message) { - String header = "PrecipMonitorSettingsManager.loadOfficeSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - loadSettings(fileHandler); - } - - private class SaveOfficeSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - saveOfficeSettings(message); - } - } - - private class LoadOfficeSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - loadOfficeSettings(message); - } - } - - private class LoadSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - loadSettings(message); - } - } - - private class SaveSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - saveSettings(message); - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorViewManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorViewManager.java deleted file mode 100755 index e6ab621960..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorViewManager.java +++ /dev/null @@ -1,541 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.util.List; - -import javax.swing.JFileChooser; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.precip.PrecipMonitorJTableRowData; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableColumnDisplaySettings; -import ohd.hseb.util.gui.jtable.JTableManager; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class PrecipMonitorViewManager extends BaseManager -{ - private SessionLogger _logger; - - private PrecipMonitorDataManager _precipMonitorDataManager; - private JTableManager _precipMonitorTableManager; - private ViewSettings _viewSettings; - - private JSplitPane _splitPane; - - private List _precipMonitorAllRowDataList; - - private String _columnNamesCurrentlyDisplayed[]; - private DerivedColumnsFileManager _derivedColumnsFileManager; - private MonitorFrame _mainFrame; - - private AppsDefaults _appsDefaults; - - private PrecipMonitorJTableRowData _selectedRowData; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - public PrecipMonitorViewManager(MonitorFrame mainFrame, MessageSystemManager msgSystemManager, SessionLogger logger, - PrecipMonitorDataManager precipMonitorDataManager, JSplitPane splitPane, ViewSettings viewSettings, - DerivedColumnsFileManager derivedColumnsFileManager, MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager, - AppsDefaults appsDefaults) - { - _logger = logger; - _precipMonitorDataManager = precipMonitorDataManager; - _splitPane = splitPane; - _mainFrame = mainFrame; - _viewSettings = viewSettings; - - _derivedColumnsFileManager = derivedColumnsFileManager; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - _appsDefaults = appsDefaults; - - List precipColumnsList = new PrecipColumns().getPrecipColumnsList(null); - - _derivedColumnsFileManager.getDerivedColumns(); - String derivedColumnNames[] = _derivedColumnsFileManager.getDerivedColumnNames(); - String alignmentForDerivedColumns[] = _derivedColumnsFileManager.getAlignmentForDerivedColumns(); - if(derivedColumnNames != null) - { - addDerivedColumnNames(precipColumnsList, derivedColumnNames, alignmentForDerivedColumns); - } - - Dimension columnHeaderPreferredSize = new Dimension(100, 50); - _precipMonitorTableManager = new ComplexJTableManager(precipColumnsList, _precipMonitorAllRowDataList, columnHeaderPreferredSize); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new SelectViewItemReceiver(), MessageType.FILTER_SELECT_ITEM); - _msgSystemManager.registerReceiver(new ChangeColumnsReceiver(), MessageType.CHANGE_COLUMNS); - _msgSystemManager.registerReceiver(new AppSortReceiver(), MessageType.APP_SORT); - _msgSystemManager.registerReceiver(new PrecipThreatSortReceiver(), MessageType.PRECIP_THREAT_SORT); - _msgSystemManager.registerReceiver(new ClearSortReceiver(), MessageType.CLEAR_SORT); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), MessageType.REFRESH_DISPLAY); - _msgSystemManager.registerReceiver(new SaveViewReceiver(), MessageType.CREATE_TEXT_FROM_VIEW); - _msgSystemManager.registerReceiver(new UpdateSettingsReceiver(), MessageType.UPDATE_SETTINGS); - - } - - private void addDerivedColumnNames(List precipColumnsList, String derivedColumnNames[], String alignmentForDerivedColumns[]) - { - for(int i=0; i < derivedColumnNames.length; i++) - { - precipColumnsList.add(new JTableColumnDescriptor(derivedColumnNames[i], alignmentForDerivedColumns[i], derivedColumnNames[i])); - } - } - - private void createTableAndApplySettings(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.createTableAndApplySettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _precipMonitorAllRowDataList = _precipMonitorDataManager.getPrecipMonitorRowDataList(); - - _columnNamesCurrentlyDisplayed = null; - String columnDisplaySettingsString = _viewSettings.getColumnDisplaySettings(); - JTableColumnDisplaySettings columnDisplaySettings = _precipMonitorTableManager.getTableSettings(); - columnDisplaySettings.setSettingsFromString(columnDisplaySettingsString); - - _columnNamesCurrentlyDisplayed = _precipMonitorTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - if(_columnNamesCurrentlyDisplayed == null) - { - _columnNamesCurrentlyDisplayed = new String[] {LocationInfoColumns.LOCATION_ID, LocationInfoColumns.GROUP_NAME}; - } - - List selectedRowDataList = _precipMonitorDataManager.getTreeFilterManager().filter(_precipMonitorAllRowDataList); - _precipMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _precipMonitorTableManager.setDisplayableColumns(_columnNamesCurrentlyDisplayed, true, true); - _precipMonitorTableManager.setPreferredSizeForJScrollPane(new Dimension(690, 645)); - - JScrollPane tableScrollPane = _precipMonitorTableManager.getJScrollPane(); - _splitPane.setRightComponent(tableScrollPane); - - _precipMonitorTableManager.addTableListener(new TableMouseMotionListener()); - _precipMonitorTableManager.addTableListener(new TableListSelectionListener()); - _precipMonitorTableManager.addTableListener(new TableMouseListener()); - } - - - public void refreshDisplay(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.refreshDisplay(): "; - - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _precipMonitorAllRowDataList = _precipMonitorDataManager.getPrecipMonitorRowDataList(); - List selectedRowDataList = _precipMonitorDataManager.getTreeFilterManager().filter(_precipMonitorAllRowDataList); - _precipMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _precipMonitorTableManager.refreshDisplay(); - - JScrollPane tableScrollPane = _precipMonitorTableManager.getJScrollPane(); - - _splitPane.setRightComponent(tableScrollPane); - } - - private void setSplitPaneDividerLocation() - { - String header = "PrecipMonitorViewManager.setSplitPaneDividerLocation(): "; - - int newDividerLocation = _splitPane.getDividerLocation(); - - _splitPane.setDividerLocation(newDividerLocation); - - return; - } - - private void updateSettings(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.updateSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - updateSettings(); - } - - private void updateSettings() - { - String header = "PrecipMonitorViewManager.updateSettings(): "; - JTableColumnDisplaySettings columnDisplaySettings = _precipMonitorTableManager.getTableSettings(); - String settings = columnDisplaySettings.getSettingsString(); - _viewSettings.setColumnDisplaySettings(settings); - } - - private void selectViewItem(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.selectViewItem(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - String lidOfInterest = _precipMonitorDataManager.getLidOfCurrentInterest(); - int rowToHighLight = _precipMonitorTableManager.getTheRowIndexToHighLightBasedOnValue(lidOfInterest, LocationInfoColumns.LOCATION_ID); - System.out.println("Row to highlight:" + rowToHighLight); - if(rowToHighLight != -1) - _precipMonitorTableManager.selectRows(rowToHighLight, rowToHighLight); - } - - public void printFileException(IOException exception, String header) - { - header = header+".printFileException(): "; - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - _logger.log(header+"End of stack trace"); - } - - private void saveTableToFile(String fileName) - { - File fileHandler = new File(fileName); - String header = "PrecipMonitorViewManager.saveTableToFile(): "; - String displayedColumns[] = _precipMonitorTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - String rowData[][] = _precipMonitorTableManager.getDisplayRowDataArray(); - BufferedWriter out = null; - int maxStringLen = 33; - try - { - FileOutputStream fileOutput = new FileOutputStream(fileName, false); - OutputStreamWriter outputStream = new OutputStreamWriter(fileOutput); - out = new BufferedWriter(outputStream); - } - catch(IOException exception) - { - printFileException(exception, header); - } - if(displayedColumns != null) - { - try - { - out.newLine(); - StringBuffer columnNameStringBuffer = new StringBuffer(); - for(int i=0; i < displayedColumns.length; i++) - { - columnNameStringBuffer.append(getTrimmedOrPaddedString(displayedColumns[i], maxStringLen)); - columnNameStringBuffer.append(" |"); - } - out.write(columnNameStringBuffer.toString()); - out.newLine(); - } - catch(IOException exception) - { - printFileException(exception, header); - } - } - try - { - for(int i=0; i < rowData.length; i++) - { - out.newLine(); - StringBuffer dataStringBuffer = new StringBuffer(); - for(int j=0; j < rowData[i].length; j++) - { - dataStringBuffer.append(getTrimmedOrPaddedString(rowData[i][j], maxStringLen)); - dataStringBuffer.append(" |"); - } - out.write(dataStringBuffer.toString()); - } - } - catch(IOException exception) - { - printFileException(exception,header); - } - - try - { - out.close(); - } - catch(IOException exception) - { - _logger.log(header+ "Unable to close file["+ - fileHandler.getAbsolutePath()+"]"); - printFileException(exception, header); - } - } - - private String getTrimmedOrPaddedString(String origString, int desiredLength) - { - String newString = origString; - - String formatString = "%-"+ String.valueOf(desiredLength) +"s"; - - newString = String.format(formatString, origString); - - if (newString.length() > desiredLength) - { - newString = newString.substring(0, desiredLength); - } - - return newString; - } - - private void saveView(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.saveView(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File file = null; - JFileChooser saveFileChooser = new JFileChooser(); - String settingsDir = _appsDefaults.getToken("whfs_report_dir", "/awips/hydroapps/whfs/local/data/report"); - saveFileChooser.setDialogTitle("Export Table To Text File"); - saveFileChooser.setCurrentDirectory(new File(settingsDir)); - saveFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = saveFileChooser.showSaveDialog(_mainFrame); - if(result == JFileChooser.CANCEL_OPTION) - file = null; - else - file = saveFileChooser.getSelectedFile(); - - if(file != null) - { - saveTableToFile(file.toString()); - } - } - - private void changeColumns(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.changeColumns(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _precipMonitorTableManager.invokeColumnSelector(_mainFrame); - - updateSettings(); - } - - private void updateSort(String[] columnNamesToSort,int[] columnSortNumber,boolean[] columnSortOrder) - { - _precipMonitorTableManager.setSortInfoNotBasedOnUserClicks(columnNamesToSort, columnSortOrder, columnSortNumber); - updateSettings(); - } - - private void precipThreatSort(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.precipThreatSort(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = {PrecipColumns.PRECIP_THREAT}; - int columnSortNumber[] = {0}; - boolean columnSortOrder[] = {false}; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void appSort(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.appSort(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = {LocationInfoColumns.HSA, LocationInfoColumns.GROUP_ORDINAL, - LocationInfoColumns.LOCATION_ORDINAL}; - int columnSortNumber[] = {0,1,2}; - boolean columnSortOrder[] = {true, true, true}; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void clearSort() - { - _precipMonitorTableManager.clearSort(); - } - - private void clearSort(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.clearSort(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - clearSort(); - updateSettings(); - } - - private void rowSelected(PrecipMonitorJTableRowData selectedRowData) - { - String header = "PrecipMonitorViewManager.rowSelected(): "; - - System.out.print(header); - send(this, MessageType.VIEW_SELECT_ITEM, selectedRowData); - } - -// ------------------------------------------------------------------------------------- - public String getToolTipForSelectedCell(String columnName, int rowIndex) - { - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData)_precipMonitorTableManager.getSelectedRowData(rowIndex); - String toolTip = ""; - if(columnName.equals(PrecipColumns.PRECIP_THREAT)) - { - toolTip = rowData.getToolTipTextForPrecipThreatSummary(); - } - if(toolTip.length() <= 12) // tooltip has "" only - { - String name = rowData.getName(); - String state = rowData.getState(); - String county = rowData.getCounty(); - String hsa = rowData.getHsa(); - - toolTip = "Name:["+ name+"]\n
"+ - "County: ["+county+"] State: ["+state+"] HSA: ["+hsa+"]\n
"; - } - return toolTip; - } - - private class ChangeColumnsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - changeColumns(message); - } - } - - private class ClearSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - clearSort(message); - } - } - - private class PrecipThreatSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - precipThreatSort(message); - } - } - - private class AppSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - appSort(message); - } - } - - private class SelectViewItemReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - selectViewItem(message); - } - } - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - refreshDisplay(message); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTableAndApplySettings(message); - } - } - - private class UpdateSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - updateSettings(message); - } - } - - private class SaveViewReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveView(message); - } - } - - private class TableListSelectionListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent e) - { - if(e.getValueIsAdjusting() == false) - { - List selectedRowData = _precipMonitorTableManager.getSelectedRowsData(); - for(int i=0; i < selectedRowData.size(); i++) - { - if(i == 0) - { - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData) selectedRowData.get(i); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - } - } - } - } - } - - private class TableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - //String header = "PrecipMonitorViewManager.TableMouseListener.mouseClicked(): "; - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _precipMonitorTableManager.getMousePointedRowIndex(p); - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData) _precipMonitorTableManager.getSelectedRowData(rowIndex); - - if(e.getClickCount() == 2) - { - //System.out.println(header + " starting TSL for " + rowData.getLid()); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, _selectedRowData, 1); - } - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -// ------------------------------------------------------------------------------------- - class TableMouseMotionListener implements MouseMotionListener - { - public void mouseDragged(MouseEvent e) - { - } - public void mouseMoved(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _precipMonitorTableManager.getMousePointedRowIndex(p); - int colIndex = _precipMonitorTableManager.getMousePointedColumnIndex(p); - String columnName = _precipMonitorTableManager.getColumnNameAtIndex(colIndex); - String toolTip=""; - if(rowIndex != -1) - { - toolTip = getToolTipForSelectedCell(columnName, rowIndex); - _precipMonitorTableManager.setRowToolTipText(toolTip); - } - } - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipColumnDataSettings.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipColumnDataSettings.java deleted file mode 100755 index acd05c37f2..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipColumnDataSettings.java +++ /dev/null @@ -1,355 +0,0 @@ -package ohd.hseb.monitor.precip.settings; - -public class PrecipColumnDataSettings -{ - private double _precipAlert1Hr ; - private double _precipAlert3Hr ; - private double _precipAlert6Hr ; - - private double _precipCaution1Hr ; - private double _precipCaution3Hr ; - private double _precipCaution6Hr ; - - private int _ratioAlert1Hr ; - private int _ratioAlert3Hr ; - private int _ratioAlert6Hr ; - - private int _ratioCaution1Hr ; - private int _ratioCaution3Hr ; - private int _ratioCaution6Hr ; - - private double _diffAlert1Hr ; - private double _diffAlert3Hr ; - private double _diffAlert6Hr ; - - private double _diffCaution1Hr ; - private double _diffCaution3Hr ; - private double _diffCaution6Hr ; - - public static final String PRECIP_SETTINGS_BEGIN_TAG = "#Precip Settings Begin"; - public static final String PRECIP_SETTINGS_END_TAG = "#Precip Settings End"; - public static final String PRECIP_ALERT_TAG = "Precip Alert 1Hr | 3Hr | 6Hr"; - public static final String PRECIP_CAUTION_TAG = "Precip Caution 1Hr | 3Hr | 6Hr"; - public static final String RATIO_ALERT_TAG = "Ratio Alert 1Hr | 3Hr | 6Hr"; - public static final String RATIO_CAUTION_TAG = "Ratio Caution 1Hr | 3Hr | 6Hr"; - public static final String DIFF_ALERT_TAG = "Diff Alert 1Hr | 3Hr | 6Hr"; - public static final String DIFF_CAUTION_TAG = "Diff Caution 1Hr | 3Hr | 6Hr"; - - public static double DEFAULT_PRECIP_THRESHOLD_6HR = 1; - public static double DEFAULT_PRECIP_THRESHOLD_3HR = 1.25; - public static double DEFAULT_PRECIP_THRESHOLD_1HR = 1.15; - - public static double DEFAULT_PRECIP_MIN_THRESHOLD_6HR = 0; - public static double DEFAULT_PRECIP_MIN_THRESHOLD_3HR = 0; - public static double DEFAULT_PRECIP_MIN_THRESHOLD_1HR = 0; - - public static double DEFAULT_PRECIP_MAX_THRESHOLD_6HR = 5; - public static double DEFAULT_PRECIP_MAX_THRESHOLD_3HR = 5; - public static double DEFAULT_PRECIP_MAX_THRESHOLD_1HR = 5; - - public static double DEFAULT_DIFF_THRESHOLD_6HR = -0.25; - public static double DEFAULT_DIFF_THRESHOLD_3HR = -0.3; - public static double DEFAULT_DIFF_THRESHOLD_1HR = -0.35; - - public static double DEFAULT_DIFF_MIN_THRESHOLD_6HR = -5; - public static double DEFAULT_DIFF_MIN_THRESHOLD_3HR = -5; - public static double DEFAULT_DIFF_MIN_THRESHOLD_1HR = -5; - - public static double DEFAULT_DIFF_MAX_THRESHOLD_6HR = 5; - public static double DEFAULT_DIFF_MAX_THRESHOLD_3HR = 5; - public static double DEFAULT_DIFF_MAX_THRESHOLD_1HR = 5; - - public static int DEFAULT_RATIO_THRESHOLD_6HR = 90; - public static int DEFAULT_RATIO_THRESHOLD_3HR = 90; - public static int DEFAULT_RATIO_THRESHOLD_1HR = 90; - - public static int DEFAULT_RATIO_MIN_THRESHOLD_6HR = 0; - public static int DEFAULT_RATIO_MIN_THRESHOLD_3HR = 0; - public static int DEFAULT_RATIO_MIN_THRESHOLD_1HR = 0; - - public static int DEFAULT_RATIO_MAX_THRESHOLD_6HR = 400; - public static int DEFAULT_RATIO_MAX_THRESHOLD_3HR = 400; - public static int DEFAULT_RATIO_MAX_THRESHOLD_1HR = 400; - - public PrecipColumnDataSettings() - { - resetSettings(); - } - - public PrecipColumnDataSettings(double precipAlert1Hr, double precipAlert3Hr, double precipAlert6Hr, - double precipCaution1Hr, double precipCaution3Hr, double precipCaution6Hr, - int ratioAlert1Hr, int ratioAlert3Hr ,int ratioAlert6Hr, - int ratioCaution1Hr, int ratioCaution3Hr, int ratioCaution6Hr, - double diffAlert1Hr, double diffAlert3Hr, double diffAlert6Hr, - double diffCaution1Hr ,double diffCaution3Hr, double diffCaution6Hr) - { - _precipAlert1Hr = precipAlert1Hr; - _precipAlert3Hr = precipAlert3Hr; - _precipAlert6Hr = precipAlert6Hr; - - _precipCaution1Hr = precipCaution1Hr; - _precipCaution3Hr = precipCaution3Hr; - _precipCaution6Hr = precipCaution6Hr; - - _ratioAlert1Hr = ratioAlert1Hr; - _ratioAlert3Hr = ratioAlert3Hr; - _ratioAlert6Hr = ratioAlert6Hr; - - _ratioCaution1Hr = ratioCaution1Hr; - _ratioCaution3Hr = ratioCaution3Hr; - _ratioCaution6Hr = ratioCaution6Hr; - - _diffAlert1Hr = diffAlert1Hr; - _diffAlert3Hr = diffAlert3Hr; - _diffAlert6Hr = diffAlert6Hr; - - _diffCaution1Hr = diffCaution1Hr; - _diffCaution3Hr = diffCaution3Hr; - _diffCaution6Hr = diffCaution6Hr; - - } - - public void setPrecipSettings(double precipAlert1Hr, double precipAlert3Hr, double precipAlert6Hr, - double precipCaution1Hr, double precipCaution3Hr, double precipCaution6Hr, - int ratioAlert1Hr, int ratioAlert3Hr ,int ratioAlert6Hr, - int ratioCaution1Hr, int ratioCaution3Hr, int ratioCaution6Hr, - double diffAlert1Hr, double diffAlert3Hr, double diffAlert6Hr, - double diffCaution1Hr ,double diffCaution3Hr, double diffCaution6Hr) - { - _precipAlert1Hr = precipAlert1Hr; - _precipAlert3Hr = precipAlert3Hr; - _precipAlert6Hr = precipAlert6Hr; - - _precipCaution1Hr = precipCaution1Hr; - _precipCaution3Hr = precipCaution3Hr; - _precipCaution6Hr = precipCaution6Hr; - - _ratioAlert1Hr = ratioAlert1Hr; - _ratioAlert3Hr = ratioAlert3Hr; - _ratioAlert6Hr = ratioAlert6Hr; - - _ratioCaution1Hr = ratioCaution1Hr; - _ratioCaution3Hr = ratioCaution3Hr; - _ratioCaution6Hr = ratioCaution6Hr; - - _diffAlert1Hr = diffAlert1Hr; - _diffAlert3Hr = diffAlert3Hr; - _diffAlert6Hr = diffAlert6Hr; - - _diffCaution1Hr = diffCaution1Hr; - _diffCaution3Hr = diffCaution3Hr; - _diffCaution6Hr = diffCaution6Hr; - - } - - public void setPrecipSettings(PrecipColumnDataSettings precipSettings) - { - setPrecipSettings(precipSettings.getPrecipAlert1Hr(), precipSettings.getPrecipAlert3Hr(), precipSettings.getPrecipAlert6Hr(), - precipSettings.getPrecipCaution1Hr(), precipSettings.getPrecipCaution3Hr(), precipSettings.getPrecipCaution6Hr(), - precipSettings.getRatioAlert1Hr(), precipSettings.getRatioAlert3Hr (),precipSettings.getRatioAlert6Hr(), - precipSettings.getRatioCaution1Hr(), precipSettings.getRatioCaution3Hr(), precipSettings.getRatioCaution6Hr(), - precipSettings.getDiffAlert1Hr(), precipSettings.getDiffAlert3Hr(), precipSettings.getDiffAlert6Hr(), - precipSettings.getDiffCaution1Hr (),precipSettings.getDiffCaution3Hr(), precipSettings.getDiffCaution6Hr()); - } - - public void resetSettings() - { - _precipAlert1Hr = DEFAULT_PRECIP_THRESHOLD_1HR; - _precipAlert3Hr = DEFAULT_PRECIP_THRESHOLD_3HR; - _precipAlert6Hr = DEFAULT_PRECIP_THRESHOLD_6HR; - - _precipCaution1Hr = DEFAULT_PRECIP_THRESHOLD_1HR; - _precipCaution3Hr = DEFAULT_PRECIP_THRESHOLD_3HR; - _precipCaution6Hr = DEFAULT_PRECIP_THRESHOLD_6HR; - - _ratioAlert1Hr = DEFAULT_RATIO_THRESHOLD_1HR; - _ratioAlert3Hr = DEFAULT_RATIO_THRESHOLD_3HR; - _ratioAlert6Hr = DEFAULT_RATIO_THRESHOLD_6HR; - - _ratioCaution1Hr = DEFAULT_RATIO_THRESHOLD_1HR; - _ratioCaution3Hr = DEFAULT_RATIO_THRESHOLD_3HR; - _ratioCaution6Hr = DEFAULT_RATIO_THRESHOLD_6HR; - - _diffAlert1Hr = DEFAULT_DIFF_THRESHOLD_1HR; - _diffAlert3Hr = DEFAULT_DIFF_THRESHOLD_3HR; - _diffAlert6Hr = DEFAULT_DIFF_THRESHOLD_6HR; - - _diffCaution1Hr = DEFAULT_DIFF_THRESHOLD_1HR; - _diffCaution3Hr = DEFAULT_DIFF_THRESHOLD_3HR; - _diffCaution6Hr = DEFAULT_DIFF_THRESHOLD_6HR; - } - - public double getDiffAlert1Hr() - { - return _diffAlert1Hr; - } - public void setDiffAlert1Hr(double diffAlert1Hr) - { - _diffAlert1Hr = diffAlert1Hr; - } - public double getDiffAlert3Hr() - { - return _diffAlert3Hr; - } - public void setDiffAlert3Hr(double diffAlert3Hr) - { - _diffAlert3Hr = diffAlert3Hr; - } - public double getDiffAlert6Hr() - { - return _diffAlert6Hr; - } - public void setDiffAlert6Hr(double diffAlert6Hr) - { - _diffAlert6Hr = diffAlert6Hr; - } - public double getDiffCaution1Hr() - { - return _diffCaution1Hr; - } - public void setDiffCaution1Hr(double diffCaution1Hr) - { - _diffCaution1Hr = diffCaution1Hr; - } - public double getDiffCaution3Hr() - { - return _diffCaution3Hr; - } - public void setDiffCaution3Hr(double diffCaution3Hr) - { - _diffCaution3Hr = diffCaution3Hr; - } - public double getDiffCaution6Hr() - { - return _diffCaution6Hr; - } - public void setDiffCaution6Hr(double diffCaution6Hr) - { - _diffCaution6Hr = diffCaution6Hr; - } - public double getPrecipAlert1Hr() - { - return _precipAlert1Hr; - } - public void setPrecipAlert1Hr(double precipAlert1Hr) - { - _precipAlert1Hr = precipAlert1Hr; - } - public double getPrecipAlert3Hr() - { - return _precipAlert3Hr; - } - public void setPrecipAlert3Hr(double precipAlert3Hr) - { - _precipAlert3Hr = precipAlert3Hr; - } - public double getPrecipAlert6Hr() - { - return _precipAlert6Hr; - } - public void setPrecipAlert6Hr(double precipAlert6Hr) - { - _precipAlert6Hr = precipAlert6Hr; - } - public double getPrecipCaution1Hr() - { - return _precipCaution1Hr; - } - public void setPrecipCaution1Hr(double precipCaution1Hr) - { - _precipCaution1Hr = precipCaution1Hr; - } - public double getPrecipCaution3Hr() - { - return _precipCaution3Hr; - } - public void setPrecipCaution3Hr(double precipCaution3Hr) - { - _precipCaution3Hr = precipCaution3Hr; - } - public double getPrecipCaution6Hr() - { - return _precipCaution6Hr; - } - public void setPrecipCaution6Hr(double precipCaution6Hr) - { - _precipCaution6Hr = precipCaution6Hr; - } - public int getRatioAlert1Hr() - { - return _ratioAlert1Hr; - } - public void setRatioAlert1Hr(int ratioAlert1Hr) - { - _ratioAlert1Hr = ratioAlert1Hr; - } - public int getRatioAlert3Hr() - { - return _ratioAlert3Hr; - } - public void setRatioAlert3Hr(int ratioAlert3Hr) - { - _ratioAlert3Hr = ratioAlert3Hr; - } - public int getRatioAlert6Hr() - { - return _ratioAlert6Hr; - } - public void setRatioAlert6Hr(int ratioAlert6Hr) - { - _ratioAlert6Hr = ratioAlert6Hr; - } - public int getRatioCaution1Hr() - { - return _ratioCaution1Hr; - } - public void setRatioCaution1Hr(int ratioCaution1Hr) - { - _ratioCaution1Hr = ratioCaution1Hr; - } - public int getRatioCaution3Hr() - { - return _ratioCaution3Hr; - } - public void setRatioCaution3Hr(int ratioCaution3Hr) - { - _ratioCaution3Hr = ratioCaution3Hr; - } - public int getRatioCaution6Hr() - { - return _ratioCaution6Hr; - } - public void setRatioCaution6Hr(int ratioCaution6Hr) - { - _ratioCaution6Hr = ratioCaution6Hr; - } - - public PrecipColumnDataSettings getMenuSettings() - { - return this; - } - - public String toString() - { - String result = _precipAlert1Hr + "|" + - _precipAlert3Hr + "|" + - _precipAlert6Hr + "|" + - _precipCaution1Hr + "|" + - _precipCaution3Hr + "|" + - _precipCaution6Hr + "|" + - _ratioAlert1Hr + "|" + - _ratioAlert3Hr + "|" + - _ratioAlert6Hr + "|" + - _ratioCaution1Hr + "|" + - _ratioCaution3Hr + "|" + - _ratioCaution6Hr + "|" + - _diffAlert1Hr + "|" + - _diffAlert3Hr + "|" + - _diffAlert6Hr + "|" + - _diffCaution1Hr + "|" + - _diffCaution3Hr + "|" + - _diffCaution6Hr ; - - return result; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorMenuSettings.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorMenuSettings.java deleted file mode 100755 index 859ac66164..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorMenuSettings.java +++ /dev/null @@ -1,81 +0,0 @@ -package ohd.hseb.monitor.precip.settings; - -import ohd.hseb.util.BooleanHolder; - -public class PrecipMonitorMenuSettings -{ - private int _refreshInterval; - - public static final String REFRESH_INTERVAL_TAG = "RefreshInterval"; - - public static final String SHOW_MISSING_PRECIP_TAG = "ShowMissingPrecip"; - - public static int DEFAULT_REFRESH_INTERVAL = 15; - - private BooleanHolder _showMissingPrecipBooleanHolder = new BooleanHolder(true); - - private PrecipColumnDataSettings _precipSettings; - - public PrecipMonitorMenuSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingPrecip(false); - _precipSettings = new PrecipColumnDataSettings(); - } - - public void resetSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingPrecip(false); - _precipSettings.resetSettings(); - } - - public PrecipMonitorMenuSettings(int refreshInterval, boolean showMissingPrecip) - { - _refreshInterval = refreshInterval; - setShowMissingPrecip(showMissingPrecip); - _precipSettings = new PrecipColumnDataSettings(); - } - - public void setPrecipSettings(PrecipColumnDataSettings precipSettings) - { - _precipSettings = precipSettings; - } - - public PrecipColumnDataSettings getPrecipSettings() - { - return _precipSettings; - } - - public boolean shouldShowMissingPrecip() - { - return _showMissingPrecipBooleanHolder.getValue(); - } - - public void setShowMissingPrecip(boolean showMissingPrecip) - { - _showMissingPrecipBooleanHolder.setValue(showMissingPrecip); - } - - public void setRefreshInterval(int refreshInterval) - { - _refreshInterval = refreshInterval; - } - - public int getRefreshInterval() - { - return _refreshInterval; - } - - private void setShowMissingPrecipBooleanHolder(BooleanHolder showMissingPrecipBooleanHolder) - { - _showMissingPrecipBooleanHolder = showMissingPrecipBooleanHolder; - } - - public BooleanHolder getShowMissingPrecipBooleanHolder() - { - return _showMissingPrecipBooleanHolder; - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorSettingsFileManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorSettingsFileManager.java deleted file mode 100755 index a51f2a1d89..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorSettingsFileManager.java +++ /dev/null @@ -1,241 +0,0 @@ -package ohd.hseb.monitor.precip.settings; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.MonitorSettingsFileManager; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; - -public class PrecipMonitorSettingsFileManager extends MonitorSettingsFileManager -{ - private PrecipMonitorMenuSettings _menuSettings; - - public PrecipMonitorSettingsFileManager(SessionLogger logger, ViewSettings viewSettings, - FilterSettings filterSettings, PrecipMonitorMenuSettings menuSettings) - { - super(logger, "#PrecipMonitorSettings File", viewSettings, filterSettings); - _menuSettings = menuSettings; - _logger = logger; - createDisplayTokenSet(); - createMenuTokenSet(); - } - - public Set createMenuTokenSet() - { - _menuTokenSet = new HashSet(); - - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_CAUTION_TAG); - _menuTokenSet.add(PrecipMonitorMenuSettings.REFRESH_INTERVAL_TAG); - _menuTokenSet.add(PrecipMonitorMenuSettings.SHOW_MISSING_PRECIP_TAG); - - return _displayTokenSet; - } - - public boolean setSettingsFromFile(File fileHandler) - { - String header = "PrecipMonitorSettingsFileManager.setSettingsFromFile(): "; - boolean isReadCompleted = true; - - resetSettings(); - - if(isValidSettingsFile(_logger, fileHandler, _settingsFileBeginTag )) - { - BufferedReader in = null; - String line; - try - { - in = new BufferedReader(new FileReader(fileHandler)); - - while(( line = in.readLine()) != null) - { - line = line.trim(); - processLine(line); - } - - } - catch(IOException e) - { - printFileException(_logger, e,header); - isReadCompleted = false ; - } - } - else - { - isReadCompleted = false; - } - - setViewAndFilterSettings(); - return isReadCompleted; - } - - private void resetSettings() - { - _tableDisplaySettingsList = null; - _expandPathTokenValuesList = null; - _pathTokenValuesList = null; - - setViewAndFilterSettings(); - _menuSettings.resetSettings(); - } - - - public void saveSettingsToFile(File fileHandler) - { - createSettingsFile(fileHandler); - - BufferedWriter out = null; - String header = "PrecipMonitorSettingsFileManager.saveSettingsToFile(): "; - try - { - out = new BufferedWriter(new FileWriter(fileHandler)); - } - catch(IOException exception) - { - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - } - - saveDisplaySettings(out); - - saveMenuSettingsToFile(out); - } - - public void processMenuToken(String tokenName, String tokenValue) - { - if(tokenName.compareTo(PrecipMonitorMenuSettings.REFRESH_INTERVAL_TAG) == 0) - { - _menuSettings.setRefreshInterval(new Integer(tokenValue)); - System.out.println("Setting in menu refresh interval:" + tokenValue); - } - if(tokenName.compareTo(PrecipMonitorMenuSettings.SHOW_MISSING_PRECIP_TAG) == 0) - { - _menuSettings.setShowMissingPrecip(new Boolean(tokenValue)); - System.out.println("Setting Show Missing Precip Flag:" + tokenValue); - } - else - { - String spiltStr[] = tokenValue.split("\\|"); - String hr1, hr3, hr6; - - if(spiltStr != null) - { - if(spiltStr.length == 3) // we have 3 values 1hr | 3hr | 6hr correctly - { - hr1 = null; hr3 = null; hr6 = null; - - hr1 = spiltStr[0].trim(); - hr3 = spiltStr[1].trim(); - hr6 = spiltStr[2].trim(); - - if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipCaution6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioAlert1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioAlert3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioAlert6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioCaution1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioCaution3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioCaution6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffCaution6Hr(new Double(hr6)); - } - } - } - } - } - - public void saveMenuSettingsToFile(BufferedWriter writer) - { - String header = "PrecipMonitorSettingsFileManager.saveMenuSettingsToFile(): "; - try - { - if(_menuSettings != null) - { - writer.newLine(); - writer.write(PrecipMonitorMenuSettings.REFRESH_INTERVAL_TAG + " : " + _menuSettings.getRefreshInterval()); - writer.newLine(); - - writer.newLine(); - writer.write(PrecipMonitorMenuSettings.SHOW_MISSING_PRECIP_TAG + " : " + _menuSettings.shouldShowMissingPrecip()); - writer.newLine(); - - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_BEGIN_TAG); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getRatioAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getDiffAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert6Hr() ); - writer.newLine(); - - writer.write(PrecipColumnDataSettings.PRECIP_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getRatioCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getDiffCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_END_TAG); - - writer.close(); - } - } - catch(IOException exception) - { - printFileException(_logger, exception,header); - } - - } - - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/LookBackTimeDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/LookBackTimeDialog.java deleted file mode 100755 index 45f8ac64a8..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/LookBackTimeDialog.java +++ /dev/null @@ -1,152 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.river.settings.RiverColumnDataSettings; -import ohd.hseb.util.gui.WindowResizingManager; - -public class LookBackTimeDialog extends JDialog -{ - private JSpinner _timeSpinBox; - private JLabel _validTimeLabel; - private JButton _closeButton; - private String _settingsTokenName; - private RiverColumnDataSettings _riverSettings; - - public LookBackTimeDialog( MonitorFrame mainFrame, RiverColumnDataSettings riverSettings, - String dialogTitle, - JLabel label, - String settingsTokenName, - int maxNumOfHrs, - int minNumOfHrs) - { - super(mainFrame, true); - _settingsTokenName = settingsTokenName; - _riverSettings = riverSettings; - this.setTitle(dialogTitle); - createDialogComponents(label, maxNumOfHrs, minNumOfHrs); - this.pack(); - this.setVisible(true); - } - - public void createDialogComponents(JLabel label, int maxNumOfHrs, int minNumOfHrs) - { - _validTimeLabel = label; - int incrNumOfHrs = 1; - int initialNumOfHrs = 1; - - if(_settingsTokenName.equals(RiverColumnDataSettings.VALID_TIME_TAG)) - initialNumOfHrs = _riverSettings.getAlertAlarmLookBack(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG)) - initialNumOfHrs = _riverSettings.getVtecEventProductTimeLookBack(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG)) - initialNumOfHrs = _riverSettings.getVtecEventEndTimeApproach(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG)) - initialNumOfHrs = _riverSettings.getUgcExpireTimeApproach(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG)) - initialNumOfHrs = _riverSettings.getLatestFcstBasisTimeLookBack(); - else // LatestObs_Time - initialNumOfHrs = _riverSettings.getLatestObsLookBack(); - - SpinnerModel spinnerModel = new SpinnerNumberModel(initialNumOfHrs, - minNumOfHrs, - maxNumOfHrs, - incrNumOfHrs); - - _timeSpinBox = new JSpinner(spinnerModel); - JPanel spinnerPanel = new JPanel(); - spinnerPanel.setLayout(new GridLayout(3,1)); - spinnerPanel.add(createDummyPanel()); - spinnerPanel.add(_timeSpinBox); - spinnerPanel.add(createDummyPanel()); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(1,3)); - infoPanel.add(_validTimeLabel); - infoPanel.add(spinnerPanel); - infoPanel.add(createDummyPanel()); - - _closeButton = new JButton("Close"); - JPanel closePanel = new JPanel(); - closePanel.setLayout(new GridLayout(3,1)); - closePanel.add(createDummyPanel()); - closePanel.add(_closeButton); - closePanel.add(createDummyPanel()); - - JPanel actionPanel = new JPanel(); - actionPanel.setLayout(new GridLayout(1,3)); - actionPanel.add(createDummyPanel()); - actionPanel.add(closePanel); - actionPanel.add(createDummyPanel()); - - JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(2,1)); - panel.add(infoPanel); - panel.add(actionPanel); - - this.setLocation(25, 25); - Dimension dim = new Dimension(300,200); - new WindowResizingManager(this, dim, dim); - this.getContentPane().add(panel); - - CloseButtonListener closeButtonListener = new CloseButtonListener(); - _closeButton.addActionListener(closeButtonListener); - - DialogListener dialogListener = new DialogListener(); - this.addWindowListener(dialogListener); - } - - private JPanel createDummyPanel() - { - JPanel dummyPanel = new JPanel(); - return dummyPanel; - } - - private void closeTimeDialog() - { - this.setVisible(false); - - if(_settingsTokenName.equals(RiverColumnDataSettings.VALID_TIME_TAG)) - _riverSettings.setAlertAlarmLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG)) - _riverSettings.setVtecEventProductTimeLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG)) - _riverSettings.setVtecEventEndTimeApproach(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG)) - _riverSettings.setUgcExpireTimeApproach(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG)) - _riverSettings.setLatestFcstBasisTimeLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - else // LatestObs_Time - _riverSettings.setLatestObsLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - } - - class CloseButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeTimeDialog(); - } - } - - class DialogListener extends WindowAdapter - { - public void windowClosing(WindowEvent e) - { - closeTimeDialog(); - } - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverColumns.java deleted file mode 100755 index 28f9721f11..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverColumns.java +++ /dev/null @@ -1,104 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class RiverColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String GROUP_NAME = "Group Name"; - public static final String LOCATION_ID = "Location Id"; - public static final String LOCATION_NAME = "Location Name"; - public static final String HSA = "HSA"; - public static final String GROUP_ORDINAL = "Group Ordinal"; - public static final String LOCATION_ORDINAL = "Location Ordinal"; - public static final String COUNTY = "County"; - public static final String STATE = "State"; - public static final String STREAM = "Stream"; - public static final String RIVER_BASIN = "River Basin"; - public static final String BANK_FULL = "Bank Full"; - - public static final String PRIMARY_RIVER_PE = "Primary River PE"; - - public static final String FLD_STG = "Flood Stage"; - public static final String ACT_STG = "Action Stage"; - public static final String FLD_FLOW = "Flood Flow"; - public static final String ACT_FLOW = "Action Flow"; - public static final String MIN_STG = "Minor Stage"; - public static final String MAJ_STG = "Major Stage"; - public static final String MOD_STG = "Moderate Stage"; - public static final String LAT_OBS_VALUE = "LatestObs Value"; - public static final String LAT_OBS_TIME = "LatestObs Time"; - public static final String MAX_FCST_VALUE = "MaxFcst Value"; - public static final String MAX_FCST_VALID_TIME = "MaxFcst ValidTime"; - public static final String MAX_FCST_BASIS_TIME = "MaxFcst BasisTime"; - public static final String OBSFCST_MAX = "ObsFcstMax"; - public static final String LAT_STG_VALUE = "Latest StgValue"; - public static final String LAT_STG_TIME = "Latest StgTime";; - public static final String LAT_FLOW_VALUE = "Latest FlowValue"; - public static final String LAT_FLOW_TIME = "Latest FlowTime"; - public static final String FLD_STG_DEP = "FldStg Departure"; - public static final String ACT_STG_DEP = "ActStg Departure"; - public static final String THREAT = "Threat"; - public static final String ALERT_ALARM = "AlertAlarm"; - public static final String VTEC_SUMMARY = "VTEC Summary"; - public static final String EVENT_END_TIME = "Event EndTime"; - public static final String UGC_EXPIRE_TIME = "UGCExpire Time"; - public static final String SSHP_MAX_FCST_VALUE = "SSHP MaxFcstValue"; - public static final String SSHP_MAX_FCST_VALID_TIME = "SSHP MaxFcstValidTime"; - public static final String SSHP_FCST_BASIS_TIME = "SSHP FcstBasisTime"; - public static final String SSHP_FCST_FLD_TIME = "SSHP FcstFloodTime"; - - - public List getRiverColumnsList(List riverMonitorColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - String timeAlignment = "center"; - - if(riverMonitorColumnDescriptorList == null) - { - riverMonitorColumnDescriptorList = new ArrayList(); - riverMonitorColumnDescriptorList = new LocationInfoColumns().getLocationInfoColumnsList(riverMonitorColumnDescriptorList); - riverMonitorColumnDescriptorList = new PrecipColumns().getPrecipColumnsList(riverMonitorColumnDescriptorList); - } - - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PRIMARY_RIVER_PE, textAlignment, "Primary River PE")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(STREAM, textAlignment, "Stream Name")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(BANK_FULL, numberAlignment, "Bank Full Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(FLD_STG, numberAlignment, "Flood Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ACT_STG, numberAlignment, "Warning Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(FLD_FLOW, numberAlignment, "Flood Flow")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ACT_FLOW, numberAlignment, "Action Flow")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MIN_STG, numberAlignment, "Minor Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAJ_STG, numberAlignment, "Major Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MOD_STG, numberAlignment, "Moderate Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_OBS_VALUE, numberAlignment, "Latest Observed Value")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_OBS_TIME, timeAlignment, "Latest Observed Time")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAX_FCST_VALUE, numberAlignment, "MaxFcst Value")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAX_FCST_VALID_TIME, timeAlignment, "MaxFcst ValidTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAX_FCST_BASIS_TIME, timeAlignment, "MaxFcst BasisTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(OBSFCST_MAX, numberAlignment, "ObsFcstMax")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_STG_VALUE, numberAlignment, "Latest StgValue")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_STG_TIME, timeAlignment, "Latest StgTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_FLOW_VALUE, numberAlignment, "Latest FlowValue")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_FLOW_TIME, timeAlignment, "Latest FlowTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(FLD_STG_DEP, numberAlignment, "FldStg Departure")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ACT_STG_DEP, numberAlignment, "ActStg Departure")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(THREAT, textAlignment,"Threat")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ALERT_ALARM, textAlignment, "AlertAlarm")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(VTEC_SUMMARY, textAlignment, "VTEC Summary")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(EVENT_END_TIME, timeAlignment, "Event EndTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(UGC_EXPIRE_TIME, timeAlignment, "UGCExpire Time")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_MAX_FCST_VALUE, numberAlignment, "SSHP MaxFcstValue")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_MAX_FCST_VALID_TIME, timeAlignment, "SSHP MaxFcstValidTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_FCST_BASIS_TIME, timeAlignment, "SSHP FcstBasisTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_FCST_FLD_TIME, timeAlignment, "SSHP FcstFloodTime")); - - return riverMonitorColumnDescriptorList; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverLocationDataFilter.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverLocationDataFilter.java deleted file mode 100755 index d5ba53ac51..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverLocationDataFilter.java +++ /dev/null @@ -1,74 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTable; -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.util.BooleanHolder; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class RiverLocationDataFilter extends LocationDataFilter -{ - - private BooleanHolder _showMissingBooleanHolder = null; - - public RiverLocationDataFilter(Map locationDisplayMap, BooleanHolder showMissingBooleanHolder) - { - _locationDisplayMap = locationDisplayMap; - _showMissingBooleanHolder = showMissingBooleanHolder; - } - - - public List filter(List allRowDataList) - { - boolean showMissing = _showMissingBooleanHolder.getValue(); - List filteredRowDataList = new ArrayList(); - - if (_locationDisplayMap != null) - { - for (int i = 0; i < allRowDataList.size(); i++) - { - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) allRowDataList.get(i); - String lid = rowData.getLid(); - Boolean shouldDisplay = _locationDisplayMap.get(lid); - if ((shouldDisplay != null) && (shouldDisplay) ) //based on selection in the tree - { - // String header = "RiverLocationDataFilter.filter(): "; - // System.out.println(header + " lid = " + lid + "hsa = " + rowData.getHsa() + " groupId = " + rowData.getGroupId()); - - if (showMissing) //based on menu selection - { - filteredRowDataList.add(rowData); - } - else //don't show missing - { - if (isDataAvailable(rowData)) - { - filteredRowDataList.add(rowData); - } - } - } //end if shouldDisplay - } //end for - - } //end if (_locationDisplayMap != null) - return filteredRowDataList; - } - - private boolean isDataAvailable(RiverMonitorJTableRowData rowData) - { - boolean result = false; - - if (rowData.getLatestObsValue() != DbTable.getNullDouble() || - rowData.getMaxFcstValue() != DbTable.getNullDouble()) - { - result = true; - } - - return result; - } - - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorDataManager.java deleted file mode 100755 index e38f7d2c6b..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorDataManager.java +++ /dev/null @@ -1,1691 +0,0 @@ -package ohd.hseb.monitor.river; - -import static ohd.hseb.util.TimeHelper.MILLIS_PER_HOUR; - -import java.awt.Color; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.AdminRecord; -import ohd.hseb.ihfsdb.generated.AdminTable; -import ohd.hseb.ihfsdb.generated.AlertAlarmValRecord; -import ohd.hseb.ihfsdb.generated.AlertAlarmValTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LocRiverMonRecord; -import ohd.hseb.ihfsdb.generated.LocRiverMonView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RiverStatusRecord; -import ohd.hseb.ihfsdb.generated.RiverStatusTable; -import ohd.hseb.ihfsdb.generated.ShefPeRecord; -import ohd.hseb.ihfsdb.generated.ShefPeTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.ihfsdb.generated.VTECeventTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.monitor.TreeFilterManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.precip.PrecipData; -import ohd.hseb.monitor.precip.PrecipDataManager; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.rivermonlocgroup.RiverMonLocGroupDataManager; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeSeriesFileManager; - -import org.apache.bsf.BSFEngine; -import org.apache.bsf.BSFManager; - -import com.raytheon.uf.common.ohd.AppsDefaults; - - -public class RiverMonitorDataManager { - private Database _db; - - private AppsDefaults _appsDefaults; - - private SessionLogger _logger; - - private String _defaultHsa; - - private Set _riverLidSet = null; - - private String _peConfigFileName; - - private List _validHeightAndDischargePEList; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private List _derivedColumnsList; - - private BSFManager _bsfManager; - - private BSFEngine _beanShellEngine; - - private String _missingRepresentation; - - private List _riverMonitorRowDataList; - - private List _missingRiverMonitorRowDataList = new ArrayList(); - - private Map _lidToRiverBasinMap = new HashMap(); - - private Map _lidDescDetailsMap; - - private TreeFilterManager _treeFilterManager; - - private String _lidOfCurrentInterest; - - private RiverMonitorMenuSettings _menuSettings; - - private RiverMonLocGroupDataManager _riverMonLocGroupDataManager; - - private OfficeNotesDataManager _officeNotesDataManager; - - private Map _sshpLidFcstMap; - - private String _sshpFcstDataDir; - - private PrecipDataManager _precipDataManager; - - private Map _lidHeightPEMap = null; - - private Map _lidDischargePEMap = null; - - public RiverMonitorDataManager(Database db, AppsDefaults appsDefaults, - String missingRepresentation, SessionLogger logger, - RiverMonitorMenuSettings menuSettings, - DerivedColumnsFileManager derivedColumnsFileManager) { - _appsDefaults = appsDefaults; - _menuSettings = menuSettings; - _db = db; - _missingRepresentation = missingRepresentation; - _logger = logger; - - readValidHeightAndDischargePE(); - _precipDataManager = new PrecipDataManager(_db, _appsDefaults, - _missingRepresentation, _logger); - - _sshpFcstDataDir = _appsDefaults - .getToken("sshp_background_forecast_output_dir", - "/awips2/awipsShare/hydroapps/whfs/local/data/sshp/forecast"); - String settingsDir = _appsDefaults - .getToken("rivermon_config_dir", - "/awips2/awipsShare/hydroapps/whfs/local/data/app/rivermon"); - - _peConfigFileName = settingsDir + "/" + "RiverMonitorPEConfig.txt"; - - readAdminTable(); - _derivedColumnsFileManager = derivedColumnsFileManager; - - _riverMonLocGroupDataManager = new RiverMonLocGroupDataManager(db, - _logger, missingRepresentation, getDefaultHsa()); - - _officeNotesDataManager = new OfficeNotesDataManager(db, _logger, - missingRepresentation); - - try { - initializeBSF(); - } catch (Exception e) { - _logger.log("PrecipMonitorDataManager.PrecipMonitorDataManager(): Error while initialize BSF..." - + e); - } - } - - public RiverMonLocGroupDataManager getRiverMonLocGroupDataManager() { - return _riverMonLocGroupDataManager; - } - - public OfficeNotesDataManager getOfficeNotesDataManager() { - return _officeNotesDataManager; - } - - public TreeFilterManager getTreeFilterManager() { - if (_treeFilterManager == null) { - _treeFilterManager = new TreeFilterManager(_logger, - getLocationDataFilter()); - } - return _treeFilterManager; - } - - public void setLidOfCurrentInterest(String lid) { - _lidOfCurrentInterest = lid; - } - - public String getLidOfCurrentInterest() { - return _lidOfCurrentInterest; - } - - public long getPdcUpdateTime() { - return _precipDataManager.getPdcFileUpdateLongTime(); - } - - public long getDisplayedRecordCount() { - - List selectedRowDataList = getTreeFilterManager().filter( - _riverMonitorRowDataList); - long displayedCount = selectedRowDataList.size(); - - return displayedCount; - } - - public void disconnect() { - _db.disconnect(); - } - - private void printLocationCounts(String header) { - System.out.println(header + "There are " - + _riverMonitorRowDataList.size() + " displayed with " - + _missingRiverMonitorRowDataList.size() - + " non-displayed missing locations."); - - } - - public Map getLidToCriticalColorMap() { - String header = "RiverMonitorDataManager.getLidToCriticalColorMap(): "; - - Map lidToCriticalColorMap = new HashMap(); - - for (RiverMonitorJTableRowData rowData : _riverMonitorRowDataList) { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - for (RiverMonitorJTableRowData rowData : _missingRiverMonitorRowDataList) { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - return lidToCriticalColorMap; - } - - private void readAdminTable() { - AdminTable adminTable = new AdminTable(_db); - List adminList = null; - try { - adminList = adminTable.select(""); - } catch (SQLException e) { - logSQLException(e); - } - _defaultHsa = ((AdminRecord) adminList.get(0)).getHsa(); - } - - protected void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - private LocationDataFilter getLocationDataFilter() { - RiverLocationDataFilter locationDataFilter; - List lidList = getLidList(); - Map locationDisplayMap = new HashMap(); - - for (String lid : lidList) { - locationDisplayMap.put(lid, false); - } - - locationDataFilter = new RiverLocationDataFilter(locationDisplayMap, - _menuSettings.getShowMissingDataBooleanHolder()); - return locationDataFilter; - } - - public List getLidList() { - List lidList = new ArrayList(); - for (RiverMonitorJTableRowData rowData : _riverMonitorRowDataList) { - String lid = rowData.getLid(); - lidList.add(lid); - } - return lidList; - } - - // --------------------------------------------------------------------------------------------------- - - private void initializeBSF() throws Exception { - _bsfManager = new BSFManager(); - BSFManager.registerScriptingEngine("beanshell", - "bsh.util.BeanShellBSFEngine", null); - _beanShellEngine = _bsfManager.loadScriptingEngine("beanshell"); - } - - // --------------------------------------------------------------------------------------------------- - - protected void getDerivedColumnsInfo( - RiverMonitorJTableRowData riverMonitorRowData) { - if (_derivedColumnsList != null) { - try { - _bsfManager.declareBean("row", riverMonitorRowData, - RiverMonitorJTableRowData.class); - _bsfManager.declareBean("precip", - riverMonitorRowData.getPrecipData(), PrecipData.class); - for (int j = _derivedColumnsList.size() - 1; j >= 0; j--) { - DerivedColumn derivedColumnDesc = (DerivedColumn) _derivedColumnsList - .get(j); - String equationForCellValue = ((String) derivedColumnDesc - .getEquationForCellValue()); - - Object returnValueForCell = _beanShellEngine.eval( - "rowtest", 1, 1, equationForCellValue); - if (derivedColumnDesc.getReturnType().equalsIgnoreCase( - "double")) { - double value = roundTo2DecimalPlaces(Double - .parseDouble(returnValueForCell.toString())); - derivedColumnDesc.setvalue(Double.valueOf(value)); - } else - derivedColumnDesc.setvalue(returnValueForCell); - - String equationForCellColor = ((String) derivedColumnDesc - .getEquationForCellColor()); - Object returnColorForCell = _beanShellEngine.eval( - "rowtest", 1, 1, equationForCellColor); - if (returnColorForCell != null) - derivedColumnDesc - .setCellBackgroundColor(returnColorForCell - .toString()); - } - _bsfManager.undeclareBean("row"); - _bsfManager.undeclareBean("precip"); - } catch (Exception e) { - e.printStackTrace(); - } - } - riverMonitorRowData.setDerivedColumnsDetailsList(_derivedColumnsList); - } - - public void alterRiverMonitorRowDataListBasedOnMissingPrecipFilter() { - _missingRiverMonitorRowDataList.clear(); - - if (!_menuSettings.shouldShowMissingRiver()) // show missing river is - // set to false(ie., skip - // missing river) - { - List finalRiverMonitorRowDataList = new ArrayList(); - - // for each point, check to see if it has some data, if so, then add - // it to the list. - // at the end, replace the _riverMonitorRowDataList with the - // filtered list. - for (RiverMonitorJTableRowData riverMonitorRowData : _riverMonitorRowDataList) { - if (riverMonitorRowData.getLatestObsValue() != DbTable - .getNullDouble() - || riverMonitorRowData.getMaxFcstValue() != DbTable - .getNullDouble()) { - finalRiverMonitorRowDataList.add(riverMonitorRowData); - } else { - // add to the missing list so that the - // RiverMonitorDataManager.getLidToCriticalColorMap() method - // can - // give a complete list - _missingRiverMonitorRowDataList.add(riverMonitorRowData); - } - } - _riverMonitorRowDataList = finalRiverMonitorRowDataList; - finalRiverMonitorRowDataList = null; - Runtime.getRuntime().gc(); - } - } - - /** - * Reads the locrivermon view and creates the list of - * RiverMonitorJtableRowdata objects for each location and fills in its - * name, state , county info - * - * @return - */ - public List readRiverLocationInfo() { - if (_riverLidSet == null) - _riverLidSet = new HashSet(); - else - _riverLidSet.clear(); - - if (_riverMonitorRowDataList != null) { - for (RiverMonitorJTableRowData riverMonitorRowData : _riverMonitorRowDataList) { - riverMonitorRowData.resetCellMap(); - } - _riverMonitorRowDataList.clear(); - } - - Runtime.getRuntime().gc(); - List riverMonitorRowDataList = new ArrayList(); - - LocRiverMonView locRivermonView = new LocRiverMonView(_db); - List locRiverMonRecordList; - - loadRiverBasinData(); - - try { - String whereClause = "order by lid"; - locRiverMonRecordList = locRivermonView.select(whereClause); - if (locRiverMonRecordList != null) { - for (LocRiverMonRecord locRiverMonRecord : locRiverMonRecordList) { - RiverMonitorJTableRowData riverMonitorRowData = new RiverMonitorJTableRowData( - _missingRepresentation, this, _logger, - _menuSettings); - riverMonitorRowData.setLid(locRiverMonRecord.getLid()); - - riverMonitorRowData.setName(locRiverMonRecord.getName()); - riverMonitorRowData - .setCounty(locRiverMonRecord.getCounty()); - riverMonitorRowData.setState(locRiverMonRecord.getState()); - riverMonitorRowData - .setStream(locRiverMonRecord.getStream()); - - String primaryRiverPe = locRiverMonRecord.getPrimary_pe(); - if (primaryRiverPe == null || primaryRiverPe.length() < 2) { - primaryRiverPe = "HG"; - } - riverMonitorRowData.setPrimaryRiverPe(primaryRiverPe); - - riverMonitorRowData - .setBankFull(roundTo2DecimalPlaces(locRiverMonRecord - .getBankfull())); - - if (locRiverMonRecord.getFlood_stage() == 0.0) { - riverMonitorRowData.setFloodStage(DbTable - .getNullDouble()); - } else { - riverMonitorRowData - .setFloodStage(roundTo2DecimalPlaces(locRiverMonRecord - .getFlood_stage())); - } - - if (locRiverMonRecord.getAction_stage() == 0.0) { - riverMonitorRowData.setActionStage(DbTable - .getNullDouble()); - } else { - riverMonitorRowData - .setActionStage(roundTo2DecimalPlaces(locRiverMonRecord - .getAction_stage())); - } - - if (locRiverMonRecord.getAction_flow() == 0.0) { - riverMonitorRowData.setActionFlow(DbTable - .getNullDouble()); - } else { - riverMonitorRowData - .setActionFlow(roundTo2DecimalPlaces(locRiverMonRecord - .getAction_flow())); - } - - if (locRiverMonRecord.getFlood_flow() == 0.0) { - riverMonitorRowData.setFloodFlow(DbTable - .getNullDouble()); - } else { - riverMonitorRowData - .setFloodFlow(roundTo2DecimalPlaces(locRiverMonRecord - .getFlood_flow())); - } - - riverMonitorRowData - .setMinorStage(roundTo2DecimalPlaces(locRiverMonRecord - .getMinor())); - riverMonitorRowData - .setMajorStage(roundTo2DecimalPlaces(locRiverMonRecord - .getMajor())); - riverMonitorRowData - .setModerateStage(roundTo2DecimalPlaces(locRiverMonRecord - .getModerate())); - - setRiverBasinData(riverMonitorRowData); - - riverMonitorRowDataList.add(riverMonitorRowData); - - _riverLidSet.add(locRiverMonRecord.getLid()); - } - } - - } catch (SQLException e) { - logSQLException(e); - } - return riverMonitorRowDataList; - } - - private void setRiverBasinData(RiverMonitorJTableRowData rowData) { - String riverBasin = _lidToRiverBasinMap.get(rowData.getLid()); - - rowData.setRiverBasin(riverBasin); - - return; - } - - private void loadRiverBasinData() { - LocationTable table = new LocationTable(_db); - String whereClause = "order by lid"; - List recordList = null; - - _lidToRiverBasinMap.clear(); - try { - recordList = (List) table.select(whereClause); - for (LocationRecord record : recordList) { - _lidToRiverBasinMap.put(record.getLid(), record.getRb()); - } - } catch (SQLException e) { - - } - - } - - public boolean isRiverLocation(String lid) { - boolean result = false; - - if (_riverLidSet != null) { - if (_riverLidSet.contains(lid)) { - result = true; - } - } - return result; - } - - protected void readCurrentRiverMonTableData() { - /* - * String header = - * "RiverMonitorDataManager.readCurrentRiverMonTableData(): "; - * _riverMonLocGroupDataManager.readLocationHsaMap(); - * _riverMonLocGroupDataManager.readGroupInfo(); - * _riverMonLocGroupDataManager.readLocationInfo(); - * _riverMonLocGroupDataManager.readGroupHsaMap(); - * _riverMonLocGroupDataManager - * .updateRiverMonitorGroupWithAppropriateHsa(); - */ - _riverMonLocGroupDataManager.initializeRiverMonTableData(); - } - - public List getRiverMonitorRowDataList() { - return _riverMonitorRowDataList; - } - - public void createRiverMonitorRowDataList() { - String header = "RiverMonitorDataManager.createRiverMonitorRowDataList(): "; - - _logger.log(header + " Memory Info before creating rowdata list:" - + printMemoryInfo()); - Runtime.getRuntime().gc(); - _riverMonitorRowDataList = readRiverLocationInfo(); - - String fcstTs = _menuSettings.getRiverSettings().getFcstTypeSource(); - - readConfigFileToFormLidHeightPEAndLidDischargePEMap(); - - Map lidRowDataMap = new HashMap(); - if (_riverMonitorRowDataList != null) { - String dischargePE = null; - String heightPE = null; - - readCurrentRiverMonTableData(); - - Runtime.getRuntime().gc(); - _logger.log(header + " Here 1: " + printMemoryInfo()); - _precipDataManager - .readPrecipData(_riverMonitorRowDataList, "RIVER"); - Runtime.getRuntime().gc(); - _logger.log(header + " Here 2: " + printMemoryInfo()); - - Map vtecMap = createGeoIdToVtecEventListMap(); - Map alertAlarmMap = createAlertAlarmInfoToLidMap(); - determineLidToSshpFcstMap(); - - _derivedColumnsList = _derivedColumnsFileManager - .getDerivedColumns(); - - for (RiverMonitorJTableRowData riverMonitorRowData : _riverMonitorRowDataList) { - String lid = riverMonitorRowData.getLid(); - String groupId = _riverMonLocGroupDataManager.getGroupId(lid); - String groupName = _riverMonLocGroupDataManager - .getGroupName(groupId); - int groupOrdinal = _riverMonLocGroupDataManager - .getGroupOrdinal(groupId); - String hsa = _riverMonLocGroupDataManager.getHsa(groupId); - int locationOrdinal = _riverMonLocGroupDataManager - .getLocationOrdinal(lid); - - riverMonitorRowData.setLid(riverMonitorRowData.getLid()); - riverMonitorRowData.setLocationOrdinal(locationOrdinal); - riverMonitorRowData.setHsa(hsa); - riverMonitorRowData.setGroupName(groupName); - riverMonitorRowData.setGroupId(groupId); - riverMonitorRowData.setGroupOrdinal(groupOrdinal); - - // Read the latest obs from riverstatus for this lid - RiverStatusRecord riverStatusRecordForObs = null; - riverStatusRecordForObs = determineObsOrFcstRecordFromRiverStatus( - lid, riverMonitorRowData.getPrimaryRiverPe(), "OBS", - null); - - if (riverStatusRecordForObs == null) { - riverMonitorRowData.setLatestObsValue(DbTable - .getNullDouble()); - riverMonitorRowData.setLatestObsTime(DbTable.getNullLong()); - riverMonitorRowData.setObsTypeSource(null); - } else { - riverMonitorRowData - .setLatestObsValue(roundTo2DecimalPlaces(riverStatusRecordForObs - .getValue())); - riverMonitorRowData - .setLatestObsTime(riverStatusRecordForObs - .getValidtime()); - riverMonitorRowData - .setObsTypeSource(riverStatusRecordForObs.getTs()); - } - - // Read the max future forecast from riverstatus for this - // lid - RiverStatusRecord riverStatusRecordForFcst = determineObsOrFcstRecordFromRiverStatus( - lid, riverMonitorRowData.getPrimaryRiverPe(), "FCST", - fcstTs); - if (riverStatusRecordForFcst == null) { - riverMonitorRowData.setMaxFcstValidTime(DbTable - .getNullLong()); - riverMonitorRowData.setMaxFcstBasisTime(DbTable - .getNullLong()); - riverMonitorRowData - .setMaxFcstValue(DbTable.getNullDouble()); - if (!fcstTs.equalsIgnoreCase("IngestFilter")) - riverMonitorRowData.setFcstTypeSource(fcstTs); - else - riverMonitorRowData.setFcstTypeSource(null); - } else { - riverMonitorRowData - .setMaxFcstValue(roundTo2DecimalPlaces(riverStatusRecordForFcst - .getValue())); - riverMonitorRowData - .setMaxFcstValidTime(riverStatusRecordForFcst - .getValidtime()); - riverMonitorRowData - .setMaxFcstBasisTime(riverStatusRecordForFcst - .getBasistime()); - riverMonitorRowData - .setFcstTypeSource(riverStatusRecordForFcst.getTs()); - } - - dischargePE = null; - heightPE = null; - - // heightPE = ""; dischargePE = ""; - if (_lidHeightPEMap != null && _lidDischargePEMap != null) { - if (_lidHeightPEMap.size() > 0 - && _lidDischargePEMap.size() > 0) { - heightPE = (String) _lidHeightPEMap.get(lid); - dischargePE = (String) _lidDischargePEMap.get(lid); - } - } - if (heightPE == null || dischargePE == null) // No entry - // found in - // file - { - char firstLetterInPrimaryPE = riverMonitorRowData - .getPrimaryRiverPe().charAt(0); - - if (firstLetterInPrimaryPE == 'H') { - heightPE = riverMonitorRowData.getPrimaryRiverPe(); - dischargePE = getEquivalentDischargePE(riverMonitorRowData - .getPrimaryRiverPe()); - } else - // firstLetterInPrimaryPE is 'Q' - { - dischargePE = riverMonitorRowData.getPrimaryRiverPe(); - heightPE = getEquivalentHeightPE(riverMonitorRowData - .getPrimaryRiverPe()); - } - } - - riverStatusRecordForObs = null; - if (heightPE != null) // could be null if the user hasn't - // configured and if the primary pe - // is not QR, QT - riverStatusRecordForObs = determineObsOrFcstRecordFromRiverStatus( - lid, heightPE, "OBS", null); - - if (riverStatusRecordForObs == null) { - riverMonitorRowData.setLatestStgValue(DbTable - .getNullDouble()); - riverMonitorRowData.setLatestStgTime(DbTable.getNullLong()); - } else { - riverMonitorRowData - .setLatestStgValue(roundTo2DecimalPlaces(riverStatusRecordForObs - .getValue())); - riverMonitorRowData - .setLatestStgTime(riverStatusRecordForObs - .getValidtime()); - } - - riverStatusRecordForObs = null; - if (dischargePE != null) // could be null if the user - // hasn't configured and if the - // primary pe is not HG, HT - riverStatusRecordForObs = determineObsOrFcstRecordFromRiverStatus( - lid, dischargePE, "OBS", null); - - if (riverStatusRecordForObs == null) { - riverMonitorRowData.setLatestFlowValue(DbTable - .getNullDouble()); - riverMonitorRowData - .setLatestFlowTime(DbTable.getNullLong()); - } else { - riverMonitorRowData - .setLatestFlowValue(roundTo2DecimalPlaces(riverStatusRecordForObs - .getValue())); - riverMonitorRowData - .setLatestFlowTime(riverStatusRecordForObs - .getValidtime()); - } - - SshpFcstDetails sshpFcstDetails = getSshpFcstDetailsForLid( - riverMonitorRowData.getLid(), - riverMonitorRowData.getFloodStage()); - riverMonitorRowData.setSshpFcstDetails(sshpFcstDetails); - - int numOfHrsForObsLookBack = _menuSettings.getRiverSettings() - .getLatestObsLookBack(); - long earliestAcceptableTimeForObs = System.currentTimeMillis() - - TimeHelper.MILLIS_PER_HOUR * numOfHrsForObsLookBack; - - if (riverMonitorRowData.getLatestObsTime() > earliestAcceptableTimeForObs) { - riverMonitorRowData - .setObsFcstMax(roundTo2DecimalPlaces(Math.max( - riverMonitorRowData.getLatestObsValue(), - riverMonitorRowData.getMaxFcstValue()))); - } else { - riverMonitorRowData - .setObsFcstMax(roundTo2DecimalPlaces(riverMonitorRowData - .getMaxFcstValue())); - } - - if ((riverMonitorRowData.getObsFcstMax() != DbTable - .getNullDouble()) - && (riverMonitorRowData.getFloodStage() != DbTable - .getNullDouble())) { - riverMonitorRowData - .setFldStgDeparture(roundTo2DecimalPlaces(riverMonitorRowData - .getObsFcstMax() - - riverMonitorRowData.getFloodStage())); - } else { - riverMonitorRowData - .setFldStgDeparture(roundTo2DecimalPlaces(DbTable - .getNullDouble())); - } - - if ((riverMonitorRowData.getObsFcstMax() != DbTable - .getNullDouble()) - && (riverMonitorRowData.getActionStage() != DbTable - .getNullDouble())) - riverMonitorRowData - .setActStgDeparture(roundTo2DecimalPlaces(riverMonitorRowData - .getObsFcstMax() - - riverMonitorRowData.getActionStage())); - else - riverMonitorRowData - .setActStgDeparture(roundTo2DecimalPlaces(DbTable - .getNullDouble())); - - riverMonitorRowData.setVtecEventList(getVtecEventList(lid, - vtecMap)); - - setAlertAlarmDetails(riverMonitorRowData, alertAlarmMap); - - riverMonitorRowData.addAllCellsToMap(); - /* - * _logger.log(riverMonitorRowData.getLid() + "|" + - * riverMonitorRowData.getName() + "|" + - * riverMonitorRowData.getGroupId() + "|" + - * riverMonitorRowData.getGroupName() + "|" + - * riverMonitorRowData.getLocationOrdinal() + "|" + - * riverMonitorRowData.getGroupOrdinal() + "|" + - * riverMonitorRowData.getPrecipData().getFFG1Hr() + "|" + - * riverMonitorRowData.getPrecipData().getFFG3Hr() + "|" + - * riverMonitorRowData.getPrecipData().getFFG6Hr()); - */ - - getDerivedColumnsInfo(riverMonitorRowData); - riverMonitorRowData.addDerivedDataToCellMap(); - - lidRowDataMap.put(riverMonitorRowData.getLid(), - riverMonitorRowData); - - } - - /* - * _logger.log(header + - * "Before missing precip filter is applied, alllocationinfo list size:" - * + _riverMonitorRowDataList.size()); - * - * alterRiverMonitorRowDataListBasedOnMissingPrecipFilter(); - * - * _logger.log(header + - * "After missing precip filter is applied, alllocationinfo list size:" - * + _riverMonitorRowDataList.size()); - */ - } - - Runtime.getRuntime().gc(); - _logger.log(header + " Memory Info after creating rowdata list:" - + printMemoryInfo()); - - } - - // --------------------------------------------------------------------------------------------------- - - public String printMemoryInfo() { - String str = "Free:" + Runtime.getRuntime().freeMemory() + " Max:" - + Runtime.getRuntime().maxMemory() + " total:" - + Runtime.getRuntime().totalMemory(); - return str; - } - - public PrecipColumnDataSettings getPrecipSettings() { - return _menuSettings.getPrecipSettings(); - } - - // --------------------------------------------------------------------------------------------------- - - private List getListOfLocationIds() { - List locationIdList = new ArrayList(); - - for (RiverMonitorJTableRowData rowData : _riverMonitorRowDataList) { - locationIdList.add(rowData.getLid()); - } - - return locationIdList; - - } - - // --------------------------------------------------------------------------------------------------- - - public List createStringArrayListOfFilterItems() { - String header = "RiverMonitorDataManager.createStringArrayListOfFilterItems(): "; - - List locationIdList = getListOfLocationIds(); - - List listOfNodePathStringArray = _riverMonLocGroupDataManager - .createStringArrayListOfFilterItems(locationIdList); - - return listOfNodePathStringArray; - } - - // --------------------------------------------------------------------------------------------------- - /* - * private List createStringArrayListOfFilterItemsOld() { List - * listOfStringArray = new ArrayList(); - * - * List locationIdList = getListOfLocationIds(); - * - * - * String rootItem = "HSA"; String firstLevelFilterItems[] = - * _riverMonLocGroupDataManager.getAllHsa(); String[] currentStringArray; - * - * if(firstLevelFilterItems != null && firstLevelFilterItems.length > 0) { - * String currentFirstLevelFilterItem = null; for(int i=0; i < - * firstLevelFilterItems.length; i++) { currentFirstLevelFilterItem = - * firstLevelFilterItems[i]; String secondLevelFilterItems[] = - * _riverMonLocGroupDataManager.getGroupsForHsa(firstLevelFilterItems[i]); - * if(secondLevelFilterItems != null && secondLevelFilterItems.length > 0) { - * String currentSecondLevelFilterItem = null; for(int j=0; j < - * secondLevelFilterItems.length; j++) { currentSecondLevelFilterItem = - * _riverMonLocGroupDataManager.getGroupName(secondLevelFilterItems[j]); - * String thirdLevelFilterItems[] = - * _riverMonLocGroupDataManager.getAllLocationsForGroup - * (secondLevelFilterItems[j], locationIdList); if(thirdLevelFilterItems != - * null && thirdLevelFilterItems.length > 0) { for(int k=0; k < - * thirdLevelFilterItems.length; k++) { - * if(isRiverLocation(thirdLevelFilterItems[k])) { currentStringArray = new - * String[4]; currentStringArray[0] = rootItem; currentStringArray[1] = - * currentFirstLevelFilterItem; currentStringArray[2] = - * currentSecondLevelFilterItem; currentStringArray[3] = - * thirdLevelFilterItems[k]; listOfStringArray.add(currentStringArray); } } - * } else { currentStringArray = new String[3]; currentStringArray[0] = - * rootItem; currentStringArray[1] = currentFirstLevelFilterItem; - * currentStringArray[2] = currentSecondLevelFilterItem; - * listOfStringArray.add(currentStringArray); } } } else { - * currentStringArray = new String[2]; currentStringArray[0] = rootItem; - * currentStringArray[1] = currentFirstLevelFilterItem; - * listOfStringArray.add(currentStringArray); } } } else { - * currentStringArray = new String[1]; currentStringArray[0] = rootItem; - * listOfStringArray.add(currentStringArray); } - * - * return listOfStringArray; } - */ - - private Map createGeoIdToVtecEventListMap() { - String header = "RiverMonitorDataManager.createGeoIdToVtecEventListMap():"; - Map vtecMap = new HashMap(); - VTECeventTable vtecEventTable = new VTECeventTable(_db); - String whereClause = null; - CodeTimer timer = new CodeTimer(); - try { - timer.start(); - - // retrieve data for VTEC events which are not statements and the - // end time has been set - whereClause = " where signif != 'S' and endtime is not null order by geoid, endtime asc"; - _logger.log(header + " where clause:" + whereClause); - List tempVtecEventWhichArentStatementAndEndTimeIsNotNull = vtecEventTable - .select(whereClause); - - // retrieve data for VTEC events which are not statements and the - // end time has NOT been set - whereClause = " where signif != 'S' and endtime is null order by geoid "; - _logger.log(header + " where clause:" + whereClause); - List tempVtecEventWhichArentStatementAndEndTimeIsNull = vtecEventTable - .select(whereClause); - - // merge the two lists - List allVtecEventWhichArentStatementsList = new ArrayList(); - allVtecEventWhichArentStatementsList - .addAll(tempVtecEventWhichArentStatementAndEndTimeIsNotNull); - allVtecEventWhichArentStatementsList - .addAll(tempVtecEventWhichArentStatementAndEndTimeIsNull); - - timer.stop("Rivermonitor data mgr- read vtec event time elapsed:"); - - // assign each record to the map - for (int i = 0; i < allVtecEventWhichArentStatementsList.size(); i++) { - VTECeventRecord record = (VTECeventRecord) allVtecEventWhichArentStatementsList - .get(i); - String geoId = record.getGeoid(); - - List eventList = (List) vtecMap.get(geoId); - if (eventList == null) { - eventList = new ArrayList(); - vtecMap.put(geoId, eventList); - } - eventList.add(record); - } - } catch (SQLException e) { - _logger.log(header); - logSQLException(e); - } - - return vtecMap; - } - - private List getVtecEventList(String lid, Map vtecMap) { - List finalVtecEventList = null; - - if (vtecMap != null) { - if (vtecMap.size() > 0) { - finalVtecEventList = (List) vtecMap.get(lid); - } - } - return finalVtecEventList; - } - - protected String getEquivalentHeightPE(String pe) { - String heightPE = null; - if (pe.equalsIgnoreCase("QR")) - heightPE = "HG"; - else if (pe.equalsIgnoreCase("QT")) - heightPE = "HT"; - return heightPE; - } - - protected String getEquivalentDischargePE(String pe) { - String dischargePE = null; - if (pe.equalsIgnoreCase("HG")) - dischargePE = "QR"; - else if (pe.equalsIgnoreCase("HT")) - dischargePE = "QT"; - return dischargePE; - } - - private void readValidHeightAndDischargePE() { - List shefPEInfoList = null; - - ShefPeTable shefPeTable = new ShefPeTable(_db); - String whereClause = null; - String header = "RiverMonitorDataManager.readValidHeightAndDischargePE(): "; - - CodeTimer timer = new CodeTimer(); - try { - whereClause = "where pe like 'H%' or pe like 'Q%'"; - timer.start(); - shefPEInfoList = shefPeTable.select(whereClause); - timer.stop("Read from shefpe time elapsed:"); - _logger.log(header + " Where Clause:" + whereClause); - if (shefPEInfoList == null) { - _logger.log(header + " height and discharge pe list is null"); - } else { - _logger.log(header - + " height and discharge pe list is NOT null"); - if (shefPEInfoList.size() > 0) { - _logger.log(header + - " height and discharge pe list SIZE IS > 0"); - _validHeightAndDischargePEList = new ArrayList(); - for (int i = 0; i < shefPEInfoList.size(); i++) { - - ShefPeRecord record = (ShefPeRecord) shefPEInfoList - .get(i); - _validHeightAndDischargePEList.add(record.getPe()); - } - } - } - } catch (SQLException e) { - logSQLException(e); - } - } - - private boolean validatePE(String pe) { - boolean result = false; - - if (_validHeightAndDischargePEList != null) { - for (int i = 0; i < _validHeightAndDischargePEList.size(); i++) { - String tempStr = (String) _validHeightAndDischargePEList.get(i); - if (pe.equals(tempStr)) { - result = true; - break; - } - } - } - return result; - } - - private void readConfigFileToFormLidHeightPEAndLidDischargePEMap() { - Map lidHeightPEMap = null; - Map lidDischargePEMap = null; - - String header = "RiverMonitorDataManager.readConfigFileAndFormConfigMap(): "; - File fileHandler = new File(_peConfigFileName); - - if (fileHandler.exists()) { - BufferedReader in = null; - String str; - List stringList = new ArrayList(); - - try { - in = new BufferedReader(new FileReader(fileHandler)); - while ((str = in.readLine()) != null) { - stringList.add(str); - } - } catch (IOException exception) { - printFileException(exception, header); - } - if (stringList.size() > 0) { - for (int i = 0; i < stringList.size(); i++) { - String tempString = (String) stringList.get(i); - if (tempString.length() == 0) - continue; - if (tempString.charAt(0) == '#') - continue; - String splitStr[] = null; - splitStr = tempString.split("\\|"); - if (splitStr == null) - continue; - String lid, heightPE, dischargePE; - if (splitStr.length == 3) { - splitStr[0] = splitStr[0].trim(); - splitStr[1] = splitStr[1].trim(); - splitStr[2] = splitStr[2].trim(); - if (splitStr[0].length() > 0 - && splitStr[1].length() == 2 - && splitStr[2].length() == 2) { - lid = splitStr[0]; - heightPE = splitStr[1]; - dischargePE = splitStr[2]; - if (heightPE.charAt(0) != 'H' - || dischargePE.charAt(0) != 'Q') { - _logger.log(header - + "Invalid height and discharge PE [" - + heightPE + "|" + dischargePE + "]"); - continue; - } - if ((!validatePE(heightPE)) - || (!validatePE(dischargePE))) { - _logger.log(header - + "Invalid height and discharge PE [" - + heightPE + "|" + dischargePE + "]"); - continue; - } else { - if (lidHeightPEMap == null) { - lidHeightPEMap = new HashMap(); - } - lidHeightPEMap.put(lid, heightPE); - if (lidDischargePEMap == null) { - lidDischargePEMap = new HashMap(); - } - lidDischargePEMap.put(lid, dischargePE); - } - - } else - // invalid entry - { - _logger.log(header + "1. Invalid entry[" - + tempString + "] in ConfigFile "); - continue; - } - - } else - // line not having the format lid|PETS|PETS - { - _logger.log(header + "2. Invalid entry[" + tempString - + "] in ConfigFile "); - continue; - } - } - } - } else { - _logger.log(header + "ConfigFile [" + _peConfigFileName - + "] doesn't exist"); - } - - _lidHeightPEMap = lidHeightPEMap; - _lidDischargePEMap = lidDischargePEMap; - } - - protected void printFileException(IOException exception, String header) { - header = header + ".printFileException(): "; - _logger.log(header + "ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - _logger.log(header + "End of stack trace"); - } - - // --------------------------------------------------------------------------------------------------- - - private double roundTo2DecimalPlaces(double number) { - double result = DbTable.getNullDouble(); - if (number != DbTable.getNullDouble()) - result = MathHelper.roundToNDecimalPlaces(number, 2); - - return result; - } - - public String getDefaultHsa() { - return _defaultHsa; - } - - public Map getLidDescDetails() { - if (_lidDescDetailsMap == null) { - LocRiverMonView riverMonView = new LocRiverMonView(_db); - try { - List riverMonViewList = (List) riverMonView.select(""); - if (riverMonViewList != null) { - if (riverMonViewList.size() > 0) { - _lidDescDetailsMap = new HashMap(); - for (int i = 0; i < riverMonViewList.size(); i++) { - LocRiverMonRecord record = (LocRiverMonRecord) riverMonViewList - .get(i); - String name = record.getName(); - if (name != null) { - if (name.length() > 0) { - if (name.length() > 50) { - name = name.substring(0, 50); - } - } - } - String desc = name + ";" + record.getState() + ";" - + record.getCounty(); - _lidDescDetailsMap.put(record.getLid(), desc); - } - } - } - } catch (SQLException e) { - logSQLException(e); - } - } - return _lidDescDetailsMap; - } - - private void setAlertAlarmDetails(RiverMonitorJTableRowData rowData, - Map alertAlarmMap) { - String lid = rowData.getLid(); - AlertAlarmValRecord alertAlarmValRecord = (AlertAlarmValRecord) alertAlarmMap - .get(lid); - if (alertAlarmValRecord != null) { - if (alertAlarmValRecord.getPe().equals(rowData.getPrimaryRiverPe()) - && alertAlarmValRecord.getLid().equals(rowData.getLid())) { - String categ = alertAlarmValRecord.getAa_categ(); - String check = alertAlarmValRecord.getAa_check(); - - if ((check.equalsIgnoreCase("Upper")) - && categ.equalsIgnoreCase("alert")) { - rowData.setAlertUpperLimit(true); - } else if ((check.equalsIgnoreCase("Upper")) - && categ.equalsIgnoreCase("alarm")) { - rowData.setAlarmUpperLimit(true); - } else if ((check.equalsIgnoreCase("Lower")) - && categ.equalsIgnoreCase("alert")) { - rowData.setAlertLowerLimit(true); - } else if ((check.equalsIgnoreCase("Lower")) - && categ.equalsIgnoreCase("alarm")) { - rowData.setAlarmLowerLimit(true); - } else if ((check.equalsIgnoreCase("Diff")) - && categ.equalsIgnoreCase("alert")) { - rowData.setAlertDiffLimit(true); - } else if ((check.equalsIgnoreCase("Diff")) - && categ.equalsIgnoreCase("alarm")) { - rowData.setAlarmDiffLimit(true); - } else if ((check.equalsIgnoreCase("Roc")) - && categ.equalsIgnoreCase("alert")) { - rowData.setAlertRocLimit(true); - } else if ((check.equalsIgnoreCase("Roc")) - && categ.equalsIgnoreCase("alarm")) { - rowData.setAlarmRocLimit(true); - } - } - } - } - - private Map createAlertAlarmInfoToLidMap() { - String header = "RiverMonitorDataManager.addAlertAlarmInfoToRowDataList(): "; - List alertAlarmList; - Map alertAlarmMap = new HashMap(); - AlertAlarmValTable alertAlarmValTable = new AlertAlarmValTable(_db); - int numOfHrsForAlertAlarmValidTimeLookBack = 1; - numOfHrsForAlertAlarmValidTimeLookBack = _menuSettings - .getRiverSettings().getAlertAlarmLookBack(); - - _logger.log(header + "numOfHrsForValidTimeLookBack:" - + numOfHrsForAlertAlarmValidTimeLookBack); - - String whereClause = null; - long tempTime = System.currentTimeMillis() - MILLIS_PER_HOUR - * numOfHrsForAlertAlarmValidTimeLookBack; - String validTime = DbTimeHelper.getDateTimeStringFromLongTime(tempTime); - - try { - whereClause = " where validtime >" + "'" + validTime + "'" - + " order by lid, pe"; - _logger.log(header + "Where clause:" + whereClause); - - alertAlarmList = alertAlarmValTable.select(whereClause); - - for (int i = 0; i < alertAlarmList.size(); i++) { - AlertAlarmValRecord alertAlarmValRecord = (AlertAlarmValRecord) alertAlarmList - .get(i); - alertAlarmMap.put(alertAlarmValRecord.getLid(), - alertAlarmValRecord); - } - } catch (SQLException e) { - logSQLException(e); - } - - return alertAlarmMap; - } - - // ----------------------------------------------------------------------------------------------------------------------- - - private SshpFcstDetails getSshpFcstDetailsForLid(String lid, - double floodStage) { - - if (_sshpLidFcstMap == null) - determineLidToSshpFcstMap(); - SshpFcstDetails sshpFcstDetails = new SshpFcstDetails(); - RegularTimeSeries fcstRegularTimeSeries = (RegularTimeSeries) _sshpLidFcstMap - .get(lid); - if (fcstRegularTimeSeries != null) { - AbsTimeMeasurement maxMeasurement = (AbsTimeMeasurement) fcstRegularTimeSeries - .getMaxMeasurement(); - if (maxMeasurement != null) { - sshpFcstDetails - .setCrestValue(roundTo2DecimalPlaces(maxMeasurement - .getValue())); - sshpFcstDetails.setCrestTime(maxMeasurement.getTime()); - - for (int index = 0; index < fcstRegularTimeSeries - .getMeasurementCount(); index++) { - AbsTimeMeasurement forecastMeasurement = fcstRegularTimeSeries - .getAbsTimeMeasurementByIndex(index); - - if (forecastMeasurement.getValue() >= floodStage) { - sshpFcstDetails - .setTimeAboveFldStg(fcstRegularTimeSeries - .getMeasurementTimeByIndex(index)); - break; - } - } - // basis time will be the last modified time of the file - // basinid_fcst_stage.dat - sshpFcstDetails.setBasisTime(new File(_sshpFcstDataDir + "/" - + lid + "_fcst_stage.dat").lastModified()); - } - - } - return sshpFcstDetails; - } - - // --------------------------------------------------------------------------------------------------------------- - private RegularTimeSeries loadForecastFileMapTimeSeries(String filePath) { - TimeSeriesFileManager reader = new TimeSeriesFileManager(); - - RegularTimeSeries timeSeries = null; - - timeSeries = reader.readRegularTimeSeries(filePath, - MeasuringUnit.inches); - - return timeSeries; - } - - // ----------------------------------------------------------------------------------------------------------------------- - - private void determineLidToSshpFcstMap() { - _sshpLidFcstMap = new HashMap(); - - File sshpFcstDataPath = new File(_sshpFcstDataDir); - - if (!sshpFcstDataPath.exists()) { - _logger.log("Sshp fcst data dir:[" - + _sshpFcstDataDir - + "] doesn't exist...Check the token value for sshp_background_forecast_output_dir"); - } else { - File[] fcstFilesArray = sshpFcstDataPath.listFiles(); - - if (fcstFilesArray != null) { - if (fcstFilesArray.length > 0) { - // basis time look back window filter value - int numOfHrsForLatestFcstLookBack = _menuSettings - .getRiverSettings() - .getLatestFcstBasisTimeLookBack(); - long lookBackWindowTimeLong = System.currentTimeMillis() - - MILLIS_PER_HOUR * numOfHrsForLatestFcstLookBack; - - for (int i = 0; i < fcstFilesArray.length; i++) { - // if file's last modified time is within the basis time - // look back window - if (fcstFilesArray[i].lastModified() >= lookBackWindowTimeLong) { - String fileName = fcstFilesArray[i].getName(); - if (fileName.endsWith(".dat")) { - RegularTimeSeries fcstRegularTimeSeries = loadForecastFileMapTimeSeries(fcstFilesArray[i] - .getAbsolutePath()); - - if (fcstRegularTimeSeries == null) - continue; - - int indexOfUnderScore = fileName.indexOf('_'); - String lid = fileName.substring(0, - indexOfUnderScore); - _sshpLidFcstMap.put(lid, fcstRegularTimeSeries); - - // System.out.println("Read the sshp forecast - // file["+ fcstFilesArray[i].getAbsolutePath() - // +"] and added the time series to the map"); - } - } - } - } else { - _logger.log("Sshp fcst files are not available in the sshpfcst dir:[" - + _sshpFcstDataDir + "]"); - } - } - } - } - - // ----------------------------------------------------------------------------------------------------------------------- - - private RiverStatusRecord determineObsOrFcstRecordFromRiverStatus( - String lid, String primaryPe, String tag, String fcstTs) { - List riverStatusRecordList = new ArrayList(); - RiverStatusTable riverStatusTable = new RiverStatusTable(_db); - RiverStatusRecord riverStatusRecord = null; - Map tsRankMap = null; - List tsDurExtValTimeList = new ArrayList(); - String whereClause = null; - - if (tag.compareTo("OBS") == 0) { - whereClause = " where lid = " + "'" + lid + "'" + " and pe='" - + primaryPe + "' and (ts like 'R%')" - + " order by validtime desc"; - } else - // Tag is FCST - { - int numOfHrsForBasisTimeLookBack = 1; - numOfHrsForBasisTimeLookBack = _menuSettings.getRiverSettings() - .getLatestFcstBasisTimeLookBack(); - - long allowedBasisTime = System.currentTimeMillis() - - (MILLIS_PER_HOUR * numOfHrsForBasisTimeLookBack); - - String allowedBasisTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(allowedBasisTime); - - if (fcstTs.compareTo("IngestFilter") == 0) { - whereClause = " where lid = " + "'" + lid + "'" + " and pe='" - + primaryPe + "' and (ts like 'F%')" - + " and basistime >= '" + allowedBasisTimeString - + "' order by value desc"; - } else - // TS for fcst recs is chosen to be 'FF' or 'FZ' - { - whereClause = " where lid = " + "'" + lid + "'" + " and pe='" - + primaryPe + "' and ts='" + fcstTs + "'" - + " and basistime >= '" + allowedBasisTimeString + "'"; - } - } - - // ("Tag:"+tag +" clause:"+ whereClause); - try { - riverStatusRecordList = riverStatusTable.select(whereClause); - } catch (SQLException e) { - logSQLException(e); - } - - if (riverStatusRecordList.size() == 0) - return riverStatusRecord; - - // Key for riverstatus table are lid, pe, ts. So we will get only one - // record if - // fcstTs is either FF or FZ .Hence the list size will be 1. So move to - // else part - // The below If logic will be used only if fcsTs has value IngestFilter. - // If more than one rec is found then use ingest filter decide based on - // ts rank - // Else return the single record in the list. - if (riverStatusRecordList.size() > 1) { - for (int loopcnt = 0; loopcnt < riverStatusRecordList.size(); loopcnt++) { - riverStatusRecord = (RiverStatusRecord) riverStatusRecordList - .get(loopcnt); - TsDurExtValTime tsDurExtValTime = new TsDurExtValTime(); - - /* - * System.out.println("statusrec - * has:"+riverStatusRecord.getTs()+"|"+ - * riverStatusRecord.getDur()+"|"+ - * riverStatusRecord.getExtremum()+"|"+ - * riverStatusRecord.getValidtime()+"|"+ - * riverStatusRecord.getValue()); - */ - - tsDurExtValTime.setTs(riverStatusRecord.getTs()); - tsDurExtValTime.setDuration(riverStatusRecord.getDur()); - tsDurExtValTime.setExtremum(riverStatusRecord.getExtremum()); - tsDurExtValTime.setTime(riverStatusRecord.getValidtime()); - tsDurExtValTime.setValue(riverStatusRecord.getValue()); - tsDurExtValTimeList.add(tsDurExtValTime); - - tsDurExtValTime = (TsDurExtValTime) tsDurExtValTimeList - .get(loopcnt); - /* - * System.out.println("After add In list - * loopcnt:"+loopcnt+"|"+tsDurExtValTime.getTs()+" - * |"+tsDurExtValTime.getDuration()+"|"+ - * tsDurExtValTime.getExtremum()); - */ - - } - tsRankMap = createIngestFilterTsRankMap(lid, tsDurExtValTimeList, - primaryPe); - riverStatusRecord = compareTsRankAndRiverStatusInfo(tsRankMap, - riverStatusRecordList, tsDurExtValTimeList); - - } else { - riverStatusRecord = null; - riverStatusRecord = (RiverStatusRecord) riverStatusRecordList - .get(0); - } - /* - * System.out.println("Rec is:"+ riverStatusRecord.getLid()+"|"+ - * riverStatusRecord.getPe()+"|"+riverStatusRecord.getTs()+"|"+ - * riverStatusRecord.getValue()); - */ - - return riverStatusRecord; - } - - private Map createIngestFilterTsRankMap(String lid, - List tsDurExtValTimeList, String pe) { - Map tsRankMap = new HashMap(); - IngestFilterTable ingestFilterTable = new IngestFilterTable(_db); - IngestFilterRecord ingestFilterRecord = null; - List ingestFilterRecordList = new ArrayList(); - String whereClause = null; - String ts = null; - int duration = 0; - String extremum = null; - TsDurExtValTime tsDurExt = null; - Integer curTsRank = null; - - for (int loopcnt = 0; loopcnt < tsDurExtValTimeList.size(); loopcnt++) { - tsDurExt = (TsDurExtValTime) tsDurExtValTimeList.get(loopcnt); - ts = tsDurExt.getTs(); - duration = tsDurExt.getDuration(); - extremum = tsDurExt.getExtremum(); - // System.out.println("For:ts|dur|ext:"+ts+"|"+duration+"|"+extremum); - try { - whereClause = " where lid='" + lid + "' and pe='" + pe - + "' and ts='" + ts + "' and dur=" + duration - + " and extremum='" + extremum + "'"; - - // System.out.println("ingestfilter whereclause:"+whereClause); - ingestFilterRecordList = ingestFilterTable.select(whereClause); - // System.out.println("after ingestfilter - // whereclause:"+whereClause); - if (ingestFilterRecordList.size() > 0) { - ingestFilterRecord = (IngestFilterRecord) ingestFilterRecordList - .get(0); - curTsRank = new Integer(ingestFilterRecord.getTs_rank()); - } else { - curTsRank = new Integer(-1); - } - /* - * System.out.println("Before add to map ts|dur|ext|curtsrank: "+ - * ts+"|"+duration+"|"+extremum+"|"+ curTsRank); - */ - - tsRankMap.put(new Integer(loopcnt), curTsRank); - - // System.out.println("After Add to rankmap"); - } catch (SQLException e) { - logSQLException(e); - } - } - - return tsRankMap; - } - - private RiverStatusRecord compareTsRankAndRiverStatusInfo(Map tsRankMap, - List riverStatusRecordList, List tsDurExtValTimeList) { - RiverStatusRecord matchRiverStatusRecord = null; - int prevTsRank = -1; - int bestTsRank = -1; - int matchIndex = -1; - int cntOfSameTsRank = 0; - List indexOfSameTsRankList = new ArrayList(); - - // System.out.println("In compare function"); - for (int loopcnt = 0; loopcnt < riverStatusRecordList.size(); loopcnt++) { - int curTsRank = new Integer(tsRankMap.get(new Integer(loopcnt)) - .toString()).intValue(); - if (curTsRank == -1) - continue; - if (bestTsRank == -1) { - prevTsRank = curTsRank; - bestTsRank = curTsRank; - matchIndex = loopcnt; - // System.out.println("loop:[ "+ loopcnt+"]:"+ bestTsRank+ " "+ - // matchIndex); - } else { - // System.out.println("Comparing curTsRank < bestTsRank" + - // curTsRank + bestTsRank); - if (curTsRank < bestTsRank) { - prevTsRank = curTsRank; - bestTsRank = curTsRank; - matchIndex = loopcnt; - // System.out.println("loop:[ "+ loopcnt+"]:"+ bestTsRank+ " - // "+ matchIndex); - } else { - bestTsRank = prevTsRank; - prevTsRank = curTsRank; - // System.out.print("False"); - // System.out.println("loop:[ "+ loopcnt+"]:"+ bestTsRank+ " - // "+ matchIndex); - } - } - } - - // Match is found for highest ts_rank. Now check if there are multiple - // ts with same ts rank. - // If so consider all the recs in riverstatus that have the same ts rank - // and decide as below. - // For obs data consider the rec that has latest valid time. - // For fcst data consider the rec that has max value. - if (matchIndex != -1) { - int highestTsRank = bestTsRank; - int curTsRank; - - // System.out.println("riverstatsrecscnt:"+riverStatusRecordList.size()); - // System.out.println("tsranksize:"+tsRankMap.size()); - for (int loopcnt = 0; loopcnt < tsRankMap.size(); loopcnt++) { - // System.out.println("here3:"+Integer.valueOf(tsRankMap.get(Integer.valueOf(loopcnt)).toString()).intValue()); - curTsRank = new Integer(tsRankMap.get(new Integer(loopcnt)) - .toString()).intValue(); - - if (curTsRank == highestTsRank) { - cntOfSameTsRank++; - indexOfSameTsRankList.add(new Integer(loopcnt)); - } - } - if (cntOfSameTsRank == 1) - matchRiverStatusRecord = (RiverStatusRecord) riverStatusRecordList - .get(matchIndex); - } - - // At this point more than 1 rec is got from riverstatus and - // either no match is found in ingestfilter and since - // Or multiple ts having same ts rank then do the following - if (matchIndex == -1 || cntOfSameTsRank > 1) { - // since we query the riverstatus with valid time desc/ value desc - // for fcst/obs - // respectively we will use the - // first rec that match the highest rank ts amongst the recs - // obtained - int index = new Integer(indexOfSameTsRankList.get(0).toString()) - .intValue(); - matchRiverStatusRecord = (RiverStatusRecord) riverStatusRecordList - .get(index); - } - - /* - * System.out.println("Final best match:"+ - * matchRiverStatusRecord.getLid()+"|"+ - * matchRiverStatusRecord.getPe()+"|"+ matchRiverStatusRecord.getTs()+ - * "|"+ matchRiverStatusRecord.getExtremum()+ - * "|"+matchRiverStatusRecord.getDur()+ - * "|"+matchRiverStatusRecord.getValue()+"|"+ "Rank: "+bestTsRank); - */ - return matchRiverStatusRecord; - } - - private class TsDurExtValTime { - private String ts = null; - - private int duration = 0; - - private String extremum = null; - - private long time; - - private double value; - - protected void setTs(String ts) { - this.ts = ts; - } - - protected String getTs() { - return this.ts; - } - - protected void setDuration(int dur) { - this.duration = dur; - } - - protected int getDuration() { - return this.duration; - } - - protected void setExtremum(String ext) { - this.extremum = ext; - } - - protected String getExtremum() { - return this.extremum; - } - - protected long getTime() { - return time; - } - - protected void setTime(long time) { - this.time = time; - } - - protected double getValue() { - return value; - } - - protected void setValue(double value) { - this.value = value; - } - } - - public class SshpFcstDetails { - private double _crestValue; - - private long _crestTime; - - private long _timeAboveFldStg; - - private long _basisTime; - - public SshpFcstDetails() { - _crestValue = DbTable.getNullDouble(); - _crestTime = DbTable.getNullLong(); - _timeAboveFldStg = DbTable.getNullLong(); - _basisTime = DbTable.getNullLong(); - } - - public long getBasisTime() { - return _basisTime; - } - - public void setBasisTime(long basisTime) { - this._basisTime = basisTime; - } - - public long getCrestTime() { - return _crestTime; - } - - public void setCrestTime(long crestTime) { - this._crestTime = crestTime; - } - - public double getCrestValue() { - return _crestValue; - } - - public void setCrestValue(double crestValue) { - this._crestValue = crestValue; - } - - public long getTimeAboveFldStg() { - return _timeAboveFldStg; - } - - public void setTimeAboveFldStg(long timeAboveFldStg) { - this._timeAboveFldStg = timeAboveFldStg; - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorJTableRowData.java deleted file mode 100755 index cd0cd3e3c1..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorJTableRowData.java +++ /dev/null @@ -1,1947 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.monitor.MonitorCell; -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.monitor.precip.PrecipData; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.river.RiverMonitorDataManager.SshpFcstDetails; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.CellType; - -public class RiverMonitorJTableRowData extends AbstractJTableRowData /*implements JTableRowData */ -{ - private int _defaultDecimalPoints = 2; - - private static Map _derivedReturnTypeToCellTypeMap = new HashMap(); - - private String _groupName; - private String _lid; - private String _name; - private String _county; - private String _state; - private String _hsa; - private String _stream; - private String _riverBasin; - private double _bankFull; - private double _actionStage; - private double _floodStage; - private double _foodFlow; - private double _actionFlow; - private String _groupId; - private double _latestObsValue; - private long _latestObsTime; - private double _latestStgValue; - private long _latestStgTime; - private double _latestFlowValue; - private long _latestFlowTime; - private double _maxFcstValue; - private long _maxFcstValidTime; - private long _maxFcstBasisTime; - private double _sshpMaxFcstValue; - private long _sshpMaxFcstTime; - private long _sshpFcstBasisTime; - private long _sshpFcstFloodTime; - private int _groupOrdinal; - private int _locationOrdinal; - private double _obsFcstMax; - private double _fldStgDeparture; - private double _actStgDeparture; - private double _minorStage; - private double _majorStage; - private double _moderateStage; - private List _derivedColumnsDetailsList; - private List _vtecEventList; - private boolean _alertUpperLimit = false; - private boolean _alarmUpperLimit = false; - private boolean _alertLowerLimit = false; - private boolean _alarmLowerLimit = false; - private boolean _alertRocLimit = false; - private boolean _alarmRocLimit = false; - private boolean _alertDiffLimit = false; - private boolean _alarmDiffLimit = false; - private String _primaryRiverPe; - private String _obsTypeSource; - private String _fcstTypeSource; - protected RiverMonitorDataManager _riverMonitorDataManager; - protected RiverMonitorVtecEventDataManager _riverMonitorVtecEventDataManager; - private String _toolTipTextForAlertAlarmSummary; - private String _toolTipTextForThreatSummary; - private String _toolTipTextForPrecipThreatSummary; - private SshpFcstDetails _sshpFcstDetails; - - private PrecipData _precipData; - private SessionLogger _logger; - - private static Set _ignoreColumnNameForThreatSet = new HashSet(); - - private RiverMonitorMenuSettings _menuSettings; - - static - { - _derivedReturnTypeToCellTypeMap.put("boolean", CellType.BOOLEAN); - _derivedReturnTypeToCellTypeMap.put("double", CellType.DOUBLE); - _derivedReturnTypeToCellTypeMap.put("float", CellType.FLOAT); - _derivedReturnTypeToCellTypeMap.put("long", CellType.LONG); - _derivedReturnTypeToCellTypeMap.put("int", CellType.INTEGER); - _derivedReturnTypeToCellTypeMap.put("string", CellType.STRING); - - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_FLOW_TIME); - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_FLOW_VALUE); - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_STG_TIME); - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_STG_VALUE); - - } - - public RiverMonitorJTableRowData() - { - - } - - public RiverMonitorJTableRowData(String missingRepresentation, RiverMonitorDataManager riverMonitorDataManager, - SessionLogger logger, RiverMonitorMenuSettings menuSettings) - { - setMissingRepresentation(missingRepresentation); - _riverMonitorDataManager = riverMonitorDataManager; - _logger = logger; - - _menuSettings = menuSettings; - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RiverMonitorJTableRowData(RiverMonitorJTableRowData origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setHsa(origRecord.getHsa()); - setStream(origRecord.getStream()); - setRiverBasin(origRecord.getRiverBasin()); - setBankFull(origRecord.getBankFull()); - setActionStage(origRecord.getActionStage()); - setFloodStage(origRecord.getFloodStage()); - setFloodFlow(origRecord.getFloodFlow()); - setActionFlow(origRecord.getActionFlow()); - setGroupId(origRecord.getGroupId()); - setGroupName(origRecord.getGroupName()); - } - - public String getLid() - { - return _lid; - } - - public void setLid(String lid) - { - this._lid = lid ; - } - - public String getName() - { - return _name; - } - - public void setName(String name) - { - this._name = name ; - } - - public String getCounty() - { - return _county; - } - - public void setCounty(String county) - { - this._county = county ; - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - this._state = state ; - } - - public String getHsa() - { - return _hsa; - } - - public void setHsa(String hsa) - { - this._hsa = hsa ; - } - - public String getStream() - { - return _stream; - } - - public void setStream(String stream) - { - this._stream = stream ; - } - - public double getBankFull() - { - return _bankFull; - } - - public void setBankFull(double bankFull) - { - this._bankFull = bankFull ; - } - - public double getActionStage() - { - return _actionStage; - } - - public void setActionStage(double actionStage) - { - this._actionStage = actionStage ; - } - - public double getFloodStage() - { - return _floodStage; - } - - public void setFloodStage(double floodStage) - { - this._floodStage = floodStage ; - } - - public double getFloodFlow() - { - return _foodFlow; - } - - public void setFloodFlow(double floodFlow) - { - this._foodFlow = floodFlow ; - } - - public double getActionFlow() - { - return _actionFlow; - } - - public void setActionFlow(double actionFlow) - { - this._actionFlow = actionFlow ; - } - - public String getGroupName() - { - return _groupName; - } - - public void setGroupName(String groupName) - { - this._groupName = groupName ; - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - this._groupId = groupId ; - } - - public double getLatestObsValue() - { - return _latestObsValue; - } - - public void setLatestObsValue(double latestObsValue) - { - this._latestObsValue = latestObsValue ; - } - - public long getLatestObsTime() - { - return _latestObsTime; - } - - public void setLatestObsTime(long latestObsTime) - { - this._latestObsTime = latestObsTime ; - } - - public double getLatestStgValue() - { - return _latestStgValue; - } - - public void setLatestStgValue(double latestStgValue) - { - this._latestStgValue = latestStgValue ; - } - - public long getLatestStgTime() - { - return _latestStgTime; - } - - public void setLatestStgTime(long latestStgTime) - { - this._latestStgTime = latestStgTime ; - } - - public double getLatestFlowValue() - { - return _latestFlowValue; - } - - public void setLatestFlowValue(double latestFlowValue) - { - this._latestFlowValue = latestFlowValue ; - } - - public long getLatestFlowTime() - { - return _latestFlowTime; - } - - public void setLatestFlowTime(long latestFlowTime) - { - this._latestFlowTime = latestFlowTime ; - } - - public double getMaxFcstValue() - { - return _maxFcstValue; - } - - public void setMaxFcstValue(double maxFcstValue) - { - this._maxFcstValue = maxFcstValue ; - } - - public long getMaxFcstValidTime() - { - return _maxFcstValidTime; - } - - public void setMaxFcstValidTime(long maxFcstValidTime) - { - this._maxFcstValidTime = maxFcstValidTime; - } - - public long getMaxFcstBasisTime() - { - return _maxFcstBasisTime; - } - - public void setMaxFcstBasisTime(long maxFcstBasisTime) - { - this._maxFcstBasisTime = maxFcstBasisTime; - } - - public long getSshpFcstBasisTime() - { - if(_sshpFcstDetails != null) - _sshpFcstBasisTime = _sshpFcstDetails.getBasisTime(); - else - _sshpFcstBasisTime = DbTable.getNullLong(); - return _sshpFcstBasisTime; - } - - public void setSshpFcstBasisTime(long sshpFcstBasisTime) - { - this._sshpFcstBasisTime = sshpFcstBasisTime; - } - - public long getSshpFcstFloodTime() - { - if(_sshpFcstDetails != null) - _sshpFcstFloodTime = _sshpFcstDetails.getTimeAboveFldStg(); - else - _sshpFcstFloodTime = DbTable.getNullLong(); - return _sshpFcstFloodTime; - } - - public void setSshpFcstFloodTime(long sshpFcstFloodTime) - { - this._sshpFcstFloodTime = sshpFcstFloodTime; - } - - public long getSshpMaxFcstValidTime() - { - if(_sshpFcstDetails != null) - _sshpMaxFcstTime = _sshpFcstDetails.getCrestTime(); - else - _sshpMaxFcstTime = DbTable.getNullLong(); - return _sshpMaxFcstTime; - } - - public void setSshpMaxFcstValidTime(long sshpMaxFcstTime) - { - this._sshpMaxFcstTime = sshpMaxFcstTime; - } - - public double getSshpMaxFcstValue() - { - if(_sshpFcstDetails != null) - _sshpMaxFcstValue = _sshpFcstDetails.getCrestValue(); - else - _sshpMaxFcstValue = DbTable.getNullDouble(); - return _sshpMaxFcstValue; - } - - public void setSshpMaxFcstValue(double sshpMaxFcstValue) - { - this._sshpMaxFcstValue = sshpMaxFcstValue; - } - - public int getGroupOrdinal() - { - return _groupOrdinal; - } - - public void setGroupOrdinal(int groupOrdinal) - { - this._groupOrdinal = groupOrdinal ; - } - - public int getLocationOrdinal() - { - return _locationOrdinal; - } - - public void setLocationOrdinal(int locationOrdinal) - { - this._locationOrdinal = locationOrdinal ; - } - - public void setObsFcstMax(double obsFcstMax) - { - this._obsFcstMax = obsFcstMax; - } - - public double getObsFcstMax() - { - return _obsFcstMax; - } - - public void setFldStgDeparture(double fldStgDeparture) - { - this._fldStgDeparture = fldStgDeparture; - } - - public double getFldStgDeparture() - { - return _fldStgDeparture; - } - - public void setActStgDeparture(double actStgDeparture) - { - this._actStgDeparture = actStgDeparture; - } - - public double getActStgDeparture() - { - return _actStgDeparture; - } - - public void setMinorStage(double minorStage) - { - this._minorStage = minorStage; - } - - public double getMinorStage() - { - return _minorStage; - } - - public void setMajorStage(double majorStage) - { - this._majorStage = majorStage; - } - - public double getMajorStage() - { - return _majorStage; - } - - public void setModerateStage(double moderateStage) - { - this._moderateStage = moderateStage; - } - - public double getModerateStage() - { - return _moderateStage; - } - - public void setDerivedColumnsDetailsList(List list) - { - _derivedColumnsDetailsList = list; - } - - public List getDerivedColumnsDetailsList() - { - return _derivedColumnsDetailsList; - } - - private List getVtecEventList() - { - return _vtecEventList; - } - - public void setVtecEventList(List list) - { - _vtecEventList = list; - _riverMonitorVtecEventDataManager = new RiverMonitorVtecEventDataManager(_vtecEventList); - } - - public RiverMonitorVtecEventDataManager getVtecEventDataManager() - { - return _riverMonitorVtecEventDataManager; - } - - public boolean getAlertUpperLimit() - { - return _alertUpperLimit; - } - - public void setAlertUpperLimit(boolean alertUpperLimit) - { - _alertUpperLimit = alertUpperLimit; - } - - public boolean getAlarmUpperLimit() - { - return _alarmUpperLimit; - } - - public void setAlarmUpperLimit(boolean alarmUpperLimit) - { - _alarmUpperLimit = alarmUpperLimit; - } - - public boolean getAlertLowerLimit() - { - return _alertLowerLimit; - } - - public void setAlertLowerLimit(boolean alertLowerLimit) - { - _alertLowerLimit = alertLowerLimit; - } - - public boolean getAlarmLowerLimit() - { - return _alarmLowerLimit; - } - - public void setAlarmLowerLimit(boolean alarmLowerLimit) - { - _alarmLowerLimit = alarmLowerLimit; - } - - public boolean getAlertRocLimit() - { - return _alertRocLimit; - } - - public void setAlertRocLimit(boolean alertRocLimit) - { - _alertRocLimit = alertRocLimit; - } - - public boolean getAlarmRocLimit() - { - return _alarmRocLimit; - } - - public void setAlarmRocLimit(boolean alarmRocLimit) - { - _alarmRocLimit = alarmRocLimit; - } - - public boolean getAlertDiffLimit() - { - return _alertDiffLimit; - } - - public void setAlertDiffLimit(boolean alertDiffLimit) - { - _alertDiffLimit = alertDiffLimit; - } - - public boolean getAlarmDiffLimit() - { - return _alarmDiffLimit; - } - - public void setAlarmDiffLimit(boolean alarmDiffLimit) - { - _alarmDiffLimit = alarmDiffLimit; - } - - public String getPrimaryRiverPe() - { - return _primaryRiverPe; - } - - public void setPrimaryRiverPe(String pe) - { - _primaryRiverPe = pe; - } - - public PrecipData getPrecipData() - { - return _precipData; - } - - public void setPrecipData(PrecipData precipData) - { - _precipData = precipData; - } - - public String getToolTipTextForAlertAlarmSummary() - { - return _toolTipTextForAlertAlarmSummary; - } - - public void setToolTipTextForAlertAlarmSummary(String toolTipText) - { - _toolTipTextForAlertAlarmSummary = toolTipText; - } - - public String getObsTypeSource() - { - return _obsTypeSource; - } - - public void setObsTypeSource(String obsTypeSource) - { - _obsTypeSource = obsTypeSource; - } - - public String getFcstTypeSource() - { - return _fcstTypeSource; - } - - public void setFcstTypeSource(String fcstTypeSource) - { - _fcstTypeSource = fcstTypeSource; - } - - public VTECeventRecord getVtecEventRecordForEndTime() - { - return _riverMonitorVtecEventDataManager.getVtecEventRecordForEndTime(); - } - - public VTECeventRecord getVtecEventRecordForExpireTime() - { - return _riverMonitorVtecEventDataManager.getVtecEventRecordForExpireTime(); - } - - public SshpFcstDetails getSshpFcstDetails() - { - return _sshpFcstDetails; - } - - public void setSshpFcstDetails(SshpFcstDetails sshpFcstDetails) - { - this._sshpFcstDetails = sshpFcstDetails; - } - - public String getStringValue(long value, long missingValue) - { - String result = super.getStringValue(value, missingValue); - if(result != super.getMissingRepresentation()) - { - String tempStr = result.substring(5, result.length()-3); - tempStr = tempStr.replace('-','/'); - tempStr = tempStr.replace(' ', '-'); - result = tempStr; - } - return result; - } - - // If primary pe is null assume it to be stage. - protected boolean isPrimaryPeStage() - { - boolean result = true; - if(_primaryRiverPe != null) - { - if(_primaryRiverPe.length() != 2) - { - System.out.println("Primarype:["+ _primaryRiverPe+"]"+ "lid:"+getLid()+ "len:"+ _primaryRiverPe.length()); - } - if(_primaryRiverPe.charAt(0) != 'H') - result = false; - } - return result; - } - - public String getVtecSummary() - { - return (_riverMonitorVtecEventDataManager.getVtecSummary()); - } - - public long getEventEndTime() - { - int numOfHrsForVtecEventProductTimeLookBack = _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack(); - long earliestAcceptableTimeForVtecEventProductTimeLookBack = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForVtecEventProductTimeLookBack; - - return (_riverMonitorVtecEventDataManager.getEventEndTime(earliestAcceptableTimeForVtecEventProductTimeLookBack)); - } - - public long getUGCExpireTime() - { - int numOfHrsForVtecEventProductTimeLookBack = _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack(); - long earliestAcceptableTimeForVtecEventProductTimeLookBack = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForVtecEventProductTimeLookBack; - - return (_riverMonitorVtecEventDataManager.getUGCExpireTime(earliestAcceptableTimeForVtecEventProductTimeLookBack)); - } - - public String getAlertAlarmSummary() - { - String summary = ""; - StringBuffer summaryStringBufffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - if(_alertUpperLimit || _alarmUpperLimit || _alertLowerLimit || _alarmLowerLimit|| _alertRocLimit || - _alarmRocLimit || _alertDiffLimit || _alarmDiffLimit) - { - toolTipStringBuffer.append(""); - } - _toolTipTextForAlertAlarmSummary = ""; - if(_alertUpperLimit) - { - summaryStringBufffer = summaryStringBufffer.append("u"); - toolTipStringBuffer.append("u: Value Exceeded Alert Upper Limit\n
"); - } - else if(_alarmUpperLimit) - { - summaryStringBufffer = summaryStringBufffer.append("U"); - toolTipStringBuffer.append("U: Value Exceeded Alarm Upper Limit\n
"); - } - if(_alertLowerLimit) - { - summaryStringBufffer = summaryStringBufffer.append("l"); - toolTipStringBuffer.append("l: Value Exceeded Alert Lower Limit\n
"); - } - else if(_alarmLowerLimit) - { - summaryStringBufffer = summaryStringBufffer.append("L"); - toolTipStringBuffer.append("L: Value Exceeded Alarm Lower Limit\n
"); - } - if(_alertRocLimit) - { - summaryStringBufffer = summaryStringBufffer.append("c"); - toolTipStringBuffer.append("c: Value Exceeded Alert ROC Limit
"); - } - else if(_alarmRocLimit) - { - summaryStringBufffer = summaryStringBufffer.append("C"); - toolTipStringBuffer.append("C: Value Exceeded Alarm ROC Limit
"); - } - if(_alertDiffLimit) - { - summaryStringBufffer = summaryStringBufffer.append("d"); - toolTipStringBuffer.append("d: Value Exceeded Alert Diff Limit\n
"); - } - else if(_alarmDiffLimit) - { - summaryStringBufffer = summaryStringBufffer.append("D"); - toolTipStringBuffer.append("D: Value Exceeded Alarm Diff Limit\n
"); - } - - summary = summaryStringBufffer.toString(); - _toolTipTextForAlertAlarmSummary = toolTipStringBuffer.toString(); - return summary; - } - - public String getToolTipTextForThreatSummary() - { - return _toolTipTextForThreatSummary; - } - - public void setToolTipTextForThreatSummary(String toolTipText) - { - _toolTipTextForThreatSummary = toolTipText; - } - - public String getToolTipTextForPrecipThreatSummary() - { - return _toolTipTextForPrecipThreatSummary; - } - - public void setToolTipTextForPrecipThreatSummary(String toolTipText) - { - _toolTipTextForPrecipThreatSummary = toolTipText; - } - - - public void addAllCellsToMap() - { - ThreatLevel defaultThreatLevel = ThreatLevel.NO_THREAT; - MonitorCell cell = null; - String header = "RiverMonitorJTableRowData2.addAllCellsToMap(): "; - - String dateTimeFormatString = "MM/dd - HH:mm"; - - //static data - - addToCellMap(RiverColumns.PRIMARY_RIVER_PE, CellType.STRING, getPrimaryRiverPe() ); - - addToCellMap(RiverColumns.GROUP_NAME, CellType.STRING, getGroupName() ); - addToCellMap(RiverColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(RiverColumns.GROUP_ORDINAL, CellType.INTEGER, getGroupOrdinal()); - - addToCellMap(RiverColumns.LOCATION_ID, CellType.STRING, getLid() ); - addToCellMap(RiverColumns.LOCATION_NAME, CellType.STRING, getName() ); - addToCellMap(RiverColumns.LOCATION_ORDINAL, CellType.INTEGER, getLocationOrdinal()); - - addToCellMap(RiverColumns.COUNTY, CellType.STRING, getCounty() ); - - addToCellMap(RiverColumns.STATE, CellType.STRING, getState() ); - addToCellMap(RiverColumns.STREAM, CellType.STRING, getStream() ); - addToCellMap(RiverColumns.RIVER_BASIN, CellType.STRING, getRiverBasin() ); - addToCellMap(RiverColumns.HSA, CellType.STRING, getHsa() ); - addToCellMap(RiverColumns.BANK_FULL, CellType.DOUBLE, getBankFull() ); - addToCellMap(RiverColumns.FLD_STG, CellType.DOUBLE, getFloodStage() ); - addToCellMap(RiverColumns.ACT_STG, CellType.DOUBLE, getActionStage() ); - - addToCellMap(RiverColumns.FLD_FLOW, CellType.DOUBLE, getFloodFlow(), defaultThreatLevel, getMissingRepresentation(), 0); - addToCellMap(RiverColumns.ACT_FLOW, CellType.DOUBLE, getActionFlow(), defaultThreatLevel, getMissingRepresentation(), 0); - - addToCellMap(RiverColumns.MIN_STG, CellType.DOUBLE, getMinorStage()); - addToCellMap(RiverColumns.MAJ_STG, CellType.DOUBLE, getMajorStage()); - addToCellMap(RiverColumns.MOD_STG, CellType.DOUBLE, getModerateStage()); - - //dynamic data - int numOfHrsForObsLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - long earliestAcceptableTimeForObs = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForObsLookBack; - - // latest obs value and time - ThreatLevel latestObsValueThreatLevel = getThreatLevelForLatestObsValue(earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_OBS_VALUE, CellType.DOUBLE, - getLatestObsValue(), latestObsValueThreatLevel, - getMissingRepresentation()); - - ThreatLevel latestObsTimeThreatLevel = getThreatLevelForThisTime(getLatestObsTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_OBS_TIME, CellType.DATE_TIME, - getLatestObsTime(), latestObsTimeThreatLevel, - getMissingRepresentation(), dateTimeFormatString ); - - - // latest stage value and time - ThreatLevel latestStageValueThreatLevel = getThreatLevelForStage(getLatestStgValue(),getLatestStgTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_STG_VALUE, CellType.DOUBLE, getLatestStgValue(), latestStageValueThreatLevel, getMissingRepresentation(), 2); - - ThreatLevel latestStageTimeThreatLevel = getThreatLevelForThisTime(getLatestStgTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_STG_TIME, CellType.DATE_TIME, getLatestStgTime(), latestStageTimeThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - - // latest flow value and time - ThreatLevel latestFlowValueThreatLevel = getThreatLevelForFlow(getLatestFlowValue(), getLatestFlowTime(), earliestAcceptableTimeForObs ); - addToCellMap(RiverColumns.LAT_FLOW_VALUE, CellType.DOUBLE, getLatestFlowValue(), latestFlowValueThreatLevel); - - ThreatLevel latestFlowTimeThreatLevel = getThreatLevelForThisTime(getLatestFlowTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_FLOW_TIME, CellType.DATE_TIME, getLatestFlowTime(), latestFlowTimeThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - - int numOfHrsForFcstLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - long earliestAcceptableTimeForFcst = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForFcstLookBack; - - //max forecast - ThreatLevel maxForecastThreatLevel = getThreatLevelForMaxFcstValue(earliestAcceptableTimeForFcst); - addToCellMap(RiverColumns.MAX_FCST_VALUE, CellType.DOUBLE, getMaxFcstValue(), maxForecastThreatLevel); - - addToCellMap(RiverColumns.MAX_FCST_VALID_TIME, CellType.DATE_TIME, getMaxFcstValidTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - addToCellMap(RiverColumns.MAX_FCST_BASIS_TIME, CellType.DATE_TIME, getMaxFcstBasisTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - //sshp forecast - addToCellMap(RiverColumns.SSHP_MAX_FCST_VALID_TIME, CellType.DATE_TIME, getSshpMaxFcstValidTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - addToCellMap(RiverColumns.SSHP_FCST_BASIS_TIME, CellType.DATE_TIME, getSshpFcstBasisTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - ThreatLevel maxSshpForecastThreatLevel = getThreatLevelForSshpFcstValue(earliestAcceptableTimeForFcst); - addToCellMap(RiverColumns.SSHP_MAX_FCST_VALUE, CellType.DOUBLE, getSshpMaxFcstValue(), maxSshpForecastThreatLevel); - - ThreatLevel maxSshpFcstFloodTimeThreatLevel = getThreatLevelForSshpTimeAboveFloodLevel(earliestAcceptableTimeForFcst); - addToCellMap(RiverColumns.SSHP_FCST_FLD_TIME, CellType.DATE_TIME, getSshpFcstFloodTime(), maxSshpFcstFloodTimeThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - ThreatLevel obsFcstMaxThreatLevel = getThreatLevelForObsFcstMax(); - addToCellMap(RiverColumns.OBSFCST_MAX, CellType.DOUBLE, getObsFcstMax(), obsFcstMaxThreatLevel, getMissingRepresentation(), 2); - - //stg departures - addToCellMap(RiverColumns.FLD_STG_DEP, CellType.DOUBLE, getFldStgDeparture()); - addToCellMap(RiverColumns.ACT_STG_DEP, CellType.DOUBLE, getActStgDeparture()); - - addToCellMap(PrecipColumns.LATEST_PRECIP_PARAM_CODE, CellType.STRING, getPrecipData().getLatestPrecipParamCodeString() ); - - addToCellMap(PrecipColumns.LATEST_30MIN, CellType.DOUBLE, getPrecipData().getLatestPrecip30Min()); - addToCellMap(PrecipColumns.LATEST_1HR, CellType.DOUBLE, getPrecipData().getLatestPrecip1Hr(), getThreatLevelForPrecipColumn("INSTANT", 1)); - addToCellMap(PrecipColumns.LATEST_3HR, CellType.DOUBLE, getPrecipData().getLatestPrecip3Hr(), getThreatLevelForPrecipColumn("INSTANT", 3)); - addToCellMap(PrecipColumns.LATEST_6HR, CellType.DOUBLE, getPrecipData().getLatestPrecip6Hr(), getThreatLevelForPrecipColumn("INSTANT", 6)); - - addToCellMap(PrecipColumns.LATEST_12HR, CellType.DOUBLE, getPrecipData().getLatestPrecip12Hr()); - addToCellMap(PrecipColumns.LATEST_18HR, CellType.DOUBLE, getPrecipData().getLatestPrecip18Hr()); - addToCellMap(PrecipColumns.LATEST_24HR, CellType.DOUBLE, getPrecipData().getLatestPrecip24Hr()); - - addToCellMap(PrecipColumns.TOH_PRECIP_1HR_PARAM_CODE, CellType.STRING, getPrecipData().getTohPrecip1HrParamCodeString() ); - - addToCellMap(PrecipColumns.TOH_PRECIP_1HR, CellType.DOUBLE, getPrecipData().getTohPrecip1Hr(), getThreatLevelForPrecipColumn("PRECIP", 1)); - - addToCellMap(PrecipColumns.FFG_1HR, CellType.DOUBLE, getPrecipData().getFFG1Hr()); - addToCellMap(PrecipColumns.FFG_3HR, CellType.DOUBLE, getPrecipData().getFFG3Hr()); - addToCellMap(PrecipColumns.FFG_6HR, CellType.DOUBLE, getPrecipData().getFFG6Hr()); - - addToCellMap(PrecipColumns.DIFF_1HR, CellType.DOUBLE, getPrecipData().getDiff1Hr(), getThreatLevelForPrecipColumn("DIFF", 1)); - addToCellMap(PrecipColumns.DIFF_3HR, CellType.DOUBLE, getPrecipData().getDiff3Hr(), getThreatLevelForPrecipColumn("DIFF", 3)); - addToCellMap(PrecipColumns.DIFF_6HR, CellType.DOUBLE, getPrecipData().getDiff6Hr(), getThreatLevelForPrecipColumn("DIFF", 6)); - - addToCellMap(PrecipColumns.RATIO_1HR, CellType.INTEGER, getPrecipData().getRatio1Hr(), getThreatLevelForPrecipColumn("RATIO", 1)); - addToCellMap(PrecipColumns.RATIO_3HR, CellType.INTEGER, getPrecipData().getRatio3Hr(), getThreatLevelForPrecipColumn("RATIO", 3)); - addToCellMap(PrecipColumns.RATIO_6HR, CellType.INTEGER, getPrecipData().getRatio6Hr(), getThreatLevelForPrecipColumn("RATIO", 6)); - - addToCellMap(RiverColumns.ALERT_ALARM, CellType.STRING, getAlertAlarmSummary(), getThreatLevelForAlertAlarmSummary()); - - int numOfHrsForVtecEventEndTimeLookAhead = 1; - numOfHrsForVtecEventEndTimeLookAhead = _menuSettings.getRiverSettings().getVtecEventEndTimeApproach(); - ThreatLevel vtecEventTimeThreatLevel = getThreatLevelForVtecTimeCell(getEventEndTime(), numOfHrsForVtecEventEndTimeLookAhead); - - addToCellMap(RiverColumns.VTEC_SUMMARY, CellType.STRING, getVtecSummary(),vtecEventTimeThreatLevel) ; - - // use a different missing representation - String vtecTimeMissingRepresentation = getEventEndTimeOrUgcExpireTimeMissingRepresentation(getMissingRepresentation()); - addToCellMap(RiverColumns.EVENT_END_TIME, CellType.DATE_TIME, getEventEndTime(), vtecEventTimeThreatLevel, vtecTimeMissingRepresentation, dateTimeFormatString ); - - int numOfHrsForExpireTimeLookAhead = 1; - numOfHrsForExpireTimeLookAhead = _menuSettings.getRiverSettings().getUgcExpireTimeApproach(); - ThreatLevel vtecUgcExpireTimeThreatLevel = getThreatLevelForVtecTimeCell(getUGCExpireTime(), numOfHrsForExpireTimeLookAhead); - - addToCellMap(RiverColumns.UGC_EXPIRE_TIME, CellType.DATE_TIME, getUGCExpireTime(), vtecUgcExpireTimeThreatLevel, vtecTimeMissingRepresentation, dateTimeFormatString); - - ThreatLevel threatLevel = getThreatLevelForPrecipThreatSummary(); - cell = addToCellMap(PrecipColumns.PRECIP_THREAT, CellType.EXTENSION, - getPrecipThreatSummary(), threatLevel, - getMissingRepresentation()); - - threatLevel = getThreatLevelForThreatSummary(); - cell = addToCellMap(RiverColumns.THREAT, CellType.EXTENSION, - getThreatSummary(), threatLevel, - getMissingRepresentation()); - - - // addCell(cell); - - } //end addAllCellsToMap - - // ----------------------------------------------------------------------------------- - public double round(double value, int decimalPlacesToMaintain) - { - return MathHelper.roundToNDecimalPlaces(value, decimalPlacesToMaintain); - } - - // ----------------------------------------------------------------------------------- - - public String getEventEndTimeOrUgcExpireTimeMissingRepresentation(String standardMissingRepresentation) - { - String missingRepresentationString = standardMissingRepresentation; - - if(_riverMonitorVtecEventDataManager.thereAreAnyActiveEventsForThisLocation()) - { - missingRepresentationString = "TBD"; - } - - return missingRepresentationString; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel,Color cellBackgroundColor, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, cellBackgroundColor, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, Color cellBackgroundColor) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, cellBackgroundColor, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - protected void addDerivedDataToCellMap() - { - // add all derived columns as well - List derivedColumnsDetailsList = this.getDerivedColumnsDetailsList(); - for(int i=0 ; i < derivedColumnsDetailsList.size(); i++) - { - DerivedColumn desc1 = (DerivedColumn) derivedColumnsDetailsList.get(i); - - CellType cellType = getCellTypeFromReturnType(desc1.getReturnType()); - - addToCellMap(desc1.getColumnName(), cellType, desc1.getValue(), desc1.getCellBackgroundColor()); - } - } - // ----------------------------------------------------------------------------------- - - public Color getCellBackgroundColorForThreatSummary() - { - return getCellBackgroundColor("Threat"); - } - - private CellType getCellTypeFromReturnType(String derivedColumnReturnType) - { - CellType cellType = null; - - cellType = (CellType) _derivedReturnTypeToCellTypeMap.get(derivedColumnReturnType.toLowerCase()); - - return cellType; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value) - { - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, getMissingRepresentation()); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } -// ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, missingRepresentation, _defaultDecimalPoints); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - String dateFormatString) - { - - MonitorCell cell = new MonitorCell (columnName, cellType, value, threatLevel, - missingRepresentation, dateFormatString); - - - // addToCellMap(cell); - addCell(cell); - - - return cell; - } - - - // ----------------------------------------------------------------------------------- - - public Color getCellBackgroundColor(String columnName) - { - Color color = Color.white; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellBackgroundColor(); - } - - return color; - } - - // ----------------------------------------------------------------------------------- - - public Color getCellForegroundColor(String columnName) - { - Color color = Color.black; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellForegroundColor(); - } - return color; - } - - - // helper methods - - // ----------------------------------------------------------------------------------- - public Color getCriticalColorForThisRow() - { - Color color = Color.WHITE; - ThreatLevel level = getRiverMonitorThreatLevel(); - if(level == ThreatLevel.ALERT) - { - color = Color.RED; - } - else if(level == ThreatLevel.CAUTION) - { - color = Color.YELLOW; - } - else if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - color = Color.GRAY; - } - else - { - boolean flowLevelIsPresent = false; - boolean stageLevelIsPresent = false; - - if( ! DbTable.isNull(getFloodFlow()) && ! DbTable.isNull(getActionFlow()) ) - { - flowLevelIsPresent = true; - } - if( ! DbTable.isNull(getFloodStage()) && ! DbTable.isNull(getActionStage()) ) - { - stageLevelIsPresent = true; - } - if(flowLevelIsPresent || stageLevelIsPresent) - { - color = new Color(0, 153, 0); // Dark green - } - } - - return color; - } - - // ----------------------------------------------------------------------------------- - public ThreatLevel getThreatLevelForThreatSummary() - { - ThreatLevel level = getRiverMonitorThreatLevel(); - - //Threat cell should be color red/yellow/white. So skip threat aged / missing threat level - if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - - return level; - } - - // ----------------------------------------------------------------------------------- - public ThreatLevel getThreatLevelForPrecipThreatSummary() - { - ThreatLevel level = getPrecipThreatLevelForPrecipThreatSummary(); - - //Threat cell should be color red/yellow/white. So skip threat aged / missing threat level - if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - - return level; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getRiverMonitorThreatLevel() - { - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = new ArrayList( getCellMap().values()); - cellThreatLevel = getMaxRowThreatLevel(cellList); - - return cellThreatLevel; - } -// ----------------------------------------------------------------------------------- - public ThreatLevel getMaxRowThreatLevel(List cellList) - { - String header = "RiverMonitorJTableRowData.getMaxRowThreatLevel(): "; - //this method assumes that the threat column has not yet been added to the cell map, when this - // method is invoked - ThreatLevel level = ThreatLevel.NO_THREAT; - ThreatLevel maxLevel = ThreatLevel.ALERT; - - //make sure the threat cell's threat level does not get used to calculate row's threat level, so clear it to zero - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - //iterate through each cell, and set the level to the max threat level found - for (int i = 0; i < cellList.size(); i++) - { - - MonitorCell cell = (MonitorCell) cellList.get(i); - - if (cell == null) - { - continue; - } - else - { - cellThreatLevel = cell.getThreatLevel(); - - - if ( _ignoreColumnNameForThreatSet.contains(cell.getColumnName()) ) - { - //ignore this column - } - - else if (cellThreatLevel.isGreater(level)) - { - //System.out.println(header + "Cell " + cell.getColumnName() + " cellThreatLevel = " + cellThreatLevel); - level = cellThreatLevel; - if (level == maxLevel) - { - break; //quit looking, because we have determined it is maxed out - } - } - } - } - return level; - } - - // ----------------------------------------------------------------------------------- - - public List getPrecipCells() - { - List cellList = new ArrayList(); - - addCell(cellList, PrecipColumns.LATEST_30MIN); - addCell(cellList, PrecipColumns.LATEST_1HR); - addCell(cellList, PrecipColumns.LATEST_3HR ); - addCell(cellList, PrecipColumns.LATEST_6HR ); - - addCell(cellList, PrecipColumns.TOH_PRECIP_1HR ); - - addCell(cellList, PrecipColumns.DIFF_1HR ); - addCell(cellList, PrecipColumns.DIFF_3HR ); - addCell(cellList, PrecipColumns.DIFF_6HR ); - - addCell(cellList, PrecipColumns.RATIO_1HR ); - addCell(cellList, PrecipColumns.RATIO_3HR ); - addCell(cellList, PrecipColumns.RATIO_6HR ); - - return cellList; - } - - // ----------------------------------------------------------------------------------- - - private void addCell(List cellList, String columnName ) - { - MonitorCell cell = null; - - cell = (MonitorCell) getCellMap().get(columnName); - if(cell != null) - { - cellList.add(cell); - } - - return; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getPrecipThreatLevelForPrecipThreatSummary() - { - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = getPrecipCells(); - cellThreatLevel = getMaxRowThreatLevel(cellList); - - return cellThreatLevel; - } - - //---------------------------------------------------------------------------------- - - public ThreatLevel getThreatLevelForValueAtThisTime(double value, long time, long earliestAcceptableTime, - double actionValue, double floodValue) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if (DbTable.isNull(value)) - { - level = ThreatLevel.MISSING_DATA; - //level = ThreatLevel.NO_THREAT; - } - else if(isDataAged(time, earliestAcceptableTime)) - { - level = ThreatLevel.AGED_DATA; - //level = ThreatLevel.NO_THREAT; - } - else if( ( ! DbTable.isNull(floodValue)) && value >= floodValue) - { - level = ThreatLevel.ALERT; - } - else if(( ! DbTable.isNull(actionValue)) && value >= actionValue) - { - level = ThreatLevel.CAUTION; - } - - return level; - } - // ------------------------------------------------------------------------------------- - - public ThreatLevel getThreatLevelForThisTime(long time, long earliestAcceptableTime) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - if (DbTable.isNull(time)) - { - level = ThreatLevel.MISSING_DATA; - } - else if(isDataAged(time, earliestAcceptableTime)) - { - level = ThreatLevel.AGED_DATA; - } - return level; - } - // ------------------------------------------------------------------------------------- - /* - * The sshp time above flood level cell is colored red if there is any value in it, - * or it is colored white if it is blank or if the basis time is outside the window - */ - public ThreatLevel getThreatLevelForSshpTimeAboveFloodLevel(long earliestAcceptableTime) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - if(isDataAged(getSshpFcstBasisTime(), earliestAcceptableTime)) - { - level = ThreatLevel.NO_THREAT; - } - else if (! DbTable.isNull(getSshpFcstFloodTime())) - { - level = ThreatLevel.ALERT; - } - return level; - } - - //-------------------------------------------------------------------------------------- - /* - * Returns true if the data is aged, by checking the time with earliestAcceptableTime - */ - protected boolean isDataAged(long time, long earliestAcceptableTime) - { - boolean result = false; - - if (time < earliestAcceptableTime) - { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelBasedOnPrimaryPe(double value, long time, long earliestAcceptableTime) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - if(isPrimaryPeStage()) - { - level = getThreatLevelForStage( value, time, earliestAcceptableTime); - } - else // 'Q'-- flow - { - level = getThreatLevelForFlow( value, time, earliestAcceptableTime); - - } - return level; - } - // ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForLatestObsValue(long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelBasedOnPrimaryPe(getLatestObsValue(), getLatestObsTime(), earliestAcceptableTime); - return level; - } - - // ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForStage(double value, long time, long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelForValueAtThisTime(value, time, earliestAcceptableTime, - getActionStage(), getFloodStage()); - - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForFlow(double value, long time, long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelForValueAtThisTime(value, time, earliestAcceptableTime, - getActionFlow(), getFloodFlow()); - return level; - } - // ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForMaxFcstValue(long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelBasedOnPrimaryPe(getMaxFcstValue(), getMaxFcstBasisTime(), earliestAcceptableTime); - if(level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForSshpFcstValue(long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelForStage(getSshpMaxFcstValue(), getSshpFcstBasisTime(), earliestAcceptableTime); - if(level == ThreatLevel.MISSING_DATA || level == ThreatLevel.AGED_DATA) - { - level = ThreatLevel.NO_THREAT; - } - return level; - } -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelBasedOnValue(double value, double floodLevel, double actionLevel) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(DbTable.isNull(value)) - { - level = ThreatLevel.MISSING_DATA; - } - else if(floodLevel != DbTable.getNullDouble() && value > floodLevel) - { - level = ThreatLevel.ALERT; - } - else if( actionLevel != DbTable.getNullDouble() && value > actionLevel) - { - level = ThreatLevel.CAUTION; - } - return level; - } - - -// ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForObsFcstMax() - { - ThreatLevel level = ThreatLevel.NO_THREAT; - int numOfHrsToLookBack ; - long earliestAcceptableTime ; - - if(getMaxFcstValue() == getLatestObsValue()) - { - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - ThreatLevel obslevel = getThreatLevelForLatestObsValue(earliestAcceptableTime); - - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - ThreatLevel fcstlevel = getThreatLevelForMaxFcstValue(earliestAcceptableTime); - - if(obslevel == fcstlevel && obslevel == ThreatLevel.AGED_DATA) - { - level = obslevel; - } - else if(obslevel.isGreater(fcstlevel)) - { - if(obslevel != ThreatLevel.AGED_DATA) - level = obslevel; - } - else - { - if(fcstlevel != ThreatLevel.AGED_DATA) - level = fcstlevel; - } - } - else if(getObsFcstMax() == getMaxFcstValue()) // Fcst data - { - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - level = getThreatLevelForMaxFcstValue(earliestAcceptableTime); - } - else // obs data - { - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - level = getThreatLevelForLatestObsValue(earliestAcceptableTime); - } - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForAlertAlarmSummary() - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - String summary = getAlertAlarmSummary(); - - int indexOfL, indexOfU, indexOfC, indexOfR, indexOfD; - indexOfL = -1; indexOfU = -1; indexOfC = -1; indexOfD = -1; indexOfR = -1; - - if(summary.length() > 0) - { - indexOfL = summary.indexOf('L'); - indexOfU = summary.indexOf('U'); - indexOfC = summary.indexOf('C'); - indexOfD = summary.indexOf('D'); - indexOfR = summary.indexOf('R'); - if(indexOfL != -1 || indexOfU != -1 || indexOfC != -1 || indexOfD != -1 || indexOfR != -1 ) - { - level = ThreatLevel.ALERT; - } - else - { - level = ThreatLevel.CAUTION; - } - } - - return level; - } -// ------------------------------------------------------------------------------------- - private ThreatLevel getPrecipThreatLevel(double value, double alert, double caution) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(! DbTable.isNull(value)) - { - if(value >= alert) - level = ThreatLevel.ALERT; - else if(value >= caution) - level = ThreatLevel.CAUTION; - } - - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipValueThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings, String type) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double missing = DbTable.getNullDouble(); - double value; - switch(hour) - { - - case 1: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip1Hr(); - else - value = _precipData.getTohPrecip1Hr(); - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert1Hr(), precipSettings.getPrecipCaution1Hr()); - break; - - case 3: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip3Hr(); - else - // value = _precipData.getTohPrecip3Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert3Hr(), precipSettings.getPrecipCaution3Hr()); - break; - case 6: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip6Hr(); - else - //value = _precipData.getTohPrecip6Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert6Hr(), precipSettings.getPrecipCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipRatioThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - int value; - switch(hour) - { - - case 1: - value = _precipData.getRatio1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert1Hr(), precipSettings.getRatioCaution1Hr()); - break; - case 3: - value = _precipData.getRatio3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert3Hr(), precipSettings.getRatioCaution6Hr()); - break; - case 6: - value = _precipData.getRatio6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert6Hr(), precipSettings.getRatioCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipDiffThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double value; - - switch(hour) - { - case 1: - value = _precipData.getDiff1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert1Hr(), precipSettings.getDiffCaution1Hr()); - break; - case 3: - value = _precipData.getDiff3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert3Hr(), precipSettings.getDiffCaution3Hr()); - break; - case 6: - value = _precipData.getDiff6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert6Hr(), precipSettings.getDiffCaution6Hr()); - break; - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForPrecipColumn(String type, int hour) - { - - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(type.compareTo("INSTANT") == 0) // instant precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings(), "INSTANT"); - } - else if(type.compareTo("TOH") == 0) // toh precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings(), "TOH"); - } - else if(type.compareTo("RATIO") == 0) - { - level = getPrecipRatioThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings()); - } - else //type is DIFF - { - level = getPrecipDiffThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings()); - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForVtecTimeCell(long time, long lookAheadHrs) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - long curTime = System.currentTimeMillis(); - String summary = getVtecSummary(); - - if(summary.length() > 0) - { - if(time != DbTable.getNullLong()) - { - if((curTime + (TimeHelper.MILLIS_PER_HOUR*lookAheadHrs)) >= time) - { - level = ThreatLevel.ALERT; - } - else - { - level = ThreatLevel.CAUTION; - } - } - else - { - level = ThreatLevel.CAUTION; - } - } - return level; - } - -// ------------------------------------------------------------------------------------- - - public ThreatLevel getCellThreatLevelForColumn(String columnName) - { - ThreatLevel level; - - MonitorCell cell = (MonitorCell) getCellMap().get(columnName); - - level = cell.getThreatLevel(); - - return level; - } - -// ------------------------------------------------------------------------------------- - - - public String getThreatSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - - ThreatLevel level; - level = getCellThreatLevelForColumn(RiverColumns.ALERT_ALARM); - if(level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("A"); - toolTipStringBuffer.append(_toolTipTextForAlertAlarmSummary); - } - - level = getThreatLevelForPrecipThreatSummary(); - if(level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("P"); - String precipThreatSummary = getPrecipThreatSummary(); - if(precipThreatSummary.contains("L")) - { - toolTipStringBuffer.append("P: Latest Precip has exceeded threat level
"); - } - if(precipThreatSummary.contains("T")) - { - toolTipStringBuffer.append("P: Top of the Hour Precip has exceeded threat level
"); - } - if(precipThreatSummary.contains("D")) - { - toolTipStringBuffer.append("P: TOH Precip - FFG diff has exceeded threat level
"); - } - if(precipThreatSummary.contains("R")) - { - toolTipStringBuffer.append("P: TOH Precip / FFG ratio has exceeded threat level
"); - } - } - - level = getCellThreatLevelForColumn(RiverColumns.VTEC_SUMMARY); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("V"); - int lookBackHours = _menuSettings.getRiverSettings().getVtecEventEndTimeApproach(); - String tempStr; - String eventEndTimeString = getDataValue(RiverColumns.EVENT_END_TIME); - if(level == ThreatLevel.ALERT) - { - tempStr = "V: VTEC EndTime["+ eventEndTimeString +"] is within " + lookBackHours+ "hrs
"; - } - else - { - tempStr = "V: VTEC EndTime["+ eventEndTimeString +"] is not within " + lookBackHours+ "hrs
"; - } - toolTipStringBuffer.append(tempStr); - } - - level = getCellThreatLevelForColumn(RiverColumns.UGC_EXPIRE_TIME); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION ) - { - summaryStringBuffer = summaryStringBuffer.append("X"); - int lookBackHours = _menuSettings.getRiverSettings().getUgcExpireTimeApproach(); - String tempStr ; - String ugcExpireTimeString = getDataValue(RiverColumns.UGC_EXPIRE_TIME); - if(level == ThreatLevel.ALERT) - { - tempStr = "X: UGC ExpireTime["+ ugcExpireTimeString +"] is within " + lookBackHours + "hrs or in the past
"; - } - else - { - tempStr = "X: UGC ExpireTime["+ ugcExpireTimeString +"] is not within " + lookBackHours+ "hrs
"; - } - toolTipStringBuffer.append(tempStr); - } - - - level = getCellThreatLevelForColumn(RiverColumns.MAX_FCST_VALUE); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("F"); - if(level == ThreatLevel.ALERT) - { - toolTipStringBuffer.append("F: FcstValue exceeded the flood level
"); - } - else - { - toolTipStringBuffer.append("F: FcstValue exceeded the action level
"); - } - - } - - level = getCellThreatLevelForColumn(RiverColumns.SSHP_MAX_FCST_VALUE); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("S"); - if(level == ThreatLevel.ALERT) - { - toolTipStringBuffer.append("S: Sshp FcstValue exceeded the flood level
"); - } - else - { - toolTipStringBuffer.append("S: Sshp FcstValue exceeded the action level
"); - } - - } - - level = ThreatLevel.NO_THREAT; // reset the threat level - - //check if any of the obs column are in alert threat - if((getCellThreatLevelForColumn(RiverColumns.LAT_OBS_VALUE) == ThreatLevel.ALERT) - || (getCellThreatLevelForColumn(RiverColumns.LAT_STG_VALUE) == ThreatLevel.ALERT) - || (getCellThreatLevelForColumn(RiverColumns.LAT_FLOW_VALUE) == ThreatLevel.ALERT)) - { - summaryStringBuffer = summaryStringBuffer.append("O"); - level = ThreatLevel.ALERT; - } - //check if any of the obs column are in caution threat - else if((getCellThreatLevelForColumn(RiverColumns.LAT_OBS_VALUE) == ThreatLevel.CAUTION) - || (getCellThreatLevelForColumn(RiverColumns.LAT_STG_VALUE) == ThreatLevel.CAUTION) - || (getCellThreatLevelForColumn(RiverColumns.LAT_FLOW_VALUE) == ThreatLevel.CAUTION)) - { - summaryStringBuffer = summaryStringBuffer.append("O"); - level = ThreatLevel.CAUTION; - } - - if(level == ThreatLevel.ALERT ) - { - toolTipStringBuffer.append("O: ObsValue exceeded the flood level
"); - } - else if(level == ThreatLevel.CAUTION) - { - toolTipStringBuffer.append("O: ObsValue exceeded the action level
"); - } - - summary = summaryStringBuffer.toString(); - _toolTipTextForThreatSummary = toolTipStringBuffer.toString(); - return summary; - } - - -// ------------------------------------------------------------------------------------- - - - public String getPrecipThreatSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - - ThreatLevel level; - ThreatLevel level1Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_1HR); - ThreatLevel level3Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_3HR); - ThreatLevel level6Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("L"); - toolTipStringBuffer.append("L: Latest Precip Exceeded the threshold
"); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_1HR); - // level3Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_3HR); - // level6Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) - /* - || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) - */ - ) - { - summaryStringBuffer = summaryStringBuffer.append("T"); - toolTipStringBuffer.append("T: Top Of The Hour Precip Exceeded the threshold
"); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("D"); - toolTipStringBuffer.append("D: TOH Precip - FFG Difference Exceeded the threshold
"); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("R"); - toolTipStringBuffer.append("R: TOH Precip / FFG Ratio Exceeded the threshold
"); - } - - summary = summaryStringBuffer.toString(); - _toolTipTextForPrecipThreatSummary = toolTipStringBuffer.toString(); - return summary; - } -// ------------------------------------------------------------------------------------- - - public void setRiverBasin(String riverBasin) - { - _riverBasin = riverBasin; - } - - public String getRiverBasin() - { - return _riverBasin; - } - - -} //end class diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorVtecEventDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorVtecEventDataManager.java deleted file mode 100755 index 906c34e25d..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/RiverMonitorVtecEventDataManager.java +++ /dev/null @@ -1,323 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; - -public class RiverMonitorVtecEventDataManager -{ - - private List _vtecAllEventList = null; - private List _mostRecentEventList = null; - private List _mostRecentActiveEventList = null; - private VTECeventRecord _vtecEventRecordForEndTime = null; - private VTECeventRecord _vtecEventRecordForExpireTime = null; - - public RiverMonitorVtecEventDataManager(List vtecAllEventList) - { - _vtecAllEventList = vtecAllEventList; - } - - public List getMostRecentEventList() - { - if(_mostRecentEventList == null) - _mostRecentEventList = calculateMostRecentEventList(); - return _mostRecentEventList; - } - - public List getMostRecentActiveEventList() - { - if(_mostRecentActiveEventList == null) - _mostRecentActiveEventList = calculateMostRecentActiveEventList(); - return _mostRecentActiveEventList; - } - - public VTECeventRecord getVtecEventRecordForEndTime() - { - return _vtecEventRecordForEndTime; - } - - public VTECeventRecord getVtecEventRecordForExpireTime() - { - return _vtecEventRecordForExpireTime; - } - - //Creates the list that contains the recent event info for each signif - public List calculateMostRecentEventList() - { - Map mostRecentEventMap = new HashMap(); - VTECeventRecord mostRecentEventRecord = null; - - if(_vtecAllEventList != null) - { - for(int i=0; i < _vtecAllEventList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) _vtecAllEventList.get(i); - String key = record.getSignif(); - - mostRecentEventRecord = (VTECeventRecord) mostRecentEventMap.get(key); - - //the first time, add the current record - if (mostRecentEventRecord == null) - { - mostRecentEventMap.put(key, record); - mostRecentEventRecord = record; - } - - else // this is not the first active record for this geoId|signif - { - //this one is more recent, so replace the old record. - if (record.getProducttime() > mostRecentEventRecord.getProducttime()) - { - mostRecentEventMap.put(key, record); - } - } - } - } - List mostRecentEventList = new ArrayList (mostRecentEventMap.values()); - - return mostRecentEventList; - } - - public List calculateMostRecentActiveEventList() - { - List mostRecentActiveEventList = null; - - getMostRecentEventList(); - - if(_mostRecentEventList != null) - { - for(int i=0;i < _mostRecentEventList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) _mostRecentEventList.get(i); - if(RiverMonitorVtecEventDataManager.checkIfEventActive(record)) - { - if(mostRecentActiveEventList == null) - { - mostRecentActiveEventList = new ArrayList(); - } - - mostRecentActiveEventList.add(record); - } - } - } - return mostRecentActiveEventList; - } - - public static boolean checkIfEventActive(VTECeventRecord record) - { - boolean active = false; - String action = record.getAction(); - long endTime = record.getEndtime(); - long curTime = System.currentTimeMillis(); - /* if the event is explicity expired or cancelled, - then the event tracking is not active. - also, all ROU events are considered inactive. - otherwise, see if the event end time has not passed yet */ - - if (action.equals("CAN") || action.equals("EXP") || - action.equals("ROU") || action.length() == 0) - { - active = false; - } - else - { - /* if the endtime is not specified, assume the event is still active. - unspecified can occur if the endtime has a missing value indicator - or is set to 0. A 0 value can occur because the time may be NULL in - the database, which is converted to a 0 value by the time conversion - functions. */ - - if (endTime == (long) DbTable.getNullLong()) - active = true; - else //end time is past the current time, so the event is still active. - { - if (endTime > curTime) - active = true; - else - active = false; - } - } - return(active); - } - - - public boolean thereAreAnyActiveEventsForThisLocation() - { - boolean result = false; - - getMostRecentActiveEventList(); - - if(_mostRecentActiveEventList != null)//there are active events - { - result = true; - } - return result; - } - - public String getVtecSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - - getMostRecentActiveEventList(); - - if(thereAreAnyActiveEventsForThisLocation()) - { - for(int i=0;i < _mostRecentActiveEventList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) _mostRecentActiveEventList.get(i); - summaryStringBuffer = summaryStringBuffer.append(record.getSignif()); - } - } - summary = summaryStringBuffer.toString(); - return summary; - } - - public long getEventEndTime(long earliestAcceptableTimeForVtecEventProductTimeLookBack) - { - VTECeventRecord record = null; - long endTime = DbTable.getNullLong(); - - getMostRecentActiveEventList(); - - //if there are any active events among the recent event for various signif - //use the one that has the endtime close to current time (which is the earliest endtime in the most recent event list) - if(thereAreAnyActiveEventsForThisLocation()) - { - // loop thru the mostRecentActiveEventsList - // This list will have size 0 (min) size 3 (max- accouting for W A Y) - // Find the earliest endtime - // Ignore the record with missing endtime - - long tempEndTime = Long.MAX_VALUE; - for (int i = 0; i < _mostRecentActiveEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentActiveEventList.get(i); - - if(record.getEndtime() != DbTable.getNullLong()) - { - if(record.getEndtime() < tempEndTime) - { - tempEndTime = record.getEndtime(); - endTime = tempEndTime; - _vtecEventRecordForEndTime = record; - } - } - } - - if(endTime == DbTable.getNullLong()) //ie., The recent active list has 1 or more events and all of their endtime is null - { - _vtecEventRecordForEndTime = (VTECeventRecord)_mostRecentActiveEventList.get(0); - } - } - else if(_mostRecentEventList != null)//No active events going on, so consider the latest/most recent endtime(max of all endtime) - { - for (int i = 0; i < _mostRecentEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentEventList.get(i); - - if(i==0) - { - endTime = record.getEndtime(); - _vtecEventRecordForEndTime = record; - } - else - { - if(record.getEndtime() > endTime) - { - endTime = record.getEndtime(); - _vtecEventRecordForEndTime = record; - } - } - } - - //check if the record's product time is within the window - if( _vtecEventRecordForEndTime != null && - (_vtecEventRecordForEndTime.getProducttime() < earliestAcceptableTimeForVtecEventProductTimeLookBack)) - { - _vtecEventRecordForEndTime = null; - endTime = DbTable.getNullLong(); - } - } - - return endTime; - } - - public long getUGCExpireTime(long earliestAcceptableTimeForVtecEventProductTimeLookBack) - { - VTECeventRecord record = null; - long expireTime = DbTable.getNullLong(); - - getMostRecentActiveEventList(); - - //if there are any active events among the recent event for various signif - //use the one that has the expiretime close to current time (which is the earliest endtime in the most recent event list) - if(thereAreAnyActiveEventsForThisLocation()) - { - // loop thru the mostRecentActiveEventsList - // This list will have size 0 (min) size 3 (max- accouting for W A Y) - // Find the earliest expiretime - // Ignore the record with missing expiretime - - long tempExpireTime = Long.MAX_VALUE; - for (int i = 0; i < _mostRecentActiveEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentActiveEventList.get(i); - - if(record.getExpiretime() != DbTable.getNullLong()) - { - if(record.getExpiretime() < tempExpireTime) - { - tempExpireTime = record.getExpiretime(); - _vtecEventRecordForExpireTime = record; - expireTime = tempExpireTime; - } - } - } - - if(expireTime == DbTable.getNullLong()) //ie., The recent active list has 1 or more events and all of their expiretime is null - _vtecEventRecordForExpireTime = (VTECeventRecord) _mostRecentActiveEventList.get(0);// expiretime will be TBD - - } - else if(_mostRecentEventList != null)//No active events going on, so consider the latest/most recent expiretime(max of all expiretime) - { - for (int i = 0; i < _mostRecentEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentEventList.get(i); - - if(i==0) - { - expireTime = record.getExpiretime(); - _vtecEventRecordForExpireTime = record; - } - else - { - if(record.getExpiretime() > expireTime) - { - expireTime = record.getExpiretime(); - _vtecEventRecordForExpireTime = record; - } - } - } - - //check if the record's product time is within the window - if(_vtecEventRecordForExpireTime != null && - (_vtecEventRecordForExpireTime.getProducttime() < earliestAcceptableTimeForVtecEventProductTimeLookBack)) - { - _vtecEventRecordForExpireTime = null; - expireTime = DbTable.getNullLong(); - } - } - - return expireTime; - } - - -// ------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorAppManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorAppManager.java deleted file mode 100755 index e16f98509e..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorAppManager.java +++ /dev/null @@ -1,152 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.Container; -import java.awt.GridBagLayout; - -import javax.swing.JPanel; -import javax.swing.JSplitPane; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.db.Database; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorSplitPane; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.util.MemoryLogger; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.vtecevent.VtecEventDataManager; -import com.raytheon.uf.common.ohd.AppsDefaults; - - -public class RiverMonitorAppManager { - private MessageSystemManager _msgSystemManager; - - private RiverMonitorDataManager _riverMonitorDataManager; - - private AppsDefaults _appsDefaults; - - public static final String DEFAULT_RIVER_SETTINGS_FILE = "DefaultRiverMonitorSettings.txt"; - - public static final String SITE_RIVER_SETTINGS_FILE = "RiverMonitorSettings.txt"; - - public static final String PE_CONFIG_FILE = "RiverMonitorPEConfig.txt"; - - private SessionLogger _logger; - - private MonitorFrame _mainFrame; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private String _appName = "RiverMonitor"; - - public static String DERIVED_COLUMNS_FILE = "DerivedColumns.txt"; - - public RiverMonitorAppManager(Database db, String missingRepresentation, - String version, String versionDate, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) { - - _appsDefaults = AppsDefaults.getInstance(); - - createLogger(); - - ViewSettings viewSettings = new ViewSettings(); - FilterSettings filterSettings = new FilterSettings(); - RiverMonitorMenuSettings menuSettings = new RiverMonitorMenuSettings(); - - createFrame(db, version); - - JSplitPane splitPane = new MonitorSplitPane( - JSplitPane.HORIZONTAL_SPLIT, true); - - JPanel timeDisplayPanel = new JPanel(); - JToolBar toolBar = new JToolBar(); - - OfficeNotesDataManager officeNotesDataMgr = new OfficeNotesDataManager( - db, _logger, missingRepresentation); - AlertAlarmDataManager alertAlarmDataMgr = new AlertAlarmDataManager(db, - _logger, missingRepresentation); - VtecEventDataManager vtecEventDataMgr = new VtecEventDataManager(db, - _logger, missingRepresentation); - - String settingsDir = _appsDefaults - .getToken("rivermon_config_dir", - "/awips2/awipsShare/hydroapps/whfs/local/data/app/rivermon"); - - _derivedColumnsFileManager = new DerivedColumnsFileManager(settingsDir - + "/" + DERIVED_COLUMNS_FILE, _logger); - - _riverMonitorDataManager = new RiverMonitorDataManager(db, - _appsDefaults, missingRepresentation, _logger, menuSettings, - _derivedColumnsFileManager); - - _msgSystemManager = new MessageSystemManager(); - - MemoryLogger.setLogger(_logger); - - new RiverMonitorRefreshManager(_msgSystemManager, _logger, - _riverMonitorDataManager, splitPane); - - new RiverMonitorFilterManager(_msgSystemManager, _logger, _mainFrame, - _riverMonitorDataManager, splitPane, _appsDefaults, - filterSettings); - - new RiverMonitorMenuManager(_msgSystemManager, _logger, _mainFrame, - version, versionDate, _appsDefaults, toolBar, - _riverMonitorDataManager, officeNotesDataMgr, - alertAlarmDataMgr, vtecEventDataMgr, menuSettings, - timeDisplayPanel, _appName, monitorTimeSeriesLiteManager); - - new RiverMonitorViewManager(_mainFrame, _msgSystemManager, _logger, - _riverMonitorDataManager, splitPane, viewSettings, - _derivedColumnsFileManager, monitorTimeSeriesLiteManager, - _appsDefaults); - - RiverMonitorSettingsManager settingsManager = new RiverMonitorSettingsManager( - _msgSystemManager, _appsDefaults, _logger, _mainFrame, - viewSettings, filterSettings, menuSettings); - - settingsManager.startRiverMonitor(); - - Container frameContentPane = _mainFrame.getContentPane(); - _mainFrame.setLayout(new GridBagLayout()); - - // col, row, width, height, weightx, weighty, fill - ComponentHelper.addFrameComponent(frameContentPane, toolBar, 0, 0, 1, - 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, timeDisplayPanel, - 1, 0, 1, 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, splitPane, 0, 1, 2, - 1, 1, 1, 1); - - _mainFrame.pack(); - _mainFrame.setVisible(true); - } - - private void createLogger() { - String logDir = _appsDefaults - .getToken("rivermon_log_dir", - "/awips2/awipsShare/hydroapps/whfs/local/data/log/rivermon"); - String logFile = logDir + "/" + _appName; - - _logger = new SessionLogger(_appName, logFile, true, true, null); - _logger.log(null); - _logger.log(_appName + " Started"); - - } - - private void createFrame(Database db, String version) { - _mainFrame = new MonitorFrame(); - String title = _appName + " DbName : " + db.getDatabaseName() - + " Session : " + _logger.getSessionId(); - _mainFrame.setTitle(title); - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorFilterManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorFilterManager.java deleted file mode 100755 index bcaa601715..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorFilterManager.java +++ /dev/null @@ -1,277 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; -import java.util.Map; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.TreeDataManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeManager; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeSelectionModel; -import ohd.hseb.util.SessionLogger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class RiverMonitorFilterManager extends BaseManager -{ - private SessionLogger _logger; - - private RiverMonitorDataManager _riverMonitorDataManager; - private FilterSettings _filterSettings; - - private JSplitPane _splitPane; - - private AppsDefaults _appsDefaults; - - private MonitorCheckTreeManager _checkTreeManager; - - private JScrollPane _treeScrollPane; - - private JPopupMenu _popupMenuForTree; - private JMenuItem _expandTreeMenuItem; - private JMenuItem _collapseTreeMenuItem; - - private MonitorFrame _mainFrame; - private String _iconsDir; - - - public RiverMonitorFilterManager(MessageSystemManager msgSystemManager,SessionLogger logger, - MonitorFrame mainFrame, RiverMonitorDataManager riverMonitorDataManager, JSplitPane splitPane, - AppsDefaults appsDefaults, FilterSettings filterSettings) - { - _riverMonitorDataManager = riverMonitorDataManager; - _splitPane = splitPane; - _appsDefaults = appsDefaults; - _mainFrame = mainFrame; - _filterSettings = filterSettings; - _iconsDir = _appsDefaults.getToken("rivermon_config_dir", "/awips/hydroapps/whfs/local/data/app/rivermon"); - - createPopupMenuForTree(); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), MessageType.REFRESH_DISPLAY); - } - - private void createTreeAndApplySettings(MonitorMessage message) - { - final String header = "RiverMonitorFilterManager.createTreeAndApplySettings(): "; - System.out.println(header + " thread = " + Thread.currentThread().getId()); - - _mainFrame.setWaitCursor(); - if(message.getMessageSource() != this) - { - System.out.println(header +" Invoked" + "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - List stringArrayListOfFilterItems = _riverMonitorDataManager.createStringArrayListOfFilterItems(); - - TreeDataManager treeDataManager = new TreeDataManager(); - - DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("HSA"); - - JTree tree = treeDataManager.createFilterTreeFromList(rootNode, stringArrayListOfFilterItems); - - tree.setBackground(Color.BLACK); - - TreePath[] preSelectedPaths = _filterSettings.getSelectedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preSelectedPaths :"); - - TreePath[] preExpandedPaths = _filterSettings.getExpandedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preExpandedPaths :"); - - Map lidToCriticalColorMap = _riverMonitorDataManager.getLidToCriticalColorMap(); - - _checkTreeManager = new MonitorCheckTreeManager(tree, preSelectedPaths, preExpandedPaths, lidToCriticalColorMap, _iconsDir); - CheckTreeSelectionListener treeListener = new CheckTreeSelectionListener(); - tree.addMouseListener(treeListener); - - _treeScrollPane = new JScrollPane(tree); - _treeScrollPane.setPreferredSize(new Dimension(300,645)); - - _splitPane.setLeftComponent(_treeScrollPane); - - // printTreePathArray(_checkTreeManager.getSelectionModel().getSelectionPaths(), "Create Tree: "); - - _riverMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(_checkTreeManager.getValidTreePaths(preSelectedPaths)); - - } - _mainFrame.setDefaultCursor(); - } - - private void highlightThisRow() - { - String header = "RiverMonitorFilterManager.highlightThisRow(): "; - - System.out.print(header ); - send(this, MessageType.FILTER_SELECT_ITEM); - } - - private void sendRefreshDisplayMessage() - { - String header = "RiverMonitorFilterManager.sendRefreshDisplayMessage(): "; - - System.out.print(header); - send(this, MessageType.REFRESH_DISPLAY); - } - - private void setFilterSettings() - { - String header = "RiverMonitorFilterManager.setFilterSettings(): "; - System.out.println(header); - - TreePath[] paths = _checkTreeManager.getSelectionModel().getSelectionPaths(); - _filterSettings.setSelectedPaths(paths); - - // printTreePathArray(paths, header + " selected path in "); - - TreePath[] expandedPaths = _checkTreeManager.getAllExpandedPaths(); - _filterSettings.setExpandedPaths(expandedPaths); - - } - - private void createPopupMenuForTree() - { - _popupMenuForTree = new JPopupMenu(); - _expandTreeMenuItem = new JMenuItem("Expand Entire Tree"); - _expandTreeMenuItem.setMnemonic('E'); - _collapseTreeMenuItem = new JMenuItem("Collapse Entire Tree"); - _collapseTreeMenuItem.setMnemonic('C'); - _popupMenuForTree.add(_expandTreeMenuItem); - _popupMenuForTree.add(_collapseTreeMenuItem); - - TreePopupMenuListener treePopupMenuListener = new TreePopupMenuListener(); - _expandTreeMenuItem.addActionListener(treePopupMenuListener); - _collapseTreeMenuItem.addActionListener(treePopupMenuListener); - } - - private void printTreePathArray(TreePath[] treePathArray, String message) - { - if (message != null) - { - System.out.println(message); - } - - if (treePathArray != null) - { - for (TreePath treePath : treePathArray) - { - System.out.println(treePath); - } - } - - return; - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - private class TreePopupMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - - TreePath[] allAvailablePaths = _checkTreeManager.getAllAvailablePaths(); - if(e.getSource().toString().contains("Expand Entire Tree")) - { - _checkTreeManager.expandThesePaths(allAvailablePaths); - } - else //collapse tree - { - _checkTreeManager.collapseEntireTree(); - } - - setFilterSettings(); - } - } - - class CheckTreeSelectionListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - - MonitorCheckTreeSelectionModel selectionModel = (MonitorCheckTreeSelectionModel) (_checkTreeManager.getSelectionModel()); - - selectionModel.printInstanceId(); - - TreePath paths[] = selectionModel.getSelectionPaths(); - - // printTreePathArray(paths, "CheckTreeSelectionListener.mouseClicked(): "); - - setFilterSettings(); - - _riverMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(paths); - sendRefreshDisplayMessage(); - - if(SwingUtilities.isLeftMouseButton(e)) - { - JTree tree = (JTree) e.getSource(); - int row = tree.getRowForLocation(e.getX(), e.getY()); - TreePath path = tree.getPathForRow(row); - String itemClickedOnJtree = null; - if(path != null) - { - if(path.getPathCount() == 4) - { - itemClickedOnJtree = path.getLastPathComponent().toString(); - System.out.println("Item of interest:"+ itemClickedOnJtree); - _riverMonitorDataManager.setLidOfCurrentInterest(itemClickedOnJtree); - highlightThisRow(); - } - } - } - } - public void mousePressed(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - - public void mouseReleased(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorMenuManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorMenuManager.java deleted file mode 100755 index 4416743862..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorMenuManager.java +++ /dev/null @@ -1,1145 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.swing.ButtonGroup; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButtonMenuItem; -import javax.swing.JSeparator; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.alertalarm.AlertAlarmDialog; -import ohd.hseb.monitor.Monitor; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.MonitorToolBarManager; -import ohd.hseb.monitor.manager.MonitorMenuManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.LookBackTimeDialog; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.monitor.river.settings.RiverColumnDataSettings; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.officenotes.OfficeNotesDialog; -import ohd.hseb.rivermonlocgroup.RiverMonGroupDialog; -import ohd.hseb.rivermonlocgroup.RiverMonLocationDialog; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.vtecevent.VtecEventDataManager; -import ohd.hseb.vtecevent.VtecEventDialog; - -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.common.util.RunProcess; - -public class RiverMonitorMenuManager extends MonitorMenuManager { - private JMenuBar _menuBar; - - private JMenu _fileMenu, _displayMenu, _sortMenu, _configMenu, - _detailsMenu, _helpMenu; - - private JMenu _fcstTsMenu; - - private JRadioButtonMenuItem _fcstTsFZMenuItem; - - private JRadioButtonMenuItem _fcstTsFFMenuItem; - - private JRadioButtonMenuItem _fcstTsIngestFilterMenuItem; - - private ButtonGroup _fcstTsGroup; - - private JMenuItem _selectColumnsMenuItem; - - private JCheckBoxMenuItem _showMissingRiverMenuItem; - - private JMenuItem _saveColumnSettingsMenuItem; - - private JMenuItem _loadSettingsMenuItem; - - private JMenuItem _loadOfficeSettingsMenuItem; - - private JMenuItem _saveOfficeSettingsMenuItem; - - private JMenuItem _refreshColumnMenuItem; - - private JMenuItem _exportTableToTextMenuItem; - - private JMenuItem _exitApplicationMenuItem; - - private JMenuItem _officeNotesMenuItem; - - private JMenuItem _alertAlarmMenuItem; - - private JMenuItem _vtecEventMenuItem; - - private JMenuItem _siteSpecificMenuItem; - - private JMenuItem _timeSeriesLiteMenuItem; - - private JMenuItem _riverMonitorPEConfigMenuItem; - - private JMenuItem _riverMonGroupMenuItem; - - private JMenuItem _riverMonLocationMenuItem; - - private JMenuItem _derivedColumnsMenuItem; - - private JMenuItem _hsagrplocSortMenuItem; - - private JMenuItem _riverThreatSortMenuItem; - - private JMenuItem _precipThreatSortMenuItem; - - private JMenuItem _clearSortMenuItem; - - private JMenuItem _validTimeLookUpForAlertAlarmMenuItem; - - private JMenuItem _endTimeLookUpForVTECEventMenuItem; - - private JMenuItem _ugcExpireTimeLookUpMenuItem; - - private JMenuItem _vtecEventProductTimeLookUpMenuItem; - - private JMenuItem _obsTimeLookUpForLatestObsValueMenuItem; - - private JMenuItem _fcstBasisTimeLookUpForMaxFcstValueMenuItem; - - private JMenuItem _precipThresholdForThreatColorMenuItem; - - private JMenuItem _aboutMenuItem; - - private RiverMonGroupDialog _riverMonGroupDialog = null; - - private RiverMonLocationDialog _riverMonLocationDialog; - - private RiverMonitorDataManager _rivermonitorDataManager; - - private RiverMonitorMenuSettings _menuSettings; - - private OfficeNotesDialog _officeNotesDialog; - - private OfficeNotesDataManager _officeNotesDataMgr; - - private AlertAlarmDialog _alertAlarmDialog; - - private AlertAlarmDataManager _alertAlarmDataMgr; - - private VtecEventDataManager _vtecEventDataMgr; - - private VtecEventDialog _vtecEventDialog; - - private String _settingsDir; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - private RiverMonitorJTableRowData _selectedRowData; - - private MonitorToolBarManager _toolBarManager; - - public RiverMonitorMenuManager(MessageSystemManager msgSystemManager, - SessionLogger logger, MonitorFrame mainFrame, String version, - String versionDate, AppsDefaults appsDefaults, JToolBar toolBar, - RiverMonitorDataManager riverMonitorDataManager, - OfficeNotesDataManager officeNotesDataMgr, - AlertAlarmDataManager alertAlarmDataMgr, - VtecEventDataManager vtecEventDataMgr, - RiverMonitorMenuSettings menuSettings, JPanel timeDisplayPanel, - String appName, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) { - super(msgSystemManager, appsDefaults, logger); - _appsDefaults = appsDefaults; - _rivermonitorDataManager = riverMonitorDataManager; - - _menuSettings = menuSettings; - - _officeNotesDataMgr = officeNotesDataMgr; - _alertAlarmDataMgr = alertAlarmDataMgr; - _vtecEventDataMgr = vtecEventDataMgr; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - "/awips/hydroapps/whfs/local/data/app/rivermon"); - - int defaultRefreshInterval = 15; - createRefreshComponents(defaultRefreshInterval, timeDisplayPanel); - - _toolBarManager = new MonitorToolBarManager(toolBar, _appsDefaults, - _officeNotesDataMgr); - _toolBarManager.getOfficeNotesButton().addActionListener( - new OfficeNotesDialogListener()); - - setAboutInfo(version, versionDate, appName); - _mainFrame = mainFrame; - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver( - new UpdateDisplayWithSettingsReceiver(), - MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new ViewSelectItemReceiver(), - MessageType.VIEW_SELECT_ITEM); - - _msgSystemManager.registerReceiver(new UpdateDisplayReceiver(), - MessageType.REFRESH_DISPLAY); - - createMenus(); - setFrameListener(); - } - - @Override - protected long getDataUpdateTime() { - return _rivermonitorDataManager.getPdcUpdateTime(); - } - - @Override - protected long getDisplayedRecordCount() { - return _rivermonitorDataManager.getDisplayedRecordCount(); - } - - @Override - public void setMenuSettingsRefreshInterval(int value) { - _menuSettings.setRefreshInterval(value); - } - - @Override - public void setRefreshTimeSpinnerValue() { - _refreshTimeSpinner.setValue(_menuSettings.getRefreshInterval()); - } - - private void createMenus() { - _menuBar = new JMenuBar(); - _mainFrame.setJMenuBar(_menuBar); - - _toolBarManager.getOfficeNotesButton().addActionListener( - new OfficeNotesDialogListener()); - - _fileMenu = new JMenu("File"); - _configMenu = new JMenu("Config"); - _displayMenu = new JMenu("Display"); - _sortMenu = new JMenu("Sort"); - _detailsMenu = new JMenu("Details"); - _helpMenu = new JMenu("Help"); - - _fileMenu.setMnemonic('F'); - _configMenu.setMnemonic('C'); - _displayMenu.setMnemonic('D'); - _sortMenu.setMnemonic('S'); - _detailsMenu.setMnemonic('E'); - _helpMenu.setMnemonic('H'); - - // File Menu - - _refreshColumnMenuItem = new JMenuItem("Refresh"); - _refreshColumnMenuItem.setMnemonic('R'); - _fileMenu.add(_refreshColumnMenuItem); - - _fileMenu.add(new JSeparator()); - - _saveColumnSettingsMenuItem = new JMenuItem("Save Custom Settings ..."); - _saveColumnSettingsMenuItem.setMnemonic('S'); - _fileMenu.add(_saveColumnSettingsMenuItem); - - _saveOfficeSettingsMenuItem = new JMenuItem("Save Office Settings"); - _saveOfficeSettingsMenuItem.setMnemonic('F'); - _saveOfficeSettingsMenuItem - .setToolTipText("Save office settings to PrecipMonitorSettings.txt"); - _fileMenu.add(_saveOfficeSettingsMenuItem); - - _loadSettingsMenuItem = new JMenuItem("Load Custom Settings ..."); - _loadSettingsMenuItem.setMnemonic('L'); - _fileMenu.add(_loadSettingsMenuItem); - - _loadOfficeSettingsMenuItem = new JMenuItem("Load Office Settings"); - _loadOfficeSettingsMenuItem.setMnemonic('O'); - _loadOfficeSettingsMenuItem - .setToolTipText("Load office settings from PrecipMonitorSettings.txt"); - _fileMenu.add(_loadOfficeSettingsMenuItem); - - _fileMenu.add(new JSeparator()); - - _exportTableToTextMenuItem = new JMenuItem( - "Export Data To Text File ..."); - _exportTableToTextMenuItem.setMnemonic('x'); - _fileMenu.add(_exportTableToTextMenuItem); - - _fileMenu.add(new JSeparator()); - - _exitApplicationMenuItem = new JMenuItem("Exit"); - _exitApplicationMenuItem.setMnemonic('E'); - _fileMenu.add(_exitApplicationMenuItem); - - // Display Menu - - _selectColumnsMenuItem = new JMenuItem("Select Columns ..."); - _selectColumnsMenuItem.setMnemonic('S'); - _displayMenu.add(_selectColumnsMenuItem); - - _displayMenu.add(new JSeparator()); - - _fcstTsMenu = new JMenu("Forecast Source"); - _fcstTsMenu.setMnemonic('F'); - _displayMenu.add(_fcstTsMenu); - - _validTimeLookUpForAlertAlarmMenuItem = new JMenuItem( - "Alert Alarm ValidTime ..."); - _validTimeLookUpForAlertAlarmMenuItem.setMnemonic('A'); - _displayMenu.add(_validTimeLookUpForAlertAlarmMenuItem); - - _endTimeLookUpForVTECEventMenuItem = new JMenuItem( - "VTEC Event EndTime ..."); - _endTimeLookUpForVTECEventMenuItem.setMnemonic('V'); - _displayMenu.add(_endTimeLookUpForVTECEventMenuItem); - - _ugcExpireTimeLookUpMenuItem = new JMenuItem("UGCExpire Time ..."); - _ugcExpireTimeLookUpMenuItem.setMnemonic('U'); - _displayMenu.add(_ugcExpireTimeLookUpMenuItem); - - _vtecEventProductTimeLookUpMenuItem = new JMenuItem( - "VTEC Event Product Time ..."); - _vtecEventProductTimeLookUpMenuItem.setMnemonic('P'); - _displayMenu.add(_vtecEventProductTimeLookUpMenuItem); - - _obsTimeLookUpForLatestObsValueMenuItem = new JMenuItem( - "Latest ObsTime ..."); - _obsTimeLookUpForLatestObsValueMenuItem.setMnemonic('O'); - _displayMenu.add(_obsTimeLookUpForLatestObsValueMenuItem); - - _fcstBasisTimeLookUpForMaxFcstValueMenuItem = new JMenuItem( - "Latest Fcst Basis Time ..."); - _fcstBasisTimeLookUpForMaxFcstValueMenuItem.setMnemonic('B'); - _displayMenu.add(_fcstBasisTimeLookUpForMaxFcstValueMenuItem); - - _precipThresholdForThreatColorMenuItem = new JMenuItem( - "Precip Threshold ..."); - _precipThresholdForThreatColorMenuItem.setMnemonic('P'); - _displayMenu.add(_precipThresholdForThreatColorMenuItem); - - _displayMenu.add(new JSeparator()); - - _showMissingRiverMenuItem = new JCheckBoxMenuItem( - "Show Locations with Missing Obs/Fcst Data"); - _showMissingRiverMenuItem.setMnemonic('M'); - _displayMenu.add(_showMissingRiverMenuItem); - - // Config Menu - - _riverMonGroupMenuItem = new JMenuItem("Group Definitions ..."); - _riverMonGroupMenuItem.setMnemonic('G'); - _configMenu.add(_riverMonGroupMenuItem); - - _riverMonLocationMenuItem = new JMenuItem( - "Location Grouping/Ordering ..."); - _riverMonLocationMenuItem.setMnemonic('L'); - _configMenu.add(_riverMonLocationMenuItem); - - _configMenu.add(new JSeparator()); - - _riverMonitorPEConfigMenuItem = new JMenuItem( - "River Data Type Override ..."); - _riverMonitorPEConfigMenuItem.setMnemonic('P'); - _configMenu.add(_riverMonitorPEConfigMenuItem); - - _configMenu.add(new JSeparator()); - - _derivedColumnsMenuItem = new JMenuItem("Derived Columns ..."); - _derivedColumnsMenuItem.setMnemonic('D'); - _configMenu.add(_derivedColumnsMenuItem); - - // Sort Menu - - _clearSortMenuItem = new JMenuItem("Clear Sort"); - _clearSortMenuItem.setMnemonic('C'); - _clearSortMenuItem.setToolTipText("Clear All Sorts"); - _sortMenu.add(_clearSortMenuItem); - - _sortMenu.add(new JSeparator()); - - _hsagrplocSortMenuItem = new JMenuItem( - "Sort by HSA | Group | Location Columns"); - _hsagrplocSortMenuItem.setMnemonic('O'); - _hsagrplocSortMenuItem - .setToolTipText("Sort by HSA, group id, location id"); - _sortMenu.add(_hsagrplocSortMenuItem); - - _riverThreatSortMenuItem = new JMenuItem("River Threat Sort"); - _riverThreatSortMenuItem.setMnemonic('R'); - _riverThreatSortMenuItem.setToolTipText("Sort by Threat Column"); - _sortMenu.add(_riverThreatSortMenuItem); - - _precipThreatSortMenuItem = new JMenuItem("Precip Threat Sort"); - _precipThreatSortMenuItem.setMnemonic('P'); - _precipThreatSortMenuItem - .setToolTipText("Sort by Precip Threat Column"); - _sortMenu.add(_precipThreatSortMenuItem); - - // Details Menu - - _officeNotesMenuItem = new JMenuItem("Office Notes ..."); - _officeNotesMenuItem.setMnemonic('O'); - _detailsMenu.add(_officeNotesMenuItem); - - _alertAlarmMenuItem = new JMenuItem("Alert Alarm ..."); - _alertAlarmMenuItem.setMnemonic('A'); - _detailsMenu.add(_alertAlarmMenuItem); - - _vtecEventMenuItem = new JMenuItem("VTEC Events ..."); - _vtecEventMenuItem.setMnemonic('V'); - _detailsMenu.add(_vtecEventMenuItem); - - _detailsMenu.add(new JSeparator()); - - _siteSpecificMenuItem = new JMenuItem("SiteSpecific App..."); - _siteSpecificMenuItem.setMnemonic('S'); - _detailsMenu.add(_siteSpecificMenuItem); - - _timeSeriesLiteMenuItem = new JMenuItem("Time Series Lite..."); - _timeSeriesLiteMenuItem.setMnemonic('T'); - _detailsMenu.add(_timeSeriesLiteMenuItem); - - // Help Menu - - _aboutMenuItem = new JMenuItem("About ..."); - _aboutMenuItem.setMnemonic('A'); - _helpMenu.add(_aboutMenuItem); - - // sub menus - _fcstTsGroup = new ButtonGroup(); - _fcstTsIngestFilterMenuItem = new JRadioButtonMenuItem("IngestFilter"); - _fcstTsIngestFilterMenuItem.setSelected(true); - FcstTsMenuItemListener fcstTsListener = new FcstTsMenuItemListener(); - _fcstTsIngestFilterMenuItem.addActionListener(fcstTsListener); - _fcstTsGroup.add(_fcstTsIngestFilterMenuItem); - _fcstTsMenu.add(_fcstTsIngestFilterMenuItem); - _fcstTsFFMenuItem = new JRadioButtonMenuItem("FF"); - _fcstTsFFMenuItem.addActionListener(fcstTsListener); - _fcstTsGroup.add(_fcstTsFFMenuItem); - _fcstTsMenu.add(_fcstTsFFMenuItem); - _fcstTsFZMenuItem = new JRadioButtonMenuItem("FZ"); - _fcstTsFZMenuItem.addActionListener(fcstTsListener); - _fcstTsGroup.add(_fcstTsFZMenuItem); - _fcstTsMenu.add(_fcstTsFZMenuItem); - - setMenuListeners(); - - _menuBar.add(_fileMenu); - _menuBar.add(_displayMenu); - _menuBar.add(_configMenu); - _menuBar.add(_sortMenu); - _menuBar.add(_detailsMenu); - _menuBar.add(_helpMenu); - } - - private void setMenuListeners() { - ChangeColumnsDisplayedMenuListener changeMenuListener = new ChangeColumnsDisplayedMenuListener(); - _selectColumnsMenuItem.addActionListener(changeMenuListener); - - ShowMissingRiverMenuListener showMissingPrecipMenuListener = new ShowMissingRiverMenuListener(); - _showMissingRiverMenuItem - .addItemListener(showMissingPrecipMenuListener); - - SaveSettingsListener saveMenuListener = new SaveSettingsListener(); - _saveColumnSettingsMenuItem.addActionListener(saveMenuListener); - - LoadSettingsListener loadMenuListener = new LoadSettingsListener(); - _loadSettingsMenuItem.addActionListener(loadMenuListener); - - LoadOfficeSettingsListener loadOfficeSettingsListener = new LoadOfficeSettingsListener(); - _loadOfficeSettingsMenuItem - .addActionListener(loadOfficeSettingsListener); - - SaveOfficeSettingsListener saveOfficeSettingsListener = new SaveOfficeSettingsListener(); - _saveOfficeSettingsMenuItem - .addActionListener(saveOfficeSettingsListener); - - ExitApplicationListener exitApplicationListener = new ExitApplicationListener(); - _exitApplicationMenuItem.addActionListener(exitApplicationListener); - - RefreshMenuListener RefreshMenuListener = new RefreshMenuListener(); - _refreshColumnMenuItem.addActionListener(RefreshMenuListener); - - SaveTableListener saveTableListener = new SaveTableListener(); - _exportTableToTextMenuItem.addActionListener(saveTableListener); - - AppSortListener appSortListener = new AppSortListener(); - _hsagrplocSortMenuItem.addActionListener(appSortListener); - - PrecipThreatSortListener precipThreatSortListener = new PrecipThreatSortListener(); - _precipThreatSortMenuItem.addActionListener(precipThreatSortListener); - - RiverThreatSortListener riverThreatSortListener = new RiverThreatSortListener(); - _riverThreatSortMenuItem.addActionListener(riverThreatSortListener); - - ClearSortListener clearSortListener = new ClearSortListener(); - _clearSortMenuItem.addActionListener(clearSortListener); - - AlertAlarmDialogListener alertAlarmDialogListener = new AlertAlarmDialogListener(); - _alertAlarmMenuItem.addActionListener(alertAlarmDialogListener); - - VtecEventDialogListener vtecEventDialogListener = new VtecEventDialogListener(); - _vtecEventMenuItem.addActionListener(vtecEventDialogListener); - - SiteSpecificListener siteSpecificListener = new SiteSpecificListener(); - _siteSpecificMenuItem.addActionListener(siteSpecificListener); - - OfficeNotesDialogListener officeNotesDialogListener = new OfficeNotesDialogListener(); - _officeNotesMenuItem.addActionListener(officeNotesDialogListener); - - TimeSeriesLiteMenuItemListener timeSeriesLiteMenuItemListener = new TimeSeriesLiteMenuItemListener(); - _timeSeriesLiteMenuItem - .addActionListener(timeSeriesLiteMenuItemListener); - - RiverMonitorPEConfigEditorListener riverMonitorPEConfigEditorListener = new RiverMonitorPEConfigEditorListener(); - _riverMonitorPEConfigMenuItem - .addActionListener(riverMonitorPEConfigEditorListener); - - RiverMonGroupDialogListener riverMonGroupDialogListener = new RiverMonGroupDialogListener(); - _riverMonGroupMenuItem.addActionListener(riverMonGroupDialogListener); - - RiverMonLocationDialogListener riverMonLocationDialogListener = new RiverMonLocationDialogListener(); - _riverMonLocationMenuItem - .addActionListener(riverMonLocationDialogListener); - - AlertAlarmValidTimeListener alertAlarmValidTimeListener = new AlertAlarmValidTimeListener(); - _validTimeLookUpForAlertAlarmMenuItem - .addActionListener(alertAlarmValidTimeListener); - - VtecEventEndTimeListener vtecEventEndTimeListener = new VtecEventEndTimeListener(); - _endTimeLookUpForVTECEventMenuItem - .addActionListener(vtecEventEndTimeListener); - - UGCExpireTimeListener ugcExpireTimeListener = new UGCExpireTimeListener(); - _ugcExpireTimeLookUpMenuItem.addActionListener(ugcExpireTimeListener); - - VtecEventProductTimeListener vtecEventProductTimeListener = new VtecEventProductTimeListener(); - _vtecEventProductTimeLookUpMenuItem - .addActionListener(vtecEventProductTimeListener); - - LatestObsTimeListener latestObsTimeListener = new LatestObsTimeListener(); - _obsTimeLookUpForLatestObsValueMenuItem - .addActionListener(latestObsTimeListener); - - LatestFcstBasisTimeListener latestFcstBasisTimeListener = new LatestFcstBasisTimeListener(); - _fcstBasisTimeLookUpForMaxFcstValueMenuItem - .addActionListener(latestFcstBasisTimeListener); - - PrecipThresholdListener precipThresholdListener = new PrecipThresholdListener( - _menuSettings.getPrecipSettings()); - _precipThresholdForThreatColorMenuItem - .addActionListener(precipThresholdListener); - - DerivedColumnsEditorListener derivedColumnsEditorListener = new DerivedColumnsEditorListener(); - _derivedColumnsMenuItem.addActionListener(derivedColumnsEditorListener); - - AboutListener aboutListener = new AboutListener(); - _aboutMenuItem.addActionListener(aboutListener); - - } - - private class DerivedColumnsEditorListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String editorTitle = ("\"").concat("Derived Columns").concat("\""); - String file = _settingsDir + "/" - + RiverMonitorAppManager.DERIVED_COLUMNS_FILE; - launchTextEditor(editorTitle, file, "RiverMonitor Application"); - } - } - - private void setFrameListener() { - FrameListener frameListener = new FrameListener(); - _mainFrame.addWindowListener(frameListener); - } - - public void closeApplication() { - _logger.log("RiverMonitor Application Exiting...."); - _logger.log("===================================="); - _rivermonitorDataManager.disconnect(); - _mainFrame.setVisible(false); - _mainFrame.dispose(); - Monitor.disposeRiver(); - } - - private void createOfficeNotesDialog() { - List lidList = _rivermonitorDataManager.getLidList(); - String lids[] = new String[lidList.size()]; - for (int i = 0; i < lidList.size(); i++) { - lids[i] = lidList.get(i).toString(); - } - Arrays.sort(lids); - System.out.println("Create officenotes lids size:" + lidList.size()); - Map lidDescDetailsMap = _rivermonitorDataManager.getLidDescDetails(); - if (_officeNotesDialog == null) - _officeNotesDialog = new OfficeNotesDialog(_mainFrame, - _officeNotesDataMgr, "RIVERMON", lids, lidDescDetailsMap, - _logger); - } - - public void loadSettings() { - String header = "RiverMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - - private void loadOfficeSettings() { - String header = "RiverMonitorMenuManager.loadOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_OFFICE_SETTINGS); - } - - public void viewSelectItem(MonitorMessage message) { - String header = "RiverMonitorMenuManager.viewSelectItem(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - _selectedRowData = (RiverMonitorJTableRowData) message.getMessageData(); - } - - private class UpdateDisplayReceiver implements Receiver { - public void receive(MonitorMessage message) { - updateRecordCount(); - } - } - - public void updateDisplayWithSettings(MonitorMessage message) { - String header = "RiverMonitorMenuManager.updateDisplayWithSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - refreshTimeDisplay(); - updateMenuWithNewSettings(); - } - - private void updateMenuWithNewSettings() { - String fcstTypeSource = _menuSettings.getRiverSettings() - .getFcstTypeSource(); - - if (fcstTypeSource != null) { - if (fcstTypeSource.equals("IngestFilter")) { - _fcstTsIngestFilterMenuItem.setSelected(true); - } else if (fcstTypeSource.equals("FF")) { - _fcstTsFFMenuItem.setSelected(true); - } else { - _fcstTsFZMenuItem.setSelected(true); - } - } else { - _fcstTsFZMenuItem.setActionCommand("IngestFilter"); - } - - if (_menuSettings.shouldShowMissingRiver()) - _showMissingRiverMenuItem.setSelected(true); - else - _showMissingRiverMenuItem.setSelected(false); - } - - public void saveSettings() { - String header = "RiverMonitorMenuManager.saveSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_SETTINGS); - } - - private void saveOfficeSettings() { - String header = "RiverMonitorMenuManager.saveOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_OFFICE_SETTINGS); - } - - public void loadSettings(File fileHandler) { - if (fileHandler != null) { - String header = "RiverMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - } - - public void loadSettingsFromFile(File fileHandler) { - String header = "RiverMonitorMenuManager.loadSettingsFromFile(): "; - if (fileHandler != null) { - _logger.log(header + "Read settings from " - + fileHandler.getAbsolutePath()); - loadSettings(fileHandler); - } - } - - private void changeColumns() { - String header = "RiverMonitorMenuManager.changeColumns(): "; - - System.out.print(header); - send(this, MessageType.CHANGE_COLUMNS); - } - - private void saveTable() { - String header = "RiverMonitorMenuManager.saveTable(): "; - - System.out.print(header); - send(this, MessageType.CREATE_TEXT_FROM_VIEW); - } - - private void precipThreatSort() { - String header = "RiverMonitorMenuManager.precipThreatSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.PRECIP_THREAT_SORT); - } - - private void riverThreatSort() { - String header = "RiverMonitorMenuManager.riverThreatSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.RIVER_THREAT_SORT); - } - - private void appSort() { - String header = "RiverMonitorMenuManager.appSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.APP_SORT); - } - - private void clearSort() { - String header = "RiverMonitorMenuManager.clearSort(): "; - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - } - - private void createRiverMonGroupDialog() { - String defaultHsa = _rivermonitorDataManager.getDefaultHsa(); - if (_riverMonGroupDialog == null) - _riverMonGroupDialog = new RiverMonGroupDialog(_mainFrame, - _rivermonitorDataManager.getRiverMonLocGroupDataManager(), - _logger, defaultHsa); - } - - private void createRiverMonLocationDialog() { - if (_riverMonLocationDialog == null) - _riverMonLocationDialog = new RiverMonLocationDialog(_mainFrame, - _rivermonitorDataManager.getRiverMonLocGroupDataManager(), - _logger); - } - - private void createAlertAlarmDialog() { - if (_alertAlarmDialog == null) - _alertAlarmDialog = new AlertAlarmDialog(_mainFrame, - _alertAlarmDataMgr, _logger); - } - - private void createVtecEventDialog() { - if (_vtecEventDialog == null) - _vtecEventDialog = new VtecEventDialog(_mainFrame, - _vtecEventDataMgr, _logger); - } - - private class ExitApplicationListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - closeApplication(); - } - } - - private class VtecEventDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createVtecEventDialog(); - if (_selectedRowData != null) { - _vtecEventDialog.showVtecEventDialog(_selectedRowData.getLid()); - } else - _vtecEventDialog.showVtecEventDialog(null); - } - } - - private class AlertAlarmDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createAlertAlarmDialog(); - if (_selectedRowData != null) { - _alertAlarmDialog.showAlertAlarmDialog(_selectedRowData - .getLid()); - } else - _alertAlarmDialog.showAlertAlarmDialog(null); - } - } - - private class TimeSeriesLiteMenuItemListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (_selectedRowData != null) { - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, - _selectedRowData); - } else { - String textMsg = " Unable to display TimeSeriesLite
" - + "Please highlight a row... "; - JOptionPane.showMessageDialog(_mainFrame, textMsg, - "TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - } - } - - private class SiteSpecificListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String whfsBinDir = _appsDefaults.getToken("whfs_bin_dir", - "/awips/hydroapps/whfs/bin"); - String siteSpecificExe = whfsBinDir + "/run_SiteSpecific"; - - // DR#10955 - RunProcess rt = RunProcess.getRunProcess(); - - String cmd; - if (_selectedRowData != null) - cmd = siteSpecificExe + " " + _selectedRowData.getLid(); - else - cmd = siteSpecificExe; - - try { - _mainFrame.setWaitCursor(); - rt.exec(cmd); - _logger.log("SiteSpecific App is launched [cmd:" + cmd + "]"); - _mainFrame.setDefaultCursor(); - } catch (IOException ex) { - _mainFrame.setDefaultCursor(); - String str = "Unable to launch SiteSpecific Appln:[" + cmd - + "]" + "Exception:" + ex; - JOptionPane.showMessageDialog(_mainFrame, str, - "RiverMonitor Application", JOptionPane.PLAIN_MESSAGE); - } - } - } - - private class PrecipMonitorListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - // startMonitor("PrecipMonitor Application", "PRECIP"); - } - } - - private class SaveTableListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - saveTable(); - } - } - - public class OLDShowMissingRiverMenuListener implements ItemListener { - public void itemStateChanged(ItemEvent e) { - boolean prevValue = _menuSettings.shouldShowMissingRiver(); - boolean newValue = false; - if (e.getStateChange() == ItemEvent.SELECTED) { - newValue = true; - } else if (e.getStateChange() == ItemEvent.DESELECTED) { - newValue = false; - } - - _menuSettings.setShowMissingRiver(newValue); - - if (prevValue != newValue) { - menuChange(); - } - } - } - - public class ShowMissingRiverMenuListener implements ItemListener { - public void itemStateChanged(ItemEvent e) { - String header = "RiverMonitorMenuManager.ShowMissingPrecipMenuListener.itemStateChanged()"; - - boolean prevValue = _menuSettings.shouldShowMissingRiver(); - boolean newValue = false; - if (e.getStateChange() == ItemEvent.SELECTED) { - newValue = true; - } - - _menuSettings.setShowMissingRiver(newValue); - - if (prevValue != newValue) { - sendMissingFilterChanged(); - } - } - } - - public class ChangeColumnsDisplayedMenuListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - changeColumns(); - } - } - - private class ClearSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - clearSort(); - } - } - - private class PrecipThreatSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - precipThreatSort(); - } - } - - private class RiverThreatSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - riverThreatSort(); - } - } - - private class AppSortListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - appSort(); - } - } - - private class RefreshMenuListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - refresh(); - } - } - - private class AlertAlarmValidTimeListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int prevValue = _menuSettings.getRiverSettings() - .getAlertAlarmLookBack(); - - new LookBackTimeDialog( - _mainFrame, - _menuSettings.getRiverSettings(), - "AlertAlarm----ValidTime Filter", - new JLabel( - "
Num Of Hrs To Lookback:
"), - RiverColumnDataSettings.VALID_TIME_TAG, 168, 1); - - if (prevValue != _menuSettings.getRiverSettings() - .getAlertAlarmLookBack()) { - menuChange(); - } - } - } - - private class VtecEventEndTimeListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int prevValue = _menuSettings.getRiverSettings() - .getVtecEventEndTimeApproach(); - - new LookBackTimeDialog( - _mainFrame, - _menuSettings.getRiverSettings(), - "VTEC Event----EndTime Filter", - new JLabel( - "
Num Of Hrs To LookAhead:
"), - RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG, 24, 1); - - if (prevValue != _menuSettings.getRiverSettings() - .getVtecEventEndTimeApproach()) { - menuChange(); - } - } - } - - private class VtecEventProductTimeListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int prevValue = _menuSettings.getRiverSettings() - .getVtecEventProductTimeLookBack(); - - new LookBackTimeDialog( - _mainFrame, - _menuSettings.getRiverSettings(), - "VTEC Event----Product Time Filter", - new JLabel( - "
Num Of Hrs To Lookback:
"), - RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG, 9000, - 1); - - if (prevValue != _menuSettings.getRiverSettings() - .getVtecEventProductTimeLookBack()) { - menuChange(); - } - } - } - - private class UGCExpireTimeListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int prevValue = _menuSettings.getRiverSettings() - .getUgcExpireTimeApproach(); - - new LookBackTimeDialog( - _mainFrame, - _menuSettings.getRiverSettings(), - "UGC ExpireTime Filter", - new JLabel( - "
Num Of Hrs To LookAhead:
"), - RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG, 24, 1); - - if (prevValue != _menuSettings.getRiverSettings() - .getUgcExpireTimeApproach()) { - menuChange(); - } - } - } - - private class LatestObsTimeListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int prevValue = _menuSettings.getRiverSettings() - .getLatestObsLookBack(); - - new LookBackTimeDialog( - _mainFrame, - _menuSettings.getRiverSettings(), - "Latest ObsTime Filter", - new JLabel( - "
Num Of Hrs To Lookback:
"), - RiverColumnDataSettings.LATEST_OBS_TIME_TAG, 720, 1); - - if (prevValue != _menuSettings.getRiverSettings() - .getLatestObsLookBack()) { - menuChange(); - } - } - } - - private class LatestFcstBasisTimeListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - int prevValue = _menuSettings.getRiverSettings() - .getLatestFcstBasisTimeLookBack(); - - new LookBackTimeDialog( - _mainFrame, - _menuSettings.getRiverSettings(), - "Latest Fcst BasisTime Filter", - new JLabel( - "
Num Of Hrs To Lookback:
"), - RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG, 720, 1); - - if (prevValue != _menuSettings.getRiverSettings() - .getLatestFcstBasisTimeLookBack()) { - menuChange(); - } - } - } - - private class FcstTsMenuItemListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String prevValue = _menuSettings.getRiverSettings() - .getFcstTypeSource(); - String selectedItem = e.getActionCommand(); - _menuSettings.getRiverSettings().setFcstTypeSource(selectedItem); - - if (!prevValue.equalsIgnoreCase(_menuSettings.getRiverSettings() - .getFcstTypeSource())) { - menuChange(); - } - } - } - - private class RiverMonitorPEConfigEditorListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String editorTitle = ("\"").concat("PEConfig File").concat("\""); - String file = _settingsDir + RiverMonitorAppManager.PE_CONFIG_FILE; - launchTextEditor(editorTitle, file, "RiverMonitor Application"); - } - } - - private class RiverMonGroupDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createRiverMonGroupDialog(); - boolean hasTableChanged = _riverMonGroupDialog - .showRiverMonGroupDialog(); - if (hasTableChanged) { - menuChange(); - } - } - } - - private class RiverMonLocationDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createRiverMonLocationDialog(); - boolean hasTableChanged = _riverMonLocationDialog - .showRiverMonLocationDialog(); - System.out.println("Rivermonlocation table changed:" - + hasTableChanged); - if (hasTableChanged) { - menuChange(); - } - } - } - - private class LoadOfficeSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - loadOfficeSettings(); - } - } - - private class SaveOfficeSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - String message = " This will overwrite standard office settings for RiverMonitor.
" - + "Are you sure ?
"; - if (confirmSaveOfficeSettings(message)) - saveOfficeSettings(); - } - } - - private class LoadSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - loadSettings(); - } - } - - private class FrameListener extends WindowAdapter { - @Override - public void windowClosing(WindowEvent event) { - closeApplication(); - } - } - - private class OfficeNotesDialogListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - createOfficeNotesDialog(); - if (_selectedRowData != null) { - _officeNotesDialog.showOfficeNotesDialog(_selectedRowData - .getLid()); - } else - _officeNotesDialog.showOfficeNotesDialog(null); - - _toolBarManager.setOfficeNotesButtonIcon(_officeNotesDataMgr - .getCountOfOfficeNotes()); - } - } - - private class SaveSettingsListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - saveSettings(); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - setInitialRefreshTimeInfo(); - updateDisplayWithSettings(message); - } - } - - private class ViewSelectItemReceiver implements Receiver { - public void receive(MonitorMessage message) { - viewSelectItem(message); - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorRefreshManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorRefreshManager.java deleted file mode 100755 index 172729d996..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorRefreshManager.java +++ /dev/null @@ -1,48 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import javax.swing.JSplitPane; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.MonitorRefreshManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.DialogHelper; - -public class RiverMonitorRefreshManager extends MonitorRefreshManager -{ - - private RiverMonitorDataManager _riverMonitorDataManager; - - public RiverMonitorRefreshManager(MessageSystemManager msgSystemManager, SessionLogger logger, - RiverMonitorDataManager riverMonitorDataManager, JSplitPane splitPane) - { - super(msgSystemManager, logger, splitPane); - - _riverMonitorDataManager = riverMonitorDataManager; - } - - protected void reloadData(MonitorMessage incomingMessage, MessageType outgoingMessageType) - { - - DialogHelper.setWaitCursor(_splitPane); - - String header = "MonitorRefreshManager.reloadData: "; - System.out.println(header +" Invoked"+ "...Source:" + incomingMessage.getMessageSource() + " Type:" + incomingMessage.getMessageType()); - - Runtime.getRuntime().gc(); - - _riverMonitorDataManager.createRiverMonitorRowDataList(); - - Runtime.getRuntime().gc(); - - System.out.println(header); - send(this, outgoingMessageType); - - DialogHelper.setDefaultCursor(_splitPane); - - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorSettingsManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorSettingsManager.java deleted file mode 100755 index 849ccf24ba..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorSettingsManager.java +++ /dev/null @@ -1,201 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.io.File; - -import javax.swing.JFileChooser; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.river.settings.RiverMonitorSettingsFileManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class RiverMonitorSettingsManager extends BaseManager { - private String _settingsDir; - - private AppsDefaults _appsDefaults; - - private SessionLogger _logger; - - private JFileChooser _fileChooser; - - private MonitorFrame _mainFrame; - - private ViewSettings _viewSettings; - - private FilterSettings _filterSettings; - - private RiverMonitorMenuSettings _menuSettings; - - private RiverMonitorSettingsFileManager _riverMonitorSettingsFileManger; - - private String _officeSettingsFile; - - private String _defaultSettingsFile; - - public RiverMonitorSettingsManager(MessageSystemManager msgSystemManager, - AppsDefaults appsDefaults, SessionLogger logger, - MonitorFrame mainFrame, ViewSettings viewSettings, - FilterSettings filterSettings, RiverMonitorMenuSettings menuSettings) { - _appsDefaults = appsDefaults; - _logger = logger; - _viewSettings = viewSettings; - _filterSettings = filterSettings; - _menuSettings = menuSettings; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - "/awips/hydroapps/whfs/local/data/app/rivermon"); - - _riverMonitorSettingsFileManger = new RiverMonitorSettingsFileManager( - _logger, _viewSettings, _filterSettings, _menuSettings); - - _mainFrame = mainFrame; - - _officeSettingsFile = _settingsDir.concat("/").concat( - RiverMonitorAppManager.SITE_RIVER_SETTINGS_FILE); - _defaultSettingsFile = _settingsDir.concat("/").concat( - RiverMonitorAppManager.DEFAULT_RIVER_SETTINGS_FILE); - - setMessageSystemManager(msgSystemManager); - - _msgSystemManager.registerReceiver(new LoadSettingsReceiver(), - MessageType.LOAD_SETTINGS); - _msgSystemManager.registerReceiver(new LoadOfficeSettingsReceiver(), - MessageType.LOAD_OFFICE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveSettingsReceiver(), - MessageType.SAVE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveOfficeSettingsReceiver(), - MessageType.SAVE_OFFICE_SETTINGS); - } - - private void saveSettings(MonitorMessage message) { - String header = "RiverMonitorSettingsManager.saveSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File fileHandler = null; - _fileChooser = new JFileChooser(); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = _fileChooser.showSaveDialog(_mainFrame); - if (result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveOfficeSettings(MonitorMessage message) { - String header = "RiverMonitorSettingsManager.saveOfficeSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveSettingsToFile(File fileHandler) { - send(this, MessageType.UPDATE_SETTINGS); - - if (fileHandler != null) { - _riverMonitorSettingsFileManger.saveSettingsToFile(fileHandler); - } - } - - private void loadSettings(MonitorMessage message) { - String header = "RiverMonitorSettingsManager.loadSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - if (message.getMessageSource() != this) { - File fileHandler = null; - _fileChooser = new JFileChooser(); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - int result = _fileChooser.showOpenDialog(_mainFrame); - - if (result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - loadSettings(fileHandler); - } - } - - public void startRiverMonitor() { - String header = "RiverMonitorSettings.startRiverMonitor(): "; - File fileHandler = new File(_officeSettingsFile); - if (fileHandler == null || (!fileHandler.exists())) { - fileHandler = new File(_defaultSettingsFile); - } - - _logger.log(header + "Trying to load from file :" - + fileHandler.getAbsolutePath()); - // loadSettings(fileHandler); - } - - private void loadSettings(File fileHandler) { - String header = "RiverMonitorSettingsManager.loadSettings(): "; - if (fileHandler != null) { - _riverMonitorSettingsFileManger.setSettingsFromFile(fileHandler); - - System.out.print(header); - send(this, MessageType.RELOAD_DATA_WITH_NEW_SETTINGS); - } - } - - private void loadOfficeSettings(MonitorMessage message) { - String header = "RiverMonitorSettingsManager.loadOfficeSettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - loadSettings(fileHandler); - } - - private class SaveOfficeSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - saveOfficeSettings(message); - } - } - - private class LoadOfficeSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - loadOfficeSettings(message); - } - } - - private class LoadSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - loadSettings(message); - } - } - - private class SaveSettingsReceiver implements Receiver { - public void receive(MonitorMessage message) { - saveSettings(message); - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorViewManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorViewManager.java deleted file mode 100755 index c1fd864a1b..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/manager/RiverMonitorViewManager.java +++ /dev/null @@ -1,703 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.util.List; - -import javax.swing.JFileChooser; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.monitor.river.RiverColumns; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableColumnDisplaySettings; -import ohd.hseb.util.gui.jtable.JTableManager; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class RiverMonitorViewManager extends BaseManager -{ - private SessionLogger _logger; - - private RiverMonitorDataManager _riverMonitorDataManager; - - private JTableManager _riverMonitorTableManager; - - private ViewSettings _viewSettings; - - private JSplitPane _splitPane; - - private List _riverMonitorAllRowDataList; - - private String _columnNamesCurrentlyDisplayed[]; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private MonitorFrame _mainFrame; - - private RiverMonitorJTableRowData _selectedRowData; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - private AppsDefaults _appsDefaults; - - public RiverMonitorViewManager(MonitorFrame mainFrame, - MessageSystemManager msgSystemManager, SessionLogger logger, - RiverMonitorDataManager riverMonitorDataManager, - JSplitPane splitPane, ViewSettings viewSettings, - DerivedColumnsFileManager derivedColumnsFileManager, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager, - AppsDefaults appsDefaults) - { - _logger = logger; - _riverMonitorDataManager = riverMonitorDataManager; - _splitPane = splitPane; - _mainFrame = mainFrame; - _viewSettings = viewSettings; - - _derivedColumnsFileManager = derivedColumnsFileManager; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - _appsDefaults = appsDefaults; - - List riverColumnsList = new RiverColumns() - .getRiverColumnsList(null); - - _derivedColumnsFileManager.getDerivedColumns(); - String derivedColumnNames[] = _derivedColumnsFileManager - .getDerivedColumnNames(); - String alignmentForDerivedColumns[] = _derivedColumnsFileManager - .getAlignmentForDerivedColumns(); - if (derivedColumnNames != null) - { - addDerivedColumnNames(riverColumnsList, derivedColumnNames, - alignmentForDerivedColumns); - } - - Dimension columnHeaderPreferredSize = new Dimension(100, 50); - _riverMonitorTableManager = new ComplexJTableManager(riverColumnsList, - _riverMonitorAllRowDataList, columnHeaderPreferredSize); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new SelectViewItemReceiver(), - MessageType.FILTER_SELECT_ITEM); - _msgSystemManager.registerReceiver(new ChangeColumnsReceiver(), - MessageType.CHANGE_COLUMNS); - _msgSystemManager.registerReceiver(new AppSortReceiver(), - MessageType.APP_SORT); - _msgSystemManager.registerReceiver(new RiverThreatSortReceiver(), - MessageType.RIVER_THREAT_SORT); - _msgSystemManager.registerReceiver(new PrecipThreatSortReceiver(), - MessageType.PRECIP_THREAT_SORT); - _msgSystemManager.registerReceiver(new ClearSortReceiver(), - MessageType.CLEAR_SORT); - _msgSystemManager.registerReceiver( - new UpdateDisplayWithSettingsReceiver(), - MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), - MessageType.REFRESH_DISPLAY); - _msgSystemManager.registerReceiver(new SaveViewReceiver(), - MessageType.CREATE_TEXT_FROM_VIEW); - _msgSystemManager.registerReceiver(new UpdateSettingsReceiver(), - MessageType.UPDATE_SETTINGS); - - } - - private void addDerivedColumnNames(List riverColumnsList, - String derivedColumnNames[], String alignmentForDerivedColumns[]) - { - for (int i = 0; i < derivedColumnNames.length; i++) - { - riverColumnsList.add(new JTableColumnDescriptor( - derivedColumnNames[i], alignmentForDerivedColumns[i], - derivedColumnNames[i])); - } - } - - private void createTableAndApplySettings(MonitorMessage message) - { - String header = "RiverViewManager.createTableAndApplySettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - _riverMonitorAllRowDataList = _riverMonitorDataManager - .getRiverMonitorRowDataList(); - - _columnNamesCurrentlyDisplayed = null; - String columnDisplaySettingsString = _viewSettings - .getColumnDisplaySettings(); - JTableColumnDisplaySettings columnDisplaySettings = _riverMonitorTableManager - .getTableSettings(); - columnDisplaySettings - .setSettingsFromString(columnDisplaySettingsString); - - _columnNamesCurrentlyDisplayed = _riverMonitorTableManager - .getColumnNamesThatAreCurrentlyDisplayed(); - if (_columnNamesCurrentlyDisplayed == null) - { - _columnNamesCurrentlyDisplayed = new String[] { - LocationInfoColumns.LOCATION_ID, - LocationInfoColumns.GROUP_NAME }; - } - - List selectedRowDataList = _riverMonitorDataManager - .getTreeFilterManager().filter(_riverMonitorAllRowDataList); - _riverMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _riverMonitorTableManager.setDisplayableColumns( - _columnNamesCurrentlyDisplayed, true, true); - _riverMonitorTableManager.setPreferredSizeForJScrollPane(new Dimension( - 690, 645)); - - JScrollPane tableScrollPane = _riverMonitorTableManager - .getJScrollPane(); - - _splitPane.setRightComponent(tableScrollPane); - - _riverMonitorTableManager - .addTableListener(new TableMouseMotionListener()); - _riverMonitorTableManager - .addTableListener(new TableListSelectionListener()); - _riverMonitorTableManager.addTableListener(new TableMouseListener()); - } - - public void refreshDisplay(MonitorMessage message) - { - String header = "RiverMonitorViewManager.refreshDisplay(): "; - - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _riverMonitorAllRowDataList = _riverMonitorDataManager.getRiverMonitorRowDataList(); - List selectedRowDataList = _riverMonitorDataManager.getTreeFilterManager().filter(_riverMonitorAllRowDataList); - _riverMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _riverMonitorTableManager.refreshDisplay(); - - JScrollPane tableScrollPane = _riverMonitorTableManager.getJScrollPane(); - - _splitPane.setRightComponent(tableScrollPane); - - } - - private void updateSettings(MonitorMessage message) - { - String header = "RiverViewManager.selectViewItem(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - updateSettings(); - } - - private void updateSettings() - { - JTableColumnDisplaySettings columnDisplaySettings = _riverMonitorTableManager - .getTableSettings(); - String settings = columnDisplaySettings.getSettingsString(); - _viewSettings.setColumnDisplaySettings(settings); - } - - private void selectViewItem(MonitorMessage message) - { - String header = "RiverViewManager.selectViewItem(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - String lidOfInterest = _riverMonitorDataManager - .getLidOfCurrentInterest(); - int rowToHighLight = _riverMonitorTableManager - .getTheRowIndexToHighLightBasedOnValue(lidOfInterest, - LocationInfoColumns.LOCATION_ID); - System.out.println("Row to highlight:" + rowToHighLight); - if (rowToHighLight != -1) - _riverMonitorTableManager - .selectRows(rowToHighLight, rowToHighLight); - } - - public void printFileException(IOException exception, String header) - { - header = header + ".printFileException(): "; - _logger.log(header + "ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - _logger.log(header + "End of stack trace"); - } - - private void saveTableToFile(String fileName) - { - File fileHandler = new File(fileName); - String header = "RiverMonitorViewManager.saveTableToFile(): "; - String displayedColumns[] = _riverMonitorTableManager - .getColumnNamesThatAreCurrentlyDisplayed(); - String rowData[][] = _riverMonitorTableManager.getDisplayRowDataArray(); - BufferedWriter out = null; - int maxStringLen = 33; - try - { - FileOutputStream fileOutput = new FileOutputStream(fileName, false); - OutputStreamWriter outputStream = new OutputStreamWriter(fileOutput); - out = new BufferedWriter(outputStream); - } - catch (IOException exception) - { - printFileException(exception, header); - } - if (displayedColumns != null) - { - try - { - out.newLine(); - StringBuffer columnNameStringBuffer = new StringBuffer(); - for (int i = 0; i < displayedColumns.length; i++) - { - columnNameStringBuffer.append(getTrimmedOrPaddedString( - displayedColumns[i], maxStringLen)); - columnNameStringBuffer.append(" |"); - } - out.write(columnNameStringBuffer.toString()); - out.newLine(); - } - catch (IOException exception) - { - printFileException(exception, header); - } - } - try - { - for (int i = 0; i < rowData.length; i++) - { - out.newLine(); - StringBuffer dataStringBuffer = new StringBuffer(); - for (int j = 0; j < rowData[i].length; j++) - { - dataStringBuffer.append(getTrimmedOrPaddedString( - rowData[i][j], maxStringLen)); - dataStringBuffer.append(" |"); - } - out.write(dataStringBuffer.toString()); - } - } - catch (IOException exception) - { - printFileException(exception, header); - } - - try - { - out.close(); - } - catch (IOException exception) - { - _logger.log(header + "Unable to close file[" - + fileHandler.getAbsolutePath() + "]"); - printFileException(exception, header); - } - } - - private String getTrimmedOrPaddedString(String origString, int desiredLength) - { - String newString = origString; - - String formatString = "%-" + String.valueOf(desiredLength) + "s"; - - newString = String.format(formatString, origString); - - if (newString.length() > desiredLength) - { - newString = newString.substring(0, desiredLength); - } - - return newString; - } - - private void saveView(MonitorMessage message) - { - String header = "RiverMonitorViewManager.saveView(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File file = null; - JFileChooser saveFileChooser = new JFileChooser(); - String settingsDir = _appsDefaults.getToken("whfs_report_dir", - "/awips/hydroapps/whfs/local/data/report"); - saveFileChooser.setDialogTitle("Export Table To Text File"); - saveFileChooser.setCurrentDirectory(new File(settingsDir)); - saveFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = saveFileChooser.showSaveDialog(_mainFrame); - if (result == JFileChooser.CANCEL_OPTION) - file = null; - else - file = saveFileChooser.getSelectedFile(); - - if (file != null) - { - saveTableToFile(file.toString()); - } - } - - private void changeColumns(MonitorMessage message) - { - String header = "RiverMonitorViewManager.changeColumns(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - _riverMonitorTableManager.invokeColumnSelector(_mainFrame); - - updateSettings(); - } - - private void updateSort(String[] columnNamesToSort, int[] columnSortNumber, - boolean[] columnSortOrder) - { - _riverMonitorTableManager.setSortInfoNotBasedOnUserClicks( - columnNamesToSort, columnSortOrder, columnSortNumber); - updateSettings(); - } - - private void riverThreatSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.riverThreatSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = { RiverColumns.THREAT }; - int columnSortNumber[] = { 0 }; - boolean columnSortOrder[] = { false }; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void precipThreatSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.precipThreatSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = { PrecipColumns.PRECIP_THREAT }; - int columnSortNumber[] = { 0 }; - boolean columnSortOrder[] = { false }; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void appSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.appSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = { LocationInfoColumns.HSA, - LocationInfoColumns.GROUP_ORDINAL, - LocationInfoColumns.LOCATION_ORDINAL }; - int columnSortNumber[] = { 0, 1, 2 }; - boolean columnSortOrder[] = { true, true, true }; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void clearSort() - { - _riverMonitorTableManager.clearSort(); - } - - private void clearSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.clearSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - updateSettings(); - } - - private void rowSelected(RiverMonitorJTableRowData selectedRowData) - { - String header = "RiverMonitorViewManager.rowSelected(): "; - - System.out.print(header); - send(this, MessageType.VIEW_SELECT_ITEM, selectedRowData); - } - - // ------------------------------------------------------------------------------------- - public String getToolTipForSelectedCell(String columnName, int rowIndex) - { - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) _riverMonitorTableManager - .getSelectedRowData(rowIndex); - String toolTip = ""; - VTECeventRecord record = null; - - if (columnName.equals(RiverColumns.UGC_EXPIRE_TIME)) - { - record = rowData.getVtecEventRecordForExpireTime(); - } - else if (columnName.equals(RiverColumns.EVENT_END_TIME) - || columnName.equals(RiverColumns.VTEC_SUMMARY)) - { - record = rowData.getVtecEventRecordForEndTime(); - } - - if (record != null) - { - long missingValue = DbTable.getNullLong(); - String beginTime = rowData.getStringValue(record.getBegintime(), - missingValue); - String endTime = rowData.getStringValue(record.getEndtime(), - missingValue); - String productTime = rowData.getStringValue( - record.getProducttime(), missingValue); - String expireTime = rowData.getStringValue(record.getExpiretime(), - missingValue); - - toolTip = "Action: [" + record.getAction() - + "] Signif: [" + record.getSignif() + "]\n
" - + "BeginTime: [" + beginTime + "] EndTime: [" + endTime - + "]\n
" + "ProductTime: [" + productTime - + "] ExpireTime: [" + expireTime + "]\n
"; - } - else if (columnName.equals(RiverColumns.THREAT)) - { - toolTip = rowData.getToolTipTextForThreatSummary(); - } - else if (columnName.equals(PrecipColumns.PRECIP_THREAT)) - { - toolTip = rowData.getToolTipTextForPrecipThreatSummary(); - } - else if (columnName.equals(RiverColumns.ALERT_ALARM)) - { - toolTip = rowData.getToolTipTextForAlertAlarmSummary(); - } - - if (toolTip.length() <= 12) // tooltip has "" only - { - String name = rowData.getName(); - String state = rowData.getState(); - String county = rowData.getCounty(); - String hsa = rowData.getHsa(); - String stream = rowData.getStream(); - String bankfull = rowData.getDataValue(RiverColumns.BANK_FULL); - String actionStage = rowData.getDataValue(RiverColumns.ACT_STG); - String floodStage = rowData.getDataValue(RiverColumns.FLD_STG); - String actionFlow = rowData.getDataValue(RiverColumns.ACT_FLOW); - String floodFlow = rowData.getDataValue(RiverColumns.FLD_FLOW); - String modStage = rowData.getDataValue(RiverColumns.MOD_STG); - String minStage = rowData.getDataValue(RiverColumns.MIN_STG); - String majStage = rowData.getDataValue(RiverColumns.MAJ_STG); - - toolTip = "Name:[" + name + "]\n
" + "County: [" - + county + "] State: [" + state + "] HSA: [" + hsa - + "]\n
" + "Stream: [" + stream + "] BankFull: [" - + bankfull + "]\n
" + "ActionStg: [" + actionStage - + "] FloodStg: [" + floodStage + "]\n
" - + "ActionFlow: [" + actionFlow + "] FloodFlow: [" - + floodFlow + "]\n
" + "MinStg: [" + minStage - + "] ModStg: [" + modStage + "] MajStg: [" + majStage - + "]\n
"; - } - return toolTip; - } - - private class ChangeColumnsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - changeColumns(message); - } - } - - private class ClearSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - clearSort(message); - } - } - - private class PrecipThreatSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - precipThreatSort(message); - } - } - - private class RiverThreatSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - riverThreatSort(message); - } - } - - private class AppSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - appSort(message); - } - } - - private class SelectViewItemReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - selectViewItem(message); - } - } - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - refreshDisplay(message); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTableAndApplySettings(message); - } - } - - private class UpdateSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - updateSettings(message); - } - } - - private class SaveViewReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveView(message); - } - } - - private class TableListSelectionListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent e) - { - if (e.getValueIsAdjusting() == false) - { - List selectedRowData = _riverMonitorTableManager - .getSelectedRowsData(); - for (int i = 0; i < selectedRowData.size(); i++) - { - if (i == 0) - { - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) selectedRowData - .get(i); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - } - } - } - } - } - - private class TableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - // String header = - // "RiverMonitorViewManager.TableMouseListener.mouseClicked(): "; - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _riverMonitorTableManager.getMousePointedRowIndex(p); - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) _riverMonitorTableManager - .getSelectedRowData(rowIndex); - - if (e.getClickCount() == 2) - { - // System.out.println(header + " starting TSL for " + - // rowData.getLid()); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, - _selectedRowData); - } - } - - public void mousePressed(MouseEvent e) - { - } - - public void mouseReleased(MouseEvent e) - { - } - - public void mouseEntered(MouseEvent e) - { - } - - public void mouseExited(MouseEvent e) - { - } - } - - // ------------------------------------------------------------------------------------- - class TableMouseMotionListener implements MouseMotionListener - { - public void mouseDragged(MouseEvent e) - { - } - - public void mouseMoved(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _riverMonitorTableManager.getMousePointedRowIndex(p); - int colIndex = _riverMonitorTableManager - .getMousePointedColumnIndex(p); - String columnName = _riverMonitorTableManager - .getColumnNameAtIndex(colIndex); - String toolTip = ""; - if (rowIndex != -1) - { - toolTip = getToolTipForSelectedCell(columnName, rowIndex); - _riverMonitorTableManager.setRowToolTipText(toolTip); - } - } - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverColumnDataSettings.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverColumnDataSettings.java deleted file mode 100755 index cd2a814bfd..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverColumnDataSettings.java +++ /dev/null @@ -1,106 +0,0 @@ -package ohd.hseb.monitor.river.settings; - -public class RiverColumnDataSettings -{ - private String _fcstTypeSource; - private int _alertalarmLookBack; - private int _latestObsLookBack; - private int _latestFcstBasisTimeLookBack; - private int _vtecEventEndTimeApproach; - private int _ugcExpireTimeApproach; - private int _vtecEventProductTimeLookBack; - - public static String DEFAULT_FCST_TYPESOURCE = "IngestFilter" ; - public static int DEFAULT_ALERTALARM_LOOKBACK = 8; - public static int DEFAULT_LATEST_OBS_LOOKBACK = 12 ; - public static int DEFAULT_LATEST_FCST_BASISTIME_LOOKBACK = 24; - public static int DEFAULT_VTEC_ENDTIME_APPROACH = 4; - public static int DEFAULT_UGC_EXPIRETIME_APPROACH = 4; - public static int DEFAULT_VTEC_EVENT_PRODUCT_TIME_LOOKBACK = 168; - - public static final String RIVER_SETTINGS_BEGIN_TAG = "#River Settings Begin"; - public static final String RIVER_SETTINGS_END_TAG = "#River Settings End"; - public static String FCST_TS_TAG = "FCST_TS"; - public static String VALID_TIME_TAG = "Valid_Time"; - public static String VTEC_EVENT_END_TIME_TAG = "VTECEventEnd_Time"; - public static String UGC_EXPIRE_TIME_TAG = "UGCExpire_Time"; - public static String VTEC_EVENT_PRODUCT_TIME_TAG = "VTECEventProduct_Time"; - public static String LATEST_FCST_BASIS_TIME_TAG = "LatestFcst_BasisTime"; - public static String LATEST_OBS_TIME_TAG = "LatestObs_Time"; - - public RiverColumnDataSettings() - { - resetSettings(); - } - - public void resetSettings() - { - _fcstTypeSource = DEFAULT_FCST_TYPESOURCE ; - _alertalarmLookBack = DEFAULT_ALERTALARM_LOOKBACK; - _latestObsLookBack = DEFAULT_LATEST_OBS_LOOKBACK; - _latestFcstBasisTimeLookBack = DEFAULT_LATEST_FCST_BASISTIME_LOOKBACK; - _vtecEventEndTimeApproach = DEFAULT_VTEC_ENDTIME_APPROACH; - _ugcExpireTimeApproach = DEFAULT_UGC_EXPIRETIME_APPROACH; - _vtecEventProductTimeLookBack = DEFAULT_VTEC_EVENT_PRODUCT_TIME_LOOKBACK; - } - - public String getFcstTypeSource() - { - return _fcstTypeSource; - } - public void setFcstTypeSource(String fcstTypeSource) - { - _fcstTypeSource = fcstTypeSource; - } - public int getAlertAlarmLookBack() - { - return _alertalarmLookBack; - } - public void setAlertAlarmLookBack(int alertalarmLookBack) - { - _alertalarmLookBack = alertalarmLookBack; - } - public int getLatestObsLookBack() - { - return _latestObsLookBack; - } - public void setLatestObsLookBack(int latestObsLookBack) - { - _latestObsLookBack = latestObsLookBack; - } - public int getLatestFcstBasisTimeLookBack() - { - return _latestFcstBasisTimeLookBack; - } - public void setLatestFcstBasisTimeLookBack(int fcstBasisTimeLookBack) - { - _latestFcstBasisTimeLookBack = fcstBasisTimeLookBack; - } - public int getVtecEventEndTimeApproach() - { - return _vtecEventEndTimeApproach; - } - public void setVtecEventEndTimeApproach(int vtecEventEndTimeApproach) - { - _vtecEventEndTimeApproach = vtecEventEndTimeApproach; - } - public int getUgcExpireTimeApproach() - { - return _ugcExpireTimeApproach; - } - public void setUgcExpireTimeApproach(int ugcExpireTimeApproach) - { - _ugcExpireTimeApproach = ugcExpireTimeApproach; - } - - public int getVtecEventProductTimeLookBack() - { - return _vtecEventProductTimeLookBack; - } - - public void setVtecEventProductTimeLookBack(int vtecEventProductTimeLookBack) - { - _vtecEventProductTimeLookBack = vtecEventProductTimeLookBack; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverMonitorMenuSettings.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverMonitorMenuSettings.java deleted file mode 100755 index 493a4288ec..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverMonitorMenuSettings.java +++ /dev/null @@ -1,99 +0,0 @@ -package ohd.hseb.monitor.river.settings; - -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.BooleanHolder; - -public class RiverMonitorMenuSettings -{ - private int _refreshInterval; - - public static final String REFRESH_INTERVAL_TAG = "RefreshInterval"; - - public static final String SHOW_MISSING_RIVER_TAG = "ShowMissingRiver"; - - public static int DEFAULT_REFRESH_INTERVAL = 15; - - private PrecipColumnDataSettings _precipSettings; - private RiverColumnDataSettings _riverSettings; - - // public boolean _showMissingRiver; - - private BooleanHolder _showMissingDataBooleanHolder = new BooleanHolder(true); - - - public RiverMonitorMenuSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingRiver(false); - _precipSettings = new PrecipColumnDataSettings(); - _riverSettings = new RiverColumnDataSettings(); - } - - public void resetSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingRiver(false); - _precipSettings.resetSettings(); - _riverSettings.resetSettings(); - } - - public RiverMonitorMenuSettings(int refreshInterval, boolean showMissingPrecip) - { - _refreshInterval = refreshInterval; - setShowMissingRiver(showMissingPrecip); - _precipSettings = new PrecipColumnDataSettings(); - _riverSettings = new RiverColumnDataSettings(); - } - - public void setPrecipSettings(PrecipColumnDataSettings precipSettings) - { - _precipSettings = precipSettings; - } - - public PrecipColumnDataSettings getPrecipSettings() - { - return _precipSettings; - } - - public void setRiverSettings(RiverColumnDataSettings riverSettings) - { - _riverSettings = riverSettings; - } - - public RiverColumnDataSettings getRiverSettings() - { - return _riverSettings; - } - - public void setRefreshInterval(int refreshInterval) - { - _refreshInterval = refreshInterval; - } - - public int getRefreshInterval() - { - return _refreshInterval; - } - - public boolean shouldShowMissingRiver() - { - return getShowMissingDataBooleanHolder().getValue(); - } - - public void setShowMissingRiver(boolean showMissingRiver) - { - _showMissingDataBooleanHolder.setValue(showMissingRiver); - } - - private void setShowMissingDataBooleanHolder(BooleanHolder showMissingPrecipBooleanHolder) - { - _showMissingDataBooleanHolder = showMissingPrecipBooleanHolder; - } - - public BooleanHolder getShowMissingDataBooleanHolder() - { - return _showMissingDataBooleanHolder; - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverMonitorSettingsFileManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverMonitorSettingsFileManager.java deleted file mode 100755 index f0eccfb643..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/river/settings/RiverMonitorSettingsFileManager.java +++ /dev/null @@ -1,347 +0,0 @@ -package ohd.hseb.monitor.river.settings; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.MonitorSettingsFileManager; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; - -public class RiverMonitorSettingsFileManager extends MonitorSettingsFileManager -{ - private RiverMonitorMenuSettings _menuSettings; - private Map _filterTokenValuesMap; - - public RiverMonitorSettingsFileManager(SessionLogger logger, ViewSettings viewSettings, - FilterSettings filterSettings, RiverMonitorMenuSettings menuSettings) - { - super(logger, "#RiverMonitorSettings File", viewSettings, filterSettings); - _menuSettings = menuSettings; - _logger = logger; - createDisplayTokenSet(); - createMenuTokenSet(); - } - - public Set createMenuTokenSet() - { - _menuTokenSet = new HashSet(); - - _menuTokenSet.add(RiverColumnDataSettings.FCST_TS_TAG); - _menuTokenSet.add(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.LATEST_OBS_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.VALID_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG); - _menuTokenSet.add(RiverMonitorMenuSettings.REFRESH_INTERVAL_TAG); - _menuTokenSet.add(RiverMonitorMenuSettings.SHOW_MISSING_RIVER_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_CAUTION_TAG); - - return _displayTokenSet; - } - - public boolean setSettingsFromFile(File fileHandler) - { - String header = "RiverMonitorSettingsFileManager.setSettingsFromFile(): "; - boolean isReadCompleted = true; - - resetSettings(); - - if(isValidSettingsFile(_logger, fileHandler, _settingsFileBeginTag )) - { - BufferedReader in = null; - String line; - try - { - in = new BufferedReader(new FileReader(fileHandler)); - - while(( line = in.readLine()) != null) - { - line = line.trim(); - processLine(line); - } - } - catch(IOException e) - { - printFileException(_logger, e,header); - isReadCompleted = false ; - } - } - else - { - isReadCompleted = false; - } - - setViewAndFilterSettings(); - setRiverSettings(); - return isReadCompleted; - } - - private void resetSettings() - { - _tableDisplaySettingsList = null; - _expandPathTokenValuesList = null; - _pathTokenValuesList = null; - _filterTokenValuesMap = null; - - setViewAndFilterSettings(); - _menuSettings.resetSettings(); - } - - private void setRiverSettings() - { - - if(_filterTokenValuesMap != null) - { - Object object = _filterTokenValuesMap.get(RiverColumnDataSettings.FCST_TS_TAG); - if(object != null) - { - String fcstTypeSource = _filterTokenValuesMap.get(RiverColumnDataSettings.FCST_TS_TAG).toString(); - _menuSettings.getRiverSettings().setFcstTypeSource(fcstTypeSource); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.VALID_TIME_TAG); - if(object != null) - { - Integer alerAlarmLoookback = new Integer(object.toString()); - _menuSettings.getRiverSettings().setAlertAlarmLookBack(alerAlarmLoookback); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_OBS_TIME_TAG); - if(object != null) - { - Integer latestObsLookback = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_OBS_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setLatestObsLookBack(latestObsLookback); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG); - if(object != null) - { - Integer latestFcstBasisTime = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setLatestFcstBasisTimeLookBack(latestFcstBasisTime); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG); - if(object != null) - { - Integer vtecEventProductTimeLookback = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setVtecEventProductTimeLookBack(vtecEventProductTimeLookback); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG); - if(object != null) - { - Integer vtecEventEndTimeApproach = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setVtecEventEndTimeApproach(vtecEventEndTimeApproach); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG); - if(object != null) - { - Integer ugcExpireTimeApproach = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setUgcExpireTimeApproach(ugcExpireTimeApproach); - } - } - } - - public void saveSettingsToFile(File fileHandler) - { - createSettingsFile(fileHandler); - - BufferedWriter out = null; - String header = "RiverMonitorSettingsFileManager.saveSettingsToFile(): "; - try - { - out = new BufferedWriter(new FileWriter(fileHandler)); - } - catch(IOException exception) - { - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - } - - saveDisplaySettings(out); - - saveMenuSettingsToFile(out); - } - - private void processPrecipToken(String tokenName, String tokenValue) - { - - String spiltStr[] = tokenValue.split("\\|"); - String hr1, hr3, hr6; - - if(spiltStr != null) - { - if(spiltStr.length == 3) // we have 3 values 1hr | 3hr | 6hr correctly - { - hr1 = null; hr3 = null; hr6 = null; - - hr1 = spiltStr[0].trim(); - hr3 = spiltStr[1].trim(); - hr6 = spiltStr[2].trim(); - - if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipCaution6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioAlert1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioAlert3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioAlert6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioCaution1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioCaution3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioCaution6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffCaution6Hr(new Double(hr6)); - } - } - } - } - - public void processMenuToken(String tokenName, String tokenValue) - { - if(tokenName.compareTo(RiverMonitorMenuSettings.REFRESH_INTERVAL_TAG) == 0) - { - _menuSettings.setRefreshInterval(new Integer(tokenValue)); - } - if(tokenName.compareTo(RiverMonitorMenuSettings.SHOW_MISSING_RIVER_TAG) == 0) - { - _menuSettings.setShowMissingRiver(new Boolean(tokenValue)); - } - else if( (tokenName.equals(PrecipColumnDataSettings.DIFF_ALERT_TAG) || - tokenName.equals(PrecipColumnDataSettings.DIFF_CAUTION_TAG) || - tokenName.equals(PrecipColumnDataSettings.PRECIP_ALERT_TAG) || - tokenName.equals(PrecipColumnDataSettings.PRECIP_CAUTION_TAG) || - tokenName.equals(PrecipColumnDataSettings.RATIO_ALERT_TAG) || - tokenName.equals(PrecipColumnDataSettings.RATIO_CAUTION_TAG) )) - { - processPrecipToken(tokenName, tokenValue); - } - else - { - if(_filterTokenValuesMap == null) - { - _filterTokenValuesMap = new HashMap(); - } - - if(tokenValue.length() > 0 && tokenValue.charAt(0) != '\n') - { - _filterTokenValuesMap.put(tokenName, tokenValue); - } - } - } - - public void saveMenuSettingsToFile(BufferedWriter writer) - { - String header = "SettingsFileManager.saveMenuSettingsToFile(): "; - try - { - if(_menuSettings != null) - { - writer.newLine(); - writer.write(RiverMonitorMenuSettings.REFRESH_INTERVAL_TAG + " : " + _menuSettings.getRefreshInterval()); - writer.newLine(); - - writer.newLine(); - writer.write(RiverMonitorMenuSettings.SHOW_MISSING_RIVER_TAG + " : " + _menuSettings.shouldShowMissingRiver()); - writer.newLine(); - - writer.newLine(); - writer.write(RiverColumnDataSettings.RIVER_SETTINGS_BEGIN_TAG); - writer.newLine(); - writer.write(RiverColumnDataSettings.FCST_TS_TAG + " : " + _menuSettings.getRiverSettings().getFcstTypeSource()); - writer.newLine(); - writer.write(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG + " : " + _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.LATEST_OBS_TIME_TAG + " : " + _menuSettings.getRiverSettings().getLatestObsLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.VALID_TIME_TAG + " : " + _menuSettings.getRiverSettings().getAlertAlarmLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG + " : " + _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG + " : " + _menuSettings.getRiverSettings().getVtecEventEndTimeApproach()); - writer.newLine(); - writer.write(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG + " : " + _menuSettings.getRiverSettings().getUgcExpireTimeApproach()); - writer.newLine(); - writer.write(RiverColumnDataSettings.RIVER_SETTINGS_END_TAG); - writer.newLine(); - - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_BEGIN_TAG); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getRatioAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getDiffAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert6Hr() ); - writer.newLine(); - - writer.write(PrecipColumnDataSettings.PRECIP_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getRatioCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getDiffCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_END_TAG); - - writer.close(); - } - } - catch(IOException exception) - { - printFileException(_logger, exception,header); - } - - } - -} \ No newline at end of file diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/FilterSettings.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/FilterSettings.java deleted file mode 100755 index 0c98d6bc06..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/FilterSettings.java +++ /dev/null @@ -1,35 +0,0 @@ -package ohd.hseb.monitor.settings; - -import javax.swing.tree.TreePath; - -public class FilterSettings -{ - public static String PATH_TAG = "PATH"; - public static String EXPAND_PATH_TAG = "EXPANDPATH"; - - public static String TREE_SETTINGS_BEGIN_TAG = "#HSA-GROUP-LOCATION TREE SETTINGS"; - - private TreePath[] _selectedPaths; - private TreePath[] _expandedPaths; - - public TreePath[] getSelectedPaths() - { - return _selectedPaths; - } - - public void setSelectedPaths(TreePath[] selectedPaths) - { - _selectedPaths = selectedPaths; - } - - public TreePath[] getExpandedPaths() - { - return _expandedPaths; - } - - public void setExpandedPaths(TreePath[] expandedPaths) - { - _expandedPaths = expandedPaths; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/MonitorSettingsFileManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/MonitorSettingsFileManager.java deleted file mode 100755 index ac14d55b68..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/MonitorSettingsFileManager.java +++ /dev/null @@ -1,418 +0,0 @@ -package ohd.hseb.monitor.settings; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.util.SessionLogger; - -public abstract class MonitorSettingsFileManager -{ - protected SessionLogger _logger; - - protected FilterSettings _filterSettings; - protected ViewSettings _viewSettings; - - protected Set _displayTokenSet; - protected Set _menuTokenSet; - - protected List _tableDisplaySettingsList; - protected List _pathTokenValuesList; - protected List _expandPathTokenValuesList; - - protected String _settingsFileBeginTag; - - public MonitorSettingsFileManager(SessionLogger logger, String settingsFileBeginTag, - ViewSettings viewSettings, - FilterSettings filterSettings) - { - _logger = logger; - _settingsFileBeginTag = settingsFileBeginTag; - _viewSettings = viewSettings; - _filterSettings = filterSettings; - } - - public Set createDisplayTokenSet() - { - _displayTokenSet = new HashSet(); - - _displayTokenSet.add(FilterSettings.PATH_TAG); - _displayTokenSet.add(FilterSettings.EXPAND_PATH_TAG); - _displayTokenSet.add(ViewSettings.COLUMN_TAG); - _displayTokenSet.add(ViewSettings.SORT_TAG); - - return _displayTokenSet; - } - - public boolean isValidSettingsFile(SessionLogger logger, File fileHandler, String checkString) - { - boolean isValidFile = true; - String header = "SettingsFileManager.isValidSettingsFile(): "; - if(fileHandler.exists()) - { - BufferedReader in = null; - String str; - try - { - in = new BufferedReader(new FileReader(fileHandler)); - - if(( str = in.readLine()) != null) - { - if(!str.equals(checkString)) - { - isValidFile = false; - } - } - else - isValidFile = false; - } - catch(IOException exception) - { - printFileException(logger, exception, header); - isValidFile = false; - } - } - else - { - isValidFile = false; - logger.log(header + "[" + fileHandler.getAbsolutePath() +"] doesn't exist" ); - } - - return isValidFile; - } - - public void printFileException(SessionLogger logger, IOException exception, String header) - { - header = header+".printFileException(): "; - logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(logger.getPrintWriter()); - logger.log(header+"End of stack trace"); - } - - public void saveDisplaySettings(BufferedWriter out) - { - String columnDisplaySettings = _viewSettings.getColumnDisplaySettings(); - saveTableDisplaySettings(out, columnDisplaySettings); - - //Write the selected paths - TreePath[] selectedPaths = _filterSettings.getSelectedPaths(); - - saveTreeSettings(out, selectedPaths, FilterSettings.PATH_TAG); - - //Write the expanded paths - TreePath[] expandedPaths = _filterSettings.getExpandedPaths(); - - saveTreeSettings(out, expandedPaths, FilterSettings.EXPAND_PATH_TAG); - } - - public void createSettingsFile(File fileHandler) - { - boolean fileExist = false; - fileExist = fileHandler.exists(); - String header = "RiverMonitorApplicationSettingsManager.createSettingsFile(): "; - - if(!fileExist) - { - try - { - fileHandler.createNewFile(); - } - catch(IOException e) - { - _logger.log(header+ "Unable to Create file:"+ - fileHandler.getAbsolutePath()+ - " for saving table settings"); - } - } - else - { - boolean fileDelete = false; - fileDelete = fileHandler.delete(); - - if(!fileDelete) - { - _logger.log(header+"FileName [" + fileHandler.getAbsolutePath()+ - "]exists already" + - " and unable to delete inorder to" + - "create a new file"); - } - else - { - try - { - fileHandler.createNewFile(); - } - catch(IOException exception) - { - _logger.log(header+"Unable to Create file:"+ - fileHandler.getAbsolutePath()+ - " for saving column setting"); - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - } - } - } - } - - public FilterSettings getFilterSettings() - { - return _filterSettings; - } - - public ViewSettings getViewSettings() - { - return _viewSettings; - } - - public boolean isSettingsLine(String line) - { - boolean result = false; - - if(line.length() > 0) - { - if(line.charAt(0) != '\n') - { - if(line.charAt(0) != '#') - { - result = true; - } - } - } - return result; - } - - public void processTableDisplayToken(String line) - { - if(_tableDisplaySettingsList == null) - { - _tableDisplaySettingsList = new ArrayList(); - } - - _tableDisplaySettingsList.add(line); - } - - public void processPathToken(String tokenValue) - { - if(_pathTokenValuesList == null) - { - _pathTokenValuesList = new ArrayList(); - } - - if(tokenValue.length() > 0 && tokenValue.charAt(0) != '\n') - { - tokenValue = tokenValue.replace('[', ' ').replace(']', ' ').trim(); - _pathTokenValuesList.add(tokenValue); - } - } - - public void processExpandPathToken(String tokenValue) - { - if(_expandPathTokenValuesList == null) - { - _expandPathTokenValuesList = new ArrayList(); - } - if(tokenValue.length() > 0 && tokenValue.charAt(0) != '\n') - { - tokenValue = tokenValue.replace('[', ' ').replace(']', ' ').trim(); - _expandPathTokenValuesList.add(tokenValue); - } - } - - - public void processDisplayToken(String tokenName, String tokenValue) - { - if((tokenName.compareTo(ViewSettings.COLUMN_TAG) == 0) - || (tokenName.compareTo(ViewSettings.SORT_TAG) == 0)) - { - processTableDisplayToken(tokenName + ":" + tokenValue); - } - else if(tokenName.compareTo(FilterSettings.PATH_TAG) == 0) - { - processPathToken(tokenValue); - } - else if(tokenName.compareTo(FilterSettings.EXPAND_PATH_TAG) == 0) - { - processExpandPathToken(tokenValue); - } - } - - public void processLine(String line) - { - String tokenName; - String tokenValue; - - if(isSettingsLine(line)) - { - String[] splitString = line.split(":"); - - if(splitString != null) - { - if( splitString.length == 2 ) - { - tokenName = splitString[0].trim(); - tokenValue = splitString[1].trim(); - if(_menuTokenSet.contains(tokenName)) - { - processMenuToken(tokenName, tokenValue); - } - else if(_displayTokenSet.contains(tokenName)) - { - processDisplayToken(tokenName, tokenValue); - } // token is a valid token - - } // is a valid line line str1:str2 - - } // line has the delimiter : - - }// is a valid settings line - - } - - public void processMenuToken(String tokenName, String tokenValue) - { - - } - - public TreePath[] getTreePathArray(List pathList) - { - TreePath[] paths = null; - if(pathList != null) - { - paths = new TreePath[pathList.size()]; - for(int i=0; i < pathList.size(); i++) - { - String splitStr[] = pathList.get(i).toString().split(", "); - DefaultMutableTreeNode node[] = new DefaultMutableTreeNode[splitStr.length]; - for(int j=0; j < splitStr.length; j++) - { - node[j] = new DefaultMutableTreeNode(splitStr[j]); - } - paths[i] = new TreePath(node); - - } - } - return paths; - } - - public void setViewAndFilterSettings() - { - String header = "MonitorSettingsFileManager.setViewAndFilterSettings(): "; - System.out.println(header); - - String tableDisplaySettingsString = null; - - if(_tableDisplaySettingsList != null) - { - for(int i=0; i < _tableDisplaySettingsList.size(); i++) - { - String str = _tableDisplaySettingsList.get(i); - if(tableDisplaySettingsString == null) - tableDisplaySettingsString = str +"\n"; - else - tableDisplaySettingsString = tableDisplaySettingsString + str +"\n"; - } - } - - //TODO CHIP says: a StringBuffer should be used instead of tableDisplaySettingsString, which will create a lot of String objects - // - // System.out.println(header + "tableDisplaySettingsString = \n" + tableDisplaySettingsString); - _viewSettings.setColumnDisplaySettings(tableDisplaySettingsString); - - TreePath[] paths = getTreePathArray(_pathTokenValuesList); - _filterSettings.setSelectedPaths(paths); - - paths = getTreePathArray(_expandPathTokenValuesList); - _filterSettings.setExpandedPaths(paths); - } - - public void saveTableDisplaySettings(BufferedWriter out, String columnDisplaySettings) - { - String header = "DisplaySettingsFileManager.saveTableDisplaySettings(): "; - - if(columnDisplaySettings != null) - { - for(int i=0; i < columnDisplaySettings.length(); i++) - { - try - { - if(i==0) - { - out.write(_settingsFileBeginTag); - out.newLine(); - } - if(columnDisplaySettings.charAt(i) == '\n') - out.newLine(); - else - out.write(columnDisplaySettings.charAt(i)); - } - catch(IOException exception) - { - printFileException(_logger, exception,header); - return; - } - } - } - - } - - public void saveTreeSettings(BufferedWriter out, TreePath paths[], String settingsTag) - { - String header = "DisplaySettingsFileManager.saveFilterTreeSettings(): "; - - if(paths == null) - { - _logger.log(header + " Paths sent are null while Trying to save " + settingsTag); - return; - } - - for(int j=0; j < paths.length; j++) - { - try - { - if(j == 0) - { - out.newLine(); - out.write(FilterSettings.TREE_SETTINGS_BEGIN_TAG); - out.newLine(); - } - out.write(settingsTag); - out.write(":"); - } - catch(IOException exception) - { - printFileException(_logger,exception,header); - } - - String pathStr = paths[j].toString(); - for(int i=0; i < pathStr.length(); i++) - { - try - { - if(i==pathStr.length()-1) - { - out.write(pathStr.charAt(i)); - out.newLine(); - } - else - out.write(pathStr.charAt(i)); - } - catch(IOException exception) - { - printFileException(_logger,exception,header); - return; - } - } - } - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/ViewSettings.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/ViewSettings.java deleted file mode 100755 index 758a195554..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/settings/ViewSettings.java +++ /dev/null @@ -1,25 +0,0 @@ -package ohd.hseb.monitor.settings; - -public class ViewSettings -{ - public static String COLUMN_TAG = "COLUMN"; - public static String SORT_TAG = "SORT"; - - private String _columnDisplaySettings; - - public ViewSettings() - { - - } - - public String getColumnDisplaySettings() - { - return _columnDisplaySettings; - } - - public void setColumnDisplaySettings(String columnDisplaySettings) - { - _columnDisplaySettings = columnDisplaySettings; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeCellRenderer.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeCellRenderer.java deleted file mode 100755 index d686a02030..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeCellRenderer.java +++ /dev/null @@ -1,1059 +0,0 @@ -package ohd.hseb.monitor.treefilter; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Image; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.Map; - -import javax.swing.AbstractAction; -import javax.swing.ActionMap; -import javax.swing.ButtonGroup; -import javax.swing.ButtonModel; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.ActionMapUIResource; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreeCellRenderer; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.util.CodeTimer; - -public class MonitorCheckTreeCellRenderer extends JPanel implements TreeCellRenderer -{ - /** This is a type-safe enumerated type */ - public static class State { private State() { } } - public static final State NOT_SELECTED = new State(); - public static final State SELECTED = new State(); - public static final State DONT_CARE = new State(); - - private MonitorCheckTreeSelectionModel _selectionModel; - private TreeCellRenderer _delegate; - private TristateCheckBox _checkBox = new TristateCheckBox(); - - private String _greenLocationIconFile ; - private String _redLocationIconFile ; - private String _yellowLocationIconFile; - private String _darkGreenLocationIconFile; - private String _grayLocationIconFile; - - private String _greenGroupIconFile; - private String _yellowGroupIconFile; - private String _redGroupIconFile; - private String _darkGreenGroupIconFile; - private String _grayGroupIconFile; - - private String _greenHsaIconFile; - private String _yellowHsaIconFile; - private String _redHsaIconFile; - private String _darkGreenHsaIconFile; - private String _grayHsaIconFile; - - private Icon _greenLocationIcon ; - private Icon _redLocationIcon ; - private Icon _yellowLocationIcon; - private Icon _darkGreenLocationIcon; - private Icon _grayLocationIcon; - - private Icon _greenGroupIcon ; - private Icon _redGroupIcon ; - private Icon _yellowGroupIcon; - private Icon _darkGreenGroupIcon; - private Icon _grayGroupIcon; - - private Icon _greenHsaIcon ; - private Icon _redHsaIcon ; - private Icon _yellowHsaIcon; - private Icon _darkGreenHsaIcon; - private Icon _grayHsaIcon; - - private JLabel _redLocationLabel = null; - private JLabel _greenLocationLabel = null; - private JLabel _yellowLocationLabel = null; - private JLabel _darkGreenLocationLabel = null; - private JLabel _grayLocationLabel = null; - private JLabel _redGroupLabel = null; - private JLabel _greenGroupLabel = null; - private JLabel _yellowGroupLabel = null; - private JLabel _darkGreenGroupLabel = null; - private JLabel _grayGroupLabel = null; - private JLabel _redHsaLabel = null; - private JLabel _greenHsaLabel = null; - private JLabel _yellowHsaLabel = null; - private JLabel _darkGreenHsaLabel = null; - private JLabel _grayHsaLabel = null; - - // private List _rowDataForAllLocationsList; - private Map _rowToCriticalColorMap = null; - - public MonitorCheckTreeCellRenderer(TreeCellRenderer delegate, MonitorCheckTreeSelectionModel selectionModel, - Map rowToCriticalColorMap, String iconsDir) - { - this._delegate = delegate; - this._selectionModel = selectionModel; - _rowToCriticalColorMap = rowToCriticalColorMap; - setLayout(new BorderLayout()); - setOpaque(false); - _checkBox.setOpaque(false); - - //createIcons(iconsDir); - createLabels(); - } - - public void setRowToCriticalColorMap(Map rowToCriticalColorMap) - { - _rowToCriticalColorMap = rowToCriticalColorMap; - } - - private void createLabels() - { - _redLocationLabel = new JLabel(); - _redLocationLabel.setIcon(_redLocationIcon); - _redLocationLabel.setForeground(Color.RED); - _greenLocationLabel = new JLabel(); - _greenLocationLabel.setIcon(_greenLocationIcon); - _greenLocationLabel.setForeground(Color.GREEN); - _yellowLocationLabel = new JLabel(); - _yellowLocationLabel.setIcon(_yellowLocationIcon); - _yellowLocationLabel.setForeground(Color.YELLOW); - _darkGreenLocationLabel = new JLabel(); - _darkGreenLocationLabel.setIcon(_darkGreenLocationIcon); - _darkGreenLocationLabel.setForeground(new Color(0, 153, 0)); - _grayLocationLabel = new JLabel(); - _grayLocationLabel.setIcon(_grayLocationIcon); - _grayLocationLabel.setForeground(Color.LIGHT_GRAY); - - _redGroupLabel = new JLabel(); - _redGroupLabel.setIcon(_redGroupIcon); - _redGroupLabel.setForeground(Color.RED); - _yellowGroupLabel = new JLabel(); - _yellowGroupLabel.setIcon(_yellowGroupIcon); - _yellowGroupLabel.setForeground(Color.YELLOW); - _greenGroupLabel = new JLabel(); - _greenGroupLabel.setIcon(_greenGroupIcon); - _greenGroupLabel.setForeground(Color.GREEN); - _darkGreenGroupLabel = new JLabel(); - _darkGreenGroupLabel.setIcon(_darkGreenGroupIcon); - _darkGreenGroupLabel.setForeground(new Color(0, 153, 0)); - _grayGroupLabel = new JLabel(); - _grayGroupLabel.setIcon(_grayGroupIcon); - _grayGroupLabel.setForeground(Color.LIGHT_GRAY); - - _redHsaLabel = new JLabel(); - _redHsaLabel.setIcon(_redHsaIcon); - _redHsaLabel.setForeground(Color.RED); - _yellowHsaLabel = new JLabel(); - _yellowHsaLabel.setIcon(_yellowHsaIcon); - _yellowHsaLabel.setForeground(Color.YELLOW); - _greenHsaLabel = new JLabel(); - _greenHsaLabel.setIcon(_greenHsaIcon); - _greenHsaLabel.setForeground(Color.GREEN); - _darkGreenHsaLabel = new JLabel(); - _darkGreenHsaLabel.setIcon(_darkGreenHsaIcon); - _darkGreenHsaLabel.setForeground(new Color(0, 153, 0)); - _grayHsaLabel = new JLabel(); - _grayHsaLabel.setIcon(_grayHsaIcon); - _grayHsaLabel.setForeground(Color.LIGHT_GRAY); - } - - - private void createIcons(String iconsDir) - { - _greenHsaIconFile = iconsDir + "GreenHsa.GIF"; - _redHsaIconFile = iconsDir + "RedHsa.GIF"; - _yellowHsaIconFile = iconsDir + "YellowHsa.GIF"; - _darkGreenHsaIconFile = iconsDir + "DarkGreenHsa.GIF"; - _grayHsaIconFile = iconsDir + "GrayHsa.GIF"; - - _greenGroupIconFile = iconsDir + "GreenGroup.GIF"; - _redGroupIconFile = iconsDir + "RedGroup.GIF"; - _yellowGroupIconFile = iconsDir + "YellowGroup.GIF"; - _darkGreenGroupIconFile = iconsDir + "DarkGreenGroup.GIF"; - _grayGroupIconFile = iconsDir + "GrayGroup.GIF"; - - _greenLocationIconFile = iconsDir + "GreenLocation.GIF"; - _redLocationIconFile = iconsDir + "RedLocation.GIF"; - _yellowLocationIconFile = iconsDir + "YellowLocation.GIF"; - _darkGreenLocationIconFile = iconsDir + "DarkGreenLocation.GIF"; - _grayLocationIconFile = iconsDir + "GrayLocation.GIF"; - - _greenLocationIcon = createIcon(_greenLocationIconFile); - _redLocationIcon = createIcon(_redLocationIconFile); - _yellowLocationIcon = createIcon(_yellowLocationIconFile); - _darkGreenLocationIcon = createIcon(_darkGreenLocationIconFile); - _grayLocationIcon = createIcon(_grayLocationIconFile); - - _greenGroupIcon= createIcon(_greenGroupIconFile); - _yellowGroupIcon= createIcon(_yellowGroupIconFile); - _redGroupIcon= createIcon(_redGroupIconFile); - _darkGreenGroupIcon= createIcon(_darkGreenGroupIconFile); - _grayGroupIcon= createIcon(_grayGroupIconFile); - - _greenHsaIcon= createIcon(_greenHsaIconFile); - _yellowHsaIcon= createIcon(_yellowHsaIconFile); - _redHsaIcon= createIcon(_redHsaIconFile); - _darkGreenHsaIcon= createIcon(_darkGreenHsaIconFile); - _grayHsaIcon= createIcon(_grayHsaIconFile); - - } - - public Component getTreeCellRendererComponent(JTree tree, Object value, - boolean selected, boolean expanded, - boolean leaf, int row, boolean hasFocus) - { - Component renderer = _delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); - TreePath path = tree.getPathForRow(row); - Component returnedComponent = null; - DefaultTreeCellRenderer tempRenderer = (DefaultTreeCellRenderer) renderer; - returnedComponent = getAppropriateLabel(leaf, path, tempRenderer, value); - if(path!=null) - { - if(_selectionModel.isPathSelected(path, true)) - { - _checkBox.setState(SELECTED); - } - else - { - _checkBox.setState(_selectionModel.isPartiallySelected(path) ? null : NOT_SELECTED); - } - } - removeAll(); - add(_checkBox, BorderLayout.WEST); - add(returnedComponent, BorderLayout.CENTER); - return this; - } - - private JLabel getAppropriateLabelOld(boolean isLeaf, TreePath path, DefaultTreeCellRenderer renderer, Object value) - { - String header = "MonitorCheckTreeCellRenderer.getAppropriateLabelOld(): "; - - JLabel returnedComponent = null; - renderer.setLeafIcon(null); - renderer.setClosedIcon(null); - renderer.setOpenIcon(null); - CodeTimer timer = new CodeTimer(); - timer.restart(); - - if (path == null) - { - System.out.println(header + "null value for value = " + value); - } - - if (isLeaf) - { - // System.out.println(header + "Leaf: value = " + value); - - returnedComponent = getLabelComponentForChild(value); - if (returnedComponent == null) - { - - - _greenLocationLabel.setText(value.toString()); - returnedComponent = _greenLocationLabel; - } - } - else - { - if(path != null) - { - if(path.getPathCount() == 3) // group node - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - - JLabel groupLabel = null; - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(node); - if (locationLabel == _redLocationLabel) - { - groupLabel = _redGroupLabel; - } - else if (locationLabel == _yellowLocationLabel) - { - groupLabel = _yellowGroupLabel; - } - else if (locationLabel == _grayLocationLabel) - { - // groupLabel = _grayGroupLabel; - groupLabel = _greenGroupLabel; - } - else if (locationLabel == _darkGreenLocationLabel) - { - groupLabel = _darkGreenGroupLabel; - } - else - { - groupLabel = _greenGroupLabel; - } - groupLabel.setText(value.toString()); - returnedComponent = groupLabel; - }// else if pathCount == 3 ends here - else if(path.getPathCount() == 2) //hsa node - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - int groupCount = node.getChildCount(); - JLabel hsaLabel = null; - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _redLocationLabel) - { - hsaLabel = _redHsaLabel; - break; - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _yellowLocationLabel) - { - hsaLabel = _yellowHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _grayLocationLabel) - { - hsaLabel = _greenHsaLabel; - // hsaLabel = _grayHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _darkGreenLocationLabel) - { - hsaLabel = _darkGreenHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - hsaLabel = _greenHsaLabel; - } - hsaLabel.setText(value.toString()); - returnedComponent = hsaLabel; - }// else if pathCount == 2 ends here - }// path != null ends here - - if(returnedComponent == null) - returnedComponent = renderer; - } - // timer.stop("Time elapsed in getAppropriateLabel():"); - return returnedComponent; - } - - // ------------------------------------------------------------------------------------------------------------- - - private void analyzePathInfo(boolean isLeaf, TreePath path, Object value) - { - //This method is just for debugging purposes and can be commented out at will - String header = "MonitorCheckTreeCellRenderer.analyzePathInfo(): "; - - boolean path2 = false; - boolean path3 = false; - boolean path4 = false; - boolean nullPath = false; - - int pathCount = -1; - String pathString = null; - if (path != null) - { - pathCount = path.getPathCount(); - pathString = path.toString(); - } - - - System.out.println(header + "isLeaf = " + isLeaf + - " pathCount = " + pathCount + - " treePath = " + pathString + - " for nodeValue = " + value); - - /* - if (path != null) - { - pathCount = path.getPathCount(); - - switch(pathCount) - { - case 2: - path2 = true; - break; - case 3: - path3 = true; - break; - case 4: - path4 = true; - break; - } - } - else // (path == null) - { - nullPath = true; - } - - if (isLeaf != path4) - { - - System.out.print(header + "isLeaf = " + isLeaf + - " but path4 = " + path4 + - " pathCount = " + pathCount + - " treePath = " + path.toString() + - " for nodeValue = " + value); - - if (nullPath) - { - System.out.println(" nullPath is true"); - } - else - { - System.out.println(); - } - - } - else //isLeaf == path4 - { - // System.out.print(header + "isLeaf = " + isLeaf + - // " AND path4 = " + path4 + - // " for nodeValue = " + value); - - if (nullPath) - { - System.out.println(" nullPath is true"); - } - else - { - System.out.println(); - } - } - - */ - - } - - // ------------------------------------------------------------------------------------------------------------- - - - private JLabel getAppropriateLabel(boolean isLeaf, TreePath path, DefaultTreeCellRenderer renderer, Object value) - { - String header = "MonitorCheckTreeCellRenderer.getAppropriateLabel(): "; - - JLabel returnedComponent = null; - renderer.setLeafIcon(null); - renderer.setClosedIcon(null); - renderer.setOpenIcon(null); - CodeTimer timer = new CodeTimer(); - timer.restart(); - - - int pathCount = -1; - if (path != null) - { - pathCount = path.getPathCount(); - } - - // analyzePathInfo(isLeaf, path, value); - - if (isLeaf) - // if (path != null && path.getPathCount() == 4) - { - // System.out.println(header + "Leaf: value = " + value); - - if (pathCount == 4) - { - - returnedComponent = getLabelComponentForChild(value); - if (returnedComponent == null) - { - System.out.println(header + "********** - got here **************"); - _greenLocationLabel.setText(value.toString()); - returnedComponent = _greenLocationLabel; - } - } - else if (pathCount == 3) - { - returnedComponent = getGroupLabel(path, value); - } - else if (pathCount == 2) - { - returnedComponent = getHsaLabel(path, value); - } - else if (pathCount == -1) - { - returnedComponent = getLabelComponentForChild(value); - } - } - else //not a leaf - { - if(path != null) - { - if(path.getPathCount() == 3) // group node - { - returnedComponent = getGroupLabel(path, value); - } - else if(path.getPathCount() == 2) //hsa node - { - returnedComponent = getHsaLabel(path, value); - - } - }// path != null ends here - else //path == null - { - System.out.println(header + "value = " + value + " and the path == null !!!!!!!!!!!!!!!!!!!!!!!!"); - } - - if(returnedComponent == null) - returnedComponent = renderer; - } - // timer.stop("Time elapsed in getAppropriateLabel():"); - return returnedComponent; - } - - // --------------------------------------------------------------------------------------------------------------- - - private JLabel getGroupLabel(TreePath treePath, Object value) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - JLabel groupLabel = null; - - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(node); - if (locationLabel == _redLocationLabel) - { - groupLabel = _redGroupLabel; - } - else if (locationLabel == _yellowLocationLabel) - { - groupLabel = _yellowGroupLabel; - } - else if (locationLabel == _grayLocationLabel) - { - // groupLabel = _grayGroupLabel; - groupLabel = _greenGroupLabel; - } - else if (locationLabel == _darkGreenLocationLabel) - { - groupLabel = _darkGreenGroupLabel; - } - else - { - groupLabel = _greenGroupLabel; - } - groupLabel.setText(value.toString()); - - - return groupLabel; - } - - // ------------------------------------------------------------------------------------------------------- - - private JLabel getHsaLabel(TreePath treePath, Object value) - { - JLabel hsaLabel = null; - - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - int groupCount = node.getChildCount(); - - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _redLocationLabel, _redHsaLabel, node, groupCount); - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _yellowLocationLabel, _yellowHsaLabel, node, groupCount); - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _grayLocationLabel, _greenHsaLabel, node, groupCount); //gray to green on purpose - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _darkGreenLocationLabel, _darkGreenHsaLabel, node, groupCount); - - if(hsaLabel == null) - { - hsaLabel = _greenHsaLabel; - } - hsaLabel.setText(value.toString()); - - - return hsaLabel; - - } - // --------------------------------------------------------------------------------------------------------------- - private JLabel getHsaLabelOld(TreePath treePath, Object value) - { - JLabel hsaLabel = null; - - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - int groupCount = node.getChildCount(); - - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _redLocationLabel) - { - hsaLabel = _redHsaLabel; - break; - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _yellowLocationLabel) - { - hsaLabel = _yellowHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _grayLocationLabel) - { - hsaLabel = _greenHsaLabel; - // hsaLabel = _grayHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _darkGreenLocationLabel) - { - hsaLabel = _darkGreenHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - hsaLabel = _greenHsaLabel; - } - hsaLabel.setText(value.toString()); - - - return hsaLabel; - - } - // --------------------------------------------------------------------------------------------------------------- - private JLabel getHsaLocationLabelChildByColorLabelMatch(JLabel resultHsaLabel, JLabel targetLocationLabel, - JLabel targetHsaLabel, TreeNode node, int groupCount ) - { - if (resultHsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(resultHsaLabel == null) - { - if(locationLabel == targetLocationLabel) - { - resultHsaLabel = targetHsaLabel; - break; - } - } - } //end for - } - - return resultHsaLabel; - } - - // --------------------------------------------------------------------------------------------------------------- - - private JLabel getLocationLabelDenotingCurrentStateForParentNode(DefaultMutableTreeNode groupNode) - { - // CodeTimer timer = new CodeTimer(); - // timer.restart(); - int locationCount = groupNode.getChildCount(); - JLabel locationLabelDenotingCurrentState = null; - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - - if(locationLabelDenotingCurrentState == _redLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - if(locationLabelDenotingCurrentState != _redLocationLabel) - { - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - if(locationLabelDenotingCurrentState == _yellowLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - } - if(locationLabelDenotingCurrentState != _yellowLocationLabel) - { - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - if(locationLabelDenotingCurrentState == _grayLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - } - if(locationLabelDenotingCurrentState != _grayLocationLabel) - { - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - if(locationLabelDenotingCurrentState == _darkGreenLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - } - locationLabelDenotingCurrentState = _greenLocationLabel; - // timer.stop("Time elapsed in getLocationLabelDenotingCurrentStateForParentNode():"); - return locationLabelDenotingCurrentState; - } - - private JLabel getLabelComponentForChild(Object value) - { - // _timer.restart(); - JLabel label = null; - Color darkGreen = new Color(0, 153, 0); - String lid = value.toString(); - - Color criticalColor = (Color) _rowToCriticalColorMap.get(lid); - if(criticalColor == Color.RED) - { - _redLocationLabel.setText(value.toString()); - label = _redLocationLabel; - } - else if(criticalColor == Color.YELLOW) - { - _yellowLocationLabel.setText(value.toString()); - label = _yellowLocationLabel; - } - else if(criticalColor == Color.GRAY) - { - _grayLocationLabel.setText(value.toString()); - label = _grayLocationLabel; - } - // else if(criticalColor.equals(new Color(0, 153, 0))) - else if(criticalColor == darkGreen) - { - _darkGreenLocationLabel.setText(value.toString()); - label = _darkGreenLocationLabel; - } - else - { - _greenLocationLabel.setText(value.toString()); - label = _greenLocationLabel; - } - - // _timer.stop("Time elapsed in getLabelComponentForChild()"); - return label; - } - - /* private JLabel getLabelComponentForChild(Object value) - { - // _timer.restart(); - JLabel label = null; - //List allRowDataList = _tableManager.getAllRowDataList(); - List rowDataForAllLocationsList = _rowDataForAllLocationsList; - for(int i=0; i < rowDataForAllLocationsList.size(); i++) - { - RiverMonitorJTableRowData2 rowData = (RiverMonitorJTableRowData2) rowDataForAllLocationsList.get(i); - if(rowData.getDataValue("Location Id").toString().equals(value.toString())) - { - Color criticalColor = rowData.getCriticalColorForThisRow(); - if(criticalColor == Color.RED) - { - _redLocationLabel.setText(value.toString()); - label = _redLocationLabel; - break; - } - else if(criticalColor == Color.YELLOW) - { - _yellowLocationLabel.setText(value.toString()); - label = _yellowLocationLabel; - break; - } - else if(criticalColor == Color.GRAY) - { - _grayLocationLabel.setText(value.toString()); - label = _grayLocationLabel; - break; - } - else if(criticalColor.equals(new Color(0, 153, 0))) - { - _darkGreenLocationLabel.setText(value.toString()); - label = _darkGreenLocationLabel; - break; - } - else - { - _greenLocationLabel.setText(value.toString()); - label = _greenLocationLabel; - break; - } - } - } - // _timer.stop("Time elapsed in getLabelComponentForChild()"); - return label; - } - */ - - private Icon createIcon(String fileName) - { - Icon icon = null; - int width = 15; - int height = 15; - Image image = Toolkit.getDefaultToolkit().getImage(fileName); - Image newImage = image.getScaledInstance(width, height, Image.SCALE_FAST); - icon = new ImageIcon(newImage); - return icon; - } - - - /** - * Maintenance tip - There were some tricks to getting this code - * working: - * - * 1. You have to overwite addMouseListener() to do nothing - * 2. You have to add a mouse event on mousePressed by calling - * super.addMouseListener() - * 3. You have to replace the UIActionMap for the keyboard event - * "pressed" with your own one. - * 4. You have to remove the UIActionMap for the keyboard event - * "released". - * 5. You have to grab focus when the next state is entered, - * otherwise clicking on the component won't get the focus. - * 6. You have to make a TristateDecorator as a button model that - * wraps the original button model and does state management. - */ - public class TristateCheckBox extends JCheckBox { - - private final TristateDecorator model; - - public TristateCheckBox(String text, Icon icon, State initial){ - super(text, icon); - // Add a listener for when the mouse is pressed - super.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e) { - grabFocus(); - model.nextState(); - } - }); - // Reset the keyboard action map - ActionMap map = new ActionMapUIResource(); - map.put("pressed", new AbstractAction() { - public void actionPerformed(ActionEvent e) { - grabFocus(); - model.nextState(); - } - }); - map.put("released", null); - SwingUtilities.replaceUIActionMap(this, map); - // set the model to the adapted model - model = new TristateDecorator(getModel()); - setModel(model); - setState(initial); - } - public TristateCheckBox(String text, State initial) { - this(text, null, initial); - } - public TristateCheckBox(String text) { - this(text, DONT_CARE); - } - public TristateCheckBox() { - this(null); - } - - /** No one may add mouse listeners, not even Swing! */ - public void addMouseListener(MouseListener l) { } - /** - * Set the new state to either SELECTED, NOT_SELECTED or - * DONT_CARE. If state == null, it is treated as DONT_CARE. - */ - public void setState(State state) { model.setState(state); } - /** Return the current state, which is determined by the - * selection status of the model. */ - public State getState() { return model.getState(); } - public void setSelected(boolean b) { - if (b) { - setState(SELECTED); - } else { - setState(NOT_SELECTED); - } - } - /** - * Exactly which Design Pattern is this? Is it an Adapter, - * a Proxy or a Decorator? In this case, my vote lies with the - * Decorator, because we are extending functionality and - * "decorating" the original model with a more powerful model. - */ - private class TristateDecorator implements ButtonModel { - private final ButtonModel other; - private TristateDecorator(ButtonModel other) { - this.other = other; - } - private void setState(State state) { - if (state == NOT_SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(false); - } else if (state == SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(true); - } else { // either "null" or DONT_CARE - other.setArmed(true); - setPressed(true); - setSelected(true); - } - } - /** - * The current state is embedded in the selection / armed - * state of the model. - * - * We return the SELECTED state when the checkbox is selected - * but not armed, DONT_CARE state when the checkbox is - * selected and armed (grey) and NOT_SELECTED when the - * checkbox is deselected. - */ - private State getState() { - if (isSelected() && !isArmed()) { - // normal black tick - return SELECTED; - } else if (isSelected() && isArmed()) { - // don't care grey tick - return DONT_CARE; - } else { - // normal deselected - return NOT_SELECTED; - } - } - /** We rotate between NOT_SELECTED, SELECTED and DONT_CARE.*/ - private void nextState() { - State current = getState(); - if (current == NOT_SELECTED) { - setState(SELECTED); - } else if (current == SELECTED) { - setState(DONT_CARE); - } else if (current == DONT_CARE) { - setState(NOT_SELECTED); - } - } - /** Filter: No one may change the armed status except us. */ - public void setArmed(boolean b) { - } - /** We disable focusing on the component when it is not - * enabled. */ - public void setEnabled(boolean b) { - setFocusable(b); - other.setEnabled(b); - } - /** All these methods simply delegate to the "other" model - * that is being decorated. */ - public boolean isArmed() { return other.isArmed(); } - public boolean isSelected() { return other.isSelected(); } - public boolean isEnabled() { return other.isEnabled(); } - public boolean isPressed() { return other.isPressed(); } - public boolean isRollover() { return other.isRollover(); } - public void setSelected(boolean b) { other.setSelected(b); } - public void setPressed(boolean b) { other.setPressed(b); } - public void setRollover(boolean b) { other.setRollover(b); } - public void setMnemonic(int key) { other.setMnemonic(key); } - public int getMnemonic() { return other.getMnemonic(); } - public void setActionCommand(String s) { - other.setActionCommand(s); - } - public String getActionCommand() { - return other.getActionCommand(); - } - public void setGroup(ButtonGroup group) { - other.setGroup(group); - } - public void addActionListener(ActionListener l) { - other.addActionListener(l); - } - public void removeActionListener(ActionListener l) { - other.removeActionListener(l); - } - public void addItemListener(ItemListener l) { - other.addItemListener(l); - } - public void removeItemListener(ItemListener l) { - other.removeItemListener(l); - } - public void addChangeListener(ChangeListener l) { - other.addChangeListener(l); - } - public void removeChangeListener(ChangeListener l) { - other.removeChangeListener(l); - } - public Object[] getSelectedObjects() { - return other.getSelectedObjects(); - } - } - } -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeManager.java deleted file mode 100755 index 49ae55609c..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeManager.java +++ /dev/null @@ -1,351 +0,0 @@ -package ohd.hseb.monitor.treefilter; - -import java.awt.Color; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.JCheckBox; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -public class MonitorCheckTreeManager extends MouseAdapter implements TreeSelectionListener -{ - private MonitorCheckTreeSelectionModel _selectionModel; - private JTree _tree = new JTree(); - int _hotspot = new JCheckBox().getPreferredSize().width; - - private List _allAvailablePathsList = null; - private TreePath[] _allAvailablePaths = null; - private Map _allAvailablePathsMap = new HashMap(); - - public MonitorCheckTreeManager(JTree tree, - TreePath[] preSelectedPaths, - TreePath[] preExpandedPaths, - Map rowToCriticalColorMap, - String iconsDir) - { - final String header = "MonitorCheckTreeManager - constructor()"; - - System.out.println("In "+ header); - this._tree = tree; - _selectionModel = new MonitorCheckTreeSelectionModel(tree.getModel()); - tree.setCellRenderer(new MonitorCheckTreeCellRenderer(tree.getCellRenderer(), _selectionModel, rowToCriticalColorMap, iconsDir)); - - _allAvailablePathsList = new ArrayList(); - TreeNode root = (TreeNode)tree.getModel().getRoot(); - determineAllAvailablePaths(new TreePath(root)); - _allAvailablePaths = (TreePath[]) (_allAvailablePathsList.toArray(new TreePath[0])); - - printTreePathArray(preSelectedPaths, header); - if(preSelectedPaths != null) - { - setPreSelectedPathsAsSelected(getValidTreePaths(preSelectedPaths)); -// printTreePathArray(getAppropriateTreePaths(preSelectedPaths), header + "getAppPaths(): "); - } - - if(preExpandedPaths != null) - { - expandThesePaths(getValidTreePaths(preExpandedPaths)); - } - - tree.addMouseListener(this); - _selectionModel.addTreeSelectionListener(this); - - } - - private void printTreePathArray(TreePath[] treePathArray, String message) - { - if (message != null) - { - System.out.println(message); - } - - if (treePathArray != null) - { - for (TreePath treePath : treePathArray) - { - System.out.println(treePath); - } - } - - return; - } - - public void setRowToCriticalColorMap(Map rowToCriticalColorMap) - { - MonitorCheckTreeCellRenderer renderer = (MonitorCheckTreeCellRenderer) _tree.getCellRenderer(); - renderer.setRowToCriticalColorMap(rowToCriticalColorMap); - } - - public TreePath[] getAllAvailablePaths() - { - return _allAvailablePaths; - } - - public void setPreSelectedPathsAsSelected(TreePath[] preSelectedPathArray) - { - String header = "MonitorCheckTreeManager.setPreSelectedPathsAsSelected(): "; - - //This is to prevent a whole bunch of defunct selectionModels from acting as listeners, - _selectionModel.removeTreeSelectionListener(this); - - for(int i=0 ; i < preSelectedPathArray.length; i++) - { - selectAPath(preSelectedPathArray[i]); - } - - _selectionModel.addTreeSelectionListener(this); - _tree.treeDidChange(); - } - -//------------------------------------------------------------------------------------------------- - - public TreePath[] getValidTreePaths(TreePath desiredPathArray[]) - { - String header = "MonitorCheckTreeManager.getAppropriateTreePaths(): "; - - if (desiredPathArray == null) - return null; - - TreePath pathsToReturn[] = null; - Set pathsToReturnSet = new HashSet(); - - // if the desiredPath is [HSA] then return all valid paths - if(desiredPathArray.length == 1 && desiredPathArray[0].toString().equals("[HSA]")) - { - for(int i=0 ; i< _allAvailablePathsList.size(); i++) - { - TreePath path = (TreePath) _allAvailablePathsList.get(i); - pathsToReturnSet.add(path); - } - } - else - { - //Create a set to search - Set desiredPathStringSet = new HashSet(); - for (TreePath desiredPath : desiredPathArray) - { - desiredPathStringSet.add(desiredPath.toString()); - } - - //check each path - for(int i=0 ; i< _allAvailablePathsList.size(); i++) - { - TreePath path = (TreePath) _allAvailablePathsList.get(i); - if ( withinTreeSet(path, desiredPathStringSet) ) - { - pathsToReturnSet.add(path); - } - } - } - - pathsToReturn = (TreePath[]) pathsToReturnSet.toArray(new TreePath[0]); - - // printTreePathArray(pathsToReturn, header); - - return pathsToReturn; - } - -// ------------------------------------------------------------------------------------------------- - - private void removeSelectedPaths() - { - _selectionModel.removeTreeSelectionListener(this); - - TreePath paths[] = _selectionModel.getSelectionPaths(); - if(paths != null) - { - for(int i=0; i < paths.length; i++) - { - - try - { - _selectionModel.removeSelectionPath(paths[i]); - } - finally - { - - _tree.treeDidChange(); - } - } - } - - _selectionModel.addTreeSelectionListener(this); - } - - private void selectAPath(TreePath path) - { - boolean selected = _selectionModel.isPathSelected(path, true); - - //TODO - What does the following line do? - //This was to prevent a whole bunch of defunct selectionModels from acting as listeners, - //although, it seems like overkill to be called that many times. - // _selectionModel.removeTreeSelectionListener(this); - try - { - if(!selected) - { - _selectionModel.addSelectionPath(path); - } - } - finally - { - - } - - } - - public void mouseClicked(MouseEvent me) - { - TreePath path = _tree.getPathForLocation(me.getX(), me.getY()); - if(path==null) - return; - if(me.getX()>_tree.getPathBounds(path).x+_hotspot) - return; - - boolean selected = _selectionModel.isPathSelected(path, true); - _selectionModel.removeTreeSelectionListener(this); - try - { - if(selected) - _selectionModel.removeSelectionPath(path); - else - _selectionModel.addSelectionPath(path); - } - finally - { - _selectionModel.addTreeSelectionListener(this); - _tree.treeDidChange(); - } - } - - public MonitorCheckTreeSelectionModel getSelectionModel() - { - return _selectionModel; - } - - public void valueChanged(TreeSelectionEvent e) - { - // Auto-generated method stub - } - - - private void determineAllAvailablePaths(TreePath parent) - { - // Traverse children - TreeNode node = (TreeNode) parent.getLastPathComponent(); - if (node.getChildCount() >= 0) - { - for (Enumeration e = node.children(); e.hasMoreElements();) - { - TreeNode n = (TreeNode) e.nextElement(); - - TreePath path = parent.pathByAddingChild(n); - determineAllAvailablePaths(path); - - if(_allAvailablePathsList != null) - { - _allAvailablePathsList.add(path); - _allAvailablePathsMap.put(path.toString(), path); - } - } - } - - } - - private boolean withinTreeSet(TreePath path, Set treePathStringSet) - { - boolean result = false; - - result = treePathStringSet.contains(path.toString()); - - return result; - } - - - private boolean withinTree(TreePath path, TreePath[] pathArray) - { - boolean result = false; - - Set set = new HashSet(); - - for (TreePath pathFromArray: pathArray) - { - set.add(pathFromArray.toString()); - } - - result = set.contains(path.toString()); - - return result; - } - - public void collapseEntireTree() - { - for(int i = 0; i < _allAvailablePathsList.size(); i++) - { - TreePath treePath = (TreePath) _allAvailablePathsList.get(i); - - Object[] pathArray = treePath.getPath(); - if (pathArray.length == 2) //just collapse the 2nd level. Collapsing this level collapses the rest. - { - _tree.collapsePath(treePath); - } - - } - } - - public void expandThesePaths(TreePath[] paths) - { String header = "MonitorCheckTreeManager.expandThesePaths(): "; - try - { - for(int i=0; i< paths.length ; i++) - { - _tree.expandPath(paths[i]); - } - - } - catch(Exception e) - { - System.out.println("Exception :"+e); - } - finally - { - } - - - } - - public TreePath[] getAllExpandedPaths() - { - TreePath[] allExpandedPaths = null; - List allExpandedPathList = new ArrayList(); - - for(int i=0; i < _allAvailablePaths.length; i++) - { - TreePath path = _allAvailablePaths[i]; - if(_tree.isExpanded(path)) - { - allExpandedPathList.add(path); - - } - else - continue; - } - - allExpandedPaths = (TreePath[]) allExpandedPathList.toArray(new TreePath[0]); - - return allExpandedPaths; - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeSelectionModel.java b/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeSelectionModel.java deleted file mode 100755 index d20e95db4e..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeSelectionModel.java +++ /dev/null @@ -1,206 +0,0 @@ -package ohd.hseb.monitor.treefilter; - -import java.util.ArrayList; -import java.util.Stack; - -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -public class MonitorCheckTreeSelectionModel extends DefaultTreeSelectionModel -{ - private static int _instanceCount = 0; - private int _instanceId = 0; - private TreeModel model; - - public MonitorCheckTreeSelectionModel(TreeModel model) - { - this.model = model; - setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - _instanceCount ++; - _instanceId = _instanceCount; - System.out.println("MonitorCheckTreeSelectionModel(): _instanceId = " + _instanceId); - } - - public TreePath[] getSelectionPaths() - { - // printInstanceId(); - - return super.getSelectionPaths(); - } - - public void printInstanceId() - { - System.out.println("MonitorCheckTreeSelectionModel.getSelectionPaths(): instanceId = " + _instanceId + "/" + _instanceCount); - } - - // tests whether there is any unselected node in the subtree of given path - public boolean isPartiallySelected(TreePath path) - { - if(isPathSelected(path, true)) - return false; - TreePath[] selectionPaths = getSelectionPaths(); - if(selectionPaths==null) - return false; - for(int j = 0; j getOfficeNotesColumnsList(List officeNotesColumnDescriptorList) - { - if( officeNotesColumnDescriptorList == null) - { - officeNotesColumnDescriptorList = new ArrayList(); - } - - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(TOPIC, true, 75, "center")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(ID, true, 75, "center")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(POSTING_TIME, true, 145, "center")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(NOTE, true, 640, "left")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(EXPIRE_TIME, true, 145, "center")); - - return officeNotesColumnDescriptorList; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesDataManager.java deleted file mode 100755 index 5148b69b14..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesDataManager.java +++ /dev/null @@ -1,125 +0,0 @@ -package ohd.hseb.officenotes; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.OfficeNotesRecord; -import ohd.hseb.ihfsdb.generated.OfficeNotesTable; -import ohd.hseb.util.SessionLogger; - -public class OfficeNotesDataManager -{ - private Database _db = null; - private SessionLogger _logger = null; - private String _missingRepresentation; - - public OfficeNotesDataManager(Database dbHandler, SessionLogger logger, String missingRepresentation) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public int delete(OfficeNotesRecord rec) - { - int ret = -1; - OfficeNotesTable officeNotesTable = new OfficeNotesTable(_db); - try - { - ret = officeNotesTable.delete(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public int updateOrInsert(OfficeNotesRecord rec) - { - int ret = -1; - OfficeNotesTable officeNotesTable = new OfficeNotesTable(_db); - try - { - ret = officeNotesTable.insertOrUpdate(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public List readDataFromOfficeNotes() - { - List officeNotesInfoList = null; - List dataList = null; - - OfficeNotesTable officeNotesTable = new OfficeNotesTable(_db); - OfficeNotesRecord officeNotesRecord = null; - String whereClause = null; - String header = "OfficeNotesDataManager.readDataFromOfficeNotes(): "; - - try - { - whereClause = "order by topic, id, postingtime"; - officeNotesInfoList = officeNotesTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(officeNotesInfoList != null) - { - dataList = new ArrayList(); - for(int i=0;i < officeNotesInfoList.size(); i++) - { - officeNotesRecord = (OfficeNotesRecord) officeNotesInfoList.get(i); - OfficeNotesJTableRowData rowData = new OfficeNotesJTableRowData(_missingRepresentation); - rowData.setOfficeNotesRecord(officeNotesRecord); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" Officeinfo list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - public int getCountOfOfficeNotes() - { - int numOfOfficeNotes = -1; - List notesList = readDataFromOfficeNotes(); - if(notesList != null) - { - numOfOfficeNotes = notesList.size(); - } - return numOfOfficeNotes; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesDialog.java deleted file mode 100755 index 8afdaada43..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesDialog.java +++ /dev/null @@ -1,658 +0,0 @@ -package ohd.hseb.officenotes; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.text.JTextComponent; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.OfficeNotesRecord; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class OfficeNotesDialog extends JDialog -{ - private List _officeNotesColumnDescriptorList = null; - private JTableManager _officeNotesTableManager = null; - private OfficeNotesDataManager _officeNotesDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JFrame _mainFrame; - private String _id; - private Map _lidDescDetailsMap; - private String _definedIds[]; - private int _selectedRowIndex; - private boolean _isUpdateOrDeleteToBeDone = false; - - private JLabel _topicLabel; - private JTextField _topicField ; - private JLabel _idLabel; - private JLabel _nameLabel; - private JLabel _countyLabel; - private JLabel _stateLabel; - private JTextField _nameField; - private JTextField _countyField; - private JTextField _stateField; - private JComboBox _idComboBox; - private JTextComponent _idComboBoxTextComponent; - private JLabel _noteLabel ; - private JTextArea _noteArea; - private JLabel _dataTimeLabel ; - private JTextField _dataTimeField; - private JLabel _postingTimeLabel ; - private JTextField _postingTimeField ; - private JLabel _updateTimeLabel ; - private JTextField _updateTimeField ; - private JLabel _expireTimeLabel; - private JTextField _expireTimeField ; - private JButton _updateButton; - private JButton _deleteButton ; - private JButton _closeButton ; - private String _missingRepresentation; - - private boolean _infoDialogShown = false; - private boolean _displayingSelectedRowData = false; - private SessionLogger _logger = null; - - private OfficeNotesJTableRowData _selectedRowData; - private TextFieldInputVerifier _textFieldInputVerifier = new TextFieldInputVerifier(); - - private int _previousRowToHighlight = -1; - - public OfficeNotesDialog(JFrame mainFrame, OfficeNotesDataManager officeNotesDataMgr, String topic, String[] ids, Map lidDescDetailsMap, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - _mainFrame = mainFrame; - _lidDescDetailsMap = lidDescDetailsMap; - _definedIds = ids; - this.setTitle("OfficeNotes"); - this.getContentPane().setLayout(new GridBagLayout()); - _officeNotesDataMgr = officeNotesDataMgr; - initialize(officeNotesDataMgr, topic, ids); - Dimension min = new Dimension(1100,570); - new WindowResizingManager(this, min, min); - this.pack(); - this.setLocation(25, 25); - } - - public void showOfficeNotesDialog(String id) - { - if(id != null) - { - _idComboBox.setSelectedItem(id); - _officeNotesTableManager.deselectRows(_previousRowToHighlight, _previousRowToHighlight); - int rowToHighLight = _officeNotesTableManager.getTheRowIndexToHighLightBasedOnValue(id); - if(rowToHighLight != -1) - { - _officeNotesTableManager.selectRows(rowToHighLight, rowToHighLight); - _previousRowToHighlight = rowToHighLight; - } - } - this.setVisible(true); - } - - private void initialize(OfficeNotesDataManager officeNotesDataMgr, String topic, String[] ids) - { - _officeNotesColumnDescriptorList = new OfficeNotesColumns().getOfficeNotesColumnsList(_officeNotesColumnDescriptorList); - _allRowDataList = officeNotesDataMgr.readDataFromOfficeNotes(); - _officeNotesTableManager = new ComplexJTableManager(_officeNotesColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _officeNotesTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _officeNotesTableManager.setDisplayableColumns(columnsSelected, true, true); - _officeNotesTableManager.setPreferredSizeForJScrollPane(new Dimension(1080, 300)); - _officeNotesTableManager.setVerifyInputWhenFocusTarget(false); - OfficeNotesTableMouseListener tableMouseListener = new OfficeNotesTableMouseListener(); - _officeNotesTableManager.addTableListener(tableMouseListener); - _tableScrollPane = _officeNotesTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(1090,310)); - - _topicLabel = new JLabel("Topic"); - _topicField = new JTextField(25); - _topicField.setInputVerifier(_textFieldInputVerifier); - if(topic != null) - { - _topicField.setText(topic); - } - - _idLabel = new JLabel("Id"); - _idLabel.setMaximumSize(_topicLabel.getPreferredSize()); - if(ids == null) - { - _idComboBox = new JComboBox(); - } - else - { - _idComboBox = new JComboBox(ids); - } - _idComboBoxTextComponent = (JTextComponent) _idComboBox.getEditor().getEditorComponent(); - _idComboBoxTextComponent.setInputVerifier(_textFieldInputVerifier); - _idComboBox.setEditable(true); - - _nameLabel = new JLabel(" Name"); - _countyLabel = new JLabel(" County"); - _stateLabel = new JLabel(" State"); - _nameField = new JTextField(); - _countyField = new JTextField(); - _stateField = new JTextField(); - _nameField.setEditable(false); - _countyField.setEditable(false); - _stateField.setEditable(false); - - _noteLabel = new JLabel("Note"); - _noteArea = new JTextArea(); - _noteArea.setLineWrap(true); - JScrollPane textPane = new JScrollPane(_noteArea); - - _dataTimeLabel = new JLabel("Data Time"); - _dataTimeField = new DateTimeTextField(System.currentTimeMillis(), _mainFrame, "Data Time", 20); - _dataTimeField.setInputVerifier(_textFieldInputVerifier); - - _postingTimeLabel = new JLabel("Posting Time"); - _postingTimeField = new JTextField(); - _postingTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _postingTimeField.setEditable(false); - - _updateTimeLabel = new JLabel("Update Time"); - _updateTimeField = new JTextField(); - _updateTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _updateTimeField.setEditable(false); - - _expireTimeLabel = new JLabel("Expire Time"); - _expireTimeField = new DateTimeTextField(System.currentTimeMillis(), _mainFrame, "Expire Time", 20); - _expireTimeField.setPreferredSize(new Dimension(100,30)); - _expireTimeField.setInputVerifier(_textFieldInputVerifier); - - JPanel idPanel = new JPanel(); - idPanel.setLayout(new GridLayout(1,2)); - idPanel.add(_idLabel); - idPanel.add(_idComboBox); - - JPanel nameLabelPanel = new JPanel(); - nameLabelPanel.setLayout(new GridLayout(1,1)); - nameLabelPanel.add(_nameLabel); - - JPanel nameFieldPanel = new JPanel(); - nameFieldPanel.setLayout(new GridLayout(1,1)); - nameFieldPanel.add(_nameField); - - JPanel countyPanel = new JPanel(); - countyPanel.setLayout(new GridLayout(1,2)); - countyPanel.add(_countyLabel); - countyPanel.add(_countyField); - - JPanel statePanel = new JPanel(); - statePanel.setLayout(new GridLayout(1,2)); - statePanel.add(_stateLabel); - statePanel.add(_stateField); - - JPanel idInfoCountyInfoStateInfoPanel = new JPanel(); - idInfoCountyInfoStateInfoPanel.setLayout(new GridLayout(1,3)); - idInfoCountyInfoStateInfoPanel.add(idPanel); - idInfoCountyInfoStateInfoPanel.add(countyPanel); - idInfoCountyInfoStateInfoPanel.add(statePanel); - - JPanel topicPanel = new JPanel(); - topicPanel.setLayout(new GridLayout(1,3)); - topicPanel.add(_topicLabel); - topicPanel.add(_topicField); - topicPanel.add(_nameLabel); - - JPanel topicNamePanel = new JPanel(); - topicNamePanel.setLayout(new GridLayout(1,2)); - topicNamePanel.add(topicPanel); - topicNamePanel.add(nameFieldPanel); - - JPanel noteLabelPanel = new JPanel(); - noteLabelPanel.setLayout(new GridLayout(1,1)); - noteLabelPanel.add(_noteLabel); - - JPanel topicInfoIdInfoNoteLabelPanel = new JPanel(); - topicInfoIdInfoNoteLabelPanel.setLayout(new GridLayout(3,1)); - topicInfoIdInfoNoteLabelPanel.add(topicNamePanel); - topicInfoIdInfoNoteLabelPanel.add(idInfoCountyInfoStateInfoPanel); - topicInfoIdInfoNoteLabelPanel.add(noteLabelPanel); - - JPanel noteFieldPanel = new JPanel(); - noteFieldPanel.setLayout(new GridLayout(1,1)); - noteFieldPanel.add(textPane); - - JPanel topicIdNotePanel = new JPanel(); - topicIdNotePanel.setLayout(new GridLayout(2,1)); - topicIdNotePanel.add(topicInfoIdInfoNoteLabelPanel); - topicIdNotePanel.add(noteFieldPanel); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(1,1)); - infoPanel.add(topicIdNotePanel); - - JPanel timePanel = new JPanel(); - timePanel.setLayout(new GridLayout(4,3)); - timePanel.add(createDummyPanel()); - timePanel.add(_dataTimeLabel); - _dataTimeField.setColumns(20); - timePanel.add(_dataTimeField); - timePanel.add(createDummyPanel()); - timePanel.add(_expireTimeLabel); - _expireTimeField.setColumns(20); - timePanel.add(_expireTimeField); - - timePanel.add(createDummyPanel()); - timePanel.add(_postingTimeLabel); - _postingTimeField.setColumns(20); - timePanel.add(_postingTimeField); - timePanel.add(createDummyPanel()); - timePanel.add(_updateTimeLabel); - _updateTimeField.setColumns(20); - timePanel.add(_updateTimeField); - - JPanel actionPanel = new JPanel(); - actionPanel = new JPanel(); - _updateButton = new JButton("Save"); - _deleteButton = new JButton("Delete"); - _closeButton = new JButton("Close"); - _closeButton.setVerifyInputWhenFocusTarget(false); - actionPanel.add(_updateButton); - actionPanel.add(_deleteButton); - actionPanel.add(_closeButton); - - JPanel editPanel = new JPanel(); - editPanel.setLayout(new GridLayout(1,2)); - editPanel.setBorder(BorderFactory.createTitledBorder("Details")); - - editPanel.add(infoPanel); - editPanel.add(timePanel); - - Container contentPane = this.getContentPane(); - ComponentHelper.addFrameComponent(contentPane, tableScrollPanePanel, 0, 0,1,1,1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, editPanel, 0, 1,1,1, 1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, actionPanel, 0, 2,1,1, 1, 1, 0); - - IdListener idListener = new IdListener(); - _idComboBox.addActionListener(idListener); - - UpdateListener updateListener = new UpdateListener(); - _updateButton.addActionListener(updateListener); - - DeleteListener deleteListener = new DeleteListener(); - _deleteButton.addActionListener(deleteListener); - - CloseListener closeListener = new CloseListener(); - _closeButton.addActionListener(closeListener); - - _idComboBox.setSelectedIndex(0); - } - - private JPanel createDummyPanel() - { - JPanel dummyPanel = new JPanel(); - return dummyPanel; - } - - private void closeOfficeNotesDialog() - { - this.setVisible(false); - } - - private void showCurrentRowData(String id) - { - if(_selectedRowData != null) - { - _displayingSelectedRowData = true; - _topicField.setText(_selectedRowData.getTopic()); - _idComboBox.setSelectedItem(_selectedRowData.getId()); - _noteArea.setText(_selectedRowData.getNote()); - - String timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getPostingTime()); - _postingTimeField.setText(timeStr); - - if(! _selectedRowData.getDataValue(OfficeNotesColumns.UPDATE_TIME).equals(_missingRepresentation)) - { - timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getUpdateTime()); - _updateTimeField.setText(timeStr); - } - else - _updateTimeField.setText("yyyy-mm-dd hh:mm:ss"); - - if(! _selectedRowData.getDataValue(OfficeNotesColumns.DATA_TIME).equals(_missingRepresentation)) - { - timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getDataTime()); - _dataTimeField.setText(timeStr); - } - else - _dataTimeField.setText("yyyy-mm-dd hh:mm:ss"); - - if(!_selectedRowData.getDataValue(OfficeNotesColumns.EXPIRE_TIME).equals(_missingRepresentation)) - { - timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getExpireTime()); - _expireTimeField.setText(timeStr); - } - else - _expireTimeField.setText("yyyy-mm-dd hh:mm:ss"); - _displayingSelectedRowData = false; - } - else if(id == null) - { - String str=""; - _topicField.setText(str); - _idComboBox.setSelectedItem(_idComboBox.getSelectedItem().toString()); - _noteArea.setText(str); - _postingTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _updateTimeField.setText(_postingTimeField.getText()); - _dataTimeField.setText("yyyy-mm-dd hh:mm:ss"); - _expireTimeField.setText("yyyy-mm-dd hh:mm:ss"); - } - else // id is not null - { - _topicField.setText(_topicField.getText()); - _idComboBox.setSelectedItem(id); - _noteArea.setText(_noteArea.getText()); - _postingTimeField.setText(_postingTimeField.getText()); - _updateTimeField.setText(_updateTimeField.getText()); - _dataTimeField.setText(_dataTimeField.getText()); - _expireTimeField.setText(_expireTimeField.getText()); - } - } - - private OfficeNotesJTableRowData getMatchingRecordIfIdExistsInTable(String id) - { - OfficeNotesJTableRowData rowData = null; - for(int i=0; i < _allRowDataList.size(); i++) - { - OfficeNotesJTableRowData tempRec = (OfficeNotesJTableRowData) _allRowDataList.get(i); - if(tempRec.getId().equals(id)) - { - rowData = tempRec; - break; - } - } - return rowData; - } - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeOfficeNotesDialog(); - } - } - - private OfficeNotesRecord getOfficeNotesRecord() - { - OfficeNotesRecord record = new OfficeNotesRecord(); - if(!(_topicField.getInputVerifier().verify(_topicField))) - { - JOptionPane.showMessageDialog(null, "Topic length must be >=1 and <= 8","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setTopic(_topicField.getText()); - } - - if(!(_idComboBoxTextComponent.getInputVerifier().verify(_idComboBoxTextComponent))) - { - JOptionPane.showMessageDialog(null, "Id length must be >=1 and <= 8","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setId(_idComboBox.getSelectedItem().toString()); - } - - if(!(_dataTimeField.getInputVerifier().verify(_dataTimeField))) - { - JOptionPane.showMessageDialog(null, "Enter valid data time","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setDatatime(DbTimeHelper.getLongTimeFromDateTimeString(_dataTimeField.getText())); - } - if(!(_expireTimeField.getInputVerifier().verify(_expireTimeField))) - { - JOptionPane.showMessageDialog(null, "Enter valid expire time","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - long dataTime = DbTimeHelper.getLongTimeFromDateTimeString(_dataTimeField.getText()); - long expireTime = DbTimeHelper.getLongTimeFromDateTimeString(_expireTimeField.getText()); - if(dataTime > expireTime) - { - JOptionPane.showMessageDialog(null, "Expire Time should be Greater than Data Time","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setExpiretime(DbTimeHelper.getLongTimeFromDateTimeString(_expireTimeField.getText())); - _infoDialogShown = false; - } - } - record.setPostingtime(DbTimeHelper.getLongTimeFromDateTimeString(_postingTimeField.getText())); - record.setUpdatetime(DbTimeHelper.getLongTimeFromDateTimeString(_updateTimeField.getText())); - String note = _noteArea.getText(); - if(note.length() > 510) - note = note.substring(0, 510); - record.setNote(note); - return record; - } - - private class TextFieldInputVerifier extends InputVerifier - { - public boolean verify(JComponent component) - { - boolean returnValue = true; - - if(!_isUpdateOrDeleteToBeDone) - return returnValue; - - JTextField textField = (JTextField)component; - if(component == _topicField) - { - String topic= textField.getText(); - if(topic != null) - { - if(topic.length() == 0) - returnValue = false; - else if(topic.length() > 8) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _idComboBoxTextComponent) - { - String id= textField.getText(); - if(id != null) - { - if(id.length() == 0) - returnValue = false; - else if(id.length() > 8) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _dataTimeField) - { - String dataTime = textField.getText(); - if(dataTime != null) - { - if(_dataTimeField.getText().equals("yyyy-mm-dd hh:mm:ss")) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _expireTimeField) - { - String expireTime = textField.getText(); - if(expireTime != null) - { - if(_expireTimeField.getText().equals("yyyy-mm-dd hh:mm:ss")) - returnValue = false; - } - else - returnValue = false; - } - return returnValue; - } - } - - private void getCurrentDataFromDataMgr() - { - List dbInfoList = null; - String header = "OfficeNotesDialog.getCurrentDataFromDataMgr() "; - try - { - dbInfoList = _officeNotesDataMgr.readDataFromOfficeNotes(); - } - catch(Exception e) - { - _logger.log(header+ e); - } - _allRowDataList = dbInfoList; - _officeNotesTableManager.setChangedAllRowDataList(_allRowDataList); - } - - class IdListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _id = _idComboBox.getSelectedItem().toString(); - boolean isDefinedId = false; - for(int i=0; i < _definedIds.length; i++) - { - if(_definedIds[i].equals(_id)) - { - isDefinedId = true; - break; - } - } - if(isDefinedId) - { - String desc = (String)_lidDescDetailsMap.get(_id); - if(desc != null) - { - String splitStr[] = desc.split(";"); - _nameField.setText(splitStr[0]); - _countyField.setText(splitStr[2]); - _stateField.setText(splitStr[1]); - } - } - else - { - _nameField.setText(""); - _countyField.setText(""); - _stateField.setText(""); - } - - if(!_displayingSelectedRowData) - { - _selectedRowData = null; - showCurrentRowData(_id); - } - } - } - - class DeleteListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _isUpdateOrDeleteToBeDone = true; - String header = "OfficeNotesDialog.DeleteListener.actionPerformed(): "; - OfficeNotesRecord record = getOfficeNotesRecord(); - if(!_infoDialogShown) - { - _logger.log(header+" Delete record"+ record.toString()); - _officeNotesDataMgr.delete(record); - getCurrentDataFromDataMgr(); - _officeNotesTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(_idComboBox.getSelectedItem().toString()); - } - _isUpdateOrDeleteToBeDone = false; - - } - } - - class UpdateListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _isUpdateOrDeleteToBeDone = true; - String header = "OfficeNotesDialog.UpdateListener.actionPerformed(): "; - if(getMatchingRecordIfIdExistsInTable(_idComboBox.getSelectedItem().toString()) == null) - { - _postingTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _updateTimeField.setText(_postingTimeField.getText()); - } - else - { - _updateTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - } - OfficeNotesRecord record = getOfficeNotesRecord(); - if(!_infoDialogShown) - { - _logger.log(header+" Update record"+ record.toString()); - _officeNotesDataMgr.updateOrInsert(record); - getCurrentDataFromDataMgr(); - _officeNotesTableManager.refreshDisplay(); - int rowToHighLight = _officeNotesTableManager.getTheRowIndexToHighLightBasedOnValue(_idComboBox.getSelectedItem().toString()); - _officeNotesTableManager.selectRows(rowToHighLight, rowToHighLight); - } - _isUpdateOrDeleteToBeDone = false; - } - - } - - class OfficeNotesTableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - _selectedRowIndex = _officeNotesTableManager.getMousePointedRowIndex(p); - _selectedRowData = (OfficeNotesJTableRowData) _officeNotesTableManager.getSelectedRowData(_selectedRowIndex); - showCurrentRowData(null); - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesJTableRowData.java deleted file mode 100755 index 6ed756c2a4..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/officenotes/OfficeNotesJTableRowData.java +++ /dev/null @@ -1,112 +0,0 @@ -package ohd.hseb.officenotes; - -import ohd.hseb.ihfsdb.generated.OfficeNotesRecord; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class OfficeNotesJTableRowData extends AbstractJTableRowData -{ - private String _topic; - private String _id; - private long _dataTime; - private long _postingTime; - private long _updateTime; - private long _expireTime; - private String _note; - - public OfficeNotesJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getTopic() - { - return _topic; - } - public void setTopic(String topic) - { - _topic = topic; - } - public long getDataTime() - { - return _dataTime; - } - public void setDataTime(long dataTime) - { - _dataTime = dataTime; - } - public long getExpireTime() - { - return _expireTime; - } - public void setExpireTime(long expireTime) - { - _expireTime = expireTime; - } - public String getId() - { - return _id; - } - public void setId(String id) - { - _id = id; - } - public String getNote() - { - return _note; - } - public void setNote(String note) - { - _note = note; - } - public long getPostingTime() - { - return _postingTime; - } - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - public long getUpdateTime() - { - return _updateTime; - } - public void setUpdateTime(long time) - { - _updateTime = time; - } - - public void setOfficeNotesRecord(OfficeNotesRecord officeNotesRecord) - { - setTopic(officeNotesRecord.getTopic()); - setId(officeNotesRecord.getId()); - setDataTime(officeNotesRecord.getDatatime()); - setPostingTime(officeNotesRecord.getPostingtime()); - setUpdateTime(officeNotesRecord.getUpdatetime()); - setExpireTime(officeNotesRecord.getExpiretime()); - setNote(officeNotesRecord.getNote()); - } - - public void addAllCellsToMap() - { - addToCellMap(OfficeNotesColumns.TOPIC, CellType.STRING, getTopic() ); - addToCellMap(OfficeNotesColumns.ID, CellType.STRING, getId() ); - addToCellMap(OfficeNotesColumns.NOTE, CellType.STRING, getNote()); - addToCellMap(OfficeNotesColumns.DATA_TIME, CellType.DATE_TIME, getDataTime()); - addToCellMap(OfficeNotesColumns.UPDATE_TIME, CellType.DATE_TIME, getUpdateTime()); - addToCellMap(OfficeNotesColumns.POSTING_TIME, CellType.DATE_TIME, getPostingTime()); - addToCellMap(OfficeNotesColumns.EXPIRE_TIME, CellType.DATE_TIME, getExpireTime()); - } - - // ----------------------------------------------------------------------------------- - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation(), "MM/dd - HH:mm"); - addCell(cell); - - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupColumns.java deleted file mode 100755 index 29e46fb97d..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupColumns.java +++ /dev/null @@ -1,41 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class RiverMonGroupColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String GROUP_NAME = "Group Name"; - public static final String GROUP_ORDINAL = "Group Ordinal"; - public static final String HSA = "HSA"; - - /** - * Creates a list of rivermon group columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the rivermon group columns are added to it, - * if not the location info columns are added to the list that is passed as argument. - * The created new list is returned. - * @param riverMonGroupColumnDescriptorList - * @return - */ - public List getRiverMonGroupColumnsList(List riverMonGroupColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if( riverMonGroupColumnDescriptorList == null) - { - riverMonGroupColumnDescriptorList = new ArrayList(); - } - - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ID, true, 95, textAlignment)); - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_NAME, true, 335, textAlignment)); - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ORDINAL, true, 85, numberAlignment)); - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(HSA, true, 75, textAlignment)); - - return riverMonGroupColumnDescriptorList; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupDialog.java deleted file mode 100755 index 4e1241695a..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupDialog.java +++ /dev/null @@ -1,439 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.RiverMonGroupRecord; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.FrameCloseWindowListener; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RiverMonGroupDialog extends JDialog -{ - private List _riverMonGroupColumnDescriptorList = null; - private JTableManager _riverMonGroupTableManager = null; - private RiverMonLocGroupDataManager _riverMonLocGroupDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private int _selectedRowIndex; - private boolean _riverMonGroupTableChanged = false; - private String _defaultHsa = null; - - private JLabel _groupIdLabel; - private JTextField _groupIdField ; - private JLabel _groupNameLabel; - private JTextField _groupNameField ; - private JLabel _groupOrdinalLabel; - private JTextField _groupOrdinalField ; - private JLabel _hsaLabel; - private JTextField _hsaField; - private JButton _updateButton; - private JButton _deleteButton ; - private JButton _closeButton ; - - private boolean _infoDialogShown = false; - private SessionLogger _logger = null; - - private RiverMonGroupJTableRowData _selectedRowData; - private TextFieldInputVerifier _textFieldInputVerifier = new TextFieldInputVerifier(); - - public RiverMonGroupDialog(JFrame mainFrame, RiverMonLocGroupDataManager riverMonLocGroupDataMgr, SessionLogger logger, String defaultHsa) - { - super(mainFrame, true); - _logger = logger; - _defaultHsa = defaultHsa; - this.setTitle("RiverMonGroup"); - this.getContentPane().setLayout(new GridBagLayout()); - _riverMonLocGroupDataMgr = riverMonLocGroupDataMgr; - initialize(riverMonLocGroupDataMgr); - Dimension min = new Dimension(600,570); - Dimension max = new Dimension(700,570); - new WindowResizingManager(this, min, max); - this.pack(); - this.setLocation(25, 25); - } - - public boolean showRiverMonGroupDialog() - { - _riverMonGroupTableChanged = false; - _allRowDataList = _riverMonLocGroupDataMgr.readDataFromRiverMonGroup(); - _riverMonGroupTableManager.setChangedAllRowDataList(_allRowDataList); - _riverMonGroupTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(); - this.setVisible(true); - return _riverMonGroupTableChanged; - } - - private void initialize(RiverMonLocGroupDataManager riverMonLocGroupDataMgr) - { - _riverMonGroupColumnDescriptorList = new RiverMonGroupColumns().getRiverMonGroupColumnsList(_riverMonGroupColumnDescriptorList); - - _allRowDataList = riverMonLocGroupDataMgr.readDataFromRiverMonGroup(); - System.out.println("All row data list:"+ _allRowDataList.size()); - System.out.println("Column list:"+ _riverMonGroupColumnDescriptorList.size()); - - _riverMonGroupTableManager = new ComplexJTableManager(_riverMonGroupColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _riverMonGroupTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _riverMonGroupTableManager.setDisplayableColumns(columnsSelected, true, true); - _riverMonGroupTableManager.setPreferredSizeForJScrollPane(new Dimension(590, 300)); - _riverMonGroupTableManager.setVerifyInputWhenFocusTarget(false); - RiverMonitorGroupTableMouseListener tableMouseListener = new RiverMonitorGroupTableMouseListener(); - _riverMonGroupTableManager.addTableListener(tableMouseListener); - _tableScrollPane = _riverMonGroupTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(600,310)); - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - tablePanel.setMinimumSize(new Dimension(600,310)); - - _groupIdLabel = new JLabel("Group Id"); - _groupIdField = new JTextField(); - _groupIdField.setInputVerifier(_textFieldInputVerifier); - - _groupNameLabel = new JLabel("Group Name"); - _groupNameField = new JTextField(); - _groupNameField.setInputVerifier(_textFieldInputVerifier); - - _groupOrdinalLabel = new JLabel("Group Ordinal"); - _groupOrdinalField = new JTextField(); - _groupOrdinalField.setInputVerifier(_textFieldInputVerifier); - - _hsaLabel = new JLabel("HSA"); - _hsaField = new JTextField(); - _hsaField.setEditable(false); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(4,4)); - JPanel dummyPanel1 = createDummyPanel(); - infoPanel.add(dummyPanel1); - infoPanel.add(_groupIdLabel); - infoPanel.add(_groupIdField); - JPanel dummyPanel2 = createDummyPanel(); - infoPanel.add(dummyPanel2); - - JPanel dummyPanel3 = createDummyPanel(); - infoPanel.add(dummyPanel3); - infoPanel.add(_groupNameLabel); - infoPanel.add(_groupNameField); - JPanel dummyPanel4 = createDummyPanel(); - infoPanel.add(dummyPanel4); - - JPanel dummyPanel5 = createDummyPanel(); - infoPanel.add(dummyPanel5); - infoPanel.add(_groupOrdinalLabel); - infoPanel.add(_groupOrdinalField); - JPanel dummyPanel6 = createDummyPanel(); - infoPanel.add(dummyPanel6); - - JPanel dummyPanel7 = createDummyPanel(); - infoPanel.add(dummyPanel7); - infoPanel.add(_hsaLabel); - infoPanel.add(_hsaField); - JPanel dummyPanel8 = createDummyPanel(); - infoPanel.add(dummyPanel8); - - JPanel actionPanel = new JPanel(); - actionPanel = new JPanel(); - _updateButton = new JButton("Save"); - _deleteButton = new JButton("Delete"); - _closeButton = new JButton("Close"); - _closeButton.setVerifyInputWhenFocusTarget(false); - actionPanel.add(_updateButton); - actionPanel.add(_deleteButton); - actionPanel.add(_closeButton); - - JPanel editPanel = new JPanel(); - editPanel.setLayout(new GridLayout(1,2)); - editPanel.setBorder(BorderFactory.createTitledBorder("Details")); - - editPanel.add(infoPanel); - - Container contentPane = this.getContentPane(); - ComponentHelper.addFrameComponent(contentPane, tablePanel, 0, 0,1,1,1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, editPanel, 0, 1,1,1, 1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, actionPanel, 0, 2,1,1, 1, 1, 0); - - UpdateListener updateListener = new UpdateListener(); - _updateButton.addActionListener(updateListener); - - DeleteListener deleteListener = new DeleteListener(); - _deleteButton.addActionListener(deleteListener); - - CloseListener closeListener = new CloseListener(); - _closeButton.addActionListener(closeListener); - - } - - private JPanel createDummyPanel() - { - JPanel dummyPanel = new JPanel(); - return dummyPanel; - } - - private void closeRiverMonGroupDialog() - { - this.setVisible(false); - } - - private void showCurrentRowData() - { - if(_selectedRowData != null) - { - _groupIdField.setText(_selectedRowData.getGroupId()); - _groupNameField.setText(_selectedRowData.getGroupName()); - _groupOrdinalField.setText(new Integer(_selectedRowData.getGroupOrdinal()).toString()); - _hsaField.setText(_selectedRowData.getHsa()); - _selectedRowData = null; - } - else - { - _groupIdField.setText(""); - _groupNameField.setText(""); - _groupOrdinalField.setText(""); - _hsaField.setText(""); - } - } - - private RiverMonGroupRecord getRiverMonGroupRecord() - { - RiverMonGroupRecord record = new RiverMonGroupRecord(); - if(!(_groupIdField.getInputVerifier().verify(_groupIdField))) - { - JOptionPane.showMessageDialog(null, "Group Id length must be >=1 and <= 8","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setGroup_id(_groupIdField.getText().toUpperCase()); - } - if(!(_groupNameField.getInputVerifier().verify(_groupNameField))) - { - JOptionPane.showMessageDialog(null, "Group Name length must be >=1 and <= 32","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setGroup_name(_groupNameField.getText()); - } - if(!(_groupOrdinalField.getInputVerifier().verify(_groupOrdinalField))) - { - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setOrdinal(Integer.parseInt(_groupOrdinalField.getText())); - } - if(_hsaField.getText().length() > 0) - { - record.setHsa(_hsaField.getText().toUpperCase()); - } - else - { - _hsaField.setText(_defaultHsa); - record.setHsa(_defaultHsa); - } - - return record; - } - - private void getCurrentDataFromDataMgr() - { - List dbInfoList = null; - String header = "RiverMonGroupDialog.getCurrentDataFromDataMgr() "; - try - { - dbInfoList = _riverMonLocGroupDataMgr.readDataFromRiverMonGroup(); - } - catch(Exception e) - { - _logger.log(header+ e); - } - _allRowDataList = dbInfoList; - _riverMonGroupTableManager.setChangedAllRowDataList(_allRowDataList); - } - - private class TextFieldInputVerifier extends InputVerifier - { - public boolean verify(JComponent component) - { - boolean returnValue = true; - JTextField textField = (JTextField)component; - if(component == _groupIdField) - { - String id= textField.getText(); - if(id != null) - { - if(id.length() == 0) - returnValue = false; - else if(id.length() > 8) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _groupNameField) - { - String name = textField.getText(); - if(name != null) - { - if(name.length() == 0) - returnValue = false; - else if(name.length() > 32) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _groupOrdinalField) - { - try - { - Integer.parseInt(textField.getText()); - returnValue = true; - } - catch (NumberFormatException e) - { - returnValue = false; - } - } - if(!returnValue) - { - if(component ==_groupIdField) - JOptionPane.showMessageDialog(null, "Group Id length must be >=1 and <= 8","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - else if(component == _groupNameField) - JOptionPane.showMessageDialog(null, "Group Name length must be >=1 and <= 32","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - else if(component == _groupOrdinalField) - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - } - return returnValue; - } - } - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeRiverMonGroupDialog(); - } - } - - private class DeleteListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonitorGroupDialog.DeleteListener.actionPerformed(): "; - RiverMonGroupRecord record = getRiverMonGroupRecord(); - if(!_infoDialogShown) - { - _logger.log(header+" Delete record"+ record.toString()); - _riverMonLocGroupDataMgr.delete(record); - getCurrentDataFromDataMgr(); - _riverMonGroupTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(); - _riverMonGroupTableChanged = true; - } - } - } - - private class UpdateListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonGroupDialog.UpdateListener.actionPerformed(): "; - RiverMonGroupRecord record = getRiverMonGroupRecord(); - boolean recordExists = _riverMonLocGroupDataMgr.checkIfRecordExists(record); - if(!recordExists) - { - record.setHsa(_defaultHsa); - _hsaField.setText(_defaultHsa); - } - if(!_infoDialogShown) - { - _logger.log(header+" Update record"+ record.toString()); - _riverMonLocGroupDataMgr.updateOrInsert(record); - getCurrentDataFromDataMgr(); - _riverMonGroupTableManager.refreshDisplay(); - int rowToHighLight = _riverMonGroupTableManager.getTheRowIndexToHighLightBasedOnValue(_groupIdField.getText()); - _riverMonGroupTableManager.selectRows(rowToHighLight, rowToHighLight); - _riverMonGroupTableChanged = true; - } - } - } - - private class RiverMonitorGroupTableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - _selectedRowIndex = _riverMonGroupTableManager.getMousePointedRowIndex(p); - _selectedRowData = (RiverMonGroupJTableRowData) _riverMonGroupTableManager.getSelectedRowData(_selectedRowIndex); - showCurrentRowData(); - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - - public static void main(String[] args) - { - /* - * This main is for testing purposes - */ - - String jdbcUrl = args[0]; - String baseLogFilePath = args[1]; - String defaultHsa = args[2]; - - System.out.println("jdbcUrl = " + jdbcUrl ); - - Database database = new Database(jdbcUrl); - - String messageId = "M1"; - SessionLogger logger = new SessionLogger("RiverMonGroup", baseLogFilePath, true, true, messageId); - - RiverMonLocGroupDataManager dataMgr = new RiverMonLocGroupDataManager(database, logger, "", defaultHsa ); - - JFrame frame = new JFrame(); - - FrameCloseWindowListener.addFrameCloseWindowListener(frame); - - RiverMonGroupDialog dialog = new RiverMonGroupDialog(frame, dataMgr, logger, defaultHsa); - dialog.setVisible(true); - frame.setVisible(true); - - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupJTableRowData.java deleted file mode 100755 index e190c9c3dc..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupJTableRowData.java +++ /dev/null @@ -1,90 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class RiverMonGroupJTableRowData extends AbstractJTableRowData -{ - private String _groupId; - private String _groupName; - private int _groupOrdinal; - private String _hsa; - - public RiverMonGroupJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - _groupId = groupId; - } - - public String getGroupName() - { - return _groupName; - } - - public void setGroupName(String groupName) - { - _groupName = groupName; - } - - public String getHsa() - { - return _hsa; - } - - public void setHsa(String hsa) - { - _hsa = hsa; - } - - public int getGroupOrdinal() - { - return _groupOrdinal; - } - - public void setGroupOrdinal(int groupOrdinal) - { - _groupOrdinal = groupOrdinal; - } - - public void addAllCellsToMap() - { - addToCellMap(RiverMonGroupColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(RiverMonGroupColumns.GROUP_NAME, CellType.STRING, getGroupName() ); - addToCellMap(RiverMonGroupColumns.GROUP_ORDINAL, CellType.INTEGER, getGroupOrdinal()); - addToCellMap(RiverMonGroupColumns.HSA, CellType.STRING, getHsa() ); - } - - // ----------------------------------------------------------------------------------- - - // ----------------------------------------------------------------------------------- - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation()); - addCell(cell); - - } - - /* private void addToCellMap(String columnName, CellType cellType, - Object value) - { - int decimalPointsForDisplay = 2; - MonitorCell cell = new MonitorCell (columnName, cellType, - value, ThreatLevel.NO_THREAT, - _missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - }*/ - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocGroupDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocGroupDataManager.java deleted file mode 100755 index b3730cd9a8..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocGroupDataManager.java +++ /dev/null @@ -1,1354 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.LocRiverMonRecord; -import ohd.hseb.ihfsdb.generated.LocRiverMonView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RiverMonGroupRecord; -import ohd.hseb.ihfsdb.generated.RiverMonGroupTable; -import ohd.hseb.ihfsdb.generated.RiverMonLocationRecord; -import ohd.hseb.ihfsdb.generated.RiverMonLocationTable; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.SessionLogger; - -public class RiverMonLocGroupDataManager -{ - private Database _db ; - private SessionLogger _logger; - private String _missingRepresentation; - - private Map _lidToRiverMonLocationMap; - private Map> _groupIdToLocationIdListMap = new HashMap>(); - private List _locationInfoList; - private String _defaultHsa; - private Map _locationIdToOrdinalMap; - - private Map _groupIdToRiverMonGroupMap = null; - private List _groupInfoList = null; - - private Map _groupHsaMap = null; - - private Set _hsaInfoSet = null; - private Map _locationHsaMap = null; - - private List _locationsUnderDefaultGroupList = null; - private int _locationOrdinalForDefaultLocations = 1; - - private final String _defaultGroupId = "DEFAULT"; - - public RiverMonLocGroupDataManager(Database dbHandler, SessionLogger logger, - String missingRepresentation, String defaultHsa) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - _defaultHsa = defaultHsa; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","RiverMonLocation Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void initializeRiverMonTableData() - { - String header = "RiverMonLocGroupDataManager.initializeRiverMonTableData()"; - - initLocationHsaMap(); - initRiverMonGroupMap(); - initRiverMonLocationMap(); - initGroupHsaMap(); - - //any undefined default hsa-based groups will be created here - //any defined hsa-based groups groups will be overwritten in the following for loop - initAllDefaultGroupsToMap(); - - updateRiverMonitorGroupWithAppropriateHsa(); - } - - public List createStringArrayListOfFilterItems( List locationIdList) - { - String header = "RiverMonLocGroupDataManager.createStringArrayListOfFilterItems(): "; - List listOfStringArray = new ArrayList(); - - String rootItem = "HSA"; - String hsaArray[] = getAllHsa(); - String[] nodePathStringArray; - - buildGroupIdToLocationIdListMap(locationIdList); - LocationOrdinalComparator locationComparator = new LocationOrdinalComparator(); - - if(hsaArray != null && hsaArray.length > 0) - { - String hsa = null; - for(int i=0; i < hsaArray.length; i++) - { - hsa = hsaArray[i]; - String groupIdArray[] = getGroupsForHsa(hsaArray[i]); - if(groupIdArray != null && groupIdArray.length > 0) - { - String groupName = null; - for(int j=0; j < groupIdArray.length; j++) - { - groupName = getGroupName(groupIdArray[j]); - String locationId[] = getAllLocationsForGroup(groupIdArray[j], locationIdList, locationComparator); - if(locationId != null && locationId.length > 0) - { - for(int k=0; k < locationId.length; k++) - { - nodePathStringArray = new String[4]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - nodePathStringArray[2] = groupName; - nodePathStringArray[3] = locationId[k]; - listOfStringArray.add(nodePathStringArray); - } - } - else //it is a group - { - nodePathStringArray = new String[3]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - nodePathStringArray[2] = groupName; - listOfStringArray.add(nodePathStringArray); - } - } - } - else //it is an hsa - { - nodePathStringArray = new String[2]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - listOfStringArray.add(nodePathStringArray); - } - } - } - else //it is the root - { - nodePathStringArray = new String[1]; - nodePathStringArray[0] = rootItem; - listOfStringArray.add(nodePathStringArray); - } - - System.out.println(header + "listOfStringArray.size() = " + listOfStringArray.size()); - - return listOfStringArray; - } - - - private String getDefaultHsa() - { - return _defaultHsa; - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public int delete(RiverMonLocationRecord rec) - { - int ret = -1; - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - try - { - ret = riverMonLocationTable.delete(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public int updateOrInsert(RiverMonLocationRecord rec) - { - int ret = -1; - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - try - { - ret = riverMonLocationTable.insertOrUpdate(rec); - updateOrdinalValuesInRiverMonLocation(rec.getLid(), rec.getGroup_id(), rec.getOrdinal()); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public void updateOrdinalValuesInRiverMonLocation(String locationId, String groupId, int locationOrdinal) - { - - RiverMonLocationTable table = new RiverMonLocationTable(_db); - List recordList = null; - - String where = "WHERE group_id = '" + groupId + "' ORDER BY ordinal ASC, lid ASC"; - - try - { - recordList = table.select(where); - - int ordinalValue = locationOrdinal + 1; - for (RiverMonLocationRecord oldRecord : recordList) - { - //if the location is not the same as that passed in as argument - if (! oldRecord.getLid().equalsIgnoreCase(locationId)) - { - //if the ordinal is equal or higher than that passed in - if (oldRecord.getOrdinal() >= locationOrdinal) - { - //alter and insert the rest of the records. - RiverMonLocationRecord newRecord = new RiverMonLocationRecord(oldRecord); - - newRecord.setOrdinal(ordinalValue); - - table.update(oldRecord, newRecord); - - ordinalValue++; - } - - } - - } - - } - catch (SQLException e) - { - e.printStackTrace(); - } - - } - - /** - * Read loc rivermon view location and precip location ( lids which report PC / PP data and have - * ingest filter on) - * @return - */ - public String[] getAllLid() - { - String header = "RiverMonLocationDataManager.getAllLid(): "; - List lidList = null; - String lid[] = null; - List locRiverMonRecordList = null; - LocRiverMonView rivermonView = new LocRiverMonView(_db); - - LocationTable locationTable = new LocationTable(_db); - String whereClause = null; - - try - { - whereClause = " order by lid "; - locRiverMonRecordList = rivermonView.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(locRiverMonRecordList != null) - { - lidList = new ArrayList(); - - for(LocRiverMonRecord locRiverMonRecord: locRiverMonRecordList) - { - lidList.add(locRiverMonRecord.getLid()); - } - - whereClause = "where lid in (select distinct(lid) from ingestfilter where pe in('PC', 'PP') and ingest='T')"; - List locationRecordList = locationTable.select(whereClause); - if(locationRecordList != null) - { - for(LocationRecord locationRecord: locationRecordList) - { - lidList.add(locationRecord.getLid()); - } - } - - if(! lidList.isEmpty() ) - { - lid = new String[lidList.size()]; - int i=0; - for(String str: lidList) - { - lid[i++] = str; - } - } - else - { - _logger.log(header+"read location table for precip lids --- lid list is null"); - } - } - else - { - _logger.log(header+"read loc rivermon --- lid list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return lid; - } - - private void initRiverMonLocationMap() - { - List riverMonLocationInfoList = null; - - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - String whereClause = null; - String header = "RiverMonitorLocGroupDataManager.initRiverMonLocationMap(): "; - - try - { - whereClause = "where group_id not like 'DEFAULT' order by ordinal"; - riverMonLocationInfoList = riverMonLocationTable.select(whereClause); - _logger.log(header + " Where Clause:" + whereClause); - if (riverMonLocationInfoList == null) - { - _logger.log(header + " RiverMonlocation list is null"); - } - else - { - _lidToRiverMonLocationMap = new HashMap(); - for (int i = 0; i < riverMonLocationInfoList.size(); i++) - { - RiverMonLocationRecord record = (RiverMonLocationRecord) riverMonLocationInfoList.get(i); - _lidToRiverMonLocationMap.put(record.getLid(), record); - } - } - } - catch (SQLException e) - { - _logger.log("In " + header); - logSQLException(e); - } - - _locationInfoList = riverMonLocationInfoList; - } - - public String[] getAllGroup() - { - String group[] = null; - List groupList = null; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - RiverMonGroupRecord riverMonGroupRecord = null; - String header = "RiverMonLocationDataManager.getAllGroup(): "; - String whereClause = null; - - try - { - whereClause = " order by group_id "; - groupList = riverMonGroupTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(groupList != null) - { - group = new String[groupList.size()]; - for(int i=0; i < groupList.size(); i++) - { - riverMonGroupRecord = (RiverMonGroupRecord) groupList.get(i); - group[i] = riverMonGroupRecord.getGroup_id(); - } - } - else - { - _logger.log(header+" Group list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return group; - } - - public boolean checkIfRiverMonLocationTableHasRecords() - { - boolean result = false; - List riverMonLocationInfoList = null; - - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - String whereClause = null; - String header = "RiverMonLocationDataManager.checkIfRiverMonLocationTableHasRecords()"; - try - { - whereClause = ""; - riverMonLocationInfoList = riverMonLocationTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonLocationInfoList != null) - { - if(riverMonLocationInfoList.size() > 0) - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - - public List readDataFromRiverMonLocation() - { - List riverMonLocationInfoList = null; - List dataList = null; - - _locationIdToOrdinalMap = new HashMap(); - - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - RiverMonLocationRecord riverMonLocationRecord = null; - String whereClause = null; - String header = "RiverMonLocationDataManager.readDataFromRiverMonLocation(): "; - - try - { - whereClause = "order by lid"; - riverMonLocationInfoList = riverMonLocationTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonLocationInfoList != null) - { - dataList = new ArrayList(); - - for(int i=0;i < riverMonLocationInfoList.size(); i++) - { - riverMonLocationRecord = (RiverMonLocationRecord) riverMonLocationInfoList.get(i); - RiverMonLocationJTableRowData rowData = new RiverMonLocationJTableRowData(_missingRepresentation); - - _locationIdToOrdinalMap.put(riverMonLocationRecord.getLid(), riverMonLocationRecord.getOrdinal()); - - rowData.setLid(riverMonLocationRecord.getLid()); - rowData.setGroupId(riverMonLocationRecord.getGroup_id()); - rowData.setLocationOrdinal(riverMonLocationRecord.getOrdinal()); - - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" RiverMonLocation list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - private class LocationOrdinalComparator implements Comparator - { - public LocationOrdinalComparator() - { - if(_locationIdToOrdinalMap == null) - { - readDataFromRiverMonLocation(); - } - } - - public int compare(Object obj1, Object obj2) - { - String lid1, lid2; - lid1 = (String) obj1; - lid2 = (String) obj2; - - Integer ordinal1 = (Integer) _locationIdToOrdinalMap.get(lid1); - Integer ordinal2 = (Integer) _locationIdToOrdinalMap.get(lid2); - - int ret; - - if(ordinal1 == null && ordinal2 == null) - { - ret = lid1.compareTo(lid2); - } - else if (ordinal1 == null) - { - return -1; // ordinal2 is greater - } - else if (ordinal2 == null) - { - return 1; // ordinal1 is greater - } - else // both ordinals are not null - { - return ordinal1.compareTo(ordinal2); - } - - return ret; - } - - } - - public int delete(RiverMonGroupRecord rec) - { - int ret = -1; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - try - { - ret = riverMonGroupTable.delete(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public int updateOrInsert(RiverMonGroupRecord rec) - { - int ret = -1; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - try - { - ret = riverMonGroupTable.insertOrUpdate(rec); - updateOrdinalValuesInRiverMonGroup(rec.getGroup_id(), rec.getHsa(), rec.getOrdinal()); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public void updateOrdinalValuesInRiverMonGroup(String groupId, String hsa, int groupOrdinal) - { - - RiverMonGroupTable table = new RiverMonGroupTable(_db); - List recordList = null; - - String where = "WHERE hsa = '" + hsa + "' ORDER BY ordinal ASC, group_id ASC"; - - try - { - recordList = table.select(where); - - int ordinalValue = groupOrdinal + 1; - for (RiverMonGroupRecord oldRecord : recordList) - { - //if the location is not the same as that passed in as argument - if (! oldRecord.getGroup_id().equalsIgnoreCase(groupId)) - { - //if the ordinal is equal or higher than that passed in - if (oldRecord.getOrdinal() >= groupOrdinal) - { - //alter and insert the rest of the records. - RiverMonGroupRecord newRecord = new RiverMonGroupRecord(oldRecord); - - newRecord.setOrdinal(ordinalValue); - - table.update(oldRecord, newRecord); - - ordinalValue++; - } - - } - - } - - } - catch (SQLException e) - { - e.printStackTrace(); - } - - } - - public boolean checkIfRecordExists(RiverMonGroupRecord record) - { - boolean exists = false; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - String groupId = record.getGroup_id(); - String whereClause = "where group_id="+groupId ; - List recordList = null; - try - { - recordList = riverMonGroupTable.select(whereClause); - } - catch(SQLException e) - { - logSQLException(e); - } - - if(recordList != null) - { - if (recordList.size() > 0) - { - exists = true; - } - } - - return exists; - } - - public boolean checkIfRiverMonGroupTableHasRecords() - { - boolean result = false; - List riverMonGroupInfoList = null; - - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - String whereClause = null; - String header = "RiverMonGroupDataManager.checkIfRiverMonGroupTableHasRecords()"; - try - { - whereClause = ""; - riverMonGroupInfoList = riverMonGroupTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonGroupInfoList != null) - { - if(riverMonGroupInfoList.size() > 0) - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - - public List readDataFromRiverMonGroup() - { - List riverMonGroupInfoList = null; - List dataList = null; - - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - RiverMonGroupRecord riverMonGroupRecord = null; - String whereClause = null; - String header = "RiverMonGroupDataManager.readDataFromRiverMonGroup(): "; - - try - { - whereClause = "order by group_id"; - riverMonGroupInfoList = riverMonGroupTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonGroupInfoList != null) - { - dataList = new ArrayList(); - - for(int i=0;i < riverMonGroupInfoList.size(); i++) - { - riverMonGroupRecord = (RiverMonGroupRecord) riverMonGroupInfoList.get(i); - RiverMonGroupJTableRowData rowData = new RiverMonGroupJTableRowData(_missingRepresentation); - - rowData.setGroupId(riverMonGroupRecord.getGroup_id()); - rowData.setGroupName(riverMonGroupRecord.getGroup_name()); - rowData.setGroupOrdinal(riverMonGroupRecord.getOrdinal()); - rowData.setHsa(riverMonGroupRecord.getHsa()); - - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" RiverMonGroup list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - private void initRiverMonGroupMap() - { - List riverMonGroupInfoList = null; - - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - String whereClause = null; - String header = "RiverMonLocGroupDataManager.initRiverMonGroupMap(): "; - - try - { - whereClause = "order by ordinal"; - riverMonGroupInfoList = riverMonGroupTable.select(whereClause); - - _logger.log(header + " Where Clause:" + whereClause); - if (riverMonGroupInfoList == null) - { - _logger.log(header + " RiverMonGroup list is null"); - } - else - { - _groupIdToRiverMonGroupMap = new HashMap(); - - for (int i = 0; i < riverMonGroupInfoList.size(); i++) - { - RiverMonGroupRecord record = (RiverMonGroupRecord) riverMonGroupInfoList.get(i); - _groupIdToRiverMonGroupMap.put(record.getGroup_id(), record); - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - - _groupInfoList = riverMonGroupInfoList; - } - - - public List getAllHsaCustom() - { - //new Chip - List fullHsaList = new ArrayList(_locationHsaMap.values()); - - Set hsaSet = new HashSet(); - - for (String hsa : fullHsaList) - { - hsaSet.add(hsa); - } - - List hsaList = new ArrayList(hsaSet); - - - return hsaList; - - } - - - private void initAllDefaultGroupsToMap() - { - - Map groupIdToGroupMap = _groupIdToRiverMonGroupMap; - Map groupToHsaMap = _groupHsaMap; - - - //new Chip - String header = "RiverMonLocGroupDataManager.initAllDefaultGroupsToMap(): "; - List hsaList = getAllHsaCustom(); - - for (String hsa : hsaList) - { - String groupId = "DEF_" + hsa; - String groupName = hsa + " DEFAULT GROUP"; - - // System.out.println(header + " groupId = " + groupId + " groupName = " + groupName); - - RiverMonGroupRecord group = new RiverMonGroupRecord(); - group.setGroup_id(groupId); - group.setGroup_name(groupName); - group.setOrdinal(0); - - _groupIdToRiverMonGroupMap.put(groupId, group); - _groupHsaMap.put(groupId, hsa); - _groupInfoList.add(group); - } - } - - - private void initGroupHsaMap() - { - Set hsaInfoSet = new HashSet(); - Map groupHsaMap = null; - if (_groupInfoList != null) - groupHsaMap = new HashMap(); - - if (getDefaultHsa() != null) - hsaInfoSet.add(getDefaultHsa()); - else - _logger.log("RiverMonitorLocGroupDataManager.initGroupHsaMap() : Admin HSA is null"); - - - - for (int i = 0; i < _groupInfoList.size(); i++) - { - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(i); - String groupId = riverMonGroupRecord.getGroup_id(); - if (! (groupId.equals(_defaultGroupId))) - { - String lids[] = getLocationsForGroup(groupId); - String hsa = null; - if (lids != null) - { - if (lids.length > 0) - { - //the default hsa for a group is defined by the HSA of the first location in that group - hsa = _locationHsaMap.get(lids[0]).toString(); - } - else - { - hsa = getDefaultHsa(); - } - } - else - { - hsa = getDefaultHsa(); - } - // System.out.println("For GroupId :"+groupId+" HSA Old:"+ - // riverMonGroupRecord.getHsa() +" New:"+hsa); - groupHsaMap.put(groupId, hsa); - hsaInfoSet.add(hsa); - } - else - { - String hsa = getDefaultHsa(); - // System.out.println("For GroupId :"+groupId+" HSA Old:"+ - // riverMonGroupRecord.getHsa() +" New:"+hsa); - groupHsaMap.put(groupId, hsa); - hsaInfoSet.add(hsa); - } - } - - //check if groupHsaMap has an entry for DEFAULT group - if not add one for DEFAULT group - if(groupHsaMap != null) - { - if(groupHsaMap.get(_defaultGroupId) == null) - { - // System.out.println("For GroupId :"+_defaultGroupId+" HSA "+getDefaultHsa()); - groupHsaMap.put(_defaultGroupId, getDefaultHsa()); - } - } - - _groupHsaMap = groupHsaMap; - _hsaInfoSet = hsaInfoSet; - } - - // -------------------------------------------------------------------------------------- - - public String[] getAllLocationsForGroup(String groupId, List locationIdList, LocationOrdinalComparator locationComparator) - { - String [] returnArray = null; - - /* if (_groupIdToLocationIdListMap.size() == 0) - { - buildGroupIdToLocationIdListMap(locationIdList); - locationComparator = new LocationOrdinalComparator(); - } - */ - List listOfLocationsInGroup = _groupIdToLocationIdListMap.get(groupId); - - if (listOfLocationsInGroup != null) - { - - Collections.sort(listOfLocationsInGroup, locationComparator); - //convert to String array - returnArray = new String[listOfLocationsInGroup.size()]; - int i = 0; - for (String locationId : listOfLocationsInGroup) - { - returnArray[i] = locationId; - i++; - } - } - - return returnArray; - } - - - // ------------------------------------------------------------------------------- - public void buildGroupIdToLocationIdListMap(List locationIdList) - { - - _groupIdToLocationIdListMap.clear(); - - for (String locationId : locationIdList ) - { - String groupId = getGroupId(locationId); - - List groupLocationIdList = _groupIdToLocationIdListMap.get(groupId); - if (groupLocationIdList == null) - { - groupLocationIdList = new ArrayList(); - _groupIdToLocationIdListMap.put(groupId, groupLocationIdList); - } - - groupLocationIdList.add(locationId); - - } - return; - } - - // ------------------------------------------------------------------------------- - public String[] getLocationsForGroup(String groupId) - { - String returnArray[] = null; - if (_lidToRiverMonLocationMap == null) - initRiverMonLocationMap(); - List locationList = new ArrayList(); - if(groupId.compareTo(_defaultGroupId) == 0) - { - returnArray = getLocationsUnderDefaultGroup(); - } - else - { - for (int i = 0; i < _locationInfoList.size(); i++) - { - RiverMonLocationRecord riverMonLocationRecord = (RiverMonLocationRecord) _locationInfoList.get(i); - String tempGroupId = riverMonLocationRecord.getGroup_id(); - if (tempGroupId.compareTo(groupId) == 0) - locationList.add(riverMonLocationRecord.getLid()); - } - if (locationList != null) - { - returnArray = new String[locationList.size()]; - for (int i = 0; i < locationList.size(); i++) - { - returnArray[i] = locationList.get(i).toString(); - } - } - } - return returnArray; - } - - protected String[] getLocationsUnderDefaultGroup() - { - String[] returnArray = null; - if(_locationsUnderDefaultGroupList != null) - { - returnArray = new String[_locationsUnderDefaultGroupList.size()]; - for (int i = 0; i < returnArray.length; i++) - returnArray[i] = (String) _locationsUnderDefaultGroupList.get(i); - } - return returnArray; - - } - - protected void addThisLocationToDefaultGroupList(String lid) - { - boolean isNewLocation = true; - if(_locationsUnderDefaultGroupList == null) - { - _locationsUnderDefaultGroupList = new ArrayList (); - } - else - { - for(String str: _locationsUnderDefaultGroupList) - { - if(str.compareTo(lid) == 0) - { - isNewLocation = false; - break; - } - } - } - - if(isNewLocation) - _locationsUnderDefaultGroupList.add(lid); - } - - - public void initLocationHsaMap() - { - Map locationHsaMap = null; - String header = "LocationInfoDataManager.readLocationHsaMap(): "; - LocationTable locationTable = new LocationTable(_db); - String whereClause = "order by lid"; - List locationList = null; - try - { - locationList = locationTable.select(whereClause); - if (locationList != null) - { - if (locationList.size() != 0) - { - locationHsaMap = new HashMap(); - for (int i = 0; i < locationList.size(); i++) - { - LocationRecord record = (LocationRecord) locationList.get(i); - String lid = record.getLid(); - String hsa = record.getHsa(); - locationHsaMap.put(lid, hsa); - } - } - else - { - _logger.log(header + "No Records found in LocationTable ..."); - } - } - else - { - _logger.log(header + "No Records found in LocationTable ..."); - } - } - catch (SQLException e) - { - logSQLException(e); - } - _locationHsaMap = locationHsaMap; - } - - - //------------------------------------------------------------------------------------ - - public void updateRiverMonitorGroupWithAppropriateHsa() - { - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - List riverMonGroupList = null; - String whereClause = ""; - CodeTimer timer = new CodeTimer(); - try - { - timer.start(); - riverMonGroupList = riverMonGroupTable.select(whereClause); - if (riverMonGroupList != null) - { - if (riverMonGroupList.size() > 0) - { - for (int i = 0; i < riverMonGroupList.size(); i++) - { - RiverMonGroupRecord oldRiverMonGroupRecord = (RiverMonGroupRecord) riverMonGroupList.get(i); - RiverMonGroupRecord newRiverMonGroupRecord = new RiverMonGroupRecord(); - newRiverMonGroupRecord.setGroup_id(oldRiverMonGroupRecord.getGroup_id()); - String hsa = (String) _groupHsaMap.get(oldRiverMonGroupRecord.getGroup_id()); - if(hsa != null) - newRiverMonGroupRecord.setHsa(hsa); - else - { - System.out.println("hsa is null for:"+ oldRiverMonGroupRecord.getGroup_id()); - } - newRiverMonGroupRecord.setOrdinal(oldRiverMonGroupRecord.getOrdinal()); - newRiverMonGroupRecord.setGroup_name(oldRiverMonGroupRecord.getGroup_name()); - riverMonGroupTable.update(oldRiverMonGroupRecord, newRiverMonGroupRecord); - } - } - } - timer.stop("Time elapsed in updating rivermongrouptable for hsa:"); - } - catch (SQLException e) - { - _logger.log("In " + " RiverMonitorLocGroupDataManager.updateRiverMonitorGroupWithAppropriateHsa()"); - logSQLException(e); - } - } - - public String[] getAllHsa() - { - String hsa[] = new String[_hsaInfoSet.size()]; // Stores the final hsa - // array in the - // alphabetical order, - // with default hsa as - // the first item - String tempHsaArray[] = new String[_hsaInfoSet.size() - 1]; - int i = 0; - Iterator it = _hsaInfoSet.iterator(); - - while (it.hasNext() && i < _hsaInfoSet.size()) - { - String tempHsa = it.next().toString(); - - if (tempHsa.equals(getDefaultHsa())) // if default hsa found then - // skip - { - continue; - } - else - tempHsaArray[i++] = tempHsa; - } - Arrays.sort(tempHsaArray); // Alphabetize the array - - // Assign default hsa to be the first - so it will be displayed as first - // in the tree, and the rest will be in alphabetical order - hsa[0] = getDefaultHsa(); - System.arraycopy(tempHsaArray, 0, hsa, 1, tempHsaArray.length); - - return hsa; - } - - private String[] getGroupsForHsa(String hsa) - { - String returnArray[] = null; - List groupList = new ArrayList(); - for (int i = 0; i < _groupInfoList.size(); i++) - { - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(i); - String groupId = riverMonGroupRecord.getGroup_id(); - String groupHsa = _groupHsaMap.get(groupId).toString(); - if (hsa.equals(groupHsa)) - { - groupList.add(groupId); - } - } - if (groupList != null) - { - returnArray = new String[groupList.size()]; - for (int i = 0; i < groupList.size(); i++) - { - returnArray[i] = groupList.get(i).toString(); - } - } - - return returnArray; - } - - - public String getGroupName(String groupId) - { - String groupName = null; - if (_groupIdToRiverMonGroupMap == null) - { - initRiverMonGroupMap(); - } - - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - try - { - groupName = riverMonGroupRecord.getGroup_name(); - } - catch (NullPointerException e) - { - System.out.println("groupId = " + groupId); - System.exit(1); - } - return groupName; - } - - public String getGroupId(String lid) - { - String groupId = null; - RiverMonLocationRecord riverMonlocationRecord = null; - - if (_lidToRiverMonLocationMap != null) - { - - - riverMonlocationRecord = (RiverMonLocationRecord) _lidToRiverMonLocationMap.get(lid); - - // pick the group for the location - if (riverMonlocationRecord != null) - { - groupId = riverMonlocationRecord.getGroup_id(); - } - else // (riverMonlocationRecord == null) - { - - String hsa = (String) _locationHsaMap.get(lid); - - if (hsa != null) - { - groupId = "DEF_" + hsa; - } - else //hsa == null - { - groupId = _defaultGroupId; - addThisLocationToDefaultGroupList(lid); - } - - } - - - } - - return groupId; - } - - public String getHsa(String groupId) - { - //return getHsaOrig(groupId); - return getHsa3(groupId); - } - - public String getHsaOrig(String groupId) - { - String hsa ; - RiverMonGroupRecord riverMonGroupRecord = null; - if (_groupIdToRiverMonGroupMap != null) - { - if (_groupIdToRiverMonGroupMap.size() > 0) - riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - } - - if (riverMonGroupRecord != null) - { - hsa = (String ) _groupHsaMap.get(riverMonGroupRecord.getGroup_id()); - } - else - { - hsa = getDefaultHsa(); - } - return hsa; - } - - public String getHsa2(String groupId) - { - String hsa = getDefaultHsa(); - - if (_groupIdToRiverMonGroupMap != null) - { - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - - if (riverMonGroupRecord != null) - { - hsa = _groupHsaMap.get(riverMonGroupRecord.getGroup_id()).toString(); - } - } - - return hsa; - } - - public String getHsa3(String groupId) - { - String hsa = (String) _groupHsaMap.get(groupId); - - if (hsa == null) - { - hsa = getDefaultHsa(); - } - - return hsa; - } - - public void resetLocationOrdinalForDefaultLocations() - { - _locationOrdinalForDefaultLocations = 1; - } - - public int getLocationOrdinal(String lid) - { - String header = "RiverMonLocGroupDataManager.getLocationOrdinal(): "; - int locationOrdinal = 1; - RiverMonLocationRecord riverMonlocationRecord = null; - - String groupId = getGroupId(lid); - - if (groupId == null) - { - System.out.println(header + "groupId was null for lid = " + lid); - } - - else - { - if( ! groupId.equals(_defaultGroupId)) - { - riverMonlocationRecord = (RiverMonLocationRecord) _lidToRiverMonLocationMap.get(lid); - - if (riverMonlocationRecord != null) - { - locationOrdinal = riverMonlocationRecord.getOrdinal(); - } - } - else // default group id - { - locationOrdinal = _locationOrdinalForDefaultLocations++; - } - } - - return locationOrdinal; - } - - - public int getGroupOrdinal(String groupId) - { - int groupOrdinal = 1; - - RiverMonGroupRecord riverMonGroupRecord = null; - if (_groupIdToRiverMonGroupMap != null) - { - riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - } - - if (riverMonGroupRecord != null) - { - groupOrdinal = riverMonGroupRecord.getOrdinal(); - } - else - { - // scenario where default group doesn't have entry in - // RivermonGroup - - if ((_groupInfoList != null) && (_groupInfoList.size() > 0) )// RiverMonGroup has - // some entries - { - - RiverMonGroupRecord tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(0); - int max = tempRiverMonGroupRecord.getOrdinal(); - - for (int k = 1; k < _groupInfoList.size(); k++) - { - tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(k); - if (max < tempRiverMonGroupRecord.getOrdinal()) - { - max = tempRiverMonGroupRecord.getOrdinal(); - } - } - groupOrdinal = max + 1; - } - } - - return groupOrdinal; - } - - private int getGroupOrdinalOld(String groupId) - { - int groupOrdinal = 1; - - RiverMonGroupRecord riverMonGroupRecord = null; - if (_groupIdToRiverMonGroupMap != null) - { - if (_groupIdToRiverMonGroupMap.size() > 0) - riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - } - - if (riverMonGroupRecord != null) - { - groupOrdinal = riverMonGroupRecord.getOrdinal(); - } - else - // scenario where default group doesn't have entry in - // RivermonGroup - { - if (_groupIdToRiverMonGroupMap != null) - { - if (_groupIdToRiverMonGroupMap.size() > 0)// RiverMonGroup has - // some records - { - if (_groupInfoList != null) // RiverMonGroup has - // some entries - { - if (_groupInfoList.size() > 0) - { - RiverMonGroupRecord tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap - .get(_defaultGroupId); - int max; - tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(0); - max = tempRiverMonGroupRecord.getOrdinal(); - for (int k = 1; k < _groupInfoList.size(); k++) - { - tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(k); - if (max < tempRiverMonGroupRecord.getOrdinal()) - max = tempRiverMonGroupRecord.getOrdinal(); - } - groupOrdinal = max + 1; - } - else - { - groupOrdinal = 1; - } - } - } - else - // No entries in RiverMonGroup - { - groupOrdinal = 1; - } - } - } - - return groupOrdinal; - } - -} - diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationColumns.java deleted file mode 100755 index f087abf40c..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationColumns.java +++ /dev/null @@ -1,39 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class RiverMonLocationColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String LOCATION_ID = "Location"; - public static final String LOCATION_ORDINAL = "Location Ordinal"; - - /** - * Creates a list of rivermon location columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the rivermon location columns are added to it, - * if not the location info columns are added to the list that is passed as argument. - * The created new list is returned. - * @param riverMonLocationColumnDescriptorList - * @return - */ - public List getRiverMonLocationColumnsList(List riverMonLocationColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if( riverMonLocationColumnDescriptorList == null) - { - riverMonLocationColumnDescriptorList = new ArrayList(); - } - - riverMonLocationColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ID, true, 95, textAlignment, "Group Identification")); - riverMonLocationColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ID, true, 95, textAlignment, "Location Identification")); - riverMonLocationColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ORDINAL, true, 105, numberAlignment, "Location Ordinal")); - - return riverMonLocationColumnDescriptorList; - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationDialog.java deleted file mode 100755 index 568720c3ca..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationDialog.java +++ /dev/null @@ -1,383 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.RiverMonLocationRecord; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.FrameCloseWindowListener; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RiverMonLocationDialog extends JDialog -{ - private List _riverMonLocationColumnDescriptorList = null; - private JTableManager _riverMonLocationTableManager = null; - private RiverMonLocGroupDataManager _riverMonLocGroupDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private int _selectedRowIndex; - private boolean _riverMonLocationTableChanged = false; - - private JLabel _lidLabel; - private JComboBox _lidComboBox ; - private JLabel _lidOrdinalLabel; - private JTextField _lidOrdinalField ; - private JLabel _groupIdLabel; - private JComboBox _groupIdComboBox; - private JButton _updateButton; - private JButton _deleteButton ; - private JButton _closeButton ; - private String _groupIdArray[]; - private String _lidArray[]; - - private boolean _infoDialogShown = false; - private SessionLogger _logger = null; - - private RiverMonLocationJTableRowData _selectedRowData; - private TextFieldInputVerifier _textFieldInputVerifier = new TextFieldInputVerifier(); - - public RiverMonLocationDialog(JFrame mainFrame, RiverMonLocGroupDataManager riverMonLocGroupDataMgr, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - this.setTitle("RiverMonLocation"); - this.getContentPane().setLayout(new GridBagLayout()); - _riverMonLocGroupDataMgr = riverMonLocGroupDataMgr; - _groupIdArray = _riverMonLocGroupDataMgr.getAllGroup(); - discardDefaultGroupInGroupIdArray(); - _lidArray = _riverMonLocGroupDataMgr.getAllLid(); - initialize(riverMonLocGroupDataMgr); - Dimension min = new Dimension(300,570); - Dimension max = new Dimension(350,570); - new WindowResizingManager(this, min, max); - this.pack(); - this.setLocation(25, 25); - } - - public boolean showRiverMonLocationDialog() - { - _riverMonLocationTableChanged = false; - _allRowDataList = _riverMonLocGroupDataMgr.readDataFromRiverMonLocation(); - _riverMonLocationTableManager.setChangedAllRowDataList(_allRowDataList); - _riverMonLocationTableManager.refreshDisplay(); - - _groupIdArray = _riverMonLocGroupDataMgr.getAllGroup(); - _groupIdComboBox.removeAllItems(); - discardDefaultGroupInGroupIdArray(); - for(int i=0; i <_groupIdArray.length; i++) - { - _groupIdComboBox.addItem(_groupIdArray[i]); - } - - _lidArray = _riverMonLocGroupDataMgr.getAllLid(); - _lidComboBox.removeAllItems(); - for(int i=0; i <_lidArray.length; i++) - { - _lidComboBox.addItem(_lidArray[i]); - } - this.setVisible(true); - return(_riverMonLocationTableChanged); - } - - private void discardDefaultGroupInGroupIdArray() - { - List groupIdList = new ArrayList(); - for(int i=0; i < _groupIdArray.length; i++) - { - if(_groupIdArray[i].equalsIgnoreCase("default")) - continue; - else - groupIdList.add(_groupIdArray[i]); - } - String[] groupIdArray = new String[groupIdList.size()]; - for(int i=0; i < groupIdList.size(); i++) - { - groupIdArray[i] = (String) groupIdList.get(i); - } - _groupIdArray = groupIdArray; - } - - private void initialize(RiverMonLocGroupDataManager riverMonLocGroupDataMgr) - { - _riverMonLocationColumnDescriptorList = new RiverMonLocationColumns().getRiverMonLocationColumnsList(_riverMonLocationColumnDescriptorList); - - _allRowDataList = riverMonLocGroupDataMgr.readDataFromRiverMonLocation(); - _riverMonLocationTableManager = new ComplexJTableManager(_riverMonLocationColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _riverMonLocationTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _riverMonLocationTableManager.setDisplayableColumns(columnsSelected, true, true); - _riverMonLocationTableManager.setPreferredSizeForJScrollPane(new Dimension(315, 300)); - _riverMonLocationTableManager.setVerifyInputWhenFocusTarget(false); - RiverMonitorLocationTableMouseListener tableMouseListener = new RiverMonitorLocationTableMouseListener(); - _riverMonLocationTableManager.addTableListener(tableMouseListener); - _tableScrollPane = _riverMonLocationTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(315,310)); - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - tablePanel.setMinimumSize(new Dimension(315,310)); - - _lidLabel = new JLabel("Location"); - _lidComboBox = new JComboBox(_lidArray); - - _lidOrdinalLabel = new JLabel("Location Ordinal"); - _lidOrdinalField = new JTextField(); - _lidOrdinalField.setInputVerifier(_textFieldInputVerifier); - - _groupIdLabel = new JLabel("Group Id"); - _groupIdComboBox = new JComboBox(_groupIdArray); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(3,2)); - infoPanel.add(_lidLabel); - infoPanel.add(_lidComboBox); - - infoPanel.add(_groupIdLabel); - infoPanel.add(_groupIdComboBox); - - infoPanel.add(_lidOrdinalLabel); - infoPanel.add(_lidOrdinalField); - - JPanel actionPanel = new JPanel(); - actionPanel = new JPanel(); - _updateButton = new JButton("Save"); - _deleteButton = new JButton("Delete"); - _closeButton = new JButton("Close"); - _closeButton.setVerifyInputWhenFocusTarget(false); - actionPanel.add(_updateButton); - actionPanel.add(_deleteButton); - actionPanel.add(_closeButton); - - JPanel editPanel = new JPanel(); - editPanel.setLayout(new GridLayout(1,2)); - editPanel.setBorder(BorderFactory.createTitledBorder("Details")); - - editPanel.add(infoPanel); - - Container contentPane = this.getContentPane(); - ComponentHelper.addFrameComponent(contentPane, tablePanel, 0, 0,1,1,1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, editPanel, 0, 1,1,1, 1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, actionPanel, 0, 2,1,1, 1, 1, 0); - - UpdateListener updateListener = new UpdateListener(); - _updateButton.addActionListener(updateListener); - - DeleteListener deleteListener = new DeleteListener(); - _deleteButton.addActionListener(deleteListener); - - CloseListener closeListener = new CloseListener(); - _closeButton.addActionListener(closeListener); - - } - - private void closeRiverMonLocationDialog() - { - this.setVisible(false); - } - - private void showCurrentRowData() - { - if(_selectedRowData != null) - { - _groupIdComboBox.setSelectedItem(_selectedRowData.getGroupId()); - _lidComboBox.setSelectedItem(_selectedRowData.getLid()); - _lidOrdinalField.setText(new Integer(_selectedRowData.getLocationOrdinal()).toString()); - } - } - - private RiverMonLocationRecord getRiverMonLocationRecord() - { - RiverMonLocationRecord record = new RiverMonLocationRecord(); - - record.setLid(_lidComboBox.getSelectedItem().toString()); - - if(!(_lidOrdinalField.getInputVerifier().verify(_lidOrdinalField))) - { - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setOrdinal(Integer.parseInt(_lidOrdinalField.getText())); - } - record.setGroup_id(_groupIdComboBox.getSelectedItem().toString()); - - return record; - } - - private void getCurrentDataFromDataMgr() - { - List dbInfoList = null; - String header = "RiverMonLocationDialog.getCurrentDataFromDataMgr() "; - try - { - dbInfoList = _riverMonLocGroupDataMgr.readDataFromRiverMonLocation(); - } - catch(Exception e) - { - _logger.log(header+ e); - } - _allRowDataList = dbInfoList; - _riverMonLocationTableManager.setChangedAllRowDataList(_allRowDataList); - } - - private void delete() - { - String header = "RiverMonLocationDialog.delete(): "; - - RiverMonLocationRecord record = getRiverMonLocationRecord(); - - _logger.log(header+" Delete record"+ record.toString()); - _riverMonLocGroupDataMgr.delete(record); - getCurrentDataFromDataMgr(); - _riverMonLocationTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(); - _riverMonLocationTableChanged = true; - - } - - private void insertOrUpdate() - { - String header = "RiverMonLocationDialog.insertOrUpdate(): "; - - RiverMonLocationRecord record = getRiverMonLocationRecord(); - - _logger.log(header+" Update record"+ record.toString()); - _riverMonLocGroupDataMgr.updateOrInsert(record); - getCurrentDataFromDataMgr(); - _riverMonLocationTableManager.refreshDisplay(); - int rowToHighLight = _riverMonLocationTableManager.getTheRowIndexToHighLightBasedOnValue(_lidComboBox.getSelectedItem().toString()); - _riverMonLocationTableManager.selectRows(rowToHighLight, rowToHighLight); - _riverMonLocationTableChanged = true; - - } - - private class TextFieldInputVerifier extends InputVerifier - { - public boolean verify(JComponent component) - { - boolean returnValue = true; - JTextField textField = (JTextField)component; - try - { - Integer.parseInt(textField.getText()); - returnValue = true; - } - catch (NumberFormatException e) - { - returnValue = false; - } - if(!returnValue) - { - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - } - return returnValue; - } - } - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeRiverMonLocationDialog(); - } - } - - private class DeleteListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonitorLocationDialog.DeleteListener.actionPerformed(): "; - if(!_infoDialogShown) - { - delete(); - } - } - } - - private class UpdateListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonLocationDialog.UpdateListener.actionPerformed(): "; - if(!_infoDialogShown) - { - insertOrUpdate(); - } - } - } - - private class RiverMonitorLocationTableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - _selectedRowIndex = _riverMonLocationTableManager.getMousePointedRowIndex(p); - _selectedRowData = (RiverMonLocationJTableRowData) _riverMonLocationTableManager.getSelectedRowData(_selectedRowIndex); - showCurrentRowData(); - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - - public static void main(String[] args) - { - /* - * This main is for testing purposes - */ - - String jdbcUrl = args[0]; - String baseLogFilePath = args[1]; - String defaultHsa = args[2]; - - System.out.println("jdbcUrl = " + jdbcUrl ); - - Database database = new Database(jdbcUrl); - - String messageId = "M1"; - SessionLogger logger = new SessionLogger("RiverMonLocation", baseLogFilePath, true, true, messageId); - - RiverMonLocGroupDataManager dataMgr = new RiverMonLocGroupDataManager(database, logger, "", defaultHsa ); - - JFrame frame = new JFrame(); - - FrameCloseWindowListener.addFrameCloseWindowListener(frame); - - RiverMonLocationDialog dialog = new RiverMonLocationDialog(frame, dataMgr, logger); - dialog.setVisible(true); - frame.setVisible(true); - - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationJTableRowData.java deleted file mode 100755 index 7bdea0dae1..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationJTableRowData.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import ohd.hseb.monitor.MonitorCell; -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.CellType; - -public class RiverMonLocationJTableRowData extends AbstractJTableRowData -{ - private String _lid; - private String _groupId; - private int _locationOrdinal; - - public RiverMonLocationJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getLid() - { - return _lid; - } - - public void setLid(String lid) - { - _lid = lid; - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - _groupId = groupId; - } - - public int getLocationOrdinal() - { - return _locationOrdinal; - } - - public void setLocationOrdinal(int groupOrdinal) - { - _locationOrdinal = groupOrdinal; - } - - public void addAllCellsToMap() - { - addToCellMap(RiverMonLocationColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(RiverMonLocationColumns.LOCATION_ID, CellType.STRING, getLid() ); - addToCellMap(RiverMonLocationColumns.LOCATION_ORDINAL, CellType.INTEGER, getLocationOrdinal()); - - } - - // ----------------------------------------------------------------------------------- - - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - int decimalPointsForDisplay = 2; - MonitorCell cell = new MonitorCell (columnName, cellType, - value, ThreatLevel.NO_THREAT, - _missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventColumns.java b/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventColumns.java deleted file mode 100755 index ed6f7b118e..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventColumns.java +++ /dev/null @@ -1,75 +0,0 @@ -package ohd.hseb.vtecevent; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class VtecEventColumns -{ - public static String OFFICE_ID ="OffId"; - public static String LID = "LocId"; - public static String PRODUCT_MODE = "Mode"; - public static String ACTION = "Act"; - public static String PHENOMENON ="Ph"; - public static String SIGNIFICANCE ="Sig"; - public static String EVENT_TRACKING_NUMBER ="ETN"; - public static String BEGIN_TIME ="BeginTime"; - public static String END_TIME ="EndTime"; - public static String ACTIVE ="Active"; - public static String SEVERITY ="Sev"; - public static String IMMEDIATE_CAUSE ="ImC"; - public static String RISE_TIME ="RiseTime"; - public static String CREST_TIME ="CrestTime"; - public static String FALL_TIME ="FallTime"; - public static String PRODUCT_ID ="ProdId"; - public static String PRODUCT_TIME ="ProductTime"; - public static String UGC_EXPIRE_TIME ="UGCExpTime"; - public static String RECORD ="Rec"; - public static String RISE_TS ="TSr"; - public static String CREST_TS ="TSc"; - public static String FALL_TS ="TSf"; - public static String CREST_VALUE ="CrestVal"; - - /** - * Creates a list of vtecevent columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the vtecevent columns are added to it, - * if not the vtecevent columns are added to the list that is passed as argument. - * The created new list is returned. - * @param officeNotesColumnDescriptorList - * @return - */ - public List getVtecEventColumnsList(List vtecEventColumnDescriptorList) - { - if( vtecEventColumnDescriptorList == null) - { - vtecEventColumnDescriptorList = new ArrayList(); - } - - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(OFFICE_ID, true, 30, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(LID, true, 50, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_MODE, true, 35, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(ACTION, true, 35, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PHENOMENON, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(SIGNIFICANCE, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(EVENT_TRACKING_NUMBER, true, 35, "right")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(BEGIN_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(END_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(ACTIVE, true, 40, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(SEVERITY, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(IMMEDIATE_CAUSE, true, 35, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(RISE_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(CREST_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(FALL_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_ID, true, 100, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(UGC_EXPIRE_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(RECORD, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(RISE_TS, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(CREST_TS, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(FALL_TS, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(CREST_VALUE, true, 60, "right")); - - return vtecEventColumnDescriptorList; - } -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventDataManager.java b/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventDataManager.java deleted file mode 100755 index d43cd9c920..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventDataManager.java +++ /dev/null @@ -1,119 +0,0 @@ -package ohd.hseb.vtecevent; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.ihfsdb.generated.VTECeventTable; -import ohd.hseb.monitor.river.RiverMonitorVtecEventDataManager; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.SessionLogger; - -public class VtecEventDataManager -{ - private Database _db = null; - private SessionLogger _logger = null; - private String _missingRepresentation; - - public VtecEventDataManager(Database dbHandler, SessionLogger logger, String missingRepresentation) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","Vtec Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public List readDataFromVtecEvent() - { - List vtecEventInfoList = null; - List dataList = null; - - VTECeventTable vtecEventTable = new VTECeventTable(_db); - VTECeventRecord vtecEventRecord = null; - String whereClause = null; - String header = "VtecEventDataManager.readDataFromVtecEvent(): "; - - CodeTimer timer = new CodeTimer(); - - try - { - whereClause = "order by geoid"; - timer.start(); - vtecEventInfoList = vtecEventTable.select(whereClause); - timer.stop("Read from vtec event elapsed time:"); - _logger.log(header+ "Where Clause:"+ whereClause); - if(vtecEventInfoList != null) - { - dataList = new ArrayList(); - for(int i=0;i < vtecEventInfoList.size(); i++) - { - vtecEventRecord = (VTECeventRecord) vtecEventInfoList.get(i); - VtecJTableRowData rowData = new VtecJTableRowData(_missingRepresentation); - String active = (RiverMonitorVtecEventDataManager.checkIfEventActive(vtecEventRecord)?"Y":""); - //rowData.setVtecRecord(vtecEventRecord, active); - - rowData.setGeoId(vtecEventRecord.getGeoid()); - rowData.setAction(vtecEventRecord.getAction()); - rowData.setBeginTime(vtecEventRecord.getBegintime()); - rowData.setCrests(vtecEventRecord.getCrests()); - rowData.setCrestTime(vtecEventRecord.getCresttime()); - rowData.setEndTime(vtecEventRecord.getEndtime()); - rowData.setUGCExpireTime(vtecEventRecord.getExpiretime()); - rowData.setEtn(vtecEventRecord.getEtn()); - rowData.setFallTime(vtecEventRecord.getFalltime()); - rowData.setFallts(vtecEventRecord.getFallts()); - rowData.setImmedCause(vtecEventRecord.getImmed_cause()); - rowData.setOfficeId(vtecEventRecord.getOffice_id()); - rowData.setPhenom(vtecEventRecord.getPhenom()); - rowData.setProductId(vtecEventRecord.getProduct_id()); - rowData.setProductMode(vtecEventRecord.getProductmode()); - rowData.setProductTime(vtecEventRecord.getProducttime()); - rowData.setRecord(vtecEventRecord.getRecord()); - rowData.setRiseTime(vtecEventRecord.getRisetime()); - rowData.setRisets(vtecEventRecord.getRisets()); - rowData.setSeverity(vtecEventRecord.getSeverity()); - rowData.setSignif(vtecEventRecord.getSignif()); - rowData.setCrestValue(vtecEventRecord.getCrest_value()); - - rowData.setActive(active); - - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+"VtecEventinfo list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventDialog.java b/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventDialog.java deleted file mode 100755 index 8867785498..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecEventDialog.java +++ /dev/null @@ -1,88 +0,0 @@ -package ohd.hseb.vtecevent; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.util.List; - -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class VtecEventDialog extends JDialog -{ - private List _vtecEventColumnDescriptorList = null; - private JTableManager _vtecEventTableManager = null; - private VtecEventDataManager _vtecDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private SessionLogger _logger; - private int _previousRowToHighlight = -1; - - public VtecEventDialog(JFrame mainFrame, VtecEventDataManager vtecDataMgr, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - this.setTitle("Valid Time Event Code (VTEC) History"); - this.getContentPane().setLayout(new GridBagLayout()); - _vtecDataMgr = vtecDataMgr; - initialize(); - Dimension dim; - dim = new Dimension(1250,560); - new WindowResizingManager(this, dim, dim); - this.pack(); - this.setLocation(25, 25); - } - - public void showVtecEventDialog(String geoId) - { - _allRowDataList = _vtecDataMgr.readDataFromVtecEvent(); - _vtecEventTableManager.setChangedAllRowDataList(_allRowDataList); - _vtecEventTableManager.refreshDisplay(); - - if(geoId != null) - { - _vtecEventTableManager.deselectRows(_previousRowToHighlight, _previousRowToHighlight); - int rowToHighLight = _vtecEventTableManager.getTheRowIndexToHighLightBasedOnValue(geoId); - if(rowToHighLight != -1) - { - _vtecEventTableManager.selectRows(rowToHighLight, rowToHighLight); - _previousRowToHighlight = rowToHighLight; - } - } - this.setVisible(true); - } - - private void initialize() - { - _vtecEventColumnDescriptorList = new VtecEventColumns().getVtecEventColumnsList(_vtecEventColumnDescriptorList); - _allRowDataList = _vtecDataMgr.readDataFromVtecEvent(); - - _vtecEventTableManager = new ComplexJTableManager(_vtecEventColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _vtecEventTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - - _vtecEventTableManager.setDisplayableColumns(columnsSelected, true, true); - - _vtecEventTableManager.setPreferredSizeForJScrollPane(new Dimension(1230, 500)); - - _tableScrollPane = _vtecEventTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - - tableScrollPanePanel.setMinimumSize(new Dimension(1240,510)); - - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - - Container contentPane = this.getContentPane(); - contentPane.add(tablePanel); - } - -} diff --git a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecJTableRowData.java b/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecJTableRowData.java deleted file mode 100755 index d00878b75a..0000000000 --- a/cave/ohd.hseb.monitor/src/ohd/hseb/vtecevent/VtecJTableRowData.java +++ /dev/null @@ -1,309 +0,0 @@ -package ohd.hseb.vtecevent; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class VtecJTableRowData extends AbstractJTableRowData -{ - private String _geoId; - private String _productId; - private long _productTime; - private long _ugcExpireTime; - private String _productMode; - private String _action; - private String _officeId; - private String _phenom; - private String _signif; - private short _etn; - private long _beginTime; - private long _endTime; - private String _severity; - private String _immedCause; - private long _riseTime; - private long _crestTime; - private long _fallTime; - private String _record; - private String _risets; - private String _crests; - private String _fallts; - private String _active; - private double _crestValue; - - public VtecJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getAction() - { - return _action; - } - - public void setAction(String action) - { - this._action = action; - } - - public long getBeginTime() - { - return _beginTime; - } - - public void setBeginTime(long beginTime) - { - _beginTime = beginTime; - } - - public String getCrests() - { - return _crests; - } - - public void setCrests(String crests) - { - this._crests = crests; - } - - public long getCrestTime() - { - return _crestTime; - } - - public void setCrestTime(long crestTime) - { - _crestTime = crestTime; - } - - public long getEndTime() - { - return _endTime; - } - - public void setEndTime(long endTime) - { - _endTime = endTime; - } - - public short getEtn() - { - return _etn; - } - - public void setEtn(short etn) - { - this._etn = etn; - } - - public long getFallTime() - { - return _fallTime; - } - - public void setFallTime(long fallTime) - { - _fallTime = fallTime; - } - - public String getFallts() - { - return _fallts; - } - - public void setFallts(String fallts) - { - this._fallts = fallts; - } - - public String getGeoId() - { - return _geoId; - } - - public void setGeoId(String geoId) - { - _geoId = geoId; - } - - public String getImmedCause() - { - return _immedCause; - } - - public void setImmedCause(String immedCause) - { - _immedCause = immedCause; - } - - public String getOfficeId() - { - return _officeId; - } - - public void setOfficeId(String officeId) - { - _officeId = officeId; - } - - public String getPhenom() - { - return _phenom; - } - - public void setPhenom(String phenom) - { - this._phenom = phenom; - } - - public String getProductId() - { - return _productId; - } - - public void setProductId(String productId) - { - _productId = productId; - } - - public String getProductMode() - { - return _productMode; - } - - public void setProductMode(String productMode) - { - _productMode = productMode; - } - - public long getProductTime() - { - return _productTime; - } - - public void setProductTime(long productTime) - { - _productTime = productTime; - } - - public long getUGCExpireTime() - { - return _ugcExpireTime; - } - - public void setUGCExpireTime(long ugcExpireTime) - { - _ugcExpireTime = ugcExpireTime; - } - - public String getRecord() - { - return _record; - } - - public void setRecord(String record) - { - this._record = record; - } - - public long getRiseTime() - { - return _riseTime; - } - - public void setRiseTime(long riseTime) - { - _riseTime = riseTime; - } - - public String getRisets() - { - return _risets; - } - - public void setRisets(String risets) - { - this._risets = risets; - } - - public String getSeverity() - { - return _severity; - } - - public void setSeverity(String severity) - { - this._severity = severity; - } - - public String getSignif() - { - return _signif; - } - - public void setSignif(String signif) - { - this._signif = signif; - } - - public String getActive() - { - return _active; - } - - public void setActive(String active) - { - this._active = active; - } - - public double getCrestValue() - { - return _crestValue; - } - - public void setCrestValue(double crestValue) - { - _crestValue = crestValue; - } - - public String toString() - { - String str = null; - return str; - } - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation(), "MM/dd - HH:mm"); - addCell(cell); - - } - - public void addAllCellsToMap() - { - addToCellMap(VtecEventColumns.OFFICE_ID, CellType.STRING, getOfficeId()); - addToCellMap(VtecEventColumns.LID, CellType.STRING, getGeoId()); - addToCellMap(VtecEventColumns.PRODUCT_MODE, CellType.STRING, getProductMode()); - addToCellMap(VtecEventColumns.ACTION, CellType.STRING, getAction()); - addToCellMap(VtecEventColumns.PHENOMENON, CellType.STRING, getPhenom()); - addToCellMap(VtecEventColumns.SIGNIFICANCE, CellType.STRING,getSignif()); - addToCellMap(VtecEventColumns.EVENT_TRACKING_NUMBER,CellType.SHORT, getEtn()); - addToCellMap(VtecEventColumns.BEGIN_TIME,CellType.DATE_TIME, getBeginTime()); - addToCellMap(VtecEventColumns.END_TIME,CellType.DATE_TIME, getEndTime()); - addToCellMap(VtecEventColumns.ACTIVE, CellType.STRING, getActive()); - addToCellMap(VtecEventColumns.SEVERITY, CellType.STRING, getSeverity()); - addToCellMap(VtecEventColumns.IMMEDIATE_CAUSE,CellType.STRING, getImmedCause()); - addToCellMap(VtecEventColumns.RISE_TIME, CellType.DATE_TIME, getRiseTime()); - addToCellMap(VtecEventColumns.CREST_TIME, CellType.DATE_TIME, getCrestTime()); - addToCellMap(VtecEventColumns.FALL_TIME, CellType.DATE_TIME, getFallTime()); - addToCellMap(VtecEventColumns.PRODUCT_ID, CellType.STRING, getProductId()); - addToCellMap(VtecEventColumns.PRODUCT_TIME, CellType.DATE_TIME, getProductTime()); - addToCellMap(VtecEventColumns.UGC_EXPIRE_TIME, CellType.DATE_TIME, getUGCExpireTime()); - addToCellMap(VtecEventColumns.RECORD, CellType.STRING, getRecord()); - addToCellMap(VtecEventColumns.RISE_TS, CellType.STRING, getRisets()); - addToCellMap(VtecEventColumns.CREST_TS, CellType.STRING, getCrests()); - addToCellMap(VtecEventColumns.FALL_TS, CellType.STRING, getFallts()); - addToCellMap(VtecEventColumns.CREST_VALUE, CellType.DOUBLE,getCrestValue()); - } - -} diff --git a/cave/ohd.hseb.monitor/src/scripts/init_rivermon_tables.ksh b/cave/ohd.hseb.monitor/src/scripts/init_rivermon_tables.ksh deleted file mode 100755 index 7331768dcd..0000000000 --- a/cave/ohd.hseb.monitor/src/scripts/init_rivermon_tables.ksh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/ksh - -#Author: Varalakshmi Rajaram -#Date : May 10th 2006 -#Initialize rivermonlocation and rivermongroup tables - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -###################### function -fn(){ - psql $DB_NAME -e << END - \copy rpffcstgroup (group_id, group_name, ordinal) to './input.grp' with delimiter '|' - \copy rivermongroup(group_id, group_name, ordinal) from './input.grp' with delimiter '|' - insert into rivermongroup values('DEFAULT', 'DEFAULT GROUP', 1); - update rivermongroup set hsa=(select hsa from admin) where hsa is null; - \copy rpffcstpoint (lid, group_id, ordinal) to './input.lid1' with delimiter '|' - create table dummytable(lid varchar(8)); - insert into dummytable select lid from location where lid not in(select lid from rpffcstpoint); - \copy dummytable (lid) to './input.lid2' with delimiter '|' - \copy rivermonlocation(lid, group_id, ordinal) from './input.lid1' with delimiter '|' - \copy rivermonlocation(lid) from './input.lid2' with delimiter '|' - update rivermonlocation set ordinal=1 where ordinal is null; - update rivermonlocation set group_id='DEFAULT' where group_id is null; - drop table dummytable; -END - - rm -f ./input.grp ./input.lid1 ./input.lid2 -} - -fn diff --git a/cave/ohd.hseb.monitor/src/scripts/start_rivermonitor b/cave/ohd.hseb.monitor/src/scripts/start_rivermonitor deleted file mode 100755 index 6adb3fbc74..0000000000 --- a/cave/ohd.hseb.monitor/src/scripts/start_rivermonitor +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/ksh - -# File name: start_rivermonitor -# Author : Varalakshmi Rajaram - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH:$PLUGINDIR:$WHFS_BIN_DIR/RiverMonitor.jar:$CLASSPATH - -MISSING_REPRESENTATION=' ' - -#Execute the RiverMonitor - -if [[ $# > 0 ]] -then -MONITOR_NAME="$1" -else -MONITOR_NAME="River" -fi - -xterm -T $MONITOR_NAME"Monitor" -iconic \ --e $SYS_JAVA_DIR/bin/java -Xms64m -Xmx512m ohd.hseb.monitor.Monitor $JDBCURL "$MISSING_REPRESENTATION" $MONITOR_NAME & - diff --git a/cave/ohd.hseb.sshp/.classpath b/cave/ohd.hseb.sshp/.classpath deleted file mode 100644 index 1fa3e6803d..0000000000 --- a/cave/ohd.hseb.sshp/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/cave/ohd.hseb.sshp/.project b/cave/ohd.hseb.sshp/.project deleted file mode 100644 index 052b6793c4..0000000000 --- a/cave/ohd.hseb.sshp/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.hseb.sshp - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/cave/ohd.hseb.sshp/.settings/org.eclipse.jdt.core.prefs b/cave/ohd.hseb.sshp/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index add0faab90..0000000000 --- a/cave/ohd.hseb.sshp/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -#Thu Mar 26 11:32:06 CDT 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cave/ohd.hseb.sshp/META-INF/MANIFEST.MF b/cave/ohd.hseb.sshp/META-INF/MANIFEST.MF deleted file mode 100644 index 606133c568..0000000000 --- a/cave/ohd.hseb.sshp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,21 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Sshp Plug-in -Bundle-SymbolicName: ohd.hseb.sshp;singleton:=true -Bundle-Version: 1.0.0.qualifier -Bundle-Activator: ohd.hseb.sshp.Activator -Require-Bundle: ohd.hseb.ihfsdb, - ohd.hseb.common, - org.eclipse.ui, - org.eclipse.core.runtime, - org.postgres, - com.raytheon.viz.core, - ohd.hseb.monitor -Bundle-ActivationPolicy: lazy -Export-Package: ohd.hseb.sshp, - ohd.hseb.sshp.gui, - ohd.hseb.sshp.messaging, - ohd.hseb.sshp.precip, - ohd.hseb.sshp.window -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: com.raytheon.uf.common.ohd diff --git a/cave/ohd.hseb.sshp/build.properties b/cave/ohd.hseb.sshp/build.properties deleted file mode 100644 index 3459198753..0000000000 --- a/cave/ohd.hseb.sshp/build.properties +++ /dev/null @@ -1,5 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - localization/ diff --git a/cave/ohd.hseb.sshp/localization/menus/sshp/baseSshp.xml b/cave/ohd.hseb.sshp/localization/menus/sshp/baseSshp.xml deleted file mode 100644 index 885bc187d7..0000000000 --- a/cave/ohd.hseb.sshp/localization/menus/sshp/baseSshp.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/cave/ohd.hseb.sshp/localization/menus/sshp/index.xml b/cave/ohd.hseb.sshp/localization/menus/sshp/index.xml deleted file mode 100644 index 1fc76b41be..0000000000 --- a/cave/ohd.hseb.sshp/localization/menus/sshp/index.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - \ No newline at end of file diff --git a/cave/ohd.hseb.sshp/ohd.hseb.sshp.ecl b/cave/ohd.hseb.sshp/ohd.hseb.sshp.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cave/ohd.hseb.sshp/src/com/raytheon/sshp/action/OpenSshpAction.java b/cave/ohd.hseb.sshp/src/com/raytheon/sshp/action/OpenSshpAction.java deleted file mode 100644 index ab1d2ac035..0000000000 --- a/cave/ohd.hseb.sshp/src/com/raytheon/sshp/action/OpenSshpAction.java +++ /dev/null @@ -1,115 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.sshp.action; - -import ohd.hseb.sshp.SSHP; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -import com.raytheon.monitor.activator.Activator; -import com.raytheon.monitor.preferences.PreferenceConstants; -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.viz.core.localization.LocalizationManager; - -/** - * Opens the SSHP dialog. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * 
- * 
- * 
- * - * @author mfegan - * @version 1.0 - */ - -public class OpenSshpAction extends AbstractHandler { - - public static final String JDBC_URL = "jdbcUrl"; - - public static final String MISSING_PRESENTATION = "missingPresentation"; - - public static final String HSEB_PREFERENCES = "ohd.hseb.monitor"; - -// private static final String DB_CONNECTION_FORMAT = "jdbc:postgresql://%s:%s/%s?user=%s&password=%s"; - - private String databaseConnectionString = ""; - - private String logFileDir = ""; - - /** - * Constructor. - */ - public OpenSshpAction() { - // TODO Auto-generated constructor stub - super(); - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands. - * ExecutionEvent) - */ - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { -// getAppsDefaults(); - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - databaseConnectionString = Activator.getDefault() - .getPreferenceStore().getString(PreferenceConstants.JDBC_URL); - logFileDir = Activator.getDefault().getPreferenceStore() - .getString(PreferenceConstants.RIVERMON_LOG_DIR); - LocalizationManager mgr = LocalizationManager.getInstance(); - String site = mgr.getCurrentSite(); - if (databaseConnectionString == null - || databaseConnectionString.equals("")) { - MessageDialog - .openError( - shell, - "Error Starting SSHP", - "Database connection string not set, or incorrect, please verify River Apps settings on preference page."); - } else { - System.out.println(databaseConnectionString); - System.out.println(logFileDir); - String[] args = { databaseConnectionString, logFileDir, site }; - SSHP.main(args); - } - return null; - } - - /** - * Not currently used, may be added back later. - */ - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - logFileDir = ad.getToken("sshp_log_dir"); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/AboutInfo.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/AboutInfo.java deleted file mode 100644 index 6539f9db69..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/AboutInfo.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Created on Aug 6, 2004 - * - * - */ -package ohd.hseb.sshp; - -/** - * @author GobsC - * - * - */ -public class AboutInfo -{ - private static final String _versionString = "OB 8.2"; - private static final String _aboutText = " Application : Site Specific Hydrologic Predictor\n" + - " Version : " + _versionString + "\n" + - " Date : 9/21/2007 " + "\n" + - " Developed by :\n" + - " National Weather Service\n" + - " Office of Hydrologic Development\n" + - " Hydrology Laboratory"; - - private AboutInfo() - { - - - } - - public static String getText() - { - return _aboutText; - } - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/Activator.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/Activator.java deleted file mode 100644 index 426d3e0866..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/Activator.java +++ /dev/null @@ -1,50 +0,0 @@ -package ohd.hseb.sshp; - -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -/** - * The activator class controls the plug-in life cycle - */ -public class Activator extends AbstractUIPlugin { - - // The plug-in ID - public static final String PLUGIN_ID = "ohd.hseb.sshp"; - - // The shared instance - private static Activator plugin; - - /** - * The constructor - */ - public Activator() { - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); - } - - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/AppController.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/AppController.java deleted file mode 100644 index 48ef3bfbd0..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/AppController.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Created on Sep 17, 2003 - * - */ -package ohd.hseb.sshp; - -import java.awt.Rectangle; - -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.sshp.window.AnalysisWindow; -import ohd.hseb.sshp.window.ControlWindow; -import ohd.hseb.util.gui.DialogHelper; - -/** - * @author Chip Gobs - * - * This class is the controller under the Model-View-Controller pattern. - * It provides the "glue" application functionality. - * (as a separate concept from the GUI functionality.); -*/ -public class AppController -{ - - private DataMgr _dataMgr = null; - private ControlWindow _controlWindow = null; - // private FileLogger _logger = null; - private String _logDirName = null; - - private String _operatingSystemString = null; - -//----------------------------------------------------------- - - public AppController(DataMgr dataMgr, String logDirName) - { - _dataMgr = dataMgr; - - _logDirName = logDirName; - // _logger = new FileLogger(_logDirName, true, true); - - return; - } -// ----------------------------------------------------------- - /* - public FileLogger getLogger() - { - return _logger; - } - */ - -// ----------------------------------------------------------- - - public String getLogDirName() - { - return _logDirName; - } - -// ----------------------------------------------------------- - - private StreamModel createStreamModel(String locationId) - { - - RainfallRunoffModelType rrModelType = - _dataMgr.getPreferredRainfallRunoffModelType(locationId); - - StreamModel streamModel = new StreamModel(locationId, - rrModelType, - _dataMgr); - - return streamModel; - } - -// ----------------------------------------------------------- - public void displayAnalysisWindow(String locationId) - { - //make sure that a launch window is available - displayControlWindowIfNotDisplayed(); - _controlWindow.enableLaunchButton(false); - - if (_dataMgr.isLocationIdValidForSSHP(locationId)) - { - - StreamModel streamModel = createStreamModel(locationId); - - AnalysisWindow analysisWindow = new AnalysisWindow(streamModel, this); - - Rectangle bounds = analysisWindow.getBounds(); - bounds.x = 80; - analysisWindow.setBounds(bounds); - - analysisWindow.setVisible(true); - analysisWindow.show(); - - } - else // this location is not valid for display in SSHP - { - String message = "Location :" + locationId + ": is not configured for used with SSHP"; - String dialogTitle = "SSHP Error Dialog"; - DialogHelper.displayErrorDialog(_controlWindow, message, dialogTitle); - } - - _controlWindow.enableLaunchButton(true); - } - -// ----------------------------------------------------------- - - - public void displayControlWindowIfNotDisplayed() - { - //displays launch window if one is not already displayed - if (_controlWindow == null) - { - - _controlWindow = new ControlWindow(_dataMgr, this); - - _controlWindow.setVisible(true); - - Rectangle bounds = _controlWindow.getBounds(); - bounds.x = 80; - _controlWindow.setBounds(bounds); - - _controlWindow.show(); - } - } //end displayLaunchWindow() -// ----------------------------------------------------------- - - - public void bringLaunchWindowToFront() - { - //displays launch window if one is not already displayed - if (_controlWindow != null) - { - _controlWindow.requestFocus(); - _controlWindow.setVisible(false); - _controlWindow.setVisible(true); - } - - } //end displayLaunchWindow() - - public boolean isRunningOnWindows() - { - boolean result = false; - - if (_operatingSystemString == null) - { - _operatingSystemString = System.getProperty("os.name").toLowerCase(); - } - - if ( (_operatingSystemString.indexOf("windows") > -1) || - (_operatingSystemString.indexOf("nt") > -1)) - { - // thanks to JuanFran for the xp fix! - result = true; - } - - return result; - } - -// ----------------------------------------------------------- - /* public void finalize() - { - if (_logger!= null) - { - _logger.close(); - } - } - */ -} //end class AppController diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/DataMgr.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/DataMgr.java deleted file mode 100644 index e622d7e350..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/DataMgr.java +++ /dev/null @@ -1,4962 +0,0 @@ -/* - * Created on Jul 30, 2003 - * - * - */ -package ohd.hseb.sshp; - -import java.io.File; -import java.sql.SQLException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.ArealFcstRecord; -import ohd.hseb.ihfsdb.generated.ArealFcstTable; -import ohd.hseb.ihfsdb.generated.ArealObsRecord; -import ohd.hseb.ihfsdb.generated.ArealObsTable; -import ohd.hseb.ihfsdb.generated.ContingencyValueRecord; -import ohd.hseb.ihfsdb.generated.ContingencyValueTable; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.FcstOtherRecord; -import ohd.hseb.ihfsdb.generated.FcstOtherTable; -import ohd.hseb.ihfsdb.generated.FcstPrecipRecord; -import ohd.hseb.ihfsdb.generated.FcstPrecipTable; -import ohd.hseb.ihfsdb.generated.FloodcatRecord; -import ohd.hseb.ihfsdb.generated.FloodcatTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LineSegsRecord; -import ohd.hseb.ihfsdb.generated.LineSegsTable; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.MonthlyValuesRecord; -import ohd.hseb.ihfsdb.generated.MonthlyValuesTable; -import ohd.hseb.ihfsdb.generated.ProcValueRecord; -import ohd.hseb.ihfsdb.generated.ProcValueTable; -import ohd.hseb.ihfsdb.generated.RWResultRecord; -import ohd.hseb.ihfsdb.generated.RWResultTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverStatusRecord; -import ohd.hseb.ihfsdb.generated.RiverStatusTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.SacSmaParamsRecord; -import ohd.hseb.ihfsdb.generated.SacSmaParamsTable; -import ohd.hseb.ihfsdb.generated.SacSmaStateRecord; -import ohd.hseb.ihfsdb.generated.SacSmaStateTable; -import ohd.hseb.ihfsdb.generated.ShefPeRecord; -import ohd.hseb.ihfsdb.generated.ShefPeTable; -import ohd.hseb.ihfsdb.generated.SshpConfigRecord; -import ohd.hseb.ihfsdb.generated.SshpConfigTable; -import ohd.hseb.ihfsdb.generated.UnitGraphRecord; -import ohd.hseb.ihfsdb.generated.UnitGraphTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RelTimeMeasurement; -import ohd.hseb.model.ForecastInterpolationMethod; -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.RatingShift; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.UnitHydrograph; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.sshp.precip.BasinHrapHelper; -import ohd.hseb.util.BooleanHolder; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeSeriesFileManager; - -/** - * DataMgr manages the data for the SSHP application - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- ----------------------------------
- * May 13, 2011  8079       jnjanga    refactored runLoadMaxFcst() 
- *                                     into postMaxFcst()
- * 
- * 
- * - * @author Chip Gobs - */ -public class DataMgr { - public final double MISSING = -999.0; - - private static final int _defaultQualityCode = 1879048191; - - private static final int _questionable_bad_threshold = 1073741824; - - private static final long _millisPerHour = 60 * 60 * 1000; - - private static final long _millisPerYear = (365L * 24L * 60L * 60L * 1000L); - - private Database _db = null; - - private Logger _logger = null; - - private Map _locationDescriptorMap = new HashMap();; - - private Map _sshpConfigMap = new HashMap(); - - private List _sshpConfigList = null; - - private TimeSeriesFileManager _reader = new TimeSeriesFileManager(); - - private static int _referenceCount = 0; - - // ------------------------------------------------------------------------ - - // ------------------------------------------------------------------------ - - public DataMgr() { - - this(null, null); - _logger = new FileLogger("DataMgr.log"); - - _referenceCount++; - - if (_referenceCount > 1) { - throw new Error("Singleton violation error!"); - } - } - - // ------------------------------------------------------------------------ - - public DataMgr(String baseConnectionString, Logger logger) { - super(); - - _db = new Database(); - _logger = logger; - - if (baseConnectionString == null) { - baseConnectionString = getBaseConnectionString(); - } - - _db.connectWithDriverSearch(baseConnectionString); - - } - - // ------------------------------------------------------------------------ - - public String getDatabaseName() { - String dbName = _db.getDatabaseName(); - return dbName; - } - - // ------------------------------------------------------------------------ - - private String getBaseConnectionString() { - // this is used in testing mode, not the production mode - String connectionURLPart = "jdbc:informix-sqli://ds1-nhdr:1530/hd_ob5ounx:informixserver=ONLINE;"; - return connectionURLPart; - } - - // ------------------------------------------------------------------------ - public void disconnect() { - _db.disconnect(); - } - - // ------------------------------------------------------------------------ - public void finalize() { - disconnect(); - } - - // ------------------------------------------------------------------------ - public String getLocationName(String locationId) { - String locationName = null; - - LocationDescriptor desc = getLocationDescriptor(locationId); - if (desc != null) { - locationName = desc.getLocationName(); - } - return locationName; - } - - // ------------------------------------------------------------------------ - private void loadLocationInfo(LocationDescriptor desc, String locationId) { - String locationName = null; - - LocationRecord record = null; - LocationTable table = new LocationTable(_db); - - try { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (LocationRecord) recordList.get(0); - desc.setLocationName(record.getName()); - desc.setHsa(record.getHsa()); - } - } catch (SQLException e) { - logSQLException(e); - } - - return; - } - - // ------------------------------------------------------------------------ - - private String loadStreamName(String locationId) { - String streamName = null; - - RiverstatRecord record = null; - RiverstatTable table = new RiverstatTable(_db); - - try { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (RiverstatRecord) recordList.get(0); - streamName = record.getStream(); - } - } catch (SQLException e) { - logSQLException(e); - } - - return streamName; - } - - // ------------------------------------------------------------------------ - - public LocationDescriptor loadLocationDescriptor(String locationId) { - LocationDescriptor desc = new LocationDescriptor(); - String basinId = null; - String modelPreference = null; - SSHPConfig config = null; - String streamName = null; - - loadLocationInfo(desc, locationId); // load name and hsa from Location - // Table - - streamName = loadStreamName(locationId); - - config = getSSHPConfig(locationId); - if (config != null) { - basinId = config.getBasinId(); - modelPreference = config.getModelPref(); - } - - desc.setId(locationId); - desc.setStreamName(streamName); - desc.setBasinId(basinId); - desc.setModelPreference(modelPreference); - - return desc; - } - - // ------------------------------------------------------------------------ - - public LocationDescriptor getLocationDescriptor(String locationId) { - LocationDescriptor desc = null; - - desc = (LocationDescriptor) _locationDescriptorMap.get(locationId); - - if (desc == null) { - desc = loadLocationDescriptor(locationId); - _locationDescriptorMap.put(locationId, desc); - } - - return desc; - } - - // ------------------------------------------------------------------------ - - public List loadAllSshpBasinIds() { - - String header = "DataMgr.loadAllSshpBasinIds(): "; - - // This method just reads in all the valid basinIds from the SshpConfig - // table - // and returns a list of the basins - HashSet basinSet = new HashSet(); - List basinIdList = new ArrayList(); - - List recordList = null; - - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = null; - - String whereClause = null; - - try { - - whereClause = " ORDER BY basin_id "; - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (SshpConfigRecord) recordList.get(i); - String basinId = record.getBasin_id(); - - if (!basinSet.contains(basinId)) { - basinSet.add(basinId); - basinIdList.add(basinId); - } - - // _logger.log(header + "basinId = " + record.getBasin_id()); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return basinIdList; - } - - // ------------------------------------------------------------------------ - public boolean isLocationIdValidForSSHP(String locationId) { - boolean isValid = false; - String header = "DataMgr.isLocationIdValidForSSHP():"; - List validLocationIdList = loadLocationIdsForForecasts(); - - if (validLocationIdList != null) { - isValid = validLocationIdList.contains(locationId); - _logger.log(header + " locationId = " + locationId); - } - - return isValid; - } - - // ----------------------------------------------------------------------- - public List loadLocationIdsForForecasts() { - // much of this method's select clause taken from Russ Erb's version - List locationIdList = new ArrayList(); - - List recordList = null; - - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - String whereClause = null; - - try { - whereClause = " WHERE lid IN (SELECT lid FROM SshpConfig)" - + " AND lid IN (SELECT distinct(lid) FROM Rating) " - + " AND lid IN (SELECT distinct(lid) FROM UnitGraph) " - + " AND ((fs IS NOT NULL) OR (fq is NOT NULL)) ORDER BY lid "; - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (RiverstatRecord) recordList.get(i); - - locationIdList.add(record.getLid()); - // _locationNameMap.add(record.getLid(), record.get()); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return locationIdList; - } - - // ------------------------------------------------------- - public void saveRatingCurve(RatingCurve ratingCurve) { - RatingTable table = new RatingTable(_db); - - RatingRecord record = new RatingRecord(); - - record.setLid(ratingCurve.getLocationId()); - - try { - - for (int i = 0; i < ratingCurve.getRatingPointCount(); i++) { - RatingPoint point = ratingCurve.getRatingPoint(i); - record.setStage(point.getUnshiftedStage()); - record.setDischarge(point.getDischarge()); - - table.insertOrUpdate(record); - - } - } catch (SQLException e) { - logSQLException(e); - } - - return; - - } - - // ------------------------------------------------------- - public RatingCurve loadRatingCurve(String locationId) { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - try { - ratingRecordList = ratingTable.select("WHERE LID = '" + locationId - + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" - + locationId + "' AND active = 'T' ORDER BY date desc", 1); - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId - + "'"); - - // determine total amount of active - // rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList - .get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - // System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - // initialize the RatingCurve object with data from the database, - // including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - // done by addRatingPoint - // ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } // end for - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList - .get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord - .getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } catch (SQLException e) { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - // ------------------------------------------------------- - public UnitHydrograph loadUnitHydrograph(String locationId, String areaId, - String modelName) { - // String header = "DataMgr.loadUnitHydrograph(): "; - // System.out.println(header + - // "loading unit hydrograph for modelName = " + modelName); - int intervalInHours = 1; - UnitHydrograph unitHydrograph = new UnitHydrograph(MeasuringUnit.cfs, - intervalInHours); - unitHydrograph.setLocationId(locationId); - unitHydrograph.setRainfallRunoffModel(modelName); - - UnitGraphTable table = new UnitGraphTable(_db); - String whereClause = "WHERE lid = '" + locationId + "' AND " - + " area_id = '" + areaId + "' AND " + " model = '" + modelName - + "' AND " + " dur = 1001 " + " ORDER BY area_id, ordinal"; - - List recordList = null; - - try { - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(i); - - long relativeTime = (i * _millisPerHour); - RelTimeMeasurement measurement = new RelTimeMeasurement( - record.getDischarge(), relativeTime, MeasuringUnit.cfs); - - unitHydrograph.addMeasurement(measurement); - } - } catch (SQLException e) { - logSQLException(e); - } - - return unitHydrograph; - - } // end getUnitHydrograph() - - // ------------------------------------------------------- - - private UnitHydrograph loadUnitHydrograph_unused(String locationId) { - int intervalInHours = 1; - UnitHydrograph unitHydrograph = new UnitHydrograph(MeasuringUnit.cfs, - intervalInHours); - unitHydrograph.setLocationId(locationId); - - UnitGraphTable table = new UnitGraphTable(_db); - String whereClause = "WHERE lid = '" + locationId - + " ORDER BY area_id, ordinal"; - - List recordList = null; - - try { - String areaId = null; - - recordList = table.select(whereClause); - - if (recordList.size() > 0) { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(0); - areaId = record.getArea_id(); - unitHydrograph.setAreaId(areaId); - } - - for (int i = 0; i < recordList.size(); i++) { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(i); - - // if a unithydrograph for a different area, but the same - // location, - // ignore the later ones. - if (!areaId.equals(record.getArea_id())) { - break; - } - - long relativeTime = (i * _millisPerHour); - RelTimeMeasurement measurement = new RelTimeMeasurement( - record.getDischarge(), relativeTime, MeasuringUnit.cfs); - - unitHydrograph.addMeasurement(measurement); - } - } catch (SQLException e) { - logSQLException(e); - } - - // System.out.println(header + "ugh = " + unitHydrograph); - - return unitHydrograph; - - } // end getUnitHydrograph() - - // ----------------------------------------------------------------------- - /* - * private RegularTimeSeries _unused_getFileBasedPrecipTimeSeries(long - * endTime, double valueScaling) { MeasuringUnit unit = MeasuringUnit.mm; - * RegularTimeSeries ts = null; double[] precipArray = null; - * - * try { - * - * String fileName = "D:/Data/code/exampleCode/sacsma/rainfile"; precipArray - * = DataFileReader.readPrecipArray(fileName); - * - * int hoursBack = precipArray.length; - * - * long startTime = endTime - (hoursBack * _millisPerHour); startTime = - * TimeHelper.truncateTimeInMillisToNearestHour(startTime, 1); - * - * - * int intervalInHours = 1; - * - * - * ts = new RegularTimeSeries(startTime, endTime, intervalInHours, unit); - * - * - * long millisPerInterval = (intervalInHours *_millisPerHour); - * - * - * //System.out.println( - * "DataMgr.getFileBasedPrecipTimeSeries(): precipArray.length = " + - * precipArray.length ); - * - * long currentTime = startTime; for (int i = 0; i < precipArray.length; - * i++) { // - * System.out.println("DataMgr.getFileBasedPrecipTimeSeries(): i = " + i + - * // " currentTime = " + DbTimeHelper.getStringFromLongTime(currentTime)); - * - * double newValue = precipArray[i]* valueScaling; Measurement measurement = - * new Measurement( newValue, unit); - * - * ts.setMeasurementByTime(measurement, currentTime); - * - * currentTime += millisPerInterval; } } catch(IOException e) { - * e.printStackTrace(); } - * - * return ts; } // end getFileBasedPrecipTimeSeries() - * - * // ------------------------------------------------------- private - * RegularTimeSeries _unused_getFileBasedEvaporationTimeSeries(long - * timeShift, double valueScaling) { MeasuringUnit unit = MeasuringUnit.mm; - * RegularTimeSeries ts = null; double[] evapArray = null; - * - * try { int hoursBack = 72; long startTime = System.currentTimeMillis() - - * (hoursBack * _millisPerHour); startTime = - * TimeHelper.truncateTimeInMillisToNearestHour(startTime, 1); - * - * startTime += timeShift; - * - * String fileName = "D:/Data/code/exampleCode/sacsma/evapfile"; evapArray = - * DataFileReader.readEvapArray(fileName); - * - * int intervalInHours = 1; long intervalInMillis = intervalInHours * - * _millisPerHour; - * - * long endTime = startTime + ( intervalInMillis * (evapArray.length -1)); - * - * ts = new RegularTimeSeries(startTime, endTime, intervalInHours, unit); - * long currentTime = startTime; - * - * long millisPerInterval = (intervalInHours *_millisPerHour); - * - * - * //System.out.println( - * "DataMgr.getFileBasedEvapTimeSeries(): precipArray.length = " + - * precipArray.length ); - * - * - * for (int i = 0; i < evapArray.length; i++) { - * - * currentTime = startTime + (i * millisPerInterval); // - * System.out.println("DataMgr.getFileBasedPrecipTimeSeries(): i = " + i + - * // " currentTime = " + DbTimeHelper.getStringFromLongTime(currentTime)); - * - * double newValue = evapArray[i]* valueScaling; Measurement measurement = - * new Measurement( newValue, unit); - * - * ts.setMeasurementByTime(measurement, currentTime); } } catch(IOException - * e) { e.printStackTrace(); } - * - * return ts; } // end getFileBasedEvaporationTimeSeries() - */ - // ------------------------------------------------------- - public double loadThresholdRunoffValue(String locationId) { - double value = MISSING; - try { - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - String whereClause = "WHERE lid = '" + locationId - + "' AND threshold_runoff is not null"; - - List list = table.selectNRecords(whereClause, 1); - if (list.size() > 0) { - record = (RiverstatRecord) list.get(0); - value = record.getThreshold_runoff(); - } - - } catch (SQLException e) { - logSQLException(e); - } - - if (value != MISSING) { - _logger.log("DataMgr.getThresholdRunoffValue(): value = " + value); - } - - return value; - } - - // ------------------------------------------------------- - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId) { - String header = "DataMgr.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries( - MeasuringUnit.feet); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - _millisPerYear; - long lateTime = currentTime + _millisPerYear; - - /* - * String whereClause = " WHERE lid = '" + locationId + "'" + - * " AND pe = '" + pe + "'" + " AND dur = " + duration + " AND ts = '" + - * typeSource + "'" + " AND extremum = 'Z' ORDER by obstime ASC"; - */ - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe <> 'HI' " + " AND dur = 0" + " AND extremum = 'Z'" - + " AND quality_code >= " + _questionable_bad_threshold; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (HeightRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), MeasuringUnit.feet); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------- - public IrregularTimeSeries loadObservedStageTimeSeriesOld(String locationId) { - // return the best observed stage time series available, that - // based on ts_rank usage - final String header = "DataMgr.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = null; - - String pe = "HG"; - int duration = 0; - - String[] preferredObsTsArray = loadPreferredObsTypeSourceArray( - locationId, pe, duration); - - boolean success = false; - - for (int i = 0; i < preferredObsTsArray.length && !success; i++) { - String ts = preferredObsTsArray[i]; - System.out.println(header + "locationId = " + locationId + " ts = " - + ts); - stageTimeSeries = loadObservedStageTimeSeriesByTsOld(locationId, - pe, duration, ts); - if (stageTimeSeries.getMeasurementCount() > 0) { - System.out.println(header + "found " - + stageTimeSeries.getMeasurementCount() + " records."); - success = true; - } - } - - return stageTimeSeries; - } - - // ------------------------------------------------------- - - // ------------------------------------------------------- - public IrregularTimeSeries loadObservedStageTimeSeriesByTsOld( - String locationId, String pe, int duration, String typeSource) { - String header = "DataMgr.loadObservedStageTimeSeriesByTs(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries( - MeasuringUnit.feet); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - _millisPerYear; - long lateTime = currentTime + _millisPerYear; - // String earlyTimeString = - // DbTimeHelper.getDateTimeStringFromLongTime(earlyTime); - // String lateTimeString = - // DbTimeHelper.getDateTimeStringFromLongTime(lateTime); - String earlyTimeString = "2001-01-01 00:00:00"; - String lateTimeString = "3001-01-01 00:00:00"; - - /* - * String whereClause = " WHERE lid = '" + locationId + "'" + - * " AND pe = '" + pe + "'" + " AND dur = " + duration + " AND ts = '" + - * typeSource + "'" + " AND extremum = 'Z' ORDER by obstime ASC"; - */ - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + pe + "'" + " AND dur = " + duration - + " AND ts = '" + typeSource + "'" + " AND extremum = 'Z'" - + " AND shef_qual_code != 'F' "; - - try { - CodeTimer timer = new CodeTimer(); - timer.start(); - _db.getStatement().execute("SET EXPLAIN ON"); - recordList = table.select(whereClause); - _db.getStatement().execute("SET EXPLAIN OFF"); - timer.stop(header + "Height select with " + whereClause - + "\n took "); - - for (int i = 0; i < recordList.size(); i++) { - record = (HeightRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), MeasuringUnit.feet); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadObservedDischargeTimeSeries(String locationId) - - { - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries( - MeasuringUnit.cfs); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND dur = 0" + " AND extremum = 'Z'" - + " AND quality_code >= " + _questionable_bad_threshold; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (DischargeRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), MeasuringUnit.cfs); - - dischargeTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return dischargeTimeSeries; - - } - - // ----------------------------------------------------------------------------------- - public IrregularTimeSeries loadObservedDischargeTimeSeriesByTsOld( - String locationId, String pe, int duration, String typeSource) { - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries( - MeasuringUnit.cfs); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + pe + "'" + " AND dur = " + duration - + " AND ts = '" + typeSource + "'" - + " AND extremum = 'Z' ORDER by obstime ASC"; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (DischargeRecord) recordList.get(i); - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), MeasuringUnit.cfs); - - dischargeTimeSeries.insertMeasurement(measurement); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return dischargeTimeSeries; - - } - - // ------------------------------------------------------- - public IrregularTimeSeries loadObservedDischargeTimeSeriesOld( - String locationId) { - // return the best observed discharge time series available, that - // based on ts_rank usage - - IrregularTimeSeries dischargeTimeSeries = null; - - String pe = "QR"; - int duration = 0; - - String[] preferredObsTsArray = loadPreferredObsTypeSourceArray( - locationId, pe, duration); - - boolean success = false; - - for (int i = 0; i < preferredObsTsArray.length && !success; i++) { - String ts = preferredObsTsArray[i]; - dischargeTimeSeries = loadObservedDischargeTimeSeriesByTsOld( - locationId, pe, duration, ts); - if (dischargeTimeSeries.getMeasurementCount() > 0) { - success = true; - } - } - - return dischargeTimeSeries; - } - - // ------------------------------------------------------- - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - String pe) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "DataMgr.loadFcstStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + pe + "'" + " ORDER BY basistime DESC "; - - long originalBasisTime = 0; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (FcstHeightRecord) recordList.get(i); - - if (i == 0) { - originalBasisTime = record.getBasistime(); - } else { - if (record.getBasistime() != originalBasisTime) { - break; - } - } - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), unit); - - stageTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + - // measurement); - - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return stageTimeSeries; - } - - // ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - String pe) { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstDischargeTimeSeries(): "; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + pe + "'" + " ORDER BY basistime DESC "; - - long originalBasisTime = 0; - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (FcstDischargeRecord) recordList.get(i); - - if (i == 0) { - originalBasisTime = record.getBasistime(); - } else { - if (record.getBasistime() != originalBasisTime) { - break; - } - } - - // don't let the missing values be included - if (record.getValue() != missingValue) { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + - // measurement); - - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return dischargeTimeSeries; - } - - // --------------------------------------------------------------------------------------------- - - public Measurement _unused_getHeightMeasurement2(String locationId) { - RiverStatusTable table = new RiverStatusTable(_db); - RiverStatusRecord record = null; - List recordList = null; - Measurement measurement = null; - - String whereClause = " WHERE lid = '" + locationId + "'"; - - try { - recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (RiverStatusRecord) recordList.get(0); - - measurement = new Measurement(record.getValue(), - MeasuringUnit.feet); - } - } catch (Exception e) { - System.err.println("error retrieving RiverStatusRecord " - + whereClause); - e.printStackTrace(); - } - - return measurement; - - } - - // ------------------------------------------------------- - - public SacSmaParameters loadSacSmaParameters(String basinId, - long modelRunStartTime) { - String header = "DataMgr.getSacSmaParameters(): "; - SacSmaParameters sacParams = null; - - SacSmaParamsTable table = new SacSmaParamsTable(_db); - - String whereClause = "WHERE basin_id = '" + basinId - + "' ORDER by validtime DESC"; - - try { - List recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - SacSmaParamsRecord record = (SacSmaParamsRecord) recordList - .get(i); - - if (record.getValidtime() <= modelRunStartTime) { - // String dateTime = - // DbTimeHelper.getDateTimeStringFromLongTime(record.getValidtime()); - - // System.out.println(header + " validtime found = " + - // dateTime); - sacParams = new SacSmaParameters(); - setSacSmaParametersFromRecord(sacParams, record); - break; - } - // else, keep looking for a record before the modelRunStartTime - } - } catch (SQLException e) { - logSQLException(e); - } - return sacParams; - } - - // ------------------------------------------------------- - public void setSacSmaParametersFromRecord(SacSmaParameters sacParams, - SacSmaParamsRecord record) { - - sacParams.setBasinId(record.getBasin_id()); - sacParams.setSource(record.getSource()); - sacParams.setValidTime(record.getValidtime()); - sacParams.setPostingTime(record.getPostingtime()); - - sacParams.setUztwm(record.getUztwm()); - sacParams.setUzfwm(record.getUzfwm()); - sacParams.setUzk(record.getUzk()); - - sacParams.setPctim(record.getPctim()); - - sacParams.setAdimp(record.getAdimp()); - - sacParams.setRiva(record.getRiva()); - - sacParams.setZperc(record.getZperc()); - sacParams.setRexp(record.getRexp()); - sacParams.setLztwm(record.getLztwm()); - sacParams.setLzfsm(record.getLzfsm()); - - sacParams.setLzfpm(record.getLzfpm()); - - sacParams.setLzsk(record.getLzsk()); - sacParams.setLzpk(record.getLzpk()); - - sacParams.setPfree(record.getPfree()); - - sacParams.setRserv(record.getRserv()); - sacParams.setSide(record.getSide()); - - sacParams.setPeadj(record.getPeadj()); - sacParams.setPxadj(record.getPxadj()); - sacParams.setEfc(record.getEfc()); - - return; - } - - // ------------------------------------------------------- - public SacSmaState loadSacSmaState(String basinId, long modelRunStartTime) { - SacSmaState sacState = loadSacSmaState(basinId, null, modelRunStartTime); - - return sacState; - } - - // ------------------------------------------------------- - - public SacSmaState loadSacSmaState(String basinId, String source, - long modelRunStartTime) { - // returns null when no state is found - String header = "DataMgr.getSacSmaState(): "; - SacSmaState sacState = null; - SacSmaStateTable table = new SacSmaStateTable(_db); - - String sourceClause = null; - - if (source == null) { - sourceClause = ""; - } else // source is not null - { - sourceClause = " AND source = '" + source + "'"; - } - - String whereClause = "WHERE basin_id = '" + basinId + "'" - + sourceClause + " ORDER by validtime DESC"; - - try { - List recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - SacSmaStateRecord record = (SacSmaStateRecord) recordList - .get(i); - - if (record.getValidtime() <= modelRunStartTime) { - String dateTime = DbTimeHelper - .getDateTimeStringFromLongTime(record - .getValidtime()); - - System.out.println(header + " validtime found = " - + dateTime); - - sacState = new SacSmaState(); - setSacSmaStateFromRecord(sacState, record); - break; - } - // else, keep looking for a record with a validtime before the - // modelRunStartTime - } - } catch (SQLException e) { - logSQLException(e); - } - - return sacState; - } - - public SacSmaState oldLoadSacSmaState(String basinId, long modelRunStartTime) { - // returns null when no state is found - String header = "DataMgr.getSacSmaState(): "; - SacSmaState sacState = null; - - SacSmaStateTable table = new SacSmaStateTable(_db); - - String whereClause = "WHERE basin_id = '" + basinId - + "' ORDER by validtime DESC"; - - try { - List recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - SacSmaStateRecord record = (SacSmaStateRecord) recordList - .get(i); - - if (record.getValidtime() <= modelRunStartTime) { - String dateTime = DbTimeHelper - .getDateTimeStringFromLongTime(record - .getValidtime()); - - System.out.println(header + " validtime found = " - + dateTime); - - sacState = new SacSmaState(); - setSacSmaStateFromRecord(sacState, record); - break; - } - // else, keep looking for a record with a validtime before the - // modelRunStartTime - } - } catch (SQLException e) { - logSQLException(e); - } - - return sacState; - } - - // ------------------------------------------------------- - public long loadTimeOfBestRecentSacState(String locationId) { - long bestTime = 0; - - long hourLimit = 25; // a little over 24 hours - - long preferredSourceValidTime = 0; - long allSourceValidTime = 0; - - // - SSHPConfig config = this.getSSHPConfig(locationId); - String basinId = null; - String preferredSource = null; - - if (config != null) { - basinId = config.getBasinId(); - preferredSource = config.getSourcePref(); - } else { - throw new Error( - "DataMgr.getTimeOfBestRecentState(): no SSHPConfig record for locationId = " - + locationId); - } - - String preferredSourceWhereClause = " WHERE basin_id = '" + basinId - + "' " + " AND source = '" + preferredSource + "' " - + " ORDER BY validtime DESC "; - - String allSourceWhereClause = " WHERE basin_id = '" + basinId + "' " - + " ORDER BY validtime DESC "; - - SacSmaStateTable table = new SacSmaStateTable(_db); - - try { - - // select the most recent record with the preferred source - List preferredRecordList = table.selectNRecords( - preferredSourceWhereClause, 1); - - if (preferredRecordList.size() > 0) { - SacSmaStateRecord record = (SacSmaStateRecord) preferredRecordList - .get(0); - - preferredSourceValidTime = record.getValidtime(); - } - - // select all the records, regardless of source - List allRecordList = table.selectNRecords(allSourceWhereClause, 1); - - if (allRecordList.size() > 0) { - SacSmaStateRecord record = (SacSmaStateRecord) allRecordList - .get(0); - - allSourceValidTime = record.getValidtime(); - } - - // get current system time - long currentTime = System.currentTimeMillis(); - - // select the preferredSourceValidTime as the best if it is within - // the time window - long diffTime = currentTime - preferredSourceValidTime; - - if (diffTime < _millisPerHour * hourLimit) { - bestTime = preferredSourceValidTime; - } else // the preferred is not available, so use the next best thing - { - bestTime = allSourceValidTime; - } - - } catch (SQLException e) { - logSQLException(e); - } - - return bestTime; - } - - // ------------------------------------------------------- - public SacSmaState loadBestRecentSacState(String locationId) { - - SacSmaState preferredSourceState = null; - SacSmaState allSourceState = null; - SacSmaState bestState = null; - - long bestTime = 0; - - long hourLimit = 25; // a little over 24 hours - - long preferredSourceValidTime = 0; - long allSourceValidTime = 0; - - // - SSHPConfig config = this.getSSHPConfig(locationId); - String basinId = null; - String preferredSource = null; - - if (config != null) { - basinId = config.getBasinId(); - preferredSource = config.getSourcePref(); - } else { - throw new Error( - "DataMgr.getTimeOfBestRecentState(): no SSHPConfig record for locationId = " - + locationId); - } - - String preferredSourceWhereClause = " WHERE basin_id = '" + basinId - + "' " + " AND source = '" + preferredSource + "' " - + " ORDER BY validtime DESC "; - - String allSourceWhereClause = " WHERE basin_id = '" + basinId + "' " - + " ORDER BY validtime DESC "; - - SacSmaStateTable table = new SacSmaStateTable(_db); - - try { - - // select the most recent record with the preferred source - List preferredRecordList = table.selectNRecords( - preferredSourceWhereClause, 1); - - if (preferredRecordList.size() > 0) { - SacSmaStateRecord record = (SacSmaStateRecord) preferredRecordList - .get(0); - - preferredSourceState = getSacSmaStateFromRecord(record); - preferredSourceValidTime = record.getValidtime(); - } - - // select all the records, regardless of source - List allRecordList = table.selectNRecords(allSourceWhereClause, 1); - - if (allRecordList.size() > 0) { - SacSmaStateRecord record = (SacSmaStateRecord) allRecordList - .get(0); - allSourceState = getSacSmaStateFromRecord(record); - - allSourceValidTime = record.getValidtime(); - } - - // get current system time - long currentTime = System.currentTimeMillis(); - - // select the preferredSourceValidTime as the best if it is within - // the time window - long diffTime = currentTime - preferredSourceValidTime; - - if (diffTime < _millisPerHour * hourLimit) { - bestState = preferredSourceState; - bestTime = preferredSourceValidTime; - } else // the preferred is not available, so use the next best thing - { - bestState = allSourceState; - bestTime = allSourceValidTime; - } - - } catch (SQLException e) { - logSQLException(e); - } - - return bestState; - } - - // ------------------------------------------------------- - - public long getTimeOfBestRecentFFH(String locationId, String basinId) { - long bestTime = 0; - - long currentTime = System.currentTimeMillis(); - AbsTimeMeasurement ffhMeasurement = loadMostCurrentFfhMeasurement( - locationId, basinId, currentTime); - if (ffhMeasurement != null) { - bestTime = ffhMeasurement.getTime(); - } - - return bestTime; - } - - // ------------------------------------------------------- - - public long getLatestHourTime() { - return TimeHelper.truncateTimeInMillisToNearestHour( - System.currentTimeMillis(), 1); - } - - // ------------------------------------------------------- - - public void setSacSmaStateFromRecord(SacSmaState sacState, - SacSmaStateRecord record) { - - sacState.setBasinId(record.getBasin_id()); - sacState.setSource(record.getSource()); - sacState.setBasisTime(record.getBasistime()); - sacState.setValidTime(record.getValidtime()); - sacState.setPostingTime(record.getPostingtime()); - - sacState.setUztwc(record.getUztwc()); - sacState.setUzfwc(record.getUzfwc()); - sacState.setLztwc(record.getLztwc()); - sacState.setLzfsc(record.getLzfsc()); - sacState.setLzfpc(record.getLzfpc()); - sacState.setAdimc(record.getAdimc()); - - // System.out.println("DataMgr.setSacSmaStageFromRecord() sacState = " + - // sacState); - - return; - } - - // ------------------------------------------------------- - /* - * - * public void testGeneratedCodeWithNulls() { TestHeightTable heightTable = - * new TestHeightTable(_db); TestHeightRecord record = null; List recordList - * = null; CodeTimer timer = new CodeTimer(); - * - * try { timer.start(); recordList = - * heightTable.select("where lid = 'BLUO2' order by obstime DESC "); - * timer.stop("after Select from Height Table"); - * - * if (recordList.size() > 0) { record = (TestHeightRecord) - * recordList.get(0); System.out.println("1 retrieved record = " + record); - * - * heightTable.delete("Where lid = 'CHIP1'"); - * heightTable.delete("Where lid = 'CHIP3'"); - * - * record.setLid("CHIP1"); - * - * heightTable.insert(record); - * - * - * recordList = heightTable.select("where lid = 'CHIP1'" ); record = - * (TestHeightRecord) recordList.get(0); - * - * System.out.println("2 retrieved record = " + record); - * - * TestHeightRecord newRecord = new TestHeightRecord(record); - * - * System.out.println("3 after copy record orig = " + record); - * System.out.println("4 after copy record new = " + newRecord); - * - * newRecord.setLid("CHIP3"); newRecord.setNullDur(true); - * - * heightTable.update(record, newRecord ); - * - * recordList = heightTable.select("where lid = '" + newRecord.getLid() + - * "'" ); record = (TestHeightRecord) recordList.get(0); - * - * System.out.println("5 retrieved updated record with null Dur = " + - * record); - * - * // insertOrUpdate Test newRecord.setLid("Chip4"); - * heightTable.insertOrUpdate(newRecord); - * - * recordList = heightTable.select("where lid = '" + newRecord.getLid() + - * "'" ); record = (TestHeightRecord) recordList.get(0); - * - * System.out.println("6 retrieved insertedOrUpdated record = " + record); - * - * - * timer.start(); Measurement height2Measurement = - * _dataMgr.getHeightMeasurementWithShortCircuit(_locationId); - * timer.stop("AppController.runModel(): Short Circuited Height retrieval took" - * ); - * - * - * timer.start(); heightMeasurement = - * _dataMgr.getHeightMeasurement(_locationId); - * timer.stop("AppController.runModel(): Normal Height retrieval took"); - * heightMeasurement.convert(MeasuringUnit.feet); - * - * - * - * } - * - * } catch (SQLException e) { logSQLException(e); } - * - * } - */ - // ------------------------------------------------------- - public void testGeneratedCode() { - HeightTable heightTable = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - CodeTimer timer = new CodeTimer(); - - try { - timer.start(); - recordList = heightTable - .select("where lid = 'BLUO2' order by obstime DESC "); - timer.stop("after Select from Height Table"); - - if (recordList.size() > 0) { - record = (HeightRecord) recordList.get(0); - System.out.println("1 retrieved record = " + record); - - heightTable.delete("Where lid = 'CHIP1'"); - heightTable.delete("Where lid = 'CHIP3'"); - - record.setLid("CHIP1"); - - heightTable.insert(record); - - recordList = heightTable.select("where lid = 'CHIP1'"); - record = (HeightRecord) recordList.get(0); - - System.out.println("2 retrieved record = " + record); - - HeightRecord newRecord = new HeightRecord(record); - System.out.println("3 after copy record orig = " + record); - System.out.println("4 after copy record new = " + newRecord); - - newRecord.setLid("CHIP3"); - - heightTable.update(record, newRecord); - - recordList = heightTable.select("where lid = '" - + newRecord.getLid() + "'"); - record = (HeightRecord) recordList.get(0); - - System.out.println("5 retrieved updated record = " + record); - - // insertOrUpdate Test - newRecord.setLid("Chip4"); - heightTable.insertOrUpdate(newRecord); - - recordList = heightTable.select("where lid = '" - + newRecord.getLid() + "'"); - record = (HeightRecord) recordList.get(0); - - System.out.println("6 retrieved insertedOrUpdated record = " - + record); - - /* - * timer.start(); Measurement height2Measurement = - * _dataMgr.getHeightMeasurementWithShortCircuit(_locationId); - * timer.stop( - * "AppController.runModel(): Short Circuited Height retrieval took" - * ); - * - * - * timer.start(); heightMeasurement = - * _dataMgr.getHeightMeasurement(_locationId); timer.stop( - * "AppController.runModel(): Normal Height retrieval took"); - * heightMeasurement.convert(MeasuringUnit.feet); - */ - - } - - } catch (SQLException e) { - logSQLException(e); - } - - } - - // ------------------------------------------------------- - - // ------------------------------------------------------- - private void logSQLException(SQLException exception) { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " - + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - // ------------------------------------------------------- - public SigRiverLevels loadSigRiverLevels(String locationId) { - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (RiverstatRecord) recordList.get(0); - - String primaryPe = record.getPrimary_pe(); - if (primaryPe == null) { - primaryPe = "HG"; - } - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - - levels = new SigRiverLevels(locationId, primaryPe, floodStage, - actionStage, floodFlow, actionFlow); - - loadFloodCategories(levels); - } - } catch (SQLException e) { - logSQLException(e); - } - - return levels; - } - - // ------------------------------------------------------- - private void loadFloodCategories(SigRiverLevels levels) { - FloodcatTable table = new FloodcatTable(_db); - FloodcatRecord record = null; - - String whereClause = "WHERE lid = '" + levels.getLocationId() + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (FloodcatRecord) recordList.get(0); - - levels.setMinorFloodFlow(record.getMinor_flow()); - levels.setModerateFloodFlow(record.getModerate_flow()); - levels.setMajorFloodFlow(record.getMajor_flow()); - - levels.setMinorFloodStage(record.getMinor_stage()); - levels.setModerateFloodStage(record.getModerate_stage()); - levels.setMajorFloodStage(record.getMajor_stage()); - } - } catch (SQLException e) { - logSQLException(e); - } - - return; - } - - // ------------------------------------------------------- - public String[] loadPhysicalElementArray(char firstLetterOfPhysicalElement) { - String[] peArray = null; - - ShefPeTable table = new ShefPeTable(_db); - ShefPeRecord record = null; - - String primaryPe = null; - - String whereClause = "WHERE pe LIKE '" + firstLetterOfPhysicalElement - + "%' ORDER BY pe"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - for (int i = 0; i < recordList.size(); i++) { - record = (ShefPeRecord) recordList.get(i); - if (i == 0) { - peArray = new String[recordList.size()]; - } - peArray[i] = record.getPe(); - } - } - } catch (SQLException e) { - logSQLException(e); - } - - return peArray; - } - - // ------------------------------------------------------- - public String loadPrimaryPe(String locationId) { - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - String primaryPe = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try { - List recordList = table.select(whereClause); - if (recordList.size() > 0) { - record = (RiverstatRecord) recordList.get(0); - - primaryPe = record.getPrimary_pe(); - } - } catch (SQLException e) { - logSQLException(e); - } - - return primaryPe; - } - - // ------------------------------------------------------- - - public long getLatestObsTimeForMAPPreprocessor() { - ArealObsTable table = new ArealObsTable(_db); - - ArealObsRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - long latestPostingTime = 0; - - // String whereClause = "WHERE product_id like 'SSHP%' " + - // " ORDER BY postingtime DESC"; - - String whereClause = "WHERE product_id = 'SSHP_MAP' " - + " ORDER BY obstime DESC"; - - try { - recordList = table.selectNRecords(whereClause, 1); - - if (recordList.size() > 0) { - record = (ArealObsRecord) recordList.get(0); - // latestPostingTime = record.getPostingtime(); - latestPostingTime = record.getObstime(); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return latestPostingTime; - } - - // ----------------------------------------------------------------------------------- - public long getLatestPostingTimeForMAPPreprocessor() { - ArealObsTable table = new ArealObsTable(_db); - - ArealObsRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - long latestPostingTime = 0; - - String whereClause = "WHERE product_id like 'SSHP_MAP' " - + " ORDER BY postingtime DESC"; - - try { - recordList = table.selectNRecords(whereClause, 1); - - if (recordList.size() > 0) { - record = (ArealObsRecord) recordList.get(0); - latestPostingTime = record.getPostingtime(); - // latestPostingTime = record.getObstime(); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return latestPostingTime; - } - - // ----------------------------------------------------------------------------------- - - public RegularTimeSeries loadObsMapTimeSeriesFromDb(String areaId) { - String header = "DataMgr.loadObsMapTimeSeriesFromDb(): "; - - MeasuringUnit precipUnit = MeasuringUnit.inches; - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - String whereClause = "WHERE lid = '" + areaId - + "' AND dur = 1001 AND pe='PP' AND ts = 'PM' " - + " ORDER BY obstime ASC"; - - // System.out.println(header + " where string = " + whereClause); - - long startTime = 0; - long endTime = 0; - - try { - recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (ArealObsRecord) recordList.get(0); - startTime = record.getObstime(); - - record = (ArealObsRecord) recordList.get(recordList.size() - 1); - endTime = record.getObstime(); - } else { - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - } - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - - // System.out.println(header + " startTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - // " endTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - - // String startTimeString = - // DbTimeHelper.getDateTimeStringFromLongTime(startTime); - // String endTimeString = - // DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - for (int i = 0; i < recordList.size(); i++) { - - record = (ArealObsRecord) recordList.get(i); - double value = record.getValue(); - long time = record.getObstime(); - - if ((time >= startTime) && (time <= endTime)) { - Measurement m = new Measurement(value, precipUnit); - - ts.setMeasurementByTime(m, time); - } else if (time > endTime) { - break; // done, since we went past the last one that we want - } - - } // end for - - } // end try - - catch (SQLException e) { - logSQLException(e); - - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - } - - return ts; - - } - - // ---------------------------------------------------------------------------------- - - public RegularTimeSeries loadObsMapTimeSeriesFromDb_old(String areaId) { - // we don't use ProcValue anymore for this; we use ArealObsPrecip. - String header = "DataMgr.loadObsMapTimeSeriesFromDb(): "; - - MeasuringUnit precipUnit = MeasuringUnit.inches; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - String whereClause = "WHERE lid = '" + areaId - + "' AND dur = 1001 AND pe='PP' AND ts = 'PM' " - + " ORDER BY obstime ASC"; - - // System.out.println(header + " where string = " + whereClause); - - long startTime = 0; - long endTime = 0; - - try { - recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (ProcValueRecord) recordList.get(0); - startTime = record.getObstime(); - - record = (ProcValueRecord) recordList - .get(recordList.size() - 1); - endTime = record.getObstime(); - } else { - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - } - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - - // System.out.println(header + " startTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - // " endTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - - // String startTimeString = - // DbTimeHelper.getDateTimeStringFromLongTime(startTime); - // String endTimeString = - // DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - for (int i = 0; i < recordList.size(); i++) { - - record = (ProcValueRecord) recordList.get(i); - double value = record.getValue(); - long time = record.getObstime(); - - if ((time >= startTime) && (time <= endTime)) { - Measurement m = new Measurement(value, precipUnit); - - ts.setMeasurementByTime(m, time); - } else if (time > endTime) { - break; // done, since we went past the last one that we want - } - - } // end for - - } // end try - - catch (SQLException e) { - logSQLException(e); - - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - } - - return ts; - - } - - // ------------------------------------------------------- - - // ------------------------------------------------------- - private RegularTimeSeries loadFcstMapTimeSeriesByTs(String areaId, - long forecastStartTime, String typeSource, - BooleanHolder successHolder) { - String header = "DataMgr.loadFcstMapTimeSeriesByTs(): "; - - MeasuringUnit precipUnit = MeasuringUnit.inches; - - // System.out.println(header + "running"); - - ArealFcstTable table = new ArealFcstTable(_db); - ArealFcstRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - String whereClause = "WHERE lid = '" + areaId - + "' AND dur = 1001 AND pe= 'PP'" + " AND ts = '" + typeSource - + "'" + " ORDER BY basistime DESC, validtime ASC"; - - // System.out.println(header + " where string = " + whereClause); - - long startTime = 0; - long endTime = 0; - - // initialize the fcst time series - startTime = forecastStartTime; - endTime = startTime; - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - - successHolder.setValue(false); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - - record = (ArealFcstRecord) recordList.get(i); - double value = record.getValue(); - long time = record.getValidtime(); - - if (time >= startTime) { - Measurement m = new Measurement(value, precipUnit); - - ts.setMeasurementByTime(m, time); - successHolder.setValue(true); - } else if (time > endTime) { - break; // done, since we went past the last one that we want - } - } // end for - - } // end try - - catch (SQLException e) { - logSQLException(e); - } - - return ts; - - } // end loadFcstMapTimeSeriesByTs() - // ------------------------------------------------------- - - public String[] loadPreferredFcstTypeSourceArray(String areaId, - String physicalElement, int duration) { - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - List recordList = null; - - String whereString = " WHERE lid = '" + areaId + "' AND pe = '" - + physicalElement + "' AND dur = " + duration - + " AND ts LIKE 'F%'" + " ORDER by ts_rank ASC "; - - String[] tsArray = new String[0]; - - try { - recordList = table.select(whereString); - - int lowestRank = 0; - - tsArray = new String[recordList.size()]; - for (int i = 0; i < recordList.size(); i++) { - record = (IngestFilterRecord) recordList.get(i); - - tsArray[i] = record.getTs(); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return tsArray; - - } - - // ------------------------------------------------------- - public RegularTimeSeries loadFcstMapTimeSeries(String areaId, - long forecastStartTime) { - String header = "DataMgr.loadFcstMapTimeSeries(): "; - - RegularTimeSeries fcstPrecipTimeSeries = null; - MeasuringUnit precipUnit = MeasuringUnit.inches; - - ArealFcstTable table = new ArealFcstTable(_db); - ArealFcstRecord record = null; - List recordList = null; - BooleanHolder successHolder = new BooleanHolder(false); - - String pe = "PP"; - int dur = 1001; - String[] preferredTypeSourceArray = loadPreferredFcstTypeSourceArray( - areaId, pe, dur); - boolean success = false; - - // in priority of the preferred sources, try to load the FCST MAP time - // series - // stop after successfully loading the time series - for (int i = 0; i < preferredTypeSourceArray.length && !success; i++) { - String preferredTypeSource = preferredTypeSourceArray[i]; - RegularTimeSeries tempFcstPrecipTimeSeries = loadFcstMapTimeSeriesByTs( - areaId, forecastStartTime, preferredTypeSource, - successHolder); - - if (successHolder.getValue() == true) { - fcstPrecipTimeSeries = tempFcstPrecipTimeSeries; - // System.out.println("chosen preferredTypeSource = " + - // preferredTypeSource); - success = true; - } else { - // System.out.println("NOT chosen preferredTypeSource = " + - // preferredTypeSource); - } - } - - if (!success) { - fcstPrecipTimeSeries = new RegularTimeSeries(forecastStartTime, - forecastStartTime, 1, precipUnit); - } - - return fcstPrecipTimeSeries; - } - - // ------------------------------------------------------- - - public RegularTimeSeries loadFileMapTimeSeries(String filePath) { - String header = "DataMgr.loadFileMapTimeSeries(): "; - - TimeSeriesFileManager reader = new TimeSeriesFileManager(); - - RegularTimeSeries precipTimeSeries = null; - MeasuringUnit precipUnit = MeasuringUnit.inches; - - precipTimeSeries = reader.readRegularTimeSeries(filePath, - MeasuringUnit.inches); - - return precipTimeSeries; - } - - // ------------------------------------------------------- - - public RegularTimeSeries loadFcstMapTimeSeries_old(String areaId, - long forecastStartTime) { - String header = "DataMgr.loadFcstMapTimeSeries(): "; - - RegularTimeSeries fcstPrecipTimeSeries = null; - MeasuringUnit precipUnit = MeasuringUnit.inches; - - FcstPrecipTable table = new FcstPrecipTable(_db); - FcstPrecipRecord record = null; - List recordList = null; - BooleanHolder successHolder = new BooleanHolder(false); - - String pe = "PP"; - int dur = 1001; - String[] preferredTypeSourceArray = loadPreferredFcstTypeSourceArray( - areaId, pe, dur); - boolean success = false; - - for (int i = 0; i < preferredTypeSourceArray.length; i++) { - String preferredTypeSource = preferredTypeSourceArray[i]; - RegularTimeSeries tempFcstPrecipTimeSeries = loadFcstMapTimeSeriesByTs( - areaId, forecastStartTime, preferredTypeSource, - successHolder); - - if (successHolder.getValue() == true) { - fcstPrecipTimeSeries = tempFcstPrecipTimeSeries; - // System.out.println("chosen preferredTypeSource = " + - // preferredTypeSource); - success = true; - break; - } else { - // System.out.println("NOT chosen preferredTypeSource = " + - // preferredTypeSource); - } - } - - if (!success) { - fcstPrecipTimeSeries = new RegularTimeSeries(forecastStartTime, - forecastStartTime, 1, precipUnit); - } - - return fcstPrecipTimeSeries; - } - - // ------------------------------------------------------- - - // ------------------------------------------------------- - /* - * public RegularTimeSeries loadMapTimeSeriesFromFiles(String areaId, long - * startTime, long endTime) { - * - * String header = "DataMgr.getMapTimeSeriesFromFiles(): "; - * - * _logger.log(header + " startTime = " + - * DbTimeHelper.getDateTimeStringFromLongTime(startTime) + " endTime = " + - * DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - * - * CodeTimer timer = new CodeTimer(_logger); - * - * timer.start(); MAP map = new MAP(_db, areaId, startTime, endTime); - * timer.stop("reading xmrg files for " + areaId + " took"); - * - * RegularTimeSeries ts = map.getMpeMapTimeSeries(); - * - * - * - * return ts; - * - * } - */ - - // ------------------------------------------------------- - public void saveMapTimeSeries_old(String areaId, RegularTimeSeries ts, - Set timeSet, Logger localLogger) { - // we don't use ProcValue anymore for this; we use ArealObsPrecip. - String header = "DataMgr.saveMapTimeSeries(): "; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - ProcTsDescriptor descriptor = new ProcTsDescriptor("ProcValue"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - saveToIngestFilterIfNeeded(descriptor); - - // initialize the constant record fields - long productTime = System.currentTimeMillis(); - - record = new ProcValueRecord(); - record.setLid(areaId); - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); // one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_T2"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short) 0); - record.setShef_qual_code("Z"); - - for (int i = 0; i < ts.getMeasurementCount(); i++) { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - - if (timeSet.contains(new Long(time))) { - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try { - if (value != MISSING) { - if (value > 0.0) { - localLogger.log(header + "record with precip = " - + record); - } else { - // localLogger.log(header + - // "record with no precip = " + record); - } - - // only save records that might be different from before - // see the outer if block - table.insertOrUpdate(record); - - } else { - /* - * String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime(time); - * localLogger.log(header + - * "missing data for period ending at " + timeString + - * ", so not saving (relying on previously saved data)" - * ); - */ - } - } catch (SQLException e) { - logSQLException(e); - } - } - } // end for - } - - // ------------------------------------------------------- - public void saveMapTimeSeries(String areaId, RegularTimeSeries ts, - Set timeSet, Logger localLogger) { - String header = "DataMgr.saveMapTimeSeries(): "; - - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - saveToIngestFilterIfNeeded(descriptor); - - // initialize the constant record fields - long productTime = System.currentTimeMillis(); - - record = new ArealObsRecord(); - record.setLid(areaId); - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); // one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_T2"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short) 0); - record.setShef_qual_code("Z"); - - for (int i = 0; i < ts.getMeasurementCount(); i++) { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - - if (timeSet.contains(new Long(time))) { - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try { - if (value != MISSING) { - if (value > 0.0) { - localLogger.log(header + "record with precip = " - + record); - } else { - // localLogger.log(header + - // "record with no precip = " + record); - } - - // only save records that might be different from before - // see the outer if block - table.insertOrUpdate(record); - - } else { - /* - * String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime(time); - * localLogger.log(header + - * "missing data for period ending at " + timeString + - * ", so not saving (relying on previously saved data)" - * ); - */ - } - } catch (SQLException e) { - logSQLException(e); - } - } - } // end for - } - - // ---------------------------------------------------------------------------------- - public void saveMapTimeSeries_old(String areaId, RegularTimeSeries ts, - Logger localLogger) { - // we don't use ProcValue anymore for this; we use ArealObsPrecip. - String header = "DataMgr.saveMapTimeSeries(): "; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ProcValue"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - saveToIngestFilterIfNeeded(descriptor); - - long productTime = System.currentTimeMillis(); - - // initial the record object - record = new ProcValueRecord(); - record.setLid(areaId); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); // one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_MAP"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short) 0); - record.setShef_qual_code("Z"); - - for (int i = 0; i < ts.getMeasurementCount(); i++) { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try { - if (value != MISSING) { - if (value > 0.0) { - localLogger.log(header + "record with precip = " - + record); - } else { - // localLogger.log(header + "record with no precip = " + - // record); - } - - table.insertOrUpdate(record); - } else { - /* - * String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime(time); - * localLogger.log(header + - * "missing data for period ending at " + timeString + - * ", so not saving (relying on previously saved data)"); - */ - } - } catch (SQLException e) { - logSQLException(e); - } - } // end for - } - - // ---------------------------------------------------------------------------------- - public void saveMapTimeSeriesToFile(RegularTimeSeries regularTimeSeries, - String filePath) { - _reader.saveRegularTimeSeries(regularTimeSeries, filePath); - - return; - } - - // ---------------------------------------------------------------------------------- - - public void saveMapTimeSeries(String areaId, RegularTimeSeries ts, - Logger localLogger) { - String header = "DataMgr.saveMapTimeSeries(): "; - - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - saveToIngestFilterIfNeeded(descriptor); - - long productTime = System.currentTimeMillis(); - - // initial the record object - record = new ArealObsRecord(); - record.setLid(areaId); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); // one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_MAP"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short) 0); - record.setShef_qual_code("Z"); - - for (int i = 0; i < ts.getMeasurementCount(); i++) { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try { - if (value != MISSING) { - if (value > 0.0) { - localLogger.log(header + "record with precip = " - + record); - } else { - // localLogger.log(header + "record with no precip = " + - // record); - } - - table.insertOrUpdate(record); - } else { - /* - * String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime(time); - * localLogger.log(header + - * "missing data for period ending at " + timeString + - * ", so not saving (relying on previously saved data)"); - */ - } - } catch (SQLException e) { - logSQLException(e); - } - } // end for - } - - // ------------------------------------------------------- - public void saveMapRowsToIngestFilterAsNeeded(List areaIdList) { - CodeTimer timer = new CodeTimer(_logger); - timer.start(); - - String areaId = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - // select all the MAP rows to Check - String whereString = "WHERE pe = '" + descriptor.getPe() - + "' AND dur = " + descriptor.getDur() + " AND extremum = '" - + descriptor.getExtremum() + "' AND ts = '" - + descriptor.getTs() + "'"; - - System.out.println("whereString = " + whereString); - - IngestFilterRecord record; - IngestFilterTable table = new IngestFilterTable(_db); - List recordList = null; - HashSet filterSet = new HashSet(); - - // select from the ingestfilter table and - // add all of the lids to a hashset - try { - recordList = table.select(whereString); - for (int i = 0; i < recordList.size(); i++) { - record = (IngestFilterRecord) recordList.get(i); - filterSet.add(record.getLid()); - _logger.log("Adding " + record.getLid() + " to the filter set"); - } - } catch (SQLException e) { - logSQLException(e); - } - - // for each areaId in the list, - // check to see if it is in the hashset (which indicates it is already - // in the db) - // if not, then add it to the db - for (int i = 0; i < areaIdList.size(); i++) { - areaId = (String) areaIdList.get(i); - - System.out.println("areaId to check = :" + areaId + ":"); - - if (!filterSet.contains(areaId)) { - // add it to the db - descriptor.setLid(areaId); - saveToIngestFilter(descriptor); - } - } - - timer.stop("DataMgr.saveMapRowsToIngestFilterAsNeeded for all ids took "); - - } - - // ------------------------------------------------------------------------------------------------- - public void saveMapRowToIngestFilterIfNeeded_unused(String areaId) { - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - CodeTimer timer = new CodeTimer(_logger); - - timer.start(); - saveToIngestFilterIfNeeded(descriptor); - timer.stop("DataMgr.saveToIngestFilterIfNeeded() for " + areaId - + " took "); - - } - - // ------------------------------------------------------------------------------------------------- - public void saveMapMeasurement(String areaId, Measurement mapMeasurement, - long time, Logger localLogger) { - MeasuringUnit dbPrecipUnit = MeasuringUnit.inches; - String header = "DataMgr.saveMapMeasurement(): "; - - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - - long productTime = System.currentTimeMillis(); - - double value = mapMeasurement.getValue(dbPrecipUnit); - - record = new ArealObsRecord(); - record.setLid(areaId); - - record.setObstime(time); - record.setValue(value); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); // one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_MAP"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short) 0); - record.setShef_qual_code("Z"); - - try { - if (value != MISSING) { - if (value > 0.0) { - localLogger.log(header + "record with precip = " + record); - } else { - // localLogger.log(header + "record with no precip = " + - // record); - } - - table.insertOrUpdate(record); - - } else { - /* - * String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime(time); - * localLogger.log(header + "missing data for period ending at " - * + timeString + - * ", so not saving (relying on previously saved data)"); - */ - } - } catch (SQLException e) { - logSQLException(e); - } - - } // end saveMAPMeasurement - - // ------------------------------------------------------------------------------------------------- - public void saveMapMeasurement_old(String areaId, - Measurement mapMeasurement, long time, Logger localLogger) { - // we don't use ProcValue anymore for this; we use ArealObsPrecip. - MeasuringUnit dbPrecipUnit = MeasuringUnit.inches; - String header = "DataMgr.saveMapMeasurement(): "; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - - short durationCode = 1001; // one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - // make sure record is in ingestfilter - - long productTime = System.currentTimeMillis(); - - double value = mapMeasurement.getValue(dbPrecipUnit); - - record = new ProcValueRecord(); - record.setLid(areaId); - - record.setObstime(time); - record.setValue(value); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); // one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_T3"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short) 0); - record.setShef_qual_code("Z"); - - try { - if (value != MISSING) { - if (value > 0.0) { - localLogger.log(header + "record with precip = " + record); - } else { - // localLogger.log(header + "record with no precip = " + - // record); - } - - table.insertOrUpdate(record); - - } else { - /* - * String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime(time); - * localLogger.log(header + "missing data for period ending at " - * + timeString + - * ", so not saving (relying on previously saved data)"); - */ - } - } catch (SQLException e) { - logSQLException(e); - } - - } // end saveMAPMeasurement - - // ------------------------------------------------------- - public AbsTimeMeasurement loadMostCurrentFfhMeasurement(String lid, - String basinId, long endTime) { - Measurement measurement = null; - AbsTimeMeasurement ffhMeasurement = null; - - List ffhDescriptorList = loadFfhDescriptorList(lid, basinId); - for (int i = 0; i < ffhDescriptorList.size(); i++) { - FFHDescriptor descriptor = (FFHDescriptor) ffhDescriptorList.get(i); - if (descriptor.getTime() <= endTime) { - measurement = descriptor.getFfhMeasurement(); - ffhMeasurement = new AbsTimeMeasurement(measurement, - descriptor.getTime()); - break; - } - } - - return ffhMeasurement; - } - - // ------------------------------------------------------- - /* - * public AbsTimeMeasurement loadMostCurrentFfhMeasurement(String lid, long - * endTime) { //String header = "DataMgr.getFfgValue(): "; - * - * AbsTimeMeasurement measurement = null; double ffhValue = -1.0; - * - * ContingencyValueTable table = new ContingencyValueTable(this._db); - * ContingencyValueRecord record = null; - * - * // Go to UnitGraph table to get basin id String whereClause = null; // - * " WHERE lid='" + basinId + "' "; - * - * List recordList = null; - * - * // Go to ContingencyValue table to get the FFH //whereClause = - * " WHERE lid='" + lid + "'" + // - * " AND dur=1001 AND pe='PP' AND ts IN ('CF','CP') " + // - * " AND validtime > (TODAY - 5) " + // " ORDER BY validtime DESC, ts "; - * - * whereClause = " WHERE lid='" + lid + "'" + - * " AND dur=1001 AND pe='PP' AND ts IN ('CF','CP') " + - * " ORDER BY validtime DESC, basistime DESC, ts "; - * - * // System.out.println( "DataMgr.getFfhMeasurement.whereClause = " + - * whereClause ); - * - * try { recordList = table.select(whereClause); - * - * // find the value that is the latest that is before or equal to the end - * time for (int i = 0; i < recordList.size(); i++) { record = - * (ContingencyValueRecord) recordList.get(i); - * - * if (record.getValidtime() <= endTime) { ffhValue = record.getValue(); - * long time = record.getValidtime(); measurement = new - * AbsTimeMeasurement(ffhValue, time, MeasuringUnit.inches); break; //don't - * look anymore, since the first one is the one I want } } //end for i - * - * } catch(SQLException e) { logSQLException(e); } - * - * - * return measurement; } // end of loadFFHMeasurement method - */ - // ------------------------------------------------------------------------- - - public List loadFfhDescriptorList(String lid, String basinId) { - // String header = "DataMgr.getFfgValue(): "; - - FFHDescriptor descriptor = null; - AbsTimeMeasurement measurement = null; - double ffhValue = -1.0; - int durationCode = 0; - - ContingencyValueTable table = new ContingencyValueTable(this._db); - ContingencyValueRecord record = null; - - String whereClause = null; - - List recordList = null; - - List descriptorList = new ArrayList(); - - whereClause = " WHERE (lid='" - + lid - + "' OR lid = '" - + basinId - + "') " - + " AND dur in (1001, 1003, 1006) AND pe='PP' AND ts IN ('CF','CP') " - + " ORDER BY validtime DESC, basistime DESC, ts, dur "; - - long oldValidTime = 0; - String oldTypeSource = ""; - - try { - recordList = table.select(whereClause); - - // find the value that is the latest that is before or equal to the - // end time - for (int i = 0; i < recordList.size(); i++) { - record = (ContingencyValueRecord) recordList.get(i); - - long validTime = record.getValidtime(); - String typeSource = record.getTs(); - - oldValidTime = validTime; - oldTypeSource = typeSource; - - ffhValue = record.getValue(); - - measurement = new AbsTimeMeasurement(ffhValue, validTime, - MeasuringUnit.inches); - - durationCode = record.getDur(); - - boolean isGridded = false; - if (record.getTs().toUpperCase().equals("CF")) // areal - { - isGridded = false; - } else // gridded - { - isGridded = true; - } - - descriptor = new FFHDescriptor(lid, measurement, durationCode, - isGridded); - descriptorList.add(descriptor); - // System.out.println(" FFH record = " + record); - - } // end for i - - } catch (SQLException e) { - logSQLException(e); - } - - return descriptorList; - - } // end of load FFHDescriptor Listmethod - - // ------------------------------------------------------- - - public void saveSacState(SacSmaState sacSmaState) { - SacSmaStateTable table = new SacSmaStateTable(_db); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id(sacSmaState.getBasinId()); - record.setSource(sacSmaState.getSource()); - record.setValidtime(sacSmaState.getValidTime()); - record.setBasistime(sacSmaState.getBasisTime()); - - long currentTime = System.currentTimeMillis(); - - record.setPostingtime(currentTime); - - record.setUztwc(sacSmaState.getUztwc()); - record.setUzfwc(sacSmaState.getUzfwc()); - record.setLztwc(sacSmaState.getLztwc()); - record.setLzfsc(sacSmaState.getLzfsc()); - record.setLzfpc(sacSmaState.getLzfpc()); - record.setAdimc(sacSmaState.getAdimc()); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - public RegularTimeSeries loadPriorRunoffTimeSeries(String locationId, - String typeSource, long modelRunStartTime, - long unitHydrographWholeDuration) { - String header = "DataMgr.loadPriorRunoffTimeSeries(): "; - // System.out.println(header + "loading prior runoff time series"); - - MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - - String typeSourceClause = null; - - if (typeSource == null) { - typeSourceClause = ""; - } else { - typeSourceClause = " AND ts = '" + typeSource + "'"; - } - - long initialTime = modelRunStartTime - - (unitHydrographWholeDuration * _millisPerHour); - String initialTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(initialTime); - String modelRunStartTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(modelRunStartTime); - - // create the select where clause - String whereClause = "WHERE lid = '" + locationId + "'" - + " AND pe = 'QB' AND dur = 1001" + typeSourceClause - + " ORDER BY basistime DESC, validtime ASC"; - - RegularTimeSeries ts = null; - - long desiredBasisTime = 0; // use the most recent basistime returned - // from the db - long startTime = modelRunStartTime - - (unitHydrographWholeDuration * _millisPerHour); - - try { - recordList = table.select(whereClause); - - System.out.println(header + "validtimes must be between " - + initialTimeString + " and " + modelRunStartTimeString); - - List subRecordList = getSubListForPriorRunoffTimeSeries(recordList, - initialTime, modelRunStartTime); - - if (subRecordList == null) { - System.out.println(header + "subRecordList is null for " - + locationId); - } - - else if (subRecordList.size() > 0) { - - record = (FcstDischargeRecord) subRecordList.get(0); - desiredBasisTime = record.getBasistime(); - startTime = record.getValidtime(); - - long endTime = modelRunStartTime; - int intervalInHours = 1; - - ts = new RegularTimeSeries(startTime, endTime, intervalInHours, - tsRunoffUnit); - - // System.out.println(header + "record count = " + - // recordList.size()); - } - - // for the selected subRecordList, create a runoff time series - - boolean done = false; - for (int i = 0; !done && (subRecordList != null) - && (i < subRecordList.size()); i++) { - record = (FcstDischargeRecord) subRecordList.get(i); - - if (record.getValidtime() > modelRunStartTime) { - done = true; - } else { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbRunoffUnit); - - ts.setMeasurementByTime(m, validTime); - } - } // end for i - } // end try - - catch (SQLException e) { - logSQLException(e); - } - - return ts; - } - - // ------------------------------------------------------------------------------- - - private List createListOfFcstDischargeRecordLists( - List recordList) { - String header = "DataMgr.createListOfFcstDischargeRecordLists()"; - List listOfLists = new ArrayList(); - List subRecordList = null; - - long previousBasisTime = -1; - - for (FcstDischargeRecord record : recordList) { - // if the record is the first one of its basistime, then create a - // new sublist and add it to the listOfLists - if (record.getBasistime() != previousBasisTime) { - subRecordList = new ArrayList(); - listOfLists.add(subRecordList); - previousBasisTime = record.getBasistime(); - // System.out.println(header + "basisTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(record.getBasistime())); - } - - // add the record to the current subRecordList, - // which itself has already been added to the listOfLists - subRecordList.add(record); - - } - - // System.out.println(header + "listOfLists has " +listOfLists.size() + - // " sublists."); - - return listOfLists; - } - - // ------------------------------------------------------------------------------- - - private List getSubListForPriorRunoffTimeSeries( - List recordList, long initialTime, long endTime) { - String header = "DataMgr.getSubListForPriorRunoffTimeSeries(): "; - // This method assumes: - // recordList is ordered by basistime DESC (most recent basistime - // first), validtime ASC (oldest first) - // - List subList = null; - - // put all time series into a List of Lists - List listOfFcstDischargeRecordLists = createListOfFcstDischargeRecordLists(recordList); - - // iterate through the list of lists until you find the subList that - // includes a validtime - // set that overlaps the time from initialTime to endTime (inclusive) - // Take that sublist's basistime and quit - for (int i = 0; i < listOfFcstDischargeRecordLists.size(); i++) { - List subRecordList = (List) listOfFcstDischargeRecordLists - .get(i); - - int lastIndex = subRecordList.size() - 1; - if (lastIndex > -1) { - FcstDischargeRecord firstRecord = subRecordList.get(0); - FcstDischargeRecord lastRecord = subRecordList.get(lastIndex); - - String time1String = DbTimeHelper - .getDateTimeStringFromLongTime(firstRecord - .getValidtime()); - String time2String = DbTimeHelper - .getDateTimeStringFromLongTime(lastRecord - .getValidtime()); - - // System.out.println(header + "validtime 1 = " + time1String + - // " validtime 2 = " + time2String); - - if ((firstRecord.getValidtime() <= initialTime) - && (lastRecord.getValidtime() >= endTime)) { - subList = subRecordList; - break; - } - } - - } - - return subList; - } - - // ------------------------------------------------------------------------------- - /* - * public RegularTimeSeries oldLoadPriorRunoffTimeSeries(String locationId, - * long modelRunStartTime, long unitHydrographWholeDuration) { // String - * header = "DataMgr.getPriorRunoffTimeSeries(): "; // - * System.out.println(header + "loading prior runoff time series"); - * - * MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; MeasuringUnit dbRunoffUnit - * = MeasuringUnit.inches; - * - * FcstDischargeTable table = new FcstDischargeTable(_db); - * FcstDischargeRecord record = null; List recordList = null; - * - * // NOTE: We may at some point have to select based on the Type/source - * whose // prior runoff is favored String whereClause = "WHERE lid = '" + - * locationId + "'" + " AND pe = 'QB' AND dur = 1001 " + - * " ORDER BY basistime DESC, validtime ASC"; - * - * RegularTimeSeries ts = null; - * - * long desiredBasisTime = 0; // use the most recent basistime in the db - * long startTime = modelRunStartTime - (unitHydrographWholeDuration * - * _millisPerHour); - * - * try { recordList = table.select(whereClause); - * - * if (recordList.size() > 0) { record = (FcstDischargeRecord) - * recordList.get(0); desiredBasisTime = record.getBasistime(); startTime = - * record.getValidtime(); - * - * long endTime = modelRunStartTime; int intervalInHours = 1; - * - * ts = new RegularTimeSeries(startTime, endTime, intervalInHours, - * tsRunoffUnit); - * - * // System.out.println(header + "record count = " + recordList.size()); } - * - * // for the desiredBasisTime, create a runoff time series - * - * boolean done = false; for (int i = 0 ; !done && (i < recordList.size()); - * i++) { // System.out.println(header + "i = " + i); record = - * (FcstDischargeRecord) recordList.get(i); - * - * if (record.getBasistime() != desiredBasisTime) { // - * System.out.println(header + "part1"); // we are done, since the - * desiredBasisTime comes first in the // list done = true; } else if - * (record.getValidtime() > modelRunStartTime) { // - * System.out.println(header + "part2, validtime = " + // - * DbTimeHelper.getDateTimeStringFromLongTime(record.getValidtime()) + // - * " modelRunStartTime = " + - * DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime)); // we - * only want PRIOR runoff to the model StartTime, so // stop now done = - * true; } else { // System.out.println(header + "part3"); double value = - * record.getValue(); long validTime = record.getValidtime(); Measurement m - * = new Measurement(value, dbRunoffUnit); - * - * ts.setMeasurementByTime(m, validTime); - * - * // System.out.println(header + "measurement = " + m); } } //end for i } - * //end try - * - * catch ( SQLException e ) { logSQLException(e); } - * - * return ts; } - */ - // ------------------------------------------------------------------------------- - public String[] loadPreferredObsTypeSourceArray(String areaId, - String physicalElement, int duration) { - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - List recordList = null; - - String whereString = " WHERE lid = '" + areaId + "'" + " AND pe = '" - + physicalElement + "'" + " AND dur = " + duration - + " AND ts LIKE 'R%'" + " ORDER by ts_rank ASC "; - - String[] tsArray = new String[0]; - - try { - recordList = table.select(whereString); - - int lowestRank = 0; - - tsArray = new String[recordList.size()]; - for (int i = 0; i < recordList.size(); i++) { - record = (IngestFilterRecord) recordList.get(i); - - tsArray[i] = record.getTs(); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return tsArray; - } - - // ------------------------------------------------------- - public RegularTimeSeries loadPotentialEvaporationTimeSeries(String basinId, - long modelRunStartTime, long modelRunEndTime) { - RegularTimeSeries ts = null; - MeasuringUnit tsEvapUnit = MeasuringUnit.mm; - MeasuringUnit dbEvapUnit = MeasuringUnit.inches; - - FcstOtherTable table = new FcstOtherTable(_db); - FcstOtherRecord record = null; - List recordList = null; - - long desiredBasisTime = 0; // use the most recent basistime in the db - long startTime = modelRunStartTime; - long endTime = modelRunEndTime; - - int intervalInHours = 1; - ts = new RegularTimeSeries(startTime, endTime, intervalInHours, - tsEvapUnit); - - String whereClause = " WHERE lid = '" - + basinId - + "' AND " - + "pe = 'EA' AND dur = 1001 ORDER BY basistime DESC, validtime ASC"; - - try { - recordList = table.select(whereClause); - - if (recordList.size() > 0) { - record = (FcstOtherRecord) recordList.get(0); - desiredBasisTime = record.getBasistime(); - } - - boolean done = false; - for (int i = 0; !done && (i < recordList.size()); i++) { - record = (FcstOtherRecord) recordList.get(i); - - if (record.getBasistime() != desiredBasisTime) { - // we are done, since the desiredBasisTime comes first in - // the - // list - done = true; - } else if (record.getValidtime() > modelRunEndTime) { - // we are done, since we don't need the data past this time - done = true; - } else if (record.getValidtime() >= modelRunStartTime) { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbEvapUnit); - - ts.setMeasurementByTime(m, validTime); - } - // else, the data comes from before the modelRunStartTime and we - // are - // not interested. - - } // end for i - } catch (SQLException e) { - logSQLException(e); - } - - return ts; - - } - - // --------------------------------------------------------------------------------------- - - public void saveRunoffTimeSeries(String locationId, - RegularTimeSeries runoffTimeSeries) { - saveRunoffTimeSeries(locationId, "SSHPRUNOFF", runoffTimeSeries); - } // end saveRunoffTimeSeries (2 arg version) - - // --------------------------------------------------------------------------------------- - public void saveRunoffTimeSeries(String locationId, String productId, - RegularTimeSeries runoffTimeSeries) { - long basisTime = System.currentTimeMillis(); - String typeSource = "FZ"; - saveRunoffTimeSeries(locationId, typeSource, basisTime, productId, - runoffTimeSeries); - - return; - } // end saveRunoffTimeSeries (3 arg version) - // ---------------------------------------------------------------------------------------- - - public void saveRunoffTimeSeries(String locationId, String typeSource, - long basisTime, String productId, RegularTimeSeries runoffTimeSeries) { - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - - int length = runoffTimeSeries.getMeasurementCount(); - short durationCode = 1001; - record = new FcstDischargeRecord(); - record.setLid(locationId); - record.setPe("QB"); - - long currentTime = System.currentTimeMillis(); - record.setBasistime(basisTime); - record.setProducttime(basisTime); - record.setPostingtime(currentTime); - - record.setTs(typeSource); - record.setDur(durationCode); - record.setExtremum("Z"); - record.setProbability(-1.0f); - record.setProduct_id(productId); - record.setShef_qual_code(""); - - FcstTsDescriptor descriptor = new FcstTsDescriptor("FcstDischarge"); - descriptor.setLid(record.getLid()); - descriptor.setPe(record.getPe()); - descriptor.setTs(record.getTs()); - descriptor.setDur(record.getDur()); - descriptor.setExtremum(record.getExtremum()); - - saveToIngestFilterIfNeeded(descriptor); - - for (int i = 0; i < length; i++) { - Measurement measurement = runoffTimeSeries.getMeasurementByIndex(i); - long time = runoffTimeSeries.getMeasurementTimeByIndex(i); - - // make sure my units are correct - measurement = measurement.getCopy(dbRunoffUnit); - - double value = measurement.getValue(); - - record.setValidtime(time); - record.setValue(value); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - - } - - } // end saveRunoffTimeSeries (6 arg version) - - // ------------------------------------------------------- - public List loadSacSmaParamsList(String where) { - List sacSmaParamsRecordList = null; - SacSmaParamsTable table = new SacSmaParamsTable(_db); - - try { - sacSmaParamsRecordList = table.select(where); - } catch (SQLException e) { - logSQLException(e); - } - - return getSacSmaParamsListFromSacSmaParamsRecordList(sacSmaParamsRecordList); - } - - // ------------------------------------------------------- - private SacSmaState getSacSmaStateFromRecord(SacSmaStateRecord record) { - SacSmaState state = new SacSmaState(); - - state.setBasinId(record.getBasin_id()); - - state.setValidTime(record.getValidtime()); - state.setBasisTime(record.getBasistime()); - state.setPostingTime(record.getPostingtime()); - - state.setSource(record.getSource()); - - state.setAdimc(record.getAdimc()); - state.setLzfpc(record.getLzfpc()); - state.setLzfsc(record.getLzfsc()); - state.setLztwc(record.getLztwc()); - - state.setUzfwc(record.getUzfwc()); - state.setUztwc(record.getUztwc()); - - return state; - - } - - private List getSacSmaParamsListFromSacSmaParamsRecordList( - List sacSmaParamsRecordList) { - List sacSmaParamsList = new ArrayList(); - - for (int i = 0; i < sacSmaParamsRecordList.size(); i++) { - SacSmaParameters addSacSmaParams = new SacSmaParameters(); - SacSmaParamsRecord sacSmaParamsRecord = (SacSmaParamsRecord) sacSmaParamsRecordList - .get(i); - - addSacSmaParams.setBasinId(sacSmaParamsRecord.getBasin_id()); - addSacSmaParams.setSource(sacSmaParamsRecord.getSource()); - addSacSmaParams.setValidTime(sacSmaParamsRecord.getValidtime()); - addSacSmaParams.setPostingTime(sacSmaParamsRecord.getPostingtime()); - addSacSmaParams.setUztwm(sacSmaParamsRecord.getUztwm()); - addSacSmaParams.setUzfwm(sacSmaParamsRecord.getUzfwm()); - addSacSmaParams.setUzk(sacSmaParamsRecord.getUzk()); - addSacSmaParams.setPctim(sacSmaParamsRecord.getPctim()); - addSacSmaParams.setAdimp(sacSmaParamsRecord.getAdimp()); - addSacSmaParams.setRiva(sacSmaParamsRecord.getRiva()); - addSacSmaParams.setZperc(sacSmaParamsRecord.getZperc()); - addSacSmaParams.setRexp(sacSmaParamsRecord.getRexp()); - addSacSmaParams.setLztwm(sacSmaParamsRecord.getLztwm()); - addSacSmaParams.setLzfsm(sacSmaParamsRecord.getLzfsm()); - addSacSmaParams.setLzfpm(sacSmaParamsRecord.getLzfpm()); - addSacSmaParams.setLzsk(sacSmaParamsRecord.getLzsk()); - addSacSmaParams.setLzpk(sacSmaParamsRecord.getLzpk()); - addSacSmaParams.setPfree(sacSmaParamsRecord.getPfree()); - addSacSmaParams.setRserv(sacSmaParamsRecord.getRserv()); - addSacSmaParams.setSide(sacSmaParamsRecord.getSide()); - - addSacSmaParams.setPeadj(sacSmaParamsRecord.getPeadj()); - addSacSmaParams.setPxadj(sacSmaParamsRecord.getPxadj()); - addSacSmaParams.setEfc(sacSmaParamsRecord.getEfc()); - - sacSmaParamsList.add(addSacSmaParams); - } - - return sacSmaParamsList; - } - - // ------------------------------------------------------- - public List loadSacSmaStateDescriptorListByBasinId(String basinId) { - String whereString = "WHERE basin_id = '" + basinId - + "' ORDER BY validtime desc, basistime desc"; - List stateList = loadSacSmaStateList(whereString); - - List descriptorList = new ArrayList(); - - for (int i = 0; i < stateList.size(); i++) { - SacSmaState state = (SacSmaState) stateList.get(i); - - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - descriptorList.add(descriptor); - - } - - return descriptorList; - - } - - public List loadSacSmaStateList(String where) { - List sacSmaStateRecordList = null; - SacSmaStateTable table = new SacSmaStateTable(_db); - - try { - sacSmaStateRecordList = table.select(where); - } catch (SQLException e) { - logSQLException(e); - } - return getSacSmaStateListFromSacSmaStateRecordList(sacSmaStateRecordList); - } - - // ------------------------------------------------------- - - private List getSacSmaStateListFromSacSmaStateRecordList( - List sacSmaStateRecordList) { - List sacSmaStateList = new ArrayList(); - - if (sacSmaStateRecordList != null) { - for (int i = 0; i < sacSmaStateRecordList.size(); i++) { - SacSmaState addSacSmaState = new SacSmaState(); - SacSmaStateRecord sacSmaStateRecord = (SacSmaStateRecord) sacSmaStateRecordList - .get(i); - - addSacSmaState.setBasinId(sacSmaStateRecord.getBasin_id()); - addSacSmaState.setSource(sacSmaStateRecord.getSource()); - addSacSmaState.setValidTime(sacSmaStateRecord.getValidtime()); - addSacSmaState.setBasisTime(sacSmaStateRecord.getBasistime()); - addSacSmaState.setPostingTime(sacSmaStateRecord - .getPostingtime()); - addSacSmaState.setUztwc(sacSmaStateRecord.getUztwc()); - addSacSmaState.setUzfwc(sacSmaStateRecord.getUzfwc()); - addSacSmaState.setLztwc(sacSmaStateRecord.getLztwc()); - addSacSmaState.setLzfsc(sacSmaStateRecord.getLzfsc()); - addSacSmaState.setLzfpc(sacSmaStateRecord.getLzfpc()); - addSacSmaState.setAdimc(sacSmaStateRecord.getAdimc()); - - sacSmaStateList.add(addSacSmaState); - } - } - - return sacSmaStateList; - } - - // ------------------------------------------------------- - private SacSmaParamsRecord getSacSmaParamsRecord( - SacSmaParameters sacSmaParams) { - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - record.setBasin_id(sacSmaParams.getBasinId()); - record.setSource(sacSmaParams.getSource()); - record.setValidtime(sacSmaParams.getValidTime()); - record.setPostingtime(sacSmaParams.getPostingTime()); - - record.setUztwm(sacSmaParams.getUztwm()); - record.setUzfwm(sacSmaParams.getUzfwm()); - record.setUzk(sacSmaParams.getUzk()); - record.setPctim(sacSmaParams.getPctim()); - record.setAdimp(sacSmaParams.getAdimp()); - record.setRiva(sacSmaParams.getRiva()); - record.setZperc(sacSmaParams.getZperc()); - record.setRexp(sacSmaParams.getRexp()); - record.setLztwm(sacSmaParams.getLztwm()); - record.setLzfsm(sacSmaParams.getLzfsm()); - record.setLzfpm(sacSmaParams.getLzfpm()); - record.setLzsk(sacSmaParams.getLzsk()); - record.setLzpk(sacSmaParams.getLzpk()); - record.setPfree(sacSmaParams.getPfree()); - record.setRserv(sacSmaParams.getRserv()); - record.setSide(sacSmaParams.getSide()); - - record.setPeadj(sacSmaParams.getPeadj()); - record.setPxadj(sacSmaParams.getPxadj()); - record.setEfc(sacSmaParams.getEfc()); - - return record; - } - - // ------------------------------------------------------- - - public void saveParams(SacSmaParameters sacSmaParams) { - SacSmaParamsTable table = new SacSmaParamsTable(_db); - SacSmaParamsRecord record = getSacSmaParamsRecord(sacSmaParams); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - - public void saveState(SacSmaState sacSmaState) { - SacSmaStateTable table = new SacSmaStateTable(_db); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id(sacSmaState.getBasinId()); - record.setSource(sacSmaState.getSource()); - record.setValidtime(sacSmaState.getValidTime()); - record.setBasistime(sacSmaState.getBasisTime()); - record.setPostingtime(sacSmaState.getPostingTime()); - - record.setUztwc(sacSmaState.getUztwc()); - record.setUzfwc(sacSmaState.getUzfwc()); - record.setLztwc(sacSmaState.getLztwc()); - record.setLzfsc(sacSmaState.getLzfsc()); - record.setLzfpc(sacSmaState.getLzfpc()); - record.setAdimc(sacSmaState.getAdimc()); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - public boolean saveFcstTimeSeries(FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, int hoursToSave) { - - boolean result = false; - - if (descriptor.getTableName().equalsIgnoreCase("FcstHeight")) { - result = saveFcstHeightTs(descriptor, timeSeries, hoursToSave); - } else if (descriptor.getTableName().equalsIgnoreCase("FcstOther")) { - result = saveFcstEvapTs(descriptor, timeSeries, hoursToSave); - } else if (descriptor.getTableName().equalsIgnoreCase("FcstDischarge")) { - result = saveFcstDischargeTs(descriptor, timeSeries, hoursToSave); - } - - return result; - } - - // ------------------------------------------------------- - - private boolean saveFcstEvapTs(FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, int hoursToSave) { - MeasuringUnit dbUnit = MeasuringUnit.inches; - boolean success = false; - - saveToIngestFilterIfNeeded(descriptor); - - FcstOtherTable table = new FcstOtherTable(_db); - FcstOtherRecord record = new FcstOtherRecord(); - - long startTime, endTime, interval; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - - // adjust the endtime - long possibleEndTime = startTime + ((hoursToSave - 1) * HOUR_IN_MILLIS); - if (possibleEndTime <= endTime) { - endTime = possibleEndTime; - } - - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - int recordCount = 0; - int insertOrUpdateCount = 0; - int failureCount = 0; - int skippedCount = 0; - - for (long time = startTime; time <= endTime; time += interval) { - Measurement measurement = timeSeries.getMeasurementByTime(time); - - record.setValidtime(time); - record.setValue(measurement.getValue(dbUnit)); - - recordCount++; - - if (record.getValue() >= 0.0) { - - try { - table.insertOrUpdate(record); - insertOrUpdateCount++; - // System.out.println("count = " + count); - } catch (SQLException e) { - failureCount++; - logSQLException(e); - _logger.log("record # = " + recordCount); - } - } else { - skippedCount++; - _logger.log("DataMgr.saveFcstHeight(): measurement = " - + measurement + " record = " + record); - } - } // end for - - _logger.log("DataMgr.saveFcstHeight(): " + " recordCount = " - + recordCount + " insertOrUpdateCount = " + insertOrUpdateCount - + " failureCount = " + failureCount + " skippedCount = " - + skippedCount); - - if ((insertOrUpdateCount + skippedCount) == recordCount) { - success = true; - } - - return success; - - } - - // ------------------------------------------------------- - - /** - * Publish data to the riverstatus table. - */ - private void postMaxFcst(String locationId, String physicalElement, - String typeSource) { - String table = null; - - _logger.log("Updating RiverStatus for: " + locationId + " " - + physicalElement); - - if (physicalElement.startsWith("H") || physicalElement.startsWith("h")) - table = "FcstHeight"; - else - table = "FcstDischarge"; - - ForecastPoster fcstPoster = new ForecastPoster(_db, _logger); - boolean status = fcstPoster.loadMaxFcstData(table, locationId, - physicalElement); - - if (status) - _logger.log("RiverStatus update complete !"); - else - _logger.log("RiverStatus update FAILED !!!"); - } - - /* - * private void runLoadMaxFcst(String locationId, String physicalElement, - * String typeSource) { // get the database name and build the command line - * arguments for the // load max forecast program - * - * String cmdLineArgString = null; String dbName = _db.getDatabaseName(); - * int returnCode = 0; - * - * // check if there is a value for db_name if (dbName != null) { if - * (dbName.length() != 0) { cmdLineArgString = " -d" + dbName + " -l" + - * locationId + " -p" + physicalElement + " -t" + typeSource; } - * - * - * String osSuffix = ".LX"; - * - * - * EnvHelper envHelper = new EnvHelper(); String dirString = - * envHelper.getProperty("WHFS_BIN_DIR"); String programPath = dirString + - * "/load_maxfcst" + osSuffix; - * - * String commandString = programPath + " " + cmdLineArgString; - * - * - * try { _logger.log("executing " + commandString); Process process = - * Runtime.getRuntime().exec(commandString); process.waitFor(); - * - * _logger.log("Completed execution of " + commandString); - * - * returnCode = process.exitValue(); } catch(IOException e) { - * e.printStackTrace(); } - * - * catch( InterruptedException e ) { e.printStackTrace(); } - * - * if (returnCode != 0) { System.out.println("returnCode from loadMaxFcst=" - * + returnCode); } - * - * } - * - * } //end runLoadMaxFcst - */ - // ------------------------------------------------------- - - private boolean saveFcstHeightTs(FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, int hoursToSave) { - boolean success = false; - MeasuringUnit dbUnit = MeasuringUnit.feet; - - saveToIngestFilterIfNeeded(descriptor); - - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = new FcstHeightRecord(); - long startTime, endTime, interval; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - - // adjust the endtime - long possibleEndTime = startTime + ((hoursToSave - 1) * HOUR_IN_MILLIS); - if (possibleEndTime <= endTime) { - endTime = possibleEndTime; - } - - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - int recordCount = 0; - int insertOrUpdateCount = 0; - int failureCount = 0; - int skippedCount = 0; - - for (long time = startTime; time <= endTime; time += interval) { - Measurement measurement = timeSeries.getMeasurementByTime(time); - - record.setValidtime(time); - record.setValue(measurement.getValue(dbUnit)); - - recordCount++; - - if (record.getValue() >= 0.0) { - - try { - table.insertOrUpdate(record); - insertOrUpdateCount++; - // System.out.println("count = " + count); - } catch (SQLException e) { - failureCount++; - logSQLException(e); - _logger.log("failed record # = " + recordCount); - } - } else { - skippedCount++; - // _logger.log("DataMgr.saveFcstHeight(): measurement = " + - // measurement + - // " record = " + record); - } - } - - _logger.log("saveFcstHeightTs(): " + " recordCount = " + recordCount - + " insertOrUpdateCount = " + insertOrUpdateCount - + " failureCount = " + failureCount + " skippedCount = " - + skippedCount); - - if ((insertOrUpdateCount + skippedCount) == recordCount) { - success = true; - } - - saveHeightCrestMeasurement(table, record, startTime, endTime, - timeSeries); - - postMaxFcst(descriptor.getLid(), descriptor.getPe(), descriptor.getTs()); - - return success; - - } - - // ------------------------------------------------------- - private boolean saveFcstDischargeTs(FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, int hoursToSave) { - boolean success = false; - MeasuringUnit dbUnit = MeasuringUnit.cfs; - - saveToIngestFilterIfNeeded(descriptor); - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = new FcstDischargeRecord(); - long startTime, endTime, interval; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - - // adjust the endtime - long possibleEndTime = startTime + ((hoursToSave - 1) * HOUR_IN_MILLIS); - if (possibleEndTime <= endTime) { - endTime = possibleEndTime; - } - - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - int recordCount = 0; - int insertOrUpdateCount = 0; - int failureCount = 0; - int skippedCount = 0; - - for (long time = startTime; time <= endTime; time += interval) { - Measurement measurement = timeSeries.getMeasurementByTime(time); - - record.setValidtime(time); - record.setValue(measurement.getValue(dbUnit)); - - recordCount++; - - if (record.getValue() >= 0.0) { - - try { - table.insertOrUpdate(record); - insertOrUpdateCount++; - // System.out.println("count = " + count); - } catch (SQLException e) { - failureCount++; - logSQLException(e); - _logger.log("failed record # = " + recordCount); - } - } else { - skippedCount++; - // _logger.log("DataMgr.saveFcstDischarge(): measurement = " + - // measurement + - // " record = " + record); - } - } - - _logger.log("DataMgr.saveFcstDischarge(): " + " recordCount = " - + recordCount + " insertOrUpdateCount = " + insertOrUpdateCount - + " failureCount = " + failureCount + " skippedCount = " - + skippedCount); - - if ((insertOrUpdateCount + skippedCount) == recordCount) { - success = true; - } - - saveDischargeCrestMeasurement(table, record, startTime, endTime, - timeSeries); - - postMaxFcst(descriptor.getLid(), descriptor.getPe(), descriptor.getTs()); - - return success; - - } - - // ------------------------------------------------------- - private void saveHeightCrestMeasurement(FcstHeightTable table, - FcstHeightRecord record, long startTime, long endTime, - RegularTimeSeries timeSeries) { - - AbsTimeMeasurement crestMeasurement = timeSeries.getMaxMeasurement( - startTime, endTime); - record.setValue(crestMeasurement.getValue()); - record.setValidtime(crestMeasurement.getTime()); - record.setExtremum("X"); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - _logger.log("failed to insert crest for FcstHeight record = " - + record); - } - return; - } - - // ------------------------------------------------------- - private void saveDischargeCrestMeasurement(FcstDischargeTable table, - FcstDischargeRecord record, long startTime, long endTime, - RegularTimeSeries timeSeries) { - - AbsTimeMeasurement crestMeasurement = timeSeries.getMaxMeasurement( - startTime, endTime); - record.setValue(crestMeasurement.getValue()); - record.setValidtime(crestMeasurement.getTime()); - record.setExtremum("X"); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - _logger.log("failed to insert crest for FcstDischarge record = " - + record); - } - return; - } - - // ------------------------------------------------------- - private void saveToIngestFilterIfNeeded(IngestFilterTsDescriptor descriptor) { - // String header = "DataMgr.saveToIngestFilterIfNeeded(): "; - // System.out.println(header + "inside"); - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = new IngestFilterRecord(); - - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setDur(descriptor.getDur()); - - record.setTs_rank((short) 1); - record.setIngest("T"); - record.setOfs_input("F"); - record.setStg2_input("F"); - - try { - String whereString = record.getWhereString(); - int recordCount = table.selectCount(whereString); - - // System.out.println(header + " Attempting to insert" + record); - - if (recordCount < 1) { - table.insert(record); - } - } catch (SQLException e) { - logSQLException(e); - - } - - return; - } - - // ------------------------------------------------------- - private void saveToIngestFilter(IngestFilterTsDescriptor descriptor) { - // String header = "DataMgr.saveToIngestFilter(): "; - - // System.out.println(header + "inside"); - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = new IngestFilterRecord(); - - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setDur(descriptor.getDur()); - - record.setTs_rank((short) 1); - record.setIngest("T"); - record.setOfs_input("F"); - record.setStg2_input("F"); - - try { - System.out.println("Attempting to insert" + record); - table.insert(record); - - } catch (SQLException e) { - logSQLException(e); - - } - - return; - } - - // ------------------------------------------------------- - - // ------------------------------------------------------- - - public void deleteState(SacSmaState sacSmaState) { - SacSmaStateTable table = new SacSmaStateTable(_db); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id(sacSmaState.getBasinId()); - record.setSource(sacSmaState.getSource()); - record.setValidtime(sacSmaState.getValidTime()); - record.setBasistime(sacSmaState.getBasisTime()); - record.setPostingtime(sacSmaState.getPostingTime()); - - record.setUztwc(sacSmaState.getUztwc()); - record.setUzfwc(sacSmaState.getUzfwc()); - record.setLztwc(sacSmaState.getLztwc()); - record.setLzfsc(sacSmaState.getLzfsc()); - record.setLzfpc(sacSmaState.getLzfpc()); - record.setAdimc(sacSmaState.getAdimc()); - - try { - table.delete(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - - public void deleteParams(SacSmaParameters sacSmaParams) { - SacSmaParamsTable table = new SacSmaParamsTable(_db); - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - record.setBasin_id(sacSmaParams.getBasinId()); - record.setSource(sacSmaParams.getSource()); - record.setValidtime(sacSmaParams.getValidTime()); - record.setPostingtime(sacSmaParams.getPostingTime()); - - record.setUztwm(sacSmaParams.getUztwm()); - record.setUzfwm(sacSmaParams.getUzfwm()); - record.setUzk(sacSmaParams.getUzk()); - record.setPctim(sacSmaParams.getPctim()); - record.setAdimp(sacSmaParams.getAdimp()); - record.setRiva(sacSmaParams.getRiva()); - record.setZperc(sacSmaParams.getZperc()); - record.setRexp(sacSmaParams.getRexp()); - record.setLztwm(sacSmaParams.getLztwm()); - record.setLzfsm(sacSmaParams.getLzfsm()); - record.setLzfpm(sacSmaParams.getLzfpm()); - record.setLzsk(sacSmaParams.getLzsk()); - record.setLzpk(sacSmaParams.getLzpk()); - record.setPfree(sacSmaParams.getPfree()); - record.setRserv(sacSmaParams.getRserv()); - record.setSide(sacSmaParams.getSide()); - - try { - table.delete(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - public boolean hasSacSmaParams(String basinId) { - boolean result = false; - - SacSmaParamsTable table = new SacSmaParamsTable(_db); - - String whereClause = "where basin_id = '" + basinId + "'"; - int count = 0; - - try { - count = table.selectCount(whereClause); - } catch (SQLException e) { - logSQLException(e); - } - - if (count > 0) { - result = true; - } - - return result; - } - - // ------------------------------------------------------- - public MonthlyValues loadMonthlyValues(String locationId, - boolean isAdjustment) { - String header = "loadMonthlyValues():"; - - MonthlyValues monthlyValues = null; - - String baseWhereClause = "WHERE lid = '" + locationId + "' AND pe='EA'"; - String whereClause = null; - - String adjustmentClause = null; - if (isAdjustment) { - adjustmentClause = " AND adjustment = 'Y' AND dur = 1001 "; - } else { - adjustmentClause = " AND adjustment != 'Y' AND dur = 2001 "; - } - - whereClause = baseWhereClause + adjustmentClause; - - List monthlyValuesList = loadMonthlyValuesList(whereClause); - - // System.out.println(header + " whereClause = " + whereClause); - - if (monthlyValuesList.size() > 0) { - monthlyValues = (MonthlyValues) monthlyValuesList.get(0); - } else { - monthlyValues = new MonthlyValues(); - } - - return monthlyValues; - - } // end getMonthlyValues - - // ------------------------------------------------------- - - public List loadMonthlyValuesList(String where) { - List monthlyValuesRecordList = null; - MonthlyValuesTable table = new MonthlyValuesTable(_db); - - try { - - monthlyValuesRecordList = table.select(where); - - } catch (SQLException e) { - _logger.log("Error code = " + e.getMessage()); - _logger.log("error retrieving SacSmaStateRecord: " + where); - } - - return getMonthlyValuesListFromMonthlyValuesRecordList(monthlyValuesRecordList); - } - - // ------------------------------------------------------- - - private List getMonthlyValuesListFromMonthlyValuesRecordList( - List monthlyValuesRecordList) { - List monthlyValuesList = new ArrayList(); - - for (int i = 0; i < monthlyValuesRecordList.size(); i++) { - MonthlyValues addMonthlyValues = new MonthlyValues(); - MonthlyValuesRecord monthlyValuesRecord = (MonthlyValuesRecord) monthlyValuesRecordList - .get(i); - double[] valueArray = new double[12]; - - addMonthlyValues.setBasinId(monthlyValuesRecord.getLid()); - addMonthlyValues.setPe(monthlyValuesRecord.getPe()); - addMonthlyValues.setDur(monthlyValuesRecord.getDur()); - addMonthlyValues.setTs(monthlyValuesRecord.getTs()); - addMonthlyValues.setExtremum(monthlyValuesRecord.getExtremum()); - if (monthlyValuesRecord.getAdjustment().equalsIgnoreCase("Y")) { - addMonthlyValues.setAdjustment(true); - } else { - addMonthlyValues.setAdjustment(false); - } - addMonthlyValues.setPostingTime(monthlyValuesRecord - .getPostingtime()); - - valueArray[0] = monthlyValuesRecord.getJan_value(); - valueArray[1] = monthlyValuesRecord.getFeb_value(); - valueArray[2] = monthlyValuesRecord.getMar_value(); - valueArray[3] = monthlyValuesRecord.getApr_value(); - valueArray[4] = monthlyValuesRecord.getMay_value(); - valueArray[5] = monthlyValuesRecord.getJun_value(); - valueArray[6] = monthlyValuesRecord.getJul_value(); - valueArray[7] = monthlyValuesRecord.getAug_value(); - valueArray[8] = monthlyValuesRecord.getSep_value(); - valueArray[9] = monthlyValuesRecord.getOct_value(); - valueArray[10] = monthlyValuesRecord.getNov_value(); - valueArray[11] = monthlyValuesRecord.getDec_value(); - - addMonthlyValues.setValues(valueArray); - - monthlyValuesList.add(addMonthlyValues); - } - - return monthlyValuesList; - } - - // ------------------------------------------------------- - - public void saveMonthlyValues(MonthlyValues monthlyValues) { - MonthlyValuesTable table = new MonthlyValuesTable(_db); - MonthlyValuesRecord record = new MonthlyValuesRecord(); - long currentTime = System.currentTimeMillis(); - double[] valueArray = monthlyValues.getValueArray(); - - record.setLid(monthlyValues.getBasinId()); - record.setPe(monthlyValues.getPe()); - record.setDur(monthlyValues.getDur()); - record.setTs(monthlyValues.getTs()); - record.setExtremum(monthlyValues.getExtremum()); - if (monthlyValues.isAdjustment()) { - record.setAdjustment("Y"); - } else { - record.setAdjustment("N"); - } - record.setPostingtime(currentTime); - record.setJan_value(valueArray[0]); - record.setFeb_value(valueArray[1]); - record.setMar_value(valueArray[2]); - record.setApr_value(valueArray[3]); - record.setMay_value(valueArray[4]); - record.setJun_value(valueArray[5]); - record.setJul_value(valueArray[6]); - record.setAug_value(valueArray[7]); - record.setSep_value(valueArray[8]); - record.setOct_value(valueArray[9]); - record.setNov_value(valueArray[10]); - record.setDec_value(valueArray[11]); - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - - public void deleteMonthlyValues(MonthlyValues monthlyValues) { - MonthlyValuesTable table = new MonthlyValuesTable(_db); - MonthlyValuesRecord record = new MonthlyValuesRecord(); - double[] valueArray = monthlyValues.getValueArray(); - - record.setLid(monthlyValues.getBasinId()); - record.setPe(monthlyValues.getPe()); - record.setDur(monthlyValues.getDur()); - record.setTs(monthlyValues.getTs()); - record.setExtremum(monthlyValues.getExtremum()); - if (monthlyValues.isAdjustment()) { - record.setAdjustment("Y"); - } else { - record.setAdjustment("N"); - } - record.setPostingtime(monthlyValues.getPostingTime()); - record.setJan_value(valueArray[0]); - record.setFeb_value(valueArray[1]); - record.setMar_value(valueArray[2]); - record.setApr_value(valueArray[3]); - record.setMay_value(valueArray[4]); - record.setJun_value(valueArray[5]); - record.setJul_value(valueArray[6]); - record.setAug_value(valueArray[7]); - record.setSep_value(valueArray[8]); - record.setOct_value(valueArray[9]); - record.setNov_value(valueArray[10]); - record.setDec_value(valueArray[11]); - - try { - table.delete(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------- - - private SshpConfigRecord getSshpConfigRecord(SSHPConfig config) { - SshpConfigRecord record = new SshpConfigRecord(); - - record.setLid(config.getLid()); - record.setBasin_id(config.getBasinId()); - record.setPostingtime(config.getPostingTime()); - - record.setModel_pref(config.getModelPref()); - record.setSource_pref(config.getSourcePref()); - - // convert and set boolean Y or N strings - record.setUse_static_evap(getStringFromBoolean(config.useStaticEvap())); - record.setAuto_process(getStringFromBoolean(config.isAutoProcess())); - record.setUse_blend(getStringFromBoolean(config.useBlend())); - - record.setBlend_method(config.getBlendMethod().getName()); - record.setBlend_hours(config.getBlendHours()); - - return record; - } - - // ------------------------------------------------------- - public SSHPConfig getSSHPConfig(String locationId) { - String header = "DataMgr.getSshpConfig(): "; - SSHPConfig config = null; - - config = (SSHPConfig) _sshpConfigMap.get(locationId); - if (config == null) { - String whereClause = " "; - loadSSHPConfigList(whereClause); // throw out the returned list, we - // don't need it - config = (SSHPConfig) _sshpConfigMap.get(locationId); - } - - return config; - - } - - // ------------------------------------------------------- - - private SSHPConfig getSshpConfigFromRecord(SshpConfigRecord record) { - SSHPConfig config = new SSHPConfig(); - - config.setLid(record.getLid()); - - config.setBasinId(record.getBasin_id()); - config.setPostingTime(record.getPostingtime()); - - config.setModelPref(record.getModel_pref()); - config.setSourcePref(record.getSource_pref()); - - config.setUseStaticEvap(getBooleanFromString(record - .getUse_static_evap())); - config.setAutoProcess(getBooleanFromString(record.getAuto_process())); - - config.setUseBlend(getBooleanFromString(record.getUse_blend())); - - ForecastInterpolationMethod method = ForecastInterpolationMethod - .getMethodByName(record.getBlend_method()); - config.setBlendMethod(method); - - config.setBlendHours(record.getBlend_hours()); - - return config; - } - - // ------------------------------------------------------- - private boolean getBooleanFromString(String booleanString) { - boolean result = false; - if (booleanString.equalsIgnoreCase("Y")) { - result = true; - } - - return result; - } - - // ------------------------------------------------------- - private String getStringFromBoolean(boolean value) { - String resultString = null; - if (value) { - resultString = "Y"; - } else { - resultString = "N"; - } - - return resultString; - } - - // ------------------------------------------------------- - - public void saveSSHPConfig(SSHPConfig config) { - - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = getSshpConfigRecord(config); - - record.setPostingtime(System.currentTimeMillis()); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - - return; - - } - - // ------------------------------------------------------- - - public void deleteSSHPConfig(SSHPConfig config) { - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = getSshpConfigRecord(config); - - try { - table.delete(record); - _sshpConfigMap.remove(record.getLid()); - } catch (SQLException e) { - logSQLException(e); - } - - return; - - } - - // ------------------------------------------------------- - public List getSSHPConfigList() { - if (_sshpConfigList == null) { - _sshpConfigList = loadSSHPConfigList(" order by lid "); - } - - return _sshpConfigList; - - } - - // ------------------------------------------------------- - - public List loadSSHPConfigList(String whereClause) { - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = null; - List recordList = null; - - _sshpConfigList = new ArrayList(); - - try { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) { - record = (SshpConfigRecord) recordList.get(i); - SSHPConfig config = getSshpConfigFromRecord(record); - _sshpConfigList.add(config); - _sshpConfigMap.put(config.getLid(), config); - } - - } catch (SQLException e) { - logSQLException(e); - } - - return _sshpConfigList; - - } - - // ------------------------------------------------------- - - public List loadAllPreferredSacSmaBasinIds() { - List locationIdList = new ArrayList(); - List sshpConfigList = getSSHPConfigList(); - - for (int i = 0; i < sshpConfigList.size(); i++) { - SSHPConfig config = (SSHPConfig) sshpConfigList.get(i); - String basinId = config.getLid(); - - if (config.getModelPref().equals( - RainfallRunoffModelType.SAC_SMA.getName())) { - locationIdList.add(basinId); - } - } - - return locationIdList; - } - - // ------------------------------------------------------- - public List loadAllLocationIdsToAutoUpdateSacStates() { - List locationIdList = new ArrayList(); - List sshpConfigList = getSSHPConfigList(); - - for (int i = 0; i < sshpConfigList.size(); i++) { - SSHPConfig config = (SSHPConfig) sshpConfigList.get(i); - String locationId = config.getLid(); - - if ((config.getModelPref().equals(RainfallRunoffModelType.SAC_SMA - .getName())) && (config.isAutoProcess())) { - locationIdList.add(locationId); - } - } - - return locationIdList; - } - - // ------------------------------------------------------- - - public RainfallRunoffModelType getPreferredRainfallRunoffModelType( - String locationId) { - String header = "DataMgr.getPreferredRainfallRunoffModelType(): "; - RainfallRunoffModelType type = RainfallRunoffModelType.API_MKC; - - SSHPConfig config = getSSHPConfig(locationId); - - if (config != null) { - String modelPref = config.getModelPref(); - - _logger.log(header + "modelPref = :" + modelPref + ":"); - - type = RainfallRunoffModelType - .getRainfallRunoffModelTypeByName(modelPref); - } - - _logger.log(header + "type = " + type); - - return type; - } - - // --------------------------------------------------------------------------------------- - - public BasinHrapHelper loadBasinHrapHelper(String basinId) { - - BasinHrapHelper basinHrapHelper = initBasinHrapHelper(basinId); - - return basinHrapHelper; - } - - // ---------------------------------------------------------------------------------------- - - private BasinHrapHelper initBasinHrapHelper(String basinId) { - List recordList = null; - String whereClause = new String(); - - LineSegsTable table = new LineSegsTable(this._db); - LineSegsRecord record = null; - - BasinHrapHelper basinHrapSet = null; - - // Go to LineSegs table to get number of rows and HRAP rows and columns - whereClause = " WHERE area_id='" + basinId + "' ORDER BY hrap_row ASC "; - - try { - recordList = table.select(whereClause); - } catch (SQLException e) { - e.printStackTrace(); - } - - for (int i = 0; i < recordList.size(); i++) { - record = (LineSegsRecord) recordList.get(i); - - if (i == 0) { - basinHrapSet = new BasinHrapHelper(basinId, recordList.size()); - basinHrapSet.setIsValid(true); - basinHrapSet.setAreaSize(record.getArea()); - } - - basinHrapSet.setBasinHrapRow(i, record.getHrap_row()); - basinHrapSet.setBasinHrapBegColumn(i, record.getHrap_beg_col()); - basinHrapSet.setBasinHrapEndColumn(i, record.getHrap_end_col()); - } - - if (basinHrapSet == null) { - basinHrapSet = new BasinHrapHelper(basinId, 0); - basinHrapSet.setIsValid(false); - } - - return (basinHrapSet); - - } // end of getBasinRowsCols method - - // ------------------------------------------------------------------------------------------------- - - public List getNewerBestQpeXmrgFileTimeList(long lastPostingTime) { - - String header = "DataMgr.getNewerBestQpeXmrgFileTimeList(): "; - - RWResultTable table = new RWResultTable(_db); - RWResultRecord record = null; - List recordList = null; - - List timeList = new ArrayList(); - - try { - String lastPostingTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(lastPostingTime); - String whereString = " WHERE last_save_time >= '" - + lastPostingTimeString + "' ORDER BY obstime "; - - System.out.println(header + " whereString = " + whereString); - recordList = table.select(whereString); - - for (int i = 0; i < recordList.size(); i++) { - record = (RWResultRecord) recordList.get(i); - - long time = record.getObstime(); - timeList.add(new Long(time)); - } - - } - - catch (SQLException e) { - logSQLException(e); - } - - return timeList; - - } - - // ------------------------------------------------------------------------------------------------- - public List getNewerRfcXmrgFileTimeList(long lastPostingTime, - String gridDirectoryString, SimpleDateFormat dateFormat) { - String header = "DataMgr.getNewerRfcXmrgTimeList(): "; - - File directory = new File(gridDirectoryString); - File[] fileArray = directory.listFiles(); - List timeList = new ArrayList(); - - // for each file in the directory - // examine the last update time, - // if it is newer than the last update time, - // then parse out its time and then add it to the list - // If it fails to parse, then we don't want it anyway; - // It is some other type of file that got in the directory somehow. - for (int i = 0; i < fileArray.length; i++) { - File file = fileArray[i]; - long lastModTime = 0; - try { - - lastModTime = file.lastModified(); - if (lastModTime >= lastPostingTime) // is it new? - { - _logger.log(header - + "lastModTime = " - + DbTimeHelper - .getDateTimeStringFromLongTime(lastModTime) - + " fileName = " + file.getName()); - - Date date = dateFormat.parse(file.getName()); - long gridTime = date.getTime(); - - _logger.log(header - + "gridTime = " - + DbTimeHelper - .getDateTimeStringFromLongTime(gridTime) - + " fileName = " + file.getName()); - - timeList.add((new Long(gridTime))); - } - } catch (ParseException e) { - // some other kind of file was parsed, - // we don't want it - } - } - - return timeList; - - } - - // ------------------------------------------------------------------------------------------------- - - public List loadUnitHydrographEntryList(String lid, String orderClause) - // Used by UnitHydrographEditor to retrieve data from the UnitGraph table - { - List unitHydrographRecordList = null; - String where = " WHERE lid='" + lid + "' " + orderClause; - UnitGraphTable table = new UnitGraphTable(_db); - - try { - unitHydrographRecordList = table.select(where); - } - - catch (SQLException e) { - logSQLException(e); - } - - return getUnitHydrographEntryListFromUnitGraphRecordList(unitHydrographRecordList); - } - - // ------------------------------------------------------------------------------------------------- - - public List loadUnitHydrographDescriptorList(String lid) { - List descList = new ArrayList(); - UnitGraphTable table = new UnitGraphTable(_db); - List recordList = null; - - String where = " WHERE lid='" + lid + "' ORDER BY area_id, model, dur "; - - String oldAreaId = null; - String oldModel = null; - int oldDur = 0; - - try { - recordList = table.select(where); - - boolean addToDescriptorList = false; - - for (int i = 0; i < recordList.size(); i++) { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(i); - - if (i > 0) { - // if the record is not the same as the previous record then - // add it to the - // list - if ((!record.getArea_id().equals(oldAreaId)) - || (!record.getModel().equals(oldModel)) - || (record.getDur() != oldDur)) { - addToDescriptorList = true; - } - - } else // i == 0, there are no "old" variables - { - addToDescriptorList = true; - - } - - if (addToDescriptorList) { - UnitHydrographDescriptor desc = new UnitHydrographDescriptor( - record.getLid(), record.getArea_id(), - record.getModel(), record.getDur()); - - descList.add(desc); - - addToDescriptorList = false; - } - - // set the "old" variables for next iteration - oldAreaId = record.getArea_id(); - oldModel = record.getModel(); - oldDur = record.getDur(); - - } - } - - catch (SQLException e) { - logSQLException(e); - } - - /* - * for (int i = 0; i < descList.size(); i++) { UnitHydrographDescriptor - * desc = (UnitHydrographDescriptor) descList.get(i); - * System.out.println(desc); } - */ - - return descList; - - } // loadUnitHydrographDescriptorList - - // ------------------------------------------------------------------------------------------------- - - private List getUnitHydrographEntryListFromUnitGraphRecordList( - List unitGraphRecordList) { - List unitHydrographEntryList = new ArrayList(); - - for (int i = 0; i < unitGraphRecordList.size(); i++) { - UnitHydrographEntry newUnitHydrographEntry = new UnitHydrographEntry(); - UnitGraphRecord unitGraphRecord = (UnitGraphRecord) unitGraphRecordList - .get(i); - - newUnitHydrographEntry.setLocationId(unitGraphRecord.getLid()); - newUnitHydrographEntry.setAreaId(unitGraphRecord.getArea_id()); - newUnitHydrographEntry.setModel(unitGraphRecord.getModel()); - newUnitHydrographEntry.setDur(unitGraphRecord.getDur()); - newUnitHydrographEntry.setOrdinal(unitGraphRecord.getOrdinal()); - - newUnitHydrographEntry.setDischarge(unitGraphRecord.getDischarge()); - - unitHydrographEntryList.add(newUnitHydrographEntry); - } - - return unitHydrographEntryList; - } - - // ------------------------------------------------------------------------------------------------- - - public List getRatingShift(String lid) - // Used by RatingCurveEditor to retrieve data from the RatingShift table - { - List ratingShiftRecordList = null; - String where = " WHERE lid='" + lid + "' ORDER BY date desc"; - RatingShiftTable table = new RatingShiftTable(_db); - - try { - ratingShiftRecordList = table.select(where); - } catch (SQLException e) { - _logger.log("Error code = " + e.getMessage()); - _logger.log("error retrieving SacSmaStateRecord: " + where); - } - - List ratingShiftEntryList = null; - - if (ratingShiftRecordList != null) { - ratingShiftEntryList = getRatingShiftEntryListFromRatingShiftRecordList(ratingShiftRecordList); - } - - return ratingShiftEntryList; - } - - // ------------------------------------------------------------------------------------------------- - - private List getRatingShiftEntryListFromRatingShiftRecordList( - List recordList) { - List ratingShiftEntryList = new ArrayList(); - - for (int i = 0; i < recordList.size(); i++) { - RatingShift addRatingShiftEntry = new RatingShift(); - RatingShiftRecord record = (RatingShiftRecord) recordList.get(i); - - addRatingShiftEntry.setLid(record.getLid()); - addRatingShiftEntry.setDate(record.getDate()); - addRatingShiftEntry.setShiftAmount(record.getShift_amount()); - - if (record.getActive().trim().equalsIgnoreCase("T")) { - addRatingShiftEntry.setActive(true); - } else { - addRatingShiftEntry.setActive(false); - } - - ratingShiftEntryList.add(addRatingShiftEntry); - } - return ratingShiftEntryList; - } - - // ------------------------------------------------------------------------------------------------- - - public void saveUnitHydrographEntry(UnitHydrographEntry entry) { - UnitGraphRecord record = new UnitGraphRecord(); - UnitGraphTable table = new UnitGraphTable(_db); - - record = getUnitGraphRecordFromUnitHydrographEntry(entry); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------------------------------------------------- - - private UnitGraphRecord getUnitGraphRecordFromUnitHydrographEntry( - UnitHydrographEntry entry) { - UnitGraphRecord returnRecord = new UnitGraphRecord(); - - returnRecord.setLid(entry.getLocationId()); - returnRecord.setArea_id(entry.getAreaId()); - returnRecord.setModel(entry.getModel()); - returnRecord.setDur(entry.getDur()); - returnRecord.setOrdinal(entry.getOrdinal()); - - returnRecord.setDischarge(entry.getDischarge()); - - return returnRecord; - } - - // ------------------------------------------------------------------------------------------------- - - public void removeUnitHydrographEntry(UnitHydrographEntry entry) { - UnitGraphRecord record = new UnitGraphRecord(); - UnitGraphTable table = new UnitGraphTable(_db); - - record = getUnitGraphRecordFromUnitHydrographEntry(entry); - - try { - table.delete(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------------------------------------------------- - - public void deleteUnitHydrograph(String lid, String basinId, String model, - int duration) { - UnitGraphTable table = new UnitGraphTable(_db); - String whereString = " WHERE lid='" + lid + "' AND area_id='" + basinId - + "' AND model = '" + model + "' AND dur = " + duration; - - try { - table.delete(whereString); - } catch (SQLException e) { - logSQLException(e); - } - } - - // ------------------------------------------------------------------------------------------------- - - public void deleteRatingShift(RatingShift shift) { - RatingShiftRecord record = new RatingShiftRecord(); - RatingShiftTable table = new RatingShiftTable(_db); - - record = getRatingShiftRecordFromRatingShift(shift); - try { - table.delete(record); - } catch (SQLException e) { - logSQLException(e); - } - } - - public void saveRatingShift(RatingShift shift) { - RatingShiftRecord record = new RatingShiftRecord(); - RatingShiftTable table = new RatingShiftTable(_db); - - record = getRatingShiftRecordFromRatingShift(shift); - - try { - table.insertOrUpdate(record); - } catch (SQLException e) { - logSQLException(e); - } - - } - - private RatingShiftRecord getRatingShiftRecordFromRatingShift( - RatingShift shift) { - RatingShiftRecord record = new RatingShiftRecord(); - - record.setLid(shift.getLid()); - record.setDate(shift.getDate()); - record.setShift_amount(shift.getShiftAmount()); - if (shift.isActive()) { - record.setActive("T"); - } else { - record.setActive("F"); - } - return record; - } - - /* - * private void insertParams(String locationId) { SacSmaParamsTable table = - * new SacSmaParamsTable(_db); SacSmaParamsRecord record = new - * SacSmaParamsRecord(); - * - * long currentTime = System.currentTimeMillis(); - * - * - * record.setBasin_id(locationId); - * - * record.setValidtime(currentTime); record.setPostingtime(currentTime); - * - * record.setUztwm(65.0); record.setUzfwm(30.0); record.setUzk(0.180); - * record.setPctim(0.010); record.setAdimp(0.130); record.setRiva(0.03); - * record.setZperc(125.0); record.setRexp(3.5); record.setLztwm(175.0); - * record.setLzfsm(100.0); record.setLzfpm(260.0); record.setLzsk(0.0450); - * record.setLzpk(0.0030); record.setPfree(0.60); record.setRserv(0.30); - * record.setSide(0.00); - * - * try { table.insert(record); } catch (SQLException e) { - * logSQLException(e); } } - */ - // ------------------------------------------------------- - /* - * private void insertState(String locationId) { SacSmaStateTable table = - * new SacSmaStateTable(_db); SacSmaStateRecord record = new - * SacSmaStateRecord(); - * - * long currentTime = System.currentTimeMillis(); - * - * record.setBasin_id(locationId); - * - * record.setValidtime(currentTime); record.setPostingtime(currentTime); - * - * record.setUztwc(63.33); record.setUzfwc(0.090); record.setLztwc(135.71); - * record.setLzfsc(12.187); record.setLzfpc(165.26); - * record.setAdimc(215.75); - * - * try { table.insert(record); } catch (SQLException e) { - * logSQLException(e); } } - */ - -} // end class DataMgr diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/FFHDescriptor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/FFHDescriptor.java deleted file mode 100644 index 621f8c71b3..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/FFHDescriptor.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Created on Apr 19, 2004 - * - * - */ -package ohd.hseb.sshp; - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; - -/** - * @author GobsC - * - * - */ -public class FFHDescriptor -{ - private String _locationId = null; - - private AbsTimeMeasurement _ffhMeasurement = null; - private int _ihfsDurationCode = 0; - - private boolean _isGridded = false; - private boolean _isDefaultValue = false; - - private String _description = null; - -// --------------------------------------------------------------- - - public FFHDescriptor(String locationId, - AbsTimeMeasurement measurement, - int ihfsDurationCode, - boolean isGridded) - { - _locationId = locationId; - _ffhMeasurement = measurement; - _ihfsDurationCode = ihfsDurationCode; - _isGridded = isGridded; - - return; - } - -// --------------------------------------------------------------- - - - - public void setFfhMeasurement(AbsTimeMeasurement ffhMeasurement) - { - _ffhMeasurement = ffhMeasurement; - } -// --------------------------------------------------------------- - - public Measurement getFfhMeasurement() - { - return _ffhMeasurement; - } -// --------------------------------------------------------------- - public double getValueInInches() - { - return _ffhMeasurement.getValue(MeasuringUnit.inches); - } -// --------------------------------------------------------------- - public long getTime() - { - return _ffhMeasurement.getTime(); - } - -// --------------------------------------------------------------- - - /** - * @param ihfsDurationCode The ihfsDurationCode to set. - */ - public void setIhfsDurationCode(int ihfsDurationCode) - { - _ihfsDurationCode = ihfsDurationCode; - } - -// --------------------------------------------------------------- - - /** - * @return Returns the ihfsDurationCode. - */ - public int getIhfsDurationCode() - { - return _ihfsDurationCode; - } - - -// --------------------------------------------------------------- - - public void setDescription(String description) - { - _description = description; - } -// --------------------------------------------------------------- - - public String getDescription() - { - return _description; - } -// --------------------------------------------------------------- - - public void setGridded(boolean isGridded) - { - _isGridded = isGridded; - } -// --------------------------------------------------------------- - - public boolean isGridded() - { - return _isGridded; - } - - //---------------------------------------------------------------------- - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + "Z"; - - return timeString; - } - - -// --------------------------------------------------------------- - public boolean equals(FFHDescriptor descriptor) - { - boolean result = false; - - if ( - - (this.getTime() == descriptor.getTime()) && - (this._isGridded == descriptor._isGridded)&& - (this._ffhMeasurement.equals(descriptor._ffhMeasurement) ) - - - ) - { - result = true; - } - - - return result; - - } - -// --------------------------------------------------------------- - public void setIsDefaultValue(boolean isDefaultValue) - { - _isDefaultValue = isDefaultValue; - } -// --------------------------------------------------------------- - - public boolean isDefaultValue() - { - return _isDefaultValue; - } -// --------------------------------------------------------------- - - public String toString() - { - String outString = null; - - String timeString = getDateTimeStringToMinutes(this.getTime()); - - double value = this.getValueInInches(); - - String ffhTypeString= null; - - if (this.isGridded()) - { - ffhTypeString = "Gridded"; - } - else if (! isDefaultValue() ) - { - ffhTypeString = "Areal"; - } - else - { - ffhTypeString = "BOGUS DEFAULT"; - } - - NumberFormat format = new DecimalFormat("0.00"); - - String formattedString = format.format(value); - - int duration = _ihfsDurationCode - 1000; - - outString = _locationId + " " + timeString + " " + - duration + " hr " + - ffhTypeString + " FFH=" + - formattedString; - - return outString; - } //end toString - - - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/FcstTsDescriptor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/FcstTsDescriptor.java deleted file mode 100644 index 6e579dc695..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/FcstTsDescriptor.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Created on Dec 9, 2003 - * - * Filename : FcstTsDescriptor.java - * Author : Gautam Sood - * Last Revision Date : Dec 9, 2003 - * - */ -package ohd.hseb.sshp; - -import java.text.DecimalFormat; -import java.text.NumberFormat; - - -public class FcstTsDescriptor implements IngestFilterTsDescriptor -{ - private String _tableName = null; - private String _lid = null; - private String _pe = null; - private String _ts = null; - private String _extremum = null; - private String _shef_qual_code = null; - private String _product_id = null; - private double _value = 0.0; - private float _probability = 0; - private int _quality_code = 0; - private short _revision = 0; - private short _dur = 0; - private long _producttime = 0; - private long _postingtime = 0; - private long _validtime = 0; - private long _basistime = 0; - - //***************************************************************************** - // Empty constructor - //***************************************************************************** - public FcstTsDescriptor(String tableName) - { - setTableName(tableName); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( short dur ) - { - _dur = dur; - } - - public short getDur() - { - return _dur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setValue ( double value ) - { - _value = value; - } - - public double getValue() - { - return _value; - } - - public void setShef_qual_code( String shef_qual_code ) - { - _shef_qual_code = shef_qual_code; - } - - public String getShef_qual_code() - { - return _shef_qual_code; - } - - public void setQuality_code( int quality_code ) - { - _quality_code = quality_code; - } - - public int getQuality_code() - { - return _quality_code; - } - - public void setRevision( short revision ) - { - _revision = revision; - } - - public short getRevision() - { - return _revision; - } - - public void setProduct_id( String product_id ) - { - _product_id = product_id; - } - - public String getProduct_id() - { - return _product_id; - } - - public void setProducttime( long producttime ) - { - _producttime = producttime; - } - - public long getProducttime() - { - return _producttime; - } - - public void setPostingtime( long postingtime ) - { - _postingtime = postingtime; - } - - public long getPostingtime() - { - return _postingtime; - } - - public void setProbability( float probability ) - { - _probability = probability; - } - - public float getProbability() - { - return _probability; - } - - public void setValidtime( long validtime ) - { - _validtime = validtime; - } - - public long getValidtime() - { - return _validtime; - } - - public void setBasistime( long basistime ) - { - _basistime = basistime; - } - - public long getBasistime() - { - return _basistime; - } - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat f = new DecimalFormat(formatString); - - String outString = "FcstHeight: " + - " Lid = " + _lid + - " Table NAme = " + _tableName + - " pe = " + _pe + - " ts = " + _ts + "\n" + - " Extremum = " + _extremum + - " Shef_qual_code = " + _shef_qual_code + - " Product ID = " + _product_id + "\n" + - " Value = " + f.format( _value ) + - " Probability = " + f.format( _probability ) + - " Quality Code = " + _quality_code + "\n" + - " Revision = " + _revision + - " Dur = " + _dur + - " Product Time = " + _producttime + "\n" + - " Posting Time = " + _postingtime + - " Valid Time = " + _validtime + - " Basis Time = " + _basistime; - return outString; - } - - public void setTableName(String tableName) - { - _tableName = tableName; - } - - public String getTableName() - { - return _tableName; - } -} - diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/ForecastPoster.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/ForecastPoster.java deleted file mode 100644 index a7469aa2bb..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/ForecastPoster.java +++ /dev/null @@ -1,1194 +0,0 @@ -/* This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package ohd.hseb.sshp; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.RiverStatusRecord; -import ohd.hseb.ihfsdb.generated.RiverStatusTable; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.RpfParamsTable; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -/** - * Provides functions to load the max fcst info into the RiverStatus table. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * May 13, 2011  8079       jnjanga
- * 
- * 
- * - * @see com.raytheon.edex.plugin.shef.database.PostShef - * @author jnjanga - * @version 1.0 - */ - -public class ForecastPoster { - - private long basishrs = 72; - - private long fcsthrs = 72; - - private long obshrs = 72; - - private String basis_hours_str = null; - - private boolean isHoursLoad = false; - - private FileLogger logger = null; - - private Database db = null; - - public static final String MISSING = "-9999"; - - public static final int MISSING_VALUE = -9999; - - public static final int QUESTIONABLE_BAD_THRESHOLD = 1073741824; - - /** - * Constructor - * - * @param db - * @param logger - */ - public ForecastPoster(Database db, Logger logger) { - this.logger = (FileLogger) logger; - this.db = db; - } - - /** - * Loads the max fcst info into the RiverStatus table for the current - * location and pe. - * - * @param db - * The database - * - * @param lid - * The location id - * @param pe - * The physical element - * @param ts - * The type source - * @throws SQLException - */ - public void loadMaxFcstItem(String lid, String pe, String ts) - throws SQLException { - boolean useLatest = false; - long basisBeginTime = 0; - ArrayList fcstList = null; - Forecast maxFcstfcst = null; - int qcFilter = 1; - - /* - * get the setting for the use_latest_fcst field for the current - * location from the riverstat table. - */ - - String useLatestFcst = getUseLatestForecast(lid); - - if (useLatestFcst == null) { - useLatest = true; - } else { - if (useLatestFcst.equalsIgnoreCase("F")) { - useLatest = false; - } else { - useLatest = true; - } - } - - /* - * get the forecast time series for this location, pe, and ts using any - * instructions on any type-source to screen and whether to use only the - * latest basis time - */ - basisBeginTime = getBasisTime(); - - fcstList = (ArrayList) buildTsFcstRiv(lid, pe, ts, qcFilter, - useLatest, basisBeginTime); - - /* - * find the data for this location, pe, and ts given the forecast - * time-series and the count of values in it. if data found, determine - * its max and load the value - */ - if ((fcstList != null) && (fcstList.size() > 0)) { - maxFcstfcst = findMaxFcst(fcstList); - boolean updateFlag = updateRiverStatus(lid, pe, ts); - /* load the maxim data into the RiverStatus table */ - loadRiverStatus(maxFcstfcst, updateFlag); - } - - return; - } - - private long getBasisTime() { - - String hourQuery = "select obshrs,fcsthrs from RpfParams"; - long currentTime = System.currentTimeMillis(); - long basisBeginTime = 0; - Statement stmt = null; - ResultSet rs = null; - - /* - * This code sets the time values - */ - try { - if (!isHoursLoad) { - RpfParamsTable rpfTb = new RpfParamsTable(db); - stmt = db.newStmtForScrollableRset(); - rs = rpfTb.executeQuery(stmt, hourQuery); - if (rs.next()) { - obshrs = rs.getLong("obshrs"); - fcsthrs = rs.getLong("fcsthrs"); - } else { - logger.log("No fcsts in RpfParams table, using defaults"); - } - - rs.close(); - stmt.close(); - - if (basis_hours_str != null) { - basishrs = Long.parseLong(basis_hours_str); - if ((basishrs <= 0) || (basishrs > 480)) { - logger.log("invalid value for basis_hours_filter token: " - + basishrs); - basishrs = 72; - } - } - isHoursLoad = true; - } - } catch (Exception e) { - logger.log(" - PostgresSQL error in getBasisTime()"); - logger.printStackTrace(e); - } - - basisBeginTime = currentTime - (basishrs * 3600 * 1000); - return basisBeginTime; - } - - /** - * Determines if the lid,pe,ts already exists and whether or not the - * riverstatus table needs to be updated. - * - * @param lid - * - locationId - * @param pe - * - Physical Element - * @param ts - * - Timestamp - * @return - */ - - private boolean updateRiverStatus(String lid, String pe, String ts) { - Statement stmt = null; - boolean rval = false; - - String query = "select lid " + "from riverstatus where lid = '" + lid - + "' and " + "pe = '" + pe + "' and " + "ts = '" + ts + "'"; - - try { - RiverStatusTable rst = new RiverStatusTable(db); - stmt = db.newStmtForScrollableRset(); - ResultSet rs = rst.executeQuery(stmt, query); - - if (rs.next()) - rval = true; - rs.close(); - stmt.close(); - } catch (Exception e) { - logger.log(" - PostgresSQL error searching riverstatus"); - logger.log("Query = [" + query + "]"); - logger.printStackTrace(e); - - } - - return rval; - } - - /** - * Loads the max fcst info into the RiverStatus table for the current - * location and pe. - * - * @param fcst - * - Forecast fcst to load - * @param updateFlag - * - the boolean value if an update versus an insert should be - * performed - * @return - status of action, 1 is good, 0 is bad - */ - public synchronized int loadRiverStatus(Forecast fcst, Boolean updateFlag) { - - int status = -1; - - // turn fcst into a riverstatus record - RiverStatusRecord record = new RiverStatusRecord(); - record.setLid(fcst.getLid()); - record.setPe(fcst.getPe()); - record.setDur(fcst.getDur()); - record.setTs(fcst.getTs()); - record.setExtremum(fcst.getExtremum()); - record.setProbability(fcst.getProbability()); - record.setValidtime(fcst.getValidTime().getTime()); - record.setBasistime(fcst.getBasisTime().getTime()); - record.setValue(fcst.getValue()); - try { - RiverStatusTable rst = new RiverStatusTable(db); - - if (updateFlag) { - status = rst.insertOrUpdate(record); - } else { - status = rst.insert(record); - } - - } catch (Exception e) { - logger.log("lid = [" + fcst.getLid() + "]"); - logger.log("PE = [" + fcst.getPe() + "]"); - logger.log("Duration = [" + fcst.getDur() + "]"); - logger.log("TS = [" + fcst.getTs() + "]"); - logger.log("Extremum = [" + fcst.getExtremum() + "]"); - logger.log("Probability = [" + fcst.getProbability() + "]"); - logger.log("valid timestamp = [" + fcst.getValidTime() + "]"); - logger.log("basis timestamp = [" + fcst.getBasisTime() + "]"); - logger.log("Data Value = [" + fcst.getValue() + "]"); - - logger.printStackTrace(e); - if (updateFlag) { - logger.log(" - PostgresSQL error updating into riverstatus"); - } else { - logger.log(" - PostgresSQL error inserting into riverstatus"); - } - - } - - return status; - } - - /** - * Get the Use Latest Forecast flag from riverstat table. - * - * @param lid - * - The location id - * @return The use latest forecast flag, or null if nothing in db - */ - private String getUseLatestForecast(String lid) { - String sql = "select use_latest_fcst from riverstat where lid = '" - + lid + "'"; - String useLatest = null; - Statement stmt = null; - ResultSet rs = null; - - try { - RiverstatTable rstb = new RiverstatTable(db); - stmt = db.newStmtForScrollableRset(); - rs = rstb.executeQuery(stmt, sql); - if (rs.next()) - useLatest = rs.getString("use_latest_fcst"); - rs.close(); - stmt.close(); - } catch (SQLException e) { - logger.log("Error executing getUseLatestForecast(" + lid + ")"); - logger.printStackTrace(e); - } - return useLatest; - } - - /** - * This gets the max forecast value from a forecast time-series that has - * already been prepared. This function returns the ts, value, basistime, - * and validtime for the maximum forecast value. - * - * @param fcstList - * ArrayList of Forecast data - * @return The max Forecast object - */ - private Forecast findMaxFcst(ArrayList fcstList) { - Forecast max = null; - double maxValue = MISSING_VALUE; - int maxIndex = MISSING_VALUE; - - /* just in case */ - if ((fcstList == null) || (fcstList.size() == 0)) { - return null; - } - - /* loop and get the max */ - for (int i = 0; i < fcstList.size(); i++) { - if (fcstList.get(i).getValue() > maxValue) { - maxValue = fcstList.get(i).getValue(); - maxIndex = i; - } - } - - /* if for some bizarre reason, load the first fcst */ - if (maxIndex == MISSING_VALUE) { - logger.log("ERROR - find_maxfcst couldn't find max?!\n"); - maxIndex = 0; - } - - max = fcstList.get(maxIndex); - - return max; - } - - /** - * Processes forecast data for the given table, lid and pe. - * - * @param table - * - The table - * @param lid - * - The location id - * @param pe - * - The physical element - */ - public boolean loadMaxFcstData(String table, String lid, String pe) { - Statement stmt = null; - ResultSet rs = null; - boolean status = true; - - String sql = "select DISTINCT(ts) " + "from " + table - + " where lid = '" + lid + "' and " + "pe = '" + pe + "' and " - + "validtime > CURRENT_TIMESTAMP and " + "probability < 0.0"; - try { - FcstHeightTable fht = new FcstHeightTable(db); - stmt = db.newStmtForScrollableRset(); - rs = fht.executeQuery(stmt, sql); - while (rs.next()) { - loadMaxFcstItem(lid, pe, rs.getString("ts")); - } - rs.close(); - stmt.close(); - } catch (SQLException se) { - status = !status; - logger.log("Error executing loadMaxFcsftData(" + table + ", " + lid - + ", " + pe + ")"); - logger.printStackTrace(se); - } - return status; - } - - /** - * This function assembles a forecast time series for a given location and - * pe. The data are retrieved for: 1) either the specified type-source or - * for the type-source defined in the ingest filter as the one to use, based - * on its rank; and for 2) either all forecast values regardless of basis - * time or only those forecasts with the latest basis time. 3) for - * non-probabilistic values only. - * - * It returns a times series of values in an array of structures, and also - * returns the count of values. - * - * Presuming that the duration and extremum values in the forecast table - * never yield duplicates, then there can only be duplicates for the same - * validtime due to multiple basis times. - * - * There is a passed in limit regarding how far in the future data is - * considered, and how old the forecast (basistime) can be. - * - * This function is needed since some locations have short-term forecasts - * and long-term forecasts, both of which are valid and do not prempt the - * other. This avoids problems with the previous method where the software - * always used the forecast with the latest creation time and ignored all - * other forecasts, for certain purposes. - * - * The approach herein does NOT assume that the creation data corresponds to - * the valid time covered - i.e. it does NOT require that long-term forecast - * have the latest creation time. The heart of the logic for this function - * is contained in the adjust_startend() function. - * - * @param lid - * @param pe - * @param tsFilter - * @param qcFilter - * @param useLatest - * @param basisBegintime - * @return A list of forecast records - */ - private List buildTsFcstRiv(String lid, String pe, - String tsFilter, int qcFilter, boolean useLatest, - long basisBegintime) { - int fcstCount = 0; - int keepCount = 0; - String useTs = null; - String tableName = null; - String sql = null; - String sqlForecast = null; - java.sql.Timestamp basisTimeAnsi = null; - - int[] doKeep = null; - Statement stmt = null; - Statement stmt2 = null; - ResultSet ulHead = null; - int ulCount = 0; - List fcstHead = null; - Forecast fcstHght = null; - - List fcstList = new ArrayList(); - Forecast forecast = null; - DbTable dbTable = null; - - if ((tsFilter == null) || (tsFilter.length() == 0)) { - useTs = getBestTs(lid, pe, "F%", 0); - if (useTs == null) - return null; - } else { - useTs = tsFilter; - } - - try { - if (pe.startsWith("H") || pe.startsWith("h")) - tableName = "FcstHeight"; - else - tableName = "FcstDischarge"; - - dbTable = getDbTableInstance(db, tableName); - - basisTimeAnsi = new Timestamp(basisBegintime); - /* - * retrieve a list of unique basis times; use descending sort. only - * consider forecast data before some ending time, and with some - * limited basis time ago - */ - - sql = "SELECT DISTINCT(basistime) FROM " + tableName + " " - + "WHERE lid = '" + lid + "' and " + "pe = '" + pe - + "' and " + "ts = '" + useTs + "' and " - + "validtime >= CURRENT_TIMESTAMP and " + "basistime >= '" - + basisTimeAnsi + "' and " + "value != " + MISSING_VALUE - + " and " + "quality_code >= " + QUESTIONABLE_BAD_THRESHOLD - + " " + "ORDER BY basistime DESC "; - - stmt = db.newStmtForScrollableRset(); - ulHead = dbTable.executeQuery(stmt, sql); - ulCount = getResultSetSize(ulHead); - - /* - * retrieve the data; the ordering by validtime is important. as - * before, limit the forecast time valid time window and as needed, - * the age of the forecast (basistime). - */ - - sqlForecast = "SELECT lid,pe,dur,ts,extremum,probability,validtime,basistime,value " - + "FROM " - + tableName - + " " - + "WHERE lid = '" - + lid - + "' AND " - + "pe = '" - + pe - + "' AND " - + "ts = '" - + useTs - + "' AND " - + "validtime >= CURRENT_TIMESTAMP AND " - + "probability < 0.0 AND "; - - if (useLatest || ulCount == 1) { - java.sql.Timestamp tempStamp = null; - ulHead.next(); - tempStamp = ulHead.getTimestamp("basistime"); - sqlForecast += "basistime >= '" + tempStamp + "' AND "; - - } else { - sqlForecast += "basistime >= '" + basisTimeAnsi + "' AND "; - } - - sqlForecast += "value != " + Integer.parseInt(MISSING) + " AND " - + "quality_code >= " + Integer.parseInt(MISSING) + " " - + "ORDER BY validtime ASC"; - - stmt2 = db.newStmtForScrollableRset(); - ResultSet oa = dbTable.executeQuery(stmt2, sqlForecast); - - int soa = getResultSetSize(oa); - - if ((oa != null) && soa > 0) { - fcstHead = new ArrayList(soa); - while (oa.next()) { - fcstHght = new Forecast(); - Date tmpDate = null; - fcstHght.setLid(oa.getString("lid")); - fcstHght.setPe(oa.getString("Pe")); - fcstHght.setDur(oa.getShort("dur")); - fcstHght.setTs(oa.getString("ts")); - fcstHght.setExtremum(oa.getString("extremum")); - fcstHght.setProbability(oa.getFloat("probability")); - tmpDate = new Date(oa.getTimestamp("validtime").getTime()); - fcstHght.setValidTime(tmpDate); - tmpDate = new Date(oa.getTimestamp("basistime").getTime()); - fcstHght.setBasisTime(tmpDate); - fcstHght.setValue(oa.getDouble("value")); - fcstHead.add(fcstHght); - } - } - - if (fcstHead != null) { - fcstCount = fcstHead.size(); - } - - /* - * define a local array to determine which items in the time series - * to keep and return - */ - if (fcstCount > 0) { - doKeep = new int[fcstCount]; - } else { - return null; - } - - /* - * if only getting the latest basis time's data or only one basis - * time was found, then consider all; otherwise, need to adjoin/butt - * the time series together for the multiple basis times. - */ - - if (useLatest || ulCount <= 1) { - for (int i = 0; i < doKeep.length; i++) { - doKeep[i] = 1; - } - } else { - doKeep = setFcstKeep(ulHead, ulCount, fcstHead); - } - - /* - * now load the values and info to return, knowing which items to - * keep since all the values have been tagged. first get the count - * of the number of values to keep and allocate the data - */ - - for (int j = 0; j < fcstCount; j++) { - if (doKeep[j] == 1) { - keepCount++; - } - } - - for (int y = 0; y < fcstCount; y++) { - forecast = new Forecast(); - if (doKeep[y] == 1) { - forecast.setLid(fcstHead.get(y).getLid()); - forecast.setPe(fcstHead.get(y).getPe()); - convertDur(fcstHead.get(y).getDur(), forecast); - forecast.setTs(fcstHead.get(y).getTs()); - forecast.setExtremum(fcstHead.get(y).getExtremum()); - forecast.setValidTime(fcstHead.get(y).getValidTime()); - forecast.setBasisTime(fcstHead.get(y).getBasisTime()); - forecast.setValue(fcstHead.get(y).getValue()); - } - fcstList.add(forecast); - } - - stmt.close(); - stmt2.close(); - } catch (Error e) { - logger.log(" - SQL error in buildTsFcstRiv"); - logger.printStackTrace(e); - } catch (Exception e) { - logger.log("Query = [" + sql + "]"); - logger.log("Query = [" + sqlForecast + "]"); - logger.log(" - SQL Exception in buildTsFcstRiv"); - logger.printStackTrace(e); - } - - return fcstList; - } - - private int getResultSetSize(ResultSet rs) { - int rowcount = 0; - try { - if (rs.last()) { - rowcount = rs.getRow(); - rs.beforeFirst(); - } - } catch (SQLException e) { - logger.log("Error computing Resultset size !"); - logger.printStackTrace(e); - } - return rowcount; - } - - /** - * Converts duration int to String character. - * - * @param dur - * - The duration value - * @return The single character duration value - */ - private void convertDur(short dur, Forecast data) { - String value = null; - String durationCode = null; - - switch (dur) { - case 0: - value = "I"; - break; - case 1: - value = "U"; - break; - case 5: - value = "E"; - break; - case 10: - value = "G"; - break; - case 15: - value = "C"; - break; - case 30: - value = "J"; - break; - case 1001: - value = "H"; - break; - case 1002: - value = "B"; - break; - case 1003: - value = "T"; - break; - case 1004: - value = "F"; - break; - case 1006: - value = "Q"; - break; - case 1008: - value = "A"; - break; - case 1012: - value = "K"; - break; - case 1018: - value = "L"; - break; - case 2001: - value = "D"; - break; - case 2007: - value = "W"; - break; - // case 'N': - // Not sure what to return. Shef maunal explanation: - // N Mid month, duration for the period from the 1st day of the - // month to and ending on the - // 15th day of the same month - // break; - case 3001: - value = "M"; - break; - case 4001: - value = "Y"; - break; - case 5004: - value = "P"; - break; - case 5000: { - value = "Z"; - break; - } - case 5001: - value = "S"; - break; - case 5002: - value = "R"; - break; - case 5005: - value = "X"; - break; - default: { - // Anything that didn't get picked up above is - // probably a variable duration. - if (dur >= 7000) { - value = "V"; - durationCode = "S"; - } else if (dur < 1000) { - value = "V"; - durationCode = "N"; - } else if (dur < 2000) { - value = "V"; - durationCode = "H"; - } else if (dur < 3000) { - value = "V"; - durationCode = "D"; - } else if (dur < 4000) { - value = "V"; - durationCode = "M"; - } else if (dur < 5000) { - value = "V"; - durationCode = "Y"; - } else { - // Not sure what value this would be. - value = "Z"; - } - } - } - - data.setDur(dur); - } - - /** - * Determine which items in the forecast time series to keep, as there may - * be overlap due to multiple time_series. - * - * @param ulHead - * @param count - * @param fcstHead - * @return - * @throws SQLException - */ - private int[] setFcstKeep(ResultSet ulHead, int count, - List fcstHead) throws SQLException { - int fcstCount = fcstHead.size(); - int ulCount = count; - int[] doKeep = new int[fcstCount]; - int[] basisIndex = new int[fcstCount]; - int[] tsFirstChk = new int[ulCount]; - Timestamp[] startTime = new Timestamp[ulCount]; - Timestamp[] endTime = new Timestamp[ulCount]; - Timestamp[] basisTime = new Timestamp[ulCount]; - Timestamp fcstBasisTime = null; - Timestamp fcstValidTime = null; - Timestamp ulBasisTime = null; - - for (int i = 0; i < ulCount; i++) { - tsFirstChk[i] = 0; - } - - Timestamp validTime = null; - ulHead.beforeFirst(); - for (int i = 0; i < fcstCount; i++) { - - /* find out which basis time's time series this value belongs to */ - - fcstBasisTime = new Timestamp(fcstHead.get(i).getBasisTime() - .getTime()); - - basisIndex[i] = MISSING_VALUE; - - for (int j = 0; ((j < ulCount) && (basisIndex[i] == MISSING_VALUE)); j++) { - ulBasisTime = ulHead.getTimestamp("ts"); - - if (ulBasisTime.compareTo(fcstBasisTime) == 0) { - basisIndex[i] = j; - } - } - - if (basisIndex[i] == MISSING_VALUE) { - logger.log("Unexpected error assigning basis_index for " + i); - } - - /* - * check if the values constitute the start or end times for the - * time series and fcst these times if they do - */ - - validTime = new Timestamp(fcstHead.get(i).getValidTime().getTime()); - - if (tsFirstChk[basisIndex[i]] == 1) { - if (validTime.before(startTime[basisIndex[i]])) { - startTime[basisIndex[i]] = validTime; - } else if (validTime.after(endTime[basisIndex[i]])) { - endTime[basisIndex[i]] = validTime; - } - } else { - startTime[basisIndex[i]] = validTime; - endTime[basisIndex[i]] = validTime; - tsFirstChk[basisIndex[i]] = 1; - } - } - - /* - * for each of the unique basis times, assign the basis time in a - * convenient array for use in the adjust_startend function. - */ - - ulHead.beforeFirst(); - ArrayList bst = new ArrayList(); - while (ulHead.next()) { - bst.add(ulHead.getTimestamp("ts")); - } - basisTime = (Timestamp[]) bst.toArray(); - - /* - * knowing the actual start and end times for the multiple time series, - * loop thru the time series and adjust the start and end times so that - * they reflect the time span to use; i.e. there is no overlap. THIS IS - * THE KEY STEP IN THE PROCESS OF DEFINING AN AGGREGATE VIRTUAL TIME - * SERIES!!! - */ - Object[] tmp = adjustStartEnd(ulCount, basisTime, startTime, endTime); - startTime = (Timestamp[]) tmp[0]; - endTime = (Timestamp[]) tmp[1]; - - /* - * loop thru the complete retrieved time series and only keep the value - * if it lies between the start and end time for this basis time - */ - for (int i = 0; i < fcstCount; i++) { - fcstValidTime = new Timestamp(fcstHead.get(i).getValidTime() - .getTime()); - if ((fcstValidTime.compareTo(startTime[basisIndex[i]]) >= 0) - && (fcstValidTime.compareTo(endTime[basisIndex[i]]) <= 0)) { - doKeep[i] = 1; - } else { - doKeep[i] = 0; - } - } - return doKeep; - } - - /** - * This method uses the time series with the latest basis time first, and - * uses it in its entirety. Then the time series with the next latest basis - * time is used. If it overlaps portions of the already saved time series, - * then only that portion which doesn't overlap is used. This process - * continues until all time series have been considered. In essences, this - * method adjoins adjacent time series. - * - * @param count - * @param basisTime - * @param startValidTime - * @param endValidTime - * @return - */ - private Object[] adjustStartEnd(int count, Timestamp[] basisTime, - Timestamp[] startValidTime, Timestamp[] endValidTime) { - boolean found = false; - int currentIndex = 0; - int[] basisOrder = new int[count]; - Timestamp fullStartValidTime = null; - Timestamp fullEndValidTime = null; - Timestamp tmpTime = null; - Timestamp zero = new Timestamp((new Date(0)).getTime()); - Object[] rval = new Object[2]; // [startValidTime[]] [endValidTime[]] - - for (int i = 0; i < count; i++) { - basisOrder[i] = -1; - } - - /* - * find the order of the time series by their latest basis time. if two - * time series have the same basis time, use the one that has the - * earlier starting time. note that the order is such that the latest - * basis time is last in the resulting order array. - */ - - for (int i = 0; i < count; i++) { - tmpTime = zero; - currentIndex = 0; - - for (int j = 0; j < count; j++) { - /* - * only consider the time series if it hasn't been accounted for - * in the order array - */ - found = false; - - for (int k = 0; k < i; k++) { - if (j == basisOrder[k]) { - found = true; - break; - } - } - - if (!found) { - if (basisTime[j].compareTo(tmpTime) > 0) { - currentIndex = j; - tmpTime = basisTime[j]; - } else if (basisTime[j].compareTo(tmpTime) == 0) { - if (startValidTime[j] - .compareTo(startValidTime[currentIndex]) < 0) { - currentIndex = j; - tmpTime = basisTime[j]; - } - } - } - } - - basisOrder[i] = currentIndex; - } - - /* - * do NOT adjust the start and end time of the time series with the - * latest ending time. loop through all the other time series and adjust - * their start and end times as necessary so that they do not overlap - * the time limits of the being-built aggregate time series. - */ - - currentIndex = basisOrder[0]; - fullStartValidTime = startValidTime[currentIndex]; - fullEndValidTime = endValidTime[currentIndex]; - - for (int i = 1; i < count; i++) { - currentIndex = basisOrder[i]; - - /* - * each additional time series being considered is checked to see if - * it falls outside the time window already encompassed by the - * assembled time series. there are four cases that can occur; each - * is handled below. - */ - - if ((startValidTime[currentIndex].compareTo(fullStartValidTime) >= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) <= 0)) { - /* - * if the basis time series being considered is fully within the - * time of the already existing time series, then ignore it - * completely, and reset its times. - */ - startValidTime[currentIndex] = zero; - endValidTime[currentIndex] = zero; - } else if ((startValidTime[currentIndex] - .compareTo(fullStartValidTime) <= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) >= 0)) { - /* - * if the basis time series being considered covers time both - * before and after the existing time series, use the portion of - * it that is before the time series. it is not desirable to use - * both the before and after portion (this results in a - * non-contiguous time-series that is weird), and given a choice - * it is better to use the forecast data early on than the later - * forecast data, so use the before portion - */ - endValidTime[currentIndex] = new Timestamp( - fullStartValidTime.getTime() - 1000); - fullStartValidTime = startValidTime[currentIndex]; - - } else if ((startValidTime[currentIndex] - .compareTo(fullStartValidTime) <= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) <= 0)) { - /* - * if the basis time series being considered straddles the - * beginning or is completely before the existing time series, - * then use the portion of it that is before the time series. - */ - endValidTime[currentIndex] = new Timestamp( - fullStartValidTime.getTime() - 1000); - fullStartValidTime = startValidTime[currentIndex]; - } else if ((startValidTime[currentIndex] - .compareTo(fullStartValidTime) >= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) >= 0)) { - /* - * if the basis time series being considered straddles the end - * or is completely after the existing time series, then use the - * portion of it that is after the time series. - */ - startValidTime[currentIndex] = new Timestamp( - fullEndValidTime.getTime() + 1000); - fullEndValidTime = endValidTime[currentIndex]; - - } - } /* end for loop on the unique ordered basis times */ - - // Need to find a better way to do this - rval[0] = startValidTime; - rval[1] = endValidTime; - return rval; - } - - /** - * For a given location and pe code and type-source prefix, this function - * returns the type-source code with the lowest rank in IngestFilter. - * Alternatively, if a specific ordinal number is passed, then the Nth - * ranking ts is returned. If no (<= 0) ordinal number (i.e. 1st, 2nd) is - * requested, then the highest rank (1st) is returned. The type-source - * prefix is normally given as a one-character string, R for observed data - * and F for forecast data. - * - * The function argument returns a status variable indicating whether the - * request was satisfied. - * - * @param lid - * @param pe - * @param tsPrefix - * @param ordinal - * @return - */ - private String getBestTs(String lid, String pe, String tsPrefix, int ordinal) { - - int count = 0; - String tsFound = null; - String query = "SELECT ts_rank,ts FROM ingestfilter " + "WHERE lid = '" - + lid + "' AND " + "pe = '" + pe + "' AND " + "ts like '" - + tsPrefix + "' AND " + "ingest = 'T' " - + "ORDER BY ts_rank, ts"; - - try { - /* - * get the ingest filter entries for this location. note that the - * retrieval is ordered so that if multiple best ranks exist, there - * is some predicatibility for the identified best one. also note - * that this approach ignores the duration, extremum, and probabilty - * code. - */ - - IngestFilterTable ift = new IngestFilterTable(db); - Statement stmt = db.newStmtForScrollableRset(); - ResultSet rs = ift.executeQuery(stmt, query); - - if (rs.next()) { - /* - * if no specific ordinal number was requested, return with the - * highest rank. - */ - if (ordinal <= 0) { - tsFound = rs.getString("ts"); - } else { - /* - * get a count of the number of matching ts entries. if the - * requested ordinal number is greater than the number - * available then return with a not found status. - */ - - count = getResultSetSize(rs); - - if (ordinal <= count) { - rs.relative(ordinal - 1); - tsFound = rs.getString("ts"); - } - } - } - rs.close(); - stmt.close(); - } catch (Exception e) { - logger.log(" - PostgresSQL error retrieving from ingestfilter"); - logger.log("Query = [" + query + "]"); - logger.printStackTrace(e); - - } - - return tsFound; - } - - private class Forecast extends FcstHeightRecord { - - private Date validTime = null; - - private Date basisTime = null; - - public void setValidTime(Date validTime) { - this.validTime = validTime; - } - - public Date getValidTime() { - return validTime; - } - - public void setBasisTime(Date basisTime) { - this.basisTime = basisTime; - } - - public Date getBasisTime() { - return basisTime; - } - - public boolean equals(Object other) { - if ((this == other)) - return true; - if ((other == null)) - return false; - if (!(other instanceof Forecast)) - return false; - Forecast castOther = (Forecast) other; - - return ((this.getLid() == castOther.getLid()) || (this.getLid() != null - && castOther.getLid() != null && this.getLid().equals( - castOther.getLid()))) - && ((this.getPe() == castOther.getPe()) || (this.getPe() != null - && castOther.getPe() != null && this.getPe() - .equals(castOther.getPe()))) - && (this.getDur() == castOther.getDur()) - && ((this.getTs() == castOther.getTs()) || (this.getTs() != null - && castOther.getTs() != null && this.getTs() - .equals(castOther.getTs()))) - && ((this.getExtremum() == castOther.getExtremum()) || (this - .getExtremum() != null - && castOther.getExtremum() != null && this - .getExtremum().equals(castOther.getExtremum()))) - && (this.getProbability() == castOther.getProbability()) - && ((this.getValidTime() == castOther.getValidTime()) || (this - .getValidTime() != null - && castOther.getValidTime() != null && this - .getValidTime().equals(castOther.getValidTime()))) - && ((this.getBasisTime() == castOther.getBasisTime()) || (this - .getBasisTime() != null - && castOther.getBasisTime() != null && this - .getBasisTime().equals(castOther.getBasisTime()))); - } - - public int hashCode() { - int result = 17; - - result = 37 * result - + (getLid() == null ? 0 : this.getLid().hashCode()); - result = 37 * result - + (getPe() == null ? 0 : this.getPe().hashCode()); - result = 37 * result + this.getDur(); - result = 37 * result - + (getTs() == null ? 0 : this.getTs().hashCode()); - result = 37 - * result - + (getExtremum() == null ? 0 : this.getExtremum() - .hashCode()); - result = 37 * result + (int) this.getProbability(); - result = 37 - * result - + (getValidTime() == null ? 0 : this.getValidTime() - .hashCode()); - result = 37 - * result - + (getBasisTime() == null ? 0 : this.getBasisTime() - .hashCode()); - return result; - } - } - - /** - * A utility DbTable factory - * - * @param db - * @param table - * @return - */ - private DbTable getDbTableInstance(Database db, String table) { - if (table.equalsIgnoreCase("FcstHeight")) - return new FcstHeightTable(db); - else if (table.equalsIgnoreCase("FcstDischarge")) - return new FcstDischargeTable(db); - // Default for now is FcstHeight so we're never returning null. - return new FcstHeightTable(db); - } - -} \ No newline at end of file diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/IngestFilterTsDescriptor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/IngestFilterTsDescriptor.java deleted file mode 100644 index 5a949fedd8..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/IngestFilterTsDescriptor.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Created on Apr 15, 2004 - * - * - */ -package ohd.hseb.sshp; - -/** - * @author GobsC - * - * - */ -public interface IngestFilterTsDescriptor -{ - - public String getLid(); - - public String getPe(); - - public short getDur(); - - public String getTs(); - - public String getExtremum(); - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/ProcTsDescriptor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/ProcTsDescriptor.java deleted file mode 100644 index cbc2ddb20e..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/ProcTsDescriptor.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Created on Dec 9, 2003 - * - * Filename : Height.java - * Author : Gautam Sood - * Last Revision Date : Dec 9, 2003 - * - */ -package ohd.hseb.sshp; - -import java.text.DecimalFormat; -import java.text.NumberFormat; - - -public class ProcTsDescriptor implements IngestFilterTsDescriptor -{ - - private String _tableName = null; - private String _lid = null; - private String _pe = null; - private String _ts = null; - private short _dur= 0; - private String _extremum = null; - - - //***************************************************************************** - // Empty constructor - //***************************************************************************** - public ProcTsDescriptor(String tableName) - { - setTableName(tableName); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( short dur ) - { - _dur = dur; - } - - public short getDur() - { - return _dur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat f = new DecimalFormat(formatString); - - String outString = "FcstHeight: " + - " Lid = " + _lid + - " Table NAme = " + _tableName + - " pe = " + _pe + - " ts = " + _ts + "\n" + - " Extremum = " + _extremum + - " dur = " + _dur; - return outString; - } - - public void setTableName(String tableName) - { - _tableName = tableName; - } - - public String getTableName() - { - return _tableName; - } -} - diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHP.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHP.java deleted file mode 100644 index 1f3fec6315..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHP.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Created on Oct 3, 2003 - * - * - */ -package ohd.hseb.sshp; - -import javax.swing.UIManager; - -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -/** - * @author Chip Gobs - * - * This is the driver class for the SSHP Application - */ -public class SSHP -{ - - public static void main(String[] args) - { - try - { - //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); - } - catch (Exception e) - { - System.err.print(e.getMessage()); - e.printStackTrace(); - } - - if (args.length < 2) - { - System.err.println("Usage: ohd.hseb.sshp.SSHP connection_string logFileDir [location_id] "); -// System.exit(0); - } - - String baseConnectionString = args[0]; - - String logDirName = args[1]; - - - String logFileName = logDirName + "/SSHP.log"; - - Logger logger = new FileLogger(logFileName, true, true); - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - - AppController controller = new AppController(dataMgr, logDirName); - - if (args.length >= 3) - { - String locationId = args[2]; - controller.displayAnalysisWindow(locationId); - } - else - { - controller.displayControlWindowIfNotDisplayed(); - } - } //end main - -} //end class SSHP diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHPConfig.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHPConfig.java deleted file mode 100644 index bc0ed1658d..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHPConfig.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Created on Feb 4, 2004 - * - * Filename : SshpConfig.java - * Author : Gautam Sood - * Last Revision Date : Feb 4, 2004 - * - */ -//package ohd.hseb.model; -package ohd.hseb.sshp; - -import ohd.hseb.model.ForecastInterpolationMethod; - -public class SSHPConfig -{ - private String _lid = null; - private String _basinId = null; - private long _postingTime = 0; - private String _modelPref = null; - private boolean _autoProcess = false; - private String _sourcePref = null; - private boolean _useStaticEvap = false; - private boolean _useBlend = false; - private ForecastInterpolationMethod _blendMethod = null; - private int _blendHours = 0; - - public SSHPConfig() - { - } - - public SSHPConfig( SSHPConfig sshpConfig ) - { - - - _lid = sshpConfig.getLid(); - _basinId = sshpConfig.getBasinId(); - _postingTime = sshpConfig.getPostingTime(); - _modelPref = sshpConfig.getModelPref(); - _autoProcess = sshpConfig.isAutoProcess(); - _sourcePref = sshpConfig.getSourcePref(); - _useStaticEvap = sshpConfig.useStaticEvap(); - - _blendMethod = sshpConfig.getBlendMethod(); - - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setBasinId( String basinId ) - { - _basinId = basinId; - } - - public String getBasinId() - { - return _basinId; - } - - public void setPostingTime( long postingTime ) - { - _postingTime = postingTime; - } - - public long getPostingTime() - { - return _postingTime; - } - - public void setModelPref( String modelPref ) - { - _modelPref = modelPref; - } - - public String getModelPref() - { - return _modelPref; - } - - public void setAutoProcess( boolean autoProcess ) - { - _autoProcess = autoProcess; - } - - public boolean isAutoProcess() - { - return _autoProcess; - } - - public void setSourcePref( String sourcePref ) - { - _sourcePref = sourcePref; - } - - public String getSourcePref() - { - return _sourcePref; - } - - public void setUseStaticEvap( boolean useStaticEvap ) - { - _useStaticEvap = useStaticEvap; - } - - public boolean useStaticEvap() - { - return _useStaticEvap; - } - - - public String toString() - { - return "Lid = " + _lid + - "Basin id = " + _basinId + - "Posting Time = " + _postingTime + - "Model Pref = " + _modelPref + - "Auto Process = " + _autoProcess + - "Source Pref = " + _sourcePref + - "Use Static Evap = " + _useStaticEvap; - } - - /** - * @param useBlend The useBlend to set. - */ - public void setUseBlend(boolean useBlend) - { - _useBlend = useBlend; - } - - /** - * @return Returns the useBlend. - */ - public boolean useBlend() - { - return _useBlend; - } - - /** - * @param blendMethod The blendMethod to set. - */ - public void setBlendMethod(ForecastInterpolationMethod blendMethod) - { - _blendMethod = blendMethod; - } - - /** - * @return Returns the blendMethod. - */ - public ForecastInterpolationMethod getBlendMethod() - { - return _blendMethod; - } - - /** - * @param blendHours The blendHours to set. - */ - public void setBlendHours(int blendHours) - { - _blendHours = blendHours; - } - - /** - * @return Returns the blendHours. - */ - public int getBlendHours() - { - return _blendHours; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHPSource.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHPSource.java deleted file mode 100644 index f2a83a11a6..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SSHPSource.java +++ /dev/null @@ -1,112 +0,0 @@ -package ohd.hseb.sshp; - -import java.util.ArrayList; -import java.util.List; - -public class SSHPSource -{ - // ----------------------------------------------------------------------------------------- - - public final static SSHPSource ADJUSTED_VAR = new SSHPSource("adjusted var" , "ADJ_VAR" , "FA", "ADJRUNOFF"); - public final static SSHPSource UNADJUSTED_VAR = new SSHPSource("unadjusted var", "UNADJ_VAR", "FU", "UADJRUNOFF"); - - public final static SSHPSource RFC = new SSHPSource("RFC", "RFC", "FZ", "RFCRUNOFF"); - public final static SSHPSource SSHP_UPDATER = new SSHPSource("SSHP_Updater", "LOCAL", "FZ", "SSHPRUNOFF" ); - - private String _name = null; - private String _productId = null; - private String _sacSmaSource = null; //this is to be used for SacSmaStates - private String _typeSource = null; //this is to be used for TimeSeries info such as PriorComputerRunoff - - // ----------------------------------------------------------------------------------------- - - private static List _sourceList = new ArrayList(); - - static - { - _sourceList.add(ADJUSTED_VAR); - _sourceList.add(UNADJUSTED_VAR); - _sourceList.add(RFC); - _sourceList.add(SSHP_UPDATER); - } - // ----------------------------------------------------------------------------------------- - - private SSHPSource(String name, String sacSmaSource, String typeSource, String productId) - { - setName(name); - setSacSmaSource(sacSmaSource); - setTypeSource(typeSource); - setProductId(productId); - } - // ----------------------------------------------------------------------------------------- - - public static SSHPSource findMatchingSSHPSourceBySacSmaSource(String sacSmaSource) - { - SSHPSource matchingSource = null; - - for ( SSHPSource source : _sourceList) - { - if (sacSmaSource.equals(source.getSacSmaSource())) - { - matchingSource = source; - break; - } - } - - return matchingSource; - } - - // ----------------------------------------------------------------------------------------- - - public void setName(String name) - { - _name = name; - } - - // ----------------------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - - // ----------------------------------------------------------------------------------------- - - public void setSacSmaSource(String sacSmaSource) - { - _sacSmaSource = sacSmaSource; - } - - // ----------------------------------------------------------------------------------------- - - public String getSacSmaSource() - { - return _sacSmaSource; - } - - // ----------------------------------------------------------------------------------------- - - public void setTypeSource(String typeSource) - { - _typeSource = typeSource; - } - - // ----------------------------------------------------------------------------------------- - - public String getTypeSource() - { - return _typeSource; - } - // ----------------------------------------------------------------------------------------- - - public void setProductId(String productId) { - _productId = productId; - } - - // ----------------------------------------------------------------------------------------- - - public String getProductId() { - return _productId; - } - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SacSmaStateDescriptor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SacSmaStateDescriptor.java deleted file mode 100644 index 583c236db2..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SacSmaStateDescriptor.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Created on Apr 22, 2004 - * - * - */ -package ohd.hseb.sshp; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.model.sacsma.SacSmaState; - -/** - * @author GobsC - * - * This class is used to summarize the states available for use by - * SSHP. Instances of this class may be used as items in a ComboBox. - */ -public class SacSmaStateDescriptor -{ - - private SacSmaState _state = null; - private boolean _isDefaultValue = false; - -// ----------------------------------------------------------------- - - public SacSmaStateDescriptor(SacSmaState state) - { - _state = state; - - } -// ----------------------------------------------------------------- - - public boolean equals(SacSmaStateDescriptor descriptor) - { - - boolean result = false; - - if (this.getState().equals(descriptor.getState())) - { - result = true; - } - - return result; - - } -// ----------------------------------------------------------------- - public long getValidTime() - { - long time = 0; - - if (_state != null) - { - time = _state.getValidTime(); - } - - return time; - } - -// ----------------------------------------------------------------- - - public void setIsDefaultValue(boolean isDefaultValue) - { - _isDefaultValue = isDefaultValue; - } -// --------------------------------------------------------------- - - public boolean isDefaultValue() - { - return _isDefaultValue; - } -// --------------------------------------------------------------- - -// ----------------------------------------------------------------- - - public void setState(SacSmaState state) - { - _state = state; - } -//----------------------------------------------------------------- - - public SacSmaState getState() - { - return _state; - } -// ----------------------------------------------------------------- - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + " Z"; - - return timeString; - } -// ----------------------------------------------------------------- - - public String toString() - { - String outString = null; - - if (!isDefaultValue()) - { - outString = _state.getSource()+ " State " + "at " + - getDateTimeStringToMinutes(_state.getValidTime()); - } - else //is bogus default value - { - outString = "BOGUS DEFAULT" + " State " + "at " + - getDateTimeStringToMinutes(_state.getValidTime()); - } - return outString; - } -// ----------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SacStateUpdater.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SacStateUpdater.java deleted file mode 100644 index 12574c5c97..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/SacStateUpdater.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Created on Mar 16, 2004 - * - * - */ -package ohd.hseb.sshp; - -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeSeriesFileManager; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -/** - * @author GobsC - * - * The purpose of this class is to check the most recent saved - * Sacramento Model states and run the model from the last saved state - * if the states have aged too much. - * - * The class also is responsible for creating "background" forecasts for - * situational awareness. - */ -public class SacStateUpdater { - - private FileLogger _logger = null; - - private static final long _millisPerHour = 1000 * 60 * 60; - - private long _timeDiffMax = 0; - - private int _hoursForward = 0; - - private DataMgr _dataMgr = null; - - private String _backgroundFcstOutputDirectoryNameString = null; - - private static final String SSHP_BACKGROUND_FORECAST_OUTPUT_DIR = "sshp_background_forecast_output_dir"; - - private static final int _defaultBackgroundFcstLengthInHours = 48; - - private int _backgroundFcstLengthInHours = _defaultBackgroundFcstLengthInHours; - - private static final String SSHP_BACKGROUND_FORECAST_FCST_LENGTH = "sshp_background_forecast_length"; - - // ------------------------------------------------------------- - - public SacStateUpdater(DataMgr dataMgr, int expirationHours, - int hoursForward, String logFileName) { - _dataMgr = dataMgr; - _timeDiffMax = expirationHours * _millisPerHour; - - _hoursForward = hoursForward; - - boolean keepFileOpen = true; - boolean appendDateTime = true; - - _logger = new FileLogger(logFileName, keepFileOpen, appendDateTime); - - AppsDefaults ad = AppsDefaults.getInstance(); - - _backgroundFcstOutputDirectoryNameString = ad - .getToken(SSHP_BACKGROUND_FORECAST_OUTPUT_DIR); - _backgroundFcstLengthInHours = ad.getInt( - SSHP_BACKGROUND_FORECAST_FCST_LENGTH, - _defaultBackgroundFcstLengthInHours); - - return; - } - - // ------------------------------------------------------------- - @Override - public void finalize() { - _logger.close(); - } - - // ------------------------------------------------------------- - - public void updateAllStates() { - /* - * get list of locations to maintain (from SSHPConfig) - * - * for each locationId time = _dataMgr.getTimeOfBestRecentState() if - * more than expirationHours old, then run model for that locationId - * - * save the SacState, and the prior runoff - */ - - List locationIdList = _dataMgr - .loadAllLocationIdsToAutoUpdateSacStates(); - - for (String locationId : locationIdList) { - updateStatesByLocation(locationId, true); - } - - if (locationIdList.size() == 0) { - _logger - .log("There are no locations for which auto process has been set."); - } - - } // update states - - // ------------------------------------------------------------- - public void updateStatesByLocation(String locationId, boolean saveStates) { - String header = "updateStatesByLocation(): "; - _logger.log(header + "Checking states for " + locationId); - - SacSmaState bestState = _dataMgr.loadBestRecentSacState(locationId); - - if (bestState != null) { - long bestStateTime = bestState.getValidTime(); - - // long bestStateTime = - // _dataMgr.loadTimeOfBestRecentSacState(locationId); - - long currentTime = System.currentTimeMillis(); - currentTime = TimeHelper.truncateTimeInMillisToNearestHour( - currentTime, 1); - - long timeDiff = (currentTime - bestStateTime); - if (timeDiff > _timeDiffMax) { - _logger.log("Updating states for " + locationId + "."); - - StreamModel model = new StreamModel(locationId, - RainfallRunoffModelType.SAC_SMA, _dataMgr); - - model.setSacSmaStateDescriptor(new SacSmaStateDescriptor( - bestState)); - model.setModelStartTime(bestState.getValidTime()); - - long modelEndTime = currentTime - + (_hoursForward * _millisPerHour); - model.setModelEndTime(modelEndTime); - - _logger.log("Last saved state time = " - + DbTimeHelper - .getDateTimeStringFromLongTime(bestStateTime)); - _logger.log("Model run end time = " - + DbTimeHelper - .getDateTimeStringFromLongTime(modelEndTime)); - - model.runModel(); - - if (saveStates) { - - _logger.log("Saving model states for " + locationId + "."); - model.saveModelStates(_logger); - - _logger.log("Saving computed runoff time series for " - + locationId + "."); - model.saveRunoffTimeSeries(_logger); - } - - } else { - _logger.log("Model States for " + locationId - + " are up to date."); - } - } // end if bestState != null - else { - _logger.log("No original model States for " + locationId - + " are available. Unable to update."); - } - } - - // ------------------------------------------------------------- - public void updateAllBackgroundForecasts() { - /* - * get list of locations for which to compute forecasts - * - * for each locationId run the model and update the latest forecast - * stored on disk as a flat file - */ - - List locationIdList = _dataMgr.loadLocationIdsForForecasts(); - - for (String locationId : locationIdList) { - _logger.log("Attempting to update a background forecast for " - + locationId); - updateForecastByLocation(locationId); - } - - if (locationIdList.size() == 0) { - _logger - .log("There are no locations for which to update a background forecast."); - } - - } // update states - - // ------------------------------------------------------------- - - public void updateForecastByLocation(String locationId) { - String header = "updateForecastByLocation(): "; - // _logger.log(header + " search for valid model states for " + - // locationId); - - StreamModel model = null; - SSHPConfig config = _dataMgr.getSSHPConfig(locationId); - - long currentTime = System.currentTimeMillis(); - currentTime = TimeHelper.truncateTimeInMillisToNearestHour(currentTime, - 1); - - boolean isStateAvailable = false; - - String modelPreference = config.getModelPref(); - - if (modelPreference.equals("SAC-SMA")) { - SacSmaState bestState = _dataMgr.loadBestRecentSacState(locationId); - - if (bestState != null) { - isStateAvailable = true; - - model = new StreamModel(locationId, - RainfallRunoffModelType.SAC_SMA, _dataMgr); - - model.setSacSmaStateDescriptor(new SacSmaStateDescriptor( - bestState)); - model.setModelStartTime(bestState.getValidTime()); - - long modelEndTime = currentTime - + (_hoursForward * _millisPerHour); - model.setModelEndTime(modelEndTime); - } - } else // API_MKC - { - AbsTimeMeasurement ffhMeasurement = _dataMgr - .loadMostCurrentFfhMeasurement(locationId, config - .getBasinId(), currentTime); - - if (ffhMeasurement != null) { - isStateAvailable = true; - - model = new StreamModel(locationId, - RainfallRunoffModelType.API_MKC, _dataMgr); - - model.setModelStartTime(ffhMeasurement.getTime()); - - long modelEndTime = currentTime - + (_backgroundFcstLengthInHours * _millisPerHour); - model.setModelEndTime(modelEndTime); - } - } - - if (isStateAvailable) { - _logger.log("Updating Forecasts for " + locationId + "."); - - // _logger.log("Last saved state time = " + - // DbTimeHelper.getDateTimeStringFromLongTime(bestStateTime)); - // _logger.log("Model run end time = " + - // DbTimeHelper.getDateTimeStringFromLongTime(modelEndTime)); - - model.runModel(); - - // for situational awareness applications (e.g. RiverMonitor) - TimeSeriesFileManager fileManager = new TimeSeriesFileManager(); - RegularTimeSeries fcstStageTimeSeries = model - .getForecastStageTimeSeriesHolder().getTimeSeries(); - - // This feature can be turned off by not setting the token - if (_backgroundFcstOutputDirectoryNameString != null) { - String filePath = _backgroundFcstOutputDirectoryNameString - + "/" + model.getLocationId() + "_fcst_stage.dat"; - - _logger.log(header + "saving forecasts for " + locationId - + " to " + filePath); - - fileManager.saveRegularTimeSeries(fcstStageTimeSeries, - filePath, MeasuringUnit.feet); - } else { - _logger.log(header - + "_backgroundFcstOutputDirectoryNameString is null," - + " unable to save forecast timeseries to a file."); - } - - } // end isStateAvailable - else { - _logger - .log(header - + "No valid " - + modelPreference - + " model states for " - + locationId - + " are available. Unable to create and save a background forecast."); - } - } - - // ------------------------------------------------------------- - - public static void main(String[] args) { - - if (args.length < 4) { - System.err - .println("Usage: ohd.hseb.sshp.StateUpdater connection_string expirationHours hoursForward logFilePath"); -// System.exit(0); - } - - String baseConnectionString = args[0]; - - String expirationHoursString = args[1]; - String hoursForwardString = args[2]; - String logFilePath = args[3]; - // String logFileDir = args[3]; - - int expirationHours = Integer.parseInt(expirationHoursString); - - if (expirationHours <= 0) { - System.err.println("expirationHours must be a number > 0"); -// System.exit(0); - } - - int hoursForward = Integer.parseInt(hoursForwardString); - // zero is ok - - // String logFilePath = logFileDir + "/SacStateUpdater.log"; - Logger logger = new FileLogger(logFilePath); - - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - SacStateUpdater updater = new SacStateUpdater(dataMgr, expirationHours, - hoursForward, logFilePath); - - updater.updateAllStates(); - - updater.updateAllBackgroundForecasts(); - - dataMgr.disconnect(); - - } // end main() - - // ------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/StreamModel.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/StreamModel.java deleted file mode 100644 index d93181e4b7..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/StreamModel.java +++ /dev/null @@ -1,1872 +0,0 @@ -/* - * Created on Nov 3, 2003 - * This class took over nearly all of AppController's old duties. - * AppController now is in charge of setting up the environment - * for handling multiple model windows. - * AppController was created on Sep 17, 2003 - * - */ -package ohd.hseb.sshp; - -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementHolder; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.measurement.RelTimeMeasurement; -import ohd.hseb.model.ForecastAdjuster; -import ohd.hseb.model.ForecastAdjusterParams; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.RainfallRunoffModel; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.RainfallToStageModel; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.model.UnitHydrograph; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.model.mkcapi.KcApiRainfallRunoffModel; -import ohd.hseb.model.mkcapi.KcApiRainfallToStageModel; -import ohd.hseb.model.sacsma.SacRainfallToStageModel; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaRainfallRunoffModel; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.CodeTracer; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -/** - * @author Chip Gobs - * - * This class hooks together all the computational elements for running - * a hydrologic model. It is also in charge of making calls to the - * DataMgr. - */ -public class StreamModel { - public static final int DEFAULT_FFG_DURATION_CODE = 1001; // REPRESENTS 1 - // HOUR - - private static final MeasuringUnit _stageUnit = MeasuringUnit.feet; - - private static final MeasuringUnit _dischargeUnit = MeasuringUnit.cfs; - - private static final int MAX_DAYS_OF_TIME_SERIES = 100; - - private static final int MILLIS_PER_HOUR = 60 * 60 * 1000; - - private static final int MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; - - // FORECAST ADJUSTMENT PARAMETERS (THE BLENDING TIME IS IN THE DATABASE) - private static final int DEFAULT_ADJUSTMENT_PAIRING_MINUTES = 70; - - private static final int DEFAULT_ADJUSTMENT_INTERPOLATION_HOURS = 3; - - private static final int MAX_BLENDING_HOURS = 1000; - - private int _adjustmentPairingMinutes = 0; - - private int _adjustmentInterpolationHours = 0; - - private DataMgr _dataMgr = null; - - private SSHPConfig _config = null; - - private RainfallRunoffModelType _rainfallRunoffModelType = null; - - private int _modelRunCount = 0; - - // location-related variables - private String _locationId = null; - - private String _locationName = null; - - private String _basinId = null; - - private String _primaryPe = null; // HG or QR, height or discharge - - private static final int DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS = 24; - - private static final int DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS = 120; - - private int _forecastLengthInHours = DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS; - - private int _maxForecastLengthInHours = DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS; - - // various time series holders - - // precip - private RegularTimeSeriesHolder _precipTimeSeriesHolder = new RegularTimeSeriesHolder(); - - // evaporation - needed by SAC-SMA model - private RegularTimeSeriesHolder _evaporationTimeSeriesHolder = new RegularTimeSeriesHolder(); - - // calculated runoff - private RegularTimeSeriesHolder _runoffTimeSeriesHolder = new RegularTimeSeriesHolder(); - - // prior runoff - private RegularTimeSeriesHolder _priorRunoffTimeSeriesHolder = new RegularTimeSeriesHolder(); - - // stage - private IrregularTimeSeriesHolder _observedStageTimeSeriesHolder = new IrregularTimeSeriesHolder(); - - private RegularTimeSeriesHolder _simulatedStageTimeSeriesHolder = new RegularTimeSeriesHolder(); - - private RegularTimeSeriesHolder _forecastStageTimeSeriesHolder = new RegularTimeSeriesHolder(); - - private IrregularTimeSeriesHolder _priorForecastStageTimeSeriesHolder = new IrregularTimeSeriesHolder(); - - // discharge - private RegularTimeSeriesHolder _simulatedDischargeTimeSeriesHolder = new RegularTimeSeriesHolder(); - - private SigRiverLevels _sigRiverLevels = null; - - // modeling objects - private RainfallToStageModel _rainfallToStageModel = null; - - private RainfallRunoffModel _rainfallRunoffModel = null; - - private RatingCurve _ratingCurve = null; - - private UnitHydrograph _unitHydrograph = null; - - private UnitHydrograph _customUnitHydrograph = null; - - private MeasurementHolder _initialStageMeasurementHolder = new MeasurementHolder(); - - // a rating-related object - private StageToFlowValueMapper _stageToFlowValueMapper = null; - - // SAC model variables - private List _sacStateDescriptorList = null; - - private SacSmaParameters _sacParams = null; - - private SacSmaState _sacState = null; - - private SacSmaStateDescriptor _sacSmaStateDescriptor = null; - - private boolean _isAdjustmentOn = false; - - private ForecastAdjuster _forecastAdjuster = null; - - // KC model variables - private List _ffhDescriptorList = null; - - private FFHDescriptor _ffhDescriptor = null; - - private static final MeasuringUnit _ffhUnit = MeasuringUnit.inches; - - private static final double _defaultFFHValue = 5.0; - - private double _ffhValue = 0.0; - - private double _thresholdRunoff = 0.0; - - // basistime - private static final int _intervalInHours = 1; - - // private static final int _hoursBack = 24; - private static final int _millisPerHour = 1000 * 60 * 60; - - // model run start and end times - // Note: the end time is currently hardcoded to go out some hours beyond - // the current time - private TimeHolder _modelStartTimeHolder = new TimeHolder(); - - private TimeHolder _modelEndTimeHolder = new TimeHolder(); - - // for debugging - CodeTracer _tracer = null; - - // ----------------------------------------------------------- - - // ----------------------------------------------------------- - - public StreamModel(String locationId, RainfallRunoffModelType modelType, - DataMgr dataMgr) { - - // _tracer = new CodeTracer(); - - _locationId = locationId; - - _rainfallRunoffModelType = modelType; - - _dataMgr = dataMgr; - - _config = _dataMgr.getSSHPConfig(_locationId); - - AppsDefaults ad = AppsDefaults.getInstance(); - - // load the forecast length parameters - _forecastLengthInHours = ad.getInt("sshp_initial_forecast_length", - DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS); - - _maxForecastLengthInHours = ad.getInt("sshp_max_forecast_length", - DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS); - - if (_forecastLengthInHours > _maxForecastLengthInHours) { - _maxForecastLengthInHours = _forecastLengthInHours; - } - - // load the adjustment parameters - _adjustmentPairingMinutes = ad.getInt( - "sshp_adjustment_pairing_minutes", - DEFAULT_ADJUSTMENT_PAIRING_MINUTES); - _adjustmentInterpolationHours = ad.getInt( - "sshp_adjustment_interpolation_hours", - DEFAULT_ADJUSTMENT_INTERPOLATION_HOURS); - - // set the basin id associated with the locationId - if (_config != null) { - _basinId = _config.getBasinId(); - } else { - _basinId = "BOGUS_BASIN"; - } - - // get the location name - _locationName = dataMgr.getLocationName(_locationId); - - // set the model run start time - long modelStartTime = getTimeOfBestRecentState(_locationId, _basinId); - if (modelStartTime == 0) { - modelStartTime = getLatestHourTime(); - } else { - modelStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - modelStartTime, 1); - } - - setModelStartTime(modelStartTime); - - // init the model states, parameters and input time series data - - initModelData(); - - initAllTimeSeries(); - - return; - } - - private void trace() { - try { - throw new Exception("trace"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - // ------------------------------------------------------------------------------------- - public String[] getPeArray(char firstLetterOfPhysicalElement) { - String[] peArray = null; - String[] heightArray = { "HG", "HP", "HT" }; - String[] dischargeArray = { "QR" }; - - peArray = _dataMgr - .loadPhysicalElementArray(firstLetterOfPhysicalElement); - if (peArray == null) { - if (firstLetterOfPhysicalElement == 'H') { - peArray = heightArray; - } else if (firstLetterOfPhysicalElement == 'Q') { - peArray = dischargeArray; - } - } - - return peArray; - } - - // ------------------------------------------------------------------------------------- - public String getRainfallRunoffModelTypeName() { - String modelTypeName = null; - if (_rainfallRunoffModelType != null) { - modelTypeName = _rainfallRunoffModelType.getName(); - } - - return modelTypeName; - } - - // ------------------------------------------------------------------------------------- - public RainfallRunoffModelType getRainfallRunoffModelType() { - return _rainfallRunoffModelType; - - } - - // ------------------------------------------------------------------------------------- - - public double findThresholdRunoffValue() { - - // _unitHydrograph = getBestUnitHydrograph(_unitHydrograph); - - if (_ratingCurve == null) { - _ratingCurve = _dataMgr.loadRatingCurve(_locationId); - } - - return findThresholdRunoffValue(_unitHydrograph, _ratingCurve); - } - - // ------------------------------------------------------------------------------------- - - public boolean setRainfallRunoffModelType(RainfallRunoffModelType modelType) { - boolean success = false; - - if (isValidModelTypeForLocation(modelType)) { - success = true; - - _rainfallRunoffModelType = modelType; - - _customUnitHydrograph = null; - - initModelData(); - - initAllNonPrecipTimeSeries(); - } - - return success; - - } - - // ------------------------------------------------------------------------------------- - - private boolean isValidModelTypeForLocation(RainfallRunoffModelType type) { - boolean valid = false; - - if (type == RainfallRunoffModelType.API_MKC) { - valid = true; - } - // SshpConfig config = _dataMgr.loadSshpConfig(_locationId); - else { - if (_config != null) { - valid = true; - } - } - - return valid; - - } - - // ------------------------------------------------------------------------------------- - - public void reloadModelData() { - // CodeTimer timer = new CodeTimer(); - - // timer.start(); - // String header = "StreamModel.reloadModelData():"; - - // System.out.println(header + "called"); - - _unitHydrograph = null; - _ratingCurve = null; - _stageToFlowValueMapper = null; - - initModelData(); - - // timer.stop(header + "took"); - - } - - // ------------------------------------------------------------------------------------- - - private long getTimeOfBestRecentState(String locationId, String basinId) { - long bestStateTime = 0; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - SacSmaState state = getLatestSacSmaStateFromDescriptorList(); - bestStateTime = state.getValidTime(); - } else if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) { - bestStateTime = _dataMgr - .getTimeOfBestRecentFFH(locationId, basinId); - } - - return bestStateTime; - - } - - // ------------------------------------------------------------------------------------- - - private void initModelData() { - String header = "StreamModel.initModelData(): "; - // System.out.println(header + "start. "); - - // this method is to be called when the model is going to - // be run for the first time with this set of settings - // it is called again when any modelData setting is changed - - // make sure that _unitHydrograph contains the best data available - if (_customUnitHydrograph != null) { - _unitHydrograph = _customUnitHydrograph; - } else { - _unitHydrograph = getBestUnitHydrograph(_unitHydrograph); - } - - if (_ratingCurve == null) { - _ratingCurve = _dataMgr.loadRatingCurve(_locationId); - } - - if (_stageToFlowValueMapper == null) { - _stageToFlowValueMapper = new StageToFlowValueMapper(_ratingCurve); - } - - // init the forecastAdjust object - if (_forecastAdjuster == null) { - ForecastAdjusterParams params = new ForecastAdjusterParams(); - - params.setPairingTimeMinutes(_adjustmentPairingMinutes); - params.setInterpolationHours(_adjustmentInterpolationHours); - params.setBlendingHours(_config.getBlendHours()); - - params.setBlendingMethod(_config.getBlendMethod()); - params.setShouldDoAdjustment(_config.useBlend()); - _forecastAdjuster = new ForecastAdjuster(params); - _isAdjustmentOn = _config.useBlend(); - } - - initRainfallRunoffModelData(); - - // timer.stop("StreamModel.initModelData took"); - - } // end initModelData - - // ------------------------------------------------------------------------------------- - - private void initRainfallRunoffModelData() { - if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) { - if (_unitHydrograph == null) { - trace(); - } - - _rainfallRunoffModel = initKcApiModelData(_unitHydrograph, - _ratingCurve); - _rainfallToStageModel = new KcApiRainfallToStageModel( - _rainfallRunoffModel, _unitHydrograph, _ratingCurve, - _initialStageMeasurementHolder, - _observedStageTimeSeriesHolder, _forecastAdjuster, - _simulatedDischargeTimeSeriesHolder); - - } else if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - - loadPriorRunoffTimeSeries(); - - // System.out.println(header + "start. "); - - _rainfallRunoffModel = initSacSmaModelData(); - _rainfallToStageModel = new SacRainfallToStageModel( - _rainfallRunoffModel, _unitHydrograph, _ratingCurve, - _priorRunoffTimeSeriesHolder, - _observedStageTimeSeriesHolder, _forecastAdjuster, - _simulatedDischargeTimeSeriesHolder); - - } - - } - - // ------------------------------------------------------------------------------------- - - public String[] getUnitHydrographNameArray() { - List uhgDescList = _dataMgr - .loadUnitHydrographDescriptorList(getLocationId()); - UnitHydrographDescriptor descriptor; - - String[] nameArray = new String[uhgDescList.size()]; - - for (int i = 0; i < uhgDescList.size(); i++) { - descriptor = (UnitHydrographDescriptor) uhgDescList.get(i); - nameArray[i] = descriptor.getModel(); - } - - return nameArray; - } - - // ------------------------------------------------------------------------------------- - public void changeUnitHydrograph(String unitHydrographName) { - // String header = "StreamModel.changeUnitHydrograph() : "; - - // System.out.println(header + "inside"); - - // if there is a change, then load the different unitHydrograph - if (!_unitHydrograph.getRainfallRunoffModelTypeName().equals( - unitHydrographName)) { - - // System.out.println(header + "making UHG change to " + - // unitHydrographName); - _unitHydrograph = _dataMgr.loadUnitHydrograph(_locationId, - _basinId, unitHydrographName); - _customUnitHydrograph = _unitHydrograph; - - initModelData(); - - } else { - // System.out.println(header + "REFUSING to making UHG change to " + - // unitHydrographName); - } - - return; - } - - // ------------------------------------------------------------------------------------- - - public String getUnitHydrographSelectionName() { - String currentName = null; - - currentName = _unitHydrograph.getRainfallRunoffModelTypeName(); - - return currentName; - } - - // ------------------------------------------------------------------------------------- - - private UnitHydrograph getBestUnitHydrograph( - UnitHydrograph oldUnitHydrograph) { - String header = "StreamModel.getBestUnitHydrograph() : "; - - /* - * This method will just return the passed-in unit hydrograph if it is - * not null and its model type matches the current RainfallRunoffModel - * type. - * - * If the oldUnitHydrograph is null, then a UHG will be loaded. - * - * else if a customUnitHydrograph has been chosen, then the unitgraph - * will not change. - * - * else if the model types of the currently selected UHG - * (oldUnitHydrograph) does not match with the RainfallRunoff Model - * type, this routine loads the unithydrograph from the DataMgr. - * - * If after that, the unit hydrograph has no points, then the routine - * tries to load the unithydrograph for the same location and basin but - * for a different rainfall runoff model. It is anticipated that this - * last bit of functionality will be used mostly when the user is trying - * to use the SAC-SMA, and has not define a SAC-SMA unit hydrograph, but - * does have an API-MKC model unit hydrograph available. - */ - // final String header = "StreamModel.getBestUnitHydrograph(): "; - UnitHydrograph newUnitHydrograph = null; - - String oldUnitHydrographModelType = null; - String modelTypeName = null; - - if (oldUnitHydrograph != null) { - oldUnitHydrographModelType = oldUnitHydrograph - .getRainfallRunoffModelTypeName(); - modelTypeName = _rainfallRunoffModelType.getName(); - } - - // Determine if need to load new unit hydrograph - boolean needToChangeUhg = false; - - if (oldUnitHydrograph == null) { - needToChangeUhg = true; - } else if ((_customUnitHydrograph == null) - && (!oldUnitHydrographModelType.equals(modelTypeName))) { - needToChangeUhg = true; - } - - if (needToChangeUhg) { - newUnitHydrograph = _dataMgr.loadUnitHydrograph(_locationId, - _basinId, _rainfallRunoffModelType.getName()); - _customUnitHydrograph = null; // clear out the custom unit - // hydrograph - - // if did not read any ordinates, try to load a different 1-hour UHG - if (newUnitHydrograph.getOrdinateCount() == 0) { - String otherModelTypeName = null; - - newUnitHydrograph = _dataMgr.loadUnitHydrograph(_locationId, - _basinId, "ANY"); - _customUnitHydrograph = null; - } else { - // System.out.println(header + - // "Unitgraph loaded successfully for the " + - // _rainfallRunoffModelType.getName() + " model."); - } - } - - else // not null and the rainfall-runoff model types match - { - newUnitHydrograph = oldUnitHydrograph; - } - - return newUnitHydrograph; - } - - // ------------------------------------------------------------------------------------- - - private void refreshModelData() { - String header = "StreamModel.refreshModelData(): "; - // System.out.println(header + " started"); - - // This is to be called when the model is being re-run - - if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) { - // _rainfallRunoffModel = initKcApiModelData(_unitHydrograph, - // _ratingCurve); - } else if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - SacSmaRainfallRunoffModel sacModel = (SacSmaRainfallRunoffModel) _rainfallRunoffModel; - sacModel.setState(_sacState); - } - - } // refreshModelData() - // ------------------------------------------------------------------------------------- - - private RainfallRunoffModel initSacSmaModelData() { - String header = "StreamModel.initSacSmaModelData():"; - - // CodeTimer timer1 = new CodeTimer(); - // timer1.start(); - - // long lastValidTime = getLatestHourTime(); - long lastValidTime = _modelStartTimeHolder.getTime(); - - _sacParams = _dataMgr.loadSacSmaParameters(_basinId, lastValidTime); - if (_sacParams == null) { - _sacParams = getDefaultParams(); - } - // System.out.println("sacParams = " + _sacParams); - - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - _sacState = getSacSmaStateFromDescriptorList(lastValidTime); - if (_sacState == null) { - _sacState = getDefaultSacSmaState(); - } - - // _sacState = _dataMgr.loadSacSmaState(_basinId, lastValidTime); - - // System.out.println("sacState = " + _sacState); - - // - boolean useStaticMape = true; - - if (_config != null) { - useStaticMape = _config.useStaticEvap(); - } - - boolean isAdjustment = false; - - if (useStaticMape) // using the 12 monthly values straight - { - isAdjustment = false; - } else // using the MAPE time series. Using the 12 monthly values as - // adjustment factors - { - isAdjustment = true; - } - - MonthlyValues monthlyValues = _dataMgr.loadMonthlyValues(_basinId, - isAdjustment); - - double peAdjust = _sacParams.getPeadj(); - double pxAdjust = _sacParams.getPxadj(); - - RainfallRunoffModel rainfallRunoffModel = new SacSmaRainfallRunoffModel( - _sacState, _sacParams, peAdjust, pxAdjust, useStaticMape, - monthlyValues, _evaporationTimeSeriesHolder); - - // timer1.stop(header + "model setup took"); - - return rainfallRunoffModel; - - } - - // ------------------------------------------------------------------------------------- - - private RainfallRunoffModel initKcApiModelData( - UnitHydrograph unitHydrograph, RatingCurve ratingCurve) { - String header = "StreamModel.initKcApiModelData():"; - - // CodeTimer timer1 = new CodeTimer(); - // timer1.start(); - - _thresholdRunoff = findThresholdRunoffValue(unitHydrograph, ratingCurve); - - // System.out.println(header + "before getFfgValue() ffhValue = " + - // _ffhValue); - _ffhValue = findFfhValue(_ffhDescriptor); - // System.out.println(header + "after getFfgValue() ffhValue = " + - // _ffhValue); - - RainfallRunoffModel rainfallRunoffModel = new KcApiRainfallRunoffModel( - _thresholdRunoff, _ffhValue); - - // timer1.stop(header + "model setup took"); - - return rainfallRunoffModel; - - } - - // ------------------------------------------------------------------------------------- - public StageToFlowValueMapper getStageToFlowValueMapper() { - return _stageToFlowValueMapper; - } - - // ------------------------------------------------------------------------------------- - - public String getLocationName() { - return _locationName; - } - - // ------------------------------------------------------------------------------------- - - public boolean hasSacSmaParams() { - return _dataMgr.hasSacSmaParams(_basinId); - } - - // ------------------------------------------------------------------------------------- - - public long getSacParamsValidTime() { - long time = 0; - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - time = _sacParams.getValidTime(); - - } - - return time; - } - - // ------------------------------------------------------------------------------------- - - public long getSacStateValidTime() { - long time = 0; - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - time = _sacState.getValidTime(); - } - - return time; - } - - // ------------------------------------------------------------------------------------- - - private double findThresholdRunoffValue(UnitHydrograph unitHydrograph, - RatingCurve ratingCurve) { - - String header = "StreamModel.getThresholdRunoffValue()"; - - double thresholdRunoff = _dataMgr.loadThresholdRunoffValue(_locationId); - - if (thresholdRunoff == _dataMgr.MISSING) { - // System.out.println(header + - // "going to calculate the ThresholdRunoff value"); - SigRiverLevels sigStages = _dataMgr.loadSigRiverLevels(_locationId); - - if (sigStages != null) { - thresholdRunoff = calculateThresholdRunoffValue(sigStages - .getFloodStage(), unitHydrograph, ratingCurve); - } else { - thresholdRunoff = _dataMgr.MISSING; - } - } - return thresholdRunoff; - } - - // ---------------------------------------------------------------------------- - private double calculateThresholdRunoffValue(double floodStage, - UnitHydrograph unitHydrograph, RatingCurve ratingCurve) { - String header = "StreamModel.calculateThresholdRunoffValue()"; - // System.out.println(header + " - just starting"); - - double thresholdRunoffValue = 0; - double peakFlow = _dataMgr.MISSING; - double floodFlow = ratingCurve.getDischargeFromStage(floodStage); - RelTimeMeasurement peakMeasurement = unitHydrograph - .getPeakFlowMeasurement(); - - if (peakMeasurement != null) { - peakFlow = peakMeasurement.getValue(); - thresholdRunoffValue = floodFlow / peakFlow; - } - - // System.out.println(header + "thresholdRunoff = " + - // thresholdRunoffValue); - return thresholdRunoffValue; - } - - // ---------------------------------------------------------------------------- - public double findFfhValue() { - return findFfhValue(_ffhDescriptor); - } - - // ---------------------------------------------------------------------------- - - private double findFfhValue(FFHDescriptor descriptor) { - double ffhValue = -999; - - if (descriptor != null) { - ffhValue = descriptor.getValueInInches(); - } - - else // (descriptor == null) - { - AbsTimeMeasurement ffhMeasurement = _dataMgr - .loadMostCurrentFfhMeasurement(_locationId, _basinId, - _modelStartTimeHolder.getTime()); - - // System.out.println( - // "StreamModel.findFfhValue(): modelStartTimeHolder : " + - // _modelStartTimeHolder.getTime() ); - - if (ffhMeasurement != null) { - ffhValue = ffhMeasurement.getValue(MeasuringUnit.inches); - } else { - ffhValue = getDefaultFFHDescriptor().getValueInInches(); - } - // System.out.println("StreamModel.getFfhValue() = " + ffhValue); - - } - - return ffhValue; - } - - // ---------------------------------------------------------------------------- - public List getFFHDescriptorList() { - _ffhDescriptorList = _dataMgr.loadFfhDescriptorList(_locationId, - _basinId); - - if (_ffhDescriptorList.size() == 0) { - _ffhDescriptorList.add(getDefaultFFHDescriptor()); - } - - return _ffhDescriptorList; - } - - // ---------------------------------------------------------------------------- - private FFHDescriptor getDefaultFFHDescriptor() { - AbsTimeMeasurement measurement = new AbsTimeMeasurement( - _defaultFFHValue, getLatestHourTime(), _ffhUnit); - FFHDescriptor descriptor = new FFHDescriptor(_locationId, measurement, - DEFAULT_FFG_DURATION_CODE, false); - descriptor.setIsDefaultValue(true); - - return descriptor; - } - - // ---------------------------------------------------------------------------- - public List getSacSmaStateDescriptorList() { - List list = _dataMgr - .loadSacSmaStateDescriptorListByBasinId(getBasinId()); - if (list.size() == 0) { - SacSmaState state = getDefaultSacSmaState(); - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - - list.add(descriptor); - } - return list; - } - - // ---------------------------------------------------------------------------- - private SacSmaState getSacSmaStateFromDescriptorList(long modelRunStartTime) { - // trace(); - String header = "StreamModel.getSacSmaStateFromDescriptorList(): "; - SacSmaState returnState = null; - - if (_sacStateDescriptorList == null) { - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - } - - for (int i = 0; i < _sacStateDescriptorList.size(); i++) { - SacSmaStateDescriptor descriptor = (SacSmaStateDescriptor) _sacStateDescriptorList - .get(i); - SacSmaState state = descriptor.getState(); - - // System.out.println(header + " modelRunStartTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime)); - // System.out.println(header + " i = " + i + " state = " + state); - - if (state.getValidTime() <= modelRunStartTime) { - returnState = state; - // System.out.println(header + "will return this state i = " + i - // + " state = " + state); - - break; - } - - } - - return returnState; - } - - // ---------------------------------------------------------------------------- - private SacSmaState getLatestSacSmaStateFromDescriptorList() { - // trace(); - String header = "StreamModel.getLatestSacSmaStateFromDescriptorList(): "; - SacSmaState returnState = null; - - if (_sacStateDescriptorList == null) { - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - } - - if (_sacStateDescriptorList.size() > 0) { - SacSmaStateDescriptor descriptor = (SacSmaStateDescriptor) _sacStateDescriptorList - .get(0); - SacSmaState state = descriptor.getState(); - returnState = state; - // System.out.println(header + "will return state = " + state); - } - - return returnState; - } - - // ---------------------------------------------------------------------------- - private SacSmaState getDefaultSacSmaState() { - SacSmaState state = new SacSmaState(); - state.setSource("BOGUS DEFAULT"); - - state.setBasinId(_basinId); - state.setValidTime(getLatestHourTime()); - - state.setUztwc(31.02); - state.setUzfwc(0.009); - state.setLztwc(31.94); - state.setLzfsc(0.060); - state.setLzfpc(74.74); - state.setAdimc(62.04); - - return state; - } - - // ---------------------------------------------------------------------------- - private static SacSmaParameters getDefaultParams() { - // uses sept93 data for ELDO2) - /* - * PXADJ = 1.000 PEADJ = 1.000 UZTWM = 60.000 UZFWM = 25.000 UZK = 0.350 - * PCTIM = 0.000 ADIMP = 0.000 RIVA = 0.003 ZPERC = 210.000 REXP = 1.40 - * LZTWM = 120.000 LZFSM = 25.000 LZFPM = 150.000 LZSK = 0.080 LZPK = - * 0.004 PFREE = 0.250 RSERV = 0.300 SIDE = 0.000 IOPTET=0 //we don't - * have this one, so ignore it EFC = 0.50 - */ - - SacSmaParameters params = new SacSmaParameters(); - - params.setPxadj(1.0); - params.setPeadj(1.0); - params.setUztwm(60.0); - params.setUzfwm(25.0); - params.setUzk(0.35); - params.setPctim(0.000); - params.setAdimp(0.000); - params.setRiva(0.003); - params.setZperc(210.000); - params.setRexp(1.40); - params.setLztwm(120.000); - params.setLzfsm(25.0); - params.setLzfpm(150.000); - params.setLzsk(0.080); - params.setLzpk(0.004); - params.setPfree(0.250); - params.setRserv(0.300); - params.setSide(0.000); - params.setEfc(.50); - - return params; - } - - // ----------------------------------------------------------------------- - - public void reloadPrecipTimeSeries() { - initDbPrecipTimeSeries(); - - return; - } - - // --------------------------------------------------------------------- - - public void reloadFilePrecipTimeSeries(String filePathString) { - initFilePrecipTimeSeries(filePathString); - - return; - } - - // --------------------------------------------------------------------- - - private void initDbPrecipTimeSeries() { - String header = "StreamModel.initDbPrecipTimeSeries() : "; - - long lastTimeSeriesHour = _modelEndTimeHolder.getTime(); - long firstTimeSeriesHour = lastTimeSeriesHour - MAX_DAYS_OF_TIME_SERIES - * 24 * MILLIS_PER_HOUR; - - // precip - long lastObsTime = TimeHelper.truncateTimeInMillisToNearestHour(System - .currentTimeMillis(), 1); - long firstObsTime = lastObsTime - MAX_DAYS_OF_TIME_SERIES * 24 - * MILLIS_PER_HOUR; - RegularTimeSeries obsPrecipTs = loadObservedPrecipTimeSeries( - firstObsTime, lastObsTime); - obsPrecipTs.setName("Original Observed Precip Ts"); - // System.out.println(header + - // "after loadObservedPrecipTimeSeries, obs precip ts = " + - // obsPrecipTs); - - // new code - // CodeTimer timer = new CodeTimer(); - // timer.start(); - RegularTimeSeries fcstPrecipTs = _dataMgr.loadFcstMapTimeSeries( - _basinId, getLatestHourTime() + _millisPerHour); - // timer.stop("_dataMgr.loadFcstMapTimeSeries took "); - - RegularTimeSeries fullPrecipTs = RegularTimeSeries.concatenate( - obsPrecipTs, fcstPrecipTs); - // end new code - - long precipStartTime = obsPrecipTs.getStartTime(); - if ((precipStartTime < firstTimeSeriesHour) - || (precipStartTime > lastTimeSeriesHour)) { - // System.out.println(header + " creating a new time series"); - // obsPrecipTs = new RegularTimeSeries(firstTimeSeriesHour, - // lastTimeSeriesHour, - // 1, MeasuringUnit.inches); - // System.out.println(header + "after re-creation obs precip ts = " - // + obsPrecipTs); - } else { - // System.out.println(header + "before stretching obs precip ts = " - // + obsPrecipTs); - - // obsPrecipTs.stretchTimeSeries(firstTimeSeriesHour, - // lastTimeSeriesHour, 0.0); - fullPrecipTs.stretchTimeSeries(firstTimeSeriesHour, - lastTimeSeriesHour, 0.0); - - // System.out.println(header + "after stretching obs precip ts = " + - // obsPrecipTs); - } - - // _precipTimeSeriesHolder.setTimeSeries(obsPrecipTs); - _precipTimeSeriesHolder.setTimeSeries(fullPrecipTs); - - return; - } - - // ---------------------------------------------------------------------------- - - private void initFilePrecipTimeSeries(String filePathString) { - String header = "StreamModel.initFilePrecipTimeSeries() : "; - - long lastTimeSeriesHour = _modelEndTimeHolder.getTime(); - long firstTimeSeriesHour = lastTimeSeriesHour - MAX_DAYS_OF_TIME_SERIES - * 24 * MILLIS_PER_HOUR; - - // precip - long lastObsTime = TimeHelper.truncateTimeInMillisToNearestHour(System - .currentTimeMillis(), 1); - long firstObsTime = lastObsTime - MAX_DAYS_OF_TIME_SERIES * 24 - * MILLIS_PER_HOUR; - RegularTimeSeries obsPrecipTs = loadObservedPrecipTimeSeries( - firstObsTime, lastObsTime); - obsPrecipTs.setName("Original Observed Precip Ts"); - // System.out.println(header + - // "after loadObservedPrecipTimeSeries, obs precip ts = " + - // obsPrecipTs); - - RegularTimeSeries fcstPrecipTs = _dataMgr.loadFcstMapTimeSeries( - _basinId, getLatestHourTime() + _millisPerHour); - - RegularTimeSeries fullPrecipTs = _dataMgr - .loadFileMapTimeSeries(filePathString); - - long precipStartTime = obsPrecipTs.getStartTime(); - if ((precipStartTime < firstTimeSeriesHour) - || (precipStartTime > lastTimeSeriesHour)) { - - } else { - fullPrecipTs.stretchTimeSeries(firstTimeSeriesHour, - lastTimeSeriesHour, 0.0); - - } - - _precipTimeSeriesHolder.setTimeSeries(fullPrecipTs); - - return; - } - - // ---------------------------------------------------------------------------- - - // -------------------------------------------------------- - - private void initAllNonPrecipTimeSeries() { - // long lastEvenHour = getLatestHourTime(); - long lastEvenHour = _modelStartTimeHolder.getTime(); - long nextEvenHour = lastEvenHour + _millisPerHour; - long endOfPrecipForecastTime = _modelEndTimeHolder.getTime(); - - // potential evaporation - RegularTimeSeries evaporationTimeSeries = _dataMgr - .loadPotentialEvaporationTimeSeries(_basinId, - _modelStartTimeHolder.getTime(), _modelEndTimeHolder - .getTime()); - - _evaporationTimeSeriesHolder.setTimeSeries(evaporationTimeSeries); - - // stage - if (_observedStageTimeSeriesHolder.getTimeSeries() == null) { - IrregularTimeSeries obsStageTimeSeries = loadObservedStageTimeSeries(); - _observedStageTimeSeriesHolder.setTimeSeries(obsStageTimeSeries); - - } - - // stage - if (_priorForecastStageTimeSeriesHolder.getTimeSeries() == null) { - IrregularTimeSeries priorForecastTimeSeries = loadPriorForecastTimeSeries(); - _priorForecastStageTimeSeriesHolder - .setTimeSeries(priorForecastTimeSeries); - - } - - // used for some rainfall-runoff models - setInitialStageMeasurement(findInitialStageMeasurement()); - - // runoff, both calculated now and prior runoff read from the database - if (_runoffTimeSeriesHolder.getTimeSeries() == null) { - RegularTimeSeries runoffTimeSeries = new RegularTimeSeries( - nextEvenHour, endOfPrecipForecastTime, _intervalInHours, - MeasuringUnit.mm); - - _runoffTimeSeriesHolder.setTimeSeries(runoffTimeSeries); - - } - - // used in initRainfallRunoffModelData() now - // remove after 6/1/07 - // loadPriorRunoffTimeSeries(); - - } - - // ---------------------------------------------------------------------------- - private void loadPriorRunoffTimeSeries() { - String header = "StreamModel.loadPriorRunoffTimeSeries() "; - System.out.println(header + " - called."); - // load prior runoff - String typeSource = determineTypeSourceForPriorRunoffTimeSeries(); - - _unitHydrograph = getBestUnitHydrograph(_unitHydrograph); - - RegularTimeSeries priorRunoffTimeSeries = _dataMgr - .loadPriorRunoffTimeSeries(_locationId, typeSource, - getModelStartTime(), _unitHydrograph.getOrdinateCount()); - - _priorRunoffTimeSeriesHolder.setTimeSeries(priorRunoffTimeSeries); - } - - // ---------------------------------------------------------------------------- - - private String determineTypeSourceForPriorRunoffTimeSeries() { - String typeSource = null; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - if (_sacState != null) { - SSHPSource source = SSHPSource - .findMatchingSSHPSourceBySacSmaSource(_sacState - .getSource()); - - if (source != null) { - typeSource = source.getTypeSource(); - } - } - } - - return typeSource; - } - - // ---------------------------------------------------------------------------- - - private void initAllTimeSeries() { - // _tracer.trace(); - - setModelStartTime(getLatestHourTime()); - - initDbPrecipTimeSeries(); - - initAllNonPrecipTimeSeries(); - - return; - } - - // ----------------------------------------------------------- - public TimeHolder getModelStartTimeHolder() { - return _modelStartTimeHolder; - } - - // ---------------------------------------------------------------------------- - - public long getModelStartTime() { - return _modelStartTimeHolder.getTime(); - } - - // ---------------------------------------------------------------------------- - - public void setFFHProductDescriptor(FFHDescriptor descriptor) { - _ffhDescriptor = descriptor; - - } - - // ---------------------------------------------------------------------------- - public void setSacSmaStateDescriptor(SacSmaStateDescriptor descriptor) { - String header = "StreamModel.setSacSmaStateDescriptor(): "; - _sacSmaStateDescriptor = descriptor; - - _sacState = _sacSmaStateDescriptor.getState(); - } - - // ---------------------------------------------------------------------------- - - public void setModelStartTime(long modelStartTime) { - modelStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - modelStartTime, 1); - // trace(); - _modelStartTimeHolder.setTime(modelStartTime); - - // sets the model end time - setForecastLengthInHours(_forecastLengthInHours); - - /* - * int baseHours = 72; int unitHydrographDuration = 0; - * - * if (_unitHydrograph != null) { unitHydrographDuration = - * _unitHydrograph.getOrdinateCount(); } - * - * int totalHours = baseHours + unitHydrographDuration; - * - * //make sure that the time series are not too huge // 100 days should - * be enough if (totalHours > 2400) { totalHours = 2400; } - */ - - return; - } - - // ----------------------------------------------------------- - public void setForecastLengthInHours(int lengthInHours) { - // String header = "StreamModel.setForecastLengthInHours(): "; - - // System.out.println(header + "lengthInHours = " + lengthInHours); - - if (lengthInHours > 0) { - _forecastLengthInHours = lengthInHours; - long duration = ((long) (lengthInHours) * (long) MILLIS_PER_HOUR); - long newEndTime = _modelStartTimeHolder.getTime() + duration; - - setModelEndTime(newEndTime); - } - - return; - } - - // ----------------------------------------------------------- - - public int getForecastHours() { - return _forecastLengthInHours; - } - - // ----------------------------------------------------------- - - public void setModelEndTime(long modelEndTime) { - _modelEndTimeHolder.setTime(modelEndTime); - } - - // ----------------------------------------------------------- - public long getLatestHourTime() { - return TimeHelper.truncateTimeInMillisToNearestHour(System - .currentTimeMillis(), 1); - } - - // ----------------------------------------------------------- - - public String getLocationId() { - return _locationId; - - } - - public String getBasinId() { - return _basinId; - } - - // ------------------------------------------------------------- - - public SigRiverLevels getSigRiverLevels() { - // if needed, retrieve and cache the data - // then return the value - if (_sigRiverLevels == null) { - _sigRiverLevels = _dataMgr.loadSigRiverLevels(_locationId); - - boolean stagesAreMissing = false; - if (!_sigRiverLevels.hasFloodStage() - || !_sigRiverLevels.hasActionStage()) { - stagesAreMissing = true; - } - - // if the site is set up to use discharge (flow) instead of stage, - // convert from flow to stage and populate the floodStage and - // actionStage - // (if possible), - // so that they are available to other parts of the program - if (stagesAreMissing) { - RatingCurve ratingCurve = getRatingCurve(); - if (_sigRiverLevels.hasFloodFlow()) { - double floodFlow = _sigRiverLevels.getFloodFlow(); - double floodStage = ratingCurve - .getStageFromDischarge(floodFlow); - _sigRiverLevels.setFloodStage(floodStage); - } - if (_sigRiverLevels.hasActionFlow()) { - double actionFlow = _sigRiverLevels.getActionFlow(); - double actionStage = ratingCurve - .getStageFromDischarge(actionFlow); - _sigRiverLevels.setActionStage(actionStage); - } - } - - } - - return _sigRiverLevels; - } - - // ----------------------------------------------------------- - private IrregularTimeSeries loadPriorForecastTimeSeries() { - IrregularTimeSeries forecastStageTimeSeries = null; - - forecastStageTimeSeries = _dataMgr.loadFcstStageTimeSeries( - getLocationId(), getPrimaryPe()); - - return forecastStageTimeSeries; - } - - // ----------------------------------------------------------- - - private RegularTimeSeries loadObservedPrecipTimeSeries(long startTime, - long endTime) { - RegularTimeSeries observedPrecipTimeSeries = null; - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - observedPrecipTimeSeries = _dataMgr - .loadObsMapTimeSeriesFromDb(_basinId); - - if (observedPrecipTimeSeries == null) { - observedPrecipTimeSeries = new RegularTimeSeries(startTime, - endTime, 1, MeasuringUnit.inches); - } - - // timer.stop("StreamModel.loadObservedPrecipTimeSeries() called DataMgr.loadObsMapTimeSeries() which took "); - - // System.out.println("StreamModel.loadObservedPrecipTimeSeries() = " + - // observedPrecipTimeSeries); - - return observedPrecipTimeSeries; - } - - // ----------------------------------------------------------- - - // ----------------------------------------------------------- - - private IrregularTimeSeries loadObservedStageTimeSeries() { - String header = "StreamModel.loadObservedStageTimeSeries() "; - CodeTimer timer = new CodeTimer(); - timer.start(); - - IrregularTimeSeries observedStageTimeSeries = null; - - if (getSigRiverLevels().useStage()) { - - observedStageTimeSeries = _dataMgr - .loadObservedStageTimeSeries(_locationId); - } else // use flow and then convert it - { - IrregularTimeSeries observedDischargeTimeSeries = null; - observedDischargeTimeSeries = _dataMgr - .loadObservedDischargeTimeSeries(_locationId); - if (observedDischargeTimeSeries.getMeasurementCount() > 0) { - observedStageTimeSeries = getRatingCurve().getStageTimeSeries( - observedDischargeTimeSeries); - } else // there is no discharge time series - { - observedStageTimeSeries = _dataMgr - .loadObservedStageTimeSeries(_locationId); - } - } - - setLastObservedTimeForAdjustment(observedStageTimeSeries.getEndTime()); - - timer.stop("StreamModel.loadObservedStageTimeSeries() took "); - - return observedStageTimeSeries; - } - - // ----------------------------------------------------------- - - public void reloadObservedStageTimeSeries() { - IrregularTimeSeries observedStageTimeSeries = loadObservedStageTimeSeries(); - _observedStageTimeSeriesHolder.setTimeSeries(observedStageTimeSeries); - - } - - // ----------------------------------------------------------- - - public DataMgr getDataMgr() { - return _dataMgr; - } - - // ----------------------------------------------------------- - public RegularTimeSeries getDischargeTimeSeries() { - RegularTimeSeries fcstStageTimeSeries = _forecastStageTimeSeriesHolder - .getTimeSeries(); - RegularTimeSeries timeSeries = _ratingCurve - .getDischargeRegularTimeSeries(fcstStageTimeSeries); - - return timeSeries; - - } - - // ----------------------------------------------------------- - - public RegularTimeSeriesHolder getForecastStageTimeSeriesHolder() { - return _forecastStageTimeSeriesHolder; - } - - public IrregularTimeSeriesHolder getPriorForecastStageTimeSeriesHolder() { - return _priorForecastStageTimeSeriesHolder; - } - - // ----------------------------------------------------------- - public RegularTimeSeriesHolder getSimulationStageTimeSeriesHolder() { - return _simulatedStageTimeSeriesHolder; - } - - // ----------------------------------------------------------- - - /* - * public RegularTimeSeriesHolder getObservedPrecipTimeSeriesHolder() { - * return _observedPrecipTimeSeriesHolder; } - */ - // ----------------------------------------------------------- - public IrregularTimeSeriesHolder getObservedStageTimeSeriesHolder() { - return _observedStageTimeSeriesHolder; - } - - // ----------------------------------------------------------- - public RegularTimeSeriesHolder getPrecipTimeSeriesHolder() { - return _precipTimeSeriesHolder; - } - - /* - * public RegularTimeSeriesHolder getForecastPrecipTimeSeriesHolder() { - * return _forecastPrecipTimeSeriesHolder; } - */ - - // ----------------------------------------------------------- - public RegularTimeSeriesHolder getEvaporationTimeSeriesHolder() { - return _evaporationTimeSeriesHolder; - } - - // ----------------------------------------------------------- - - public RegularTimeSeriesHolder getRunoffTimeSeriesHolder() { - return _runoffTimeSeriesHolder; - } - - public RegularTimeSeriesHolder getPriorRunoffTimeSeriesHolder() { - return _priorRunoffTimeSeriesHolder; - } - - // ----------------------------------------------------------- - public String getPrimaryPe() { - - if (_primaryPe == null) { - _primaryPe = _dataMgr.loadPrimaryPe(_locationId); - - } - - return _primaryPe; - } - - // ----------------------------------------------------------- - // load the baseflow - - public Measurement findBaseflowMeasurementOld() { - - String header = "StreamModel.getBaseflowMeasurementOld():"; - - long modelRunStartTime = _modelStartTimeHolder.getTime(); - IrregularTimeSeries observedStageTs = _observedStageTimeSeriesHolder - .getTimeSeries(); - - AbsTimeMeasurement latestMeasurement = null; - Measurement baseflowMeasurement = null; - - boolean done = false; - - // find the latestHeightValue that is not beyond the modelRunStartTime - for (int i = 0; i < observedStageTs.getMeasurementCount() && (!done); i++) { - AbsTimeMeasurement m = observedStageTs - .getAbsTimeMeasurementByIndex(i); - - long measurementTime = m.getTime(); - - if (measurementTime < modelRunStartTime) { - latestMeasurement = m; - } else if (measurementTime > modelRunStartTime) { - done = true; - } - - } // for i - - Measurement heightMeasurement = latestMeasurement; - - if (heightMeasurement != null) { - double heightValue = heightMeasurement.getValue(); - - if (_ratingCurve == null) { - _ratingCurve = getRatingCurve(); - } - - if (_ratingCurve != null) { - double baseflowValue = _ratingCurve - .getDischargeFromStage(heightValue); - - // System.out.println(header + " heightValue = " + heightValue + - // " baseflowValue = " + baseflowValue ); - - // System.out.println(header + "stage measurement = " + - // latestMeasurement); - - baseflowMeasurement = new Measurement(baseflowValue, - MeasuringUnit.cfs); - } - } - - // timer.stop(header + "baseflow retrieval took" ); - - if (baseflowMeasurement == null) { - baseflowMeasurement = new Measurement(0.0, MeasuringUnit.cfs); - } - - return baseflowMeasurement; - - } // end getBaseflowMeasurement() - - // ----------------------------------------------------------- - // load the initial stage measurement from the time series - - public Measurement findInitialStageMeasurement() { - - String header = "StreamModel.findInitialStageMeasurement():"; - - long modelRunStartTime = _modelStartTimeHolder.getTime(); - IrregularTimeSeries observedStageTs = _observedStageTimeSeriesHolder - .getTimeSeries(); - - AbsTimeMeasurement latestMeasurement = null; - Measurement initialStageMeasurement = null; - - boolean done = false; - - // find the latestHeightValue that is not beyond the modelRunStartTime - for (int i = 0; i < observedStageTs.getMeasurementCount() && (!done); i++) { - AbsTimeMeasurement m = observedStageTs - .getAbsTimeMeasurementByIndex(i); - - long measurementTime = m.getTime(); - - if (measurementTime <= modelRunStartTime) { - latestMeasurement = m; - } else if (measurementTime > modelRunStartTime) { - done = true; - } - - } // for i - - initialStageMeasurement = latestMeasurement; - - if (initialStageMeasurement == null) { - initialStageMeasurement = new Measurement(0.0, _stageUnit); - } - - return initialStageMeasurement; - - } // end findInitialStageMeasurement() - - // ----------------------------------------------------------- - public void setBaseflowMeasurementByStageMeasurementOld( - Measurement stageMeasurement) { - double stageValue = 0.0; - double baseflowValue = 0.0; - - if (stageMeasurement != null) { - stageValue = stageMeasurement.getValue(_stageUnit); - } - - if (_ratingCurve != null) { - baseflowValue = _ratingCurve.getDischargeFromStage(stageValue); - } - - Measurement baseflowMeasurement = new Measurement(baseflowValue, - _dischargeUnit); - _initialStageMeasurementHolder.setMeasurement(baseflowMeasurement); - } - - // ----------------------------------------------------------- - public void setInitialStageMeasurement(Measurement stageMeasurement) { - - if (stageMeasurement == null) { - stageMeasurement = new Measurement(0.0, _stageUnit); - } - - _initialStageMeasurementHolder.setMeasurement(stageMeasurement); - } - - // ----------------------------------------------------------- - public void setBaseflowMeasurementOld(Measurement baseflowMeasurement) { - _initialStageMeasurementHolder.setMeasurement(baseflowMeasurement); - } - - // ----------------------------------------------------------- - - public void setFfhValue(double ffhValue) { - String header = "StreamModel.setFfgValue(): "; - // System.out.println(header + " ffhValue = " + ffhValue); - _ffhValue = ffhValue; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) { - KcApiRainfallRunoffModel model = (KcApiRainfallRunoffModel) _rainfallRunoffModel; - model.setFfhValue(_ffhValue); - } - } - - // ----------------------------------------------------------- - - public RegularTimeSeries runModel() { - String header = "StreamModel.runModel()"; - - // System.out.println(header + "inside method"); - - // make sure that model states start out fresh - refreshModelData(); - - _modelRunCount++; - - Measurement initialStageMeasurement = _initialStageMeasurementHolder - .getMeasurement(); - - if (initialStageMeasurement == null) { - initialStageMeasurement = findInitialStageMeasurement(); - /* - * if (_ratingCurve != null) { double stageValue = - * initialStageMeasurement.getValue(MeasuringUnit.feet); double - * baseflowValue = _ratingCurve.getDischargeFromStage(stageValue); - * baseflowMeasurement = new Measurement(baseflowValue, - * MeasuringUnit.cfs); } - */ - - _initialStageMeasurementHolder - .setMeasurement(initialStageMeasurement); - } - - // System.out.println(header + "baseflowMeasurement = " + - // baseflowMeasurement); - - // do the actual calculations - RegularTimeSeries forecastStageTimeSeries = _rainfallToStageModel - .calculateStageTimeSeries(_modelStartTimeHolder.getTime(), - _modelEndTimeHolder.getTime(), _precipTimeSeriesHolder - .getTimeSeries(), _runoffTimeSeriesHolder); - - forecastStageTimeSeries = forecastStageTimeSeries.getSubTimeSeries( - _modelStartTimeHolder.getTime(), _modelEndTimeHolder.getTime()); - - // trim the simulated dischargeTimeSeries - RegularTimeSeries simulatedDischargeTimeSeries = _simulatedDischargeTimeSeriesHolder - .getTimeSeries(); - simulatedDischargeTimeSeries = simulatedDischargeTimeSeries - .getSubTimeSeries(_modelStartTimeHolder.getTime(), - _modelEndTimeHolder.getTime()); - _simulatedDischargeTimeSeriesHolder - .setTimeSeries(simulatedDischargeTimeSeries); - - // convert simulated to stage and put in holder - RegularTimeSeries simulatedStageTimeSeries = _ratingCurve - .getStageRegularTimeSeries(simulatedDischargeTimeSeries); - _simulatedStageTimeSeriesHolder.setTimeSeries(simulatedStageTimeSeries); - - forecastStageTimeSeries.setName("Forecast#" + _modelRunCount); - - _forecastStageTimeSeriesHolder.setTimeSeries(forecastStageTimeSeries); - - return forecastStageTimeSeries; - - } // end runModel - - // ----------------------------------------------------------- - - // ----------------------------------------------------------- - public RatingCurve getRatingCurve() { - return _dataMgr.loadRatingCurve(_locationId); - } - - // ----------------------------------------------------------- - - public void setThresholdRunoff(double thresholdRunoff) { - _thresholdRunoff = thresholdRunoff; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) { - KcApiRainfallRunoffModel model = (KcApiRainfallRunoffModel) _rainfallRunoffModel; - model.setThresholdRunoff(_thresholdRunoff); - } - } - - // ----------------------------------------------------------- - public void saveModelStates(Logger logger) { - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) { - SacSmaRainfallRunoffModel model = (SacSmaRainfallRunoffModel) _rainfallRunoffModel; - - SacSmaState state = model.getState(); - - state.setSource("LOCAL"); - logger.log("StreamModel.saveModelStates(): saved State = " + state); - - _dataMgr.saveSacState(state); - - } - } - - // ----------------------------------------------------------- - public void saveRunoffTimeSeries(Logger logger) { - RegularTimeSeries runoffTimeSeries = getRunoffTimeSeriesHolder() - .getTimeSeries(); - RegularTimeSeries priorRunoffTimeSeries = getPriorRunoffTimeSeriesHolder() - .getTimeSeries(); - - RegularTimeSeries allRunoffTs = null; - - if ((runoffTimeSeries != null) && (priorRunoffTimeSeries != null)) { - allRunoffTs = RegularTimeSeries.concatenate(runoffTimeSeries, - priorRunoffTimeSeries); - } else if (runoffTimeSeries != null) { - allRunoffTs = runoffTimeSeries; - } else if (priorRunoffTimeSeries != null) { - allRunoffTs = priorRunoffTimeSeries; - } - - logger - .log("StreamModel.saveRunoffTimeSeries(): saved runoff time series = " - + allRunoffTs); - - _dataMgr.saveRunoffTimeSeries(_locationId, allRunoffTs); - - } - - // ----------------------------------------------------------- - public void savePrecipTimeSeriesToFile(String filePath) { - RegularTimeSeries precipTimeSeries = getPrecipTimeSeriesHolder() - .getTimeSeries(); - - if (precipTimeSeries != null) { - _dataMgr.saveMapTimeSeriesToFile(precipTimeSeries, filePath); - } - - return; - } - - // ----------------------------------------------------------- - - /** - * @param isBlendingOn - * The isBlendingOn to set. - */ - public void setAdjustmentOn(boolean isAdjustmentOn) { - - _isAdjustmentOn = isAdjustmentOn; - - // Note: params refers to the same object, not a copy - ForecastAdjusterParams params = _forecastAdjuster.getParams(); - params.setShouldDoAdjustment(_isAdjustmentOn); - - // System.out.println("StreamModel.setAdjustmentOn(): new value = " + - // _isAdjustmentOn); - } - - // ----------------------------------------------------------- - public void setLastObservedTimeForAdjustment(long lastTime) { - String header = "StreamModel.setLastObservedTimeForAdjustment():"; - - System.out.println(header + "lastTime = " - + DbTimeHelper.getDateTimeStringFromLongTime(lastTime)); - if (_forecastAdjuster != null) { - _forecastAdjuster.setLastObservedTimeToUseAsInput(lastTime); - } - } - - // ----------------------------------------------------------- - public int getBlendingHours() { - int hoursToAdjust = -1; - final String header = "StreamModel.getBlendingHours():"; - - if (_forecastAdjuster != null) { - hoursToAdjust = _forecastAdjuster.getParams().getBlendingHours(); - } - - return hoursToAdjust; - } - - // ----------------------------------------------------------- - public int getMaxBlendingHours() { - return MAX_BLENDING_HOURS; - } - - // ----------------------------------------------------------- - public void setAdjustmentHours(int hoursToAdjust) { - // final String header = "StreamModel.setAdjustmentHours():"; - - if (_forecastAdjuster != null) { - _forecastAdjuster.getParams().setBlendingHours(hoursToAdjust); - // System.out.println(header + "value = " + hoursToAdjust); - } - - return; - } - - // ----------------------------------------------------------- - - /** - * @return Returns the isBlendingOn. - */ - public boolean isAdjustmentOn() { - return _isAdjustmentOn; - } - - /** - * @return Returns the sacParams. - */ - public SacSmaParameters getSacParams() { - return _sacParams; - } - - /** - * @return Returns the sacState. - */ - public SacSmaState getSacState() { - return _sacState; - } - - public void setSacState(SacSmaState state) { - _sacState = state; - } - - /** - * @param maxForecastLengthInHours - * The maxForecastLengthInHours to set. - */ - public void setMaxForecastLengthInHours(int maxForecastLengthInHours) { - _maxForecastLengthInHours = maxForecastLengthInHours; - } - - /** - * @return Returns the maxForecastLengthInHours. - */ - public int getMaxForecastLengthInHours() { - return _maxForecastLengthInHours; - } - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/GuiHelper.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/GuiHelper.java deleted file mode 100644 index 2a442a0b36..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/GuiHelper.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Created on Jul 23, 2004 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Color; -import java.awt.Dimension; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; - -/** - * @author GobsC - * - * - */ -public class GuiHelper -{ - private static final Color _comboBoxColor = new Color(194, 141,237); - private static final Color _buttonColor = new Color(158,244,252); - - private GuiHelper() - { - //does nothing. No one is allowed to call this. - } - - public static JComboBox getJComboBox(String[] contentArray) - { - String header = "AnalysisWindow.getJButton(): "; - - - JComboBox comboBox = new JComboBox(contentArray); - - // Color color = new Color(97, 166, 96); - - // comboBox.setBackground(_comboBoxColor); - - return comboBox; - - } - // ------------------------------------------------------------ - public static JComboBox getJComboBox() - { - String header = "AnalysisWindow.getJButton(): "; - - - JComboBox comboBox = new JComboBox(); - - // Color color = new Color(97, 166, 96); - - // comboBox.setBackground(_comboBoxColor); - - return comboBox; - - } - // ------------------------------------------------------------ - - - public static JButton getJButton(String text) - { - String header = "AnalysisWindow.getJButton(): "; - - int width = 150; - int height = 35; - - JButton button = new JButton(text); - - //button.setFont(_buttonFont); - - // Color color = new Color(158, 244, 252); - - // button.setBackground(_buttonColor); - - button.setSize(new Dimension(width, height)); - - return button; - - } - - // ------------------------------------------------------------ - - public static JButton getJButton(ImageIcon imageIcon) - { - JButton button = new JButton(imageIcon); - - //button.setBackground(Color.GRAY); - - return button; - - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PositionedText.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PositionedText.java deleted file mode 100644 index e5bbfa04a4..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PositionedText.java +++ /dev/null @@ -1,42 +0,0 @@ -package ohd.hseb.sshp.gui; - -import java.awt.Point; - -public class PositionedText -{ - private StringBuffer _stringBuffer = null; - private Point _position; - - public PositionedText() - { - _stringBuffer = new StringBuffer(); - _position = new Point(0, 0); - } - - public void clear() - { - _stringBuffer.delete(0, _stringBuffer.length()); - } - - public void setStringBuffer(StringBuffer stringBuffer) - { - _stringBuffer = stringBuffer; - } - - public StringBuffer getStringBuffer() - { - return _stringBuffer; - } - - public void setPosition(Point position) - { - _position = position; - } - - public Point getPosition() - { - return _position; - } - - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PrecipPainter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PrecipPainter.java deleted file mode 100644 index 3124264dea..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PrecipPainter.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Point; -import java.text.DecimalFormat; -import java.text.NumberFormat; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.TsCanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of precipitation data on a PaintableCanvas - */ -public class PrecipPainter implements TsCanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _barColor = null; - private Color _outlineColor = null; - - private RegularTimeSeriesHolder _precipTimeSeriesHolder = null; - private TsPaintableCanvas _canvas = null; - - private boolean _shouldDrawBars = true; - - private boolean _shouldPaint = true; - - private boolean _showPrecipAmounts = false; - - private static final Font _labelFont = new Font("Helvetica",Font.PLAIN,9); - - private static final double VERY_SMALL_NUMBER = 0.0000000000000001; - - private NumberFormat _numberFormat = null; - - // --------------------------------------------------------- - public PrecipPainter(Color barColor, - Color outlineColor, - RegularTimeSeriesHolder timeSeriesHolder, - boolean showPrecipAmounts, - TsPaintableCanvas canvas) - { - - _precipTimeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _barColor = barColor; - _outlineColor = outlineColor; - - setShowPrecipAmounts(showPrecipAmounts); - - _numberFormat = new DecimalFormat("#.0#"); - } - -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - - //System.out.println("PrecipPainter.paint(): precip ts = " + getTimeSeries()); - if (_shouldPaint) - { - drawDataBars(g); - } - } - -// ---------------------------------------------------- - private void drawDataBars( Graphics g ) - { - String header = "PrecipPainter.drawDataBars(): "; - // System.out.println(header + "-------------------------"); - int x1; - int y1; - int x2; - int y2; - g.setColor(_barColor); - - if (_showPrecipAmounts) - { - g.setFont( _labelFont ); - } - - //draw each data bar - for ( int i = 0; (getTimeSeries() != null) && - ( i < getTimeSeries().getMeasurementCount()); i++) - { - - Measurement measurement = (Measurement) - getTimeSeries().getMeasurementByIndex(i); - - Measurement convertedMeasurement = Measurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double value = convertedMeasurement.getValue(); - - if (value > VERY_SMALL_NUMBER) - - { - - long endTime = getTimeSeries().getMeasurementTimeByIndex(i); - long startTime = endTime - MILLIS_PER_HOUR; - - /* - if (!_shouldDrawBars) - { - String timeString = CanvasHelper.getDateTimeStringFromLongTime(endTime); - System.out.println("Time = " + timeString + " value = " + value); - } - */ - - DataPoint dp1 = new DataPoint(startTime, 0); - DataPoint dp2 = new DataPoint(endTime, value); - - - if ( (getViewport().isViewable(dp1)) && - (getViewport().isViewable(dp2)) - ) - { - - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - - int barHeight = Math.abs(p1.y - p2.y); - int barWidth = Math.abs(p1.x - p2.x); - - if (_shouldDrawBars) - { - g.setColor(_barColor); - g.fillRect(p1.x, p2.y, barWidth, barHeight); - - g.setColor(_outlineColor); - g.drawRect(p1.x, p2.y, barWidth, barHeight); - - if (_showPrecipAmounts) - { - g.setColor(_outlineColor); - - g.drawString(_numberFormat.format(value), p1.x, p2.y -2); - } - } - else //draw Lines - { - g.setColor(_barColor); - g.drawLine(p1.x, p2.y, p1.x + barWidth, p2.y); - - } - } - - }//end if value > 0.0 - - } // for loop - - - } // end of drawDataBars method -// ---------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - private RegularTimeSeries getTimeSeries() - { - return _precipTimeSeriesHolder.getTimeSeries(); - } - -//--------------------------------------------------------- - public Measurement getMinMeasurement() - { - //force this method to return 0.0 always, since - //I always want 0 shown, regardless of the actual measurements - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - /* - - Measurement minMeasurement = null; - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - if (minMeasurement != null) - { - minMeasurement = new Measurement(minMeasurement); - } - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - - */ - return minMeasurement; - } -//---------------------------------------------------- - - public Measurement getMaxMeasurement() - { - - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - - String header = "PrecipPainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - if (maxMeasurement != null) - { - maxMeasurement = new Measurement(maxMeasurement); - - if ( maxMeasurement.getValue(_canvas.getDisplayedMeasuringUnit()) < 1.0) - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - //System.out.println(header + " time series was null, setting max measurement to 1.0 "); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - - - //System.out.println(header + " max measurement is " + maxMeasurement); - - return maxMeasurement; - } - -// ---------------------------------------------------- - - public void setShouldDrawBars(boolean shouldDrawBars) - { - _shouldDrawBars = shouldDrawBars; - } - -// ---------------------------------------------------- - - - public boolean shouldDrawBars() - { - return _shouldDrawBars; - } - - public void setShowPrecipAmounts(boolean showPrecipAmounts) - { - _showPrecipAmounts = showPrecipAmounts; - } - - public boolean isShowPrecipAmounts() - { - return _showPrecipAmounts; - } - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PrecipTotalTextPainter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PrecipTotalTextPainter.java deleted file mode 100644 index 6a7b2635ae..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/PrecipTotalTextPainter.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Point; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.measurement.TimeSeriesTotaller; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.CanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends CanvasPainter and encapsulates the - * drawing of precipitation total textual data on a PaintableCanvas - */ -public class PrecipTotalTextPainter implements CanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - private static final Font _labelFont = new Font("Helvetica",Font.PLAIN,12); - private static final int Y_OFFSET = 2; - private static final double VERY_SMALL_NUMBER = 0.0000000000000001; - - private RegularTimeSeriesHolder _precipTimeSeriesHolder = null; - private TsPaintableCanvas _canvas = null; - - private boolean _shouldPaint = true; - private boolean _showPrecipAmounts = false; - - private NumberFormat _numberFormat = null; - private Color _textColor = null; - - private RegularTimeSeries _sixHourTimeSeries = null; - private RegularTimeSeries _twelveHourTimeSeries = null; - private RegularTimeSeries _twentyFourHourTimeSeries = null; - - private Map _timeToPositionedTextMap = new HashMap(); - // --------------------------------------------------------- - public PrecipTotalTextPainter(Color textColor, - RegularTimeSeriesHolder timeSeriesHolder, - boolean shouldPaint, - TsPaintableCanvas canvas) - { - - _precipTimeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _textColor = textColor; - setShouldPaint(shouldPaint); - - _numberFormat = new DecimalFormat("#.0#"); - } - -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - //System.out.println("PrecipTotalTextPainter.paint(): precip ts = " + getTimeSeries()); - - if (_shouldPaint) - { - _timeToPositionedTextMap.clear(); - - - positionText(g, 6, 0, true); - // positionText(g, 12, 0, false); - - positionText(g, 24, 0, false); - positionText(g, 24, 6, false); - positionText(g, 24, 12, false); - positionText(g, 24, 18, false); - - drawText(g); - } - - } -// ---------------------------------------------------- - public void drawText(Graphics g) - { - FontHelper fontHelper = new FontHelper(_labelFont); - - RegularTimeSeries timeSeries = _precipTimeSeriesHolder.getTimeSeries(); - long startTime = timeSeries.getStartTime(); - long endTime = timeSeries.getEndTime(); - - for ( long t = startTime; (timeSeries != null) && - ( t <= endTime ); t+= MILLIS_PER_HOUR) - { - PositionedText positionedText = - getPositionedText(t); - - if (positionedText != null) - { - String text = positionedText.getStringBuffer().toString(); - int x = positionedText.getPosition().x; - int y = positionedText.getPosition().y; - - - int width = fontHelper.getWidth(g, text); - - x -= width/2; - - g.drawString(text, x, y ); - - } - } - } - -// ---------------------------------------------------- - - private void positionText( Graphics g, - int intervalInHours, - int shiftInHours, - boolean isFirst) - { - String header = "PrecipTotalTextPainter.positionText(): "; - - int y = _canvas.getHeight() - Y_OFFSET; - - g.setFont( _labelFont ); - - RegularTimeSeries precipTimeSeries = _precipTimeSeriesHolder.getTimeSeries(); - - RegularTimeSeries timeSeries = - TimeSeriesTotaller.getRegularTimeSeries(intervalInHours, - shiftInHours, - precipTimeSeries); - - - // System.out.println(header + "--------------------\n" + timeSeries.toString()); - // System.out.println(header + "-------end of time series-------------n" ); - - StringBuffer stringBuffer = new StringBuffer(); - //draw each data bar - for ( int i = 0; (timeSeries != null) && - ( i < timeSeries.getMeasurementCount()); i++) - { - - AbsTimeMeasurement measurement = (AbsTimeMeasurement) - timeSeries.getAbsTimeMeasurementByIndex(i); - - AbsTimeMeasurement convertedMeasurement = AbsTimeMeasurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double value = convertedMeasurement.getValue(); - - long endTime = convertedMeasurement.getTime(); - - // System.out.println(header + "value = " + value + " endTime = " + getTimeString(endTime)); - - DataPoint dp1 = new DataPoint(endTime, 0); - Point p1 = getViewport().getScreenPoint(dp1); - - g.setColor(_textColor); - - PositionedText positionedText = getPositionedText(endTime, true); - if (isFirst) - { - positionedText.clear(); - } - else - { - positionedText.getStringBuffer().append(" / "); - } - positionedText.getStringBuffer().append(_numberFormat.format(value)); - positionedText.setPosition(new Point(p1.x, y)); - - } // for loop - - - } // end of drawDataBars method - - // -------------------------------------------------------------------------------- - - private static String getTimeString(long time) - { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } - - // -------------------------------------------------------------------------------- - - private PositionedText getPositionedText(long time, boolean createNewOne) - { - // String header = "PrecipTotalTextPainter.getPositionedText(): "; - - PositionedText text = null; - text = (PositionedText) _timeToPositionedTextMap.get(new Long(time)); - if ((text == null) && (createNewOne)) - { - text = new PositionedText(); - _timeToPositionedTextMap.put(new Long(time), text); - // System.out.println(header + getTimeString(time)); - } - - return text; - } - -// ---------------------------------------------------- - - private PositionedText getPositionedText(long time) - { - return getPositionedText(time, false); - } -// ---------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - private RegularTimeSeries getTimeSeries() - { - return _precipTimeSeriesHolder.getTimeSeries(); - } - - public void setShowPrecipAmounts(boolean showPrecipAmounts) - { - _showPrecipAmounts = showPrecipAmounts; - } - - public boolean isShowPrecipAmounts() - { - return _showPrecipAmounts; - } - -//--------------------------------------------------------- - -} //end of PrecipPainter diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/SettingPanel.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/SettingPanel.java deleted file mode 100644 index 56fce9f7f6..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/SettingPanel.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Created on Nov 12, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - - - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JTextField; - -/** - * @author GobsC - * - * This group of controls is used for an idiom in which - * a text field shows the value and allows the user to change it, - * a label tells the user what the value represents, - * and a buttom allows the user to reset the value - * to one retrieved from the database value. - */ -public class SettingPanel -{ - - private JLabel _label = null; - private JTextField _textField = null; - private JButton _button = null; - - - public SettingPanel(String labelString, int textFieldLength, String buttonString, String toolTipString) - { - initGui(labelString, textFieldLength, buttonString, toolTipString); - - } //end SettingPanel() - - // ----------------------------------------------------------------------------- - private void initGui(String labelString, int textFieldLength, String buttonString, String toolTipString) - { - - - - _label = new JLabel(labelString); - _textField = new JTextField(textFieldLength); - //_textField.setColumns(textFieldLength); - - _button = GuiHelper.getJButton(buttonString); - _button.setToolTipText(toolTipString); - - return; - - } //end initGui(); - - // --------------------------------------------------------- - - - // --------------------------------------------------------- - - - public JLabel getLabel() - { - return _label; - } - - // --------------------------------------------------------- - - public JTextField getTextField() - { - return _textField; - } - - // --------------------------------------------------------- - - public JButton getButton() - { - return _button; - } - // --------------------------------------------------------- - -} //end class SettingPanel diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/SigStageLinePainter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/SigStageLinePainter.java deleted file mode 100644 index d48ac4f77f..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/SigStageLinePainter.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.TsCanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of significant stage line data on a TsPaintableCanvas - */ -public class SigStageLinePainter implements TsCanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private Measurement _sigStageMeasurement = null; - - private boolean _shouldPaint = false; -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - - - // --------------------------------------------------------- - public SigStageLinePainter(Color lineColor, - Measurement sigStageMeasurement, - TsPaintableCanvas canvas) - { - - _lineColor = lineColor; - _canvas = canvas; - - _sigStageMeasurement = Measurement.getConvertedCopy(sigStageMeasurement, - _canvas.getDisplayedMeasuringUnit()); - - - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - MeasuringUnit unit = _canvas.getDisplayedMeasuringUnit(); - // convert again just in case the _canvas has had its units changed, - // even though this feature is not available at this time - if (_sigStageMeasurement.getUnit() != unit) - { - _sigStageMeasurement = - Measurement.getConvertedCopy(_sigStageMeasurement, unit); - - } - double value = _sigStageMeasurement.getValue(); - long minTime = (long) _canvas.getViewport().getMinDataPoint().getX(); - long maxTime = (long) _canvas.getViewport().getMaxDataPoint().getX(); - - DataPoint dp1 = new DataPoint(minTime, value); - DataPoint dp2 = new DataPoint(maxTime, value); - - if (getViewport().isViewable(dp1)) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - - } - - //--------------------------------------------------------------- - - - //--------------------------------------------------------------- - - - public Measurement getMaxMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _sigStageMeasurement; - } - - return measurement; - } - - - public Measurement getMinMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _sigStageMeasurement; - } - - return measurement; - } - -//---------------------------------------------------- - - -} //end of SigStageLinePainter diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/StagePainter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/StagePainter.java deleted file mode 100644 index da1b56acad..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/StagePainter.java +++ /dev/null @@ -1,467 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.TsCanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of precipitation data on a TsPaintableCanvas - */ -public class StagePainter implements TsCanvasPainter -{ - - private static double MISSING_VALUE = -9999.0; - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _pointColor = null; - - private IrregularTimeSeriesHolder _timeSeriesHolder = null; - private RegularTimeSeriesHolder _regularTimeSeriesHolder = null; - - private TsPaintableCanvas _canvas = null; - - private boolean _isRegular = false; // distinguishes between the kind of time series - - private boolean _drawLinesBetweenPoints = false; - private boolean _shouldPaint = true; - - private String _pointString = null; - private Point _shiftAmount = new Point(0,0); - - - // --------------------------------------------------------- - public StagePainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder, - TsPaintableCanvas canvas, - boolean drawLinesBetweenPoints) - { - - _isRegular = true; - - _regularTimeSeriesHolder = regularTimeSeriesHolder; - _canvas = canvas; - - _pointColor = pointColor; - - _drawLinesBetweenPoints = drawLinesBetweenPoints; - - } - // --------------------------------------------------------- - public StagePainter(Color pointColor, - IrregularTimeSeriesHolder timeSeriesHolder, - TsPaintableCanvas canvas, - boolean drawLinesBetweenPoints - ) - { - - _isRegular = false; - - _timeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _pointColor = pointColor; - - _drawLinesBetweenPoints = drawLinesBetweenPoints; - } - -// --------------------------------------------------------- - public StagePainter(Color pointColor, - IrregularTimeSeriesHolder timeSeriesHolder, - TsPaintableCanvas canvas) - { - - _isRegular = false; - - _timeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _pointColor = pointColor; - } - - // --------------------------------------------------------- - public StagePainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder, - TsPaintableCanvas canvas) - { - this (pointColor, regularTimeSeriesHolder, canvas, false); - - } -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - //String header = "StagePainter.paint(): "; - - if (_shouldPaint) - { - - Graphics2D g2d = (Graphics2D) g; - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - drawDataPoints(g); - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_OFF); - - } - } - -// ---------------------------------------------------------- - private void drawDataPoints( Graphics g ) - { - if (_isRegular) - { - drawRegularDataPoints(g); - } - else - { - drawIrregularDataPoints(g); - } - } -// ---------------------------------------------------------- - private void drawRegularDataPoints( Graphics g ) - { - String header = "StagePainter.drawRegularDataPoints():"; - - - if (getRegularTimeSeries() == null ) - { - //System.out.println(header + " time series is null"); - return; - } - - long startTime = getRegularTimeSeries().getStartTime(); - long endTime = getRegularTimeSeries().getEndTime(); - - - g.setColor(_pointColor); - - - long hoursPerInterval = 1; - long millisPerInterval = MILLIS_PER_HOUR * hoursPerInterval; - - DataPoint previousDataPoint = null; - - //draw each data point - for ( long time = startTime; time <= endTime; time += millisPerInterval) - { - - Measurement measurement = getRegularTimeSeries().getMeasurementByTime(time); - - measurement = measurement.getCopy(getDisplayedMeasuringUnit()); - - - double value = measurement.getValue(); - - if (value != MISSING_VALUE) - { - DataPoint dp1 = new DataPoint(time, value); - - drawDataPoint(dp1, g); - - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - } - - } // for loop - - } // end of drawRegularDataPoints() method - - -// ---------------------------------------------------------- - - private void drawIrregularDataPoints( Graphics g ) - { - String header = "StagePainter.drawIrregularDataPoints():"; - //System.out.println(header + " at beginning"); - - if (getTimeSeries() == null) - { - //System.out.println(header + " time series is null"); - } - - g.setColor(_pointColor); - - //System.out.println(header + "time series = " + getTimeSeries()); - - DataPoint previousDataPoint = null; - - - //draw each data point - for ( int i = 0; (getTimeSeries() != null) && - i < getTimeSeries().getMeasurementCount(); i++) - { - - AbsTimeMeasurement measurement = (AbsTimeMeasurement) - getTimeSeries().getAbsTimeMeasurementByIndex(i); - - - - AbsTimeMeasurement convertedMeasurement = - AbsTimeMeasurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double convertedValue = convertedMeasurement.getValue(); - long time = measurement.getTime(); - - DataPoint dp1 = new DataPoint(time, convertedValue); - - drawDataPoint(dp1, g); - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - - - } // for loop - - } // end of drawIrregularDataPoints() method - -// --------------------------------------------------------- - private void drawSegment(DataPoint dp1, DataPoint dp2, Graphics g) - { - - Viewport viewport = getViewport(); - -// if it is viewable, then draw it - if ( (getViewport().isViewable(dp1)) && (getViewport().isViewable(dp2)) ) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - else - { - //System.out.println("StagePainter.drawSegment(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } - -// --------------------------------------------------------- - - private void drawDataPoint(DataPoint dp, Graphics g) - { - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - - if (_pointString == null) - { - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - } - else if (_pointString.equalsIgnoreCase("x")) - { - int x1 = p1.x - radius; - int y1 = p1.y + radius; - int x2 = p1.x + radius; - int y2 = p1.y - radius; - - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1, y2, x2, y1); - } - else - { - String string = getPointString(); - - int x = p1.x + _shiftAmount.x; - int y = p1.y + _shiftAmount.y; - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - g.drawString(getPointString(), x, y ); - } - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } -// -------------------------------------------------------- - private IrregularTimeSeries getTimeSeries() - { - IrregularTimeSeries ts = null; - - if (_timeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _timeSeriesHolder.getTimeSeries(); - } - return ts; - } - -// --------------------------------------------------------- - - private RegularTimeSeries getRegularTimeSeries() - { - RegularTimeSeries ts = null; - - - if (_regularTimeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _regularTimeSeriesHolder.getTimeSeries(); - } - - return ts; - } -// --------------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - - public Measurement getMinMeasurement() - { - String header = "StagePainter.getMinMeasurement()"; - - Measurement minMeasurement = null; - - //extremes don't count unless displayed - if (_shouldPaint) - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - minMeasurement = getRegularTimeSeries().getMinMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - } - // System.out.println(header + "minMeasurement = " + minMeasurement); - - - return minMeasurement; - } - -// ---------------------------------------------------- - -// ---------------------------------------------------- - public Measurement getMaxMeasurement() - { - String header = "StagePainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - - if (_shouldPaint) //extremes don't count unless displayed - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - maxMeasurement = getRegularTimeSeries().getMaxMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - } - else - { - //System.out.println(header + "No time series found!!!!"); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - } - - return maxMeasurement; - } - public void setPointString(String pointString) - { - _pointString = pointString; - } - public String getPointString() - { - return _pointString; - } - public void setShiftAmount(Point shiftAmount) - { - _shiftAmount = shiftAmount; - } - public Point getShiftAmount() - { - return _shiftAmount; - } - - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TableAdapter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TableAdapter.java deleted file mode 100644 index 671889a054..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TableAdapter.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; - -import ohd.hseb.sshp.window.SshpTableModel; -import ohd.hseb.util.gui.TableColumnComparator; -import ohd.hseb.util.gui.TableHelper2; - -/** - * @author Chip Gobs - * - * The purpose of this class is to wrap-up the usual way we use JTable, with all of its - * associated classes. - */ -abstract public class TableAdapter -{ - private JTable _table = null; - private List _dataList = null; - - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel = null; - private JScrollPane _scrollPane = null; - private TableHelper2 _tableHelper = null; - - private String[] _columnNameArray = null; - private String[][] _dataStringArray = null; - - abstract public String[][] getDataStringArrayFromDataList(List dataList); - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - - public TableAdapter(TableColumnComparator comparator, - String[] columnNameArray, - List dataList) - { - setColumnNameArray(columnNameArray); - - String[][] dataStringArray = getDataStringArrayFromDataList(dataList); - //setDataStringArray(dataStringArray); - - _dataList = dataList; - - _tableHelper = new TableHelper2(comparator, _columnNameArray); - - _tableModel = new SshpTableModel( _columnNameArray, dataStringArray ); - _table = new JTable(_tableModel); - _table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _table.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - - - int index = 0; - - Rectangle rect = _table.getCellRect(index, 0, true); - _scrollPane = new JScrollPane(_table); - - // a suggestion I read somewhere, said to try the following instead of - // _scrollPane = new JScrollPane(_table); - - // _scrollPane = new JScrollPane(); - // _scrollPane.setViewportView(_table); - // _scrollPane.revalidate(); - - - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - - _listSelectionModel = _table.getSelectionModel(); - _listSelectionModel.setSelectionInterval( 0, 0 ); - - - addListeners(); - } - // -------------------------------------------------------------------------------- - - - protected int[] getSelectedRowIndexArray() - { - //returns =1 if nothing selected - List selectedRowIndexList = new ArrayList(); - - for (int i = 0; i < selectedRowIndexList.size(); i++) - { - if (_listSelectionModel.isSelectedIndex(i)) - { - selectedRowIndexList.add(new Integer(i)); - } - - } - - int[] indexArray = new int[selectedRowIndexList.size()]; - - for (int i = 0; i < indexArray.length; i++ ) - { - Integer integer = (Integer)selectedRowIndexList.get(i); - indexArray[i] = integer.intValue(); - } - - return indexArray; - } - - public void setAllowMultipleSelection(boolean allowMultipleSelection) - { - if (allowMultipleSelection) - { - _table.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); - } - else - { - _table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - } - - return; - } - // -------------------------------------------------------------------------------- - - public void setColumnNameArray(String[] columnNameArray) - { - _columnNameArray = new String[columnNameArray.length]; - for (int i = 0; i < _columnNameArray.length; i++) - { - _columnNameArray[i] = columnNameArray[i]; - } - } - // -------------------------------------------------------------------------------- - public String[] getColumnNameArray() - { - return _columnNameArray; - } - -// -------------------------------------------------------------------------------- - private void addListeners() - { - //_listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _table.getTableHeader().addMouseListener( new TableSortingListener() ); - - return; - } -/** - * @param table The table to set. - */ - public void setTable(JTable table) - { - _table = table; - } - /** - * @return Returns the table. - */ - public JTable getTable() - { - return _table; - } - /** - * @param scrollPane The scrollPane to set. - */ - private void setScrollPane(JScrollPane scrollPane) - { - _scrollPane = scrollPane; - } - /** - * @return Returns the scrollPane. - */ - public JScrollPane getScrollPane() - { - return _scrollPane; - } - // -------------------------------------------------------------------------------- - public void refreshTableModel(List dataList) - { - // int index = 0; - - -// int[] indexArray = getSelectedRowIndexArray(); - - System.out.println("TableAdapter.refreshTableModel(): - should be calling same method in subclass "); - //_tableModel.updateData( _dataStringArray ); - //_tableModel.fireTableChanged( null ); - - - // reselect all the items that -// _listSelectionModel.setSelectionInterval() - - //make sure that the item is visible -// Rectangle rect = _table.getCellRect(index, 0, true); -// _scrollPane.getViewport().setViewPosition(rect.getLocation()); - - //load up the data entry fields -// loadTextFields(); - - //redraw the canvas - //_canvasMgr.refreshCanvas(_uhgList); - - return; - } - - // -------------------------------------------------------------------------------- - - /** - * @param dataList The dataList to set. - */ - public void setDataList(List dataList) - { - _dataList = dataList; - } - - /** - * @return Returns the dataList. - */ - public List getDataList() - { - return _dataList; - } - - /** - * @param listSelectionModel The listSelectionModel to set. - */ - protected void setListSelectionModel(ListSelectionModel listSelectionModel) - { - _listSelectionModel = listSelectionModel; - } - /** - * @return Returns the listSelectionModel. - */ - public ListSelectionModel getListSelectionModel() - { - return _listSelectionModel; - } - - /** - * @param tableModel The tableModel to set. - */ - public void setTableModel(SshpTableModel tableModel) - { - _tableModel = tableModel; - } - /** - * @return Returns the tableModel. - */ - public SshpTableModel getTableModel() - { - return _tableModel; - } - - //------------------------------------------------------------------------------ - public int getFirstSelectedIndex() - { - int index = -1; - - index = _table.getSelectedRow(); - - return index; - - } - //------------------------------------------------------------------------------ - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _table.getTableHeader().columnAtPoint( point ); - - _tableHelper.sortList( _dataList, column, true ); - refreshTableModel(_dataList); - } - } -// ------------------------------------------------------------------------------ -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TimeLinePainter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TimeLinePainter.java deleted file mode 100644 index 8d849d4c21..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TimeLinePainter.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.gui.drawing.CanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of the vertical time line indicator on a TsPaintableCanvas - */ -public class TimeLinePainter implements CanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private TimeHolder _timeHolder = null; - - // --------------------------------------------------------- - public TimeLinePainter(Color lineColor, - TimeHolder timeHolder, - TsPaintableCanvas canvas) - { - - _lineColor = lineColor; - _canvas = canvas; - - _timeHolder = timeHolder; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - - double dataX = _timeHolder.getTime(); - double maxDataY = getViewport().getMaxDataPoint().getY(); - double minDataY = getViewport().getMinDataPoint().getY(); - - DataPoint dp1 = new DataPoint(dataX, maxDataY); - DataPoint dp2 = new DataPoint(dataX, minDataY); - - if (getViewport().isViewable(dp1)) - { - - Point p1 = _canvas.getViewport().getScreenPoint(dp1); - Point p2 = _canvas.getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - - } // end of drawDataLine() - -//---------------------------------------------------- - - -} //end of TimeLinePainter diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TsBackgroundPainter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TsBackgroundPainter.java deleted file mode 100644 index f65809ea8d..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/gui/TsBackgroundPainter.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -//import ohd.hseb.db.DbTimeHelper; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Point; -import java.awt.Rectangle; -import java.text.NumberFormat; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.CanvasHelper; -import ohd.hseb.util.gui.drawing.CanvasPainter; -import ohd.hseb.util.gui.drawing.ScalingHelper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.drawing.Viewport; - -/** - * @author Chip Gobs - * - * This class implements CanvasPainter and encapsulates the - * drawing of the X and Y axes and all the tick marks - */ -public class TsBackgroundPainter implements CanvasPainter -{ - - - private TsPaintableCanvas _canvas = null; - - private ValueMapper _rightLabelValueMapper = null; - - -// graphing hours - private int _hoursPerMajorXTick = 6; - private int _hoursPerMinorXTick = 1; - - //time constant - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - //number formatter - private NumberFormat _numberFormat = NumberFormat.getInstance(); - - // various colors - private static final Color _backgroundColor = Color.black; - - - // NOTE: future changes: - // will want to have multiple time series, so there needs - // to be a way to have different colors for timeseries - - //private Color _lineColor = null; - private static final Color _gridColor = Color.GRAY; - private Color _outlineColor = Color.WHITE; - private static final Color _labelColor = Color.WHITE; - private static final Color _currentTimeColor = Color.YELLOW; - - //unit labels - private String _leftUnitLabelString = null; - private String _rightUnitLabelString = null; - - -// fonts - private Font _titleFont = null; - private Font _labelFont = null; - - //FontHelper - custom class - private FontHelper _titleFontHelper = null; - private FontHelper _labelFontHelper = null; - - // margins and shifts - private final static int _titleYShift = - 20; - private int _leftLabelShift = 30; - private int _rightLabelShift = 10; - - private double _smallRoundingError = 0.000000001; - - - private boolean _showMinorTicks = true; - - // --------------------------------------------------------- - public TsBackgroundPainter(Color outlineColor, - TsPaintableCanvas canvas, - String leftUnitLabelString, - String rightUnitLabelString) - { - _outlineColor = outlineColor; - _canvas = canvas; - - _leftUnitLabelString = leftUnitLabelString; - _rightUnitLabelString = rightUnitLabelString; - - _numberFormat.setMaximumFractionDigits(2); - - _titleFont = new Font("TimesRoman",Font.BOLD,14); - _labelFont = new Font("Helvetica",Font.PLAIN,9); - - _titleFontHelper = new FontHelper(_titleFont); - _labelFontHelper = new FontHelper(_labelFont); - - _showMinorTicks = true; - - } //tsBackgroundPainter() - -// --------------------------------------------------------- - public void setShowMinorTicks(boolean showMinorTicks) - { - _showMinorTicks = showMinorTicks; - } -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawBackground(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// ---------------------------------------------------- - - public void setRightLabelValueMapper(ValueMapper rightLabelValueMapper) - { - _rightLabelValueMapper = rightLabelValueMapper; - } -// ---------------------------------------------------- - - private ValueMapper getRightLabelValueMapper() - { - return _rightLabelValueMapper; - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - public void drawBackground(Graphics g) - { - - Rectangle r = _canvas.getBounds(); - - //set the normal font to use - g.setFont( _labelFont ); - - //clear the image - g.setColor(_backgroundColor); - g.fillRect(0, 0, r.width, r.height); - - //draw the axis labels, ticks, and dotted lines - drawHorizontalLines( g ); - drawVerticalLines( g ); - - //draw the Title - drawTitle(g); - - int x = 0; - int y = 0; - - x = 10; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_leftUnitLabelString, g, x, y); - - x = _canvas.getViewport().getMaxScreenPoint().x + 20; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_rightUnitLabelString, g, x, y); - - - } - -//---------------------------------------------------- - private void drawTitle(Graphics g) - { - String titleString = _canvas.getTitle(); - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, titleString) / 2; - - int x = middleX - totalLeftShift; - int y = (_canvas.getTopMargin() + _titleYShift); - - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(titleString, x, y); - - return; - } //drawTitle - - private void drawUnitLabel(String unitLabel, Graphics g, int x, int y) - { - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(unitLabel, x, y); - - return; - } //drawTitle - -// -------------------------------------------------------------------------- - - private void drawVerticalLines(Graphics g) - { - // determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - Point point1 = null; - Point point2 = null; - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - // draw each tick line - double tickValue = minXValue; - - int minorTickHours = _hoursPerMinorXTick; - int majorTickHours = _hoursPerMajorXTick; - - for (; tickValue <= maxXValue; tickValue += minorTickHours * MILLIS_PER_HOUR) - { - point1 = getViewport().getScreenPoint(new DataPoint(tickValue, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(tickValue, maxYValue)); - - - //if on a majorTick - if (isOnATick((long)tickValue, majorTickHours)) - { - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on graph boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else //not on a graph boundary - { - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - } - - //draw the major tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+6, point2.x, point1.y); - - //draw a major tick - //build the labels - String hourLabelString = CanvasHelper.getHourString((long)tickValue) + "Z"; - String dateLabelString = CanvasHelper.getDateString((long)tickValue); - - // draw the labels - g.setColor(_labelColor); - g.drawString(hourLabelString, point1.x-5, point1.y + 15); - - //only draw the date string at 00Z - if (hourLabelString.equals("00Z")) - { - g.drawString(dateLabelString, point1.x-5, point1.y + 30); - } - } - else //on a minor tick - { - - //draw a minor tick - //draw the minor tick extension - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+2, point2.x, point1.y); - - } - } //end for i - - - // if applicable, draw current time line - long currentTime = System.currentTimeMillis(); - if ( (currentTime >= minXValue) && (currentTime <=maxXValue)) - { - point1 = getViewport().getScreenPoint(new DataPoint(currentTime, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(currentTime, maxYValue)); - - g.setColor(_currentTimeColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - } //end drawXAxis - -// -------------------------------------------------------------------------- - private boolean isOnATick(long timeValue, int hoursPerTick) - { - boolean result = false; - - long roundedTime = TimeHelper.truncateTimeInMillisToNearestHour((long)timeValue, hoursPerTick); - - // String timeValueString = DbTimeHelper.getDateTimeStringFromLongTime(timeValue); - // String roundedTimeString = DbTimeHelper.getDateTimeStringFromLongTime(roundedTime); - - if ( ( timeValue == roundedTime ) || - ( timeValue == roundedTime + (hoursPerTick*MILLIS_PER_HOUR)) - ) - { - result = true; - } - return result; - } //end isOnATick - - -// ------------------------------------------------------------------------------------------- - - private void drawHorizontalLines(Graphics g) - { - //determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - //String header = "TsBackgroundPainter.drawHorizontalLines(): "; - - //System.out.println(header + "minDataPoint = " + minDataPoint); - //System.out.println(header + "maxDataPoint = " + maxDataPoint); - - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - ScalingHelper scalingHelper = new ScalingHelper(minYValue, maxYValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - // int totalTickCount = majorTickCountMax * minorTickCount; - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minYValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_labelFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxYValue + _smallRoundingError); - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minYValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(minXValue, majorTickValue)); - point2 = getViewport().getScreenPoint(new DataPoint(maxXValue, majorTickValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not working due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - //CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - - } - - - //draw the left side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x-5, point1.y, point1.x, point2.y); - - // draw the label - String numberLabelString = _numberFormat.format(majorTickValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point1.x - _leftLabelShift , point1.y + 3); - - - - - //draw the right side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point2.x+5, point2.y, point2.x, point2.y); - - // draw the label - ValueMapper valueMapper = getRightLabelValueMapper(); - - double newValue = majorTickValue; - if (valueMapper != null) - { - Measurement m = new Measurement(majorTickValue, valueMapper.getInputMeasuringUnit()); - newValue = valueMapper.getResultMeasurement(m).getValue(); - } - - numberLabelString = _numberFormat.format(newValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point2.x + _rightLabelShift , point2.y + 3); - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minXValue, minorTickValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(maxXValue, minorTickValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, minorPoint1.x, minorPoint1.y, minorPoint2.x, minorPoint2.y); - - } - } - - } //end if _showMinorTicks - - } - - } //end drawYAxis - -// ------------------------------------------------------------------------------ - - - - -} //end of SigStageLinePainter diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/DecoderDataMgr.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/DecoderDataMgr.java deleted file mode 100644 index 29f17e0943..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/DecoderDataMgr.java +++ /dev/null @@ -1,624 +0,0 @@ -/* - * Created on Jul 30, 2003 - * - * - */ -package ohd.hseb.sshp.messaging; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstOtherRecord; -import ohd.hseb.ihfsdb.generated.FcstOtherTable; -import ohd.hseb.ihfsdb.generated.MonthlyValuesRecord; -import ohd.hseb.ihfsdb.generated.MonthlyValuesTable; -import ohd.hseb.ihfsdb.generated.SacSmaParamsRecord; -import ohd.hseb.ihfsdb.generated.SacSmaParamsTable; -import ohd.hseb.ihfsdb.generated.SacSmaStateRecord; -import ohd.hseb.ihfsdb.generated.SacSmaStateTable; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.sshp.FcstTsDescriptor; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; - -// These are explicity imported in order to show what -// database tables are being used. - - -public class DecoderDataMgr -{ - - public final double MISSING = -999.0; - private static final int RECORD_COUNT_FOR_RECONNECT = 500; - private FileLogger _logger = null; - private Database _db = null; - private String _connectionString = null; - private int _timeSeriesRecordInsertionCounter = 0; - - private Map _oldFcstDischargeMap = new HashMap(); - -// ------------------------------------------------------------------------ - - public DecoderDataMgr( FileLogger logger ) - { - this( null, logger ); - } - -// ------------------------------------------------------------------------ - - public DecoderDataMgr( String baseConnectionString, FileLogger logger ) - { - _db = new Database(); - - _logger = logger; - - _connectionString = baseConnectionString; - - _db.connect( _connectionString ); - } - - // ------------------------------------------------------------------------ - - public void disconnect() - { - _db.disconnect(); - } - -// ------------------------------------------------------------------------ - - public void finalize() - { - disconnect(); - } - -// ------------------------------------------------------- - - private void logSQLException( SQLException exception ) - { -/* - System.out.println("ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); -*/ - _logger.log( "ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - } - -// ------------------------------------------------------- - - public SacSmaParameters loadNewestSacSmaParams( String basinId, String source ) - { - List sacSmaParamsRecordList = null; - List sacSmaParamsList = null; - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - - String where = " WHERE basin_id='" + basinId + "' AND source='" + source + "' ORDER BY validTime desc "; - - try - { - sacSmaParamsRecordList = table.selectNRecords( where, 1 ); - } - catch( SQLException e ) - { - logSQLException(e); - } - sacSmaParamsList = getSacSmaParamsListFromSacSmaParamsRecordList( sacSmaParamsRecordList ); - - if ( sacSmaParamsList.size() == 0 ) - { - return null; - } - else - { - return (SacSmaParameters) sacSmaParamsList.get( 0 ); - } - } - -// ------------------------------------------------------- - - private List getSacSmaParamsListFromSacSmaParamsRecordList( List sacSmaParamsRecordList ) - { - List sacSmaParamsList = new ArrayList(); - - for( int i = 0; i < sacSmaParamsRecordList.size(); i++ ) - { - SacSmaParameters addSacSmaParams = new SacSmaParameters(); - SacSmaParamsRecord sacSmaParamsRecord = (SacSmaParamsRecord) sacSmaParamsRecordList.get( i ); - - addSacSmaParams.setBasinId(sacSmaParamsRecord.getBasin_id()); - addSacSmaParams.setSource(sacSmaParamsRecord.getSource()); - addSacSmaParams.setValidTime(sacSmaParamsRecord.getValidtime()); - addSacSmaParams.setPostingTime(sacSmaParamsRecord.getPostingtime()); - addSacSmaParams.setUztwm(sacSmaParamsRecord.getUztwm()); - addSacSmaParams.setUzfwm(sacSmaParamsRecord.getUzfwm()); - addSacSmaParams.setUzk(sacSmaParamsRecord.getUzk()); - addSacSmaParams.setPctim(sacSmaParamsRecord.getPctim()); - addSacSmaParams.setAdimp(sacSmaParamsRecord.getAdimp()); - addSacSmaParams.setRiva(sacSmaParamsRecord.getRiva()); - addSacSmaParams.setZperc(sacSmaParamsRecord.getZperc()); - addSacSmaParams.setRexp(sacSmaParamsRecord.getRexp()); - addSacSmaParams.setLztwm(sacSmaParamsRecord.getLztwm()); - addSacSmaParams.setLzfsm(sacSmaParamsRecord.getLzfsm()); - addSacSmaParams.setLzfpm(sacSmaParamsRecord.getLzfpm()); - addSacSmaParams.setLzsk(sacSmaParamsRecord.getLzsk()); - addSacSmaParams.setLzpk(sacSmaParamsRecord.getLzpk()); - addSacSmaParams.setPfree(sacSmaParamsRecord.getPfree()); - addSacSmaParams.setRserv(sacSmaParamsRecord.getRserv()); - addSacSmaParams.setSide(sacSmaParamsRecord.getSide()); - - addSacSmaParams.setPeadj(sacSmaParamsRecord.getPeadj()); - addSacSmaParams.setPxadj(sacSmaParamsRecord.getPxadj()); - addSacSmaParams.setEfc(sacSmaParamsRecord.getEfc()); - - sacSmaParamsList.add( addSacSmaParams ); - } - return sacSmaParamsList; - } - -// ------------------------------------------------------- - - - private SacSmaParamsRecord getSacSmaParamsRecord( SacSmaParameters sacSmaParams ) - { - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - record.setBasin_id( sacSmaParams.getBasinId() ); - record.setSource(sacSmaParams.getSource()); - record.setValidtime(sacSmaParams.getValidTime() ); - record.setPostingtime(sacSmaParams.getPostingTime()); - - record.setUztwm(sacSmaParams.getUztwm()); - record.setUzfwm(sacSmaParams.getUzfwm()); - record.setUzk(sacSmaParams.getUzk()); - record.setPctim(sacSmaParams.getPctim()); - record.setAdimp(sacSmaParams.getAdimp()); - record.setRiva(sacSmaParams.getRiva()); - record.setZperc(sacSmaParams.getZperc()); - record.setRexp(sacSmaParams.getRexp()); - record.setLztwm(sacSmaParams.getLztwm()); - record.setLzfsm(sacSmaParams.getLzfsm()); - record.setLzfpm(sacSmaParams.getLzfpm()); - record.setLzsk(sacSmaParams.getLzsk()); - record.setLzpk(sacSmaParams.getLzpk()); - record.setPfree(sacSmaParams.getPfree()); - record.setRserv(sacSmaParams.getRserv()); - record.setSide(sacSmaParams.getSide()); - record.setPeadj(sacSmaParams.getPeadj()); - record.setPxadj(sacSmaParams.getPxadj()); - record.setEfc(sacSmaParams.getEfc()); - - return record; - } - - -// ------------------------------------------------------- - - - public void saveParams( SacSmaParameters sacSmaParams ) - { - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - SacSmaParamsRecord record = getSacSmaParamsRecord( sacSmaParams ); - - try - { - table.insertOrUpdate( record ); - _logger.log( " Successfully inserted or updated Params for " + record.getBasin_id() ); - } - catch ( SQLException e ) - { - logSQLException(e); - _logger.log("failed to insert or update for " + record); - } - } -// ------------------------------------------------------- - - public void saveState( SacSmaState sacSmaState ) - { - SacSmaStateTable table = new SacSmaStateTable( _db ); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id( sacSmaState.getBasinId() ); - record.setSource( sacSmaState.getSource() ); - record.setValidtime( sacSmaState.getValidTime() ); - record.setBasistime( sacSmaState.getBasisTime() ); - record.setPostingtime( sacSmaState.getPostingTime() ); - - record.setUztwc( sacSmaState.getUztwc() ); - record.setUzfwc( sacSmaState.getUzfwc() ); - record.setLztwc( sacSmaState.getLztwc() ); - record.setLzfsc( sacSmaState.getLzfsc() ); - record.setLzfpc( sacSmaState.getLzfpc() ); - record.setAdimc( sacSmaState.getAdimc() ); - - try - { - table.insertOrUpdate( record ); - _logger.log( " Successfully inserted or updated State for " + record.getBasin_id() ); - } - catch ( SQLException e ) - { - logSQLException(e); - _logger.log("failed to insert or update for " + record); - } - } - -// ------------------------------------------------------- - - public void saveMonthlyValues( MonthlyValues monthlyValues ) - { - MonthlyValuesTable table = new MonthlyValuesTable( _db ); - MonthlyValuesRecord record = new MonthlyValuesRecord(); - long currentTime = System.currentTimeMillis(); - double[] valueArray = monthlyValues.getValueArray(); - - record.setLid( monthlyValues.getBasinId() ); - record.setPe( monthlyValues.getPe() ); - record.setDur( monthlyValues.getDur() ); - record.setTs( monthlyValues.getTs() ); - record.setExtremum( monthlyValues.getExtremum() ); - if ( monthlyValues.isAdjustment() ) - { - record.setAdjustment( "Y" ); - } - else - { - record.setAdjustment( "N" ); - } - record.setPostingtime( currentTime ); - record.setJan_value( valueArray[ 0 ] ); - record.setFeb_value( valueArray[ 1 ] ); - record.setMar_value( valueArray[ 2 ] ); - record.setApr_value( valueArray[ 3 ] ); - record.setMay_value( valueArray[ 4 ] ); - record.setJun_value( valueArray[ 5 ] ); - record.setJul_value( valueArray[ 6 ] ); - record.setAug_value( valueArray[ 7 ] ); - record.setSep_value( valueArray[ 8 ] ); - record.setOct_value( valueArray[ 9 ] ); - record.setNov_value( valueArray[ 10 ] ); - record.setDec_value( valueArray[ 11 ] ); - try - { - table.insertOrUpdate( record ); - _logger.log( " Successfully inserted or updated Monthly Values for " + record.getLid() ); - } - catch ( SQLException e ) - { - logSQLException(e); - _logger.log("failed to insert or update for " + record); - } - } -// ------------------------------------------------------- - public void saveFcstTimeSeries( FcstTsDescriptor descriptor, RegularTimeSeries timeSeries ) - { - _timeSeriesRecordInsertionCounter = 0; - - if ( descriptor.getTableName().equalsIgnoreCase( "FcstDischarge" ) ) - { - saveFcstRunoffTs( descriptor, timeSeries ); - } - else if ( descriptor.getTableName().equalsIgnoreCase( "FcstOther" ) ) - { - saveFcstOtherTs( descriptor, timeSeries ); - } - } - -// ------------------------------------------------------- - - private void saveFcstOtherTs( FcstTsDescriptor descriptor, RegularTimeSeries timeSeries ) - { - FcstOtherTable table = new FcstOtherTable(_db); - FcstOtherRecord record = new FcstOtherRecord(); - - FcstOtherRecord oldRecord = null; - - String space = " "; - long startTime = 0; - long endTime = 0; - long interval = 0; - long maxBasisTime = 0; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - CodeTimer timer1 = new CodeTimer( _logger ); - - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - - timer1.start(); - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - - - //initialize the record key fields to save from the descriptor - setRecordFromDescriptor(record, descriptor); - - //delete records from the same or previous basistime - String deleteWhereString = null; - deleteWhereString = getDeleteWhereString( descriptor ); - - try - { - table.delete( deleteWhereString ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - - - - int insertCount = 0; - - //insert records - for (long time = startTime; time <= endTime; time += interval) - { - reconnectIfNeeded(); - - Measurement newMeasurement = timeSeries.getMeasurementByTime(time); - double value = newMeasurement.getValue(dbRunoffUnit); - - record.setValue(value); - record.setValidtime(time); - - try - { - table.insert(record); - _timeSeriesRecordInsertionCounter++; //used for reconnections - insertCount++; - } - - catch ( SQLException e ) - { - logSQLException( e ); - _logger.log( space + "error with insert for FcstOther " + record); - _logger.log( space + "insertCount = " + insertCount); - } - } - - _logger.log( space + insertCount + " records inserted" + - " for " + record.getLid() + "." ); - - - } -// ------------------------------------------------------- - - -// ------------------------------------------------------- - private void setRecordFromDescriptor(FcstDischargeRecord record, FcstTsDescriptor descriptor) - { - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - return; - - } - -// ------------------------------------------------------- - private void setRecordFromDescriptor(FcstOtherRecord record, FcstTsDescriptor descriptor) - { - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - return; - - } - - - -// ------------------------------------------------------- - - private void saveFcstRunoffTs( FcstTsDescriptor descriptor, RegularTimeSeries timeSeries ) - { - FcstDischargeTable table = new FcstDischargeTable( _db ); - FcstDischargeRecord record = new FcstDischargeRecord(); - - String space = " "; - long startTime = 0; - long endTime = 0; - long interval = 0; - long maxBasisTime = 0; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - CodeTimer timer1 = new CodeTimer( _logger ); - - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - - timer1.start(); - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - - - //initialize the record key fields to save from the descriptor - setRecordFromDescriptor(record, descriptor); - - - - //delete records from the same or previous basistime - String deleteWhereString = null; - - deleteWhereString = getDeleteWhereString( descriptor ); - - try - { - table.delete( deleteWhereString ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - - - //insert all records - int insertCount = 0; - for (long time = startTime; time <= endTime; time += interval) - { - reconnectIfNeeded(); - - Measurement newMeasurement = timeSeries.getMeasurementByTime(time); - double value = newMeasurement.getValue(dbRunoffUnit); - - record.setValue(value); - record.setValidtime(time); - - try - { - table.insert(record); - _timeSeriesRecordInsertionCounter++; //used for reconnections - insertCount++; - } - - catch ( SQLException e ) - { - logSQLException( e ); - _logger.log( space + "error with insert for FcstOther " + record); - _logger.log( space + "insertCount = " + insertCount); - } - } - - - _logger.log( space + insertCount + " records inserted" + - " for " + record.getLid() + "." ); - - - - - } //end saveFcstDischarge - - -// ------------------------------------------ - - private String getDeleteWhereString( FcstTsDescriptor descriptor ) - { - String whereString = - "WHERE lid = '" + descriptor.getLid() + "'" - + " AND pe = '" + descriptor.getPe() + "'" - + " AND dur = '" + descriptor.getDur() + "'" - + " AND ts = '" + descriptor.getTs() + "'" - + " AND extremum = '" + descriptor.getExtremum() + "'" - + " AND probability = '" + descriptor.getProbability() + "'" - + " AND product_id = '" + descriptor.getProduct_id() + "'" - + " AND basistime <= '" + DbTimeHelper.getDateTimeStringFromLongTime( descriptor.getBasistime() ) + "'" ; - - return whereString; - } - - - -// ------------------------------------------------------- - - - - void addRecordToMap(FcstDischargeRecord record) - { - Long key = new Long(record.getValidtime()); - Object value = record; - - _oldFcstDischargeMap.put(key, value); - - return; - } - -//------------------------------------------------------- - - - - // ------------------------------------------------------------------------------- - - -// ------------------------------------------------------- - - -// ------------------------------------------------------- - - private void testFcstOtherRecordInsertion() - { - FcstOtherRecord record = null; - FcstOtherTable table = new FcstOtherTable( _db ); - String where = " WHERE PE='EA' "; - - try - { - List recordList = table.select( where ); - if ( recordList.size() > 0 ) - { - record = (FcstOtherRecord) recordList.get( 0 ); - System.out.println( "DecoderDataMgr.testFcst: record: " + record ); - table.insertOrUpdate( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - - } - -// ------------------------------------------------------- - - private void reconnectIfNeeded() - { - int total = _timeSeriesRecordInsertionCounter; - if ( ( total > 0 ) && ( total % RECORD_COUNT_FOR_RECONNECT == 0 ) ) - { - reconnect(); - } - } - -// ------------------------------------------------------- - - private void reconnect() - { - _db.disconnect(); - _db.connect( _connectionString ); - _logger.log( " Reconnected to the Database for performance reasons" ); - } - -// ------------------------------------------------------- - - - public static void main( String args[] ) - { - DecoderDataMgr decoderMgr = new DecoderDataMgr(new FileLogger( "DecoderDataMgrtesting.log" ) ); - decoderMgr.testFcstOtherRecordInsertion(); - } -} //end class DecoderDataMgr diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/OfsFileParserException.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/OfsFileParserException.java deleted file mode 100644 index 7d48a8ff9d..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/OfsFileParserException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Created on Apr 26, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Apr 26, 2004 - * - */ -package ohd.hseb.sshp.messaging; - -/** - * @author SoodG -*/ -public class OfsFileParserException extends Exception -{ - public OfsFileParserException( String message ) - { - super( message ); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java deleted file mode 100644 index e556764351..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java +++ /dev/null @@ -1,668 +0,0 @@ -/* - * Created on Sep 11, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : March 16, 2004 - * Purpose: Decodes XML input files and posts the data to the database. - */ - -package ohd.hseb.sshp.messaging; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.sshp.FcstTsDescriptor; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; - -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.input.SAXBuilder; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; - - -public class SacXMLDecoder -{ - private String _inputDir = null; - private String _archiveDir = null; - private String _logFullPath = null; - private long _sleepTime = 0; - private Document _doc = null; - private String backupInputFilePath = null; - private boolean _isTest = true; - - private static final String PE_TIMESERIES_PE_CODE = "EA"; - private static final String RUNOFF_TIMESERIES_PE_CODE = "QB"; - private static final String TS = "FZ"; - private static final String EXTREMUM = "Z"; - private static final float PROBABILITY = -1.0f; - private static final String SHEF_QUAL_CODE = "Z"; - private static final int GOOD_QC = 1879048191; - private static final short REVISION = 0; - private static final String PRODUCT_ID = "SSHP_XFER"; - - private static final String MONTHLY_VALUES_TS = "FZ"; - private static final String MONTHLY_VALUES_EXTREMUM = "Z"; - private static final String MONTHLY_VALUES_PE = "EA"; - private static final short MONTHLY_VALUES_DUR = 2001; - private static final MeasuringUnit DB_MEASURING_UNIT = MeasuringUnit.inches; - private static final int INTERVAL_IN_HOURS = 1; - - private static Map _unitsMap = new HashMap(); - - private FileLogger _logger = null; - - private String _connectionString = null; - - private DecoderDataMgr _dataMgr = null; - - public SacXMLDecoder( String connectionString ) - { - _connectionString = connectionString; - } - - private void execute() - { - boolean executeProgram = true; - File localDirFile = null; - File[] localFileArray = null; - File backupInputFile = null; - localDirFile = new File( _inputDir ); - localFileArray = localDirFile.listFiles(); - SAXBuilder builder = new SAXBuilder(); - String fileName = null; - File inputFile = null; - Date time = new Date(); - int badFileCounter = 0; - boolean keepFileOpen = true; - boolean appendDateTime = true; - CodeTimer timer1 = null; - - _logger = new FileLogger( _logFullPath, keepFileOpen, appendDateTime ); - timer1 = new CodeTimer( _logger ); - - connect(); - - initUnitsMap(); - - while ( executeProgram ) - { - localFileArray = getFileList( localDirFile ); - if ( ( localFileArray.length - badFileCounter ) > 0 ) - { - for ( int i = 0; i < localFileArray.length; i++ ) - { - try - { - builder.setExpandEntities( true ); - fileName = localFileArray[ i ].getAbsolutePath(); - _logger.log( "Processing " + localFileArray[ i ].getName() ); - timer1.start(); - - _doc = builder.build( fileName ); - parseXMLFiles(); - backupInputFile = new File( _archiveDir + "/" + localFileArray[ i ].getName() + "_" + time.getTime() ); - - inputFile = new File( fileName ); - inputFile.renameTo( backupInputFile ); - timer1.stop( "Finished processing " + localFileArray[ i ].getName() + " in " ); - } - catch ( JDOMException e ) - { - badFileCounter++; - _logger.log( " " + fileName + " is not a valid XML file." ); - } - - catch ( IOException e ) - { - e.printStackTrace(); - } - } - } - else // if localFileArray.length <= 0 (No files found) - { - - if ( _isTest ) - { - _logger.log( "No more valid XML Files found. Moving back to sleep mode." ); - sleep(); - } - else - { - _logger.log( "No more valid XML Files found. Processing Complete." ); - executeProgram = false; - } - } - } // end While loop - } - - private File[] getFileList( File localDirFile ) - { - File[] returnFileArray = null; - File[] currentFileArray = null; - List tempFileList = new ArrayList(); - - currentFileArray = localDirFile.listFiles(); - - - for ( int i = 0; i < currentFileArray.length; i++ ) - { - if ( ! currentFileArray[ i ].isDirectory() ) - { - tempFileList.add( currentFileArray[ i ] ); - } - } - - returnFileArray = (File[]) tempFileList.toArray( new File[ tempFileList.size() ] ); - - return returnFileArray; - } - - private void initUnitsMap() - { - _unitsMap.put( new String( "mm" ), MeasuringUnit.mm ); - _unitsMap.put( new String( "cm" ), MeasuringUnit.cm ); - _unitsMap.put( new String( "m" ), MeasuringUnit.meters ); - _unitsMap.put( new String( "in" ), MeasuringUnit.inches ); - _unitsMap.put( new String( "ft" ), MeasuringUnit.feet ); - } - - private void sleep() - { - try - { -// System.out.println( "Sleeping for " + _sleepTime/1000 + " seconds..." ); - Thread.sleep( _sleepTime ); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - } - - - private void parseXMLFiles() - { - Element sacParamsListElement = _doc.getRootElement().getChild( "SacParamsList" ); - Element sacStateListElement = _doc.getRootElement().getChild( "SacStateList" ); - Element peTimeSeriesListElement = _doc.getRootElement().getChild( "PeTimeSeriesList" ); - Element runoffTimeSeriesListElement = _doc.getRootElement().getChild( "RunoffTimeSeriesList" ); - Element monthlyValuesListElement = _doc.getRootElement().getChild( "MonthlyValuesList" ); - - Element sacParamsElement = null; - Element sacStateElement = null; - Element peTimeSeriesElement = null; - Element runoffTimeSeriesElement = null; - Element monthlyValuesElement = null; - - SacSmaParameters sacSmaParams = new SacSmaParameters(); - SacSmaState sacSmaState = new SacSmaState(); - MonthlyValues monthlyValues = new MonthlyValues(); - - List elementList = null; - -// --------- Processing Sac Parameters - - elementList = sacParamsListElement.getChildren( "SacParams" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - SacSmaParameters latestParams = null; - String basinId = null; - String source = null; - - sacParamsElement = (Element) elementList.get( i ); - sacSmaParams = retrieveSacSmaParams( sacParamsElement ); - basinId = sacSmaParams.getBasinId(); - source = sacSmaParams.getSource(); - - latestParams = _dataMgr.loadNewestSacSmaParams(basinId, source ); - if ( latestParams == null ) - { - _dataMgr.saveParams( sacSmaParams ); - } - else if ( ! latestParams.equalsValues( sacSmaParams ) ) - { - _dataMgr.saveParams( sacSmaParams ); - } - } - -// --------- Processing Sac States - - elementList = sacStateListElement.getChildren( "SacState" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - sacStateElement = (Element) elementList.get( i ); - sacSmaState = retrieveSacSmaState( sacStateElement ); - _dataMgr.saveState( sacSmaState ); - } - -// --------- Processing Pe Timeseries - - elementList = peTimeSeriesListElement.getChildren( "PeTimeSeries" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - peTimeSeriesElement = (Element) elementList.get( i ); - processPeTimeSeries( peTimeSeriesElement ); - } -// --------- Processing Runoff Timeseries - - elementList = runoffTimeSeriesListElement.getChildren( "RunoffTimeSeries" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - runoffTimeSeriesElement = (Element) elementList.get( i ); - processRunoffTimeSeries( runoffTimeSeriesElement ); - } - -// --------- Processing MonthlyValues - - elementList = monthlyValuesListElement.getChildren( "MonthlyValues" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - monthlyValuesElement = (Element) elementList.get( i ); - monthlyValues = retrieveMonthlyValues( monthlyValuesElement ); - _dataMgr.saveMonthlyValues( monthlyValues ); - } - } - -// ----------------------------------------------------------------------------- - - private SacSmaParameters retrieveSacSmaParams( Element e ) - { - SacSmaParameters currentSacSmaParams = new SacSmaParameters(); - - currentSacSmaParams.setBasinId( getElementStringValue( e, "basinId" ) ); - currentSacSmaParams.setSource( getElementStringValue( e, "source" ) ); - currentSacSmaParams.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaParams.setPostingTime( System.currentTimeMillis() ); - currentSacSmaParams.setUztwm( getElementDoubleValue( e, "uztwm" ) ); - currentSacSmaParams.setUzfwm( getElementDoubleValue( e, "uzfwm" ) ); - currentSacSmaParams.setUzk( getElementDoubleValue( e, "uzk" ) ); - currentSacSmaParams.setPctim( getElementDoubleValue( e, "pctim" ) ); - currentSacSmaParams.setAdimp( getElementDoubleValue( e, "adimp" ) ); - currentSacSmaParams.setRiva( getElementDoubleValue( e, "riva" ) ); - currentSacSmaParams.setZperc( getElementDoubleValue( e, "zperc" ) ); - currentSacSmaParams.setRexp( getElementDoubleValue( e, "rexp" ) ); - currentSacSmaParams.setLztwm( getElementDoubleValue( e, "lztwm" ) ); - currentSacSmaParams.setLzfsm( getElementDoubleValue( e, "lzfsm" ) ); - currentSacSmaParams.setLzfpm( getElementDoubleValue( e, "lzfpm" ) ); - currentSacSmaParams.setLzsk( getElementDoubleValue( e, "lzsk" ) ); - currentSacSmaParams.setLzpk( getElementDoubleValue( e, "lzpk" ) ); - currentSacSmaParams.setPfree( getElementDoubleValue( e, "pfree" ) ); - currentSacSmaParams.setRserv( getElementDoubleValue( e, "rserv" ) ); - currentSacSmaParams.setSide( getElementDoubleValue( e, "side" ) ); - currentSacSmaParams.setPxadj( getElementDoubleValue( e, "pxadj" ) ); - currentSacSmaParams.setPeadj( getElementDoubleValue( e, "peadj" ) ); - currentSacSmaParams.setEfc( getElementDoubleValue( e, "efc" ) ); - - - return currentSacSmaParams; - } - -// ----------------------------------------------------------------------------- - - private SacSmaState retrieveSacSmaState( Element e ) - { - SacSmaState currentSacSmaState = new SacSmaState(); - - currentSacSmaState.setBasinId( getElementStringValue( e, "basinId") ); - currentSacSmaState.setSource( getElementStringValue( e, "source") ); - currentSacSmaState.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaState.setBasisTime( getElementLongTimeValue( e, "basisTime" ) ); - currentSacSmaState.setPostingTime( System.currentTimeMillis() ); - currentSacSmaState.setUztwc( getElementDoubleValue( e, "uztwc" ) ); - currentSacSmaState.setUzfwc( getElementDoubleValue( e, "uzfwc" ) ); - currentSacSmaState.setLztwc( getElementDoubleValue( e, "lztwc" ) ); - currentSacSmaState.setLzfsc( getElementDoubleValue( e, "lzfsc" ) ); - currentSacSmaState.setLzfpc( getElementDoubleValue( e, "lzfpc" ) ); - currentSacSmaState.setAdimc( getElementDoubleValue( e, "adimc" ) ); - - return currentSacSmaState; - } - -// ----------------------------------------------------------------------------- - - private MonthlyValues retrieveMonthlyValues( Element e ) - { - MonthlyValues currentMonthlyValues = new MonthlyValues(); - double[] valueArray = new double[ 12 ]; - - currentMonthlyValues.setBasinId( getElementStringValue( e, "locationId" ) ); - currentMonthlyValues.setPe( MONTHLY_VALUES_PE ); - currentMonthlyValues.setDur(MONTHLY_VALUES_DUR ); - currentMonthlyValues.setTs( MONTHLY_VALUES_TS ); - currentMonthlyValues.setExtremum( MONTHLY_VALUES_EXTREMUM ); - if ( getElementStringValue( e, "isAdjustment" ).equalsIgnoreCase( "TRUE" ) ) - { - currentMonthlyValues.setAdjustment( true ); - } - else - { - currentMonthlyValues.setAdjustment( false ); - } - currentMonthlyValues.setPostingTime( System.currentTimeMillis() ); - - valueArray[ 0 ] = getElementDoubleValue( e, "janValue" ); - valueArray[ 1 ] = getElementDoubleValue( e, "febValue" ); - valueArray[ 2 ] = getElementDoubleValue( e, "marValue" ); - valueArray[ 3 ] = getElementDoubleValue( e, "aprValue" ); - valueArray[ 4 ] = getElementDoubleValue( e, "mayValue" ); - valueArray[ 5 ] = getElementDoubleValue( e, "junValue" ); - valueArray[ 6 ] = getElementDoubleValue( e, "julValue" ); - valueArray[ 7 ] = getElementDoubleValue( e, "augValue" ); - valueArray[ 8 ] = getElementDoubleValue( e, "sepValue" ); - valueArray[ 9 ] = getElementDoubleValue( e, "octValue" ); - valueArray[ 10 ] = getElementDoubleValue( e, "novValue" ); - valueArray[ 11 ] = getElementDoubleValue( e, "decValue" ); - currentMonthlyValues.setValues( valueArray ); - - return currentMonthlyValues; - } - -// ----------------------------------------------------------------------------- - - private void processPeTimeSeries( Element e ) - { - String usedString = getElementStringValue( e, "isUsed" ); - boolean process = false; // Determines whether or not to process the TS - RegularTimeSeries peTimeSeries = null; - FcstTsDescriptor descriptor = new FcstTsDescriptor( "FcstOther" ); - - if ( usedString.trim().equalsIgnoreCase( "true" ) ) - { - process = true; - } - else - { - process = false; - } - - if ( process ) - { - String xmlUnitString = getElementStringValue( e, "units" ); - Element measurementListElement = e.getChild( "MeasurementList" ); - Element measurementElement = null; - List elementList = new ArrayList(); - Measurement measurement = null; - MeasuringUnit xmlMeasuringUnit = (MeasuringUnit) _unitsMap.get( xmlUnitString ); - - descriptor.setLid( getElementStringValue( e, "basinId" ) ); - descriptor.setPe( PE_TIMESERIES_PE_CODE ); - descriptor.setDur( getElementShortValue( e, "duration" ) ); - descriptor.setTs( TS ); - descriptor.setExtremum( EXTREMUM ); - descriptor.setProbability( PROBABILITY ); - descriptor.setBasistime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setShef_qual_code( SHEF_QUAL_CODE ); - descriptor.setQuality_code( GOOD_QC ); - descriptor.setRevision( REVISION ); - descriptor.setProduct_id( PRODUCT_ID ); - descriptor.setProducttime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setPostingtime( System.currentTimeMillis() ); - - elementList = measurementListElement.getChildren( "Measurement" ); - - for ( int i = 0; i < elementList.size(); i++ ) - { - measurementElement = (Element) elementList.get( i ); - double xmlValue = getElementDoubleValue( measurementElement, "value" ); - measurement = new Measurement( xmlValue, xmlMeasuringUnit ); - long time = getElementLongTimeValue( measurementElement, "time" ); - - if ( i == 0 ) - { - peTimeSeries = new RegularTimeSeries( time, time, INTERVAL_IN_HOURS, - DB_MEASURING_UNIT ); - } - peTimeSeries.setMeasurementByTime( measurement, time ); - } - _dataMgr.saveFcstTimeSeries( descriptor, peTimeSeries ); - - } // end if (process) - } - -// ----------------------------------------------------------------------------- - - private void processRunoffTimeSeries( Element e ) - { - String processString = getElementStringValue( e, "exists" ); - boolean process = false; // Determines whether or not to process the TS - RegularTimeSeries runoffTimeSeries = null; - FcstTsDescriptor descriptor = new FcstTsDescriptor( "FcstDischarge" ); - - if ( processString.trim().equalsIgnoreCase( "true" ) ) - { - process = true; - } - else - { - process = false; - } - - if ( process ) - { - String xmlUnitString = getElementStringValue( e, "units" ); - Element measurementListElement = e.getChild( "MeasurementList" ); - Element measurementElement = null; - List elementList = new ArrayList(); - Measurement measurement = null; - MeasuringUnit xmlMeasuringUnit = (MeasuringUnit) _unitsMap.get( xmlUnitString ); - - descriptor.setLid( getElementStringValue( e, "basinId" ) ); - descriptor.setPe( RUNOFF_TIMESERIES_PE_CODE ); - descriptor.setDur( getElementShortValue( e, "duration" ) ); - descriptor.setTs( TS ); - descriptor.setExtremum( EXTREMUM ); - descriptor.setProbability( PROBABILITY ); - descriptor.setBasistime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setShef_qual_code( SHEF_QUAL_CODE ); - descriptor.setQuality_code( GOOD_QC ); - descriptor.setRevision( REVISION ); - descriptor.setProduct_id( PRODUCT_ID ); - descriptor.setProducttime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setPostingtime( System.currentTimeMillis() ); - - elementList = measurementListElement.getChildren( "Measurement" ); - - for ( int i = 0; i < elementList.size(); i++ ) - { - measurementElement = (Element) elementList.get( i ); - double xmlValue = getElementDoubleValue( measurementElement, "value" ); - measurement = new Measurement( xmlValue, xmlMeasuringUnit ); - long time = getElementLongTimeValue( measurementElement, "time" ); - - if ( i == 0 ) - { - runoffTimeSeries = new RegularTimeSeries( time, time, INTERVAL_IN_HOURS, - DB_MEASURING_UNIT ); - } - runoffTimeSeries.setMeasurementByTime( measurement, time ); - } - _dataMgr.saveFcstTimeSeries( descriptor, runoffTimeSeries ); - } - } - -// ----------------------------------------------------------------------------- - - private String getElementStringValue( Element e, String subElementName ) - { - return e.getChildTextTrim( subElementName ); - } - -// ----------------------------------------------------------------------------- - - private double getElementDoubleValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Double.parseDouble( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private int getElementIntValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Integer.parseInt( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - private short getElementShortValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Short.parseShort( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private long getElementLongTimeValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return DbTimeHelper.getLongTimeFromDateTimeString( attributeValueString ); - } - -// ----------------------------------------------------------------------------- - - public String toString() - { - StringWriter stringWriter = new StringWriter(); - Format format = Format.getPrettyFormat(); - format = format.setIndent(" "); - XMLOutputter outputter = new XMLOutputter(format); - String returnValue = null; - - try - { - outputter.output( _doc, stringWriter ); - returnValue = stringWriter.toString(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - - return returnValue; - } - -// ----------------------------------------------------------------------------- - - private void connect() - { - _dataMgr = new DecoderDataMgr( _connectionString, _logger ); - } - - private boolean validateInputParameters( String[] args ) - { - String inputDir = null; - String archiveDir = null; - String logDir = null; - String sleepTimeString = null; - long sleepTimeLong = 0; - File directory = null; - boolean returnValue = true; - - if ( args.length < 3 ) - { - System.out.println( "SacXMLDecoder [ ] " ); - returnValue = false; - } - else - { - _connectionString = args[ 0 ]; - - inputDir = args[ 1 ]; - - directory = new File( inputDir ); - if ( directory.exists() ) - { - _inputDir = inputDir; - } - else - { - System.err.println( "You must specify a valid input directory" ); - returnValue = false; - } - - archiveDir = args[ 2 ]; - - directory = new File( archiveDir ); - if ( directory.exists() ) - { - _archiveDir = archiveDir; - } - else - { - System.err.println( "You must specify a valid archive directory" ); - returnValue = false; - } - - logDir = args[ 3 ]; - directory = new File( logDir ); - if ( directory.exists() ) - { - _logFullPath = logDir + "/SacXMLDecoder.log"; - } - else - { - System.err.println( "You must specify a valid log directory" ); - returnValue = false; - } - - - if ( args.length > 4 ) - { - sleepTimeString = args[ 4 ]; - try - { - sleepTimeLong = Long.parseLong( sleepTimeString ); - _sleepTime = sleepTimeLong; - _isTest = true; - } - catch ( NumberFormatException e ) - { - System.err.println( "Invalid sleep time specified. Defaulting to 60 seconds" ); - _sleepTime = 60000; - } - } - else - { - _isTest = false; - } - } // end else - - return returnValue; - } - - - - public static void main( String[] args ) - { - SacXMLDecoder sacDecoder = new SacXMLDecoder( args[ 0 ] ); - boolean validInputParameters = false; - - validInputParameters = sacDecoder.validateInputParameters( args ); - - if ( validInputParameters ) - { - sacDecoder.execute(); - } - - sacDecoder._dataMgr.disconnect(); - -// System.exit( 0 ); - } -} \ No newline at end of file diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java deleted file mode 100644 index 329605160f..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java +++ /dev/null @@ -1,665 +0,0 @@ -/* - * Created on Feb 26, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : March 16, 2004 - * Revised: - * Chip Gobs March 16, 2005 (exactly 1 year later!) - * added variables _paramsValidTime and _timeSeriesBasisTime - * now use them instead of using _extractionTime directly for SacSmaParams validTime and - * PE and Runoff time series basistime. - * The _timeSeriesBasisTime variable is set to _extractionTime, but _paramsValidTime is the - * 00:00:00 of the same date as _extractionTime - */ - -package ohd.hseb.sshp.messaging; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.StringParser; - -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; - -public class SacXMLEncoder -{ - private String _basinId = null; - private String _extractFileName = null; - private Document _doc = null; - - private BufferedReader _reader = null; - - private final long HOUR_IN_MILLIS = 1 * 60 * 60 * 1000; - private final long MILLIS_PER_DAY = 24 * HOUR_IN_MILLIS; - private final String SOURCE = "RFC"; - private long _extractionTime = 0; - private long _paramsValidTime = 0; - private long _timeSeriesBasisTime = 0; - // private String _executionTimeString = null; - private FileLogger _logger = null; - - // --------------------------------------------------------------------- - - public SacXMLEncoder( String basinId, String extractFileName, Document outputXMLDocument, FileLogger logger ) - { - _basinId = basinId; - _extractFileName = extractFileName; - _doc = outputXMLDocument; - _logger = logger; - _logger.log( "" ); - //_executionTimeString = DbTimeHelper.getDateTimeStringFromLongTime( System.currentTimeMillis() ); - } - - // --------------------------------------------------------------------- - - public void parse() throws OfsFileParserException - { -// writeXmlToFile( _doc, "D:/data/xmlencoderoutput.txt" ); - - try - { - _reader = new BufferedReader( new FileReader( _extractFileName ) ); - - Element rootElement = _doc.getRootElement(); - Element runoffTimeSeriesListElement = rootElement.getChild( "RunoffTimeSeriesList" ); - Element peTimeSeriesListElement = rootElement.getChild( "PeTimeSeriesList" ); - Element sacParamsListElement = rootElement.getChild( "SacParamsList" ); - Element sacStateListElement = rootElement.getChild( "SacStateList" ); - Element monthlyValuesListElement = rootElement.getChild( "MonthlyValuesList" ); - - String line = findLine( "Extracted on" ); - - if ( line == null ) - { - throw new OfsFileParserException( "line empty" ); - } - - int index = getNextCharIndex(line,"Extracted on"); - if ( index >= 0 ) - { - _extractionTime = parseTimeString( line.substring( index, line.length() ) ); - - //set to the same as the extraction time, since we don't have anything better - _timeSeriesBasisTime = _extractionTime; - - //round back to the beginning of the same day, - //so that whatever parameters we have for that day will be usable with - //the latest states of that day - _paramsValidTime = _extractionTime /= MILLIS_PER_DAY; - _paramsValidTime *= MILLIS_PER_DAY; - - - } - - _logger.log( "Parsing " + _extractFileName ); - _logger.log( "-----" ); - line = _reader.readLine(); - - if ( line == null ) - { - throw new OfsFileParserException( "line empty" ); - } - - parseRunoffTimeSeries( runoffTimeSeriesListElement ); - parsePeTimeSeries( peTimeSeriesListElement ); - parseMonthlyValues( monthlyValuesListElement ); - parseSacParams( sacParamsListElement ); - parseSacState( sacStateListElement ); - } - - catch ( OfsFileParserException e ) - { - _logger.log( _extractFileName + " is not a complete extracted file" ); - throw new OfsFileParserException( "line empty" ); - } - - catch ( FileNotFoundException e ) - { - _logger.log( _extractFileName + " not found." ); - e.printStackTrace( _logger.getPrintWriter() ); //we will add this to everything later - } - catch ( IOException e ) - { - _logger.log( "Unable to read from " + _extractFileName ); - e.printStackTrace( _logger.getPrintWriter() ); - } - - finally - { - try - { - _reader.close(); - } - catch ( IOException e ) - { - _logger.log( "Unable to close " + _extractFileName ); - } - } - - - } - - // --------------------------------------------------------------------- - - private long parseTimeString( String timeString ) - { - // example: String format = "yyyy-MM-dd HH:mm:ss" - String formatString = "MM/dd/yyyy HHmm"; - SimpleDateFormat sdf = new SimpleDateFormat( formatString ); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - long time = 0; - - try - { - time = sdf.parse( timeString ).getTime(); - } - catch ( ParseException e ) - { - e.printStackTrace(); - } - - return time; - } - - // --------------------------------------------------------------------- - private int getNextCharIndex(String line, String searchString) - { - int index = line.indexOf(searchString); - if (index > -1) - { - index += searchString.length(); - } - - return index; - } - // --------------------------------------------------------------------- - private void parseRunoffTimeSeries( Element runoffTimeSeriesListElement ) - { - String line = null; - int duration = 0; - - Element roTimeSeriesElement = new Element( "RunoffTimeSeries" ); - Element measurementListElement = new Element( "MeasurementList" ); - - findLine( "RO Time Series Begin" ); // Searches the input file for the string passed in - - try - { - //read next line - line = _reader.readLine(); - if ( line.startsWith( "No RO time series" ) ) - { - roTimeSeriesElement.addContent(getElement("basinId", _basinId)); - roTimeSeriesElement.addContent( getElement( "exists", "FALSE" ) ); - } - else // there is a Runoff time series - { - _logger.log( "Extracting RO Timeseries" ); - roTimeSeriesElement.addContent(getElement("exists", "TRUE")); - roTimeSeriesElement.addContent(getElement("basinId", _basinId)); - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( _timeSeriesBasisTime ); - roTimeSeriesElement.addContent(getElement("basisTime", timeString)); - - int index = getNextCharIndex( line, "Step=" ); - - if ( index > -1 ) - { - String durationString = line.substring( index, index + 2 ).trim(); - duration = Integer.parseInt( durationString ); - roTimeSeriesElement.addContent( getElement( "duration", getDuration( durationString ) ) ); - } - - index = getNextCharIndex( line,"Data Units=" ); - - if ( index > -1 ) - { - String unitsString = line.substring(index).toLowerCase().trim(); - roTimeSeriesElement.addContent(getElement("units", unitsString)); - } - - - roTimeSeriesElement.addContent( measurementListElement ); - - line = _reader.readLine(); - // parses the start and end time for the measurements - String measurementTimeString = null; - int startIndex = getNextCharIndex( line, "Time=" ); - int endIndex = getNextCharIndex( line, "Z" ); - measurementTimeString = line.substring( startIndex, endIndex - 1 ).trim(); - long measurementTimeLong = parseTimeString( measurementTimeString + "00" ); - - startIndex = getNextCharIndex( line, "Count=" ); - endIndex = startIndex + 2; - - line = _reader.readLine(); - index = getNextCharIndex( line, "Values=" ); - line = line.substring( index, line.length() ); - - while ( ! line.startsWith( "RO Time Series End" ) ) - { - String[] valueStringArray = StringParser.tokenize( line ); - - for ( int i = 0; i < valueStringArray.length; i++ ) - { - Element measurementElement = new Element( "Measurement" ); - measurementElement.addContent( getElement( "time", DbTimeHelper.getDateTimeStringFromLongTime( measurementTimeLong ) ) ); - measurementTimeLong += duration * HOUR_IN_MILLIS; - measurementElement.addContent( getElement( "value", valueStringArray[ i ] ) ); - measurementListElement.addContent( measurementElement ); - } - line = _reader.readLine(); - } - } // close bracket for else statement - runoffTimeSeriesListElement.addContent( roTimeSeriesElement ); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - - // --------------------------------------------------------------------- - private void parsePeTimeSeries( Element peTimeSeriesListElement ) - { - String line = null; - int duration = 0; - - Element peTimeSeriesElement = new Element( "PeTimeSeries" ); - Element measurementListElement = new Element( "MeasurementList" ); - - findLine( "PE Time Series Begin" ); // Searches the input file for the string passed in - - try - { - //read next line - line = _reader.readLine(); - if ( line.startsWith( "No PE Time Series" ) ) - { - peTimeSeriesElement.addContent(getElement("basinId", _basinId)); - peTimeSeriesElement.addContent(getElement("isUsed", "FALSE")); - } - else // there is a PE time series - { - _logger.log( "Extracting PE Timeseries" ); - peTimeSeriesElement.addContent(getElement("isUsed", "TRUE")); - peTimeSeriesElement.addContent(getElement("basinId", _basinId)); - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( _timeSeriesBasisTime ); - peTimeSeriesElement.addContent(getElement("basisTime", timeString)); - - int index = getNextCharIndex( line, "Step=" ); - - if ( index > -1 ) - { - String durationString = line.substring( index, index + 2 ).trim(); - duration = Integer.parseInt( durationString ); - peTimeSeriesElement.addContent( getElement( "duration", getDuration( durationString ) ) ); - } - - index = getNextCharIndex( line,"Data Units=" ); - - if ( index > -1 ) - { - String unitsString = line.substring(index).toLowerCase().trim(); - peTimeSeriesElement.addContent(getElement("units", unitsString)); - } - - - peTimeSeriesElement.addContent( measurementListElement ); - - line = _reader.readLine(); - // parses the start and end time for the measurements - String measurementTimeString = null; - int startIndex = getNextCharIndex( line, "Time=" ); - int endIndex = getNextCharIndex( line, "Z" ); - measurementTimeString = line.substring( startIndex, endIndex - 1 ).trim(); - long measurementTimeLong = parseTimeString( measurementTimeString + "00" ); - - startIndex = getNextCharIndex( line, "Count=" ); - endIndex = startIndex + 2; - - line = _reader.readLine(); - index = getNextCharIndex( line, "Values=" ); - line = line.substring( index, line.length() ); - - while ( ! line.startsWith( "PE Time Series End" ) ) - { - String[] valueStringArray = StringParser.tokenize( line ); - - for ( int i = 0; i < valueStringArray.length; i++ ) - { - Element measurementElement = new Element( "Measurement" ); - measurementElement.addContent( getElement( "time", DbTimeHelper.getDateTimeStringFromLongTime( measurementTimeLong ) ) ); - measurementTimeLong += duration * HOUR_IN_MILLIS; - measurementElement.addContent( getElement( "value", valueStringArray[ i ] ) ); - measurementListElement.addContent( measurementElement ); - } - line = _reader.readLine(); - } - - } - peTimeSeriesListElement.addContent(peTimeSeriesElement); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - private Element getElement(String elementName, String elementText) - { - Element element = new Element(elementName); - element.setText(elementText); - - return element; - } - - // --------------------------------------------------------------------- - - private void parseMonthlyValues( Element monthlyValuesListElement ) - { - // this is not done yet - work on this Gautam - String line = null; - boolean done = false; - Element monthlyValuesElement = new Element( "MonthlyValues" ); - String[] valuesStringArray = null; - - findLine( "Monthly Values Begin" ); - - try - { - line = _reader.readLine(); - if ( line != null ) - { - if ( line.startsWith( "No Monthly Values" ) ) - { - done = true; - } - else // there are monthly Values - { - _logger.log( "Extracting MonthlyValues" ); - monthlyValuesElement.addContent( getElement( "locationId", _basinId ) ); - int index = getNextCharIndex( line, "Type=" ); - String isAdjustmentString = line.substring( index, line.length() ); - if ( isAdjustmentString.startsWith( "PE Adjustment" ) ) - { - monthlyValuesElement.addContent( getElement( "isAdjustment", "TRUE" ) ); - } - else - { - monthlyValuesElement.addContent( getElement( "isAdjustment", "FALSE" ) ); - } - - line = _reader.readLine(); - valuesStringArray = StringParser.tokenize( line ); - - monthlyValuesElement.addContent( getElement( "janValue", valuesStringArray[ 0 ] ) ); - monthlyValuesElement.addContent( getElement( "febValue", valuesStringArray[ 1 ] ) ); - monthlyValuesElement.addContent( getElement( "marValue", valuesStringArray[ 2 ] ) ); - monthlyValuesElement.addContent( getElement( "aprValue", valuesStringArray[ 3 ] ) ); - monthlyValuesElement.addContent( getElement( "mayValue", valuesStringArray[ 4 ] ) ); - monthlyValuesElement.addContent( getElement( "junValue", valuesStringArray[ 5 ] ) ); - monthlyValuesElement.addContent( getElement( "julValue", valuesStringArray[ 6 ] ) ); - monthlyValuesElement.addContent( getElement( "augValue", valuesStringArray[ 7 ] ) ); - monthlyValuesElement.addContent( getElement( "sepValue", valuesStringArray[ 8 ] ) ); - monthlyValuesElement.addContent( getElement( "octValue", valuesStringArray[ 9 ] ) ); - monthlyValuesElement.addContent( getElement( "novValue", valuesStringArray[ 10 ] ) ); - monthlyValuesElement.addContent( getElement( "decValue", valuesStringArray[ 11 ] ) ); - done = true; - } - } - if ( done ) - { - monthlyValuesListElement.addContent( monthlyValuesElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - private void parseSacParams(Element sacParamsListElement) - { - String line = null; - boolean done = false; - Element sacParamsElement = new Element( "SacParams" ); - - findLine( "SAC Params Begin" ); - - try - { - line = _reader.readLine(); - if ( line != null ) - { - _logger.log( "Extracting SacSmaParameters" ); - sacParamsElement.addContent( getElement( "basinId", _basinId ) ); - sacParamsElement.addContent( getElement( "source", SOURCE ) ); - sacParamsElement.addContent( getElement( "validTime", DbTimeHelper.getDateTimeStringFromLongTime( _paramsValidTime ) ) ); - - if ( ! line.startsWith( "No SAC Params" ) ) - { - while ( ! line.startsWith( "SAC Params End" ) ) - { - int index = getNextCharIndex( line, "=" ); - String paramString = line.substring( 0, index - 1 ).trim().toLowerCase(); - String valueString = line.substring( index, line.length() ).trim(); - sacParamsElement.addContent( getElement( paramString, valueString ) ); - line = _reader.readLine(); - } - done = true; - } - } - if ( done ) - { - sacParamsListElement.addContent( sacParamsElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - - } - - // --------------------------------------------------------------------- - private void parseSacState( Element sacStateListElement ) - { - String line = null; - boolean done = false; - Element sacStateElement = new Element( "SacState" ); - long validTime = 0; - - findLine( "SAC State Begin" ); - try - { - line = _reader.readLine(); - if ( line != null ) - { - _logger.log( "Extracting SacSmaState" ); - sacStateElement.addContent( getElement( "basinId", _basinId ) ); - sacStateElement.addContent( getElement( "source", SOURCE ) ); - int dateIndex = getNextCharIndex( line, "date=" ); - String dateString = line.substring( dateIndex, line.length() ).trim(); - dateString = dateString.substring( 0, dateString.length() - 1 ); - long nonRoundedCarryOverDateTimeLong = parseTimeString( dateString + "00" ); - - - long carryOverDateTimeLong = getRoundedValidTime( nonRoundedCarryOverDateTimeLong ); - if ( carryOverDateTimeLong != nonRoundedCarryOverDateTimeLong ) - { - _logger.log( "Original valid time was NOT 12Z!" ); - } - sacStateElement.addContent( getElement( "validTime", DbTimeHelper.getDateTimeStringFromLongTime( carryOverDateTimeLong ) ) ); - sacStateElement.addContent( getElement( "basisTime", DbTimeHelper.getDateTimeStringFromLongTime( carryOverDateTimeLong ) ) ); - - line = _reader.readLine(); - - if ( ! line.startsWith( "No SAC States" ) ) - { - while ( ! line.startsWith( "SAC State End" ) ) - { - int index = getNextCharIndex( line, "=" ); - String stateString = line.substring( 0, index - 1 ).trim().toLowerCase(); - String valueString = line.substring( index, line.length() ).trim(); - sacStateElement.addContent( getElement( stateString, valueString ) ); - line = _reader.readLine(); - } - done = true; - } - } - if ( done ) - { - sacStateListElement.addContent( sacStateElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - private long getRoundedValidTime( long extractionTime ) - { - long validTime = extractionTime; - - validTime /= MILLIS_PER_DAY; - validTime *= MILLIS_PER_DAY; - validTime += ( MILLIS_PER_DAY / 2 ); - if ( validTime > extractionTime ) - { - validTime -= MILLIS_PER_DAY; - } - return validTime; - } - - // --------------------------------------------------------------------- - - private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) - { - Format format = Format.getRawFormat(); - format.setIndent(" "); - XMLOutputter _xmlOutputter = new XMLOutputter(format); - - try - { - FileWriter writer = new FileWriter(xmlFileName); - _xmlOutputter.output(outputXmlDoc, writer); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - - private static Document getBaseDocument() - { - //this is used only for testing - - Document doc = new Document(); - - Element rootElement = new Element("SacModelMessage"); - - doc.setRootElement(rootElement); - - Element sacParamsListElement = new Element("SacParamsList"); - Element sacStateListElement = new Element("SacStateList"); - Element peTimeSeriesListElement = new Element("PeTimeSeriesList"); - Element runoffTimeSeriesElement = new Element("RunoffTimeSeriesList"); - Element monthlyValuesListElement = new Element("MonthlyValuesList"); - - rootElement.addContent(sacParamsListElement); - rootElement.addContent(sacStateListElement); - rootElement.addContent(peTimeSeriesListElement); - rootElement.addContent(runoffTimeSeriesElement); - rootElement.addContent(monthlyValuesListElement); - - return doc; - } - - // --------------------------------------------------------------------- - - private String findLine( String searchString ) - { - String line = null; - try - { - line = _reader.readLine(); - while ( ! line.startsWith( searchString ) ) - { - line = _reader.readLine(); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - line = null; - } - return line; - } - - // --------------------------------------------------------------------- - - private String getDuration( String durationString ) - { - int duration = Integer.parseInt( durationString ); - duration += 1000; - return ( "" + duration ); - } - - // --------------------------------------------------------------------- - - public static void main(String[] args) - { - String extractedFileName = null; - String processedFileName = null; - SacXMLEncoder encoder = null; - - String basinId = null; - - Document xmlOutputDoc = getBaseDocument(); - - // file1 - extractedFileName = "D:/Data/SacEncoderInput/BLAS.txt"; -// extractedFileName = args[ 0 ]; - basinId = "BLASE"; - encoder = new SacXMLEncoder( basinId, extractedFileName, xmlOutputDoc, new FileLogger( "D:/data/log/SacXMLEncoder.log", true, true ) ); - try - { - encoder.parse(); - } - catch( OfsFileParserException e ) - { - } - - - // write out the output - processedFileName = "D:/Data/XMLFiles/BLASE.xml"; -// processedFileName = "/fs/home/gsood/processed_SJU.xml"; - encoder.writeXmlToFile( xmlOutputDoc, processedFileName ); - - } - - // --------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java deleted file mode 100644 index ae2616b90b..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java +++ /dev/null @@ -1,554 +0,0 @@ -/* - * Created on Sep 11, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : March 16, 2004 - * Purpose: Decodes XML input files and posts the data to the database. - */ - -package ohd.hseb.sshp.messaging; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.TimeHelper; - -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.input.SAXBuilder; -import org.jdom.output.Format.TextMode; -import org.jdom.output.XMLOutputter; -import org.jdom.output.Format; - -public class SacXMLTester -{ - private String _inputDir = null; - private String _archiveDir = null; - private String _logFullPath = null; - private long _sleepTime = 0; - private Document _inputXMLDoc = null; - private Document _outputXMLDoc = null; - private String backupInputFilePath = null; - private String _inputXMLFileName = null; - private boolean _isTest = true; - private String _basinID = null; - - private static final String PE_TIMESERIES_PE_CODE = "EA"; - private static final String RUNOFF_TIMESERIES_PE_CODE = "QB"; - private static final String TS = "FZ"; - private static final String EXTREMUM = "Z"; - private static final float PROBABILITY = -1.0f; - private static final String SHEF_QUAL_CODE = "Z"; - private static final int GOOD_QC = 1879048191; - private static final short REVISION = 0; - private static final String PRODUCT_ID = "SSHP_XFER"; - - private static final String MONTHLY_VALUES_TS = "FZ"; - private static final String MONTHLY_VALUES_EXTREMUM = "Z"; - private static final String MONTHLY_VALUES_PE = "EA"; - private static final short MONTHLY_VALUES_DUR = 2001; - private static final MeasuringUnit DB_MEASURING_UNIT = MeasuringUnit.inches; - private static final int INTERVAL_IN_HOURS = 1; - - private static Map _unitsMap = new HashMap(); - - private FileLogger _logger = null; - - private DecoderDataMgr _dataMgr = null; - - - - - - public SacXMLTester( String inputXMLFileName, Document xmlOutputDoc, String logFileName ) - { - _inputXMLFileName = inputXMLFileName; - _outputXMLDoc = xmlOutputDoc; - _logFullPath = logFileName; - } - - private void execute() - { - File backupInputFile = null; - SAXBuilder builder = new SAXBuilder(); - File inputFile = null; - Date time = new Date(); - boolean keepFileOpen = true; - boolean appendDateTime = true; - CodeTimer timer1 = null; - - _logger = new FileLogger( _logFullPath, keepFileOpen, appendDateTime ); - timer1 = new CodeTimer( _logger ); - - initUnitsMap(); - - try - { - builder.setExpandEntities( true ); - _logger.log( "Processing " + _inputXMLFileName ); - timer1.start(); - - _inputXMLDoc = builder.build( _inputXMLFileName ); - parseXMLFiles(); - backupInputFile = new File( _archiveDir + "/" + _inputXMLFileName ); - if ( backupInputFile.isFile() ) - { - backupInputFile = new File( backupInputFilePath + _inputXMLFileName + "_" + time.getTime() ); - } - inputFile = new File( _inputXMLFileName ); - inputFile.renameTo( backupInputFile ); - timer1.stop( "Finished processing " + _inputXMLFileName + " in " ); - } - catch ( JDOMException e ) - { - _logger.log( " " + _inputXMLFileName + " is not a valid XML file." ); - } - - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - private void initUnitsMap() - { - _unitsMap.put( new String( "mm" ), MeasuringUnit.mm ); - _unitsMap.put( new String( "cm" ), MeasuringUnit.cm ); - _unitsMap.put( new String( "m" ), MeasuringUnit.meters ); - _unitsMap.put( new String( "in" ), MeasuringUnit.inches ); - _unitsMap.put( new String( "ft" ), MeasuringUnit.feet ); - } - - private void parseXMLFiles() - { - Element inputSacParamsListElement = _inputXMLDoc.getRootElement().getChild( "SacParamsList" ); - Element inputSacStateListElement = _inputXMLDoc.getRootElement().getChild( "SacStateList" ); - Element monthlyValuesListElement = _inputXMLDoc.getRootElement().getChild( "MonthlyValuesList" ); - - Element outputRootElement = _outputXMLDoc.getRootElement(); - Element outputSacParamsListElement = outputRootElement.getChild( "SacParamsList" ); - Element outputSacStateListElement = outputRootElement.getChild( "SacStateList" ); - Element outputMonthlyValuesListElement = outputRootElement.getChild( "MonthlyValuesList" ); - Element outputPETimeSeriesListElement = outputRootElement.getChild( "PeTimeSeriesList" ); - Element outputRunoffTimeSeriesElement = outputRootElement.getChild( "RunoffTimeSeriesList" ); - - Element sacParamsElement = null; - Element sacStateElement = null; - Element peTimeSeriesElement = null; - Element runoffTimeSeriesElement = null; - Element monthlyValuesElement = null; - - SacSmaParameters sacSmaParamsToBeCopied = new SacSmaParameters(); - SacSmaState sacSmaStateToBeCopied = new SacSmaState(); - RegularTimeSeries peTimeSeries = null; - RegularTimeSeries roTimeSeries = null; - - Random generator = new Random(); - - List elementList = null; - - - -// --------- Processing Sac Parameters - - elementList = inputSacParamsListElement.getChildren( "SacParams" ); - - Element outputSacParamsElement = null; - for ( int i = 0; i < elementList.size(); i++ ) - { - sacParamsElement = (Element) elementList.get( i ); - - sacSmaParamsToBeCopied = retrieveSacSmaParams( sacParamsElement ); - outputSacParamsElement = convertSacSmaParamsToSacSmaParamsElement( sacSmaParamsToBeCopied ); - outputSacParamsListElement.addContent( outputSacParamsElement ); - } - - _basinID = sacSmaParamsToBeCopied.getBasinId(); -// --------- Processing Sac States - elementList = inputSacStateListElement.getChildren( "SacState" ); - Element outputSacStateElement = null; - - for ( int i = 0; i < elementList.size(); i++ ) - { - sacStateElement = (Element) elementList.get( i ); - - sacSmaStateToBeCopied = retrieveSacSmaState( sacStateElement ); - outputSacStateElement = convertSacSmaStateToSacSmaStateElement( sacSmaStateToBeCopied ); - - outputSacStateListElement.addContent( outputSacStateElement ); - } - -// --------- Processing MonthlyValues - - elementList = monthlyValuesListElement.getChildren( "MonthlyValues" ); - Element outputMonthlyValuesElement = null; - - for ( int i = 0; i < elementList.size(); i++ ) - { - monthlyValuesElement = (Element) elementList.get( i ); - - outputMonthlyValuesElement = (Element) monthlyValuesElement.clone(); - - outputMonthlyValuesListElement.addContent( outputMonthlyValuesElement ); - } - -// --------- Processing Pe Timeseries - - long endTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - long startTime = endTime - ( 100 * TimeHelper.MILLIS_PER_HOUR ); - long validTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - Element measurementListElement = new Element( "MeasurementList" ); - - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime( validTime ); - - peTimeSeries = new RegularTimeSeries(startTime, endTime, INTERVAL_IN_HOURS, DB_MEASURING_UNIT ); - - peTimeSeriesElement = new Element( "PeTimeSeries" ); - peTimeSeriesElement.addContent( getElement( "isUsed", "TRUE" ) ); - peTimeSeriesElement.addContent( getElement( "basinId", _basinID ) ); - peTimeSeriesElement.addContent( getElement( "basisTime", validTimeString ) ); - peTimeSeriesElement.addContent( getElement( "duration", "1024" ) ); - peTimeSeriesElement.addContent( getElement( "units", "mm" ) ); - peTimeSeriesElement.addContent( measurementListElement ); - - for ( long timeIndex = startTime; timeIndex <= endTime; timeIndex += TimeHelper.MILLIS_PER_HOUR ) - { - double randomNumber = Math.random() * 3; - double value = ( Math.round ( randomNumber * 1000.0 ) ) / 1000.0; - - Element measurementElement = new Element( "Measurement" ); - - measurementElement.addContent( getElement ( "time", DbTimeHelper.getDateTimeStringFromLongTime( timeIndex ) ) ); - measurementElement.addContent( getElement( "value", Double.toString( value ) ) ); - measurementListElement.addContent( measurementElement ); - } - - outputPETimeSeriesListElement.addContent( peTimeSeriesElement ); - - -// --------- Processing Runoff Timeseries - - measurementListElement = new Element( "MeasurementList" ); - - roTimeSeries = new RegularTimeSeries(startTime, endTime, INTERVAL_IN_HOURS, DB_MEASURING_UNIT ); - - runoffTimeSeriesElement = new Element( "RunoffTimeSeries" ); - runoffTimeSeriesElement.addContent( getElement( "exists", "TRUE" ) ); - runoffTimeSeriesElement.addContent( getElement( "basinId", _basinID ) ); - runoffTimeSeriesElement.addContent( getElement( "basisTime", validTimeString ) ); - runoffTimeSeriesElement.addContent( getElement( "duration", "1024" ) ); - runoffTimeSeriesElement.addContent( getElement( "units", "mm" ) ); - runoffTimeSeriesElement.addContent( measurementListElement ); - - for ( long timeIndex = startTime; timeIndex <= endTime; timeIndex += TimeHelper.MILLIS_PER_HOUR ) - { - double randomNumber = Math.random() * 3; - double value = ( Math.round ( randomNumber * 1000.0 ) ) / 1000.0; - - Element measurementElement = new Element( "Measurement" ); - - measurementElement.addContent( getElement ( "time", DbTimeHelper.getDateTimeStringFromLongTime( timeIndex ) ) ); - measurementElement.addContent( getElement( "value", Double.toString( value ) ) ); - measurementListElement.addContent( measurementElement ); - } - - outputRunoffTimeSeriesElement.addContent( runoffTimeSeriesElement ); - - } - -// ----------------------------------------------------------------------------- - - private Element convertSacSmaParamsToSacSmaParamsElement( SacSmaParameters params ) - { - Element element = new Element ( "SacParams" ); - - long validTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime( validTime ); - - - element.addContent( getElement( "basinId", params.getBasinId() ) ); - element.addContent( getElement( "source", params.getSource() ) ); - element.addContent( getElement( "validTime", validTimeString ) ); - element.addContent( getElement( "pxadj", Double.toString( params.getPxadj() ) ) ); - element.addContent( getElement( "peadj", Double.toString( params.getPeadj() ) ) ); - element.addContent( getElement( "uztwm", Double.toString( params.getUztwm() ) ) ); - element.addContent( getElement( "uzfwm", Double.toString( params.getUzfwm() ) ) ); - element.addContent( getElement( "uzk", Double.toString( params.getUzk() ) ) ); - element.addContent( getElement( "pctim", Double.toString( params.getPctim() ) ) ); - element.addContent( getElement( "adimp", Double.toString( params.getAdimp() ) ) ); - element.addContent( getElement( "riva", Double.toString( params.getRiva() ) ) ); - element.addContent( getElement( "zperc", Double.toString( params.getZperc() ) ) ); - element.addContent( getElement( "rexp", Double.toString( params.getRexp() ) ) ); - element.addContent( getElement( "lztwm", Double.toString( params.getLztwm() ) ) ); - element.addContent( getElement( "lzfsm", Double.toString( params.getLzfsm() ) ) ); - element.addContent( getElement( "lzfpm", Double.toString( params.getLzfpm() ) ) ); - element.addContent( getElement( "lzsk", Double.toString( params.getLzsk() ) ) ); - element.addContent( getElement( "lzpk", Double.toString( params.getLzpk() ) ) ); - element.addContent( getElement( "pfree", Double.toString( params.getPfree() ) ) ); - element.addContent( getElement( "rserv", Double.toString( params.getRserv() ) ) ); - element.addContent( getElement( "side", Double.toString( params.getSide() ) ) ); -// element.addContent( getElement( "ioptet", Double.toString( params.get() ) ) ); - element.addContent( getElement( "efc", Double.toString( params.getEfc() ) ) ); - - return element; - } - - private Element convertSacSmaStateToSacSmaStateElement( SacSmaState state ) - { - Element element = new Element ( "SacState" ); - - long validTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime( validTime ); - - element.addContent( getElement( "basinId", state.getBasinId() ) ); - element.addContent( getElement( "source", state.getSource() ) ); - element.addContent( getElement( "validTime", validTimeString ) ); - element.addContent( getElement( "basisTime", validTimeString ) ); - element.addContent( getElement( "uztwc", Double.toString( state.getUztwc() ) ) ); - element.addContent( getElement( "uzfwc", Double.toString( state.getUzfwc() ) ) ); - element.addContent( getElement( "lztwc", Double.toString( state.getLztwc() ) ) ); - element.addContent( getElement( "lzfsc", Double.toString( state.getLzfsc() ) ) ); - element.addContent( getElement( "lzfpc", Double.toString( state.getLzfpc() ) ) ); - element.addContent( getElement( "adimc", Double.toString( state.getAdimc() ) ) ); - - return element; - } - - private Element getElement(String elementName, String elementText) - { - Element element = new Element(elementName); - element.setText(elementText); - - return element; - } - - private SacSmaParameters retrieveSacSmaParams( Element e ) - { - SacSmaParameters currentSacSmaParams = new SacSmaParameters(); - - currentSacSmaParams.setBasinId( getElementStringValue( e, "basinId" ) ); - currentSacSmaParams.setSource( getElementStringValue( e, "source" ) ); - currentSacSmaParams.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaParams.setPostingTime( System.currentTimeMillis() ); - currentSacSmaParams.setUztwm( getElementDoubleValue( e, "uztwm" ) ); - currentSacSmaParams.setUzfwm( getElementDoubleValue( e, "uzfwm" ) ); - currentSacSmaParams.setUzk( getElementDoubleValue( e, "uzk" ) ); - currentSacSmaParams.setPctim( getElementDoubleValue( e, "pctim" ) ); - currentSacSmaParams.setAdimp( getElementDoubleValue( e, "adimp" ) ); - currentSacSmaParams.setRiva( getElementDoubleValue( e, "riva" ) ); - currentSacSmaParams.setZperc( getElementDoubleValue( e, "zperc" ) ); - currentSacSmaParams.setRexp( getElementDoubleValue( e, "rexp" ) ); - currentSacSmaParams.setLztwm( getElementDoubleValue( e, "lztwm" ) ); - currentSacSmaParams.setLzfsm( getElementDoubleValue( e, "lzfsm" ) ); - currentSacSmaParams.setLzfpm( getElementDoubleValue( e, "lzfpm" ) ); - currentSacSmaParams.setLzsk( getElementDoubleValue( e, "lzsk" ) ); - currentSacSmaParams.setLzpk( getElementDoubleValue( e, "lzpk" ) ); - currentSacSmaParams.setPfree( getElementDoubleValue( e, "pfree" ) ); - currentSacSmaParams.setRserv( getElementDoubleValue( e, "rserv" ) ); - currentSacSmaParams.setSide( getElementDoubleValue( e, "side" ) ); - currentSacSmaParams.setPxadj( getElementDoubleValue( e, "pxadj" ) ); - currentSacSmaParams.setPeadj( getElementDoubleValue( e, "peadj" ) ); - currentSacSmaParams.setEfc( getElementDoubleValue( e, "efc" ) ); - - - return currentSacSmaParams; - } - -// ----------------------------------------------------------------------------- - - private SacSmaState retrieveSacSmaState( Element e ) - { - SacSmaState currentSacSmaState = new SacSmaState(); - - currentSacSmaState.setBasinId( getElementStringValue( e, "basinId") ); - currentSacSmaState.setSource( getElementStringValue( e, "source") ); - currentSacSmaState.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaState.setBasisTime( getElementLongTimeValue( e, "basisTime" ) ); - currentSacSmaState.setPostingTime( System.currentTimeMillis() ); - currentSacSmaState.setUztwc( getElementDoubleValue( e, "uztwc" ) ); - currentSacSmaState.setUzfwc( getElementDoubleValue( e, "uzfwc" ) ); - currentSacSmaState.setLztwc( getElementDoubleValue( e, "lztwc" ) ); - currentSacSmaState.setLzfsc( getElementDoubleValue( e, "lzfsc" ) ); - currentSacSmaState.setLzfpc( getElementDoubleValue( e, "lzfpc" ) ); - currentSacSmaState.setAdimc( getElementDoubleValue( e, "adimc" ) ); - - return currentSacSmaState; - } - -// ----------------------------------------------------------------------------- - - private MonthlyValues retrieveMonthlyValues( Element e ) - { - MonthlyValues currentMonthlyValues = new MonthlyValues(); - double[] valueArray = new double[ 12 ]; - - currentMonthlyValues.setBasinId( getElementStringValue( e, "locationId" ) ); - currentMonthlyValues.setPe( MONTHLY_VALUES_PE ); - currentMonthlyValues.setDur(MONTHLY_VALUES_DUR ); - currentMonthlyValues.setTs( MONTHLY_VALUES_TS ); - currentMonthlyValues.setExtremum( MONTHLY_VALUES_EXTREMUM ); - if ( getElementStringValue( e, "isAdjustment" ).equalsIgnoreCase( "TRUE" ) ) - { - currentMonthlyValues.setAdjustment( true ); - } - else - { - currentMonthlyValues.setAdjustment( false ); - } - currentMonthlyValues.setPostingTime( System.currentTimeMillis() ); - - valueArray[ 0 ] = getElementDoubleValue( e, "janValue" ); - valueArray[ 1 ] = getElementDoubleValue( e, "febValue" ); - valueArray[ 2 ] = getElementDoubleValue( e, "marValue" ); - valueArray[ 3 ] = getElementDoubleValue( e, "aprValue" ); - valueArray[ 4 ] = getElementDoubleValue( e, "mayValue" ); - valueArray[ 5 ] = getElementDoubleValue( e, "junValue" ); - valueArray[ 6 ] = getElementDoubleValue( e, "julValue" ); - valueArray[ 7 ] = getElementDoubleValue( e, "augValue" ); - valueArray[ 8 ] = getElementDoubleValue( e, "sepValue" ); - valueArray[ 9 ] = getElementDoubleValue( e, "octValue" ); - valueArray[ 10 ] = getElementDoubleValue( e, "novValue" ); - valueArray[ 11 ] = getElementDoubleValue( e, "decValue" ); - currentMonthlyValues.setValues( valueArray ); - - return currentMonthlyValues; - } - -// ----------------------------------------------------------------------------- - - private String getElementStringValue( Element e, String subElementName ) - { - return e.getChildTextTrim( subElementName ); - } - -// ----------------------------------------------------------------------------- - - private double getElementDoubleValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Double.parseDouble( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private int getElementIntValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Integer.parseInt( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - private short getElementShortValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Short.parseShort( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private long getElementLongTimeValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return DbTimeHelper.getLongTimeFromDateTimeString( attributeValueString ); - } - -// ----------------------------------------------------------------------------- - - public String toString() - { - StringWriter stringWriter = new StringWriter(); - Format format = Format.getPrettyFormat(); - format = format.setIndent(" "); - XMLOutputter outputter = new XMLOutputter(format); - String returnValue = null; - - try - { - outputter.output( _inputXMLDoc, stringWriter ); - returnValue = stringWriter.toString(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - - return returnValue; - } - - private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) - { - Format format = Format.getRawFormat(); - format.setIndent(" "); - XMLOutputter _xmlOutputter = new XMLOutputter(format); - - try - { - FileWriter writer = new FileWriter(xmlFileName); - _xmlOutputter.output(outputXmlDoc, writer); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - private static Document getBaseDocument() - { - //this is used only for testing - - Document doc = new Document(); - - Element rootElement = new Element("SacModelMessage"); - - doc.setRootElement(rootElement); - - Element sacParamsListElement = new Element("SacParamsList"); - Element sacStateListElement = new Element("SacStateList"); - Element peTimeSeriesListElement = new Element("PeTimeSeriesList"); - Element runoffTimeSeriesElement = new Element("RunoffTimeSeriesList"); - Element monthlyValuesListElement = new Element("MonthlyValuesList"); - - rootElement.addContent(sacParamsListElement); - rootElement.addContent(sacStateListElement); - rootElement.addContent(peTimeSeriesListElement); - rootElement.addContent(runoffTimeSeriesElement); - rootElement.addContent(monthlyValuesListElement); - - return doc; - } -// ----------------------------------------------------------------------------- - - public static void main( String[] args ) - { - String inputFileName = args[ 0 ]; - String outputFileName = args[ 1 ]; - String logFileName = args [ 2 ]; - - Document xmlOutputDoc = getBaseDocument(); - - SacXMLTester sacDecoder = new SacXMLTester( inputFileName, xmlOutputDoc, logFileName ); - - sacDecoder.execute(); - - sacDecoder.writeXmlToFile( xmlOutputDoc, outputFileName ); -// System.exit( 0 ); - } -} \ No newline at end of file diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java deleted file mode 100644 index 3c8505738f..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Created on Feb 25, 2004 - * - * This is the main program for the extraction of OFS - * data, conversion to XML, and then sending to the WFO - */ -package ohd.hseb.sshp.messaging; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.TimeZone; - -import ohd.hseb.util.EnvHelper; -import ohd.hseb.util.FileLogger; - -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.input.SAXBuilder; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; - -/** - * @author GobsC - * - * - */ -public class SshpDataTransferMgr -{ - - private static String _controlFilePath = null; - private static String _extractedDirName = null; - private static String _processedDirName = null; - private static String _logDirName = null; - - private Document _controlDoc = null; - private SAXBuilder _builder = new SAXBuilder(); - private XMLOutputter _xmlOutputter = null; - - private FileLogger _logger = null; - private String _logFilePath = null; - - // -------------------------------------------------------------- - public SshpDataTransferMgr(String controlFilePath, - String extractedDirName, - String processedDirName, - String logDirName) - { - - _controlFilePath = controlFilePath; - _extractedDirName = extractedDirName; - _processedDirName = processedDirName; - - _logDirName = logDirName; - - _logFilePath = _logDirName + "/SshpDataTransferMgr.log"; - - _logger = new FileLogger(_logFilePath); - - Format format = Format.getRawFormat(); - format.setIndent(" "); - this._xmlOutputter = new XMLOutputter(format); - - loadControlFile(); - - return; - } - -// -------------------------------------------------------------- - public void execute() - { - String header = "SshpDataTransferMgr.execute(): "; - System.out.println("SshpDataTransferMgr logging to " + _logFilePath); - //using the control xml document - //for each wfo - - //for each forecast point - //extract all the segment data to a file - //translate the extract file and add contents to the live XML doc - //end for each forecast point - - //output live XML document object to a file - //send file using MHS - // end for each wfo - - Element controlRoot =_controlDoc.getRootElement(); - List wfoElementList = controlRoot.getChildren("wfo"); - int wfoCount = wfoElementList.size(); - - - long time = System.currentTimeMillis(); - String timeString = getDateTimeStringFromLongTime(time); - - - //for each wfo - for (int i = 0; i < wfoCount; i++) - { - Element wfoElement = (Element) wfoElementList.get(i); - String wfoName = wfoElement.getChildText("name"); - String mhsId = wfoElement.getChildText("mhsId"); - String productId = wfoElement.getChildText( "productId" ); - - _logger.log("processing wfoName = " + wfoName); - - List fcstPointElementList = wfoElement.getChildren("fcstPoint"); - int fcstPointCount = fcstPointElementList.size(); - - Document outputXmlDoc = getBaseDocument(); - - //for each forecast point - for (int j = 0; j < fcstPointCount; j++) - { - Element fcstPointElement = (Element) fcstPointElementList.get(j); - String segmentId = fcstPointElement.getChildText("ofsSegmentId"); - String locationId = fcstPointElement.getChildText("ihfsLocId"); - String basinId = fcstPointElement.getChildText("ihfsBasinId"); - - _logger.log("segmentId = " + segmentId + " locationId = " + locationId); - - String extractFileName = _extractedDirName + "/" + - segmentId + "." + timeString + ".txt"; - - // String extractFileName = _extractedDirName + "/" + - // segmentId + "_" + "1"; - - - // extract all the segment data to a file - extractOfsData(segmentId, extractFileName); - - - //translate the extract file and add contents to the live XML doc - translateToXml(basinId, extractFileName, outputXmlDoc); - } - - if (fcstPointCount < 1) - { - _logger.log("There were no forecast points defined in the control file: " + - _controlFilePath); - } - - //output the xml document to a file - String xmlFilePath = _processedDirName + "/" + - wfoName + "." + timeString + ".xml"; - - String xmlFileName = wfoName + "." + timeString + ".xml"; - - writeXmlToFile(outputXmlDoc, xmlFilePath); - - //send xml file to the site (WFO, usually) with this mhsId - sendXml(xmlFilePath, xmlFileName, mhsId, productId ); - } - - if ( wfoCount < 1 ) - { - _logger.log("There were no wfos defined in the control file: " + _controlFilePath); - } - - _logger.log("SshpDataTransferMgr completed."); - System.out.println("SshpDataTransferMgr completed."); - - } - -// -------------------------------------------------------------- - - private Document getBaseDocument() - { - Document doc = new Document(); - - Element rootElement = new Element("SacModelMessage"); - - doc.setRootElement(rootElement); - - Element sacParamsListElement = new Element("SacParamsList"); - Element sacStateListElement = new Element("SacStateList"); - Element peTimeSeriesListElement = new Element("PeTimeSeriesList"); - Element runoffTimeSeriesElement = new Element("RunoffTimeSeriesList"); - Element monthlyValuesListElement = new Element("MonthlyValuesList"); - - rootElement.addContent(sacParamsListElement); - rootElement.addContent(sacStateListElement); - rootElement.addContent(peTimeSeriesListElement); - rootElement.addContent(runoffTimeSeriesElement); - rootElement.addContent(monthlyValuesListElement); - - return doc; - } - -// -------------------------------------------------------------- - - private void loadControlFile() - { - try - { - _controlDoc = _builder.build( _controlFilePath ); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (JDOMException e2) - { - e2.printStackTrace(); - } - } - -// -------------------------------------------------------------- - - private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) - { - - try - { - FileWriter writer = new FileWriter(xmlFileName); - _xmlOutputter.output(outputXmlDoc, writer); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - -// -------------------------------------------------------------- - private static String getDateTimeStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy_MM_dd_HH_mm_ss"); - - return timeString; - } - - // ------------------------------------------------------- - - private static String getStringFromLongTime(long time, String dateFormat) - { - String timeString = null; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat(dateFormat); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(new java.util.Date(time)); - - return timeString; - } -// -------------------------------------------------------------- - private void extractOfsData(String segmentId, String extractFileName) - { - String header = "SshpDataTransferMgr.extractOfsData(): "; - - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - - String commandString = dirString + "/run_SSHP_ofs_extract " + segmentId + " " + extractFileName; - // System.out.println(header + "making system call:" + commandString + ":"); - Process process = null; - try - { - process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } - catch(IOException e) - { - e.printStackTrace(); - } - catch( InterruptedException e ) - { - e.printStackTrace(); - } - finally - { - // DR#10955 - if (process != null) - { - process.destroy(); - } - } - } -// -------------------------------------------------------------- - private void translateToXml(String basinId, String extractFileName, Document outputXmlDoc) - { - File file = new File(extractFileName); - - int sleepLimit = 15; - int sleepCount = 0; - - boolean done = false; - long oldLength = 0; - long length = 0; - - while (!done && (sleepCount < sleepLimit) ) - { - try - { - Thread.sleep(1000); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - sleepCount++; - - if (file.exists()) - { - length = file.length(); - if (length > 0) - { - if (length == oldLength) - { - //_logger.log("length = oldlength = " + length); - done = true; - } - } - } - - oldLength = length; - } - - SacXMLEncoder encoder = new SacXMLEncoder(basinId, extractFileName, outputXmlDoc, _logger); - - try - { - encoder.parse(); - } - catch ( OfsFileParserException e ) - { - exitOnError(); - } - - } - -// -------------------------------------------------------------- - - private void exitOnError() - { - _logger.log( "Error parsing OFS extract file" ); - _logger.log( "Please check the OFS extract files for any problems" ); - _logger.log( "Exiting..." ); -// System.exit( 0 ); - } - -// -------------------------------------------------------------- - private void sendXml(String xmlFilePath, String xmlFileName, String mhsId, String productId) - { - String header = "SshpDataTransferMgr.sendXml(): "; - - /* - # Send product to specific location - # add the one-word description and the office id - # - #echo "Sending file:$FILENAME product_ID:$PRODUCT_ID to *OFFICE* via distributeProduct" >> $LOGNAME - #SUBJECT="*DESCRIPTION* $PRODUCT_ID" - #/awips/fxa/bin/distributeProduct -c SHEFPRODUCT -s "$SUBJECT" -a *OFFICE* $PRODUCT_ID $FILENAME - #RETURN_STATUS=$? - */ - - // String commandString = "/awips/fxa/bin/distributeProduct -c HYDRO_MODEL_DATA -a " + - // mhsId + " " + productId + " " + xmlFileName; - - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - String commandString = dirString + "/run_SSHP_data_send " + xmlFilePath + " " + xmlFileName + " " + mhsId + " " + productId; - -// System.out.println(header + "making system call:" + commandString + ":"); - - Process process = null; - try - { - process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } - catch(IOException e) - { - e.printStackTrace(); - } - catch( InterruptedException e ) - { - e.printStackTrace(); - } - finally - { - // DR#10955 - if (process != null) - { - process.destroy(); - } - } - return; - } -// -------------------------------------------------------------- - - public static void main(String[] argStringArray) - { - if (argStringArray.length >= 4) - { - String controlFilePath = argStringArray[0]; - String extractedDirName = argStringArray[1]; - String processedDirName = argStringArray[2]; - String logDirName = argStringArray[3]; - - SshpDataTransferMgr mgr = new SshpDataTransferMgr(controlFilePath, extractedDirName, processedDirName, logDirName); - - mgr.execute(); - } - else - { - System.out.println("usage: ohd.hseb.sshp.message.SSHPDataTransferManager controlFilePath extractedDirName processedDirName logDirName"); - } - } - -// -------------------------------------------------------------- - - -} //end class SshpDataTransferMgr diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/BasinHrapHelper.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/BasinHrapHelper.java deleted file mode 100644 index 2f028bb907..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/BasinHrapHelper.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.sshp.precip; - -/** - * @author GobsC - * - * Encapsulates the LineSegment definition for a basin - * - */ - - -public class BasinHrapHelper -{ - -// --------------------------------------------------------------------------------------- - - private String _basinId = null; - //private String name = null; - - private double _areaSize = 0; - - private int _rowCount = 0; - - private int _basinHrapRowArray[]; - private int _basinHrapBegColumnArray[]; - private int _basinHrapEndColumnArray[]; - - private int _binCount = 0; - - - private boolean _isValid = false; - - -// --------------------------------------------------------------------------------------- - - public BasinHrapHelper(String basinId, int rowCount) - { - System.out.println("BasinHrapSet() for basinId = " + basinId); - _basinId = basinId; - - _rowCount = rowCount; - - - initializeArraysByRowCount(_rowCount); - - } - -// --------------------------------------------------------------------------------------- - - private void initializeArraysByRowCount(int rowCount) - { - String header = "BasinHrapSet.initializeArraysByRowCount()"; - System.out.println(header + " rowCount = " + rowCount); - - _basinHrapRowArray = new int[_rowCount]; - _basinHrapBegColumnArray = new int[_rowCount]; - _basinHrapEndColumnArray = new int[_rowCount]; - - return; - } - -// --------------------------------------------------------------------------------------- - public boolean isInBounds(int hrapRow, int hrapCol) - { - boolean inBounds = false; - boolean done = false; - - for (int r = 0; r < _basinHrapRowArray.length && (!done) ; r++) - { - int currentRow = _basinHrapRowArray[r]; - - if (currentRow == hrapRow) //note, there can be multiple partial rows for a single hrapRow - { - if ((hrapCol >= _basinHrapBegColumnArray[r]) && - (hrapCol <= _basinHrapEndColumnArray[r])) - { - //found the column we are looking for - inBounds = true; - done = true; - } - - } - else if (currentRow > hrapRow) // gone beyond hrapRow, so we are done - { - done = true; - } - } - - return inBounds; - } -// --------------------------------------------------------------------------------------- -/* - private boolean hasColumn(int hrapRow, int hrapColumn) - { - boolean foundRow = false; - - - for (int i = 0; i < _basinHrapRowArray.length && (! foundRow) ; i++) - { - if ( _basinHrapRowArray[i] == hrapRow) - { - foundRow = true; - - } - - } - return foundRow; - - } -*/ -// --------------------------------------------------------------------------------------- - - public void setBasinId(String basinId) - { - _basinId = basinId; - } -// --------------------------------------------------------------------------------------- - - public String getBasinId() - { - return _basinId; - } -// --------------------------------------------------------------------------------------- - public int getBasinHrapRow(int index) - { - return _basinHrapRowArray[index]; - - } -// --------------------------------------------------------------------------------------- - public void setBasinHrapRow(int index, int rowValue) - { - _basinHrapRowArray[index] = rowValue; - - } -// --------------------------------------------------------------------------------------- - public int getBasinHrapBegColumn(int index) - { - return _basinHrapBegColumnArray[index]; - - } -// --------------------------------------------------------------------------------------- - - public void setBasinHrapBegColumn(int index, int colValue) - { - _basinHrapBegColumnArray[index] = colValue; - - } - -/// --------------------------------------------------------------------------------------- - - - public int getBasinHrapEndColumn(int index) - { - return _basinHrapEndColumnArray[index]; - - } -// --------------------------------------------------------------------------------------- - - public void setBasinHrapEndColumn(int index, int colValue) - { - _basinHrapEndColumnArray[index] = colValue; - - } -// --------------------------------------------------------------------------------------- - - public int getBasinNorthernRow() - { - int lastIndex = _basinHrapRowArray.length - 1; - return _basinHrapRowArray[lastIndex]; - } -// --------------------------------------------------------------------------------------- - - public int getBasinSouthernRow() - { - - return _basinHrapRowArray[0]; - - } -// --------------------------------------------------------------------------------------- - public double getAreaSize() - { - return _areaSize; - - } - -// --------------------------------------------------------------------------------------- - public void setAreaSize(double areaSize) - { - _areaSize = areaSize; - - return; - } - -// --------------------------------------------------------------------------------------- - - public void setIsValid(boolean isValid) - { - _isValid = isValid; - } - -// --------------------------------------------------------------------------------------- - - public boolean isValid() - { - return _isValid; - } -// --------------------------------------------------------------------------------------- - - public void setRowCount(int rowCount) - { - _rowCount = rowCount; - } - // --------------------------------------------------------------------------------------- - - public int getRowCount() - { - return _rowCount; - } -// --------------------------------------------------------------------------------------- - - public void setBinCount(int binCount) - { - _binCount = binCount; - } - // --------------------------------------------------------------------------------------- - - public int getBinCount() - { - return _binCount; - } -// --------------------------------------------------------------------------------------- - public String toString() - { - - StringBuffer buffer = new StringBuffer(); - - buffer.append("BasinId = " + _basinId + "\n"); - - for (int i = 0; i < _rowCount; i++) - { - - buffer.append(" row = " + _basinHrapRowArray[i] + " cols = " + - _basinHrapBegColumnArray[i] + - " to " +_basinHrapEndColumnArray[i] + "\n"); - - - - } - - return buffer.toString(); - } - - -// --------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java deleted file mode 100644 index 051adad09e..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Created on 5/24/04 - * Last major change on 7/23/04 - */ - -package ohd.hseb.sshp.precip; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -/** - * @author Chip Gobs This is the MAPPreprocessor for OB7.2. It not only can - * process the traditional MPE best estimate files, but can also process - * the RFC MOSAIC files. - * - */ -public class MAPPreprocessor { - private static final String _className = "MAPPreprocessor"; - - private static final double _timeSeriesMissingValue = -9999.0; - - private DataMgr _dataMgr = null; - - private String _mpeQpeGridDirName = null; - - private String _rfcQpeGridDirName = null; - - private String _bestQpeDateFormatFromToken = null; - - private String _sshpMapQpeToUseTokenValueString = null; - - SimpleDateFormat _localXmrgFileDateFormat = null; - - SimpleDateFormat _rfcXmrgFileDateFormat = null; - - // QPE usage - private int _qpeUsage = MIXED_QPE; - - private static final int RFC_QPE = 0; - - private static final int MIXED_QPE = 1; - - private static final int LOCAL_BEST_QPE = 2; - - private static final String _rfcOnlyString = "RFC_ONLY"; - - private static final String _mixedString = "MIXED"; - - private static final String _localBestOnlyString = "LOCAL_BEST_ONLY"; - - private List _areaIdList = null; - - private List _basinHrapHelperList = null; - - private Logger _logger = null; - - // ---------------------------------------------------------------------------- - - public MAPPreprocessor(DataMgr dataMgr, Logger logger) { - _dataMgr = dataMgr; - _logger = logger; - - readAppsDefaults(); - - // load all the areas that are suitable for use as SSHP basins - _areaIdList = _dataMgr.loadAllSshpBasinIds(); - - // let the db manager add rows to ingest filter as needed - _dataMgr.saveMapRowsToIngestFilterAsNeeded(_areaIdList); - - // load the basinHrapHelpers and return them in a List - _basinHrapHelperList = getBasinHrapHelperList(_areaIdList); - - return; - } - - // ---------------------------------------------------------------------------- - - private void readAppsDefaults() { - String header = "MAPPreprocessor.readAppsDefaults()"; - AppsDefaults ad = AppsDefaults.getInstance(); - - // determine grid directories - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir"); - _rfcQpeGridDirName = ad.getToken("gaq_xmrg_1hr_dir"); - - // create the appropriate SimpleDateFormat objects - _bestQpeDateFormatFromToken = ad.getToken("st3_date_form"); - if (_bestQpeDateFormatFromToken != null) { - if (_bestQpeDateFormatFromToken.equals("Ymd")) { - _localXmrgFileDateFormat = new SimpleDateFormat( - "'xmrg'yyyyMMddHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone - .getTimeZone("GMT")); - - } else // mdY , this is the way .Apps_Defaults delivers it. Strange, - // huh? - { - _localXmrgFileDateFormat = new SimpleDateFormat( - "'xmrg'MMddyyyyHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone - .getTimeZone("GMT")); - } - } else // token was null - { - _localXmrgFileDateFormat = new SimpleDateFormat( - "'xmrg'MMddyyyyHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - } - - // rfc mosaic file name format - _rfcXmrgFileDateFormat = new SimpleDateFormat( - "'RFCMOSAIC01'yyyyMMddHH'z'"); - _rfcXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - // default value to use both best local and rfc data, - // with the rfc data favored - _qpeUsage = MIXED_QPE; - - _sshpMapQpeToUseTokenValueString = ad.getToken("sshp_map_qpe_to_use"); - - if (_sshpMapQpeToUseTokenValueString != null) { - if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_mixedString)) { - _qpeUsage = MIXED_QPE; - _logger.log(header + "_qpeUsage is MIXED_QPE"); - } else if (_sshpMapQpeToUseTokenValueString - .equalsIgnoreCase(_localBestOnlyString)) { - _qpeUsage = LOCAL_BEST_QPE; - _logger.log(header + "_qpeUsage is LOCAL_BEST_QPE"); - } else if (_sshpMapQpeToUseTokenValueString - .equalsIgnoreCase(_rfcOnlyString)) { - _qpeUsage = RFC_QPE; - _logger.log(header + "_qpeUsage is RFC_QPE"); - } - } - } - - // ---------------------------------------------------------------------------- - - public void preprocessAll() { - - String header = "MAPPreprocessor.preprocessAll():"; - _logger.log("Beginning Preprocessing"); - CodeTimer timer = new CodeTimer(_logger); - - // find the latest posting time in the ArealObs table - long latestPostingTime = _dataMgr - .getLatestPostingTimeForMAPPreprocessor(); - - String latestPostingTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(latestPostingTime); - - _logger.log(header + "latestPostingTime = " + latestPostingTimeString); - - // handle the local best estimate qpe files - if ((_qpeUsage == LOCAL_BEST_QPE) || (_qpeUsage == MIXED_QPE)) { - - // based on that latestPostingTime, find the times of all the newer - // Xmrg files from - // the locally-run MPE - List localFileTimeList = _dataMgr - .getNewerBestQpeXmrgFileTimeList(latestPostingTime); - - preprocessQpeFiles(localFileTimeList, _localXmrgFileDateFormat, - _mpeQpeGridDirName); - } - - // handle the RFC files - if ((_qpeUsage == RFC_QPE) || (_qpeUsage == MIXED_QPE)) { - - List rfcFileTimeList = _dataMgr.getNewerRfcXmrgFileTimeList( - latestPostingTime, _rfcQpeGridDirName, - _rfcXmrgFileDateFormat); - // // RFCMOSAIC012006060411 - preprocessQpeFiles(rfcFileTimeList, _rfcXmrgFileDateFormat, - _rfcQpeGridDirName); - - } - _logger.log("Preprocessing complete."); - - return; - } // preprocessAll - - // ---------------------------------------------------------------------------- - private void preprocessQpeFiles(List timeList, DateFormat dateFormat, - String baseDirectory) { - String header = "preprocessQpeFiles(): "; - // create an Xmrg file reader - XmrgReader reader = new XmrgReader(_logger); - - _logger.log(header + "baseDirectory = " + baseDirectory); - - // for each re-run hour of input - for (int i = 0; i < timeList.size(); i++) { - Long timeLong = (Long) timeList.get(i); - long time = timeLong.longValue(); - - String gridFileName = dateFormat.format(new Date(time)); - String fullGridPath = baseDirectory + "/" + gridFileName; - - String timeString = DbTimeHelper - .getDateTimeStringFromLongTime(time); - - XmrgGrid grid = reader.loadGrid(time, fullGridPath); - - if (grid.isValid()) { - _logger.log(header + "grid for time = " + timeString - + " is VALID "); - - // for each basin, process its data - for (int j = 0; j < _basinHrapHelperList.size(); j++) { - BasinHrapHelper basinHrapHelper = (BasinHrapHelper) _basinHrapHelperList - .get(j); - - preprocess(basinHrapHelper, grid); - } - } else { - // _logger.log(header + "grid for time = " + timeString + - // " is invalid"); - } - } - - } - - // ---------------------------------------------------------------------------- - - public void preprocess(BasinHrapHelper basinHrapHelper, XmrgGrid grid) { - String areaId = basinHrapHelper.getBasinId(); - - Measurement mapMeasurement = getMAPMeasurementFromGrid(basinHrapHelper, - grid); - - _dataMgr.saveMapMeasurement(areaId, mapMeasurement, grid.getTime(), - _logger); - - return; - - } - - // ---------------------------------------------------------------------------- - private Measurement getMAPMeasurementFromGrid( - BasinHrapHelper basinHrapHelper, XmrgGrid grid) { - String header = "MAPPreprocessor.getMAPMeasurementFromGrid(): "; - MeasuringUnit precipUnit = MeasuringUnit.inches; - double mapValue = -1.0; - double binValue = 0; - double totalValue = 0; - int validValueCount = 0; - - // CHANGE 8/23/05 - _logger.log(header + " for basinId = " + basinHrapHelper.getBasinId()); - - int rowCount = basinHrapHelper.getRowCount(); - - boolean gridAccessProblem = false; - - // for each row - for (int i = 0; (i < rowCount && !gridAccessProblem); i++) { - int hrapRow = basinHrapHelper.getBasinHrapRow(i); - - // for each column - for (int hrapCol = basinHrapHelper.getBasinHrapBegColumn(i); ((hrapCol <= basinHrapHelper - .getBasinHrapEndColumn(i)) && (!gridAccessProblem)); hrapCol++) { - // yank out the bin value at that point - binValue = grid.getValue(hrapRow, hrapCol); - if (binValue >= 0.0) { - totalValue += binValue; - validValueCount++; - } else if (binValue == XmrgGrid.OFF_GRID_VALUE) { - _logger - .log(header - + "Problem with basinId = " - + basinHrapHelper.getBasinId() - + " attempting to access out of bounds grid location row = " - + hrapRow + " and column = " + hrapCol - + "."); - gridAccessProblem = true; - - } - } - } - - // if some kind of failure occured - Measurement mapMeasurement = null; - if ((validValueCount < 1) || (gridAccessProblem)) { - mapValue = _timeSeriesMissingValue; - mapMeasurement = new Measurement(mapValue, precipUnit); - mapMeasurement.setIsMissing(true); - // System.out.println(header + "for " + basinHrapHelper.getBasinId() - // + " totalValue = " + totalValue + " validValueCount = " + - // validValueCount); - } else // success occured, so create a decent measurement - { - // System.out.println(header + "for " + basinHrapHelper.getBasinId() - // + " totalValue = " + totalValue + " validValueCount = " + - // validValueCount); - mapValue = totalValue / validValueCount; - if (mapValue < 0.005) { - mapValue = 0.0; - } - mapMeasurement = new Measurement(mapValue, precipUnit); - } - - return mapMeasurement; - - } - - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------- - private List getBasinHrapHelperList(List areaIdList) { - List basinHrapHelperList = new ArrayList(); - for (int i = 0; i < areaIdList.size(); i++) { - String areaId = (String) areaIdList.get(i); - - BasinHrapHelper helper = _dataMgr.loadBasinHrapHelper(areaId); - - if (helper != null) { - // _logger.log(helper.toString()); - - basinHrapHelperList.add(helper); - } - } - - return basinHrapHelperList; - - } - - // ---------------------------------------------------------------------------- - - @Override - public void finalize() { - try { - _dataMgr.disconnect(); - _logger.close(); - } catch (Throwable t) { - System.err.println(t.getMessage()); - } - - } - - // ---------------------------------------------------------------------------- - - public static void main(String[] argArray) { - MAPPreprocessor preprocessor = null; - String baseConnectionString = argArray[0]; - - // initialize the logging - String logFileDir = argArray[1]; - String logFilePath = logFileDir + "/" + _className + ".log"; - Logger logger = new FileLogger(logFilePath, true, true); - - logger.log("Initializing " + _className); - - // start the clock on the timer - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - // initialize the database connection - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - // create a new MAPPreprocessor instance and preprocess all the - // unprocessed - // XMRG files. - preprocessor = new MAPPreprocessor(dataMgr, logger); - preprocessor.preprocessAll(); - - timer.stop("All of Processing for " + _className + " took "); - - preprocessor.finalize(); - - return; - } - // ---------------------------------------------------------------------------- - -} // MAPPreprocessor diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java.new b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java.new deleted file mode 100644 index 603ee2f042..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java.new +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Created on 5/24/04 - * Last major change on 7/23/04 -*/ - -package ohd.hseb.sshp.precip; - - -import ohd.hseb.sshp.DataMgr; -//import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.*; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - - -import java.text.SimpleDateFormat; -import java.util.*; - - -/** - * @author Chip Gobs - * This is the MAPPreprocessor for OB6. - * It reads each MPE QPE file only one time. - * It is the 3rd version of the MAPPreprocessor - * - */ -public class MAPPreprocessor -{ - private static final String _className = "MAPPreprocessor"; - private static final double _timeSeriesMissingValue = -9999.0; - - private DataMgr _dataMgr = null; - - private String _mpeQpeGridDirName = null; - - //private long _startTime = 0; - //private long _endTime = 0; - private List _areaIdList = null; - - - private List _basinHrapHelperList = null; - - private Logger _logger = null; - - // ---------------------------------------------------------------------------- - - public MAPPreprocessor(DataMgr dataMgr, Logger logger) - { - _dataMgr = dataMgr; - _logger = logger; - - readAppsDefaults(); - - // load all the areas that are suitable for use as SSHP basins - _areaIdList = _dataMgr.loadAllSshpBasinIds(); - - //let the db manager add rows to ingest filter as needed - _dataMgr.saveMapRowsToIngestFilterAsNeeded(_areaIdList); - - //load the basinHrapHelpers and return them in a List - _basinHrapHelperList = getBasinHrapHelperList(_areaIdList); - - - return; - } - - // ---------------------------------------------------------------------------- - - private void readAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir"); - if (_mpeQpeGridDirName == null) - { - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir".toUpperCase()); - } - - } - - // ---------------------------------------------------------------------------- - - public void preprocessAll() - { - - String header = "MAPPreprocessor.preprocessAll():"; - _logger.log("Beginning Preprocessing"); - CodeTimer timer = new CodeTimer(_logger); - - //find the latest posting time in the ArealObsPrecip table - long latestPostingTime = _dataMgr.getLatestObsTimeForMAPPreprocessor(); - - // based on that latestPostingTime, find the times of all the newer Xmrg files from - // the locally-run MPE - List localFileTimeList = _dataMgr.getNewerXmrgFileTimeList(latestPostingTime); - - // create an Xmrg file reader - XmrgReader reader = new XmrgReader(_logger); - - SimpleDateFormat xmrgFileDateFormat = new SimpleDateFormat("'xmrg'MMddyyyyHH'z'"); - xmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - - // for each re-run hour of input - for (int i = 0; i < localFileTimeList.size(); i++) - { - Long timeLong = (Long) localFileTimeList.get(i); - long time = timeLong.longValue(); - - String gridFileName = xmrgFileDateFormat.format(new Date(time)); - String fullGridPath = _mpeQpeGridDirName + "/" + gridFileName; - - // String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - // timer.start(); - XmrgGrid grid = reader.loadGrid(time, fullGridPath); - // timer.stop(header + "Reading the whole grid for time =" + timeString + " took "); - - - if (grid.isValid()) - { - // _logger.log(header + "grid for time = " + timeString + " is VALID "); - - // for each basin, process its data - for (int j = 0; j < _basinHrapHelperList.size(); j++) - { - BasinHrapHelper basinHrapHelper = (BasinHrapHelper) _basinHrapHelperList.get(j); - - preprocess(basinHrapHelper, grid); - } - } - else - { - // _logger.log(header + "grid for time = " + timeString + " is invalid"); - } - } - - _logger.log("Preprocessing complete."); - - return; - } // preprocessAll - - - // ---------------------------------------------------------------------------- - - public void preprocess(BasinHrapHelper basinHrapHelper, XmrgGrid grid) - { - String areaId = basinHrapHelper.getBasinId(); - - - // CodeTimer timer = new CodeTimer(_logger); - // timer.start(); - - Measurement mapMeasurement = getMAPMeasurementFromGrid(basinHrapHelper, grid); - - // timer.stop("calculating the MAP from the grid took "); - - - - // _accumulatedSaveTimer.restart(); - _dataMgr.saveMapMeasurement(areaId, mapMeasurement, grid.getTime(), _logger); - // _accumulatedSaveTimer.stop("accumulated saving the MAP measurement to the database so far has taken "); - - return; - - } - - // ---------------------------------------------------------------------------- - private Measurement getMAPMeasurementFromGrid(BasinHrapHelper basinHrapHelper, XmrgGrid grid) - { - String header = "MAPPreprocessor.getMAPMeasurementFromGrid(): "; - MeasuringUnit precipUnit = MeasuringUnit.inches; - double mapValue = -1.0; - double binValue = 0; - double totalValue = 0; - int validValueCount = 0; - - // CHANGE 8/23/05 - _logger.log(header + " for basinId = " + basinHrapHelper.getBasinId()); - - int rowCount = basinHrapHelper.getRowCount(); - - boolean gridAccessProblem = false; - - //for each row - for (int i = 0; (i < rowCount && !gridAccessProblem) ; i++) - { - int hrapRow = basinHrapHelper.getBasinHrapRow(i); - - // for each column - for (int hrapCol = basinHrapHelper.getBasinHrapBegColumn(i); - ( (hrapCol <= basinHrapHelper.getBasinHrapEndColumn(i)) && - (!gridAccessProblem)); - hrapCol++) - { - //yank out the bin value at that point - binValue = grid.getValue(hrapRow, hrapCol); - if (binValue >= 0.0) - { - totalValue += binValue; - validValueCount++; - } - else if (binValue == XmrgGrid.OFF_GRID_VALUE) - { - _logger.log(header + "Problem with basinId = " + basinHrapHelper.getBasinId() + - " attempting to access out of bounds grid location row = " + - hrapRow + " and column = " + hrapCol + "."); - gridAccessProblem = true; - - } - } - } - - - // if some kind of failure occured - Measurement mapMeasurement = null; - if ( (validValueCount < 1) || (gridAccessProblem) ) - { - mapValue = _timeSeriesMissingValue; - mapMeasurement = new Measurement(mapValue, precipUnit); - mapMeasurement.setIsMissing(true); - // System.out.println(header + "for " + basinHrapHelper.getBasinId() + " totalValue = " + totalValue + " validValueCount = " + validValueCount); - } - else //success occured, so create a decent measurement - { - //System.out.println(header + "for " + basinHrapHelper.getBasinId() + " totalValue = " + totalValue + " validValueCount = " + validValueCount); - mapValue = totalValue / validValueCount; - if (mapValue < 0.005) - { - mapValue = 0.0; - } - mapMeasurement = new Measurement(mapValue, precipUnit); - } - - - - return mapMeasurement; - - } - - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------- - private List getBasinHrapHelperList(List areaIdList) - { - List basinHrapHelperList = new ArrayList(); - for (int i = 0; i < areaIdList.size(); i++) - { - String areaId = (String ) areaIdList.get(i); - - BasinHrapHelper helper = _dataMgr.loadBasinHrapHelper(areaId); - - if (helper != null) - { - //_logger.log(helper.toString()); - - basinHrapHelperList.add(helper); - } - } - - - return basinHrapHelperList; - - } - // ---------------------------------------------------------------------------- - - public void finalize() - { - try - { - _dataMgr.disconnect(); - _logger.close(); - } - catch (Throwable t) - { - System.err.println(t.getMessage()); - } - - - } - // ---------------------------------------------------------------------------- - - public static void main(String[] argArray) - { - MAPPreprocessor preprocessor = null; - String baseConnectionString = argArray[0]; - - //initialize the logging - String logFileDir = argArray[1]; - String logFilePath = logFileDir + "/" + _className + ".log"; - Logger logger = new FileLogger(logFilePath, true, true); - - logger.log("Initializing " + _className); - - // start the clock on the timer - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - //initialize the database connection - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - //create a new MAPPreprocessor instance and preprocess all the unprocessed - //XMRG files. - preprocessor = new MAPPreprocessor(dataMgr, logger); - preprocessor.preprocessAll(); - - timer.stop("All of Processing for " + _className + " took "); - - preprocessor.finalize(); - - return; - } - // ---------------------------------------------------------------------------- - -} //MAPPreprocessor diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java deleted file mode 100644 index a4305a6bf9..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Created on May 24, 2004 - * - * - */ -package ohd.hseb.sshp.precip; - - -//import java.util.*; // needed for Vector class -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.text.SimpleDateFormat; - -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.EndianConverter; -import ohd.hseb.util.Logger; - -//import whfs.db.gen.*; - - -public class XmrgReader -{ - - // each value was stored in mm of precip times 100 - // Conversion factor needed to convert (mm x 100) to inches - // need to divide by 2540.0 (25.4mm/inch x 100) to get inches - private static final double _CONVERSION_FACTOR = 2540.0; - private static final double _missingValue = -999.0; - - private String _mpeQpeGridDirName = null; - private SimpleDateFormat _xmrgFileDateFormat = null; - private boolean _needEndianChange = false; - - // I may be able to turn these into local variables - private int _numBinsPerColXmrg=0; - private int _numBinsPerRowXmrg=0; - - private int _swHrapRowXmrg=0; - private int _swHrapColXmrg=0; - - private int _southernRowXmrg = 0; - private int _northernRowXmrg = 0; - private int _westernColXmrg = 0; - private int _easternColXmrg = 0; - - private Logger _logger; - //private CodeTimer _loadGridAccumulatedTimer = null; - //private CodeTimer _readLoopAccumulatedTimer = null; - //private CodeTimer _readSetAccumulatedTimer = null; - - -// ----------------------------------------------------------------------------------- - - public XmrgReader(Logger logger) - { - _logger = logger; - } -// ----------------------------------------------------------------------------------- - - public XmrgGrid loadGrid(long time, String gridFileName) - { - - XmrgGrid grid = readMPEGridFile(time, gridFileName); - - return grid; - } -// ----------------------------------------------------------------------------------- - private DataInputStream initDataInputStream(String fullGridFilePath) - { - String header = "XmrgReader.initDataInputStream: "; - - DataInputStream dis = null; - - boolean normalMode = true; - - CodeTimer timer = new CodeTimer(_logger); - - - try - { - - if (normalMode) - { - // timer.start(); - FileInputStream fis = new FileInputStream(fullGridFilePath); - BufferedInputStream bis = new BufferedInputStream(fis); - dis = new DataInputStream(bis); - //timer.stop(header + "init of 'normal' reading " ); - - } - - else // "faster" mode - { - // timer.start(); - - FileInputStream fis = new FileInputStream(fullGridFilePath); - - int byteCount = fis.available(); - byte[] byteArray = new byte[byteCount]; - - fis.read(byteArray); - fis.close(); - - ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); - dis = new DataInputStream(bais); - - //timer.stop(header + "init of 'faster' reading " + byteCount + " bytes from the file " + fullGridFilePath + " took "); - - } - } - catch (java.io.IOException e) - { - e.printStackTrace(_logger.getPrintWriter()); - } - - return dis; - - } -// ----------------------------------------------------------------------------------- - - private XmrgGrid readMPEGridFile(long gridTime, String gridFileName) - { - XmrgGrid grid = null; - - String header = "XmrgReaderFaster.readMPEGridFile(): "; - - String fullGridFilePath; - - if (_mpeQpeGridDirName != null) - fullGridFilePath = _mpeQpeGridDirName + "/" + gridFileName.trim(); - else - fullGridFilePath = gridFileName.trim(); - - File xmrgFile = new File(fullGridFilePath); - - - if (xmrgFile.exists()) - { - try - { - - DataInputStream dis = initDataInputStream(fullGridFilePath); - - int numBytesRecordBegin; - int numBytesRecordEnd; - - // read in the first header of the xmrg file which contains - // the SouthWest HRAP column, row, # of columns and # of rows - numBytesRecordBegin = dis.readInt(); - - // System.out.println(header + "raw numBytesRecordBegin = " + numBytesRecordBegin); - - - //determine endianess - if (numBytesRecordBegin == 16) - { - _needEndianChange = false; - // System.out.println(header + "good raw numBytesRecordBegin = " + numBytesRecordBegin); - - } - else - { - _needEndianChange = true; - numBytesRecordBegin = EndianConverter.convert(numBytesRecordBegin); - // System.out.println(header + "converted raw numBytesRecordBegin = " + numBytesRecordBegin); - } - - _swHrapColXmrg = readInt(dis); - _swHrapRowXmrg = readInt(dis); - - - - /* - System.out.println(header + "XOR = " + swHrapColXmrg + - " YOR = " + swHrapRowXmrg); - */ - - _numBinsPerRowXmrg = readInt(dis); - - if ( (_numBinsPerRowXmrg < 1) || (_numBinsPerRowXmrg > 1000) ) - { - _logger.log("Error: The number of HRAP Bins Per Row for " + fullGridFilePath + " is " + _numBinsPerRowXmrg); - _logger.log(" Note: This number should be in the range of 1 - 1000. This MPE xmrg file is being skipped."); - return XmrgGrid.getInvalidGrid(gridTime); - } - - _numBinsPerColXmrg = readInt(dis); - - - - - if ( (_numBinsPerColXmrg < 1) || (_numBinsPerColXmrg > 1000) ) - { - _logger.log("Error: The number of HRAP Bins Per Col for " + fullGridFilePath + " is " + _numBinsPerColXmrg); - _logger.log(" Note: This number should be in the range of 1 - 1000. This MPE xmrg file is being skipped."); - return( XmrgGrid.getInvalidGrid(gridTime)); - } - - numBytesRecordEnd = readInt(dis); - - // System.out.println("XOR=" + swHrapColXmrg + " YOR=" + swHrapRowXmrg + - // " MAXX=" + numBinsPerRowXmrg + " MAXY=" + numBinsPerColXmrg); - - // calculate the Southern and Northern most rows of the XMRG file - _southernRowXmrg = _swHrapRowXmrg; - _northernRowXmrg = _southernRowXmrg + _numBinsPerColXmrg - 1; - - // calculate the Western and Eastern most columns of the XMRG file - _westernColXmrg = _swHrapColXmrg; - _easternColXmrg = _westernColXmrg + _numBinsPerRowXmrg - 1; - - - int rowCount = _numBinsPerColXmrg; - int colCount = _numBinsPerRowXmrg; - - grid = new XmrgGrid(gridTime, - _southernRowXmrg, _westernColXmrg, - rowCount, colCount); - - // read in the second header of the xmrg file which contains - // the userid, saved date, process flag, valid date, - // maximum value and version number and throw them away - numBytesRecordBegin = readInt(dis); - numBytesRecordEnd = dis.skipBytes(numBytesRecordBegin); - numBytesRecordEnd = readInt(dis); - - double value = _missingValue; - - - // _readLoopAccumulatedTimer.restart(); - - for (int hrapRow = _southernRowXmrg; hrapRow <= _northernRowXmrg && grid.isValid(); hrapRow++) - { - numBytesRecordBegin = readInt(dis); - // IF numBytesRecordBegin NOT EQUAL TO TWICE numBinsPerRowXmrg THEN BAIL - if ( numBytesRecordBegin != (_numBinsPerRowXmrg * 2) ) - { - _logger.log("Error: The number of bytes per record " + numBytesRecordBegin + - " should be twice the number of bins per row " + _numBinsPerRowXmrg ); - grid.setIsValid(false); - - } - - // if ( (ctrRows < firstRowToBeRead) || (ctrRows > lastRowToBeRead) ) - // numBytesRecordEnd = dis.skipBytes(numBytesRecordBegin); - // else - - - - for (int hrapCol=_westernColXmrg; hrapCol <= _easternColXmrg && grid.isValid(); hrapCol++) - { - value = (double)readShort(dis); - - - if (value != _missingValue) - { - value /= _CONVERSION_FACTOR; - // _readSetAccumulatedTimer.restart(); - grid.setValue(hrapRow, hrapCol, value); - // _readSetAccumulatedTimer.stop(); - } - else - { - grid.setValue(hrapRow, hrapCol, _missingValue); - // System.out.println("value at " + hrapRow + ", " + hrapCol + " is missing"); - } - } - - numBytesRecordEnd = readInt(dis); - } - // _readLoopAccumulatedTimer.stop("The total time in the nested for loop took "); - // _logger.log("The total accumulated time of grid.setValue() is " + _readSetAccumulatedTimer.getElapsedTime()); - /* - for (int ctr=0; ctr 0.0) - System.out.println("gridValue[" + ctr + "]=" + gridValues[ctr]); - } - */ - - dis.close(); - } - catch(EOFException ioe) - { - _logger.log( "Read End Of File" + ioe); - grid.setIsValid(false); - } - catch(IOException ioe) - { - _logger.log( "Something went wrong trying to read " + ioe); - grid.setIsValid(false); - } - } - else - { - //_logger.log("\nWarning: file " + gridFileName + " does NOT Exist!"); - grid = XmrgGrid.getInvalidGrid(gridTime); - } - - - return grid; - - } // end of readMPEGridFile method - -// ----------------------------------------------------------------------------------- - - -// ---------------------------------------------------- - private int readInt(DataInputStream dis) throws IOException - { - int value = dis.readInt(); - - if (_needEndianChange) - { - value = EndianConverter.convert(value); - } - return value; - } -// ---------------------------------------------------- - - private short readShort(DataInputStream dis) throws IOException - { - short value = dis.readShort(); - - if (_needEndianChange) - { - value = EndianConverter.convert(value); - } - return value; - } - // ---------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java.new b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java.new deleted file mode 100644 index e51af96315..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java.new +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Created on May 24, 2004 - * - * - */ -package ohd.hseb.sshp.precip; - - -//import java.util.*; // needed for Vector class -import java.io.*; // needed for ByteArrayInputStream - -import java.text.SimpleDateFormat; // needed for SimpleDateFormat class - -//import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.EndianConverter; -import ohd.hseb.util.Logger; - -//import whfs.db.gen.*; - - -public class XmrgReader -{ - - // each value was stored in mm of precip times 100 - // Conversion factor needed to convert (mm x 100) to inches - // need to divide by 2540.0 (25.4mm/inch x 100) to get inches - private final double _CONVERSION_FACTOR = 2540.0; - - - private static final double _missingValue = -999.0; - - private String _mpeQpeGridDirName = null; - - private SimpleDateFormat _xmrgFileDateFormat = null; - - private boolean _needEndianChange = false; - - - - // I may be able to turn these into local variables - - private int _numBinsPerColXmrg=0; - private int _numBinsPerRowXmrg=0; - - //private int _numRows = 0; - // private int _numCols = 0; - - private int _swHrapRowXmrg=0; - private int _swHrapColXmrg=0; - - private int _southernRowXmrg = 0; - private int _northernRowXmrg = 0; - private int _westernColXmrg = 0; - private int _easternColXmrg = 0; - - private Logger _logger; - //private CodeTimer _loadGridAccumulatedTimer = null; - //private CodeTimer _readLoopAccumulatedTimer = null; - //private CodeTimer _readSetAccumulatedTimer = null; - - -// ----------------------------------------------------------------------------------- - - public XmrgReader(Logger logger) - { - _logger = logger; - /* - _xmrgFileDateFormat = new SimpleDateFormat("'xmrg'MMddyyyyHH'z'"); - _xmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - AppsDefaults ad = new AppsDefaults(); - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir"); - if (_mpeQpeGridDirName == null) - { - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir".toUpperCase()); - } - - _logger.log("rfcwide_xmrg_dir = "+ _mpeQpeGridDirName); - */ - - - // _loadGridAccumulatedTimer = new CodeTimer(_logger); - // _readLoopAccumulatedTimer = new CodeTimer(_logger); - // _readSetAccumulatedTimer = new CodeTimer(_logger); - - - } -// ----------------------------------------------------------------------------------- - - public XmrgGrid loadGrid(long time, String gridFileName) - { - - XmrgGrid grid = readMPEGridFile(time, gridFileName); - - return grid; - } -// ----------------------------------------------------------------------------------- - private DataInputStream initDataInputStream(String fullGridFilePath) - { - String header = "XmrgReader.initDataInputStream: "; - - DataInputStream dis = null; - - boolean normalMode = true; - - CodeTimer timer = new CodeTimer(_logger); - - - try - { - - if (normalMode) - { - // timer.start(); - FileInputStream fis = new FileInputStream(fullGridFilePath); - BufferedInputStream bis = new BufferedInputStream(fis); - dis = new DataInputStream(bis); - //timer.stop(header + "init of 'normal' reading " ); - - } - - else // "faster" mode - { - // timer.start(); - - FileInputStream fis = new FileInputStream(fullGridFilePath); - - int byteCount = fis.available(); - byte[] byteArray = new byte[byteCount]; - - fis.read(byteArray); - fis.close(); - - ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); - dis = new DataInputStream(bais); - - //timer.stop(header + "init of 'faster' reading " + byteCount + " bytes from the file " + fullGridFilePath + " took "); - - } - } - catch (java.io.IOException e) - { - e.printStackTrace(_logger.getPrintWriter()); - } - - return dis; - - } -// ----------------------------------------------------------------------------------- - - private XmrgGrid readMPEGridFile(long gridTime, String gridFileName) - { - XmrgGrid grid = null; - - String header = "XmrgReaderFaster.readMPEGridFile(): "; - - String fullGridFilePath; - - if (_mpeQpeGridDirName != null) - fullGridFilePath = _mpeQpeGridDirName + "/" + gridFileName.trim(); - else - fullGridFilePath = gridFileName.trim(); - - File xmrgFile = new File(fullGridFilePath); - - - if (xmrgFile.exists()) - { - try - { - - DataInputStream dis = initDataInputStream(fullGridFilePath); - - int numBytesRecordBegin; - int numBytesRecordEnd; - - // read in the first header of the xmrg file which contains - // the SouthWest HRAP column, row, # of columns and # of rows - numBytesRecordBegin = dis.readInt(); - - // System.out.println(header + "raw numBytesRecordBegin = " + numBytesRecordBegin); - - - //determine endianess - if (numBytesRecordBegin == 16) - { - _needEndianChange = false; - // System.out.println(header + "good raw numBytesRecordBegin = " + numBytesRecordBegin); - - } - else - { - _needEndianChange = true; - numBytesRecordBegin = EndianConverter.convert(numBytesRecordBegin); - // System.out.println(header + "converted raw numBytesRecordBegin = " + numBytesRecordBegin); - } - - _swHrapColXmrg = readInt(dis); - _swHrapRowXmrg = readInt(dis); - - - - /* - System.out.println(header + "XOR = " + swHrapColXmrg + - " YOR = " + swHrapRowXmrg); - */ - - _numBinsPerRowXmrg = readInt(dis); - - if ( (_numBinsPerRowXmrg < 1) || (_numBinsPerRowXmrg > 1000) ) - { - _logger.log("Error: The number of HRAP Bins Per Row for " + fullGridFilePath + " is " + _numBinsPerRowXmrg); - _logger.log(" Note: This number should be in the range of 1 - 1000. This MPE xmrg file is being skipped."); - return XmrgGrid.getInvalidGrid(gridTime); - } - - _numBinsPerColXmrg = readInt(dis); - - - - - if ( (_numBinsPerColXmrg < 1) || (_numBinsPerColXmrg > 1000) ) - { - _logger.log("Error: The number of HRAP Bins Per Col for " + fullGridFilePath + " is " + _numBinsPerColXmrg); - _logger.log(" Note: This number should be in the range of 1 - 1000. This MPE xmrg file is being skipped."); - return( XmrgGrid.getInvalidGrid(gridTime)); - } - - numBytesRecordEnd = readInt(dis); - - // System.out.println("XOR=" + swHrapColXmrg + " YOR=" + swHrapRowXmrg + - // " MAXX=" + numBinsPerRowXmrg + " MAXY=" + numBinsPerColXmrg); - - // calculate the Southern and Northern most rows of the XMRG file - _southernRowXmrg = _swHrapRowXmrg; - _northernRowXmrg = _southernRowXmrg + _numBinsPerColXmrg - 1; - - // calculate the Western and Eastern most columns of the XMRG file - _westernColXmrg = _swHrapColXmrg; - _easternColXmrg = _westernColXmrg + _numBinsPerRowXmrg - 1; - - - int rowCount = _numBinsPerColXmrg; - int colCount = _numBinsPerRowXmrg; - - grid = new XmrgGrid(gridTime, - _southernRowXmrg, _westernColXmrg, - rowCount, colCount); - - // read in the second header of the xmrg file which contains - // the userid, saved date, process flag, valid date, - // maximum value and version number and throw them away - numBytesRecordBegin = readInt(dis); - numBytesRecordEnd = dis.skipBytes(numBytesRecordBegin); - numBytesRecordEnd = readInt(dis); - - double value = _missingValue; - - - // _readLoopAccumulatedTimer.restart(); - - for (int hrapRow = _southernRowXmrg; hrapRow <= _northernRowXmrg && grid.isValid(); hrapRow++) - { - numBytesRecordBegin = readInt(dis); - // IF numBytesRecordBegin NOT EQUAL TO TWICE numBinsPerRowXmrg THEN BAIL - if ( numBytesRecordBegin != (_numBinsPerRowXmrg * 2) ) - { - _logger.log("Error: The number of bytes per record " + numBytesRecordBegin + - " should be twice the number of bins per row " + _numBinsPerRowXmrg ); - grid.setIsValid(false); - - } - - // if ( (ctrRows < firstRowToBeRead) || (ctrRows > lastRowToBeRead) ) - // numBytesRecordEnd = dis.skipBytes(numBytesRecordBegin); - // else - - - - for (int hrapCol=_westernColXmrg; hrapCol <= _easternColXmrg && grid.isValid(); hrapCol++) - { - value = (double)readShort(dis); - - - if (value != _missingValue) - { - value /= _CONVERSION_FACTOR; - // _readSetAccumulatedTimer.restart(); - grid.setValue(hrapRow, hrapCol, value); - // _readSetAccumulatedTimer.stop(); - } - else - { - grid.setValue(hrapRow, hrapCol, _missingValue); - // System.out.println("value at " + hrapRow + ", " + hrapCol + " is missing"); - } - } - - numBytesRecordEnd = readInt(dis); - } - // _readLoopAccumulatedTimer.stop("The total time in the nested for loop took "); - // _logger.log("The total accumulated time of grid.setValue() is " + _readSetAccumulatedTimer.getElapsedTime()); - /* - for (int ctr=0; ctr 0.0) - System.out.println("gridValue[" + ctr + "]=" + gridValues[ctr]); - } - */ - - dis.close(); - } - catch(EOFException ioe) - { - _logger.log( "Read End Of File" + ioe); - grid.setIsValid(false); - } - catch(IOException ioe) - { - _logger.log( "Something went wrong trying to read " + ioe); - grid.setIsValid(false); - } - } - else - { - //_logger.log("\nWarning: file " + gridFileName + " does NOT Exist!"); - grid = XmrgGrid.getInvalidGrid(gridTime); - } - - - return grid; - - } // end of readMPEGridFile method - -// ----------------------------------------------------------------------------------- - - -// ---------------------------------------------------- - private int readInt(DataInputStream dis) throws IOException - { - int value = dis.readInt(); - - if (_needEndianChange) - { - value = EndianConverter.convert(value); - } - return value; - } -// ---------------------------------------------------- - - private short readShort(DataInputStream dis) throws IOException - { - short value = dis.readShort(); - - if (_needEndianChange) - { - value = EndianConverter.convert(value); - } - return value; - } - // ---------------------------------------------------- - - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/AnalysisWindow.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/AnalysisWindow.java deleted file mode 100644 index 0ea5230159..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/AnalysisWindow.java +++ /dev/null @@ -1,4227 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.AWTException; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Robot; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.awt.event.MouseMotionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.io.File; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.imageio.ImageIO; -import javax.imageio.stream.FileImageOutputStream; -import javax.imageio.stream.ImageOutputStream; -import javax.swing.BorderFactory; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JSpinner; -import javax.swing.JSplitPane; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.border.Border; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.filechooser.FileFilter; - -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.measurement.TimeIntervalMeasurement; -import ohd.hseb.measurement.TimeSeriesEvent; -import ohd.hseb.measurement.TimeSeriesListener; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.sshp.AboutInfo; -import ohd.hseb.sshp.AppController; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.FFHDescriptor; -import ohd.hseb.sshp.SacSmaStateDescriptor; -import ohd.hseb.sshp.StreamModel; -import ohd.hseb.sshp.gui.GuiHelper; -import ohd.hseb.sshp.gui.PrecipPainter; -import ohd.hseb.sshp.gui.PrecipTotalTextPainter; -import ohd.hseb.sshp.gui.SettingPanel; -import ohd.hseb.sshp.gui.SigStageLinePainter; -import ohd.hseb.sshp.gui.StagePainter; -import ohd.hseb.sshp.gui.TimeLinePainter; -import ohd.hseb.sshp.gui.TsBackgroundPainter; -import ohd.hseb.util.CodeTracer; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; -import ohd.hseb.util.gui.StandardImageIcons; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -/** - * @author Chip Gobs - * - * Main Frame for the Precip and Stage Canvases and the application - * itself. - */ -public class AnalysisWindow extends JFrame { - private static final String _className = "AnalysisWindow"; - - private static final double MIN_PRECIP_IN_INCHES_PER_HOUR = 0.0; - - private static final double MAX_PRECIP_IN_INCHES_PER_HOUR = 20.0; - - private static final double MIN_STAGE_IN_FEET = -10.0; - - private static final double MAX_STAGE_IN_FEET = 40000.0; - - private static final double MIN_EVAP_PER_HOUR = 0.0; - - private static final double MAX_EVAP_PER_HOUR = 100.0; - - private static final double MIN_RUNOFF_IN_INCHES_PER_HOUR = 0.0; - - private static final double MAX_RUNOFF_IN_INCHES_PER_HOUR = MAX_PRECIP_IN_INCHES_PER_HOUR; - - private static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - // forecast length and spinner constants - // see StreamModel.java for the default length in hours - private static final int FORECAST_LENGTH_SPINNER_STEPS = 6; - - private static final MeasuringUnit _stageUnit = MeasuringUnit.feet; - - private static final String ALLOW_LIVE_SAC_STATE_ADJUSTMENT_TOKEN_NAME = "sshp_allow_live_state_adjustment"; - - // determines whether to default to showing the simulated time series or not - private static final String SHOW_SIMULATED_TS_TOKEN_NAME = "sshp_show_simulated_timeseries"; - - private static final boolean _default_show_simulated_timeseries = true; - - // image storage directory - private String _whfs_image_directoryString = null; - - private String _sshp_precip_directoryString = null; - - // window sizing data - private Dimension _maxDimension = new Dimension(1280, 1024); - - private Dimension _initialDimension = new Dimension(1200, 944); - - private Dimension _minDimension = new Dimension(800, 700); - - private StreamModel _streamModel = null; - - private AppController _controller = null; - - // the canvases - private TsPaintableCanvas _precipCanvas = null; - - private TsPaintableCanvas _stageCanvas = null; - - // data to be used with the canvases - private int _hoursToShowBeforeModelStartTime = 24; - - private int _hoursToShowAfterModelStartTime = 72; - - // split pane and its direct contents - private JSplitPane _splitPane = null; - - // canvas value mappers - private ValueMapper _precipValueMapper = null; - - private ValueMapper _stageValueMapper = null; - - // these Painters are in this class because of the ability to modify the way - // the canvases are - // painted. The modifications are made in this class. - // The painters have special options which are invoked. Then, upon - // repainting, the - // painter paints in the way dictated by those options. - private SigStageLinePainter _floodStageLinePainter = null; - - private SigStageLinePainter _majorFloodStageLinePainter = null; - - private StagePainter _observedStageTsPainter = null; - - private StagePainter _simulatedStageTsPainter = null; - - private PrecipPainter _precipPainter = null; - - private PrecipTotalTextPainter _precipTextTotalPainter = null; - - private TsBackgroundPainter _stageBackgroundPainter = null; - - private TsBackgroundPainter _precipBackgroundPainter = null; - - private Font _buttonFont = null; - - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - - // vcr buttons - private JPanel _timeButtonPanel = null; - - private JButton _forwardButton = null; - - private JButton _forward1DayButton = null; - - private JButton _backButton = null; - - private JButton _back1DayButton = null; - - private JButton _recenterButton = null; - - // action buttons - private JButton _closeButton = null; - - private JButton _windowLauncherButton = null; - - private JPanel _windowButtonPanel = null; - - private JButton _screenCaptureButton = null; - - // model control panel - private JPanel _modelControlPanel = null; - - private JLabel _modelControlPanelLabel = null; - - private JLabel _modelTypeComboBoxLabel = null; - - private JComboBox _modelTypeComboBox = null; - - private String[] _modelTypeNameArray = null; - - private JLabel _uhgComboBoxLabel = null; - - private JComboBox _uhgComboBox = null; - - private JLabel _adjustmentCheckBoxLabel = null; - - private JCheckBox _adjustmentCheckBox = null; - - private JLabel _adjustmentLastObsInputTimeLabel = null; - - private DateTimeTextField _adjustmentLastObsInputTimeTextField = null; - - private JLabel _blendPeriodSpinnerLabel = null; - - private JSpinner _blendPeriodSpinner = null; - - // These share the same spot on the model control panel, depending on - // the model being used - private JComboBox _sacStartingStateComboBox = null; - - private JButton _sacStateListRefreshButton = null; - - private JComboBox _apiMkcStartingStateComboBox = null; - - private JButton _apiMkcStateRefreshButton = null; - - private JLabel _forecastHoursSpinnerLabel = null; - - private JSpinner _forecastHoursSpinner = null; - - // loose on the button panel - private JLabel _modelRunStartTimeLabel = null; - - private JLabel _modelRunStartTimeValueLabel = null; - - // SAC_SMA control panel - private JPanel _sacControlPanel = null; - - private JLabel _sacControlPanelLabel = null; - - private JButton _sacParamsButton = null; - - private JButton _sacStateButton = null; - - private JButton _sacMonthlyMapeValuesEditorButton = null; - - private JButton _sacLiveStateAdjustmentButton = null; - - private boolean _allowLiveSacAdjustment = false; - - // time series editing and saving panel - private JMenuBar _menuBar = null; - - // API-MKC variable setting/resetting buttons for model settings - private JPanel _apiMkcControlPanel = null; - - private JLabel _apiMkcSettingsLabel = null; - - private JLabel _modelStateLabel = null; - - private SettingPanel _apiMkcInitialStagePanel = null; - - private SettingPanel _apiMkcFfhPanel = null; - - private SettingPanel _apiMkcThreshRPanel = null; - - private JCheckBox _apiMkcUseCustomModelRunTimeCheckBox = null; - - private DateTimeTextField _apiMkcCustomModelRunDateTimeTextField = null; - - private JButton _apiMkcApplySettingsButton = null; - - // associated API-MKC variables - private boolean _apiMkcUseCustomModelRunTime = false; - - // used to help control how events are processed - private boolean _reloadingApiMkcStartingStateComboBox = false; - - private boolean _reloadingSacStartingStateComboBox = false; - - // graphing controls - private JPanel _graphControlPanel = null; - - private JLabel _graphControlPanelLabel = null; - - private JCheckBox _showFloodStageCheckBox = null; - - private JCheckBox _showMajorFloodStageCheckBox = null; - - private JCheckBox _showObsHeightTsCheckBox = null; - - private JCheckBox _showPrecipAmountsCheckBox = null; - - private JCheckBox _delayRerunCheckBox = null; - - private JCheckBox _showMinorPrecipTicksCheckBox = null; - - private JCheckBox _showMinorStageTicksCheckBox = null; - - private JCheckBox _showSimulatedStageCheckBox = null; - - // booleans related to visual controls - private boolean _forceShowFloodStage = true; - - private boolean _forceShowMajorFloodStage = false; - - private boolean _showPrecipAmounts = true; - - private boolean _showObservedHeightData = true; - - private boolean _delayRerunModelWhileDrawing = false; - - private boolean _showMinorPrecipTicks = false; - - private boolean _showMinorStageTicks = true; - - private boolean _showSimulatedStage = true; - - // main window layer - private JPanel _mainPanel = null; - - private JPanel _buttonPanel = null; - - // misc - private JFileChooser _imageFileChooser = null; - - private FileChooserHelper _precipFileChooserHelper = null; - - private FileChooserHelper _imageFileChooserHelper = null; - - // data - private TimeHolder _modelStartTimeHolder = null; - - private int _intervalInHours = 1; - - private int _millisPerHour = 1000 * 60 * 60; - - private String _defaultFormatString = "0.00"; - - private double _defaultMissingValue = -9999.0; - - // model starting state descriptors - private SacSmaStateDescriptor _selectedSacStateDescriptor = null; - - private FFHDescriptor _selectedFFHDescriptor = null; - - // debugging - private CodeTracer _tracer = null; - - // ----constructors------------------------------------- - - public AnalysisWindow(StreamModel streamModel, AppController controller) { - // init the other application objects that this object talks to - _streamModel = streamModel; - - _controller = controller; - - _tracer = new CodeTracer(); - - _modelStartTimeHolder = _streamModel.getModelStartTimeHolder(); - - getAppsDefaults(); - - initGui(); - - } // AnalysisWindow - - // ------------------------------------------------------------ - private void getAppsDefaults() { - AppsDefaults ad = AppsDefaults.getInstance(); - - // determine if the secret adjustment window should be available - if (ad.getToken(ALLOW_LIVE_SAC_STATE_ADJUSTMENT_TOKEN_NAME) != null) { - _allowLiveSacAdjustment = true; - } - - // default value for the show simulated stage time series toggle button - _showSimulatedStage = ad.getBoolean(SHOW_SIMULATED_TS_TOKEN_NAME, - _default_show_simulated_timeseries); - - _sshp_precip_directoryString = ad.getToken("sshp_precip_dir"); - - _whfs_image_directoryString = ad.getToken("whfs_image_dir"); - - } - - // ------------------------------------------------------------ - - private void initGui() { - - String header = "AnalysisWindow.initGui(): "; - // System.out.println(header + "starting."); - int x = 10; - int y = 10; - int width = 700; - int height = 200; - - int horizontalMargin = 50; - int verticalMargin = 40; - - Dimension prefSplitPaneSize = new Dimension(width + horizontalMargin, - (2 * height) + verticalMargin); - - initTitle(); - - initMenuBar(); - - // set up the 2 canvases and all of their containers - initPrecipCanvas(x, y, width, height, _modelStartTimeHolder); - initStageCanvas(x, y, width, height, _modelStartTimeHolder); - - _splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, _precipCanvas, - _stageCanvas); - - _splitPane.setOneTouchExpandable(true); - _splitPane.setPreferredSize(prefSplitPaneSize); - // _splitPane.setDividerLocation(.50); - - // init "loose" GUI items - initStatusAndReloadControls(); - - // init model control panel - initModelControlPanel(); - - // create the window control button(s) - initWindowButtonPanel(); - - // SAC gui launch buttons - initSacControlPanel(); - - // init the KC-API model parameter controls - initApiMkcControlPanel(); - - // visual controls - initGraphControlPanel(); - - // add the buttons to the _buttonPanel - _buttonPanel = new JPanel(); - _buttonPanel.setLayout(new GridBagLayout()); - GridBagConstraints buttonGbc = new GridBagConstraints(); - - // panel for the model run start time Labels - JPanel modelRunStartTimePanel = new JPanel(); - modelRunStartTimePanel.add(_modelRunStartTimeLabel); - modelRunStartTimePanel.add(_modelRunStartTimeValueLabel); - - // col, row numCols numRows Wcol wrow - // row 0 - buttonGbc.insets = new Insets(5, 2, 5, 2); - - addComponent(_buttonPanel, _modelControlPanel, buttonGbc, 0, 0, 1, 3, - 0, 0); - addComponent(_buttonPanel, _graphControlPanel, buttonGbc, 1, 0, 1, 3, - 0, 0); - // only 1 of the following panels shows at a time - - addComponent(_buttonPanel, _apiMkcControlPanel, buttonGbc, 2, 0, 1, 3, - 0, 0); - addComponent(_buttonPanel, _sacControlPanel, buttonGbc, 2, 0, 1, 3, 0, - 0); - - addComponent(_buttonPanel, modelRunStartTimePanel, buttonGbc, 0, 4, 1, - 1, 0, 0); - - // col, row numCols numRows Wcol wrow - - // row 6 - - buttonGbc.insets = new Insets(5, 5, 5, 5); - buttonGbc.anchor = GridBagConstraints.WEST; - addComponent(_buttonPanel, _windowButtonPanel, buttonGbc, 1, 4, 1, 1, - 1, 0); - - // create the main panel - _mainPanel = new JPanel(); - - // add the components to the panel - GridBagLayout layoutMgr = new GridBagLayout(); - - GridBagConstraints mainGbc = new GridBagConstraints(); - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _mainPanel.setLayout(layoutMgr); - - // add components to the main panel - - // col, row numCols numRows Wcol wrow - - setJMenuBar(_menuBar); - addComponent(_mainPanel, _splitPane, mainGbc, 0, 0, 3, 10, 1, 1); - addComponent(_mainPanel, _buttonPanel, mainGbc, 0, 10, 1, 2, 0, 0); - - // set up initial bounds limitations - // see WindowResize listener for the minimum setting - - Rectangle maxBoundsRectangle = new Rectangle(_maxDimension); - this.setMaximizedBounds(maxBoundsRectangle); - - // add the panel to the Frame and initialize the frame - this.getContentPane().add(_mainPanel); - this.pack(); - - Rectangle initialBoundsRectangle = new Rectangle(_initialDimension); - this.setBounds(initialBoundsRectangle); - - // set up the KC-API settings - resetInitialStageMeasurementFromModel(); - resetFfhFromModel(); - resetThresholdRunoffFromModel(); - - // make sure that the appropriate controls are visible - setComponentVisibility(); - - // add all of the event handlers - addListeners(); - - // select the RainfallRunoffModel - initModelChoice(); - } - - // ------------------------------------------------------------ - private String getCenteredText(String origText) { - String centeredText = "
" + origText + "
"; - - return centeredText; - } - - // ------------------------------------------------------------ - private String getVerticalText(String origText) { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) { - buffer.append(charArray[i]); - - // don't do a break for the last one - if (i < charArray.length - 1) { - buffer.append("
"); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } - - // ------------------------------------------------------------ - - private void initTimeButtonPanel() { - Dimension dimension = new Dimension(24, 28); - - Color buttonColor = this.getBackground(); - Color imageColor = Color.BLUE; - - ImageIcon rightArrowIcon = StandardImageIcons.getImageIcon( - StandardImageIcons.RIGHT_ARROW, imageColor, buttonColor, - dimension); - ImageIcon leftArrowIcon = StandardImageIcons.getImageIcon( - StandardImageIcons.LEFT_ARROW, imageColor, buttonColor, - dimension); - - ImageIcon doubleRightArrowIcon = StandardImageIcons.getImageIcon( - StandardImageIcons.DOUBLE_RIGHT_ARROW, imageColor, buttonColor, - dimension); - - ImageIcon doubleLeftArrowIcon = StandardImageIcons.getImageIcon( - StandardImageIcons.DOUBLE_LEFT_ARROW, imageColor, buttonColor, - dimension); - - ImageIcon circleIcon = StandardImageIcons.getImageIcon( - StandardImageIcons.CIRCLE, imageColor, buttonColor, dimension); - - _forwardButton = GuiHelper.getJButton(rightArrowIcon); - _forwardButton.setToolTipText("Slide display forward 1 hour."); - - _forward1DayButton = GuiHelper.getJButton(doubleRightArrowIcon); - _forward1DayButton.setToolTipText("Slide display forward 24 hours."); - - _recenterButton = GuiHelper.getJButton(circleIcon); - _recenterButton - .setToolTipText("Recenter display around the model run start time."); - - _backButton = GuiHelper.getJButton(leftArrowIcon); - _backButton.setToolTipText("Slide display back 1 hour."); - - _back1DayButton = GuiHelper.getJButton(doubleLeftArrowIcon); - _back1DayButton.setToolTipText("Slide display back 24 hours."); - - _timeButtonPanel = new JPanel(); - // _timeButtonPanel.setBorder(_panelBorder); - _timeButtonPanel.add(_back1DayButton); - _timeButtonPanel.add(_backButton); - _timeButtonPanel.add(_recenterButton); - _timeButtonPanel.add(_forwardButton); - _timeButtonPanel.add(_forward1DayButton); - - } // end initTimeButtonPanel - - // ---------------------------------------------------------------------------------------------------- - private void initGraphControlPanel() { - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.weightx = 1; - gbc.weighty = 1; - - gbc.insets = new Insets(2, 2, 2, 2); - - _graphControlPanel = new JPanel(); - - JPanel panel = _graphControlPanel; - panel.setBorder(_panelBorder); - - panel.setLayout(new GridBagLayout()); - - _graphControlPanelLabel = new JLabel(getCenteredText("Graph Controls:")); - - initTimeButtonPanel(); - - // init the option buttons and the painters that are associated with - // them - _showFloodStageCheckBox = new JCheckBox("Scale To Flood Stage", - _forceShowFloodStage); - String text = "Display Horizontal Line to represent the flood stage"; - _showFloodStageCheckBox.setToolTipText(text); - _floodStageLinePainter.setShouldPaint(_forceShowFloodStage); - - // init the option buttons and the painters that are associated with - // them - _showMajorFloodStageCheckBox = new JCheckBox( - "Scale To Major Flood Stage", _forceShowMajorFloodStage); - text = "Display Horizontal Line to represent the major flood stage"; - _showMajorFloodStageCheckBox.setToolTipText(text); - if (_majorFloodStageLinePainter != null) { - _majorFloodStageLinePainter - .setShouldPaint(_forceShowMajorFloodStage); - } - - // init the option buttons and the painters that are associated with - // them - - // precip totals - _showPrecipAmountsCheckBox = new JCheckBox("Show Precip Amounts", - _showPrecipAmounts); - text = "Display precip totals (in inches) on the precip bars"; - _showPrecipAmountsCheckBox.setToolTipText(text); - _precipPainter.setShowPrecipAmounts(_showPrecipAmounts); - _precipTextTotalPainter.setShouldPaint(_showPrecipAmounts); - - // observed stages - _showObsHeightTsCheckBox = new JCheckBox("Show Obs Stages", - _showObservedHeightData); - text = "Toggle Observed Stage Time Series"; - _showObsHeightTsCheckBox.setToolTipText(text); - _observedStageTsPainter.setShouldPaint(_showObservedHeightData); - - // add simulated stage checkbox - _showSimulatedStageCheckBox = new JCheckBox("Show Simulated Stages", - _showSimulatedStage); - text = "Toggle Simulated Stage Time Series"; - _showSimulatedStageCheckBox.setToolTipText(text); - _simulatedStageTsPainter.setShouldPaint(_showSimulatedStage); - - // add delay button - _delayRerunCheckBox = new JCheckBox("Delay Rerun While Drawing", - _delayRerunModelWhileDrawing); - text = "For graphical precip editing, postpones rerunning the model until after the button is released."; - _delayRerunCheckBox.setToolTipText(text); - - // add minor precip tick checkbox - _showMinorPrecipTicksCheckBox = new JCheckBox( - "Show Minor Precip Lines", _showMinorPrecipTicks); - text = "Toggle minor precip lines"; - _showMinorPrecipTicksCheckBox.setToolTipText(text); - _precipBackgroundPainter.setShowMinorTicks(_showMinorPrecipTicks); - - // add minor stage tick checkbox - _showMinorStageTicksCheckBox = new JCheckBox("Show Minor Stage Lines", - _showMinorStageTicks); - text = "Toggle minor stage lines"; - _showMinorStageTicksCheckBox.setToolTipText(text); - _stageBackgroundPainter.setShowMinorTicks(_showMinorStageTicks); - - JPanel verticalSpacer = new JPanel(); - verticalSpacer.setPreferredSize(new Dimension(30, 34)); - - // JPanel verticalSpacer2 = new JPanel(); - // verticalSpacer2.setPreferredSize(new Dimension(30, 8)); - - // col, row numCols numRows Wcol wrow - addComponent(panel, _graphControlPanelLabel, gbc, 0, 0, 2, 1, 0, 1); - - addComponent(panel, _timeButtonPanel, gbc, 0, 1, 2, 1, 0, 1); - - // addComponent(panel, verticalSpacer, gbc, 0, 2, 2, 1, 0, 1); - - addComponent(panel, _showObsHeightTsCheckBox, gbc, 0, 2, 1, 1, 0, 1); - addComponent(panel, _showSimulatedStageCheckBox, gbc, 1, 2, 1, 1, 0, 1); - - addComponent(panel, _delayRerunCheckBox, gbc, 0, 3, 1, 1, 0, 1); - addComponent(panel, _showFloodStageCheckBox, gbc, 1, 3, 1, 1, 0, 1); - - addComponent(panel, _showPrecipAmountsCheckBox, gbc, 0, 4, 1, 1, 0, 1); - addComponent(panel, _showMajorFloodStageCheckBox, gbc, 1, 4, 1, 1, 0, 1); - - addComponent(panel, _showMinorPrecipTicksCheckBox, gbc, 0, 5, 1, 1, 0, - 1); - addComponent(panel, _showMinorStageTicksCheckBox, gbc, 1, 5, 1, 1, 0, 1); - - // addComponent(panel, verticalSpacer2, gbc, 0, 6, 2, 1, 0, 1); - - return; - } // end initVisualControlPanel - - // ---------------------------------------------------------------------------------------------------- - - private void initWindowButtonPanel() { - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.weightx = 1; - gbc.weighty = 1; - - _windowLauncherButton = GuiHelper.getJButton("Control Window..."); - - _screenCaptureButton = GuiHelper.getJButton("Capture Screen"); - - _closeButton = GuiHelper.getJButton("Close"); - - _windowButtonPanel = new JPanel(); - // _windowButtonPanel.setPreferredSize(new Dimension(150, 40)); - - JPanel panel = _windowButtonPanel; - - // JPanel spacingPanel = new JPanel(); - // spacingPanel.setPreferredSize(new Dimension(160, 40)); - - // spacingPanel.setBackground(Color.blue); - // panel.setBackground(Color.yellow); - - // col, row numCols numRows Wcol wrow - - addComponent(panel, _windowLauncherButton, gbc, 0, 0, 1, 1, 1, 0); - addComponent(panel, _screenCaptureButton, gbc, 1, 0, 1, 1, 1, 0); - addComponent(panel, _closeButton, gbc, 2, 0, 1, 1, 1, 0); - // addComponent(panel, spacingPanel, gbc, 1, 0, 1, 1, 1, 1); - - return; - } - - // ---------------------------------------------------------------------------------------------------- - - private void initApiMkcControlPanel() { - Dimension panelDimension = new Dimension(500, 120); - String toolTipText = null; - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.weightx = 1; - gbc.weighty = 1; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.ipadx = 5; - - _apiMkcControlPanel = new JPanel(); - JPanel panel = _apiMkcControlPanel; - panel.setPreferredSize(panelDimension); - - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - // settings panels for KC-API - _apiMkcSettingsLabel = new JLabel(getCenteredText("API-MKC Settings:")); - - // _apiMkcBaseflowPanel = new SettingPanel("Baseflow (cfs):", 6, - // "Reload Baseflow"); - _apiMkcInitialStagePanel = new SettingPanel("Initial Stage(feet):", 6, - "Reload", "Reload the initial stage from the time series."); - toolTipText = "Initial stage in feet is converted to baseflow in cfs during model run."; - _apiMkcInitialStagePanel.getLabel().setToolTipText(toolTipText); - - // _apiMkcFfhPanel = new SettingPanel("FFH (inches):", 6, "Reload FFH"); - _apiMkcFfhPanel = new SettingPanel("FFH(inches):", 6, "Reload", - "Reload the headwater guidance from the database."); - toolTipText = "Headwater guidance value in inches."; - _apiMkcFfhPanel.getLabel().setToolTipText(toolTipText); - - // Threshold Runoff SettingPanel - // _apiMkcThreshRPanel = new SettingPanel("Threshold Runoff (inches):", - // 6, "Reload T. Runoff"); - _apiMkcThreshRPanel = new SettingPanel("T.Runoff(inches):", 6, - "Reload", "Reload the threshold runoff."); - toolTipText = "Threshold Runoff value in inches."; - _apiMkcThreshRPanel.getLabel().setToolTipText(toolTipText); - - _apiMkcUseCustomModelRunTimeCheckBox = new JCheckBox("Use Custom Time", - _apiMkcUseCustomModelRunTime); - _apiMkcUseCustomModelRunTimeCheckBox - .setToolTipText("Sets the Model Run Start Time by overriding the selected FFH time."); - - long latestHourTime = TimeHelper.truncateTimeInMillisToNearestHour( - System.currentTimeMillis(), 1); - _apiMkcCustomModelRunDateTimeTextField = new DateTimeTextField( - latestHourTime, AnalysisWindow.this, "Model Run Start Time", 20); - _apiMkcCustomModelRunDateTimeTextField.setAllowOnlyEvenHours(true); - _apiMkcCustomModelRunDateTimeTextField.setPreferredSize(new Dimension( - 150, 20)); - _apiMkcCustomModelRunDateTimeTextField.setMaximumSize(new Dimension( - 150, 20)); - _apiMkcCustomModelRunDateTimeTextField.setMinimumSize(new Dimension( - 150, 20)); - - // apply button - _apiMkcApplySettingsButton = GuiHelper - .getJButton(getVerticalText("Apply")); - _apiMkcApplySettingsButton - .setToolTipText("Applies manual changes to settings on the left."); - - // create a panel for vertical spacing purposes - JPanel verticalSpacer = new JPanel(); - Dimension verticalSpacerDimension = new Dimension(30, 15); - verticalSpacer.setPreferredSize(verticalSpacerDimension); - verticalSpacer.setMaximumSize(verticalSpacerDimension); - verticalSpacer.setMinimumSize(verticalSpacerDimension); - - // JPanel for layout purposes of the dateTimeTextField - JPanel dateTimeTextFieldPanel = new JPanel(); - dateTimeTextFieldPanel.setLayout(new GridBagLayout()); - // dateTimeTextFieldPanel.setBackground(Color.yellow); - dateTimeTextFieldPanel.setPreferredSize(new Dimension(209, 30)); - - JPanel spacer1 = new JPanel(); - // spacer1.setBackground(Color.red); - Dimension spacer1Dimension = new Dimension(50, 30); - spacer1.setPreferredSize(spacer1Dimension); - spacer1.setMaximumSize(spacer1Dimension); - spacer1.setMinimumSize(spacer1Dimension); - - // add components to the special dateTimeTextFieldPanel - // col, row numCols numRows Wcol wrow - addComponent(dateTimeTextFieldPanel, - _apiMkcCustomModelRunDateTimeTextField, gbc, 0, 0, 3, 1, 1, 0); - addComponent(dateTimeTextFieldPanel, spacer1, gbc, 3, 0, 1, 1, 0, 0); - - // col, row numCols numRows Wcol wrow - - addComponent(panel, _apiMkcSettingsLabel, gbc, 0, 0, 2, 1, 0, 0); - - addComponent(panel, _apiMkcUseCustomModelRunTimeCheckBox, gbc, 0, 2, 1, - 1, 0, 0); - addComponent(panel, dateTimeTextFieldPanel, gbc, 1, 2, 3, 1, 0, 0); - - addComponent(panel, _apiMkcInitialStagePanel.getLabel(), gbc, 0, 3, 1, - 1, 0, 0); - addComponent(panel, _apiMkcInitialStagePanel.getTextField(), gbc, 1, 3, - 1, 1, 0, 0); - addComponent(panel, _apiMkcInitialStagePanel.getButton(), gbc, 3, 3, 1, - 1, 0, 0); - - addComponent(panel, _apiMkcFfhPanel.getLabel(), gbc, 0, 4, 1, 1, 0, 0); - addComponent(panel, _apiMkcFfhPanel.getTextField(), gbc, 1, 4, 1, 1, 0, - 0); - addComponent(panel, _apiMkcFfhPanel.getButton(), gbc, 3, 4, 1, 1, 0, 0); - - addComponent(panel, _apiMkcThreshRPanel.getLabel(), gbc, 0, 5, 1, 1, 0, - 0); - addComponent(panel, _apiMkcThreshRPanel.getTextField(), gbc, 1, 5, 1, - 1, 0, 0); - addComponent(panel, _apiMkcThreshRPanel.getButton(), gbc, 3, 5, 1, 1, - 0, 0); - - // gbc.insets = new Insets(3, 3, 3, 3); - addComponent(panel, _apiMkcApplySettingsButton, gbc, 2, 3, 1, 3, 0, 0); - - addComponent(panel, verticalSpacer, gbc, 1, 6, 1, 1, 0, 0); - - } // end initApiModelPanel() - - // ---------------------------------------------------------------------------------------------------- - - private void initApiMkcStateComboBox(JComboBox comboBox) { - String header = "AnalysisWindow.initApiMkcTimeComboBox(): "; - // System.out.println(header + "starting"); - - _reloadingApiMkcStartingStateComboBox = true; - - // load all of the possible values from the db - List ffhDescriptorList = _streamModel.getFFHDescriptorList(); - boolean foundMatch = false; - - FFHDescriptor localSelectedDescriptor = null; - - // get a list of strings for this descriptor list - - comboBox.removeAllItems(); - - // add the FFHDescriptors as items to the list - - // System.out.println(header + "initially selectedFFHDescriptor = " + - // _selectedFFHDescriptor); - - for (int i = 0; i < ffhDescriptorList.size(); i++) { - FFHDescriptor descriptor = (FFHDescriptor) ffhDescriptorList.get(i); - - // if the item being added equals the previously selected item, - // note the item. - if (_selectedFFHDescriptor != null) { - // System.out.println(header + "selectedFFHDescriptor = " + - // _selectedFFHDescriptor); - // System.out.println(header + - // "testing equality against Descriptor = " + descriptor); - if ((!foundMatch) - && (_selectedFFHDescriptor.equals(descriptor))) - - { - localSelectedDescriptor = descriptor; - foundMatch = true; - // System.out.println(header + "localSelectedDescriptor = " - // + localSelectedDescriptor); - } - } - - // add it to the list - comboBox.addItem(descriptor); - } - - _reloadingApiMkcStartingStateComboBox = false; - - // select the already selected item, if there was one - if (localSelectedDescriptor != null) { - comboBox.setSelectedItem(localSelectedDescriptor); - } - - return; - - } // end initKcApiTimeComboBox() - - // ---------------------------------------------------------------------------------------------------- - /* - * private long getModelRunTimeFromKcApiComboBox() { long time = 0; - * FFHDescriptor descriptor - * =(FFHDescriptor)_apiMkcStartingStateComboBox.getSelectedItem(); - * - * if (descriptor != null) { time = descriptor.getTime(); } - * - * return time; } - */ - // ---------------------------------------------------------------------------------------------------- - private void initSacStateComboBox(JComboBox comboBox) { - // prevent selection of the added items until it is done loading - _reloadingSacStartingStateComboBox = true; - - comboBox.removeAllItems(); - - List sacSmaStateDescriptorList = _streamModel - .getSacSmaStateDescriptorList(); - SacSmaStateDescriptor localSelectedSacStateDescriptor = null; - boolean foundMatch = false; - - // load each descriptor into the combobox. Also when you find the - // selected descriptor store a reference to it. - for (int i = 0; i < sacSmaStateDescriptorList.size(); i++) { - SacSmaStateDescriptor descriptor = (SacSmaStateDescriptor) sacSmaStateDescriptorList - .get(i); - - if ((!foundMatch) && (_selectedSacStateDescriptor != null) - && (descriptor.equals(_selectedSacStateDescriptor))) { - foundMatch = true; - localSelectedSacStateDescriptor = descriptor; - } - - comboBox.addItem(descriptor); - - } - - // set the combobox to the selected descriptor, if it exists - _reloadingSacStartingStateComboBox = false; - - if (localSelectedSacStateDescriptor != null) { - comboBox.setSelectedItem(localSelectedSacStateDescriptor); - } else { - comboBox.setSelectedIndex(0); - } - - return; - - } - - // ---------------------------------------------------------------------------------- - private void initStatusAndReloadControls() { - /* - * init the following controls _modelRunStartTimeLabel - * _modelRunStartTimeValueLabel - */ - Dimension buttonDimension = new Dimension(120, 30); - _modelRunStartTimeLabel = new JLabel("Model Run Start Time: "); - - // initialize the model run start time value label - JPanel panel = _buttonPanel; - - _modelRunStartTimeValueLabel = new JLabel(); - String dateTimeString = getDateTimeStringToMinutes(_modelStartTimeHolder - .getTime()); - _modelRunStartTimeValueLabel.setText(dateTimeString); - - return; - } - - // ---------------------------------------------------------------------------------- - - private void initModelControlPanel() { - Dimension panelDimension = new Dimension(400, 250); - Dimension buttonDimension = new Dimension(120, 30); - String text = null; - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - _modelControlPanel = new JPanel(); - _modelControlPanel.setPreferredSize(panelDimension); - - JPanel panel = _modelControlPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - _modelControlPanelLabel = new JLabel(getCenteredText("Model Controls:")); - - // init ComboBox panel - // _modelTypeComboBoxLabel = new JLabel("Rainfall-Runoff Model:"); - _modelTypeComboBoxLabel = new JLabel("Rainfall-Runoff Model:"); - initModelComboBox(); - // _modelTypeComboBox.setPreferredSize(new Dimension(100, 35)); - - _uhgComboBoxLabel = new JLabel("UHG:"); - initUHGComboBox(); - - // API-MKC model state comboBox related controls - - // state refresh controls - - // _modelStateLabel = new JLabel("State:"); - _apiMkcStartingStateComboBox = GuiHelper.getJComboBox(); - initApiMkcStateComboBox(_apiMkcStartingStateComboBox); - - _apiMkcStateRefreshButton = GuiHelper.getJButton("Refresh State List"); - text = "Reload available API-MKC states from the database."; - _apiMkcStateRefreshButton.setToolTipText(text); - _apiMkcStateRefreshButton.setPreferredSize(buttonDimension); - - // SAC-SMA model state comboBox related controls - _sacStartingStateComboBox = GuiHelper.getJComboBox(); - initSacStateComboBox(_sacStartingStateComboBox); - _sacStateListRefreshButton = GuiHelper.getJButton("Refresh State List"); - text = "Reload available SAC-SMA states from the database."; - _sacStateListRefreshButton.setToolTipText(text); - _sacStateListRefreshButton.setPreferredSize(buttonDimension); - - // JSeparator separator1 = new JSeparator(); - - // The forecast length spinner - // set up the spinner control for time - - _forecastHoursSpinnerLabel = new JLabel("Fcst Hours:"); - - int initialValue = _streamModel.getForecastHours(); - int min = 1; - int max = _streamModel.getMaxForecastLengthInHours(); - int step = FORECAST_LENGTH_SPINNER_STEPS; - - SpinnerModel forecastHoursSpinnerModel = new SpinnerNumberModel( - initialValue, min, max, step); - - _forecastHoursSpinner = new JSpinner(forecastHoursSpinnerModel); - - JPanel spinnerPanel = new JPanel(); // used to get the controls to stick - // together nicely - spinnerPanel.add(_forecastHoursSpinnerLabel); - spinnerPanel.add(_forecastHoursSpinner); - - // ------- The forecast adjustment controls - - // Forecast Adjustment ON/OFF controls - _adjustmentCheckBoxLabel = new JLabel("Adjust by Observed"); - _adjustmentCheckBox = new JCheckBox(); - _adjustmentCheckBox.setSelected(_streamModel.isAdjustmentOn()); - - JPanel adjustmentCheckBoxPanel = new JPanel(); - adjustmentCheckBoxPanel.add(_adjustmentCheckBoxLabel); - adjustmentCheckBoxPanel.add(_adjustmentCheckBox); - - // Blending period hours Spinner - _blendPeriodSpinnerLabel = new JLabel("Blend Ahead Hours"); - String toolTipText = "Note: Zero hours blended can still result in 1 \"extra\" non-blended adjustment (by pairing)."; - _blendPeriodSpinnerLabel.setToolTipText(toolTipText); - - int initialAdjustmentHoursValue = _streamModel.getBlendingHours(); - - // Initialize spinner to select the blending hours - min = 0; - max = _streamModel.getMaxBlendingHours(); - step = 6; - - if (initialAdjustmentHoursValue < 0) { - initialAdjustmentHoursValue = 0; - } - if (initialAdjustmentHoursValue > max) { - max = initialAdjustmentHoursValue; - } - - SpinnerModel blendSpinnerModel = new SpinnerNumberModel( - initialAdjustmentHoursValue, min, max, step); - _blendPeriodSpinner = new JSpinner(blendSpinnerModel); - _blendPeriodSpinner - .setToolTipText("The number of hours after the last observed input time to blend.\n" - + "Zero hours will blend the last observed input hour if there is a match with the forecast."); - - JPanel adjustmentSpinnerPanel = new JPanel(); - adjustmentSpinnerPanel.add(_blendPeriodSpinnerLabel); - adjustmentSpinnerPanel.add(_blendPeriodSpinner); - - // init the DateTimeTextField (our custom class) - - toolTipText = "Last Observed Input Time For Adjustment. Click on Text Box to edit."; - _adjustmentLastObsInputTimeLabel = new JLabel( - "Last Obs. Time For Adjust"); - _adjustmentLastObsInputTimeLabel.setToolTipText(toolTipText); - - _adjustmentLastObsInputTimeTextField = new DateTimeTextField( - getLastObservedStageTime(), AnalysisWindow.this, - "Last Observed Input Time For Adjustment", 20); - - _adjustmentLastObsInputTimeTextField.setPreferredSize(new Dimension( - 100, 30)); - - // JSeparator separator2 = new JSeparator(); - - JPanel modelTypePanel = new JPanel(); - - modelTypePanel.add(_modelTypeComboBoxLabel); - modelTypePanel.add(_modelTypeComboBox); - modelTypePanel.add(_uhgComboBoxLabel); - modelTypePanel.add(_uhgComboBox); - - modelTypePanel.setPreferredSize(new Dimension(100, 40)); - // _modelTypeComboBox.setPreferredSize(new Dimension(100, 40)); - // _modelTypeComboBoxLabel.setPreferredSize(new Dimension(50, 40)); - - // col, row numCols numRows Wcol wrow - addComponent(panel, _modelControlPanelLabel, gbc, 0, 0, 1, 1, 1, 0); - - // addComponent(panel, _modelTypeComboBoxLabel, gbc, 0, 1, 1, 1, 0, 0); - // addComponent(panel, _modelTypeComboBox, gbc, 1, 1, 2, 1, 0, 0); - addComponent(panel, modelTypePanel, gbc, 0, 1, 4, 1, 0, 0); - - // addComponent(panel, _uhgComboBoxLabel, gbc, 3, 1, 1, 1, 0, 0); - // addComponent(panel, _uhgComboBox, gbc, 4, 1, 1, 1, 0, 0); - - // API_MKC controls - - addComponent(panel, _apiMkcStartingStateComboBox, gbc, 0, 2, 2, 1, 0, 0); - addComponent(panel, _apiMkcStateRefreshButton, gbc, 0, 3, 1, 1, 0, 0); - - // /SAC-SMA controls - addComponent(panel, _sacStartingStateComboBox, gbc, 0, 2, 2, 1, 0, 0); - addComponent(panel, _sacStateListRefreshButton, gbc, 0, 3, 1, 1, 0, 0); - - addComponent(panel, spinnerPanel, gbc, 1, 3, 1, 1, 0, 0); - - // addComponent(panel, _modelStateLabel, gbc, 0, 3, 1, 1, 0, 0); - // one or the other will be visible - - JSeparator separator = new JSeparator(JSeparator.HORIZONTAL); - addComponent(panel, separator, gbc, 0, 4, 2, 1, 0, 0); - - // adjustment controls - addComponent(panel, adjustmentCheckBoxPanel, gbc, 0, 5, 1, 1, 0, 0); - - addComponent(panel, adjustmentSpinnerPanel, gbc, 1, 5, 1, 1, 0, 0); - - addComponent(panel, _adjustmentLastObsInputTimeLabel, gbc, 0, 6, 1, 1, - 0, 0); - addComponent(panel, _adjustmentLastObsInputTimeTextField, gbc, 1, 6, 1, - 1, 0, 0); - - return; - - } - - // ---------------------------------------------------------------------------------- - private void initSacControlPanel() { - Dimension panelDimension = new Dimension(500, 300); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(3, 3, 3, 3); - gbc.weightx = 1; - gbc.weighty = 1; - - _sacControlPanel = new JPanel(); - - String toolTipText = null; - - JPanel panel = _sacControlPanel; - panel.setPreferredSize(new Dimension(325, 300)); - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - panel.setPreferredSize(panelDimension); - - _sacControlPanelLabel = new JLabel(getCenteredText("SAC-SMA Settings:")); - - _sacParamsButton = new JButton("Edit Params..."); - _sacParamsButton.setToolTipText("Open the SAC-SMA Parameters Editor"); - - _sacStateButton = new JButton("Edit States...."); - _sacStateButton.setToolTipText("Open the SAC-SMA State Editor"); - - _sacMonthlyMapeValuesEditorButton = new JButton( - "MAPE Monthly Values..."); - _sacMonthlyMapeValuesEditorButton - .setToolTipText("Open the MAPE Monthly Values Editor"); - - // init the (probably temporary) Setting adjustment button. - - _sacLiveStateAdjustmentButton = new JButton("Adjust State..."); - _sacLiveStateAdjustmentButton.setPreferredSize(new Dimension(50, 30)); - - // panel to take up space - - // Note: setMinimumSize() does not work for this purpose, use - // setPreferredSize() instead - - JPanel verticalSpaceFiller1 = new JPanel(); - verticalSpaceFiller1.setPreferredSize(new Dimension(50, 50)); - JPanel verticalSpaceFiller2 = new JPanel(); - verticalSpaceFiller2.setPreferredSize(new Dimension(85, 150)); - JPanel horizontalSpaceFiller1 = new JPanel(); - horizontalSpaceFiller1.setPreferredSize(new Dimension(85, 100)); - - JPanel verticalSpaceFiller3 = new JPanel(); - verticalSpaceFiller2.setPreferredSize(new Dimension(85, 150)); - - // just to make things look pretty - // gbc.insets = new Insets(5, 5, 5, 5); - - // col, row numCols numRows Wcol wrow - addComponent(panel, _sacControlPanelLabel, gbc, 0, 0, 1, 1, 1, 0); - - if (!_allowLiveSacAdjustment) { - addComponent(panel, verticalSpaceFiller1, gbc, 0, 1, 1, 2, 1, 0); - addComponent(panel, horizontalSpaceFiller1, gbc, 1, 1, 1, 2, 1, 1); - } - - addComponent(panel, _sacParamsButton, gbc, 0, 5, 1, 1, 1, 0); - - if (!_allowLiveSacAdjustment) { - addComponent(panel, verticalSpaceFiller2, gbc, 0, 6, 1, 1, 1, 1); - } - - addComponent(panel, _sacStateButton, gbc, 0, 7, 1, 1, 1, 0); - - if (!_allowLiveSacAdjustment) { - addComponent(panel, verticalSpaceFiller3, gbc, 0, 8, 1, 1, 1, 1); - } - - addComponent(panel, _sacMonthlyMapeValuesEditorButton, gbc, 0, 11, 1, - 1, 1, 0); - - if (_allowLiveSacAdjustment) { - gbc.insets = new Insets(5, 5, 5, 5); - addComponent(panel, _sacLiveStateAdjustmentButton, gbc, 0, 12, 1, - 1, 1, 0); - } - - } // end initSacButtonPanel() - - // ------------------------------------------------------------ - // ------------------------------------------------------------ - - private void initModelChoice() { - // trace(); - - String header = "AnalysisWindow.initModelChoice(): "; - int initialIndex = 0; - String initialSelectedTypeName = _streamModel - .getRainfallRunoffModelTypeName(); - - // System.out.println(header + "initialSelectedTypeName = " + - // initialSelectedTypeName); - - RainfallRunoffModelType[] modelTypeArray = RainfallRunoffModelType - .getModelTypeArray(); - - // find initialSelectedType - for (int i = 0; i < modelTypeArray.length; i++) { - if (modelTypeArray[i].getName().equals(initialSelectedTypeName)) { - initialIndex = i; - break; - } - } - - _modelTypeComboBox.setSelectedIndex(initialIndex); - - return; - } - - // ------------------------------------------------------------ - - private void initModelComboBox() { - // note: at some point might want to separate the presentation of the - // name of the model from the built-in model type name - - RainfallRunoffModelType[] modelTypeArray = RainfallRunoffModelType - .getModelTypeArray(); - - _modelTypeNameArray = new String[modelTypeArray.length]; - - // add the choices to the string array - for (int i = 0; i < modelTypeArray.length; i++) { - _modelTypeNameArray[i] = modelTypeArray[i].getName(); - } - - // create the comboBox with all the choices in it - _modelTypeComboBox = GuiHelper.getJComboBox(_modelTypeNameArray); - - return; - } - - // ------------------------------------------------------------ - private void initUHGChoice() { - // trace(); - - String header = "AnalysisWindow.initUHGChoice(): "; - int initialIndex = 0; - String initialSelectedTypeName = _streamModel - .getRainfallRunoffModelTypeName(); - - // System.out.println(header + "initialSelectedTypeName = " + - // initialSelectedTypeName); - - RainfallRunoffModelType[] modelTypeArray = RainfallRunoffModelType - .getModelTypeArray(); - - // find initialSelectedType - for (int i = 0; i < modelTypeArray.length; i++) { - if (modelTypeArray[i].getName().equals(initialSelectedTypeName)) { - initialIndex = i; - break; - } - } - - _uhgComboBox.setSelectedIndex(initialIndex); - - return; - } - - // ----------------------------------------------------------------- - - private void initUHGComboBox() { - - String[] uhgNamesArray = _streamModel.getUnitHydrographNameArray(); - - // create the comboBox with all the choices in it - _uhgComboBox = GuiHelper.getJComboBox(uhgNamesArray); - - refreshUhgSelection(); - - return; - } - - // ----------------------------------------------------------------- - private void refreshUhgSelection() { - String selectedUHGModelName = _streamModel - .getUnitHydrographSelectionName(); - - _uhgComboBox.setSelectedItem(selectedUHGModelName); - - } - - // ----------------------------------------------------------------- - - private void addComponent(Container container, Component component, - GridBagConstraints gbc, int column, int row, int columnCells, - int rowCells, int weightX, int weightY) { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - // the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - // ----------------------------------------------------------------- - - private void initTitle() { - String locationId = _streamModel.getLocationId(); - String locationName = _streamModel.getLocationName(); - String basinId = _streamModel.getBasinId(); - - String rainfallRunoffModelName = _streamModel - .getRainfallRunoffModelTypeName(); - - String titleString = "SSHP Analysis Window - Modeling " + locationId - + ", " + locationName + " With BASIN : " + basinId - + " using the " + rainfallRunoffModelName + " model"; - setTitle(titleString); - - return; - } - - // ----------------------------------------------------------------- - private void initPrecipCanvas(int x, int y, int width, int height, - TimeHolder modelStartTimeHolder) { - // _precipCanvas = new PrecipCanvas(x, y, width, height); - _precipCanvas = new TsPaintableCanvas(MeasuringUnit.inches, x, y, - width, height); - - _precipCanvas.setPreferredSize(new Dimension(width, height)); - _precipCanvas.setMinimumSize(new Dimension(100, 10)); - - MeasuringUnit unit = _precipCanvas.getDisplayedMeasuringUnit(); - - Color outlineColor = Color.WHITE; - - // background painter - _precipBackgroundPainter = new TsBackgroundPainter(outlineColor, - _precipCanvas, "inches", "mm"); - - _precipValueMapper = new UnitValueMapper(MeasuringUnit.inches, - MeasuringUnit.mm); - - _precipBackgroundPainter.setRightLabelValueMapper(_precipValueMapper); - _precipCanvas.addCanvasPainter(_precipBackgroundPainter); - - // precip bar painters ------------------------------ - - // add the precip painter - Color barColor = Color.BLUE; - _precipPainter = new PrecipPainter(barColor, outlineColor, _streamModel - .getPrecipTimeSeriesHolder(), _showPrecipAmounts, _precipCanvas); - _precipCanvas.addTsCanvasPainter(_precipPainter); - - // add the precip text total painter - _precipTextTotalPainter = new PrecipTotalTextPainter(Color.yellow, - _streamModel.getPrecipTimeSeriesHolder(), _showPrecipAmounts, - _precipCanvas); - _precipCanvas.addCanvasPainter(_precipTextTotalPainter); - - // add the prior runoff painter - Color runoffColor = Color.YELLOW; - PrecipPainter priorRunoffPrecipPainter = new PrecipPainter(runoffColor, - outlineColor, _streamModel.getPriorRunoffTimeSeriesHolder(), - false, _precipCanvas); - - priorRunoffPrecipPainter.setShouldDrawBars(false); - - _precipCanvas.addTsCanvasPainter(priorRunoffPrecipPainter); - - // add the runoff painter - Color runoffColor2 = Color.MAGENTA; - PrecipPainter runoffPrecipPainter = new PrecipPainter(runoffColor2, - outlineColor, _streamModel.getRunoffTimeSeriesHolder(), false, - _precipCanvas); - - runoffPrecipPainter.setShouldDrawBars(false); - - _precipCanvas.addTsCanvasPainter(runoffPrecipPainter); - - // Model time line color - Color timeLineColor = Color.MAGENTA; - TimeLinePainter modelStartTimeLinePainter = new TimeLinePainter( - timeLineColor, _modelStartTimeHolder, _precipCanvas); - - _precipCanvas.addCanvasPainter(modelStartTimeLinePainter); - - // set the display time window - setTimeWindowAroundModelStartTime(_precipCanvas); - - _precipCanvas.setTitle("1-Hour Mean Areal Precipitation Time Series"); - - } // end initPrecipCanvas - - // ----------------------------------------------------------------- - private void initStageCanvas(int x, int y, int width, int height, - TimeHolder modelStartTimeHolder) { - _stageCanvas = new TsPaintableCanvas(MeasuringUnit.feet, x, y, width, - height); - - _stageCanvas.setPreferredSize(new Dimension(width, height)); - _stageCanvas.setMinimumSize(new Dimension(100, 10)); - - Color outlineColor = Color.WHITE; - - // background Painter - _stageBackgroundPainter = new TsBackgroundPainter(outlineColor, - _stageCanvas, "feet", "cfs"); - - _stageValueMapper = _streamModel.getStageToFlowValueMapper(); - - _stageBackgroundPainter.setRightLabelValueMapper(_stageValueMapper); - _stageCanvas.addCanvasPainter(_stageBackgroundPainter); - - setUpSigRiverLevelDrawing(); - - // observed hydrograph painter - Color obsColor = Color.yellow; - _observedStageTsPainter = new StagePainter(obsColor, _streamModel - .getObservedStageTimeSeriesHolder(), _stageCanvas); - _stageCanvas.addTsCanvasPainter(_observedStageTsPainter); - - // simulated hydrograph painter - Color simulationColor = Color.blue; - _simulatedStageTsPainter = new StagePainter(simulationColor, - _streamModel.getSimulationStageTimeSeriesHolder(), - _stageCanvas, true); - _simulatedStageTsPainter.setPointString("X"); - _stageCanvas.addTsCanvasPainter(_simulatedStageTsPainter); - // _simulatedStageTsPainter.setShiftAmount(new Point(-4, 3)); - - // forecast hydrograph painter - Color forecastColor = Color.green; - StagePainter forecastPainter = new StagePainter(forecastColor, - _streamModel.getForecastStageTimeSeriesHolder(), _stageCanvas, - true); - forecastPainter.setPointString("X"); - - _stageCanvas.addTsCanvasPainter(forecastPainter); - - // prior forecast hydrograph painter - // Color priorForecastColor = new Color(154, 205, 50); //yellow green - Color priorForecastColor = new Color(160, 32, 240); // purple - StagePainter priorForecastPainter = new StagePainter( - priorForecastColor, _streamModel - .getPriorForecastStageTimeSeriesHolder(), _stageCanvas, - true); - priorForecastPainter.setPointString("X"); - _stageCanvas.addTsCanvasPainter(priorForecastPainter); - - // Model time line color - Color timeLineColor = Color.MAGENTA; - TimeLinePainter modelStartTimeLinePainter = new TimeLinePainter( - timeLineColor, _modelStartTimeHolder, _stageCanvas); - - _stageCanvas.addCanvasPainter(modelStartTimeLinePainter); - - // int intervalInHours = 1; - - long startTime = modelStartTimeHolder.getTime() - (24 * _millisPerHour); - int hoursForward = 72; - long endTime = startTime + (hoursForward * _millisPerHour); - - _stageCanvas.setTimeWindow(startTime, endTime); - - // set the display time window - setTimeWindowAroundModelStartTime(_stageCanvas); - - _stageCanvas.setTitle("Forecast Stage Time Series"); - - } // end initStageCanvas - // ----------------------------------------------------------------- - - private void setUpSigRiverLevelDrawing() { - // set up painters for significant stages - SigRiverLevels sigStages = _streamModel.getSigRiverLevels(); - - // action stage painter - if ((sigStages != null) && (sigStages.hasActionStage())) - - { - Color actionStageColor = Color.yellow; - Measurement actionStageMeasurement = new Measurement(sigStages - .getActionStage(), MeasuringUnit.feet); - SigStageLinePainter actionStageLinePainter = new SigStageLinePainter( - actionStageColor, actionStageMeasurement, _stageCanvas); - - _stageCanvas.addTsCanvasPainter(actionStageLinePainter); - } - - // flood stage painter - if ((sigStages != null) && (sigStages.hasFloodStage())) { - // this is a darker orange, more easily distinguished - // from Color.yellow than Color.orange - Color betterOrange = new Color(0xFF8C00); - Color floodStageColor = betterOrange; - Measurement floodStageMeasurement = new Measurement(sigStages - .getFloodStage(), MeasuringUnit.feet); - _floodStageLinePainter = new SigStageLinePainter(floodStageColor, - floodStageMeasurement, _stageCanvas); - - _stageCanvas.addTsCanvasPainter(_floodStageLinePainter); - } - - if ((sigStages != null) && (sigStages.hasModerateFloodStage())) { - Color moderateFloodStageColor = Color.red; - Measurement moderateFloodStageMeasurement = new Measurement( - sigStages.getModerateFloodStage(), MeasuringUnit.feet); - - SigStageLinePainter moderateFloodStageLinePainter = new SigStageLinePainter( - moderateFloodStageColor, moderateFloodStageMeasurement, - _stageCanvas); - - _stageCanvas.addTsCanvasPainter(moderateFloodStageLinePainter); - } - - if ((sigStages != null) && (sigStages.hasMajorFloodStage())) { - Color majorFloodStageColor = Color.magenta; - Measurement majorFloodStageMeasurement = new Measurement(sigStages - .getMajorFloodStage(), MeasuringUnit.feet); - - _majorFloodStageLinePainter = new SigStageLinePainter( - majorFloodStageColor, majorFloodStageMeasurement, - _stageCanvas); - - _stageCanvas.addTsCanvasPainter(_majorFloodStageLinePainter); - } - - } - - // ----------------------------------------------------------------- - private void recenterTimeWindowsAroundModelStartTime() { - setTimeWindowAroundModelStartTime(_precipCanvas); - setTimeWindowAroundModelStartTime(_stageCanvas); - } - - // ----------------------------------------------------------------- - - private void setTimeWindowAroundModelStartTime(TsPaintableCanvas canvas) { - int hoursBack = _hoursToShowBeforeModelStartTime; - int hoursForward = _hoursToShowAfterModelStartTime; - - long startTime = _modelStartTimeHolder.getTime() - - (hoursBack * _millisPerHour); - - long endTime = startTime + (hoursForward * _millisPerHour); - canvas.setTimeWindow(startTime, endTime); - - } - - // ----------------------------------------------------------------- - - public void updateDataPointText(DataPoint dataPoint, - ValueMapper valueMapper, TsPaintableCanvas canvas) { - // System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String leftUnitString = canvas.getDisplayedMeasuringUnit().toString(); - String rightUnitString = valueMapper.getOutputMeasuringUnit() - .toString(); - - String message = getDataPointString(dataPoint, valueMapper, - leftUnitString, rightUnitString); - - // textField.setText(message); - - canvas.setToolTipText(message); - - return; - } - - // ----------------------------------------------------------------- - private void setComponentVisibility() { - RainfallRunoffModelType modelType = _streamModel - .getRainfallRunoffModelType(); - - boolean apiMkcVisible = false; - boolean sacSmaVisible = false; - - if (modelType == RainfallRunoffModelType.API_MKC) { - apiMkcVisible = true; - sacSmaVisible = false; - } else if (modelType == RainfallRunoffModelType.SAC_SMA) { - apiMkcVisible = false; - sacSmaVisible = true; - } - - _apiMkcControlPanel.setVisible(apiMkcVisible); - _apiMkcStartingStateComboBox.setVisible(apiMkcVisible); - // _modelStateLabel.setVisible(apiMkcVisible); - _apiMkcStateRefreshButton.setVisible(apiMkcVisible); - - _sacControlPanel.setVisible(sacSmaVisible); - _sacStartingStateComboBox.setVisible(sacSmaVisible); - _sacStateListRefreshButton.setVisible(sacSmaVisible); - - return; - } - - // ---------------------------------------------------------------------- - private String getDateTimeStringToMinutes(long time) { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + " Z"; - - return timeString; - } - - // ---------------------------------------------------------------------- - private long getTimeOfLatestHour() { - long time = System.currentTimeMillis(); - - time = TimeHelper.truncateTimeInMillisToNearestHour(time, 1); - - return time; - } - - // --------------------------------------------------------------------- - private long getLastObservedStageTime() { - long time = -1; - - try { - time = _streamModel.getObservedStageTimeSeriesHolder() - .getTimeSeries().getEndTime(); - } catch (Throwable t) { - System.out.println("getLastObservedStageTime(): " - + "caught a throwable, but don't worry"); - } - - return time; - } - - // ------------------------------------------------------------------------ - - // //---------------------------------------------------------------------- - - private String getDataPointString(DataPoint dataPoint, - ValueMapper valueMapper, String leftUnitString, - String rightUnitString) { - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(dataPoint.getY()); - - String mappedValueString = ""; - - if (valueMapper != null) { - MeasuringUnit inputUnit = valueMapper.getInputMeasuringUnit(); - Measurement inputMeasurement = new Measurement(dataPoint.getY(), - inputUnit); - - Measurement mappedMeasurement = valueMapper - .getResultMeasurement(inputMeasurement); - - double mappedValue = mappedMeasurement.getValue(); - - mappedValueString = nf.format(mappedValue); - } - - long time = (long) Math.floor(dataPoint.getX()); - - String timeString = getDateTimeStringToMinutes(time); - - String dataPointString = timeString + ", " + valueString + " " - + leftUnitString + ", " + mappedValueString + " " - + rightUnitString; - - return dataPointString; - } - - // event handler -------------------------------------------------- - - // ---------------------------------------------------------------------- - - private void replaceTimeSeriesValue( - RegularTimeSeriesHolder timeSeriesHolder, - TimeIntervalMeasurement newMeasurement) { - // String header = "AnalysisWindow.replaceTimeSeriesValue(): "; - - RegularTimeSeries timeSeries = timeSeriesHolder.getTimeSeries(); - - // System.out.println(header + "before conversion, newMeasurement is " + - // newMeasurement); - - newMeasurement = TimeIntervalMeasurement.getConvertedCopy( - newMeasurement, timeSeries.getMeasuringUnit()); - - // System.out.println(header + "after conversion, newMeasurement is " + - // newMeasurement); - - long endTimeInMillis = newMeasurement.getEndTime(); - - timeSeries.setMeasurementByTime(newMeasurement, endTimeInMillis); - - } // end replaceTimeSeriesValue() - - // ---------------------------------------------------------------------- - - private void replaceTimeSeriesValue( - RegularTimeSeriesHolder timeSeriesHolder, - AbsTimeMeasurement newMeasurement) { - String header = "AnalysisWindow.replaceTimeSeriesValue(): "; - - RegularTimeSeries timeSeries = timeSeriesHolder.getTimeSeries(); - - // System.out.println(header + "timeSeries = " + timeSeries); - - if (timeSeries != null) { - newMeasurement = AbsTimeMeasurement.getConvertedCopy( - newMeasurement, timeSeries.getMeasuringUnit()); - - timeSeries.setMeasurementByTime(newMeasurement, newMeasurement - .getTime()); - } else { - // System.err.println(header + " time series is null "); - } - - } // end replaceTimeSeriesValue() - - // ---------------------------------------------------------------- - private void runModel() { - - // String header = "AnalysisWindow.runModel(): "; - // System.out.println(header + "inside the method"); - - _streamModel.runModel(); - - redrawCanvases(); - - announceModelRun(); - - } - - // ---------------------------------------------------------------- - - private void announceModelRun() { - announceTimeSeriesChange("Model Run"); - } - - // ----------------------------------------------------------------- - - private void announceForecastStageEdited() { - String message = "Manually Edited Fcst Stage"; - TimeSeriesEvent event = new TimeSeriesEvent(message, - AnalysisWindow.this); - - _streamModel.getForecastStageTimeSeriesHolder().forwardEvent(event); - } - - // ----------------------------------------------------------------- - private void announceTimeSeriesChange(String message) { - TimeSeriesEvent event = new TimeSeriesEvent(message, - AnalysisWindow.this); - - _streamModel.getPrecipTimeSeriesHolder().forwardEvent(event); - _streamModel.getForecastStageTimeSeriesHolder().forwardEvent(event); - - _streamModel.getEvaporationTimeSeriesHolder().forwardEvent(event); - _streamModel.getPriorRunoffTimeSeriesHolder().forwardEvent(event); - - _streamModel.getRunoffTimeSeriesHolder().forwardEvent(event); - - } - - // ----------------------------------------------------------------- - - private void setModelTypeToComboBoxSelection() { - - int selectedIndex = _modelTypeComboBox.getSelectedIndex(); - - RainfallRunoffModelType[] typeArray = RainfallRunoffModelType - .getModelTypeArray(); - - RainfallRunoffModelType type = typeArray[selectedIndex]; - - changeModelType(type); - } - - // ----------------------------------------------------------------- - - private void changeModelType(RainfallRunoffModelType newType) { - - RainfallRunoffModelType oldType = _streamModel - .getRainfallRunoffModelType(); - - String header = "AnalysisWindow.changeModelType()"; - // System.out.println(header +": changing type to " + newType); - - // _tracer.trace("in " + header); - - boolean success = _streamModel.setRainfallRunoffModelType(newType); - - if (success) { - - if ((oldType != null) && (oldType == newType)) { - // System.out.println(header + - // "changing to same RR model type"); - } - - setComponentVisibility(); - - // the title needs to update because the - // model may have changed - initTitle(); - - // take any already graphically set parameters and put them back - // into the - // streamModel to be used for model runs - updateModelSettingsFromGui(); - - if (newType == RainfallRunoffModelType.API_MKC) { - setApiMkcModelState(); - } else if (newType == RainfallRunoffModelType.SAC_SMA) { - setSacModelState(); - } - - // recenter the canvases around the model run start time - recenterTimeWindowsAroundModelStartTime(); - - // refresh the selected Unit HydroGraph - refreshUhgSelection(); - - // run the stream model again - // runModel(); - } else // failed, so change it back to MKC_API - { - - String locationId = _streamModel.getLocationId(); - - String message = "Location: " - + locationId - + " is not configured properly to run the SAC-SMA.\n" - + " Please add a record in the SSHPConfig Dialog to configure it."; - - String dialogTitle = locationId + " Configuration Message"; - DialogHelper.displayMessageDialog(this, message, dialogTitle); - - int index = getIndexOfModelType(RainfallRunoffModelType.API_MKC); - _modelTypeComboBox.setSelectedIndex(index); - - } - return; - } - - // ----------------------------------------------------------------- - private int getIndexOfModelType(RainfallRunoffModelType type) { - int index = -1; - - for (int i = 0; i < _modelTypeNameArray.length; i++) { - if (type.getName().equalsIgnoreCase(_modelTypeNameArray[i])) { - index = i; - } - } - - return index; - } - - // ----------------------------------------------------------------- - - private void setUnitHydrographToComboBoxSelection() { - - Object selectedItem = _uhgComboBox.getSelectedItem(); - - String selectedUnitHydrographName = (String) selectedItem; - - _streamModel.changeUnitHydrograph(selectedUnitHydrographName); - - runModel(); - } - - // ----------------------------------------------------------------- - - private void updateModelSettingsFromGui() { - RainfallRunoffModelType modelType = _streamModel - .getRainfallRunoffModelType(); - - if (modelType == RainfallRunoffModelType.API_MKC) { - seInitialStageMeasurementFromGui(); - setFfhFromGui(); - setThresholdRunoffFromGui(); - } else if (modelType == RainfallRunoffModelType.SAC_SMA) { - // do nothing - } - - return; - } - - // ----------------------------------------------------------------- - - // add all of the event handlers - private void addListeners() { - - // allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - // addComponentListener(new WindowResizeComponentListener()); - // this object does not get garbage collected right away, since in the - // constructor, it adds itself as a Window listener - WindowResizingManager mgr = new WindowResizingManager(this, - _minDimension, _maxDimension); - - // set up the action to perform when the close button is pressed - _closeButton.addActionListener(new CloseListener()); - - // setup of the action for the screen capture button - _screenCaptureButton - .addActionListener(new ScreenCaptureActionListener()); - - // set up the window launcher button - _windowLauncherButton - .addActionListener(new ControlWindowFocusActionListener()); - - // set up the action to perform when the forward button is pressed - _forwardButton.addActionListener(new TimeWindowSlideListener(1)); - - // set up the action to perform when the forward button is pressed - _forward1DayButton.addActionListener(new TimeWindowSlideListener(24)); - - // setup of the action to perform when the recenter button is pressed - _recenterButton - .addActionListener(new TimeWindowRecenterActionListener()); - - // set up the action to perform when the back button is pressed - _back1DayButton.addActionListener(new TimeWindowSlideListener(-24)); - - // set up the action to perform when the back button is pressed - _backButton.addActionListener(new TimeWindowSlideListener(-1)); - - // set up the action to perform when the time mode check box is pressed - // _timeModeCheckBox.addActionListener( new TimeModeCheckBoxListener()); - - // set up the action to perform when the show flood stage check box is - // pressed - _showFloodStageCheckBox - .addActionListener(new FloodStageCheckBoxListener()); - - // set up the action to perform when the show major flood stage check - // box is pressed - _showMajorFloodStageCheckBox - .addActionListener(new MajorFloodStageCheckBoxListener()); - - // set up the action to perform when the _showPrecipAmountsCheckBox is - // pressed - _showPrecipAmountsCheckBox - .addActionListener(new ShowPrecipAmountsCheckBoxListener()); - - // set up the action to perform when the show obs stage time series - // check box is pressed - _showObsHeightTsCheckBox - .addActionListener(new ShowObservedHeightTsCheckBoxListener()); - - // addListener for the delayRerunCheckBox - _delayRerunCheckBox.addActionListener(new DelayRerunCheckBoxListener()); - - // SHOW MINOR PRECIP TICKS - _showMinorPrecipTicksCheckBox - .addActionListener(new ShowMinorPrecipTicksCheckBoxListener()); - - // SHOW MINOR STAGE TICKS - _showMinorStageTicksCheckBox - .addActionListener(new ShowMinorStageTicksCheckBoxListener()); - - // SHOW Simulated Stage - _showSimulatedStageCheckBox - .addActionListener(new ShowSimulatedStageCheckBoxListener()); - - // CANVAS LISTENERS - - // addlistener for the PrecipCanvas - _precipCanvas.addMouseMotionListener(new CanvasMouseMovedListener( - _precipCanvas, _precipValueMapper)); - - // addlistener for the StageCanvas - _stageCanvas.addMouseMotionListener(new CanvasMouseMovedListener( - _stageCanvas, _stageValueMapper)); - - // --- KC API model settings - - // baseflow reset - _apiMkcInitialStagePanel.getButton().addActionListener( - new InitialStageResetListener()); - - // baseflow adjustment - _apiMkcInitialStagePanel.getTextField().addFocusListener( - new InitalStageFocusListener()); - - // FFH reset - _apiMkcFfhPanel.getButton().addActionListener(new FfhResetListener()); - - // FFH adjustment - _apiMkcFfhPanel.getTextField().addFocusListener(new FfhFocusListener()); - - _apiMkcStartingStateComboBox - .addActionListener(new ModelRunStartingStateActionListener( - _apiMkcStartingStateComboBox)); - - // threshold Runoff reset - _apiMkcThreshRPanel.getButton().addActionListener( - new ThreshRunoffResetListener()); - - // threshold Runoff adjustment - _apiMkcThreshRPanel.getTextField().addFocusListener( - new ThreshRunoffFocusListener()); - - _apiMkcUseCustomModelRunTimeCheckBox - .addActionListener(new UseCustomModelRunStartTimeCheckBoxListener()); - - // the apply button for API-MKC - _apiMkcApplySettingsButton - .addActionListener(new ApplySettingsActionListener()); - - // refresh button for API-MKC state/time list - _apiMkcStateRefreshButton - .addActionListener(new RefreshApiMkcStateListActionListener()); - - _apiMkcCustomModelRunDateTimeTextField.getDocument() - .addDocumentListener( - new CustomModelRunDateTimeChangedDocumentListener()); - - // add listener for Model Change - _modelTypeComboBox.addActionListener(new ModelChoiceListener()); - - // Unithydrograph manual change - _uhgComboBox.addActionListener(new UnitHydrographChoiceListener()); - - // add listener for the Mouse events from TsCanvas - AdjustPrecipMouseListener precipAdjustmentListener = new AdjustPrecipMouseListener(); - _precipCanvas.addMouseListener(precipAdjustmentListener); - _precipCanvas.addMouseMotionListener(precipAdjustmentListener); - _precipCanvas.addKeyListener(precipAdjustmentListener); - - // add listener for the Mouse events from TsCanvas - // _stageCanvas.addTsCanvasEventListener(new - // ModelTimeAdjustmentTsCanvasEventListener()); - AdjustStageMouseListener adjustStageListener = new AdjustStageMouseListener(); - _stageCanvas.addMouseListener(adjustStageListener); - _stageCanvas.addMouseMotionListener(adjustStageListener); - - // SAC_SMA controls - - // add Frame launching button actions - _sacParamsButton.addActionListener(new SacParamsLaunchActionListener()); - _sacStateButton.addActionListener(new SacStateLaunchActionListener()); - - _sacMonthlyMapeValuesEditorButton - .addActionListener(new MonthlyMapeEditorLaunchActionListener()); - - _sacStartingStateComboBox - .addActionListener(new ModelRunStartingStateActionListener( - _sacStartingStateComboBox)); - - // model controls - // add listener for setting the length of forecast - _forecastHoursSpinner - .addChangeListener(new ForecastHoursChangeListener()); - - _adjustmentCheckBox.addActionListener(new AdjustToggleActionListener()); - - _adjustmentLastObsInputTimeTextField.getDocument().addDocumentListener( - new LastObsTimeForAdjustmentChangedDocumentListener()); - - _blendPeriodSpinner - .addChangeListener(new AdjustmentHoursChangeListener()); - - // launches the LiveSacState editor dialog (the one with sliders) - _sacLiveStateAdjustmentButton - .addActionListener(new LiveSacStateLaunchActionListener()); - - // refresh button for SAC_SMA state/time list - _sacStateListRefreshButton - .addActionListener(new RefreshSacSmaStateListActionListener()); - - // create listeners for the time series that can be editted - _streamModel.getEvaporationTimeSeriesHolder().addListener( - new EvaporationTimeSeriesChangeListener()); - _streamModel.getPrecipTimeSeriesHolder().addListener( - new PrecipTimeSeriesChangeListener()); - _streamModel.getForecastStageTimeSeriesHolder().addListener( - new ForecastHeightTimeSeriesChangeListener()); - - } // end addListeners - - // -------used by inner classes - // -------------------------------------------------------------------- - private void usePrecipFileChooserForReading() { - String defaultDirectory = null; - - if (_precipFileChooserHelper == null) { - String[] extensions = { "work" }; - _precipFileChooserHelper = new FileChooserHelper( - _sshp_precip_directoryString, extensions, - "Precip Work files .work"); - } - - String filePath = _precipFileChooserHelper - .displayForOpen(AnalysisWindow.this); - - if (filePath != null) { - _streamModel.reloadFilePrecipTimeSeries(filePath); - runModel(); - } - - return; - } - - // ----------------------------------------------------------------------------------- - private void usePrecipFileChooserForSaving() { - String defaultDirectory = null; - - if (_precipFileChooserHelper == null) { - String[] extensions = { "work" }; - _precipFileChooserHelper = new FileChooserHelper( - _sshp_precip_directoryString, extensions, - "Precip Work files .work"); - } - - String filePath = _precipFileChooserHelper - .displayForSave(AnalysisWindow.this); - - if (filePath != null) { - _streamModel.savePrecipTimeSeriesToFile(filePath); - } - - return; - } - - // ----------------------------------------------------------------------------------- - private void useCaptureScreenFileChooserForSaving() { - BufferedImage image = captureScreenToImage(); - - String defaultDirectory = null; - - if (_imageFileChooserHelper == null) { - String[] extensions = { "jpg", "JPEG", "JPG" }; - _imageFileChooserHelper = new FileChooserHelper( - _whfs_image_directoryString, extensions, - "JPEG files .jpg .JPEG .JPG "); - } - - String filePath = _imageFileChooserHelper - .displayForSave(AnalysisWindow.this); - - if (filePath != null) { - writeImageToFile(image, new File(filePath)); - } - - return; - } - - // -------------------------------------------------------------------------------- - private void displayCaptureScreenFileChooser() { - BufferedImage image = captureScreenToImage(); - - if (_imageFileChooser == null) { - _imageFileChooser = new JFileChooser(_whfs_image_directoryString); - } - - // add a FileFilter for JPG files - List filterList = new ArrayList(); - - filterList.add("JPEG"); - filterList.add("JPG"); - FileFilter fileFilter = new ExtensionFileFilter(filterList, - "JPEG Image Files (*.jpg, *.JPG) "); - - // set the file filter - _imageFileChooser.setFileFilter(fileFilter); - // _imageFileChooser.set - - // open the dialog - int returnVal = _imageFileChooser.showSaveDialog(this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = _imageFileChooser.getSelectedFile(); - - // ensure ends in ".jpg" - if ((!file.getName().endsWith(".jpg")) - && (!file.getName().endsWith(".JPG"))) { - String newFilePath = file.getPath() + ".jpg"; - file = new File(newFilePath); - } - - writeImageToFile(image, file); - } - - else { - // System.out.println("AnalysisWindow.displayCaptureScreenFileChooser(): "); - // JOptionPane.showMessageDialog(AnalysisWindow.this, - // "Image file not saved."); - DialogHelper.displayMessageDialog(AnalysisWindow.this, - "Image file not saved."); - - } - - return; - } - - // ----------------------------------------------------------------- - private void sleep(int millis) { - - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - // ----------------------------------------------------------------- - private BufferedImage captureScreenToImage() { - BufferedImage bufferedImage = null; - try { - - Robot robot = new Robot(); - int x = AnalysisWindow.this.getX(); - int y = AnalysisWindow.this.getY(); - int width = AnalysisWindow.this.getWidth(); - int height = AnalysisWindow.this.getHeight(); - Rectangle rectangleBounds = new Rectangle(x, y, width, height); - - // System.out.println("bounds rectangle of image capture = " + - // rectangleBounds); - bufferedImage = robot.createScreenCapture(rectangleBounds); - - } // end try - - catch (AWTException e) { - e.printStackTrace(); - } - - return bufferedImage; - } - - // ----------------------------------------------------------------- - - private void writeImageToFile(BufferedImage image, File file) { - try { - ImageOutputStream imageOutputStream = new FileImageOutputStream( - file); - ImageIO.write(image, "JPG", imageOutputStream); - imageOutputStream.close(); - } - - catch (java.io.IOException e) { - e.printStackTrace(); - } - - } - - // ----------------------------------------------------------------- - - private void seInitialStageMeasurementFromGui() { - String valueString = _apiMkcInitialStagePanel.getTextField().getText(); - - setInitalStageMeasurementInModelFromString(valueString); - } - - // ----------------------------------------------------------------- - - private void setInitalStageMeasurementInModelFromString( - String initialStageString) { - double value = Double.parseDouble(initialStageString); - - Measurement measurement = new Measurement(value, _stageUnit); - - _streamModel.setInitialStageMeasurement(measurement); - - } - - // ----------------------------------------------------------------- - - private void resetInitialStageMeasurementFromModel() { - // uses a streamModel call to get the Baseflow value, but does not - // change the - // value STORED by the streamModel object - Measurement initialStageMeasurement = _streamModel - .findInitialStageMeasurement(); - - // set the value STORED by the streamModel - _streamModel.setInitialStageMeasurement(initialStageMeasurement); - - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(initialStageMeasurement.getValue()); - - _apiMkcInitialStagePanel.getTextField().setText("" + valueString); - } - - // ----------------------------------------------------------------- - - private void setFfhFromGui() { - String valueString = _apiMkcFfhPanel.getTextField().getText(); - - setFfhFromString(valueString); - } - - // ----------------------------------------------------------------- - - private void setFfhFromString(String ffhString) { - double value = Double.parseDouble(ffhString); - _streamModel.setFfhValue(value); - } - - private void resetFfhFromModel() { - // uses a streamModel call to get the FFH value, but does not change the - // value STORED by the streamModel object - double ffh = _streamModel.findFfhValue(); - - // set the value STORED by the streamModel - _streamModel.setFfhValue(ffh); - - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(ffh); - // System.out.println( - // "AnalysisWindow:resetFfhFromModel(): FFHValue = : " + valueString ); - _apiMkcFfhPanel.getTextField().setText(valueString); - } - - // ----------------------------------------------------------------- - private void loadModelData() { - _streamModel.reloadModelData(); - - if (_streamModel.getRainfallRunoffModelType() == RainfallRunoffModelType.SAC_SMA) { - // do nothing - } else if (_streamModel.getRainfallRunoffModelType() == RainfallRunoffModelType.API_MKC) { - resetFfhFromModel(); - resetInitialStageMeasurementFromModel(); - resetThresholdRunoffFromModel(); - } - } - - // ----------------------------------------------------------------- - private void setApiMkcModelState() { - - String header = "AnalysisWindow.setApiMkcModelState():"; - - FFHDescriptor descriptorToUse = null; - MeasuringUnit ffhUnit = MeasuringUnit.inches; - - if (_apiMkcUseCustomModelRunTime) { - // should use some other method for this - double value = Double.parseDouble(_apiMkcFfhPanel.getTextField() - .getText()); - - long time = _apiMkcCustomModelRunDateTimeTextField.getTime(); - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, - time, ffhUnit); - descriptorToUse = new FFHDescriptor(_streamModel.getLocationId(), - measurement, StreamModel.DEFAULT_FFG_DURATION_CODE, false); - - } else // use the standard selection method - { - - _selectedFFHDescriptor = (FFHDescriptor) _apiMkcStartingStateComboBox - .getSelectedItem(); - - descriptorToUse = _selectedFFHDescriptor; - } - - // if there are no products, - if (descriptorToUse == null) { - - AbsTimeMeasurement fakeFfmMeasurement = new AbsTimeMeasurement(10, - getTimeOfLatestHour(), MeasuringUnit.inches); - - String lid = _streamModel.getLocationId(); - descriptorToUse = new FFHDescriptor(lid, fakeFfmMeasurement, - StreamModel.DEFAULT_FFG_DURATION_CODE, false); - } - - selectFFHProduct(descriptorToUse); - - // System.out.println("AnalysisWindow.setApiMkcModelState : descriptor = " - // + - // descriptorToUse.toString()); - - long newTime = descriptorToUse.getTime(); - - setModelRunStartTime(newTime); - - recenterTimeWindowsAroundModelStartTime(); - - // runModel(); - } - - // ----------------------------------------------------------------- - - private void setSacModelState() { - String header = "AnalysisWindow.setSacModelState():"; - - _selectedSacStateDescriptor = (SacSmaStateDescriptor) _sacStartingStateComboBox - .getSelectedItem(); - - selectSacSmaStateDescriptor(_selectedSacStateDescriptor); - - // make sure that we reload the prior runoff time series, which happens - // in here - - // System.out.println(" ********* AnalysisWindow.setSacModelState() : descriptor = " - // + - // _selectedSacStateDescriptor.toString()); - - long newTime = _selectedSacStateDescriptor.getValidTime(); - setModelRunStartTime(newTime); - - recenterTimeWindowsAroundModelStartTime(); - - // runModel(); - } - - // ----------------------------------------------------------------- - private void selectFFHProduct(FFHDescriptor descriptor) { - _streamModel.setFFHProductDescriptor(descriptor); - - } - - // ----------------------------------------------------------------- - private void selectSacSmaStateDescriptor(SacSmaStateDescriptor descriptor) { - _streamModel.setSacSmaStateDescriptor(descriptor); - } - - // ----------------------------------------------------------------- - private void setModelRunStartTime(long newStartTime) { - - newStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - newStartTime, 1); - _streamModel.setModelStartTime(newStartTime); - - // to make the response time to the clicking faster - // this will happen eventually, anyway after the model run - // _precipCanvas.refresh(); - - String dateTimeString = getDateTimeStringToMinutes(newStartTime); - - // _modelRunStartTimeValueLabel.setText("Model Run Start Time: " + - // dateTimeString); - _modelRunStartTimeValueLabel.setText(dateTimeString); - - // reload the model data, so that the correct parameters and - // states are used. - loadModelData(); - - runModel(); - - } - - // ----------------------------------------------------------------- - - private void setThresholdRunoffFromGui() { - String valueString = _apiMkcThreshRPanel.getTextField().getText(); - - setThresholdRunoffFromString(valueString); - } - - // ----------------------------------------------------------------- - - private void setThresholdRunoffFromString(String thresholdRunoffString) { - double value = Double.parseDouble(thresholdRunoffString); - _streamModel.setThresholdRunoff(value); - } - - // ----------------------------------------------------------------- - - private void resetThresholdRunoffFromModel() { - // uses a streamModel call to get the threshold Runoff value, - // but does not change the - // value STORED by the streamModel object - double thresholdRunoff = _streamModel.findThresholdRunoffValue(); - - // set the value STORED by the streamModel - _streamModel.setThresholdRunoff(thresholdRunoff); - - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(thresholdRunoff); - - _apiMkcThreshRPanel.getTextField().setText(valueString); - } - - // ----------------------------------------------------------------------- - - private void redrawCanvases() { - String header = "AnalysisWindow.redrawCanvases()"; - - _precipCanvas.refresh(); - - _stageCanvas.refresh(); - } - - // ----------------------------------------------------------------------- - - private void initMenuBar() { - _menuBar = new JMenuBar(); - - JMenu menu = null; - JMenuItem menuItem = null; - - // File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new CloseListener()); - menu.add(menuItem); - - // Edit/View Menu - menu = new JMenu("View/Edit"); - menu.setMnemonic(KeyEvent.VK_V); - menu.getAccessibleContext().setAccessibleDescription( - "View/Edit time series data."); - _menuBar.add(menu); - - // edit menu items - - // Precip editor - menuItem = new JMenuItem("Precip Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem.addActionListener(new PrecipTimeSeriesLaunchActionListener()); - - // Forecast Stage Editor - menuItem = new JMenuItem("Forecast Stage Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem - .addActionListener(new ForecastHeightTimeSeriesLaunchActionListener()); - - // ET Time Series editor - menuItem = new JMenuItem("Evapotranspiration Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem - .addActionListener(new EvaporationTimeSeriesLaunchActionListener()); - - // Prior Computed Runoff Viewer - menuItem = new JMenuItem("Prior Runoff Viewer..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem - .addActionListener(new PriorRunoffTimeSeriesLaunchActionListener()); - - // Computed Runoff Viewer - menuItem = new JMenuItem("Runoff Viewer..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem.addActionListener(new RunoffTimeSeriesLaunchActionListener()); - - // Save Menu - menu = new JMenu("Save"); - menu.setMnemonic(KeyEvent.VK_S); - menu.getAccessibleContext().setAccessibleDescription( - "Save time series changes to database."); - _menuBar.add(menu); - - // Save Forecast Stage - menuItem = new JMenuItem("Save Forecast Stage..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem - .addActionListener(new ForecastHeightSaveLaunchActionListener()); - - // Save Forecast Discharge - menuItem = new JMenuItem("Save Forecast Discharge Time Series..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem - .addActionListener(new ForecastDischargeSaveLaunchActionListener()); - - // Save Evaporation Time Series - menuItem = new JMenuItem("Save Evap Time Series.."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem.addActionListener(new EvapSaveLaunchActionListener()); - - // Save Edited MAP Time Series - menuItem = new JMenuItem("Save Edited MAP Time Series.."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription(""); - menu.add(menuItem); - - menuItem.addActionListener(new MAPSaveLaunchActionListener()); - - // reloadPrecipButton directly on menuBar - Color menuBarColor = _menuBar.getBackground(); - Border invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - JButton button = new JButton(" Reload Precip "); - button.addActionListener(new ReloadPrecipTimeSeriesActionListener()); - button.setBorder(invisibleBorder); - button.setSize(60, 30); - String text = "Reload the MAP time series from the database.\n" - + "Changes will be lost."; - button.setToolTipText(text); - _menuBar.add(button); - - // reloadFilePrecipButton directly on menuBar - menuBarColor = _menuBar.getBackground(); - invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - button = new JButton(" Reload File Precip "); - button - .addActionListener(new ReloadFilePrecipTimeSeriesActionListener()); - button.setBorder(invisibleBorder); - button.setSize(60, 30); - text = "Reload the MAP time series from a workfile.\n" - + "Changes will be lost."; - button.setToolTipText(text); - _menuBar.add(button); - - // reloadObsStageButton directly on menuBar - button = new JButton(" Reload Stream Obs. "); - button.addActionListener(new ReloadObsStageTimeSeriesActionListener()); - button.setBorder(invisibleBorder); - button.setSize(80, 30); - text = "Reload the observed stage/discharge time series from the database."; - button.setToolTipText(text); - _menuBar.add(button); - - // separator - - // JSeparator menuSeparator = new JSeparator(); - // menuSeparator.setOrientation(SwingConstants.VERTICAL); - // _menuBar.add(menuSeparator); - - // acts as a separator to move the Help menu all the way to the right - menuItem = new JMenuItem(""); - menuItem.setEnabled(false); - _menuBar.add(menuItem); - - // Help Menu - - menu = new JMenu("Help"); - menu.setMnemonic(KeyEvent.VK_HELP); - menu.getAccessibleContext().setAccessibleDescription( - "Access help menu items."); - _menuBar.add(menu); - - menuItem = new JMenuItem("About..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Display the About Dialog."); - menu.add(menuItem); - - menuItem.addActionListener(new AboutLaunchListener()); - - } - - // ----------------------------------------------------------------------- - - // -----inner classes ------------------------------------------------------ - private class AboutLaunchListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - String aboutText = AboutInfo.getText(); - DialogHelper.displayMessageDialog(AnalysisWindow.this, aboutText, - "About SSHP"); - } - } - - // ----------------------------------------------------------------- - - private class InitialStageResetListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - resetInitialStageMeasurementFromModel(); - runModel(); - - } - } - - // ----------------------------------------------------------------- - - private class InitalStageFocusListener implements FocusListener { - - public InitalStageFocusListener() { - - } - - public void focusGained(FocusEvent event) { - - } - - public void focusLost(FocusEvent event) { - // System.out.println("InitalStageFocusListener triggered"); - - JTextField textField = (JTextField) event.getSource(); - - String initialStageString = textField.getText().trim(); - if (initialStageString.length() == 0) { - // consider putting an error dialog here - } else { - try { - setInitalStageMeasurementInModelFromString(initialStageString); - } catch (Throwable t) { - // consider putting an error dialog here - } - } - - // the apply button does this now - // runModel(); - - } // end focusLost - - } - - // ----------------------------------------------------------------- - - private class FfhResetListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - resetFfhFromModel(); - runModel(); - } - } - - // ----------------------------------------------------------------- - - private class ApplySettingsActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - // System.out.println("ApplySettingsActionListener triggered"); - updateModelSettingsFromGui(); - // setApiMkcModelState(); - runModel(); - } - } - - // ----------------------------------------------------------------- - - private class RefreshSacSmaStateListActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - // System.out.println("RefreshSacSmaStateListActionListener triggered"); - - initSacStateComboBox(_sacStartingStateComboBox); - } - } - - // ----------------------------------------------------------------- - - private class RefreshApiMkcStateListActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - // System.out.println("RefreshApiMkcStateListActionListener triggered"); - - initApiMkcStateComboBox(_apiMkcStartingStateComboBox); - } - } - - private class ReloadPrecipTimeSeriesActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - DialogHelper.setWaitCursor(_menuBar); - _streamModel.reloadPrecipTimeSeries(); - runModel(); - DialogHelper.setDefaultCursor(_menuBar); - } - } - - // ----------------------------------------------------------------- - - private class ReloadFilePrecipTimeSeriesActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - DialogHelper.setWaitCursor(_menuBar); - - usePrecipFileChooserForReading(); - - DialogHelper.setDefaultCursor(_menuBar); - } - } - - // ----------------------------------------------------------------- - - private class ReloadObsStageTimeSeriesActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - DialogHelper.setWaitCursor(_menuBar); - - _streamModel.reloadObservedStageTimeSeries(); - runModel(); - - DialogHelper.setDefaultCursor(_menuBar); - - } - } - - // ----------------------------------------------------------------- - - private class FfhFocusListener implements FocusListener { - - public FfhFocusListener() { - - } - - public void focusGained(FocusEvent event) { - - } - - public void focusLost(FocusEvent event) { - // System.out.println("FfhFocusListener triggered"); - - JTextField textField = (JTextField) event.getSource(); - - String ffhString = textField.getText().trim(); - if (ffhString.length() == 0) { - resetFfhFromModel(); // just set it back to the value in the - // streamModel. - } else { - try { - setFfhFromString(ffhString); - - } catch (Throwable t) { - resetFfhFromModel(); // just set it back to the value in the - // streamModel. - } - } - - // the apply button does this now - // runModel(); - - } // end focusLost - - } - - // ----------------------------------------------------------------- - - private class ThreshRunoffResetListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - resetThresholdRunoffFromModel(); - runModel(); - - } - } - - // ----------------------------------------------------------------- - - private class ThreshRunoffFocusListener implements FocusListener { - - public ThreshRunoffFocusListener() { - - } - - public void focusGained(FocusEvent event) { - - } - - public void focusLost(FocusEvent event) { - // System.out.println("ThreshRunoffFocusListener triggered"); - - JTextField textField = (JTextField) event.getSource(); - - // System.out.println("AnalysisWindow.ThreshRFocusLost listener activated"); - - String thresholdRunoffString = textField.getText().trim(); - if (thresholdRunoffString.length() == 0) { - resetThresholdRunoffFromModel(); // just set it back to the - // value in the streamModel. - } else { - try { - setThresholdRunoffFromString(thresholdRunoffString); - } catch (Throwable t) { - resetThresholdRunoffFromModel(); // just set it back to the - // value in the - // streamModel. - } - } - - // the apply button does this now - // runModel(); - - } // end focusLost - - } - - // ----------------------------------------------------------------- - - private class CanvasMouseMovedListener extends MouseMotionAdapter { - private TsPaintableCanvas _canvas = null; - - private ValueMapper _valueMapper = null; - - public CanvasMouseMovedListener(TsPaintableCanvas canvas, - ValueMapper valueMapper) { - _canvas = canvas; - _valueMapper = valueMapper; - } - - @Override - public void mouseMoved(MouseEvent event) { - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = _canvas.getViewport().getDataPoint( - screenPoint); - - if (_canvas.getViewport().isViewable(dataPoint)) { - updateDataPointText(dataPoint, _valueMapper, _canvas); - } - } - - } - - // ----------------------------------------------------------------- - - private class FrameCloseWindowListener extends WindowAdapter { - @Override - public void windowClosing(WindowEvent evt) { - dispose(); - } - - } - - // ----------------------------------------------------------------- - - private class CloseListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - dispose(); - } - } - - // ----------------------------------------------------------------- - private class ControlWindowFocusActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - _controller.bringLaunchWindowToFront(); - } - } - - // ----------------------------------------------------------------- - private class FloodStageCheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - _forceShowFloodStage = _showFloodStageCheckBox.isSelected(); - _floodStageLinePainter.setShouldPaint(_forceShowFloodStage); - redrawCanvases(); - } - - } - - // ----------------------------------------------------------------- - - private class MajorFloodStageCheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - if (_majorFloodStageLinePainter != null) { - _forceShowMajorFloodStage = _showMajorFloodStageCheckBox - .isSelected(); - _majorFloodStageLinePainter - .setShouldPaint(_forceShowMajorFloodStage); - redrawCanvases(); - } - } - } - - // ----------------------------------------------------------------- - private class ShowPrecipAmountsCheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - _showPrecipAmounts = _showPrecipAmountsCheckBox.isSelected(); - _precipPainter.setShowPrecipAmounts(_showPrecipAmounts); - _precipTextTotalPainter.setShouldPaint(_showPrecipAmounts); - redrawCanvases(); - } - - } - - // ----------------------------------------------------------------- - private class ShowObservedHeightTsCheckBoxListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - _showObservedHeightData = _showObsHeightTsCheckBox.isSelected(); - _observedStageTsPainter.setShouldPaint(_showObservedHeightData); - - redrawCanvases(); - } - } - - // ----------------------------------------------------------------- - private class DelayRerunCheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - _delayRerunModelWhileDrawing = _delayRerunCheckBox.isSelected(); - } - - } - - // ----------------------------------------------------------------- - private class ShowMinorPrecipTicksCheckBoxListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - _showMinorPrecipTicks = _showMinorPrecipTicksCheckBox.isSelected(); - _precipBackgroundPainter.setShowMinorTicks(_showMinorPrecipTicks); - redrawCanvases(); - } - - } - - // ----------------------------------------------------------------- - private class ShowMinorStageTicksCheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - _showMinorStageTicks = _showMinorStageTicksCheckBox.isSelected(); - _stageBackgroundPainter.setShowMinorTicks(_showMinorStageTicks); - redrawCanvases(); - } - - } - - private class ShowSimulatedStageCheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - _showSimulatedStage = _showSimulatedStageCheckBox.isSelected(); - _simulatedStageTsPainter.setShouldPaint(_showSimulatedStage); - redrawCanvases(); - } - - } - - // ----------------------------------------------------------------- - private class UseCustomModelRunStartTimeCheckBoxListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - - _apiMkcUseCustomModelRunTime = _apiMkcUseCustomModelRunTimeCheckBox - .isSelected(); - setApiMkcModelState(); - runModel(); - } - - } - - // ----------------------------------------------------------------- - private class TimeWindowRecenterActionListener implements ActionListener { - - public void actionPerformed(ActionEvent evt) { - recenterTimeWindowsAroundModelStartTime(); - } - - } // end TimeWindowRecenterActionListener - - // ----------------------------------------------------------------- - private class TimeWindowSlideListener implements ActionListener { - private int _slideHours = 0; - - public TimeWindowSlideListener(int slideHours) { - _slideHours = slideHours; - } - - public void actionPerformed(ActionEvent evt) { - - _precipCanvas.slideTimeWindow(_slideHours); - _stageCanvas.slideTimeWindow(_slideHours); - - } - - } // end TimeWindowSlideListener; - - // ----------------------------------------------------------------- - private class AdjustStageMouseListener extends MouseAdapter implements - MouseMotionListener { - private boolean _button3Down = false; - - private boolean _tipShownOnce = false; - - @Override - public void mouseDragged(MouseEvent event) { - - if (_button3Down) { - Point point = event.getPoint(); - adjustStage(point); - } - - } - - @Override - public void mouseMoved(MouseEvent event) { - // do nothing - return; - } - - @Override - public void mouseReleased(MouseEvent event) { - int button = event.getButton(); - - if (button == MouseEvent.BUTTON3) { - _button3Down = false; - } - - return; - } - - @Override - public void mousePressed(MouseEvent event) { - int button = event.getButton(); - - if (button == MouseEvent.BUTTON3) { - _button3Down = true; - } - - return; - - } - - @Override - public void mouseClicked(MouseEvent event) { - if (event.getButton() == MouseEvent.BUTTON3) { - adjustStage(event.getPoint()); - } else if ((event.getButton() == MouseEvent.BUTTON1) - || ((event.getButton() == MouseEvent.BUTTON2))) { - if (!_tipShownOnce) { - _tipShownOnce = true; - DialogHelper - .displayMessageDialog( - AnalysisWindow.this, - "TIP: To avoid accidental editing of the forecast hydrograph,\n the" - + " application requires the user to click the right mouse\n button to edit the hydrograph."); - } - } - _button3Down = false; - - } // end mouseClicked - - private void adjustStage(Point point) { - AbsTimeMeasurement measurement = _stageCanvas - .getAbsTimeMeasurementByRounding(point); - - if (measurement.getValue() < 0.0) { - measurement.setValue(0.0); - } - - if (measurement.getTime() >= _modelStartTimeHolder.getTime())// forecast - // precip - { - if (measurement.getValue(MeasuringUnit.feet) <= MAX_STAGE_IN_FEET) { - replaceTimeSeriesValue(_streamModel - .getForecastStageTimeSeriesHolder(), measurement); - - // redraw the StageCanvas - _stageCanvas.refresh(); - - // let any observer know of the change - announceForecastStageEdited(); - } - } - - } - - } // end StageAdjustmentTsCanvasEventListener - - // ----------------------------------------------------------------- - private class AdjustPrecipMouseListener extends MouseAdapter implements - MouseMotionListener, KeyListener - - { - private boolean _button1Down = false; - - private boolean _tipShownOnce = false; - - // variables related to keyboard commands - private boolean _hasFocus = false; - - private Point _mousePosition = null; - - // List _pointList = new ArrayList(); - - @Override - public void mouseDragged(MouseEvent event) { - // Point point = event.getPoint(); - // _pointList.add(point); - - if (_button1Down) { - Point point = event.getPoint(); - // System.out.println("activated mouseDragged"); - // System.out.println("activated mouseDragged, button = " + - // button ); - adjustPrecip(point); - } - - } - - @Override - public void mouseMoved(MouseEvent event) { - _mousePosition = event.getPoint(); - // do nothing - } - - @Override - public void mousePressed(MouseEvent event) { - // System.out.println("Precip adjust listener: mousePressed()"); - int button = event.getButton(); - if (button == MouseEvent.BUTTON1) { - _button1Down = true; - } else { - if (!_tipShownOnce) { - _tipShownOnce = true; - DialogHelper.displayMessageDialog(AnalysisWindow.this, - "TIP: Use the left mouse button to edit precip."); - - } - } - - return; - - } - - @Override - public void mouseReleased(MouseEvent event) { - // System.out.println("Precip adjust listener: mouseReleased()"); - int button = event.getButton(); - - if (button == MouseEvent.BUTTON1) { - _button1Down = false; - - adjustPrecip(event.getPoint()); - - // if I am delaying, I need to redraw when button released, - // otherwise, adjustPrecip - if (_delayRerunModelWhileDrawing) { - runModel(); - } - } - - } - - @Override - public void mouseEntered(MouseEvent event) { - // get the focus on this canvas, so that the keyboard commands will - // work on it - AnalysisWindow.this._precipCanvas.requestFocusInWindow(); - // System.out.println("mouseEntered():" + " requested focus "); - _hasFocus = true; - } - - @Override - public void mouseExited(MouseEvent event) { - // System.out.println("mouseExited():" + - // " requested focus elsewhere "); - // System.out.println("Precip adjust listener: mouseExited()"); - - // when exit the window, if was delaying drawing, stop delaying - if ((_delayRerunModelWhileDrawing) && (_button1Down)) { - runModel(); - } - - // make sure that some other widget has focus, - // so that keyboard clicks are not registered by the - // precip canvas listeners - AnalysisWindow.this._stageCanvas.requestFocusInWindow(); - - _hasFocus = false; - } - - public void keyPressed(KeyEvent e) { - int keyCode = e.getKeyCode(); - char keyChar = e.getKeyChar(); - - System.out.println("keyPressed: " + keyChar); - - if ((keyCode == KeyEvent.VK_UP) || (keyCode == KeyEvent.VK_RIGHT)) { - System.out.println("Up typed"); - adjustPrecipByDeltaValue(0.01, _mousePosition); - } - - if ((keyCode == KeyEvent.VK_DOWN) || (keyCode == KeyEvent.VK_LEFT)) { - System.out.println("Down typed"); - adjustPrecipByDeltaValue(-0.01, _mousePosition); - } - } - - public void keyReleased(KeyEvent e) { - - } - - public void keyTyped(KeyEvent e) { - - } - - private void adjustPrecipByDeltaValue(double changeInValue, Point point) { - System.out - .println("Precip adjust listener: adjustPrecipByDeltaValue()"); - - AbsTimeMeasurement measurement = _precipCanvas - .getAbsTimeMeasurementByTruncation(point); - - // for precip, we are focused on the end time, so add an hour - long endTime = measurement.getTime() - + (_intervalInHours * MILLIS_PER_HOUR); - - RegularTimeSeriesHolder tsHolder = _streamModel - .getPrecipTimeSeriesHolder(); - - AbsTimeMeasurement oldMeasurement = tsHolder.getTimeSeries() - .getAbsTimeMeasurementByTime(endTime); - - measurement.setValue(oldMeasurement.getValue() + changeInValue); - measurement.setTime(endTime); - - if (measurement.getValue() < 0.0) { - measurement.setValue(0.0); - } - - TimeIntervalMeasurement newMeasurement = new TimeIntervalMeasurement( - measurement.getValue(), measurement.getTime(), - _intervalInHours, measurement.getUnit()); - - double value = measurement.getValue(MeasuringUnit.inches); - boolean valueIsInRange = false; - boolean timeIsInRange = false; - - if (value <= MAX_PRECIP_IN_INCHES_PER_HOUR) { - valueIsInRange = true; - } - - // ending time at or before model start time is not allowed, since - // the period is before - if (measurement.getTime() > _streamModel.getModelStartTime()) { - timeIsInRange = true; - } - - if (valueIsInRange && timeIsInRange) { - RegularTimeSeriesHolder timeSeriesHolder = null; - - timeSeriesHolder = _streamModel.getPrecipTimeSeriesHolder(); - replaceTimeSeriesValue(timeSeriesHolder, newMeasurement); - - // redraw the PrecipCanvas - _precipCanvas.refresh(); - - // if not delaying, then rerun the model right now - if (!_delayRerunModelWhileDrawing) { - runModel(); - } - } - - } // end adjustPrecipByValue - - private void adjustPrecip(Point point) { - // System.out.println("Precip adjust listener: adjustPrecip()"); - - AbsTimeMeasurement measurement = _precipCanvas - .getAbsTimeMeasurementByTruncation(point); - - // System.out.println(header + measurement); - - if (measurement.getValue() < 0.0) { - measurement.setValue(0.0); - } - - // for precip, we are focused on the end time, so add an hour - long endTime = measurement.getTime() - + (_intervalInHours * MILLIS_PER_HOUR); - measurement.setTime(endTime); - - TimeIntervalMeasurement newMeasurement = new TimeIntervalMeasurement( - measurement.getValue(), measurement.getTime(), - _intervalInHours, measurement.getUnit()); - - double value = measurement.getValue(MeasuringUnit.inches); - boolean valueIsInRange = false; - boolean timeIsInRange = false; - - if (value <= MAX_PRECIP_IN_INCHES_PER_HOUR) { - valueIsInRange = true; - } - - // ending time at or before model start time is not allowed, since - // the period is before - if (measurement.getTime() > _streamModel.getModelStartTime()) { - timeIsInRange = true; - } - - if (valueIsInRange && timeIsInRange) { - RegularTimeSeriesHolder timeSeriesHolder = null; - - timeSeriesHolder = _streamModel.getPrecipTimeSeriesHolder(); - replaceTimeSeriesValue(timeSeriesHolder, newMeasurement); - - // redraw the PrecipCanvas - _precipCanvas.refresh(); - - // if not delaying, then rerun the model right now - if (!_delayRerunModelWhileDrawing) { - runModel(); - } - } - - } // end adjustPrecip - - } // end PrecipAdjustmentTsCanvasEventListener - - // -------------------------------------------------------------------- - private class ModelRunStartingStateActionListener implements ActionListener { - - private JComboBox _comboBox = null; - - public ModelRunStartingStateActionListener(JComboBox comboBox) { - _comboBox = comboBox; - } - - public void actionPerformed(ActionEvent evt) { - - if (_comboBox == AnalysisWindow.this._apiMkcStartingStateComboBox) { - if (!_reloadingApiMkcStartingStateComboBox) { - setApiMkcModelState(); - } - } else if (_comboBox == AnalysisWindow.this._sacStartingStateComboBox) { - if (!_reloadingSacStartingStateComboBox) { - setSacModelState(); - } - } - - } - - } // end ModelRunStartTimeActionListener; - - // -------------------------------------------------------------------- - private class CustomModelRunDateTimeChangedDocumentListener implements - DocumentListener { - - public void insertUpdate(DocumentEvent arg0) { - // don't bother to rerun the model if you aren't supposed to use - // this time anyway - if (_apiMkcUseCustomModelRunTime) { - setApiMkcModelState(); - runModel(); - } - } - - public void removeUpdate(DocumentEvent arg0) { - // System.out.println("CustomModelRunDateTimeChangedActionListener.removeUpdate()"); - - } - - public void changedUpdate(DocumentEvent arg0) { - // System.out.println("CustomModelRunDateTimeChangedActionListener.changedUpdate()"); - // setApiMkcModelState(); - // runModel(); - - } - - } - - private class LastObsTimeForAdjustmentChangedDocumentListener implements - DocumentListener { - - public void insertUpdate(DocumentEvent arg0) { - - // String header = - // "LastObsTimeForAdjustmentChangedDocumentListener.insertUpdate(): "; - - long lastTime = _adjustmentLastObsInputTimeTextField.getTime(); - - // System.out.println(header + " lastTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(lastTime)); - - _streamModel.setLastObservedTimeForAdjustment(lastTime); - - // don't bother to rerun the model if you aren't supposed to use - // this time anyway - if (_streamModel.isAdjustmentOn()) { - - runModel(); - } - } - - public void removeUpdate(DocumentEvent arg0) { - - } - - public void changedUpdate(DocumentEvent arg0) { - - } - - } - - // -------------------------------------------------------------------- - private class ModelChoiceListener implements ActionListener { - // private int _invocationCount = 0; - - public void actionPerformed(ActionEvent event) { - // _invocationCount ++; - // System.out.println("---------------ModelChoiceListener.actionPerformed() invoked " - // + _invocationCount + " times."); - - setModelTypeToComboBoxSelection(); - } - } - - // -------------------------------------------------------------------- - private class UnitHydrographChoiceListener implements ActionListener { - // private int _invocationCount = 0; - - public void actionPerformed(ActionEvent event) { - setUnitHydrographToComboBoxSelection(); - } - } - - // -------------------------------------------------------------------- - private class ForecastHeightTimeSeriesLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getForecastStageTimeSeriesHolder(); - String titleString = "Forecast Stage Editor"; - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - } - String valueLabelString = "Stage (" + unitString + ")"; - ValueMapper valueMapper = new StageToFlowValueMapper(_streamModel - .getRatingCurve()); - - String mappedUnitString = valueMapper.getOutputMeasuringUnit() - .getName(); - String mappedValueLabelString = "Discharge(" + mappedUnitString - + ")"; - - boolean isModal = false; - boolean isEditable = true; - - long initialSearchTime = 0; - double missingValue = _defaultMissingValue; - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, MIN_STAGE_IN_FEET, - MAX_STAGE_IN_FEET); - - editor = new RegularTimeSeriesEditor(descriptor); - - // editor.addApplyActionListener(new - // ForecastHeightTimeSeriesApplyActionListener()); - editor.setVisible(true); - } - } - - // -------------------------------------------------------------------- - private class PrecipTimeSeriesLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getPrecipTimeSeriesHolder(); - String titleString = "Mean Areal Precip Editor"; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - } - String valueLabelString = "Precip (" + unitString + ")"; - - boolean isEditable = true; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - long initialSearchTime = _streamModel.getModelStartTime() - + _millisPerHour; - double missingValue = _defaultMissingValue; - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, - MIN_PRECIP_IN_INCHES_PER_HOUR, - MAX_PRECIP_IN_INCHES_PER_HOUR); - - editor = new RegularTimeSeriesEditor(descriptor); - editor.setVisible(true); - - return; - } - } - - // -------------------------------------------------------------------- - private class EvaporationTimeSeriesLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getEvaporationTimeSeriesHolder(); - String titleString = "Mean Areal Potential Evaporation"; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - } - String valueLabelString = "Evap. (" + unitString + ")"; - - // editor = new RegularTimeSeriesEditor(AnalysisWindow.this, - // tsHolder, title, valueLabelString); - - boolean isEditable = true; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - long initialSearchTime = _streamModel.getModelStartTime(); - double missingValue = _defaultMissingValue; - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, MIN_EVAP_PER_HOUR, - MAX_EVAP_PER_HOUR); - - editor = new RegularTimeSeriesEditor(descriptor); - - editor.setVisible(true); - - } - } - - // -------------------------------------------------------------------- - private class PriorRunoffTimeSeriesLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getPriorRunoffTimeSeriesHolder(); - String titleString = "Prior Computed Runoff "; - - RegularTimeSeries ts = tsHolder.getTimeSeries(); - MeasuringUnit unit = null; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - String valueLabelString = "Runoff (" + unitString + ")"; - - boolean isEditable = false; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - long initialSearchTime = _streamModel.getModelStartTime(); - double missingValue = _defaultMissingValue; - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, - MIN_RUNOFF_IN_INCHES_PER_HOUR, - MAX_RUNOFF_IN_INCHES_PER_HOUR); - - editor = new RegularTimeSeriesEditor(descriptor); - - // this is not editable, so there is no apply action listener - // editor.addApplyActionListener(new - // PriorRunoffTimeSeriesApplyActionListener()); - - editor.setVisible(true); - - } - - else { - // JOptionPane.showMessageDialog(AnalysisWindow.this, - // "Sorry, there is no prior computed runoff."); - DialogHelper.displayMessageDialog(AnalysisWindow.this, - "Sorry, there is no prior computed runoff."); - } - - } - } - - // -------------------------------------------------------------------- - private class RunoffTimeSeriesLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getRunoffTimeSeriesHolder(); - String titleString = "Computed Runoff "; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - } - String valueLabelString = "Runoff (" + unitString + ")"; - - boolean isEditable = false; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - long initialSearchTime = _streamModel.getModelStartTime() - + _millisPerHour; - double missingValue = _defaultMissingValue; - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, - MIN_RUNOFF_IN_INCHES_PER_HOUR, - MAX_RUNOFF_IN_INCHES_PER_HOUR); - - editor = new RegularTimeSeriesEditor(descriptor); - editor.setVisible(true); - } - } - - // -------------------------------------------------------------------- - private class ForecastHeightSaveLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - ForecastTsSaveDialog dialog = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getForecastStageTimeSeriesHolder(); - String title = "Forecast Height Time Series Save Dialog"; - String locId = _streamModel.getLocationId(); - - String tableName = "FcstHeight"; - // String[] physicalElementStringArray = {"HG", "HP", "HT"}; - - String[] physicalElementStringArray = _streamModel.getPeArray('H'); - - String primaryPe = _streamModel.getPrimaryPe(); - String preferredPhysicalElement = primaryPe; - - if (primaryPe.charAt(0) != 'H') { - preferredPhysicalElement = "HG"; - } - - dialog = new ForecastTsSaveDialog(AnalysisWindow.this, locId, - title, tsHolder, _streamModel.getDataMgr(), tableName, - physicalElementStringArray, preferredPhysicalElement); - - dialog.setVisible(true); - - } - } - - // -------------------------------------------------------------------- - private class ForecastDischargeSaveLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - ForecastTsSaveDialog dialog = null; - - RegularTimeSeries dischargeTimeSeries = _streamModel - .getDischargeTimeSeries(); - RegularTimeSeriesHolder dischargeTimeSeriesHolder = new RegularTimeSeriesHolder(); - dischargeTimeSeriesHolder.setTimeSeries(dischargeTimeSeries); - - String title = "Forecast Discharge Time Series Save Dialog"; - String locId = _streamModel.getLocationId(); - - String tableName = "FcstDischarge"; - // String[] physicalElementStringArray = {"QR"}; - - String[] physicalElementStringArray = _streamModel.getPeArray('Q'); - - String primaryPe = _streamModel.getPrimaryPe(); - String preferredPhysicalElement = primaryPe; - if (primaryPe.charAt(0) != 'Q') { - preferredPhysicalElement = "QR"; - } - - dialog = new ForecastTsSaveDialog(AnalysisWindow.this, locId, - title, dischargeTimeSeriesHolder, - _streamModel.getDataMgr(), tableName, - physicalElementStringArray, preferredPhysicalElement); - - dialog.setVisible(true); - - } - } - - // -------------------------------------------------------------------- - private class EvapSaveLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - ForecastTsSaveDialog dialog = null; - - RegularTimeSeriesHolder tsHolder = _streamModel - .getEvaporationTimeSeriesHolder(); - String title = "Evapotranspiration Time Series Save Dialog"; - String locId = _streamModel.getLocationId(); - - String tableName = "FcstOther"; - String[] physicalElementStringArray = { "EA" }; - String preferredPhysicalElement = "EA"; - - dialog = new ForecastTsSaveDialog(AnalysisWindow.this, locId, - title, tsHolder, _streamModel.getDataMgr(), tableName, - physicalElementStringArray, preferredPhysicalElement); - dialog - .addApplyActionListener(new ForecastOtherSaveCompleteListener()); - - dialog.setVisible(true); - - } - } - - // ---------------------------------------------------------------------------------------------- - - private class MAPSaveLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - usePrecipFileChooserForSaving(); - } - } - - // -------------------------------------------------------------------- - private class SacParamsLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - - String basinId = _streamModel.getBasinId(); - - SacParamsEditor editor = null; - editor = new SacParamsEditor(AnalysisWindow.this, _streamModel - .getDataMgr(), basinId); - - editor - .addApplyActionListener(new SacParamsSaveCompleteActionListener()); - - editor.setVisible(true); - } - } - - // -------------------------------------------------------------------- - private class AdjustToggleActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - boolean isAdjustmentOn = _adjustmentCheckBox.isSelected(); - _streamModel.setAdjustmentOn(isAdjustmentOn); - runModel(); - } - } - - // -------------------------------------------------------------------- - private class AdjustmentHoursChangeListener implements ChangeListener { - public void stateChanged(ChangeEvent e) { - - Integer integer = (Integer) _blendPeriodSpinner.getValue(); - - int newValue = integer.intValue(); - - // _blendPeriodValueLabel.setText(newValue + "" ); - - if (_streamModel.isAdjustmentOn()) { - _streamModel.setAdjustmentHours(newValue); - runModel(); - } - } - - } - - // -------------------------------------------------------------------- - - private class LiveSacStatesAdjustmentActionListener implements - ActionListener { - public void actionPerformed(ActionEvent event) { - // final String header = - // "LiveSacStatesAdjustmentActionListener.actionPeformed(): "; - // System.out.println(header + "message = " + - // event.getActionCommand()); - - runModel(); - } - } - - // -------------------------------------------------------------------- - - private class ForecastHoursChangeListener implements ChangeListener { - public void stateChanged(ChangeEvent e) { - Integer integer = (Integer) _forecastHoursSpinner.getValue(); - int newValue = integer.intValue(); - - _streamModel.setForecastLengthInHours(newValue); - runModel(); - - } - } - - // -------------------------------------------------------------------- - - private class SacStateLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - String basinId = _streamModel.getBasinId(); - - SacStateEditor editor = null; - editor = new SacStateEditor(AnalysisWindow.this, _streamModel - .getDataMgr(), basinId); - - editor - .addApplyActionListener(new SacStateSaveCompleteActionListener()); - editor.setVisible(true); - - } - } - - private class LiveSacStateLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - boolean isModal = false; - - // used by AnalysisWindow to call runModel(); - ActionListener liveSacStatesAdjustmentActionListener = new LiveSacStatesAdjustmentActionListener(); - - LiveSacStateEditor editor = new LiveSacStateEditor( - AnalysisWindow.this, _streamModel.getSacState(), - _streamModel.getSacParams(), isModal, - liveSacStatesAdjustmentActionListener); - - editor.setVisible(true); - - } - } - - // -------------------------------------------------------------------- - - private class SacStateSaveCompleteActionListener implements ActionListener { - // make sure that the model settings are reloaded and - // then rerun the model - public void actionPerformed(ActionEvent evt) { - - _streamModel.reloadModelData(); - - _streamModel.runModel(); - - } - } - - // -------------------------------------------------------------------- - - private class SacParamsSaveCompleteActionListener implements ActionListener { - // make sure that the model settings are reloaded and - // then rerun the model - public void actionPerformed(ActionEvent evt) { - _streamModel.reloadModelData(); - - _streamModel.runModel(); - - } - } - - // -------------------------------------------------------------------- - - private class MonthlyMapeEditorLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - MonthlyValueEditor editor = null; - - JFrame ownerFrame = AnalysisWindow.this; - DataMgr dataMgr = _streamModel.getDataMgr(); - String basinId = _streamModel.getBasinId(); - boolean isModal = false; - String pe = "EA"; - - editor = new MonthlyValueEditor(ownerFrame, dataMgr, basinId, pe, - isModal); - editor.setVisible(true); - - } - } - - // -------------------------------------------------------------------- - - private class ForecastOtherSaveCompleteListener implements ActionListener { - // a listener for the forecast save dialog - public void actionPerformed(ActionEvent event) { - // System.out.println("ForecastOtherSaveCompleteListener invoked"); - // do nothing, needed to fulfill editor class obligations - } - - } - - // -------------------------------------------------------------------- - - private class ForecastHeightTimeSeriesChangeListener implements - TimeSeriesListener { - public Object getReceiver() { - return AnalysisWindow.this; - } - - public void handleTimeSeriesEvent(TimeSeriesEvent event) { - // String header = - // "ForecastHeightTimeSeriesChangeListener.handleTimeSeriesEvent()"; - // System.out.println(header + "event = " + event.toString()); - redrawCanvases(); - - } - } - - // -------------------------------------------------------------------- - - private class PrecipTimeSeriesChangeListener implements TimeSeriesListener { - - public Object getReceiver() { - return AnalysisWindow.this; - } - - // used for receiving events from precip tabular editing - public void handleTimeSeriesEvent(TimeSeriesEvent event) { - // String header = - // "PrecipTimeSeriesChangeListener.handleTimeSeriesEvent()"; - // System.out.println(header + "event = " + event.toString()); - runModel(); - - } - - } - - // -------------------------------------------------------------------- - - private class EvaporationTimeSeriesChangeListener implements - TimeSeriesListener { - - public Object getReceiver() { - return AnalysisWindow.this; - } - - // used for tabular editing of the evaporation time series - public void handleTimeSeriesEvent(TimeSeriesEvent event) { - // String header = - // "EvaporationTimeSeriesChangeListener.handleTimeSeriesEvent()"; - // System.out.println(header + "event = " + event.toString()); - runModel(); - - } - - } - - // -------------------------------------------------------------------- - - private class ScreenCaptureActionListener implements ActionListener { - public void actionPerformed(ActionEvent event) { - - useCaptureScreenFileChooserForSaving(); - // AnalysisWindow.this.displayCaptureScreenFileChooser(); - - } // end actionPerformed - - } // end ScreenCaptureActionListener - - // -------------------------------------------------------------------- - - // ----------------------------------------------------------------- -} // end class AnalysisWindow diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindow.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindow.java deleted file mode 100644 index d4adf5bc7f..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindow.java +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Created on Dec 19, 2003 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableColumn; - -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.sshp.AboutInfo; -import ohd.hseb.sshp.AppController; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.gui.GuiHelper; -import ohd.hseb.sshp.precip.MAPPreprocessor; -import ohd.hseb.util.EnvHelper; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableColumnComparator; -import ohd.hseb.util.gui.WindowResizingManager; - -import com.raytheon.uf.common.util.RunProcess; - -/** - * @author GobsC This class is the startup window for the SSHP application when - * no argument for the location id is entered. It allows for the - * selection of a location. - */ -public class ControlWindow extends JFrame { - private Dimension _maxDimension = new Dimension(800, 700); - - private Dimension _initialDimension = new Dimension(800, 400); - - private Dimension _minDimension = new Dimension(600, 200); - - private AppController _controller = null; - - private List _locationIdList = null; - - private DataMgr _dataMgr = null; - - // ---GUI items------------------------ - - private JMenuBar _menuBar = null; - - private JPanel _mainPanel = null; - - private JPanel _selectionPanel = null; - - private JLabel _locationLabel = null; - - private ControlWindowTableAdapter _tableAdapter = null; - - private JPanel _buttonPanel = null; - - private JButton _exitButton = null; - - private JButton _launchButton = null; - - public static final String LID = "Location Id"; - - public static final String NAME = "Name"; - - public static final String BASIN_ID = "Basin Id"; - - public static final String STREAM_NAME = "Stream Name"; - - public static final String HSA = "HSA"; - - public static final String MODEL_PREFERENCE = "RR Model Pref"; // rainfall-runoff - // model - // preference - - private List _descriptorList = null; - - private LocationDescriptor _selectedLocationDescriptor = null; - - // --------------------------------------------------------------------- - - public ControlWindow(DataMgr dataMgr, AppController controller) { - _dataMgr = dataMgr; - _controller = controller; - - initGui(); - } - - // --------------------------------------------------------------------- - public void enableLaunchButton(boolean value) { - _launchButton.setEnabled(value); - } - - // --------------------------------------------------------------------- - - private void initGui() { - // Dimension scrolledPaneDimension = new Dimension(500, 300); - - initMenuBar(); - setJMenuBar(_menuBar); - - // String header = "LaunchWindow.initGui(): "; - setTitle("Site Specific Hydrologic Predictor Control Window on " - + _dataMgr.getDatabaseName()); - - JPanel spaceFiller = new JPanel(); - // Note: setMinimumSize() does not work for this purpose - spaceFiller.setPreferredSize(new Dimension(300, 100)); - - // selection Panel - - createSelectionPanel(); - - // button Panel - _buttonPanel = new JPanel(); - _launchButton = GuiHelper.getJButton("Analysis Window..."); - _exitButton = GuiHelper.getJButton("Exit Application"); - - _buttonPanel.add(_launchButton); - _buttonPanel.add(_exitButton); - - // setup the main panel - - _mainPanel = new JPanel(); - // _mainPanel.setPreferredSize(new Dimension(DEFAULT_WIDTH, - // DEFAULT_HEIGHT)); - - GridBagLayout layoutMgr = new GridBagLayout(); - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _mainPanel.setLayout(layoutMgr); - // col, row numCols numRows Wcol wrow - addComponent(_mainPanel, spaceFiller, mainGbc, 0, 0, 1, 1, 0, 0); - addComponent(_mainPanel, _selectionPanel, mainGbc, 0, 1, 1, 1, 1, 1); - addComponent(_mainPanel, _buttonPanel, mainGbc, 0, 2, 2, 2, 0, 0); - - // set up initial bounds limitations - // see WindowResize listener for the minimum setting - - Rectangle maxBoundsRectangle = new Rectangle(_maxDimension); - this.setMaximizedBounds(maxBoundsRectangle); - - // hook up the mainPanel to the contentPane - - this.getContentPane().add(_mainPanel); - this.pack(); - - Rectangle initialBoundsRectangle = new Rectangle(_initialDimension); - this.setBounds(initialBoundsRectangle); - - addListeners(); - - return; - } - - // --------------------------------------------------------------------- - private void createSelectionPanel() { - Dimension selectionPanelDimension = new Dimension(800, 700); - - _locationLabel = new JLabel("Available Locations:"); - _locationIdList = _dataMgr.loadLocationIdsForForecasts(); - - int listSize = _locationIdList.size(); - _selectionPanel = new JPanel(); - _selectionPanel.setPreferredSize(selectionPanelDimension); - - // create the JTable from which to choose the Location - _descriptorList = createLocationDescriptorList(_locationIdList); - _tableAdapter = createDescriptorTableAdapter(_descriptorList); - - GridBagLayout layoutMgr = new GridBagLayout(); - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _selectionPanel.setLayout(layoutMgr); - - JScrollPane scrollPane = _tableAdapter.getScrollPane(); - - // col, row numCols numRows Wcol wrow - addComponent(_selectionPanel, _locationLabel, mainGbc, 0, 0, 1, 1, 0, 0); - addComponent(_selectionPanel, scrollPane, mainGbc, 0, 1, 1, 1, 1, 1); - - } - - // --------------------------------------------------------------------- - private ControlWindowTableAdapter createDescriptorTableAdapter( - List descriptorList) { - - Dimension scrolledPaneDimension = new Dimension(500, 150); - Dimension scrolledPaneViewportDimension = new Dimension(300, 100); - - JTable table = null; - String[] columnNameArray = { LID, NAME, BASIN_ID, STREAM_NAME, HSA, - MODEL_PREFERENCE }; - ControlWindowTableAdapter tableAdapter = null; - - TableColumnComparator comparator = new ControlWindowTableColumnComparator(); - tableAdapter = new ControlWindowTableAdapter(comparator, - columnNameArray, descriptorList); - - JScrollPane tableScrollPane = tableAdapter.getScrollPane(); - tableScrollPane.setPreferredSize(scrolledPaneDimension); - tableScrollPane.setMinimumSize(scrolledPaneDimension); - - // select the first descriptor in the list - if (tableAdapter.getDescriptorCount() > -1) { - tableAdapter.setSelectedIndex(0); - LocationDescriptor descriptor = tableAdapter - .getDescriptorByIndex(0); - } - - tableAdapter.getTable().setPreferredScrollableViewportSize( - scrolledPaneViewportDimension); - - TableColumn col = tableAdapter.getTable().getColumnModel().getColumn(0); - int width = 20; - col.setPreferredWidth(width); - - return tableAdapter; - - } - - // --------------------------------------------------------------------- - - private List createLocationDescriptorList(List locationIdList) { - List locationDescriptorList = new ArrayList(); - final int maxNameStringLength = 20; - - // StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < locationIdList.size(); i++) { - // clear out any old string - // buffer.setLength(0); - - String locationId = (String) locationIdList.get(i); - - LocationDescriptor descriptor = _dataMgr - .getLocationDescriptor(locationId); - locationDescriptorList.add(descriptor); - - } - - return locationDescriptorList; - - } - - // --------------------------------------------------------------------- - - // --------------------------------------------------------------------- - - private void initMenuBar() { - _menuBar = new JMenuBar(); - - JMenu menu = null; - JMenuItem menuItem = null; - - // File Menu - - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - menuItem = new JMenuItem("Open Analysis Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Open a new Analysis Window"); - menu.add(menuItem); - menuItem.addActionListener(new AnalysisWindowLaunchListener()); - - menuItem = new JMenuItem("Exit Application"); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Exit the Application"); - menu.add(menuItem); - menuItem.addActionListener(new ExitListener()); - - // Configuration Menu - menu = new JMenu("Configuration"); - menu.setMnemonic(KeyEvent.VK_C); - menu.getAccessibleContext().setAccessibleDescription( - "Configure the forecast points"); - _menuBar.add(menu); - - menuItem = new JMenuItem("Configure Fcst Points for SSHP..."); - // menuItem.setAccelerator(KeyStroke.getKeyStroke( - // KeyEvent.VK_S, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Configure a point for SSHP"); - menu.add(menuItem); - - menuItem.addActionListener(new ConfigureLaunchListener()); - - // monthly values menuItem - menuItem = new JMenuItem("MAPE Monthly Values Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit MAPE Monthly Values"); - menu.add(menuItem); - - menuItem.addActionListener(new MonthlyMapeEditorLaunchActionListener()); - - // SAC-SMA parameters editor menu item - menuItem = new JMenuItem("SAC-SMA Parameters Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit SAC-SMA Parameters"); - menu.add(menuItem); - - menuItem.addActionListener(new SacParamsLaunchActionListener()); - - // SAC-SMA states editor menu Item - menuItem = new JMenuItem("SAC-SMA States Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit SAC-SMA States"); - menu.add(menuItem); - - menuItem.addActionListener(new SacStateLaunchActionListener()); - - // Rating Curve editor menu Item - menuItem = new JMenuItem("Rating Curve Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit Rating Curves"); - menu.add(menuItem); - - menuItem.addActionListener(new RatingCurveLaunchActionListener()); - - // UnitHydrograph editor menu Item - menuItem = new JMenuItem("Unit Hydrograph Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit Unit Hyddrographs"); - menu.add(menuItem); - - menuItem.addActionListener(new UnitHydrographLaunchActionListener()); - - // extra - menu = new JMenu("Extra"); - menu.setMnemonic(KeyEvent.VK_X); - menu.getAccessibleContext().setAccessibleDescription( - "Extra functionality"); - _menuBar.add(menu); - - // Run preprocessor - menuItem = new JMenuItem("Run MAP Preprocessor..."); - // menuItem.setAccelerator(KeyStroke.getKeyStroke( - // KeyEvent.VK_P, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Run MAP Preprocessor"); - menu.add(menuItem); - - menuItem.addActionListener(new MapPreprocessorRunListener()); - - // separator - - // JSeparator menuSeparator = new JSeparator(); - // _menuBar.add(menuSeparator); - - // acts as a separator to move the Help menu all the way to the right - menuItem = new JMenuItem(""); - menuItem.setEnabled(false); - _menuBar.add(menuItem); - - // Help Menu - - menu = new JMenu("Help"); - menu.setMnemonic(KeyEvent.VK_HELP); - menu.getAccessibleContext().setAccessibleDescription( - "Access help menu items."); - _menuBar.add(menu); - - menuItem = new JMenuItem("About..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, - ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Display the About Dialog."); - menu.add(menuItem); - - menuItem.addActionListener(new AboutLaunchListener()); - - } - - // --------------------------------------------------------------------- - private void addComponent(Container container, Component component, - GridBagConstraints gbc, int column, int row, int columnCells, - int rowCells, int weightX, int weightY) { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - // the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - // --------------------------------------------------------------------- - private void runMAPPreprocessor() { - final long millisPerHour = 1000 * 60 * 60; - MAPPreprocessor preprocessor = null; - - long endTime = System.currentTimeMillis(); - endTime = (endTime / millisPerHour) * millisPerHour; - - long startTime = endTime - (6 * 24 * millisPerHour); - - String fileDir = _controller.getLogDirName(); - String fileName = "/MAPPreprocessor.log"; - String filePath = null; - - if (fileDir != null) { - filePath = fileDir + fileName; - } else { - filePath = fileName; - } - - Logger logger = new FileLogger(filePath, true, true); - - // preprocessor = new MAPPreprocessor(_dataMgr, startTime, endTime, - // logger); - preprocessor = new MAPPreprocessor(_dataMgr, logger); - - System.out.println("Beginning MAP preprocessing"); - preprocessor.preprocessAll(); - System.out.println("Completed MAP preprocessing"); - - } // runMAPPreprocessor (in same VM) - // --------------------------------------------------------------------- - - private void runMAPPreprocessorAsSeparateProcess() { - String header = "ControlWindow.runMAPPreprocessorAsSeparateProcess(): "; - System.out.println("Beginning MAP preprocessing"); - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - - String commandString = dirString + "/run_SSHP_MAP_preprocess"; - - if (_controller.isRunningOnWindows()) { - commandString += ".bat"; - } - - System.out - .println(header + "making system call:" + commandString + ":"); - System.out.flush(); - - try { - // DR#10955 - RunProcess process = RunProcess.getRunProcess().exec(commandString); - process.waitFor(); - } catch (IOException e) { - e.printStackTrace(); - } - - System.out.println("Completed MAP preprocessing"); - } - - // --------------------------------------------------------------------- - - private void addListeners() { - // allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - // hook up the configure launch button - // _configButton.addActionListener(new ConfigureLaunchListener()); - - // hook up the run MAP preprocessor button - // _mapPreprocessorButton.addActionListener(new - // MapPreprocessorRunListener()); - - // hook up the application launch button and the double click launching - // from the table - _launchButton.addActionListener(new AnalysisWindowLaunchListener()); - _tableAdapter.getTable().addMouseListener( - new DoubleClickAnalysisWindowLaunchListener()); - - // set up the action to perform when the close button is pressed - _exitButton.addActionListener(new ExitListener()); - - // sets up the minimum and maximum sizes for the window - WindowResizingManager mgr = new WindowResizingManager(this, - _minDimension, _maxDimension); - - _tableAdapter.getListSelectionModel().addListSelectionListener( - new DescriptorRowSelectionListener()); - - } - - // --------------------------------------------------------------------------------- - public String getSelectedLocationId() { - String locationId = null; - int listSize = _locationIdList.size(); - - int selectedIndex = _tableAdapter.getFirstSelectedIndex(); - if ((selectedIndex >= 0) && (listSize > 0)) { - // locationId = (String) _locationIdList.get(selectedIndex); - - LocationDescriptor desc = (LocationDescriptor) _tableAdapter - .getDataList().get(selectedIndex); - locationId = desc.getId(); - } - - return locationId; - } - - // --------------------------------------------------------------------- - private synchronized void launchAnalysisWindow() { - DialogHelper.setWaitCursor(ControlWindow.this); - _launchButton.setEnabled(false); - - String locationId = getSelectedLocationId(); - - if (locationId != null) { - _controller.displayAnalysisWindow(locationId); - - } else { - DialogHelper - .displayErrorDialog( - ControlWindow.this, - "You need to select a station in order to display the Analysis Window.", - "No Station Selected"); - } - - _launchButton.setEnabled(true); - - DialogHelper.setDefaultCursor(ControlWindow.this); - - } - - // --------------------------------------------------------------------- - private class FrameCloseWindowListener extends WindowAdapter { - public void windowClosing(WindowEvent evt) { - dispose(); - _dataMgr.disconnect(); - // System.exit(0); - } - - } - - // --------------------------------------------------------------------- - - private class MapPreprocessorRunListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - DialogHelper.setWaitCursor(_menuBar); - runMAPPreprocessorAsSeparateProcess(); - DialogHelper.setDefaultCursor(_menuBar); - } - } - - // --------------------------------------------------------------------- - - private class ExitListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - dispose(); - // System.exit(0); - } - } - - // --------------------------------------------------------------------- - private class AboutLaunchListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - // JOptionPane.showMessageDialog(LaunchWindow.this, _aboutText, - // "About SSHP", JOptionPane.INFORMATION_MESSAGE ); - String aboutText = AboutInfo.getText(); - DialogHelper.displayMessageDialog(ControlWindow.this, aboutText, - "About SSHP"); - } - } - - // --------------------------------------------------------------------- - private class AnalysisWindowLaunchListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - - launchAnalysisWindow(); - - return; - } - } - - // --------------------------------------------------------------------- - - private class DoubleClickAnalysisWindowLaunchListener extends MouseAdapter { - public void mouseClicked(MouseEvent event) { - int button = event.getButton(); - if (button == MouseEvent.BUTTON1) { - if (event.getClickCount() > 1) { - launchAnalysisWindow(); - } - } - return; - } - } - - // --------------------------------------------------------------------- - private class ConfigureLaunchListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - SSHPConfigDialog dialog = new SSHPConfigDialog(ControlWindow.this, - _dataMgr); - - dialog.setVisible(true); - - } - } // ConfigureLaunchListener - - // --------------------------------------------------------------------- - - private class MonthlyMapeEditorLaunchActionListener implements - ActionListener { - public void actionPerformed(ActionEvent evt) { - MonthlyValueEditor editor = null; - - JFrame ownerFrame = ControlWindow.this; - DataMgr dataMgr = _dataMgr; - String basinId = null; - boolean isModal = false; - String pe = "EA"; - - editor = new MonthlyValueEditor(ownerFrame, dataMgr, basinId, pe, - isModal); - editor.setVisible(true); - - } - } - - // -------------------------------------------------------------------- - - private class SacParamsLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - - String basinId = null; - SacParamsEditor editor = null; - - editor = new SacParamsEditor(ControlWindow.this, _dataMgr, basinId); - editor.setVisible(true); - } - } - - // -------------------------------------------------------------------- - - private class SacStateLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - String basinId = null; - - SacStateEditor editor = null; - editor = new SacStateEditor(ControlWindow.this, _dataMgr, basinId); - - editor.setVisible(true); - } - } - - // -------------------------------------------------------------------- - private class RatingCurveLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - - String lid = getSelectedLocationId(); - - if (lid != null) { - RatingCurveEditor editor = null; - // editor = new RatingCurveEditor(ControlWindow.this, _dataMgr, - // basinId); - boolean isModal = false; - editor = new RatingCurveEditor(ControlWindow.this, _dataMgr, - lid, isModal); - - editor.setVisible(true); - } - } - } - - // -------------------------------------------------------------------- - - private class UnitHydrographLaunchActionListener implements ActionListener { - public void actionPerformed(ActionEvent evt) { - - String lid = getSelectedLocationId(); - - if (lid != null) { - UnitHydrographEditor editor = null; - boolean isModal = false; - editor = new UnitHydrographEditor(ControlWindow.this, _dataMgr, - lid, isModal); - - editor.setVisible(true); - } - } - } - - // -------------------------------------------------------------------- - private class DescriptorRowSelectionListener implements - ListSelectionListener { - - public void valueChanged(ListSelectionEvent event) { - String header = "DescriptorRowSelectionListener.valueChanged(): "; - LocationDescriptor descriptor = null; - - int index = _tableAdapter.getFirstSelectedIndex(); - - if (index > -1) { - _selectedLocationDescriptor = (LocationDescriptor) _descriptorList - .get(index); - // System.out.println(header + "selected lid = " + - // _selectedLocationDescriptor.getId()); - } else { - _selectedLocationDescriptor = null; - } - - } - } - // -------------------------------------------------------------------- - -} // end LaunchWindow class diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindowTableAdapter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindowTableAdapter.java deleted file mode 100644 index 6caa4a1072..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindowTableAdapter.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.util.List; - -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.sshp.gui.TableAdapter; -import ohd.hseb.util.gui.TableColumnComparator; - - -/** - * @author GobsC - * - * - */ -public class ControlWindowTableAdapter extends TableAdapter -{ - - private LocationDescriptor _descriptor = null; - private List _descriptorList = null; - - // --------------------------------------------------------------------------------- - - - - public ControlWindowTableAdapter(TableColumnComparator comparator, - String[] columnNameArray, - List dataList) - { - super(comparator, columnNameArray, dataList); - - setAllowMultipleSelection(false); - - } - - // --------------------------------------------------------------------------------- - public String[][] getDataStringArrayFromDataList(List locationDescriptorList) - { - - //set alias for cut-and-paste-ability of code - List dataList = locationDescriptorList; - - int fieldCount = 6; - String[][] dataArray = new String[dataList.size()][fieldCount]; - - - for (int i = 0; i < dataList.size(); i++) - { - LocationDescriptor desc = (LocationDescriptor) dataList.get(i); - - dataArray[i][0] = desc.getId(); - dataArray[i][1] = desc.getLocationName(); - - dataArray[i][2] = desc.getBasinId(); - dataArray[i][3] = desc.getStreamName(); - dataArray[i][4] = desc.getHsa(); - dataArray[i][5] = desc.getModelPreference(); - } - - return dataArray; - - } - // --------------------------------------------------------------------------------- - public void refreshTableModel(List dataList) - { - setDataList(dataList);// for super class - - _descriptorList = dataList; - - String[][] dataStringArray = getDataStringArrayFromDataList(dataList); - getTableModel().updateData( dataStringArray ); - getTableModel().fireTableChanged( null ); - - - return; - - } - // --------------------------------------------------------------------------------- - - public int getDescriptorCount() - { - int count = getDataList().size(); - return count; - } - - // --------------------------------------------------------------------------------- - - public LocationDescriptor getDescriptorByIndex(int index) - { - List dataList = getDataList(); - LocationDescriptor desc = null; - - if ( dataList.size() > 0 ) - { - Object object = dataList.get(index); - desc = (LocationDescriptor) object; - } - return desc; - } - - // --------------------------------------------------------------------------------- - - private int findIndexOfDescriptor(LocationDescriptor desc) - { - int index = _descriptorList.indexOf(desc); - - return index; - } - // ------------------------------------------------------------------------------------- - public void setDataList(List dataList) - { - - super.setDataList(dataList); - _descriptorList = dataList; - - } - - // --------------------------------------------------------------------------------- - - - private void selectAll() - { - - getListSelectionModel().setSelectionInterval(0, getTable().getModel().getRowCount()-1); - } - - - // --------------------------------------------------------------------------------- - public void setSelectedIndex(int index) - { - - getListSelectionModel().setSelectionInterval(index, index); - - } - // --------------------------------------------------------------------------------- - - public void selectItems(List selectedDescriptorList) - { - getListSelectionModel().clearSelection(); - - for (int i = 0; i < selectedDescriptorList.size(); i++) - { - LocationDescriptor descriptor = (LocationDescriptor) selectedDescriptorList.get(i); - - int index = findIndexOfDescriptor(descriptor); - - if (index >= 0) - { - getListSelectionModel().setSelectionInterval(index, index); - } - } - } - // --------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindowTableColumnComparator.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindowTableColumnComparator.java deleted file mode 100644 index 32383f98aa..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ControlWindowTableColumnComparator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - - -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author GobsC - * - */ -public class ControlWindowTableColumnComparator extends TableColumnComparator -{ - public ControlWindowTableColumnComparator() - { - } - - public int compareLid( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - int result = compareStrings(desc1.getId(), desc2.getId()); - return result; - } - - public int compareName( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getLocationName(), desc2.getLocationName() ) ); - } - - public int compareStreamName( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getStreamName(), desc2.getStreamName() ) ); - } - - public int compareBasinId( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getBasinId(), desc2.getBasinId() ) ); - } - - public int compareHsa( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getHsa(), desc2.getHsa() ) ); - } - - public int compareModelPreference( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getModelPreference(), desc2.getModelPreference() ) ); - } - - public int compare(Object object1, Object object2) - { - LocationDescriptor desc1 = (LocationDescriptor) object1; - LocationDescriptor desc2 = (LocationDescriptor) object2; - - int returnValue = 0; - - - if( _columnName.equalsIgnoreCase( ControlWindow.LID ) ) - { - returnValue = compareLid( desc1, desc2 ); - } - else if ( _columnName.equalsIgnoreCase( ControlWindow.NAME ) ) - { - returnValue = compareName( desc1, desc2 ); - } - else if ( _columnName.equalsIgnoreCase( ControlWindow.STREAM_NAME)) - { - returnValue = compareStreamName( desc1, desc2 ); - } - else if (_columnName.equalsIgnoreCase( ControlWindow.BASIN_ID) ) - { - returnValue = compareBasinId( desc1, desc2 ); - } - - else if (_columnName.equalsIgnoreCase( ControlWindow.HSA) ) - { - returnValue = compareHsa( desc1, desc2 ); - } - - else if (_columnName.equalsIgnoreCase( ControlWindow.MODEL_PREFERENCE) ) - { - returnValue = compareModelPreference(desc1, desc2); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/FileChooserHelper.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/FileChooserHelper.java deleted file mode 100644 index ec8b8b8054..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/FileChooserHelper.java +++ /dev/null @@ -1,153 +0,0 @@ -package ohd.hseb.sshp.window; - -import java.awt.Window; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileFilter; - -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; - -public class FileChooserHelper -{ - - private String _lastUsedDirectory = null; - private JFileChooser _fileChooser = null; - private FileFilter _fileFilter = null; - private String[] _acceptableExtensionArray = null; - - private File _selectedFile; - - // ------------------------------------------------------------------------------ - - public FileChooserHelper(String defaultDirectory, - String[] acceptableExtensionArray, - String fileTypeDescriptionString) - { - _fileChooser = new JFileChooser(defaultDirectory); - - _acceptableExtensionArray = acceptableExtensionArray; - - //add a FileFilter - List filterList = new ArrayList(); - - for (int i = 0 ; i < _acceptableExtensionArray.length; i++) - { - filterList.add( _acceptableExtensionArray[i]); - } - - _fileFilter = new ExtensionFileFilter( filterList, fileTypeDescriptionString); - _fileChooser.setFileFilter( _fileFilter ); - - return; - } - - // ------------------------------------------------------------------------------ - private boolean endsWithProperExtension(String filePathString) - { - boolean hasProperExtension = false; - - for (int i = 0; i < _acceptableExtensionArray.length; i++) - { - String extension = "." + _acceptableExtensionArray[i]; - if (filePathString.endsWith(extension)) - { - hasProperExtension = true; - break; - } - } - - return hasProperExtension; - } - - // ------------------------------------------------------------------------------ - public String displayForOpen(Window window) - { - return display(window, true); - } - - // ------------------------------------------------------------------------------ - public String displayForSave(Window window) - { - return display(window, false); - } - - // ------------------------------------------------------------------------------ - - - private String display(Window window, boolean forOpening) - { - String header = "FileChooserHelper.display(): "; - - String filePath = null; - File file = null; - int returnValue = 0; - - if (forOpening) - { - returnValue = _fileChooser.showOpenDialog( window ); - } - else //for Saving - { - returnValue = _fileChooser.showSaveDialog( window ); - } - - if (returnValue == JFileChooser.APPROVE_OPTION) - { - file = _fileChooser.getSelectedFile(); - setSelectedFile(file); - - try - { - filePath = file.getCanonicalPath(); - - //ensure ends with a proper extension - if (! endsWithProperExtension(filePath) ) - { - String extension = ""; - if (_acceptableExtensionArray.length > 0) - { - extension = "." + _acceptableExtensionArray[0]; - filePath = filePath + extension; - } - - } - - } - catch (IOException e) - { - DialogHelper.displayMessageDialog(window, "Error: File not selected."); - } - } - else - { - DialogHelper.displayMessageDialog(window, "File not selected."); - } - - return filePath; - - } - - /** - * @param selectedFile The selectedFile to set. - */ - public void setSelectedFile(File selectedFile) - { - _selectedFile = selectedFile; - } - - /** - * @return Returns the selectedFile. - */ - public File getSelectedFile() - { - return _selectedFile; - } - - // ------------------------------------------------------------------------------ - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ForecastTsSaveDialog.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ForecastTsSaveDialog.java deleted file mode 100644 index 2b4ed080e6..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/ForecastTsSaveDialog.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * Created on Dec 8, 2003 - * - * Filename : ForecastTsSaveDialog.java - * Author : Gautam Sood - * Last Revision Date : Dec 8, 2003 - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.FcstTsDescriptor; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.DialogHelper; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class ForecastTsSaveDialog extends JDialog { - private static final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - private static final int GOOD_QC = 1879048191; - - private RegularTimeSeriesHolder _timeSeriesHolder = null; - - private RegularTimeSeries _timeSeries = null; - - private DataMgr _dataMgr = null; - - private static final int DEFAULT_WIDTH = 390; - - private static final int DEFAULT_HEIGHT = 390; - - private static final int MAX_WIDTH = DEFAULT_WIDTH; - - private static final int MAX_HEIGHT = DEFAULT_HEIGHT; - - private static final int MIN_WIDTH = 266; - - private static final int MIN_HEIGHT = 296; - - private static final int SAVE_HOURS_STEPS = 6; - - private String _extremum = "Z"; - - private float _probability = -1.0f; - - private int _revision = 0; - - private String _physicalElement = null; - - private String[] _physicalElementStringArray = null; - - private String _lid = null; - - private String _productId = ""; - - private String _basisProductTime = null; - - private String _tableName = null; - - private String[] _typeSourceStringArray = { "FE", "FF", "FG", "FM", "FZ" }; - - private String _sshpForecastTsToken = null; - - private String[] _shefQualifierStringArray = { "Z", "E" }; - - private long _productTime = 0; - - private long _basisTime = 0; - - // used for custom notification - private List _applyListenerList = new ArrayList(); - - // GUI Components - private Container _frameContentPane = getContentPane(); - - private JLabel _physicalElementLabel = new JLabel("Physical Element: "); - - private JLabel _pElementValueLabel = new JLabel(); - - private JComboBox _physicalElementComboBox = null; - - private JLabel _typeSourceLabel = new JLabel("Type Source: "); - - private JLabel _shefQualifierLabel = new JLabel("SHEF Qualifier: "); - - private JLabel _productIDLabel = new JLabel("Product ID: "); - - private JLabel _basisTimeLabel = new JLabel("Basis Time: "); - - private JLabel _productTimeLabel = new JLabel("Product Time: "); - - private JTextField _productIDTextField = new JTextField(10); - - private DateTimeTextField _basisTimeTextField = null; - - private DateTimeTextField _productTimeTextField = null; - - private JComboBox _typeSourceComboBox = new JComboBox( - _typeSourceStringArray); - - private JComboBox _shefQualifierComboBox = new JComboBox( - _shefQualifierStringArray); - - private JPanel _dataPanel = new JPanel(); - - private JPanel _buttonPanel = new JPanel(); - - private JLabel _hoursToSaveLabel = new JLabel("Hours to Save:"); - - private JSpinner _hoursToSaveSpinner = null; - - // private JButton _saveButton = new JButton( - // "
Save to
Database
" ); - private JButton _saveButton = new JButton("Save to Database"); - - private JButton _closeButton = new JButton("Close"); - - /* - * Empty Constructor Sets the basis and product time to the current system - * time - */ - - public ForecastTsSaveDialog(JFrame owner, String lid, String title, - RegularTimeSeriesHolder timeSeriesHolder, DataMgr dataMgr, - String tableName, String[] physicalElementStringArray, - String preferredPhysicalElement) { - - this(owner, lid, title, timeSeriesHolder, System.currentTimeMillis(), - System.currentTimeMillis(), dataMgr, tableName, - physicalElementStringArray, preferredPhysicalElement, true); - } - - public ForecastTsSaveDialog(JFrame owner, String lid, String title, - RegularTimeSeriesHolder timeSeriesHolder, long productTime, - long basisTime, DataMgr dataMgr, String tableName, - String[] physicalElementStringArray, String preferredPhysicalElement) { - this(owner, lid, title, timeSeriesHolder, productTime, basisTime, - dataMgr, tableName, physicalElementStringArray, - preferredPhysicalElement, true); - } - - public ForecastTsSaveDialog(JFrame owner, String lid, String title, - RegularTimeSeriesHolder timeSeriesHolder, long productTime, - long basisTime, DataMgr dataMgr, String tableName, - String[] physicalElementStringArray, - String preferredPhysicalElement, boolean isModal) { - super(owner, isModal); - this.setTitle(title + ": " + lid); - _timeSeriesHolder = timeSeriesHolder; - _timeSeries = _timeSeriesHolder.getTimeSeries(); - _basisTime = basisTime; - _productTime = productTime; - _lid = lid; - _dataMgr = dataMgr; - _tableName = tableName; - - long currentTime = System.currentTimeMillis(); - long latestHourTime = TimeHelper.truncateTimeInMillisToNearestHour( - currentTime, 1); - _basisTimeTextField = new DateTimeTextField(latestHourTime, owner, - "Basis Time", 19); - - _productTimeTextField = new DateTimeTextField(latestHourTime, owner, - "Product Time", 19); - - _physicalElementComboBox = new JComboBox(physicalElementStringArray); - _physicalElementComboBox.setSelectedItem(preferredPhysicalElement); - _physicalElement = preferredPhysicalElement; - - _pElementValueLabel.setText(_physicalElement); - - // set up the spinner control for time - int initialValue = timeSeriesHolder.getTimeSeries() - .getMeasurementCount(); - int min = 1; - int max = initialValue; - int step = SAVE_HOURS_STEPS; - - SpinnerModel model = new SpinnerNumberModel(initialValue, min, max, - step); - _hoursToSaveSpinner = new JSpinner(model); - - // load this token and set the initially selected type/source to this - // default value - AppsDefaults ad = AppsDefaults.getInstance(); - - _sshpForecastTsToken = ad.getToken("sshp_fcst_ts"); - if (_sshpForecastTsToken == null) { - _sshpForecastTsToken = ad.getToken("SSHP_FCST_TS"); - } - // System.out.println("ForecastTsSaveDialog(): _sshpForecastTsToken = " - // + _sshpForecastTsToken); - initialize(); - } - - private void initialize() { - - addDataPanelComponents(); - addButtonPanelComponents(); - addFrameComponents(); - - selectDefaultTypeSource(_sshpForecastTsToken); - - addListeners(); - - setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); - } - - private void selectDefaultTypeSource(String typeSource) { - - // System.out.println("ForecastTsSaveDialog.selectDefaultTypeSource() typeSource=" - // + typeSource); - if (typeSource == null) { - // System.out.println("ForecastTsSaveDialog.selectDefaultTypeSource() since typeSource token was null, use value of FZ"); - typeSource = "FZ"; - } - - _typeSourceComboBox.setSelectedItem(typeSource); - - } - - private void addDataPanelComponents() { - _dataPanel.setLayout(new GridBagLayout()); - JPanel hSeparator[] = new JPanel[7]; - - for (int i = 0; i < hSeparator.length; i++) { - hSeparator[i] = new JPanel(); - hSeparator[i].setPreferredSize(new Dimension(5, 15)); - } - - _basisTimeTextField.setText(DbTimeHelper - .getDateTimeStringFromLongTime(_basisTime)); - _productTimeTextField.setText(DbTimeHelper - .getDateTimeStringFromLongTime(_productTime)); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent(_dataPanel, _physicalElementLabel, 0, - 0, 3, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _physicalElementComboBox, - 3, 0, 1, 1, GridBagConstraints.NONE); - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[0], 0, 1, 4, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _typeSourceLabel, 0, 2, - 3, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _typeSourceComboBox, 3, - 2, 2, 1, GridBagConstraints.NONE); - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[1], 0, 3, 4, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _shefQualifierLabel, 0, - 4, 3, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _shefQualifierComboBox, - 3, 4, 2, 1, GridBagConstraints.NONE); - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[2], 0, 5, 4, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _productIDLabel, 0, 6, 3, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _productIDTextField, 3, - 6, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[3], 0, 7, 4, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _basisTimeLabel, 0, 8, 3, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _basisTimeTextField, 3, - 8, 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[4], 0, 9, 4, - 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _productTimeLabel, 0, 10, - 3, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _productTimeTextField, 3, - 10, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[5], 0, 11, 4, - 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_dataPanel, _hoursToSaveLabel, 0, 12, - 3, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dataPanel, _hoursToSaveSpinner, 3, - 12, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_dataPanel, hSeparator[6], 0, 13, 4, - 1, GridBagConstraints.BOTH); - - _basisTimeTextField.setEditable(false); - _productTimeTextField.setEditable(false); - } - - private void addButtonPanelComponents() { - _buttonPanel.setLayout(new GridBagLayout()); - - JPanel horizSeparatorPanel = new JPanel(); - horizSeparatorPanel.setPreferredSize(new Dimension(30, 30)); - _saveButton.setPreferredSize(new Dimension(180, 30)); - _closeButton.setPreferredSize(new Dimension(80, 30)); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent(_buttonPanel, _saveButton, 0, 0, 1, - 1, GridBagConstraints.NONE); - ComponentHelper.addPanelComponent(_buttonPanel, horizSeparatorPanel, 1, - 0, 1, 1, GridBagConstraints.NONE); - ComponentHelper.addPanelComponent(_buttonPanel, _closeButton, 2, 0, 1, - 1, GridBagConstraints.BOTH); - } - - private void addFrameComponents() { - JPanel hLine = new JPanel(); - JPanel hSeparator = new JPanel(); - - _frameContentPane.setLayout(new GridBagLayout()); - hLine.setPreferredSize(new Dimension(300, 1)); - hSeparator.setPreferredSize(new Dimension(300, 10)); - hLine.setBackground(Color.BLACK); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent(_frameContentPane, _dataPanel, 0, 0, - 4, 13, GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, hLine, 0, 13, 4, - 1, GridBagConstraints.NONE); - ComponentHelper.addFrameComponent(_frameContentPane, hSeparator, 0, 14, - 4, 1, GridBagConstraints.NONE); - ComponentHelper.addFrameComponent(_frameContentPane, _buttonPanel, 0, - 15, 4, 1, GridBagConstraints.BOTH); - } - - private FcstTsDescriptor getFcstTsDescriptor(String tableName) { - FcstTsDescriptor fcstTs = new FcstTsDescriptor(tableName); - - fcstTs.setLid(_lid); - fcstTs.setTableName(tableName); - fcstTs.setPe((String) _physicalElementComboBox.getSelectedItem()); - fcstTs.setTs((String) _typeSourceComboBox.getSelectedItem()); - - fcstTs.setExtremum(_extremum); - fcstTs.setShef_qual_code((String) _shefQualifierComboBox - .getSelectedItem()); - fcstTs.setProduct_id(_productIDTextField.getText().trim()); - - fcstTs.setProbability(_probability); - fcstTs.setQuality_code(GOOD_QC); - fcstTs.setRevision((short) _revision); - - if ((tableName.equalsIgnoreCase("FcstHeight")) - || (tableName.equalsIgnoreCase("FcstDischarge"))) { - fcstTs.setDur((short) 0); - } else // evapotranspiration - { - int dur = (1000 + _timeSeries.getIntervalInHours()); - fcstTs.setDur((short) dur); - } - - fcstTs.setProducttime(_productTimeTextField.getTime()); - fcstTs.setBasistime(_basisTimeTextField.getTime()); - - return fcstTs; - } - - private void addListeners() { - _saveButton.addActionListener(new SaveButtonListener()); - WindowCloserListener windowCloser = new WindowCloserListener(); - addWindowListener(windowCloser); - _closeButton.addActionListener(windowCloser); - // _basisTimeTextField.addMouseListener( new TimeTextFieldListener() ); - // _productTimeTextField.addMouseListener( new TimeTextFieldListener() - // ); - addComponentListener(new WindowResizeComponentListener()); - } - - /* - * private class TimeTextFieldListener extends MouseAdapter { public void - * mousePressed( MouseEvent e ) { long dateTime = 0; JTextField textField = - * (JTextField) e.getSource(); - * - * if ( ! textField.getText().equals( "yyyy-mm-dd hh:mm:ss" ) ) { dateTime = - * DbTimeHelper.getLongTimeFromDateTimeString( textField.getText() ); } else - * { dateTime = new Date().getTime(); } - * - * DateTimeDialog dateTimeGUI = null; if ( textField == _basisTimeTextField - * ) { dateTimeGUI = new DateTimeDialog( ForecastTsSaveDialog.this, - * dateTime, "Basis Time" ); - * - * } else { dateTimeGUI = new DateTimeDialog( ForecastTsSaveDialog.this, - * dateTime, "Product Time" ); } - * - * dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) - * ); dateTimeGUI.show(); _basisTime = - * DbTimeHelper.getLongTimeFromDateTimeString( - * _basisTimeTextField.getText().trim() ); _productTime = - * DbTimeHelper.getLongTimeFromDateTimeString( - * _productTimeTextField.getText().trim() ); } } - */ - /* - * private class DateTimeListener implements DateTimeEventListener { private - * JTextField _timeTextField = null; - * - * public DateTimeListener( JTextField timeTextField ) { _timeTextField = - * timeTextField; } - * - * public void dateTimeEntered( DateTimeEvent dateTimeEvent ) { if ( - * dateTimeEvent.isGoodDate() ) { String timeString = - * DbTimeHelper.getDateTimeStringFromLongTime( - * dateTimeEvent.getDateTimeLong() ); _timeTextField.setText( timeString ); - * } } } - */ - private class SaveButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - boolean success = false; - - FcstTsDescriptor fcstTs = new FcstTsDescriptor(_tableName); - - fcstTs = getFcstTsDescriptor(_tableName); - - Integer hoursToSaveInteger = (Integer) _hoursToSaveSpinner - .getValue(); - int hoursToSave = hoursToSaveInteger.intValue(); - - success = _dataMgr.saveFcstTimeSeries(fcstTs, _timeSeries, - hoursToSave); - - if (success) { - DialogHelper.displayMessageDialog(ForecastTsSaveDialog.this, - "Insert Successful!"); - } else { - DialogHelper.displayMessageDialog(ForecastTsSaveDialog.this, - "Insert Failed!"); - } - notifyAllApplyActionListeners(); - } - } - - public void addApplyActionListener(ActionListener listener) { - _applyListenerList.add(listener); - } - - private void notifyAllApplyActionListeners() { - for (int i = 0; i < _applyListenerList.size(); i++) { - ActionListener listener = (ActionListener) _applyListenerList - .get(i); - ActionEvent event = new ActionEvent(this, - ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - private class WindowCloserListener extends WindowAdapter implements - ActionListener { - @Override - public void windowClosing(WindowEvent e) { - closeWindow(); - } - - public void actionPerformed(ActionEvent e) { - closeWindow(); - } - } - - private void closeWindow() { - this.dispose(); - } - - private class WindowResizeComponentListener extends ComponentAdapter { - @Override - public void componentResized(ComponentEvent e) { - int height = ForecastTsSaveDialog.this.getHeight(); - int width = ForecastTsSaveDialog.this.getWidth(); - - // System.err.println( width + "\n" + height ); - if (width < MIN_WIDTH) { - ForecastTsSaveDialog.this.setSize(new Dimension(MIN_WIDTH, - height)); - } - if (width > MAX_WIDTH) { - ForecastTsSaveDialog.this.setSize(new Dimension(MAX_WIDTH, - height)); - } - if (height < MIN_HEIGHT) { - ForecastTsSaveDialog.this.setSize(new Dimension(width, - MIN_HEIGHT)); - } - if (height > MAX_HEIGHT) { - ForecastTsSaveDialog.this.setSize(new Dimension(width, - MAX_HEIGHT)); - } - } - } - - private static RegularTimeSeries getTestTimeSeries() { - RegularTimeSeries testTimeSeries = null; - - Date date = new Date(); - long currentTime = date.getTime(); - - currentTime = TimeHelper.truncateTimeInMillisToNearestHour(currentTime, - 1); - long startTime = currentTime - (24 * HOUR_IN_MILLIS); - long endTime = startTime + (10 * HOUR_IN_MILLIS); - testTimeSeries = new RegularTimeSeries(startTime, endTime, 1, - MeasuringUnit.inches); - for (int i = 0; i < testTimeSeries.getMeasurementCount(); i++) { - Measurement m = new Measurement(i, MeasuringUnit.inches); - long time = startTime + (i * HOUR_IN_MILLIS); - testTimeSeries.setMeasurementByTime(m, time); - } - return testTimeSeries; - } - - public static void main(String[] args) { - RegularTimeSeries timeSeries = ForecastTsSaveDialog.getTestTimeSeries(); - DataMgr dataMgr = new DataMgr(); - RegularTimeSeriesHolder holder = new RegularTimeSeriesHolder(); - holder.setTimeSeries(timeSeries); - - String[] physicalElementStringArray = { "HG", "HP", "HT" }; - - ForecastTsSaveDialog saveForecast = new ForecastTsSaveDialog( - new JFrame(), "BLUO2", "Save Fcst Time Series Dialog ", holder, - dataMgr, "FcstHeight", physicalElementStringArray, "HG"); - saveForecast.setVisible(true); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/LiveSacStateEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/LiveSacStateEditor.java deleted file mode 100644 index a88db23188..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/LiveSacStateEditor.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Created on Nov 12, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.border.Border; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.gui.LabeledSlider; -import ohd.hseb.util.gui.WindowResizingManager; - - -/** - * @author Chip Gobs - * - * - */ -public class LiveSacStateEditor extends JDialog -{ - - private SacSmaState _state = null; - private SacSmaParameters _params = null; - - - // window sizing data - private Dimension _maxDimension = new Dimension(700, 300); - private Dimension _initialDimension = new Dimension(700, 300); - private Dimension _minDimension = new Dimension(300, 300); - - - private JPanel _mainPanel = null; - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - private JButton _closeButton = null; - - private LabeledSlider _uztwcLabeledSlider = null; - private LabeledSlider _uzfwcLabeledSlider = null; - - private LabeledSlider _lztwcLabeledSlider = null; - private LabeledSlider _lzfscLabeledSlider = null; - private LabeledSlider _lzfpcLabeledSlider = null; - - private LabeledSlider _adimcLabeledSlider = null; // 0.0 <= ADIMC <= UZTWM + LZTWM - - - private ActionListener _updateActionListener = null; - - // ----------------------------------------------------------------------------------- - public LiveSacStateEditor(Frame owner, - SacSmaState state, - SacSmaParameters params, - boolean isModal, - ActionListener listener) - { - super( owner, isModal ); - - _state = state; - _params = params; - - _updateActionListener = listener; - - initGui(); - - } - - // ----------------------------------------------------------------------------------- - public SacSmaState getCurrentSacSmaState() - { - return _state; - } - - // ----------------------------------------------------------------------------------- - - private void initGui() - { - - setTitle("LiveSacStateEditor Dialog"); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - JPanel verticalSeparatorPanel = new JPanel(); - verticalSeparatorPanel.setPreferredSize(new Dimension(30, 30)); - - JPanel horizontalSeparatorPanel = new JPanel(); - horizontalSeparatorPanel.setPreferredSize(new Dimension(30, 30)); - - - JPanel horizontalSeparatorPanel2 = new JPanel(); - horizontalSeparatorPanel2.setPreferredSize(new Dimension(30, 30)); - - JPanel horizontalSeparatorPanel3 = new JPanel(); - horizontalSeparatorPanel3.setPreferredSize(new Dimension(30, 30)); - - - _mainPanel = new JPanel(); - JPanel panel = _mainPanel; - - _closeButton = new JButton("Close"); - _closeButton.setPreferredSize(new Dimension(50, 30)); - - _mainPanel.setLayout( new GridBagLayout() ); - - initSliders(); - - - //arrange the layout - - // X, Y, #Col, #Row - - addComponent(panel, _uztwcLabeledSlider, gbc, 0, 0, 3, 1, 1, 0); - addComponent(panel, _uzfwcLabeledSlider, gbc, 0, 1, 3, 1, 1, 0); - addComponent(panel, _lztwcLabeledSlider, gbc, 0, 2, 3, 1, 1, 0); - addComponent(panel, _lzfscLabeledSlider, gbc, 0, 3, 3, 1, 1, 0); - addComponent(panel, _lzfpcLabeledSlider, gbc, 0, 4, 3, 1, 1, 0); - addComponent(panel, _adimcLabeledSlider, gbc, 0, 5, 3, 1, 1, 0); - - addComponent(panel, horizontalSeparatorPanel,gbc, 1, 6, 1, 1, 1, 0); - - - addComponent(panel, horizontalSeparatorPanel2, gbc, 0, 7, 1, 1, 1, 0); - - addComponent(panel, _closeButton, gbc, 1, 7, 1, 1, 0, 0); - addComponent(panel, horizontalSeparatorPanel3, gbc, 2, 7, 1, 1, 1, 0); - - - - //set up initial bounds limitations - //see WindowResize listener for the minimum setting - - Rectangle maxBoundsRectangle = new Rectangle(_maxDimension); - // this.setMaximizedBounds(maxBoundsRectangle); - - //hook up the mainPanel to the contentPane - - this.getContentPane().add(_mainPanel); - this.pack(); - - Rectangle initialBoundsRectangle = new Rectangle(_initialDimension); - this.setBounds(initialBoundsRectangle); - - - - addListeners(); - } - // ----------------------------------------------------------------------------------- - private void setSacSlidersFromModel() - { - - SacSmaState state = _state; - - _uztwcLabeledSlider.setModelValue(state.getUztwc()); - _uzfwcLabeledSlider.setModelValue(state.getUzfwc()); - - _lztwcLabeledSlider.setModelValue( state.getLztwc()); - _lzfscLabeledSlider.setModelValue( state.getLzfsc()); - _lzfpcLabeledSlider.setModelValue( state.getLzfpc()); - - _adimcLabeledSlider.setModelValue( state.getAdimc()); - - - } - - // ----------------------------------------------------------------------------------- - - private void initSliders() - { - - int width = 150; - int height = 40; - - //UZTWC adjustment controls - // note: the slide values go from 0 to 100 and are mapped to - // a double - - SacSmaState state = getCurrentSacSmaState(); - SacSmaParameters params = _params; - - - _uztwcLabeledSlider = new LabeledSlider("UZTWC:", - state.getUztwc(), - 0.0, - params.getUztwm(), - width, - height ); - - - _uzfwcLabeledSlider = new LabeledSlider("UZFWC:", - state.getUzfwc(), - 0.0, - params.getUzfwm(), - width, - height ); - - - _lztwcLabeledSlider = new LabeledSlider("LZTWC:", - state.getLztwc(), - 0.0, - params.getLztwm(), - width, - height ); - - _lzfscLabeledSlider = new LabeledSlider("LZFSC:", - state.getLzfsc(), - 0.0, - params.getLzfsm(), - width, - height ); - - _lzfpcLabeledSlider = new LabeledSlider("LZFPC:", - state.getLzfpc(), - 0.0, - params.getLzfpm(), - width, - height ); - - - _adimcLabeledSlider = new LabeledSlider("ADIMC:", - state.getAdimc(), - 0.0, - params.getUztwm() + params.getLztwm(), - width, - height ); - - - } - - // ----------------------------------------------------------------------------------- - - private void addListeners() - { - WindowCloseListener windowCloser = new WindowCloseListener(); - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - - // this adds its own listener internally - WindowResizingManager resizingMgr = - new WindowResizingManager(LiveSacStateEditor.this, - _minDimension, - _maxDimension); - - - //slider listeners - - _uztwcLabeledSlider.addChangeListener(new ValueChangeListener("UZTWC")); - _uzfwcLabeledSlider.addChangeListener(new ValueChangeListener("UZFWC")); - - _lztwcLabeledSlider.addChangeListener(new ValueChangeListener("LZTWC")); - _lzfscLabeledSlider.addChangeListener(new ValueChangeListener("LZFSC")); - _lzfpcLabeledSlider.addChangeListener(new ValueChangeListener("LZFPC")); - - _adimcLabeledSlider.addChangeListener(new ValueChangeListener("ADIMC")); - - - return; - - } - - // ----------------------------------------------------------------------------------- - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - // ------------------------------------------------------------ - - private void closeWindow() - { - this.dispose(); - } - // ------------------------------------------------------------ - - private void notifyListeners(String eventMessage) - { - ActionEvent event = new ActionEvent(LiveSacStateEditor.this, 0, eventMessage); - _updateActionListener.actionPerformed(event); - } - // ------------------------------------------------------------ - - - // Inner classes---------------------------------------------------------------------- - // - private class WindowCloseListener extends WindowAdapter implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - closeWindow(); - } - - public void windowClosing(WindowEvent evt) - { - closeWindow(); - } - - } - - // ----------------------------------------------------------------------------------- - private class ValueChangeListener implements ChangeListener - { - private String _valueName = null; - - public ValueChangeListener(String valueName) - { - _valueName = valueName; - } - - public void stateChanged(ChangeEvent e) - { - - - _state.setUztwc(_uztwcLabeledSlider.getModelValue()); - _state.setUzfwc(_uzfwcLabeledSlider.getModelValue()); - - _state.setLztwc(_lztwcLabeledSlider.getModelValue()); - _state.setLzfsc(_lzfscLabeledSlider.getModelValue()); - _state.setLzfpc(_lzfpcLabeledSlider.getModelValue()); - - _state.setAdimc(_adimcLabeledSlider.getModelValue()); - - - setSacSlidersFromModel(); - - notifyListeners(_valueName + " changed"); - } - } - - - - // ----------------------------------------------------------------------------------- - - - - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/MonthlyValueEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/MonthlyValueEditor.java deleted file mode 100644 index 682ef22a40..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/MonthlyValueEditor.java +++ /dev/null @@ -1,735 +0,0 @@ -/* - * Created on Jan 22, 2004 - * - * Filename : MonthlyValueEditor.java - * Author : Gautam Sood - * Last Revision Date : Jan 22, 2004 - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableHelper; - -public class MonthlyValueEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _monthlyValueListPanel = new JPanel(); - private JPanel _monthlyValueTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private DataMgr _dataMgr = null; - private MonthlyValues _monthlyValues = null; - - private List _monthlyValuesList = null; - - private static final int DEFAULT_WIDTH = 450; - private static final int DEFAULT_HEIGHT = 654; - - private static final int MAX_WIDTH = 500; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 430; - private static final int MIN_HEIGHT = 500; - - private static final int NUMBER_OF_MONTHS = 12; - - private String _pe = "EA"; - - private String[] _durStringArray = { "1 hour", "3 hours", "6 hours", "12 hours", "1 day" }; - private int[] _durDbValueIntArray = { 1001, 1003, 1006, 1012, 2001 }; - private Map _durationMap = new HashMap(); - - private String _basinId = null; - - private JFrame _owner = null; - - private JLabel _basinIdLabel = getJLabel( "Basin ID" ); - private JLabel _peLabel = getJLabel( "PE" ); - private JLabel _durLabel = getJLabel( "Duration" ); - private JLabel _tsLabel = getJLabel( "TS" ); - private JLabel _extremumLabel = getJLabel( "Extremum" ); - private JLabel _postingTimeLabel = getJLabel( "Posting Time" ); - private JLabel _adjustmentLabel = getJLabel( "Adjustment?" ); - private JLabel _janLabel = getJLabel( "January" ); - private JLabel _febLabel = getJLabel( "February" ); - private JLabel _marLabel = getJLabel( "March" ); - private JLabel _aprLabel = getJLabel( "April" ); - private JLabel _mayLabel = getJLabel( "May" ); - private JLabel _junLabel = getJLabel( "June" ); - private JLabel _julLabel = getJLabel( "July" ); - private JLabel _augLabel = getJLabel( "August" ); - private JLabel _sepLabel = getJLabel( "September" ); - private JLabel _octLabel = getJLabel( "October" ); - private JLabel _novLabel = getJLabel( "November" ); - private JLabel _decLabel = getJLabel( "December" ); - - private static final int TEXTFIELD_LENGTH = 17; - private JTextField _basinIdTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _peTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _tsTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _extremumTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _postingTimeTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _janTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _febTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _marTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _aprTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _mayTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _junTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _julTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _augTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _sepTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _octTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _novTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _decTextField = getJTextField( TEXTFIELD_LENGTH ); - - private JCheckBox _adjustmentCheckBox = new JCheckBox(); - - private JComboBox _durComboBox = new JComboBox( _durStringArray ); - - private JScrollPane _dataScrollPane = new JScrollPane( _monthlyValueTextPanel ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for the Table - private String[] _columnNames = { "Basin ID", "PE", "DUR", "TS", "Extremum", "Adjustment" }; - private String[] _dbColumnNames = { "lid", "pe", "dur", "ts", "extremum", "adjustment" }; - private String[][] _monthlyValuesStringArray = null; - private JTable _monthlyValuesTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel =null; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - - private MonthlyValueEditor( JFrame owner, DataMgr dataMgr ) - { - this( owner, dataMgr, "", "EA", true ); - } - - private MonthlyValueEditor( JFrame owner, DataMgr dataMgr, String basinId ) - { - this( owner, dataMgr, basinId, "EA", true ); - } - - public MonthlyValueEditor( JFrame owner, DataMgr dataMgr, String basinId, String pe, boolean isModal ) - { - super( owner, isModal ); - this.setTitle( "Monthly Value Editor" ); - - _owner = owner; - _basinId = basinId; - _dataMgr = dataMgr; - _pe = pe; - initialize(); - } - - private void initialize() - { - - long currentTime = System.currentTimeMillis(); - - setupDurationHashMap(); - setupTable(); - - AddMonthlyValueListPanelComponents(); - AddMonthlyValueDataPanelComponents(); - AddButtons(); - AddFrameComponents(); - AddListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - { - int index = -1; - boolean foundBasinId= false; - - _tableHelper.setOrderByClause( 0 ); - - String whereString = " WHERE pe='" + _pe + "' "; - - whereString += _tableHelper.getOrderByClause(); - _monthlyValuesList = _dataMgr.loadMonthlyValuesList( whereString ); - - _monthlyValuesStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _monthlyValuesStringArray ); - _monthlyValuesTable = new JTable( _tableModel ); - _monthlyValuesTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _monthlyValuesTable.setPreferredScrollableViewportSize( new Dimension( 380, 100 ) ); - _listSelectionModel = _monthlyValuesTable.getSelectionModel(); - _scrollPane = new JScrollPane( _monthlyValuesTable ); - if ( _basinId != null ) - { - for ( int i = 0; i < _monthlyValuesList.size(); i++ ) - { - MonthlyValues monthlyValues = (MonthlyValues) _monthlyValuesList.get( i ); - - if ( _basinId.equalsIgnoreCase( monthlyValues.getBasinId().trim() ) ) - { - index = i; - foundBasinId = true; - _monthlyValues = monthlyValues; - break; - } - } - } - - if ( ! foundBasinId ) // If no basin ID found in the Params list, selects the first one by default. - { - if (_monthlyValuesList.size() > 0) - { - _monthlyValues = (MonthlyValues) _monthlyValuesList.get( 0 ); - } - } - - - if ( foundBasinId ) // Checks if a Basin Id was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _monthlyValuesTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void setupDurationHashMap() - { - for ( int i = 0; i < _durStringArray.length; i++ ) - { - Integer key = new Integer( _durDbValueIntArray[ i ] ); - String value = _durStringArray[ i ] ; - _durationMap.put( key, value ); - } - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _monthlyValuesList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - Integer durationInteger = null; - - MonthlyValues monthlyValues = (MonthlyValues) _monthlyValuesList.get( i ); - - int duration = monthlyValues.getDur(); - durationInteger = new Integer( duration ); - String durationString = (String) _durationMap.get( durationInteger ); - - dataArray[ i ][ 0 ] = monthlyValues.getBasinId(); - dataArray[ i ][ 1 ] = monthlyValues.getPe(); - dataArray[ i ][ 2 ] = durationString; - dataArray[ i ][ 3 ] = monthlyValues.getTs(); - dataArray[ i ][ 4 ] = monthlyValues.getExtremum(); - dataArray[ i ][ 5 ] = "" + monthlyValues.isAdjustment(); - } - return dataArray; - } - - private void refreshMonthlyValuesTable() - { - int index = 0; - - String whereString = " WHERE pe='" + _pe + "' "; - - whereString += _tableHelper.getOrderByClause(); - - _monthlyValuesList = _dataMgr.loadMonthlyValuesList( whereString ); - - _monthlyValuesStringArray = convertListToArray(); - if ( _monthlyValues != null ) - { - for ( int i = 0; i < _monthlyValuesList.size(); i++ ) - { - MonthlyValues monthlyValues = (MonthlyValues) _monthlyValuesList.get( i ); - - if ( _monthlyValues.equals( monthlyValues ) ) - { - index = i; - break; - } - } - } - _tableModel.updateData( _monthlyValuesStringArray ); - _tableModel.fireTableChanged( null ); - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _monthlyValuesTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void AddMonthlyValueListPanelComponents() - /******************** - Purpose: Add's Components to the JTable Scroll Pane Panel - *********************/ - { - _monthlyValueListPanel.setLayout( new GridBagLayout() ); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _monthlyValueListPanel, _scrollPane, 0, 0, 5, 25, 0, 1, GridBagConstraints.BOTH ); - } - - private void AddMonthlyValueDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the _monthlyValueTextPanel - *********************/ - { - _monthlyValueTextPanel.setLayout( new GridBagLayout() ); - - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _basinIdLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _basinIdTextField, 10, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _peLabel, 0, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _peTextField, 10, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _durLabel, 0, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _durComboBox, 10, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _tsLabel, 0, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _tsTextField, 10, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _extremumLabel, 0, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _extremumTextField, 10, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _postingTimeLabel, 0, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _postingTimeTextField, 10, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _adjustmentLabel, 0, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _adjustmentCheckBox, 10, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _janLabel, 0, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _janTextField, 10, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _febLabel, 0, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _febTextField, 10, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _marLabel, 0, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _marTextField, 10, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _aprLabel, 0, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _aprTextField, 10, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _mayLabel, 0, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _mayTextField, 10, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _junLabel, 0, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _junTextField, 10, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _julLabel, 0, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _julTextField, 10, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _augLabel, 0, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _augTextField, 10, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _sepLabel, 0, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _sepTextField, 10, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _octLabel, 0, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _octTextField, 10, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _novLabel, 0, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _novTextField, 10, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _decLabel, 0, 180, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _decTextField, 10, 180, 5, 1, GridBagConstraints.BOTH ); - - _postingTimeTextField.setEditable( false ); - _peTextField.setEditable( false ); - } - - private void AddButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _buttonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 3, 22, 2, GridBagConstraints.BOTH ); - } - - private void AddFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - _dataScrollPane.setPreferredSize( new Dimension( 150, 300 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _monthlyValueListPanel, 0, 0, 10, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 17, 20, 15, 0, .5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - - if ( _monthlyValues != null ) - { - double[] valueArray = _monthlyValues.getValueArray(); - - int duration = 0; - - _basinIdTextField.setText( _monthlyValues.getBasinId() ); - _postingTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _monthlyValues.getPostingTime() ) ); - _peTextField.setText( _monthlyValues.getPe() ); - - duration = _monthlyValues.getDur(); // Returns either 1001, 1003, 1006, or 1012 - - _durComboBox.setSelectedIndex( getDurationValueIndex( duration ) ); - - _tsTextField.setText( _monthlyValues.getTs() ); - _extremumTextField.setText( _monthlyValues.getExtremum() ); - _adjustmentCheckBox.setSelected( _monthlyValues.isAdjustment() ); - _janTextField.setText( Double.toString( valueArray[ 0 ] ) ); - _febTextField.setText( Double.toString( valueArray[ 1 ] ) ); - _marTextField.setText( Double.toString( valueArray[ 2 ] ) ); - _aprTextField.setText( Double.toString( valueArray[ 3 ] ) ); - _mayTextField.setText( Double.toString( valueArray[ 4 ] ) ); - _junTextField.setText( Double.toString( valueArray[ 5 ] ) ); - _julTextField.setText( Double.toString( valueArray[ 6 ] ) ); - _augTextField.setText( Double.toString( valueArray[ 7 ] ) ); - _sepTextField.setText( Double.toString( valueArray[ 8 ] ) ); - _octTextField.setText( Double.toString( valueArray[ 9 ] ) ); - _novTextField.setText( Double.toString( valueArray[ 10 ] ) ); - _decTextField.setText( Double.toString( valueArray[ 11 ] ) ); - } - else - { - _basinIdTextField.setText( "" ); - _postingTimeTextField.setText( "Not Posted Yet" ); - _peTextField.setText( _pe ); - _durComboBox.setSelectedIndex( 0 ); - _tsTextField.setText( "" ); - _extremumTextField.setText( "" ); - _adjustmentCheckBox.setSelected( false ); - _janTextField.setText( "" ); - _febTextField.setText( "" ); - _marTextField.setText( "" ); - _aprTextField.setText( "" ); - _mayTextField.setText( "" ); - _junTextField.setText( "" ); - _julTextField.setText( "" ); - _augTextField.setText( "" ); - _sepTextField.setText( "" ); - _octTextField.setText( "" ); - _novTextField.setText( "" ); - _decTextField.setText( "" ); - } - } - - private void AddListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _monthlyValuesTable.getTableHeader().addMouseListener( new TableSortingListener() ); - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _monthlyValuesTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshMonthlyValuesTable(); - } - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _monthlyValuesTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _monthlyValuesList.isEmpty() ) ) - { - _monthlyValues = (MonthlyValues) _monthlyValuesList.get( index ); - } - else - { - _monthlyValues = null; - } - loadTextFields(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - - MonthlyValues monthlyValues = new MonthlyValues(); - double[] valueArray = new double[ NUMBER_OF_MONTHS ]; - - if ( - ( ! isEmptyString( _basinIdTextField.getText() ) ) && - ( ! isEmptyString( _peTextField.getText() ) ) && - ( ! isEmptyString( _tsTextField.getText() ) ) && - ( ! isEmptyString( _extremumTextField.getText() ) ) - ) // Checks to make sure the basinID and source - // are not empty strings - { - try - { - int index = 0; - - monthlyValues.setBasinId( _basinIdTextField.getText().trim() ); - monthlyValues.setPe( _pe ); - - index = _durComboBox.getSelectedIndex(); - monthlyValues.setDur( (short) _durDbValueIntArray[ index ] ); - - monthlyValues.setTs( _tsTextField.getText().trim() ); - monthlyValues.setExtremum( _extremumTextField.getText().trim() ); - monthlyValues.setAdjustment( _adjustmentCheckBox.isSelected() ); - valueArray[ 0 ] = Double.parseDouble( _janTextField.getText().trim() ); - valueArray[ 1 ] = Double.parseDouble( _febTextField.getText().trim() ); - valueArray[ 2 ] = Double.parseDouble( _marTextField.getText().trim() ); - valueArray[ 3 ] = Double.parseDouble( _aprTextField.getText().trim() ); - valueArray[ 4 ] = Double.parseDouble( _mayTextField.getText().trim() ); - valueArray[ 5 ] = Double.parseDouble( _junTextField.getText().trim() ); - valueArray[ 6 ] = Double.parseDouble( _julTextField.getText().trim() ); - valueArray[ 7 ] = Double.parseDouble( _augTextField.getText().trim() ); - valueArray[ 8 ] = Double.parseDouble( _sepTextField.getText().trim() ); - valueArray[ 9 ] = Double.parseDouble( _octTextField.getText().trim() ); - valueArray[ 10 ] = Double.parseDouble( _novTextField.getText().trim() ); - valueArray[ 11 ] = Double.parseDouble( _decTextField.getText().trim() ); - - monthlyValues.setValues( valueArray ); - - _dataMgr.saveMonthlyValues( monthlyValues ); - _monthlyValues = monthlyValues; - refreshMonthlyValuesTable(); - } - catch ( NumberFormatException exception ) - { - - DialogHelper.displayMessageDialog(null, - "There is a parsing error in your input", - "Error Message" ); - - //JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - else - { - DialogHelper.displayMessageDialog(null, - "Empty Strings are not allowed", - "Error Message" ); - - //JOptionPane.showMessageDialog( null, "Empty Strings are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _monthlyValues = null; - loadTextFields(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - if ( _monthlyValues != null ) - { - confirm = DialogHelper.displayConfirmDialog(null, "Are you sure you want to delete this Monthly Value?", - "Delete Monthly Value"); - /* - choice = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete this Monthly Value?", - "Delete Monthly Value", JOptionPane.YES_NO_OPTION, - JOptionPane.WARNING_MESSAGE ); - */ - //if ( choice == JOptionPane.YES_OPTION ) - /* User selected YES */ - - if (confirm) - { - _dataMgr.deleteMonthlyValues( _monthlyValues ); - _monthlyValues = null; - refreshMonthlyValuesTable(); - } - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = MonthlyValueEditor.this.getHeight(); - int width = MonthlyValueEditor.this.getWidth(); -// System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - MonthlyValueEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - MonthlyValueEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - MonthlyValueEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - MonthlyValueEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private int getDurationValueIndex( int duration ) - { - int index = 0; - - for( int i = 0; i < _durDbValueIntArray.length; i++ ) - { - if ( _durDbValueIntArray [ i ] == duration ) - { - index = i; - } - - } - return index; - } - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - public static void main( String[] args ) - { - String basin_Id = "BLUO2"; - JFrame frame = new JFrame(); - DataMgr dataMgr = new DataMgr(); - - MonthlyValueEditor editor = new MonthlyValueEditor( frame, dataMgr, basin_Id, "EA", true ); - editor.setVisible(true); - } -} \ No newline at end of file diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingCurveDataPointCanvasAdapter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingCurveDataPointCanvasAdapter.java deleted file mode 100644 index 7a453fb518..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingCurveDataPointCanvasAdapter.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Created on Jul 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Comparator; -import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasurementPointComparator; -import ohd.hseb.measurement.MeasurementPointSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.DataCurvePainter; -import ohd.hseb.util.gui.drawing.DataPointCanvas; -import ohd.hseb.util.gui.drawing.DataPointCanvasBackgroundPainter; -import ohd.hseb.util.gui.drawing.ScalingHelper; - -/** - * @author GobsC - * - * - */ -public class RatingCurveDataPointCanvasAdapter -{ - private DataPointCanvas _canvas = null; - private DataPointCanvasBackgroundPainter _dataBackgroundPainter = null; - private DataCurvePainter _dataPointCurvePainter = null; - private MeasurementPointSeries _measurementPointSeries = null; - - MeasuringUnit _xUnit = MeasuringUnit.cfs; - MeasuringUnit _yUnit = MeasuringUnit.feet; - -//------------------------------------------------------------------------------------- - - - private class CanvasMouseMotionListener extends MouseMotionAdapter - { - private DataPointCanvas _canvas2 = null; - - public CanvasMouseMotionListener(DataPointCanvas canvas) - { - _canvas2 = canvas; - } - - public void mouseMoved(MouseEvent event) - { - - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas2.getViewport().getDataPoint(screenPoint); - - - if (_canvas2.getViewport().isViewable(dataPoint)) - { - updateCanvasDataPointText(dataPoint, _canvas); - } - } - - } - -// ------------------------------------------------------------------------------------- - - - public void updateCanvasDataPointText(DataPoint dataPoint, - DataPointCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String xUnitString = canvas.getDisplayedXMeasuringUnit().toString(); - String yUnitString = canvas.getDisplayedYMeasuringUnit().toString(); - - String message = getCanvasDataPointString(dataPoint, xUnitString, - yUnitString); - - canvas.setToolTipText(message); - - return; - } - -// ------------------------------------------------------------------------------------- - - private String getCanvasDataPointString(DataPoint dataPoint, - String xUnitString, - String yUnitString) - { - NumberFormat nfX = new DecimalFormat("###"); - - long hour = (long) Math.round(dataPoint.getX()); - String xValueString = nfX.format(hour); - - NumberFormat nfY = new DecimalFormat("###.##"); - String yValueString = nfY.format(dataPoint.getY()); - - String dataPointString = xValueString + " " + xUnitString + " , " - + yValueString + " " + yUnitString; - - return dataPointString; - } -// ------------------------------------------------------------------------------------- - public DataPointCanvas initCanvas() - { - - - // init the drawing variables - boolean compareXValues = true; - boolean ascendingOrder = true; - Comparator comparator = new MeasurementPointComparator(compareXValues, ascendingOrder); // compare X values - - _measurementPointSeries = new MeasurementPointSeries(_xUnit, _yUnit, comparator); - - int x = 0; - int y = 0; - int width = 1000; - int height = 700; - - - // scaling helpers end up affecting the overall viewport window and - // what numbers are displayed for major and minor tick marks by painter - ScalingHelper horizontalScalingHelper = new ScalingHelper(0.0, 0.0); - ScalingHelper verticalScalingHelper = new ScalingHelper(0.0, 0.0); - - /* - double[] niceMinorIncrementArray = {1, 2, 4, 8, 12, 24 }; - horizontalScalingHelper.setNiceMinorIncrementArray(niceMinorIncrementArray); - - double[] niceMajorIncrementArray = {6, 12, 24, 48, 96, 120 }; - horizontalScalingHelper.setNiceMajorIncrementArray(niceMajorIncrementArray); - */ - - _canvas = new DataPointCanvas(_xUnit, _yUnit, - x, y, - width, height, - horizontalScalingHelper, - verticalScalingHelper); - - _canvas.setPreferredSize(new Dimension(width, height)); - _canvas.setMinimumSize(new Dimension(width, height)); - - Color outlineColor = Color.WHITE; - boolean showMinorHorizontalTicks = true; - boolean showMinorVerticalTicks = true; - boolean showMinorVerticalLabels = false; - - // background Painter - _dataBackgroundPainter = - new DataPointCanvasBackgroundPainter(outlineColor, _canvas, - "cfs", "feet", - horizontalScalingHelper, verticalScalingHelper); - - _dataBackgroundPainter.setShowMinorHorizontalTicks(showMinorHorizontalTicks); - _dataBackgroundPainter.setShowMinorVerticalTicks(showMinorVerticalTicks); - _dataBackgroundPainter.setShowMinorVerticalLabels(showMinorVerticalLabels); - - // this painter is not to be used for determining scaling, - //so, this is just considered a plain-old CanvasPainter, - // instead of a DataPointCanvasPainter - _canvas.addCanvasPainter(_dataBackgroundPainter); - - - // data point curve painter - Color curveColor = Color.green; - _dataPointCurvePainter = new DataCurvePainter(_measurementPointSeries, _canvas, curveColor); - - _canvas.addDataPointCanvasPainter(_dataPointCurvePainter); - - _canvas.setTitle("Rating Curve"); - - _canvas.addMouseMotionListener(new CanvasMouseMotionListener(_canvas)); - - return _canvas; - - - - } //end initCanvas - - // ------------------------------------------------------------------------------------- - - public void refreshCanvas(Object dataObject) - { - List ratingPointList = (List) dataObject; - loadCanvasWithData(ratingPointList); - - _canvas.refresh(); - } - -// ------------------------------------------------------------------------------------ - - - private void loadCanvasWithData(List ratingPointList) - { - _measurementPointSeries.clear(); - - for ( int i = 0; i < ratingPointList.size(); i++ ) - { - RatingPoint ratingPoint = (RatingPoint) ratingPointList.get( i ); - - // add Measurement Points to the points for the unitHydrograph - Measurement dischargeMeasurement = new Measurement(ratingPoint.getDischarge(), _xUnit); - Measurement stageMeasurement = new Measurement(ratingPoint.getShiftedStage(), _yUnit); - - MeasurementPoint point = new MeasurementPoint(dischargeMeasurement, stageMeasurement); - - _measurementPointSeries.addPoint(point); - - } - - // System.out.println("loadCanvasWithData says it has " + - // _measurementPointSeries.getPointCount() + " points."); - } - -// ------------------------------------------------------------------------------------ - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingCurveEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingCurveEditor.java deleted file mode 100644 index 6f0fedcf40..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingCurveEditor.java +++ /dev/null @@ -1,1096 +0,0 @@ -/* - * Created on Jun 22, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 22, 2004 - * - */ - -/** - * @author SoodG -*/ - -package ohd.hseb.sshp.window; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.RatingShift; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.StringParser; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeDialog; -import ohd.hseb.util.gui.DateTimeEvent; -import ohd.hseb.util.gui.DateTimeEventListener; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; -import ohd.hseb.util.gui.TableHelper2; -import ohd.hseb.util.gui.drawing.DataPointCanvas; - - -//------------------------------------------------------------------------------------ - -public class RatingCurveEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _ratingShiftPanel = new JPanel(); - private JPanel _ratingCurveDataPanel = new JPanel(); - private JPanel _ratingCurveButtonPanel = new JPanel(); - private JPanel _ratingCurveDisplayPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private DataMgr _dataMgr = null; - - private String _locationId = null; - - private RatingShift _ratingShift = null; - private RatingCurve _ratingCurve = null; - private RatingPoint _ratingPoint = null; - - //private double _shiftAmount = 0.0; - - private static final int DEFAULT_WIDTH = 1200; - private static final int DEFAULT_HEIGHT = 900; - - private static final int MAX_WIDTH = 5000; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 1075; - private static final int MIN_HEIGHT = 860; - - private List _ratingShiftList = null; -// private List _ratingPointList = new ArrayList(); - - //used for JFormattedTextFields - private static final String _decimalFormatString = "0.000"; - private DecimalFormat _decimalFormat = new DecimalFormat( _decimalFormatString ); - - //used for the rating shift entries - private JLabel _shiftDateLabel = getJLabel( "Shift Date" ); - private JLabel _shiftValueLabel = getJLabel( "Value" ); - private JLabel _shiftActiveLabel = getJLabel( "Active?" ); - - private JTextField _shiftDateTextField = getJTextField( 15 ); - private JTextField _shiftValueTextField = getJTextField( 15 ); - private JCheckBox _shiftActiveCheckBox = new JCheckBox(); - - private JButton _removeShiftButton = new JButton( "Remove Shift" ); - private JButton _saveShiftButton = new JButton( "Save Shift" ); - - // used for the rating curve entries - private JLabel _stageLabel = getJLabel( "Stage" ); - private JLabel _dischargeLabel = getJLabel( "Discharge" ); - private JLabel _tableHeaderLabel = getJLabel( "Active Rating Curve" ); - private JLabel _dateOfRatingLabel = null; - private JLabel _USGSRatingNumberLabel = null; - - private JTextField _stageTextField = getJTextField( 11 ); - private JTextField _dischargeTextField = getJTextField( 11 ); - - private JButton _importCurveButton = new JButton( "Import Curve" ); - private JButton _exportCurveButton = new JButton( "Export Curve" ); - private JButton _clearAllCurveButton = new JButton( "Clear All" ); - private JButton _removePointButton = new JButton( "Remove Point" ); - private JButton _updateInsertPointButton = new JButton( "Update/Insert" ); - private JButton _saveRatingCurveButton = new JButton( "Save Rating" ); - - // used for the buttonPanel - private JButton _closeButton = new JButton( "Close" ); - - //used for the ratingShift JTable - public static final String SHIFT_DATE = "Shift Date"; - public static final String VALUE = "Value"; - public static final String ACTIVE = "Active?"; - private String[] _shiftColumnNames = { SHIFT_DATE, VALUE, ACTIVE }; - - private String[][] _ratingShiftStringArray = null; - private JTable _ratingShiftJTable = null; - private JScrollPane _shiftScrollPane = null; - private SshpTableModel _shiftTableModel = null; - private ListSelectionModel _shiftListSelectionModel = null; - private RatingShiftComparator _shiftComparator = new RatingShiftComparator(); - private TableHelper2 _shiftTableHelper = new TableHelper2( _shiftComparator, _shiftColumnNames ); - - //used for the ratingCurve JTable - public static final String STAGE = "Stage"; - public static final String STAGE_WITH_SHIFT = "Stage w/ Shift"; - public static final String DISCHARGE = "Discharge"; - private String[] _ratingCurveColumnNames = { STAGE, STAGE_WITH_SHIFT, DISCHARGE }; - - private String[][] _ratingCurveStringArray = null; - private JTable _ratingCurveJTable = null; - private JScrollPane _curveScrollPane = null; - private SshpTableModel _curveTableModel = null; - private ListSelectionModel _curveListSelectionModel = null; -// private RatingPointComparator _pointComparator = new RatingPointComparator(); -// private TableHelper2 _curveTableHelper = new TableHelper2( _pointComparator, _ratingCurveColumnNames ); - - // ---------------------------------------------------------------------------------------------- - //drawing variables - - RatingCurveDataPointCanvasAdapter _canvasMgr = null; - DataPointCanvas _canvas = null; - // ---------------------------------------------------------------------------------------------- - - - public RatingCurveEditor( Frame owner, DataMgr dataMgr, String locationId, boolean isModal ) - { - super( owner, isModal ); - _locationId = locationId; - this.setTitle( "Rating Curve - " + _locationId ); - _dataMgr = dataMgr; - initialize(); - } -// ------------------------------------------------------------------------------------ - - private void initialize() - { - - // initialize the drawing area (canvas) - _canvasMgr = new RatingCurveDataPointCanvasAdapter(); - _canvas = _canvasMgr.initCanvas(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - - setupRatingShiftTable(); - setupRatingCurveTable(); - - addRatingShiftPanelComponents(); - addRatingCurvePanelComponents(); - addRatingCurveButtonPanelComponents(); - addButtonPanelComponents(); - addFrameComponents(); - - - - - addListeners(); - - // setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - - } -// ------------------------------------------------------------------------------------ - - - - private void addRatingShiftPanelComponents() - { - _ratingShiftPanel.setLayout( new GridBagLayout() ); - - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - JPanel horizontalSeparatorPanel3 = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - - horizontalSeparatorPanel3.setPreferredSize( new Dimension( 35, 40 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftScrollPane, 0, 0, 3, 5, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, horizontalSeparatorPanel, 0, 5, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftDateLabel, 0, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftValueLabel, 1, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftActiveLabel, 2, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftDateTextField, 0, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftValueTextField, 1, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftActiveCheckBox, 2, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, verticalSeparatorPanel, 3, 0, 1, 8, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, horizontalSeparatorPanel3, 4, 0, 2, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _removeShiftButton, 4, 1, 2, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, horizontalSeparatorPanel2, 4, 2, 2, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _saveShiftButton, 4, 3, 2, 1, GridBagConstraints.BOTH ); - - java.awt.Color background = _shiftDateTextField.getBackground(); //store the editable color - _shiftDateTextField.setEditable( false ); - _shiftDateTextField.setBackground(background); //make it appear editable - } -// ------------------------------------------------------------------------------------ - - private void addButtonPanelComponents() - { - _buttonPanel.setLayout( new GridBagLayout() ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 0, 0, 1, 1, GridBagConstraints.BOTH ); - - - } -// ------------------------------------------------------------------------------------ - - private void addRatingCurvePanelComponents() - { - JPanel horizontalSeparatorPanel = new JPanel(); - _ratingCurveDataPanel.setLayout( new GridBagLayout() ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _tableHeaderLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _dateOfRatingLabel, 0, 1, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _USGSRatingNumberLabel, 0, 2, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _curveScrollPane, 0, 3, 5, 10, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, horizontalSeparatorPanel, 0, 13, 5, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _importCurveButton, 0, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _exportCurveButton, 1, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _saveRatingCurveButton, 2, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _clearAllCurveButton, 3, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _removePointButton, 4, 15, 1, 1, GridBagConstraints.NONE ); - - if ( _ratingCurve.getRatingPointCount() > 0 ) - { - _importCurveButton.setEnabled( false ); - } - - } -// ------------------------------------------------------------------------------------ - - private void addRatingCurveButtonPanelComponents() - { - _ratingCurveButtonPanel.setLayout( new GridBagLayout() ); - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _updateInsertPointButton, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, verticalSeparatorPanel, 1, 0, 1, 6, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _stageLabel, 2, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _dischargeLabel, 3, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _stageTextField, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _dischargeTextField, 3, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, horizontalSeparatorPanel, 0, 2, 4, 4, 1, 1, GridBagConstraints.BOTH ); - } - -// ------------------------------------------------------------------------------------ - - - private void addFrameComponents() - { - _frameContentPane.setLayout( new GridBagLayout() ); - - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - JPanel horizontalSeparatorPanel3 = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - -/* - verticalSeparatorPanel.setBackground( Color.YELLOW ); - horizontalSeparatorPanel.setBackground( Color.YELLOW ); - horizontalSeparatorPanel2.setBackground( Color.YELLOW ); - horizontalSeparatorPanel3.setBackground( Color.YELLOW ); -*/ - _canvas.setPreferredSize( new Dimension( 300, 500 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _canvas, 0, 0, 10, 8, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, verticalSeparatorPanel, 10, 0, 2, 22, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 8, 10, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _ratingShiftPanel, 0, 17, 8, 5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _ratingCurveDataPanel, 12, 0, 9, 17, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel3, 12, 17, 9, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _ratingCurveButtonPanel, 12, 19, 9, 5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 24, 21, 3, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 27, 21, 1, GridBagConstraints.BOTH ); - - } -// ------------------------------------------------------------------------------------ - - private void setupRatingShiftTable() - { - int index = 0; - - _ratingShiftList = _dataMgr.getRatingShift( _locationId ); - if (_ratingShiftList == null) - { - _ratingShiftList = new ArrayList(); - } - - _ratingShiftStringArray = convertShiftListToArray(); - - if (_ratingShiftList != null && _ratingShiftList.size() != 0 ) - { - _ratingShift = (RatingShift) _ratingShiftList.get( 0 ); - } - - _shiftTableModel = new SshpTableModel( _shiftColumnNames, _ratingShiftStringArray ); - _ratingShiftJTable = new JTable( _shiftTableModel ); - _ratingShiftJTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _ratingShiftJTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - _shiftListSelectionModel = _ratingShiftJTable.getSelectionModel(); - _shiftScrollPane = new JScrollPane( _ratingShiftJTable ); - - _shiftListSelectionModel.setSelectionInterval( 0, 0 ); - - Rectangle rect = _ratingShiftJTable.getCellRect( index, 0, true ); - _shiftScrollPane.getViewport().setViewPosition( rect.getLocation() ); - - loadShiftTextFields(); - } -// ------------------------------------------------------------------------------------ - - private String[][] convertShiftListToArray() - { - int ratingShiftListSize = 0; - if (_ratingShiftList != null) - { - ratingShiftListSize = _ratingShiftList.size(); - } - - String[][] dataArray = new String[ ratingShiftListSize ][ _shiftColumnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - RatingShift entry = (RatingShift) _ratingShiftList.get( i ); - - dataArray[ i ][ 0 ] = DbTimeHelper.getDateStringFromLongTime( entry.getDate() ); - dataArray[ i ][ 1 ] = "" + entry.getShiftAmount(); - dataArray[ i ][ 2 ] = "" + entry.isActive(); - } - return dataArray; - } -// ------------------------------------------------------------------------------------ - - private void refreshShiftListJTable() - { - int index = 0; - - _ratingShiftStringArray = convertShiftListToArray(); - - if ( _ratingShift != null ) - { - if ( _ratingShiftList.size() != 0 ) - { - for ( int i = 0; i < _ratingShiftList.size(); i++ ) - { - RatingShift shift = (RatingShift) _ratingShiftList.get( i ); - - if ( shift.equals( _ratingShift ) ) - { - index = i; - break; - } - } - } - } - - _shiftTableModel.updateData( _ratingShiftStringArray ); - _shiftTableModel.fireTableChanged( null ); - - _shiftListSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _ratingShiftJTable.getCellRect(index, 0, true); - _shiftScrollPane.getViewport().setViewPosition(rect.getLocation()); - loadShiftTextFields(); - } -// ------------------------------------------------------------------------------------ - - private void setupRatingCurveTable() - { - int index = 0; - - _ratingCurve = _dataMgr.loadRatingCurve( _locationId ); - _ratingCurveStringArray = convertCurveListToArray(); - -/* - for ( int i = 0; i < _ratingCurve.getRatingPointCount(); i++ ) - { - _ratingPointList.add( _ratingCurve.getRatingPoint( i ) ); - } -*/ - - if ( _ratingCurve.getRatingPointCount() != 0 ) - { - _ratingPoint = _ratingCurve.getFirstRatingPoint(); - } - - _curveTableModel = new SshpTableModel( _ratingCurveColumnNames, _ratingCurveStringArray ); - _ratingCurveJTable = new JTable( _curveTableModel ); - _ratingCurveJTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _ratingCurveJTable.setPreferredScrollableViewportSize( new Dimension( 300, 400 ) ); - _curveListSelectionModel = _ratingCurveJTable.getSelectionModel(); - _curveScrollPane = new JScrollPane( _ratingCurveJTable ); - - _curveListSelectionModel.setSelectionInterval( 0, 0 ); - - Rectangle rect = _ratingCurveJTable.getCellRect( index, 0, true ); - _curveScrollPane.getViewport().setViewPosition( rect.getLocation() ); - - _dateOfRatingLabel = getJLabel( "Date of Rating: " + DbTimeHelper.getDateStringFromLongTime( _ratingCurve.getRatingDate() ) ); - _USGSRatingNumberLabel = getJLabel ( "USGS Rating No.: " + _ratingCurve.getUsgsRatingNumber() ); - loadCurveTextFields(); - - List ratingPointList = _ratingCurve.getRatingPointList(); - _canvasMgr.refreshCanvas(ratingPointList); - } - -// ------------------------------------------------------------------------------------ - - - private void refreshRatingCurveListJTable(boolean shouldReloadData) - { - int index = 0; - - if (shouldReloadData) - { - _ratingCurve = _dataMgr.loadRatingCurve( _locationId ); - } - _ratingCurveStringArray = convertCurveListToArray(); - - if ( ( _ratingCurve != null ) && ( _ratingPoint != null ) ) - { - if ( _ratingCurve.getRatingPointCount() > 0 ) - { - for ( int i = 0; i < _ratingCurve.getRatingPointCount(); i++ ) - { - RatingPoint point = (RatingPoint) _ratingCurve.getRatingPoint( i ); - - if ( point.equals( _ratingPoint ) ) - { - index = i; - break; - } - } - } - } - - _curveTableModel.updateData( _ratingCurveStringArray ); - _curveTableModel.fireTableChanged( null ); - - _curveListSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _ratingCurveJTable.getCellRect(index, 0, true); - _curveScrollPane.getViewport().setViewPosition(rect.getLocation()); - loadCurveTextFields(); - - _canvasMgr.refreshCanvas(_ratingCurve.getRatingPointList()); - } - -// ------------------------------------------------------------------------------------ - - private String[][] convertCurveListToArray() - { - String[][] dataArray = new String[ _ratingCurve.getRatingPointCount() ][ _ratingCurveColumnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - RatingPoint point = _ratingCurve.getRatingPoint( i ); - - dataArray[ i ][ 0 ] = "" + _decimalFormat.format( point.getUnshiftedStage() ); - dataArray[ i ][ 1 ] = "" + _decimalFormat.format( point.getShiftedStage() ); - dataArray[ i ][ 2 ] = "" + _decimalFormat.format( point.getDischarge() ); - } - return dataArray; - } -// ------------------------------------------------------------------------------------ - - private void loadCurveTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _ratingPoint != null ) - { - _stageTextField.setText( "" + _ratingPoint.getUnshiftedStage() ); - _dischargeTextField.setText( "" + _ratingPoint.getDischarge() ); - } - else - { - _stageTextField.setText( "" ); - _dischargeTextField.setText( "" ); - } - } -// ------------------------------------------------------------------------------------ - - private void loadShiftTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _ratingShift != null ) - { - _shiftDateTextField.setText( DbTimeHelper.getDateStringFromLongTime( _ratingShift.getDate() ) ); - _shiftValueTextField.setText( "" + _ratingShift.getShiftAmount() ); - _shiftActiveCheckBox.setSelected( _ratingShift.isActive() ); - } - else - { - _shiftDateTextField.setText( "" ); - _shiftValueTextField.setText( "" ); - _shiftActiveCheckBox.setSelected( false ); - } - } -// ------------------------------------------------------------------------------------ - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _closeButton.addActionListener( windowCloser ); - _removeShiftButton.addActionListener( new RemoveShiftButtonListener() ); - _saveShiftButton.addActionListener( new SaveShiftButtonListener() ); - _shiftDateTextField.addMouseListener( new TimeTextFieldListener() ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _shiftListSelectionModel.addListSelectionListener( new RatingShiftTableUpdateListener() ); - - _updateInsertPointButton.addActionListener( new UpdateInsertPointButtonListener() ); - _removePointButton.addActionListener( new RemovePointButtonListener() ); - _clearAllCurveButton.addActionListener( new ClearAllCurveButtonListener() ); - _saveRatingCurveButton.addActionListener( new SaveRatingCurveButtonListener() ); - _importCurveButton.addActionListener( new ImportRatingCurveButtonListener() ); - - _shiftListSelectionModel.addListSelectionListener( new RatingShiftTableUpdateListener() ); - _curveListSelectionModel.addListSelectionListener( new RatingCurveTableUpdateListener() ); - _ratingShiftJTable.getTableHeader().addMouseListener( new TableSortingListener( _ratingShiftJTable, true ) ); - _ratingCurveJTable.getTableHeader().addMouseListener( new TableSortingListener( _ratingCurveJTable, false ) ); - - } - -// ------------------------------------------------------------------------------------ - private boolean isNewEntry( RatingShift newShift ) - { - boolean isNew = true; - - if (_ratingShiftList != null) - { - for (int i = 0; i < _ratingShiftList.size(); i++) - { - RatingShift shift = (RatingShift) _ratingShiftList.get(i); - - if (shift.equals(newShift)) - { - isNew = false; - } - } - } - return isNew; - } - -// -------------------------------------------------------------------------------------- - - private void importRatingCurveFromFile( File importFile ) - { - boolean addToDatabase = true; - - try - { - BufferedReader _reader = new BufferedReader( new FileReader( importFile ) ); - String line = _reader.readLine(); - - // if ( ( _ratingCurve.getRatingPointCount() == 0) && ( _ratingPointList.size() == 0 ) ) - if ( ( _ratingCurve.getRatingPointCount() == 0)) - { - while( line != null ) - { - while( line.startsWith( "x" ) ) - { - line = _reader.readLine(); - } - String[] tokenizedLine = StringParser.tokenize( line ); - - RatingPoint point = new RatingPoint(); - - point.setUnshiftedStage( Double.parseDouble( tokenizedLine[ 0 ] ) ); - point.setDischarge( Double.parseDouble( tokenizedLine[ 1 ] ) ); - - _ratingCurve.addRatingPoint( point ); - // _ratingPointList.add( point ); - - line = _reader.readLine(); - } - } - _importCurveButton.setEnabled( false ); - - refreshRatingCurveListJTable(true); - } - catch( FileNotFoundException e ) - { - } - catch( IOException e ) - { - } - catch( ArrayIndexOutOfBoundsException e ) - { - System.out.println( "Invalid file format: " + importFile.getName() ); - } - - } -// -------------------------------------------------------------------------------------- - - private File displayImportFileChooser() - { - JFileChooser _importFileChooser = new JFileChooser( "d:/data/rating_curve" ); - File file = null; - List filterList = new ArrayList(); - - filterList.add( "rating" ); - - _importFileChooser.addChoosableFileFilter( new ExtensionFileFilter( filterList, "Rating Curve Files (RATING)" ) ); - - int returnVal = _importFileChooser.showOpenDialog( this ); - - if (returnVal == JFileChooser.APPROVE_OPTION) - { - file = _importFileChooser.getSelectedFile(); - } - else - { - DialogHelper.displayMessageDialog( RatingCurveEditor.this, "Rating Curve file not imported." ); - } - return file; - } -// -------------------------------------------------------------------------------------- - private void addOrReplacePointInRatingPointList(RatingPoint pointToInsert) - { - - _ratingCurve.addRatingPoint(pointToInsert); - - } - -// -------------------------------------------------------------------------------------- - - private class RemoveShiftButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete the rating shift for " - + _locationId + "?", "Delete Rating Shift"); - - if ( confirm ) - { - _dataMgr.deleteRatingShift( _ratingShift ); - _ratingShiftList.remove( _ratingShift ); - _ratingShift = null; - refreshShiftListJTable(); - refreshRatingCurveListJTable(true); - } - - } - - } -// -------------------------------------------------------------------------------------- - - private class RatingCurveTableUpdateListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent arg0 ) - { - int index = _ratingCurveJTable.getSelectedRow(); - if ( ( index >= 0 ) && ( _ratingCurve.getRatingPointCount() >= 1 ) ) - { - _ratingPoint = _ratingCurve.getRatingPoint( index ); - } - else - { - _ratingPoint = null; - } - loadCurveTextFields(); - } - } -// -------------------------------------------------------------------------------------- - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } -// -------------------------------------------------------------------------------------- - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = RatingCurveEditor.this.getHeight(); - int width = RatingCurveEditor.this.getWidth(); - // System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - RatingCurveEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - RatingCurveEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - RatingCurveEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - RatingCurveEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } -// -------------------------------------------------------------------------------------- - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } -// -------------------------------------------------------------------------------------- - -/* - private boolean isEmptyString( String testingString ) - // - //Purpose: Check's whether the string passed in is an empty string - // - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } -*/ -// -------------------------------------------------------------------------------------- - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( "
" + label + "
" ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } -// -------------------------------------------------------------------------------------- - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } -// -------------------------------------------------------------------------------------- - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } -// -------------------------------------------------------------------------------------- - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - - // ------------------------------------------------------------------------------------ - - private class TableSortingListener extends MouseAdapter - { - JTable __table = null; - boolean __isRatingShiftJTable; - - public TableSortingListener( JTable table, boolean ratingShiftJTable ) - { - __table = table; - __isRatingShiftJTable = ratingShiftJTable; - } - - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = __table.getTableHeader().columnAtPoint( point ); - - if ( __isRatingShiftJTable ) - { - _shiftTableHelper.sortList( _ratingShiftList, column, true ); - refreshShiftListJTable(); - } - else - { - - } - } - } -// ------------------------------------------------------------------------------------ - - private class RatingShiftTableUpdateListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent arg0 ) - { - int index = _ratingShiftJTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _ratingShiftList.isEmpty() ) ) - { - _ratingShift = (RatingShift) _ratingShiftList.get( index ); - } - else - { - _ratingShift = null; - } - loadShiftTextFields(); - } - } -// ------------------------------------------------------------------------------------ - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - - if ( _shiftDateTextField.getText().trim().equals( "" ) ) - { - dateTime = System.currentTimeMillis(); - } - else - { - dateTime = DbTimeHelper.getLongTimeFromDateString( _shiftDateTextField.getText() ); - } - - JTextField textField = (JTextField) e.getSource(); - - DateTimeDialog dateTimeGUI = new DateTimeDialog( RatingCurveEditor.this, dateTime, "Rating Shift Date" ); - dateTimeGUI.setDateOnly(); - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - } - } -// ------------------------------------------------------------------------------------ - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } -// ------------------------------------------------------------------------------------ - - private class UpdateInsertPointButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - RatingPoint point = new RatingPoint(); - - point.setDischarge( Double.parseDouble( _dischargeTextField.getText() ) ); - point.setUnshiftedStage( Double.parseDouble( _stageTextField.getText() ) ); - point.setShiftAmount( _ratingCurve.getShiftAmount() ); - - - _ratingCurve.addRatingPoint( point ); - - addOrReplacePointInRatingPointList(point); - - if ( _importCurveButton.isEnabled() ) - { - _importCurveButton.setEnabled( false ); - } - refreshRatingCurveListJTable(false); - } - } -// ------------------------------------------------------------------------------------ - - private class RemovePointButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to remove the rating point from the rating curve?", - "Remove Rating Point"); - if ( confirm ) - { - // _ratingPointList.remove( _ratingPoint ); - _ratingCurve.removeRatingPoint( _ratingPoint ); - _ratingPoint = null; - - if ( _ratingCurve.getRatingPointCount() == 0 ) - { - _importCurveButton.setEnabled( true ); - } - else - { - _importCurveButton.setEnabled( false ); - } - refreshRatingCurveListJTable(false); - } - } - } -// ------------------------------------------------------------------------------------ - - private class ClearAllCurveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to remove all of the rating points?", - "Clear Rating Curve"); - - if ( confirm ) - { - int ratingPointCount = _ratingCurve.getRatingPointCount(); - - for ( int i = 0; i < ratingPointCount; i++ ) - { - _ratingCurve.removeRatingPoint( _ratingCurve.getFirstRatingPoint() ); - } - - // _ratingPointList.clear(); - - refreshRatingCurveListJTable(false); - - _importCurveButton.setEnabled( true ); - } - } - } -// ------------------------------------------------------------------------------------ - - private class SaveShiftButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean newEntry = false; - boolean validEntry = true; - - RatingShift newShift = new RatingShift(); - try - { - - newShift.setLid( _locationId ); - newShift.setDate( DbTimeHelper.getLongTimeFromDateString( _shiftDateTextField.getText().trim() ) ); - newShift.setShiftAmount( Double.parseDouble( _shiftValueTextField.getText().trim() ) ); - newShift.setActive( _shiftActiveCheckBox.isSelected() ); - } - catch( NumberFormatException error ) - { - DialogHelper.displayErrorDialog( RatingCurveEditor.this, "Illegal characters in the text fields", "Parsing Error" ); - validEntry = false; - } - - if ( validEntry ) - { - _dataMgr.saveRatingShift( newShift ); - - newEntry = isNewEntry( newShift ); - - if( newEntry ) - { - _ratingShift = newShift; - _ratingShiftList.add( _ratingShift ); - } - else - { - _ratingShiftList.remove( _ratingShift ); - _ratingShiftList.add( newShift ); - } - - _ratingCurve = _dataMgr.loadRatingCurve( _locationId ); - - refreshShiftListJTable(); - refreshRatingCurveListJTable(true); - } - } - } -// ------------------------------------------------------------------------------------ - - private class SaveRatingCurveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _dataMgr.saveRatingCurve( _ratingCurve ); - - DialogHelper.displayMessageDialog( null, - "Successfully saved Rating Curve", - "Save Successful" ); - } - } - -// ------------------------------------------------------------------------------------ - - private class ImportRatingCurveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - File importFile = RatingCurveEditor.this.displayImportFileChooser(); - if ( importFile != null ) - { - RatingCurveEditor.this.importRatingCurveFromFile( importFile ); - } - } - } -// ------------------------------------------------------------------------------------ - - - public static void main( String args[] ) - { - RatingCurveEditor editor = new RatingCurveEditor( new Frame(), new DataMgr(), "BLUO2", true ); - editor.show(); - } -// -------------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingPointComparator.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingPointComparator.java deleted file mode 100644 index b79fad798f..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingPointComparator.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Created on Jun 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 14, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.RatingPoint; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author SoodG -*/ -public class RatingPointComparator extends TableColumnComparator -{ - public RatingPointComparator() - { - } - - public int compareUnshiftedStage( RatingPoint entry1, RatingPoint entry2 ) - { - return( numberComparison( entry1.getUnshiftedStage(), entry2.getUnshiftedStage() ) ); - } - - public int compareShiftedStage( RatingPoint entry1, RatingPoint entry2 ) - { - return( numberComparison( entry1.getUnshiftedStage(), entry2.getUnshiftedStage() ) ); - } - - public int compareDischarge( RatingPoint entry1, RatingPoint entry2 ) - { - return( numberComparison( entry1.getDischarge(), entry2.getDischarge() ) ); - } - - public int numberComparison( double value1, double value2 ) - { - int returnValue = 0; - - if ( value1 < value2 ) - { - returnValue = -1; - } - else if ( value1 == value2 ) - { - returnValue = 0; - } - else // value1 > value2 - { - returnValue = 1; - } - - return returnValue; - } - - - public int compare( Object object1, Object object2 ) - { - RatingPoint entry1 = (RatingPoint) object1; - RatingPoint entry2 = (RatingPoint) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( RatingCurveEditor.STAGE ) ) - { - returnValue = compareUnshiftedStage( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.STAGE_WITH_SHIFT) ) - { - returnValue = compareShiftedStage( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.DISCHARGE ) ) - { - returnValue = compareDischarge( entry1, entry2 ); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingShiftComparator.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingShiftComparator.java deleted file mode 100644 index 5dff68620f..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RatingShiftComparator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Created on Jun 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 14, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.RatingShift; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author SoodG -*/ -public class RatingShiftComparator extends TableColumnComparator -{ - public RatingShiftComparator() - { - } - - public int compareShiftDate( RatingShift entry1, RatingShift entry2 ) - { - return( numberComparison( entry1.getDate(), entry2.getDate() ) ); - } - - public int compareValue( RatingShift entry1, RatingShift entry2 ) - { - return( numberComparison( entry1.getShiftAmount(), entry2.getShiftAmount() ) ); - } - - public int compareActive( RatingShift entry1, RatingShift entry2 ) - { - String entry1Active = Boolean.toString( entry1.isActive() ); - String entry2Active = Boolean.toString(entry2.isActive() ); - - int result = entry1Active.compareTo( entry2Active ); - - return result; - } - - public int numberComparison( double value1, double value2 ) - { - int returnValue = 0; - - if ( value1 < value2 ) - { - returnValue = -1; - } - else if ( value1 == value2 ) - { - returnValue = 0; - } - else // value1 > value2 - { - returnValue = 1; - } - - return returnValue; - } - - - public int compare( Object object1, Object object2 ) - { - RatingShift entry1 = (RatingShift) object1; - RatingShift entry2 = (RatingShift) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( RatingCurveEditor.SHIFT_DATE ) ) - { - returnValue = compareShiftDate( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.VALUE ) ) - { - returnValue = compareValue( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.ACTIVE ) ) - { - returnValue = compareActive( entry1, entry2 ); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditor.java deleted file mode 100644 index 957b7d58a3..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditor.java +++ /dev/null @@ -1,847 +0,0 @@ -/* - * Created on Nov 26, 2003 - * - * Filename : RegularTimeSeriesEditor.java - * Author : Gautam Sood - * Last Revision Date : Nov 26, 2003 - * - */ - -package ohd.hseb.sshp.window; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.measurement.TimeSeriesEvent; -import ohd.hseb.measurement.TimeSeriesListener; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; - -public class RegularTimeSeriesEditor extends JDialog -{ - private RegularTimeSeriesHolder _timeSeriesHolder = new RegularTimeSeriesHolder(); - - private TimeSeriesListener _timeSeriesListener = null; - - private List _absTimeMeasurementAndFieldsList = new ArrayList(); - private AbsTimeMeasurementAndFields _absTimeMeasurementAndFields = null; - - //nice initial scrolling members - private AbsTimeMeasurementAndFields _searchAbsTimeMeasurementAndFields = null; - private JPanel _searchMeasurementAndFieldsPanel = null; - - - private boolean _isEditable = true; - private long _startTime = 0; - private long _endTime = 0; - private long _intervalInHours = 0; - private long _intervalInMillis = 0; - private long _searchTime = 0; - private static final long HOUR_IN_MILLIS = 60 * 60 * 1000; - private DecimalFormat _decimalFormat = null; - private static final String _defaultFormatString = "0.00"; - private String _formatString = _defaultFormatString; - private ValueMapper _valueMapper = null; - private String _mappedValueLabelString = null; - private double _missingValue = 0.0; - private boolean _displayMappedValue = false; - private boolean _wasWindowActivated = false; - private double _minValue = 0.0; - private double _maxValue = 0.0; - - private static final int DEFAULT_WIDTH = 550; - private static final int DEFAULT_HEIGHT = 450; - - private static final int MAX_WIDTH = 600; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 450; - private static final int MIN_HEIGHT = 312; - - private Container _frameContentPane = getContentPane(); - private JButton _applyButton = new JButton( "Apply" ); - private JButton _closeButton = new JButton( "Close" ); - private JLabel _timeLabel = new JLabel( "Time (GMT) " ); - private JLabel _valueLabel = null; - private JLabel _mappedValueLabel = null; - private JLabel _missingValueLabel = new JLabel( "
Missing
Value?
" ); - private JPanel _dataPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - private JPanel _labelPanel = new JPanel(); - private JScrollPane _dataScrollPane = new JScrollPane( _dataPanel ); - - //used for custom notification - //private List _applyListenerList = new ArrayList(); - - // ------------------------------------------------------------------------------------------ - - public RegularTimeSeriesEditor( RegularTimeSeriesEditorDescriptor descriptor ) - { - super( descriptor.getOwner(), descriptor.isModal() ); - this.setTitle( descriptor.getTitleLabelString() ); - _valueLabel = new JLabel( descriptor.getValueLabelString() ); - _timeSeriesHolder = descriptor.getRegularTimeSeriesHolder(); - _isEditable = descriptor.isEditable(); - - _valueMapper = descriptor.getValueMapper(); - _mappedValueLabelString = descriptor.getMappedValueLabelString(); - - if ( _valueMapper != null ) - { - _mappedValueLabel = new JLabel( _mappedValueLabelString ); - _displayMappedValue = true; - } - _searchTime = descriptor.getInitialSearchTime(); - - String searchTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_searchTime); - - _formatString = descriptor.getTextFieldFormatString(); - _missingValue = descriptor.getMissingValue(); - _decimalFormat = new DecimalFormat( _formatString ); - _minValue = descriptor.getMinValue(); - _maxValue = descriptor.getMaxValue(); - - initialize(); - } - -// ------------------------------------------------------------------------------------------ - - - private void initialize() - { - _startTime = getTimeSeries().getStartTime(); - _endTime = getTimeSeries().getEndTime(); - _intervalInHours = getTimeSeries().getIntervalInHours(); - _intervalInMillis = _intervalInHours * HOUR_IN_MILLIS; - - addLabelPanelComponents(); - addDataPanelComponents(); - addButtonPanelComponents(); - addFrameComponents(); - addListeners(); - - refreshDataPanel(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - -// ------------------------------------------------------------------------------------------ - - private void initializeScrollAmount() - { - - int fieldHeight = 50; - if (_absTimeMeasurementAndFieldsList.size() > 0) - { - AbsTimeMeasurementAndFields measurementAndFields = - (AbsTimeMeasurementAndFields) _absTimeMeasurementAndFieldsList.get(0); - fieldHeight = measurementAndFields._valueTextField.getHeight(); - } - - // set the amount to scroll when clicking on the slider bar - _dataScrollPane.getVerticalScrollBar().setUnitIncrement( 2* fieldHeight ); - - return; - } -// ------------------------------------------------------------------------------------------ - - private void initializeScrollPosition() - { -// initialize the location of the slider bar - if ( ( _searchTime != 0 ) && ( _searchAbsTimeMeasurementAndFields != null ) ) - { - // rect is set to the dimensions of one of the value Text Fields - // so that we can use the y value - Rectangle rect = _searchAbsTimeMeasurementAndFields._valueTextField.getBounds(); - - _searchAbsTimeMeasurementAndFields._valueTextField.requestFocus( true ); - - Rectangle parentPanelRect = _searchMeasurementAndFieldsPanel.getBounds(); - - // Sets the y value of rectangle to the middle of the visible screen. - - int newY = rect.y + parentPanelRect.y; - if (newY < 0) - { - newY = 0; - } - int newX = rect.x; - - Point viewLocation = new Point (newX, newY); - - // String header = "RegularTimeSeriesEditor.initializeScrollPosition()"; - // System.out.println(header + "trying to set viewPosition to " + viewLocation); - - // System.out.println(header + "before setting, getViewPosition() = " + _dataScrollPane.getViewport().getViewPosition()); - _dataScrollPane.getViewport().setViewPosition(viewLocation); - - - // System.out.println(header + "after setting, getViewPosition() = " + _dataScrollPane.getViewport().getViewPosition()); - } - - } -// ------------------------------------------------------------------------------------------ - - private void initializeScrolling() - { - // Sets the scroll bar increment to 2 text fields per click - initializeScrollAmount(); - - initializeScrollPosition(); - - return; - } -// ------------------------------------------------------------------------------------------ - - private void addFrameComponents() - { - _frameContentPane.setLayout( new GridBagLayout() ); - - JPanel hSeparatorPanel = new JPanel(); - JPanel hSeparatorPanel2 = new JPanel(); - - hSeparatorPanel.setPreferredSize( new Dimension( 300, 5 ) ); - hSeparatorPanel2.setPreferredSize( new Dimension( 300, 20 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _labelPanel, 0, 0, 11, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, hSeparatorPanel, 0, 1, 11, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 3, 11, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, hSeparatorPanel2, 0, 23, 11, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 25, 11, 2, GridBagConstraints.BOTH ); - } -// ------------------------------------------------------------------------------------------ - - private void addLabelPanelComponents() - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - - _labelPanel.setLayout( new GridBagLayout() ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 100, 15 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 65, 15 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 65, 15 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _labelPanel, _timeLabel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, verticalSeparatorPanel, 1, 0, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, _valueLabel, 5, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, verticalSeparatorPanel2, 6, 0, 4, 1, GridBagConstraints.BOTH ); - if ( _mappedValueLabel != null ) - { - ComponentHelper.addFrameComponent( _labelPanel, _mappedValueLabel, 10, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, verticalSeparatorPanel3, 11, 0, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, _missingValueLabel, 15, 0, 1, 1, GridBagConstraints.BOTH ); - } - else - { - ComponentHelper.addFrameComponent( _labelPanel, _missingValueLabel, 10, 0, 1, 1, GridBagConstraints.BOTH ); - } - } -// ------------------------------------------------------------------------------------------ - - private void addDataPanelComponents() - { - //String header = "RegularTimeSeriesEditor.addDataPanelComponents():"; - int counter = 0; - - int yCoor = 1; - int yPanelCounter = 0; - - _dataPanel.setLayout( new GridBagLayout() ); - - JPanel subDataPanel = new JPanel(); - - for ( long time = _startTime; time <= _endTime; time += _intervalInMillis ) - { - if ( ( counter % 400 ) == 0 ) - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 40, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 60, 20 ) ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 20, 25 ) ); - - subDataPanel = new JPanel(); - yCoor = 0; - counter = 0; - subDataPanel.setLayout( new GridBagLayout() ); - ComponentHelper.addPanelComponent( subDataPanel, verticalSeparatorPanel2, 2, 0, 2, 20, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, verticalSeparatorPanel, 6, 0, 1, 20, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, verticalSeparatorPanel3, 8, 0, 1, 20, GridBagConstraints.BOTH ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataPanel, subDataPanel, 0, yPanelCounter, 1, 1, GridBagConstraints.BOTH ); - yPanelCounter++; - } - - Measurement measurement = getTimeSeries().getMeasurementByTime( time ); - double value = measurement.getValue(); - - _absTimeMeasurementAndFields = new AbsTimeMeasurementAndFields( time, value ); - _absTimeMeasurementAndFieldsList.add( _absTimeMeasurementAndFields ); - - if ( time == _searchTime ) - { - _searchAbsTimeMeasurementAndFields = _absTimeMeasurementAndFields; - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - _searchMeasurementAndFieldsPanel = subDataPanel; - // System.out.println(header + "timeString = " + timeString); - // System.out.println(header + "yPanelCounter = " + yPanelCounter); - } -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._valueDateTimeLabel, 0, yCoor, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._valueTextField, 4, yCoor, 1, 1, GridBagConstraints.BOTH ); - if ( _displayMappedValue ) - { - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._mappedValueTextField, 7, yCoor, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._missingValueCheckBox, 10, yCoor, 1, 1, GridBagConstraints.BOTH ); - } - else - { - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._missingValueCheckBox, 7, yCoor, 1, 1, GridBagConstraints.BOTH ); - } - yCoor++; - counter++; - } - _dataScrollPane.setPreferredSize( new Dimension( 375, 200 ) ); - } -// ------------------------------------------------------------------------------------------ - - private void addButtonPanelComponents() - { - JPanel verticalSeparatorPanel = new JPanel(); - - _buttonPanel.setLayout( new GridBagLayout() ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 80, 20 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _applyButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 2, 0, 3, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 5, 0, 2, 2, GridBagConstraints.BOTH ); - if ( ! _isEditable ) - { - _applyButton.setVisible( false ); - } - } -// ------------------------------------------------------------------------------------------ - - private RegularTimeSeries getTimeSeries() - { - return _timeSeriesHolder.getTimeSeries(); - } -// ------------------------------------------------------------------------------------------ - - private void addListeners() - { - _timeSeriesListener = new UpdateTimeSeriesListener(); - _timeSeriesHolder.addListener(_timeSeriesListener); - - _applyButton.addActionListener( new ApplyButtonListener() ); - - - - - - WindowEventManager windowEventManager = new WindowEventManager(); - _closeButton.addActionListener( windowEventManager ); - addWindowListener( windowEventManager ); - addComponentListener( new WindowResizeComponentListener() ); - } -// ------------------------------------------------------------------------------------------ - - private class ApplyButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateTimeSeries(); - refreshDataPanel(); - - //notification occurs in updateTimeSeries( - } - } - -// ------------------------------------------------------------------------------------------ - - private class ValueChangedFocusListener implements FocusListener - { - - public ValueChangedFocusListener () - { - - } - - public void focusGained(FocusEvent event) - { - - } - - public void focusLost(FocusEvent event) - { - updateTimeSeries(); - refreshDataPanel(); - - } //end focusLost - - } -// ------------------------------------------------------------------------------------------ -/* - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } -*/ -// ------------------------------------------------------------------------------------------ -/* - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } -*/ -// ------------------------------------------------------------------------------------------ - - private void updateTimeSeries() - { - int index = 0; - RegularTimeSeries timeSeries = new RegularTimeSeries(getTimeSeries().getStartTime(), - getTimeSeries().getEndTime(), - getTimeSeries().getIntervalInHours(), - getTimeSeries().getMeasuringUnit() ); - boolean success = true; - - for ( long time = _startTime; time <= _endTime ; time += _intervalInMillis ) - { - AbsTimeMeasurementAndFields absTimeMeasurementAndFields = null; - - absTimeMeasurementAndFields = - (AbsTimeMeasurementAndFields) _absTimeMeasurementAndFieldsList.get( index ); - try - { - String textFieldString = absTimeMeasurementAndFields._valueTextField.getText().trim(); - double value = Double.parseDouble( textFieldString ); - Measurement measurement = new Measurement( value , timeSeries.getMeasuringUnit() ); - timeSeries.setMeasurementByTime( measurement, time ); - - } - catch ( NumberFormatException e ) - { - DialogHelper.displayMessageDialog(null, - "Non-numerical values are not allowed!", - "Error Message" ); - success = false; - - //JOptionPane.showMessageDialog( null, "Non-numerical values are not allowed!", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - index++; - } - - if ( success ) - { - _timeSeriesHolder.setTimeSeries( timeSeries ); - - TimeSeriesEvent event = new TimeSeriesEvent("RegularTimeSeriesEditor Update", - RegularTimeSeriesEditor.this); - _timeSeriesHolder.forwardEvent(event); - } - } - - private class WindowEventManager extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - - public void windowActivated( WindowEvent e ) - { - if ( ! _wasWindowActivated ) - { - initializeScrolling(); - repaint(); - _wasWindowActivated = true; - } - } - } -// ------------------------------------------------------------------------------------------ - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = RegularTimeSeriesEditor.this.getHeight(); - int width = RegularTimeSeriesEditor.this.getWidth(); - -// System.err.println( width + "\n" + height ); - if ( width <= MIN_WIDTH ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - width = MIN_WIDTH; - } - if ( width >= MAX_WIDTH ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - width = MAX_WIDTH; - } - if ( height <= MIN_HEIGHT ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - height = MIN_HEIGHT; - } - if ( height >= MAX_HEIGHT ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - height = MAX_HEIGHT; - } - } - } -// ------------------------------------------------------------------------------------------ - - private void closeWindow() - { - //don't want to get messages when this window is gone - _timeSeriesHolder.removeListener(_timeSeriesListener); - - //make it go away - this.dispose(); - } -// ------------------------------------------------------------------------------------------ - - private String getFormattedValue( double value ) - { - return _decimalFormat.format( value ); - } -// ------------------------------------------------------------------------------------------ - - private void refreshDataPanel() - { - // String header = "RegularTimeSeriesEditor.refreshDataPanel():"; - int index = 0; - - _startTime = getTimeSeries().getStartTime(); - _endTime = getTimeSeries().getEndTime(); - - //System.out.println(header + "called." ); - - for ( long time = _startTime; time <= _endTime; time += _intervalInMillis ) - { - Measurement measurement = getTimeSeries().getMeasurementByTime( time ); - double value = measurement.getValue(); - _absTimeMeasurementAndFields = (AbsTimeMeasurementAndFields) _absTimeMeasurementAndFieldsList.get( index ); - _absTimeMeasurementAndFields.refresh( time, value ); - index++; - } - // System.out.println(header + "getViewPosition() = " + _dataScrollPane.getViewport().getViewPosition()); - } -// ------------------------------------------------------------------------------------------ - - private static RegularTimeSeries getTestTimeSeries() - { - RegularTimeSeries testTimeSeries = null; - - Date date = new Date(); - long currentTime = date.getTime(); - - currentTime = TimeHelper.truncateTimeInMillisToNearestHour( currentTime, 1 ); - long startTime = currentTime - ( 24*HOUR_IN_MILLIS ); - long endTime = startTime + ( 100*HOUR_IN_MILLIS ); - testTimeSeries = new RegularTimeSeries( startTime, endTime, 1, MeasuringUnit.inches ); - for ( int i = 0; i < testTimeSeries.getMeasurementCount(); i++ ) - { - long time = startTime + (i * HOUR_IN_MILLIS); - Measurement m = new Measurement( i, MeasuringUnit.inches ); - testTimeSeries.setMeasurementByTime( m, time ); - } - return testTimeSeries; - } -// ------------------------------------------------------------------------------------------ - - private class AbsTimeMeasurementAndFields - { - private JLabel _valueDateTimeLabel = new JLabel(); - private JFormattedTextField _valueTextField = null; - private JFormattedTextField _mappedValueTextField = null; - private JCheckBox _missingValueCheckBox = new JCheckBox(); - private boolean _isMissingValue = false; - private long _time = 0; - - public AbsTimeMeasurementAndFields( long time, double value ) - { - _time = time; - - _valueTextField = new JFormattedTextField( _decimalFormat ); - _mappedValueTextField = new JFormattedTextField( _decimalFormat ); - _valueTextField.setColumns( 8 ); - _mappedValueTextField.setColumns( 8 ); - _mappedValueTextField.setEditable( false ); - _mappedValueTextField.setFocusable( false ); - - if ( _isEditable ) - { - _valueTextField.setEditable( true ); - } - else - { - _valueTextField.setEditable( false ); - _valueTextField.setFocusable( false ); - _missingValueCheckBox.setEnabled( false ); - } - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( time ); - _valueDateTimeLabel.setText( timeString ); - _valueTextField.setText( getFormattedValue( value ) ); - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - _missingValueCheckBox.setSelected( false ); - addListeners(); - } - - public void refresh( long time, double value ) - { - _time = time; - _valueTextField.setText( getFormattedValue( value ) ); - if ( _displayMappedValue ) - { - if ( ! _isMissingValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - } - } - - private String getMappedValueString( double value ) - { - double mappedValue = 0; - String mappedValueString = null; - - if ( value != _missingValue ) - { - Measurement measurement = new Measurement( value, getTimeSeries().getMeasuringUnit() ); - Measurement mappedMeasurement = _valueMapper.getResultMeasurement( measurement ); - mappedValue = mappedMeasurement.getValue(); - - } - else - { - mappedValue = _missingValue; - } - - mappedValueString = getFormattedValue( mappedValue ); - return mappedValueString; - } - - private void addListeners() - { - _missingValueCheckBox.addActionListener( new MissingValueCheckBoxListener() ); - _valueTextField.addKeyListener( new PrecipTextFieldListener() ); - _valueTextField.addFocusListener( new FocusLostFocusListener() ); - - //_valueTextField.addFocusListener(RegularTimeSeriesEditor.this._focusListener); - } - - private class MissingValueCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _isMissingValue = _missingValueCheckBox.isSelected(); - if ( _isMissingValue ) - { - _valueTextField.setText( "" + _missingValue ); - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( "" + _missingValue ); - } - } - else - { - double value = getTimeSeries().getMeasurementValueByTime( _time, getTimeSeries().getMeasuringUnit() ); - _valueTextField.setText( getFormattedValue( value ) ); - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - } - } - } - - private class PrecipTextFieldListener implements KeyListener - { - public void keyPressed(KeyEvent arg0) - { - _missingValueCheckBox.setSelected( false ); - _isMissingValue = _missingValueCheckBox.isSelected(); - } - - public void keyReleased(KeyEvent arg0) - { - } - - public void keyTyped(KeyEvent arg0) - { - } - } - - private class FocusLostFocusListener implements FocusListener - { - private double parseDouble(String valueString) - { - - double value = 0.0; - - try - { - value = Double.parseDouble( valueString ); - } - catch (java.lang.NumberFormatException e) - { - value = 0.0; - _valueTextField.setText(getFormattedValue(value)); - } - - return value; - } - - - public void focusGained(FocusEvent arg0) - { - } - - public void focusLost(FocusEvent arg0) - { - String valueString = _valueTextField.getText().trim(); - double value = parseDouble( valueString ); - - if ( valueString.length() == 0 ) - { - _valueTextField.setText( getFormattedValue(value)); - } - - if ( ! _missingValueCheckBox.isSelected() ) - { - if ( value < _minValue ) - { - _valueTextField.setText( "" + _minValue ); - } - - if ( value > _maxValue ) - { - _valueTextField.setText( "" + _maxValue ); - } - - valueString = _valueTextField.getText().trim(); - value = parseDouble( valueString ); - } - - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - - //Allows for an immediate update of precip once values have been changed. - updateTimeSeries(); - //refreshDataPanel(); - - } - } - - } -// ------------------------------------------------------------------------------------------ - - private class UpdateTimeSeriesListener implements TimeSeriesListener - { - public Object getReceiver() - { - return RegularTimeSeriesEditor.this; - } - - public void handleTimeSeriesEvent(TimeSeriesEvent event) - { - if (event.getSource() != RegularTimeSeriesEditor.this) - { - // System.out.println("UpdateTimeSeriesListener event = " + event.toString()); - refreshDataPanel(); - } - } - - } -// ------------------------------------------------------------------------------------------ - - public static void main( String args[] ) - { - String valueLabel = null; - String titleLabel = null; - - RegularTimeSeries timeSeries = RegularTimeSeriesEditor.getTestTimeSeries(); - RegularTimeSeriesHolder holder = new RegularTimeSeriesHolder(); - holder.setTimeSeries( timeSeries ); - - valueLabel = "MAP(" + timeSeries.getMeasuringUnit() + ")"; - titleLabel = "Forecast Stage Editor"; - ValueMapper mapper = new UnitValueMapper( MeasuringUnit.feet, MeasuringUnit.mm ); - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( new Frame(), holder, valueLabel ); - descriptor.setValueMapper( mapper ); - descriptor.setMappedValueLabelString( "cfs" ); - descriptor.setTitleLabelString( titleLabel ); - descriptor.setInitialSearchTime( System.currentTimeMillis() ); - descriptor.setMissingValue( -9999.0 ); - descriptor.setMinValue( 0.0 ); - descriptor.setMaxValue( 20.0 ); - - RegularTimeSeriesEditor editor = new RegularTimeSeriesEditor( descriptor ); - editor.show(); - } -// ------------------------------------------------------------------------------------------ - -} - - diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditorDescriptor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditorDescriptor.java deleted file mode 100644 index 77f00e5ca6..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditorDescriptor.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Created on Apr 19, 2004 - * - * Filename : RegularTimeSeriesHelper.java - * Author : Gautam Sood - * Last Revision Date : Apr 19, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import java.awt.Frame; - -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.ValueMapper; - -public class RegularTimeSeriesEditorDescriptor -{ - private Frame _owner = null; - private RegularTimeSeriesHolder _regularTimeSeriesHolder = null; - private String _titleLabelString = "Timeseries Editor"; - private String _valueLabelString = null; - private String _textFieldFormatString = "0.00"; - private boolean _isEditable = true; - private boolean _isModal = true; - private ValueMapper _valueMapper = null; - private String _mappedValueLabelString = null; - private long _initialSearchTime = 0; - private double _missingValue = -9999.00; - private double _minValue = 0.0; - private double _maxValue = 20.0; - - - public RegularTimeSeriesEditorDescriptor( Frame owner, - RegularTimeSeriesHolder regularTimeSeriesHolder, - String titleLabelString, - String valueLabelString, - String textFieldFormatString, - boolean isEditable, - boolean isModal, - ValueMapper valueMapper, - String mappedValueLabelString, - long initialSearchTime, - double missingValue, - double minValue, - double maxValue ) - { - _owner = owner; - _regularTimeSeriesHolder = regularTimeSeriesHolder; - _titleLabelString = titleLabelString; - _valueLabelString = valueLabelString; - _textFieldFormatString = textFieldFormatString; - _isEditable = isEditable; - _isModal = isModal; - _valueMapper = valueMapper; - _mappedValueLabelString = mappedValueLabelString; - _missingValue = missingValue; - _minValue = minValue; - _maxValue = maxValue; - setInitialSearchTime( getRoundedTime( initialSearchTime ) ); - } - - public RegularTimeSeriesEditorDescriptor( Frame owner, - RegularTimeSeriesHolder regularTimeSeriesHolder, - String valueLabelString ) - { - _owner = owner; - _regularTimeSeriesHolder = regularTimeSeriesHolder; - _valueLabelString = valueLabelString; - } - - public long getRoundedTime( long initialSearchTime ) - { - return TimeHelper.truncateTimeInMillisToNearestHour( initialSearchTime, 1 ); - } - - public void setOwner( Frame owner ) - { - _owner = owner; - } - - public Frame getOwner() - { - return _owner; - } - - public void setRegularTimeSeriesHolder( RegularTimeSeriesHolder regularTimeSeriesHolder ) - { - _regularTimeSeriesHolder = regularTimeSeriesHolder; - } - - public RegularTimeSeriesHolder getRegularTimeSeriesHolder() - { - return _regularTimeSeriesHolder; - } - - public void setTitleLabelString( String titleLabelString ) - { - _titleLabelString = titleLabelString; - } - - public String getTitleLabelString() - { - return _titleLabelString; - } - - public void setValueLabelString( String valueLabelString ) - { - _valueLabelString = valueLabelString; - } - - public String getValueLabelString() - { - return _valueLabelString; - } - - public void setTextFieldFormatString( String textFieldFormatString ) - { - _textFieldFormatString = textFieldFormatString; - } - - public String getTextFieldFormatString() - { - return _textFieldFormatString; - } - - public void setEditable( boolean isEditable ) - { - _isEditable = isEditable; - } - - public boolean isEditable() - { - return _isEditable; - } - - public void setModal( boolean isModal ) - { - _isModal = isModal; - } - - public boolean isModal() - { - return _isModal; - } - - public void setValueMapper( ValueMapper valueMapper ) - { - _valueMapper = valueMapper; - } - - public ValueMapper getValueMapper() - { - return _valueMapper; - } - - public void setMappedValueLabelString( String mappedValueLabelString ) - { - _mappedValueLabelString = mappedValueLabelString; - } - - public String getMappedValueLabelString() - { - return _mappedValueLabelString; - } - - public void setInitialSearchTime( long initialSearchTime ) - { - _initialSearchTime = getRoundedTime( initialSearchTime ); - } - - public long getInitialSearchTime() - { - return _initialSearchTime; - } - - public void setMissingValue( double missingValue ) - { - _missingValue = missingValue; - } - - public double getMissingValue() - { - return _missingValue; - } - - public void setMinValue( double minValue ) - { - _minValue = minValue; - } - - public double getMinValue() - { - return _minValue; - } - - public void setMaxValue( double maxValue ) - { - _maxValue = maxValue; - } - - public double getMaxValue() - { - return _maxValue; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SSHPConfigDialog.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SSHPConfigDialog.java deleted file mode 100644 index 2975f0e74c..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SSHPConfigDialog.java +++ /dev/null @@ -1,716 +0,0 @@ -/* - * Created on Feb 4, 2004 - * - * Filename : SSHPConfigDialog.java - * Author : Gautam Sood - * Last Revision Date : Feb 4, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.border.Border; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableColumn; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.ForecastInterpolationMethod; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.SSHPConfig; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableHelper; - -public class SSHPConfigDialog extends JDialog -{ - private static final int MAX_BLENDING_HOURS = 1000; - - private Container _frameContentPane = getContentPane(); - - private JPanel _sshpConfigListPanel = new JPanel(); - private JPanel _sshpConfigTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 12 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private DataMgr _dataMgr = null; - private SSHPConfig _sshpConfig = null; - - private List _sshpConfigList = null; - - private static final int DEFAULT_WIDTH = 850; - private static final int DEFAULT_HEIGHT = 654; - - private static final int MAX_WIDTH = 850; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 750; - private static final int MIN_HEIGHT = 500; - - private String[] _sourcePrefStringArray = { "LOCAL", "RFC" }; - private String[] _modelPrefStringArray = { RainfallRunoffModelType.API_MKC.getName(), - RainfallRunoffModelType.SAC_SMA.getName() }; - private String[] _blendMethodStringArray = { "DIFF", "RATIO" }; - - private String _lid = null; -// JComponents - -// JLabels for the Text Panel - private JLabel _lidLabel = getJLabel( "LID" ); - private JLabel _basinIdLabel = getJLabel( "Basin ID" ); - private JLabel _postingTimeLabel = getJLabel( "Posting Time" ); - private JLabel _modelPrefLabel = getJLabel( "Model Preference" ); - - // the subpanel for the SAC-SMA settings - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - private JPanel _sacSettingsPanel = new JPanel(); - private JLabel _sacSettingsPanelLabel = getJLabel("SAC-SMA settings"); - - private JLabel _autoProcessLabel = getJLabel( "Update States Locally?" ); - private JLabel _sourcePrefLabel = getJLabel( "Data Source Preference" ); - private JLabel _useStaticEvapLabel = getJLabel( "Use ET Demand Curve?" ); - - private JLabel _blendHoursLabel = getJLabel("Blending Hours"); - private JLabel _useBlendLabel = getJLabel("Use Adjustment?"); - private JLabel _blendMethodLabel = getJLabel("Adjustment Method"); - -// JTextFields for the Data Panel - private JTextField _lidTextField = getJTextField( 17 ); - private JTextField _basinIdTextField = getJTextField( 17 ); - private JTextField _postingTimeTextField = getJTextField( 17 ); - - private JSpinner _blendHoursSpinner = null; - -// JCheckboxes for the Data Panel - private JCheckBox _autoProcessCheckBox = new JCheckBox(); - private JCheckBox _useStaticEvapCheckBox = new JCheckBox(); - private JCheckBox _useBlendCheckBox = new JCheckBox(); - -// JComboboxes for the Data Panel - private JComboBox _sourcePrefComboBox = new JComboBox( _sourcePrefStringArray ); - private JComboBox _modelPrefComboBox = new JComboBox( _modelPrefStringArray ); - private JComboBox _blendMethodComboBox = new JComboBox( _blendMethodStringArray ); - - private JScrollPane _dataScrollPane = new JScrollPane( _sshpConfigTextPanel ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for the Table - private String[] _columnNames = { "LID", "Basin ID", "Model Pref", - "Update States Locally?", "Source Pref", - "ET-Demand Curve?", "Use Adjust?", - "Adjust Method", "Blend Hours"}; - - private String[][] _sshpConfigStringArray = null; - private JTable _sshpConfigTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel =null; - - //used for sorting the Table - private String[] _dbColumnNames = { "lid", "basin_id", "model_pref", "auto_process", "source_pref", "use_static_evap" }; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - public SSHPConfigDialog( Frame owner, DataMgr dataMgr ) - { - this( owner, dataMgr, null, true ); - } - - public SSHPConfigDialog( Frame owner, DataMgr dataMgr, String lid ) - { - this( owner, dataMgr, lid, true ); - } - - public SSHPConfigDialog( Frame owner, DataMgr dataMgr, String lid, boolean isModal ) - { - super( owner, isModal ); - this.setTitle( "SSHP Config" ); - _dataMgr = dataMgr; - _lid = lid; - - - //set up the spinner control for time - int initialValue = 0; - int min = 0; - int max = MAX_BLENDING_HOURS; - int step = 6; - - SpinnerModel model = new SpinnerNumberModel(initialValue, min, max, step); - _blendHoursSpinner = new JSpinner(model); - - - initialize(); - } - - private void initialize() - { - - setupTable(); - - - addSSHPConfigListPanelComponents(); - addSSHPConfigDataPanelComponents(); - addButtons(); - addFrameComponents(); - addListeners(); - - refreshSSHPConfigTable(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - /******************** - Purpose: Sets up the JTable - *********************/ - { - int index = -1; - boolean foundLid= false; - - _tableHelper.setOrderByClause( 0 ); - - _sshpConfigList = _dataMgr.loadSSHPConfigList( _tableHelper.getOrderByClause() ); - _sshpConfigStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _sshpConfigStringArray ); - _sshpConfigTable = new JTable( _tableModel ); - _sshpConfigTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _sshpConfigTable.setPreferredScrollableViewportSize( new Dimension( 600, 100 ) ); - _listSelectionModel = _sshpConfigTable.getSelectionModel(); - _scrollPane = new JScrollPane( _sshpConfigTable ); - if ( _lid != null ) - { - for ( int i = 0; i < _sshpConfigList.size(); i++ ) - { - SSHPConfig sshpConfig = (SSHPConfig) _sshpConfigList.get( i ); - - if ( _lid.equalsIgnoreCase( sshpConfig.getLid().trim() ) ) - { - index = i; - foundLid = true; - _sshpConfig = sshpConfig; - break; - } - } - } - - adjustColumnWidths(); - - - - - if ( foundLid ) // Checks if a Lid was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _sshpConfigTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void adjustColumnWidths() - { - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sshpConfigTable.getColumnModel().getColumn( i ); - if ( ( i == 3 ) || ( i == 5 ) ) - { - column.setPreferredWidth( 125 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - } - - private void refreshSSHPConfigTable() - { - int index = 0; - - _sshpConfigList = _dataMgr.loadSSHPConfigList( _tableHelper.getOrderByClause() ); - - _sshpConfigStringArray = convertListToArray(); - if ( _sshpConfig != null ) - { - for ( int i = 0; i < _sshpConfigList.size(); i++ ) - { - SSHPConfig sshpConfig = (SSHPConfig) _sshpConfigList.get( i ); - - if ( _sshpConfig.equals( sshpConfig ) ) - { - index = i; - break; - } - } - } - - _tableModel.updateData( _sshpConfigStringArray ); - _tableModel.fireTableChanged( null ); - - adjustColumnWidths(); - - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _sshpConfigTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _sshpConfigList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - SSHPConfig sshpConfig = (SSHPConfig) _sshpConfigList.get( i ); - - dataArray[ i ][ 0 ] = sshpConfig.getLid(); - dataArray[ i ][ 1 ] = sshpConfig.getBasinId(); - dataArray[ i ][ 2 ] = sshpConfig.getModelPref(); - dataArray[ i ][ 3 ] = "" + sshpConfig.isAutoProcess(); - dataArray[ i ][ 4 ] = sshpConfig.getSourcePref(); - dataArray[ i ][ 5 ] = "" + sshpConfig.useStaticEvap(); - dataArray[ i ][ 6 ] = "" + sshpConfig.useBlend(); - dataArray[ i ][ 7 ] = sshpConfig.getBlendMethod().getName(); - dataArray[ i ][ 8 ] = "" + sshpConfig.getBlendHours(); - } - return dataArray; - } - - - private void addSSHPConfigListPanelComponents() - /******************** - Purpose: Add's Components to the JList Scroll Pane Panel - *********************/ - { - _sshpConfigListPanel.setLayout( new GridBagLayout() ); - - ComponentHelper.addPanelComponent( _sshpConfigListPanel, _scrollPane, 0, 0, 2, 12, 1, 1, GridBagConstraints.BOTH ); - } - - private void addSSHPConfigDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the _sshpConfigTextPanel - *********************/ - { - _sshpConfigTextPanel.setLayout( new GridBagLayout() ); - -// XCol, YRow, ColCount, RowCount - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _lidLabel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _lidTextField, 1, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _basinIdLabel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _basinIdTextField, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _modelPrefLabel, 0, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _modelPrefComboBox, 1, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _useBlendLabel, 0, 3, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _useBlendCheckBox, 1, 3, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendMethodLabel, 0, 4, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendMethodComboBox, 1, 4, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendHoursLabel, 0, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendHoursSpinner, 1, 5, 1, 1, GridBagConstraints.BOTH ); - - - - // inside the SAC Settings sub panel - _sacSettingsPanel.setLayout(new GridBagLayout()); - _sacSettingsPanel.setBorder(_panelBorder); - - ComponentHelper.addPanelComponent( _sacSettingsPanel, _autoProcessLabel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _autoProcessCheckBox, 1, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _sourcePrefLabel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _sourcePrefComboBox, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _useStaticEvapLabel, 0, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _useStaticEvapCheckBox, 1, 2, 1, 1, GridBagConstraints.BOTH ); - - - - - - //add the subpanel to the _sshpConfigTextPanel - JPanel separatorPanel1 = new JPanel(); - JPanel separatorPanel2 = new JPanel(); - - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, separatorPanel1, 0, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _sacSettingsPanelLabel,0, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _sacSettingsPanel, 0, 8, 4, 5, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, separatorPanel2, 0, 14, 1, 1, GridBagConstraints.BOTH ); - - - - //continue with more of the _sshpConfigTextPanel - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _postingTimeLabel, 0, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _postingTimeTextField, 1, 15, 1, 1, GridBagConstraints.BOTH ); - - _postingTimeTextField.setEditable( false ); - _postingTimeTextField.setToolTipText("Indicates the last time that this record was saved"); - } - - - private void addButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _buttonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 2, 22, 2, GridBagConstraints.BOTH ); - } - - private void addFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - _dataScrollPane.setPreferredSize( new Dimension( 150, 300 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _sshpConfigListPanel, 0, 0, 10, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 17, 20, 15, 0, .5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - - if ( _sshpConfig != null ) - { - _lidTextField.setText( _sshpConfig.getLid() ); - _basinIdTextField.setText( _sshpConfig.getBasinId() ); - _postingTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sshpConfig.getPostingTime() ) ); - _modelPrefComboBox.setSelectedItem( _sshpConfig.getModelPref().trim() ); - _autoProcessCheckBox.setSelected( _sshpConfig.isAutoProcess() ); - _sourcePrefComboBox.setSelectedItem( _sshpConfig.getSourcePref().trim() ); - _useStaticEvapCheckBox.setSelected( _sshpConfig.useStaticEvap() ); - _useBlendCheckBox.setSelected(_sshpConfig.useBlend()); - _blendMethodComboBox.setSelectedItem( _sshpConfig.getBlendMethod()); - _blendHoursSpinner.setValue(new Integer( _sshpConfig.getBlendHours())); - } - else - { - _lidTextField.setText( "" ); - _basinIdTextField.setText( "" ); - _postingTimeTextField.setText( "Not Posted Yet" ); - _modelPrefComboBox.setSelectedIndex( 0 ); - _autoProcessCheckBox.setSelected( false ); - _sourcePrefComboBox.setSelectedIndex( 0 ); - _useStaticEvapCheckBox.setSelected( false ); - _useBlendCheckBox.setSelected(false); - _blendMethodComboBox.setSelectedIndex(0); - _blendHoursSpinner.setValue(new Integer(999)); - } - } - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _sshpConfigTable.getTableHeader().addMouseListener( new TableSortingListener() ); - - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _sshpConfigTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _sshpConfigList.isEmpty() ) ) - { - _sshpConfig = (SSHPConfig) _sshpConfigList.get( index ); - } - else - { - _sshpConfig = null; - } - loadTextFields(); - } - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _sshpConfigTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshSSHPConfigTable(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - SSHPConfig sshpConfig = new SSHPConfig(); - - if ( - ( ! isEmptyString( _lidTextField.getText() ) ) && - ( ! isEmptyString( _basinIdTextField.getText() ) ) - ) // Checks to make sure the basinID and source - // are not empty strings - { - try - { - sshpConfig.setLid( _lidTextField.getText().trim() ); - sshpConfig.setBasinId( _basinIdTextField.getText().trim() ); - sshpConfig.setModelPref( (String) _modelPrefComboBox.getSelectedItem() ); - sshpConfig.setAutoProcess( _autoProcessCheckBox.isSelected() ); - sshpConfig.setSourcePref( (String) _sourcePrefComboBox.getSelectedItem() ); - sshpConfig.setUseStaticEvap( _useStaticEvapCheckBox.isSelected() ); - sshpConfig.setUseBlend(_useBlendCheckBox.isSelected()); - - - //get the method name and translate that to an actual ForecastBlendMethod object - String methodName = (String) _blendMethodComboBox.getSelectedItem(); - ForecastInterpolationMethod method = ForecastInterpolationMethod.getMethodByName(methodName); - sshpConfig.setBlendMethod ( method ); - - // get and parse the string from the blend hours text field - Integer hoursInteger = (Integer) _blendHoursSpinner.getValue(); - int hours = 0; - try - { - hours = hoursInteger.intValue(); - } - catch (NumberFormatException formatException) - { - hours = 999; - } - sshpConfig.setBlendHours(hours); - - - // save the configuration to the database and reload the JTable - _dataMgr.saveSSHPConfig( sshpConfig ); - _sshpConfig = sshpConfig; - refreshSSHPConfigTable(); - } - catch ( NumberFormatException exception ) - { - DialogHelper.displayMessageDialog(null, - "There is a parsing error in your input", - "Error Message"); - //JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - else - { - DialogHelper.displayMessageDialog(null, - "Empty Strings are not allowed", - "Error Message"); - - //JOptionPane.showMessageDialog( null, "Empty Strings are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - if ( _sshpConfig != null ) - { - // choice = JOptionPane.showConfirmDialog( null, "Are you sre you want to delete this Config?", - // "Delete SSHP Config", JOptionPane.YES_NO_OPTION, - // JOptionPane.WARNING_MESSAGE ); - - confirm = DialogHelper.displayConfirmDialog(null, "Are you sre you want to delete this Config?", - "Delete SSHP Config"); - - if ( confirm ) - /* User selected YES */ - { - _dataMgr.deleteSSHPConfig( _sshpConfig ); - _sshpConfig = null; - refreshSSHPConfigTable(); - } - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _sshpConfig = null; - loadTextFields(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = SSHPConfigDialog.this.getHeight(); - int width = SSHPConfigDialog.this.getWidth(); - -// System.err.println( "Width: " + width + " Height: " + height ); - if ( width < MIN_WIDTH ) - { - SSHPConfigDialog.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - SSHPConfigDialog.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - SSHPConfigDialog.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - SSHPConfigDialog.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private JLabel getJLabel( String label ) - /******************** - Purpose: Returns a JLabel set to the string passed in - *********************/ - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - /******************** - Purpose: Returns a JTextField using the size passed in - *********************/ - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - public static void main( String[] args ) - { - SSHPConfigDialog dialog = new SSHPConfigDialog( new Frame(), new DataMgr(), "BLUO2" ); - dialog.show(); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SacParamsEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SacParamsEditor.java deleted file mode 100644 index 2b674b040a..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SacParamsEditor.java +++ /dev/null @@ -1,807 +0,0 @@ -/* - * Created on Oct 21, 2003 - * - * Filename : SacParamsEditor.java - * Author : Gautam Sood - * Last Revision Date : Oct 21, 2003 - * Purpose: Display GUI for the SacSMA Parameters. - */ - -package ohd.hseb.sshp.window; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableColumn; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeDialog; -import ohd.hseb.util.gui.DateTimeEvent; -import ohd.hseb.util.gui.DateTimeEventListener; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableHelper; - -public class SacParamsEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _sacParamsListPanel = new JPanel(); - private JPanel _sacParamsTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private List _sacParamsList = null; - - private DataMgr _dataMgr = null; - private SacSmaParameters _sacSmaParameters = null; - - private String _basinId = null; - - private static final int DEFAULT_WIDTH = 340; - private static final int DEFAULT_HEIGHT = 654; - - private static final int MAX_WIDTH = 500; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 340; - private static final int MIN_HEIGHT = 500; - - //used for JFormattedTextFields - private static final String _threeDecimalFormatString = "0.000"; - private DecimalFormat _decimalFormat = new DecimalFormat( _threeDecimalFormatString ); - - private JLabel _basinIDLabel = getJLabel( "Basin ID" ); - private JLabel _sourceLabel = getJLabel( "Source" ); - private JLabel _validTimeLabel = getJLabel( "Valid Time" ); - private JLabel _uztwmLabel = getJLabel( "UZTWM" ); - private JLabel _uzfwmLabel = getJLabel( "UZFWM" ); - private JLabel _uzkLabel = getJLabel( "UZK" ); - private JLabel _pctimLabel = getJLabel( "PCTIM" ); - private JLabel _adimpLabel = getJLabel( "ADIMP" ); - private JLabel _rivaLabel = getJLabel( "RIVA" ); - private JLabel _zpercLabel = getJLabel( "ZPERC" ); - private JLabel _rexpLabel = getJLabel( "REXP" ); - private JLabel _lztwmLabel = getJLabel( "LZTWM" ); - private JLabel _lzfsmLabel = getJLabel( "LZFSM" ); - private JLabel _lzfpmLabel = getJLabel( "LZFPM" ); - private JLabel _lzskLabel = getJLabel( "LZSK" ); - private JLabel _lzpkLabel = getJLabel( "LZPK" ); - private JLabel _pfreeLabel = getJLabel( "PFREE" ); - private JLabel _rservLabel = getJLabel( "RSERV" ); - private JLabel _sideLabel = getJLabel( "SIDE" ); - private JLabel _peAdjustLabel = getJLabel( "PEADJ" ); - private JLabel _pxAdjustLabel = getJLabel( "PXADJ" ); - private JLabel _efcLabel = getJLabel( "EFC" ); - - private JTextField _basinIDTextField = getJTextField( 17 ); - private JTextField _sourceTextField = getJTextField( 17 ); - private JTextField _validTimeTextField = getJTextField( 17 ); - private JFormattedTextField _uztwmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _uzfwmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _uzkTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _pctimTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _adimpTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _rivaTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _zpercTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _rexpTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lztwmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfsmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfpmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzskTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzpkTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _pfreeTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _rservTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _sideTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _peAdjustTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _pxAdjustTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _efcTextField = getJFormattedTextField( _threeDecimalFormatString ); - - private JScrollPane _dataScrollPane = new JScrollPane( _sacParamsTextPanel ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for custom notification - private List _applyListenerList = new ArrayList(); - - //used for the Table - private String[] _columnNames = { "Basin ID", "Source", "Valid Time" }; - private String[][] _sacParamsStringArray = null; - private JTable _sacSmaParamsTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel = null; - - //used for sorting the Table - private String[] _dbColumnNames = { "basin_id", "source", "validtime" }; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - public SacParamsEditor( Frame owner, DataMgr dataMgr ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, null, false ); - } - - - public SacParamsEditor( Frame owner, DataMgr dataMgr, String basinId ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, basinId, false ); - } - - public SacParamsEditor( Frame owner, DataMgr dataMgr, String basinId, boolean isModal ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, isModal ); - this.setTitle( "SacSma Parameters" ); - _basinId = basinId; - _dataMgr = dataMgr; - initialize(); - } - - private void initialize() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - setupTable(); - - AddSacParamsListPanelComponents(); - AddSacParamsDataPanelComponents(); - AddButtons(); - AddFrameComponents(); - AddListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - { - int index = -1; - boolean foundBasinId= false; - - _tableHelper.setOrderByClause( 0 ); - - _sacParamsList = _dataMgr.loadSacSmaParamsList( _tableHelper.getOrderByClause() ); - _sacParamsStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _sacParamsStringArray ); - _sacSmaParamsTable = new JTable( _tableModel ); - _sacSmaParamsTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _sacSmaParamsTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - _listSelectionModel = _sacSmaParamsTable.getSelectionModel(); - _scrollPane = new JScrollPane( _sacSmaParamsTable ); - if ( _basinId != null ) - { - for ( int i = 0; i < _sacParamsList.size(); i++ ) - { - SacSmaParameters sacSmaParams = (SacSmaParameters) _sacParamsList.get( i ); - - if ( _basinId.equalsIgnoreCase( sacSmaParams.getBasinId().trim() ) ) - { - index = i; - foundBasinId = true; - _sacSmaParameters = sacSmaParams; - break; - } - } - } - - if ( ! foundBasinId ) // If no basin ID found in the Params list, selects the first one by default. - { - if (_sacParamsList.size() > 0) - { - _sacSmaParameters = (SacSmaParameters) _sacParamsList.get( 0 ); - } - } - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaParamsTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - if ( foundBasinId ) // Checks if a Basin Id was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _sacSmaParamsTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void refreshSacSmaParamsTable() - { - int index = 0; - - _sacParamsList = _dataMgr.loadSacSmaParamsList( _tableHelper.getOrderByClause() ); - - _sacParamsStringArray = convertListToArray(); - if ( _sacSmaParameters != null ) - { - for ( int i = 0; i < _sacParamsList.size(); i++ ) - { - SacSmaParameters sacSmaParams = (SacSmaParameters) _sacParamsList.get( i ); - - if ( _sacSmaParameters.equals( sacSmaParams ) ) - { - index = i; - break; - } - } - } - _tableModel.updateData( _sacParamsStringArray ); - _tableModel.fireTableChanged( null ); - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaParamsTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _sacSmaParamsTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _sacParamsList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - SacSmaParameters sacParams = (SacSmaParameters) _sacParamsList.get( i ); - - dataArray[ i ][ 0 ] = sacParams.getBasinId(); - dataArray[ i ][ 1 ] = sacParams.getSource(); - dataArray[ i ][ 2 ] = "" + DbTimeHelper.getDateTimeStringFromLongTime( sacParams.getValidTime() ); - } - return dataArray; - } - - private void AddFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - _dataScrollPane.setPreferredSize( new Dimension( 150, 300 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _sacParamsListPanel, 0, 0, 10, 15, 1, .5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 17, 20, 15, 0, .8, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private void AddSacParamsListPanelComponents() - /******************** - Purpose: Add's Components to the JList Scroll Pane Panel - *********************/ - { - _sacParamsListPanel.setLayout( new GridBagLayout() ); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _sacParamsListPanel, _scrollPane, 0, 0, 5, 25, 1, 1, GridBagConstraints.BOTH ); - - } - - - private void AddSacParamsDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the sacParamsTextPanel - *********************/ - { - _sacParamsTextPanel.setLayout( new GridBagLayout() ); - - java.awt.Color backgroundColor = _validTimeTextField.getBackground(); - _validTimeTextField.setEditable( false ); - _validTimeTextField.setBackground(backgroundColor); - - - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _basinIDLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _basinIDTextField, 10, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sourceLabel, 0, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sourceTextField, 10, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _validTimeLabel, 0, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _validTimeTextField, 10, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uztwmLabel, 0, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uztwmTextField, 10, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzfwmLabel, 0, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzfwmTextField, 10, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzkLabel, 0, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzkTextField, 10, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pctimLabel, 0, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pctimTextField, 10, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _adimpLabel, 0, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _adimpTextField, 10, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rivaLabel, 0, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rivaTextField, 10, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _zpercLabel, 0, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _zpercTextField, 10, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rexpLabel, 0, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rexpTextField, 10, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lztwmLabel, 0, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lztwmTextField, 10, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfsmLabel, 0, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfsmTextField, 10, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfpmLabel, 0, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfpmTextField, 10, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzskLabel, 0, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzskTextField, 10, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzpkLabel, 0, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzpkTextField, 10, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pfreeLabel, 0, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pfreeTextField, 10, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rservLabel, 0, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rservTextField, 10, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sideLabel, 0, 180, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sideTextField, 10, 180, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _peAdjustLabel, 0, 190, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _peAdjustTextField, 10, 190, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pxAdjustLabel, 0, 200, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pxAdjustTextField, 10, 200, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _efcLabel, 0, 210, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _efcTextField, 10, 210, 5, 1, GridBagConstraints.BOTH ); - } - - private void AddButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _buttonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 2, 22, 2, GridBagConstraints.BOTH ); - } - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _sacSmaParameters != null ) - { - _basinIDTextField.setText( _sacSmaParameters.getBasinId() ); - _sourceTextField.setText( _sacSmaParameters.getSource() ); - _validTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sacSmaParameters.getValidTime() ) ); - - _uztwmTextField.setText( getFormattedValue( _sacSmaParameters.getUztwm() ) ); - _uzfwmTextField.setText( getFormattedValue( _sacSmaParameters.getUzfwm() ) ); - _uzkTextField.setText( getFormattedValue( _sacSmaParameters.getUzk() ) ); - _pctimTextField.setText( getFormattedValue( _sacSmaParameters.getPctim() ) ); - _adimpTextField.setText( getFormattedValue( _sacSmaParameters.getAdimp() ) ); - _rivaTextField.setText( getFormattedValue( _sacSmaParameters.getRiva() ) ); - _zpercTextField.setText( getFormattedValue( _sacSmaParameters.getZperc() ) ); - _rexpTextField.setText( getFormattedValue( _sacSmaParameters.getRexp() ) ); - _lztwmTextField.setText( getFormattedValue( _sacSmaParameters.getLztwm() ) ); - _lzfsmTextField.setText( getFormattedValue( _sacSmaParameters.getLzfsm() ) ); - _lzfpmTextField.setText( getFormattedValue( _sacSmaParameters.getLzfpm() ) ); - _lzskTextField.setText( getFormattedValue( _sacSmaParameters.getLzsk() ) ); - _lzpkTextField.setText( getFormattedValue( _sacSmaParameters.getLzpk() ) ); - _pfreeTextField.setText( getFormattedValue( _sacSmaParameters.getPfree() ) ); - _rservTextField.setText( getFormattedValue( _sacSmaParameters.getRserv() ) ); - _sideTextField.setText( getFormattedValue( _sacSmaParameters.getSide() ) ); - _peAdjustTextField.setText( getFormattedValue( _sacSmaParameters.getPeadj() ) ); - _pxAdjustTextField.setText( getFormattedValue( _sacSmaParameters.getPxadj() ) ); - _efcTextField.setText( getFormattedValue( _sacSmaParameters.getEfc() ) ); - } - else - { - _basinIDTextField.setText( "" ); - _sourceTextField.setText( "" ); - _validTimeTextField.setText( "yyyy-mm-dd hh:mm:ss" ); - _uztwmTextField.setText( "" ); - _uzfwmTextField.setText( "" ); - _uzkTextField.setText( "" ); - _pctimTextField.setText( "" ); - _adimpTextField.setText( "" ); - _rivaTextField.setText( "" ); - _zpercTextField.setText( "" ); - _rexpTextField.setText( "" ); - _lztwmTextField.setText( "" ); - _lzfsmTextField.setText( "" ); - _lzfpmTextField.setText( "" ); - _lzskTextField.setText( "" ); - _lzpkTextField.setText( "" ); - _pfreeTextField.setText( "" ); - _rservTextField.setText( "" ); - _sideTextField.setText( "" ); - _peAdjustTextField.setText( "" ); - _pxAdjustTextField.setText( "" ); - _efcTextField.setText( "" ); - } - } - - private void AddListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _validTimeTextField.addMouseListener( new TimeTextFieldListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _sacSmaParamsTable.getTableHeader().addMouseListener( new TableSortingListener() ); - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _sacSmaParamsTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshSacSmaParamsTable(); - } - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _sacSmaParamsTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _sacParamsList.isEmpty() ) ) - { - _sacSmaParameters = (SacSmaParameters) _sacParamsList.get( index ); - } - else - { - _sacSmaParameters = null; - } - loadTextFields(); - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _sacSmaParameters = null; - loadTextFields(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - SacSmaParameters params = new SacSmaParameters(); - - if ( - ( ! isEmptyString( _basinIDTextField.getText() ) ) && - ( ! isEmptyString( _sourceTextField.getText() ) ) && - ( ! _validTimeTextField.getText().trim().equals( "yyyy-mm-dd hh:mm:ss" ) ) - ) // Checks to make sure the basinID and source - // are not empty strings - { - try - { - params.setBasinId( _basinIDTextField.getText().trim() ); - params.setSource( _sourceTextField.getText().trim() ); - params.setValidTime( DbTimeHelper.getLongTimeFromDateTimeString( _validTimeTextField.getText() ) ); - params.setPostingTime( getCurrentTime() ); - params.setUztwm( Double.parseDouble( _uztwmTextField.getText() ) ); - params.setUzfwm( Double.parseDouble( _uzfwmTextField.getText() ) ); - params.setUzk( Double.parseDouble( _uzkTextField.getText() ) ); - params.setPctim( Double.parseDouble( _pctimTextField.getText() ) ); - params.setAdimp( Double.parseDouble( _adimpTextField.getText() ) ); - params.setRiva( Double.parseDouble( _rivaTextField.getText() ) ); - params.setZperc( Double.parseDouble( _zpercTextField.getText() ) ); - params.setRexp( Double.parseDouble( _rexpTextField.getText() ) ); - params.setLztwm( Double.parseDouble( _lztwmTextField.getText() ) ); - params.setLzfsm( Double.parseDouble( _lzfsmTextField.getText() ) ); - params.setLzfpm( Double.parseDouble( _lzfpmTextField.getText() ) ); - params.setLzsk( Double.parseDouble( _lzskTextField.getText() ) ); - params.setLzpk( Double.parseDouble( _lzpkTextField.getText() ) ); - params.setPfree( Double.parseDouble( _pfreeTextField.getText() ) ); - params.setRserv( Double.parseDouble( _rservTextField.getText() ) ); - params.setSide( Double.parseDouble( _sideTextField.getText() ) ); - params.setPeadj( Double.parseDouble( _peAdjustTextField.getText() ) ); - params.setPxadj( Double.parseDouble( _pxAdjustTextField.getText() ) ); - params.setEfc( Double.parseDouble( _efcTextField.getText() ) ); - - _dataMgr.saveParams( params ); - _sacSmaParameters = params; - refreshSacSmaParamsTable(); - - notifyAllApplyActionListeners(); // notifies all the listeners - } - catch ( NumberFormatException exception ) - { - DialogHelper.displayErrorDialog(null, - "There is a parsing error in your input", - "Error Message"); - - /* - JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - "Error Message", JOptionPane.ERROR_MESSAGE ); - */ - } - } - else - { - DialogHelper.displayErrorDialog(null, "Empty Strings are not allowed", - "Error Message"); - //JOptionPane.showMessageDialog( null, "Empty Strings are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - - private long getCurrentTime() - { - // Get's the current system time truncated to the nearest second. - long time = System.currentTimeMillis(); - - time /= 1000; - time *= 1000; - return time; - } - - } - - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } - - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - if ( _sacSmaParameters != null ) - { - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete this Parameter?", - "Delete Parameter"); - - if ( confirm ) - /* User selected YES */ - { - _dataMgr.deleteParams( _sacSmaParameters ); - _sacSmaParameters = null; - refreshSacSmaParamsTable(); - } - } - } - } - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if ( ! textField.getText().equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - DateTimeDialog dateTimeGUI = new DateTimeDialog( SacParamsEditor.this, dateTime, "Valid Time" ); - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = SacParamsEditor.this.getHeight(); - int width = SacParamsEditor.this.getWidth(); -// System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - SacParamsEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - SacParamsEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - SacParamsEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - SacParamsEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - public static void main(String[] args) - { - SacParamsEditor sacParamsGUI = new SacParamsEditor( new Frame(), new DataMgr(), "BLUZ2" ); - sacParamsGUI.show(); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SacStateEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SacStateEditor.java deleted file mode 100644 index b3f23c9609..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SacStateEditor.java +++ /dev/null @@ -1,751 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * Filename : SacStateEditor.java - * Author : Gautam Sood - * Last Revision Date : Oct 23, 2003 - * - * - */ -package ohd.hseb.sshp.window; - - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFormattedTextField; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableColumn; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeEvent; -import ohd.hseb.util.gui.DateTimeEventListener; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableHelper; - -public class SacStateEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _sacStateListPanel = new JPanel(); - private JPanel _sacStateTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private List _sacStateList = null; - - private DataMgr _dataMgr = null; - private SacSmaState _sacSmaState = null; - - private static final int DEFAULT_WIDTH = 340; - private static final int DEFAULT_HEIGHT = 470; - - private static final int MAX_WIDTH = 500; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 340; - private static final int MIN_HEIGHT = 450; - - - //JFrame owner - private JFrame _owner = null; - - //used for JFormattedTextFields - private static final String _threeDecimalFormatString = "0.000"; - private DecimalFormat _decimalFormat = new DecimalFormat( _threeDecimalFormatString ); - - private String _basinId = null; - - private JLabel _basinIDLabel = getJLabel( "Basin ID" ); - private JLabel _sourceLabel = getJLabel( "Source" ); - private JLabel _validTimeLabel = getJLabel( "Valid Time" ); - private JLabel _basisTimeLabel = getJLabel( "Basis Time" ); - private JLabel _uztwcLabel = getJLabel( "UZTWC" ); - private JLabel _uzfwcLabel = getJLabel( "UZFWC" ); - private JLabel _lztwcLabel = getJLabel( "LZTWC" ); - private JLabel _lzfscLabel = getJLabel( "LZFSC" ); - private JLabel _lzfpcLabel = getJLabel( "LZFPC" ); - private JLabel _adimcLabel = getJLabel( "ADIMC" ); - - private JTextField _basinIDTextField = getJTextField( 17 ); - private JTextField _sourceTextField = getJTextField( 17 ); - -// private JTextField _validTimeTextField = getJTextField( 17 ); -// private JTextField _basisTimeTextField = getJTextField( 17 ); - - private DateTimeTextField _validTimeTextField = null; - private DateTimeTextField _basisTimeTextField = null; - - private JFormattedTextField _uztwcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _uzfwcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lztwcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfscTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfpcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _adimcTextField = getJFormattedTextField( _threeDecimalFormatString ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for custom notification - private List _applyListenerList = new ArrayList(); - - //used for the Table - private String[] _columnNames = { "Basin ID", "Source", "Valid Time" }; - private String[][] _sacStateStringArray = null; - private JTable _sacSmaStateTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel = null; - - //used for sorting purposes - private String[] _dbColumnNames = { "basin_id", "source", "validtime" }; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - public SacStateEditor( JFrame owner, DataMgr dataMgr ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, null, false ); - } - - public SacStateEditor( JFrame owner, DataMgr dataMgr, String basinId ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, basinId, false ); - } - - public SacStateEditor( JFrame owner, DataMgr dataMgr, String basinId, boolean isModal ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, isModal ); - this.setTitle( "SacSma State" ); - - _owner = owner; - _basinId = basinId; - _dataMgr = dataMgr; - initialize(); - } - - private void initialize() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - - long latestHourTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(),1); - - _validTimeTextField = new DateTimeTextField(latestHourTime, _owner, "Valid Time", 17); - _basisTimeTextField = new DateTimeTextField(latestHourTime, _owner, "Basis Time", 17); - - - setupTable(); - - addSacStateListPanelComponents(); - addSacStateDataPanelComponents(); - addButtons(); - addFrameComponents(); - addListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - { - int index = -1; - boolean foundBasinId= false; - - _tableHelper.setOrderByClause( 0 ); - _sacStateList = _dataMgr.loadSacSmaStateList( _tableHelper.getOrderByClause() ); - _sacStateStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _sacStateStringArray ); - _sacSmaStateTable = new JTable( _tableModel ); - _sacSmaStateTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _sacSmaStateTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - _listSelectionModel = _sacSmaStateTable.getSelectionModel(); - _scrollPane = new JScrollPane( _sacSmaStateTable ); - if ( _basinId != null ) - { - for ( int i = 0; i < _sacStateList.size(); i++ ) - { - SacSmaState sacSmaState = (SacSmaState) _sacStateList.get( i ); - - if ( _basinId.equalsIgnoreCase( sacSmaState.getBasinId().trim() ) ) - { - index = i; - foundBasinId = true; - _sacSmaState = sacSmaState; - break; - } - } - } - - if ( ! foundBasinId ) // If no basin ID found in the Params list, selects the first one by default. - { - if (_sacStateList.size() > 0) - { - _sacSmaState = (SacSmaState) _sacStateList.get( 0 ); - } - } - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaStateTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - if ( foundBasinId ) // Checks if a Basin Id was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _sacSmaStateTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - private void refreshSacSmaStateTable() - { - int index = 0; - - _sacStateList = _dataMgr.loadSacSmaStateList( _tableHelper.getOrderByClause() ); - - _sacStateStringArray = convertListToArray(); - - if ( _sacSmaState != null ) - { - for ( int i = 0; i < _sacStateList.size(); i++ ) - { - SacSmaState sacSmaState = (SacSmaState) _sacStateList.get( i ); - - if ( _sacSmaState.equals( sacSmaState ) ) - { - index = i; - break; - } - } - } - - _tableModel.updateData( _sacStateStringArray ); - _tableModel.fireTableChanged( null ); - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaStateTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _sacSmaStateTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void addFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _sacStateListPanel, 0, 0, 10, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _sacStateTextPanel, 0, 17, 20, 15, 0, .4, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _sacStateList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - SacSmaState sacState = (SacSmaState) _sacStateList.get( i ); - - dataArray[ i ][ 0 ] = sacState.getBasinId(); - dataArray[ i ][ 1 ] = sacState.getSource(); - dataArray[ i ][ 2 ] = "" + DbTimeHelper.getDateTimeStringFromLongTime( sacState.getValidTime() ); - } - return dataArray; - } - - - private void addSacStateListPanelComponents() - /******************** - Purpose: Add's Components to the JTable Scroll Pane Panel - *********************/ - { - _sacStateListPanel.setLayout( new GridBagLayout() ); - - ComponentHelper.addPanelComponent( _sacStateListPanel, _scrollPane, 0, 0, 5, 25, 1, 1, GridBagConstraints.BOTH ); - - } - - - private void addSacStateDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the sacStateTextPanel - *********************/ - { - _sacStateTextPanel.setLayout( new GridBagLayout() ); - - _validTimeTextField.setEditable( false ); - _basisTimeTextField.setEditable( false ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basinIDLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basinIDTextField, 10, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _sourceLabel, 0, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _sourceTextField, 10, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _validTimeLabel, 0, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _validTimeTextField, 10, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basisTimeLabel, 0, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basisTimeTextField, 10, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uztwcLabel, 0, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uztwcTextField, 10, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uzfwcLabel, 0, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uzfwcTextField, 10, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lztwcLabel, 0, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lztwcTextField, 10, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfscLabel, 0, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfscTextField, 10, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfpcLabel, 0, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfpcTextField, 10, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _adimcLabel, 0, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _adimcTextField, 10, 90, 5, 1, GridBagConstraints.BOTH ); - } - - private void addButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - _buttonPanel.setLayout( new GridBagLayout() ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 20 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 2, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 3, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 3, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 3, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 4, 22, 2, GridBagConstraints.BOTH ); - } - - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _sacSmaState != null ) - { - _basinIDTextField.setText( _sacSmaState.getBasinId() ); - _sourceTextField.setText( _sacSmaState.getSource() ); - _validTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sacSmaState.getValidTime() ) ); - _basisTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sacSmaState.getBasisTime() ) ); - _uztwcTextField.setText( getFormattedValue( _sacSmaState.getUztwc() ) ); - _uzfwcTextField.setText( getFormattedValue( _sacSmaState.getUzfwc() ) ); - _lztwcTextField.setText( getFormattedValue( _sacSmaState.getLztwc() ) ); - _lzfscTextField.setText( getFormattedValue( _sacSmaState.getLzfsc() ) ); - _lzfpcTextField.setText( getFormattedValue( _sacSmaState.getLzfpc() ) ); - _adimcTextField.setText( getFormattedValue( _sacSmaState.getAdimc() ) ); - } - else - { - _basinIDTextField.setText( "" ); - _sourceTextField.setText( "" ); - _validTimeTextField.setText( "yyyy-mm-dd hh:mm:ss" ); - _basisTimeTextField.setText( "yyyy-mm-dd hh:mm:ss" ); - _uztwcTextField.setText( "" ); - _uzfwcTextField.setText( "" ); - _lztwcTextField.setText( "" ); - _lzfscTextField.setText( "" ); - _lzfpcTextField.setText( "" ); - _adimcTextField.setText( "" ); - } - } - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - // _basisTimeTextField.addMouseListener( new TimeTextFieldListener() ); - // _validTimeTextField.addMouseListener( new TimeTextFieldListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _sacSmaStateTable.getTableHeader().addMouseListener( new TableSortingListener() ); - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _sacSmaStateTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _sacStateList.isEmpty() ) ) - { - _sacSmaState = (SacSmaState) _sacStateList.get( index ); - } - else - { - _sacSmaState = null; - } - loadTextFields(); - } - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _sacSmaStateTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshSacSmaStateTable(); - } - } - - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - SacSmaState state = new SacSmaState(); - - if ( - ( ! isEmptyString( _basinIDTextField.getText() ) ) && - ( ! isEmptyString( _sourceTextField.getText() ) ) && - ( ! _validTimeTextField.getText().trim().equals( "yyyy-mm-dd hh:mm:ss" ) ) && - ( ! _basisTimeTextField.getText().trim().equals( "yyyy-mm-dd hh:mm:ss" ) ) - ) - { - try - { - state.setBasinId( _basinIDTextField.getText().trim() ); - state.setSource( _sourceTextField.getText().trim() ); - state.setValidTime( DbTimeHelper.getLongTimeFromDateTimeString( - _validTimeTextField.getText().trim() ) ); - state.setBasisTime( DbTimeHelper.getLongTimeFromDateTimeString( - _basisTimeTextField.getText().trim() ) ); - state.setPostingTime( getCurrentTime() ); - state.setUztwc( Double.parseDouble( _uztwcTextField.getText() ) ); - state.setUzfwc( Double.parseDouble( _uzfwcTextField.getText() ) ); - state.setLztwc( Double.parseDouble( _lztwcTextField.getText() ) ); - state.setLzfsc( Double.parseDouble( _lzfscTextField.getText() ) ); - state.setLzfpc( Double.parseDouble( _lzfpcTextField.getText() ) ); - state.setAdimc( Double.parseDouble( _adimcTextField.getText() ) ); - _dataMgr.saveState( state ); - _sacSmaState = state; - refreshSacSmaStateTable(); - notifyAllApplyActionListeners(); // notifies all the listeners - - } - catch ( NumberFormatException exception ) - { - DialogHelper.displayMessageDialog(null, - "There is a parsing error in your input", - "Error Message"); - //JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - else - { - DialogHelper.displayMessageDialog(null, - "Empty Strings/Dates are not allowed", - "Error Message"); - - //JOptionPane.showMessageDialog( null, "Empty Strings/Dates are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - - private long getCurrentTime() - { - // Get's the current system time truncated to the nearest second. - long time = System.currentTimeMillis(); - - time /= 1000; - time *= 1000; - return time; - } - } - - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } - - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - if ( _sacSmaState != null ) - { - //choice = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete this State?", - // "Delete State", JOptionPane.YES_NO_OPTION, - // JOptionPane.WARNING_MESSAGE ); - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete this State?", - "Delete State" ); - - if ( confirm ) - { - _dataMgr.deleteState( _sacSmaState ); - _sacSmaState = null; - refreshSacSmaStateTable(); - } - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _sacSmaState = null; - loadTextFields(); - } - } - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } - - /* - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if ( ! textField.getText().equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - DateTimeDialog dateTimeGUI = null; - - if ( textField == _basisTimeTextField ) - { - dateTimeGUI = new DateTimeDialog( SacStateEditor.this, dateTime, "Basis Time" ); - } - else - { - dateTimeGUI = new DateTimeDialog( SacStateEditor.this, dateTime, "Valid Time" ); - } - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - } - } - */ - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = SacStateEditor.this.getHeight(); - int width = SacStateEditor.this.getWidth(); - -// System.err.println( width + "\n" + height ); - if ( width < MIN_WIDTH ) - { - SacStateEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - SacStateEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - SacStateEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - SacStateEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private void closeWindow() - /******************** - Purpose: closes the window - *********************/ - { - this.dispose(); - } - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - public static void main(String[] args) - { - SacStateEditor sacStateGUI = new SacStateEditor( new JFrame(), new DataMgr(), "BLUO2" ); - sacStateGUI.show(); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SshpTableModel.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SshpTableModel.java deleted file mode 100644 index 61f09fa575..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/SshpTableModel.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Created on Feb 12, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Feb 12, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import javax.swing.table.DefaultTableModel; - -public class SshpTableModel extends DefaultTableModel -{ - private String[] _columnNames = null; - - private Object[][] _data = null; - - public SshpTableModel( String[] colNames, String[][] dataStringArray ) - { - _columnNames = colNames; - _data = dataStringArray; - } - - public void updateData( String[][] dataStringArray ) - { - _data = dataStringArray; - } - - public int getColumnCount() - { - return _columnNames.length; - } - - public int getRowCount() - { - if ( _data != null ) - { - return _data.length; - } - else - { - return 0; - } - } - - public String getColumnName(int col) - { - return _columnNames[col]; - } - - public Object getValueAt(int row, int col) - { - return _data[row][col]; - } - - public boolean isCellEditable(int row, int col) - { - return false; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographCanvasPanel.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographCanvasPanel.java deleted file mode 100644 index b191694935..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographCanvasPanel.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Created on Aug 23, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.TableColumnComparator; -import ohd.hseb.util.gui.drawing.DataPointCanvas; - -/** - * @author GobsC - * This class owns and controls the UnitHydrographCanvasAdapter and the - * UnitHydrographDescriptorTableAdapter, and so, by delegation, - * owns their Canvas and Table. It also is the messenger between the - * rest of the UnitHydrographEditor and its components. - * - */ -public class UnitHydrographCanvasPanel extends JPanel -{ - private List _descriptorList = null; - - //This is needed by the UnitHydrographDataPointCanvasAdapter - //and the UnitHydrographDescriptorTableAdapter, so - //this class will manage it. - private List _displayedDescriptorList = null; - - private UnitHydrographDescriptorTableAdapter _tableAdapter = null; - //private JPanel _canvasButtonPanel = new JPanel(); - - - - private UnitHydrographDataPointCanvasAdapter _canvasAdapter = null; - private DataPointCanvas _canvas = null; - - public static final String AREA_ID = "Area ID"; - public static final String MODEL = "Model"; - public static final String DURATION = "Duration"; - - - public UnitHydrographCanvasPanel(List unitHydrographEntryList) - { - Dimension minCanvasSize = new Dimension( 700, 750 ); - Dimension minScrollPaneSize = new Dimension( 700, 250 ); - Dimension minCanvasPanelSize = new Dimension( 700, 1000 ); - - - Dimension prefCanvasSize = new Dimension( 700, 750 ); - Dimension prefScrollPaneSize = new Dimension( 700, 250 ); - Dimension prefCanvasPanelSize = new Dimension( 700, 1000 ); - - - - // - this.setLayout( new GridBagLayout() ); - this.setPreferredSize( prefCanvasPanelSize ); - this.setMinimumSize(minCanvasPanelSize); - // this.setBackground(Color.blue); - - _descriptorList = - UnitHydrographDescriptor.createUnitHydrographDescriptorList( - unitHydrographEntryList); - - _displayedDescriptorList = new ArrayList(); - - //objects for the drawing - _canvasAdapter = new UnitHydrographDataPointCanvasAdapter(); - _canvas = _canvasAdapter.initCanvas(_descriptorList); - _canvas.setPreferredSize(prefCanvasSize ); - _canvas.setMinimumSize(minCanvasSize ); - - _tableAdapter = createDescriptorTableAdapter(_descriptorList); - JScrollPane tableScrollPane = _tableAdapter.getScrollPane(); - tableScrollPane.setPreferredSize(prefScrollPaneSize); - tableScrollPane.setMinimumSize(minScrollPaneSize); - - //select the first descriptor in the list - - if (_tableAdapter.getDescriptorCount() > -1) - { - _tableAdapter.setSelectedIndex(0); - UnitHydrographDescriptor descriptor = _tableAdapter.getDescriptorByIndex(0); - _displayedDescriptorList.add(descriptor); - } - - //button panel for the canvas - // _canvasButtonPanel.setLayout(new GridBagLayout() ); - // _canvasButtonPanel.setLayout(new FlowLayout() ); - // _canvasButtonPanel.setPreferredSize(prefCanvasButtonPanelSize ); - // _canvasButtonPanel.setMinimumSize(minCanvasButtonPanelSize ); - - //separators for appearance - JPanel horizontalSeparatorPanel = new JPanel(); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - - JPanel verticalSeparatorPanel = new JPanel(); - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - - GridBagConstraints gbc = new GridBagConstraints(); - //gbc.insets = new Insets(20, 0, 20, 0); - - - gbc.fill = 1; - gbc.insets = new Insets(0, 0, 0, 0); - gbc.weightx = 1.0; - gbc.weighty = 1.0; - - //add components to the canvasPanel - ComponentHelper.addPanelComponent( this, _canvas, gbc, 0, 0, 1, 10, GridBagConstraints.BOTH ); - - - gbc.anchor = GridBagConstraints.NORTH; - ComponentHelper.addPanelComponent( this, tableScrollPane , gbc, 0, 11, 1, 8, GridBagConstraints.BOTH ); - - - addListeners(); - - } - - public void addListeners() - { - _tableAdapter.getListSelectionModel().addListSelectionListener( new DescriptorRowSelectionListener() ); - } - - - - private UnitHydrographDescriptorTableAdapter createDescriptorTableAdapter(List descriptorList) - { - JTable table = null; - String[] columnNameArray = { AREA_ID, MODEL, DURATION }; - UnitHydrographDescriptorTableAdapter tableAdapter = null; - - TableColumnComparator comparator = new UnitHydrographDescriptorComparator(); - - - tableAdapter = new UnitHydrographDescriptorTableAdapter(comparator, columnNameArray, descriptorList ); - - return tableAdapter; - - } - // ------------------------------------------------------------------------------------- - - public void refreshData(List unitHydrographEntryList) - { - //CodeTracer tracer = new CodeTracer(); - //tracer.trace(); - - _descriptorList = UnitHydrographDescriptor.createUnitHydrographDescriptorList(unitHydrographEntryList); - - //save off this list, since the refreshTableModel command will call the - //listener, which will overwrite the contents of _displayDiscriptorList - List tempDisplayDescriptorList = new ArrayList(_displayedDescriptorList); - - - _tableAdapter.refreshTableModel(_descriptorList); - - //pull out the origin displayDescriptorList - -// creates own descriptorList, for coding reasons, from the unitHydrographEntryList - _canvasAdapter.refreshCanvas(unitHydrographEntryList); - - _displayedDescriptorList = tempDisplayDescriptorList; - - _tableAdapter.selectItems(_displayedDescriptorList); - } - - // ------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------- - private class DescriptorRowSelectionListener implements - ListSelectionListener - { - - public void valueChanged(ListSelectionEvent event) - { - - String header = "DescriptorRowSelectionListener.valueChanged(): "; - UnitHydrographDescriptor descriptor = null; - JTable table = _tableAdapter.getTable(); - - // for each from in the table, reset the shouldPaints in the - // canvasAdapter - - // clear out the displayed Descriptor list - _displayedDescriptorList.clear(); - - for (int i = 0; i < table.getRowCount(); i++) - { - boolean isSelected = table.isRowSelected(i); - - descriptor = _tableAdapter.getDescriptorByIndex(i); - - if ( descriptor != null ) - { - //maintain the list of selected items - if (isSelected) - { - _displayedDescriptorList.add(descriptor); - } - - _canvasAdapter.setPainterShouldPaint(descriptor, isSelected); - - // System.out.println(header + "descriptor = " + descriptor - // + " shouldPaint = " + isSelected); - } - } - - _canvasAdapter.redrawCanvas(); - - - } - } - // ------------------------------------------------------------------------------------- -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDataPointCanvasAdapter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDataPointCanvasAdapter.java deleted file mode 100644 index a9baf0ca38..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDataPointCanvasAdapter.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Created on Jul 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Comparator; -import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasurementPointComparator; -import ohd.hseb.measurement.MeasurementPointSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.DurationCode; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.DataCurvePainter; -import ohd.hseb.util.gui.drawing.DataPointCanvas; -import ohd.hseb.util.gui.drawing.DataPointCanvasAdapter; -import ohd.hseb.util.gui.drawing.DataPointCanvasBackgroundPainter; -import ohd.hseb.util.gui.drawing.ScalingHelper; - -/** - * @author GobsC - * This class helps the user to use the DataPointCanvas class from within The UnitHydrographEditor - * dialog. It serves to keep all of the drawing-related code together. - * - */ -public class UnitHydrographDataPointCanvasAdapter implements DataPointCanvasAdapter -{ - private List _unitHydrographDescriptorList = null; - - private DataPointCanvas _canvas = null; - private DataPointCanvasBackgroundPainter _dataBackgroundPainter = null; - - private DataCurvePainter[] _curvePainterArray = null; - - private MeasurementPointSeries[] _measurementPointSeriesArray = null; - - private MeasuringUnit _xUnit = MeasuringUnit.hours; - private MeasuringUnit _yUnit = MeasuringUnit.cfs; - - private static final Color[] _colorCurveArray = {Color.YELLOW, - Color.RED, - Color.BLUE, - Color.CYAN, - Color.MAGENTA, - Color.GREEN, - Color.ORANGE, - Color.GRAY, - Color.PINK}; - - - //------------------------------------------------------------------------------------- - - public UnitHydrographDataPointCanvasAdapter() - { - - - } -//------------------------------------------------------------------------------------- - public DataPointCanvas initCanvas(Object initializationObject) - { - _unitHydrographDescriptorList = (List) initializationObject; - - - - int x = 0; - int y = 0; - int width = 700; - int height = 700; - - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - MeasuringUnit timeUnit = MeasuringUnit.hours; - - // scaling helpers end up affecting the overall viewport window and - // what numbers are displayed for major and minor tick marks by painter - ScalingHelper horizontalScalingHelper = new ScalingHelper(0.0, 0.0); - ScalingHelper verticalScalingHelper = new ScalingHelper(0.0, 0.0); - - double[] niceMinorIncrementArray = {1, 2, 4, 8, 12, 24 }; - horizontalScalingHelper.setNiceMinorIncrementArray(niceMinorIncrementArray); - - double[] niceMajorIncrementArray = { 6, 12, 24, 48, 96, 120 }; - horizontalScalingHelper.setNiceMajorIncrementArray(niceMajorIncrementArray); - - horizontalScalingHelper.setBaseFactorStartingPoint(1.0); - - - _canvas = new DataPointCanvas(timeUnit, dischargeUnit, - x, y, - width, height, - horizontalScalingHelper, - verticalScalingHelper); - - _canvas.setPreferredSize(new Dimension(width, height)); - _canvas.setMinimumSize(new Dimension(width, height)); - - - Color outlineColor = Color.WHITE; - - - // background Painter - _dataBackgroundPainter = - new DataPointCanvasBackgroundPainter(outlineColor, _canvas, - "hours", "cfs", - horizontalScalingHelper, - verticalScalingHelper); - - _dataBackgroundPainter.setShowMinorHorizontalTicks(true); - _dataBackgroundPainter.setShowMinorVerticalTicks(true); - - // this painter is not to be used for determining scaling, - //so, this is just considered a plain-old CanvasPainter, - // instead of a DataPointCanvasPainter - _canvas.addCanvasPainter(_dataBackgroundPainter); - - - initMeasurementPointSeriesAndPainters(_unitHydrographDescriptorList); - - - //overall canvas settings - _canvas.setTitle("Unit Hydrograph"); - _canvas.addMouseMotionListener(new CanvasMouseMotionListener(_canvas)); - - return _canvas; - - } //end initCanvas - // ------------------------------------------------------------------------------------- - private void addBackgroundPainter() - { - - - } - - // ------------------------------------------------------------------------------------- - - public void redrawCanvas() - { - _canvas.refresh(); - } - - public void refreshCanvas(Object dataObject) - { - List unitHydrographEntryList = (List) dataObject; - loadCanvasWithData(unitHydrographEntryList); - _canvas.refresh(); - } - // ------------------------------------------------------------------------------------- - public void setPainterShouldPaint(UnitHydrographDescriptor descriptor, boolean shouldPaint) - { - int index = findIndexOfDescriptor(descriptor); - - if (index > -1) - { - DataCurvePainter painter = _curvePainterArray[index]; - - painter.setShouldPaint(shouldPaint); - } - } - // ------------------------------------------------------------------------------------- - - - private void initMeasurementPointSeriesAndPainters(List unitHydrographDescriptorList) - { - // init the drawing variables - boolean compareXValues = true; - boolean ascendingOrder = true; - Comparator comparator = new MeasurementPointComparator(compareXValues, ascendingOrder); // compare X values - - - - int listSize = unitHydrographDescriptorList.size(); - _curvePainterArray = new DataCurvePainter[listSize]; - _measurementPointSeriesArray = new MeasurementPointSeries[listSize]; - - for (int i = 0; i < _measurementPointSeriesArray.length; i++) - { - MeasurementPointSeries series = new MeasurementPointSeries(_xUnit, - _yUnit, comparator); - _measurementPointSeriesArray[i] = series; - } - - - //remove all the paints and re-add the background painter - _canvas.removeAllDataPointCanvasPainters(); - - if (_dataBackgroundPainter != null) - { - _canvas.addCanvasPainter(_dataBackgroundPainter); - } - - - // painter creation Loop - // there is 1 MeasurementPointSeries per painter - // There is 1 MeasurementPointSeries per UnitHydrographDescriptor - for (int i = 0; i < _measurementPointSeriesArray.length; i++) - { - MeasurementPointSeries series = _measurementPointSeriesArray[i]; - Color curveColor = getCurveColor(i); - - DataCurvePainter painter = new DataCurvePainter(series, _canvas, - curveColor); - - _curvePainterArray[i] = painter; - _canvas.addDataPointCanvasPainter(painter); - painter.setShouldPaint(false); - - } - - } //end initMeasurementPointSeries - - // ------------------------------------------------------------------------------------- - - private class CanvasMouseMotionListener extends MouseMotionAdapter - { - private DataPointCanvas _canvas2 = null; - - public CanvasMouseMotionListener(DataPointCanvas canvas) - { - _canvas2 = canvas; - } - - public void mouseMoved(MouseEvent event) - { - - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas2.getViewport().getDataPoint(screenPoint); - - - if (_canvas2.getViewport().isViewable(dataPoint)) - { - updateCanvasDataPointText(dataPoint, _canvas); - } - } - - } - -// ------------------------------------------------------------------------------------- - - - public void updateCanvasDataPointText(DataPoint dataPoint, - DataPointCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String xUnitString = canvas.getDisplayedXMeasuringUnit().toString(); - String yUnitString = canvas.getDisplayedYMeasuringUnit().toString(); - - String message = getCanvasDataPointString(dataPoint, xUnitString, - yUnitString); - - canvas.setToolTipText(message); - - return; - } - -// ------------------------------------------------------------------------------------- - - private String getCanvasDataPointString(DataPoint dataPoint, - String xUnitString, - String yUnitString) - { - NumberFormat nfX = new DecimalFormat("###"); - - long hour = (long) Math.round(dataPoint.getX()); - String xValueString = nfX.format(hour); - - NumberFormat nfY = new DecimalFormat("###.##"); - String yValueString = nfY.format(dataPoint.getY()); - - String dataPointString = xValueString + " " + xUnitString + " , " - + yValueString + " " + yUnitString; - - return dataPointString; - } -// ------------------------------------------------------------------------------------- - - private Color getCurveColor(int index) - { - if (index >= _colorCurveArray.length) - { - index = index % _colorCurveArray.length; - } - - return _colorCurveArray[index]; - } - - // ------------------------------------------------------------------------------------- - private int findIndexOfDescriptor(UnitHydrographDescriptor desc) - { - int index = _unitHydrographDescriptorList.indexOf(desc); - - return index; - } - // ------------------------------------------------------------------------------------- - private void loadCanvasWithData(List uhgList) - { - - - int measurementPointSeriesIndex = 0; - - _unitHydrographDescriptorList = - UnitHydrographDescriptor.createUnitHydrographDescriptorList(uhgList); - - initMeasurementPointSeriesAndPainters(_unitHydrographDescriptorList); - - - boolean loadApiModel = true; - - Measurement ordinalMeasurement = null; - Measurement dischargeMeasurement = null; - MeasurementPoint point = null; - - - // load the various MeasurementPointSeries with their data - for (int i = 0; i < uhgList.size(); i++) - { - UnitHydrographEntry uhgEntry = (UnitHydrographEntry) uhgList.get(i); - - // add Measurement Points to the points for the unitHydrograph - int hourInterval = DurationCode.getHoursFromCode(uhgEntry.getDur()); - - ordinalMeasurement = new Measurement(uhgEntry.getOrdinal()*hourInterval, _xUnit); - dischargeMeasurement = new Measurement(uhgEntry.getDischarge(),_yUnit); - - point = new MeasurementPoint(ordinalMeasurement, - dischargeMeasurement); - - //find the right measurement point series and add the point to it - measurementPointSeriesIndex = findMeasurementPointSeriesIndexByEntry(uhgEntry); - MeasurementPointSeries series = _measurementPointSeriesArray[measurementPointSeriesIndex]; - if (series != null) - { - series.addPoint(point); - } - } - - - // make sure that the MeasurementPointSeries end in a 0 discharge - // the last Y measurement needs to be 0 for graphing the unitgraph, so - // that - // the scaling does not start, at say, 10, instead of 0 - - for (int i = 0; i < _measurementPointSeriesArray.length; i++) - { - ensureMeasurementSeriesStartsAndEndsInZero(_measurementPointSeriesArray[i]); - } - - } - - // ------------------------------------------------------------------------------------- - private int findMeasurementPointSeriesIndexByEntry(UnitHydrographEntry uhgEntry) - { - int index = -1; - - for (int i = 0; i < _unitHydrographDescriptorList.size(); i++) - { - UnitHydrographDescriptor descriptor = (UnitHydrographDescriptor) - _unitHydrographDescriptorList.get(i); - if (descriptor.isMatchingEntry(uhgEntry)) - { - index = i; - break; - } - } - - return index; - } - // ------------------------------------------------------------------------------------- - - private void ensureMeasurementSeriesStartsAndEndsInZero(MeasurementPointSeries series) - { - MeasurementPoint lastPoint = null; - int lastIndex = series.size() - 1; - - - if (lastIndex >= 0) - { - lastPoint = series.getPoint(lastIndex); - - Measurement lastXMeasurement = lastPoint.getXMeasurement(); - Measurement lastYMeasurement = lastPoint.getYMeasurement(); - - MeasuringUnit xUnit = lastXMeasurement.getUnit(); - MeasuringUnit yUnit = lastYMeasurement.getUnit(); - - Measurement firstXMeasurement = new Measurement(0.0, xUnit); - Measurement firstYMeasurement = new Measurement(0.0, yUnit); - - //add a (0.0, 0.0) first point to the series - MeasurementPoint firstPoint = new MeasurementPoint(firstXMeasurement, firstYMeasurement); - series.addPoint(firstPoint); - - lastPoint = series.getPoint(lastIndex); - - - if (lastYMeasurement.getValue() != 0) - { - Measurement newYMeasurement = new Measurement(0.0, - yUnit); - - - double newXValue = lastXMeasurement.getValue() + 1.0; - Measurement newXMeasurement = new Measurement(newXValue, - xUnit); - - MeasurementPoint newLastPoint = new MeasurementPoint( - newXMeasurement, newYMeasurement); - series.addPoint(newLastPoint); - } - } - - - - - return; - - } - // ------------------------------------------------------------------------------------- -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorComparator.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorComparator.java deleted file mode 100644 index e5a3512368..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorComparator.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author GobsC - * - */ -public class UnitHydrographDescriptorComparator extends TableColumnComparator -{ - public UnitHydrographDescriptorComparator() - { - } - - - public int compareArea_Id( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - int result = entry1.getAreaId().compareToIgnoreCase( entry2.getAreaId() ); - return result; - } - - public int compareModel( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareStrings( entry1.getModel(), entry2.getModel() ) ); - } - - public int compareDuration( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getDur(), entry2.getDur() ) ); - } - - - public int compare(Object object1, Object object2) - { - UnitHydrographEntry entry1 = (UnitHydrographEntry) object1; - UnitHydrographEntry entry2 = (UnitHydrographEntry) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( UnitHydrographEditor.AREA_ID ) ) - { - returnValue = compareArea_Id( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.MODEL ) ) - { - returnValue = compareModel( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.DURATION ) ) - { - returnValue = compareDuration( entry1, entry2 ); - } - - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorTableAdapter.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorTableAdapter.java deleted file mode 100644 index a66a9af4b4..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorTableAdapter.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.util.List; - -import ohd.hseb.model.DurationCode; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.sshp.gui.TableAdapter; -import ohd.hseb.util.gui.TableColumnComparator; - - -/** - * @author GobsC - * - * - */ -public class UnitHydrographDescriptorTableAdapter extends TableAdapter -{ - - private UnitHydrographDescriptor _descriptor = null; - private List _descriptorList = null; - - // --------------------------------------------------------------------------------- - - - - public UnitHydrographDescriptorTableAdapter(TableColumnComparator comparator, - String[] columnNameArray, - List dataList) - { - super(comparator, columnNameArray, dataList); - - setAllowMultipleSelection(true); - - } - - // --------------------------------------------------------------------------------- - public String[][] getDataStringArrayFromDataList(List dataList) - { - int fieldCount = 3; - String[][] dataArray = new String[dataList.size()][fieldCount]; - - - for (int i = 0; i < dataList.size(); i++) - { - UnitHydrographDescriptor desc = (UnitHydrographDescriptor) dataList.get(i); - dataArray[i][0] = desc.getBasinId(); - dataArray[i][1] = desc.getModel(); - dataArray[i][2] = "" + DurationCode.getHoursFromCode(desc.getDuration()); - } - - return dataArray; - - } - // --------------------------------------------------------------------------------- - public void refreshTableModel(List dataList) - { - setDataList(dataList);// for super class - - _descriptorList = dataList; - - String[][] dataStringArray = getDataStringArrayFromDataList(dataList); - getTableModel().updateData( dataStringArray ); - getTableModel().fireTableChanged( null ); - - - return; - - } - // --------------------------------------------------------------------------------- - - public int getDescriptorCount() - { - int count = getDataList().size(); - return count; - } - - // --------------------------------------------------------------------------------- - - public UnitHydrographDescriptor getDescriptorByIndex(int index) - { - List dataList = getDataList(); - UnitHydrographDescriptor desc = null; - - if ( dataList.size() > 0 ) - { - Object object = dataList.get(index); - desc = (UnitHydrographDescriptor) object; - } - return desc; - } - - // --------------------------------------------------------------------------------- - - private int findIndexOfDescriptor(UnitHydrographDescriptor desc) - { - int index = _descriptorList.indexOf(desc); - - return index; - } - // ------------------------------------------------------------------------------------- - public void setDataList(List dataList) - { - - super.setDataList(dataList); - _descriptorList = dataList; - - } - - // --------------------------------------------------------------------------------- - - - private void selectAll() - { - - getListSelectionModel().setSelectionInterval(0, getTable().getModel().getRowCount()-1); - } - - - // --------------------------------------------------------------------------------- - public void setSelectedIndex(int index) - { - - getListSelectionModel().setSelectionInterval(index, index); - - } - // --------------------------------------------------------------------------------- - - public void selectItems(List selectedDescriptorList) - { - getListSelectionModel().clearSelection(); - - for (int i = 0; i < selectedDescriptorList.size(); i++) - { - UnitHydrographDescriptor descriptor = (UnitHydrographDescriptor) selectedDescriptorList.get(i); - - int index = findIndexOfDescriptor(descriptor); - - if (index >= 0) - { - getListSelectionModel().setSelectionInterval(index, index); - - } - } - } - // --------------------------------------------------------------------------------- - -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographEditor.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographEditor.java deleted file mode 100644 index a81f5426fe..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographEditor.java +++ /dev/null @@ -1,1659 +0,0 @@ -/* - * Created on June 08, 2004 - * - * Filename : UnitHydrographEditor.java - * Author : Gautam Sood - * Modified by: Chip Gobs (addition of graphics and the table to control them). - * Purpose: Display GUI for Unit Hydrograph. - * Last Revision Date : October 8, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.model.DurationCode; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.StringParser; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; -import ohd.hseb.util.gui.OptionSelectionDialog; -import ohd.hseb.util.gui.TableHelper2; - -import com.raytheon.uf.common.ohd.AppsDefaults; - -public class UnitHydrographEditor extends JDialog { - private Container _frameContentPane = getContentPane(); - - private JPanel _uhgListPanel = new JPanel(); - - private JPanel _uhgTextPanel = new JPanel(); - - private JPanel _listButtonPanel = new JPanel(); - - private JPanel _dialogButtonPanel = new JPanel(); - - private Font _labelFont = new Font("Helvetica", Font.BOLD, 13); - - private Font _textFieldFont = new Font("Helvetica", Font.PLAIN, 12); - - private List _uhgList = null; - - private List _uhgEntryAddModifyDeleteList = new ArrayList(); - - private DataMgr _dataMgr = null; - - private UnitHydrographEntry _unitHydrographEntry = null; - - private String _locationId = null; - - private String _connectionString = null; - - private FileLogger _logger = null; - - private static final int DEFAULT_WIDTH = 1200; - - private static final int DEFAULT_HEIGHT = 800; // 909 - - private static final int MAX_WIDTH = 1200; - - private static final int MAX_HEIGHT = 1000; - - private static final int MIN_WIDTH = 545; - - private static final int MIN_HEIGHT = 500; - - // used for JFormattedTextFields - private static final String _decimalFormatString = "0.0"; - - private DecimalFormat _decimalFormat = new DecimalFormat( - _decimalFormatString); - - private JLabel _areaIdLabel = getJLabel("Area ID"); - - private JLabel _durationLabel = getJLabel("Duration"); - - private JLabel _ordLabel = getJLabel("Ordinal"); - - private JLabel _dischargeLabel = getJLabel("Discharge"); - - private JLabel _modelLabel = getJLabel("Model"); - - private static final String[] _modelStringArray = { "ANY", "API-MKC", - "SAC-SMA" }; - - private JComboBox _modelComboBox = new JComboBox(_modelStringArray); - - private static final String[] _durationStringArray = { "1", "6" }; - - private JComboBox _durationComboBox = new JComboBox(_durationStringArray); - - private JTextField _areaIdTextField = getJTextField(13); - - private JTextField _ordTextField = getJTextField(13); - - private JTextField _dischargeTextField = getJTextField(13); - - private JButton _saveButton = new JButton("Save"); - - private JButton _deleteButton = new JButton("Delete"); - - private JButton _closeButton = new JButton("Close"); - - private JButton _addButton = new JButton("Add"); - - private JButton _modifyButton = new JButton("Modify"); - - private JButton _removeButton = new JButton("Remove"); - - private JButton _importButton = new JButton("Import"); - - private JButton _exportButton = new JButton("Export"); - - // used for custom notification - private List _applyListenerList = new ArrayList(); - - // used for the row and master Tables - public static final String AREA_ID = "Area ID"; - - public static final String MODEL = "Model"; - - public static final String DURATION = "Duration"; - - // used for the row table - public static final String ORDINAL = "Ordinal"; - - public static final String DISCHARGE = "Discharge"; - - public static final String DISPLAY = "Display"; - - private String[] _rowTableColumnNames = { AREA_ID, MODEL, DURATION, - ORDINAL, DISCHARGE }; - - private int _lastColumnSorted = 0; - - private String[][] _unitHydrographStringArray = null; - - private JTable _uhgRowJTable = null; - - private JScrollPane _scrollPane = null; - - private SshpTableModel _rowTableModel = null; - - private ListSelectionModel _rowListSelectionModel = null; - - private boolean _needsSaving = false; - - private String _importDirString = null; - - private String _exportDirString = null; - - private String _fileChooserDirectory = null; - - // used for sorting the Table - private UnitHydrographEntryComparator _comparator = new UnitHydrographEntryComparator(); - - private TableHelper2 _tableHelper = new TableHelper2(_comparator, - _rowTableColumnNames); - - // ---- picture related objects - // ----------------------------------------------- - // canvas Panel - private UnitHydrographCanvasPanel _canvasPanel = null; - - // ------------------------------------------------------------------------------------- - - public UnitHydrographEditor() { - } - - public UnitHydrographEditor(Frame owner, DataMgr dataMgr, - String locationId, boolean isModal) - /******************** - * Purpose: Constructor - *********************/ - { - super(owner, isModal); - _locationId = locationId; - this.setTitle("Unit Hydrograph - " + _locationId); - _dataMgr = dataMgr; - - AppsDefaults ad = AppsDefaults.getInstance(); - _importDirString = ad.getToken("whfs_import_dir"); - - initGui(); - } - - // ------------------------------------------------------------------------------------- - - private void initGui() - /******************** - * Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - - // init the rest of the variables - initJTable(); - - // initialize the drawing area (canvas) panel - _canvasPanel = new UnitHydrographCanvasPanel(_uhgList); - - initUnitHydrographJTableComponents(); - initUnitHydrographDataPanelComponents(); - initListButtons(); - initDialogButtons(); - initFrameComponents(); - - addListeners(); - - setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); - - // set the initial sort to the "model" column - initializeTableSort(); - - // let the sort take visual effect - refreshUnitHydrographTable(); - - return; - } - - // ------------------------------------------------------------------------------------- - private int getColumnIndex(String columnName) { - // this does NOT keep track of whether the column has been moved - // graphically - int index = -1; - - for (int i = 0; i < _rowTableColumnNames.length; i++) { - if (_rowTableColumnNames[i].equalsIgnoreCase(columnName)) { - index = i; - break; - } - } - - return index; - } - - // ------------------------------------------------------------------------------------- - private List loadUhgList() { - - List list = _dataMgr.loadUnitHydrographEntryList(_locationId, - "ORDER BY ordinal"); - - return list; - } - - // ------------------------------------------------------------------------------------- - - private void initJTable() { - int index = 0; - final String header = "UnitHydrographEditor.setupTables(): "; - _uhgList = loadUhgList(); - _unitHydrographStringArray = convertListToArray(); - if ((_uhgList != null) && (_uhgList.size() != 0)) { - _unitHydrographEntry = (UnitHydrographEntry) _uhgList.get(0); - } - - _rowTableModel = new SshpTableModel(_rowTableColumnNames, - _unitHydrographStringArray); - _uhgRowJTable = new JTable(_rowTableModel); - _uhgRowJTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - _uhgRowJTable - .setPreferredScrollableViewportSize(new Dimension(300, 100)); - - _rowListSelectionModel = _uhgRowJTable.getSelectionModel(); - _rowListSelectionModel.setSelectionInterval(index, index); - - Rectangle rect = _uhgRowJTable.getCellRect(index, 0, true); - _scrollPane = new JScrollPane(_uhgRowJTable); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - // ------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------- - - private void refreshUnitHydrographTable() { - int index = 0; - - // find index of matching entry - if (_unitHydrographEntry != null) { - for (int i = 0; i < _uhgList.size(); i++) { - UnitHydrographEntry uhgEntry = (UnitHydrographEntry) _uhgList - .get(i); - - if (_unitHydrographEntry.hasEqualKey(uhgEntry)) { - index = i; - break; - } - } - } - - // update the Jtable with the just-loaded data from the DB - _unitHydrographStringArray = convertListToArray(); - _rowTableModel.updateData(_unitHydrographStringArray); - _rowTableModel.fireTableChanged(null); - - // have the one item be selected - _rowListSelectionModel.setSelectionInterval(index, index); - - // make sure that the item is visible - Rectangle rect = _uhgRowJTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - - // load up the data entry fields - loadTextFields(); - - // give the canvas the latest data - it will then redraw - _canvasPanel.refreshData(_uhgList); - - return; - } - - // ------------------------------------------------------------------------------------- - private String[][] convertMasterListToArray() { - String[][] dataArray = new String[_uhgList.size()][_rowTableColumnNames.length]; - - for (int i = 0; i < dataArray.length; i++) { - UnitHydrographEntry unitHydrographEntry = (UnitHydrographEntry) _uhgList - .get(i); - - dataArray[i][0] = unitHydrographEntry.getAreaId(); - dataArray[i][1] = "" + unitHydrographEntry.getModel(); - dataArray[i][2] = "" + unitHydrographEntry.getDur(); - dataArray[i][3] = "" + unitHydrographEntry.getOrdinal(); - dataArray[i][4] = "" + unitHydrographEntry.getDischarge(); - } - return dataArray; - } - - private String[][] convertListToArray() { - String[][] dataArray = new String[_uhgList.size()][_rowTableColumnNames.length]; - - for (int i = 0; i < dataArray.length; i++) { - UnitHydrographEntry unitHydrographEntry = (UnitHydrographEntry) _uhgList - .get(i); - - dataArray[i][0] = unitHydrographEntry.getAreaId(); - dataArray[i][1] = "" + unitHydrographEntry.getModel(); - dataArray[i][2] = "" - + DurationCode.getHoursFromCode(unitHydrographEntry - .getDur()); - dataArray[i][3] = "" + unitHydrographEntry.getOrdinal(); - dataArray[i][4] = "" + unitHydrographEntry.getDischarge(); - } - return dataArray; - } - - // ------------------------------------------------------------------------------------- - - private void initFrameComponents() - /******************** - * Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - JPanel horizontalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel4 = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - - _frameContentPane.setLayout(new GridBagLayout()); - - // _dataScrollPane.setPreferredSize( new Dimension( 150, 50 ) ); - - horizontalSeparatorPanel.setPreferredSize(new Dimension(300, 10)); - horizontalSeparatorPanel2.setPreferredSize(new Dimension(300, 30)); - horizontalSeparatorPanel3.setPreferredSize(new Dimension(300, 30)); - horizontalSeparatorPanel4.setPreferredSize(new Dimension(300, 30)); - - JSeparator buttonSeparator = new JSeparator(); - - _uhgListPanel.setMinimumSize(new Dimension(400, 500)); - // _uhgListPanel.setMaximumSize(new Dimension(500, 500)); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent(_frameContentPane, _uhgListPanel, 0, - 0, 25, 5, 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, - horizontalSeparatorPanel, 0, 5, 25, 2, GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, _uhgTextPanel, 0, - 7, 25, 1, 1, 0, GridBagConstraints.BOTH); - ComponentHelper - .addFrameComponent(_frameContentPane, - horizontalSeparatorPanel2, 0, 8, 25, 2, - GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, _listButtonPanel, - 0, 10, 25, 1, GridBagConstraints.NONE); - ComponentHelper.addFrameComponent(_frameContentPane, - horizontalSeparatorPanel3, 0, 11, 25, 2, - GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, buttonSeparator, - 0, 13, 25, 2, GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, - horizontalSeparatorPanel4, 0, 15, 25, 2, - GridBagConstraints.BOTH); - - ComponentHelper.addFrameComponent(_frameContentPane, - _dialogButtonPanel, 0, 17, 25, 2, GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, - verticalSeparatorPanel, 25, 0, 1, 15, GridBagConstraints.BOTH); - ComponentHelper.addFrameComponent(_frameContentPane, _canvasPanel, 26, - 0, 15, 15, 1, 1, GridBagConstraints.BOTH); - - return; - } - - // ------------------------------------------------------------------------------------- - - private void initUnitHydrographJTableComponents() - /******************** - * Purpose: Add's Components to the JList Scroll Pane Panel - *********************/ - { - _uhgListPanel.setLayout(new GridBagLayout()); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent(_uhgListPanel, _scrollPane, 0, 0, 5, - 25, 1, 1, GridBagConstraints.BOTH); - - } - - // ------------------------------------------------------------------------------------- - - private void initUnitHydrographDataPanelComponents() - /******************** - * Purpose: Add's Label/TextField componenets to the uhgDataPanel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - _uhgTextPanel.setLayout(new GridBagLayout()); - - verticalSeparatorPanel.setPreferredSize(new Dimension(10, 20)); - verticalSeparatorPanel2.setPreferredSize(new Dimension(10, 20)); - verticalSeparatorPanel3.setPreferredSize(new Dimension(10, 20)); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.insets = new Insets(5, 5, 5, 5); - - // _areaIdTextField.setPreferredSize(new Dimension(100, 40)); - _areaIdTextField.setMinimumSize(new Dimension(80, 20)); - _dischargeTextField.setMinimumSize(new Dimension(80, 20)); - - _modelComboBox.setEditable(true); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent(_uhgTextPanel, _areaIdLabel, gbc, 0, - 0, 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, _areaIdTextField, gbc, - 0, 1, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_uhgTextPanel, _modelLabel, gbc, 2, - 0, 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, _modelComboBox, gbc, - 2, 1, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_uhgTextPanel, _durationLabel, gbc, - 4, 0, 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, _durationComboBox, - gbc, 4, 1, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_uhgTextPanel, _ordLabel, gbc, 6, 0, - 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, _ordTextField, gbc, 6, - 1, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_uhgTextPanel, _dischargeLabel, gbc, - 8, 0, 1, 1, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, _dischargeTextField, - gbc, 8, 1, 1, 1, GridBagConstraints.BOTH); - - ComponentHelper.addPanelComponent(_uhgTextPanel, - verticalSeparatorPanel, gbc, 1, 0, 1, 2, - GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, - verticalSeparatorPanel2, gbc, 3, 0, 1, 2, - GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_uhgTextPanel, - verticalSeparatorPanel3, gbc, 5, 0, 1, 2, - GridBagConstraints.BOTH); - } - - // ------------------------------------------------------------------------------------- - - private void initListButtons() - /******************** - * Purpose: adds the buttons to the list button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - - _listButtonPanel.setLayout(new GridBagLayout()); - // - GridBagConstraints gbc = new GridBagConstraints(); - gbc.insets = new Insets(5, 5, 5, 5); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent(_listButtonPanel, _addButton, gbc, 0, - 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_listButtonPanel, - verticalSeparatorPanel, gbc, 2, 0, 1, 2, - GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_listButtonPanel, _modifyButton, gbc, - 3, 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_listButtonPanel, - verticalSeparatorPanel2, gbc, 5, 0, 1, 2, - GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_listButtonPanel, _removeButton, gbc, - 6, 0, 2, 2, GridBagConstraints.BOTH); - - /* - * if ( _uhgList.size() > 0 ) { _importButton.setEnabled( false ); } - */ - - } - - // ------------------------------------------------------------------------------------- - - private void initDialogButtons() - /******************** - * Purpose: adds the buttons to the dialog button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel verticalSeparatorPanel4 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize(new Dimension(50, 20)); - verticalSeparatorPanel2.setPreferredSize(new Dimension(50, 20)); - verticalSeparatorPanel3.setPreferredSize(new Dimension(50, 20)); - verticalSeparatorPanel4.setPreferredSize(new Dimension(50, 20)); - horizontalSeparatorPanel.setPreferredSize(new Dimension(300, 10)); - - _dialogButtonPanel.setLayout(new GridBagLayout()); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent(_dialogButtonPanel, _saveButton, 6, - 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, - verticalSeparatorPanel, 8, 0, 4, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, _deleteButton, - 12, 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, - verticalSeparatorPanel2, 14, 0, 4, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, _importButton, - 18, 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, - verticalSeparatorPanel3, 20, 0, 4, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, _exportButton, - 24, 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, - verticalSeparatorPanel4, 26, 0, 4, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, _closeButton, 30, - 0, 2, 2, GridBagConstraints.BOTH); - ComponentHelper.addPanelComponent(_dialogButtonPanel, - horizontalSeparatorPanel, 0, 2, 20, 2, GridBagConstraints.BOTH); - } - - // ------------------------------------------------------------------------------------- - - private void loadTextFields() - /******************** - * Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if (_unitHydrographEntry != null) { - _areaIdTextField.setText(_unitHydrographEntry.getAreaId()); - // _modelComboBox.setSelectedIndex( - // getModelIndex(_unitHydrographEntry.getModel())); - - ensureModelIsInModelComboBox(_modelComboBox, _unitHydrographEntry - .getModel()); - _modelComboBox.setSelectedItem(_unitHydrographEntry.getModel()); - - _durationComboBox.setSelectedItem("" - + DurationCode.getHoursFromCode(_unitHydrographEntry - .getDur())); - - // _durationTextField.setText( "" + _unitHydrographEntry.getDur() ); - _ordTextField.setText("" + _unitHydrographEntry.getOrdinal()); - _dischargeTextField.setText("" - + _unitHydrographEntry.getDischarge()); - } else { - _areaIdTextField.setText(""); - _modelComboBox.setSelectedIndex(0); - _durationComboBox.setSelectedIndex(0); - - // _durationTextField.setText( "" ); - _ordTextField.setText(""); - _dischargeTextField.setText(""); - } - } - - // ------------------------------------------------------------------------------------- - private void ensureModelIsInModelComboBox(JComboBox comboBox, - String modelString) - - { - boolean isInComboBox = false; - - for (int i = 0; i < comboBox.getItemCount(); i++) { - String item = (String) comboBox.getItemAt(i); - if (item.equalsIgnoreCase(modelString)) { - isInComboBox = true; - } - } - - if (!isInComboBox) { - comboBox.addItem(modelString); - } - - return; - - } - - // ------------------------------------------------------------------------------------- - private int getModelIndex(String model) { - int index = -1; - for (int i = 0; i < _modelStringArray.length; i++) { - if (_modelStringArray[i].equalsIgnoreCase(model)) { - index = i; - break; - } - } - - return index; - } - - // ------------------------------------------------------------------------------------- - - private void addListeners() - /******************** - * Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _addButton.addActionListener(new AddModifyButtonListener()); - _modifyButton.addActionListener(new AddModifyButtonListener()); - _removeButton.addActionListener(new RemoveButtonListener()); - _importButton.addActionListener(new ImportButtonListener()); - _exportButton.addActionListener(new ExportButtonListener()); - _saveButton.addActionListener(new SaveButtonListener()); - _closeButton.addActionListener(windowCloser); - _deleteButton.addActionListener(new DeleteButtonListener()); - addWindowListener(windowCloser); - addComponentListener(new WindowResizeComponentListener()); - _rowListSelectionModel - .addListSelectionListener(new TableUpdateListener()); - _uhgRowJTable.getTableHeader().addMouseListener( - new TableSortingListener()); - - // _apiMkcCheckBox.addActionListener(new - // UnitgraphDrawingListener("API-MKC")); - // _sacSmaCheckBox.addActionListener(new - // UnitgraphDrawingListener("SAC-SMA")); - } - - // ------------------------------------------------------------------------------------- - - private void saveChanges() { - for (int i = 0; i < _uhgEntryAddModifyDeleteList.size(); i++) { - UnitHydrographEntryCommand entry = (UnitHydrographEntryCommand) _uhgEntryAddModifyDeleteList - .get(i); - - if (entry.AddToDatabase()) { - _dataMgr.saveUnitHydrographEntry(entry.getUhgEntry()); - } else if (!entry.AddToDatabase()) { - _dataMgr.removeUnitHydrographEntry(entry.getUhgEntry()); - } - } - _uhgEntryAddModifyDeleteList.clear(); - - setNeedsSaving(false); - - } - - // ------------------------------------------------------------------------------------- - private void setNeedsSaving(boolean value) { - _needsSaving = value; - - if (_needsSaving) { - _saveButton.setText("* Save!!! *"); - } else { - _saveButton.setText("Save"); - } - - } - - // ------------------------------------------------------------------------------------- - private class TableSortingListener extends MouseAdapter { - @Override - public void mouseClicked(MouseEvent e) { - Point point = e.getPoint(); - _lastColumnSorted = _uhgRowJTable.getTableHeader().columnAtPoint( - point); - // System.out.println("TableSortingListener(): mouseClicked()"); - _tableHelper.sortList(_uhgList, _lastColumnSorted, true); - refreshUnitHydrographTable(); - } - } - - // ------------------------------------------------------------------------------------- - - private class TableUpdateListener implements ListSelectionListener { - public void valueChanged(ListSelectionEvent arg0) { - int index = _uhgRowJTable.getSelectedRow(); - if ((index >= 0) && (!_uhgList.isEmpty())) { - _unitHydrographEntry = (UnitHydrographEntry) _uhgList - .get(index); - } else { - _unitHydrographEntry = null; - } - loadTextFields(); - } - } - - // ------------------------------------------------------------------------------------- - - private class SaveButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - saveChanges(); - } - } - - // ------------------------------------------------------------------------------------- - - private class DeleteButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - boolean confirm = false; - - String basinId = _areaIdTextField.getText(); - String model = (String) _modelComboBox.getSelectedItem(); - - String durationString = (String) _durationComboBox - .getSelectedItem(); - int durationCode = DurationCode - .getCodeFromHoursString(durationString); - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete the unit hydrograph for \n " - + _locationId + " for the basin = " + basinId - + "\n" + " and the model = " + model + " AND " - + " duration = " + durationCode + "?", - "Delete Unit Hydrograph"); - - if (confirm) { - _dataMgr.deleteUnitHydrograph(_locationId, basinId, model, - durationCode); - _uhgEntryAddModifyDeleteList.clear(); // Clears the queue of all - // updates/deletions - - _uhgList = loadUhgList(); - - resortUsingTableSort(); - refreshUnitHydrographTable(); - - } - } - } - - // ------------------------------------------------------------------------------------- - - private boolean isAnyFieldEmpty() { - boolean isEmpty = false; - - if ((isEmptyString(_areaIdTextField.getText())) - || (isEmptyString((String) _modelComboBox.getSelectedItem())) - || (isEmptyString((String) _durationComboBox.getSelectedItem())) - || (isEmptyString(_ordTextField.getText())) - || (isEmptyString(_dischargeTextField.getText()))) // Checks to - // make sure - // the text - // fields do - // not - // contain - // empty strings - { - isEmpty = true; - } - return isEmpty; - } - - // ------------------------------------------------------------------------------------- - - private UnitHydrographEntry getUnitHydrographEntryFromFields() { - UnitHydrographEntry newUHGEntry = new UnitHydrographEntry(); - - try { - - newUHGEntry.setAreaId(_areaIdTextField.getText().trim()); - newUHGEntry.setModel((String) _modelComboBox.getSelectedItem()); - newUHGEntry.setDur(DurationCode - .getCodeFromHoursString((String) _durationComboBox - .getSelectedItem())); - newUHGEntry.setOrdinal(Integer.parseInt(_ordTextField.getText() - .trim())); - newUHGEntry.setDischarge(Double.parseDouble(_dischargeTextField - .getText().trim())); - newUHGEntry.setLocationId(_locationId); - } - - catch (Exception e) { - DialogHelper.displayErrorDialog(this, - "Error parsing an input field, please examine.", - "UnitHydrographEditor Data Entry Error"); - newUHGEntry = null; - - } - - return newUHGEntry; - } - - // ------------------------------------------------------------------------------------- - - private class AddModifyButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - - UnitHydrographEntry newUHGEntry = null; - - if (!isAnyFieldEmpty()) { - boolean addToDatabase = true; - boolean duplicateEntry = false; - // int column = _lastSortedColumn; - - newUHGEntry = getUnitHydrographEntryFromFields(); - - if (newUHGEntry != null) { - - duplicateEntry = validateNewUnitHydrographEntry(newUHGEntry); - - if (e.getSource() == _addButton) { - if (!duplicateEntry) { - UnitHydrographEntryCommand addEntry = new UnitHydrographEntryCommand( - newUHGEntry, addToDatabase); - _uhgEntryAddModifyDeleteList.add(addEntry); - _unitHydrographEntry = newUHGEntry; - _uhgList.add(newUHGEntry); - } else { - DialogHelper - .displayErrorDialog( - UnitHydrographEditor.this, - "Duplicate Ordinal values may not be entered.", - "Error Message"); - } - - } else if (e.getSource() == _modifyButton) { - if (duplicateEntry) { - UnitHydrographEntryCommand changedEntry = new UnitHydrographEntryCommand( - newUHGEntry, addToDatabase); - _uhgEntryAddModifyDeleteList.add(changedEntry); - _uhgList.remove(_unitHydrographEntry); - _uhgList.add(newUHGEntry); - - _unitHydrographEntry = newUHGEntry; - } - } - - // System.out.println("AddModifyButtonListener(): actionPerformed()"); - - // sort by ordinal so that it looks good - _tableHelper.sortWithoutMemory(_uhgList, - getColumnIndex(ORDINAL), true); - - // sort by whatever is the last requested sort order - _tableHelper.resortList(_uhgList); - - refreshUnitHydrographTable(); - - notifyAllApplyActionListeners(); // notifies all the - // listeners - - setNeedsSaving(true); - - } // end newUHGEntry - - } - - } - - // ------------------------------------------------------------------------------------- - - private boolean validateNewUnitHydrographEntry( - UnitHydrographEntry newUHGEntry) { - boolean foundEntry = false; - - for (int i = 0; i < _uhgList.size(); i++) { - UnitHydrographEntry entry = (UnitHydrographEntry) _uhgList - .get(i); - - if (entry.hasEqualKey(newUHGEntry)) { - _unitHydrographEntry = entry; - foundEntry = true; - } - } - return foundEntry; - } - } - - // ------------------------------------------------------------------------------------- - - private class ExportButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - UnitHydrographEditor.this.exportUnitHydrographToFile(); - } - } - - // ------------------------------------------------------------------------------------- - - private void exportUnitHydrographToFile() { - File fileName = null; - OutputStream outputStream = null; - PrintWriter writer = null; - boolean confirm = false; - boolean fileIsOpen = false; - - // get confirmation of desire to Export the unit hydrograph - String basinId = _areaIdTextField.getText(); - String model = (String) _modelComboBox.getSelectedItem(); - - String durationString = (String) _durationComboBox.getSelectedItem(); - int durationCode = DurationCode.getCodeFromHoursString(durationString); - - // use this to ensure only 1 unithydrograph is exported - UnitHydrographDescriptor selectedDescriptor = new UnitHydrographDescriptor( - _locationId, basinId, model, durationCode); - - String message = "Are you sure you want to export the unit hydrograph for \n " - + _locationId - + " for the basin = " - + basinId - + "\n" - + " and the model = " - + model - + " AND " - + " durationCode = " - + durationCode - + "?\n" - + "Note: the export file will be overwritten if it already exists\n"; - - confirm = DialogHelper.displayConfirmDialog(null, message, - "Export Unit Hydrograph"); - - if (confirm) { - fileName = displayExportFileChooser(); - - if (!fileIsOpen) { - try { - if (fileName != null) { - outputStream = new FileOutputStream(fileName, false); - fileIsOpen = true; - } else // fileName is null - { - outputStream = System.out; - } - - writer = new PrintWriter(outputStream); - } catch (java.io.IOException e) { - String errorMessage = "Error exporting file: " - + e.getMessage(); - DialogHelper.displayErrorDialog(null, message, - "Export Error"); - // e.printStackTrace(); - } - } - for (int i = 0; i < _uhgList.size(); i++) { - UnitHydrographEntry entry = (UnitHydrographEntry) _uhgList - .get(i); - - // only write out the unithydrograph that matches the one - // selected to be - // exported - if (selectedDescriptor.isMatchingEntry(entry)) { - - writer.println(entry.getAreaId() + " " + entry.getModel() - + " " + entry.getDur() + " " + entry.getOrdinal() - + " " + entry.getDischarge()); - writer.flush(); - - } - } - writer.close(); - - } - - } - - // ------------------------------------------------------------------------------------- - - private class ImportButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - File importFile = UnitHydrographEditor.this - .displayImportFileChooser(); - if (importFile != null) { - boolean result = UnitHydrographEditor.this - .importUnitHydrographFromFile(importFile); - - if (result) { - saveChanges(); - } - } - - } - } - - // ------------------------------------------------------------------------------------- - - public void addApplyActionListener(ActionListener listener) { - _applyListenerList.add(listener); - } - - // ------------------------------------------------------------------------------------- - - private void notifyAllApplyActionListeners() { - for (int i = 0; i < _applyListenerList.size(); i++) { - ActionListener listener = (ActionListener) _applyListenerList - .get(i); - ActionEvent event = new ActionEvent(this, - ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - // ------------------------------------------------------------------------------------- - - private class RemoveButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - boolean confirm = false; - - if (_unitHydrographEntry != null) { - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete this Entry?", - "Delete Entry"); - if (confirm) // User selected YES - { - boolean addToDatabase = false; - - UnitHydrographEntryCommand deleteEntry = new UnitHydrographEntryCommand( - _unitHydrographEntry, addToDatabase); - - _uhgEntryAddModifyDeleteList.add(deleteEntry); - _uhgList.remove(_unitHydrographEntry); - _unitHydrographEntry = null; - - resortUsingTableSort(); - refreshUnitHydrographTable(); - - } - } - - setNeedsSaving(true); - } - } - - // ------------------------------------------------------------------------------------- - - private class WindowCloserListener extends WindowAdapter implements - ActionListener { - @Override - public void windowClosing(WindowEvent e) { - closeWindow(); - } - - public void actionPerformed(ActionEvent e) { - closeWindow(); - } - } - - // ------------------------------------------------------------------------------------- - - private class WindowResizeComponentListener extends ComponentAdapter { - @Override - public void componentResized(ComponentEvent e) { - int height = UnitHydrographEditor.this.getHeight(); - int width = UnitHydrographEditor.this.getWidth(); - // System.out.println( "Width/Height = [" + width + ", " + height + - // "]" ); - - if (width < MIN_WIDTH) { - UnitHydrographEditor.this.setSize(new Dimension(MIN_WIDTH, - height)); - } - if (width > MAX_WIDTH) { - UnitHydrographEditor.this.setSize(new Dimension(MAX_WIDTH, - height)); - } - if (height < MIN_HEIGHT) { - UnitHydrographEditor.this.setSize(new Dimension(width, - MIN_HEIGHT)); - } - if (height > MAX_HEIGHT) { - UnitHydrographEditor.this.setSize(new Dimension(width, - MAX_HEIGHT)); - } - - } - } - - // ------------------------------------------------------------------------------------- - - private boolean importUnitHydrographFromFile(File importFile) { - boolean result = false; - boolean addToDatabase = true; - final int newFormatTokenCount = 5; - final int oldFormatTokenCount = 4; - boolean needToAddModelType = false; - String defaultModelType = null; - - try { - BufferedReader _reader = new BufferedReader(new FileReader( - importFile)); - String line = _reader.readLine(); - if (_uhgList == null) { - _uhgList = new ArrayList(); - _uhgEntryAddModifyDeleteList = new ArrayList(); - } - - // determine if need to do something special to translate from - // original format UHG files to - // new format - - String[] initialTokenizedLine = StringParser.tokenize(line); - int tokenCount = initialTokenizedLine.length; - if (tokenCount == oldFormatTokenCount) { - // need to translate == true; - needToAddModelType = true; - defaultModelType = getModelTypeFromDialog(); - } else if (tokenCount == newFormatTokenCount) { - // things are good - } else { - String message = "Invalid file format. There are " + tokenCount - + " fields in the line instead of " - + oldFormatTokenCount + " or " + newFormatTokenCount - + " fields."; - throw new Exception(message); - } - - // read in each line and add it to the JTable - while (line != null) { - // String[] tokenizedLine = StringParser.tokenize( line ); - String[] tokenizedLine = getTokenizedLine(line, - needToAddModelType, defaultModelType); - - UnitHydrographEntry entry = new UnitHydrographEntry(); - - entry.setLocationId(_locationId); - entry.setAreaId(tokenizedLine[0]); - - // special model type name processing, tries - // to correct any misspellings or wrong case - String model = tokenizedLine[1]; - model = correctModelName(model); - entry.setModel(model); - - entry.setDur(Integer.parseInt(tokenizedLine[2])); - entry.setOrdinal(Integer.parseInt(tokenizedLine[3])); - entry.setDischarge(Double.parseDouble(tokenizedLine[4])); - - UnitHydrographEntryCommand entryCommand = new UnitHydrographEntryCommand( - entry, addToDatabase); - - // add the entry if it is not already present - if (!_uhgList.contains(entry)) { - _uhgList.add(entry); - _uhgEntryAddModifyDeleteList.add(entryCommand); - } - line = _reader.readLine(); - } - - _reader.close(); - - // everything worked, update the display - result = true; - - resortUsingTableSort(); - refreshUnitHydrographTable(); - - } catch (FileNotFoundException e) { - String errorMessage = e.getMessage(); - String title = "Import Error - File Not Found"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " - + errorMessage, title); - } catch (IOException e) { - String errorMessage = e.getMessage(); - String title = "Import Error - I/O Error"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " - + errorMessage, title); - } catch (ArrayIndexOutOfBoundsException e) { - String errorMessage = e.getMessage(); - String title = "Import Error - I/O Error"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " - + errorMessage, title); - - System.out.println("Invalid file format: " + importFile.getName()); - } catch (Exception e) { - String errorMessage = e.getMessage(); - if (errorMessage == null) { - errorMessage = "- Check for extra or incomplete lines at end of file."; - } - String title = "Import File Formatting Error"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " - + errorMessage, title); - - System.out.println("Invalid file format: " + importFile.getName()); - } - - // the import failed, so rollback any changes - // reload the uhgList and refresh the display - if (result == false) { - _uhgEntryAddModifyDeleteList.clear(); - _uhgList = loadUhgList(); - - resortUsingTableSort(); - - refreshUnitHydrographTable(); - - } - - return result; - - } - - // ------------------------------------------------------------------------------------- - private void initializeTableSort() { - - // set the initial sort to the "model" column - _lastColumnSorted = getColumnIndex("model"); - - _tableHelper.sortList(_uhgList, _lastColumnSorted, false); - - } - - // ------------------------------------------------------------------------------------- - private void resortUsingTableSort() { - _tableHelper.sortList(_uhgList, _lastColumnSorted, false); - - } - - // ------------------------------------------------------------------------------------- - private String getModelTypeFromDialog() { - String modelTypeString = null; - - String title = "Rainfall-Runoff Model Selection"; - String message = "Please enter the rainfall-runoff model\n" - + " for which this unit hydrograph is appropriate.\n" - + " "; - String comboBoxLabelString = "Rainfall-Runoff Model:"; - String[] optionArray = { "ANY ", "API-MKC", "SAC-SMA" }; - - OptionSelectionDialog dialog = new OptionSelectionDialog(); - - dialog.requestItemByDialog(title, message, comboBoxLabelString, - optionArray); - - modelTypeString = dialog.getItemString(); - - return modelTypeString; - - } - - // ------------------------------------------------------------------------------------- - - private String[] getTokenizedLine(String line, boolean needToAddModelType, - String defaultModelType) { - String header = "UnitHydrographEditor.getTokenizedLine(): "; - - if (needToAddModelType) { - StringBuffer buffer = new StringBuffer(line); - - int spacePos = buffer.indexOf(" "); - buffer.insert(spacePos, " " + defaultModelType); - - // System.out.println(header + "old line = :" + line + ":" ); - - line = buffer.toString(); - - // System.out.println(header + "new line = :" + line + ":" ); - } - - String[] tokenizedLine = StringParser.tokenize(line); - - return tokenizedLine; - } - - // ------------------------------------------------------------------------------------- - private String correctModelName(String origModelName) throws Exception { - String newModelName = null; - - String apiName = RainfallRunoffModelType.API_MKC.getName(); - String sacSmaName = RainfallRunoffModelType.SAC_SMA.getName(); - String anyName = "ANY"; - - String[] incorrectApiMkcNameArray = { "API_MKC", "APIMKC", "API MKC", - "MKCAPI", "KCAPI", "KC_API", "KC-API" }; - - String[] incorrectSacNameArray = { "SAC_SMA", "SACSMA", "SAC SMA" }; - - String[] incorrectAnyNameArray = { "default", "none" }; - - // do case correction - if (origModelName.equalsIgnoreCase(apiName)) { - newModelName = apiName; - } else if (origModelName.equalsIgnoreCase(sacSmaName)) { - newModelName = sacSmaName; - } else if (origModelName.equalsIgnoreCase(anyName)) { - newModelName = anyName; - } else // no match so far - { - boolean found = false; - - // look for common errors in typing of the model names - for (int i = 0; i < incorrectApiMkcNameArray.length && !found; i++) { - if (origModelName.equalsIgnoreCase(incorrectApiMkcNameArray[i])) { - newModelName = apiName; - found = true; - } - } - - for (int i = 0; i < incorrectSacNameArray.length && !found; i++) { - if (origModelName.equalsIgnoreCase(incorrectSacNameArray[i])) { - newModelName = sacSmaName; - found = true; - } - } - - for (int i = 0; i < incorrectAnyNameArray.length && !found; i++) { - if (origModelName.equalsIgnoreCase(incorrectAnyNameArray[i])) { - newModelName = anyName; - found = true; - } - } - - if (!found) { - newModelName = origModelName; - // String message = "Invalid modelName - " + origModelName; - // throw new Exception(message); - } - - } - - return newModelName; - - } - - // ------------------------------------------------------------------------------------- - - private File displayImportFileChooser() { - - AppsDefaults ad = AppsDefaults.getInstance(); - _importDirString = ad.getToken("whfs_import_dir"); - - // reset the import directory to the last one imported from, if it - // exists - if (_fileChooserDirectory != null) { - _importDirString = _fileChooserDirectory; - } - - JFileChooser _importFileChooser = new JFileChooser(_importDirString); - File file = null; - List filterList = new ArrayList(); - - filterList.add("UHG"); - - _importFileChooser.addChoosableFileFilter(new ExtensionFileFilter( - filterList, "Unit Hydrograph Files (UHG)")); - - int returnVal = _importFileChooser.showOpenDialog(this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - file = _importFileChooser.getSelectedFile(); - _fileChooserDirectory = file.getParentFile().getPath().toString(); - } else { - DialogHelper.displayMessageDialog(UnitHydrographEditor.this, - "Unit Hydrograph file not imported."); - } - return file; - } - - // ------------------------------------------------------------------------------------- - - private File displayExportFileChooser() { - - if (_fileChooserDirectory != null) { - _exportDirString = _fileChooserDirectory; - } else { - AppsDefaults ad = AppsDefaults.getInstance(); - _exportDirString = ad.getToken("whfs_import_dir"); // shares with - // import - // directory - } - - JFileChooser _exportFileChooser = new JFileChooser(_exportDirString); - File file = null; - List filterList = new ArrayList(); - - filterList.add("UHG"); - - _exportFileChooser.addChoosableFileFilter(new ExtensionFileFilter( - filterList, "Unit Hydrograph Files (UHG)")); - - int returnVal = _exportFileChooser.showSaveDialog(this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - file = _exportFileChooser.getSelectedFile(); - _fileChooserDirectory = file.getParentFile().getPath().toString(); - } else { - DialogHelper.displayMessageDialog(UnitHydrographEditor.this, - "Unit Hydrograph not exported."); - } - - String extension = ExtensionFileFilter.getExtension(file); - - if (file != null) { - if ((extension == null) - || (!isExtensionInExtensionFilterList(extension, filterList))) { - file = new File(file.getAbsoluteFile() + "." - + (String) filterList.get(0)); - } - } - - return file; - } - - // ------------------------------------------------------------------------------------- - - private boolean isExtensionInExtensionFilterList(String extension, - List filterList) { - boolean extensionExists = false; - - for (int i = 0; i < filterList.size(); i++) { - String ext = (String) filterList.get(i); - if (extension.equalsIgnoreCase(ext)) { - extensionExists = true; - break; - } - } - return extensionExists; - } - - // ------------------------------------------------------------------------------------- - - private class UnitHydrographEntryCommand { - private UnitHydrographEntry _uhgEntry = null; - - private boolean _addToDatabase = false; - - public UnitHydrographEntryCommand(UnitHydrographEntry entry, - boolean addToDatabase) { - _uhgEntry = entry; - _addToDatabase = addToDatabase; - } - - public void setUhgEntry(UnitHydrographEntry uhgEntry) { - _uhgEntry = uhgEntry; - } - - public UnitHydrographEntry getUhgEntry() { - return _uhgEntry; - } - - public void setAddToDatabase(boolean addToDatabase) { - _addToDatabase = addToDatabase; - } - - public boolean AddToDatabase() { - return _addToDatabase; - } - } - - // ------------------------------------------------------------------------------------- - - private void closeWindow() - /******************** - * Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - // ------------------------------------------------------------------------------------- - - private boolean isEmptyString(String testingString) - /******************** - * Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if (testingString.trim().equals("")) { - returnValue = true; - } - return returnValue; - } - - // ------------------------------------------------------------------------------------- - - private JLabel getJLabel(String label) { - JLabel returnJLabel = new JLabel(label); - returnJLabel.setFont(_labelFont); - return returnJLabel; - } - - // ------------------------------------------------------------------------------------- - - private JTextField getJTextField(int size) { - JTextField returnJTextField = new JTextField(size); - returnJTextField.setFont(_textFieldFont); - - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < size; i++) { - buffer.append("W"); - } - - returnJTextField.setText(buffer.toString()); - return returnJTextField; - } - - // ------------------------------------------------------------------------------------- - - private JFormattedTextField getJFormattedTextField(String formatString) { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( - formatString); - returnJFormattedTextField.setFont(_textFieldFont); - returnJFormattedTextField.setColumns(17); - return returnJFormattedTextField; - } - - // ------------------------------------------------------------------------------------- - - private String getFormattedValue(double valueString) { - return _decimalFormat.format(valueString); - } - - // ------------------------------------------------------------------------------------- - - public void setConnectionString(String connectionString) { - _connectionString = connectionString; - } - - // ------------------------------------------------------------------------------------- - - public String getConnectionString() { - return _connectionString; - } - - // ------------------------------------------------------------------------------------- - - public void setLogger(FileLogger logger) { - _logger = logger; - } - - // ------------------------------------------------------------------------------------- - - public FileLogger getLogger() { - return _logger; - } - - // ------------------------------------------------------------------------------------- - - public void setLocationId(String locationId) { - _locationId = locationId; - } - - // ------------------------------------------------------------------------------------- - - public String getLocationId() { - return _locationId; - } - - private boolean validateInputParameters(String[] args) { - String logDir = null; - File directory = null; - boolean returnValue = true; - - if (args.length < 3) { - System.out - .println("UnitHydrographEditor "); - returnValue = false; - } else { - _connectionString = args[0]; - - _locationId = args[1]; - - _logger = new FileLogger(args[2]); - } // end else - return returnValue; - } - - public static void main(String[] args) { - String basinId = null; - DataMgr dataMgr = null; - UnitHydrographEditor editor = new UnitHydrographEditor(); - - boolean validInputParameters = false; - - validInputParameters = editor.validateInputParameters(args); - - if (validInputParameters) { - dataMgr = new DataMgr(editor.getConnectionString(), editor - .getLogger()); - - editor = new UnitHydrographEditor(new Frame(), dataMgr, editor - .getLocationId(), true); - editor.show(); - } - -// System.exit(0); - } -} diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographEntryComparator.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographEntryComparator.java deleted file mode 100644 index 8a171c2659..0000000000 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/window/UnitHydrographEntryComparator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Created on Jun 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 14, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author SoodG -*/ -public class UnitHydrographEntryComparator extends TableColumnComparator -{ - public UnitHydrographEntryComparator() - { - } - - public int compareArea_Id( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - int result = entry1.getAreaId().compareToIgnoreCase( entry2.getAreaId() ); - return result; - } - - public int compareModel( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareStrings( entry1.getModel(), entry2.getModel() ) ); - } - - public int compareDuration( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getDur(), entry2.getDur() ) ); - } - - public int compareOrdinal( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getOrdinal(), entry2.getOrdinal() ) ); - } - - public int compareDischarge( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getDischarge(), entry2.getDischarge() ) ); - } - - - public int compare(Object object1, Object object2) - { - UnitHydrographEntry entry1 = (UnitHydrographEntry) object1; - UnitHydrographEntry entry2 = (UnitHydrographEntry) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( UnitHydrographEditor.AREA_ID ) ) - { - returnValue = compareArea_Id( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.MODEL ) ) - { - returnValue = compareModel( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.DURATION ) ) - { - returnValue = compareDuration( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.ORDINAL ) ) - { - returnValue = compareOrdinal( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.DISCHARGE ) ) - { - returnValue = compareDischarge( entry1, entry2 ); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/javaUtilities/hydro/build.ohd/.project b/javaUtilities/hydro/build.ohd/.project deleted file mode 100644 index 34eb9c45ca..0000000000 --- a/javaUtilities/hydro/build.ohd/.project +++ /dev/null @@ -1,11 +0,0 @@ - - - build.ohd - - - - - - - - diff --git a/javaUtilities/hydro/build.ohd/build-RIVERMONITOR.xml b/javaUtilities/hydro/build.ohd/build-RIVERMONITOR.xml deleted file mode 100644 index 7881ea7014..0000000000 --- a/javaUtilities/hydro/build.ohd/build-RIVERMONITOR.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/build.ohd/build-SITESPECIFIC.xml b/javaUtilities/hydro/build.ohd/build-SITESPECIFIC.xml deleted file mode 100644 index 3bb9cf8715..0000000000 --- a/javaUtilities/hydro/build.ohd/build-SITESPECIFIC.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/build.ohd/build-common.xml b/javaUtilities/hydro/build.ohd/build-common.xml deleted file mode 100644 index 69b9eba9a1..0000000000 --- a/javaUtilities/hydro/build.ohd/build-common.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/build.ohd/build.ohd.ecl b/javaUtilities/hydro/build.ohd/build.ohd.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/build.ohd/clean-ALL.xml b/javaUtilities/hydro/build.ohd/clean-ALL.xml deleted file mode 100644 index f556120cea..0000000000 --- a/javaUtilities/hydro/build.ohd/clean-ALL.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/build.ohd/dependencies.xml b/javaUtilities/hydro/build.ohd/dependencies.xml deleted file mode 100644 index be3f03e9d7..0000000000 --- a/javaUtilities/hydro/build.ohd/dependencies.xml +++ /dev/null @@ -1,630 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ------------------ ${projects.basedir} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/build.ohd/project.list b/javaUtilities/hydro/build.ohd/project.list deleted file mode 100644 index 1de38ef3be..0000000000 --- a/javaUtilities/hydro/build.ohd/project.list +++ /dev/null @@ -1,23 +0,0 @@ -build.ohd -ohd.bias_trans -ohd.common -ohd.damcrest -ohd.damcrestdb -ohd.db -ohd.dimensions_file_uploader -ohd.fcstservice -ohd.ihfsdb -ohd.lib -ohd.map -ohd.misc_dialogs -ohd.mpe -ohd.pdc_pp -ohd.prism -ohd.rax_apps -ohd.raxdb -ohd.rivermonitor -ohd.sshp -ohd.swttable -ohd.sys_monitor -ohd.tsl -ohd.var \ No newline at end of file diff --git a/javaUtilities/hydro/hydro.ecl b/javaUtilities/hydro/hydro.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.bias_trans/.classpath b/javaUtilities/hydro/ohd.bias_trans/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.bias_trans/.project b/javaUtilities/hydro/ohd.bias_trans/.project deleted file mode 100644 index bbc47d9034..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.bias_trans - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.bias_trans/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.bias_trans/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index f983104a4f..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:13:08 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.bias_trans/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.bias_trans/META-INF/MANIFEST.MF deleted file mode 100644 index a7fce3d2b0..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Bias_trans -Bundle-SymbolicName: ohd.bias_trans -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.db;bundle-version="1.0.0", - ohd.damcrest;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.bias_trans/build.properties b/javaUtilities/hydro/ohd.bias_trans/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.bias_trans/build.xml b/javaUtilities/hydro/ohd.bias_trans/build.xml deleted file mode 100644 index 82c9d732c4..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.bias_trans/ohd.bias_trans.ecl b/javaUtilities/hydro/ohd.bias_trans/ohd.bias_trans.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.bias_trans/scripts/process_rfc_bias b/javaUtilities/hydro/ohd.bias_trans/scripts/process_rfc_bias deleted file mode 100644 index dce784ff3f..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/scripts/process_rfc_bias +++ /dev/null @@ -1,100 +0,0 @@ -#!/bin/ksh -# -############################################################################### -# FILENAME: process_rfc_bias -# DESCRIPTION: This script is invoked via the message handling service (MHS) -# mechanisms. It is called when a rfc bias message file -# from a RFC is received at the local WFO. This script copies -# this file to a local directory where it is then processed -# by the process_rfc_bias program. -# -# The MHS places the incoming file in the directory: -# /data/x400/mhs/msg/hydro -# This script copies this file to the directory: -# /awips/hydroapps/precip_proc/local/data/rfc_bias_input -# -# -# The arguments to this script are provided via the -# message handling system (MHS) and are translated -# from the MHS args %ENCLOSE(1) %SUBJECT %MSGTYPE -# -# -# USAGE: process_rfc_bias filename subject_string msgtype -# -# AUTHOR: Bryon Lawrence -# CREATION DATE: April 5, 2007 -# ORGANIZATION: OHD-11/HSEB -# MACHINE/SHELL: Korn shell -# MODIFICATION HISTORY: -# DATE PROGRAMMER DESCRIPTION/REASON -# 4/5/2007 B. Lawrence Created. -################################################################################ -# - -# This allows this script to be run from outside of the bin directory -RUN_FROM_DIR=`dirname $0` - -# Set up the WHFS runtime environment -export FXA_HOME=/awips/fxa -. $FXA_HOME/readenv.sh -. $RUN_FROM_DIR/../../set_hydro_env - -export CLASSPATH=$DB_DRIVER_PATH:$PPROC_BIN/bias_trans.jar - -# Prepare the log file. -process_bias_log=`date +$PROCESS_BIAS_LOG_DIR/process_rfc_bias_%m%d` - -echo "--------------------------------------------------" >> $process_bias_log -echo "Starting process_rfc_bias as $LOGNAME at $(date -u +"%T %Z") on \ - $(date -u +"%a %b %d %Y") on $HOSTNAME" >> $process_bias_log - -FILENAME=$1 -SUBJECT=$2 -MSGTYPE=$3 - -echo "The filename supplied by the MHS: $FILENAME" >> $process_bias_log -echo "The subject line supplied by the MHS: $SUBJECT" >> $process_bias_log -echo "The type of message supplied by the MHS: $MSGTYPE" >> $process_bias_log - -# -# Use a shell function to extract the argument from the subject line -# the subject string is a quoted string with a filename, followed -# by a space, followed by the product identifier. -parseSubject() -{ - DESCRIP=$1 - PRODUCTID=$2 - return -} - -# -# Create the destination filename and path. -parseSubject $SUBJECT -DATESTR=`date -u +%m%d` -TIMESTR=`date -u +%H%M%S` -DESTINATION_FILENAME=$RFC_BIAS_INPUT_DIR/$PRODUCTID.$DATESTR.$TIMESTR - -# -# Copy the MHS rfc bias file to the rfc_bias_input directory -echo "Copying $FILENAME to $DESTINATION_FILENAME" >> $process_bias_log -cp -f $FILENAME $DESTINATION_FILENAME >> $process_bias_log 2>&1 - -if [[ $? -ne 0 ]] -then - echo "The copy of $FILENAME to $DESTINATION_FILENAME failed." >> \ - $process_bias_log - exit 1 -fi - -# -# Start the process_rfc_bias.LX program -echo "Starting the bias message reading program" >> $process_bias_log -echo "${SYS_JAVA_DIR}/bin/java ohd.hseb.bias_trans/BiasMessageReader $JDBCURL $DESTINATION_FILENAME" >> $process_bias_log - -${SYS_JAVA_DIR}/bin/java ohd.hseb.bias_trans/BiasMessageReader $JDBCURL \ - $DESTINATION_FILENAME >> $process_bias_log 2>&1 -# -# Remove the bias message file -rm -f $DESTINATION_FILENAME >> $process_bias_log 2>&1 - -exit 0 diff --git a/javaUtilities/hydro/ohd.bias_trans/scripts/transmit_rfc_bias b/javaUtilities/hydro/ohd.bias_trans/scripts/transmit_rfc_bias deleted file mode 100644 index c3674b7b5d..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/scripts/transmit_rfc_bias +++ /dev/null @@ -1,128 +0,0 @@ -#!/bin/ksh - -############################################################################### -# transmit_rfc_bias -# -# This script creates a rfc bias message and transmits it across the WAN. -# -# The office must set the PRODUCT_ID and RECIPIENTS variables at the -# beginning of this script. The PRODUCT_ID is the 10 character WMO id - -# CCCCNNNXXX. The product category (NNN) should be left as "RRM" indicating -# miscellaneous hydrologic data. For example for MARFC, the WMO id could -# be set as "KRHARRMRHA". -# -# The RECIPIENTS variable contains a comma-separated list of offices the -# RFC would like to send the bias message to. For example for MARFC, -# this list could be defined as: -# RECIPIENTS="LWX,CTP,PHI,PBZ,BGM,BUF,OKX" -# -# Usage: -# -# transmit_rfc_bias -# YYYY is the year -# MM is the month -# DD is the day -# HH is the hour -# -# Logs for this script are written to: -# /awips/hydroapps/precip_proc/local/data/log/process_bias_message -# -# Modification History -# March 26, 2007 Bryon Lawrence Script Written -# -############################################################################### -export PRODUCT_ID="CCCCRRMXXX" -export RECIPIENTS="" - -# -# Export WHFS environmental variables. -# -RUN_FROM_DIR=`dirname $0` - -# These lines are commented out because this script will be run -# from mpe_editor using mpe_editor's environment. If this script -# is run stand alone, these lines must be uncommented. -export FXA_HOME=/awips/fxa -. $FXA_HOME/readenv.sh -. $RUN_FROM_DIR/../../set_hydro_env - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH:$PPROC_BIN/bias_trans.jar - -# -# Open the log file to track the status of the transmission of the RFC Bias -# Message. -# -transmit_log=`date +$PROCESS_BIAS_LOG_DIR/transmit_rfc_bias_%m%d` - -echo "------------------------------------------------" >> $transmit_log - -Dte=`date -u` -echo "Starting transmit_rfc_bias at $Dte" >> $transmit_log - -# -# Check the mpe_transmit_bias token to make sure it is on. -# -if [[ $MPE_TRANSMIT_BIAS = "OFF" || $MPE_TRANSMIT_BIAS = "off" ]] -then - echo "Token mpe_transmit_bias is off. RFC Bias Message not generated." - exit 1 -fi - -if [[ -z "$RECIPIENTS" ]] -then - echo "No recipients specified in transmit_rfc_bias script." >> $transmit_log - exit 1 -fi - -# -# Create the RFC Bias message. -# -echo "Calling the bias message creating program" >> $transmit_log -echo "${SYS_JAVA_DIR}/bin/java/ ohd.hseb.bias_trans/BiasMessageCreator $JDBCURL $1" >> $transmit_log -${SYS_JAVA_DIR}/bin/java ohd.hseb.bias_trans/BiasMessageCreator $JDBCURL $1 \ - >> $transmit_log 2>&1 - -# -# Call distribute product and send the RFC Bias Message across the WAN. -# -FILENAME=${FXA_LOCAL_SITE}${1}z -FILEPATH=$RFC_BIAS_OUTPUT_DIR/$FILENAME - -# -# Check to make sure this file exists. -if [[ ! -a $FILEPATH ]] -then - echo "$FILEPATH does not exist." - exit 1 -fi - -SUBJECT="$FILENAME $PRODUCT_ID RADAR_PRECIP_BIAS" - -# -# Call distributeProduct for the recipients. -echo "Sending file:$FILENAME product_ID:$PRODUCT_ID to '$RECIPIENTS' via "\ - "distributeProduct" >> $transmit_log -echo "distributeProduct -c RADAR_PRECIP_BIAS -s\"$SUBJECT\" "\ - "-a\"$RECIPIENTS\" $PRODUCT_ID $FILEPATH" >> $transmit_log -/awips/fxa/bin/distributeProduct -c RADAR_PRECIP_BIAS -s "$SUBJECT" -a \ - "$RECIPIENTS" $PRODUCT_ID \ - $FILEPATH >> $transmit_log 2>&1 - -# -# Test the exit status of distributeProduct. -# -if [[ $? -ne 0 ]] -then - echo "The call to distributeProduct failed." >> $transmit_log - exit 1 -else - echo "The call to distributeProduct was successful." >> $transmit_log -fi - -# -# Remove the RFC bias message -rm -f $FILEPATH >> $transmit_log 2>&1 - -# End of script. -# diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDataMgr.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDataMgr.java deleted file mode 100644 index 947636805d..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDataMgr.java +++ /dev/null @@ -1,702 +0,0 @@ -package ohd.hseb.bias_trans; - - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.sql.*; -import java.util.*; -import ohd.hseb.db.*; -import ohd.hseb.ihfsdb.generated.*; -import ohd.hseb.util.AppsDefaults; - -/** - * - * This class is the bridge between the database and the radar bias message for the BiasMessageCreator - * and the BiasMessageReader programs. - * @author lawrence - * - */ - -public class BiasDataMgr implements RfcBiasConstants -{ - private Database _db; - - //private DataOutputStream _outFile; - private File _file; - - private String _fxaLocalSite; - private String _jdbcUrl; - private String _rfcId; - private String _fileName; - private String _outputFilePath; - - private final String RFC_BIAS_MESSAGE_DIR_TOK = "rfc_bias_output_dir"; - private final String FXA_LOCAL_SITE_TOK = "FXA_LOCAL_SITE"; - - private List _radarIdList = null; - - - public BiasDataMgr ( String jdbcUrl ) throws Exception - { - _jdbcUrl = jdbcUrl; - - _db = new Database ( ); - - // Create a database connection. - _db.connectWithDriverSearch( _jdbcUrl ); - - // Get Tokens needed for queries and to build the file path. - getBiasTokens(); - - } - - - public RadarBias getRadarBias ( String dateTime ) throws Exception - { - RadarBias radarBias = new RadarBias(); - radarBias.setDateTime(dateTime); - radarBias.setMemorySpanGroup ( getMemorySpanGroup() ); - List radarIdList = getRadarIdList ( ); - radarBias.setBiasDynGroupList ( getBiasDynGroupList ( radarIdList, dateTime ) ); - return radarBias; - } - - private DataOutputStream openOutputFile ( String dateTime ) throws FileNotFoundException - { - DataOutputStream outFile = null; - - // Create the file path - _fileName = _rfcId + dateTime + "z"; - File file = new File ( _outputFilePath, _fileName); - - // Open the bias message file. - try - { - outFile = new DataOutputStream ( new BufferedOutputStream - (new FileOutputStream( file))); - } - catch ( FileNotFoundException e) - { - System.out.println ( "Could not open file " + file.toString () ); - throw e; - } - - System.out.println ( "Opened file " + file.toString() ); - - return outFile; - } - - private DataInputStream openInputFile ( File filePath ) throws FileNotFoundException - { - DataInputStream inputStream = null; - - try - { - _file = filePath; - inputStream = new DataInputStream ( new BufferedInputStream - ( new FileInputStream ( filePath))); - } - catch ( FileNotFoundException e) - { - System.out.println ( "Could not open file " + filePath.toString() ); - throw e; - } - - System.out.println ( "Opened file " + filePath.toString ( ) ); - return inputStream; - } - - private void getBiasTokens ( ) throws Exception - { - AppsDefaults apps_defaults; - String token; - - apps_defaults = new AppsDefaults ( ); - token = apps_defaults.getToken ( RFC_BIAS_MESSAGE_DIR_TOK ); - - if ( token == null || token.length() == 0 ) - { - String message = "Token " + RFC_BIAS_MESSAGE_DIR_TOK + " not defined."; - throw new Exception( message ); - } - - _outputFilePath = token; - - token = apps_defaults.getToken( FXA_LOCAL_SITE_TOK ); - - if ( token == null || token.length() == 0 ) - { - String message = "Token " + FXA_LOCAL_SITE_TOK + " not defined."; - throw new Exception(message); - } - - _rfcId = token.toUpperCase(); - _fxaLocalSite = _rfcId; - } - - private MemorySpanGroup getMemorySpanGroup ( ) throws Exception - { - List biasStatList = null; - RWBiasStatTable biasStat = new RWBiasStatTable( _db ); - RWBiasStatRecord record = null; - MemorySpanGroup rwBiasStat = null; - - try - { - biasStatList = biasStat.select ("WHERE office_id = '" + _fxaLocalSite + "'"); - - if ( !biasStatList.isEmpty()) - { - record = (RWBiasStatRecord) biasStatList.get(0); - rwBiasStat = getRWBiasStatFromRecord(record); - } - else - { - throw new Exception ("The RWBiasStat table is empty."); - } - } - catch ( SQLException e ) - { - System.out.println( e.getMessage()); - throw e; - } - - return rwBiasStat; - } - - private List loadRadarIdList ( ) - { - // List recordList = null;; - RadarLocTable table = new RadarLocTable ( _db ); - List radarIdList = new ArrayList(); - - try - { - List recordList = table.select("WHERE use_radar = 'T' ORDER BY radid ASC"); - - // Iterator iterator = recordList.iterator(); - - // while ( iterator.hasNext()) - for (RadarLocRecord record : recordList ) - { - //RadarLocRecord record = (RadarLocRecord) iterator.next(); - radarIdList.add(record.getRadid()); - } - } - catch ( SQLException e) - { - System.out.println(e.getMessage()); - return null; - } - - if ( radarIdList.size() == 0 ) - { - System.out.println ( "No radars found in the RadarLoc table."); - } - - return radarIdList; - } - - public Set loadRadarIdSetForGivenOffice ( ) - { - List recordList = null; - RadarLocTable table = new RadarLocTable ( _db ); - Set radarIdSet = new HashSet(); - - try - { - recordList = table.select("WHERE use_radar = 'T' AND office_id = '" + _rfcId + - "' ORDER BY radid ASC"); - - Iterator iterator = recordList.iterator(); - - while ( iterator.hasNext()) - { - RadarLocRecord record = (RadarLocRecord) iterator.next(); - radarIdSet.add(record.getRadid()); - } - } - catch ( SQLException e) - { - System.out.println(e.getMessage()); - return null; - } - - if ( radarIdSet.size() == 0 ) - { - System.out.println ("No radars found for " + _rfcId + " in RadarLoc Table."); - } - - return radarIdSet; - } - - // ---------------------------------------------------------------------------------- - private List getBiasDynGroupList ( List radarIdList, String _dateTime ) - { - Iterator biasDynIterator = null; - Iterator radarIdIterator = null; - List recordList = null; - List biasDynGroupList = new ArrayList (); - RWBiasDynRecord record; - RWBiasDynTable table = new RWBiasDynTable ( _db ); - String obsTime; - String radarId; - - /* Format the obstime as YYYY-MM-DD HH:MM:SS for use in the RWBiasDyn - * query. - */ - obsTime = _dateTime.substring(0, NUM_DIGITS_IN_YEAR) + "-" + - _dateTime.substring(NUM_DIGITS_IN_YEAR,NUM_DIGITS_IN_YEAR + - NUM_DIGITS_IN_MONTH ) + "-" + - _dateTime.substring(NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH, - NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH + - NUM_DIGITS_IN_DAY) + " " + - _dateTime.substring(NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH + - NUM_DIGITS_IN_DAY, NUM_DIGITS_IN_YEAR + - NUM_DIGITS_IN_MONTH + - NUM_DIGITS_IN_DAY + - NUM_DIGITS_IN_HOUR ) + ":00:00"; - - radarIdIterator = radarIdList.iterator(); - - while ( radarIdIterator.hasNext()) - { - List biasDynSetList = new ArrayList(); - radarId = (String) radarIdIterator.next(); - - try - { - recordList = table.select ("WHERE radid='" + radarId + "' AND " + - " obstime = '" + obsTime + "' AND office_id = '" + _fxaLocalSite + - "' ORDER BY " + "memspan_ind ASC"); - - biasDynIterator = recordList.iterator(); - - while ( biasDynIterator.hasNext()) - { - record = (RWBiasDynRecord)biasDynIterator.next(); - biasDynSetList.add( getRWBiasDynFromRecord( record )); - } - - } - catch ( SQLException e) - { - System.out.println (e.getMessage()); - return null; - } - - BiasDynGroup biasDynGroup = new BiasDynGroup(); - biasDynGroup.setRadarId(radarId); - biasDynGroup.setBiasDynSetList(biasDynSetList); - biasDynGroupList.add(biasDynGroup); - } - - return biasDynGroupList; - } - - public List getRadarIdList() - { - if ( _radarIdList == null ) - { - _radarIdList = loadRadarIdList(); - } - - return _radarIdList; - } - - private MemorySpanGroup getRWBiasStatFromRecord ( RWBiasStatRecord record) - { - MemorySpanGroup rwBiasStat = new MemorySpanGroup(); - - rwBiasStat.setMinGrValueBias(record.getMin_gr_value_bias()); - rwBiasStat.setNpairBiasSelect(record.getNpair_bias_select()); - rwBiasStat.setNpairSvarUpdate(record.getNpair_svar_update()); - rwBiasStat.setNumSpan(record.getNum_span()); - rwBiasStat.setStdCut(record.getStd_cut()); - rwBiasStat.setBiasQcOpt(record.getBias_qc_opt()); - rwBiasStat.setInitSpan(record.getInit_span()); - rwBiasStat.setLagCut(record.getLag_cut()); - rwBiasStat.setMemSpan1(record.getMem_span1()); - rwBiasStat.setMemSpan2(record.getMem_span2()); - rwBiasStat.setMemSpan3(record.getMem_span3()); - rwBiasStat.setMemSpan4(record.getMem_span4()); - rwBiasStat.setMemSpan5(record.getMem_span5()); - rwBiasStat.setMemSpan6(record.getMem_span6()); - rwBiasStat.setMemSpan7(record.getMem_span7()); - rwBiasStat.setMemSpan8(record.getMem_span8()); - rwBiasStat.setMemSpan9(record.getMem_span9()); - rwBiasStat.setMemSpan10(record.getMem_span10()); - - return rwBiasStat; - } - - private BiasDynSet getRWBiasDynFromRecord ( RWBiasDynRecord record ) - { - BiasDynSet biasDynSet = new BiasDynSet(); - - biasDynSet.setMeanFieldBias(record.getBias()); - biasDynSet.setMemSpanIndex(record.getMemspan_ind()); - biasDynSet.setGageRadarPairCount(record.getNumpairs()); - biasDynSet.setSumOfGageValues(record.getSumgag()); - biasDynSet.setSumOfRadarValues(record.getSumrad()); - - return biasDynSet; - } - - public void writeRadarBiasToFile ( RadarBias radarBias, String dateTime ) throws Exception - { - //Open the file - DataOutputStream outFile = openOutputFile( dateTime ); - - //Write Header - writeHeader ( radarBias, dateTime, outFile ); - - //Write body - writeBody ( radarBias, outFile ); - - //Close File - outFile.close(); - } - - private void writeHeader ( RadarBias radarBias, String dateTime, - DataOutputStream outFile) throws IOException - { - outFile.writeUTF("BIAS"); - outFile.writeUTF(_rfcId); - outFile.writeUTF(dateTime); - MemorySpanGroup memorySpanGroup = radarBias.getMemorySpanGroup(); - outFile.writeFloat(memorySpanGroup.getMinGrValueBias()); - outFile.writeInt(memorySpanGroup.getNpairBiasSelect()); - outFile.writeInt(memorySpanGroup.getNpairSvarUpdate()); - outFile.writeInt(memorySpanGroup.getStdCut()); - outFile.writeInt(memorySpanGroup.getLagCut()); - outFile.writeInt(memorySpanGroup.getInitSpan()); - outFile.writeInt(memorySpanGroup.getBiasQcOpt()); - outFile.writeInt(memorySpanGroup.getNumSpan()); - outFile.writeFloat(memorySpanGroup.getMemSpan1()); - outFile.writeFloat(memorySpanGroup.getMemSpan2()); - outFile.writeFloat(memorySpanGroup.getMemSpan3()); - outFile.writeFloat(memorySpanGroup.getMemSpan4()); - outFile.writeFloat(memorySpanGroup.getMemSpan5()); - outFile.writeFloat(memorySpanGroup.getMemSpan6()); - outFile.writeFloat(memorySpanGroup.getMemSpan7()); - outFile.writeFloat(memorySpanGroup.getMemSpan8()); - outFile.writeFloat(memorySpanGroup.getMemSpan9()); - outFile.writeFloat(memorySpanGroup.getMemSpan10()); - } - - private void writeBody ( RadarBias radarBias, - DataOutputStream outFile) throws IOException - { - List biasDynGroupList = radarBias.getBiasDynGroupList(); - - for ( int i = 0; i < biasDynGroupList.size(); ++i ) - { - BiasDynGroup biasDynGroup = (BiasDynGroup) biasDynGroupList.get(i); - outFile.writeUTF ( biasDynGroup.getRadarId()); - - List biasDynSetList = biasDynGroup.getBiasDynSetList(); - - outFile.writeInt(biasDynSetList.size()); - - for ( int j = 0; j < biasDynSetList.size(); ++j) - { - BiasDynSet biasDynSet = (BiasDynSet) biasDynSetList.get(j); - - outFile.writeShort(biasDynSet.getMemSpanIndex()); - outFile.writeDouble(biasDynSet.getGageRadarPairCount()); - outFile.writeFloat(biasDynSet.getSumOfGageValues()); - outFile.writeFloat(biasDynSet.getSumOfRadarValues()); - outFile.writeFloat(biasDynSet.getMeanFieldBias()); - } - - } - - } - - private void readHeader ( DataInputStream inputStream, RadarBias radarBias ) throws IOException - { - String biasIndicator; - - try - { - biasIndicator = inputStream.readUTF(); - - if ( biasIndicator.compareTo("BIAS") != 0) - { - throw new IOException ( "Invalid bias message indicator field " + biasIndicator); - } - - _rfcId = inputStream.readUTF(); - - /* If, for some reason, this message originated from this office - * do not process any further. - */ - System.out.println ("RFC ID " + _rfcId + " FXA_LOCAL_SITE " + _fxaLocalSite ); - - if ( _rfcId.compareTo(_fxaLocalSite) == 0) - { - throw new IOException ( _file.getPath() + " originated from this office - " + - _fxaLocalSite + "\nThis file will not be processed." ); - } - - radarBias.setDateTime(inputStream.readUTF()); - - MemorySpanGroup memorySpanGroup = new MemorySpanGroup(); - - memorySpanGroup.setMinGrValueBias(inputStream.readFloat()); - memorySpanGroup.setNpairBiasSelect(inputStream.readInt()); - memorySpanGroup.setNpairSvarUpdate(inputStream.readInt()); - memorySpanGroup.setStdCut(inputStream.readInt()); - memorySpanGroup.setLagCut(inputStream.readInt()); - memorySpanGroup.setInitSpan(inputStream.readInt()); - memorySpanGroup.setBiasQcOpt(inputStream.readInt()); - memorySpanGroup.setNumSpan(inputStream.readInt()); - memorySpanGroup.setMemSpan1(inputStream.readFloat()); - memorySpanGroup.setMemSpan2(inputStream.readFloat()); - memorySpanGroup.setMemSpan3(inputStream.readFloat()); - memorySpanGroup.setMemSpan4(inputStream.readFloat()); - memorySpanGroup.setMemSpan5(inputStream.readFloat()); - memorySpanGroup.setMemSpan6(inputStream.readFloat()); - memorySpanGroup.setMemSpan7(inputStream.readFloat()); - memorySpanGroup.setMemSpan8(inputStream.readFloat()); - memorySpanGroup.setMemSpan9(inputStream.readFloat()); - memorySpanGroup.setMemSpan10(inputStream.readFloat()); - - radarBias.setMemorySpanGroup(memorySpanGroup); - } - catch (IOException e) - { - e.printStackTrace(); - throw e; - } - } - - /** - @param inputStream - @param radarBias - */ - private void readBody ( DataInputStream inputStream, RadarBias radarBias ) throws IOException - { - boolean completeGroup = true; - int biasSetSize; - - /*List biasDynGroupList = radarBias.getBiasDynGroupList();*/ - ArrayList biasDynGroupList = new ArrayList(); - - try - { - while ( true ) - { - BiasDynGroup biasDynGroup = new BiasDynGroup(); - - /* Read a Radar Id. Are there any left? */ - biasDynGroup.setRadarId(inputStream.readUTF()); - completeGroup = false; - biasSetSize = inputStream.readInt(); - ArrayList biasDynSetList = new ArrayList(); - - for ( int i = 0; i < biasSetSize; ++i ) - { - BiasDynSet biasDynSet = new BiasDynSet(); - biasDynSet.setMemSpanIndex(inputStream.readShort()); - biasDynSet.setGageRadarPairCount(inputStream.readDouble()); - biasDynSet.setSumOfGageValues(inputStream.readFloat()); - biasDynSet.setSumOfRadarValues(inputStream.readFloat()); - biasDynSet.setMeanFieldBias(inputStream.readFloat()); - - biasDynSetList.add(biasDynSet); - } - - completeGroup = true; - biasDynGroup.setBiasDynSetList(biasDynSetList); - biasDynGroupList.add(biasDynGroup); - } - } - catch (EOFException e) - { - if ( !completeGroup ) - { - throw new IOException ( "Error reading bias message file"); - } - - } - - radarBias.setBiasDynGroupList(biasDynGroupList); - } - - public RadarBias readRadarBiasFromFile ( File filePath ) throws Exception - { - RadarBias radarBias = new RadarBias (); - - // Attempt to open the input file. - DataInputStream inputStream = openInputFile(filePath); - - // Read the file header. - readHeader ( inputStream, radarBias ); - - // Read the file body. - readBody ( inputStream, radarBias ); - - inputStream.close(); - - return radarBias; - } - - public void writeRadarBiasToDatabase ( RadarBias radarBias ) throws Exception - { - /* Retrieve the list of offices for which to process bias information. */ - Set radarIdSet = loadRadarIdSetForGivenOffice(); - - if ( radarIdSet.size() != 0 ) - { - - /* Write to the RWBiasStat table. */ - writeMemorySpanGroup ( radarBias ); - - /* Write to the RWBiasDyn table. */ - writeBiasDynSet ( radarBias, radarIdSet ); - } - else - { - System.out.println ( "No radars to process for office " + _rfcId + "."); - } - } - - private void writeMemorySpanGroup ( RadarBias radarBias ) throws Exception - { - /* The memory span data from the RadarBias object to the - * RWBiasStat Record. - */ - RWBiasStatRecord record = null; - - try - { - RWBiasStatTable table = new RWBiasStatTable ( _db ); - record = getRecordFromMemorySpan ( radarBias.getMemorySpanGroup()); - table.insertOrUpdate(record); - } - catch (SQLException e) - { - System.out.println("Could not insert/update record in RWBiasStat table."); - throw e; - } - } - - private void writeBiasDynSet ( RadarBias radarBias, - Set radarIdSet ) throws Exception - { - RWBiasDynRecord record = null; - List biasDynGroupList = radarBias.getBiasDynGroupList(); - List biasDynSetList = null; - BiasDynSet biasDynSet = null; - - BiasDynGroup biasDynGroup = null; - - try - { - RWBiasDynTable table = new RWBiasDynTable ( _db ); - - /* Construct the obstime into the proper format. */ - String obstimeYYYYMMDD = radarBias.getDateTime(); - String obstimeSQL = obstimeYYYYMMDD.substring( 0, NUM_DIGITS_IN_YEAR) + "-" + - obstimeYYYYMMDD.substring( NUM_DIGITS_IN_YEAR,NUM_DIGITS_IN_YEAR + - NUM_DIGITS_IN_MONTH ) + "-" + - obstimeYYYYMMDD.substring( NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH, - NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH + - NUM_DIGITS_IN_DAY) + " " + - obstimeYYYYMMDD.substring( NUM_DIGITS_IN_YEAR + NUM_DIGITS_IN_MONTH + - NUM_DIGITS_IN_DAY, NUM_DIGITS_IN_YEAR + - NUM_DIGITS_IN_MONTH + - NUM_DIGITS_IN_DAY + - NUM_DIGITS_IN_HOUR ) + ":00:00"; - - for ( int i = 0; i < biasDynGroupList.size(); ++i ) - { - biasDynGroup = (BiasDynGroup) biasDynGroupList.get(i); - - /* Check if this BiasDyn group radar is in the radar map. */ - if ( radarIdSet.contains(biasDynGroup.getRadarId())) - { - biasDynSetList = biasDynGroup.getBiasDynSetList(); - - for ( int j = 0; j < biasDynSetList.size(); ++j ) - { - biasDynSet = (BiasDynSet) biasDynSetList.get(j); - record = getRecordFromBiasDynSet (biasDynGroup.getRadarId(), - obstimeSQL, biasDynSet); - table.insertOrUpdate(record); - } - } - else - { - System.out.println ( "Bias information from office " + _rfcId + - " not stored for Radar " + biasDynGroup.getRadarId() + - "."); - } - } - } - catch ( SQLException e) - { - System.out.println ( "Could not insert/update the RWBiasDynTable."); - throw e; - } - } - - private RWBiasStatRecord getRecordFromMemorySpan ( MemorySpanGroup memorySpanGroup ) - { - RWBiasStatRecord record = new RWBiasStatRecord ( ); - - record.setBias_qc_opt(memorySpanGroup.getBiasQcOpt()); - record.setInit_span(memorySpanGroup.getInitSpan()); - record.setLag_cut(memorySpanGroup.getLagCut()); - record.setMem_span1(memorySpanGroup.getMemSpan1()); - record.setMem_span2(memorySpanGroup.getMemSpan2()); - record.setMem_span3(memorySpanGroup.getMemSpan3()); - record.setMem_span4(memorySpanGroup.getMemSpan4()); - record.setMem_span5(memorySpanGroup.getMemSpan5()); - record.setMem_span6(memorySpanGroup.getMemSpan6()); - record.setMem_span7(memorySpanGroup.getMemSpan7()); - record.setMem_span8(memorySpanGroup.getMemSpan8()); - record.setMem_span9(memorySpanGroup.getMemSpan9()); - record.setMem_span10(memorySpanGroup.getMemSpan10()); - record.setMin_gr_value_bias(memorySpanGroup.getMinGrValueBias()); - record.setNpair_bias_select(memorySpanGroup.getNpairBiasSelect()); - record.setNpair_svar_update(memorySpanGroup.getNpairSvarUpdate()); - record.setNum_span(memorySpanGroup.getNumSpan()); - record.setStd_cut(memorySpanGroup.getStdCut()); - record.setOffice_id(_rfcId); - - return record; - } - - private RWBiasDynRecord getRecordFromBiasDynSet ( String radarId, - String obstimeSQL, - BiasDynSet biasDynSet ) - { - RWBiasDynRecord record = new RWBiasDynRecord(); - - record.setBias(biasDynSet.getMeanFieldBias()); - record.setMemspan_ind(biasDynSet.getMemSpanIndex()); - record.setNumpairs(biasDynSet.getGageRadarPairCount()); - record.setObstime(DbTimeHelper.getLongTimeFromDateTimeString(obstimeSQL)); - record.setRadid(radarId); - record.setSumgag(biasDynSet.getSumOfGageValues()); - record.setSumrad(biasDynSet.getSumOfRadarValues()); - record.setOffice_id(_rfcId); - - return record; - } -} - - - - diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDynGroup.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDynGroup.java deleted file mode 100644 index 1619c3baab..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDynGroup.java +++ /dev/null @@ -1,46 +0,0 @@ -package ohd.hseb.bias_trans; -import java.util.*; - -public class BiasDynGroup -{ - private String _radarId; - private List _biasDynSetList; - - public BiasDynGroup ( ) - { - } - - public void setRadarId(String radarId) - { - _radarId = radarId; - } - - public String getRadarId() - { - return _radarId; - } - - public void setBiasDynSetList(List biasDynSetList) - { - _biasDynSetList = biasDynSetList; - } - - public List getBiasDynSetList() - { - return _biasDynSetList; - } - - public String toString () - { - - StringBuffer outputBuffer = new StringBuffer ("_radarId = " + _radarId +"\n"); - - - for ( int i = 0; i < _biasDynSetList.size(); ++i ) - { - outputBuffer.append ( _biasDynSetList.get(i)); - } - - return outputBuffer.toString(); - } -} diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDynSet.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDynSet.java deleted file mode 100644 index f72d832e8c..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasDynSet.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.bias_trans; - -public class BiasDynSet -{ - private short _memSpanIndex; /* usually 0 - 9. */ - private double _gageRadarPairCount; - private float _sumOfGageValues; - private float _sumOfRadarValues; - private float _meanFieldBias; - - public void setMemSpanIndex(short memSpanIndex) - { - _memSpanIndex = memSpanIndex; - } - - public short getMemSpanIndex() - { - return _memSpanIndex; - } - - public void setGageRadarPairCount(double numPairs) - { - _gageRadarPairCount = numPairs; - } - - public double getGageRadarPairCount() - { - return _gageRadarPairCount; - } - - public void setSumOfGageValues(float sumGag) - { - _sumOfGageValues = sumGag; - } - - public float getSumOfGageValues() - { - return _sumOfGageValues; - } - - public void setSumOfRadarValues(float sumRad) - { - _sumOfRadarValues = sumRad; - } - - public float getSumOfRadarValues() - { - return _sumOfRadarValues; - } - - public void setMeanFieldBias(float bias) - { - _meanFieldBias = bias; - } - - public float getMeanFieldBias() - { - return _meanFieldBias; - } - - public String toString () - { - String output = "_memspanInd = " + _memSpanIndex + " _numPairs = " + _gageRadarPairCount + " " + - " _sumGag = " + _sumOfGageValues + " _sumRad = " + _sumOfRadarValues + " _bias = " + _meanFieldBias + "\n"; - return output; - } - -} diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasMessageCreator.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasMessageCreator.java deleted file mode 100644 index 81674c6b6e..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasMessageCreator.java +++ /dev/null @@ -1,123 +0,0 @@ -package ohd.hseb.bias_trans; - -import ohd.hseb.util.CodeTimer; -import ohd.hseb.db.*; - -public class BiasMessageCreator -{ - public static final String VERSION = "OB82"; - public static final String RELEASE_DATE = "April 11, 2007"; - public static final String PROGRAM_NAME = "BiasMessageCreator"; - - private static final String _usage = "Usage: " + PROGRAM_NAME + - " "; - - private BiasDataMgr _dataMgr = null; - - private String _dateTime; // YYYYMMDDHH - private String _jdbcUrl; - // ----------------------------------------------------------------------------------------------------- - - public BiasMessageCreator ( String[] args ) throws Exception - { - getBiasArguments ( args ); - - // Create the data manager - setDataMgr( new BiasDataMgr ( _jdbcUrl )); - } - // ----------------------------------------------------------------------------------------------------- - - private void getBiasArguments ( String args [ ]) throws Exception - { - boolean failed = false; - int datetimeAsInteger; - - if ( args.length != 2) - { - failed = true; - } - else - { - - // Process the database name supplied as the first argument. - _jdbcUrl = args[0]; - _dateTime = args[1]; - - // Make sure the time string is the correct length. - if ( _dateTime.length() != RfcBiasConstants.DATEHOUR_LENGTH ) - { - failed = true; - } - - // Make sure the time string is an integer. - try - { - datetimeAsInteger = Integer.parseInt(_dateTime); - } - catch ( NumberFormatException e) - { - failed = true; - } - } - - if ( failed ) - { - throw new Exception (_usage); - } - } - // ----------------------------------------------------------------------------------------------------- - - private void setDataMgr(BiasDataMgr dataMgr) - { - _dataMgr = dataMgr; - } - // ----------------------------------------------------------------------------------------------------- - - private BiasDataMgr getDataMgr() - { - return _dataMgr; - } - // ----------------------------------------------------------------------------------------------------- - - public void process () throws Exception - { - RadarBias radarBias = _dataMgr.getRadarBias( _dateTime ); - - System.out.println ("Bias Message Retrieved.\n" + radarBias ); - - _dataMgr.writeRadarBiasToFile ( radarBias, _dateTime ); - } - // ----------------------------------------------------------------------------------------------------- - /** - * @param args - */ - public static void main(String[] args) - { - long startingTime = System.currentTimeMillis(); - String startingTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startingTime); - - System.out.println("The Starting Time is: " + startingTimeString); - try - { - CodeTimer codeTimer = new CodeTimer(); - codeTimer.start(); - - BiasMessageCreator messageCreator = new BiasMessageCreator( args); - - System.out.println("Starting Program " + PROGRAM_NAME ); - System.out.println("Version: " + VERSION + " Release Date: " + - RELEASE_DATE ); - - messageCreator.process(); - - codeTimer.stop("Create_rfc_bias_message completed in "); - - } - catch ( Exception e) - { - - System.out.println (e.getMessage()); - System.out.println (e.getStackTrace()); - } - } -} diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasMessageReader.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasMessageReader.java deleted file mode 100644 index 22ff9439c3..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/BiasMessageReader.java +++ /dev/null @@ -1,106 +0,0 @@ -package ohd.hseb.bias_trans; - -import java.io.File; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; - -public class BiasMessageReader -{ - private static final String VERSION = "OB82"; - private static final String RELEASE_DATE = "April 11, 2007"; - private static final String PROGRAM_NAME = "BiasMessageReader"; - - private static final String _usage = "Usage: " + PROGRAM_NAME + - " "; - - private BiasDataMgr _dataMgr = null; - private String _jdbcUrl = null; - private File _filePath = null; - - public BiasMessageReader ( String[] args, String PROGRAM_NAME ) throws Exception - { - getBiasArguments ( args, PROGRAM_NAME); - - // Create the data manager - setDataMgr( new BiasDataMgr ( _jdbcUrl )); - } - - /** - * @param args - */ - private void getBiasArguments ( String args [ ], final String program_name ) throws Exception - { - boolean failed = false; - - if (args.length != 2) - { - failed = true; - } - else - { - // Process the database name supplied via the -d argument. - _jdbcUrl = args[0]; - - // Process the filename/path supplied via the -f argument. - - _filePath = new File ( args[1] ); - System.out.println ("File path for file reader = " + _filePath); - } - - if ( failed ) - { - throw new Exception (_usage); - } - } - - public void process ( ) throws Exception - { - RadarBias radarBias = _dataMgr.readRadarBiasFromFile ( _filePath ); - - System.out.println ("Bias Message Retrieved.\n" + radarBias ); - - _dataMgr.writeRadarBiasToDatabase ( radarBias ); - } - - public static void main(String[] args) - { - long startingTime = System.currentTimeMillis(); - String startingTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startingTime); - System.out.println("The Starting Time is: " + startingTimeString); - - try - { - CodeTimer codeTimer = new CodeTimer(); - codeTimer.start(); - - BiasMessageReader messageReader = new BiasMessageReader( args, PROGRAM_NAME); - - System.out.println("Starting Program " + PROGRAM_NAME ); - System.out.println("Version: " + VERSION + " Release Date: " + - RELEASE_DATE ); - - messageReader.process(); - - codeTimer.stop("process_rfc_bias_message completed in "); - } - catch ( Exception e) - { - System.out.println (e.getMessage()); - System.out.println (e.getStackTrace()); - } - - } - - public void setDataMgr(BiasDataMgr dataMgr) - { - _dataMgr = dataMgr; - } - - public BiasDataMgr getDataMgr() - { - return _dataMgr; - } - -} - diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/MemorySpanGroup.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/MemorySpanGroup.java deleted file mode 100644 index dd2aed58f8..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/MemorySpanGroup.java +++ /dev/null @@ -1,224 +0,0 @@ -package ohd.hseb.bias_trans; - -public class MemorySpanGroup -{ - private float _minGrValueBias; - private int _npairBiasSelect; - private int _npairSvarUpdate; - private int _stdCut; - private int _lagCut; - private int _initSpan; - private int _biasQcOpt; - private int _numSpan; - private float _memSpan1; - private float _memSpan2; - private float _memSpan3; - private float _memSpan4; - private float _memSpan5; - private float _memSpan6; - private float _memSpan7; - private float _memSpan8; - private float _memSpan9; - private float _memSpan10; - - public MemorySpanGroup ( ) - { - } - - public void setMinGrValueBias(float minGrValueBias) - { - this._minGrValueBias = minGrValueBias; - } - public float getMinGrValueBias() - { - return _minGrValueBias; - } - - public void setNpairBiasSelect(int npairBiasSelect) - { - this._npairBiasSelect = npairBiasSelect; - } - - public int getNpairBiasSelect() - { - return _npairBiasSelect; - } - - public void setNpairSvarUpdate(int npairSvarUpdate) - { - this._npairSvarUpdate = npairSvarUpdate; - } - - public int getNpairSvarUpdate() - { - return _npairSvarUpdate; - } - - public void setStdCut(int stdCut) - { - this._stdCut = stdCut; - } - - public int getStdCut() - { - return _stdCut; - } - - public void setLagCut(int lagCut) - { - this._lagCut = lagCut; - } - - public int getLagCut() - { - return _lagCut; - } - - public void setInitSpan(int initSpan) - { - this._initSpan = initSpan; - } - - public int getInitSpan() - { - return _initSpan; - } - - public void setBiasQcOpt(int biasQcOpt) - { - this._biasQcOpt = biasQcOpt; - } - - public int getBiasQcOpt() - { - return _biasQcOpt; - } - - public void setNumSpan(int numSpan) - { - this._numSpan = numSpan; - } - - public int getNumSpan() - { - return _numSpan; - } - - public void setMemSpan1(float memSpan1) - { - this._memSpan1 = memSpan1; - } - - public float getMemSpan1() - { - return _memSpan1; - } - - public void setMemSpan2(float memSpan2) - { - this._memSpan2 = memSpan2; - } - - public float getMemSpan2() - { - return _memSpan2; - } - - public void setMemSpan3(float memSpan3) - { - this._memSpan3 = memSpan3; - } - - public float getMemSpan3() - { - return _memSpan3; - } - - public void setMemSpan4(float memSpan4) - { - this._memSpan4 = memSpan4; - } - - public float getMemSpan4() - { - return _memSpan4; - } - - public void setMemSpan5(float memSpan5) - { - this._memSpan5 = memSpan5; - } - - public float getMemSpan5() - { - return _memSpan5; - } - - public void setMemSpan6(float memSpan6) - { - this._memSpan6 = memSpan6; - } - - public float getMemSpan6() - { - return _memSpan6; - } - - public void setMemSpan7(float memSpan7) - { - this._memSpan7 = memSpan7; - } - - public float getMemSpan7() - { - return _memSpan7; - } - - public void setMemSpan8(float memSpan8) - { - this._memSpan8 = memSpan8; - } - - public float getMemSpan8() - { - return _memSpan8; - } - - public void setMemSpan9(float memSpan9) - { - this._memSpan9 = memSpan9; - } - - public float getMemSpan9() - { - return _memSpan9; - } - - public void setMemSpan10(float memSpan10) - { - this._memSpan10 = memSpan10; - } - - public float getMemSpan10() - { - return _memSpan10; - } - - public String toString ( ) - { - String output; - output = "Memory Span Info:\n"; - output += "_minGrValueBias = " + _minGrValueBias + "\n" + "_npairBiasSelect = " + _npairBiasSelect +"\n"; - output += "_npairSvarUpdate = " + _npairSvarUpdate + "\n" + "_stdCut = " + _stdCut + "\n"; - output += "_lagCut = " + _lagCut + "\n" + "_initSpan = " + _initSpan + "\n"; - output += "_biasQcOpt = " + _biasQcOpt + "\n" + "_numSpan = " + _numSpan + "\n"; - output += "_memSpan1 = " + _memSpan1 + "\n" + "_memSpan2 = " + _memSpan2 + "\n"; - output += "_memSpan3 = " + _memSpan3 + "\n" + "_memSpan4 = " + _memSpan4 + "\n"; - output += "_memSpan5 = " + _memSpan5 + "\n" + "_memSpan6 = " + _memSpan6 + "\n"; - output += "_memSpan7 = " + _memSpan7 + "\n" + "_memSpan8 = " + _memSpan8 + "\n"; - output += "_memSpan9 = " + _memSpan9 + "\n" + "_memSpan10 = " + _memSpan10 + "\n"; - - return output; - } - -} diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RadarBias.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RadarBias.java deleted file mode 100644 index 2b9585ed93..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RadarBias.java +++ /dev/null @@ -1,53 +0,0 @@ -package ohd.hseb.bias_trans; - -import java.util.*; - -public class RadarBias -{ - private String _dateTime; - private MemorySpanGroup _memorySpanGroup; - private List _biasDynGroupList; - - public void setMemorySpanGroup(MemorySpanGroup memorySpanGroup) - { - _memorySpanGroup = memorySpanGroup; - } - - public MemorySpanGroup getMemorySpanGroup() - { - return _memorySpanGroup; - } - - public void setBiasDynGroupList(List biasDynGroupList) - { - _biasDynGroupList = biasDynGroupList; - } - - public List getBiasDynGroupList() - { - return _biasDynGroupList; - } - - public String toString () - { - String output ="Radar Bias Info: " + "\nDate:" + _dateTime +"\n" + _memorySpanGroup; - - for ( int i = 0; i < _biasDynGroupList.size(); ++i ) - { - output += _biasDynGroupList.get(i); - } - - return output; - } - - public void setDateTime(String dateTime) - { - _dateTime = dateTime; - } - - public String getDateTime() - { - return _dateTime; - } - -} diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RfcBiasConstants.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RfcBiasConstants.java deleted file mode 100644 index 1cd499ad85..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RfcBiasConstants.java +++ /dev/null @@ -1,10 +0,0 @@ -package ohd.hseb.bias_trans; - -public interface RfcBiasConstants -{ - public final int DATEHOUR_LENGTH = 10; - public final int NUM_DIGITS_IN_YEAR = 4; - public final int NUM_DIGITS_IN_MONTH = 2; - public final int NUM_DIGITS_IN_DAY = 2; - public final int NUM_DIGITS_IN_HOUR = 2; -} diff --git a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RfcBiasMessage.java b/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RfcBiasMessage.java deleted file mode 100644 index f4af3361d6..0000000000 --- a/javaUtilities/hydro/ohd.bias_trans/src/ohd/hseb/bias_trans/RfcBiasMessage.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.bias_trans; - - -public class RfcBiasMessage implements RfcBiasConstants -{ - - public RfcBiasMessage ( ) - { - } - - int write_bias_message ( BiasDataMgr dataMgr ) - { - - write_bias_message_header ( dataMgr ); - - // Retrieve the list of radars to get bias information for. - write_bias_message_header ( dataMgr ); - write_bias_message_body ( dataMgr ); - - return 0; - } - - private int write_bias_message_header ( BiasDataMgr dataMgr ) - { - return 0; - } - - private int write_bias_message_body ( BiasDataMgr dataMgr ) - { - return 0; - } - -} diff --git a/javaUtilities/hydro/ohd.common/.classpath b/javaUtilities/hydro/ohd.common/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.common/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.common/.project b/javaUtilities/hydro/ohd.common/.project deleted file mode 100644 index a31c8a1be7..0000000000 --- a/javaUtilities/hydro/ohd.common/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.common - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.common/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.common/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index e426b53538..0000000000 --- a/javaUtilities/hydro/ohd.common/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:10:32 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.common/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.common/META-INF/MANIFEST.MF deleted file mode 100644 index b72982fdcd..0000000000 --- a/javaUtilities/hydro/ohd.common/META-INF/MANIFEST.MF +++ /dev/null @@ -1,24 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Common -Bundle-SymbolicName: ohd.common -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.db;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" -Export-Package: ohd.hseb.geomap.contour, - ohd.hseb.geomap.model, - ohd.hseb.geomap.projection, - ohd.hseb.grid, - ohd.hseb.measurement, - ohd.hseb.model, - ohd.hseb.model.mkcapi, - ohd.hseb.model.sacsma, - ohd.hseb.util, - ohd.hseb.util.gui, - ohd.hseb.util.gui.drawing, - ohd.hseb.util.gui.jchecktree, - ohd.hseb.util.gui.jtable, - ohd.hseb.util.gui.jtable.example, - ohd.hseb.util.io, - ohd.hseb.util.test diff --git a/javaUtilities/hydro/ohd.common/build.properties b/javaUtilities/hydro/ohd.common/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.common/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.common/build.xml b/javaUtilities/hydro/ohd.common/build.xml deleted file mode 100644 index 6cc3bd813a..0000000000 --- a/javaUtilities/hydro/ohd.common/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.common/ohd.common.ecl b/javaUtilities/hydro/ohd.common/ohd.common.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/ContourGrid.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/ContourGrid.java deleted file mode 100644 index 224abbb440..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/ContourGrid.java +++ /dev/null @@ -1,19 +0,0 @@ -package ohd.hseb.geomap.contour; - -/** - * - * @author cgobs - * This is an interface for a 2-D (row * col) non-jagged array that contains doubles. - */ -public interface ContourGrid -{ - - double getValue(int row, int col); - void setValue(int row, int col, double value); - - double[][] getValuesArray(); - - int getRowCount(); - int getColCount(); - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/Interpolator.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/Interpolator.java deleted file mode 100644 index 7de2651e56..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/Interpolator.java +++ /dev/null @@ -1,23 +0,0 @@ -package ohd.hseb.geomap.contour; - -public class Interpolator -{ -// ----------------------------------------------------------------------------------------- - public Interpolator() - { - - } -// ----------------------------------------------------------------------------------------- - public double interpolate(double targetX, double x1, double y1, double x2, double y2) - { - double slope = (y2 - y1) / (x2 - x1); - double intercept = (y1) - (slope*x1); - - double y = (slope*targetX) + intercept; - - return y; - } - - // ----------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/RowColToLatLonTranslator.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/RowColToLatLonTranslator.java deleted file mode 100644 index beffac740a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/RowColToLatLonTranslator.java +++ /dev/null @@ -1,15 +0,0 @@ -package ohd.hseb.geomap.contour; - -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.RowColumnPoint; - -public interface RowColToLatLonTranslator -{ - - LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint); - LatLonPoint getLatLonPoint(double row, double col); - -// RowColumnPoint getRowColumnPoint(double lat, double lon); - RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint); - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/RowToLatLonContourer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/RowToLatLonContourer.java deleted file mode 100644 index 6db8f5438f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/contour/RowToLatLonContourer.java +++ /dev/null @@ -1,254 +0,0 @@ -package ohd.hseb.geomap.contour; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.Range; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.model.RowColumnPoint; - -public class RowToLatLonContourer -{ - private double[][] _valueArray; - private int _rowCount = 0; - private int _colCount = 0; - - private RowColToLatLonTranslator _positionTranslator = null; - - // -------------------------------------------------------------------------------------------- - public RowToLatLonContourer(short [][] valueArray, RowColToLatLonTranslator translator ) - { - this (getDoubleArrayFromShortArray(valueArray), translator); - } - // -------------------------------------------------------------------------------------------- - public RowToLatLonContourer(ContourGrid grid, RowColToLatLonTranslator translator) - { - this (grid.getValuesArray(), translator); - } - - // -------------------------------------------------------------------------------------------- - - - public RowToLatLonContourer(double [][] valueArray, RowColToLatLonTranslator translator) - { - setValueArray(valueArray); - - _rowCount = valueArray.length; - if (_rowCount > 0) - { - _colCount = valueArray[0].length; - } - - _positionTranslator = translator; - - } - - - // -------------------------------------------------------------------------------------------- - private static double[][] getDoubleArrayFromShortArray(short[][] shortArray) - { - int rowCount = shortArray.length; - int colCount = 0; - if (rowCount > 0) - { - colCount = shortArray[0].length; - } - - double[][] doubleArray = new double[rowCount][colCount]; - for (int row = 0; row < rowCount; row ++) - { - for (int col = 0; col < colCount; col++) - { - doubleArray[row][col] = shortArray[row][col]; - } - } - - return doubleArray; - } - // -------------------------------------------------------------------------------------------- - - public void setValueArray(double[][] valueArray) - { - _valueArray = valueArray; - } - - // -------------------------------------------------------------------------------------------- - - public double[][] getValueArray() - { - return _valueArray; - } - - // -------------------------------------------------------------------------------------------- - - public double getValue(int row, int col) - { - // System.out.println("row = " + row + " col = " + col); - return _valueArray[row][col]; - } - - // -------------------------------------------------------------------------------------------- - public List< List > contour(double[] levelArray) - { - List< List > listOfLatLonPolylineLists = new ArrayList >(); - - for (int i = 0; i < levelArray.length; i++) - { - List polylineList = contourOneLevel(levelArray[i]); - listOfLatLonPolylineLists.add(polylineList); - } - - return listOfLatLonPolylineLists; - } - - // -------------------------------------------------------------------------------------------- - - public List contourOneLevel(double level) - { - List polylineList = new ArrayList(); - - LatLonPoint previousPoint = null; - - for (int row = 0; row < _rowCount; row++) - { - for (int col = 0; col < _colCount; col++) - { - - List pointList = getPointsFromFourCells(level, row, col); //eliminate duplicate points - if (pointList.size() > 0) - { - LatLonPolyline polyline = new LatLonPolyline(pointList); - polylineList.add(polyline); - } - } - } - - return polylineList; - } - // -------------------------------------------------------------------------------------------- - private List getPointsFromFourCells(double level, int row, int col) - { - String header = "RowToLatLonContourer.getPointsFromFourCells(): "; - List latLonPointList = new ArrayList (); - LatLonPoint point = null; - - if (col < _colCount - 1) - { - point = getCrossOverLatLonPoint(level, row, col, row, col+1); - addPointToListIfNotNull(latLonPointList, point); - - if (row < _rowCount - 1) - { - point = getCrossOverLatLonPoint(level, row, col+1, row+1, col+1); - addPointToListIfNotNull(latLonPointList, point); - - - point = getCrossOverLatLonPoint(level, row+1, col+1, row+1, col); - addPointToListIfNotNull(latLonPointList, point); - - } - - } - if (row < _rowCount - 1) - { - point = getCrossOverLatLonPoint(level, row+1, col, row, col); - addPointToListIfNotNull(latLonPointList, point); - - } - if (latLonPointList.size() == 1) - { - latLonPointList.clear(); - System.out.println(header + "clearing list of its single point"); - } - return latLonPointList; - } - // -------------------------------------------------------------------------------------------- - private LatLonPoint getCrossOverLatLonPoint(double level, - int row1, int col1, - int row2, int col2) - { - LatLonPoint point = null; - - double value1 = getValue(row1, col1); - double value2 = getValue(row2, col2); - Range range = new Range(value1, value2); - - if (range.isBetweenInclusive(level)) - { - if (value1 == value2) //ignore it, this is counterintuitive, but needed - { - //do nothing - } - else //there is a distinct boundary and value1 != value2 - { - LatLonPoint latLonPoint1 = getLatLonPoint(row1, col1); - LatLonPoint latLonPoint2 = getLatLonPoint(row2, col2); - - LatLonPoint interpolatedPoint = interpolate(level, latLonPoint1, value1, latLonPoint2, value2); - point = interpolatedPoint; - } - - } - return point; - } - - // -------------------------------------------------------------------------------------------- - private LatLonPoint interpolate(double targetValue, - LatLonPoint point1, double value1, - LatLonPoint point2, double value2) - { - // String header = "RowToLatLonContourer.interpolate(): "; - - Interpolator interpolator = new Interpolator(); - - double lat1 = point1.getLat(); - double lat2 = point2.getLat(); - - double lon1 = point1.getLon(); - double lon2 = point2.getLon(); - - -// these are switched from the usual order, since we are seeking lat and lon instead of value - double interpolatedLat = interpolator.interpolate(targetValue, value1, lat1, value2, lat2); - double interpolatedLon = interpolator.interpolate(targetValue, value1, lon1, value2, lon2); - - LatLonPoint newPoint = new LatLonPoint(interpolatedLat, interpolatedLon); - - RowColumnPoint rcPoint = getRowColumnPoint(newPoint); - // System.out.println(header + rcPoint ); - - return newPoint; - } - - // -------------------------------------------------------------------------------------------- - - private LatLonPoint getLatLonPoint(int row, int col) - { - - LatLonPoint point = _positionTranslator.getLatLonPoint(new RowColumnPoint(row, col)); - - return point; - } - - // -------------------------------------------------------------------------------------------- - private RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - RowColumnPoint point = _positionTranslator.getRowColumnPoint(latLonPoint); - - return point; - } - - // -------------------------------------------------------------------------------------------- - private void addPointToListIfNotNull(List pointList, LatLonPoint point) - { - if (point != null) - { - pointList.add(point); - } - - return; - } - // -------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/DrawableShape.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/DrawableShape.java deleted file mode 100644 index 41fd568515..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/DrawableShape.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.geomap.model; - -public interface DrawableShape -{ - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/ElevationMap.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/ElevationMap.java deleted file mode 100644 index 727f64106a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/ElevationMap.java +++ /dev/null @@ -1,228 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; - -public class ElevationMap implements RowColToLatLonTranslator -{ - private LatLonBounds _latLonBounds = null; - private double _latResInDegrees = 0; - private double _lonResInDegrees = 0; - - private short[][] _valueArray = null; - private int _rowCount = 0; - private int _colCount = 0; - // ---------------------------------------------------------------------------------------------------------------------- - public ElevationMap(LatLonBounds latLonBounds, double latResInDegrees, double lonResInDegrees) - { - _latLonBounds = new LatLonBounds(latLonBounds); - setLatResInDegrees(latResInDegrees); - setLonResInDegrees(lonResInDegrees); - - _rowCount = (int) Math.ceil(latLonBounds.getLatDifference() / latResInDegrees); - _colCount = (int) Math.ceil(latLonBounds.getLonDifference() / lonResInDegrees); - - _valueArray = new short[getRowCount()][getColCount()]; - } - // ------------------------------------------------------------------------------ - public void setLatLonBounds(LatLonBounds latLonBounds) - { - _latLonBounds = latLonBounds; - } - // ------------------------------------------------------------------------------ - - public LatLonBounds getLatLonBounds() - { - return _latLonBounds; - } - // ------------------------------------------------------------------------------ - - public List getLatLonPointList() - { - return new ArrayList(); - } - // ------------------------------------------------------------------------------ - - public void setLatResInDegrees(double latResInDegrees) - { - _latResInDegrees = latResInDegrees; - } - - public double getLatResInDegrees() - { - return _latResInDegrees; - } - - public void setLonResInDegrees(double lonResInDegrees) - { - _lonResInDegrees = lonResInDegrees; - } - - public double getLonResInDegrees() - { - return _lonResInDegrees; - } - // ------------------------------------------------------------------------------ - public RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - double row = getRow(latLonPoint.getLat()); - double col = getCol(latLonPoint.getLon()); - - return new RowColumnPoint(row, col); - } - // ------------------------------------------------------------------------------ - public LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint) - { - double lat = getLat((int) rowColumnPoint.getRow()); - double lon = getLon((int) rowColumnPoint.getCol()); - - return new LatLonPoint(lat, lon); - } - // ------------------------------------------------------------------------------ - public LatLonPoint getLatLonPoint(double row, double col) - { - double lat = getLat((int) row); - double lon = getLon((int) col); - - return new LatLonPoint(lat, lon); - } - - // ------------------------------------------------------------------------------ - - public int getRow(double lat) - { - int row = -1; - - double latDiff = _latLonBounds.getNorthLat() - lat; - row = (int) Math.ceil(latDiff / getLatResInDegrees()); - - return row; - } - // ------------------------------------------------------------------------------ - public int getCol(double lon) - { - int col = -1; - - double lonDiff = lon - _latLonBounds.getWestLon(); - col = (int) Math.ceil(lonDiff / getLonResInDegrees()); - - return col; - } - // ------------------------------------------------------------------------------ - public double getLat(int row) - { - double lat = _latLonBounds.getNorthLat() - (row * getLatResInDegrees()); - - return lat; - } - // ------------------------------------------------------------------------------ - public double getLon(int col) - { - double lon = _latLonBounds.getWestLon() + (col * getLonResInDegrees()); - - return lon; - } - // ------------------------------------------------------------------------------ - - - public void setValueByLatLon(double lat, double lon, short value) - { - - setValue(getRow(lat), getCol(lon), value); - } - - // ------------------------------------------------------------------------------ - public void setValue(int row, int col, short value) - { - - _valueArray[row][col] = value; - } - - // ------------------------------------------------------------------------------ - public short[][] getValueArray() - { - return _valueArray; - } - // ------------------------------------------------------------------------------ - public short getValue(int row, int col) - { - short value = 0; - - if (isInRange(row, col)) - { - value = _valueArray[row][col]; - } - return value; - } - - private boolean isInRange(int row, int col) - { - boolean result = false; - if ((row >-1) && - (row < getRowCount()) && - (col >-1) && - (col < getColCount()) ) - { - result = true; - } - - return result; - } - - public short getValueByLatLon(double lat, double lon) - { - int row = getRow(lat); - int col = getCol(lon); - - return getValue(row, col); - } - - // ------------------------------------------------------------------------------ - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getLatLonBounds() + "lat res = " + getLatResInDegrees() + " lon res = " + getLonResInDegrees()); - - int rowCount = getRowCount(); - int colCount = getColCount(); - - for (int row = 0; row < rowCount; row++) - { - for (int col = 0; col < colCount; col++) - { - buffer.append(_valueArray[row][col] + " "); - } - buffer.append("\n"); - } - - return buffer.toString(); - } - - // ------------------------------------------------------------------------------ - - - public void setRowCount(int rowCount) - { - _rowCount = rowCount; - } - public int getRowCount() - { - return _rowCount; - } - public void setColCount(int colCount) - { - _colCount = colCount; - } - public int getColCount() - { - return _colCount; - } - - - // ------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/HrapRowColToLatLonConverter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/HrapRowColToLatLonConverter.java deleted file mode 100644 index 18c777b083..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/HrapRowColToLatLonConverter.java +++ /dev/null @@ -1,207 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; - -public class HrapRowColToLatLonConverter implements RowColToLatLonTranslator -{ - - private static double RADIANS_PER_DEGREE = 0.017453293; - private static double DEGREES_PER_RADIAN = 57.29577951; - private static double EARTH_RADIUS = 6371.2; - private static double MESH_LEN = 4.7625; - private static double STDLAT = 60; - private static double STDLON = 105; - - // public static int LOCAL_HRAP_ROWS = 131; - // public static int LOCAL_HRAP_COLS = 131; - - private int _baseNationalRow = 0; - private int _baseNationalColumn = 0; - - private Map _latLonCache = new HashMap(); - - // ------------------------------------------------------------------------------------------------- - /** - * This class translates between local Hrap grid locations and Lat-Lon corrdinates. - * It uses the baseNationalRow and the baseNationalColumn for this - */ - - public HrapRowColToLatLonConverter(int baseNationalRow, int baseNationalColumn) - { - _baseNationalRow = baseNationalRow; - _baseNationalColumn = baseNationalColumn; - } - // ------------------------------------------------------------------------------------------------- - - public RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - return getRowColumnPoint(latLonPoint.getLat(), latLonPoint.getLon()); - } - - // ------------------------------------------------------------------------------------------------- - - public RowColumnPoint getRowColumnPoint(double lat, double lon) - { - - double tlat, re; - double latrad, lonrad; - double r; - double x, y; - - tlat = STDLAT * RADIANS_PER_DEGREE; - - re = (EARTH_RADIUS * (1. + Math.sin(tlat))) / MESH_LEN; - latrad = lat * RADIANS_PER_DEGREE; - lonrad = (lon + 180. - STDLON) * RADIANS_PER_DEGREE; - - r = re * Math.cos(latrad) / (1. + Math.sin(latrad)); - x = r * Math.sin(lonrad); - y = r * Math.cos(lonrad); - - double col = x + 401.; - double row = y + 1601.; - - col -= getBaseNationalColumn(); - row -= getBaseNationalRow(); - - return new RowColumnPoint(row, col); - - } - // ------------------------------------------------------------------------------------------------- - public static RowColumnPoint getNationalRowColumnPoint(LatLonPoint latLonPoint) - { - return getNationalRowColumnPoint(latLonPoint.getLat(), latLonPoint.getLon()); - } - - // ------------------------------------------------------------------------------------------------- - - public static RowColumnPoint getNationalRowColumnPoint(double lat, double lon) - { - - double tlat, re; - double latrad, lonrad; - double r; - double x, y; - - tlat = STDLAT * RADIANS_PER_DEGREE; - - re = (EARTH_RADIUS * (1. + Math.sin(tlat))) / MESH_LEN; - latrad = lat * RADIANS_PER_DEGREE; - lonrad = (lon + 180. - STDLON) * RADIANS_PER_DEGREE; - - r = re * Math.cos(latrad) / (1. + Math.sin(latrad)); - x = r * Math.sin(lonrad); - y = r * Math.cos(lonrad); - - double col = x + 401.; - double row = y + 1601.; - - return new RowColumnPoint(row, col); - - } - // ------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint) - { - - return getLatLonPoint(rowColumnPoint.getRow(), rowColumnPoint.getCol()); - } - - // ------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPointOld(double row, double col) - { - - RowColumnPoint rowColumnPoint = new RowColumnPoint(row, col); - LatLonPoint latLonPoint = _latLonCache.get(rowColumnPoint); - - if (latLonPoint == null ) - { - latLonPoint = calculateLatLonPoint(row, col); - _latLonCache.put(rowColumnPoint, latLonPoint); - } - - return latLonPoint; - } - - // ------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPoint(double row, double col) - { - - return calculateLatLonPoint(row, col); - } - // ------------------------------------------------------------------------------------------------- - - public LatLonPoint calculateLatLonPoint(double row, double col) - { - - row = row + getBaseNationalRow(); - col = col + getBaseNationalColumn(); - - - double x, y; - double rr, gi; - double ang, tlat; - - double lat = 0; - double lon = 0; - - tlat = 60.0 / DEGREES_PER_RADIAN; - - x = col - 401.; - y = row - 1601.; - - rr = (x * x) + (y * y); - gi = ((EARTH_RADIUS * (1 + Math.sin(tlat)))/MESH_LEN); - gi = gi * gi; - - lat = Math.asin((gi - rr) / (gi + rr)) * DEGREES_PER_RADIAN; - - ang = Math.atan2(y, x) * DEGREES_PER_RADIAN; - - if (ang < 0) - ang=ang + 360.; - - lon = 270 + STDLON - ang; - - if (lon < 0) - lon += 360.; - - if (lon > 360) - lon -= 360.; - - lon *= -1.0; - - - return new LatLonPoint(lat, lon); - } - // ------------------------------------------------------------------------------------------------- - - private void setBaseNationalRow(int baseNationalRow) - { - _baseNationalRow = baseNationalRow; - } - // ------------------------------------------------------------------------------------------------- - - private int getBaseNationalRow() - { - return _baseNationalRow; - } - // ------------------------------------------------------------------------------------------------- - - private void setBaseNationalColumn(int baseNationalColumn) - { - _baseNationalColumn = baseNationalColumn; - } - // ------------------------------------------------------------------------------------------------- - - private int getBaseNationalColumn() - { - return _baseNationalColumn; - } - - // ------------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonBounds.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonBounds.java deleted file mode 100644 index dd37ee69a7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonBounds.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.geomap.model; - -public class LatLonBounds -{ - private double _northLat = 0; - private double _southLat = 0; - private double _westLon = 0; - private double _eastLon = 0; - - // ----------------------------------------------------------------------------------------------------------- - - public LatLonBounds(double northLat, double southLat, double westLon, double eastLon) - { - setNorthLat(northLat); - setSouthLat(southLat); - setWestLon(westLon); - setEastLon(eastLon); - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - public LatLonBounds(LatLonPoint northWestLatLong, LatLonPoint southEastLatLong) - { - setNorthLat(northWestLatLong.getLat()); - setSouthLat(southEastLatLong.getLat()); - setWestLon(northWestLatLong.getLon()); - setEastLon(southEastLatLong.getLon()); - } - // ----------------------------------------------------------------------------------------------------------- - - public LatLonBounds(LatLonBounds origBounds) - { - setNorthLat(origBounds.getNorthLat()); - setSouthLat(origBounds.getSouthLat()); - setWestLon(origBounds.getWestLon()); - setEastLon(origBounds.getEastLon()); - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setNorthLat(double northLat) - { - _northLat = northLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getNorthLat() - { - return _northLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeNorthLat(double changeAmount) - { - _northLat += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setSouthLat(double southLat) - { - _southLat = southLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getSouthLat() - { - return _southLat; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeSouthLat(double changeAmount) - { - _southLat += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setWestLon(double westLon) - { - _westLon = westLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getWestLon() - { - return _westLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeWestLon(double changeAmount) - { - _westLon += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public void setEastLon(double eastLon) - { - _eastLon = eastLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getEastLon() - { - return _eastLon; - } - // ----------------------------------------------------------------------------------------------------------- - - public void changeEastLon(double changeAmount) - { - _eastLon += changeAmount; - } - // ----------------------------------------------------------------------------------------------------------- - - public double getLatDifference() - { - return getNorthLat() - getSouthLat(); - } - - // ----------------------------------------------------------------------------------------------------------- - public double getLonDifference() - { - return getEastLon() - getWestLon(); - } - - // ----------------------------------------------------------------------------------------------------------- - - - public void updateLatLonBounds(float lat1, float lat2, - float lon1, float lon2) - { - updateLatitude(lat1); - updateLatitude(lat2); - - updateLongitude(lon1); - updateLongitude(lon2); - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - private void updateLatitude(float lat) - { - if (lat > getNorthLat()) - { - setNorthLat(lat); - } - if (lat < getSouthLat()) - { - setSouthLat(lat); - } - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - private void updateLongitude(float lon) - { - if (lon < getWestLon()) - { - setWestLon(lon); - } - if (lon > getEastLon()) - { - setEastLon(lon); - } - - return; - } - // ----------------------------------------------------------------------------------------------------------- - - public boolean equals(Object object) - { - boolean result = false; - - LatLonBounds otherBounds = (LatLonBounds) object; - if ( - (getNorthLat() == otherBounds.getNorthLat() ) && - (getSouthLat() == otherBounds.getSouthLat() ) && - (getEastLon() == otherBounds.getEastLon()) && - (getWestLon() == otherBounds.getWestLon() ) - ) - { - result = true; - } - - return result; - } - // ----------------------------------------------------------------------------------------------------------- - - public String toString() - { - String string = getNorthLat() + "," + getWestLon() + " to " + getSouthLat() + ", " + getEastLon(); - return string; - - } - // ----------------------------------------------------------------------------------------------------------- - -} //end class LatLonBounds diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonPoint.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonPoint.java deleted file mode 100644 index 36bd83347c..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonPoint.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.geomap.model; - -public class LatLonPoint implements DrawableShape -{ - private double _lat; - private double _lon; - - - public LatLonPoint(double lat, double lon) - { - setLat(lat); - setLon(lon); - } - - public void setLat(double lat) - { - _lat = lat; - } - - public double getLat() - { - return _lat; - } - - public void changeLat(double changeAmount) - { - _lat += changeAmount; - - } - - public void setLon(double lon) - { - _lon = lon; - } - - public double getLon() - { - return _lon; - } - - public void changeLon(double changeAmount) - { - _lon += changeAmount; - } - - public boolean equals(LatLonPoint point) - { - double tolerance = 0.000000001; - - boolean result = false; - - double latDiff = Math.abs(getLat() - point.getLat()); - double lonDiff = Math.abs(getLon() - point.getLon()); - - if ( (latDiff < tolerance) && (lonDiff < tolerance)) - { - result = true; - } - - return result; - } - - public String toString() - { - - return String.format("lat = %5.2f , lon = %5.2f ", _lat, _lon); - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonPolyline.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonPolyline.java deleted file mode 100644 index 0098fea749..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/LatLonPolyline.java +++ /dev/null @@ -1,73 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.ArrayList; -import java.util.List; - - -public class LatLonPolyline implements DrawableShape -{ - List _pointList = null; - - - public LatLonPolyline() - { - _pointList = new ArrayList(); - } - - public LatLonPolyline(List pointList) - { - _pointList = pointList; - } - - public void addPoint(LatLonPoint point) - { - _pointList.add(point); - } - - public void addPointList(List pointList) - { - _pointList.addAll(pointList); - } - - public List getPointList() - { - return _pointList; - } - - public boolean equals(LatLonPolyline line) - { - boolean result = false; - - if (_pointList.size() == line.getPointList().size()) - { - result = true; - for (int i = 0; i < _pointList.size(); i++) - { - LatLonPoint point1 = _pointList.get(i); - LatLonPoint point2 = line.getPointList().get(i); - if (! point1.equals(point2) ) - { - result = false; - break; - } - } - } - - - return result; - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - for (LatLonPoint point: _pointList) - { - buffer.append(point.toString()); - } - - return buffer.toString(); - - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/Polygon.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/Polygon.java deleted file mode 100644 index 03877d597f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/Polygon.java +++ /dev/null @@ -1,19 +0,0 @@ -package ohd.hseb.geomap.model; - -import java.util.ArrayList; -import java.util.List; - -public class Polygon implements DrawableShape -{ - List _pointList = new ArrayList(); - - public Polygon(List pointList) - { - _pointList = pointList; - } - - public List getPointList() - { - return _pointList; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/RowColumnPoint.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/RowColumnPoint.java deleted file mode 100644 index 84b8ffa6da..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/model/RowColumnPoint.java +++ /dev/null @@ -1,51 +0,0 @@ -package ohd.hseb.geomap.model; - -public class RowColumnPoint -{ - private double _row = 0; - private double _column = 0; - - // ----------------------------------------------------------------------------------------- - public RowColumnPoint(double row, double column) - { - setRow(row); - setColumn(column); - } - - // ----------------------------------------------------------------------------------------- - - public void setRow(double row) - { - _row = row; - } - - // ----------------------------------------------------------------------------------------- - - public double getRow() - { - return _row; - } - - // ----------------------------------------------------------------------------------------- - - public void setColumn(double column) - { - _column = column; - } - - // ----------------------------------------------------------------------------------------- - - public double getCol() - { - return _column; - } - - // ----------------------------------------------------------------------------------------- - - public String toString() - { - return "row = " + getRow() + " col = " + getCol(); - } - // ----------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/BaseMapProjection.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/BaseMapProjection.java deleted file mode 100644 index 55445355d8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/BaseMapProjection.java +++ /dev/null @@ -1,377 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; - - -public abstract class BaseMapProjection implements MapProjection -{ - protected static double RADIANS_PER_DEGREE = 0.017453292519943295 ; - protected static double DEGREES_PER_RADIAN = 1.0/RADIANS_PER_DEGREE ; - protected static double NAUTICAL_MILES_PER_DEGREE = 60; - - - private int _mapWidth = 0; - private int _mapHeight = 0; - - - private LatLonBounds _latLonBounds = null; - private double _mapScaleFactor = 90; //degrees per/ pixel - private LatLonPoint _centerLatLon = null; - - // ----------------------------------------------------------------------------------- - - protected int getOffsetX() - { - return getMapWidth() / 2; - } - - protected int getOffsetY() - { - return getMapHeight() / 2; - } - - /* - - -float zoom_multiple = 1.0 ; -float original_zoom_multiple = 1.0 ; -long orig_scale_factor; -long init_scale_factor; -long map_scale_factor; -static int MAXX = 0 ; -static int MAXY = 0 ; -int offsetx,offsety; -int polar_offsety = 0 ; // Used for keeping track of the y-offset of the - // HRAP and Polar Stereographic map projection. -int polar_offsetx = 0 ; // Used for keeping track of the x-offset of the - // HRAP projection. -int projection=M_FLAT; -int prev_projection=M_FLAT; -static int XOR = 0 ; -static int YOR = 0 ; -int zoom_scale = 1; - -float map_center_lat=33.0; -float map_center_lon=-114.0; -float original_center_lat ; -float original_center_lon ; -float top_lat,left_lon; -float width_in_nmi = 0.0 ; -float dtr = 0.017453292519943295 ; -float init_top_lat , init_width ; -int init_offsetx , init_zoom ; -float region_llat = -999.0 , - region_llon = -999.0 , - region_rlat = -999.0 , - region_rlon = -999.0 ; - -static MotifCallback pan_routine = NULL ; -static MotifCallback zoom_routine = NULL ; - - - */ - - abstract public LatLonPoint getLatLonPoint(Point screenPoint); - abstract public LatLonPoint getLatLonPoint(int x, int y); - - - abstract public Point getScreenPoint(LatLonPoint latlonPoint); - abstract public Point getScreenPoint(double lat, double lon); - - public boolean isInRange(double lat, double lon) - { - String header = "BaseMapProjection.isInRange()"; - boolean result = false; - LatLonBounds bounds = getLatLonBounds(); - - if (bounds.getNorthLat() == bounds.getSouthLat()) - { - System.out.println(header + " north and sound bounds are the same."); - } - - if ( - - (lat <= bounds.getNorthLat()) && - (lat >= bounds.getSouthLat()) && - (lon >= bounds.getEastLon()) && - (lon <= bounds.getWestLon()) - ) - { - result = true; - System.out.println(header + "finally, something is in range to be drawn"); - } - - return result; - } - - - // ---------------------------------------------------------------- - - public List getLatLonPointList(List screenCoordList) - { - List latLonPointList = new ArrayList(); - - for (Point screenPoint : screenCoordList) - { - LatLonPoint latLonPoint = getLatLonPoint(screenPoint); - latLonPointList.add(latLonPoint); - } - - return null; - } - - // ---------------------------------------------------------------- - - public List getScreenPointList(List latLongCoordinateList) - { - List screenPointList = new ArrayList(); - - for (LatLonPoint latLonPoint : latLongCoordinateList) - { - Point screenPoint = getScreenPoint(latLonPoint); - screenPointList.add(screenPoint); - } - - return screenPointList; - } - - //------------------------------------------------------------------------------------------------- - - - - protected void init(float displayWidthInNauticalMiles) - { - double degreesLongitude ; - - int offsetx = getOffsetX(); - int offsety = getOffsetY(); - - double mapCenterLat = getCenterLatLon().getLat(); - - degreesLongitude = displayWidthInNauticalMiles / - ( NAUTICAL_MILES_PER_DEGREE * Math.cos ( mapCenterLat * RADIANS_PER_DEGREE ) ) ; - - double map_scale_factor = ( long ) ( 2.0 * ( float ) getOffsetX() / degreesLongitude ) ; - - //Compute the top latitude and the left longitude. - LatLonPoint northWestLatLong = getLatLonPoint(new Point(0,0)); - _latLonBounds.setNorthLat(northWestLatLong.getLat()); - _latLonBounds.setWestLon(northWestLatLong.getLon()); - - /* - init_scale_factor = map_scale_factor ; - orig_scale_factor = init_scale_factor ; - init_top_lat = top_lat ; - init_width = width_in_nmi ; - init_offsetx = offsetx ; - */ - } - - // ---------------------------------------------------------------- - /* - - void _init_map_variables ( float nmi ) - { - float degrees_lon ; - projection = M_FLAT ; - width_in_nmi = nmi ; - - offsetx = _get_map_width ( 0 ) / 2 ; - offsety = _get_map_height ( 0 ) / 2 ; - - // New logic added by Bryon Lawrence on January 15, 2002. This is an - // attempt to incorporate an initial measurement in nautical miles into - // the initial computation of the scale factor. - degrees_lon = width_in_nmi / - ( ( float ) NUM_NMI_PER_DEGREE * cos ( map_center_lat * dtr ) ) ; - map_scale_factor = ( long ) ( 2.0 * ( float ) offsetx / degrees_lon ) ; - - //Compute the top latitude and the left longitude. - - mConvertXY2LatLon(0,0,&top_lat,&left_lon) ; - init_scale_factor = map_scale_factor ; - orig_scale_factor = init_scale_factor ; - init_top_lat = top_lat ; - init_width = width_in_nmi ; - init_offsetx = offsetx ; - } - - */ - - // ---------------------------------------------------------------- - - public void setLatLonBounds(LatLonBounds latLonBounds) - { - String header = "BaseMapProjection.setLatLonBounds(): "; - System.out.println(header); - - _latLonBounds = new LatLonBounds(latLonBounds); - - setCenterInternally(); - } - - private void setCenterInternally() - { - String header = "BaseMapProjection.setCenterInternally(): "; - System.out.println(header); - LatLonBounds bounds = getLatLonBounds(); - - double lat = (bounds.getNorthLat() + bounds.getSouthLat())/2.0 ; - double lon = (bounds.getEastLon() + bounds.getWestLon())/2.0 ; - - _centerLatLon = new LatLonPoint(lat, lon); - } - - private void setLatLonBoundsInternally() - { - String header = "BaseMapProjection.setLatLonBoundsInternally(): "; - - LatLonPoint centerPoint = getCenterLatLon(); - double pixelsPerDegree = getMapScaleFactor(); - - double latOffset = getOffsetY() / pixelsPerDegree; - double lonOffset = getOffsetX() / pixelsPerDegree; - - System.out.println(header + " latOffset = " + latOffset); - System.out.println(header + " lonOffset = " + lonOffset); - - double northLat = centerPoint.getLat() + latOffset; - double southLat = centerPoint.getLat() - latOffset; - - double westLat = centerPoint.getLon() - lonOffset; - double eastLat = centerPoint.getLon() + lonOffset; - - _latLonBounds = new LatLonBounds(northLat,southLat, westLat, eastLat); - - System.out.println(header + " latLonBounds = " + _latLonBounds); - - } - - // ---------------------------------------------------------------- - public LatLonBounds getLatLonBounds() - { - return _latLonBounds; - } - // ---------------------------------------------------------------- - - public void setMapHeight(int mapHeight) - { - _mapHeight = mapHeight; - setLatLonBoundsInternally(); - } - // ---------------------------------------------------------------- - - public int getMapHeight() - { - return _mapHeight; - - } - - //------------------------------------------------------------------------------------------------- - - public void panProportionally(double northSouthPanProportion, double eastWestPanProportion) - { - String header = "BaseMapProjection.panProportionally(): "; - // System.out.println(header + "northSouthPanProportion = " + northSouthPanProportion + - // " eastWestPanProportion = " + eastWestPanProportion); - - LatLonBounds latLonBounds = getLatLonBounds(); - double panLatAmount = northSouthPanProportion * latLonBounds.getLatDifference(); - double panLonAmount = eastWestPanProportion * latLonBounds.getLonDifference(); - - System.out.println(header + "latLonBounds.getLatDifference() = " + latLonBounds.getLatDifference() + - " latLonBounds.getLonDifference() = " + latLonBounds.getLonDifference()); - - - changeCenter(panLatAmount, panLonAmount); - - return; - } - - //------------------------------------------------------------------------------------------------- - - public void changeCenter(double changeLatAmount, double changeLonAmount) - { - - String header = "BaseMapProjection.changeCenter(): "; - System.out.println(header + "changeLatAmount " + changeLatAmount); - System.out.println(header + "changeLonAmount " + changeLonAmount); - - _centerLatLon.changeLat(changeLatAmount); - _centerLatLon.changeLon(changeLonAmount); - - System.out.println(header + "new center = " + _centerLatLon); - System.out.println(header + "mapScaleFactor = " + getMapScaleFactor()); - - - setLatLonBoundsInternally(); - } - //------------------------------------------------------------------------------------------------- - - public LatLonPoint getCenterLatLon() - { - return _centerLatLon; - } - - //------------------------------------------------------------------------------------------------- - - public void setCenterLatLon(LatLonPoint newCenter) - { - String header = "BaseMapProjection.setCenterLatLon(): "; - - LatLonPoint oldCenter = getCenterLatLon(); - - _centerLatLon = newCenter; - - System.out.println(header + "oldCenter = " + oldCenter + " newCenter = " + newCenter); - System.out.println(header + "width " + getMapWidth() + " height = " + getMapHeight()); - - - setLatLonBoundsInternally(); - - return; - } - - // ---------------------------------------------------------------- - - public void setMapScaleFactor(double mapScaleFactor) - { - _mapScaleFactor = mapScaleFactor; - } - // ---------------------------------------------------------------- - - public double getMapScaleFactor() - { - return _mapScaleFactor; - } - - // ---------------------------------------------------------------- - public void setMapWidthAndHeight(int mapWidth, int mapHeight) - { - _mapWidth = mapWidth; - _mapHeight = mapHeight; - setLatLonBoundsInternally(); - } - - public void setMapWidth(int mapWidth) - { - _mapWidth = mapWidth; - setLatLonBoundsInternally(); - } - - // ---------------------------------------------------------------- - - public int getMapWidth() - { - return _mapWidth; - } - - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/FlatMapProjection.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/FlatMapProjection.java deleted file mode 100644 index cc6048a945..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/FlatMapProjection.java +++ /dev/null @@ -1,84 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; - -import ohd.hseb.geomap.model.LatLonPoint; - -// ------------------------------------------------------------------------------------------ -public class FlatMapProjection extends BaseMapProjection -{ - -// ------------------------------------------------------------------------------------------ - - - public FlatMapProjection (LatLonPoint centerLatLonPoint) - { - setCenterLatLon(centerLatLonPoint); - } - - - public LatLonPoint getLatLonPoint(int x, int y) - { - double lat = 0.0; - double lon = 0.0; - - double mapCenterLon = getCenterLatLon().getLon(); - double mapCenterLat = getCenterLatLon().getLat(); - - lon = ( ( ( double ) (x - getOffsetX()) / getMapScaleFactor() ) + mapCenterLon) ; - lat = mapCenterLat - ( ( double ) ( y - getOffsetY() ) / getMapScaleFactor() ) ; - - LatLonPoint point = new LatLonPoint(lat, lon); - - return point; - } - - - //------------------------------------------------------------------------------------------------- - public LatLonPoint getLatLonPoint(Point screenPoint) - { - - int x = screenPoint.x; - int y = screenPoint.y; - - return getLatLonPoint(x, y); - } - //------------------------------------------------------------------------------------------------- - - public Point getScreenPoint(LatLonPoint latLonPoint) - { - - double lat = latLonPoint.getLat(); - double lon = latLonPoint.getLon(); - - return getScreenPoint(lat, lon); - - } - -// ------------------------------------------------------------------------------------------------- - - public Point getScreenPoint(double lat, double lon) - { - - double mapCenterLat = getCenterLatLon().getLat(); - double mapCenterLon = getCenterLatLon().getLon(); - - if (mapCenterLon > 0 && lon < 0) - lon = lon + 360; - - if (mapCenterLon < 0 && lon > 0) - lon = lon - 360; - - int x = (int) ((lon - mapCenterLon) * getMapScaleFactor() ) + getOffsetX(); - int y = (int) ( getOffsetY() - ((lat - mapCenterLat) * getMapScaleFactor() ) ); - - - - return new Point(x,y); - } - - //------------------------------------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/MapProjection.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/MapProjection.java deleted file mode 100644 index cbb269b6a2..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/MapProjection.java +++ /dev/null @@ -1,43 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; - -public interface MapProjection -{ - void setMapScaleFactor(double mapScaleFactor); - double getMapScaleFactor(); - - int getMapWidth(); - void setMapWidth(int mapWidth); - - int getMapHeight(); - void setMapHeight(int mapHeight); - - //configuration methods - void setLatLonBounds(LatLonBounds latLonBounds); - LatLonBounds getLatLonBounds(); - - void panProportionally(double northSouthPanProportion, double eastWestPanProportion); - - void setCenterLatLon(LatLonPoint centerLatLong); - LatLonPoint getCenterLatLon(); - - //useful methods - - boolean isInRange(double lat, double lon); - - LatLonPoint getLatLonPoint(Point screenPoint); - LatLonPoint getLatLonPoint(int x, int y); - List getLatLonPointList(List screenCoordList); - - Point getScreenPoint(LatLonPoint latlonPoint); - Point getScreenPoint(double lat, double lon); - - List getScreenPointList(List latLonPointList); - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/PolarProjection.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/PolarProjection.java deleted file mode 100644 index 821873aa03..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/geomap/projection/PolarProjection.java +++ /dev/null @@ -1,95 +0,0 @@ -package ohd.hseb.geomap.projection; - -import java.awt.Point; - -import ohd.hseb.geomap.model.LatLonPoint; - -public class PolarProjection extends BaseMapProjection -{ - - - public PolarProjection(LatLonPoint centerLatLonPoint, double mapScaleFactor) - { - setCenterLatLon(centerLatLonPoint); - setMapScaleFactor(mapScaleFactor); - } - - @Override - public LatLonPoint getLatLonPoint(Point screenPoint) - { - return getLatLonPoint(screenPoint.x, screenPoint.y); - } - - @Override - public LatLonPoint getLatLonPoint(int x, int y) - { - - double c; - double py; - double px; - double p; - - /* Be sure to take into account any panning/recentering effects. */ - x = x - getOffsetX(); - y = (-1 * y) + getOffsetY(); - - py = (double)y; - px = (double)x; - - double lon = ((getCenterLatLon().getLon() * RADIANS_PER_DEGREE) + Math.atan2(py,px)) * DEGREES_PER_RADIAN + 90.0; - - p = Math.pow(((px*px) + (py*py)),0.5); - c = 2.0 * Math.atan(p/(2.0 * ( double ) getMapScaleFactor())); - - double lat = Math.asin(Math.cos(c) * Math.sin((90.0 *RADIANS_PER_DEGREE)) + - (py * Math.sin(c) * Math.cos((90.0 * RADIANS_PER_DEGREE))/p)) * DEGREES_PER_RADIAN; - - - - - return new LatLonPoint(lat, lon); - } - - @Override - public Point getScreenPoint(LatLonPoint latLonPoint) - { - return getScreenPoint(latLonPoint.getLat(), latLonPoint.getLon()); - } - - @Override - public Point getScreenPoint(double lat, double lon) - { - double k; - double temp; - double centerLon; - - int x = 0; - int y = 0; - - lat = lat * RADIANS_PER_DEGREE; - lon = lon * RADIANS_PER_DEGREE; - centerLon = getCenterLatLon().getLon() * RADIANS_PER_DEGREE; - - temp = 1 + Math.sin(lat); - - if (temp == 0.0) - { - System.out.println("Error\n"); - } - else - { - k = getMapScaleFactor(); - - double tangentTerm = 2.0 * k * Math.tan((Math.PI /4.0) - (lat / 2.0)) ; - - temp = tangentTerm * Math.sin(lon - centerLon); - x = (int)temp + getOffsetX(); - - temp = -tangentTerm * Math.cos(lon - centerLon); - y = getOffsetY() - (int)temp; - } - - return new Point(x, y); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/grid/XmrgGrid.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/grid/XmrgGrid.java deleted file mode 100644 index 97d041e531..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/grid/XmrgGrid.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Created on May 24, 2004 - * - * - */ -package ohd.hseb.grid; - - -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; - -/** - * @author GobsC - * - * - */ -public class XmrgGrid -{ - public static final double OFF_GRID_VALUE = -8888.0; - private double _missingValue = -999.0; - - private long _time = 0; - -// old way of storing grid - private Map _valueMap = null; - // private List _valueList = null; - - -//new way of storing grid - private double[][] _gridValuesArray = null; - - private boolean _isValid = true; - - - private int _rowCount = 0; - private int _colCount = 0; - - private int _baseRow = 0; //southern row - private int _baseCol = 0; // western col - - - // private boolean _newWay = true; - - -// ----------------------------------------------------------------------------------- - private XmrgGrid() - { - _isValid = true; - } - -// ----------------------------------------------------------------------------------- - public static XmrgGrid getInvalidGrid(long time) - { - XmrgGrid grid = new XmrgGrid(time); - - grid.setIsValid(false); - - return grid; - } - - -// ----------------------------------------------------------------------------------- - - public XmrgGrid(long time) - { - _time = time; - _valueMap = new HashMap(); - // _valueList = new ArrayList(); - - } - - // ----------------------------------------------------------------------------------- - - public XmrgGrid(long time, int southernRowIndex, int westernColIndex, - int rowCount, int colCount) - { - - _time = time; - - // new way - _rowCount = rowCount; - _colCount = colCount; - - _baseRow = southernRowIndex; - _baseCol = westernColIndex; - - _gridValuesArray = new double[_rowCount][_colCount]; - - return; - } - -// ----------------------------------------------------------------------------------- - - public void setValue(int hrapRow, int hrapCol, double value) - { - int rowIndex = hrapRow - _baseRow; - int colIndex = hrapCol - _baseCol; - - _gridValuesArray[rowIndex][colIndex] = value; - - return; - } -// ----------------------------------------------------------------------------------- - - public double[][] getValuesArray() - { - return _gridValuesArray; - } - -// ----------------------------------------------------------------------------------- - - public double getValue(int hrapRow, int hrapCol) - { - int rowIndex = hrapRow - _baseRow; - int colIndex = hrapCol - _baseCol; - - double value = OFF_GRID_VALUE; - - //Chip CHANGE 8/23/05 - if ( - (rowIndex > -1) && (rowIndex < _rowCount) && - (colIndex > -1) && (colIndex < _colCount) - ) - { - value = _gridValuesArray[rowIndex][colIndex]; - } - else - { - - // System.out.println("XmrgGrid.getValue(): attempting to access " + - // "rowIndex = " + rowIndex + " colIndex = " + colIndex); - - // System.out.print(" Row Values should be >= 0 < " + _rowCount); - // System.out.println(" and column values should be >= 0 < " + _colCount); - - } - return value; - } - // ----------------------------------------------------------------------------------- - - public void setTime(long time) - { - _time = time; - } -// ----------------------------------------------------------------------------------- - - public long getTime() - { - return _time; - } - -// ----------------------------------------------------------------------------------- - private Object getKey(int hrapRow, int hrapCol) - { - Long key = new Long(hrapRow*10000 + hrapCol); - - return key; - } - -// ----------------------------------------------------------------------------------- - public String toString() - { - StringBuffer buffer = new StringBuffer(); - // String outString = null; - double value = 0; - - - buffer.append("time = " + DbTimeHelper.getDateTimeStringFromLongTime(_time) + "\n"); - /* - for (int i = 0; i < _valueList.size(); i++) - { - String keyValue = (String) _valueList.get(i); - StringTokenizer tokenizer = new StringTokenizer(keyValue, "|"); - - - while (tokenizer.hasMoreTokens()) - { - String hrapRow = tokenizer.nextToken(); - String hrapCol = tokenizer.nextToken(); - String valueString = tokenizer.nextToken(); - value = Double.parseDouble(valueString); - - if (value > 0.0) - { - buffer.append("hrapRow = " + hrapRow + " hrapCol = " + hrapCol + " value = " + value + "\n"); - } - - } - - } - */ - return buffer.toString(); - - } -// ----------------------------------------------------------------------------------- - - public void setIsValid(boolean isValid) - { - _isValid = isValid; - } -// ----------------------------------------------------------------------------------- - - public boolean isValid() - { - return _isValid; - } - - private void setBaseRow(int baseRow) - { - _baseRow = baseRow; - } - - public int getBaseRow() - { - return _baseRow; - } - - private void setBaseCol(int baseCol) - { - _baseCol = baseCol; - } - - public int getBaseCol() - { - return _baseCol; - } - - public int getRowCount() - { - return _rowCount; - } - - public int getColCount() - { - return _colCount; - } - -// ----------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/AbsTimeMeasurement.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/AbsTimeMeasurement.java deleted file mode 100644 index 87ad2ac30d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/AbsTimeMeasurement.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Created on Aug 25, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.measurement; - -import java.text.*; -import java.util.*; - -/** - * @author GobsC - * - * - */ -public class AbsTimeMeasurement extends Measurement -{ - private long _time; // the time the measurement was taken - - // ***************************************************************************** - public AbsTimeMeasurement(Measurement measurement, long timeInMillis) - { - super(measurement); - _time = timeInMillis; - - return; - } - -// ***************************************************************************** - - public AbsTimeMeasurement(double value, long timeInMillis, MeasuringUnit unit) - { - super(value, unit); - _time = timeInMillis; - - return; - } - - // ***************************************************************************** - - public AbsTimeMeasurement(AbsTimeMeasurement measurement) - { - super(measurement.getValue(), measurement.getUnit()); - _time = measurement.getTime(); - - return; - } - //--------------------------------------------------------------- - - public long getTime() - { - return _time; - } - - public void setTime(long timeInMillis) - { - _time = timeInMillis; - } - //--------------------------------------------------------------- - - private String formatTime(long time) - { - - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); - formatter.setTimeZone(TimeZone.getTimeZone("UTC")); - return formatter.format(new Date(time)) + " UTC"; - } - - - //--------------------------------------------------------------- - public static AbsTimeMeasurement getConvertedCopy(AbsTimeMeasurement origMeasurement, - MeasuringUnit toUnit) - { - - AbsTimeMeasurement newMeasurement = new AbsTimeMeasurement(origMeasurement); - - newMeasurement.convert(toUnit); - - return newMeasurement; - } - -// --------------------------------------------------------------- - - public static AbsTimeMeasurement interpolate(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long desiredTime) - { - long t1 = m1.getTime(); - long t2 = m2.getTime(); - - double value1 = m1.getValue(); - double value2 = m2.getValue(); - - double slope = (value2 - value1) / (t2 - t1); - double intercept = (value1) - (slope*t1); - - - double value = (slope*desiredTime) + intercept; - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, desiredTime, m1.getUnit()); - - measurement.setIsInterpolated(true); - - return measurement; - } - - //--------------------------------------------------------------- - - - public boolean equals(Object object) - { - boolean result = false; - - if (object instanceof AbsTimeMeasurement) - { - AbsTimeMeasurement m = (AbsTimeMeasurement) object; - result = equals(m); - } - - return result; - - } - - //--------------------------------------------------------------- - - - public boolean equals(AbsTimeMeasurement measurement) - { - boolean result = false; - - if (this.getUnit() != measurement.getUnit()) - { - measurement = AbsTimeMeasurement.getConvertedCopy(measurement, this.getUnit()); - } - - - if ( - (this.getValue() == measurement.getValue()) && - (this.getTime() == measurement.getTime()) - ) - { - result = true; - } - - return result; - - } - - // --------------------------------------------------------------- - public int hashCode() - { - int value = 0; - - MeasuringUnit standardUnit = MeasuringUnit.getStandardUnitForUnit(this.getUnit()); - value = (int) ( this.getTime() + - this.getValue(standardUnit)); - - return value; - } - // --------------------------------------------------------------- - - public String toString() - { - return getValue() + " in " + getUnit().getName() + " at " + formatTime(_time); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/AbsTimeMeasurementPair.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/AbsTimeMeasurementPair.java deleted file mode 100644 index b38f2b2072..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/AbsTimeMeasurementPair.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.measurement; - - -/** - * @author Chip Gobs - * - * Contains a pair of Measurements - */ -public class AbsTimeMeasurementPair -{ - private AbsTimeMeasurement _measurement1; - private AbsTimeMeasurement _measurement2; - - // ---------------------------------------------------------------------------------------------- - - public AbsTimeMeasurementPair(AbsTimeMeasurement measurement1, AbsTimeMeasurement measurement2) - { - setMeasurement1(measurement1); - setMeasurement1(measurement2); - - return; - } - - /** - * @param measurement1 The measurement1 to set. - */ - public void setMeasurement1(AbsTimeMeasurement measurement1) - { - _measurement1 = new AbsTimeMeasurement(measurement1); - } - - /** - * @return Returns the measurement1. - */ - public AbsTimeMeasurement getMeasurement1() - { - return _measurement1; - } - - /** - * @param measurement2 The measurement2 to set. - */ - public void setMeasurement2(AbsTimeMeasurement measurement2) - { - _measurement2 = new AbsTimeMeasurement(measurement2); - } - - /** - * @return Returns the measurement2. - */ - public AbsTimeMeasurement getMeasurement2() - { - return _measurement2; - } - - // ---------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/IrregularTimeSeries.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/IrregularTimeSeries.java deleted file mode 100644 index c2f0eef8c5..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/IrregularTimeSeries.java +++ /dev/null @@ -1,659 +0,0 @@ -/* - * Created on Sep 26, 2003 - * - * - */ -package ohd.hseb.measurement; - -import java.util.*; -import java.text.*; - -import ohd.hseb.model.ForecastAdjuster; -import ohd.hseb.model.ForecastAdjusterParams; -import ohd.hseb.model.ForecastInterpolationMethod; - -/** - * @author Chip Gobs - * - * - */ -public class IrregularTimeSeries -{ - - private static final double _missingValue = -999.0; - private static final double _otherMissingValue = -9999.0; - private List _measurementList = new ArrayList(); - private MeasuringUnit _measuringUnit = null; - private String _name = null; - - //--------------------------------------------------------------------- - - //--------------------------------------------------------------------- - - public IrregularTimeSeries(MeasuringUnit unit) - { - _measuringUnit = unit; - } - -// --------------------------------------------------------------------- - - - /** - * - * @param newTimeSeries - * This add method perfoms mathematical addition, - * not insertion to the set of values. See insertXXX methods for insertion. - */ - - public static IrregularTimeSeries add(IrregularTimeSeries ts1, IrregularTimeSeries ts2) - { - //algorithm - - //1. find out all the times for which either time series has a measurement. - // store these times in an array - //2. iterate over the list to drive the addition of the 2 time series. - // There is a getMeasurementByTime method that allows for filling in zeroes - // and for interpolation adn for exact Measurement retrieval. - - MeasuringUnit unit1 = ts1.getMeasuringUnit(); - MeasuringUnit unit2 = ts2.getMeasuringUnit(); - - IrregularTimeSeries combinedTs = new IrregularTimeSeries(unit1); - IrregularTimeSeries newTs = new IrregularTimeSeries(unit1); - - // make sure that ts2 contains the same units; - // this might create an unpleasant side effect, so I convert it back at the end - - if (unit1 != unit2) - { - ts2.convert(unit1); - } - - // insert all of the measurements into the combined time series - combinedTs.insertTimeSeries(ts1); - // System.out.println("combined with ts1 \n " + combinedTs); - - combinedTs.insertTimeSeries(ts2); - // System.out.println("combined with ts1 and ts2 \n" + combinedTs); - - // get the array out of the time series - AbsTimeMeasurement[] combinedArray = combinedTs.getMeasurementArray(); - - - //for now, assume that any values out of range for a particular time series - // = 0.0; - - - boolean allowInterpolation = true; - boolean fillInEndsWithZero = true; - - long desiredTime = -1; - long previousTime = -2; - - for (int i = 0 ; i < combinedArray.length; i++ ) - { - AbsTimeMeasurement currentMeasurement = combinedArray[i]; - - desiredTime = currentMeasurement.getTime(); - - if (desiredTime != previousTime) //don't want duplicate entries, so checking - { - - AbsTimeMeasurement m1 = ts1.getAbsTimeMeasurementByTime(desiredTime, - allowInterpolation, - fillInEndsWithZero); - - AbsTimeMeasurement m2 = ts2.getAbsTimeMeasurementByTime(desiredTime, - allowInterpolation, - fillInEndsWithZero); - double value = m1.getValue() + m2.getValue(); - AbsTimeMeasurement newM = new AbsTimeMeasurement(value, desiredTime, unit1); - newTs.insertMeasurement(newM); - } - - previousTime = desiredTime; - - } //end for i - - - //convert back - might be needed - ts2.convert(unit2); - - return newTs; - - } // end add - - - //--------------------------------------------------------------------- - public void convert(MeasuringUnit newUnit) - { - String header = "TimeSeries.convert(): "; - // System.out.println(header + "is being called for ts = " + _name ); - - // trace(); - - List newMeasurementList = new ArrayList(); - - if (_measuringUnit != newUnit) - { - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement origMeasurement = (Measurement) _measurementList.get(i); - Measurement convertedMeasurement = - Measurement.getConvertedCopy(origMeasurement, newUnit); - - newMeasurementList.add(convertedMeasurement); - - } - - _measuringUnit = newUnit; - _measurementList = newMeasurementList; - } - - } - - //--------------------------------------------------------------------- - - public long getEndTime() - { - long endTime = -1; - if (_measurementList.size() > 0) - { - endTime = getAbsTimeMeasurementByIndex(_measurementList.size() - 1).getTime(); - } - return endTime; - } - - //--------------------------------------------------------------------- - public AbsTimeMeasurement findClosestMeasurementByTime(long targetTime) - { - AbsTimeMeasurement curMeasurement = null; - - AbsTimeMeasurement closestMeasurement = null; - long smallestTimeDiff = -1; - - long previousTimeDiff = -1; - long timeDiff = 0; - - boolean done = false; - - for (int i = 0; !done && i < _measurementList.size(); i++) - { - curMeasurement = (AbsTimeMeasurement) _measurementList.get(i); - - timeDiff = Math.abs( curMeasurement.getTime() - targetTime); - - if ( closestMeasurement == null) //first time - { - smallestTimeDiff = timeDiff; - closestMeasurement = curMeasurement; - } - else //not first time - { - if (timeDiff < smallestTimeDiff) - { - smallestTimeDiff = timeDiff; - closestMeasurement = curMeasurement; - } - else if (timeDiff > previousTimeDiff) //gone too far - { - done = true; - } - } - - previousTimeDiff = timeDiff; - - } - - - return closestMeasurement; - } - - // --------------------------------------------------------------------- - public AbsTimeMeasurement getMinMeasurement(long startTime, long endTime) - { - //could keep track of this internally when items are added or deleted from the list, but then it would have to - // be called everytime something is deleted, or else set a boolean marker to note that something would have to be recalculated in this - // method the next time it is called - AbsTimeMeasurement measurement = null; - - AbsTimeMeasurement minMeasurement = null; - - //String header = "IrregularTimeSeries.getMinMeasurement(): "; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = (AbsTimeMeasurement) _measurementList.get(i); - long time = measurement.getTime(); - - if ( (time >= startTime) && (time <= endTime) ) - { - - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - - ( (minMeasurement == null) || - (measurement.getValue() < minMeasurement.getValue()) - ) - ) - { - minMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - - } //end for i - - return minMeasurement; - - } - - // --------------------------------------------------------------------- - - public AbsTimeMeasurement getMinMeasurement() - { - - return getMinMeasurement(getStartTime(), getEndTime()); - - } - - //--------------------------------------------------------------------- - public AbsTimeMeasurement getMaxMeasurement(long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement maxMeasurement = null; - - double value = 0; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = (AbsTimeMeasurement) _measurementList.get(i); - long time = measurement.getTime(); - - - if ( (time >= startTime) && (time <= endTime) ) - { - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - ( (maxMeasurement == null) || - (measurement.getValue() > maxMeasurement.getValue()) - ) - ) - { - maxMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - } //end for - - - return maxMeasurement; - } - - //--------------------------------------------------------------------- - - public AbsTimeMeasurement getMaxMeasurement() - { - return getMaxMeasurement(getStartTime(), getEndTime()); - } - - //--------------------------------------------------------------------- - - public AbsTimeMeasurement[] getMeasurementArray() - { - AbsTimeMeasurement[] measurementArray = - new AbsTimeMeasurement[_measurementList.size()]; - - for (int index = 0; index < _measurementList.size(); index++) - { - measurementArray[index] = getAbsTimeMeasurementByIndex(index); - } - return measurementArray; - - } //getMeasurementArray - //--------------------------------------------------------------------- - - - public AbsTimeMeasurement getAbsTimeMeasurementByIndex(int index) - { - AbsTimeMeasurement measurement = null; - - measurement = (AbsTimeMeasurement) _measurementList.get(index); - - return measurement; - - } //getMeasurement - - //--------------------------------------------------------------------- - - - public AbsTimeMeasurement getAbsTimeMeasurementByTime(long desiredTime, - boolean interpolate, - boolean fillEndsWithZero) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement curMeasurement = null; - - AbsTimeMeasurement previousMeasurement = null; - AbsTimeMeasurement nextMeasurement = null; - - if ((desiredTime < this.getStartTime()) - || (desiredTime > this.getEndTime())) - { - if (fillEndsWithZero) - { - measurement = new AbsTimeMeasurement(0.0, desiredTime, - this._measuringUnit); - measurement.setIsDefaulted(true); - } - } - - else - // the desired time is in the range of the measurements contained in the - // TimeSeries - { - for (int i = 0; i < _measurementList.size(); i++) - { - curMeasurement = getAbsTimeMeasurementByIndex(i); - if (curMeasurement.getTime() == desiredTime) - { - //found it exactly - measurement = curMeasurement; - break; - } - else if (curMeasurement.getTime() < desiredTime) - { - previousMeasurement = curMeasurement; - //don't break, keep looking - } - else - //curMeasurement.getTime() > time) - { - nextMeasurement = curMeasurement; - - if (interpolate) - { - measurement = AbsTimeMeasurement.interpolate( - previousMeasurement, nextMeasurement, - desiredTime); - } - - break; // it is not in here, since we are past where it - // should be - } - } //end for - - } //end else - - - return measurement; - - } //getMeasurement - - //--------------------------------------------------------------------- - - - public int getMeasurementCount() - { - return _measurementList.size(); - } - - //--------------------------------------------------------------------- - - - public double[] getMeasurementValueArray() throws Exception - { - return getMeasurementValueArray(_measuringUnit); - } //end getMeasurementValueArray - - //--------------------------------------------------------------------- - - public double[] getMeasurementValueArray(MeasuringUnit unit) throws Exception - { - double[] valueArray = new double[_measurementList.size()]; - - if (_measuringUnit != unit) - { - convert(unit); - - } - - for (int index = 0; index < _measurementList.size(); index++) - { - - valueArray[index] = getAbsTimeMeasurementByIndex(index).getValue(); - } - - return valueArray; - - } //end getMeasurementValueArray - - //--------------------------------------------------------------------- - - public MeasuringUnit getMeasuringUnit() - { - return _measuringUnit; - } - - //--------------------------------------------------------------------- - - - public long getStartTime() - { - long startTime = -1; - if (_measurementList.size() > 0) - { - startTime = getAbsTimeMeasurementByIndex(0).getTime(); - } - return startTime; - } - - //--------------------------------------------------------------------- - - - - public void insertMeasurement(AbsTimeMeasurement newMeasurement) - { - //insert the measurement in the list in ascending order of time - boolean inserted = false; - - - //convert to the units of the TimeSeries - //try - { - AbsTimeMeasurement convertedMeasurement = - AbsTimeMeasurement.getConvertedCopy(newMeasurement, - _measuringUnit); - } - //catch (MeasuringUnitConversionException e) - //{ - // e.printStackTrace(); - // throw new Error (e.getMessage()); - //} - - // if the first measurement in the list - if (_measurementList.size() == 0) - { - _measurementList.add(0, newMeasurement); - inserted = true; - } - else if (newMeasurement.getTime() >= this.getEndTime()) - { - - _measurementList.add(newMeasurement); - inserted = true; - } - - - - // if the proper location was not found - if (!inserted) - { - //find the location to insert the measurement within the list - // and insert it - for (int i = 0; i < _measurementList.size() && ( !inserted); i++) - { - AbsTimeMeasurement currentMeasurement = - (AbsTimeMeasurement) _measurementList.get(i); - if (newMeasurement.getTime() < currentMeasurement.getTime() ) - { - _measurementList.add(i, newMeasurement); - inserted = true; - } - } //end for i - } - - return; - - } //insertMeasurement - - //--------------------------------------------------------------------- - - - public void insertTimeSeries(IrregularTimeSeries ts) - { - if (ts != null) - { - try - { - for (int i = 0; i < ts._measurementList.size(); i++) - { - this.insertMeasurement((ts.getAbsTimeMeasurementByIndex(i))); - } - } - catch (Exception e) - { - //can't really happen, since the TimeSeries can't - //hold a measurement of the wrong type - throw new Error("woh! somehow a bad measurement got in here "); - - } - } - } //end insertTimeSeries -// --------------------------------------------------------------------- - public IrregularTimeSeries getSubTimeSeries(long startTime, long endTime) - { - /** - * Return the time series that is within this time window, inclusively. - */ - IrregularTimeSeries newTs = new IrregularTimeSeries(this._measuringUnit); - - for (int i= 0; i < this.getMeasurementCount(); i++) - { - AbsTimeMeasurement m = this.getAbsTimeMeasurementByIndex(i); - long mTime = m.getTime(); - if ( (mTime >= startTime) && (mTime <= endTime) ) - { - newTs.insertMeasurement(m); - } - } - - return newTs; - - } -//--------------------------------------------------------------------- - - - public void setName(String name) - { - _name = name; - } -// --------------------------------------------------------------------- - - public String getName() - { - return _name; - } - //--------------------------------------------------------------------- - - - - public String toString() - { - - StringBuffer buffer = new StringBuffer(); - - if (getName() != null) - { - buffer.append("Name = " + getName() + " "); - } - - buffer.append("Units: " + _measuringUnit + " "); - - - - NumberFormat f = new DecimalFormat("###.##"); - - for (int i = 0; i < _measurementList.size(); i++) - { - double value = getAbsTimeMeasurementByIndex(i).getValue(); - String valueString = f.format(value); - buffer.append(valueString + " "); - } - - - - return buffer.toString(); - } - -// --------------------------------------------------------------------- - public static void main(String[] argStringArray) - { - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - ForecastAdjusterParams params = new ForecastAdjusterParams(); - params.setBlendingHours(5); - params.setBlendingMethod(ForecastInterpolationMethod.DIFFERENCE); - params.setShouldDoAdjustment(true); - - ForecastAdjuster adjuster = new ForecastAdjuster(params); - - long fcstStartTime = System.currentTimeMillis(); - - final long MILLIS_PER_HOUR = 1000 * 3600; - - long obsStartTime = fcstStartTime - (3 * 24 * MILLIS_PER_HOUR); //3 days before fcst start - long obsEndTime = fcstStartTime + (7 * MILLIS_PER_HOUR); // 7 hours after fcst start - - IrregularTimeSeries observedTs = new IrregularTimeSeries(dischargeUnit); - - double[] obsMeasurementValueArray = {18, 19, 20, 22, 24, 28, 33, 28, 39, 40, 41, 43, 53, 57, 41, 29, 29, 28, 27, 26, 26, 24, 28 }; - - int index = 0; - - - - - // load up the observed time series - index = 0; - for (long time = obsStartTime; time <= obsEndTime; time+= MILLIS_PER_HOUR) - { - AbsTimeMeasurement m = new AbsTimeMeasurement(obsMeasurementValueArray[index], time, dischargeUnit); - - observedTs.insertMeasurement(m); - - index++; - if (index == obsMeasurementValueArray.length) - { - index = 0; - } - } - - long subStartTime = obsStartTime + (2 * MILLIS_PER_HOUR); - long subEndTime = obsEndTime - (2 * MILLIS_PER_HOUR); - - IrregularTimeSeries subTimeSeries = observedTs.getSubTimeSeries(subStartTime, subEndTime); - - System.out.println("origObsTimeSeries = " + observedTs); - System.out.println("subObsTimeSeries = " + subTimeSeries); - - - - } - -} //end class TimeSeries diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/IrregularTimeSeriesHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/IrregularTimeSeriesHolder.java deleted file mode 100644 index 29b0af43db..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/IrregularTimeSeriesHolder.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Created on Oct 14, 2003 - * - * - * */ -package ohd.hseb.measurement; - -/** - * @author Chip Gobs - * - * This is a simple Holder class for an IrregularTimeSeries object - */ -public class IrregularTimeSeriesHolder -{ - private IrregularTimeSeries _timeSeries; - - public void setTimeSeries(IrregularTimeSeries timeSeries) - { - _timeSeries = timeSeries; - } - - public IrregularTimeSeries getTimeSeries() - { - return _timeSeries; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/Measurement.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/Measurement.java deleted file mode 100644 index dc2d12a42f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/Measurement.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * This class is a fundamental class to be used as the basis - * for time series and other measurements. - */ - -package ohd.hseb.measurement; - -//import java.text.*; -import java.util.*; - -/** - * @author Chip Gobs - * - * - */ -public class Measurement -{ - - - private MeasuringUnit _unit; - private double _value; - - private boolean _interpolated = false; - private boolean _extrapolated = false; - private boolean _defaulted = false; - - private boolean _isMissing = false; - - private double _missingValue = -999.0; - - //conversion for degrees fahrenheit and celsius - private static final double _f_to_c_factor = 5.0/9.0; - private static final double _c_to_f_factor = 9.0/5.0; - - - //consider a separate valid time class - - - //--------------------------------------------------------------- - - public Measurement(double value, MeasuringUnit unit) - { - _value = value; - _unit = unit; - - _isMissing = false; - - if (_unit == null) - { - throw new Error("ERROR: Measurement.Measurement() MeasuringUnit may not be null"); - } - - return; - } - - //--------------------------------------------------------------- - - public Measurement(Measurement measurement) - { - _value = measurement.getValue(); - _unit = measurement.getUnit(); - - _isMissing = measurement.isMissing(); - - return; - } - - - //--------------------------------------------------------------- - public boolean equals(Object object) - { - boolean result = false; - - if (object instanceof Measurement) - { - Measurement m = (Measurement) object; - result = this.equals(m); - } - - return result; - - } - //--------------------------------------------------------------- - - public boolean equals(Measurement measurement) - { - boolean result = false; - - if (this._unit != measurement.getUnit()) - { - measurement = this.getCopy(this._unit); - } - - if (this.getValue() == measurement.getValue()) - { - result = true; - } - - return result; - - } - - //--------------------------------------------------------------- - public static Measurement getConvertedCopy(Measurement origMeasurement, MeasuringUnit toUnit) - { - Measurement newMeasurement = null; - - if (origMeasurement != null) - { - newMeasurement = new Measurement(origMeasurement); - newMeasurement.convert(toUnit); - } - return newMeasurement; - } - - //--------------------------------------------------------------- - - public Measurement getCopy() - { - return getCopy(_unit); - } - //--------------------------------------------------------------- - - public Measurement getCopy(MeasuringUnit unit) - { - return Measurement.getConvertedCopy(this, unit); - } - //--------------------------------------------------------------- - - public MeasuringUnit getUnit() - { - return _unit; - } - - //--------------------------------------------------------------- - - public double getValue() - { - if (_isMissing) - { - _value = _missingValue; - } - - return _value; - } - - //--------------------------------------------------------------- - public double getValue(MeasuringUnit unit) - { - double value = _value; - - if (_isMissing) - { - _value = _missingValue; - value = _value; - } - - else if (_unit != unit) - { - double factor = MeasuringUnit.getConversionFactor(_unit, unit); - value = _value * factor; - } - - return value; - - } - - //--------------------------------------------------------------- - public void setValue(double value) - { - _value = value; - } - - //--------------------------------------------------------------- - public void addMeasurement(Measurement measurement) - { - measurement.convert(_unit); - - this.setValue(this.getValue() + measurement.getValue()); - - } - - //--------------------------------------------------------------- - - - protected void setUnit(MeasuringUnit unit) - { - _unit = unit; - } - - - //--------------------------------------------------------------- - - - // public void convert(MeasuringUnit toUnit) throws - // MeasuringUnitConversionException - protected void convert(MeasuringUnit toUnit) - { - String header = "Measurement.convert(): "; - - MeasuringUnit fromUnit = this.getUnit(); - if (fromUnit.getType() == toUnit.getType()) - { - if (fromUnit == toUnit) //do nothing - { - // no conversion needed - } - else if (fromUnit.getType() == MeasuringUnitType.temperature) - { - if (fromUnit.equals(MeasuringUnit.degreesFahrenheit) && - (toUnit.equals(MeasuringUnit.degreesCelsius) ) ) - { - _value = fahrenHeightToCelsius(_value); - _unit = toUnit; - } - else if (fromUnit.equals(MeasuringUnit.degreesCelsius) && - (toUnit.equals(MeasuringUnit.degreesFahrenheit) ) ) - { - _value = celsiusToFahrenheit(_value); - _unit = toUnit; - } - } - else // multiplicative conversion - { - double factor = MeasuringUnit.getConversionFactor(fromUnit, toUnit); - - // System.out.println(header + " from " + _value + " in " + fromUnit + - // " to " + (_value * factor) + " in " + toUnit ); - - - _value = _value * factor; - _unit = toUnit; - - } - } - else //can't convert these types - { - //throw new MeasuringUnitConversionException(fromUnit, toUnit); - throw new Error("Bogus Unit conversion attempt from " + - fromUnit.getName() + - " to " + toUnit.getName() ); - } - } //end convert - - //--------------------------------------------------------------- - private double fahrenHeightToCelsius(double origValue) - { - double newValue = _f_to_c_factor * ( origValue - 32); - - return newValue; - } - - private double celsiusToFahrenheit(double origValue) - { - double newValue = (_c_to_f_factor * origValue) + 32; - - return newValue; - } - - //--------------------------------------------------------------- - - - public String toString() - { - String string = null; - - if (! _isMissing) - { - string = _value + " in " + _unit.getName(); - } - else - { - string = "MISSING"; - } - - return string; - } - - - //--------------------------------------------------------------- - - public void setIsInterpolated(boolean interpolated) { - this._interpolated = interpolated; - } - //--------------------------------------------------------------- - - public boolean isInterpolated() - { - return _interpolated; - } - - //--------------------------------------------------------------- - - public void setIsExtrapolated(boolean extrapolated) - { - this._extrapolated = extrapolated; - } - - //--------------------------------------------------------------- - - public boolean isExtrapolated() - { - return _extrapolated; - } - - //--------------------------------------------------------------- - - public void setIsDefaulted(boolean defaulted) - { - this._defaulted = defaulted; - } - - //--------------------------------------------------------------- - - public boolean isDefaulted() - { - return _defaulted; - } - - //--------------------------------------------------------------- - - public void setIsMissing(boolean isMissing) - { - _isMissing = isMissing; - - _value = _missingValue; - } - - //--------------------------------------------------------------- - public boolean isMissing() - { - return _isMissing; - } - - //--------------------------------------------------------------- - - public int hashCode() - { - int value = 0; - - MeasuringUnit standardUnit = MeasuringUnit.getStandardUnitForUnit(this.getUnit()); - value = (int) ( this.getValue(standardUnit)); - - return value; - } - //--------------------------------------------------------------- - - public static void main (String[] args) throws Exception - { - AbsTimeMeasurement m1 = new AbsTimeMeasurement(3.0, - new Date().getTime(), - MeasuringUnit.feet); - - System.out.println(m1); - - AbsTimeMeasurement m2 = AbsTimeMeasurement.getConvertedCopy(m1, MeasuringUnit.inches); - - System.out.println(m2); - - } //end main - - -} //end class Measurement diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementHolder.java deleted file mode 100644 index 95c6436fc7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementHolder.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on Feb 9, 2004 - * - * - */ -package ohd.hseb.measurement; - - -/** - * @author GobsC - * - * This is a holder class for Measurement objects. - */ -public class MeasurementHolder -{ - - private Measurement _measurement; - - - public Measurement getMeasurement() - { - return _measurement; - } - - - public void setMeasurement(Measurement measurement) - { - _measurement = measurement; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPoint.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPoint.java deleted file mode 100644 index 7f1e72d396..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPoint.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Created on Jul 13, 2004 - * - * - */ -package ohd.hseb.measurement; - -/** - * @author GobsC - * - * - */ -public class MeasurementPoint -{ - private Measurement _xMeasurement; - private Measurement _yMeasurement; - - - public MeasurementPoint(Measurement measurement1, Measurement measurement2) - { - _xMeasurement = measurement1; - _yMeasurement = measurement2; - } - -// ------------------------------------------------------------------------------- - - public MeasurementPoint(MeasurementPoint point, MeasuringUnit unit1, MeasuringUnit unit2) - { - _xMeasurement = point.getXMeasurement().getCopy(unit1); - _yMeasurement = point.getYMeasurement().getCopy(unit2); - } - -// ------------------------------------------------------------------------------- - public void setXMeasurement(Measurement xMeasurement) - { - _xMeasurement = xMeasurement; - } -// ------------------------------------------------------------------------------- - - public Measurement getXMeasurement() - { - return _xMeasurement; - } -// ------------------------------------------------------------------------------- - - public void setYMeasurement(Measurement yMeasurement) - { - _yMeasurement = yMeasurement; - } -// ------------------------------------------------------------------------------- - - public Measurement getYMeasurement() - { - return _yMeasurement; - } -// ------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPointComparator.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPointComparator.java deleted file mode 100644 index d594faca2f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPointComparator.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Created on Jul 15, 2004 - * - * - */ -package ohd.hseb.measurement; - -import java.util.Comparator; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasuringUnit; - -/** - * @author GobsC - * - * - */ -public class MeasurementPointComparator implements Comparator -{ - - private boolean _compareX = false; - private boolean _ascendingOrder = true; - - public MeasurementPointComparator(boolean compareX, boolean ascendingOrder ) - { - _compareX = compareX; - _ascendingOrder = ascendingOrder; - } - - public int compare(Object uhg1, Object uhg2) - { - int result = 0; - - MeasurementPoint point1 = (MeasurementPoint) uhg1; - MeasurementPoint point2= (MeasurementPoint) uhg2; - - Measurement m1 = null; - Measurement m2 = null; - - if (_compareX) - { - m1 = point1.getXMeasurement(); - m2 = point2.getXMeasurement(); - } - else - { - m1 = point1.getYMeasurement(); - m2 = point2.getYMeasurement(); - } - - //pick a standard unit - MeasuringUnit unit = m1.getUnit(); - - - double value1 = m1.getValue(unit); - double value2 = m2.getValue(unit); - - if (value1 < value2) - { - result = -1; - } - else if (value1 == value2) - { - result = 0; - } - else // value1 > value2 - { - result = 1; - } - - if (! _ascendingOrder) - { - result *= -1; - } - - return result; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPointSeries.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPointSeries.java deleted file mode 100644 index 13de9e7f21..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasurementPointSeries.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Created on Jul 14, 2004 - * - * - */ -package ohd.hseb.measurement; - - -import java.util.Comparator; -import java.util.List; -import java.util.ArrayList; - -/** - * @author Chip Gobs - * - * This class contains a collection of MeasurementPoint objects and can - * operate on the collection. - */ -public class MeasurementPointSeries -{ - // ------------------------------------------------------------------------ - - private List _measurementPointList = null; - - private MeasuringUnit _xMeasuringUnit = null; - private MeasuringUnit _yMeasuringUnit = null; - - private Comparator _comparator; - - // ------------------------------------------------------------------------ - - public MeasurementPointSeries(MeasuringUnit xMeasuringUnit, MeasuringUnit yMeasuringUnit, Comparator comparator) - { - _xMeasuringUnit = xMeasuringUnit; - _yMeasuringUnit = yMeasuringUnit; - - _comparator = comparator; - - _measurementPointList = new ArrayList(); - } - - // ------------------------------------------------------------------------ - - public void setComparator(Comparator comparator) - { - _comparator = comparator; - } - - // ------------------------------------------------------------------------ - - public Comparator getComparator() - { - return _comparator; - } - - // ------------------------------------------------------------------------ - - // ------------------------------------------------------------------------ - public void addPoint(MeasurementPoint newPoint) - { - newPoint = new MeasurementPoint(newPoint, _xMeasuringUnit, _yMeasuringUnit); - - boolean added = false; - for (int i = 0; i < _measurementPointList.size() && !added; i++) - { - MeasurementPoint existingPoint = (MeasurementPoint) _measurementPointList.get(i); - - int result = _comparator.compare(newPoint, existingPoint); - - if ((result == -1) || (result == 0)) - { - _measurementPointList.add(i, newPoint); - added = true; - } - } - - if (! added) - { - _measurementPointList.add(newPoint); - } - - return; - } - // ------------------------------------------------------------------------ - public void removePoint(MeasurementPoint point) - { - _measurementPointList.remove(point); - } - - // ------------------------------------------------------------------------ - public void clear() - { - _measurementPointList.clear(); - } - - // ------------------------------------------------------------------------ - - public int size() - { - int result = 0; - - if (_measurementPointList != null) - { - result = _measurementPointList.size(); - } - - return result; - } - // ------------------------------------------------------------------------ - - public MeasurementPoint getPoint(int index) - { - return (MeasurementPoint) _measurementPointList.get(index); - } - // ------------------------------------------------------------------------ - - public Measurement getMaxXMeasurement() - { - return getMaxMeasurement(true); - } - - // ------------------------------------------------------------------------ - - public Measurement getMinXMeasurement() - { - return getMinMeasurement(true); - } - - // ------------------------------------------------------------------------ - - - public Measurement getMaxYMeasurement() - { - return getMaxMeasurement(false); - - } - - // ------------------------------------------------------------------------ - - public Measurement getMinYMeasurement() - { - return getMinMeasurement(false); - } - - // ------------------------------------------------------------------------ - - public Measurement getMaxMeasurement(boolean isXOrdinate) - { - Measurement maxMeasurement = null; - Measurement pointMeasurement = null; - - MeasuringUnit unit = null; - - // determine which units we are dealing with - if (isXOrdinate) - { - unit = _xMeasuringUnit; - } - else - { - unit = _yMeasuringUnit; - } - - - - // look at each measurement point to determine the max - for (int i = 0; i < size(); i++) - { - MeasurementPoint point = (MeasurementPoint) _measurementPointList.get(i); - - if (isXOrdinate) - { - pointMeasurement = point.getXMeasurement(); - } - else - { - pointMeasurement = point.getYMeasurement(); - } - - if (maxMeasurement == null) - { - maxMeasurement = pointMeasurement; - } - else //maxMeasurement != null - { - if (pointMeasurement != null) - { - if (pointMeasurement.getValue(unit) > maxMeasurement.getValue(unit)) - { - maxMeasurement = pointMeasurement; - } - } - } - - } - - return maxMeasurement; - - } - - - - // ------------------------------------------------------------------------ - public Measurement getMinMeasurement(boolean isXOrdinate) - { - Measurement minMeasurement = null; - Measurement pointMeasurement = null; - - MeasuringUnit unit = null; - - // determine which units we are dealing with - if (isXOrdinate) - { - unit = _xMeasuringUnit; - } - else - { - unit = _yMeasuringUnit; - } - - - - // look at each measurement point to determine the max - for (int i = 0; i < size(); i++) - { - MeasurementPoint point = (MeasurementPoint) _measurementPointList.get(i); - - - - if (isXOrdinate) - { - pointMeasurement = point.getXMeasurement(); - } - else - { - pointMeasurement = point.getYMeasurement(); - } - - if (minMeasurement == null) - { - minMeasurement = pointMeasurement; - } - else //minMeasurement != null - { - if (pointMeasurement != null) - { - if (pointMeasurement.getValue(unit) < minMeasurement.getValue(unit)) - { - minMeasurement = pointMeasurement; - } - } - } - - } - - return minMeasurement; - - } - // ------------------------------------------------------------------------ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0 ; i < size(); i++) - { - MeasurementPoint point = getPoint(i); - - Measurement xMeasurement = point.getXMeasurement(); - Measurement yMeasurement = point.getYMeasurement(); - - buffer.append("x = " + xMeasurement + " y = " + yMeasurement + "\n"); - - } - - return buffer.toString(); - - } - - // ------------------------------------------------------------------------ - public static void main(String[] argStringArray) - { - MeasuringUnit xUnit = MeasuringUnit.hours; - MeasuringUnit yUnit = MeasuringUnit.cfs; - - boolean compareXValues = true; - boolean ascendingOrder = true; - - Comparator comparator = new MeasurementPointComparator(compareXValues, ascendingOrder); - - MeasurementPointSeries measurementPointSeries = new MeasurementPointSeries(xUnit, yUnit, comparator); - - int measurementCount = 10; - - for (int i = 0 ; i < measurementCount; i++) - { - Measurement m1 = new Measurement(measurementCount - i - 1, xUnit); - Measurement m2 = new Measurement(2*i, yUnit); - - MeasurementPoint point = new MeasurementPoint(m1, m2); - - measurementPointSeries.addPoint(point); - } - - - - for (int i = 0 ; i < measurementPointSeries.size(); i++) - { - MeasurementPoint point = measurementPointSeries.getPoint(i); - - Measurement xMeasurement = point.getXMeasurement(); - Measurement yMeasurement = point.getYMeasurement(); - - System.out.println("x = " + xMeasurement + " y = " + yMeasurement); - } - - Measurement minXMeasurement = measurementPointSeries.getMinXMeasurement(); - Measurement minYMeasurement = measurementPointSeries.getMinYMeasurement(); - - Measurement maxXMeasurement = measurementPointSeries.getMaxXMeasurement(); - Measurement maxYMeasurement = measurementPointSeries.getMaxYMeasurement(); - - System.out.println("minX = " + minXMeasurement + " minY = " + minYMeasurement); - System.out.println("maxX = " + maxXMeasurement + " maxY = " + maxYMeasurement); - } - // ------------------------------------------------------------------------ - -} //end MeasurementPointSeries diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnit.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnit.java deleted file mode 100644 index 7c2de2984c..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnit.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * To change the template for this generated file go to - * - */ -package ohd.hseb.measurement; - -import java.util.*; - -/** - * @author gobsc - * - * This is basically an enum of all possible units of measure, but it is also - * smart enough to help handle unit conversions. - */ -public class MeasuringUnit -{ - - //conversion factor map - private static Map _conversionFactorMap = new HashMap(); - - - //conversion standard map - private static Map _conversionStandardMap= new HashMap(); - - // Note: the standard unit for a particular MeasuringUnitType, MUST be the first - //one of that type created here. Otherwise, a circular lookup dependency will be created when - //when the code tries to set up Maps used to convert first to the standard unit (which wouldn't exist yet) - // and then to the desired unit. - // In the private constructor, having a conversion factor of 1.0 is used to identify the unit - // as the standard of that MeasuringUnitType. - - - //discharge types - public static final MeasuringUnit cfs = new MeasuringUnit("cfs", MeasuringUnitType.discharge, 1.0); - public static final MeasuringUnit kcfs = new MeasuringUnit("kcfs", MeasuringUnitType.discharge, 1000.0); - public static final MeasuringUnit cms = new MeasuringUnit("cms", MeasuringUnitType.discharge, 35.314666572 ); - - //length types - public static final MeasuringUnit meters = new MeasuringUnit("meters", MeasuringUnitType.length, 1.0); - public static final MeasuringUnit cm = new MeasuringUnit("cm", MeasuringUnitType.length, 0.01); - public static final MeasuringUnit mm = new MeasuringUnit("mm", MeasuringUnitType.length, 0.001); - public static final MeasuringUnit inches = new MeasuringUnit("inches", MeasuringUnitType.length, 0.0254); - public static final MeasuringUnit feet = new MeasuringUnit("feet", MeasuringUnitType.length, 0.3048); - - //relative time types - public static final MeasuringUnit hours = new MeasuringUnit("hours", MeasuringUnitType.elapsedTime, 1.0); - public static final MeasuringUnit days = new MeasuringUnit("days", MeasuringUnitType.elapsedTime, 24.0); - - //temperature types - // This implementation does NOT work right for Fahrenheit to/from Celsius conversion because - // one needs to add or subtract 32 to convert. Address this later, when needed. - // Consider adding a larger, unit conversion class - public static final MeasuringUnit degreesFahrenheit = new MeasuringUnit("degrees F", MeasuringUnitType.temperature, 1.0); - public static final MeasuringUnit degreesCelsius = - new MeasuringUnit("degrees C", MeasuringUnitType.temperature, 0); - - - //speed types - public static final MeasuringUnit mph = new MeasuringUnit("mph", MeasuringUnitType.speed, 1.0); - public static final MeasuringUnit knots = new MeasuringUnit("knots", MeasuringUnitType.speed, 1.150779448 ); - public static final MeasuringUnit kph = new MeasuringUnit("kph", MeasuringUnitType.speed, 0.621371192); - - //direction - public static final MeasuringUnit degrees = new MeasuringUnit("degrees", MeasuringUnitType.elapsedTime, 1.0); - - - - //unitless - public static final MeasuringUnit unitless = - new MeasuringUnit("unitless", MeasuringUnitType.unitless, 1.0); - - - // member variables - private MeasuringUnitType _type; - private String _name; - - //note, we simply need to convert to a standard and convert from the standard, - // so that we don't have (N*N) -N conversions, just 2*N conversions - - // -------------------------------------------------------------------- - private MeasuringUnit(String unitName, - MeasuringUnitType type, - double conversionFactor) - { - _name = unitName; - _type = type; - - - String toStandardKey = null; - String fromStandardKey = null; - - if (conversionFactor == 1.0) - { - // this is the standard unit - _conversionStandardMap.put(type, this); - - toStandardKey = getConversionKey(unitName,unitName); - fromStandardKey = getConversionKey(unitName, unitName); - - addConversionFactor(toStandardKey, conversionFactor); - addConversionFactor(fromStandardKey, 1.0/conversionFactor); - } - else - { - MeasuringUnit standardUnit = getStandardUnitForType(type); - toStandardKey = getConversionKey(unitName,standardUnit.getName()); - fromStandardKey = getConversionKey(standardUnit.getName(), unitName); - - - addConversionFactor(toStandardKey, conversionFactor); - addConversionFactor(fromStandardKey, 1.0/conversionFactor); - } - - } //end constructor - - - public String getName() - { - return _name; - } - - public MeasuringUnitType getType() - { - return _type; - } - - public String toString() - { - return _name; - } - - public static double getConversionFactor(MeasuringUnit fromUnit, - MeasuringUnit toUnit) - { - MeasuringUnit standardUnit = getStandardUnitForType(fromUnit.getType()); - double conversionFactor = 1.0; - - if (fromUnit == toUnit) - { - conversionFactor = 1.0; - } - else - { - - String conversionKey1 = getConversionKey(fromUnit, standardUnit); - Double conversionFactor1 = (Double)_conversionFactorMap.get(conversionKey1); - - String conversionKey2 = getConversionKey(standardUnit, toUnit); - Double conversionFactor2 = (Double)_conversionFactorMap.get(conversionKey2); - conversionFactor = conversionFactor1.doubleValue() * - conversionFactor2.doubleValue(); - - } - - return conversionFactor; - } //end getConversionFactor - - protected static MeasuringUnit getStandardUnitForType(MeasuringUnitType type) - { - MeasuringUnit unit = (MeasuringUnit) _conversionStandardMap.get(type); - - return unit; - - } //end getStandardUnitForType - - protected static MeasuringUnit getStandardUnitForUnit(MeasuringUnit unit) - { - MeasuringUnitType type = unit.getType(); - MeasuringUnit standardUnit = (MeasuringUnit) _conversionStandardMap.get(type); - - return standardUnit; - - } //end getStandardUnitForType - - - /* - private static void addConversionFactor(MeasuringUnit fromUnit, - MeasuringUnit toUnit, - double conversionFactor) - { - String conversionKey = getConversionKey(fromUnit, toUnit); - addConversionFactor(conversionKey, conversionFactor); - - return; - } - */ - - private static void addConversionFactor(String conversionKey, double conversionFactor) - { - _conversionFactorMap.put(conversionKey, new Double(conversionFactor)); - - return; - } - - - private static String getConversionKey(MeasuringUnit fromUnit, MeasuringUnit toUnit) - { - return getConversionKey(fromUnit.getName(), toUnit.getName()); - } - - private static String getConversionKey(String fromUnitName, String toUnitName) - { - return fromUnitName + "|" + toUnitName; - } - -} //end MeasuringUnit diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnitConversionException.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnitConversionException.java deleted file mode 100644 index 80eab5edfa..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnitConversionException.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.measurement; -/** - * @author gobsc - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class MeasuringUnitConversionException extends Exception -{ - public MeasuringUnitConversionException(MeasuringUnit fromUnit, MeasuringUnit toUnit) - { - super("Unable to convert " + fromUnit.getName() + " to " + toUnit.getName()); - - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnitType.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnitType.java deleted file mode 100644 index b66486ace0..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/MeasuringUnitType.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Created on Jul 2, 2003 - * - * - */ -package ohd.hseb.measurement; -/** - * @author gobsc - * - * This class is basically an enum for the possible types of - * MeasuringUnits. distance, volume, flow - */ -public class MeasuringUnitType -{ - - public static final MeasuringUnitType length = new MeasuringUnitType("length"); - public static final MeasuringUnitType discharge = new MeasuringUnitType("discharge"); - public static final MeasuringUnitType volume = new MeasuringUnitType("volume"); - public static final MeasuringUnitType elapsedTime = new MeasuringUnitType("elapsedTime"); - public static final MeasuringUnitType temperature = new MeasuringUnitType("temperature"); - public static final MeasuringUnitType speed = new MeasuringUnitType("speed"); - public static final MeasuringUnitType direction = new MeasuringUnitType("direction"); - - public static final MeasuringUnitType unitless = new MeasuringUnitType("unitless"); - - - private String _name = null; - - //private constructor - private MeasuringUnitType(String typeName) - { - _name = typeName; - } - - public String getName() - { - return _name; - } - - public String toString() - { - return _name; - - } //toString - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RegularTimeSeries.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RegularTimeSeries.java deleted file mode 100644 index ee4b97e9fb..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RegularTimeSeries.java +++ /dev/null @@ -1,1143 +0,0 @@ -/* - * Created on Oct 15, 2003 - * - * - * - */ -package ohd.hseb.measurement; - -import java.text.NumberFormat; -import java.text.*; -import java.util.*; -import ohd.hseb.util.*; -import ohd.hseb.db.*; - -/** - * @author Chip Gobs - * - * - */ -public class RegularTimeSeries -{ - private static final double _missingValue = -999.0; - private static final double _otherMissingValue = -9999.0; - private static final long _millisPerHour = 1000 * 60 * 60; - - private static final String _missingString = "MSG"; - - private String _name = null; - private long _startTime = 0; - private long _endTime = 0; - private int _intervalInHours = 1; - private long _shiftedTimeInMillis = 0; - private long _intervalInMillis = _intervalInHours * _millisPerHour; - private List _measurementList = new ArrayList(); - private MeasuringUnit _measuringUnit = null; - - - -// ----------------------------------------------------------------------------- - - public RegularTimeSeries(RegularTimeSeries originalTimeSeries) - { - - this(originalTimeSeries._startTime, - originalTimeSeries._endTime, - originalTimeSeries._intervalInHours, - originalTimeSeries._measuringUnit, -1.0); - - _shiftedTimeInMillis = originalTimeSeries._shiftedTimeInMillis; - - List origMeasurementList = originalTimeSeries._measurementList; - - for (int i = 0; i < origMeasurementList.size(); i++) - { - Measurement origMeasurement = (Measurement) originalTimeSeries._measurementList.get(i); - Measurement measurement = new Measurement(origMeasurement); - - setMeasurementByIndex(measurement, i); - } - - return; - } - -// ----------------------------------------------------------------------------- - - public RegularTimeSeries(long startTime, - long endTime, - int intervalInHours, - MeasuringUnit unit) - { - - // defaults to initialValue = 0.0; - this(startTime, endTime, intervalInHours, unit, 0.0); - - } - -// ----------------------------------------------------------------------------- - - public RegularTimeSeries(long startTime, - long endTime, - int intervalInHours, - MeasuringUnit unit, - double initialValue) - { - //System.out.println("RegularTimeSeries c-tor"); - _intervalInHours = intervalInHours; - _intervalInMillis = _intervalInHours * _millisPerHour; - - _startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, - _intervalInHours); - - _endTime = TimeHelper.truncateTimeInMillisToNearestHour(endTime, - _intervalInHours); - - - // System.out.println( "RegularTimeSeries ctor _startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_startTime)); - // System.out.println( "RegularTimeSeries ctor _endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_endTime)); - - - - _measuringUnit = unit; - - long numberOfIntervals = (_endTime - _startTime) / _intervalInMillis; - numberOfIntervals++; //if endTime == startTime, that is 1 interval - - //long currentTime = startTime; - for (int i = 0; i < numberOfIntervals; i++) - { - Measurement newMeasurement = new Measurement(initialValue, unit); - _measurementList.add(i, newMeasurement); - } - - } //end RegularTimeSeries() - -// --------------------------------------------------------------------------- - public void shiftStartEndTimeHours(int hoursShift) - { - - long timeDiff = hoursShift * _millisPerHour; - - _startTime += timeDiff; - _endTime += timeDiff; - - _shiftedTimeInMillis = timeDiff; - - return; - } - -// --------------------------------------------------------------------------- - - public static RegularTimeSeries add(RegularTimeSeries ts1, RegularTimeSeries ts2) - { - long startTime1 = ts1.getStartTime(); - long startTime2 = ts2.getStartTime(); - - long endTime1 = ts1.getEndTime(); - long endTime2 = ts2.getEndTime(); - - int intervalInHours = ts1.getIntervalInHours(); - long intervalInMillis = intervalInHours * _millisPerHour; - - MeasuringUnit unit = ts1.getMeasuringUnit(); - ts2.convert(unit); - - long startTime = Math.min(startTime1, startTime2); - long endTime = Math.max(endTime1, endTime2); - - // fit the 2 time series to each other - ts1.stretchTimeSeries(startTime, endTime, 0); - ts2.stretchTimeSeries(startTime, endTime, 0); - - - //create the new time series - RegularTimeSeries newTs = new RegularTimeSeries(startTime, endTime, - intervalInHours, - unit); - - - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement m1 = ts1.getMeasurementByTime(time); - Measurement m2 = ts2.getMeasurementByTime(time); - - double value1 = m1.getValue(); - double value2 = m2.getValue(); - - if ( (! m1.isMissing()) && (!m2.isMissing()) ) - { - double value = value1 + value2; - Measurement newMeasurement = new Measurement (value, unit); - newTs.setMeasurementByTime(newMeasurement, time); - } - else - { - Measurement newMeasurement = new Measurement (0.0, unit); - newMeasurement.setIsMissing(true); - newTs.setMeasurementByTime(newMeasurement, time); - } - } - - return newTs; - } -// --------------------------------------------------------------------------- - public RegularTimeSeries copy() - { - RegularTimeSeries newTs = - new RegularTimeSeries(this.getStartTime(), - this.getEndTime(), - this.getIntervalInHours(), - this.getMeasuringUnit()); - - for (int i=0; i < this._measurementList.size(); i++) - { - Measurement m = (Measurement) this._measurementList.get(i); - newTs.setMeasurementByIndex( m, i); - - } - - return newTs; - - } - -// --------------------------------------------------------------------------- - - - public void convert(MeasuringUnit newUnit) - { - String header = "RegularTimeSeries.convert(): "; - // System.out.println(header + " ts name = " + _name); - // trace(); - - List newMeasurementList = new ArrayList(); - - if (_measuringUnit != newUnit) - { - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement origMeasurement = (Measurement) _measurementList.get(i); - Measurement convertedMeasurement = - Measurement.getConvertedCopy(origMeasurement, newUnit); - - newMeasurementList.add(convertedMeasurement); - - } - - _measuringUnit = newUnit; - _measurementList = newMeasurementList; - } - - } -// ----------------------------------------------------------------------------- - public void stretchTimeSeries(long newStartTime, long endStartTime, double fillInValue) - { - prependTimeSeries(newStartTime, fillInValue); - extendTimeSeries(endStartTime, fillInValue); - - return; - } - -// ----------------------------------------------------------------------------- - public void trimTimeSeriesAtStart(long newStartTime) - { - // round off the newEndTime to the nearest hour - // if it is not already rounded, then add an hour to the rounded result - long newRoundedStartTime = TimeHelper.truncateTimeInMillisToNearestHour(newStartTime, 1); - - if (newRoundedStartTime != newStartTime) - { - newRoundedStartTime += _millisPerHour; - } - - - // remove measurements from the beginning of the list - if (newRoundedStartTime > _startTime) - { - long hoursDiff = (newRoundedStartTime - _startTime) / _millisPerHour; - for (int i = 0; i < hoursDiff; i++) - { - //remove from the beginning of the list - _measurementList.remove(0); - } - - _startTime = newRoundedStartTime; - } - - return; - } - -// ----------------------------------------------------------------------------- - public void prependTimeSeries(long newStartTime) - { - prependTimeSeries(newStartTime, 0.0); - - } - - public void prependTimeSeries(long newStartTime, double fillInValue) - { - // round off the newEndTime to the nearest hour - // if it is not already rounded, then add an hour to the rounded result - long roundedStartTime = TimeHelper.truncateTimeInMillisToNearestHour(newStartTime, 1); - - if (roundedStartTime != newStartTime) - { - roundedStartTime += _millisPerHour; - } - - - // add measurements to the beginning of the list - if (roundedStartTime < _startTime) - { - long hoursDiff = (_startTime - roundedStartTime) / _millisPerHour; - for (int i = 0; i < hoursDiff; i++) - { - Measurement newMeasurement = new Measurement(fillInValue, _measuringUnit); - - //add to the beginning of the list - _measurementList.add(0, newMeasurement); - } - - _startTime = roundedStartTime; - } - - } //end prependTimeSeries() - -// --------------------------------------------------------------------------- - public void extendTimeSeries(long newEndTime) - { - extendTimeSeries(newEndTime, 0.0); - } - - public void extendTimeSeries(long newEndTime, double fillInValue) - { - - // round off the newEndTime to the nearest hour - // if it is not already rounded, then add an hour to the rounded result - long roundedEndTime = TimeHelper.truncateTimeInMillisToNearestHour(newEndTime, 1); - - if (roundedEndTime != newEndTime) - { - roundedEndTime+= _millisPerHour; - } - - - // add measurements to the end of the list - if (roundedEndTime > _endTime) - { - long hoursDiff = (roundedEndTime - _endTime) / _millisPerHour; - for (int i = 0; i < hoursDiff; i++) - { - Measurement newMeasurement = new Measurement(fillInValue, _measuringUnit); - - //add to the end of the list - _measurementList.add(newMeasurement); - } - - _endTime = roundedEndTime; - } - - - - } //end extendTimeSeries() -// --------------------------------------------------------------------------- - public void setName(String name) - { - _name = name; - } -// --------------------------------------------------------------------------- - - public String getName() - { - return _name; - } -// --------------------------------------------------------------------------- - - public int getMeasurementCount() - { - return _measurementList.size(); - } - -// -------------------------------------------------------- - - public Measurement getMeasurementByIndex(int index) - { - /* - if (index >= _measurementList.size()) - { - - } - */ - - return (Measurement)_measurementList.get(index); - } -// -------------------------------------------------------- - - public double getMeasurementValueByIndex(int index, MeasuringUnit unit) - { - double value = _missingValue; - - Measurement m = getMeasurementByIndex(index); - if (m != null) - { - m = m.getCopy(unit); - value = m.getValue(); - } - else - { - System.err.println("RegularTimeSeries.getMeasurementValueByIndex(): no measurement for index = " + index); - } - - return value; - } - -// -------------------------------------------------------- - public double getMeasurementValueByTime(long time, MeasuringUnit unit) - { - double value = _missingValue; - - Measurement m = getMeasurementByTime(time); - - if (m != null) - { - m = m.getCopy(unit); - value = m.getValue(); - } - else - { - System.err.println("RegularTimeSeries.getMeasurementValueByTime(): no measurement for time = " + - DbTimeHelper.getDateTimeStringFromLongTime(time)); - } - return value; - } - -// -------------------------------------------------------- - - public long getMeasurementTimeByIndex(int index) - { - long newTime = _startTime + (index * _intervalInMillis); - - return newTime; - } - -// -------------------------------------------------------- - - private int getMeasurementIndexByTime(long time) - { - int index = -1; - - String header = "RegularTimeSeries.getMeasurementIndexByTime()"; - - - //System.out.println(header + "time 1 = " + time); - - //System.out.println(header + "orig time = " + DbTimeHelper.getDateTimeStringFromLongTime(time)); - - time = TimeHelper.truncateTimeInMillisToNearestHour(time, _intervalInHours) + _shiftedTimeInMillis; - - //System.out.println(header + "adjusted time = " + DbTimeHelper.getDateTimeStringFromLongTime(time)); - - //System.out.println(header + "startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_startTime)); - //System.out.println(header + "endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(_endTime)); - // - if ( (time >= _startTime) && - (time <= _endTime) ) - { - long intervalsDifference = (time - _startTime) / _intervalInMillis; - index = (int) intervalsDifference; - - /* - if (index >= _measurementList.size()) - { - System.out.println("Problem is here"); - System.out.println("Time Series name = " + getName()); - } - */ - - } - - //System.out.println(header + "index = " + index); - - return index; - } - -// -------------------------------------------------------- - - private void setMeasurementByIndex(Measurement measurement, int index) - { - Measurement newMeasurement = - Measurement.getConvertedCopy(measurement, - _measuringUnit); - _measurementList.remove(index); - _measurementList.add(index, newMeasurement); - - return; - } - -// -------------------------------------------------------- - - public void setMeasurementByTime(Measurement measurement, long time) - { - - if (time > _endTime) - { - // System.out.println("RegularTimeSeries.setMeasurementByTime(): Extending the timeSeries"); - extendTimeSeries(time); - } - else if (time < _startTime) - { - // System.out.println("RegularTimeSeries.setMeasurementByTime(): Prepending the timeSeries"); - prependTimeSeries(time); - } - - int index = getMeasurementIndexByTime(time); - - // System.out.println("RegularTimeSeries.setMeasurementByTime(): time = " + - // DbTimeHelper.getDateTimeStringFromLongTime(time) + " index = " + index); - - if (index != -1) - { - setMeasurementByIndex(measurement, index); - } - - return; - } -// -------------------------------------------------------- - /* - private void setMeasurementValueByIndex(double value, int index) - { - // System.out.println(" ** RegularTimeSeries.setMeasurementValueByIndex()"); - - Measurement measurement = getMeasurementByIndex(index); - measurement.setValue(value); - } - */ -// -------------------------------------------------------- - /* - private void setMeasurementValueByTime(double value, long time) - { - // System.out.println(" ** RegularTimeSeries.setMeasurementValueByTime()"); - Measurement measurement = getMeasurementByTime(time); - measurement.setValue(value); - } - */ -// -------------------------------------------------------- - - public Measurement getMeasurementByTime(long time) - { - Measurement measurement = null; - int index = -1; - - index = getMeasurementIndexByTime(time); - - if (index != -1) - { - measurement = getMeasurementByIndex(index); - } - - return measurement; - } - - public AbsTimeMeasurement getAbsTimeMeasurementByTime(long time) - { - Measurement measurement = null; - AbsTimeMeasurement absTimeMeasurement = null; - - - measurement = getMeasurementByTime(time); - if (measurement != null) - { - absTimeMeasurement = new AbsTimeMeasurement(measurement, time); - } - - return absTimeMeasurement; - } - -// -------------------------------------------------------- - - public AbsTimeMeasurement getAbsTimeMeasurementByIndex(int index) - { - Measurement measurement = (Measurement)_measurementList.get(index); - long time = getMeasurementTimeByIndex(index); - - AbsTimeMeasurement absTimeMeasurement = new AbsTimeMeasurement(measurement, time); - - return absTimeMeasurement; - - } - -// -------------------------------------------------------- - - public RegularTimeSeries getSubTimeSeries(long startTime, long endTime) - { - /** - * Return the time series that is within this time window, inclusively. - */ - RegularTimeSeries newTs = null; - - newTs = new RegularTimeSeries(startTime, - endTime, - this.getIntervalInHours(), - this.getMeasuringUnit() ); - - boolean firstTime = true; - for (int i= 0; i < this.getMeasurementCount(); i++) - { - AbsTimeMeasurement m = this.getAbsTimeMeasurementByIndex(i); - - //nulls are not possible, so don't check for them - - long mTime = m.getTime(); - if ( (mTime >= startTime) && (mTime <= endTime) ) - { - if (firstTime) - { - newTs = new RegularTimeSeries(mTime, - mTime, - this.getIntervalInHours(), - this.getMeasuringUnit() ); - firstTime = false; - - } - newTs.setMeasurementByTime(m, mTime); - } - } - - return newTs; - - } -// -------------------------------------------------------- -/* - private void setStartTime(long startTime) - { - _startTime = startTime; - } -*/ -//---------------------------------------------------------- - - public long getStartTime() - { - return _startTime; - } -//-------------------------------------------------------- -/* - private void setEndTime(long endTime) - { - _endTime = endTime; - } -*/ -//-------------------------------------------------------- - - public long getEndTime() - { - return _endTime; - } - -// -------------------------------------------------------- - - - public MeasuringUnit getMeasuringUnit() - { - return _measuringUnit; - } - -// -------------------------------------------------------- - -/* - public Measurement getMinMeasurement() - { - Measurement measurement = null; - Measurement minMeasurement = null; - - if (_measurementList.size() > 0) - { - minMeasurement = (Measurement) _measurementList.get(0); - } - - for (int i = 1; i < _measurementList.size(); i++) - { - measurement = (Measurement) _measurementList.get(i); - - if (measurement.getValue() < minMeasurement.getValue()) - { - minMeasurement = measurement; - } - } - - if (minMeasurement != null) - { - minMeasurement = new Measurement(minMeasurement); - } - - return minMeasurement; - } - -//--------------------------------------------------------------------- - - public Measurement getMaxMeasurement() - { - String header = "RegularTimeSeries.getMaxMeasurement(): " + - "where name = " + _name; - - // System.out.println(header + "current time series is " + this._name); - - - Measurement measurement = null; - Measurement maxMeasurement = null; - - MeasuringUnit checkingUnit = this.getMeasuringUnit(); - - double value = 0; - - if (_measurementList.size() > 0) - { - maxMeasurement = (Measurement) _measurementList.get(0); - } - - - for (int i = 1; i < _measurementList.size(); i++) - { - - - measurement = (Measurement) _measurementList.get(i); - value = measurement.getValue(); - - if (! measurement.getUnit().getName().equals(checkingUnit.getName())) - - { - System.out.println(header + " ******* HEY, the expected unit was " + checkingUnit + - " and the received unit was " + measurement.getUnit() + " and the value was " + value); - } - - - if (value > maxMeasurement.getValue()) - { - //System.out.println(header + "value for maxMeasurement so far = " + value); - maxMeasurement = measurement; - } - } //end for - - if (maxMeasurement != null) - { - maxMeasurement = new Measurement(maxMeasurement); - } - - return maxMeasurement; - } - */ - -//--------------------------------------------------------------------- - - public AbsTimeMeasurement getMinMeasurement(long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - - AbsTimeMeasurement minMeasurement = null; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = getAbsTimeMeasurementByIndex(i); - long time = measurement.getTime(); - - if ( (time >= startTime) && (time <= endTime) ) - { - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - - ( (minMeasurement == null) || - (measurement.getValue() < minMeasurement.getValue()) - ) - ) - { - minMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - } //end for i - - // System.out.println("RegularTimeSeries.getMinMeasurement(): result = " + minMeasurement); - - return minMeasurement; - - } - - // --------------------------------------------------------------------- - - public AbsTimeMeasurement getMinMeasurement() - { - - return getMinMeasurement(getStartTime(), getEndTime()); - - } - - //--------------------------------------------------------------------- - public AbsTimeMeasurement getMaxMeasurement(long startTime, long endTime) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement maxMeasurement = null; - - double value = 0; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurement = getAbsTimeMeasurementByIndex(i); - long time = measurement.getTime(); - - if ( (time >= startTime) && (time <= endTime) ) - { - - if ( (measurement.getValue() != _missingValue) && - (measurement.getValue() != _otherMissingValue) && - - - ( (maxMeasurement == null) || - (measurement.getValue() > maxMeasurement.getValue()) - ) - ) - { - maxMeasurement = measurement; - } - } - else if (time > endTime) - { - break; - } - } //end for - - // System.out.println("RegularTimeSeries.getMaxMeasurement(): result = " + maxMeasurement); - - - return maxMeasurement; - } - - //--------------------------------------------------------------------- - - public AbsTimeMeasurement getMaxMeasurement() - { - return getMaxMeasurement(getStartTime(), getEndTime()); - } - - //--------------------------------------------------------------------- - - public static RegularTimeSeries concatenate( RegularTimeSeries ts1, - RegularTimeSeries ts2) - { - String header = "RegularTimeSeries.concatenate(): "; - - long startTime = Math.min(ts1.getStartTime(), ts2.getStartTime()); - long endTime = Math.max(ts1.getEndTime(), ts2.getEndTime()); - - - RegularTimeSeries newTs = - new RegularTimeSeries(startTime, - endTime, - ts1.getIntervalInHours(), - ts1.getMeasuringUnit()); - - long intervalInMillis = ts1.getIntervalInHours() * _millisPerHour; - - // note: the ts1 timeseries takes precedence during overlapping periods - - // insert the ts2 data - for (int i = 0; i < ts2.getMeasurementCount(); i++) - { - Measurement measurement = ts2.getMeasurementByIndex(i); - long time = ts2.getMeasurementTimeByIndex(i); - - - // System.out.println(header + "ts2 " + " time = " + DbTimeHelper.getDateTimeStringFromLongTime(time) + " value = " + measurement.getValue()); - newTs.setMeasurementByTime(measurement, time); - } //end for - - - // insert the ts1 data - for (int i = 0; i < ts1.getMeasurementCount(); i++) - { - Measurement measurement = ts1.getMeasurementByIndex(i); - - long time = ts1.getMeasurementTimeByIndex(i); - - // System.out.println(header + "ts1 " + " time = " + DbTimeHelper.getDateTimeStringFromLongTime(time) + " value = " + measurement.getValue() ); - newTs.setMeasurementByTime(measurement, time); - } //end for - - - return newTs; - } - -// -------------------------------------------------------- - - public void setIntervalInHours(int intervalInHours) - { - _intervalInHours = intervalInHours; - } - - //-------------------------------------------------------- - - public int getIntervalInHours() - { - return _intervalInHours; - } - -// -------------------------------------------------------- - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - if (_name != null) - { - buffer.append("Name: " + getName()); - } - - buffer.append(" Units: " + _measuringUnit + " "); - buffer.append(" Measurement Count = " + getMeasurementCount()); - - buffer.append(" Start Time = " + DbTimeHelper.getDateTimeStringFromLongTime(_startTime)); - buffer.append(" End Time = " + DbTimeHelper.getDateTimeStringFromLongTime(_endTime)); - - buffer.append(" "); - - NumberFormat f = new DecimalFormat("##0.00"); - - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement measurement = getMeasurementByIndex(i); - - //long time = getMeasurementTimeByIndex(i); - //String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - if (! measurement.isMissing() ) - { - double value = measurement.getValue(); - String valueString = f.format(value); - - // buffer.append(timeString + "->"); - buffer.append(valueString + " "); - } - else // it is missing - { - // buffer.append(timeString + "->"); - buffer.append(_missingString + " "); - } - } - return buffer.toString(); - - } - - -// -------------------------------------------------------- - - private static void originalTests() - { - final long millisPerHour = 1000 * 60 * 60; - int hoursCount = 6; - int hoursPerDay = 24; - long startTime = System.currentTimeMillis(); - startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, 1); - - long endTime = startTime + (millisPerHour * hoursCount); - long shift = millisPerHour * hoursCount; - - int hoursPerInterval = 1; - - RegularTimeSeries ts1 = new RegularTimeSeries(startTime, endTime, - hoursPerInterval, MeasuringUnit.mm); - - - long startTime2 = endTime - (3 * millisPerHour); - long endTime2 = startTime2 + (millisPerHour * hoursCount); - RegularTimeSeries ts2 = new RegularTimeSeries(startTime2, endTime2, - hoursPerInterval, - MeasuringUnit.mm); - - - long m1Time = startTime; - long m2Time = startTime2; - for (int i = 0; i <= hoursCount; i++) - { - Measurement measurement = new Measurement(13.0 + i, MeasuringUnit.mm); - ts1.setMeasurementByTime(measurement, m1Time); - - Measurement measurement2 = new Measurement(47.0 + i, MeasuringUnit.mm); - ts2.setMeasurementByTime(measurement2, m2Time); - - m1Time += millisPerHour; - m2Time += millisPerHour; - } - - System.out.println("ts1 = " + ts1); - System.out.println("ts2 = " + ts2); - - - - // test out sub time series - RegularTimeSeries subTimeSeries = ts1.getSubTimeSeries(startTime2, endTime2); - - System.out.println("new start time = " + DbTimeHelper.getDateTimeStringFromLongTime(startTime2) + - " new end time = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime2)); - System.out.println("subTimeSeries = " + subTimeSeries); - - - - - // test out adding measurements that occur before and after the way the time series - // is currently set up - Measurement measurement = new Measurement(999.0, MeasuringUnit.mm); - ts1.setMeasurementByTime(measurement, ts1.getStartTime() - millisPerHour); - - Measurement measurement2 = new Measurement(1000.0, MeasuringUnit.mm); - ts1.setMeasurementByTime(measurement2, ts1.getEndTime() + millisPerHour); - - System.out.println("altered ts1 = " + ts1); - - - // test out adding measurements before and after the current start and end times - // of a RegularTimeSeries - - long newStartTime = ts1.getStartTime()- (5 * millisPerHour); - long newEndTime = ts1.getEndTime() + (5 * millisPerHour); - - ts1.stretchTimeSeries(newStartTime, newEndTime, -99999); - - System.out.println("stretched ts1 = " + ts1); - - - newStartTime += (10 * millisPerHour); - ts1.trimTimeSeriesAtStart(newStartTime); - System.out.println("trimmed ts1 = " + ts1); - - - /* // index testing section - int index = ts1.getMeasurementIndexByTime(startTime); - long time = ts1.getMeasurementTimeByIndex(index); - - int index2 = ts1.getMeasurementIndexByTime(time); - long time2 = ts1.getMeasurementTimeByIndex(index2); - System.out.println("ts1 index = " + index); - System.out.println("ts1 time = " + time); - System.out.println("ts1 index = " + index2); - System.out.println("ts1 time2 = " + time2); - */ - - - - RegularTimeSeries concatTs = RegularTimeSeries.concatenate(ts1, ts2); - - System.out.println("concat Ts = " + concatTs); - } -// -------------------------------------------------------- - private static void testShifting() - { - String header = "RegularTimeSeries.testShifting(): "; - final long MILLIS_PER_HOUR = _millisPerHour; - - int shiftInHours = 12; - - int intervalInHours = 24; - long intervalInMillis = intervalInHours * MILLIS_PER_HOUR; - - long startTime = System.currentTimeMillis(); - startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, intervalInHours); - long endTime = startTime + 3 * 24 * _millisPerHour; - MeasuringUnit unit = MeasuringUnit.inches; - - - - RegularTimeSeries ts1 = new RegularTimeSeries(startTime, endTime, - intervalInHours, unit); - - ts1.shiftStartEndTimeHours(shiftInHours); - startTime = ts1.getStartTime(); - - StringBuffer inBuffer = new StringBuffer(); - StringBuffer outBuffer = new StringBuffer(); - - - //initialize test values - double value = 0.0; - String valueTimeString = null; - - for (long t = startTime; t <= endTime; t+= intervalInMillis ) - { - value += 1.0; - Measurement m = new Measurement(value, unit); - ts1.setMeasurementByTime(m, t); - - valueTimeString = getValueTimeString(t, value); - - inBuffer.append(valueTimeString); - - System.out.println(header + "IN " + valueTimeString); - } - - for (long t = startTime; t <= endTime; t+= intervalInMillis) - { - Measurement m = ts1.getMeasurementByTime(t); - - if (m != null) - { - value = m.getValue(); - } - else - { - value = _missingValue; - } - valueTimeString = getValueTimeString(t, value); - - outBuffer.append(valueTimeString); - - System.out.println(header + "OUT " + valueTimeString); - } - - //verify that what went in is what comes out - if (inBuffer.toString().equals(outBuffer.toString())) - { - System.out.println(header + "The buffers are the same. "); - } - else - { - System.out.println(header + "The buffers are different. "); - } - - } -// -------------------------------------------------------- - static String getValueTimeString(long time, double value) - { - return "Value = " + value + " time = " + - DbTimeHelper.getDateTimeStringFromLongTime(time); - } -// -------------------------------------------------------- - - public static void main(String[] args) - { - - //originalTests(); - - testShifting(); - - } - -// -------------------------------------------------------- - -/* - private void trace() - { - try - { - throw new Exception("trace"); - } - catch(Exception e) - { - e.printStackTrace(); - } - - } -*/ -// -------------------------------------------------------- - - -} //end RegularTimeSeries diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RegularTimeSeriesHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RegularTimeSeriesHolder.java deleted file mode 100644 index 4dd5f97ba2..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RegularTimeSeriesHolder.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Created on Oct 14, 2003 - * - * - * */ -package ohd.hseb.measurement; - -import java.util.*; - -/** - * @author Chip Gobs - * - * This is a simple Holder class for a TimeSeries object - * It will forward TimeSeriesEvents to the listeners. - * It won't notify the listener with the same Receiver as the Event's source. - */ -public class RegularTimeSeriesHolder -{ - private RegularTimeSeries _timeSeries; - private java.util.List _listenerList = new ArrayList(); - - private long _eventCount = 0; - - - public void setTimeSeries(RegularTimeSeries timeSeries) - { - _timeSeries = timeSeries; - } - - public void forwardEvent(TimeSeriesEvent event) - { - event.setEventId(_eventCount); - - notifyListeners(event); - - _eventCount++; - } - - - public RegularTimeSeries getTimeSeries() - { - return _timeSeries; - } - - - - public void addListener(TimeSeriesListener listener) - { - _listenerList.add(listener); - } - - - public void removeListener(TimeSeriesListener listener) - { - _listenerList.remove(listener); - } - - - private void notifyListeners(TimeSeriesEvent event) - { - for (int i = 0 ; i < _listenerList.size(); i++) - { - TimeSeriesListener listener = (TimeSeriesListener) _listenerList.get(i); - - if (listener.getReceiver() != event.getSource()) - { - listener.handleTimeSeriesEvent(event); - } - } - } - - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RelTimeMeasurement.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RelTimeMeasurement.java deleted file mode 100644 index 21d3770f1d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/RelTimeMeasurement.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Created on Aug 25, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.measurement; - -import java.text.*; -import java.util.*; - -/** - * This class represents a Measurement at a time relative to some - * externally defined time. - */ -public class RelTimeMeasurement extends Measurement -{ - private long _relTimeInMillis; //time after or before another base time, defined elsewhere - - //--------------------------------------------------------------- - - public RelTimeMeasurement(double value, long relTimeInMillis, MeasuringUnit unit) - { - super(value, unit); - _relTimeInMillis = relTimeInMillis; - } - - //--------------------------------------------------------------- - - public RelTimeMeasurement(RelTimeMeasurement measurement) - { - super(measurement.getValue(), measurement.getUnit()); - _relTimeInMillis = measurement.getRelativeTime(); - } - - //--------------------------------------------------------------- - public Measurement getConvertedCopy(MeasuringUnit toUnit) - { - - RelTimeMeasurement newMeasurement = new RelTimeMeasurement(this); - - newMeasurement.convert(toUnit); - - return newMeasurement; - } - // --------------------------------------------------------------- - - public long getRelativeTime() - { - return _relTimeInMillis; - } - - //--------------------------------------------------------------- - private String formatTime(long time) - { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); - return formatter.format(new Date(time)); - } - //--------------------------------------------------------------- - - public String toString() - { - return getValue() + " in " + getUnit().getName() + " at " + formatTime(_relTimeInMillis); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeIntervalMeasurement.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeIntervalMeasurement.java deleted file mode 100644 index f534f4adfc..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeIntervalMeasurement.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Created on Sep 26, 2003 - * - * - */ -package ohd.hseb.measurement; - -import java.text.*; -import java.util.*; - -/** - * @author Chip Gobs - * - * This class handles the abstraction of - * a measurement that is taken over a period of time, - * such as 1-hour precipitation totals. - * - */ -public class TimeIntervalMeasurement extends AbsTimeMeasurement -{ - - private static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - private int _intervalInHours = -1; - - - //--------------------------------------------------------------------- - - public TimeIntervalMeasurement(double value, - long endTimeInMillis, - int intervalInHours, - MeasuringUnit unit) - { - super(value, endTimeInMillis, unit); - - setIntervalInHours(intervalInHours); - - return; - } - - //--------------------------------------------------------------------- - - public TimeIntervalMeasurement(TimeIntervalMeasurement measurement) - { - super(measurement.getValue(), - measurement.getTime(), - measurement.getUnit()); - - setIntervalInHours(measurement.getIntervalInHours()); - return; - } - //--------------------------------------------------------------- - public static TimeIntervalMeasurement getConvertedCopy( - TimeIntervalMeasurement origMeasurement, - MeasuringUnit toUnit) - { - TimeIntervalMeasurement newMeasurement = - new TimeIntervalMeasurement(origMeasurement); - - newMeasurement.convert(toUnit); - - return newMeasurement; - } - //--------------------------------------------------------------- - - // --------------------------------------------------------------- - - public long getStartTime() - { - return getTime() - (_intervalInHours * MILLIS_PER_HOUR); - } - - //--------------------------------------------------------------- - - private void setIntervalInHours(int intervalInHours) - { - _intervalInHours = intervalInHours; - } - -// --------------------------------------------------------------- - - public long getEndTime() - { - return getTime(); - } - //--------------------------------------------------------------- -/* - private void setEndTime(long endTime) - { - setTime(endTime); - } -*/ - //--------------------------------------------------------------- - - public int getIntervalInHours() - { - return _intervalInHours; - } - //--------------------------------------------------------------- - - private String formatTime(long time) - { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); - return formatter.format(new Date(time)); - } - - - //--------------------------------------------------------------- - - public String toString() - { - - String outString = getValue() + " in " + getUnit().getName() + " ending at " + - formatTime(getEndTime()) + - " over " + _intervalInHours + " hours. "; - - return outString; - } - //--------------------------------------------------------------------- - -} //end class TimeIntervalMeasurement - - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesEvent.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesEvent.java deleted file mode 100644 index 67a44d30b8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesEvent.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Created on Apr 23, 2004 - * - * - */ -package ohd.hseb.measurement; - -/** - * @author GobsC - * - * - */ -public class TimeSeriesEvent -{ - - private String _message = null; - private Object _source = null; - private long _eventId = 0; - - public TimeSeriesEvent(String message, Object source) - { - _message = message; - _source = source; - - } - - public void setMessage(String message) - { - _message = message; - } - - public String getMessage() - { - return _message; - } - - public void setSource(Object source) - { - _source = source; - } - - public Object getSource() - { - return _source; - } - - public void setEventId(long eventId) - { - _eventId = eventId; - } - - public long getEventId() - { - return _eventId; - } - - public String toString() - { - String outString = "Event #" + this.getEventId() + ": " + this.getMessage() ; - - return outString; - - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesListener.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesListener.java deleted file mode 100644 index ef9c78a727..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesListener.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Created on Apr 23, 2004 - * - * - */ -package ohd.hseb.measurement; - -/** - * @author GobsC - * - * Listener for TimeSeriesEvent objects - */ -public interface TimeSeriesListener -{ - - void handleTimeSeriesEvent(TimeSeriesEvent event); - Object getReceiver(); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesTotaller.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesTotaller.java deleted file mode 100644 index 0180de66ea..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/measurement/TimeSeriesTotaller.java +++ /dev/null @@ -1,170 +0,0 @@ -package ohd.hseb.measurement; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.TimeHelper; - -public class TimeSeriesTotaller -{ - public final static long MILLIS_PER_HOUR = 1000 * 60 * 60; - - // -------------------------------------------------------------------------------- - public static RegularTimeSeries - getRegularTimeSeries(int newIntervalInHours, - int shiftHours, - RegularTimeSeries origTimeSeries) - { - - String header = "TimeSeriesTotaller.getRegularTimeSeries(): "; - - long intervalInMillis = newIntervalInHours * MILLIS_PER_HOUR; - - long startTime = determineStartTime(origTimeSeries.getStartTime(), - newIntervalInHours, - shiftHours); - - long endTime = determineEndTime(origTimeSeries.getEndTime(), - newIntervalInHours, - shiftHours); - - // System.out.println(header + - // "startTime = " + getTimeString(startTime) + - // " endTime = " + getTimeString(endTime)); - - MeasuringUnit unit = origTimeSeries.getMeasuringUnit(); - - RegularTimeSeries newTs = new RegularTimeSeries(startTime, - endTime, - newIntervalInHours, - unit ); - newTs.shiftStartEndTimeHours(shiftHours); - - //start at end of period that we want to calculate - long scanStartTime = newTs.getStartTime(); - - long lookBackTimeInMillis = intervalInMillis - MILLIS_PER_HOUR; - - //calculate the totals - for (long newTime = scanStartTime; - newTime <= endTime; - newTime += intervalInMillis) - { - double totalValue = 0.0; - - // System.out.println("-begin -----newTime = " + getTimeString(newTime)); - - //for each original interval - for (long origTime = newTime - lookBackTimeInMillis; - origTime <= newTime; - origTime+= MILLIS_PER_HOUR) - { - // System.out.println("origTime = " + getTimeString(origTime)); - Measurement m = origTimeSeries.getMeasurementByTime(origTime); - if (m != null) - { - totalValue += m.getValue(); - } - } - // System.out.println("-end -----newTime = " + getTimeString(newTime) + - // " totalValue = " + totalValue); - - Measurement m = new Measurement(totalValue, unit); - - newTs.setMeasurementByTime(m, newTime); - - } - - - return newTs; - } - - // -------------------------------------------------------------------------------- - private static String getTimeString(long time) - { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } - - // -------------------------------------------------------------------------------- - - public static long determineStartTime(long origHourlyStartTime, int intervalInHours, int shiftHours) - { - - long newStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - origHourlyStartTime, intervalInHours); - - newStartTime += intervalInHours * MILLIS_PER_HOUR; - - // newStartTime += shiftHours; - - return newStartTime; - } - // -------------------------------------------------------------------------------- - public static long determineEndTime(long origHourlyEndTime, int intervalInHours, int shiftHours) - { - - long endStartTime = TimeHelper.truncateTimeInMillisToNearestHour( - origHourlyEndTime, intervalInHours); - - endStartTime += intervalInHours * MILLIS_PER_HOUR; - - // endStartTime += shiftHours; - - return endStartTime; - } - // -------------------------------------------------------------------------------- - - public static RegularTimeSeries - getRegularTimeSeries(int intervalInHours, - RegularTimeSeries origTimeSeries) - { - - return getRegularTimeSeries(intervalInHours, 0, origTimeSeries ); - } - - // -------------------------------------------------------------------------------- - - public static void main(String[] stringArgs) - { - long startTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 24); - long endTime = startTime + (3 * 24*MILLIS_PER_HOUR); - MeasuringUnit unit = MeasuringUnit.inches; - - RegularTimeSeries origTimeSeries = new RegularTimeSeries(startTime, - endTime, - 1, - unit); - int intervalInHours = 6; - int shiftInHours = 0; - RegularTimeSeries totalledTimeSeries = null; - - //initialize test values - double value = 0.0; - for (long t = startTime; t <= endTime; t+= MILLIS_PER_HOUR) - { - Measurement m = new Measurement(value, unit); - value += 1.0; - origTimeSeries.setMeasurementByTime(m, t); - } - - //calculate 6 hour values - - intervalInHours = 3; - shiftInHours = 2; - totalledTimeSeries = - TimeSeriesTotaller.getRegularTimeSeries( - intervalInHours, - shiftInHours, - origTimeSeries); - - - - System.out.println("original time series = \n" + origTimeSeries); - - System.out.println("for every " + intervalInHours + - " hours : \n " + totalledTimeSeries); - - return; - } - - // -------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/DurationCode.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/DurationCode.java deleted file mode 100644 index 0d8f30d1bd..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/DurationCode.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Created on Aug 20, 2004 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * - */ -public class DurationCode -{ - public static int getHoursFromCode(int durationCode) - { - int hours = 0; - if ((durationCode >= 1000) && (durationCode < 2000)) - { - hours = durationCode - 1000; - } - else if (durationCode >= 2000 && (durationCode < 3000)) - { - int days = durationCode - 2000; - hours = days * 24; - } - - - return hours; - } - - - public static int getCodeFromHours(int hours) - { - int durationCode = 0; - - if (hours <= 999) - { - durationCode = 1000 + hours; - } - - return durationCode; - } - - public static int getCodeFromHoursString(String hoursString) - { - int hours = Integer.parseInt(hoursString); - int durationCode = getCodeFromHours(hours); - - return durationCode; - - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjuster.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjuster.java deleted file mode 100644 index bf2b560e33..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjuster.java +++ /dev/null @@ -1,924 +0,0 @@ -/* - * Created on Aug 27, 2004 - * - * - */ -package ohd.hseb.model; - -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import java.util.HashMap; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -//import ohd.hseb.util.CodeTimer; - -/** - * @author Chip Gobs - * - * The job of this class is to manage the blending of observed and forecast data such - * that the forecast time series is adjusted to match better with the observed data. - */ -public class ForecastAdjuster -{ - private static final long MILLIS_PER_MINUTE = 60 * 1000; - private static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - - private ForecastAdjusterParams _params = null; - private List _observedForecastPairList = null; - private Map _observedForecastMap = null; - private long _lastObservedTimeToUseAsInput = 0; - - private final static boolean _debug = false; - - // ---------------------------------------------------------------------------------- - - public ForecastAdjuster(ForecastAdjusterParams params) - { - // String header = "ForecastAdjuster()" ; - - // System.out.println("inside " + header); - - _params = params; - - _observedForecastPairList = new ArrayList(); - _observedForecastMap = new HashMap(); - } - - - // ---------------------------------------------------------------------------------- - public RegularTimeSeries getAdjustedTimeSeries(IrregularTimeSeries observedTs, - RegularTimeSeries origFcstTs ) - { - RegularTimeSeries adjustedFcstTs = null; - - ObservedForecastMeasurementPair previousPair = null; - ObservedForecastMeasurementPair nextPair = null; - - AbsTimeMeasurement origFcstMeasurement = null; - AbsTimeMeasurement adjustedMeasurement = null; - - - //trim the observedTimeSeries as needed - IrregularTimeSeries trimmedObsTs = observedTs.getSubTimeSeries(observedTs.getStartTime(), - getLastObservedTimeToUseAsInput()); - - int allowableBlendingHours = _params.getBlendingHours(); - - ForecastBlender forwardBlender = new ForecastBlender(allowableBlendingHours); - ForecastBlender backwardBlender = new ForecastBlender(allowableBlendingHours); - - - if ( _params.shouldDoAdjustment()) - { - // System.out.println(header + "Actually doing the adjustment"); - //create the data structure for helping go from a forecast point to its matching - //observed point (if any) - - buildObsAndForecastPairList( trimmedObsTs, - origFcstTs, - _params.getPairingTimeMinutes() * MILLIS_PER_MINUTE); - - // create new forecast time series - adjustedFcstTs = new RegularTimeSeries(origFcstTs.getStartTime(), origFcstTs.getEndTime(), - origFcstTs.getIntervalInHours(), - origFcstTs.getMeasuringUnit()); - - //for each forecast value - for (long time = origFcstTs.getStartTime(); time <= origFcstTs.getEndTime(); time += MILLIS_PER_HOUR ) - { - origFcstMeasurement = origFcstTs.getAbsTimeMeasurementByTime(time); - - //used for debugging/printing purposes - String fcstTimeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - adjustedMeasurement = new AbsTimeMeasurement(origFcstMeasurement); - - //try to find the origFcstMeasurement in the hashMap - AbsTimeMeasurement matchingObsMeasurement = - (AbsTimeMeasurement) _observedForecastMap.get(origFcstMeasurement); - - - if (matchingObsMeasurement != null) //there is a matching observedMeasurement, use direct adjustment - { - - performMatchingAdjustment(matchingObsMeasurement, - adjustedMeasurement, - forwardBlender, - backwardBlender, - fcstTimeString); - - - } - else // can't do direct adjustment, try interpolation and blending - { - previousPair = findBestPreviousPairByTime(time); - nextPair = findBestNextPairByTime(time); - - boolean doBlending = performInterpolation(origFcstMeasurement, - adjustedMeasurement, - previousPair, - nextPair, - forwardBlender, - backwardBlender, - fcstTimeString); - - if (doBlending) //pairs not close enough to each other, or at least - // one pair is missing, so try to use blending - { - performBlending(origFcstMeasurement, - adjustedMeasurement, - previousPair, - nextPair, - forwardBlender, - backwardBlender, - fcstTimeString); - } - - } //end else for unmatched fcst measurements - - if (adjustedMeasurement.getValue() < 0.0) - { - adjustedMeasurement.setValue(0.0); - } - - adjustedFcstTs.setMeasurementByTime(adjustedMeasurement, time); - - } //end for each forecast value - - } - else //don't adjust anything - { - if (_debug) - { - System.out.println("Not doing the adjustment"); - } - adjustedFcstTs = origFcstTs; - } - - return adjustedFcstTs; - - } - // ------------------------------------------------------------------------------------------------- - private void performMatchingAdjustment(AbsTimeMeasurement matchingObsMeasurement, - AbsTimeMeasurement adjustedMeasurement, - ForecastBlender forwardBlender, - ForecastBlender backwardBlender, - String fcstTimeString) - { - - if (_debug) - { - double amount = matchingObsMeasurement.getValue() - adjustedMeasurement.getValue(); - System.out.println(fcstTimeString + " using direct correction by pairing. Adjusting by " + amount); - } - //set value to current pairing observed value - //adjustedMeasurement = new AbsTimeMeasurement(origFcstMeasurement); - adjustedMeasurement.setValue(matchingObsMeasurement.getValue()); - - forwardBlender.clearBlender(); - backwardBlender.clearBlender(); - - } - - - // ------------------------------------------------------------------------------------------------- - - private boolean performInterpolation(AbsTimeMeasurement origFcstMeasurement, - AbsTimeMeasurement adjustedMeasurement, - ObservedForecastMeasurementPair previousPair, - ObservedForecastMeasurementPair nextPair, - ForecastBlender forwardBlender, - ForecastBlender backwardBlender, - String fcstTimeString) - { - AbsTimeMeasurement previousObs = null; - AbsTimeMeasurement nextObs = null; - - boolean doBlending = false; - - if ((previousPair != null) && (nextPair != null)) // - { - - previousObs = previousPair.getObservedMeasurement(); - nextObs = nextPair.getObservedMeasurement(); - - long prevTime = previousObs.getTime(); - long nextTime = nextObs.getTime(); - - //consider adding a method to AbsTimeMeasurement to - // allow for time window comparisons - - long timeDiff = nextTime - prevTime; - - // if can do interpolation - if (timeDiff <= _params.getInterpolationHours() * MILLIS_PER_HOUR) - { - - if (_debug) - { - System.out.print(fcstTimeString + " using interpolation by"); - } - adjustByInterpolation(origFcstMeasurement, - adjustedMeasurement, - previousPair, - nextPair); - - forwardBlender.clearBlender(); - backwardBlender.clearBlender(); - doBlending = false; - } - else //can't do interpolation, need to try blending - { - doBlending = true; - } - } //end if previousPair and nextPair not null - - else //can't do interpolation, need to try blending - { - doBlending = true; - } - - - return doBlending; - } - // ------------------------------------------------------------------------------------------------- - - private AbsTimeMeasurement performBlending(AbsTimeMeasurement origFcstMeasurement, - AbsTimeMeasurement adjustedMeasurement, - ObservedForecastMeasurementPair previousPair, - ObservedForecastMeasurementPair nextPair, - ForecastBlender forwardBlender, - ForecastBlender backwardBlender, - String fcstTimeString) - { - AbsTimeMeasurement forwardAdjustment = forwardBlender.getBlendAdjustment(previousPair, origFcstMeasurement); - AbsTimeMeasurement backwardAdjustment = backwardBlender.getBlendAdjustment(nextPair, origFcstMeasurement); - - AbsTimeMeasurement blendingAdjustment = combineBlendingAdjustments(forwardAdjustment, - backwardAdjustment); - adjustedMeasurement.addMeasurement(blendingAdjustment); - - if (blendingAdjustment.getValue() != 0.0) - { - if (_debug) - { - System.out.println(fcstTimeString + " Total blending adjustment = " + blendingAdjustment.getValue() + - " original value = " + origFcstMeasurement.getValue() + - " new value = " + adjustedMeasurement.getValue()); - } - } - else - { - if (_debug) - { - System.out.println(fcstTimeString + " No adjustment."); - } - } - - return adjustedMeasurement; - } - - // ------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement combineBlendingAdjustments(AbsTimeMeasurement forwardBlendAdjustment, - AbsTimeMeasurement backwardBlendAdjustment) - { - - double forwardValue = forwardBlendAdjustment.getValue(); - double backwardValue = backwardBlendAdjustment.getValue(); - - double adjustmentValue = forwardValue + backwardValue; - - int notEqualsZeroCount = 0; - - //count the non-zero adjustments - if (forwardValue != 0.0) - { - notEqualsZeroCount ++; - - } - if (backwardValue != 0.0) - { - notEqualsZeroCount ++; - - } - - if (notEqualsZeroCount > 0) - { - adjustmentValue /= (double) notEqualsZeroCount; - } - else - { - adjustmentValue = 0.0; - } - - - if (_debug) - { - System.out.println("forward blending Adjustment = " + forwardValue + - " backward blending adjustment = " + backwardValue); - } - - AbsTimeMeasurement blendingAdjustment = new AbsTimeMeasurement(forwardBlendAdjustment); //sets the time, will change the value - blendingAdjustment.setValue(adjustmentValue); - - return blendingAdjustment; - - - } - - // ---------------------------------------------------------------------------------- - private void adjustByInterpolation(AbsTimeMeasurement origFcstMeasurement, - AbsTimeMeasurement adjustedFcstMeasurement, - ObservedForecastMeasurementPair prevPair, - ObservedForecastMeasurementPair nextPair) - { - - ForecastInterpolationMethod blendingMethod = _params.getBlendingMethod(); - - AbsTimeMeasurement prevObs = prevPair.getObservedMeasurement(); - AbsTimeMeasurement prevFcst = prevPair.getForecastMeasurement(); - - AbsTimeMeasurement nextObs = nextPair.getObservedMeasurement(); - AbsTimeMeasurement nextFcst = nextPair.getForecastMeasurement(); - - long origFcstTime = origFcstMeasurement.getTime(); - - if ( (blendingMethod != null ) && - (blendingMethod.equals(ForecastInterpolationMethod.RATIO) )) - { - double ratio1 = prevObs.getValue() / prevFcst.getValue(); - double ratio2 = nextObs.getValue() / nextFcst.getValue(); - - double ratioDiff = Math.abs(ratio1 - ratio2); - - //if out of sanity range, then do DIFFERENCES anyway - if ( (ratio1 > 5.0) || (ratio2 > 5.0) || (ratioDiff > 2.0) ) - { - System.out.println(" differences "); - double adjustment = getAdjustmentUsingDifferences(origFcstTime, prevPair, nextPair); - double oldValue = adjustedFcstMeasurement.getValue(); - adjustedFcstMeasurement.setValue(oldValue + adjustment); - } - else // it is OK to use ratio method - { - System.out.println(" ratios "); - double adjustment = getAdjustmentUsingRatios(origFcstTime, prevPair, nextPair); - double oldValue = adjustedFcstMeasurement.getValue(); - adjustedFcstMeasurement.setValue(oldValue * adjustment); - } - } - else //use differences - { - System.out.println(" differences "); - double adjustment = getAdjustmentUsingDifferences(origFcstTime, prevPair, nextPair); - double oldValue = adjustedFcstMeasurement.getValue(); - adjustedFcstMeasurement.setValue(oldValue + adjustment); - - } - return; - } - - // ---------------------------------------------------------------------------------- - private double getAdjustmentUsingDifferences(long origFcstTime, - ObservedForecastMeasurementPair prevPair, - ObservedForecastMeasurementPair nextPair) - { - AbsTimeMeasurement prevObs = prevPair.getObservedMeasurement(); - AbsTimeMeasurement prevFcst = prevPair.getForecastMeasurement(); - - AbsTimeMeasurement nextObs = nextPair.getObservedMeasurement(); - AbsTimeMeasurement nextFcst = nextPair.getForecastMeasurement(); - - - double diff1 = prevObs.getValue() - prevFcst.getValue(); - double diff2 = nextObs.getValue() - nextFcst.getValue(); - - AbsTimeMeasurement diff1Measurement = - new AbsTimeMeasurement(diff1, prevObs.getTime(), prevObs.getUnit()); - - AbsTimeMeasurement diff2Measurement = - new AbsTimeMeasurement(diff2, nextObs.getTime(), nextObs.getUnit()); - - - AbsTimeMeasurement adjustmentMeasurement = - interpolate(diff1Measurement, diff2Measurement, origFcstTime); - - - double adjustmentValue = adjustmentMeasurement.getValue(); - - return adjustmentValue; - - } - - // ---------------------------------------------------------------------------------- - - - private double getAdjustmentUsingRatios(long origFcstTime, - ObservedForecastMeasurementPair prevPair, - ObservedForecastMeasurementPair nextPair) - { - AbsTimeMeasurement prevObs = prevPair.getObservedMeasurement(); - AbsTimeMeasurement prevFcst = prevPair.getForecastMeasurement(); - - AbsTimeMeasurement nextObs = nextPair.getObservedMeasurement(); - AbsTimeMeasurement nextFcst = nextPair.getForecastMeasurement(); - - - double ratio1 = prevObs.getValue() / prevFcst.getValue(); - double ratio2 = nextObs.getValue() / nextFcst.getValue(); - - AbsTimeMeasurement ratio1Measurement = - new AbsTimeMeasurement(ratio1, prevObs.getTime(), prevObs.getUnit()); - - AbsTimeMeasurement ratio2Measurement = - new AbsTimeMeasurement(ratio2, nextObs.getTime(), nextObs.getUnit()); - - AbsTimeMeasurement adjustmentMeasurement = - AbsTimeMeasurement.interpolate(ratio1Measurement, ratio2Measurement, origFcstTime); - - double adjustmentValue = adjustmentMeasurement.getValue(); - - return adjustmentValue; - } - - // ---------------------------------------------------------------------------------- - - private void buildObsAndForecastPairList(IrregularTimeSeries observedTs, - RegularTimeSeries forecastTs, - long maxTimeDifferenceForPairing) - - { - // String header = "ForecastAdjuster.buildObsAndForecastPairList(): "; - - //initialize the internal structures - _observedForecastPairList = new ArrayList(); - _observedForecastMap = new HashMap(); - - - // for each forecast value - for (int fcstIndex = 0; fcstIndex < forecastTs.getMeasurementCount(); fcstIndex++) - { - - AbsTimeMeasurement forecastMeasurement = - forecastTs.getAbsTimeMeasurementByIndex(fcstIndex); - - findObsAndForecastPairAndAddtoList(forecastMeasurement, observedTs, maxTimeDifferenceForPairing); - - - } //end for each forecast value - - return; - - } // buildObsAndForecastPairList - // ----------------------------------------------------------------------------------------------- - private void findObsAndForecastPairAndAddtoList(AbsTimeMeasurement forecastMeasurement, - IrregularTimeSeries observedTs, - long maxTimeDifferenceForPairing) - { - - long forecastTime = 0; - long obsTime = 0; - long timeDiff = 0; - - int startingObsIndex = 0; - - forecastTime = forecastMeasurement.getTime(); - - //set up inner loop variables - boolean foundFirstLegalMatch = false; - long smallestTimeDifference = -1; - AbsTimeMeasurement bestObsMeasurement = null; - boolean done = false; - - // System.out.println(header + "forecastMeasurement = " + forecastMeasurement); - -// look at each observed to find the best match (if any) for this forecast value - - - for (int obsIndex = startingObsIndex; - (!done && (obsIndex < observedTs.getMeasurementCount())); - obsIndex++) - { - AbsTimeMeasurement obsMeasurement = - observedTs.getAbsTimeMeasurementByIndex(obsIndex); - - obsTime = obsMeasurement.getTime(); - - - timeDiff = Math.abs(forecastTime - obsTime); - - // observed is in valid range for pairing - if (timeDiff <= maxTimeDifferenceForPairing) - { - if (! foundFirstLegalMatch) - { - foundFirstLegalMatch = true; - smallestTimeDifference = timeDiff; - bestObsMeasurement = obsMeasurement; - } - else //have already found a valid match for this forecast point - { - if (timeDiff < smallestTimeDifference) - { - smallestTimeDifference = timeDiff; - bestObsMeasurement = obsMeasurement; - } - else //we have gone past the best-matching observed - //we have already found smallest time difference - //(list is sorted in ascending order by time) - { - done = true; - startingObsIndex = obsIndex; //next time we do the inner loop, start here - - } - } - } - else // observed is not within valid range for pairing - { - if (foundFirstLegalMatch) // we now know the best match - { - done = true; - startingObsIndex = obsIndex; //next time we do the inner loop, start here - - } - else // (! foundFirstLegalMatch) - { - if (obsTime > forecastTime) - { - // there is no match for this forecast measurement, - // since we have passed the forecastTime and - // are out of the time window - done = true; - startingObsIndex = obsIndex; - } - else // obsTime <= forecastTime, actually, if it were =, the time window would match - { - //System.out.println("obsTime < forecastTime"); - // we need to keep looking, because we have not - // yet gotten in range - } - } //end else ! foundFirstLegalMatch - - } //end else observed not within valid range for printing - - - } //end for each observed - - - //check to see if any matches were found - // if so, then add the pair of points to the list and map - if (foundFirstLegalMatch) - { - ObservedForecastMeasurementPair pair = new ObservedForecastMeasurementPair( - bestObsMeasurement, forecastMeasurement); - - _observedForecastPairList.add(pair); - _observedForecastMap.put(forecastMeasurement, bestObsMeasurement); - - if (_debug) - { - System.out.println("pair = " + pair); - } - } - else - { - - //System.out.println("did not find a pair for " + forecastMeasurement); - } - - - } // end findObsAndForecastPairAndAddtoList - - // ----------------------------------------------------------------------------------------------- - - - private ObservedForecastMeasurementPair findBestNextPairByTime(long targetTime) - { - ObservedForecastMeasurementPair nextPair = null; - ObservedForecastMeasurementPair currentPair = null; - boolean done = false; - - for (int i = 0; !done && i < _observedForecastPairList.size(); i++) - { - currentPair = (ObservedForecastMeasurementPair) _observedForecastPairList.get(i); - if (currentPair.getForecastMeasurement().getTime() > targetTime) - { - nextPair = currentPair; - done = true; - } - } - - return nextPair; - } -// ----------------------------------------------------------------------------------------------- - private ObservedForecastMeasurementPair findBestPreviousPairByTime(long targetTime) - { - ObservedForecastMeasurementPair previousPair = null; - ObservedForecastMeasurementPair currentPair = null; - boolean done = false; - - for (int i = 0; !done && i < _observedForecastPairList.size(); i++) - { - currentPair = (ObservedForecastMeasurementPair) _observedForecastPairList.get(i); - if (currentPair.getForecastMeasurement().getTime() < targetTime) - { - previousPair = currentPair; - } - else // m.time >= targetTime - { - done = true; - } - } - - return previousPair; - } -// ----------------------------------------------------------------------------------------------- - - private ObservedForecastMeasurementPair oldFindBestNextPairByTime( - IrregularTimeSeries observedTs, - RegularTimeSeries forecastTs, - long targetTime, - long maxTimeDifferenceForPairing) - { - ObservedForecastMeasurementPair pair = null; - - IrregularTimeSeries choppedObservedTs = observedTs.getSubTimeSeries( - targetTime, observedTs.getEndTime()); - - AbsTimeMeasurement currentObsMeasurement = null; - AbsTimeMeasurement forecastMeasurement = null; - - boolean done = false; - long obsTime = 0; - // the measurements returned from getAbsTimeMeasurementByIndex(index) - // are in ascending order - // from earliest to latest in time - - // start near or at targetTime and work forward in time - for (int i = 0; (!done && i < choppedObservedTs.getMeasurementCount()); i++) - { - currentObsMeasurement = choppedObservedTs.getAbsTimeMeasurementByIndex(i); - obsTime = currentObsMeasurement.getTime(); - - forecastMeasurement = - findClosestForecastByObsTimeAtOrAfterTargetTime(forecastTs, - obsTime, - targetTime); - - if (areMeasurementsCloseEnoughInTime(forecastMeasurement, - currentObsMeasurement, maxTimeDifferenceForPairing)) - { - - pair = new ObservedForecastMeasurementPair( - currentObsMeasurement, forecastMeasurement); - - done = true; - } - - else - //keep looking - { - - } - } //end for - - - return pair; - - } - - // --------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement findClosestForecastByObsTimeAtOrAfterTargetTime(RegularTimeSeries forecastTs, - long obsTime, long targetTime) - { - //find the closest forecast (by time) to the obstime. - //The forecast found must be at or after the targetTime - - boolean done = false; - boolean firstTime = true; - long smallestTimeDiff = 0; - long timeDiff = 0; - AbsTimeMeasurement bestFcstMeasurement = null; - - - for (int i = 0; !done && i < forecastTs.getMeasurementCount(); i++) - { - - AbsTimeMeasurement fcstMeasurement = forecastTs.getAbsTimeMeasurementByIndex(i); - long fcstTime = fcstMeasurement.getTime(); - - if (fcstTime >= targetTime) - { - if ( firstTime ) //first time, do some initialization - { - smallestTimeDiff = Math.abs(obsTime - fcstTime); - bestFcstMeasurement = fcstMeasurement; - firstTime = false; - } - else //not the first iteration - { - timeDiff = Math.abs(obsTime - fcstTime); - - if (timeDiff < smallestTimeDiff) - { - smallestTimeDiff = timeDiff; - bestFcstMeasurement = fcstMeasurement; - } - else //we are getting farther from the obsTime, so stop - { - done = true; - } - } - - } - else //fcstTime < targetTime, so we need to just keep iterating - { - // do nothing - } - - } - - return bestFcstMeasurement; - } - - // ----------------------------------------------------------------------------------------------- - - private boolean areMeasurementsCloseEnoughInTime(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long maxMillisForCloseness) - { - boolean result = false; - - if ((m1 != null) && (m2 != null)) - { - long timeDiff = m1.getTime() - m2.getTime(); - - if (Math.abs(timeDiff) <= maxMillisForCloseness) - { - result = true; - } - } - - return result; - } - // ---------------------------------------------------------------------------------- - public static AbsTimeMeasurement interpolate(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long desiredTime) - { - long t1 = m1.getTime(); - long t2 = m2.getTime(); - - double value1 = m1.getValue(); - double value2 = m2.getValue(); - - double slope = (value2 - value1) / (t2 - t1); - double intercept = (value1) - (slope * t1); - - double value = (slope * desiredTime) + intercept; - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, - desiredTime, m1.getUnit()); - - measurement.setIsInterpolated(true); - - return measurement; - } - - // ---------------------------------------------------------------------------------- - - - public ForecastAdjusterParams getParams() - { - return _params; - } - - // ---------------------------------------------------------------------------------- - - public void setParams(ForecastAdjusterParams params) - { - _params = params; - } - - // ---------------------------------------------------------------------------------- - public static void main(String[] argStringArray) - { - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - ForecastAdjusterParams params = new ForecastAdjusterParams(); - params.setBlendingHours(5); - params.setBlendingMethod(ForecastInterpolationMethod.DIFFERENCE); - params.setShouldDoAdjustment(true); - - ForecastAdjuster adjuster = new ForecastAdjuster(params); - - long fcstStartTime = System.currentTimeMillis(); - long fcstEndTime = fcstStartTime + (7 * 24 * MILLIS_PER_HOUR); //7 days - - long obsStartTime = fcstStartTime - (3 * 24 * MILLIS_PER_HOUR); //3 days before fcst start - long obsEndTime = fcstStartTime + (7 * MILLIS_PER_HOUR); // 7 hours after fcst start - - IrregularTimeSeries observedTs = new IrregularTimeSeries(dischargeUnit); - RegularTimeSeries forecastTs = - new RegularTimeSeries(fcstStartTime, fcstEndTime, 1, dischargeUnit); - - - - // load up the forecast time series - double[] fcstMeasurementValueArray = {20, 21, 22, 24, 26, 30, 35, 40, 41, 42, 43, 45, 55, 67, 43, 32, 31, 30, 29, 28, 27, 26, 25 }; - - int index = 0; - - for (long time = fcstStartTime; time <= fcstEndTime; time+= MILLIS_PER_HOUR) - { - Measurement m = new Measurement(fcstMeasurementValueArray[index], dischargeUnit); - forecastTs.setMeasurementByTime(m, time); - - index++; - if (index == fcstMeasurementValueArray.length) - { - index = 0; - } - } - - - // load up the observed time series - index = 0; - double[] obsMeasurementValueArray = {18, 19, 20, 22, 24, 28, 33, 28, 39, 40, 41, 43, 53, 57, 41, 29, 29, 28, 27, 26, 26, 24, 28 }; - - long MILLIS_PER_MINUTE = 1000 * 60; - for (long time = obsStartTime; time <= obsEndTime; time+= 11 * MILLIS_PER_MINUTE) - { - AbsTimeMeasurement m = new AbsTimeMeasurement(obsMeasurementValueArray[index], time, dischargeUnit); - - observedTs.insertMeasurement(m); - - index++; - if (index == obsMeasurementValueArray.length) - { - index = 0; - } - } - - - RegularTimeSeries adjustedForecastTs = null; - - adjustedForecastTs = adjuster.getAdjustedTimeSeries(observedTs, forecastTs); - - - //print results - System.out.println("observedTs = " + observedTs + "\n"); - - System.out.println("original forecast Ts = " + forecastTs + "\n"); - System.out.println("adjusted forecast Ts = " + adjustedForecastTs); - - } - - // ---------------------------------------------------------------------------------- - - /** - * @param lastObservedTimeToUseAsInput The lastObservedTimeToUseAsInput to set. - */ - public void setLastObservedTimeToUseAsInput(long lastObservedTimeToUseAsInput) - { - // String header = " ForecastAdjuster.setLastObservedTimeToUseAsInput()"; - // System.out.println(header + "lastObservedTimeToUseAsInput = " + - // DbTimeHelper.getDateTimeStringFromLongTime(lastObservedTimeToUseAsInput)); - _lastObservedTimeToUseAsInput = lastObservedTimeToUseAsInput; - } - - // ---------------------------------------------------------------------------------- - - /** - * @return Returns the lastObservedTimeToUseAsInput. - */ - public long getLastObservedTimeToUseAsInput() - { - // String header = " ForecastAdjuster.getLastObservedTimeToUseAsInput()"; - // System.out.println(header + "lastObservedTimeToUseAsInput = " + - // DbTimeHelper.getDateTimeStringFromLongTime(_lastObservedTimeToUseAsInput)); - return _lastObservedTimeToUseAsInput; - } - // ---------------------------------------------------------------------------------- - - - private class BlendingData - { - - boolean _usedBlend = false; - int _blendHoursCount = 0; - double _blendAmount = 0.0; - - - - - } - // ---------------------------------------------------------------------------------- - - -} //end ForecastAdjuster diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjusterParams.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjusterParams.java deleted file mode 100644 index ff7a1a90d2..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjusterParams.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Created on Aug 27, 2004 - * - */ -package ohd.hseb.model; - -/** - * @author Chip Gobs - * - * This class is holds the blending parameters for ForecastAdjuster - */ - -public class ForecastAdjusterParams -{ - - private boolean _shouldDoAdjustment = false; - private int _pairingTimeMinutes = 0; - private int _interpolationHours = 0; - private int _blendingHours = 0; - private int _maxBlendingHours = 500; - private ForecastInterpolationMethod _blendingMethod = ForecastInterpolationMethod.DIFFERENCE; - - - // ------------------------------------------------------------------------------- - /** - * @param useBlending The useBlending to set. - */ - public void setShouldDoAdjustment(boolean shouldDoAdjustment) - { - // String header = "ForecastAdjusterParams.setShouldDoAdjustment():"; - // System.out.println(header + "shouldDoAdjustment now = " + shouldDoAdjustment); - this._shouldDoAdjustment = shouldDoAdjustment; - } -// ------------------------------------------------------------------------------- - - /** - * @return Returns whether blending is on or off. - */ - public boolean shouldDoAdjustment() - { - return _shouldDoAdjustment; - } -// ------------------------------------------------------------------------------- - - /** - * @param blendingHours The blendingHours to set. - */ - public void setBlendingHours(int blendingHours) - { - _blendingHours = blendingHours; - } - -// ------------------------------------------------------------------------------- - - /** - * @return Returns the blendingHours. - */ - public int getBlendingHours() - { - return _blendingHours; - } - -// ------------------------------------------------------------------------------- - - /** - * @param blendMethod The blendMethod to set. - */ - public void setBlendingMethod(ForecastInterpolationMethod blendMethod) - { - _blendingMethod = blendMethod; - } -// ------------------------------------------------------------------------------- - - /** - * @return Returns the blendMethod. - */ - public ForecastInterpolationMethod getBlendingMethod() - { - return _blendingMethod; - } -// ------------------------------------------------------------------------------- - /** - * @param interpolationHours The interpolationHours to set. - */ - public void setInterpolationHours(int interpolationHours) - { - _interpolationHours = interpolationHours; - } - /** - * @return Returns the interpolationHours. - */ - public int getInterpolationHours() - { - return _interpolationHours; - } - /** - * @param pairingTimeMinutes The pairingTimeMinutes to set. - */ - public void setPairingTimeMinutes(int pairingTimeMinutes) - { - _pairingTimeMinutes = pairingTimeMinutes; - } - /** - * @return Returns the pairingTimeMinutes. - */ - public int getPairingTimeMinutes() - { - return _pairingTimeMinutes; - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjustmentTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjustmentTest.java deleted file mode 100644 index bbd1b7918d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastAdjustmentTest.java +++ /dev/null @@ -1,452 +0,0 @@ -package ohd.hseb.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -import junit.framework.TestCase; - -public class ForecastAdjustmentTest extends TestCase -{ - - protected static final long MILLIS_PER_HOUR = 3600 * 1000; - protected static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; - - - // -------------------------------------------------------------------------------------------------------- - - public ForecastAdjustmentTest(String name) - { - super(name); - } - - // -------------------------------------------------------------------------------------------------------- - - protected void setUp() throws Exception - { - super.setUp(); - - } - - // -------------------------------------------------------------------------------------------------------- - - - protected void tearDown() throws Exception - { - super.tearDown(); - } - - // -------------------------------------------------------------------------------------------------------- - - private DateValuePair dvp(String dateTimeString, double value) - { - return new DateValuePair(dateTimeString, value); - - } - - // -------------------------------------------------------------------------------------------------------- - - - private class DateValuePair - { - private String dateString = null; - private double value = 0.0; - - public DateValuePair(String dateTimeString, double value) - { - setDateString(dateTimeString); - setValue(value); - } - - public void setDateString(String dateString) - { - this.dateString = dateString; - } - public String getDateString() - { - return dateString; - } - public void setValue(double value) - { - this.value = value; - } - public double getValue() - { - return value; - } - } - - // -------------------------------------------------------------------------------------------------------- - - private RegularTimeSeries getForecastTimeSeries() - { - - DateValuePair fcstMeasurementValueArray[] = - - { - dvp("2007-03-01 13:00:00", .25), - dvp("2007-03-01 14:00:00", .10), - dvp("2007-03-01 15:00:00", .15), - dvp("2007-03-01 16:00:00", .50), - dvp("2007-03-01 17:00:00", .80), - dvp("2007-03-01 18:00:00", 1.2), - dvp("2007-03-01 19:00:00", 1.5), - dvp("2007-03-01 20:00:00", 1.9), - dvp("2007-03-01 21:00:00", 2.1), - dvp("2007-03-01 22:00:00", 2.5), - dvp("2007-03-01 23:00:00", 2.9), - dvp("2007-03-02 00:00:00", 3.2), - dvp("2007-03-02 01:00:00", 3.6), - dvp("2007-03-02 02:00:00", 4.0), - dvp("2007-03-02 03:00:00", 4.9), - dvp("2007-03-02 04:00:00", 6.1), - dvp("2007-03-02 05:00:00", 7.9), - dvp("2007-03-02 06:00:00", 10.0), - dvp("2007-03-02 07:00:00", 12.0), - dvp("2007-03-02 08:00:00", 14.1), - dvp("2007-03-02 09:00:00", 16.0), - dvp("2007-03-02 10:00:00", 17.0), - dvp("2007-03-02 11:00:00", 17.5), - dvp("2007-03-02 12:00:00", 17.8), - dvp("2007-03-02 13:00:00", 17.6), - dvp("2007-03-02 14:00:00", 17.3), - dvp("2007-03-02 15:00:00", 16.8), - dvp("2007-03-02 16:00:00", 16.0), - dvp("2007-03-02 17:00:00", 14.7), - dvp("2007-03-02 18:00:00", 13.6), - dvp("2007-03-02 19:00:00", 12.7), - dvp("2007-03-02 20:00:00", 11.9), - dvp("2007-03-02 21:00:00", 12.0), - dvp("2007-03-02 22:00:00", 12.0), - dvp("2007-03-02 23:00:00", 12.0), - dvp("2007-03-03 00:00:00", 12.0) - }; - - String dateTimeString = "2007-03-06 01:00:00"; - long fcstStartTime = DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - - long fcstEndTime = getTime("2007-03-03 06:00:00"); - - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - RegularTimeSeries forecastTs = - new RegularTimeSeries(fcstStartTime, fcstEndTime, 1, dischargeUnit); - - for (int i = 0; i < fcstMeasurementValueArray.length; i++) - { - DateValuePair dvp = fcstMeasurementValueArray[i]; - - double value = dvp.getValue(); - long time = DbTimeHelper.getLongTimeFromDateTimeString(dvp.getDateString()); - - Measurement m = new Measurement(value , dischargeUnit); - forecastTs.setMeasurementByTime(m, time); - } - - - return forecastTs; - - } - - // -------------------------------------------------------------------------------- - - private IrregularTimeSeries getObservedTimeSeries() - { - - DateValuePair obsMeasurementValueArray[] = - - { - dvp("2007-03-01 13:00:00", 4), - dvp("2007-03-01 14:00:00", 4), - dvp("2007-03-01 15:00:00", 4), - dvp("2007-03-01 16:00:00", 4), - dvp("2007-03-01 17:00:00", 4), - dvp("2007-03-01 18:00:00", 4), - dvp("2007-03-01 19:00:00", 4), - dvp("2007-03-01 20:00:00", 4), - dvp("2007-03-01 21:00:00", 4), - dvp("2007-03-01 22:00:00", 4), - dvp("2007-03-01 23:00:00", 4), - dvp("2007-03-02 00:00:00", 4), - dvp("2007-03-02 01:00:00", 4.2), - dvp("2007-03-02 02:00:00", 4.4), - - dvp("2007-03-02 03:00:00", 4.5), - dvp("2007-03-02 04:00:00", 4.8), - // dvp("2007-03-02 03:00:00", -9999), - // dvp("2007-03-02 04:00:00", -9999), - - dvp("2007-03-02 05:00:00", 5.0), - dvp("2007-03-02 06:00:00", 5.2), - dvp("2007-03-02 07:00:00", 5.4), - - dvp("2007-03-02 08:00:00", 10.1), - dvp("2007-03-02 09:00:00", 10.5), - // dvp("2007-03-02 08:00:00", -9999), - // dvp("2007-03-02 09:00:00", -9999), - - // test the big gap - dvp("2007-03-02 10:00:00", 10.8), //17 - //fcst at 11:00 is 17.5 - // dvp("2007-03-02 15:50:00", 11.8), - //fcst at 13:00 is 17.6 - - //fcst at 15 is 16.8 - dvp("2007-03-02 16:00:00", 11.8), //16 - - - //test a small gap (the size for interpolation) - dvp("2007-03-02 20:00:00", 10), - dvp("2007-03-02 23:00:00", 10) - - }; - - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - IrregularTimeSeries observedTs = new IrregularTimeSeries(dischargeUnit); - - for (int i = 0; i < obsMeasurementValueArray.length; i++) - { - DateValuePair dvp = obsMeasurementValueArray[i]; - - double value = dvp.getValue(); - long time = DbTimeHelper.getLongTimeFromDateTimeString(dvp.getDateString()); - - AbsTimeMeasurement m = new AbsTimeMeasurement(value, time, dischargeUnit); - observedTs.insertMeasurement(m); - } - - return observedTs; - - } - - // -------------------------------------------------------------------------------- - - public void testPairing() - { - RegularTimeSeries fcstTimeSeries = getForecastTimeSeries(); - IrregularTimeSeries obsTimeSeries = getObservedTimeSeries(); - - long lastObsTime = obsTimeSeries.getEndTime(); - - ForecastAdjuster adjuster = getForecastAdjuster(lastObsTime); - - RegularTimeSeries adjustedForecastTs = adjuster.getAdjustedTimeSeries(obsTimeSeries, fcstTimeSeries); - - MeasuringUnit unit = adjustedForecastTs.getMeasuringUnit(); - - double value = 0; - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 00:00:00"), unit); - assertEquals(4.0, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 05:00:00"), unit); - assertEquals(5.0, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 9:00:00"), unit); - assertEquals(10.5, value); - - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 10:00:00"), unit); - assertEquals(10.8, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 11:00:00"), unit); - assertEquals(10.8, value); - - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 15:00:00"), unit); - assertEquals(11.8, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 16:00:00"), unit); - assertEquals("after gap ", 11.8, value); - - - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 20:00:00"), unit); - assertEquals("before small gap ", 10.0, value); - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 23:00:00"), unit); - assertEquals("after small gap ", 10.0, value); - - - // System.out.println("observedTs = " + obsTimeSeries + "\n"); - // - // System.out.println("original forecast Ts = " + fcstTimeSeries + "\n"); - // System.out.println("adjusted forecast Ts = " + adjustedForecastTs); - - } - - // ---------------------------------------------------------------- - - public void testInterpolation() - { - RegularTimeSeries fcstTimeSeries = getForecastTimeSeries(); - IrregularTimeSeries obsTimeSeries = getObservedTimeSeries(); - - long lastObsTime = obsTimeSeries.getEndTime(); - - ForecastAdjuster adjuster = getForecastAdjuster(lastObsTime); - - - RegularTimeSeries adjustedForecastTs = adjuster.getAdjustedTimeSeries(obsTimeSeries, fcstTimeSeries); - - MeasuringUnit unit = adjustedForecastTs.getMeasuringUnit(); - - double value = 0; - - value = adjustedForecastTs.getMeasurementValueByTime(getTime("2007-03-02 19:00:00"), unit); - assertEquals(10.0, value); - } - - // -------------------------------------------------------------------------------------------------------- - private double getDesiredDoubleMatchedBlendedValue(ForecastAdjuster adjuster, - RegularTimeSeries fcstTimeSeries, - IrregularTimeSeries obsTimeSeries, - String prevForecastTimeString, String prevObsTimeString, - String nextForecastTimeString, String nextObsTimeString, - String targetForecastTimeString, - int targetHoursFromPrevAdjustment, - int targetHoursFromNextAdjustment) - { - - String header = "ForecastAdjustmentTest.getDesiredBlendedValue(): "; - MeasuringUnit unit = fcstTimeSeries.getMeasuringUnit(); - - double fcstValue = fcstTimeSeries.getMeasurementValueByTime(getTime(targetForecastTimeString), unit); - - - //setup of previous pair - AbsTimeMeasurement prevObsMeasurement = obsTimeSeries.findClosestMeasurementByTime(getTime(prevObsTimeString)); - double prevObsValue = prevObsMeasurement.getValue(unit); - double prevFcstValue = fcstTimeSeries.getMeasurementValueByTime(getTime(prevForecastTimeString), unit); - double prevAdjustment = prevObsValue - prevFcstValue; - - - //setup of next pair - AbsTimeMeasurement nextObsMeasurement = obsTimeSeries.findClosestMeasurementByTime(getTime(nextObsTimeString)); - double nextObsValue = nextObsMeasurement.getValue(unit); - double nextFcstValue = fcstTimeSeries.getMeasurementValueByTime(getTime(nextForecastTimeString), unit); - double nextAdjustment = nextObsValue - nextFcstValue; - - - // calculate the blend - double blendingHours = adjuster.getParams().getBlendingHours(); - - double forwardFadeFactor = (blendingHours-targetHoursFromPrevAdjustment)/(blendingHours); - double forwardBlend = prevAdjustment * forwardFadeFactor; - - double backwardFadeFactor = (blendingHours-targetHoursFromNextAdjustment)/(blendingHours); - double backwardBlend = nextAdjustment * backwardFadeFactor ; - - double totalBlend = (forwardBlend + backwardBlend) / 2; - - // add the blend shift of the original forecast value - double newDesiredValue = fcstValue + totalBlend; - - - System.out.println(header + "forwardBlend " + forwardBlend + - " backwardBlend = " + backwardBlend + - " totalBlend = " + totalBlend + - " newDesired Value = " + newDesiredValue); - - - return newDesiredValue; - } - // -------------------------------------------------------------------------------------------------------- - - - public void testBlending() - { - - String header = "ForecastAdjustmentTest.testBlending(): "; - - RegularTimeSeries fcstTimeSeries = getForecastTimeSeries(); - IrregularTimeSeries obsTimeSeries = getObservedTimeSeries(); - - long lastObsTime = obsTimeSeries.getEndTime(); - - ForecastAdjuster adjuster = getForecastAdjuster(lastObsTime); - - - RegularTimeSeries adjustedForecastTs = adjuster.getAdjustedTimeSeries(obsTimeSeries, fcstTimeSeries); - - MeasuringUnit unit = adjustedForecastTs.getMeasuringUnit(); - - String targetTimeString = "2007-03-02 13:00:00"; - double value = adjustedForecastTs.getMeasurementValueByTime(getTime(targetTimeString), unit); - - double newDesiredValue = getDesiredDoubleMatchedBlendedValue( - adjuster, fcstTimeSeries, obsTimeSeries, - "2007-03-02 11:00:00", "2007-03-02 10:00:00", //fcst can match an obs up to 70 minutes away - "2007-03-02 15:00:00", "2007-03-02 16:00:00", //fcst can match an obs up to 70 minutes away - targetTimeString, //target time - 2, - 2); - - System.out.println(header + "newDesiredValue = " + newDesiredValue); - - - assertEquals(newDesiredValue, value); - - - targetTimeString = "2007-03-02 14:00:00"; - value = adjustedForecastTs.getMeasurementValueByTime(getTime(targetTimeString), unit); - - newDesiredValue = getDesiredDoubleMatchedBlendedValue( - adjuster, fcstTimeSeries, obsTimeSeries, - "2007-03-02 11:00:00", "2007-03-02 10:00:00", //fcst can match an obs up to 70 minutes away - "2007-03-02 15:00:00", "2007-03-02 16:00:00", //fcst can match an obs up to 70 minutes away - targetTimeString, //target time - 3, - 1); - - System.out.println(header + "newDesiredValue = " + newDesiredValue); - - - assertEquals(newDesiredValue, value); - - return; - - - } - - // -------------------------------------------------------------------------------------------------------- - - private long getTime(String dateTimeString) - { - return DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - } - - // -------------------------------------------------------------------------------------------------------- - - private ForecastAdjuster getForecastAdjuster(long lastObsTime) - { - - ForecastAdjusterParams params = new ForecastAdjusterParams(); - - int pairingTimeMinutes = 70; - int interpolationHours = 3; - - - params.setBlendingHours(100); - params.setBlendingMethod(ForecastInterpolationMethod.DIFFERENCE); - params.setShouldDoAdjustment(true); - params.setPairingTimeMinutes(pairingTimeMinutes); - params.setInterpolationHours(interpolationHours); - System.out.println("pairing minutes hours = " + params.getPairingTimeMinutes()); - System.out.println("Interpolation hours = " + params.getInterpolationHours()); - - - ForecastAdjuster adjuster = new ForecastAdjuster(params); - - adjuster.setLastObservedTimeToUseAsInput(lastObsTime); - - - return adjuster; - } - - // -------------------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastBlender.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastBlender.java deleted file mode 100644 index 0cbc652e5e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastBlender.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Created on Sep 23, 2004 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; - -/** - * @author Chip Gobs - * - * Forecast Blender - */ -public class ForecastBlender -{ - - private int _blendHoursCount = 0; - private double _baseBlendAmount = 0; - private boolean _usedBlend = false; - - private int _allowableBlendingHours = 0; - - private long _allowableTimeWindow = 0; - - private static final long MILLIS_PER_MINUTE = 60 * 1000; - private static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - - private static boolean _debug = false; - - // ----------------------------------------------------------------------------------------- - public ForecastBlender(int allowableBlendingHours) - { - - _blendHoursCount = 0; - _baseBlendAmount= 0; - _usedBlend = false; - - _allowableTimeWindow = allowableBlendingHours * MILLIS_PER_HOUR; - _allowableBlendingHours = allowableBlendingHours; - } - - // ----------------------------------------------------------------------------------------- - public void clearBlender() - { - _blendHoursCount = 0; - _baseBlendAmount = 0; - _usedBlend = false; - - } - // ---------------------------------------------------------------------------------- - - /** - * @param _blendHoursCount The _blendHoursCount to set. - */ - private void setBlendHoursCount(int blendHoursCount) - { - this._blendHoursCount = blendHoursCount; - } - - // ----------------------------------------------------------------------------------------- - /** - * @return Returns the _blendHoursCount. - */ - private int getBlendHoursCount() - { - return _blendHoursCount; - } - // ----------------------------------------------------------------------------------------- - /** - * @param _baseBlendAmount The _blendAmount to set. - */ - private void setBlendAmount(double blendAmount) - { - this._baseBlendAmount = blendAmount; - } - // ----------------------------------------------------------------------------------------- - /** - * @return Returns the _blendAmount. - */ - private double getBlendAmount() - { - return _baseBlendAmount; - } - // ----------------------------------------------------------------------------------------- - /** - * @param _usedBlendForward The _usedBlendForward to set. - */ - public void setUsedBlend(boolean usedBlend) - { - this._usedBlend = usedBlend; - } - // ----------------------------------------------------------------------------------------- - /** - * @return Returns the _usedBlendForward. - */ - public boolean usedBlend() - { - return _usedBlend; - } - // ----------------------------------------------------------------------------------------- - - private boolean areMeasurementsCloseEnoughInTime(AbsTimeMeasurement m1, - AbsTimeMeasurement m2, - long maxMillisForCloseness) - { - boolean result = false; - - if ((m1 != null) && (m2 != null)) - { - long timeDiff = m1.getTime() - m2.getTime(); - - if (Math.abs(timeDiff) <= maxMillisForCloseness) - { - result = true; - } - } - - return result; - } - // ---------------------------------------------------------------------------------- - public AbsTimeMeasurement getBlendAdjustment(ObservedForecastMeasurementPair obsFcstPair, - AbsTimeMeasurement origFcstMeasurement) - { - String header = "ForecastBlender.getBlendAdjustment(): "; - - AbsTimeMeasurement adjustmentMeasurement = null; - AbsTimeMeasurement observedMeasurement = null; - AbsTimeMeasurement pairedFcstMeasurement = null; - - long fcstTime = origFcstMeasurement.getTime(); - - - if (obsFcstPair != null) - { - observedMeasurement = obsFcstPair.getObservedMeasurement(); - pairedFcstMeasurement = obsFcstPair.getForecastMeasurement(); - - if (areMeasurementsCloseEnoughInTime(observedMeasurement, - origFcstMeasurement, - _allowableTimeWindow)) - { - - - //first time for forward blending of this group of - // forecast values - if (! _usedBlend) - { - _usedBlend = true; - - long pairFcstTime = obsFcstPair.getForecastMeasurement().getTime(); - long timeDiff = fcstTime - pairFcstTime; - - _blendHoursCount = (int) (timeDiff / MILLIS_PER_HOUR); - _baseBlendAmount = observedMeasurement.getValue() - pairedFcstMeasurement.getValue(); - - } - - // have already usedBlendForward - else - { - _blendHoursCount ++; - } - - double absBlendHoursCount = Math.abs(_blendHoursCount); - - double fadeFactor = ((double) _allowableBlendingHours - (double) absBlendHoursCount) / - (double) (_allowableBlendingHours); - - double adjustmentValue = (_baseBlendAmount * fadeFactor); - - adjustmentMeasurement = new AbsTimeMeasurement(origFcstMeasurement); //conveniently copies units and time - adjustmentMeasurement.setValue(adjustmentValue); - - - if (_debug) - { - if (_blendHoursCount > 0) - { - System.out.print(header + "Forward blend for " + - DbTimeHelper.getDateTimeStringFromLongTime(origFcstMeasurement.getTime()) + " "); - } - else - { - System.out.print(header + "Backward blend for " + - DbTimeHelper.getDateTimeStringFromLongTime(origFcstMeasurement.getTime()) + " "); - } - - System.out.println("blending adjustment value = " + adjustmentValue); - - System.out.println(header + "raw blendAmount = " + _baseBlendAmount + - " fadeFactor = " + fadeFactor + - " blendHoursCount = " + _blendHoursCount + "\n"); - - } - - } //end if measurements are close in time - } //end if previous pair != null - - - //make sure that there are no null adjustments, - // if they are null at this point, make it a 0.0 adjustment - if (adjustmentMeasurement == null) - { - adjustmentMeasurement = new AbsTimeMeasurement(origFcstMeasurement); - adjustmentMeasurement.setValue(0.0); - } - - return adjustmentMeasurement; - - } //end getBlendAdjustment() - // ----------------------------------------------------------------------------------------- - -} //end class ForecastBlender diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastInterpolationMethod.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastInterpolationMethod.java deleted file mode 100644 index 7be27de389..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ForecastInterpolationMethod.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Created on Sep 3, 2004 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * This follows the java enum pattern with private constructors and public static final instances. - */ -public class ForecastInterpolationMethod -{ - private String _methodName = null; - - public static final ForecastInterpolationMethod DIFFERENCE = new ForecastInterpolationMethod("DIFFERENCE"); - public static final ForecastInterpolationMethod RATIO = new ForecastInterpolationMethod("RATIO"); - - - private static String[] _methodNameArray = { "DIFF", "DIFFERENCE", "RATIO" }; - - private static ForecastInterpolationMethod[] _methodArray = { DIFFERENCE, DIFFERENCE, RATIO }; - - // ------------------------------------------------------------------------------------- - - private ForecastInterpolationMethod(String methodName) - { - _methodName = methodName; - - return; - } - - // ------------------------------------------------------------------------------------- - public static ForecastInterpolationMethod getMethodByName(String methodName) - { - ForecastInterpolationMethod method = DIFFERENCE; //this is the default - - for (int i = 0; i < _methodNameArray.length; i++ ) - { - if (_methodNameArray[i].equalsIgnoreCase(methodName)) - { - method = _methodArray[i]; - break; - } - } - - return method; - } - // ------------------------------------------------------------------------------------- - - public String getName() - { - return _methodName; - - } - // ------------------------------------------------------------------------------------- - public String toString() - { - String outString = null; - - outString = "methodName = " + getName(); - - return outString; - - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/LocationDescriptor.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/LocationDescriptor.java deleted file mode 100644 index 1a1d917467..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/LocationDescriptor.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Created on Oct 8, 2004 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * - */ -public class LocationDescriptor -{ - private String _id; - private String _locationName; - private String _streamName; - private String _basinId; - private String _hsa; - private String _modelPreference; - // ------------------------------------------------------------------------------------------------ - /** - * @param id The id to set. - */ - public void setId(String id) - { - _id = id; - } - /** - * @return Returns the id. - */ - public String getId() - { - return _id; - } -// ------------------------------------------------------------------------------------------------ - - /** - * @param name The name to set. - */ - public void setLocationName(String locationName) - { - _locationName = locationName; - } - /** - * @return Returns the name. - */ - public String getLocationName() - { - return _locationName; - } -// ------------------------------------------------------------------------------------------------ - - /** - * @param streamName The streamName to set. - */ - public void setStreamName(String streamName) - { - _streamName = streamName; - } - /** - * @return Returns the streamName. - */ - public String getStreamName() - { - return _streamName; - } -// ------------------------------------------------------------------------------------------------ - - /** - * @param basinName The basinName to set. - */ - public void setBasinId(String basinId) - { - _basinId = basinId; - } - /** - * @return Returns the basinName. - */ - public String getBasinId() - { - return _basinId; - } -// ------------------------------------------------------------------------------------------------ - public void setHsa(String hsa) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } -// ------------------------------------------------------------------------------------------------ - public void setModelPreference(String modelPreference) - { - _modelPreference = modelPreference; - } - public String getModelPreference() - { - return _modelPreference; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/MonthlyValues.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/MonthlyValues.java deleted file mode 100644 index bd5b4cc517..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/MonthlyValues.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Created on Jan 20, 2004 - * - * - */ -package ohd.hseb.model; - -import java.util.*; -import ohd.hseb.db.*; - -/** - * @author GobsC - * - * This class encapsulates the double precision floating point values - * that are stored for each month. - */ -public class MonthlyValues -{ - private String _basinId = null; - private String _pe = null; - private short _dur = 0; - private String _ts = null; - private String _extremum = null; - private boolean _adjustment = false; - private long _postingTime = 0; - private double[] _valueArray = new double[12]; - private int _monthsInYear = 12; - - - // ------------------------------------------------------------ - - public MonthlyValues() - { - } //MonthlyValues() - - // ------------------------------------------------------------ - public MonthlyValues(double[] valueArray) - { - setValues(valueArray); - } //MonthlyValues() - - // ------------------------------------------------------------ - public void setValues(double[] valueArray) - { - for (int i = 0 ; i < valueArray.length && - i < _monthsInYear ; i++) - { - _valueArray[i] = valueArray[i]; - } - - } //setValues() - // ------------------------------------------------------------ - - // ------------------------------------------------------------ - - public double getValue(long time) - { - double value = 0.0; - //this method returns an interpolated daily value - - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(new Date(time)); - - - // extract needed info based on the current time - int monthIndex = cal.get(Calendar.MONTH); - int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); - int year = cal.get(Calendar.YEAR); - - int year1 = year; - int year2 = year; - - - int currentMonth = monthIndex; - - double month1Value = 0; - double month2Value = 0; - - double weight1 = 0; - double weight2 = 0; - - double monthToMonthDayDistance = 0.0; - double month1ToDayDistance = 0.0; - double month2ToDayDistance = 0.0; - - - //determine which months to interpolate against - if (dayOfMonth == 16) - { - value = _valueArray[currentMonth]; - - month1Value = _valueArray[currentMonth]; - month2Value = 0; - - monthToMonthDayDistance = 1; - - month1ToDayDistance = 0; - month2ToDayDistance = 1; - } - else if (dayOfMonth < 16) - { - int previousMonth = monthIndex-1; - if (previousMonth < Calendar.JANUARY) - { - previousMonth = Calendar.DECEMBER; - year1 = year - 1; - } - - month1Value = _valueArray[previousMonth]; - month2Value = _valueArray[currentMonth]; - - monthToMonthDayDistance = getDayDistance(year1, previousMonth, 16, year2, currentMonth, 16); - - month1ToDayDistance = getDayDistance(year1, previousMonth, 16, year2, currentMonth, dayOfMonth); - month2ToDayDistance = getDayDistance(year2, currentMonth, dayOfMonth, year2, currentMonth, 16); - - } - - else //dayOfMonth > 16 - { - - int nextMonth = currentMonth + 1; - if (nextMonth > Calendar.DECEMBER) - { - nextMonth = Calendar.JANUARY; - year2 = year + 1; - } - - month1Value = _valueArray[currentMonth]; - month2Value = _valueArray[nextMonth]; - - monthToMonthDayDistance = getDayDistance(year1, currentMonth, 16, year2, nextMonth, 16); - - month1ToDayDistance = getDayDistance(year1, currentMonth, 16, year1, currentMonth, dayOfMonth); - month2ToDayDistance = getDayDistance(year1, currentMonth, dayOfMonth, year2, nextMonth, 16); - - } - - - weight1 = (1.0 - (month1ToDayDistance/monthToMonthDayDistance)); - weight2 = (1.0 - (month2ToDayDistance/monthToMonthDayDistance)); - - - value = (weight1 * month1Value) + (weight2 * month2Value); - - return value; - } - - // ------------------------------------------------------------ - - private double getDayDistance(int year1, int month1, int day1, - int year2, int month2, int day2) - { - int daysInYear1 = 365; - - if (isLeapYear(year1)) - { - daysInYear1 = 366; - } - - GregorianCalendar cal1 = new GregorianCalendar(year1, month1, day1); - int dayOfYear1 = cal1.get(Calendar.DAY_OF_YEAR); - - GregorianCalendar cal2 = new GregorianCalendar(year2, month2, day2); - int dayOfYear2 = cal2.get(Calendar.DAY_OF_YEAR); - - //if there is a year change, make the first day of the second year - // start at 366 or 367 - - if (year2 != year1) - { - dayOfYear2 += daysInYear1; - } - - int dayDistance = dayOfYear2 - dayOfYear1; - - - return dayDistance; - - } //end getDayDistance() - - // ------------------------------------------------------------ - - private boolean isLeapYear(int year) - { - boolean isLeap = false; - - if ((year % 4) == 0) - { - if ((year % 100) == 0) - { - if ((year % 400) == 0 ) //2000 is a leap year, 1900 and 2100 are not - { - isLeap = true; - } - else - { - isLeap = false; - } - } - else - { - isLeap = true; - } - } - else - { - isLeap = false; - } - - return isLeap; - } //end isLeapYear() - - // ------------------------------------------------------------ - public static void main (String[] args) - { - - double[] valuesArray = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, - - 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 }; - - MonthlyValues values = new MonthlyValues(valuesArray); - - final long millisPerDay = 1000 * 60 * 60 * 24; - long currentTime = System.currentTimeMillis(); - long todayTime = (currentTime / millisPerDay) * millisPerDay; - - todayTime += 1000 * 3600 *12; //add 12 hours - - long loopTime = todayTime; - int daysInYear = 365; - - for (int i = 0; i < daysInYear; i++) - { - String dateString = DbTimeHelper.getDateStringFromLongTime(loopTime); - - String dateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(loopTime); - - double value = values.getValue(loopTime); - System.out.println("On " + dateString + " at " + dateTimeString + ", the value is " + value); - - - loopTime += millisPerDay; - } - - - } - - public String getBasinId() - { - return _basinId; - } - - public long getPostingTime() - { - return _postingTime; - } - - public void setBasinId( String basinId) - { - _basinId = basinId; - } - - public void setPostingTime( long postingTime ) - { - _postingTime = postingTime; - } - - public double[] getValueArray() - { - double[] valueArray = new double[ _valueArray.length ]; - - for ( int i = 0; i < _valueArray.length; i++ ) - { - valueArray[ i ] = _valueArray[ i ]; - } - return valueArray; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( short dur ) - { - _dur = dur; - } - - public short getDur() - { - return _dur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setAdjustment( boolean adjustment ) - { - _adjustment = adjustment; - } - - public boolean isAdjustment() - { - return _adjustment; - } - - // ------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ObservedForecastMeasurementPair.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ObservedForecastMeasurementPair.java deleted file mode 100644 index 75ef17d9c5..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ObservedForecastMeasurementPair.java +++ /dev/null @@ -1,64 +0,0 @@ -package ohd.hseb.model; - -import ohd.hseb.measurement.AbsTimeMeasurement; - - -/** - * @author Chip Gobs - * - * Contains a pair of Measurements - */ -public class ObservedForecastMeasurementPair -{ - private AbsTimeMeasurement _observedMeasurement; - private AbsTimeMeasurement _forecastMeasurement; - - // ---------------------------------------------------------------------------------------------- - - public ObservedForecastMeasurementPair(AbsTimeMeasurement observedMeasurement, - AbsTimeMeasurement forecastMeasurement) - { - setObservedMeasurement(observedMeasurement); - setForecastMeasurement(forecastMeasurement); - - return; - } - - public void setObservedMeasurement(AbsTimeMeasurement observedMeasurement) - { - _observedMeasurement = new AbsTimeMeasurement(observedMeasurement); - } - - public AbsTimeMeasurement getObservedMeasurement() - { - return _observedMeasurement; - } - - public void setForecastMeasurement(AbsTimeMeasurement forecastMeasurement) - { - _forecastMeasurement = new AbsTimeMeasurement(forecastMeasurement); - } - - public AbsTimeMeasurement getForecastMeasurement() - { - return _forecastMeasurement; - } - - public int hashCode() - { - return _observedMeasurement.hashCode() + _forecastMeasurement.hashCode(); - } - - public String toString() - { - String outString = "Observed: " + _observedMeasurement.toString() + - " Forecast: " + _forecastMeasurement.toString(); - - - return outString; - } - - // ---------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ParamCode.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ParamCode.java deleted file mode 100644 index 8efab3684a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/ParamCode.java +++ /dev/null @@ -1,268 +0,0 @@ -package ohd.hseb.model; - -import java.util.HashMap; -import java.util.Map; - -public class ParamCode -{ - private String _paramCodeString = null; - - private static final Map _shefDurCodeToIhfsDurCodeMap = new HashMap(); - private static final Map _ihfsDurCodeToShefDurCodeMap = new HashMap(); - - private String _pe = null; - private String _typeSource = null; - private int _ihfsDur = 0; - private String _shefDur = null; - private String _extremum = null; - - static - { - initDurationCodeMaps(); - } - - // ------------------------------------------------------------------------------- - public ParamCode(String paramCodeString) - { - _paramCodeString = paramCodeString; - parse(paramCodeString); - - return; - } - // ------------------------------------------------------------------------------- - - public ParamCode(ParamCode paramCode) - { - _pe = paramCode.getPe(); - _typeSource = paramCode.getTypeSource(); - _ihfsDur = paramCode.getIhfsDur(); - _shefDur = paramCode.getShefDur(); - _extremum = paramCode.getExtremum(); - _paramCodeString = paramCode._paramCodeString; - - - return; - } - // ------------------------------------------------------------------------------- - // ------------------------------------------------------------------------------- - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getPe() + - getShefDur() + - getTypeSource() + - getExtremum() ); - - Runtime rt = Runtime.getRuntime(); - - return buffer.toString(); - - - } - - // ------------------------------------------------------------------------------- - - public String toStringVerbose() - { - StringBuffer buffer = new StringBuffer(); - - - buffer.append("pe = " + getPe() + - " dur = " + getIhfsDur() + - " ts = " + getTypeSource() + - " extremum = " + getExtremum() ); - - return buffer.toString(); - - } - // ------------------------------------------------------------------------------- - - private void parse(String paramCodeString) - { - - setPe(paramCodeString.substring(0,2)); - _shefDur = paramCodeString.substring(2,3); - - _ihfsDur = getIhfsDurationCode(_shefDur); - - setTypeSource(paramCodeString.substring(3,5)); - setExtremum(paramCodeString.substring(5,6)); - - return; - } - // ------------------------------------------------------------------------------- - private static void initDurationCodeMaps() - { - - /* - 0 | I | Instantaneous - 1 | U | 1 Minute - 15 | C | 15 Minutes - 30 | J | 30 Minutes - 1001 | H | 1 Hour - 1002 | B | 2 Hour - 1003 | T | 3 Hour - 1004 | F | 4 Hour - 1006 | Q | 6 Hour - 1008 | A | 8 Hour - 1012 | K | 12 Hour - 1018 | L | 18 Hour - 2001 | D | 1 Day - 2007 | W | 1 Week - 3001 | M | 1 Month - 4001 | Y | 1 Year - 5000 | Z | Unspecified - 5001 | S | Seasonal - 5002 | R | Period of Record - 5004 | P | Total Since 7 AM - 5005 | X | Unknown - - */ - - - String code = "?"; - - String charCodeString = "IUCJHBTFQAKLDWMYZSRPX"; - - int intCodeArray[] = { 0, 1, 15, 30, - 1001, 1002, 1003, 1004, 1006, 1008, 1012, 1018, - 2001, 2007, - 3001, - 4001, - 5000, 5001, 5002, 5004, 5005 }; - - - - int i = 0; - - for (i = 0; i < charCodeString.length(); i++) - { - String shefCode = charCodeString.substring(i, i+1); - Integer intCode = new Integer(intCodeArray[i]); - - _shefDurCodeToIhfsDurCodeMap.put(shefCode, intCode); - _ihfsDurCodeToShefDurCodeMap.put(intCode, shefCode); - } - - return; - - } - // ------------------------------------------------------------------------------- - public static int getIhfsDurationCode(String shefDurationCode) - { - int ihfsCode = -1; - Integer ihfsCodeInteger = (Integer) _shefDurCodeToIhfsDurCodeMap.get(shefDurationCode); - - if (ihfsCodeInteger != null) - { - ihfsCode = ihfsCodeInteger.intValue(); - } - - return ihfsCode; - } - // ------------------------------------------------------------------------------- - public static String getShefDurationCode(int ihfsDurationCode) - { - String shefDurationCode = "?"; - - Integer ihfsDurationCodeInteger = new Integer(ihfsDurationCode); - - String shefDurationCodeFromMap = - (String) _ihfsDurCodeToShefDurCodeMap.get(ihfsDurationCodeInteger); - - if (shefDurationCodeFromMap != null) - { - shefDurationCode = shefDurationCodeFromMap; - } - - return shefDurationCode; - } - /** - * @param pe The pe to set. - */ - public void setPe(String pe) - { - _pe = pe; - } - /** - * @return Returns the pe. - */ - public String getPe() - { - return _pe; - } - /** - * @param typeSource The typeSource to set. - */ - public void setTypeSource(String typeSource) - { - _typeSource = typeSource; - } - /** - * @return Returns the typeSource. - */ - public String getTypeSource() - { - return _typeSource; - } - /** - * @param ihfsDur The ihfsDur to set. - */ - public void setIhfsDur(int ihfsDur) - { - _ihfsDur = ihfsDur; - } - /** - * @return Returns the ihfsDur. - */ - public int getIhfsDur() - { - return _ihfsDur; - } - /** - * @param shefDur The shefDur to set. - */ - public void setShefDur(String shefDur) - { - _shefDur = shefDur; - } - /** - * @return Returns the shefDur. - */ - public String getShefDur() - { - return _shefDur; - } - /** - * @param extremum The extremum to set. - */ - public void setExtremum(String extremum) - { - _extremum = extremum; - } - /** - * @return Returns the extremum. - */ - public String getExtremum() - { - return _extremum; - } - - // ------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - ParamCode code = null; - - code = new ParamCode("HGIRGZ"); - System.out.println("code = " + code.toString()); - - - code = new ParamCode("HPIRZX"); - System.out.println("code = " + code.toString()); - - } - - // ------------------------------------------------------------------------------- - -} //end ParamCode diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallRunoffModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallRunoffModel.java deleted file mode 100644 index 03ec9a475d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallRunoffModel.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Created on Nov 4, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.*; - -/** - * @author Chip Gobs - * - * This interface is made to be implemented by various - * specific rainfall-runoff models - * - **/ -public interface RainfallRunoffModel -{ - public RegularTimeSeries calculateRunoff(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries - ); - - public RainfallRunoffModelType getModelType(); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallRunoffModelType.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallRunoffModelType.java deleted file mode 100644 index f79eb5a8f2..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallRunoffModelType.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Created on Nov 5, 2003 - * - */ - -package ohd.hseb.model; - -/** - * @author Chip Gobs - */ -public class RainfallRunoffModelType -{ - - public static RainfallRunoffModelType SAC_SMA = new RainfallRunoffModelType("SAC-SMA"); - public static RainfallRunoffModelType API_MKC = new RainfallRunoffModelType("API-MKC"); - - private static final RainfallRunoffModelType[] _modelTypeArray = { API_MKC, SAC_SMA }; - - private String _name; - - private RainfallRunoffModelType(String name) - { - _name = name; - } - - /** - * This method returns a RainfallRunoffModelType, based on a name lookup. If no match is found, then the passed in - * default type is returned. The default type can be null if desired. - * @param name The name of the RainfallRunoffModelType - * @return - */ - public static RainfallRunoffModelType getRainfallRunoffModelTypeByName(String name, RainfallRunoffModelType defaultType) - { - RainfallRunoffModelType returnType = defaultType; - - for (RainfallRunoffModelType type : _modelTypeArray) - { - if (name.equalsIgnoreCase(type.getName())) - { - returnType = type; - } - } - - return returnType; - } - - /** - * This method returns a RainfallRunoffModelType, based on a name lookup. If no match is found, then the - * default type of API_MKC is returned. - * @param name The name of the RainfallRunoffModelType - * @return - */ - public static RainfallRunoffModelType getRainfallRunoffModelTypeByName(String name) - { - return getRainfallRunoffModelTypeByName(name, RainfallRunoffModelType.API_MKC); - } - - - - public static RainfallRunoffModelType[] getModelTypeArray() - { - return _modelTypeArray; - } - - public String getName() - { - return _name; - } - - public String toString() - { - return _name; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallToStageModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallToStageModel.java deleted file mode 100644 index f08754030e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RainfallToStageModel.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.*; - -/** - * @author Chip Gobs - * - * This class combines the RainfallRunoffModel - * with a UnitHydrograph and a Rating Curve to output a TimeSeries object. - */ -public interface RainfallToStageModel -{ - - -// ------------------------------------------------------------- - - - public RegularTimeSeries calculateStageTimeSeries(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries, - RegularTimeSeriesHolder runOffTimeSeriesHolder); - - - -} //end interface RainfallToStageModel \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingCurve.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingCurve.java deleted file mode 100644 index 76252d2ed5..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingCurve.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Created on Jul 7, 2003 - * - * Conversion routines modified from code by Russ Erb. - */ -package ohd.hseb.model; - -import java.util.*; - -import ohd.hseb.measurement.*; - -/** - * @author Chip Gobs - * - * This class contains all the data associated with - * a RatingCurve and allows for conversion to and from discharge and stage. - * It is not aware of the database. - * The RatingShift still needs to be accounted for; this could be done - * with the code that loads the RatingCurve in the first place. - */ -public class RatingCurve -{ - private String _locationId = null; - - private double _shiftAmount = 0.0; - - private String _usgsRatingNumber = null; - private long _ratingDate = 0; - - private List _ratingPointList = new ArrayList(); - - private int _millisPerHour = 60 * 60 * 1000; - - private MeasuringUnit _stageUnit = MeasuringUnit.feet; - private MeasuringUnit _dischargeUnit = MeasuringUnit.cfs; - - //--------------------------------------------------------------------- - public RatingCurve(String locationId) - { - setLocationId(locationId); - } - - public static RatingCurve getTestRatingCurve(String testLocationId) - { - RatingCurve rc = new RatingCurve(testLocationId); - double[] flowArray = {0.0, 5, 20, 30, 50, 100, 250, 400, 600, 800, 1000 }; - double[] stageArray = {0.0, .1, 1, 2, 5, 8, 9, 12.5, 15, 17, 19}; - - for (int i = 0; i < flowArray.length; i++) - { - RatingPoint point = new RatingPoint(); - point.setDischarge(flowArray[i]); - point.setUnshiftedStage(stageArray[i]); - - rc.addRatingPoint(point); - } - - return rc; - } - - public void setLocationId(String locationId) - { - _locationId = locationId; - } - - public String getLocationId() - { - return _locationId; - } - - public void setUsgsRatingNumber(String usgsRatingNumber) - { - _usgsRatingNumber = usgsRatingNumber; - } - - public String getUsgsRatingNumber() - { - return _usgsRatingNumber; - } - - public void setRatingDate(long ratingDate) - { - _ratingDate = ratingDate; - } - - public long getRatingDate() - { - return _ratingDate; - } - // --------------------------------------------------------------------- - - public void setShiftAmount(double shiftAmount) - { - _shiftAmount = shiftAmount; - - //update all of the associated ratingPoints - for (int i = 0; i < _ratingPointList.size(); i++) - { - RatingPoint ratingPoint = (RatingPoint) _ratingPointList.get(i); - ratingPoint.setShiftAmount(_shiftAmount); - } - } - - // --------------------------------------------------------------------- - - - public double getShiftAmount() - { - return _shiftAmount; - } - // --------------------------------------------------------------------- - - public boolean exists() - { - boolean result = false; - - if (_ratingPointList.size() > 1) - { - result = true; - } - - return result; - } - // --------------------------------------------------------------------- - - public void addRatingShift() - { - - } - // --------------------------------------------------------------------- - public List getRatingPointList() - { - List newList = new ArrayList(); - for (int i = 0; i < _ratingPointList.size(); i++) - { - RatingPoint point = (RatingPoint) _ratingPointList.get(i); - newList.add(point); - } - - return newList; - } - - // --------------------------------------------------------------------- - - public int getRatingPointCount() - { - return _ratingPointList.size(); - } - - public RatingPoint getRatingPoint(int index) - { - RatingPoint point = null; - - if ((index >= 0) && (index <= _ratingPointList.size() ) ) - point = (RatingPoint) _ratingPointList.get(index); - - return point; - } -// --------------------------------------------------------------------- - public RatingPoint getFirstRatingPoint() - { - RatingPoint point = null; - - point = getRatingPoint(0); - - return point; - } -// --------------------------------------------------------------------- - public RatingPoint getSecondRatingPoint() - { - RatingPoint point = null; - point = getRatingPoint(1); - - return point; - } -// --------------------------------------------------------------------- - public RatingPoint getLastRatingPoint() - { - RatingPoint point = null; - - point = getRatingPoint(_ratingPointList.size() - 1); - - return point; - } -// --------------------------------------------------------------------- - - public RatingPoint getNextToLastRatingPoint() - { - RatingPoint point = null; - - point = getRatingPoint(_ratingPointList.size() - 2); - - return point; - } -// --------------------------------------------------------------------- - public void addRatingPoint(RatingPoint newPoint) - { - //insert the RatingPoint at the correct point - // in order to keep the list in ascending sorted order by stage - - newPoint.setShiftAmount(_shiftAmount); - - double stage = newPoint.getShiftedStage(); - boolean inserted = false; - - - if (_ratingPointList.size() == 0) - { - _ratingPointList.add(newPoint); - inserted = true; - } - else - { - for (int i = 0; i < _ratingPointList.size() && !inserted; i++) - { - RatingPoint curPoint = (RatingPoint) _ratingPointList.get(i); - if (stage < curPoint.getShiftedStage()) - { - _ratingPointList.add(i, newPoint); - inserted = true; - } - else if (stage == curPoint.getShiftedStage()) - { - _ratingPointList.add(i, newPoint); - inserted = true; - removeRatingPoint(curPoint); - } - - } - if (!inserted) - { - //need to add to the end of the list - _ratingPointList.add(newPoint); - } - } //end else - - return; - } -// --------------------------------------------------------------------- - public boolean removeRatingPoint(RatingPoint ratingPoint) - { - //remove the RatingPoint if a match exists in the list - // - boolean removed = false; - - for (int i = 0; i < _ratingPointList.size() && ! removed ; i++) - { - RatingPoint curPoint = (RatingPoint) _ratingPointList.get(i); - if (curPoint.equals(ratingPoint)) - { - _ratingPointList.remove(ratingPoint); - removed = true; - } - } - - return removed; - } -// --------------------------------------------------------------------- - - public IrregularTimeSeries getStageTimeSeries(IrregularTimeSeries flowTimeSeries) - { - //includes the shift - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(MeasuringUnit.feet); - - for (int i = 0; i < flowTimeSeries.getMeasurementCount(); i++) - { - AbsTimeMeasurement flowMeasurement = flowTimeSeries.getAbsTimeMeasurementByIndex(i); - - double stageValue = getStageFromDischarge(flowMeasurement.getValue()); - AbsTimeMeasurement stageMeasurement = new AbsTimeMeasurement(stageValue, - flowMeasurement.getTime(), - MeasuringUnit.feet); - - stageTimeSeries.insertMeasurement(stageMeasurement); - - } //end for - - return stageTimeSeries; - } - -// --------------------------------------------------------------------- - public IrregularTimeSeries getDischargeIrregularTimeSeries(IrregularTimeSeries stageTimeSeries) - { - //ensure input units are correct - stageTimeSeries.convert(_stageUnit); - - - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(_dischargeUnit); - - for (int i = 0; i < stageTimeSeries.getMeasurementCount(); i++) - { - AbsTimeMeasurement stageMeasurement = stageTimeSeries.getAbsTimeMeasurementByIndex(i); - - double dischargeValue = getDischargeFromStage(stageMeasurement.getValue()); - long time = stageMeasurement.getTime(); - AbsTimeMeasurement dischargeMeasurement = - new AbsTimeMeasurement(dischargeValue, time, _dischargeUnit); - - dischargeTimeSeries.insertMeasurement(dischargeMeasurement); - - } //end for - - return dischargeTimeSeries; - - - - } - -// --------------------------------------------------------------------- - - public RegularTimeSeries getStageRegularTimeSeries(RegularTimeSeries flowTimeSeries) - { - - //ensure units are correct - flowTimeSeries.convert(_dischargeUnit); - - - // get info about flowTimeSeries - long startTime = flowTimeSeries.getStartTime(); - long endTime = flowTimeSeries.getEndTime(); - int intervalInHours = flowTimeSeries.getIntervalInHours(); - int intervalInMillis = intervalInHours * _millisPerHour; - - - RegularTimeSeries stageTimeSeries = new RegularTimeSeries(startTime, endTime, - intervalInHours, _stageUnit); - - - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement flowMeasurement = flowTimeSeries.getMeasurementByTime(time); - - double stageValue = getStageFromDischarge(flowMeasurement.getValue()); - Measurement stageMeasurement = new Measurement(stageValue, - _stageUnit); - - stageTimeSeries.setMeasurementByTime(stageMeasurement, time); - - } //end for - - return stageTimeSeries; - - } //end getStageRegularTimeSeries -// --------------------------------------------------------------------- - - public RegularTimeSeries getDischargeRegularTimeSeries(RegularTimeSeries stageTimeSeries) - { - - //ensure input units are correct - stageTimeSeries.convert(_stageUnit); - - - // get info about flowTimeSeries - long startTime = stageTimeSeries.getStartTime(); - long endTime = stageTimeSeries.getEndTime(); - int intervalInHours = stageTimeSeries.getIntervalInHours(); - int intervalInMillis = intervalInHours * _millisPerHour; - - - RegularTimeSeries flowTimeSeries = new RegularTimeSeries(startTime, endTime, - intervalInHours, _dischargeUnit); - - - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement stageMeasurement = stageTimeSeries.getMeasurementByTime(time); - - double flowValue = getDischargeFromStage(stageMeasurement.getValue()); - Measurement flowMeasurement = new Measurement(flowValue, - _dischargeUnit); - - flowTimeSeries.setMeasurementByTime(flowMeasurement, time); - - } //end for - - return flowTimeSeries; - - } //end getFlowRegularTimeSeries - - -// --------------------------------------------------------------------- - -// ***************************************************************************** -// taken from Russ Erb's code -// stageToDischarge() - this method is called with a stage value and returns -// the corresponding discharge -// ***************************************************************************** - public double getDischargeFromStage(double stage) - { - - RatingPoint firstStage = new RatingPoint(); - RatingPoint lastStage = new RatingPoint(); - RatingPoint lowerStage = new RatingPoint(); - RatingPoint higherStage = new RatingPoint(); - - double discharge=0.0; - double diff_discharge=0.0; - double diff_stage=0.0; - - // if the rating curve doesn't exist then return -999 - if (! this.exists()) - return(-999.0); - - // if the stage value passed in is less then the lowest stage in the - // rating table then extrapolate the discharge - firstStage = getFirstRatingPoint(); - if (stage < firstStage.getShiftedStage()) - { - higherStage = getSecondRatingPoint(); - diff_discharge = higherStage.getDischarge() - firstStage.getDischarge(); - diff_stage = higherStage.getShiftedStage() - firstStage.getShiftedStage(); - if (diff_stage == 0.0) - discharge = firstStage.getDischarge(); - else - discharge = firstStage.getDischarge() - ((diff_discharge/diff_stage) * (firstStage.getShiftedStage() - stage)); - } - - // if the stage value passed in is greater then the highest stage in the - // rating table then extrapolate the discharge - lastStage = getLastRatingPoint(); - if (stage > lastStage.getShiftedStage()) - { - lowerStage = getNextToLastRatingPoint(); - diff_discharge = lastStage.getDischarge() - lowerStage.getDischarge(); - diff_stage = lastStage.getShiftedStage() - lowerStage.getShiftedStage(); - if (diff_stage == 0.0) - discharge = lastStage.getDischarge(); - else - discharge = lastStage.getDischarge() + ((diff_discharge/diff_stage) * (stage - lastStage.getShiftedStage())); - } - - // if the stage value passed in is between the lowest and highest stage - // in the rating table then interpolate the discharge - if ( (stage >= firstStage.getShiftedStage()) && (stage <= lastStage.getShiftedStage()) ) - { - for (int ctr=0; ctr< _ratingPointList.size()-1; ctr++) - { - lowerStage = getRatingPoint(ctr); - higherStage = getRatingPoint(ctr+1); - if ( (stage >= lowerStage.getShiftedStage()) && (stage <= higherStage.getShiftedStage()) ) - { - diff_discharge = higherStage.getDischarge() - lowerStage.getDischarge(); - diff_stage = higherStage.getShiftedStage() - lowerStage.getShiftedStage(); - - if (diff_stage == 0.0) - discharge = lowerStage.getDischarge(); - else - discharge = lowerStage.getDischarge() + ((diff_discharge/diff_stage) * (stage - lowerStage.getShiftedStage())); - - break; - } - } //end for - } //end if - - // for some reason the discharge is less than zero then return zero - if (discharge < 0.0) - return(0.0); - else - return(discharge); - - } // end of stageToDischarge method - - -// ***************************************************************************** -// taken from Russ Erb's code -// dischargeToStage() - this method is called with a discharge value and returns -// the corresponding stage -// ***************************************************************************** - public double getStageFromDischarge(double discharge) - { - - RatingPoint firstDischarge = new RatingPoint(); - RatingPoint lastDischarge = new RatingPoint(); - RatingPoint lowerDischarge = new RatingPoint(); - RatingPoint higherDischarge = new RatingPoint(); - - double stage=0.0; - double diff_discharge=0.0; - double diff_stage=0.0; - - // if the rating curve doesn't exist then return -999 - if (! this.exists()) - return(-999.0); - - // if the discharge value passed in is less then the lowest discharge in the - // rating table then extrapolate the stage - firstDischarge = getFirstRatingPoint(); - if (discharge < firstDischarge.getDischarge()) - { - higherDischarge = getSecondRatingPoint(); - diff_discharge = higherDischarge.getDischarge() - firstDischarge.getDischarge(); - diff_stage = higherDischarge.getShiftedStage() - firstDischarge.getShiftedStage(); - if (diff_discharge == 0.0) - stage = firstDischarge.getShiftedStage(); - else - stage = firstDischarge.getShiftedStage() - ((diff_stage/diff_discharge) * (firstDischarge.getDischarge() - discharge)); - } - - // if the discharge value passed in is greater then the highest discharge in the - // rating table then extrapolate the stage - lastDischarge = getLastRatingPoint(); - if (discharge > lastDischarge.getDischarge()) - { - lowerDischarge = getNextToLastRatingPoint(); - diff_discharge = lastDischarge.getDischarge() - lowerDischarge.getDischarge(); - diff_stage = lastDischarge.getShiftedStage() - lowerDischarge.getShiftedStage(); - if (diff_discharge == 0.0) - stage = lastDischarge.getShiftedStage(); - else - stage = lastDischarge.getShiftedStage() + ((diff_stage/diff_discharge) * (discharge - lastDischarge.getDischarge())); - } - - // if the discharge value passed in is between the lowest and highest discharge - // in the rating table then interpolate the stage - if ( (discharge >= firstDischarge.getDischarge()) && (discharge <= lastDischarge.getDischarge()) ) - { - for (int ctr=0; ctr< _ratingPointList.size()-1; ctr++) - { - lowerDischarge = getRatingPoint(ctr); - higherDischarge = getRatingPoint(ctr+1); - if ( (discharge >= lowerDischarge.getDischarge()) && (discharge <= higherDischarge.getDischarge()) ) - { - diff_discharge = higherDischarge.getDischarge() - lowerDischarge.getDischarge(); - diff_stage = higherDischarge.getShiftedStage() - lowerDischarge.getShiftedStage(); - - if (diff_discharge == 0.0) - stage = lowerDischarge.getShiftedStage(); - else - stage = lowerDischarge.getShiftedStage() + ((diff_stage/diff_discharge) * (discharge - lowerDischarge.getDischarge())); - - break; - } - } //end for - } //end if - - // System.out.println("discharge = " + discharge + " stage = " + stage); - - return(stage); - - } // end of dischargeToStage method - - - - -// ***************************************************************************** - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getLocationId()); - - for (int i = 0; i < getRatingPointCount() ; i++) - { - RatingPoint point = (RatingPoint) this.getRatingPoint(i); - buffer.append(point + "\n"); - } - - return buffer.toString(); - - } //end toString - - - - - -} //end class RatingCurve diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingPoint.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingPoint.java deleted file mode 100644 index 3155da9e8e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingPoint.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Created on Jul 7, 2003 - * - * - */ -package ohd.hseb.model; - -/** - * @author GobsC - * - * - */ -public class RatingPoint -{ - private double _shiftAmount; - private double _unshiftedStage; - private double _discharge; - -// ------------------------------------------------------------------------------------------ - public void setUnshiftedStage(double stage) - { - this._unshiftedStage = stage; - } -// ------------------------------------------------------------------------------------------ - - public double getUnshiftedStage() - { - return _unshiftedStage; - } -// ------------------------------------------------------------------------------------------ - - public void setShiftAmount(double shiftAmount) - { - _shiftAmount = shiftAmount; - } -// ------------------------------------------------------------------------------------------ - - public double getShiftedStage() - { - return _unshiftedStage + _shiftAmount; - } -// ------------------------------------------------------------------------------------------ - public void setDischarge(double discharge) - { - this._discharge = discharge; - } -// ------------------------------------------------------------------------------------------ - - public double getDischarge() - { - return _discharge; - } -// ------------------------------------------------------------------------------------------ - public boolean equals(RatingPoint point2) - { - boolean result = false; - - if ( - (this._unshiftedStage == point2._unshiftedStage) && - (this._shiftAmount == point2._shiftAmount) && - (this._discharge == point2._discharge ) - ) - { - result = true; - } - - return result; - - } -// ------------------------------------------------------------------------------------------ - - public String toString() - { - String outString = " stage = " + getUnshiftedStage() + - " discharge = " + getDischarge(); - - return outString; - } -// ------------------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingShift.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingShift.java deleted file mode 100644 index a486172f54..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/RatingShift.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Created on Jun 9, 2004 - * - * Filename : RatingShiftEntry.java - * Author : Gautam Sood - * Last Revision Date : Jun 9, 2004 - * - */ -/** - * @author Gautam Sood -*/ - -package ohd.hseb.model; - -public class RatingShift -{ - private String _lid = null; - - private long _date = 0; - - private double _shiftAmount = 0.0; - - private boolean _active = false; - - public RatingShift() - { - } - - public RatingShift( RatingShift ratingShift ) - { - setLid( ratingShift.getLid() ); - setDate( ratingShift.getDate() ); - setShiftAmount( ratingShift.getShiftAmount() ); - setActive( ratingShift.isActive() ); - } - - public void setLid(String lid) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - - public boolean equals( RatingShift entry ) - { - boolean isEqual = false; - - if ( ( _lid.equalsIgnoreCase( entry.getLid() ) ) && - ( _date == entry.getDate() ) ) - { - isEqual = true; - } - return isEqual; - } - - public void setDate( long date ) - { - _date = date; - } - - public long getDate() - { - return _date; - } - - public void setShiftAmount( double shiftAmount ) - { - _shiftAmount = shiftAmount; - } - - public double getShiftAmount() - { - return _shiftAmount; - } - - public void setActive( boolean active ) - { - _active = active; - } - - public boolean isActive() - { - return _active; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/SigRiverLevels.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/SigRiverLevels.java deleted file mode 100644 index d3ca9873fb..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/SigRiverLevels.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Created on Oct 3, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.db.DbTable; - -/** - * @author Chip Gobs - * - * - */ -public class SigRiverLevels -{ - private String _locationId = null; - - private int MISSING_VALUE = -999; - - private boolean _useStage = true; - private String _primaryPe = null; - - //stages - private double _floodStage = MISSING_VALUE; - private double _actionStage = MISSING_VALUE; - private double _minorFloodStage = MISSING_VALUE; - private double _moderateFloodStage = MISSING_VALUE; - private double _majorFloodStage = MISSING_VALUE; - - //flows - private double _floodFlow = MISSING_VALUE; - private double _actionFlow = MISSING_VALUE; - private double _minorFloodFlow = MISSING_VALUE; - private double _moderateFloodFlow = MISSING_VALUE; - private double _majorFloodFlow = MISSING_VALUE; - - //------------------------------------------------------- - - public SigRiverLevels() - { - - } - - //-------------------------------------------------------------------------------- - - public SigRiverLevels(String locationId, String primaryPe, - double floodStage, double actionStage, - double floodFlow, double actionFlow) - { - _locationId = locationId; - - _primaryPe = primaryPe; - if (_primaryPe.substring(0,1).equalsIgnoreCase("Q")) - { - _useStage = false; - } - - _floodStage = checkMissing(floodStage); - _actionStage = checkMissing(actionStage); - - _floodFlow = checkMissing(floodFlow); - _actionFlow = checkMissing(actionFlow); - - return; - } - - // ------------------------------------------------------------------------------ - private double checkMissing(double value) - { - double resultingValue = value; - - if (value == 0.0) - { - resultingValue = MISSING_VALUE; - } - - return resultingValue; - } - - //-------------------------------------------------------------------------------- - - - public void setLocationId(String locationId) - { - _locationId = locationId; - } - - //-------------------------------------------------------------------------------- - - - public String getLocationId() - { - return _locationId; - } - - //-------------------------------------------------------------------------------- - - - public void setFloodStage(double floodStage) - { - _floodStage = floodStage; - } - - //-------------------------------------------------------------------------------- - - - public double getFloodStage() - { - return _floodStage; - } - -// -------------------------------------------------------------------------------- - - private boolean hasValue(double value) - { - boolean result = true; - - if ((value == MISSING_VALUE) || (DbTable.isNull(value))) - { - result = false; - } - - return result; - } - -// -------------------------------------------------------------------------------- - - - public boolean hasFloodStage() - { - return hasValue(_floodStage); - } - -// -------------------------------------------------------------------------------- - - public boolean hasActionStage() - { - return hasValue(_actionStage); - } - -// -------------------------------------------------------------------------------- - public boolean hasMinorFloodStage() - { - return hasValue(_minorFloodStage); - } -// -------------------------------------------------------------------------------- - public boolean hasModerateFloodStage() - { - return hasValue(_moderateFloodStage); - } -// -------------------------------------------------------------------------------- - public boolean hasMajorFloodStage() - { - return hasValue(_majorFloodStage); - } - -// -------------------------------------------------------------------------------- - - public boolean hasFloodFlow() - { - return hasValue(_floodFlow); - } - -// -------------------------------------------------------------------------------- - - public boolean hasActionFlow() - { - return hasValue(_actionFlow); - } - -// -------------------------------------------------------------------------------- - public boolean hasMinorFloodFlow() - { - return hasValue(_minorFloodFlow); - } -// -------------------------------------------------------------------------------- - public boolean hasModerateFloodFlow() - { - return hasValue(_moderateFloodFlow); - } -// -------------------------------------------------------------------------------- - public boolean hasMajorFloodFlow() - { - return hasValue(_majorFloodFlow); - } - -// -------------------------------------------------------------------------------- - - public void setActionStage(double actionStage) - { - _actionStage = actionStage; - } - -// -------------------------------------------------------------------------------- - - public double getActionStage() - { - return _actionStage; - } - -// -------------------------------------------------------------------------------- - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(_locationId + "with primary pe = " + _primaryPe); - - if (hasFloodStage()) - { - buffer.append("Flood Stage = " + _floodStage + " "); - } - else - { - buffer.append("No flood stage set."); - } - - - if (hasActionStage()) - { - buffer.append("Action Stage = " + _actionStage + "\n"); - - } - else - { - buffer.append("No action stage set."); - } - - - - if (hasFloodFlow()) - { - buffer.append("Flood Flow = " + _floodFlow + " "); - } - else - { - buffer.append("No flood flow set."); - } - - - - if (hasActionFlow()) - { - buffer.append("Action Flow = " + _actionFlow + "\n"); - - } - else - { - buffer.append("No action flow set."); - } - - - String outString = buffer.toString(); - - return outString; - - } -// -------------------------------------------------------------------------------- - - - public void setPrimaryPe(String primaryPe) - { - _primaryPe = primaryPe; - } - -// -------------------------------------------------------------------------------- - - public String getPrimaryPe() - { - return _primaryPe; - } -// -------------------------------------------------------------------------------- - - public void setFloodFlow(double floodFlow) - { - _floodFlow = floodFlow; - } -// -------------------------------------------------------------------------------- - - public double getFloodFlow() - { - return _floodFlow; - } -// -------------------------------------------------------------------------------- - - - public void setActionFlow(double actionFlow) - { - _actionFlow = actionFlow; - } - -// -------------------------------------------------------------------------------- - - public double getActionFlow() - { - return _actionFlow; - } - -// -------------------------------------------------------------------------------- - - public void setUseStage(boolean useStage) - { - _useStage = useStage; - } - -// -------------------------------------------------------------------------------- - - - public boolean useStage() - { - return _useStage; - } - - public void setMinorFloodStage(double minorFloodStage) - { - _minorFloodStage = minorFloodStage; - } - - public double getMinorFloodStage() - { - return _minorFloodStage; - } - - /** - * @param moderateFloodStage The moderateFloodStage to set. - */ - public void setModerateFloodStage(double moderateFloodStage) - { - _moderateFloodStage = moderateFloodStage; - } - - /** - * @return Returns the moderateFloodStage. - */ - public double getModerateFloodStage() - { - return _moderateFloodStage; - } - - /** - * @param majorFloodStage The majorFloodStage to set. - */ - public void setMajorFloodStage(double majorFloodStage) - { - _majorFloodStage = majorFloodStage; - } - - /** - * @return Returns the majorFloodStage. - */ - public double getMajorFloodStage() - { - return _majorFloodStage; - } - - public void setMinorFloodFlow(double minorFloodFlow) - { - _minorFloodFlow = minorFloodFlow; - } - - public double getMinorFloodFlow() - { - return _minorFloodFlow; - } - - public void setModerateFloodFlow(double moderateFloodFlow) - { - _moderateFloodFlow = moderateFloodFlow; - } - - public double getModerateFloodFlow() - { - return _moderateFloodFlow; - } - - public void setMajorFloodFlow(double majorFloodFlow) - { - _majorFloodFlow = majorFloodFlow; - } - - public double getMajorFloodFlow() - { - return _majorFloodFlow; - } - -// -------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/StageToFlowValueMapper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/StageToFlowValueMapper.java deleted file mode 100644 index a86cc8a0d0..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/StageToFlowValueMapper.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Created on Oct 22, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; - - -import ohd.hseb.util.ValueMapper; - -/** - * @author GobsC - * - * This implementation of ValueMapper maps river stages to discharge. - */ -public class StageToFlowValueMapper implements ValueMapper -{ - private MeasuringUnit _inputMeasuringUnit = MeasuringUnit.feet; - private MeasuringUnit _outputMeasuringUnit = MeasuringUnit.cfs; - - - private RatingCurve _ratingCurve = null; - - //-------------------------------------------------------- - - public StageToFlowValueMapper(RatingCurve ratingCurve) - { - _ratingCurve = ratingCurve; - } - //-------------------------------------------------------- - - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement resultMeasurement = null; - - Measurement convertedMeasurement = - Measurement.getConvertedCopy(inputMeasurement, - _inputMeasuringUnit); - double keyValue = convertedMeasurement.getValue(); - - double resultValue = 0; - if (_ratingCurve != null) - { - resultValue = _ratingCurve.getDischargeFromStage(keyValue); - resultMeasurement = new Measurement(resultValue, - _outputMeasuringUnit); - } - - return resultMeasurement; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - //-------------------------------------------------------- - -} // StageToFlowValueMapper diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrograph.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrograph.java deleted file mode 100644 index 75e0cfb6c9..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrograph.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * Created on Jun 25, 2003 - * - * This class is designed to compute the flow from runoff. - */ -package ohd.hseb.model; - -import java.util.*; - -import ohd.hseb.measurement.*; - - -/** - * @author Chip Gobs - * - * The UnitHydrograph class maps runoff to the amount of marginal flow - * generated by that runoff. - * It returns a RegularTimeSeries object that contains flow measurements. - */ - - - -public class UnitHydrograph -{ - - - //input: inches of runoff - //a starting time - //output: a time series of flow in CFS - - private static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - private MeasuringUnit _measuringUnit = MeasuringUnit.cfs; - - private String _locationId = null; - private String _areaId = null; - private String _rainfallRunoffModelTypeName = null; - - private int _interval = -1; // in hours - - private List _measurementList = new ArrayList(); - - //---------------------------------------------------------------------- - - - public UnitHydrograph(MeasuringUnit measuringUnit, int intervalInHours) - { - _measuringUnit = measuringUnit; - _interval = intervalInHours; - } - - //---------------------------------------------------------------------- - - - public void setMeasuringUnit(MeasuringUnit measuringUnit) - { - _measuringUnit = measuringUnit; - } - //---------------------------------------------------------------------- - - public MeasuringUnit getMeasuringUnit() - { - return _measuringUnit; - } - //---------------------------------------------------------------------- - - public void setLocationId(String locationId) - { - _locationId = locationId; - } - //---------------------------------------------------------------------- - - public String getLocationId() - { - return _locationId; - } - //---------------------------------------------------------------------- - - public void setAreaId(String areaId) - { - _areaId = areaId; - } - //---------------------------------------------------------------------- - - public String getAreaId() - { - return _areaId; - } - //---------------------------------------------------------------------- - - public int getOrdinateCount() - { - return _measurementList.size(); - } - //---------------------------------------------------------------------- - - public List getMeasurementList() - { - return _measurementList; - } - - //---------------------------------------------------------------------- - - public void addMeasurement(RelTimeMeasurement origMeasurement) - { - RelTimeMeasurement newMeasurement = - (RelTimeMeasurement) origMeasurement.getConvertedCopy(_measuringUnit); - - _measurementList.add(newMeasurement); - - return; - } - - // ---------------------------------------------------------------------- - - public void setInterval(int interval) - { - _interval = interval; - } - - //---------------------------------------------------------------------- - - public int getIntervalInHours() - { - return _interval; - } - - //---------------------------------------------------------------------- - - public static UnitHydrograph getTestUnitHydrograph() - { - double[] valueArray = { 100.0, 200.0, 350.0, 500.0, - 300.0, 250.0, 200.0, 150.0, - 100.0, 50.0, 25.0, 10}; - - UnitHydrograph uhg = new UnitHydrograph(MeasuringUnit.cfs, 1); - - - for (int i = 0; i < valueArray.length; i++) - { - RelTimeMeasurement measurement = new RelTimeMeasurement(valueArray[i], i, MeasuringUnit.cfs); - uhg.addMeasurement(measurement); - } - - return uhg; - - } - - //---------------------------------------------------------------------- - public UnitHydrograph getScaledUnitHydrograph(double newTotalDischarge) - { - - UnitHydrograph uhg = new UnitHydrograph(this.getMeasuringUnit(), this.getIntervalInHours()); - - double totalDischarge = this.getTotalDischarge(); - double scalingFactor = newTotalDischarge/totalDischarge; - - for (int i = 0; i < _measurementList.size(); i++) - { - RelTimeMeasurement measurement = (RelTimeMeasurement) _measurementList.get(i); - - double value = measurement.getValue() * scalingFactor; - - RelTimeMeasurement newMeasurement = new RelTimeMeasurement(measurement); - newMeasurement.setValue(value); - - uhg.addMeasurement(newMeasurement); - } - - - return uhg; - - } - - //---------------------------------------------------------------------- - - public RelTimeMeasurement getPeakFlowMeasurement() - { - RelTimeMeasurement peak = null; - - for (int i = 0; i < _measurementList.size() ; i++) - { - RelTimeMeasurement measurement = (RelTimeMeasurement) _measurementList.get(i); - if ( (peak == null) || - (measurement.getValue() > peak.getValue()) - ) - { - peak = measurement; - } - } - - return peak; - } - - //---------------------------------------------------------------------- - - public IrregularTimeSeries getFlowTimeSeries(AbsTimeMeasurement runoffMeasurement) - { - MeasuringUnit runoffUnit = MeasuringUnit.inches; - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - - //convert to inches - AbsTimeMeasurement convertedRunoffMeasurement = - AbsTimeMeasurement.getConvertedCopy(runoffMeasurement, runoffUnit); - - double scaleFactor = convertedRunoffMeasurement.getValue(); - - - IrregularTimeSeries ts = new IrregularTimeSeries(MeasuringUnit.cfs); - - long startTime = runoffMeasurement.getTime(); - long measurementTime = 0; - double discharge = 0.0; - - for (int i = 0; i < _measurementList.size(); i++) - { - measurementTime = startTime + (i)*(MILLIS_PER_HOUR); - - Measurement unitGraphValue = - (Measurement) _measurementList.get(i); - - discharge = scaleFactor * unitGraphValue.getValue(); - AbsTimeMeasurement newMeasurement = new AbsTimeMeasurement(discharge, - measurementTime, - dischargeUnit); - ts.insertMeasurement(newMeasurement); - } - - return ts; - } - - //---------------------------------------------------------------------- - - public RegularTimeSeries getFlowRegularTimeSeries(AbsTimeMeasurement runoffMeasurement) - { - MeasuringUnit runoffUnit = MeasuringUnit.inches; - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - - //convert to inches - AbsTimeMeasurement convertedRunoffMeasurement = - AbsTimeMeasurement.getConvertedCopy(runoffMeasurement, runoffUnit); - - double scaleFactor = convertedRunoffMeasurement.getValue(); - - int hourCount = _measurementList.size(); - int intervalInHours = 1; - - long intervalInMillis = intervalInHours * MILLIS_PER_HOUR; - - long startTime = runoffMeasurement.getTime(); - long endTime = startTime + ((hourCount-1) * MILLIS_PER_HOUR); - - RegularTimeSeries ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, dischargeUnit); - - - double discharge = 0.0; - - int i = 0; - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - - Measurement unitgraphValue = - (Measurement) _measurementList.get(i); - - discharge = scaleFactor * unitgraphValue.getValue(); - - Measurement newMeasurement = new Measurement(discharge, - dischargeUnit); - - ts.setMeasurementByTime(newMeasurement, time); - - i++; - } - - return ts; - - } //end getFlowRegularTimeSeries - - //---------------------------------------------------------------------- - - - public String toString() - { - String outString = null; - - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < _measurementList.size(); i++) - { - Measurement m = (Measurement) _measurementList.get(i); - buffer.append ("ordinal " + i + " = " + m.getValue() + "\n"); - } - - outString = buffer.toString(); - - return outString; - } - - //------------------------------------------------------------------------ - public double getTotalDischarge() - { - double total = 0.0; - - for(int i = 0; i < _measurementList.size(); i++) - { - RelTimeMeasurement measurement = (RelTimeMeasurement) _measurementList.get(i); - total += measurement.getValue(); - } - - return total; - } - //------------------------------------------------------------------------ - - public RegularTimeSeries calculateTotalDischargeTs(String status, - RegularTimeSeries interimFlowTimeSeries, - RegularTimeSeries runoffTs, - long startTime, - long endTime, - long intervalInMillis) - - - { - - //String header = "UnitHydrograph.calculateTotalDischargeTs(): " + status; - - // System.out.println(header); - - RegularTimeSeries unitgraphFlowTimeSeries = null; - RegularTimeSeries totalFlowTimeSeries = interimFlowTimeSeries.copy(); - - // convert the runoff to discharge through the unithydrograph - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - Measurement runoffMeasurement = null; - - if (runoffTs != null) - { - runoffMeasurement = runoffTs.getMeasurementByTime(time); - } - else - { - //System.out.println(header + " runoffTs is null"); - } - - if (runoffMeasurement == null) - { - // System.out.println(header + " runoffMeasurement is null when time = " + - // DbTimeHelper.getDateTimeStringFromLongTime(time)); - } - - else - { - - AbsTimeMeasurement absTimeRunoffMeasurement = - new AbsTimeMeasurement(runoffMeasurement, time); - - unitgraphFlowTimeSeries = - this.getFlowRegularTimeSeries(absTimeRunoffMeasurement); - - - if ( (totalFlowTimeSeries != null) && - (unitgraphFlowTimeSeries != null) - ) - { - totalFlowTimeSeries = - RegularTimeSeries.add(totalFlowTimeSeries, - unitgraphFlowTimeSeries); - - // System.out.println(header + "unitgraphFlowTimeSeries is not null"); - // System.out.println(header + "interimFlowTimeSeries is not null\n"); - } - else if (unitgraphFlowTimeSeries != null) - { - totalFlowTimeSeries = unitgraphFlowTimeSeries.copy(); - // System.out.println(header + "unitgraphFlowTimeSeries is not null"); - // System.out.println(header + "interimFlowTimeSeries is null\n"); - } - - } - } //end for - - return totalFlowTimeSeries; - } -// --------------------------------------------------------------------- - - public static void main(String[] args) throws Exception - { - UnitHydrograph uhg = UnitHydrograph.getTestUnitHydrograph(); - AbsTimeMeasurement runoff = null; - IrregularTimeSeries ts1 = null; - IrregularTimeSeries ts2 = null; - IrregularTimeSeries ts3 = null; - - long desiredTime = new Date().getTime() ; - long roundingFactor = 1000 * 60 * 60; - desiredTime /= roundingFactor; - desiredTime *= roundingFactor; - - - - runoff = new AbsTimeMeasurement(1.0, desiredTime, MeasuringUnit.inches); - ts1 = uhg.getFlowTimeSeries(runoff); - System.out.println("ts1 = " + ts1); - - runoff = new AbsTimeMeasurement(1.0, desiredTime + (1000 * 60 * 60), MeasuringUnit.inches); - ts2 = uhg.getFlowTimeSeries(runoff); - System.out.println("ts2 = " + ts2); - - ts3 = IrregularTimeSeries.add(ts1, ts2); - System.out.println("ts3 = " + ts3); - - } //main - - /** - * @param rainfallRunoffModel The rainfallRunoffModel to set. - */ - public void setRainfallRunoffModel(String rainfallRunoffModelTypeName) - { - _rainfallRunoffModelTypeName = rainfallRunoffModelTypeName; - } - - /** - * @return Returns the rainfallRunoffModel. - */ - public String getRainfallRunoffModelTypeName() - { - return _rainfallRunoffModelTypeName; - } - - - -} //end UnitHydrograph diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographDescriptor.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographDescriptor.java deleted file mode 100644 index 7838a4e1f8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographDescriptor.java +++ /dev/null @@ -1,202 +0,0 @@ -package ohd.hseb.model; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -/** - * @author GobsC - * This class describes a particular unit hydrograph, by location, basin, model, and duration. - * - */ -public class UnitHydrographDescriptor -{ - private String _locationId = null; - private String _basinId = null; - private String _model = null; - private int _duration = 0; - // ------------------------------------------------------------------------------ - public UnitHydrographDescriptor(String locationId, String basinId, - String model, int duration) - { - _locationId = locationId; - _basinId = basinId; - _model = model; - _duration = duration; - return; - } - - - // ------------------------------------------------------------------------------ - public static List createUnitHydrographDescriptorList( - List unitHydrographEntryList) - { - String header = "UnitHydrographDescriptor.createUnitHydrographDescriptorList(): "; - List descriptorList = new ArrayList(); - UnitHydrographEntry entry = null; - UnitHydrographDescriptor descriptor = null; - - HashSet descriptorSet = new HashSet(); - - boolean addToDescriptorList = false; - - for (int i = 0; i < unitHydrographEntryList.size(); i++) - { - entry = (UnitHydrographEntry) unitHydrographEntryList.get(i); - - descriptor = UnitHydrographDescriptor.createUnitHydrographDescriptorFromEntry(entry); - - - if (! descriptorSet.contains(descriptor)) - { - descriptorSet.add(descriptor); - } - } - - - - //convert the Set to a List - descriptorList = new ArrayList(descriptorSet); - - //print it all out - -/* - System.out.println(header + " UHG Descriptor List"); - for (int i = 0; i < descriptorList.size(); i++) - { - UnitHydrographDescriptor desc = (UnitHydrographDescriptor) descriptorList.get(i); - System.out.println(desc); - } -*/ - - return descriptorList; - - } - //------------------------------------------------------------------------------ - public static UnitHydrographDescriptor createUnitHydrographDescriptorFromEntry(UnitHydrographEntry entry) - { - UnitHydrographDescriptor descriptor = - new UnitHydrographDescriptor(entry.getLocationId(), - entry.getAreaId(), - entry.getModel(), - entry.getDur()); - - - - return descriptor; - } - //------------------------------------------------------------------------------ - public boolean isMatchingEntry(UnitHydrographEntry entry) - { - boolean result = false; - - if ((_locationId.equals(entry.getLocationId())) - && (_basinId.equals(entry.getAreaId())) - && (_model.equals(entry.getModel())) - && (_duration == entry.getDur())) - { - result = true; - } - - return result; - } - //------------------------------------------------------------------------------ - - /** - * @return Returns the locationId. - */ - public String getLocationId() - { - return _locationId; - } - //------------------------------------------------------------------------------ - - /** - * @return Returns the basinId. - */ - public String getBasinId() - { - return _basinId; - } - - //------------------------------------------------------------------------------ - - - /** - * @return Returns the model. - */ - public String getModel() - { - return _model; - } - //------------------------------------------------------------------------------ - - - /** - * @return Returns the duration. - */ - public int getDuration() - { - return _duration; - } - //------------------------------------------------------------------------------ - public boolean equals(Object object) - { - boolean result = false; - - if (object instanceof UnitHydrographDescriptor) - { - result = equals((UnitHydrographDescriptor) object); - } - else - { - result = false; - } - - return result; - } - - //------------------------------------------------------------------------------ - public int hashCode() - { - - String hashString = _locationId + "|" + _basinId + "|" + _model + "|" +_duration; - - int hashValue = hashString.hashCode(); - - return hashValue; - } - - //------------------------------------------------------------------------------ - - public boolean equals(UnitHydrographDescriptor desc) - { - - boolean result = false; - - if ( (_locationId.equals(desc.getLocationId())) && - (_basinId.equals(desc.getBasinId())) && - (_model.equals(desc.getModel())) && - (_duration == desc.getDuration()) - ) - { - result = true; - } - - return result; - } - //------------------------------------------------------------------------------ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("location = " + _locationId + " " + - "basin = " + _basinId + " " + - "model = " + _model + " " + - "duration = " + _duration); - - return buffer.toString(); - } - //------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographEntry.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographEntry.java deleted file mode 100644 index f713bfb4f3..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographEntry.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Created on Jun 9, 2004 - * - * Filename : UnitHydrographEntry.java - * Author : Gautam Sood - * Last Revision Date : Jun 9, 2004 - * - */ -/** - * @author Gautam Sood -*/ - -package ohd.hseb.model; - - -public class UnitHydrographEntry -{ - private String _locationId = null; - - private String _areaId = null; - - private String _model = null; - - private int _dur = 0; - - private int _ordinal = 0; - - private double _discharge = 0.0; -// ------------------------------------------------------------------------------ - - public UnitHydrographEntry() - { - } -// ------------------------------------------------------------------------------ - - public UnitHydrographEntry( UnitHydrographEntry uhgEntry ) - { - setLocationId( uhgEntry.getLocationId() ); - setAreaId( uhgEntry.getAreaId() ); - setDur( uhgEntry.getDur() ); - setOrdinal( uhgEntry.getOrdinal() ); - setDischarge( uhgEntry.getDischarge() ); - } -// ------------------------------------------------------------------------------ - - public void setLocationId(String locationId) - { - _locationId = locationId; - } -// ------------------------------------------------------------------------------ - - public String getLocationId() - { - return _locationId; - } -// ------------------------------------------------------------------------------ - - public void setAreaId(String areaId) - { - _areaId = areaId; - } -// ------------------------------------------------------------------------------ - - public String getAreaId() - { - return _areaId; - } -// ------------------------------------------------------------------------------ - - public void setDur(int dur) - { - _dur = dur; - } -// ------------------------------------------------------------------------------ - - public int getDur() - { - return _dur; - } -// ------------------------------------------------------------------------------ - - public void setOrdinal(int ordinal) - { - _ordinal = ordinal; - } -// ------------------------------------------------------------------------------ - - public int getOrdinal() - { - return _ordinal; - } -// ------------------------------------------------------------------------------ - - public void setDischarge(double discharge) - { - _discharge = discharge; - } -// ------------------------------------------------------------------------------ - - public double getDischarge() - { - return _discharge; - } -// ------------------------------------------------------------------------------ - - public boolean hasEqualKey( UnitHydrographEntry entry ) - { - boolean isEqual = false; - - if ( - ( _locationId.equalsIgnoreCase( entry.getLocationId() ) ) && - ( _areaId.equalsIgnoreCase( entry.getAreaId() ) ) && - ( _model.equalsIgnoreCase( entry.getModel() ) ) && - ( _dur == entry.getDur() ) && - ( _ordinal == entry.getOrdinal() ) - ) - { - isEqual = true; - } - return isEqual; - } -// ------------------------------------------------------------------------------ - - public boolean equals( Object object ) - { - UnitHydrographEntry entry = (UnitHydrographEntry) object; - boolean isEqual = false; - - if ( - ( _locationId.equalsIgnoreCase( entry.getLocationId() ) ) && - ( _areaId.equalsIgnoreCase( entry.getAreaId() ) ) && - ( _model.equalsIgnoreCase( entry.getModel() ) ) && - ( _dur == entry.getDur() ) && - ( _ordinal == entry.getOrdinal() ) && - ( _discharge == entry.getDischarge()) - ) - { - isEqual = true; - } - return isEqual; - } -// ------------------------------------------------------------------------------ - - public int hashCode() - { - String hashString = _locationId.toLowerCase() + "|" + _areaId.toLowerCase() + - "|" + _model.toLowerCase() + "|" + _dur + "|" + _ordinal + "|" + - _discharge; - - int hashValue = hashString.hashCode(); - - return hashValue; - } -// ------------------------------------------------------------------------------ - - /** - * @param model The model to set. - */ - public void setModel(String model) - { - _model = model; - } -// ------------------------------------------------------------------------------ - - /** - * @return Returns the model. - */ - public String getModel() - { - return _model; - } -// ------------------------------------------------------------------------------ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("location = " + _locationId + " " + - "area = " + _areaId + " " + - "model = " + _model + " " + - "duration = " + DurationCode.getHoursFromCode(_dur) + " " + - "ordinal = " +_ordinal + " " + - "discharge = " + _discharge); - - return buffer.toString(); - } - //------------------------------------------------------------------------------ - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographHolder.java deleted file mode 100644 index f797fb1ff9..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographHolder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Created on Jul 13, 2004 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.model.UnitHydrograph; - -/** - * @author GobsC - * - * - */ -public class UnitHydrographHolder -{ - private UnitHydrograph _unitHydrograph = null; - - // --------------------------------------------------------------------------------- - - public UnitHydrographHolder(UnitHydrograph unitHydrograph) - { - _unitHydrograph = unitHydrograph; - } - - // --------------------------------------------------------------------------------- - - public void setUnitHydrograph(UnitHydrograph unitHydrograph) - { - _unitHydrograph = unitHydrograph; - } - - // --------------------------------------------------------------------------------- - - - public UnitHydrograph getUnitHydrograph() - { - return _unitHydrograph; - } - - // --------------------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographTest.java deleted file mode 100644 index fdf1402c1b..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/UnitHydrographTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package ohd.hseb.model; - -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RelTimeMeasurement; -import junit.framework.TestCase; - -public class UnitHydrographTest extends TestCase -{ - - - public void testScalingAll() - { - - UnitHydrograph origUhg = getTestUnitHydrograph(); - - testScaling(origUhg.getTotalDischarge()); - testScaling(origUhg.getTotalDischarge() * 2); - testScaling(origUhg.getTotalDischarge()/2); - testScaling(100); - - - } - - public void testScaling(double desiredTotalDischarge) - { - UnitHydrograph origUhg = getTestUnitHydrograph(); - - UnitHydrograph scaledUhg = origUhg.getScaledUnitHydrograph(desiredTotalDischarge); - assertEquals(desiredTotalDischarge, scaledUhg.getTotalDischarge(), 0.0001 ); - } - - public static UnitHydrograph getTestUnitHydrograph() - { - double[] valueArray = { 100.0, 200.0, 350.0, 500.0, - 300.0, 250.0, 200.0, 150.0, - 100.0, 50.0, 25.0, 10}; - - UnitHydrograph uhg = new UnitHydrograph(MeasuringUnit.cfs, 1); - - - for (int i = 0; i < valueArray.length; i++) - { - RelTimeMeasurement measurement = new RelTimeMeasurement(valueArray[i], i, MeasuringUnit.cfs); - uhg.addMeasurement(measurement); - } - - return uhg; - - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/mkcapi/KcApiRainfallRunoffModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/mkcapi/KcApiRainfallRunoffModel.java deleted file mode 100644 index 1fc1e2f3d7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/mkcapi/KcApiRainfallRunoffModel.java +++ /dev/null @@ -1,446 +0,0 @@ -// -// filename: KcApiRainfallRunoffModel.java -// author : Chip Gobs - -// description: This class is used to encapsulate the MKC-API -// - -package ohd.hseb.model.mkcapi; - -//import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; - -public class KcApiRainfallRunoffModel implements RainfallRunoffModel -{ - - //debugging variable from 5/27/04 - // private boolean _oldWay = false; - -//***************************************************************************** -// Private data -//***************************************************************************** - private boolean _success = true; - - private double _thresholdRunoff; - private double _ffhValue; - - private double _soilMoistureIndex; - - private long _startTime = 0; //starting time of the model states - private long _tsStartTime = 0; // starting time of the output = startTime + 1hour - private long _endTime = 0; - - private RegularTimeSeries _hourlyMapTs = null; - private RegularTimeSeries _accumMapTs = null; - - private RegularTimeSeries _accumRunoffTs = null; - private RegularTimeSeries _hourlyRunoffTs = null; - - // the output dischard time series - private RegularTimeSeries _hourlyDischargeTs = null; - - private static final MeasuringUnit _precipUnit = MeasuringUnit.inches; - private static final MeasuringUnit _runoffUnit = MeasuringUnit.inches; - private static final int _millisPerHour = 60 * 60 * 1000; - - private double _missingValue = -999.0; - -//***************************************************************************** -// KcApiModel() - constructor has the Threshold Runoff, 1-hour FFH, hourly MAPs, -// and unit-hydrograph passed in and then..... -// -//***************************************************************************** - public KcApiRainfallRunoffModel(double tro, double ffh) - { - _thresholdRunoff = tro; - _ffhValue = ffh; - - - } // end of constructor - - - public void setFfhValue(double ffhValue) - { - _ffhValue = ffhValue; - } - - - public double getFfhValue() - { - return _ffhValue; - } -// ***************************************************************************** -// calcSMI() - method which calculates the Soil Moisture Index -// ***************************************************************************** - - public RegularTimeSeries calculateRunoff( long startTime, - long endTime, - RegularTimeSeries hourlyMapTimeSeries) - { - - - - _startTime = startTime; - _endTime = endTime; - - int intervalInMillis = 1 * _millisPerHour; - _tsStartTime = _startTime + intervalInMillis; - - // the time series start time is one hour after the startTime, - // which represents the last saved model state time - - - - String header = "KcApiModel.calculateRunoff():"; - /* System.out.println(header + "running the KcApiModel with startTime = " - + DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - " endTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - */ - - //note: not doing anything with the evaporationTimeSeries - // find a better way to package the specific input requirements for - // the various models - - _success = true; - - _hourlyMapTs = hourlyMapTimeSeries; - - _hourlyMapTs.convert(_precipUnit); - - - // System.out.println(header + " before stretch _hourlyMapTs = " + _hourlyMapTs); - - _hourlyMapTs.stretchTimeSeries(_tsStartTime, _endTime, 0.0); - - //System.out.println(header + " after stretch _hourlyMapTs = " + _hourlyMapTs); - - - // System.out.println(header + " _thresholdRunoff = " + _thresholdRunoff); - - // System.out.println(header + " _ffhValue = " + _ffhValue); - - - - if (_thresholdRunoff < 0.0) - _success = false; - // else if (_latestFFH < 0.0) - // _success = false; - else if (_hourlyMapTs.getMeasurementCount() < 1) - _success = false; - - if (_success) - _success = calcSMI(); - - if (_success) - _success = calcAccumMap(); - - if (_success) - _success = calcAccumRO(); - - if (_success) - _success = calcHourlyRO(); - - - return _hourlyRunoffTs; - } // end of calculateRunoff() - - -// ***************************************************************************** -// computed() - method which checks if a Discharge TS was computed or not -// ***************************************************************************** - public boolean computedSuccessfully() - { - return _success; - - } // end of computed method - - -// ***************************************************************************** -// getSMI() - method which returns the Soil Moisture Index -// ***************************************************************************** - public double getSMI() - { - return _soilMoistureIndex; - } // end of getSMI method - - -// ***************************************************************************** -// getDischargeTS() - method which returns an array which contains the hourly -// discharge values computed using the MBRFC SMI method -// ***************************************************************************** - public RegularTimeSeries getDischargeTS() - { - if (computedSuccessfully()) - return _hourlyDischargeTs; - else - return null; - - } - - public void setThresholdRunoff(double thresholdRunoff) - { - _thresholdRunoff = thresholdRunoff; - } - - public double getThresholdRunoff() - { - return _thresholdRunoff; - } - - -//***************************************************************************** -// calcSMI() - method which calculates the Soil Moisture Index -//***************************************************************************** - private boolean calcSMI() - { - String header = "KcApiRainfallRunoffModel.calcSMI(): "; - double tryThisSMI = 0.18; - double runoff = 0.0; - - // System.out.println(header + "_ffhValue = " + _ffhValue ); - // System.out.println(header + "_thresholdRunoff = " + _thresholdRunoff ); - - - runoff = _thresholdRunoff; - while (runoff >= _thresholdRunoff) - { - tryThisSMI = tryThisSMI + 0.01; - runoff = runMBRFC_API(tryThisSMI, _ffhValue); - } - - _soilMoistureIndex = tryThisSMI; - - - - // System.out.println(header + "_soilMoistureIndex = " + _soilMoistureIndex ); - - - - return true; - - } // end of calcSMI method - -//***************************************************************************** -// runMBRFC_API() - method which returns the Runoff given the SMI and precip -//***************************************************************************** - private double runMBRFC_API(double s, double p) - { - double smi = s; - double precip = p; - - double en = 0.0; - double d = 0.0; - double runoff = 0.0; - - en = 0.89 + (0.63 * smi); - d = 0.306 * Math.pow(smi, 1.865); - runoff = Math.pow( ( Math.pow(precip, en) + Math.pow(d, en) ) , (1.0/en) ) - d; - - return runoff; - - } // end of calcSMI method - -//***************************************************************************** -// calcAccumMap() - method which takes the individual hourly MAPs and -// calculates the accumulated MAPs for each hour -//***************************************************************************** - private boolean calcAccumMap() - { - String header = "KcApiModel.calcAccumMap()"; - - // long startTime = _tsStartTime; - // long endTime = _endTime; - - // old way fixed 5/27/04 - - long startTime = _tsStartTime; - long endTime = _endTime; - - - MeasuringUnit hourlyMapTsUnit = _hourlyMapTs.getMeasuringUnit(); - - _accumMapTs = new RegularTimeSeries(startTime, endTime, 1, hourlyMapTsUnit); - - Measurement accumMeasurement = null; - - - //initialize the first accumulated value to the first hourly value - - Measurement firstHourlyMeasurement = _hourlyMapTs.getMeasurementByTime(startTime); - Measurement firstAccumMeasurement = new Measurement(firstHourlyMeasurement); - - _accumMapTs.setMeasurementByTime(firstAccumMeasurement, startTime); - - double hourlyValue = 0.0; - double previousAccumValue = 0.0; - - final long millisPerHour = 1000 * 60 * 60; - - // load the time series with accumulated precip values - for (long time=startTime+millisPerHour ; time <= endTime; time+= millisPerHour) - { - - - hourlyValue = _hourlyMapTs.getMeasurementValueByTime(time, _precipUnit); - previousAccumValue = _accumMapTs.getMeasurementValueByTime(time-millisPerHour, _precipUnit); - - double newValue = 0.0; - - if (hourlyValue > 0.0) - { - newValue = previousAccumValue + hourlyValue; - } - else - { - newValue = previousAccumValue; - } - - - // This was just a coding error. It did not cause a problem since the - // values were the same anyway - INCHES - // REPLACED 5/27/04 Measurement newMeasurement = new Measurement(newValue, _hourlyMapTsUnit); - Measurement newMeasurement = new Measurement(newValue, _precipUnit); - - _accumMapTs.setMeasurementByTime(newMeasurement, time); - - } //end accum for loop - - return true; - } // end of calcAccumMap method - - -//***************************************************************************** -// calcAccumRO() - method which -//***************************************************************************** - private boolean calcAccumRO() - { - String header = "KcApiRainfallRunoffModel.calcAccumRO(): "; - - -// this block commented out 5/27/04 from KcApiRainfallRunoffModel.calcAccumRO() - //long startTime = _accumMapTs.getStartTime(); - // long endTime = _accumMapTs.getEndTime(); - - // this block added 5/27/04 to KcApiRainfallRunoffModel.calcAccumRO() - long startTime = _tsStartTime; - long endTime = _endTime; - - - - - double accumRunoffValue = 0.0; - long intervalInMillis = _millisPerHour; - - _accumRunoffTs = new RegularTimeSeries(startTime, endTime, 1, _runoffUnit); - - for (long time = startTime; time <= endTime; time += intervalInMillis) - { - //double accumMapValue = getMeasurementValueByIndex(_accumMapTs, i, _precipUnit); - double accumMapValue = _accumMapTs.getMeasurementValueByTime(time, _precipUnit); - - if (accumMapValue < 0.0) - { - accumMapValue = 0.0; - } - - accumRunoffValue = runMBRFC_API(_soilMoistureIndex, accumMapValue); - Measurement accumRunoffMeasurement = new Measurement(accumRunoffValue, _runoffUnit); - _accumRunoffTs.setMeasurementByTime(accumRunoffMeasurement, time); - } - - - - return true; - - } // end of calcAccumRO method - - -//***************************************************************************** -// calcHourlyRO() - method which -//***************************************************************************** - private boolean calcHourlyRO() - { - String header = "KcApiModel.calcHourlyRO(): "; - - long startTime = _accumRunoffTs.getStartTime(); - long endTime = _accumRunoffTs.getEndTime(); - - _hourlyRunoffTs = new RegularTimeSeries(startTime, endTime, 1, _runoffUnit); - - - - double accumValue = _accumRunoffTs.getMeasurementValueByTime( startTime, _runoffUnit); - Measurement accumMeasurement = new Measurement(accumValue, _accumRunoffTs.getMeasuringUnit()); - _hourlyRunoffTs.setMeasurementByTime(accumMeasurement, startTime); - - - for (int i=1; i<_accumRunoffTs.getMeasurementCount(); i++) - { - double currentAccumValue = getMeasurementValueByIndex(_accumRunoffTs, i, _runoffUnit); - double previousAccumValue = getMeasurementValueByIndex(_accumRunoffTs, i-1, _runoffUnit); - - double runoffValue = currentAccumValue - previousAccumValue; - - // System.out.println(header + " _accumRunoffTs.getMeasuringUnit() = " + _accumRunoffTs.getMeasuringUnit()); - - - Measurement runoffMeasurement = new Measurement(runoffValue, - _accumRunoffTs.getMeasuringUnit()); - - long time = _hourlyRunoffTs.getMeasurementTimeByIndex(i); - _hourlyRunoffTs.setMeasurementByTime(runoffMeasurement, time); - //String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - /* - if (runoffValue != 0.0) - { - System.out.println(header + " runoffMeasurement = " + - runoffMeasurement + " at " + timeString); - } - */ - } - - //System.out.println(header + "bug version = " + _oldWay); - // System.out.println(header + "_accumMapTs = " + _accumMapTs); - // System.out.println(header + "_accumRunoffTs = " + _accumRunoffTs); - // System.out.println(header + "_hourlyRunoffTs = " + _hourlyRunoffTs); - // System.out.println(header + " _accumRunoffTs = " + _accumRunoffTs); - - - return true; - - } // end of calcHourlyRO method - - // --------------------------------------------------------------------------- - private double getMeasurementValueByIndex(RegularTimeSeries ts, int index, MeasuringUnit unit) - { - double value = _missingValue; - - Measurement m = ts.getMeasurementByIndex(index); - - if (m != null) - { - if (! m.isMissing() ) - { - m = m.getCopy(unit); - value = m.getValue(); - } - else - { - value = _missingValue; //set this class's version of a missing value - } - } - - return value; - } - - - public RainfallRunoffModelType getModelType() - { - return RainfallRunoffModelType.API_MKC; - } - - -} // end of KcApi class diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/mkcapi/KcApiRainfallToStageModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/mkcapi/KcApiRainfallToStageModel.java deleted file mode 100644 index 55aaf63f89..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/mkcapi/KcApiRainfallToStageModel.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.model.mkcapi; - -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; -/** - * @author Chip Gobs - * - * This class combines the RainfallRunoffModel - * with a UnitHydrograph and a Rating Curve to output a TimeSeries object. - */ -public class KcApiRainfallToStageModel implements RainfallToStageModel -{ - private RainfallRunoffModel _rainfallRunoffModel = null; - private ForecastAdjuster _forecastAdjuster = null; - - private RatingCurve _ratingCurve = null; - private UnitHydrograph _unitgraph = null; - - private final static long _millisPerHour = 60 * 60 * 1000; - - private MeasurementHolder _baseStageMeasurementHolder = null; - private IrregularTimeSeriesHolder _observedStageTimeSeriesHolder = null; - private RegularTimeSeriesHolder _simulatedDischargeTimeSeriesHolder = null; - - - private final static MeasuringUnit _stageUnit = MeasuringUnit.feet; - private final static MeasuringUnit _dischargeUnit = MeasuringUnit.cfs; - -// ------------------------------------------------------------- - - public KcApiRainfallToStageModel(RainfallRunoffModel rainfallRunoffModel, - UnitHydrograph unitgraph, - RatingCurve ratingCurve, - MeasurementHolder baseStageMeasurementHolder, - IrregularTimeSeriesHolder observedStageTimeSeriesHolder, - ForecastAdjuster forecastAdjuster, - RegularTimeSeriesHolder simulatedDischargeTimeSeriesHolder) - { - - _rainfallRunoffModel = rainfallRunoffModel; - - _ratingCurve = ratingCurve; - _unitgraph = unitgraph; - - _baseStageMeasurementHolder = baseStageMeasurementHolder; - - _observedStageTimeSeriesHolder = observedStageTimeSeriesHolder; - - _forecastAdjuster = forecastAdjuster; - _simulatedDischargeTimeSeriesHolder = simulatedDischargeTimeSeriesHolder; - - } //end RainfallToStageModel() - - // ------------------------------------------------------------- - - public RegularTimeSeries calculateStageTimeSeries(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries, - RegularTimeSeriesHolder runoffTimeSeriesHolder) - - - { - - - Measurement baseflowMeasurement = null; - - //get the baseflow measurement - if (_ratingCurve != null) - { - double stageValue = _baseStageMeasurementHolder.getMeasurement().getValue(_stageUnit); - double dischargeValue = _ratingCurve.getDischargeFromStage(stageValue); - baseflowMeasurement = new Measurement(dischargeValue, _dischargeUnit); - } - String header = "KcApiRainfallToStageModel.calculateStageTimeSeries():"; - - int intervalInHours = 1; - long intervalInMillis = _millisPerHour * intervalInHours; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - long tsStartTime = startTime + intervalInMillis; - - - /* - System.out.println(header + "startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - " endTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - */ - - // System.out.println(header + "precipTimeSeries = " + precipTimeSeries); - // System.out.println(header + "evap TimeSeries = " + potentialEvapTimeSeries); - - - - - RegularTimeSeries runoffTs = - _rainfallRunoffModel.calculateRunoff(startTime, - endTime, - precipTimeSeries); - - runoffTimeSeriesHolder.setTimeSeries(runoffTs); - - //System.out.println(header + "--------------------------------"); - // System.out.println(header + "runoffTs = " + runoffTs); - - - RegularTimeSeries totalFlowTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, - intervalInHours, MeasuringUnit.cfs); - - - - // System.out.println(header + "after unithydrograph, prior total flow time series " + totalFlowTimeSeries); - - //use newly calculated runoff - totalFlowTimeSeries = - _unitgraph.calculateTotalDischargeTs("new ", - totalFlowTimeSeries, - runoffTs, - tsStartTime, - endTime, - intervalInMillis); - - - - //System.out.println(header + "after unithydrograph, new total flow time series " + totalFlowTimeSeries); - - // create a test baseFlow time series - RegularTimeSeries baseFlowTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, - intervalInHours, - MeasuringUnit.cfs, - baseflowMeasurement.getValue() - ); - - // System.out.println(header + "base flow time series " + baseFlowTimeSeries); - - - // add the baseflow to the current total flow - totalFlowTimeSeries = RegularTimeSeries.add(totalFlowTimeSeries, baseFlowTimeSeries); - - - - // System.out.println(header + "after addition of baseflow, new total flow time series " + totalFlowTimeSeries); - - - //store the simulation results - _simulatedDischargeTimeSeriesHolder.setTimeSeries(totalFlowTimeSeries); - - // forecast adjustment - if (_forecastAdjuster.getParams().shouldDoAdjustment()) - { - // CodeTimer timer = new CodeTimer(); - //timer.start(); - IrregularTimeSeries observedStageTimeSeries = _observedStageTimeSeriesHolder.getTimeSeries(); - IrregularTimeSeries observedDischargeTimeSeries = _ratingCurve.getDischargeIrregularTimeSeries(observedStageTimeSeries); - totalFlowTimeSeries = _forecastAdjuster.getAdjustedTimeSeries(observedDischargeTimeSeries, totalFlowTimeSeries); - // timer.stop(" the forecast adjustment took "); - } - - - - RegularTimeSeries stageTimeSeries = - _ratingCurve.getStageRegularTimeSeries(totalFlowTimeSeries); - - return stageTimeSeries; - - } //end getStageTimeSeries - -// --------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacRainfallToStageModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacRainfallToStageModel.java deleted file mode 100644 index 60eb85375d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacRainfallToStageModel.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.model.sacsma; - -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; -//import ohd.hseb.util.CodeTimer; - -/** - * @author Chip Gobs - * - * This class combines the RainfallRunoffModel - * with a UnitHydrograph and a Rating Curve to output a TimeSeries object. - */ -public class SacRainfallToStageModel implements RainfallToStageModel -{ - private RainfallRunoffModel _rainfallRunoffModel = null; - private ForecastAdjuster _forecastAdjuster = null; - - private RatingCurve _ratingCurve = null; - private UnitHydrograph _unitgraph = null; - - private RegularTimeSeriesHolder _priorRunoffTimeSeriesHolder = null; - private IrregularTimeSeriesHolder _observedStageTimeSeriesHolder = null; - private RegularTimeSeriesHolder _simulatedDischargeTimeSeriesHolder = null; - - private final static long _millisPerHour = 60 * 60 * 1000; - -// ------------------------------------------------------------- - - public SacRainfallToStageModel(RainfallRunoffModel rainfallRunoffModel, - UnitHydrograph unitgraph, - RatingCurve ratingCurve, - RegularTimeSeriesHolder priorRunoffTimeSeriesHolder, - IrregularTimeSeriesHolder observedStageTimeSeriesHolder, - ForecastAdjuster forecastAdjuster, - RegularTimeSeriesHolder simulatedDischargeTimeSeriesHolder) - { - - _rainfallRunoffModel = rainfallRunoffModel; - - _ratingCurve = ratingCurve; - _unitgraph = unitgraph; - - _priorRunoffTimeSeriesHolder = priorRunoffTimeSeriesHolder; - - - // forecast adjustment variables - _observedStageTimeSeriesHolder = observedStageTimeSeriesHolder; - _forecastAdjuster = forecastAdjuster; - _simulatedDischargeTimeSeriesHolder = simulatedDischargeTimeSeriesHolder; - - - } //end RainfallToStageModel() - - // ------------------------------------------------------------- - - public RegularTimeSeries calculateStageTimeSeries(long startTime, - long endTime, - RegularTimeSeries precipTimeSeries, - RegularTimeSeriesHolder runoffTimeSeriesHolder - ) - - { - - String header = "SacRainfallToStageModel.calculateStageTimeSeries():"; - - - RegularTimeSeries priorRunoffTimeSeries = _priorRunoffTimeSeriesHolder.getTimeSeries(); - - int intervalInHours = 1; - long intervalInMillis = _millisPerHour * intervalInHours; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - long tsStartTime = startTime + intervalInMillis; - - - - - RegularTimeSeries runoffTs = - _rainfallRunoffModel.calculateRunoff(startTime, - endTime, - precipTimeSeries); - - runoffTimeSeriesHolder.setTimeSeries(runoffTs); - - - RegularTimeSeries totalFlowTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, - intervalInHours, MeasuringUnit.cfs); - - - //note: the previous totalFlowTimeSeries will be ADDED(math) to the flow output - // from the unit hydrograph - - //use prior runoff - - long priorRunoffStartTime = startTime - - (_unitgraph.getOrdinateCount() * _millisPerHour); - - long priorRunoffEndTime = startTime; - totalFlowTimeSeries = - _unitgraph.calculateTotalDischargeTs("prior ", - totalFlowTimeSeries, - priorRunoffTimeSeries, - priorRunoffStartTime, - priorRunoffEndTime, - intervalInMillis); - - - // System.out.println(header + "after _unitgraph.calculateTotalDischargeTs(), prior total flow time series\n " + totalFlowTimeSeries); - - //use newly calculated runoff - totalFlowTimeSeries = - _unitgraph.calculateTotalDischargeTs("new ", - totalFlowTimeSeries, - runoffTs, - tsStartTime, - endTime, - intervalInMillis); - - - - - // System.out.println(header + "after _unitgraph.calculateTotalDischargeTs(), new total flow time series\n " + totalFlowTimeSeries); - - //lop off the hours at the beginning that are before the model run start time - totalFlowTimeSeries.trimTimeSeriesAtStart(tsStartTime); - - - //store the simulation results - _simulatedDischargeTimeSeriesHolder.setTimeSeries(totalFlowTimeSeries); - - // forecast adjustment - if (_forecastAdjuster.getParams().shouldDoAdjustment()) - { - // CodeTimer timer = new CodeTimer(); - //timer.start(); - IrregularTimeSeries observedStageTimeSeries = _observedStageTimeSeriesHolder.getTimeSeries(); - IrregularTimeSeries observedDischargeTimeSeries = _ratingCurve.getDischargeIrregularTimeSeries(observedStageTimeSeries); - totalFlowTimeSeries = _forecastAdjuster.getAdjustedTimeSeries(observedDischargeTimeSeries, totalFlowTimeSeries); - // timer.stop(" the forecast adjustment took "); - } - - - // System.out.println(header + "after totalFlowTimeSeries.trimTimeSeriesAtStart(), new total flow time series\n " + totalFlowTimeSeries); - - - // put through the rating curve to get the stages - RegularTimeSeries stageTimeSeries = - _ratingCurve.getStageRegularTimeSeries(totalFlowTimeSeries); - - return stageTimeSeries; - - } //end getStageTimeSeries - -// --------------------------------------------------------------------- - - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaParameters.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaParameters.java deleted file mode 100644 index 96cca98cd8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaParameters.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Created on Jun 20, 2003 - * - * - */ -package ohd.hseb.model.sacsma; -import java.text.*; - -/** - * @author gobsc - * - * - */ -public class SacSmaParameters -{ - - private String _basinId; - private String _source; - private long _validTime; - private long _postingTime; - - - // these were common block parameter variables in the FORTRAN code - private double _uztwm = 0.0; - private double _uzfwm = 0.0; - private double _uzk = 0.0; - private double _pctim = 0.0; - private double _adimp = 0.0; - private double _riva = 0.0; - private double _zperc = 0.0; - private double _rexp = 0.0; - - private double _lztwm = 0.0; - private double _lzfsm = 0.0; - private double _lzfpm = 0.0; - private double _lzsk = 0.0; - private double _lzpk = 0.0; - - private double _pfree = 0.0; - - //these 2 are calculated - //SAVED = RSERV * (LZFPM + LZFSM) - // private double _saved = 0.0; //aka rserv? - //PAREA = 1.0 - PCTIM - ADIMP - // private double _parea = 0.0; - - private double _rserv = 0.0; - - private double _side = 0.0; - - //other sac params - not soil related - - private double _peadj = 0.0; - private double _pxadj = 0.0; - private double _efc = 0.0; - - - - - - public SacSmaParameters() - { - } - - public SacSmaParameters(SacSmaParameters params) - { - //copy constructor - - setBasinId(params.getBasinId()); - setSource(params.getSource()); - setValidTime(params.getValidTime()); - setPostingTime(params.getPostingTime()); - - - setUztwm(params.getUztwm()); - setUzfwm(params.getUzfwm()); - setUzk(params.getUzk()); - setPctim(params.getPctim()); - setAdimp(params.getAdimp()); - setRiva(params.getRiva()); - setZperc(params.getZperc()); - setRexp(params.getRexp()); - - setLztwm(params.getLztwm()); - setLzfsm(params.getLzfsm()); - setLzfpm(params.getLzfpm()); - setLzsk(params.getLzsk()); - setLzpk(params.getLzpk()); - - - setPfree(params.getPfree()); - setRserv(params.getRserv()); - setSide(params.getSide()); - - return; - } - - /** - * - * @param paramArray - * The parameters are doubles in this order: - * UZTWM, UZFWM, UZK, PCTIM, ADIMP, RIVA, ZPERC, REXP,LZTWM, LZFSM, LZFPM, LZSK, LZPK, PFREE, RSERV, SIDE - */ - public SacSmaParameters(double[] paramArray) - { - int i = 0; - setUztwm(paramArray[i++]); - setUzfwm(paramArray[i++]); - setUzk(paramArray[i++]); - setPctim(paramArray[i++]); - setAdimp(paramArray[i++]); - setRiva(paramArray[i++]); - setZperc(paramArray[i++]); - setRexp(paramArray[i++]); - setLztwm(paramArray[i++]); - setLzfsm(paramArray[i++]); - - setLzfpm(paramArray[i++]); - setLzsk(paramArray[i++]); - setLzpk(paramArray[i++]); - setPfree(paramArray[i++]); - - setRserv(paramArray[i++]); - setSide(paramArray[i++]); - - } - - public boolean equals(SacSmaParameters params) - { - boolean result = false; - - if ( - (getBasinId().equalsIgnoreCase(params.getBasinId())) && - (getSource().equalsIgnoreCase(params.getSource())) && - (getValidTime() == params.getValidTime()) && - (getPostingTime() == params.getPostingTime()) && - (getUztwm() == params.getUztwm()) && - (getUzfwm() == params.getUzfwm()) && - (getUzk() == params.getUzk()) && - (getPctim() == params.getPctim()) && - (getAdimp() == params.getAdimp()) && - (getRiva() == params.getRiva()) && - (getZperc() == params.getZperc()) && - (getRexp() == params.getRexp()) && - (getLztwm() == params.getLztwm()) && - (getLzfsm() == params.getLzfsm()) && - (getLzfpm() == params.getLzfpm()) && - (getLzsk() == params.getLzsk()) && - (getLzpk() == params.getLzpk()) && - (getPfree() == params.getPfree()) && - (getRserv() == params.getRserv()) && - (getSide() == params.getSide()) && - (getPeadj() == params.getPeadj()) && - (getPxadj() == params.getPxadj()) && - (getEfc() == params.getEfc()) - ) - - { - result = true; - } - - return result; - } - - - public boolean equalsValues(SacSmaParameters params) - { - boolean result = false; - - if ( - // (getBasinId().equalsIgnoreCase(params.getBasinId())) && - //(getSource().equalsIgnoreCase(params.getSource())) && - // (getValidTime() == params.getValidTime()) && - // (getPostingTime() == params.getPostingTime()) && - (getUztwm() == params.getUztwm()) && - (getUzfwm() == params.getUzfwm()) && - (getUzk() == params.getUzk()) && - (getPctim() == params.getPctim()) && - (getAdimp() == params.getAdimp()) && - (getRiva() == params.getRiva()) && - (getZperc() == params.getZperc()) && - (getRexp() == params.getRexp()) && - (getLztwm() == params.getLztwm()) && - (getLzfsm() == params.getLzfsm()) && - (getLzfpm() == params.getLzfpm()) && - (getLzsk() == params.getLzsk()) && - (getLzpk() == params.getLzpk()) && - (getPfree() == params.getPfree()) && - (getRserv() == params.getRserv()) && - (getSide() == params.getSide()) && - (getPeadj() == params.getPeadj()) && - (getPxadj() == params.getPxadj()) && - (getEfc() == params.getEfc()) - ) - - { - result = true; - } - - return result; - } - - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat f = new DecimalFormat(formatString); - - String outString = "Params = " + - " uztwm = " + f.format(_uztwm) + - " uzfwm = " + f.format(_uzfwm) + - " uzk = " + f.format(_uzk) + - " pctim = " + f.format(_pctim) + "\n" + - " adimp = " + f.format(_adimp) + - " riva = " + f.format(_riva) + - " zperc = " + f.format(_zperc) + - - " rexp = " + f.format(_rexp) + "\n" + - " lztwm = " + f.format(_lztwm) + - " lzfsm = " + f.format(_lzfsm) + - - " lzfpm = " + f.format(_lzfpm) + - - " lzsk = " + f.format(_lzsk) + "\n" + - " lzpk = " + f.format(_lzpk) + - " pfree = " + f.format(_pfree) + - " rserv = " + f.format(_rserv) + - " side = " + f.format(_side) + "\n" + - " parea = " + f.format(getParea()) + "\n"; - - return outString; - - } - - public void setBasinId(String basinId) - { - _basinId = basinId; - } - - public String getBasinId() - { - return _basinId; - } - - public void setSource(String source) - { - _source = source; - } - - public String getSource() - { - return _source; - } - - public void setValidTime(long validTime) - { - _validTime = validTime; - } - - public long getValidTime() - { - return _validTime; - } - - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - - public long getPostingTime() - { - return _postingTime; - } - -// accessors - - public void setUztwm(double uztwm) { - this._uztwm = uztwm; - } - - public double getUztwm() { - return _uztwm; - } - - public void setUzfwm(double uzfwm) { - this._uzfwm = uzfwm; - } - - public double getUzfwm() { - return _uzfwm; - } - - public void setUzk(double uzk) { - this._uzk = uzk; - } - - public double getUzk() { - return _uzk; - } - - public void setPctim(double pctim) { - this._pctim = pctim; - } - - public double getPctim() { - return _pctim; - } - - public void setAdimp(double adimp) { - this._adimp = adimp; - } - - public double getAdimp() { - return _adimp; - } - - public void setRiva(double riva) { - this._riva = riva; - } - - public double getRiva() { - return _riva; - } - - public void setZperc(double zperc) { - this._zperc = zperc; - } - - public double getZperc() { - return _zperc; - } - - public void setRexp(double rexp) { - this._rexp = rexp; - } - - public double getRexp() { - return _rexp; - } - - public void setLztwm(double lztwm) { - this._lztwm = lztwm; - } - - public double getLztwm() { - return _lztwm; - } - - public void setLzfsm(double lzfsm) { - this._lzfsm = lzfsm; - } - - public double getLzfsm() { - return _lzfsm; - } - - public void setLzfpm(double lzfpm) { - this._lzfpm = lzfpm; - } - - public double getLzfpm() { - return _lzfpm; - } - - public void setLzsk(double lzsk) { - this._lzsk = lzsk; - } - - public double getLzsk() { - return _lzsk; - } - - public void setLzpk(double lzpk) { - this._lzpk = lzpk; - } - - public double getLzpk() { - return _lzpk; - } - - public void setPfree(double pfree) { - this._pfree = pfree; - } - - public double getPfree() { - return _pfree; - } - - public void setSide(double side) { - this._side = side; - } - - public double getSide() { - return _side; - } - - - public double getSaved() - { //calculated parameter - // - return (_rserv * (_lzfpm + _lzfsm)); - //return _saved; - } - - //public void setParea(double parea) { - // this._parea = parea; - //} - - public double getParea() - { //calculated parameter - return (1.0 - _pctim - _adimp); - //return _parea; - } - - public void setRserv(double rserv) - { - this._rserv = rserv; - } - - public double getRserv() - { - return _rserv; - } - - - public double getPeadj() - { - return _peadj; - } - - - public void setPeadj(double peadj) - { - _peadj = peadj; - } - - - public double getPxadj() - { - return _pxadj; - } - - public void setPxadj(double pxadj) - { - _pxadj = pxadj; - } - - public void setEfc(double efc) - { - _efc = efc; - } - - public double getEfc() - { - return _efc; - } - - - - -} //end SacSmaParameters diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaRainfallRunoffModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaRainfallRunoffModel.java deleted file mode 100644 index b95b86dab3..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaRainfallRunoffModel.java +++ /dev/null @@ -1,1170 +0,0 @@ -package ohd.hseb.model.sacsma; - - -import java.text.*; -//import java.io.*; - -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; - - -/** - * - * - * @author Chip Gobs - * @version 0.5 - */ -public class SacSmaRainfallRunoffModel implements RainfallRunoffModel -{ - private static final int _millisPerHour = 60 * 60 * 1000; - private SacSmaParameters _params; - private SacSmaState _state; - - private boolean _useStaticMape = false; - private MonthlyValues _monthlyMapeAdjustmentValues = null; - - private RegularTimeSeriesHolder _potentialEvapTimeSeriesHolder = null; - - private MonthlyValues _monthlyMapeValues = null; - - private double _peAdjust = 1.0; - private double _pxAdjust = 1.0; - - - // calculated, during the initial setting of params from SacSmaParameters to - // this object's variables - //private double _saved = 0.0; - // private double _parea = 0.0; - - - //private double[] _fgco = new double[6]; //unused - private double[] _rsum = new double[7]; - - // private double _ppe = 0.0; - //private double _psc = 0.0; -// private double _pta = 0.0; -// private double _pwe = 0.0; - - // common block sums - private double _srot = 0.0; - private double _simpvt = 0.0; - private double _srodt = 0.0; - private double _srost = 0.0; - private double _sintft = 0.0; - private double _sgwfp = 0.0; - private double _sgwfs = 0.0; - private double _srecht = 0.0; - private double _sett = 0.0; - - private double _se1 = 0.0; -// private double _se2 = 0.0; - private double _se3 = 0.0; - private double _se4 = 0.0; - private double _se5 = 0.0; - - - - //variables that are initialized in the main section of code - //that I need to pass to the doIncrements section - - private double _dlzp = 0.0; - private double _dlzs = 0.0; - private double _duz = 0.0; - - private double _sbf = 0.0; - private double _ssur = 0.0; - private double _sif = 0.0; - private double _sperc = 0.0; - private double _sdro = 0.0; - private double _spbf = 0.0; - - private double _pinc = 0.0; - - - //variables that could have been local, but belong to the - // object so that results of the operation can be verified - private double _bfp = 0.0; - private double _bfs = 0.0; - private double _roimp = 0.0; - private double _tci = 0.0; - - //private PrintWriter _runoffWriter = null; - //private PrintWriter _internalsWriter = null; - - private MeasuringUnit _precipUnit = MeasuringUnit.mm; - private MeasuringUnit _runoffUnit = MeasuringUnit.mm; - - -//-------------------------------------------------------------------------- - /** - * Constructor for objects of class SacSmaModel - */ - public SacSmaRainfallRunoffModel(SacSmaState state, - SacSmaParameters params, - double peAdjust, - double pxAdjust, - boolean useStaticMape, - MonthlyValues monthlyValues, - RegularTimeSeriesHolder potentialEvapTimeSeriesHolder) - { - - // _basinId = params.getBasinId(); - // _paramsSource = params.getSource(); - // _stateSource = state.getSource(); - - // says whether using MAPE time series or static monthly MAPE values - _useStaticMape = useStaticMape; - - if (_useStaticMape) - { - _monthlyMapeValues = monthlyValues; - } - else - { - _monthlyMapeAdjustmentValues = monthlyValues; - } - - // can be null - _potentialEvapTimeSeriesHolder = potentialEvapTimeSeriesHolder; - - setParameters(params); - - setState(state); - - _peAdjust = peAdjust; - _pxAdjust = pxAdjust; - - } -// -------------------------------------------------------------------------- - - private static String getStateString(SacSmaState state) - { - String formatString = "#####.#####"; - NumberFormat format = new DecimalFormat(formatString); - - String string = " uztwc = " + format.format(state.getUztwc()) + - " uzfwc = " + format.format(state.getUzfwc()) + - " lztwc = " + format.format(state.getLztwc()) + "\n" + - " lzfsc = " + format.format(state.getLzfsc()) + - " lzfpc = " + format.format(state.getLzfpc()) + - " adimc = " + format.format(state.getAdimc()) + "\n"; - - - //" rsum = " + state.getRsumString() + "\n"; - - - return string; - } //end getStateString - - -// -------------------------------------------------------------------------- - - public RegularTimeSeries calculateRunoff( long startTime, - long endTime, - RegularTimeSeries precipTimeSeries) - - - { - - String header = "SacSmaModel.calculateRunoff(): "; - - - final double hoursPerDay = 24; - int hoursPerInterval = 1; - - // the time series start time is one hour after the startTime, - // which represents the last saved model state time - long tsStartTime = startTime + (hoursPerInterval * _millisPerHour); - - - double intervalPortionOfDay = hoursPerInterval/hoursPerDay; - - RegularTimeSeries runoffTimeSeries = - new RegularTimeSeries(tsStartTime, endTime, 1, _runoffUnit); - - - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - String formatString = "#####.#####"; - NumberFormat formatter = new DecimalFormat(formatString); - - // System.out.println("Java version of SacSma:"); - - - //setupTestLogFiles(); - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(getState()) + - getParameters().toString(); - - //System.out.println(internalsMessage); - - // _internalsWriter.println(internalsMessage); - - - long millisPerHour = 60 * 60 * 1000; - - RegularTimeSeries potentialEvapTimeSeries = _potentialEvapTimeSeriesHolder.getTimeSeries(); - - - int hoursCount = Math.min(precipTimeSeries.getMeasurementCount(), - potentialEvapTimeSeries.getMeasurementCount()); - - - //for each piece of input data - - //fill in the time series out to the length of the model run - precipTimeSeries.stretchTimeSeries(tsStartTime, endTime, 0.0); - - - if (! _useStaticMape) //using time series - { - potentialEvapTimeSeries.stretchTimeSeries(tsStartTime, endTime, 0.0); - } - - - // at the start of the calculation, reset the basis time for the state - _state.setBasisTime(System.currentTimeMillis()); - - - for (long time = tsStartTime; time <= endTime; time += millisPerHour) - { - Measurement precipMeasurement = precipTimeSeries.getMeasurementByTime(time); - - if ((precipMeasurement != null) && (! precipMeasurement.isMissing())) - { - precipMeasurement = precipMeasurement.getCopy(_precipUnit); - - precipAmount = precipMeasurement.getValue(); - - if (precipAmount < 0.0) - { - precipAmount = 0.0; - } - else - { - precipAmount *= _pxAdjust; - } - } - else - { - precipAmount = 0.0; - } - - - if (_useStaticMape) - { - double dailyEvaporationAmount = _monthlyMapeValues.getValue(time); - evaporationAmount = dailyEvaporationAmount * intervalPortionOfDay; - - evaporationAmount *= _peAdjust; - - } - else //using time series - { - Measurement evapMeasurement = potentialEvapTimeSeries.getMeasurementByTime(time); - - if (evapMeasurement != null) - { - evapMeasurement = evapMeasurement.getCopy(_precipUnit); - evaporationAmount = evapMeasurement.getValue(); - - double adjustmentFactor = _monthlyMapeAdjustmentValues.getValue(time); - evaporationAmount *= adjustmentFactor; - - evaporationAmount *= _peAdjust; - } - else //evapMeasurement == null - { - evaporationAmount = 0.0; - } - } - - - double totalChannelInflow = - calculate(intervalPortionOfDay, - precipAmount, - evaporationAmount); - - // reset the valid time - _state.setValidTime(time); - - - - /* - System.out.println(header + "runoff = " + totalChannelInflow + - " precip = " + precipAmount + - " poten. evap = " + evaporationAmount); - */ - - Measurement totalChannelInflowMeasurement = - new Measurement(totalChannelInflow, _runoffUnit); - - runoffTimeSeries.setMeasurementByTime(totalChannelInflowMeasurement, time); - - } - return runoffTimeSeries; - } -// -------------------------------------------------------------------------- - - private void setParameters(SacSmaParameters params) - { - - _params = new SacSmaParameters(params); - - //_uztwm = params.getUztwm(); - //_uzfwm = params.getUzfwm(); - //_uzk = params.getUzk(); - - //_pctim = params.getPctim(); - //_adimp = params.getAdimp(); - //_riva = params.getRiva(); - //_zperc = params.getZperc(); - //_rexp = params.getRexp(); - //_lztwm = params.getLztwm(); - //_lzfsm = params.getLzfsm(); - //_lzfpm = params.getLzfpm(); - //_lzsk = params.getLzsk(); - //_lzpk = params.getLzpk(); - - //_pfree = params.getPfree(); - //_rserv = params.getRserv(); - //_side = params.getSide(); - - - } //end setParameters - -// -------------------------------------------------------------------------- - - - public SacSmaParameters getParameters() - { - SacSmaParameters params = new SacSmaParameters(); - - - /* - - params.setBasinId(_basinId); - params.setSource(_stateSource); - - - params.setUztwm( _uztwm ); - params.setUzfwm( _uzfwm ); - params.setUzk( _uzk ); - - params.setPctim(_pctim ); - params.setAdimp( _adimp ); - params.setRiva(_riva ); - params.setZperc(_zperc ); - params.setRexp(_rexp ); - params.setLztwm(_lztwm ); - params.setLzfsm(_lzfsm ); - params.setLzfpm(_lzfpm ); - params.setLzsk(_lzsk ); - params.setLzpk(_lzpk ); - - params.setPfree( _pfree ); - params.setSide(_side ); - - params.setRserv(_rserv); - */ - - params = new SacSmaParameters(_params); - - return params; - - } //end getParameters - -// -------------------------------------------------------------------------- - - public void setState(SacSmaState state) - { - - _state = new SacSmaState(state); - - //_uztwc = state.getUztwc(); - //_uzfwc = state.getUzfwc(); - - //_lztwc = state.getLztwc(); - - //_lzfsc = state.getLzfsc(); - //_lzfpc = state.getLzfpc(); - - //_adimc = state.getAdimc(); - - //private double[] _fgco = new double[6]; - // _rsum = new double[ state.getRsum().length ]; - // for (int i = 0; i < state.getRsum().length; i++) - // { - // _rsum[i] = state.getRsum()[i]; - // } - - - // _ppe = state.getPpe(); -// _psc = state.getPsc(); -// _pta = state.getPta(); -// _pwe = state.getPwe(); - - } - -//-------------------------------------------- - public SacSmaState getState() - { - SacSmaState state = new SacSmaState(_state); - - - //private double[] _fgco = new double[6]; - //double[] localRsum = new double[_rsum.length]; - //for (int i = 0; i < _rsum.length; i++) - //{ - // localRsum[i] = _rsum[i]; - //} - //state.setRsum(localRsum); - - - // _ppe = state.getPpe(); - //state.setPsc(_psc ); - //state.setPta(_pta ); - //state.setPwe(_pwe ); - - return state; - } - -// -------------------------------------------------------------------------- - - public double getSaved() - { //calculated parameter - // - return (_params.getRserv() * (_params.getLzfpm() + _params.getLzfsm())); - //return _saved; - } - - //public void setParea(double parea) { - // this._parea = parea; - //} - -// -------------------------------------------------------------------------- - - - public double getParea() - { //calculated parameter - return (1.0 - _params.getPctim() - _params.getAdimp()); - //return _parea; - } -//-------------------------------------------- - /** - * calculate() - * - * @param timeInterval a sample parameter for a method - * @return void - */ - - /* - * Translation Notes: - * dt = timeInterval in fraction of a day (for example, 1 hour = 1/24.0) - * pxv = ranfallPlusMelt - * ep = evaporation - * tci = totalChannelInflowMinusRunoffDepth - */ - - public double calculate(double dt /*dt */, - double rainfallPlusMelt /*pxv */, - double evaporation /* ep*/) - { - double evapTransDemand = evaporation; - - double e1; - double e2; - double e3; - - double residualEvapTransDemand = 0.0; - - //later put this in the object itself - boolean useFrozenGroundCalcs = false; - - - // old code does this: - //evapTransDemand = evaporation * evaporationDistribution(Kint) - - // compute et from upper zone - - e1 = evapTransDemand * (_state.getUztwc() / _params.getUztwm() ); - - residualEvapTransDemand = evapTransDemand - e1; - - //subtract off e1 - _state.setUztwc(_state.getUztwc() - e1); - - // introduce e2 - e2 = 0.0; - - boolean perform220Check = false; - - if (_state.getUztwc() < 0.0) - { - e1 += _state.getUztwc(); - _state.setUztwc(0.0); - residualEvapTransDemand = evapTransDemand - e1; - - if (_state.getUzfwc() < residualEvapTransDemand) - { - //e2 is evap from UZFWC - e2 = _state.getUzfwc(); - //trace("setting _uzfwc to 0.0"); - _state.setUzfwc(0.0); - - residualEvapTransDemand -= e2; - perform220Check = false; //simulates goto 225 - } - else //_state.getUzfwc() >= residualEvapTransDemand //simulates 221 - { - //trace("221"); - e2 = residualEvapTransDemand; - - _state.setUzfwc(_state.getUzfwc() - e2); - - //trace("near 221, _uzfwc = " + _uzfwc); - residualEvapTransDemand = 0.0; - - perform220Check = true; - } - - } - else //(state.getUztwc() >= 0.0) //simulates goto 220 - { - perform220Check = true; - } - - - if (perform220Check) - { - //trace("220"); - if (( _state.getUztwc() / _params.getUztwm() ) < (_state.getUzfwc() / _params.getUzfwm())) - { - // upper zone free water ratio exceeds upper zone tension - // water ratio, this transfer free water to tension - - double uzrat = ( (_state.getUztwc() + _state.getUzfwc()) / ( _params.getUztwm() + _params.getUzfwm()) ); - - _state.setUztwc(( _params.getUztwm() * uzrat)); - - _state.setUzfwc((_params.getUzfwm() * uzrat)); - //trace("near 220, _uzfwc = " + _uzfwc); - } - } - - // line 225 equiv - //trace("225"); - if (_state.getUztwc() < 0.00001) - { - _state.setUztwc(0.0); - } - - if ( _state.getUzfwc() < 0.00001) - { - - _state.setUzfwc(0.0); - //trace("near 225, _uzfwc set to 0.0"); - } - - // compute et from the lower zone - // compute et from LZTWC (E3) - - e3 = residualEvapTransDemand * (_state.getLztwc() / - ( _params.getUztwm() + - _params.getLztwm()) ); - - _state.setLztwc(_state.getLztwc() - e3); - - if (_state.getLztwc() < 0.0 ) //simulates the goto 226 stuff - { - // e3 cannot exceed lztwc - e3 += _state.getLztwc(); - - _state.setLztwc(0.0); - } - - //trace("226"); - - //simulates line 226 - double ratlzt = _state.getLztwc() / _params.getLztwm(); - double ratlz = (_state.getLztwc() + _state.getLzfpc() + _state.getLzfsc() - getSaved()) / - (_params.getLztwm() + _params.getLzfpm() + _params.getLzfsm() - getSaved()); - - if (ratlzt < ratlz) - { - // resupply lower zone tension water from lower - // zone free water if more water available there - - double del = (ratlz -ratlzt) * _params.getLztwm(); - - // transfer from lzfwc to lztwc - - - _state.setLztwc(_state.getLztwc() + del); - _state.setLzfsc(_state.getLzfsc() - del); - - - if (_state.getLzfsc() < 0.0) - { - //if transfer exceeds lzfsc then remainder - // comes from lzfpc - _state.setLzfpc(_state.getLzfpc() + _state.getLzfsc()); - _state.setLzfsc(0.0); - } - } - - - //line 230 stuff - //trace("230"); - if (_state.getLztwc() < 0.00001) - { - _state.setLztwc(0.0); - } - - // compute et from _adimp area - e5 - double e5 = e1 + (residualEvapTransDemand + e2) * - ((_state.getAdimc() -e1 - _state.getUztwc())/(_params.getUztwm() + _params.getLztwm())); - - //adjust adminc, additional impervious area storage, for evaporation - - - _state.setAdimc(_state.getAdimc() - e5); - - if (_state.getAdimc() < 0.0) - { - // e5 cannot exceed adminc - e5 += _state.getAdimc(); - - _state.setAdimc(0.0); - } - - //simulates line 231 - //trace("231"); - e5 *= _params.getAdimp(); - // e5 is et from the area _adimp - - //-------------------------- - // compute percolation and runoff amounts - - double twx = rainfallPlusMelt + _state.getUztwc() - _params.getUztwm(); - // twx is the time interval available moisture in excess of - // uztw requirements - - if (twx < 0.0) - { - //all moisture held in uztw - no excess - _state.setUztwc(_state.getUztwc() + rainfallPlusMelt); - twx = 0.0; - - } - else //(twc >= 0.0) //simulates line 232 - { - _state.setUztwc(_params.getUztwm()); - } - - //line 233 - //trace("233"); - - _state.setAdimc(_state.getAdimc() + ( rainfallPlusMelt - twx) ); - - //compute impervious area runoff - _roimp = rainfallPlusMelt * _params.getPctim(); - // roimp is runoff from the minimum impervious area - - _simpvt += _roimp; - - //initialize time interval sums - - _sbf = 0.0; - _ssur = 0.0; - _sif = 0.0; - _sperc = 0.0; - _sdro = 0.0; - _spbf = 0.0; - - //determine computational time increments for the basic time interval - - //make sure that the rounding here is done the same way that fortran does - // it - //incrementCount = ninc - long ninc = (long) Math.floor(1.0 + (0.2 * ( _state.getUzfwc() + twx))); - - //ninc = number of time increments that the time interval is - // is divided into for further soil-moisture accounting. no one increment - // will exceed 5.0 mm of uzfwc + pav - - //dinc = incrementLength - double dinc = (1.0 / ninc) * dt; - - //trace("dinc RESULT = " + dinc + "with inputs:"); - //trace("ninc = " + ninc); - //trace("timeInterval = " + dt); - //trace("END dinc block"); - - - // dinc = length of each increment in days - - - //_pinc = _moisturePerIncrement - _pinc = twx / ninc; - // moisturePerIncrement = amount of available moisture per increment - // compute free water depletion fractions for the time increment being use - // basic depletions are for one day - - _duz = 1.0 - Math.pow((1.0 - _params.getUzk()), dinc); - _dlzp = 1.0 - Math.pow((1.0 - _params.getLzpk()), dinc); - _dlzs = 1.0 - Math.pow((1.0 - _params.getLzsk()), dinc); - - //trace("_dlzp result = " + _dlzp + " with inputs"); - //trace("_lzpk = " + _lzpk); - //trace("dinc = " + dinc); - - //trace("_dlzs result = " + _dlzs + " with inputs"); - //trace("_lzsk = " + _lzsk); - //trace("dinc = " + dinc); - - - // start incremental do loop for the time interval - - for (int i = 0; i < ninc; i++) - { - //trace("doIncrements loop, iteration # " + i); - doIncrements(); - } - - - //compute sums and adjust runoff amounts by the area over - // which they are generated - - double eUsed = e1 + e2 + e3; - //eUsed is the et from pArea which is 1.0-_adimp-pctim - _sif *= getParea(); - - //separate channel component of baseflow - //from the non-channel component - - double tbf = _sbf * getParea(); - //tbf is toal baseflow - - double bfcc = tbf * (1.0/ (1.0 + _params.getSide()) ); - //bfcc is baseflow, channel component - - _bfp= _spbf* getParea()/(1.0 + _params.getSide()); - - // error #2, had _bfs = bfcc = bfp; - _bfs = bfcc - _bfp; - - if (_bfs < 0.0) - { - _bfs = 0.0; - } - - double bfncc = tbf - bfcc; - // bfncc is baseflow, non-channel component - - //add to monthly sums - _sintft += _sif; - _sgwfp += _bfp; - _sgwfs += _bfs; - _srecht += bfncc; - _srost += _ssur; - _srodt += _sdro; - - //compute total channel inflow for the time interval - _tci = _roimp + _sdro + _ssur +_sif + bfcc; - - //compute e4-et from riparian vegetarian - double e4 = (evapTransDemand - eUsed) * _params.getRiva(); - - //subtract e4 from channel inflow - _tci = _tci - e4; - - if (_tci < 0.0) - { - e4 += _tci; - _tci = 0.0; - } - - //trace("250"); - _srot += _tci; - - //compute total evapotranspiration - tet - eUsed *= getParea(); - double tet = eUsed + e5 + e4; - - _sett += tet; - - _se1 += e1* getParea(); - _se3 += e3 * getParea(); - - _se4 += e4; - _se5 += e5; - - //check that adimc is >= uztwc - if ( _state.getAdimc() < _state.getUztwc()) - { - _state.setAdimc( _state.getUztwc()); - } - - // add to sums of runoff components - _rsum[0] += _tci; - _rsum[1] += _roimp; - _rsum[2] += _sdro; - _rsum[3] += _ssur; - _rsum[4] += _sif; - _rsum[5] += _bfs; - _rsum[6] += _bfp; - - return _tci; - } //end calculate - - //--------------------------------------------------------------------- - - private void doIncrements() - { - //put in lines from pages 2b to 3b - double adsur = 0.0; - - //compute direct runoff (from _adimp area) - double ratio = ( _state.getAdimc() - _state.getUztwc()) / _params.getLztwm(); - - if (ratio < 0.0) - { - ratio = 0.0; - } - - double addro = _pinc * Math.pow(ratio, 2); - //addro is the amount of direct runoff from the area _adimp - - //compute baseflow and keep track of time interval sum - - double bf = _state.getLzfpc() * _dlzp; - - _state.setLzfpc( _state.getLzfpc() - bf); - - - if ( _state.getLzfpc() <= 0.0001) - { - bf += _state.getLzfpc(); - _state.setLzfpc(0.0); - } - - //simulates line 234 - //trace("234"); - _sbf += bf; - _spbf += bf; - bf = _state.getLzfsc() * _dlzs; - - - _state.setLzfsc(_state.getLzfsc()- bf); - if (_state.getLzfsc() <= 0.0001) - { - bf += _state.getLzfsc(); - _state.setLzfsc(0.0); - } - - //line 235 - //trace("235"); - _sbf += bf; - - //computer percolation - if no water available then skip - - if ((_pinc + _state.getUzfwc()) <= 0.01) - { - - _state.setUzfwc( _state.getUzfwc() + _pinc); - //trace("near 235, _uzfwc = " + _uzfwc); - - //skip most of the rest//need to goto 249 - } - else //water available line // 251 equiv - { - //trace("251"); - double percm = (_params.getLzfpm() * _dlzp) + (_params.getLzfsm()* _dlzs); - double perc = percm * ( _state.getUzfwc() / _params.getUzfwm()); - - //trace("result percm = " + percm + " with inputs :"); - //trace("_lzfpm = " + _lzfpm); - //trace("dlzp = " + _dlzp); - //trace("_lzfsm = " + _lzfsm); - //trace("_dlzs = " + _dlzs); - - //trace("result perc = " + perc + " with inputs:" ); - //trace("percm = " + percm); - //trace("_uzfwc = " + _uzfwc); - //trace("_uzfwm = " + _uzfwm); - - - - double defr = 1.0 - ( (_state.getLztwc() + _state.getLzfpc() + _state.getLzfsc()) / (_params.getLztwm() + _params.getLzfpm() + _params.getLzfsm()) ); - //trace ("near 251 defr = " + defr); - - //trace ("_lztwc = " + _lztwc); - //trace ("_lzfpc = " + _lzfpc); - //trace ("_lzfsc = " + _lzfsc); - //trace ("_lztwm = " + _lztwm); - //trace ("_lzfpm = " + _lzfpm); - //trace ("_lzfsm = " + _lzfsm); - //trace ("end of 251 defr block"); - - - //defr is the lower zone moisture deficiency ratio - - double fr = 1.0; - //fr is the change in percolation withdrawal due to frozen ground - - double fi = 1.0; - // fi is the change in interflow withdrawal due to frozen ground - - //if (useFrozenGroundCalc) - //{ - // _uzdefr = 1.0 - ((_uztwc+_uzfwc) / (_uztwm + _uzfwm )); - // frozenGround(); - //} - - //error # 3 - //trace("input perc = " + perc ); - perc = perc * (1.0 + (_params.getZperc() * Math.pow(defr, _params.getRexp()))) * fr; - //trace("before 241, result perc = " + perc); - //trace("_zperc = " + _zperc); - //trace("defr = " + defr); - //trace("_rexp = " + _rexp); - //trace("fr = " + fr); - //trace("end perc print block"); - - - //Note: percolation occurs from uzfwc before pav is added - if (perc >= _state.getUzfwc()) - { - //percolation rate exceeds uzfwc - - perc = _state.getUzfwc(); - } - - //trace("241"); - //error #4 - found 6/30/03 - - - _state.setUzfwc(_state.getUzfwc() - perc); - //trace("near 241, _uzfwc = " + _uzfwc); - - // check to see if percolation exceeds lower zone deficiency - - double check = _state.getLztwc() + _state.getLzfpc() + _state.getLzfsc() + perc - _params.getLztwm() - _params.getLzfpm() -_params.getLzfsm(); - if (check > 0.0) - { - perc -= check; - - _state.setUzfwc(_state.getUzfwc() + check); - //trace("near 241, part 2, _uzfwc = " + _uzfwc); - - } - - //trace("242"); - _sperc += perc; - //sperc is the time interval summation of perc - - //compute interflow and keep track of time interval sum - // note: moisturePerIncrement has not yet been added - - double del = _state.getUzfwc() * _duz * fi; - _sif += del; - - //trace("near 242, _uzfwc = " + _uzfwc); - _state.setUzfwc(_state.getUzfwc() - del); - - //distribute percolated water into the lower zones - //tension water must be filled first except for the pfree area - //perct is percolation to tension water and perfc is percolation - //going to free water - double percf = 0.0; - - double perct = perc * (1.0 - _params.getPfree()); - if ((perct + _state.getLztwc()) <= _params.getLztwm()) - { - _state.setLztwc(_state.getLztwc() + perct); - percf = 0.0; - } - else // (perct + _lztwc) > _lztwm) // simulates line 234 - { - //trace("234"); - percf = perct + _state.getLztwc() - _params.getLztwm(); - - _state.setLztwc(_params.getLztwm()); - } - - //distribute percolation in excess tension requirements - //among the free water storages - - - //line 244 equiv - //trace("244"); - percf += (perc * _params.getPfree()); - - if (percf != 0.0) // may have problem with exact equivalence - { - double hpl = _params.getLzfpm() / (_params.getLzfpm() + _params.getLzfsm()); - //hpl is the relative size of the primary storage - //as compared with toal lower zone free water storage - - double ratlp = _state.getLzfpc() / _params.getLzfpm(); - double ratls = _state.getLzfsc() / _params.getLzfsm(); - //ratlp and ratls are content to capacity rations, or - //in other words, the realtive fullness of each storage - - double fracp = (hpl*2.0 * (1.0 - ratlp)) / - (( 1.0 - ratlp) + (1.0 - ratls)); - - //fracp is the fraction going to primary - if (fracp > 1.0) - { - fracp = 1.0; - } - - double percp = percf * fracp; - double percs = percf - percp; - - //percp and percs are the amount of the excess - //percolation going to primary and supplemental - //storages, respectively - - _state.setLzfsc(_state.getLzfsc() + percs); - - if (_state.getLzfsc() > _params.getLzfsm()) - { - percs = percs - _state.getLzfsc() + _params.getLzfsm(); - _state.setLzfsc(_params.getLzfsm()); - } - - - //line 246 equiv - //trace("246"); - - _state.setLzfpc( _state.getLzfpc() + (percf-percs)); - - //check to make sure _lzfpc does not exceed _lzfpm - - if (_state.getLzfpc() > _params.getLzfpm()) - { - double excess = _state.getLzfpc() - _params.getLzfpm(); - - _state.setLztwc(_state.getLztwc() + excess); - - _state.setLzfpc(_params.getLzfpm()); - - } - } - - //line 245 equiv - //trace("245"); - //distribute moisturePerIncrement between _uzfwc and surface runoff - if (_pinc != 0.0) - { - //check if moisturePerIncrement exceeds _uzfwm - - if ((_pinc + _state.getUzfwc()) <= _params.getUzfwm()) - { - //no surface runoff - _state.setUzfwc(_state.getUzfwc() + _pinc); - //trace("near 245, _uzfwc = " + _uzfwc); - //simulate goto 249 - it will flow through correctly as is - } - else - { - //simulate line 248 - //trace("248"); - //compute surface runoff (sur) and keep track of time - // interval sum - double sur = _pinc + _state.getUzfwc() - _params.getUzfwm(); - - - _state.setUzfwc(_params.getUzfwm()); - //trace("near 248, _uzfwc = " + _uzfwc); - - _ssur += (sur* getParea()); - adsur = sur*(1.0 - (addro/_pinc) ); - //adsur is the amount of surface runoff which comes - //from that portion of _adimp which is not - //currently generating direct runoff. addro/moisturePerIncrement - // is the fraction of _adimp currently generating - // direct runoff - - _ssur += (adsur*_params.getAdimp()); - - - } - } - } - - //line 249 equiv - //trace("249"); - - _state.setAdimc(_state.getAdimc() + ((_pinc) - addro) - adsur ); - if (_state.getAdimc() > _params.getUztwm() + _params.getLztwm()) - { - addro += (_state.getAdimc()) - (_params.getUztwm() + _params.getLztwm()); - - _state.setAdimc(_params.getUztwm() + _params.getLztwm()); - - } - - //trace("247"); - _sdro += (addro*_params.getAdimp()); - if (_state.getAdimc() < 0.00001) - { - _state.setAdimc(0.0); - } - - - } //end doIncrements - - // -------------------------------------------------------------------------- - - - public String toString() - { - String stateString = getState().toString(); - String paramString = getParameters().toString(); - String modelString = stateString + " " + paramString; - - return modelString; - } - - // -------------------------------------------------------------------------- - - -/* - public void setupTestLogFiles() - { - try - { - _runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - _internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - } -*/ - // -------------------------------------------------------------------------- - - - public RainfallRunoffModelType getModelType() - { - return RainfallRunoffModelType.SAC_SMA; - } - - // -------------------------------------------------------------------------- - -} //end class SacSmaModel diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaState.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaState.java deleted file mode 100644 index c8420cd23d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaState.java +++ /dev/null @@ -1,346 +0,0 @@ - -/** - * Write a description of class SacSmaState here. - * - * @author Chip Gobs - * @version 6/20/03 - */ -package ohd.hseb.model.sacsma; -import java.text.*; - -import ohd.hseb.db.DbTimeHelper; - -public class SacSmaState -{ - private String _basinId = null; - private String _source = null; - private long _validTime = 0; - private long _basisTime = 0; - private long _postingTime = 0; - - - private double _uztwc = 0.0; - private double _uzfwc = 0.0; - private double _lztwc = 0.0; - private double _lzfsc = 0.0; - private double _lzfpc = 0.0; - private double _adimc = 0.0; - - //private double[] _fgco = new double[6]; - //private double[] _rsum = new double[7]; - - //private double _ppe = 0.0; - //private double _psc = 0.0; - //private double _pta = 0.0; - //private double _pwe = 0.0; - - /** - * Constructor for objects of class SacSmaState - */ - public SacSmaState() - { - - } - - public SacSmaState(SacSmaState state) - { - - setBasinId(state.getBasinId()); - setSource(state.getSource()); - setValidTime(state.getValidTime()); - setBasisTime(state.getBasisTime()); - setPostingTime(state.getPostingTime()); - - - setUztwc(state.getUztwc()); - setUzfwc(state.getUzfwc()); - setLztwc(state.getLztwc()); - setLzfsc(state.getLzfsc()); - setLzfpc(state.getLzfpc()); - setAdimc(state.getAdimc()); - - return; - - } - - public SacSmaState(double[] stateArray) - { - int i = 0; - - setUztwc(stateArray[i++]); - setUzfwc(stateArray[i++]); - setLztwc(stateArray[i++]); - setLzfsc(stateArray[i++]); - setLzfpc(stateArray[i++]); - setAdimc(stateArray[i++]); - - //consider setting - //fpcoArray - //rsumArray - - //setPpe(stateArray[i++]); - //setPsc(stateArray[i++]); - //setPta(stateArray[i++]); - //setPwe(stateArray[i++]); - - - - } - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat format = new DecimalFormat(formatString); - - - - - String string = "Basin Id = " + _basinId + - " data source = " + _source + - " valid time = " + DbTimeHelper.getDateTimeStringFromLongTime(_validTime) + - " basis time = " + DbTimeHelper.getDateTimeStringFromLongTime(_basisTime) + - " posting time = " + DbTimeHelper.getDateTimeStringFromLongTime(_postingTime) + - "\n" + - " uztwc = " + format.format(_uztwc) + - " uzfwc = " + format.format(_uzfwc) + - " lztwc = " + format.format(_lztwc) + - " lzfsc = " + format.format(_lzfsc) + - " lzfpc = " + format.format(_lzfpc) + - " adimc = " + format.format(_adimc); - //" rsum = " + getRsumString() + "\n"; - - //"ppe = " + _ppe + "\n" + - //"pse = " + _psc + - //"pta = " + _pta + - //"pwe = " + _pwe + "\n"; - - return string; - } - - public void setBasinId(String basinId) - { - _basinId = basinId; - } - - public String getBasinId() - { - return _basinId; - } - - public void setSource(String source) - { - _source = source; - } - - public String getSource() - { - return _source; - } - - public void setValidTime(long validTime) - { - _validTime = validTime; - } - - public long getValidTime() - { - return _validTime; - } - - public void setBasisTime(long basisTime) - { - _basisTime = basisTime; - } - - public long getBasisTime() - { - return _basisTime; - } - - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - - public long getPostingTime() - { - return _postingTime; - } - - public boolean equals(SacSmaState state) - { - boolean result = false; - - - - if ( - (getBasinId().equalsIgnoreCase(state.getBasinId())) && - (getSource().equalsIgnoreCase(state.getSource())) && - (getValidTime() == state.getValidTime()) && - (getBasisTime() == state.getBasisTime()) && - (getPostingTime() == state.getPostingTime()) && - (getUztwc() == state.getUztwc()) && - (getUzfwc() == state.getUzfwc()) && - (getLztwc() == state.getLztwc()) && - (getLzfsc() == state.getLzfsc()) && - (getLzfpc() == state.getLzfpc()) && - (getAdimc() == state.getAdimc())) - { - result = true; - } - - return result; - } - - - - public boolean equalsValues(SacSmaState state) - { - boolean result = false; - - - - if ( - //(getBasinId().equalsIgnoreCase(state.getBasinId())) && - //(getSource().equalsIgnoreCase(state.getSource())) && - // (getValidTime() == state.getValidTime()) && - // (getBasisTime() == state.getBasisTime()) && - // (getPostingTime() == state.getPostingTime()) && - (getUztwc() == state.getUztwc()) && - (getUzfwc() == state.getUzfwc()) && - (getLztwc() == state.getLztwc()) && - (getLzfsc() == state.getLzfsc()) && - (getLzfpc() == state.getLzfpc()) && - (getAdimc() == state.getAdimc())) - { - result = true; - } - - return result; - } - - /* - public String getRsumString() - { - String formatString = "#####.###"; - NumberFormat format = new DecimalFormat(formatString); - - StringBuffer rsumStringBuffer = new StringBuffer(); - - for (int i = 0 ; i < _rsum.length; i++) - { - rsumStringBuffer.append(format.format(_rsum[i]) + " "); - } - - return rsumStringBuffer.toString(); - } - */ - - - public void setUztwc(double uztwc) { - this._uztwc = uztwc; - } - - public double getUztwc() - { - return _uztwc; - } - - public void setUzfwc(double uzfwc) { - this._uzfwc = uzfwc; - } - - public double getUzfwc() { - return _uzfwc; - } - - public void setLztwc(double lztwc) { - this._lztwc = lztwc; - } - - public double getLztwc() { - return _lztwc; - } - - public void setLzfsc(double lzfsc) { - this._lzfsc = lzfsc; - } - - public double getLzfsc() { - return _lzfsc; - } - - public void setLzfpc(double lzfpc) { - this._lzfpc = lzfpc; - } - - public double getLzfpc() { - return _lzfpc; - } - - public void setAdimc(double adimc) { - this._adimc = adimc; - } - - public double getAdimc() { - return _adimc; - } - -/* - public void setRsum(double[] rsum) - { - this._rsum = rsum; - } -*/ -/* - public double[] getRsum() - { - return _rsum; - } -*/ - /* - public void setPpe(double ppe) - { - this._ppe = ppe; - } - - - public double getPpe() - { - return _ppe; - } - - - public void setPwe(double pwe) - { - this._pwe = pwe; - } - - public double getPwe() - { - return _pwe; - } - - public void setPsc(double psc) - { - this._psc = psc; - } - - - public double getPsc() - { - return _psc; - } - - public void setPta(double _pta) { - this._pta = _pta; - } - - public double getPta() { - return _pta; - } -*/ - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaTest.java deleted file mode 100644 index 1abf6d44f3..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/model/sacsma/SacSmaTest.java +++ /dev/null @@ -1,885 +0,0 @@ -/* - * Created on Jun 23, 2003 - * - * - */ -package ohd.hseb.model.sacsma; -import java.util.*; -import java.io.*; -import java.text.*; - -import ohd.hseb.model.*; -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; - -/** - * @author Chip Gobs - * - * - */ -public class SacSmaTest -{ - - private static boolean _newTest = true; - - -//---------------------------------------------- - public static void main(String[] args) throws Exception - { - Logger logger = new FileLogger("D:/Data/code/SiteSpecific/output/SacSmaTiming.out"); - - logger.log("log this"); - - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - testModel(); - - timer.stop("Done with 1 iteration of testModel"); - - // testAll(); - - } //end main - - //--------------------------------------------------------------------------- - - //--------------------------------------------------------------------------- - - - //----------------------------------------------------------------------- - /* - * - * - * - - PXADJ = 1.000 - PEADJ = 1.000 - UZTWM = 60.000 - UZFWM = 25.000 - UZK = 0.350 - PCTIM = 0.000 - ADIMP = 0.000 - RIVA = 0.003 - ZPERC = 210.000 - REXP = 1.40 - LZTWM = 120.000 - LZFSM = 25.000 - LZFPM = 150.000 - LZSK = 0.080 - LZPK = 0.004 - PFREE = 0.250 - RSERV = 0.300 - SIDE = 0.000 - IOPTET=0 //we don't have this one, so ignore it - EFC = 0.50 - - - use these as the starting states (put them in the database) - - UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC - 31.02 0.009 31.94 0.060 74.74 62.04 - */ - - // ----------------------------------------------------------------------- - - public static void testModel() - { - - SacSmaParameters params = null; - SacSmaState state = null; - SacSmaRainfallRunoffModel model = null; - - RegularTimeSeriesHolder evapTimeSeriesHolder = new RegularTimeSeriesHolder(); - - int hoursPerInterval = 1; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - double[] precipArray = null; - double[] evaporationArray = null; - - String dataDir = null; - - try - { - - if (_newTest) //test against data provided by Mike Smith - { - - dataDir = "D:/Data/code/SiteSpecific/input/States_params/"; - - params = getTestParams(); - state = getTestState(); - - - precipArray = readPrecipArray(dataDir + "precip.in.txt"); - evaporationArray = readEvapArray(dataDir + "et_demand.txt"); - //evaporationArray = readEvapArray(dataDir + "actual_et.txt"); - } - else //test against the data provided by LMRFC - { - dataDir = "D:/Data/code/exampleCode/sacsma/"; - double[] parameterArray = readParameterArray(dataDir + "parmsandco"); - double[] stateArray = readStateArray(dataDir + "parmsandco"); - - params = new SacSmaParameters(parameterArray); - state = new SacSmaState(stateArray); - - precipArray = readPrecipArray(dataDir + "rainfile"); - evaporationArray = readEvapArray(dataDir + "evapfile"); - } - - - RegularTimeSeries evapTimeSeries = getEvapTimeSeries(evaporationArray); - evapTimeSeriesHolder.setTimeSeries(evapTimeSeries); - - boolean useMapeTimeSeries = true; - - double[] values = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; - MonthlyValues mapeAdjustmentValues = new MonthlyValues(values); - - double peAdjust = 1.0; - double pxAdjust = 1.0; - - model = new SacSmaRainfallRunoffModel(state, - params, - peAdjust, - pxAdjust, - useMapeTimeSeries, - mapeAdjustmentValues, - evapTimeSeriesHolder); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - int length = Math.min(precipArray.length, evaporationArray.length); - - String formatString = "#####.000"; - NumberFormat formatter = new DecimalFormat(formatString); - - System.out.println("Java version of SacSma:"); - - PrintWriter runoffWriter = null; - PrintWriter internalsWriter = null; - - try - { - runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(model.getState()) + - model.getParameters().toString(); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - internalsWriter.println("DAY HR UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC RAIN+MELT ACT-ET TOT-RO "); - - - int day = 1; - int hour = 1; - - //for each piece of input data - for (int i = 0 ; i < length; i++) - { - - precipAmount = precipArray[i]; - evaporationAmount = evaporationArray[i]; - - double totalChannelInflow = - model.calculate(hoursPerInterval/ 24.0, - precipAmount, - evaporationAmount); - - - if (_newTest ) - { - - runoffMessage = "day = " + day + - " hour = " + hour + - " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + formatter.format(totalChannelInflow); - } - else //old test with LMRFC's data - { - runoffMessage = "i = " + i + - " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + formatter.format(totalChannelInflow); - } - - - - System.out.println(runoffMessage); - runoffWriter.println(runoffMessage); - //System.out.println(model); - - - - internalsMessage = day + " " + hour + - " " + getStateString(model.getState()) + " " + - precipAmount + " " + - evaporationAmount + " " + - formatter.format(totalChannelInflow); - - // System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - hour++; - if (hour > 24) - { - hour = 1; - day++; - } - - - } //end for - - runoffWriter.close(); - internalsWriter.close(); - - } //end testModel - - - //----------------------------------------------------------------------- - private static SacSmaParameters getTestParams() - { - //uses sept93 data for ELDO2) - /* - PXADJ = 1.000 - PEADJ = 1.000 - UZTWM = 60.000 - UZFWM = 25.000 - UZK = 0.350 - PCTIM = 0.000 - ADIMP = 0.000 - RIVA = 0.003 - ZPERC = 210.000 - REXP = 1.40 - LZTWM = 120.000 - LZFSM = 25.000 - LZFPM = 150.000 - LZSK = 0.080 - LZPK = 0.004 - PFREE = 0.250 - RSERV = 0.300 - SIDE = 0.000 - IOPTET=0 //we don't have this one, so ignore it - EFC = 0.50 - */ - - SacSmaParameters params = new SacSmaParameters(); - - params.setPxadj(1.0); - params.setPeadj(1.0); - params.setUztwm(60.0); - params.setUzfwm(25.0); - params.setUzk(0.35); - params.setPctim(0.000); - params.setAdimp(0.000); - params.setRiva(0.003); - params.setZperc(210.000); - params.setRexp(1.40); - params.setLztwm(120.000); - params.setLzfsm(25.0); - params.setLzfpm(150.000); - params.setLzsk(0.080); - params.setLzpk(0.004); - params.setPfree(0.250); - params.setRserv(0.300); - params.setSide(0.000); - params.setEfc(.50); - - return params; - } - - // ----------------------------------------------------------------------- - private static SacSmaState getTestState() - { - /* - use these as the starting states (put them in the database) - - UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC - 31.02 0.009 31.94 0.060 74.74 62.04 - */ - /* - - Since the sac93_states test data does not explicitly give initial conditions, - I have reconstructed the initial conditions by using the 0+1 states and - using numeric analysis approximated the previous state (0) - - The xxxxxDiff variables show the approximate change in the state variables per iteration - for a particular - calibration when there is no precip (which is the case for the first 10 or so intervals). - - */ - - double uztwcDiff = -0.103; - double uzfwcDiff = 0; - double lztwcDiff = -0.02; - double lzfscDiff = -0.0002; - double lzfpcDiff = -0.0133; - double adimcDiff = -0.12; - - SacSmaState state = new SacSmaState(); - - // started with state 1, go back to the approximate state 0 - state.setUztwc(31.02 - uztwcDiff ); - state.setUzfwc(0.009 - uzfwcDiff ); - state.setLztwc(31.94 - lztwcDiff); - state.setLzfsc(0.060 - lzfscDiff); - state.setLzfpc(74.74 - lzfpcDiff ); - state.setAdimc(62.04 - adimcDiff); - - return state; - - } - // ----------------------------------------------------------------------- - public static void testAll() throws Exception - { - - double[] stateArray = null; - double[] parameterArray = null; - - SacSmaParameters params = null; - SacSmaState state = null; - SacSmaRainfallRunoffModel model = null; - - RegularTimeSeriesHolder evapTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - - int hoursPerInterval = 1; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - double[] precipArray = null; - double[] evaporationArray = null; - - UnitHydrograph ugh = UnitHydrograph.getTestUnitHydrograph(); - IrregularTimeSeries currentTimeSeries = null; - IrregularTimeSeries totalTimeSeries = - new IrregularTimeSeries(MeasuringUnit.cfs); - - - try - { - parameterArray = readParameterArray("D:/Data/exampleCode/sacsma/parmsandco"); - stateArray = readStateArray("D:/Data/exampleCode/sacsma/parmsandco"); - - params = new SacSmaParameters(parameterArray); - state = new SacSmaState(stateArray); - - - precipArray = readPrecipArray("D:/Data/exampleCode/sacsma/rainfile"); - evaporationArray = readEvapArray("D:/Data/exampleCode/sacsma/evapfile"); - - RegularTimeSeries evapTimeSeries = getEvapTimeSeries(evaporationArray); - evapTimeSeriesHolder.setTimeSeries(evapTimeSeries); - - - boolean useMapeTimeSeries = true; - - double[] values = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; - MonthlyValues mapeAdjustmentValues = new MonthlyValues(values); - - double peAdjust = 1.0; - double pxAdjust = 1.0; - - - model = new SacSmaRainfallRunoffModel(state, - params, - peAdjust, - pxAdjust, - useMapeTimeSeries, - mapeAdjustmentValues, - evapTimeSeriesHolder); - - } - catch (java.io.IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - int length = Math.min(precipArray.length, evaporationArray.length); - - String formatString = "#####.000"; - NumberFormat formatter = new DecimalFormat(formatString); - - System.out.println("Java version of SacSma:"); - - PrintWriter runoffWriter = null; - PrintWriter internalsWriter = null; - - try - { - runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(model.getState()) + - model.getParameters().toString(); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - long time = System.currentTimeMillis(); - - //for each piece of input data - for (int i = 0 ; i < length; i++) - { - - precipAmount = precipArray[i]; - evaporationAmount = evaporationArray[i]; - - double totalChannelInflow = - model.calculate(hoursPerInterval/ 24.0, - precipAmount, - evaporationAmount); - - - AbsTimeMeasurement runoff = new AbsTimeMeasurement(totalChannelInflow, time, MeasuringUnit.mm); - time += 60 *60 * 1000; //add an hour - currentTimeSeries = ugh.getFlowTimeSeries(runoff); - - totalTimeSeries = IrregularTimeSeries.add(totalTimeSeries, currentTimeSeries); - - runoffMessage = "i = " + i + " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + - formatter.format(totalChannelInflow); - - - - System.out.println(runoffMessage); - runoffWriter.println(runoffMessage); - //System.out.println(model); - - internalsMessage = getStateString(model.getState()); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - } //end for - - runoffWriter.close(); - internalsWriter.close(); - - } //end testAll - - - // ------------------------------------------------------------- - -// ------------------------------------------------------------- -/* - private static String getStateStringVerbose(SacSmaState state) - { - String formatString = "#####.000"; - NumberFormat format = new DecimalFormat(formatString); - - String string = " uztwc = " + format.format(state.getUztwc()) + - " uzfwc = " + format.format(state.getUzfwc()) + - " lztwc = " + format.format(state.getLztwc()) + "\n" + - " lzfsc = " + format.format(state.getLzfsc()) + - " lzfpc = " + format.format(state.getLzfpc()) + - " adimc = " + format.format(state.getAdimc()) + "\n"; - - - //" rsum = " + state.getRsumString() + "\n"; - - - return string; - } -*/ -// ---------------------------------------------- -private static String getStateString(SacSmaState state) -{ - -/* UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC */ - - String formatString = "###.000"; - NumberFormat format = new DecimalFormat(formatString); - - String string = format.format(state.getUztwc()) + - " " + format.format(state.getUzfwc()) + - " " + format.format(state.getLztwc()) + - " " + format.format(state.getLzfsc()) + - " " + format.format(state.getLzfpc()) + - " " + format.format(state.getAdimc()); - - return string; -} - -//---------------------------------------------- -/* -private static String getStateLabelString() -{ - return "UZTWC UZFWC LZTWC LZFSC LZFPC ADIMC "; -} -*/ -// ---------------------------------------------- - - private static boolean isWhiteSpace(char c) - { - boolean result = false; - - if ( (c == ' ') || (c== '\t') ) - { - result = true; - - } - return result; - } - -// ---------------------------------------------- - private static boolean isPartOfANumber(char c) - { - boolean result = false; - - if ( ((c >= '0') && (c <= '9')) || - (c =='-') || (c == '.') - ) - { - result = true; - } - - return result; - } //end isPartOfANumber - -// ---------------------------------------------- - private static double[] readDoubleArray(String fileName, boolean skipFirstLine) throws java.io.IOException - { - // System.out.println("----------opening file = " + fileName); - List doubleList = new ArrayList(); - - FileReader fileReader = new FileReader(fileName); - BufferedReader bufferedReader = new BufferedReader(fileReader); - //FileReader reader = new FileReader(fileName); - - String line = null; - int lineCount = 0; - - - line = ""; - - while( line != null) - { - line = bufferedReader.readLine(); - if (line == null) - { - break; - } - lineCount++; - // System.out.println(fileName + ": line " + lineCount + " = " + line); - - if ((skipFirstLine) && (lineCount == 1) ) - { - continue; // skip this line entirely - } - - int lastPos = 0; - StringBuffer numberBuffer = new StringBuffer(); - boolean success = false; - boolean foundNumberPart = false; - String numberString = null; - - // assemble the number string from the line - for (int i = 0; i < line.length() ; i++) - { - char c = line.charAt(i); - if ( isPartOfANumber(c) || - ( isWhiteSpace(c) && (foundNumberPart == false ) ) - ) - { - if (isWhiteSpace(c)) - { - //System.out.println("I found whitespace at character " + i); - } - else - { - foundNumberPart = true; - numberBuffer.append(c); - // System.out.println("numberBuffer = " + numberBuffer + " i = " + i); - success = true; - } - } - else //we are done with looking for the number - { - numberString = numberBuffer.toString(); - //System.out.println("numberString = " + numberString); - break; - } - } //end for - - if ((success) && (numberString == null) ) - { - numberString = numberBuffer.toString(); - } - - if (success) - { - double number = -9999.9999; - number = Double.parseDouble(numberString); - doubleList.add(new Double(number)); - } - } //end while - - bufferedReader.close(); - fileReader.close(); - - //copy the list contents to the array of doubles - double[] doubleArray = new double[doubleList.size()]; - for (int i = 0; i < doubleList.size(); i++) - { - - Double doubleVar = (Double) doubleList.get(i); - doubleArray[i] = doubleVar.doubleValue(); - } - - // System.out.println("SacSmaTest.readDoubleArray size = " + - // doubleList.size()); - return doubleArray; - } - -// ---------------------------------------------- - - private static double[] readStateArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[6]; - - int skipAmount = 16; - - //skip the first 16 parameters in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i + skipAmount]; - } - - return sizedArray; - } - -// ---------------------------------------------- - - - private static double[] readParameterArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[16]; - -// skip the last 6 state/carryover variables in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i]; - } - - return sizedArray; - - } - -// ---------------------------------------------- - - private static double[] readPrecipArray(String fileName) throws java.io.IOException - { - - return readDoubleArray(fileName, true); - } - -// ---------------------------------------------- - - private static double[] readEvapArray(String fileName) throws java.io.IOException - { - - return readDoubleArray(fileName, false); - } - - -// ---------------------------------------------- - private static RegularTimeSeries getEvapTimeSeries(double[] evapArray) - { - - long endTime = System.currentTimeMillis(); - endTime = TimeHelper.truncateTimeInMillisToNearestHour(endTime, 1); - - final long millisPerHour = 60 * 60 * 1000; - long startTime = endTime - (millisPerHour * (evapArray.length -1)); - - int intervalInHours = 1; - - RegularTimeSeries ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, - MeasuringUnit.mm); - - return ts; - } - -// ---------------------------------------------- - public static void oldTestModel() - { - - double[] stateArray = null; - double[] parameterArray = null; - - SacSmaParameters params = null; - SacSmaState state = null; - SacSmaRainfallRunoffModel model = null; - - RegularTimeSeriesHolder evapTimeSeriesHolder = new RegularTimeSeriesHolder(); - - int hoursPerInterval = 1; - double evaporationAmount = 0.0; - double precipAmount = 0.0; - - - double[] precipArray = null; - double[] evaporationArray = null; - - - try - { - parameterArray = readParameterArray("D:/Data/exampleCode/sacsma/parmsandco"); - - - - stateArray = readStateArray("D:/Data/exampleCode/sacsma/parmsandco"); - - params = new SacSmaParameters(parameterArray); - state = new SacSmaState(stateArray); - - - - precipArray = readPrecipArray("D:/Data/exampleCode/sacsma/rainfile"); - evaporationArray = readEvapArray("D:/Data/exampleCode/sacsma/evapfile"); - - RegularTimeSeries evapTimeSeries = getEvapTimeSeries(evaporationArray); - evapTimeSeriesHolder.setTimeSeries(evapTimeSeries); - - boolean useMapeTimeSeries = true; - - double[] values = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; - MonthlyValues mapeAdjustmentValues = new MonthlyValues(values); - - double peAdjust = 1.0; - double pxAdjust = 1.0; - - model = new SacSmaRainfallRunoffModel(state, - params, - peAdjust, - pxAdjust, - useMapeTimeSeries, - mapeAdjustmentValues, - evapTimeSeriesHolder); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - int length = Math.min(precipArray.length, evaporationArray.length); - - String formatString = "#####.000"; - NumberFormat formatter = new DecimalFormat(formatString); - - System.out.println("Java version of SacSma:"); - - PrintWriter runoffWriter = null; - PrintWriter internalsWriter = null; - - try - { - runoffWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_runoff.out")); - - internalsWriter = - new PrintWriter(new FileOutputStream("D:/Data/code/SiteSpecific/output/java_internals.out")); - } - catch(java.io.IOException e) - { - System.out.println("Unable to open the output files."); - System.exit(1); - } - - String runoffMessage = null; - String internalsMessage = null; - - internalsMessage = "at startup: " + - getStateString(model.getState()) + - model.getParameters().toString(); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - - //for each piece of input data - for (int i = 0 ; i < length; i++) - { - - precipAmount = precipArray[i]; - evaporationAmount = evaporationArray[i]; - - double totalChannelInflow = - model.calculate(hoursPerInterval/ 24.0, - precipAmount, - evaporationAmount); - - runoffMessage = "i = " + i + " px = " + precipAmount + - " evap = " + evaporationAmount + - " runoff = " + - formatter.format(totalChannelInflow); - - - - System.out.println(runoffMessage); - runoffWriter.println(runoffMessage); - //System.out.println(model); - - internalsMessage = getStateString(model.getState()); - - System.out.println(internalsMessage); - internalsWriter.println(internalsMessage); - - - - } //end for - - runoffWriter.close(); - internalsWriter.close(); - - } //end oldTestModel - -} - - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/AppsDefaults.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/AppsDefaults.java deleted file mode 100644 index 2b199b79af..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/AppsDefaults.java +++ /dev/null @@ -1,689 +0,0 @@ -/* - * Created on Jul 10, 2003 - * - * Modified 12/28/04 to provide getInt() method. - */ -package ohd.hseb.util; - -import java.util.*; -import java.io.*; - -/** - * @author Chip Gobs - * - * This is the Java version of get_apps_defaults.c - */ -public class AppsDefaults -{ - - - private static final String APPS_DEFAULTS_USER = "APPS_DEFAULTS_USER"; - private static final String APPS_DEFAULTS_PROG = "APPS_DEFAULTS_PROG"; - private static final String APPS_DEFAULTS_SITE = "APPS_DEFAULTS_SITE"; - private static final String APPS_DEFAULTS = "APPS_DEFAULTS"; - - private static final String RFR_OPEN= "$("; - private static final String RFR_CLOSE = ")"; - - private static final char DELIM = ':'; - private static final char COMMENT = '#'; - - private static final char DOUBLE_QUOTE = '\"'; - private static final char SINGLE_QUOTE = '\''; - - private static final int RECUR_LIMIT = 40; - - private static Set _trueSet = new HashSet(); - - private int _recursionCount = 0; - - private Properties _envProperties = new Properties(); - - private String _appsDefaultsUserFilePath = null; - private String _appsDefaultsProgramFilePath = null; - private String _appsDefaultsSiteFilePath = null; - private String _appsDefaultsNationalFilePath = null; - - private BufferedReader _reader = null; - - static - { - _trueSet.add("true"); - _trueSet.add("on"); - _trueSet.add("yes"); - _trueSet.add("y"); - _trueSet.add("1"); - } - -//-------------------------------------------------------------- - public AppsDefaults() - { - EnvHelper envHelper = new EnvHelper(); - - _envProperties = envHelper.getProperties(); - - _appsDefaultsUserFilePath = _envProperties.getProperty(APPS_DEFAULTS_USER); - _appsDefaultsProgramFilePath = _envProperties.getProperty(APPS_DEFAULTS_PROG); - _appsDefaultsSiteFilePath = _envProperties.getProperty(APPS_DEFAULTS_SITE); - _appsDefaultsNationalFilePath = _envProperties.getProperty(APPS_DEFAULTS); - - return; - } -// ----------------------------------------------------- - public int getInt(String tokenName, int defaultValue) - { - int returnValue = defaultValue; - - try - { - String tokenValue = getToken(tokenName); - if (tokenValue != null) - { - returnValue = Integer.parseInt(tokenValue); - } - } - catch (Throwable e) - { - returnValue = defaultValue; - } - - - return returnValue; - } -// ---------------------------------------------------- - public boolean getBoolean(String tokenName, boolean defaultValue, String trueValueString) - { - _trueSet.add(trueValueString); - return getBoolean(tokenName, defaultValue); - } -// ----------------------------------------------------- - - - public boolean getBoolean(String tokenName, boolean defaultValue) - { - boolean returnValue = defaultValue; - - try - { - String tokenValue = getToken(tokenName); - if (tokenValue != null) - { - if (_trueSet.contains(tokenValue.toLowerCase())) - { - returnValue = true; - } - else - { - returnValue = false; - } - - } - } - catch (Throwable e) - { - returnValue = defaultValue; - } - - - return returnValue; - } - -// ----------------------------------------------------- - public String getToken(String tokenName, String defaultValue) - { - - String tokenValue = getToken(tokenName); - if (tokenValue == null) - { - tokenValue = defaultValue; - } - - return tokenValue; - } -// ----------------------------------------------------- - - - public String getToken(String tokenName) - { - String tokenValue = null; - - //System.out.println("recursion count = " + _recursionCount); - - String envValue = _envProperties.getProperty(tokenName); - - // if token is available as an environment variable, use its value - if (envValue != null) - { - tokenValue = envValue; - } - else // look for the token in each the files (if they are defined), until - // find the token, then stop looking as soon as it is found - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsUserFilePath); - if (tokenValue == null) - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsProgramFilePath); - if (tokenValue == null) - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsSiteFilePath); - if (tokenValue == null) - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsNationalFilePath); - } - } - } - } //end else - - tokenValue = expandReferBacks(tokenValue); - - return tokenValue; - - } //end getToken() - -// -------------------------------------------------------------- - - private String getTokenFromFile(String tokenName, String filePath) - { - String tokenValue = null; - boolean tokenFound = false; - String line = ""; - - NameValuePair nameValuePair = null; - - if (filePath != null) - { - - try - { - _reader = new BufferedReader (new FileReader(filePath)); - - while ((! tokenFound) && (line != null) ) - { - line = getLine(); - if (line == null) - { - break; - } - nameValuePair = parseLine(line); - - if (nameValuePair != null) - { - // System.out.println("nameValuePair.getName() = |" + - // nameValuePair.getName() + "|" ); - - // System.out.println("nameValuePair.getValue() = |" + - // nameValuePair.getValue() + "|" ); - - if ( (nameValuePair.getName().equals(tokenName)) ) - - { - tokenFound = true; - tokenValue = nameValuePair.getValue(); - } - } - } - - _reader.close(); - - } - catch (java.io.IOException e) - { - - } - - } - return tokenValue; - } - -// ----------------------------------------------------- - private String expandReferBacks(String tokenValue) - { - if (tokenValue != null) - { - while (thereAreReferBacks(tokenValue)) - { - //System.out.println("tokenValue before expandFirstReferBack = " + tokenValue); - tokenValue = expandFirstReferBack(tokenValue); - //System.out.println("tokenValue after expandFirstReferBack = " + tokenValue); - } - } - - return tokenValue; - } - -// ----------------------------------------------------- - - private boolean thereAreReferBacks(String tokenValue) - { - boolean result = false; - - if (tokenValue.indexOf(RFR_OPEN) > -1) - { - result = true; - } - - return result; - } - -// ----------------------------------------------------- - - private String expandFirstReferBack(String tokenValue) - { - - int referBackStartIndex = tokenValue.indexOf(RFR_OPEN); - int referBackEndIndex = tokenValue.indexOf(RFR_CLOSE); - String beginning = ""; - String middle = null; - String newTokenName = null; - String end = ""; - - if ((referBackStartIndex > -1) && (referBackEndIndex > -1)) - { - if (referBackStartIndex > 0) - { - beginning = tokenValue.substring(0, referBackStartIndex); - } - - newTokenName = tokenValue.substring(referBackStartIndex + RFR_OPEN.length(), - referBackEndIndex); - - _recursionCount++; - - if (_recursionCount <= RECUR_LIMIT) - { - middle = getToken(newTokenName); - _recursionCount--; - } - else - { - middle = "ERROR_ERROR_ERROR"; - System.err.println("You probably have a cycle in your Apps Defaults File's refer backs, please check it"); - } - if ( (referBackEndIndex + RFR_CLOSE.length()) < tokenValue.length() ) - { - end = tokenValue.substring(referBackEndIndex + RFR_CLOSE.length(), - tokenValue.length()); - } - - - tokenValue = beginning + middle + end; - } - - return tokenValue; - } - -// ----------------------------------------------------- - private String getLine() throws java.io.IOException - { - String line = null; - - line = _reader.readLine(); - - // System.out.println("line = " + line); - - return line; - } -// ----------------------------------------------------- - private NameValuePair parseLine(String line) - { - NameValuePair pair = null; - int delimiterIndex = -1; - - String tokenName = null; - String tokenValue = null; - - //find delimiter - - delimiterIndex = line.indexOf(DELIM); - - - if (delimiterIndex > -1) //there is a delimiter character on the line - { - //find tokenName - tokenName = findTokenName(line, delimiterIndex); - - if (tokenName != null) - { - tokenValue = findTokenValue(line, delimiterIndex); - if (tokenValue != null) - { - pair = new NameValuePair(tokenName, tokenValue); - } - } - } // end if found a delimiter - else //there is no delimiter, so can't read a pair from this line - { - pair = null; - } - - return pair; - } - -// ----------------------------------------------------- - private String findTokenName(String line, int delimiterIndex) - { - String tokenName = null; - boolean foundTokenName = false; - boolean foundStartOfTokenName = false; - boolean foundComment = false; - StringBuffer tokenNameBuffer = new StringBuffer(); - - - for (int i = 0; ((i < delimiterIndex) && - (! foundTokenName)) && - (! foundComment) ; i++) - { - char c = line.charAt(i); - if (isWhiteSpace(c)) - { - // check to see if this is white space at the beginning or the end - // of the tokenName - if (! foundStartOfTokenName) //this must beginning whitespace - { - // so ignore the whitespace - } - else //must be trailing whitespace - { - // the token is done; - tokenName = tokenNameBuffer.toString(); - foundTokenName = true; - } - } //end if isWhiteSpace - - else if (isCommentStarter(c)) - { - //There can't be a valid tokenName, tokenValue pair here, then - foundComment = true; - - //clear out the tokenNameVariables - tokenName = null; - - // works in >= java 1.2, - //tokenNameBuffer.delete(0, tokenNameBuffer.length()); - - //works in java < 1.2, but the previous line is prefered - tokenNameBuffer = new StringBuffer(); - - foundStartOfTokenName = false; - break; //exit loop - - } //end isCommentStarter - - else //part of the tokenName - { - tokenNameBuffer.append(c); - foundStartOfTokenName = true; - } - - } //end for - - if (foundStartOfTokenName) - { - tokenName = tokenNameBuffer.toString(); - } - - return tokenName; - } - - //---------------------------------------------------------------------- - - private String findTokenValue(String line, int delimiterIndex) - { - String tokenValue = null; - - boolean foundTokenValue = false; - boolean foundStartOfTokenValue = false; - boolean foundComment = false; - - boolean foundSingleOpenQuote = false; - boolean foundSingleCloseQuote = false; - - boolean foundDoubleOpenQuote = false; - boolean foundDoubleCloseQuote = false; - - boolean error = false; - - StringBuffer tokenValueBuffer = new StringBuffer(); - - for (int i = delimiterIndex + 1 ; ((i < line.length()) && - (! foundTokenValue)) && - (! foundComment) ; i++) - { - char c = line.charAt(i); - if (isWhiteSpace(c)) - { - // check to see if this is white space at the beginning or the end - // of the tokenValue - if (! foundStartOfTokenValue) //this must be beginning whitespace - { - // so ignore the whitespace - } - else if ((foundSingleOpenQuote) && (!foundSingleCloseQuote)) - { - tokenValueBuffer.append(c); - foundStartOfTokenValue = true; - } - else if ((foundDoubleOpenQuote) && (!foundDoubleCloseQuote)) - { - tokenValueBuffer.append(c); - foundStartOfTokenValue = true; - } - else //must be trailing whitespace - { - // the token value reading is done; - tokenValue = tokenValueBuffer.toString(); - foundTokenValue = true; - } - } //end if isWhiteSpace - - else if (isCommentStarter(c)) - { - if (foundStartOfTokenValue ) - { - //this character is allowed in a tokenValue - tokenValueBuffer.append(c); - } - else - { //error, there can't be a valid tokenValue - foundComment = true; - - //clear out the tokenNameVariables - tokenValue = null; - - // works in >= java 1.2, - //tokenValueBuffer.delete(0, tokenValueBuffer.length()); - - //works in java < 1.2, but the previous line is prefered - tokenValueBuffer = new StringBuffer(); - - - error = true; - } - } //end isCommentStarter - - else if (isDelimiter(c)) - { - if (foundStartOfTokenValue ) - { - //this character is allowed in a tokenValue - tokenValueBuffer.append(c); - } - else - { //error, there can't be a valid tokenValue - - //clear out the tokenNameVariables - tokenValue = null; - - // works in >= java 1.2, - //tokenValueBuffer.delete(0, tokenValueBuffer.length()); - - //works in java < 1.2, but the previous line is prefered - tokenValueBuffer = new StringBuffer(); - - error = true; - break; //exit loop - } - - } - else if (isSingleQuote(c)) - { - if (foundSingleOpenQuote) - { - foundSingleCloseQuote = true; - foundTokenValue = true; //done - } - else - { - foundSingleOpenQuote = true; - } - } - - else if (isDoubleQuote(c)) - { - if (foundDoubleOpenQuote) - { - foundDoubleCloseQuote = true; - foundTokenValue = true; //done - } - else - { - foundDoubleOpenQuote = true; - } - } - - else //part of the tokenValue - { - tokenValueBuffer.append(c); - // System.out.println("tokenValueBuffer =" + tokenValueBuffer.toString()); - foundStartOfTokenValue = true; - } - - } //end for - - if ( (foundStartOfTokenValue) && (!error)) - { - tokenValue = tokenValueBuffer.toString(); - } - - return tokenValue; - } - // ----------------------------------------------------- - - -// ----------------------------------------------------- - - - // - private static boolean isWhiteSpace(char c) - { - boolean result = false; - - if ( (c == ' ') || (c== '\t') ) - { - result = true; - } - - return result; - - } //isWhiteSpace - -// ----------------------------------------------------- - private static boolean isCommentStarter(char c) - { - boolean result = false; - - if (c == COMMENT) - { - result = true; - } - - return result; - } //isCommentStarter - - //------------------------------------------------------------- - private static boolean isDelimiter(char c) - { - boolean result = false; - - if (c == DELIM) - { - result = true; - - } - - return result; - } //isDelimiter - - //----------------------------------------------------------- - - private static boolean isSingleQuote(char c) - { - boolean result = false; - - if (c == SINGLE_QUOTE) - { - result = true; - } - - return result; - } //isSingleQuote - -// ----------------------------------------------------- - - private static boolean isDoubleQuote(char c) - { - boolean result = false; - - if (c == DOUBLE_QUOTE) - { - result = true; - } - - return result; - - } //isDoubleQuote - - -// ----------------------------------------------------- - public static void main(String[] args) - { - AppsDefaults ad = new AppsDefaults(); - String tokenName = null; - String tokenValue = null; - - // tokenName = "shef_procobs"; - // tokenValue = ad.getToken(tokenName); - - // System.out.println("tokenName = " + tokenName + - // " tokenValue = " + tokenValue); - - tokenName = "ffg_out_dir"; - tokenValue = ad.getToken(tokenName); - - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - - tokenName = "testToken1"; - //tokenRawValue = "#hank:me:'llhank' " - tokenValue = ad.getToken(tokenName); - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - tokenName = "testToken2"; - //tokenRawValue = "dd#hank:me:'llhank' " - tokenValue = ad.getToken(tokenName); - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - - tokenName = "testToken3"; - //tokenRawValue = 'dd#hank:me:"llhank" ' - tokenValue = ad.getToken(tokenName); - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - } - - -} // end class AppsDefaults diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/BooleanHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/BooleanHolder.java deleted file mode 100644 index 5ae6dbe1ec..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/BooleanHolder.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on May 14, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * - */ -public class BooleanHolder -{ - private boolean _value; - - public BooleanHolder(boolean value) - { - setValue(value); - } - - public void setValue(boolean value) - { - _value = value; - } - - public boolean getValue() - { - return _value; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/CodeTimer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/CodeTimer.java deleted file mode 100644 index b59a83b58b..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/CodeTimer.java +++ /dev/null @@ -1,110 +0,0 @@ -package ohd.hseb.util; - -// create a Logger class. Give to Gautam for java practice purposes. - -public class CodeTimer -{ - - private boolean _isRunning = false; - private long _startTime = 0; - private long _endTime = 0; - private long _elapsedTime = 0; - private Logger _logger = null; - - //----------------------------------------------- - - public CodeTimer() - { - - - } - //----------------------------------------------- - - public CodeTimer(Logger logger) - { - _logger = logger; - } - - //----------------------------------------------- - - public void start() - { - _isRunning = true; - _startTime = System.currentTimeMillis(); - _elapsedTime = 0; - - return; - } - - //----------------------------------------------- - - public long stop() - { - return this.stop(""); - } - - //----------------------------------------------- - - public long stop(String message) - { - _endTime = System.currentTimeMillis(); - _elapsedTime += (_endTime - _startTime); - - _isRunning = false; - - if ( (message != null) && (message.length() > 0) ) - { - log(message + " " + _elapsedTime + " millis."); - } - - if (_logger != null) - { - _logger.close(); - } - - return _elapsedTime; - } - - //----------------------------------------------- - - public void restart() - { - _isRunning = true; - _startTime = System.currentTimeMillis(); - } - - //----------------------------------------------- - - // reset all the state variables - public void clear() - { - _isRunning = false; - _startTime = 0; - _endTime = 0; - _elapsedTime = 0; - } - - //----------------------------------------------- - - private void log(String message) - { - if (_logger != null) - { - _logger.log(message); - } - else - { - System.out.println(message); - } - return; - } - - //----------------------------------------------- - - public long getElapsedTime() - { - return _elapsedTime; - } - - -} //end class CodeTimer diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/CodeTracer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/CodeTracer.java deleted file mode 100644 index 0ada6b3f16..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/CodeTracer.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Created on Jul 28, 2004 - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * - */ -public class CodeTracer -{ - private Logger _logger = null; - - // ------------------------------------------------------------- - // nobody can call this - public CodeTracer() - { - - } - - public CodeTracer(Logger logger) - { - _logger = logger; - - } - // ------------------------------------------------------------- - public void trace(String message) - { - - // calls trace with a prepended message - if (_logger != null) - { - _logger.log(message); - trace(); - } - else - { - System.out.println(message); - trace(); - } - } - // ------------------------------------------------------------- - public void trace() - { - try - { - throw new Exception("Just Tracing, not an actual error"); - } - catch (Exception e) - { - if (_logger != null) - { - e.printStackTrace(_logger.getPrintWriter()); - } - else - { - e.printStackTrace(); - } - } - - } //end trace() - // ------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Cryptor.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Cryptor.java deleted file mode 100644 index f1c8229576..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Cryptor.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Created on Aug 28, 2003 - * - * - */ -package ohd.hseb.util; - -import java.util.*; - - - -public class Cryptor -{ - - private String _key = "adlfkjaldfkjaldkjf"; - private static long _seed = 5234234234L; - private static int _range = 17; - - // ---------------------------------------------------------- - public static String decrypt(String encryptedString) - { - StringBuffer buffer = new StringBuffer(encryptedString); - - Random random = new Random(_seed); - for (int i = 0; i < buffer.length(); i++) - { - char c = buffer.charAt(i); - c -= getNextShift(random); - buffer.setCharAt(i,c); - } - - // System.out.println(""); - - return buffer.toString(); - } - - // ---------------------------------------------------------- - - public static String encrypt(String encryptedString) - { - StringBuffer buffer = new StringBuffer(encryptedString); - - Random random = new Random(_seed); - for (int i = 0; i < buffer.length(); i++) - { - char c = buffer.charAt(i); - c += getNextShift(random); - buffer.setCharAt(i,c); - } - - // System.out.println(""); - - return buffer.toString(); - } - - // --------------------------------------------------- - private static int getNextShift(Random random) - { - int shift = random.nextInt(2 * _range) - _range; - // System.out.print("shift = " + shift + " "); - return shift; - } - - // ---------------------------------------------------------- - - public static void main(String[] args) - { - String message = ""; - String encMessage = ""; - - String decMessage = ""; - - encMessage = encrypt(message); - decMessage = decrypt(encMessage); - - - // System.out.println("message = " + message); - System.out.println("encMessage = " + encMessage); - //System.out.println("decMessage = " + decMessage); - - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/DataPoint.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/DataPoint.java deleted file mode 100644 index 0742c1a39c..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/DataPoint.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Created on Jul 16, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author gobsc - * - * - */ -public class DataPoint -{ - private double _x; - private double _y; - - public DataPoint() - { - - } - - public DataPoint(double x, double y) - { - setX(x); - setY(y); - } - - public void setX(double x) - { - this._x = x; - } - - public double getX() - { - return _x; - } - - public void setY(double y) - { - this._y = y; - } - - public double getY() - { - return _y; - } - - public String toString() - { - String outString = "( " + _x + ", " + _y + ")"; - return outString; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/DoubleHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/DoubleHolder.java deleted file mode 100644 index f2c6937e1c..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/DoubleHolder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * Holds a double value This is needed because Double is immutable and primitives are passed by - * value to methods. - */ -public class DoubleHolder -{ - private double _value; - - public DoubleHolder(double value) - { - _value = value; - } - - public void setValue(double value) - { - _value = value; - } - - public double getValue() - { - return _value; - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/EndianConverter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/EndianConverter.java deleted file mode 100644 index 0eb102fd51..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/EndianConverter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Created on Oct 31, 2003 - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - */ -public class EndianConverter -{ - - public static int convert(int origEndianInt) - { - - int newEndianInt = - (( origEndianInt & 0x000000ff )<< 24) | - (( origEndianInt & 0x0000ff00) << 8) | - (( origEndianInt & 0x00ff0000) >>> 8) | - (( origEndianInt & 0xff000000) >>> 24); - /* - System.out.println("MAP.convertEndian(int): original int was " + origEndianInt + - " new one is newEndianInt " + - newEndianInt); - */ - - return newEndianInt; - - } -// ---------------------------------------------------- - - public static short convert(short origEndianShort) - { - short newEndianShort = - (short)( (( origEndianShort & 0x000000ff )<< 8) | - (( origEndianShort & 0x0000ff00) >>> 8) - ); - - - return newEndianShort; - - } //end convertEndian for shorts - -// ---------------------------------------------------------- - - public static float convert(float origEndianFloat) - { - - int intBits = Float.floatToIntBits(origEndianFloat); - - - int flippedInt = - (( intBits & 0x000000ff )<< 24) | - (( intBits & 0x0000ff00) << 8) | - (( intBits & 0x00ff0000) >>> 8) | - (( intBits & 0xff000000) >>> 24); - - float newEndianFloat = Float.intBitsToFloat(flippedInt); - - - return newEndianFloat; - - } -// ---------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/EnvHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/EnvHelper.java deleted file mode 100644 index 53e514aa6a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/EnvHelper.java +++ /dev/null @@ -1,149 +0,0 @@ - -package ohd.hseb.util; - -import java.util.*; -import java.io.*; - -public class EnvHelper -{ - private Properties _props = null; - - //-------------------------------------------------------------- - // Note, this version of EnvHelper uses the returned System.getenv() method. - // It was unavailable for a few java versions (1.3.x to 1.4.x ?) - // Code timings on a Linux box reveal an improvement with the old code taking - // 54 milliseconds and the new code taking only 5 millis in SSHP. - //-------------------------------------------------------------- - - public Properties getProperties() - { - - if (_props == null) - { - _props = new Properties(); - - _props.putAll(System.getenv()); - - } //end if - - return _props; - } - - //-------------------------------------------------------------- - - private Properties getProperties_old() - { - - if (_props == null) - { - _props = new Properties(); - - Process process = null; - - String commandString = this.getEnvCommandString(); - Runtime runtime = Runtime.getRuntime(); - - try - { - - process = runtime.exec(commandString); - - InputStream inStream = process.getInputStream(); - - - BufferedReader br = new BufferedReader - ( new InputStreamReader( inStream) ); - String line; - while( (line = br.readLine()) != null ) - { - int index = line.indexOf( '=' ); - if (index < 0) - { - //something is wrong with the line, - // ignore it and read the next line - continue; - } - - String key = line.substring( 0, index ); - String value = line.substring( index+1 ); - - // works in java >= 1.2 - //_props.setProperty( key, value ); - - // works in java < 1.2, and later, but is not prefered. - _props.put(key, value); - - // System.out.println( key + " = " + value ); - } - } - catch (java.io.IOException e) - { - e.printStackTrace(); - return _props; - } - - - } //end if - - return _props; - } - -// -------------------------------------------------------------- - private String getEnvCommandString() - { - String OS = System.getProperty("os.name").toLowerCase(); - String commandString = ""; - - if (OS.indexOf("windows 9") > -1) - { - commandString = "command.com /c set " ; - } - else if ( (OS.indexOf("nt") > -1) - || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1) ) - { - // thanks to JuanFran for the xp fix! - commandString = "cmd.exe /c set " ; - } - else //assume unix - { - commandString = "env"; - } - - return commandString; - } - - //-------------------------------------------------------------- - public String getProperty(String key) - { - Properties props = this.getProperties(); - - return props.getProperty(key); - } - //-------------------------------------------------------------- - public static void main(String[] args) - { - EnvHelper envHelper = new EnvHelper(); - - - Properties env = envHelper.getProperties(); - - if (env == null) - { - System.out.println("dude, env is null"); - } - else - { - System.out.println("------------------"); - env.list(System.out); - } - - String tempVar = envHelper.getProperty("TEMP"); - - System.out.println("TEMP = " + tempVar); - - - return; - } - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/FileLogger.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/FileLogger.java deleted file mode 100644 index 3c08feb87d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/FileLogger.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Created on Jul 9, 2003 - * - * - */ -package ohd.hseb.util; - -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -/** - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- -------------------------------------
- * May 13, 2011  8079       jnjanga     added custom printStackTrace method
- * 
- * 
- * - * @author gobsc - */ -public class FileLogger implements Logger { - - // private vars - private String _fileName = null; - - private OutputStream _outputStream = null; - - private PrintWriter _writer = null; - - private boolean _usingRealFile = false; - - private boolean _fileIsOpen = false; - - private static final String dateFormatString = "yyyy/MM/dd HH:mm:ss.SSS"; - - private static final SimpleDateFormat _dateFormatter = new SimpleDateFormat( - dateFormatString); - - static { - _dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - // options - private boolean _appendDateTime = false; - - private boolean _keepFileOpen = true; - - // --------------------------------------------------------------------- - - public FileLogger(boolean appendDateTime) { - - _appendDateTime = appendDateTime; - - } - - /* - */ - public FileLogger(String fileName) { - // default is to keep the file open until closed - // and to append the date and time to each line - // of text - - this(fileName, true, true); - } - - // --------------------------------------------------------------------- - - public FileLogger(String fileName, boolean keepFileOpen, - boolean appendDateTime) { - _keepFileOpen = keepFileOpen; - _appendDateTime = appendDateTime; - - _fileName = fileName; - - } - - // --------------------------------------------------------------------- - - public void log(String message) { - - // open if needed - if (!isOpen()) { - openFile(_fileName); - _writer = new PrintWriter(_outputStream); - } - - // write out the message, pre-pending date time stamp if required - if (_appendDateTime) { - _writer.println(getDateTimeStamp() + ": " + message); - } else { - _writer.println(message); - } - - _writer.flush(); - - // close if supposed to do so - if (!_keepFileOpen) { - close(); - } - } - - /** - * logs a stack trace - * - * @param aThrowable - * a thrown exception - */ - public void printStackTrace(Throwable aThrowable) { - // add the class name and any message passed to constructor - final String SPACE = " "; - final StringBuilder result = new StringBuilder(SPACE); - result.append(aThrowable.toString()); - final String NEW_LINE = System.getProperty("line.separator"); - result.append(NEW_LINE); - - // add each element of the stack trace - for (StackTraceElement element : aThrowable.getStackTrace()) { - result.append(NEW_LINE); - for (int i = 0; i < 25; i++) - result.append(SPACE); - result.append(element); - } - log(result.toString()); - } - - // --------------------------------------------------------------------- - public PrintWriter getPrintWriter() { - return _writer; - } - - // --------------------------------------------------------------------- - - private String getDateTimeStamp() { - Date date = new Date(); - - return _dateFormatter.format(date); - } - - // --------------------------------------------------------------------- - - private void openFile(String fileName) { - try { - if (fileName != null) { - _outputStream = new FileOutputStream(fileName, true); - _usingRealFile = true; - _fileIsOpen = true; - } else // fileName == null - { - _outputStream = System.out; - - } - - _writer = new PrintWriter(_outputStream); - - } catch (java.io.IOException e) { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - public void close() { - // try - { - if (isOpen() && _usingRealFile) { - _fileIsOpen = false; - _writer.close(); - } - } - // catch(java.io.IOException e) - { - // e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - private boolean isOpen() { - return _fileIsOpen; - } - - // --------------------------------------------------------------------- - -} // FileLogger \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Grid.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Grid.java deleted file mode 100644 index c78a687871..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Grid.java +++ /dev/null @@ -1,7 +0,0 @@ -package ohd.hseb.util; - - -public interface Grid -{ - double getValue(int row, int col); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/IntegerHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/IntegerHolder.java deleted file mode 100644 index 98b06e5162..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/IntegerHolder.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * Holds an int value. This is needed because Integer is immutable and int is passed by value to - * methods. - */ -public class IntegerHolder -{ - private int _value; - - public IntegerHolder(int value) - { - _value = value; - } - - public void setValue(int value) - { - _value = value; - } - - public int getValue() - { - return _value; - } - - public void change(int amount) - { - _value += amount; - } - - public void increment() - { - change(1); - } - - public void decrement() - { - change(-1); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Logger.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Logger.java deleted file mode 100644 index 6f386f48ed..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Logger.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Created on Jul 9, 2003 - * - * - */ -package ohd.hseb.util; - -import java.io.*; - -/** - * @author Chip Gobs - * - * - */ -public interface Logger -{ - public void log(String message); - public void close(); - public PrintWriter getPrintWriter(); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/LongHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/LongHolder.java deleted file mode 100644 index 713db5aba4..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/LongHolder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * Holds a LongValue. This is needed because Long is immutable. - */ -public class LongHolder -{ - private long _value; - - public LongHolder(long value) - { - _value = value; - } - - public void setValue(long value) - { - _value = value; - } - - public long getValue() - { - return _value; - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MathHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MathHelper.java deleted file mode 100644 index ba63306d21..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MathHelper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Created on Nov 14, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - * - * This class consolidates some common math functions. - */ -public class MathHelper -{ - /* public static double roundToNDecimalPlaces(double origValue, int decimalPlaces) - { - double factor = Math.pow(10, decimalPlaces); - long intValue = (long) (origValue * factor); - double newValue = intValue / factor; - - return newValue; - } //end roundToNDecimalPlaces - */ - - public static double roundToNDecimalPlaces(double numberToRound, int decimalPlacesToMaintain) - { - - long roundingFactor = 1; - long temporaryHolder; - long roundingFactorArray[] = { 1, 10, 100, 1000, 10000, 100000, - 1000000, 10000000, 100000000, 1000000000 }; - - if (decimalPlacesToMaintain < 0) - { - decimalPlacesToMaintain = 0; - } - else if (decimalPlacesToMaintain > 9) - { - decimalPlacesToMaintain = 9; - } - - - // I could have used pow(), but this is faster - roundingFactor = roundingFactorArray[decimalPlacesToMaintain]; - - temporaryHolder = (long) Math.floor((numberToRound * roundingFactor) + 0.5); - - numberToRound = (double) temporaryHolder / roundingFactor; - - return numberToRound; - - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MaxMinData.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MaxMinData.java deleted file mode 100644 index 517f0047c9..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MaxMinData.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on Jul 15, 2004 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - * - */ -public class MaxMinData -{ - private double _maxValue; - private double _minValue; -// --------------------------------------------------------------- - public MaxMinData(double maxValue, double minValue) - { - _maxValue = maxValue; - _minValue = minValue; - } -// --------------------------------------------------------------- - public void setMaxValue(double maxValue) - { - _maxValue = maxValue; - } -// --------------------------------------------------------------- - - public double getMaxValue() - { - return _maxValue; - } -// --------------------------------------------------------------- - - public void setMinValue(double minValue) - { - _minValue = minValue; - } -// --------------------------------------------------------------- - - public double getMinValue() - { - return _minValue; - } -// --------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MemoryLogger.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MemoryLogger.java deleted file mode 100644 index 45c400da60..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/MemoryLogger.java +++ /dev/null @@ -1,24 +0,0 @@ -package ohd.hseb.util; - -public class MemoryLogger -{ - - private static SessionLogger _logger = null; - - public static void setLogger(Logger logger) - { - _logger = (SessionLogger) logger; - - System.out.println("MemoryLogger.setLogger(): _logger.getSessionId() = " + _logger.getSessionId()); - } - - public static void log(String message) - { - Runtime runtime = Runtime.getRuntime(); - String text = null; - - text = message + "Free:" + runtime.freeMemory() + " Max:"+ runtime.maxMemory()+ " total:"+ runtime.totalMemory(); - _logger.log(text); - - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/NameValuePair.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/NameValuePair.java deleted file mode 100644 index a0e8820c8f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/NameValuePair.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Created on Jul 11, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.util; - -/** - * @author gobsc - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class NameValuePair -{ - private String _name; - private String _value; - - public NameValuePair() - { - - } - - public NameValuePair(String name, String value) - { - setName(name); - setValue(value); - } - - public void setName(String name) - { - this._name = name; - } - - public String getName() - { - return _name; - } - - public void setValue(String value) - { - this._value = value; - } - - public String getValue() - { - return _value; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/PrecipUtils.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/PrecipUtils.java deleted file mode 100644 index 7a24c3168c..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/PrecipUtils.java +++ /dev/null @@ -1,13 +0,0 @@ -package ohd.hseb.util; - -public class PrecipUtils -{ - - - public double get_total_hourly_PC() - { - double totalHourlyPC = 0; - - return totalHourlyPC; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Range.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Range.java deleted file mode 100644 index 384d855fa5..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/Range.java +++ /dev/null @@ -1,60 +0,0 @@ -package ohd.hseb.util; - -public class Range -{ - private double _min = 0; - private double _max = 0; - // --------------------------------------------------------------------------- - - public Range(double value1, double value2) - { - double min = Math.min(value1, value2); - double max = Math.max(value1, value2); - - setMin(min); - setMax(max); - } - // --------------------------------------------------------------------------- - public boolean isBetweenInclusive(double value) - { - boolean result = false; - - if ((value >= getMin()) && (value <= getMax() )) - { - result = true; - } - - return result; - } - - // --------------------------------------------------------------------------- - - public void setMin(double min) - { - _min = min; - } - - // --------------------------------------------------------------------------- - - public double getMin() - { - return _min; - } - - // --------------------------------------------------------------------------- - - public void setMax(double max) - { - _max = max; - } - - // --------------------------------------------------------------------------- - - public double getMax() - { - return _max; - } - - // --------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/SessionLogger.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/SessionLogger.java deleted file mode 100644 index 41489e23d2..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/SessionLogger.java +++ /dev/null @@ -1,240 +0,0 @@ -package ohd.hseb.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.TimeZone; - - -public class SessionLogger implements Logger -{ - private String _currentFileName = null; - private OutputStream _outputStream = null; - private PrintWriter _writer = null; - private boolean _usingRealFile = false; - private boolean _fileIsOpen = false; - private int _sessionId; - - private static final String dateFormatString = - "yyyyMMdd"; - private static final SimpleDateFormat _dateFormatter = - new SimpleDateFormat(dateFormatString); - - private static final String timeFormatString = - "HH:mm:ss"; - private static final SimpleDateFormat _timeFormatter = - new SimpleDateFormat(timeFormatString); - - private boolean _appendDateTime = false; - private boolean _keepFileOpen = true; - private String _messageId; - private String _baseFileName; - private String _appName; - - static - { - _dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - _timeFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - public SessionLogger(String appName, String baseFileName, - boolean keepFileOpen, boolean appendDateTime, String messageId) - { - _keepFileOpen = true; - _appendDateTime = true; - _messageId = messageId; - _baseFileName = baseFileName; - _appName = appName; - } - - public int getSessionId() - { - return _sessionId; - } - - public void log(String message) - { - boolean isCreatedNow = false; - if (!isOpen() || message == null) - { - openFile(_baseFileName, false); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - else - { - String splitStr[] = _currentFileName.split("\\."); - String dateTimeStampInFileName = splitStr[2]; - if(!(getCurrentDate().equalsIgnoreCase(dateTimeStampInFileName))) - { - openFile(_currentFileName, true); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - } - - if(isCreatedNow) - { - if(_messageId == null) - _messageId = new Integer(_sessionId).toString(); - _writer.println(_messageId); - _writer.println("**************************************"); - } - - if (_appendDateTime) - { - if(message != null) - _writer.println( getCurrentTime() + ": " + message); - } - else - { - if(message != null) - _writer.println(message); - } - _writer.flush(); - if (!_keepFileOpen) - { - close(); - } - } - - private void determineSessionId(String fileName) - { - int sessionId = -1; - String dirName; - int index = fileName.lastIndexOf("/"); - dirName = fileName.substring(0, index); - File dir = new File(dirName); - int leastPossibleNumber = 1; - if(dir.exists()) - { - if(dir.isDirectory()) - { - String files[] = dir.list(); - if(files != null) - { - if(files.length == 0) - { - sessionId = 1; - } - else - { - int existingIds[] = new int[files.length]; - for(int i=0; i < files.length; i++) - { - String str = files[i]; - String splitStr[] = str.split("\\."); - if(splitStr == null) - continue; - else if(splitStr.length != 3) - continue; - else if(!(splitStr[0].compareTo(_appName) == 0)) - continue; - else if(splitStr[2].length() != 8) - continue; - try - { - existingIds[i] = Integer.parseInt(splitStr[1]); - Integer.parseInt(splitStr[2]);// To make sure the last portion is a data (number) - } - catch(Exception e) - { - continue; - } - } - Arrays.sort(existingIds); - while(true) - { - if(Arrays.binarySearch(existingIds, leastPossibleNumber) < 0) - { - sessionId = leastPossibleNumber; - break; - } - else - leastPossibleNumber++; - } - } - } - } - else - { - System.out.println(_appName + ":["+dir+"] isn't a directory"); - } - } - else - { - System.out.println(_appName + ":Directory ["+dir+"] doesn't exist"); - } - - _sessionId = sessionId; - } - - public PrintWriter getPrintWriter() - { - return _writer; - } - - private String getCurrentDate() - { - Date date = new Date(); - return _dateFormatter.format(date); - } - - private String getCurrentTime() - { - Date date = new Date(); - return _timeFormatter.format(date); - } - - private void openFile(String fileName, boolean isExistingSession) - { - try - { - if (fileName != null) - { - if(!isExistingSession) - { - determineSessionId(_baseFileName); - } - if(_sessionId != -1) // !=-1 means able to get a session id that is valid - { - _currentFileName = _baseFileName +"."+ _sessionId + "."+getCurrentDate(); - _outputStream = new FileOutputStream(_currentFileName, true); - _usingRealFile = true; - _fileIsOpen = true; - } - else // unable to get a session id so log to console - { - _outputStream = System.out; - } - } - else //fileName == null - { - _outputStream = System.out; - } - _writer = new PrintWriter(_outputStream); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - } - } - - public void close() - { - if (isOpen() && _usingRealFile) - { - _fileIsOpen = false; - _writer.close(); - } - } - - private boolean isOpen() - { - return _fileIsOpen; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StreamDrainer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StreamDrainer.java deleted file mode 100644 index dd41f36a72..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StreamDrainer.java +++ /dev/null @@ -1,95 +0,0 @@ -package ohd.hseb.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; - -public class StreamDrainer implements Runnable -{ - private InputStream _inputStream; - private StringBuffer _buffer = null; - // ------------------------------------------------------------------------------------ - - public StreamDrainer(InputStream inputStream) - { - _inputStream = inputStream; - _buffer = new StringBuffer(); - } -// ------------------------------------------------------------------------------------ - - - public void run() - { - try - { - drainInputStream(_inputStream); - } - catch (Exception e) - { - e.printStackTrace(); - } - - } -// ------------------------------------------------------------------------------------ - /* - public String drain() - { - Thread thread = new Thread(this); - thread.start(); - - return getString(); - } - */ - - public String drain() - { // last updated 1/17/08 - Thread thread = new Thread(this); - thread.start(); - - while ( thread.isAlive() ) - { - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException e ) - { - //do nothing - } - } - // System.out.println( "Right after start" ); - return getString(); - } - -// ------------------------------------------------------------------------------------ - - public String getString() - { - return _buffer.toString(); - } - - // ------------------------------------------------------------------------------------ - - private void drainInputStream(InputStream stream) throws IOException - { - String header = "StreamDrainer.drainInputStream(): "; - StringWriter stringWriter = new StringWriter(); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - String s = null; - - while ((s = reader.readLine()) != null) - { - // stringWriter.write(s + "\n"); - _buffer.append(s + "\n"); - // System.out.println(header + s + "n"); - } - - stringWriter.flush(); - - return; - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringDataConverter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringDataConverter.java deleted file mode 100644 index a1b33c39bb..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringDataConverter.java +++ /dev/null @@ -1,204 +0,0 @@ -package ohd.hseb.util; - -import java.text.DecimalFormat; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; - -public class StringDataConverter -{ - private static final String latlonFormatString = "0.00"; - private static final DecimalFormat _latlonFormatter = new DecimalFormat(latlonFormatString); - - public StringDataConverter() - { - } - - public String getFormattedDoubleValue( double doubleValue ) - { - String returnString = ""; - if ( doubleValue != DbTable.getNullDouble() ) - { - returnString = _latlonFormatter.format( doubleValue ); - } - - return ( returnString ); - } - - public double getDoubleValue( String valueString ) - { - double value = DbTable.getNullDouble(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Double.parseDouble( valueString ); - } - - return value; - } - - public long getLongDateValue( String dateString ) - { - long value = DbTable.getNullLong(); - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - value = DbTimeHelper.getLongTimeFromDateString( dateString ); - } - - return value; - } - - public long getLongDateTimeValue( String dateTimeString ) - { - long value = DbTable.getNullLong(); - - if ( ! dateTimeString.equalsIgnoreCase( "" ) ) - { - value = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - } - - return value; - } - - public long getLongValue( String valueString ) - { - long value = DbTable.getNullLong(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Long.parseLong( valueString ); - } - return value; - } - - public String getFormattedFloatValue( float floatValue ) - { - String returnString = ""; - if ( floatValue != DbTable.getNullFloat() ) - { - returnString = _latlonFormatter.format( floatValue ); - } - - return ( returnString ); - } - - public float getFloatValue( String valueString ) - { - float value = DbTable.getNullFloat(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Float.parseFloat( valueString ); - } - return value; - } - - public int getIntValue( String valueString ) - { - int value = DbTable.getNullInt(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Integer.parseInt( valueString ); - } - - return value; - } - - public short getShortValue( String valueString ) - { - short value = DbTable.getNullShort(); - - if ( ! valueString.equalsIgnoreCase( "" ) ) - { - value = Short.parseShort( valueString ); - } - - return value; - } - - public String getStringFromDouble( double value ) - { - String valueString = ""; - - if ( value != DbTable.getNullDouble() ) - { - valueString = Double.toString( value ); - } - - return valueString; - } - - public String getStringFromInt( int value ) - { - String valueString = ""; - - if ( value != DbTable.getNullInt() ) - { - valueString = Integer.toString( value ); - } - - return valueString; - } - - public String getStringFromLong( long value ) - { - String valueString = ""; - - if ( value != DbTable.getNullLong() ) - { - valueString = Long.toString( value ); - } - - return valueString; - } - - public String getStringFromShort( short value ) - { - String valueString = ""; - - if ( value != DbTable.getNullShort() ) - { - valueString = Short.toString( value ); - } - - return valueString; - } - - public String getDateStringFromDateLong( long dateLong ) - { - String dateString = ""; - - if ( dateLong != DbTable.getNullLong() ) - { - dateString = DbTimeHelper.getDateStringFromLongTime( dateLong ); - } - - return dateString; - } - - public String getString( String string ) - { - String returnString = null; - - if ( ! string.equalsIgnoreCase( "" ) ) - { - returnString = string; - } - - return returnString; - } - - public String getDateTimeStringFromDateTimeLong( long dateTimeLong ) - { - String dateString = ""; - - if ( dateTimeLong != DbTable.getNullLong() ) - { - dateString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeLong ); - } - - return dateString; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringHelper.java deleted file mode 100644 index 33d25e2bc7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringHelper.java +++ /dev/null @@ -1,93 +0,0 @@ -package ohd.hseb.util; - -public class StringHelper -{ - public static int areArraysEqual(String[] array1, String[] array2) - { - int result = 0; - - if(array1 == null && array2 != null) - result = -1; - else if(array2 == null && array1 != null) - result = -1; - else if(array1 == null && array2 == null) - result = 0; - else if(array1.length != array2.length) - { - result = -1 ; - } - else - { - for(int i=0 ; i < array1.length; i++) - { - if(array1[i].compareTo(array2[i]) != 0) - { - result = -1; - break; - } - } - } - return result; - } - - - public static String capitalizeFirstLetterOfWords(String text) - { - String result = null; - if(text != null) - { - String tempText = text.toLowerCase(); - String splitWords[] = tempText.split("\\s+"); - - if(splitWords != null) - { - String newConvertedWords[] = new String[splitWords.length]; - - for(int i=0; i < splitWords.length; i++) - { - boolean newWordFormed = false; - String newWord = null; - String orgWord = splitWords[i]; - if(orgWord.length() != 0) - { - char begChar = orgWord.charAt(0); - if(Character.isLetter(begChar)) - { - if(Character.isLowerCase(begChar)) - { - char newBegChar = Character.toUpperCase(begChar); - newWord = newBegChar + orgWord.substring(1, orgWord.length()); - newWordFormed = true; - } - } - } - if (newWordFormed) - { - newConvertedWords[i] = newWord; - } - else - { - newConvertedWords[i] = orgWord; - } - } - - result = ""; - - for(int i=0; i < newConvertedWords.length; i++) - { - if(i == 0 ) - { - result = newConvertedWords[i]; - } - else - { - result = result + " " + newConvertedWords[i]; - } - } - } - } - - return result; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringParser.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringParser.java deleted file mode 100644 index e8673b2dc9..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/StringParser.java +++ /dev/null @@ -1,44 +0,0 @@ -package ohd.hseb.util; - - -import java.util.*; - -public class StringParser -{ - public StringParser() - { - } - - public static String[] tokenize( String stringToTokenize ) - { - StringTokenizer tokens = new StringTokenizer( stringToTokenize ); - List tokenList = new ArrayList(); - - while ( tokens.hasMoreTokens() ) - { - tokenList.add( tokens.nextToken() ); - } - - String[] stringArray = new String[ tokenList.size() ]; - - for ( int i = 0; i < tokenList.size(); i++ ) - { - stringArray[ i ] = (String) tokenList.get( i ); - } - - return stringArray; - } - - public String toString( List tokenList ) - { - StringBuffer output = new StringBuffer(); - String token = null; - - for ( int i = 0; i < tokenList.size(); i++ ) - { - token = (String) tokenList.get( i ); - output.append( token + " " ); - } - return output.toString(); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeHelper.java deleted file mode 100644 index dd517422ef..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Created on Oct 8, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - */ - -public class TimeHelper -{ - - public static final long MILLIS_PER_MINUTE = 60 * 1000; - public static final long MILLIS_PER_HALF_HOUR = 30 * MILLIS_PER_MINUTE; - public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - public static final long MILLIS_PER_12_HOURS = MILLIS_PER_HOUR * 12; - public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; - -// -------------------------------------------------------------------------- - - public static long truncateTimeInMillisToNearestHour(long timeInMillis, - int hoursToTruncate) - { - long roundingAmount = hoursToTruncate * MILLIS_PER_HOUR; - long roundedTime = timeInMillis; - roundedTime /= roundingAmount; - roundedTime *= roundingAmount; - - return roundedTime; - } -// -------------------------------------------------------------------------- - public static long roundTimeInMillisToNearestHour(long timeInMillis) - { - long roundingAmount = MILLIS_PER_HOUR; - long halfHourInMillis = MILLIS_PER_HOUR/2; - long roundedTime = truncateTimeInMillisToNearestHour(timeInMillis + halfHourInMillis, 1); - - return roundedTime; - } -// -------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeHolder.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeHolder.java deleted file mode 100644 index 544cafce9d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeHolder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Created on Oct 31, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - * - * This class is intended to be used as a way for - * other objects to point to something that is always used - * to maintain a time. Multiple objects may wish to set - * or get the time contained herein. They can do this to - * remain in synch about a particular time concept. - Example: various objects need to know what the model run time is - without explicitly know who is maintaining it, so they just have a reference - to the same timeholder, which they can access. - **/ -public class TimeHolder -{ - private long _time = 0; - - public void setTime(long time) - { - _time = time; - } - - public long getTime() - { - return _time; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeSeriesFileManager.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeSeriesFileManager.java deleted file mode 100644 index 63076f8254..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimeSeriesFileManager.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Created on Oct 2, 2003 - * - * - */ -package ohd.hseb.util; - -import java.util.*; -import java.io.*; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; - -/** - * author: Chip Gobs - */ -public class TimeSeriesFileManager -{ - - public static double[] readPrecipArray(String fileName) throws java.io.IOException - { - - return readDoubleArray(fileName, true); - } - -// ------------------------------------------------------- - - public static double[] readEvapArray(String fileName) throws java.io.IOException - { - return readDoubleArray(fileName, false); - } -// ------------------------------------------------------- - - public static double[] readDoubleArray(String fileName, boolean skipFirstLine) throws java.io.IOException - { - // System.out.println("----------opening file = " + fileName); - List doubleList = new ArrayList(); - - FileReader fileReader = new FileReader(fileName); - BufferedReader bufferedReader = new BufferedReader(fileReader); - //FileReader reader = new FileReader(fileName); - - String line = null; - int lineCount = 0; - - - line = ""; - - while( line != null) - { - line = bufferedReader.readLine(); - if (line == null) - { - break; - } - lineCount++; - // System.out.println(fileName + ": line " + lineCount + " = " + line); - - if ((skipFirstLine) && (lineCount == 1) ) - { - continue; // skip this line entirely - } - - StringBuffer numberBuffer = new StringBuffer(); - boolean success = false; - boolean foundNumberPart = false; - String numberString = null; - - // assemble the number string from the line - for (int i = 0; i < line.length() ; i++) - { - char c = line.charAt(i); - if ( isPartOfANumber(c) || - ( isWhiteSpace(c) && (foundNumberPart == false ) ) - ) - { - if (isWhiteSpace(c)) - { - //System.out.println("I found whitespace at character " + i); - } - else - { - foundNumberPart = true; - numberBuffer.append(c); - // System.out.println("numberBuffer = " + numberBuffer + " i = " + i); - success = true; - } - } - else //we are done with looking for the number - { - numberString = numberBuffer.toString(); - //System.out.println("numberString = " + numberString); - break; - } - } //end for - - if ((success) && (numberString == null) ) - { - numberString = numberBuffer.toString(); - } - - if (success) - { - double number = -9999.9999; - number = Double.parseDouble(numberString); - doubleList.add(new Double(number)); - } - } //end while - - bufferedReader.close(); - fileReader.close(); - - //copy the list contents to the array of doubles - double[] doubleArray = new double[doubleList.size()]; - for (int i = 0; i < doubleList.size(); i++) - { - - Double doubleVar = (Double) doubleList.get(i); - doubleArray[i] = doubleVar.doubleValue(); - } - - // System.out.println("SacSmaTest.readDoubleArray size = " + - // doubleList.size()); - return doubleArray; - } -// ------------------------------------------------------- - - public static double[] readStateArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[6]; - - int skipAmount = 16; - - //skip the first 16 parameters in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i + skipAmount]; - } - - return sizedArray; - } -// ------------------------------------------------------- - - public static double[] readParameterArray(String fileName) throws java.io.IOException - { - double[] wholeArray = readDoubleArray(fileName, true); - double[] sizedArray = new double[16]; - - // skip the last 6 state/carryover variables in the file - for (int i = 0; i < sizedArray.length; i++) - { - sizedArray[i] = wholeArray[i]; - } - - return sizedArray; - } - -// ---------------------------------------------- - private static boolean isWhiteSpace(char c) - { - boolean result = false; - - if ( (c == ' ') || (c== '\t') ) - { - result = true; - - } - return result; - } - -// ---------------------------------------------- - private static boolean isPartOfANumber(char c) - { - boolean result = false; - - if ( ((c >= '0') && (c <= '9')) || - (c =='-') || (c == '.') - ) - { - result = true; - } - - return result; - - } //end isPartOfANumber - -// ---------------------------------------------------------------------------------------------- - - public void saveRegularTimeSeries(RegularTimeSeries rts, String filePath) - { - saveRegularTimeSeries(rts, filePath, null); - } - -// ---------------------------------------------------------------------------------------------- - - public void saveRegularTimeSeries(RegularTimeSeries rts, String filePath, MeasuringUnit unit) - { - - if (unit == null) - { - unit = rts.getMeasuringUnit(); - } - - PrintWriter outputStream = null; - try - { - outputStream = new PrintWriter(new FileOutputStream(filePath)); - } - catch(FileNotFoundException e) - { - System.out.println("Error opening the file " + filePath); - } - - outputStream.println(DbTimeHelper.getDateTimeStringFromLongTime(rts.getStartTime())); //1st line in the file - outputStream.println(DbTimeHelper.getDateTimeStringFromLongTime(rts.getEndTime())); //2nd line in the file - outputStream.println(rts.getIntervalInHours()); //3rd line in the file - - //outputs the values of RTS to the file, starting from index = 0 - for (int i = 0; i < rts.getMeasurementCount(); i++) - { - outputStream.println(rts.getMeasurementValueByIndex(i, unit)); - } - - outputStream.close(); - - } //end of saveRegularTimeSeries() - - - /**************************************************************************** - * reading from a file, fileNameStr, returns an object of RegularTimeSeries - * or null. User needs to check the returned is null or not. - ****************************************************************************/ - public RegularTimeSeries readRegularTimeSeries(String filePath, MeasuringUnit unit) - { - RegularTimeSeries retrievedRTS = null; - - //This is where a real application would open the file. - //System.out.println("Opening: " + filePath + "."); - - BufferedReader inputStream = null; - String startTimeStr = null; - String endTimeStr = null; - int intervalInHours = 0; - - /*-------open the file and get start time & end time & intervalInHours --------*/ - try - { - inputStream = new BufferedReader(new FileReader(filePath)); - startTimeStr = inputStream.readLine().trim(); //get 1st line - endTimeStr = inputStream.readLine().trim(); //get 2nd line - intervalInHours = Integer.parseInt(inputStream.readLine().trim()); //get 3rd line - - /* retrievedRTS = new RegularTimeSeries(DbTimeHelper.getLongTimeFromDateTimeString(startTimeStr), - DbTimeHelper.getLongTimeFromDateTimeString(endTimeStr), - intervalInHours, - unit); - */ - /*-------------read the file from 4th line to end to retrieve all the values-------*/ - int count = 0; - String valueLine = null; - - while ((valueLine = inputStream.readLine()) != null) //start reading from 4th line - { - if(retrievedRTS == null) - { - retrievedRTS = new RegularTimeSeries(DbTimeHelper.getLongTimeFromDateTimeString(startTimeStr), - DbTimeHelper.getLongTimeFromDateTimeString(endTimeStr), - intervalInHours, - unit); - } - Measurement measurement = new Measurement(Double.parseDouble(valueLine.trim()), unit); - long time = (retrievedRTS.getStartTime() + count * intervalInHours * TimeHelper.MILLIS_PER_HOUR ); - retrievedRTS.setMeasurementByTime(measurement, time); - // System.out.println("count = " + count + ": " + Double.parseDouble(valueLine.trim())); - - count++; - } - inputStream.close(); - - } - catch (FileNotFoundException e) - { - System.out.println("File " + filePath + " was not found"); - } - catch (Exception e) - { - System.out.println("Error reading from file " + filePath); - } - - return retrievedRTS; //maybe an object, maybe null. user needs to check the returned. - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimerHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimerHelper.java deleted file mode 100644 index c76fa87dfc..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/TimerHelper.java +++ /dev/null @@ -1,65 +0,0 @@ -package ohd.hseb.util; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.Timer; - - -public class TimerHelper -{ - - private ActionListener _applicationListener = null; - - private Timer _refreshDisplayTimer = null; - private int _delayInMillis = 60 * 1 * 1000 ; - // -------------------------------------------------------------------------------------------------- - public TimerHelper(ActionListener applicationListener, int delayInMillis) - { - _applicationListener = applicationListener; - _delayInMillis = delayInMillis; - - startTimer(_delayInMillis); - } - - private class RefreshTimerListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - refresh(); - } - } - - // -------------------------------------------------------------------------------------------------- - - private void refresh() - { - String header = "TimerHelper.refresh(): "; - - System.out.println(header + "Refreshing"); - - _applicationListener.actionPerformed(null); - - startTimer( _delayInMillis); - } - - // -------------------------------------------------------------------------------------------------- - - protected void startTimer(int delayMilliSecs) - { - if(_refreshDisplayTimer == null) - { - RefreshTimerListener refreshDisplayTimerListener = new RefreshTimerListener(); - _refreshDisplayTimer = new Timer(delayMilliSecs, refreshDisplayTimerListener); - } - else - { - _refreshDisplayTimer.stop(); - //This timer doesn't repeat, hence it always uses setInitialDelay and not setDelay - //which is used only if the timer is set to repeat - _refreshDisplayTimer.setInitialDelay(delayMilliSecs); - } - _refreshDisplayTimer.start(); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/UnitValueMapper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/UnitValueMapper.java deleted file mode 100644 index 90d2496be4..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/UnitValueMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * - */ -package ohd.hseb.util; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; - -/** - * @author GobsC - * - * - */ -public class UnitValueMapper implements ValueMapper -{ - - private MeasuringUnit _inputMeasuringUnit = null; - private MeasuringUnit _outputMeasuringUnit = null; - - public UnitValueMapper(MeasuringUnit fromUnit, MeasuringUnit toUnit) - { - _inputMeasuringUnit = fromUnit; - _outputMeasuringUnit = toUnit; - } - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement convertedMeasurement = - Measurement.getConvertedCopy(inputMeasurement, - _inputMeasuringUnit); - double keyValue = convertedMeasurement.getValue(); - - Measurement measurement = new Measurement(keyValue, _inputMeasuringUnit); - Measurement convertedOutputMeasurement = Measurement.getConvertedCopy(measurement, _outputMeasuringUnit); - - return convertedOutputMeasurement; - - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - //-------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/ValueMapper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/ValueMapper.java deleted file mode 100644 index 39455edd41..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/ValueMapper.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Created on Oct 22, 2003 - * - * - */ -package ohd.hseb.util; - -import ohd.hseb.measurement.*; - -/** - * @author GobsC - * - * This interface is meant to be used by the TsBackgroundPainter in - * order to determine how to label the right label in the - * TsPaintableCanvas. For example, an implementor of this interface - * could provide the information needed to map between inches to mm - * or from stage to discharge. - * - */ -public interface ValueMapper -{ - public Measurement getResultMeasurement(Measurement measurement); - public MeasuringUnit getInputMeasuringUnit(); - public MeasuringUnit getOutputMeasuringUnit(); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ComponentHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ComponentHelper.java deleted file mode 100644 index 778690e92d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ComponentHelper.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Created on Oct 21, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 21, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.*; -import javax.swing.*; - -public class ComponentHelper -{ - - public static void addPanelComponent( JPanel panel, Component component, int column, int row, int width, int height, int fill ) - { - addComponent( panel, component, column, row, width, height, 0, 0, fill ); - } - - public static void addPanelComponent( JPanel panel, Component component, int column, int row, int width, int height, double weightx, double weighty, int fill ) - { - addComponent( panel, component, column, row, width, height, weightx, weighty, fill ); - } - - public static void addPanelComponent( JPanel panel, Component component, GridBagConstraints gbc, int column, int row, int width, int height, int fill ) - { - addComponent( panel, component, gbc, column, row, width, height, fill ); - } - - public static void addFrameComponent( Container frameContentPane, Component component, int column, int row, int width, int height, int fill ) - { - addComponent( frameContentPane, component, column, row, width, height, 0, 0, fill ); - } - - public static void addFrameComponent( Container frameContentPane, Component component, int column, int row, int width, int height, double weightx, double weighty, int fill ) - { - addComponent( frameContentPane, component, column, row, width, height, weightx, weighty, fill ); - } - - private static void addComponent( Container container, Component component, int column, int row, int width, int height, double weightx, double weighty, int fill) - { - GridBagConstraints gbConstraints = new GridBagConstraints(); - gbConstraints.fill = fill; - - setConstraints( gbConstraints, column, row, width, height, weightx, weighty ); - - GridBagLayout layoutMgr = (GridBagLayout) container.getLayout(); - layoutMgr.setConstraints( component, gbConstraints ); - - container.add( component ); - } - - private static void addComponent( Container container, Component component, GridBagConstraints constraints, int column, int row, int width, int height, int fill) - { - GridBagConstraints gbConstraints = constraints; - gbConstraints.fill = fill; - - double weightx = gbConstraints.weightx; - double weighty = gbConstraints.weighty; - setConstraints( gbConstraints, column, row, width, height, weightx, weighty); - - GridBagLayout layoutMgr = (GridBagLayout) container.getLayout(); - layoutMgr.setConstraints( component, gbConstraints ); - - container.add( component ); - } - - private static void setConstraints( GridBagConstraints gbConstraints, int column, int row, int width, int height, double weightx, double weighty ) - { - gbConstraints.gridx = column; - gbConstraints.gridy = row; - gbConstraints.gridwidth = width; - gbConstraints.gridheight = height; - gbConstraints.weightx = weightx; - gbConstraints.weighty = weighty; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DatePanel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DatePanel.java deleted file mode 100644 index afc26d37ab..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DatePanel.java +++ /dev/null @@ -1,611 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 30, 2003 - * - */ -package ohd.hseb.util.gui; - -import ohd.hseb.db.DbTimeHelper; - -import javax.swing.*; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; - -public class DatePanel extends JPanel -{ - private TimePanel _timePanel = null; - - private int _month = 0; - private int _day = 0; - private int _year = 0; - private long _dateTimeLong = 0; - private boolean _leapYear = false; - - private JButton _upMonthButton = new JButton(); - private JButton _upDayButton = new JButton(); - private JButton _upYearButton = new JButton(); - - private JButton _downMonthButton = new JButton(); - private JButton _downDayButton = new JButton(); - private JButton _downYearButton = new JButton(); - - private JTextField _monthTextField = new JTextField( 6 ); - private JTextField _dayTextField = new JTextField( 3 ); - private JTextField _yearTextField = new JTextField( 4 ); - - private static Map _monthNamesMap = new HashMap(); - private static Map _dayMaxMap = new HashMap(); - - public DatePanel() - /******************** - Purpose: Empty Constructor - *********************/ - { - this( new Date().getTime() ); - } - - public DatePanel( long dateLong ) - /******************** - Purpose: Constructor with a long date value - *********************/ - { - int month, day, year; - - _dateTimeLong = dateLong; - - setupMonthNamesMap(); - - String date = DbTimeHelper.getDateStringFromLongTime( dateLong ); - - year = Integer.parseInt( date.substring( 0, 4 ) ); - month = Integer.parseInt( date.substring( 5, 7 ) ); - day = Integer.parseInt( date.substring( 8, 10 ) ); - - initDate( month, day, year ); - execute(); - } - - private void execute() - /******************** - Purpose: Main execution of the program - *********************/ - { - this.setLayout( new GridBagLayout() ); - - setupDayMaxMap(); - - initDateDisplay(); - - addListeners(); - setSize( 240, 150 ); - } - - private void initDateDisplay() - /******************** - Purpose: Initializes the GUI - *********************/ - { - _upYearButton.setIcon( getUpIcon() ); - _upMonthButton.setIcon( getUpIcon() ); - _upDayButton.setIcon( getUpIcon() ); - _downYearButton.setIcon( getDownIcon() ); - _downMonthButton.setIcon( getDownIcon() ); - _downDayButton.setIcon( getDownIcon() ); - - - - _upYearButton.setBackground( Color.WHITE ); - _upMonthButton.setBackground( Color.WHITE ); - _upDayButton.setBackground( Color.WHITE ); - _downYearButton.setBackground( Color.WHITE ); - _downMonthButton.setBackground( Color.WHITE ); - _downDayButton.setBackground( Color.WHITE ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _upYearButton, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upMonthButton, 10, 0, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upDayButton, 20, 0, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _yearTextField, 0, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _monthTextField, 10, 10, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _dayTextField, 20, 10, 5, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _downYearButton, 0, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downMonthButton, 10, 20, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downDayButton, 20, 20, 1, 1, GridBagConstraints.BOTH ); - } - - - private void initDate( int month, int day, int year ) - /******************** - Purpose: Initializes the date text fields and the month, day, year member variables - *********************/ - { - String dateTimeString = null; - - _monthTextField.setText( "" + _monthNamesMap.get( new Integer( month ) ) ); - _dayTextField.setText( "" + day ); - _yearTextField.setText( "" + year ); - _month = month; - _year = year; - _day = day; - if ( _timePanel != null ) - { - dateTimeString = _year + "-" + _month + "-" + _day + " " + _timePanel.getTimeString(); - _dateTimeLong = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - } - } - - public String getDateString() - { - return _year + "-" + _month + "-" + _day; - } - - - private void updateDate() - /******************** - Purpose: Updates the date/display by calling initDate - *********************/ - { - initDate( _month, _day, _year ); - if ( _timePanel != null ) - { - setDate( _dateTimeLong ); - } - } - - - private ImageIcon getUpIcon() - /******************** - Purpose: Returns the Up Arrow icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.UP_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - private ImageIcon getDownIcon() - /******************** - Purpose: Returns the Down Arrow icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.DOWN_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - private void addListeners() - /******************** - Purpose: Adds all of the listeners - *********************/ - { - // Listeners for the 6 buttons for the date - _upYearButton.addActionListener( new UpYearListener() ); - _upMonthButton.addActionListener( new UpMonthListener() ); - _upDayButton.addActionListener( new UpDayListener() ); - _downYearButton.addActionListener( new DownYearListener() ); - _downMonthButton.addActionListener( new DownMonthListener() ); - _downDayButton.addActionListener( new DownDayListener() ); - - // Listeners for the 3 date Text Fields - _yearTextField.addFocusListener( new YearTextFieldFocusListener() ); - _monthTextField.addFocusListener( new MonthTextFieldFocusListener() ); - _dayTextField.addFocusListener( new DayTextFieldFocusListener() ); - _yearTextField.addActionListener( new YearTextFieldListener() ); - _monthTextField.addActionListener( new MonthTextFieldListener() ); - _dayTextField.addActionListener( new DayTextFieldListener() ); - } - - private void updateDayTextField() - { - int inputDay = 0; - int maxDay = getDayMax(); - - validateLeapYear(); - - try - { - inputDay = Integer.parseInt( _dayTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputDay <= maxDay ) && ( inputDay > 0 ) ) - { - _day = inputDay; - } - updateDate(); - } - - private void updateYearTextField() - { - try - { - _year = Integer.parseInt( _yearTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - validateLeapYear(); // Sets _leapYear to true if it's a leapyear - validateDayValue(); - updateDate(); - } - - private void updateMonthTextField() - { - int inputMonth = 0; - - try - { - inputMonth = Integer.parseInt( _monthTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputMonth >= 1 ) && ( inputMonth <= 12 ) ) - { - _month = inputMonth; - validateLeapYear(); - validateDayValue(); - } - updateDate(); - } - - private class DayTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - public void focusLost(FocusEvent arg0) - { - updateDayTextField(); - } - } - - private class YearTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateYearTextField(); - } - } - - private class MonthTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateMonthTextField(); - } - - } - private class YearTextFieldListener implements ActionListener - /******************** - Purpose: Year text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateYearTextField(); - } - } - - private class MonthTextFieldListener implements ActionListener - /******************** - Purpose: Month text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateMonthTextField(); - } - } - - private class DayTextFieldListener implements ActionListener - /******************** - Purpose: Day text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateDayTextField(); - } - } - - - - - private class UpYearListener implements ActionListener - /******************** - Purpose: Up year button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - _year++; - - validateLeapYear(); // Sets _leapYear to true if it's a leapyear - validateDayValue(); - updateDate(); - } - } - - private class UpMonthListener implements ActionListener - /******************** - Purpose: Up month button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _month < 12 ) - { - _month++; - } - else - { - _month = 1; - } - validateDayValue(); - updateDate(); - } - } - - private class UpDayListener implements ActionListener - /******************** - Purpose: Up day button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _day < getDayMax() ) - { - _day++; - } - else - { - _day = 1; - } - updateDate(); - } - } - - private class DownYearListener implements ActionListener - /******************** - Purpose: Down year button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - // Need to make sure the year is still A.D. - if ( _year >= 1 ) - { - _year--; - } - validateLeapYear(); - validateDayValue(); - updateDate(); - } - } - - private class DownMonthListener implements ActionListener - /******************** - Purpose: Down month button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _month > 1 ) // Checks to see if the month is greater than 1 - { - _month--; - } - else - { - _month = 12; - } - validateDayValue(); - updateDate(); - } - } - - private class DownDayListener implements ActionListener - /******************** - Purpose: Down day button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - validateLeapYear(); - - if ( _day > 1 ) - { - _day--; - } - else - { - _day = getDayMax(); - } - updateDate(); - } - } - - private int getDayMax() - /******************** - Purpose: returns the maximum # of days for the particular month/year - *********************/ - { - String dayMaxString = null; - int dayMax = 0; - - dayMaxString = "" + _dayMaxMap.get( new Integer( _month ) ); - dayMax = Integer.parseInt( dayMaxString ); - - if ( _month == 2 ) - { - if ( _leapYear ) - { - dayMax++; // Adds 1 to the max day which is 28 - } - } - return dayMax; - } - - private void validateDayValue() - /******************** - Purpose: Sets a valid day value when the month is changed - *********************/ - { - int dayMax = getDayMax(); - - if ( _day > dayMax ) - { - _day = dayMax; - } - } - - private void validateLeapYear() - /******************** - Purpose: Determines if _year is a leap year - *********************/ - { - if ( _year % 4 == 0 ) // Checks if the year is divisible by 4 - { - _leapYear = true; - if ( _year % 400 == 0 ) // Checks if the year is divisible by 400 - { - _leapYear = true; - } - if ( ( _year % 100 == 0 ) && ( _year % 400 != 0 ) ) // Checks if the year is divisible by 100 - { // and not by 400. If true, then it is NOT a leap year - _leapYear = false; - } - } - else - { - _leapYear = false; - } - } - - private void setupMonthNamesMap() - /******************** - Purpose: Initialize _monthNamesMap - *********************/ - { - String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", - "September", "October", "November", "December" }; - - for ( int i = 1; i <= 12; i++ ) - { - _monthNamesMap.put( new Integer( i ), months[ i - 1 ] ); - } - } - - private void setupDayMaxMap() - /******************** - Purpose: Initialize _dayMaxMap - *********************/ - { - int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - - for ( int i = 1; i <= 12; i++ ) - { - _dayMaxMap.put( new Integer( i ), new Integer( days[ i - 1 ] ) ); - } - } - - protected long getDateLong() - /******************** - Purpose: Return a long value for the date - *********************/ - { - long dateTimeLong = 0; - String dateString = null; - String dateTimeString = null; - - dateString = _year + "-" + _month + "-" + _day; - - dateTimeString = dateString; - - dateTimeLong = DbTimeHelper.getLongTimeFromDateString( dateTimeString ); - - return dateTimeLong; - } - - public long getDateTimeLong() - /******************** - Purpose: Returns a long value for the date/time by calling getDateTimeLong from TimePanel - *********************/ - { - return _dateTimeLong; - } - - private long getInternalDateTimeLong() - { - return _dateTimeLong; - } - - - public void linkDateTime( TimePanel timePanel ) - /******************** - Purpose: Links the Date object with the Time object - *********************/ - { - _timePanel = timePanel; - if ( _timePanel.getDatePanel() != this ) - { - _timePanel.setTime( _dateTimeLong ); - _timePanel.linkDateTime( this ); - } - } - - public TimePanel getTimePanel() - /******************** - Purpose: returns the Time object - *********************/ - { - return _timePanel; - } - - public void setDate( long dateTimeLong, boolean recurse ) - { - int month, day, year; - - _dateTimeLong = dateTimeLong; - - setupMonthNamesMap(); - - String date = DbTimeHelper.getDateStringFromLongTime( dateTimeLong ); - - year = Integer.parseInt( date.substring( 0, 4 ) ); - month = Integer.parseInt( date.substring( 5, 7 ) ); - day = Integer.parseInt( date.substring( 8, 10 ) ); - - initDate( month, day, year ); - - if ( ( _timePanel != null ) && ( recurse ) ) - { - _timePanel.setTime( dateTimeLong ); - } - } - - public void setDate( long dateTimeLong ) - { - setDate( dateTimeLong, true ); - } - - public static void main( String[] args ) - { - Date date = new Date(); - DatePanel datetimeGUI = new DatePanel( date.getTime() ); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTextField.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTextField.java deleted file mode 100644 index 7fc66e03e0..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTextField.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Created on Nov 06, 2006 - * - * - */ -package ohd.hseb.util.gui; - - -import javax.swing.*; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Date; -import ohd.hseb.db.DbTimeHelper; - -/** - * @author VarmaR - * - * - */ -public class DateTextField extends JTextField -{ - private JFrame _parent = null; - private String _dialogTitle = null; - private boolean _allowOnlyEvenHours = false; - private String _missingRepresentation = null; - - // ---------------------------------------------------------------------------------------- - public DateTextField(long initialTime, JFrame parent, String dialogTitle, int columns, String missingRepresentation) - { - super(columns); - // this.setColumns(columns); - _parent = parent; - _dialogTitle = dialogTitle; - - setTime(initialTime); - - java.awt.Color backgroundColor = getBackground(); - - setEditable(false); - - setBackground(backgroundColor); - - addListeners(); - - _missingRepresentation = missingRepresentation; - } - // ---------------------------------------------------------------------------------------- - - public long getTime() - { - long time = DbTimeHelper.getLongTimeFromDateTimeString( this.getText() ); - return time; - } - // ---------------------------------------------------------------------------------------- - - public void setTime(long time) - { - if(time != 0) - { - String timeString = DbTimeHelper.getDateStringFromLongTime(time ); - this.setText(timeString); - } - else - { - this.setText("yyyy-mm-dd"); - } - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - - } - - - // ---------------------------------------------------------------------------------------- - private void addListeners() - { - this.addMouseListener(new TimeTextFieldListener()); - - } - - // ---------------------------------------------------------------------------------------- - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if (_missingRepresentation != null && ! _missingRepresentation.equals("") && !textField.getText().equals( "yyyy-mm-dd" ) && !textField.getText().equals( _missingRepresentation )) - { - dateTime = DbTimeHelper.getLongTimeFromDateString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - - DateTimeDialog dateTimeGUI = new DateTimeDialog( _parent, dateTime, _dialogTitle ); - dateTimeGUI.setDateOnly(); - dateTimeGUI.setAllowOnlyEvenHours(_allowOnlyEvenHours); - - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.setVisible(true); - } - } - - // ---------------------------------------------------------------------------------------- - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } - // ---------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeDialog.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeDialog.java deleted file mode 100644 index 46da9ef0c1..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeDialog.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Created on Oct 29, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 29, 2003 - * - */ -package ohd.hseb.util.gui; - -import javax.swing.*; -import java.awt.*; -import java.util.*; -import java.util.List; -import java.awt.event.*; - -public class DateTimeDialog extends JDialog -{ - private Container _frameContentPane = getContentPane(); - private JButton _setTimeButton = new JButton( "Apply" ); - private JButton _cancelButton = new JButton( "Cancel" ); - private TimePanel _timePanel = null; - private DatePanel _datePanel = null; - private List _dateTimeListenerList = new ArrayList(); - private JPanel _buttonPanel = new JPanel(); - - private boolean _allowOnlyEvenHours = false; - - private boolean _dateOnly = false; - - - public DateTimeDialog( JDialog owner, String frameTitle ) - { - this( owner, new Date().getTime(), frameTitle ); - } - - public DateTimeDialog( JDialog owner ) - { - this( owner, new Date().getTime(), "" ); - } - - - public DateTimeDialog( JDialog owner, long dateTimeLong, String frameTitle ) - { - super( owner, true ); - this.setTitle( "Date/Time Display - " + frameTitle ); - _datePanel = new DatePanel(); - _timePanel = new TimePanel(); - setupGUI(); - _datePanel.setDate( dateTimeLong ); - } - - public DateTimeDialog( Frame owner, String frameTitle ) - { - this( owner, new Date().getTime(), frameTitle ); - } - - public DateTimeDialog( Frame owner ) - { - this( owner, new Date().getTime(), "" ); - } - - public DateTimeDialog( Frame owner, long dateTimeLong, String frameTitle ) - { - super( owner, true ); - this.setTitle( "Date/Time Display - " + frameTitle ); - _datePanel = new DatePanel(); - _timePanel = new TimePanel(); - setupGUI(); - _datePanel.setDate( dateTimeLong ); - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - _timePanel.setAllowOnlyEvenHours(_allowOnlyEvenHours); - } - - public void setDateOnly() - { - _timePanel.setVisible( false ); - } - - private void setupGUI() - { - JPanel horizontalSeparatorPanel = new JPanel(); - - _frameContentPane.setLayout( new GridBagLayout() ); - _buttonPanel.setLayout( new GridBagLayout() ); - - _datePanel.linkDateTime( _timePanel ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _datePanel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _timePanel, 0, 2, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _buttonPanel, _setTimeButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _cancelButton, 2, 0, 2, 2, GridBagConstraints.BOTH ); - - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 3, 4, 2, GridBagConstraints.BOTH ); - - setSize( 270, 250 ); - - addListener(); - } - - public void addDateTimeEventListener( DateTimeEventListener dateTimeEventListener ) - { - _dateTimeListenerList.add( dateTimeEventListener ); - } - - private void notifyListeners( DateTimeEvent dateTimeEvent ) - { - for ( int i = 0; i < _dateTimeListenerList.size(); i++ ) - { - DateTimeEventListener listener = (DateTimeEventListener) _dateTimeListenerList.get( i ); - listener.dateTimeEntered( dateTimeEvent ); - } - } - - - private void addListener() - { - _setTimeButton.addActionListener( new SetTimeListener() ); - _cancelButton.addActionListener( new CancelListener() ); - } - - private class SetTimeListener implements ActionListener - /******************** - Purpose: - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - long dateTime = _datePanel.getDateTimeLong(); - - DateTimeEvent dateTimeEvent = new DateTimeEvent( dateTime, true ); - notifyListeners( dateTimeEvent ); - close(); - } - } - - private class CancelListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - long dateTime = _datePanel.getDateTimeLong(); - - DateTimeEvent dateTimeEvent = new DateTimeEvent( dateTime, false ); - notifyListeners( dateTimeEvent ); - close(); - } - } - - private void close() - { - this.dispose(); - } - - - public static void main(String[] args) - { - DateTimeDialog dateTimeGUI = new DateTimeDialog( new Frame(), new Date().getTime(), "Testing" ); - dateTimeGUI.show(); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeEvent.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeEvent.java deleted file mode 100644 index 3d7f05abf7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on Nov 6, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Nov 6, 2003 - * - */ -package ohd.hseb.util.gui; - -/** - * @author SoodG -*/ -public class DateTimeEvent -{ - private boolean _isGoodDate = false; - private long _dateTimeLong = 0; - - public DateTimeEvent() - { - } - - public DateTimeEvent( long dateTimeLong, boolean isGoodDate ) - { - _dateTimeLong = dateTimeLong; - _isGoodDate = isGoodDate; - } - - public void setGoodDate( boolean isGoodDate ) - { - _isGoodDate = isGoodDate; - } - - public boolean isGoodDate() - { - return _isGoodDate; - } - - public void setDateTimeLong( long dateTimeLong ) - { - _dateTimeLong = dateTimeLong; - } - - public long getDateTimeLong() - { - return _dateTimeLong; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeEventListener.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeEventListener.java deleted file mode 100644 index cdecd5dd1e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeEventListener.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Created on Nov 6, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Nov 6, 2003 - * - */ -package ohd.hseb.util.gui; - -public interface DateTimeEventListener -{ - void dateTimeEntered( DateTimeEvent event ); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeTextField.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeTextField.java deleted file mode 100644 index 2a81597b8d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DateTimeTextField.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Created on Apr 27, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import javax.swing.*; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Date; -import ohd.hseb.db.DbTimeHelper; - -/** - * @author GobsC - * - * - */ -public class DateTimeTextField extends JTextField -{ - private JFrame _parent = null; - private String _dialogTitle = null; - private boolean _allowOnlyEvenHours = false; - private boolean _limitTimeToMinutes = false; //defaults to seconds - - // ---------------------------------------------------------------------------------------- - public DateTimeTextField(long initialTime, JFrame parent, String dialogTitle, int columns) - { - this(initialTime, parent, dialogTitle, columns, false); - } - - public DateTimeTextField(long initialTime, JFrame parent, String dialogTitle, int columns, boolean limitTimeToMinutes) - { - super(columns); - // this.setColumns(columns); - _parent = parent; - _dialogTitle = dialogTitle; - - java.awt.Color backgroundColor = getBackground(); - - setEditable(false); - - setBackground(backgroundColor); - - setLimitTimeToMinutes(limitTimeToMinutes); - - setTime(initialTime); - - addListeners(); - } - - public void setLimitTimeToMinutes(boolean limitTimeToMinutes) - { - _limitTimeToMinutes = limitTimeToMinutes; - } - // ---------------------------------------------------------------------------------------- - - public long getTime() - { - long time = 0; - - if (_limitTimeToMinutes) - { - time = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(this.getText() ); - } - else - { - time = DbTimeHelper.getLongTimeFromDateTimeString( this.getText() ); - } - return time; - } - // ---------------------------------------------------------------------------------------- - - public void setTime(long time) - { - String timeString = null; - - if (_limitTimeToMinutes) //date time string limited to minutes - { - timeString = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - } - else //normal date time string - { - timeString = DbTimeHelper.getDateTimeStringFromLongTime(time ); - } - this.setText(timeString); - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - - } - - - // ---------------------------------------------------------------------------------------- - private void addListeners() - { - this.addMouseListener(new TimeTextFieldListener()); - - } - - // ---------------------------------------------------------------------------------------- - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - String text = textField.getText(); - - if ( ! text.equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - if ( _limitTimeToMinutes) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(text); - } - else - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString(text); - } - } - else - { - dateTime = new Date().getTime(); - } - - DateTimeDialog dateTimeGUI = new DateTimeDialog( _parent, dateTime, _dialogTitle ); - dateTimeGUI.setAllowOnlyEvenHours(_allowOnlyEvenHours); - - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.setVisible(true); - } - } - - // ---------------------------------------------------------------------------------------- - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = null; - - if (_limitTimeToMinutes) - { - timeString = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(dateTimeEvent.getDateTimeLong() ); - } - else //normal, full Year to seconds string - { - timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - - } - - _timeTextField.setText( timeString ); - } - } - } - // ---------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DialogHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DialogHelper.java deleted file mode 100644 index 06f6ccf854..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/DialogHelper.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Created on Mar 16, 2004 - * - * - */ -package ohd.hseb.util.gui; - - - -import java.awt.*; - -import javax.swing.JFrame; -import javax.swing.JOptionPane; - -/** - * @author GobsC - * - * This is a simple class with static methods to make it - * easy to display error and message dialogs. - */ -public class DialogHelper -{ - - - // ----------------------------------------------------------------------------------------- - - - public static boolean displayConfirmDialog(Window parent, String message, String dialogTitle) - { - int choice = 0; - boolean confirm = false; - - choice = JOptionPane.showConfirmDialog( parent, message, dialogTitle, - JOptionPane.YES_NO_OPTION, - JOptionPane.WARNING_MESSAGE ); - - if ( choice == JOptionPane.YES_OPTION ) - { - confirm = true; - } - - return confirm; - } - - // ----------------------------------------------------------------------------------------- - - public static void displayErrorDialog(Window parent, String message, String dialogTitle) - { - - int dialogType = JOptionPane.ERROR_MESSAGE; - - JOptionPane.showMessageDialog(parent, message, dialogTitle, dialogType); - } - - // ----------------------------------------------------------------------------------------- - - public static void displayMessageDialog(Window parent, String message, String dialogTitle) - { - - int dialogType = JOptionPane.INFORMATION_MESSAGE; - - JOptionPane.showMessageDialog(parent, message, dialogTitle, dialogType); - } - - // ----------------------------------------------------------------------------------------- - - public static void displayMessageDialog(Window parent, String message) - { - - JOptionPane.showMessageDialog(parent, message); - } - - // ----------------------------------------------------------------------------------------- - - public static void setWaitCursor(JFrame frame) - { - Container c = frame.getContentPane(); // get the window's content pane - setWaitCursor(c); - //c.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - - } - - public static void setDefaultCursor(JFrame frame) - { - Container c = frame.getContentPane(); // get the window's content pane - setDefaultCursor(c); - // c.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - - } - - public static void setWaitCursor(Container container) - { - container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - - } - - public static void setDefaultCursor(Container container) - { - container.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - -} //end class DialogHelper diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ExtensionFileFilter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ExtensionFileFilter.java deleted file mode 100644 index 2d4981c1c8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ExtensionFileFilter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Created on Jun 16, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 16, 2004 - * - */ -package ohd.hseb.util.gui; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.filechooser.FileFilter; - -/** - * @author SoodG -*/ -public class ExtensionFileFilter extends FileFilter -{ - private List _extensionList = new ArrayList(); - private String _extensionDescription = null; - - public ExtensionFileFilter( List extList, String extensionDescription ) - { - _extensionList = extList; - _extensionDescription = extensionDescription; - } - - public boolean accept( File f ) - { - boolean returnValue = false; - - if ( f.isDirectory() ) - { - returnValue = true; - } - else - { - String extension = getExtension( f ); - - if ( extension != null ) - { - if ( extensionValid( extension ) ) - { - returnValue = true; - } - else - { - returnValue = false; - } - } - } - return returnValue; - } - - private boolean extensionValid( String extension ) - { - boolean isEquals = false; - - for ( int i = 0; i < _extensionList.size(); i++ ) - { - String ext = (String) _extensionList.get( i ); - if( ext.equalsIgnoreCase( extension ) ) - { - isEquals = true; - } - } - return isEquals; - } - - public static String getExtension( File f ) - { - String ext = null; - if ( f != null ) - { - String s = f.getName(); - int i = s.lastIndexOf('.'); - - if (i > 0 && i < s.length() - 1) - { - ext = s.substring(i+1).toLowerCase(); - } - } - return ext; - } - - - public String getDescription() - { - return _extensionDescription; - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/FontHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/FontHelper.java deleted file mode 100644 index 33a9ed5034..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/FontHelper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Created on Jul 20, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.awt.Graphics; -import java.awt.Font; - -/** - * @author GobsC - * - * - */ -public class FontHelper -{ - Font _font = null; - - public FontHelper(Font font) - { - - _font = font; - } - - public int getWidth(Graphics g, String textString) - { - int totalWidth = g.getFontMetrics(_font).stringWidth(textString); - - return totalWidth; - } - - public int getHeight(Graphics g) - { - int height = g.getFontMetrics(_font).getHeight(); - - return height; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/FrameCloseWindowListener.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/FrameCloseWindowListener.java deleted file mode 100644 index b110b46332..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/FrameCloseWindowListener.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JFrame; - - -public class FrameCloseWindowListener extends WindowAdapter -{ - - - - private JFrame _frame = null; - - public FrameCloseWindowListener(JFrame frame) - { - _frame = frame; - } - - public void windowClosing(WindowEvent evt) - { - _frame.dispose(); - } - - public static void addFrameCloseWindowListener(JFrame frame) - { - FrameCloseWindowListener listener = new FrameCloseWindowListener(frame); - - frame.addWindowListener(listener); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ItemsSelectionDialog.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ItemsSelectionDialog.java deleted file mode 100644 index ac395886f5..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/ItemsSelectionDialog.java +++ /dev/null @@ -1,760 +0,0 @@ -package ohd.hseb.util.gui; - -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import java.awt.*; -import java.awt.event.*; - - -import javax.swing.*; - - -/** - * @author RajaramV - * @modifiedBy CGobs - */ -public class ItemsSelectionDialog extends JDialog -{ - private String _selectedItems[]; - private String _allowedItems[]; - private String _orgSelectedItems[]; - private boolean _isSelectionCancelled = false; - private JList _allowedItemsJList; - private JList _selectedItemsJList; - private Container _container; - private JButton _addButton; - private JButton _removeButton ; - private JButton _applyButton ; - private JButton _moveUpButton; - private JButton _moveDownButton; - private JButton _closeButton; - private JLabel _allowedColLabel ; - private JLabel _selectedColLabel ; - private String _stringForPrototypeCellValue; - private String[] _newItemsAfterAdditionOrRemoval; - private boolean _isAnyItemSelectedForMovedUpOrDown = false; - - - //------------------------------------------------------------------------------------------------------------ - - public ItemsSelectionDialog(JFrame owner,String title, String[] itemsAllowed, - String[] itemsToBePresentInSelectedList) - { - super(owner, true); - _allowedItems=itemsAllowed; - Arrays.sort(_allowedItems, 0, _allowedItems.length); - - _selectedItems = itemsToBePresentInSelectedList; - _orgSelectedItems = _selectedItems; - setStringForPrototypeCellValue(); - if(title == null) - this.setTitle("Items Selection Dialog"); - else - this.setTitle(title); - initGui(); - } - - //------------------------------------------------------------------------------------------------------------ - - private void setStringForPrototypeCellValue() - { - String string = null; - if( _allowedItems.length > 0 ) - { - string = _allowedItems[0]; - for(int i = 1; i < _allowedItems.length; i++) - { - if ( _allowedItems[i].length() > string.length()) - string = _allowedItems[i]; - } - } - _stringForPrototypeCellValue = string; - } - - //------------------------------------------------------------------------------------------------------------ - - private void initGui() - { - - _container = getContentPane(); - _container.setLayout(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - _container.setPreferredSize(new Dimension(490, 490)); - - //create the top part of the gui - JPanel mainPanel = initMainPanel(); - - //add bottom button panel - _applyButton = new JButton("Apply"); - _closeButton = new JButton("Close"); - - JPanel buttonPanel = new JPanel(); - buttonPanel.add(_applyButton); - buttonPanel.add(_closeButton); - - /* col, row, width, height, weightx weighty fill(opt) */ - addComponent(_container, mainPanel, gbc, 0, 0, 4, 10, 1, 1, 1); - addComponent(_container, buttonPanel, gbc, 0, 10, 4, 1, 0, 0); - - - if(_isAnyItemSelectedForMovedUpOrDown) - { - _selectedItemsJList.clearSelection(); - _isAnyItemSelectedForMovedUpOrDown = false; - } - - // mainPanel.addComponentListener(new WindowResizeListener(mainPanel)); - - addListeners(); - - _newItemsAfterAdditionOrRemoval = new String[_selectedItems.length]; - System.arraycopy(_selectedItems, 0, _newItemsAfterAdditionOrRemoval, 0, _selectedItems.length); - this.pack(); - this.setVisible(true); - } - - //------------------------------------------------------------------------------------------------------------ - private JButton initArrowButton(String iconType) - { - Dimension dimension = new Dimension(15, 20); - - Color buttonColor = this.getBackground(); - Color imageColor = Color.BLUE; - - ImageIcon arrowIcon = StandardImageIcons.getImageIcon(iconType, - imageColor, buttonColor, dimension); - - - JButton button = new JButton(arrowIcon); - - button.setPreferredSize(dimension); - - return button; - - } - - //------------------------------------------------------------------------------------------------------------ - - private JPanel initMainPanel() - { - final int visibleRowCount = 30; - - JPanel mainPanel = new JPanel(); - mainPanel.setLayout(new GridBagLayout()); - //mainPanel.setBackground(Color.RED); - - GridBagConstraints gbc = new GridBagConstraints(); - - _addButton = new JButton("Add >>"); - _removeButton = new JButton("Remove <<"); - - _moveUpButton = initArrowButton(StandardImageIcons.UP_ARROW); - _moveDownButton = initArrowButton(StandardImageIcons.DOWN_ARROW); - - //set tooltips - _moveUpButton.setToolTipText("Move selected items up in the list."); - _moveDownButton.setToolTipText("Move selected items down in the list."); - - - // _moveUpButton = new JButton("^"); - // _moveDownButton = new JButton("v"); - - _allowedColLabel = new JLabel("Allowed Items"); - _selectedColLabel = new JLabel("Selected Items"); - - _allowedItemsJList = new JList(_allowedItems); - _allowedItemsJList.setVisibleRowCount(visibleRowCount); - _allowedItemsJList.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - if(_stringForPrototypeCellValue.length() < ("Allowed Items").length()) - { - _allowedItemsJList.setPrototypeCellValue(("Allowed Items")); - } - _allowedItemsJList.setAutoscrolls(true); - - JPanel allowedListPanel = new JPanel(); - JScrollPane allowedScrollPane = new JScrollPane(_allowedItemsJList); - allowedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - allowedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - allowedListPanel.setLayout(new GridLayout(1,1)); - allowedListPanel.add(allowedScrollPane); - - - if(_selectedItems !=null) - _selectedItemsJList = new JList(_selectedItems); - else - _selectedItemsJList = new JList(); - - _selectedItemsJList.setVisibleRowCount(visibleRowCount); - _selectedItemsJList.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - if(_stringForPrototypeCellValue.length() < ("Selected Items").length()) - { - _selectedItemsJList.setPrototypeCellValue(("Selected Items")); - } - _selectedItemsJList.setAutoscrolls(true); - - JPanel selectedListPanel = new JPanel(); - JScrollPane selectedScrollPane = new JScrollPane(_selectedItemsJList); - selectedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - selectedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - selectedListPanel.setLayout(new GridLayout(1,1)); - selectedListPanel.add(selectedScrollPane); - - - JPanel addAndRemoveButtonPanel = new JPanel(); - // addandRemoveButtonsPanel.setLayout(new GridLayout(2,1,15,15)); - - // addAndRemoveButtonPanel.setBackground(Color.PINK); - addAndRemoveButtonPanel.setLayout(new GridLayout(2, 1, 0, 15)); - addAndRemoveButtonPanel.add(_addButton); - addAndRemoveButtonPanel.add(_removeButton); - - JPanel moveButtonsPanel = new JPanel(); - moveButtonsPanel.setLayout(new GridLayout(2, 1, 0, 15)); - moveButtonsPanel.add(_moveUpButton); - moveButtonsPanel.add(_moveDownButton); - - JPanel verticalFillerPanel = new JPanel(); - verticalFillerPanel.setPreferredSize(new Dimension(50, 50)); - // verticalFillerPanel.setBackground(Color.BLUE); - - JPanel verticalFillerPanel2 = new JPanel(); - verticalFillerPanel2.setPreferredSize(new Dimension(50, 50)); - // verticalFillerPanel2.setBackground(Color.GREEN); - - gbc.insets = new Insets(5,5,5,5); - /* col, row, width, height, weightx weighty fill(opt) */ - - addComponent(mainPanel, _allowedColLabel, gbc, 1, 0, 1, 1, 0, 0); - addComponent(mainPanel, allowedListPanel, gbc, 1, 1, 1, 5, 1, 1, 1); - addComponent(mainPanel, addAndRemoveButtonPanel, gbc, - 2, 3, 1, 1, 0, 0); - - addComponent(mainPanel, verticalFillerPanel, gbc, 2, 0, 1, 2, 0, 1, 1); - addComponent(mainPanel, verticalFillerPanel2, gbc, 2, 3, 1, 2, 0, 1, 1); - - - addComponent(mainPanel, _selectedColLabel, gbc, 3, 0, 1, 1, 0, 0); - addComponent(mainPanel, selectedListPanel, gbc, 3, 1, 1, 5, 1, 1, 1); - - addComponent(mainPanel, moveButtonsPanel, gbc, 4, 3, 1, 1, 0, 0); - - - return mainPanel; - - } - - //------------------------------------------------------------------------------------------------------------ - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - addComponent(container, component, gbc, column, row, columnCells, rowCells, weightX, weightY, 0); - } - - //------------------------------------------------------------------------------------------------------------ - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY, int fill) - { - -// how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - -// what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - -// the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - gbc.fill = fill; - - container.add(component, gbc); - - return; - } - - //------------------------------------------------------------------------------------------------------------ - - - private void addListeners() - { - _addButton.addActionListener( new AddButtonListener()); - _removeButton.addActionListener(new RemoveButtonListener()); - _closeButton.addActionListener(new CloseButtonListener()); - _moveUpButton.addActionListener(new MoveUpButtonListener()); - _moveDownButton.addActionListener(new MoveDownButtonListener()); - - _applyButton.addActionListener(new ConfirmSelectionButtonListener()); - - //allows user to remove items with the delete or backspace keys - _selectedItemsJList.addKeyListener(new SelectedListKeyListener()); - _selectedItemsJList.addMouseListener(new DoubleClickOnSelectedListener()); - - _allowedItemsJList.addKeyListener(new AllowedListKeyListener()); - _allowedItemsJList.addMouseListener(new DoubleClickOnAllowedListener()); - return; - } - - // ------------------------------------------------------------------------------------------------------------ - public String[] getSelectedItems() - { - String [] returnedSelectedItems = null ; - if(!_isSelectionCancelled) - { - if(_selectedItems != null) - { - returnedSelectedItems = new String[_selectedItems.length]; - - System.arraycopy(_selectedItems, 0, - returnedSelectedItems, 0, - _selectedItems.length ); - } - } - else - { - returnedSelectedItems = _orgSelectedItems; - } - return returnedSelectedItems; - } - - // ------------------------------------------------------------------------------------------------------------ - private class DoubleClickOnAllowedListener extends MouseAdapter - { - public void mouseClicked(MouseEvent e) - { - if( e.getClickCount() == 2) - { - addSelectedItems(); - } - - } - - } - - // ------------------------------------------------------------------------------------------------------------ - - private class DoubleClickOnSelectedListener extends MouseAdapter - { - public void mouseClicked(MouseEvent e) - { - if( e.getClickCount() == 2) - { - removeSelectedItems(); - } - - } - - } - - private class AddButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - addSelectedItems(); - } - } - // ------------------------------------------------------------------------------------------------------------ - - private class CloseButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _isSelectionCancelled = true; - closeItemsSelectionDialog(); - } - } - // ------------------------------------------------------------------------------------------------------------ - private void addSelectedItems() - { - int[] indicesOfNewItemsSelectedFromAllowedList =_allowedItemsJList.getSelectedIndices(); - int numOfNewItemsSelectedFromAllowedList = indicesOfNewItemsSelectedFromAllowedList.length; - int numOfExistingItemsInNewList = _selectedItemsJList.getModel().getSize(); - - // All the items in allowed list are already present in new List - if(numOfExistingItemsInNewList == _allowedItemsJList.getModel().getSize()) - { - - } - //New List is empty, so add all the item selected from allowed list - else if (numOfExistingItemsInNewList == 0) - { - _selectedItemsJList.setListData(_allowedItemsJList.getSelectedValues()); - } - else //Compare existing new list and items newly selected from allowed list for any match then add - { - int cntOfSameItems=0; - for(int i =0; i< numOfNewItemsSelectedFromAllowedList; i++) - { - int index = indicesOfNewItemsSelectedFromAllowedList[i]; - String itemFromAllowed = _allowedItemsJList.getModel().getElementAt(index).toString(); - for(int j = 0; j < numOfExistingItemsInNewList; j++) - { - String itemFromExistingNewList = _selectedItemsJList.getModel().getElementAt(j).toString(); - if(itemFromExistingNewList.compareTo(itemFromAllowed) == 0) - { - cntOfSameItems++; - } - } - } - - - int numOfFinalItemsAfterAddition = (numOfNewItemsSelectedFromAllowedList + - numOfExistingItemsInNewList) - cntOfSameItems; - - _newItemsAfterAdditionOrRemoval = new String[numOfFinalItemsAfterAddition]; - - int cnt=0; - for(cnt=0; cnt=0; j--) - { - int indexInBlock = new Integer(blockList.get(j).toString()).intValue(); - String temp = finalSelectedItems[indexInBlock+1] ; - finalSelectedItems[indexInBlock+1] = finalSelectedItems[indexInBlock]; - finalSelectedItems[indexInBlock] = temp; - } - } - } - System.arraycopy(finalSelectedItems, 0, _newItemsAfterAdditionOrRemoval, 0, _newItemsAfterAdditionOrRemoval.length); - System.arraycopy(finalSelectedItems, 0, _selectedItems, 0, _selectedItems.length); - - _selectedItemsJList.setListData(_selectedItems); - - } - // ------------------------------------------------------------------------------------------------------------ - - private void closeItemsSelectionDialog() - { - this.dispose(); - } - - // ------------------------------------------------------------------------------------------------------------ - - private class ConfirmSelectionButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - setFinalSelectedItemsArray(); - closeItemsSelectionDialog(); - } - } - // ------------------------------------------------------------------------------------------------------------ - - private class SelectedListKeyListener implements KeyListener - { - public void keyPressed(KeyEvent e) - { - int keyCode = e.getKeyCode(); - - if ( ( keyCode == KeyEvent.VK_DELETE) || (keyCode == KeyEvent.VK_BACK_SPACE) ) - { - removeSelectedItems(); - } - - } - - public void keyReleased(KeyEvent e) - { - - } - - public void keyTyped(KeyEvent e) - { - - - } - } - - - // ------------------------------------------------------------------------------------------------------------ - private class AllowedListKeyListener implements KeyListener - { - public void keyPressed(KeyEvent e) - { - int keyCode = e.getKeyCode(); - - if (keyCode == KeyEvent.VK_ENTER) - { - addSelectedItems(); - } - } - - public void keyReleased(KeyEvent e) - { - - } - - public void keyTyped(KeyEvent e) - { - - } - } - - - // ------------------------------------------------------------------------------------------------------------ - - private static String[] initBigItemsArray(int count) - { - String [] itemStringArray = new String[count]; - - for (int i = 0; i < count; i++) - { - itemStringArray[i] = "Item" + i; - } - - return itemStringArray; - } - // ------------------------------------------------------------------------------------------------------------ - - public static void main(String[] args) - { - JFrame frame = new JFrame(); - - frame.setSize(new Dimension(250, 250)); - frame.setVisible(true); - - FrameCloseWindowListener.addFrameCloseWindowListener(frame); - - String titleString = "Test ColumnSelection"; - - String[] initialSelectedList = {"Item2", "Item4"}; - - String[] bigItemsAllowed = initBigItemsArray(100); - - new ItemsSelectionDialog(frame, titleString, bigItemsAllowed, initialSelectedList); - - frame.dispose(); - - } -} - -// ------------------------------------------------------------------------------------ - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledComboBox.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledComboBox.java deleted file mode 100644 index 568979c366..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledComboBox.java +++ /dev/null @@ -1,236 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionListener; -import java.awt.event.MouseWheelListener; -import java.util.List; - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import ohd.hseb.util.gui.ComponentHelper; - -public class LabeledComboBox extends JPanel -{ - private JLabel _label = new JLabel(); - private JComboBox _comboBox = new JComboBox(); - private GridBagConstraints _gbLabelConstraints = new GridBagConstraints(); - private GridBagConstraints _gbTFConstraints = new GridBagConstraints(); - - public LabeledComboBox() - { - setupConstraints(); - setupComponents(); - } - - public LabeledComboBox( String labelText ) - { - this(); - setLabel( labelText ); - } - - public LabeledComboBox( String labelText, String[] comboBoxStringArray ) - { - this(); - setLabel( labelText ); - setComboBox( comboBoxStringArray ); - } - - public LabeledComboBox( String labelText, String tooltip ) - { - this(); - setLabel( labelText ); - _comboBox.setToolTipText( tooltip ); - } - - public LabeledComboBox( String labelText, List comboBoxStringList ) - { - this(); - setLabel( labelText ); - setComboBox( comboBoxStringList ); - } - - public LabeledComboBox( String labelText, String[] comboBoxStringArray, String toolTipText ) - { - this( labelText, comboBoxStringArray ); - setToolTipText( toolTipText ); - } - - public LabeledComboBox( String labelText, List comboBoxStringList, String toolTipText ) - { - this( labelText, comboBoxStringList ); - setToolTipText( toolTipText ); - } - - private void setupComponents() - { - this.setLayout( new GridBagLayout() ); -// _label.setPreferredSize( new Dimension( 150, 15 ) ); -// _comboBox.setPreferredSize( new Dimension( 150, 15 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _label, _gbLabelConstraints, 0, 0, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addPanelComponent( this, _comboBox, _gbTFConstraints, 1, 0, 1, 1, GridBagConstraints.VERTICAL ); - } - - public String toString() - { - return "Label = " + _label.getText() + " | ComboBox = " + (String) _comboBox.getSelectedItem(); - } - - private void setupConstraints() - { - _gbLabelConstraints.anchor = GridBagConstraints.EAST; - _gbLabelConstraints.weightx = 1; - _gbLabelConstraints.weighty = 1; - - _gbTFConstraints.anchor = GridBagConstraints.WEST; - _gbTFConstraints.weightx = 1; - _gbTFConstraints.weighty = 1; - } - - public void setLabelPreferredSize( Dimension dimension ) - { - _label.setPreferredSize( dimension ); - } - - public void setComboBoxPreferredSize( Dimension dimension ) - { - _comboBox.setPreferredSize( dimension ); - } - - public void setLabel( String labelString ) - { - _label.setText( labelString ); - } - - public String getLabel() - { - return _label.getText(); - } - - public void setComboBox( JComboBox comboBox ) - { - _comboBox = comboBox; - } - - public void setComboBoxFromStringArray( Object[] comboBoxStringArray ) - { - String comboBoxString = null; - - for ( int i = 0; i < comboBoxStringArray.length;i++ ) - { - comboBoxString = (String) comboBoxStringArray[ i ]; - _comboBox.addItem( comboBoxString ); - } - } - - public void setComboBox( String[] comboBoxStringArray ) - { - for ( int i = 0; i < comboBoxStringArray.length; i++ ) - { - _comboBox.addItem( comboBoxStringArray[ i ] ); - } - } - - public void setComboBox( List comboBoxStringList ) - { - String comboBoxString = null; - _comboBox.removeAllItems(); - - for ( int i = 0; i < comboBoxStringList.size(); i++ ) - { - comboBoxString = (String) comboBoxStringList.get( i ); - _comboBox.addItem( comboBoxString ); - } - } - - public JComboBox getComboBox() - { - return _comboBox; - } - - public String getSelectedCBItem() - { - return ( (String) _comboBox.getSelectedItem() ); - } - - public void setToolTip( String toolTipText ) - { - _label.setToolTipText( toolTipText ); - } - - public void enableComboBox( boolean enable ) - { - _comboBox.setEnabled( enable ); - } - - public void enableLabel( boolean enable ) - { - _label.setEnabled( enable ); - } - - public void setEditComboBox( boolean editable ) - { - _comboBox.setEditable( editable ); - } - - public void setSelectedItem( Object object ) - { - _comboBox.setSelectedItem( object ); - } - - public void setSelectedIndex( int index ) - { - _comboBox.setSelectedIndex( index ); - } - - public int getSelectedIndex() - { - return _comboBox.getSelectedIndex(); - } - - public int getItemCount() - { - return _comboBox.getItemCount(); - } - - public Object getSelectedItem() - { - return _comboBox.getSelectedItem(); - } - - public void enableLabeledTextField( boolean enable ) - { - enableComboBox( enable ); - enableLabel( enable ); - } - - public void setLabelFont( Font font ) - { - _label.setFont( font ); - } - - public void setComboBoxFont( Font font ) - { - _comboBox.setFont( font ); - } - - public void addComboBoxActionListener( ActionListener actionListener ) - { - _comboBox.addActionListener( actionListener ); - } - - public void addComboBoxWheelListener( MouseWheelListener wheelListener ) - { - _comboBox.addMouseWheelListener( wheelListener ); - } - - public void removeComboBoxActionListener( ActionListener actionListener ) - { - _comboBox.removeActionListener( actionListener ); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledSlider.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledSlider.java deleted file mode 100644 index a72bbbea53..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledSlider.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Created on Nov 16, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.text.DecimalFormat; -import java.text.NumberFormat; - -import javax.swing.BoundedRangeModel; -import javax.swing.DefaultBoundedRangeModel; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeListener; - -import ohd.hseb.util.MathHelper; - -/** - * @author GobsC - * - * - */ -public class LabeledSlider extends JPanel -{ - - private JSlider _slider = null; - private JLabel _label = null; - private JLabel _valueLabel = null; - - - private double _initialModelValue = 0.0; - private double _minModelValue = 0.0; - private double _maxModelValue = 1.0; - - private int _sliderMin = 0; - private int _sliderMax = 100; - - private NumberFormat _numberFormat = new DecimalFormat("###.00"); - - -// ---------------------------------------------------------------------------- - - public LabeledSlider(String labelString, - double initialModelValue, - double minModelValue, - double maxModelValue, - int width, - int height) - { - - //set the private data member variables - - _label = new JLabel(labelString); - - _initialModelValue = initialModelValue; - _minModelValue = minModelValue; - _maxModelValue = maxModelValue; - - - //initialize the private gui variables - - int initialSliderValue = getSliderValueFromModelValue(initialModelValue); - _valueLabel = new JLabel(getSliderValueLabelString(initialModelValue)); - - BoundedRangeModel boundedRangeModel = new DefaultBoundedRangeModel(); - boundedRangeModel.setMinimum(_sliderMin); - boundedRangeModel.setMaximum(_sliderMax); - boundedRangeModel.setValue(initialSliderValue); - _slider = new JSlider(boundedRangeModel); - - //add gui elements - this.add(_label); - this.add(_slider); - this.add(_valueLabel); - - this.setSize(width, height); - - - } - - // ---------------------------------------------------------------------------- - public double getModelValue() - { - return getModelValueFromSliderValue(_slider.getValue()); - } - // ---------------------------------------------------------------------------- - - public void setModelValue(double modelValue) - { - int sliderValue = getSliderValueFromModelValue(modelValue); - - _slider.setValue(sliderValue); - - updateValueLabel(); - - } - - -// ---------------------------------------------------------------------------- - public void addChangeListener(ChangeListener listener) - { - - _slider.addChangeListener(listener); - - return; - } -// ---------------------------------------------------------------------------- - - - private int getSliderValueFromModelValue(double modelValue) - { - double modelRange = _maxModelValue - _minModelValue; - double sliderRange = _sliderMax - _sliderMin; - - double modelDiff = modelValue - _minModelValue; - double modelFraction = modelDiff / modelRange; - - double sliderDoubleValue = _sliderMin + (modelFraction * sliderRange); - - return (int) Math.round(sliderDoubleValue); - } - -// ---------------------------------------------------------------------------- - - - private double getModelValueFromSliderValue(int sliderValue) - { - - double modelRange = _maxModelValue - _minModelValue; - double sliderRange = _sliderMax - _sliderMin; - - double sliderDiff = sliderValue - _sliderMin; - double sliderFraction = sliderDiff / sliderRange; - - double modelValue = _minModelValue + (sliderFraction * modelRange); - - modelValue = MathHelper.roundToNDecimalPlaces(modelValue, 2); - - return modelValue; - } - // ---------------------------------------------------------------------------- - - private String getSliderValueLabelString(double modelValue) - { - String modelValueString = _numberFormat.format(modelValue); - modelValueString = padToNChars(modelValueString, 6); - - String maxModelValueString = _numberFormat.format(_maxModelValue); - maxModelValueString = padToNChars(maxModelValueString, 6); - - String stringValue = modelValueString + "| max = " + maxModelValueString; - return stringValue; - } - - // ---------------------------------------------------------------------------- - - private String padToNChars(String originalString, int charCount) - { - String newString = originalString; - int length = originalString.length() ; - if (length < charCount) - { - int diff = charCount - length; - StringBuffer buffer = new StringBuffer(originalString); - for (int i = 0; i < diff; i++) - { - buffer.insert(0, ' '); - } - newString = buffer.toString(); - } - - return newString; - } - // ---------------------------------------------------------------------------- - /** - * @param slider The slider to set. - */ - private void setSlider(JSlider slider) - { - _slider = slider; - } - -// ---------------------------------------------------------------------------- - - /** - * @return Returns the slider. - */ - private JSlider getSlider() - { - return _slider; - } - -// ---------------------------------------------------------------------------- - - /** - * @param sliderLabel The sliderLabel to set. - */ - private void setLabel(JLabel label) - { - _label = label; - } - -// ---------------------------------------------------------------------------- - - /** - * @return Returns the sliderLabel. - */ - private JLabel getLabel() - { - return _label; - } - -// ---------------------------------------------------------------------------- - - /** - * @param sliderValueLabel The sliderValueLabel to set. - */ - private void setValueLabel(JLabel valueLabel) - { - _valueLabel = valueLabel; - } -// ---------------------------------------------------------------------------- - private void updateValueLabel() - { - String labelString = getSliderValueLabelString(getModelValue()); - _valueLabel.setText(labelString); - } -// ---------------------------------------------------------------------------- - - /** - * @return Returns the sliderValueLabel. - */ - private JLabel getValueLabel() - { - return _valueLabel; - } -// ---------------------------------------------------------------------------- - - - - /* - private class LabeledSliderChangeListener implements ChangeListener - { - public void stateChanged(ChangeEvent e) - { - double newValue = getModelValueFromSliderValue(getSlider().getValue()); - _valueLabel.setText(getSliderValueLabelString(newValue)); - - _streamModel.setLztwc(newValue); - notifyListeners("LZTWC changed"); - } - } - */ -// ---------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledTextField.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledTextField.java deleted file mode 100644 index 36cd7f32f0..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/LabeledTextField.java +++ /dev/null @@ -1,215 +0,0 @@ -package ohd.hseb.util.gui; - -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.KeyListener; -import java.awt.event.MouseListener; -import java.util.EventListener; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.gui.ComponentHelper; - -public class LabeledTextField extends JPanel -{ - private JLabel _label = new JLabel(); - private JTextField _textField = new JTextField(); - private GridBagConstraints _gbLabelConstraints = new GridBagConstraints(); - private GridBagConstraints _gbTFConstraints = new GridBagConstraints(); - - public LabeledTextField() - { -// setPreferredSize( new Dimension( 240, 15 ) ); - setupConstraints(); - setupComponents(); -// this.setBackground( Color.YELLOW ); - } - - public LabeledTextField( String labelText, String textFieldText, int textFieldWidthInColumns ) - { - this(); - setLabel( labelText ); - setTextField( textFieldText ); - setTextFieldWidth( textFieldWidthInColumns ); - } - - public LabeledTextField( String labelText, String textFieldText, String toolTipText, int textFieldWidthInColumns ) - { - this(); - setLabel( labelText ); - setTextField( textFieldText ); - setTextFieldWidth( textFieldWidthInColumns ); - setToolTipText( toolTipText ); - _label.setToolTipText( toolTipText ); - _textField.setToolTipText( toolTipText); - } - - private void setupComponents() - { -// this.setLayout( new FlowLayout( FlowLayout.LEFT ) ); - setLayout( new GridBagLayout() );; -// _label.setPreferredSize( new Dimension( 120, 15 ) ); -// _label.setMaximumSize( new Dimension( 100, 15 ) ); -// _textField.setPreferredSize( new Dimension( 120, 15 ) ); -// _textField.setMaximumSize( new Dimension( 100, 15 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _label, _gbLabelConstraints, 0, 0, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addPanelComponent( this, _textField, _gbTFConstraints, 1, 0, 1, 1, GridBagConstraints.VERTICAL ); -// this.add( _label ); -// this.add( _textField ); - - } - - public String toString() - { - return "Label = " + _label.getText() + " | TextField = " + _textField.getText(); - } - - private void setupConstraints() - { - _gbLabelConstraints.anchor = GridBagConstraints.EAST; - _gbLabelConstraints.weightx = 1; - _gbLabelConstraints.weighty = 0; - - _gbTFConstraints.anchor = GridBagConstraints.WEST; - _gbTFConstraints.weightx = 1; - _gbTFConstraints.weighty = 0; - } - - public void setLabel( String labelString ) - { - _label.setText( labelString ); - } - - public String getLabelText() - { - return _label.getText(); - } - - public void setTextField( String textFieldText ) - { - _textField.setText( textFieldText ); - } - - public void setTextField( double textFieldNumber ) - { - setNumberField( textFieldNumber ); - } - - public void setTextField( int textFieldNumber ) - { - setNumberField( textFieldNumber ); - } - - public void setTextField( short textFieldNumber ) - { - setNumberField( textFieldNumber ); - } - - public void setTextFieldDate( long dateString ) - { - _textField.setText( DbTimeHelper.getDateStringFromLongTime( dateString ) ); - } - - private void setNumberField( double doubleValue ) - { - if ( DbTable.isNull( doubleValue ) ) - { - _textField.setText( "" ); - } - else - { - _textField.setText( Double.toString( doubleValue ) ); - } - } - - private void setNumberField( short shortValue ) - { - if ( DbTable.isNull( shortValue ) ) - { - _textField.setText( "" ); - } - else - { - _textField.setText( Short.toString( shortValue ) ); - } - } - - private void setNumberField( int doubleValue ) - { - if ( DbTable.isNull( doubleValue ) ) - { - _textField.setText( "" ); - } - else - { - _textField.setText( Integer.toString( doubleValue ) ); - } - } - - - public String getTextFieldText() - { - return _textField.getText(); - } - - public void setTextFieldWidth( int columns ) - { - _textField.setColumns( columns ); - } - - public void setToolTip( String toolTipText ) - { - _label.setToolTipText( toolTipText ); - _textField.setToolTipText( toolTipText ); - } - - public void enableTextField( boolean enable ) - { - _textField.setEnabled( enable ); - } - - public void enableLabel( boolean enable ) - { - _label.setEnabled( enable ); - } - - public void setEditTextField( boolean editable ) - { - _textField.setEditable( editable ); - } - - public void enableLabeledTextField( boolean enable ) - { - enableTextField( enable ); - enableLabel( enable ); - } - - public void addTextFieldKeyListener( KeyListener keyListener ) - { - _textField.addKeyListener( keyListener ); - } - - public void addTextFieldMouseListener( MouseListener mouseListener ) - { - _textField.addMouseListener( mouseListener ); - } - - public void setLabelPreferredSize( Dimension dimension ) - { - _label.setPreferredSize( dimension ); - } - - public void setTextFieldPreferredSize( Dimension dimension ) - { - _textField.setPreferredSize( dimension ); - } - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/OptionSelectionDialog.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/OptionSelectionDialog.java deleted file mode 100644 index 6374f0ce34..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/OptionSelectionDialog.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Created on Aug 10, 2005 - * - * - */ -package ohd.hseb.util.gui; - -import javax.swing.*; - - -/** - * @author Chip Gobs - * - * - */ -public class OptionSelectionDialog -{ - - private String _itemString = null; - - //--------------------------------------------------- - - public OptionSelectionDialog() - { - - } - //--------------------------------------------------- - - private void setItemString(String itemString) - { - this._itemString = itemString; - } - - public String getItemString() - { - return _itemString; - } - - // --------------------------------------------------- - - public boolean requestItemByDialog(String dialogTitleString, - String textMessage, - String comboBoxLabelString, - String[] optionArray) - { - String password = null; - JComboBox comboBox = new JComboBox(); - - - for (int i = 0; i < optionArray.length; i++) - { - comboBox.addItem(optionArray[i]); - } - - Object[] messageObjectArray = - { textMessage, - comboBoxLabelString, comboBox, - }; - - //_userName = JOptionPane.showInputDialog(null, messageObjectArray); - - - JOptionPane optionPane = new JOptionPane(); - - optionPane.setMessage( messageObjectArray ); - - optionPane.setMessageType( JOptionPane.QUESTION_MESSAGE ); - - JDialog dialog = optionPane.createDialog( null, dialogTitleString); - - dialog.show(); - - dialog.dispose(); - - - _itemString = (String) comboBox.getSelectedItem(); - - - return true; - } - - - - //--------------------------------------------------- - - public static void main(String[] args) - { - - OptionSelectionDialog dialog = new OptionSelectionDialog(); - - String title = "Rainfall-Runoff Model Selection"; - String message = "Please enter the rainfall-runoff model\n" + - " for which this unit hydrograph is appropriate.\n" + - " " ; - String comboBoxLabelString = "Rainfall-Runoff Model:"; - String[] optionArray = { "ANY ", - "API-MKC", - "SAC-SMA" }; - - dialog.requestItemByDialog(title, message, comboBoxLabelString, optionArray ); - - System.out.println("model = " + dialog.getItemString()); - - } - //--------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/PasswordDialog.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/PasswordDialog.java deleted file mode 100644 index 5db20b59eb..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/PasswordDialog.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Created on Aug 29, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.util.gui; - -import javax.swing.*; - - -/** - * @author Chip Gobs - * - * This class lets the user request a password and obscures it - * as it is being typed in. - */ -public class PasswordDialog -{ - - private String _userName = null; - private String _password = null; - - //--------------------------------------------------- - - public PasswordDialog() - { - - } - //--------------------------------------------------- - - public void setUserName(String userName) - { - _userName = userName; - } - - public String getUserName() - { - return _userName; - } - - public void setPassword(String password) - { - _password = password; - } - - public String getPassword() - { - return _password; - } - - //--------------------------------------------------- - - - public boolean requestPasswordByDialog(String textMessage) - { - String password = null; - JTextField userNameField = new JTextField(""); - JPasswordField passwordField = new JPasswordField(""); - - Object[] messageObjectArray = - { textMessage, - "User Name:", userNameField, - "Password:", passwordField - }; - - //_userName = JOptionPane.showInputDialog(null, messageObjectArray); - - - JOptionPane optionPane = new JOptionPane(); - - optionPane.setMessage( messageObjectArray ); - - optionPane.setMessageType( JOptionPane.QUESTION_MESSAGE ); - - JDialog dialog = optionPane.createDialog( null, "Password" ); - - dialog.show(); - - dialog.dispose(); - - - _userName = new String(userNameField.getText()); - _password = new String(passwordField.getPassword()); - - - - return true; - } - - - - //--------------------------------------------------- - public static void main(String[] args) - { - - PasswordDialog dialog = new PasswordDialog(); - - dialog.requestPasswordByDialog("Please enter your username and password, dude!"); - - System.out.println("username = " + dialog.getUserName()); - System.out.println("password = " + dialog.getPassword()); - - } - - - // --------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/StandardImageIcons.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/StandardImageIcons.java deleted file mode 100644 index 65936970ac..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/StandardImageIcons.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Created on Dec 15, 2003 - * - */ -package ohd.hseb.util.gui; - -import java.awt.*; -import java.awt.image.*; -import javax.swing.*; - -import java.util.*; - - -/** - * @author GobsC - * - * This class makes some standard image icons available to the application. - */ -public class StandardImageIcons -{ - - public static final String UP_ARROW = "UpArrow"; - public static final String DOWN_ARROW = "DownArrow"; - - public static final String RIGHT_ARROW = "RightArrow"; - public static final String LEFT_ARROW = "LeftArrow"; - - public static final String DOUBLE_RIGHT_ARROW = "DoubleRightArrow"; - public static final String DOUBLE_LEFT_ARROW = "DoubleLeftArrow"; - - public static final String CIRCLE = "Circle"; - - private static Map _imageMap = new HashMap(); - - - private static int _verticalSpacing = 3; - private static int _horizontalSpacing = 3; - - - //---------------------------------------------------------- - - //---------------------------------------------------------- - - - public static ImageIcon getImageIcon(String imageName, Color foreground, Color background, - Dimension dimension) - { - - String key = imageName + "|" + - foreground.toString() + "|" + - background.toString() + "|" + - dimension.getWidth() + "|" + dimension.getHeight(); - - BufferedImage image = (BufferedImage)_imageMap.get(key); - Image scaledImage = null; - - if (image == null) - { - image = initBufferedImage(imageName, foreground, background, dimension); - - scaledImage = image.getScaledInstance(dimension.width, dimension.height, Image.SCALE_FAST); - - _imageMap.put(imageName, image); - } - - ImageIcon imageIcon = new ImageIcon(scaledImage); - - return imageIcon; - } - - //---------------------------------------------------------- - - - private static BufferedImage initBufferedImage(String imageName, - Color foregroundColor, - Color backgroundColor, - Dimension dimension) - { - BufferedImage image = null; - String header = "BufferedCanvas.initBufferedImage()"; - - //TYPE_INT_ARGB allows for transparent background - image = new BufferedImage(dimension.width, - dimension.height, - BufferedImage.TYPE_INT_ARGB); - - Graphics2D graphics = (Graphics2D) image.createGraphics(); - - //make the icon background transparent - for (int col = 0; col < dimension.width; col++) { - for (int row = 0; row < dimension.height; row++) { - image.setRGB(col, row, 0x0); - } - } - - //make the icons smoother looking - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - //old way required a backgroundColor, the new transparent background - // way does not. - // fillBackground(graphics, backgroundColor, dimension); - - if (imageName.equals(UP_ARROW)) - { - drawUpArrow(graphics, foregroundColor, dimension); - - } - else if (imageName.equals(DOWN_ARROW)) - { - drawDownArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(LEFT_ARROW)) - { - drawLeftArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(RIGHT_ARROW)) - { - drawRightArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(DOUBLE_LEFT_ARROW)) - { - drawDoubleLeftArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(DOUBLE_RIGHT_ARROW)) - { - drawDoubleRightArrow(graphics, foregroundColor, dimension); - } - - else if (imageName.equals(CIRCLE)) - { - drawCircle(graphics, foregroundColor, dimension); - } - - - return image; - } - - //---------------------------------------------------------- - - private static void fillBackground(Graphics g, Color backgroundColor, - Dimension dimension) - { - g.setColor(backgroundColor); - g.fillRect(0, 0, dimension.width, dimension.height); - } - - //---------------------------------------------------------- - private static void drawCircle(Graphics g, Color foregroundColor, Dimension dimension) - { - - int middleX = dimension.width/2; - int middleY = dimension.height/2; - int x = 0; - int y = 0; - - g.setColor(foregroundColor); - - g.fillOval(x, y, dimension.width, dimension.height); - } - - //---------------------------------------------------------- - - private static void drawUpArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - - int[] xPoints = { middleX, left, right}; - int[] yPoints = { top, bottom, bottom}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - - - private static void drawDownArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - - int[] xPoints = { left, middleX, right}; - int[] yPoints = {top, bottom, top}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - -//---------------------------------------------------------- - - private static void drawLeftArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - - int[] xPoints = { left, right, right}; - int[] yPoints = { middleY, top, bottom}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - - - private static void drawRightArrow(Graphics g, - Color foregroundColor, - Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - int[] xPoints = { right, left, left}; - int[] yPoints = { middleY, top, bottom}; - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - private static void drawDoubleLeftArrow(Graphics g, Color foregroundColor, Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width/2 - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - int[] xPoints = { left, right, right}; - int[] yPoints = { middleY, top, bottom}; - - int shiftAmount = right; - int[] shiftedXPoints = shiftPointsHorizontally(xPoints, shiftAmount); - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - - g.fillPolygon(shiftedXPoints, yPoints, 3); - - return; - } - - //---------------------------------------------------------- - - private static void drawDoubleRightArrow(Graphics g, - Color foregroundColor, - Dimension dimension) - { - int middleX = dimension.width/2; - int middleY = dimension.height/2; - - int right = dimension.width/2 - _horizontalSpacing; - int left = _horizontalSpacing; - - int top = _verticalSpacing; - int bottom = dimension.height - _verticalSpacing; - - int[] xPoints = { right, left, left}; - int[] yPoints = { middleY, top, bottom}; - - int shiftAmount = right; - int[] shiftedXPoints = shiftPointsHorizontally(xPoints, shiftAmount); - - - g.setColor(foregroundColor); - g.fillPolygon(xPoints, yPoints, 3); - g.fillPolygon(shiftedXPoints, yPoints, 3); - - - return; - } - //---------------------------------------------------------- - private static int[] shiftPointsHorizontally(int[] origPointsArray, int shiftAmount) - { - int[] shiftedXPoints = new int[origPointsArray.length]; - for (int i = 0; i < origPointsArray.length; i++) - { - shiftedXPoints[i] = origPointsArray[i] + shiftAmount; - } - - return shiftedXPoints; - - } - - //---------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableColumnComparator.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableColumnComparator.java deleted file mode 100644 index abe719c40a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableColumnComparator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Created on Jun 24, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 24, 2004 - * - */ - -/** - * @author SoodG -*/ -package ohd.hseb.util.gui; - -import java.util.Comparator; - -public abstract class TableColumnComparator implements Comparator -{ - protected String _columnName = null; - protected boolean _ascOrder = true; -// ------------------------------------------------------------------------------- - public abstract int compare(Object arg0, Object arg1); -// ------------------------------------------------------------------------------- - public void initColumnInfo( String columnName, boolean ascOrder ) - { - _columnName = columnName; - _ascOrder = ascOrder; - } -// ------------------------------------------------------------------------------- - public int compareNumbers( double value1, double value2 ) - { - int returnValue = 0; - - if ( value1 < value2 ) - { - returnValue = -1; - } - else if ( value1 == value2 ) - { - returnValue = 0; - } - else // value1 > value2 - { - returnValue = 1; - } - - return returnValue; - } -// ------------------------------------------------------------------------------- - public int compareStrings( String string1, String string2 ) - { - int returnValue = 0; - - returnValue = string1.compareTo(string2); - - return returnValue; - } - - //------------------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableHelper.java deleted file mode 100644 index 12397a798b..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableHelper.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Created on Feb 24, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Feb 24, 2004 - * - */ -package ohd.hseb.util.gui; - -import java.util.LinkedList; - -public class TableHelper -{ - private String[] _dbColumnNameArray = null; - private LinkedList _sortColumnOrderList = new LinkedList(); - private boolean[] _sortOrderArray = null; - private int _columnCount = 0; - - - public TableHelper( String[] dbColumnNameArray ) - { - _dbColumnNameArray = dbColumnNameArray; - _columnCount = _dbColumnNameArray.length; - _sortOrderArray = new boolean[ _columnCount ]; - initialize(); - } - - private void initialize() - { - initLinkedListAndOrderArray(); - } - - public String getOrderByClause() - { - StringBuffer clauseBuffer = new StringBuffer(); - - clauseBuffer.append( " ORDER BY" ); - - for( int i = 0; i < _columnCount; i++ ) - { - String orderString = null; - - int column = Integer.parseInt( _sortColumnOrderList.get( i ).toString() ); - - if ( _sortOrderArray[ column ] == true ) - { - orderString = " asc"; - } - else - { - orderString = " desc"; - } - clauseBuffer.append( " " + _dbColumnNameArray[ column ] + orderString + "," ); - } - clauseBuffer.replace( clauseBuffer.length() - 1, clauseBuffer.length(), " " ); /* Replaces the last comma - with a space */ - return clauseBuffer.toString(); - } - - public void setOrderByClause( int column ) - { - // If true, sets it false and vice versa - setColumnOrderList( column ); -// System.out.println( _sortColumnOrderList ); - _sortOrderArray[ column ] = !( _sortOrderArray[ column ] ); - } - - private void setColumnOrderList( int column ) - { - int index = -1; - - for( int i = 0; i < _sortColumnOrderList.size(); i++ ) - { - Integer valueInteger = (Integer) _sortColumnOrderList.get( i ); - int value = valueInteger.intValue(); - if ( column == value ) - { - index = i; - } - } - if ( index != -1 ) - { - Object columnValueObject = _sortColumnOrderList.remove( index ); - _sortColumnOrderList.addFirst( columnValueObject ); - } - } - - private void initLinkedListAndOrderArray() - { - for ( int i = 0; i < _columnCount; i++ ) - { - _sortOrderArray[ i ] = false; - _sortColumnOrderList.add( i, new Integer( i ) ); - } - } - - public static void main( String args[] ) - { - String[] columnNames = { "Basin ID", "PE", "DUR", "TS", "Extremum", "Adjustment" }; - TableHelper tbhelper = new TableHelper( columnNames ); - System.out.println( tbhelper.getOrderByClause() ); - tbhelper.setOrderByClause( 4 ); - System.out.println( tbhelper.getOrderByClause() ); - tbhelper.setOrderByClause( 2 ); - System.out.println( tbhelper.getOrderByClause() ); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableHelper2.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableHelper2.java deleted file mode 100644 index da8e32255d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TableHelper2.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Created on June 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : June 14, 2004 - * - */ -package ohd.hseb.util.gui; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - - -public class TableHelper2 -{ - private String[] _columnNameArray = null; - private LinkedList _sortColumnOrderList = new LinkedList(); - private boolean[] _sortOrderArray = null; - private int _columnCount = 0; - private TableColumnComparator _listComparator = null; - private int _lastSortedColumn = 0; - - - public TableHelper2( TableColumnComparator listComparator, String[] columnNameArray ) - { - _columnNameArray = columnNameArray; - _columnCount = _columnNameArray.length; - _sortOrderArray = new boolean[ _columnCount ]; - _listComparator = listComparator; - initialize(); - } - - private void initialize() - { - initLinkedListAndOrderArray(); - } - - public void sortList( List listToSort, int column, boolean flipOrder ) - { - String columnName = _columnNameArray[ column ]; - boolean sortAscOrder = _sortOrderArray[ column ]; - - _listComparator.initColumnInfo( columnName, sortAscOrder ); - Collections.sort( listToSort, _listComparator ); - - if (flipOrder) - { - _sortOrderArray[ column ] = ! _sortOrderArray[ column ]; - } - - _lastSortedColumn = column; - } - - - public void sortWithoutMemory( List listToSort, int column, boolean isAscendingOrder ) - { - String columnName = _columnNameArray[ column ]; - boolean sortAscOrder = isAscendingOrder; - - _listComparator.initColumnInfo( columnName, sortAscOrder ); - Collections.sort( listToSort, _listComparator ); - } - - /* - public void resortList( List listToSort, int column ) - { - _sortOrderArray[ column ] = true; - sortList( listToSort, column ); - sortList( listToSort, column ); - } - */ - - public void resortList( List listToSort) - { - sortList( listToSort, _lastSortedColumn, false); - } - - private void initLinkedListAndOrderArray() - { - for ( int i = 0; i < _columnCount; i++ ) - { - _sortOrderArray[ i ] = false; - _sortColumnOrderList.add( i, new Integer( i ) ); - } - } - - public static void main( String args[] ) - { - String[] columnNames = { "Basin ID", "PE", "DUR", "TS", "Extremum", "Adjustment" }; -// TableHelper2 tbhelper = new TableHelper2( columnNames ); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TimePanel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TimePanel.java deleted file mode 100644 index 7afe596f82..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/TimePanel.java +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Created on Oct 28, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Oct 28, 2003 - * - */ -package ohd.hseb.util.gui; - -import ohd.hseb.db.DbTimeHelper; - -import javax.swing.*; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; - - -public class TimePanel extends JPanel -{ - private DatePanel _datePanel = null; - - private int _hours = 0; - private int _minutes = 0; - private int _seconds = 0; - private long _dateTimeLong = 0; - - private JButton _upHourButton = new JButton(); - private JButton _upMinuteButton = new JButton(); - private JButton _upSecondButton = new JButton(); - - private JButton _downHourButton = new JButton(); - private JButton _downMinuteButton = new JButton(); - private JButton _downSecondButton = new JButton(); - - private JTextField _hoursTextField = new JTextField( 3 ); - private JTextField _minutesTextField = new JTextField( 3 ); - private JTextField _secondsTextField = new JTextField( 3 ); - - private boolean _allowOnlyEvenHours = false; - - public TimePanel() - /******************** - Purpose: Empty Constructor - *********************/ - { - this( 0 ); - } - - public TimePanel( long dateTimeLong ) - /******************** - Purpose: Constructor with a date/time long value - *********************/ - { - int hours = 0, - minutes = 0, - seconds = 0; - - String time = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeLong ); - - hours = Integer.parseInt( time.substring( 11, 13 ) ); - minutes = Integer.parseInt( time.substring( 14, 16 ) ); - seconds = Integer.parseInt( time.substring( 17, 19 ) ); - - initTime( hours, minutes, seconds ); - - initialize(); - } - - public void setAllowOnlyEvenHours(boolean allowOnlyEvenHours) - { - _allowOnlyEvenHours = allowOnlyEvenHours; - - if (_allowOnlyEvenHours) - { - setEnableMinutesAndSeconds(false); - } - } - - private void setEnableMinutesAndSeconds(boolean enable) - { - - _minutesTextField.setEditable(enable); - _secondsTextField.setEditable(enable); - - _upMinuteButton.setEnabled(enable); - _downMinuteButton.setEnabled(enable); - - _upSecondButton.setEnabled(enable); - _downSecondButton.setEnabled(enable); - - return; - } - - - private void initialize() - /******************** - Purpose: Initializes the layout and adds the listeners - *********************/ - { - this.setLayout( new GridBagLayout() ); - - initTimeDisplay(); - - addListeners(); - - setSize( 240, 150 ); - } - - private void initTimeDisplay() - /******************** - Purpose: Initializes the Panel - *********************/ - { - _upHourButton.setIcon( getUpIcon() ); - _upMinuteButton.setIcon( getUpIcon() ); - _upSecondButton.setIcon( getUpIcon() ); - _downHourButton.setIcon( getDownIcon() ); - _downMinuteButton.setIcon( getDownIcon() ); - _downSecondButton.setIcon( getDownIcon() ); - - _upHourButton.setBackground( Color.WHITE ); - _upMinuteButton.setBackground( Color.WHITE ); - _upSecondButton.setBackground( Color.WHITE ); - _downHourButton.setBackground( Color.WHITE ); - _downMinuteButton.setBackground( Color.WHITE ); - _downSecondButton.setBackground( Color.WHITE ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( this, _upHourButton, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upMinuteButton, 10, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _upSecondButton, 20, 0, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _hoursTextField, 0, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _minutesTextField, 10, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _secondsTextField, 20, 10, 5, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( this, _downHourButton, 0, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downMinuteButton, 10, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( this, _downSecondButton, 20, 20, 1, 1, GridBagConstraints.BOTH ); - } - - - private void addListeners() - /******************** - Purpose: Adds the listeners to the buttons and text fields - *********************/ - { - // Listeners for the 6 buttons for the date - _upHourButton.addActionListener( new UpHourListener() ); - _upMinuteButton.addActionListener( new UpMinuteListener() ); - _upSecondButton.addActionListener( new UpSecondListener() ); - _downHourButton.addActionListener( new DownHourListener() ); - _downMinuteButton.addActionListener( new DownMinuteListener() ); - _downSecondButton.addActionListener( new DownSecondListener() ); - - // Listeners for the 3 date Text Fields - _hoursTextField.addFocusListener( new HoursTextFieldFocusListener() ); - _minutesTextField.addFocusListener( new MinutesTextFieldFocusListener() ); - _secondsTextField.addFocusListener( new SecondsTextFieldFocusListener() ); - _hoursTextField.addActionListener( new HoursTextFieldListener() ); - _minutesTextField.addActionListener( new MinutesTextFieldListener() ); - _secondsTextField.addActionListener( new SecondsTextFieldListener() ); - } - - private void updateHoursTextField() - { - int inputHours = -1; - - try - { - inputHours = Integer.parseInt( _hoursTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputHours >= 0 ) && ( inputHours <= 23 ) ) - { - _hours = inputHours; - } - - updateTime(); - } - - private void updateMinutesTextField() - { - int inputMinutes = -1; - - try - { - inputMinutes = Integer.parseInt( _minutesTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputMinutes >= 0 ) && ( inputMinutes < 60 ) ) - { - _minutes = inputMinutes; - } - - updateTime(); - } - - private void updateSecondsTextField() - { - int inputSeconds = -1; - - try - { - inputSeconds = Integer.parseInt( _secondsTextField.getText() ); - } - catch ( NumberFormatException exception ) - { - } - - if ( ( inputSeconds >= 0 ) && ( inputSeconds < 60 ) ) - { - _seconds = inputSeconds; - } - - updateTime(); - } - - private class HoursTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateHoursTextField(); - } - } - - private class MinutesTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateMinutesTextField(); - } - } - - private class SecondsTextFieldFocusListener implements FocusListener - { - public void focusGained(FocusEvent arg0) { } - - public void focusLost(FocusEvent arg0) - { - updateSecondsTextField(); - } - } - private class HoursTextFieldListener implements ActionListener - /******************** - Purpose: Hours text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateHoursTextField(); - } - } - - private class MinutesTextFieldListener implements ActionListener - /******************** - Purpose: Minutes text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateMinutesTextField(); - } - } - - private class SecondsTextFieldListener implements ActionListener - /******************** - Purpose: Seconds text field listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - updateSecondsTextField(); - } - } - - private class UpHourListener implements ActionListener - /******************** - Purpose: Up hour button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _hours < 23 ) - { - _hours++; - } - else - { - _hours = 0; - } - - updateTime(); - } - } - - private class UpMinuteListener implements ActionListener - /******************** - Purpose: Up minute button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _minutes < 59 ) - { - _minutes++; - } - else - { - _minutes = 0; - } - - updateTime(); - } - } - - private class UpSecondListener implements ActionListener - /******************** - Purpose: Up second button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _seconds < 59 ) - { - _seconds++; - } - else - { - _seconds = 0; - } - - updateTime(); - } - } - - private class DownHourListener implements ActionListener - /******************** - Purpose: Down hour button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _hours > 0 ) - { - _hours--; - } - else - { - _hours = 23; - } - updateTime(); - } - } - - private class DownMinuteListener implements ActionListener - /******************** - Purpose: Down minute button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _minutes > 0 ) - { - _minutes--; - } - else - { - _minutes = 59; - } - updateTime(); - - } - } - - private class DownSecondListener implements ActionListener - /******************** - Purpose: Down second button listener - *********************/ - { - public void actionPerformed( ActionEvent e ) - { - if ( _seconds > 0 ) - { - _seconds--; - } - else - { - _seconds = 59; - } - updateTime(); - } - } - - - private Icon getUpIcon() - /******************** - Purpose: Returns the up Icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.UP_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - private Icon getDownIcon() - /******************** - Purpose: Returns the down Icon - *********************/ - { - return( StandardImageIcons.getImageIcon( StandardImageIcons.DOWN_ARROW, Color.BLUE, Color.WHITE, new Dimension( 25, 25 ) ) ); - } - - - private void updateTime() - /******************** - Purpose: Updates the time/Panel - *********************/ - { - initTime( _hours, _minutes, _seconds ); - if ( _datePanel != null ) - { - setTime( _dateTimeLong ); - } - } - - public long getDateTimeLong() - /******************** - Purpose: Return a long value for the date/time - *********************/ - { - long dateTimeLong = 0; - long dateLong = 0; - StringBuffer dateTimeBuffer = new StringBuffer(); - String dateTimeString = null; - - dateLong = _datePanel.getDateLong(); - - dateTimeBuffer.append( DbTimeHelper.getDateStringFromLongTime( dateLong ) + " " ); - dateTimeBuffer.append( _hours + ":" + _minutes + ":" + _seconds ); - dateTimeString = dateTimeBuffer.toString(); - dateTimeLong = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - - return dateTimeLong; - } - - public String getTimeString() - { - return _hours + ":" + _minutes + ":" + _seconds; - } - - - public DatePanel getDatePanel() - /******************** - Purpose: Returns the datePanel object - *********************/ - { - return _datePanel; - } - - public void linkDateTime( DatePanel datePanel ) - /******************** - Purpose: links the date/time objects - *********************/ - { - _datePanel = datePanel; - if ( _datePanel.getTimePanel() != this ) - { - _datePanel.linkDateTime( this ); - } - } - - public void setTime( long dateTimeLong, boolean recurse ) - /******************** - Purpose: - *********************/ - { - int hours = 0, - minutes = 0, - seconds = 0; - - String time = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeLong ); - - hours = Integer.parseInt( time.substring( 11, 13 ) ); - minutes = Integer.parseInt( time.substring( 14, 16 ) ); - seconds = Integer.parseInt( time.substring( 17, 19 ) ); - - initTime( hours, minutes, seconds ); - - if ( ( _datePanel != null ) && ( recurse ) ) - { - _datePanel.setDate( dateTimeLong, false ); - } - } - - public void setTime( long dateTimeLong ) - /******************** - Purpose: - *********************/ - { - setTime( dateTimeLong, true ); - } - - private void initTime( int hours, int minutes, int seconds ) - /******************** - Purpose: Initializes the time values/Textfields - *********************/ - { - String dateTimeString = null; - - _hoursTextField.setText( "" + hours ); - _minutesTextField.setText( "" + minutes ); - _secondsTextField.setText( "" + seconds ); - _hours = hours; - _minutes = minutes; - _seconds = seconds; - - if ( _datePanel != null ) - { - dateTimeString = _datePanel.getDateString(); - - dateTimeString += " " + _hours + ":" + _minutes + ":" + _seconds; - - _dateTimeLong = DbTimeHelper.getLongTimeFromDateTimeString( dateTimeString ); - } - -// setTime( _dateTimeLong ); - } - - public static void main(String[] args) - { - Date date = new Date(); - TimePanel TimePanel = new TimePanel( date.getTime() ); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/WindowResizingManager.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/WindowResizingManager.java deleted file mode 100644 index 3ba0cb4329..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/WindowResizingManager.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Created on Apr 28, 2004 - * - * - */ -package ohd.hseb.util.gui; - -import java.awt.Dimension; -import java.awt.Window; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; - -/** - * @author GobsC - * - * This class manages the permissable max and min sizes of a window - */ -public class WindowResizingManager extends ComponentAdapter -{ - private Dimension _minDimension = null; - private Dimension _maxDimension = null; - - private Window _window = null; - - public WindowResizingManager(Window managedComponent, - Dimension minDimension, - Dimension maxDimension) - { - - _window = managedComponent; - - _minDimension = minDimension; - _maxDimension = maxDimension; - - - _window.addComponentListener(this); - - } - - public void componentResized( ComponentEvent e ) - { - - int height = _window.getHeight(); - int width = _window.getWidth(); - //System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - int minWidth = _minDimension.width; - int maxWidth = _maxDimension.width; - int minHeight = _minDimension.height; - int maxHeight = _maxDimension.height; - - if ( width < minWidth ) - { - _window.setSize( new Dimension( minWidth, height ) ); - } - if ( width > maxWidth ) - { - _window.setSize( new Dimension( maxWidth, height ) ); - } - if ( height < minHeight ) - { - _window.setSize( new Dimension( width, minHeight ) ); - } - if ( height > maxHeight ) - { - _window.setSize( new Dimension( width, maxHeight) ); - } - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/BufferedCanvas.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/BufferedCanvas.java deleted file mode 100644 index c140a27e08..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/BufferedCanvas.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Created on Jul 28, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.*; -import java.awt.image.*; -import javax.swing.*; -/** - * @author Chip Gobs - * - * This class acts as the abstract base class for the family of pre-defined - * custom "Canvas" classes. - */ -//public abstract class BufferedCanvas extends java.awt.Canvas -public abstract class BufferedCanvas extends JPanel -{ - private BufferedImage _bufferedImage = null; - private Graphics _bufferedImageGraphics = null; - - private boolean _needsToRedraw = true; - - //--------------------------------------------------------------------- - - public BufferedCanvas() - { - - } - - public BufferedCanvas(int x, int y, int width, int height) - { - Rectangle boundsRectangle = new Rectangle(x, y, width, height); - this.setBounds(boundsRectangle); - } - - // --------------------------------------------------------------------- - - public void setNeedsToRedraw(boolean needsToRedraw) - { - _needsToRedraw = needsToRedraw; - } - - // --------------------------------------------------------------------- - - public void paint(Graphics g) - { - //System.out.println("BufferedCanvas.paint()"); - //make sure that the bufferedImage - //is the same size as the Canvas - - if ( _bufferedImage == null)// don't have a _bufferedImage - { - - // System.out.println("BufferedCanvas.paint() _bufferedImage is null"); - initBufferedImage(); - _needsToRedraw = true; - } - - else if (!sizeSame(_bufferedImage, this) ) - { - //System.out.println("BufferedCanvas.paint() size not same"); - - resizeByVisibleArea(); - - initBufferedImage(); - _needsToRedraw = true; - } - - - // if the image needs to be redrawn to the imageBuffer, - // do it - if (_needsToRedraw) - { - _needsToRedraw = false; - - //System.out.println("BufferedCanvas.paint() size not same"); - - draw(getBufferedImageGraphics()); - } - - copyBufferedImage(g); - } //end paint() -//--------------------------------------------------------- - public void resizeByVisibleArea() - { - int width = this.getVisibleRect().width; - int height = this.getVisibleRect().height; - - this.setSize(width, height); - } -// --------------------------------------------------------- - - public void update(Graphics g) - { - paint(g); - } -//--------------------------------------------------------- - // This method must be overloaded by the subclass - public abstract void draw(Graphics g); - - public void repaint() - { - //System.out.println("BufferedCanvas.repaint()"); - setNeedsToRedraw(true); - super.repaint(); - } -//--------------------------------------------------------- - private void copyBufferedImage(Graphics canvasGraphics) - { - // Toolkit toolkit = Toolkit.getDefaultToolkit(); - - //System.out.println("BufferedCanvas.copyBufferedImage()"); - - - canvasGraphics.drawImage(_bufferedImage, 0, 0, this); - - return; - } //copyBufferedImage -//----------------------------------------------------------------- - private boolean sizeSame(BufferedImage bufferedImage, - BufferedCanvas canvas) - { - boolean result = false; - if ((bufferedImage.getWidth() == canvas.getWidth()) && - ( bufferedImage.getHeight() == canvas.getHeight()) - ) - { - result = true; - } - - return result; - } //end sizeSame -//----------------------------------------------------------------- - public BufferedImage getBufferedImage() - { - return _bufferedImage; - } - -//----------------------------------------------------------------- - protected Graphics getBufferedImageGraphics() - { - if (_bufferedImageGraphics == null) - { - if (_bufferedImage == null) - { - initBufferedImage(); - } - _bufferedImageGraphics = _bufferedImage.createGraphics(); - } - - return _bufferedImageGraphics; - } - -//----------------------------------------------------------------- - -private void initBufferedImage() -{ - - // String header = "BufferedCanvas.initBufferedImage()"; - // Rectangle visibleRectangle = getVisibleRect(); - int width = this.getWidth(); - int height = this.getHeight(); - - - // System.out.println(header + "width = " + width + " height = " + height); - - _bufferedImage = new BufferedImage(width, - height, - BufferedImage.TYPE_INT_RGB); - - _bufferedImageGraphics = _bufferedImage.createGraphics(); -} - -/* - public boolean imageUpdate(Image img, - int infoflags, - int x, - int y, - int w, - int h) - { - System.out.println("BufferedCanvas.imageUpdate(): infoflangs = " + infoflags ); - boolean result = true; - if ( (infoflags & ImageObserver.ALLBITS) == ImageObserver.ALLBITS) - { - result = false; - } - - return result; - } //imageUpdate() -*/ - -} //end BufferedCanvas diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/CanvasHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/CanvasHelper.java deleted file mode 100644 index 5918f14592..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/CanvasHelper.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Created on Sep 26, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - - -import java.awt.*; -import java.text.*; -import java.util.*; - -/** - * @author GobsC - * - * - */ -public class CanvasHelper -{ - - public static Stroke createDashedStroke() - { - float[] fArray = {4.0f, 4.0f}; - return new BasicStroke(1.0f, BasicStroke.CAP_ROUND, - BasicStroke.JOIN_ROUND, 5.0f, fArray, 0.0f); - } - -// -------------------------------------------------------------------------- - public static void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2) - { - Graphics2D g2 = (Graphics2D) g; - Stroke origStroke = g2.getStroke(); - Stroke stroke = createDashedStroke(); - - g2.setStroke(stroke); - g2.drawLine(x1, y1, x2, y2); - g2.setStroke(origStroke); - - return; - } //end drawDashedLine - -// -------------------------------------------------------------------------- - - public static String getDateString(long timeInMillis) - { - SimpleDateFormat sdf = new SimpleDateFormat("MM/dd"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(timeInMillis)); - - return timeString; - } -// -------------------------------------------------------------------------- - - public static String getHourString(long timeInMillis) - { - SimpleDateFormat sdf = new SimpleDateFormat("HH"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(timeInMillis)); - - return timeString; - } -// -------------------------------------------------------------------------- - public static String getDateTimeStringFromLongTime(long time) - { - String timeString = null; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(new java.util.Date(time)); - - return timeString; - } - -// -------------------------------------------------------------------------- - -} //end CanvasHelper diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/CanvasPainter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/CanvasPainter.java deleted file mode 100644 index 6d3311f2c5..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/CanvasPainter.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - - -import java.awt.*; - -/** - * @author GobsC - * - * This interface is used in conjunction with the - * PaintableCanvas class. - * - * Implementations of this interface will paint to the - * canvas of the PaintableCanvas. - */ -public interface CanvasPainter -{ - public void paint(Graphics g); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataCurvePainter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataCurvePainter.java deleted file mode 100644 index ac7ba2de08..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataCurvePainter.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Created on Jul 12, 2004 - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.Graphics; -import java.awt.Color; -import java.awt.Point; -//import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasurementPointSeries; - -import ohd.hseb.util.DataPoint; - - -/** - * @author GobsC - * - */ - -public class DataCurvePainter implements DataPointCanvasPainter -{ - - private MeasurementPointSeries _measurementPointSeries = null; - private DataPointCanvas _canvas = null; - private boolean _shouldPaint = true; - private Color _curveColor = null; -// ---------------------------------------------------------------------------------------- - - public DataCurvePainter (MeasurementPointSeries series, - DataPointCanvas canvas, - Color curveColor) - { - _measurementPointSeries = series; - - _canvas = canvas; - - _curveColor = curveColor; - } - - -// ---------------------------------------------------------------------------------------- - - public Measurement getMaxYMeasurement() - { - return _measurementPointSeries.getMaxYMeasurement(); - - } - -// ---------------------------------------------------------------------------------------- - - public Measurement getMinYMeasurement() - { - return _measurementPointSeries.getMinYMeasurement(); - - } - -// ---------------------------------------------------------------------------------------- - public Measurement getMaxXMeasurement() - { - return _measurementPointSeries.getMaxXMeasurement(); - } - -// ---------------------------------------------------------------------------------------- - - public Measurement getMinXMeasurement() - { - return _measurementPointSeries.getMinXMeasurement(); - } - -// ---------------------------------------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// ---------------------------------------------------------------------------------------- - public void paint(Graphics g) - { - - if (_shouldPaint) - { - drawDataPoints(g); - } - - } //end paint() - -// -------------------------------------------------------------------------- - private void drawDataPoints(Graphics g) - { - int count = _measurementPointSeries.size(); - - g.setColor(_curveColor); - - MeasuringUnit yUnit = _canvas.getDisplayedYMeasuringUnit(); - MeasuringUnit xUnit = _canvas.getDisplayedXMeasuringUnit(); - - Measurement xMeasurement = null; - Measurement yMeasurement = null; - - DataPoint oldDataPoint = null; - - for (int i = 0; i < count; i++) - { - MeasurementPoint point = _measurementPointSeries.getPoint(i); - - yMeasurement = point.getYMeasurement(); - double discharge = yMeasurement.getValue(yUnit); - - xMeasurement = point.getXMeasurement(); - double hour = xMeasurement.getValue(xUnit); - - DataPoint dp = new DataPoint(hour, discharge); - - drawDataPoint(dp, g); - - if (oldDataPoint != null) - { - drawSegment(oldDataPoint, dp, g); - } - - oldDataPoint = dp; - } - } -// -------------------------------------------------------------------------- - - private void drawSegment(DataPoint dp1, DataPoint dp2, Graphics g) - { - Viewport viewport = getViewport(); - -// if it is viewable, then draw it - if ( (getViewport().isViewable(dp1)) && (getViewport().isViewable(dp2)) ) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - else - { - //System.out.println("StagePainter.drawSegment(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } - -// -------------------------------------------------------------------------- - - private void drawDataPoint(DataPoint dp, Graphics g) - { - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } -// ---------------------------------------------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// ---------------------------------------------------------------------------------------- - - public void setMeasurementPointSeries(MeasurementPointSeries measurementPointSeries) - { - _measurementPointSeries = measurementPointSeries; - } -// ---------------------------------------------------------------------------------------- - - public MeasurementPointSeries getMeasurementPointSeries() - { - return _measurementPointSeries; - } -// ---------------------------------------------------------------------------------------- - -} //end class DataCurvePainter diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvas.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvas.java deleted file mode 100644 index dce4c03312..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvas.java +++ /dev/null @@ -1,441 +0,0 @@ -/* - * Created on Jul 12, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import java.util.List; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.PaintableCanvas; - - -/** - * @author GobsC - * - * This class is at the same hierarchical level as TsPaintableCanvas, - * but is more flexible with what kind of data is on the X axis. - * - * Unlike the TsPaintableCanvas, it assumes that all the X axis will be - * painted. - */ -public class DataPointCanvas extends PaintableCanvas -{ - - private String _className = "DataPointCanvas"; - - private MeasuringUnit _displayedYMeasuringUnit = null; - private MeasuringUnit _displayedXMeasuringUnit = null; - - private Viewport _viewport = null; - private ScalingHelper _horizontalScalingHelper = null; - private ScalingHelper _verticalScalingHelper = null; - - - private List _dataPointCanvasPainterList = new ArrayList(); - - private int _leftMargin = 50; - private int _rightMargin = 50; - private int _topMargin = 40; - private int _bottomMargin = 50; - - - private String _title = null; - - -// ---constructor------------------------------------------------ - - public DataPointCanvas(MeasuringUnit displayedXMeasuringUnit, - MeasuringUnit displayedYMeasuringUnit, - int x, int y, - int width, int height, - ScalingHelper horizontalScalingHelper, - ScalingHelper verticalScalingHelper ) - { - super(x, y, width, height); - - _displayedXMeasuringUnit = displayedXMeasuringUnit; - _displayedYMeasuringUnit = displayedYMeasuringUnit; - - _horizontalScalingHelper = horizontalScalingHelper; - _verticalScalingHelper = verticalScalingHelper; - - addListeners(); - - setVisible(true); - - - repaint(); - - } //DataPointCanvas - -// -------------------------------------------------------- - - - public void addDataPointCanvasPainter(DataPointCanvasPainter painter) - { - _dataPointCanvasPainterList.add(painter); - - addCanvasPainter(painter); - - return; - } - - public void removeAllDataPointCanvasPainters() - { - _dataPointCanvasPainterList.clear(); - return; - } - -// -------------------------------------------------------- - - public void setTitle(String graphTitleText) - { - _title = graphTitleText; - return; - } - -// -------------------------------------------------------- - - public int getLeftMargin() - { - return _leftMargin; - } - -// -------------------------------------------------------- - public int getRightMargin() - { - return _rightMargin; - } -// -------------------------------------------------------- - public int getTopMargin() - { - return _topMargin; - } -// -------------------------------------------------------- - - public int getBottomMargin() - { - return _bottomMargin; - } -// ----------------------------------------------------------------- - - public String getTitle() - { - return _title; - } - -// -------------------------------------------------------- - - public void draw(Graphics g) - { - //System.out.println("TsPaintableCanvas.draw()"); - - //drawBackground(g); - - //draw the stuff from all the custom painters - super.draw(g); - } - -// -------------------------------------------------------- - - public void setDisplayedMeasuringUnit(MeasuringUnit measuringUnit) - { - String header = "TsPaintableCanvas.setDisplayedMeasuringUnit()"; - - //System.out.println("displayed Measuring Unit is changing from " + - // _displayedMeasuringUnit + " to " + measuringUnit); - - _displayedYMeasuringUnit = measuringUnit; - - } -// -------------------------------------------------------- - - public MeasuringUnit getDisplayedYMeasuringUnit() - { - return _displayedYMeasuringUnit; - } - -// ------------------------------------------------------- - public MeasuringUnit getDisplayedXMeasuringUnit() - { - return _displayedXMeasuringUnit; - } - -// ------------------------------------------------------- - - public Viewport getViewport() - { - return _viewport; - } - - -// ------------------------------------------------------------------------ - - private void addListeners() - { - - //the resize listener - addComponentListener - ( - new ComponentAdapter() - { - public void componentResized(ComponentEvent event) - { - resize(); - } - } - ); - - - - } //end addListeners() - -// ------------------------------------------------------------------------------ - - - public void refresh() - { - adjustViewport(); - } -// ------------------------------------------------------------------------------ - - private MaxMinData getMaxAndMinCoordinateValues(boolean isXOrdinate) - { - String header = "DataPointCanvas.getMaxAndMinCoordinateValues(): "; - - Measurement minMeasurement = null; - Measurement maxMeasurement = null; - - - minMeasurement = getMinMeasurementForPainters(isXOrdinate); - maxMeasurement = getMaxMeasurementForPainters(isXOrdinate); - - - double minValue = 0.0; - double maxValue = 1.0; - - ScalingHelper scalingHelper = null; - - if (isXOrdinate) - { - scalingHelper = _horizontalScalingHelper; - } - else - { - scalingHelper = _verticalScalingHelper; - } - - - if (minMeasurement != null) - { - minValue = minMeasurement.getValue(); - } - else - { - minValue = 0.0; - } - - - if (maxMeasurement != null) - { - maxValue = maxMeasurement.getValue(); - } - - if (maxValue <= 0.0) - { - maxValue = 1.0; - } - - - scalingHelper.setMinDataValue(minValue); - scalingHelper.setMaxDataValue(maxValue); - - // System.out.println(header + "orig minValue = " + minValue + " orig maxValue = " + maxValue); - - minValue = scalingHelper.getMinScaleValue(); - maxValue = scalingHelper.getMaxScaleValue(); - -// System.out.println(header + "new minValue = " + minValue + " new maxValue = " + maxValue); - - MaxMinData maxMinData = new MaxMinData(maxValue, minValue); - - return maxMinData; - } - -// ------------------------------------------------------------------------------ - - private void adjustViewport() - { - //String header = "TsPaintableCanvas.adjustViewport(): "; - //System.out.println(header); - - int minUseableX = 0 + _leftMargin; - int minUseableY = 0 + _topMargin; - - int maxUseableX = getWidth() - _rightMargin; - int maxUseableY = getHeight() - _bottomMargin; - - Point minScreenPoint = new Point(minUseableX, minUseableY); - Point maxScreenPoint = new Point(maxUseableX, maxUseableY); - - // determine the max and min data values for the Y-axis - MaxMinData maxMinYValue = getMaxAndMinCoordinateValues(false); - - double minYValue = maxMinYValue.getMinValue(); - double maxYValue = maxMinYValue.getMaxValue(); - - - // determine the max and min data values for the X-axis - MaxMinData maxMinXValue = getMaxAndMinCoordinateValues(true); - - double minXValue = maxMinXValue.getMinValue(); - double maxXValue = maxMinXValue.getMaxValue(); - - - DataPoint minDataPoint = new DataPoint(minXValue, minYValue); - DataPoint maxDataPoint = new DataPoint(maxXValue, maxYValue); - - if (_viewport == null) - { - _viewport = new Viewport(minScreenPoint, maxScreenPoint, - minDataPoint, maxDataPoint); - _viewport.setFlipYOrientation(true); - } - - else //_viewport != null - { - _viewport.setMinScreenPoint(minScreenPoint); - _viewport.setMaxScreenPoint(maxScreenPoint); - _viewport.setMinDataPoint(minDataPoint); - _viewport.setMaxDataPoint(maxDataPoint); - - _viewport.setFlipYOrientation(true); - - } - - repaint(); - - } //end adjustViewport - -// end getMaxMeasurementForPainters() -// ----------------------------------------------------------------- - private Measurement getMinMeasurementForPainters(boolean isXOrdinate) - { - Measurement minMeasurement = null; - Measurement painterMinMeasurement = null; - MeasuringUnit unit = null; - - - if (isXOrdinate) - { - unit = getDisplayedXMeasuringUnit(); - } - else - { - unit = getDisplayedYMeasuringUnit(); - } - - // check each DataPointCanvasPainter for its min - for (int i = 0 ; _dataPointCanvasPainterList != null && i <_dataPointCanvasPainterList.size() ; i++) - { - - DataPointCanvasPainter painter = (DataPointCanvasPainter) _dataPointCanvasPainterList.get(i); - - - if (isXOrdinate) - { - painterMinMeasurement = painter.getMinXMeasurement(); - } - else - { - painterMinMeasurement = painter.getMinYMeasurement(); - } - - Measurement tempMin = Measurement.getConvertedCopy(painterMinMeasurement, unit) ; - - if (tempMin != null) - { - - if ( (minMeasurement == null) || - (tempMin.getValue() < minMeasurement.getValue()) - ) - { - minMeasurement = tempMin; - } - - } - - } //end for - - return minMeasurement; - } -// ----------------------------------------------------------------- - private Measurement getMaxMeasurementForPainters( boolean isXOrdinate) - { - Measurement maxMeasurement = null; - Measurement painterMaxMeasurement = null; - MeasuringUnit unit = null; - - if (isXOrdinate) - { - unit = getDisplayedXMeasuringUnit(); - } - else - { - unit = getDisplayedYMeasuringUnit(); - } - - // check each DataPointCanvasPainter for its max - for (int i = 0 ; _dataPointCanvasPainterList != null && i < _dataPointCanvasPainterList.size() ; i++) - { - DataPointCanvasPainter painter = (DataPointCanvasPainter) _dataPointCanvasPainterList.get(i); - - if (isXOrdinate) - { - painterMaxMeasurement = painter.getMaxXMeasurement(); - } - else - { - painterMaxMeasurement = painter.getMaxYMeasurement(); - } - - - Measurement tempMax = Measurement.getConvertedCopy( painterMaxMeasurement, unit); - - if (tempMax != null) - { - - if ( (maxMeasurement == null) || - (tempMax.getValue() > maxMeasurement.getValue()) - ) - { - maxMeasurement = tempMax; - } - - } - - } //end for - - return maxMeasurement; - - } // end getMaxMeasurementForPainters() -// ----------------------------------------------------------------- - - private void resize() - { - adjustViewport(); - } //end resize() - - - -// -------------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasAdapter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasAdapter.java deleted file mode 100644 index 76bf1c5407..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasAdapter.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Created on Jul 19, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -/** - * @author Chip Gobs - * This interface provides a facade for working with the DataPointCanvas and its - * other associated classes, such as Painters. It helps ensure that the implementation - * classes are providing all of the needed functionality. - */ -public interface DataPointCanvasAdapter -{ - public DataPointCanvas initCanvas(Object initializationObject); - public void refreshCanvas(Object dataObject); - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasBackgroundPainter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasBackgroundPainter.java deleted file mode 100644 index 3475258bb9..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasBackgroundPainter.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Created on July 14, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import ohd.hseb.util.*; -import ohd.hseb.util.gui.FontHelper; - -import java.awt.Graphics; -import java.awt.*; -import java.text.*; - -/** - * @author Chip Gobs - * - * This class implements CanvasPainter and encapsulates the - * drawing of the X and Y axes and all the tick marks - */ -public class DataPointCanvasBackgroundPainter implements CanvasPainter -{ - private String _className = "DataPointCanvasBackgroundPainter"; - - private DataPointCanvas _canvas = null; - - - //number formatter - private NumberFormat _numberFormat = NumberFormat.getInstance(); - - // various colors - private static final Color _backgroundColor = Color.black; - - - // NOTE: future changes: - // will want to have multiple time series, so there needs - // to be a way to have different colors for timeseries - - private static final Color _gridColor = Color.GRAY; - private Color _outlineColor = Color.WHITE; - private static final Color _labelColor = Color.WHITE; - private static final Color _numberColor = Color.WHITE; - - - //unit labels - private String _xUnitLabelString = null; - private String _yUnitLabelString = null; - - -// fonts - private Font _titleFont = null; - private Font _labelFont = null; - private Font _numberFont = null; - - // margins and shifts - private final static int _titleYShift = - 20; - private int _leftUnitLabelShift = 10; - private final static int _constantYAxisNumberLabelSpacing = 0; - - private int _lowerNumberLabelShift = 15; - - //FontHelper - custom class - private FontHelper _labelFontHelper = null; - private FontHelper _titleFontHelper = null; - - private double _smallRoundingError = 0.000000001; - - - private boolean _showMinorVerticalTicks = true; - private boolean _showMinorVerticalLabels = true; - private boolean _showMinorHorizontalTicks = true; - - private ScalingHelper _verticalScalingHelper = null; - private ScalingHelper _horizontalScalingHelper = null; - // --------------------------------------------------------- - public DataPointCanvasBackgroundPainter(Color lineColor, - DataPointCanvas canvas, - String xUnitLabelString, - String yUnitLabelString, - ScalingHelper horizontalScalingHelper, - ScalingHelper verticalScalingHelper) - { - _outlineColor = lineColor; - _canvas = canvas; - - - _xUnitLabelString = xUnitLabelString; - _yUnitLabelString = yUnitLabelString; - - _numberFormat.setMaximumFractionDigits(2); - - _titleFont = new Font("TimesRoman",Font.BOLD,20); - _labelFont= new Font("TimesRoman",Font.BOLD,14); - _numberFont = new Font("Helvetica",Font.PLAIN,10); - - _labelFontHelper = new FontHelper(_labelFont); - _titleFontHelper = new FontHelper(_titleFont); - - _showMinorVerticalTicks = false; - _showMinorHorizontalTicks = false; - - _horizontalScalingHelper = horizontalScalingHelper; - _verticalScalingHelper = verticalScalingHelper; - - } //tsBackgroundPainter() - -// --------------------------------------------------------- - public void setShowMinorVerticalTicks(boolean showMinorVerticalTicks) - { - _showMinorVerticalTicks = showMinorVerticalTicks; - } -// --------------------------------------------------------- - public void setShowMinorHorizontalTicks(boolean showMinorHorizontalTicks) - { - _showMinorHorizontalTicks = showMinorHorizontalTicks; - } -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawBackground(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - public void drawBackground(Graphics g) - { - - Rectangle r = _canvas.getBounds(); - - //clear the image - g.setColor(_backgroundColor); - g.fillRect(0, 0, r.width, r.height); - - //draw the axis labels, ticks, and dotted lines - drawHorizontalLines( g ); - drawVerticalLines( g ); - - // draw the title of the graph - - drawTitle(g); - - int x = 0; - int y = 0; - - //draw x axis label - int labelWidth = _labelFontHelper.getWidth(g, _xUnitLabelString); - x = (int) ((r.width * .5) - (.5 * labelWidth)); - - int labelShift = (int) (-.4 * _canvas.getBottomMargin()); - - y = (r.height) + labelShift; - drawLabel(_xUnitLabelString, g, x, y); - - - //draw y axis label - x = _leftUnitLabelShift; - y = (r.height * 4/9); - int verticalSpacing = _labelFontHelper.getHeight(g); - drawVerticalLabel(_yUnitLabelString, g, x, y, verticalSpacing); - - - } - -//---------------------------------------------------- - private void drawTitle(Graphics g) - { - String titleString = _canvas.getTitle(); - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, titleString) / 2; - - int x = middleX - totalLeftShift; - int y = (_canvas.getTopMargin() + _titleYShift); - - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(titleString, x, y); - - return; - } //drawTitle - -// -------------------------------------------------------------------------- - private void drawLabel(String labelString, Graphics g, int x, int y) - { - g.setFont(_labelFont); - g.setColor(_labelColor); - g.drawString(labelString, x, y); - - return; - } //drawUnitLabel -// -------------------------------------------------------------------------- - private void drawVerticalLabel(String labelString, Graphics g, int x, int y, int verticalSpacing) - { - Graphics2D g2 = (Graphics2D) g; - - g2.setFont(_labelFont); - g2.setColor(_labelColor); - - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < labelString.length(); i++) - { - char c = labelString.charAt(i); - String newString = Character.toString(c); - g2.drawString(newString, x, y); - y += verticalSpacing; - } - - - return; - } //drawVerticalUnitLabel -// -------------------------------------------------------------------------------------------------- - private void drawXAxisNumberLabel(Graphics g, int x, int y, double value) - { - String header = _className + ".drawXAxisNumberLabel(): "; - String numberLabelString =_numberFormat.format(value); - - g.setColor(_numberColor); - g.setFont(_numberFont); - - int totalLeftShift = _labelFontHelper.getWidth(g, numberLabelString) / 2; - g.drawString(numberLabelString, x - totalLeftShift, y + _lowerNumberLabelShift); - - - } -// -------------------------------------------------------------------------------------------------- - private void drawYAxisNumberLabel(Graphics g, int x, int y, double value) - { - String header = _className + "drawYAxisNumberLabel(): "; - String numberLabelString =_numberFormat.format(value); - - g.setColor(_numberColor); - g.setFont(_numberFont); - - int totalYShift = _labelFontHelper.getHeight(g) / 4; - int stringWidth = _labelFontHelper.getWidth(g, numberLabelString); - int totalLeftShift = -(stringWidth + _constantYAxisNumberLabelSpacing); - // System.out.println(header + "_labelFontHelper says that stringWidth of = " + - // numberLabelString + " = " + stringWidth); - - int newX = x + totalLeftShift; - if (newX < 0) - { - newX = 0; - } - - int newY = y + totalYShift; - - g.drawString(numberLabelString, newX, newY); - - - } -// -------------------------------------------------------------------------- - - private void drawVerticalLines(Graphics g) - { - String header = _className + ".drawVerticalLines(): "; - //determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - // this is correct. To draw a series of vertical lines, I need to know - // how far left and right things are, so I need to scale horizontally. - ScalingHelper scalingHelper = _horizontalScalingHelper; - - scalingHelper.setMinDataValue(minXValue); - scalingHelper.setMaxDataValue(maxXValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minXValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_numberFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxXValue + _smallRoundingError); - - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minXValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(majorTickValue, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(majorTickValue, maxYValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not working due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - - //draw the lower tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+5, point1.x, point2.y); - - // draw the label - drawXAxisNumberLabel(g, point1.x, point1.y, majorTickValue); - - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorVerticalTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minorTickValue, minYValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(minorTickValue, maxYValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, - minorPoint1.x, minorPoint1.y, - minorPoint2.x, minorPoint2.y); - - // draw the label - if (_showMinorVerticalLabels) - { - drawXAxisNumberLabel(g, minorPoint1.x, minorPoint1.y, minorTickValue); - } - - } - } - - } //end if _showMinorTicks - - } //end for - - } //end drawYAxis -// -------------------------------------------------------------------------- - - /* - private boolean isOnATick(long timeValue, int hoursPerTick) - { - boolean result = false; - - if ((timeValue % hoursPerTick) == 0 ) - { - result = true; - } - return result; - } //end isOnATick - */ - -// ------------------------------------------------------------------------------------------- - - private void drawHorizontalLines(Graphics g) - { - //determine the min and max data values to chart - - String header = "DataBackgroundPainter.drawHorizontalLines(): "; - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - // ScalingHelper scalingHelper = new ScalingHelper(minYValue, maxYValue); - - // this is correct. To draw a series of horizontal lines, I need to know - // how far up and down things are, so I need to scale vertically - ScalingHelper scalingHelper = _verticalScalingHelper; - scalingHelper.setMinDataValue(minYValue); - scalingHelper.setMaxDataValue(maxYValue); - - //scalingHelper = new ScalingHelper(minYValue, maxYValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minYValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_numberFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxYValue + _smallRoundingError); - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minYValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(minXValue, majorTickValue)); - point2 = getViewport().getScreenPoint(new DataPoint(maxXValue, majorTickValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not work due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - //CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - - } - - - //draw the left side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x-5, point1.y, point1.x, point2.y); - - // draw the label - drawYAxisNumberLabel(g, point1.x, point1.y, majorTickValue); - - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorHorizontalTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minXValue, minorTickValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(maxXValue, minorTickValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, minorPoint1.x, - minorPoint1.y, - minorPoint2.x, - minorPoint2.y); - - } - } - - } //end if _showMinorTicks - - } - - } //end drawYAxis - - - public void setShowMinorVerticalLabels(boolean showMinorVerticalLabels) - { - _showMinorVerticalLabels = showMinorVerticalLabels; - } - - - public boolean showMinorVerticalLabels() - { - return _showMinorVerticalLabels; - } - -// ------------------------------------------------------------------------------ - - -} //end of DataPointCanvasBackgroundPainter diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasPainter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasPainter.java deleted file mode 100644 index 6d484b47b6..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/DataPointCanvasPainter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Created on Jul 15, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import ohd.hseb.measurement.Measurement; - -/** - * @author GobsC - * - * - */ -public interface DataPointCanvasPainter extends CanvasPainter -{ - public Measurement getMaxXMeasurement(); - public Measurement getMinXMeasurement(); - - public Measurement getMaxYMeasurement(); - public Measurement getMinYMeasurement(); - - public void setShouldPaint(boolean shouldPaint); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/PaintableCanvas.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/PaintableCanvas.java deleted file mode 100644 index f2b22519f8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/PaintableCanvas.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.util.*; -import java.awt.Graphics; - -/** - * @author Chip Gobs - * - * This class provides a BufferedCanvas and accepts - * multiple layers of painters, each of which knows how - * to draw on it. Each painter has access to this object's - * Viewport in order to make scaling decisions. - */ -public class PaintableCanvas extends BufferedCanvas -{ - - private List _canvasPainterList = new ArrayList(); - -// ------------------------------------------------------------------ - - public PaintableCanvas(int x, int y, int width, int height) - { - super(x, y, width, height); - - return; - } - -// ------------------------------------------------------------------ - - public void draw(Graphics g) - { - //System.out.println("PaintableCanvas.draw()"); - for (int i = 0 ; i < _canvasPainterList.size(); i++) - { - CanvasPainter painter = (CanvasPainter) _canvasPainterList.get(i); - painter.paint(g); - } - } -// ------------------------------------------------------------------ - public void addCanvasPainter(CanvasPainter painter) - { - _canvasPainterList.add(painter); - return; - } -// ------------------------------------------------------------------ - - public void addCanvasPainter(int index, CanvasPainter painter) - { - _canvasPainterList.add(index, painter); - - return; - } -// ------------------------------------------------------------------ - public void removeCanvasPainter(CanvasPainter painter) - { - _canvasPainterList.remove(painter); - return; - } -// -------------------------------------------------------------------- - - public CanvasPainter removeCanvasPainter(int index) - { - CanvasPainter painter = null; - - painter = (CanvasPainter)_canvasPainterList.remove(index); - - return painter; - } - - -// ------------------------------------------------------------------ - protected int getCanvasPainterCount() - { - return _canvasPainterList.size(); - } -// ------------------------------------------------------------------ - protected CanvasPainter getCanvasPainterByIndex(int index) - { - return (CanvasPainter) _canvasPainterList.get(index); - } - - -// ------------------------------------------------------------------ - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/ScalingHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/ScalingHelper.java deleted file mode 100644 index 7527ff02c4..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/ScalingHelper.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Created on Apr 7, 2004 - * - * - */ -package ohd.hseb.util.gui.drawing; - -/** - * @author GobsC - * - * - */ -public class ScalingHelper -{ - - //includes the first and last ticks - // private final static int _minMajorTickCount = 4; - private final static int _maxMajorTickCount = 6; - - - private final static double _niceLowerNumberFactor = 5.0; - - private double[] _niceMajorIncrementArray = {1.0, 2.0, 5.0}; - private double[] _niceMinorIncrementArray = {.2, .5, 1}; - private double _baseFactorStartingPoint = .01; -// ------------------------------------------------------------------------- - private double _minDataValue; - private double _maxDataValue; - - private double _minScaleValue; - private double _maxScaleValue; - - private int _majorTickCount; - private int _minorTickCount; - - private double _majorTickIncrement; - private double _minorTickIncrement; - - - -// ------------------------------------------------------------------------- - - public ScalingHelper(double minDataValue, double maxDataValue) - { - _minDataValue = minDataValue; - _maxDataValue = maxDataValue; - - rescale(); - } - -// -------------------------------------------------------------------- - - public void setMaxDataValue(double maxDataValue) - { - _maxDataValue = maxDataValue; - - rescale(); - } - -// -------------------------------------------------------------------- - - public double getMaxDataValue() - { - return _maxDataValue; - - } - -// -------------------------------------------------------------------- - - public void setMinDataValue(double minDataValue) - { - _minDataValue = minDataValue; - rescale(); - } - -// -------------------------------------------------------------------- - - public double getMinDataValue() - { - return _minDataValue; - } - -// -------------------------------------------------------------------- - public int getMajorTickCount() - { - return _majorTickCount; - } - - public double getMajorTickIncrement() - { - return _majorTickIncrement; - } - -// -------------------------------------------------------------------- - - public double getMaxScaleValue() - { - return _maxScaleValue; - } - -// -------------------------------------------------------------------- - - - public int getMinorTickCount() - { - return _minorTickCount; - } - - // -------------------------------------------------------------------- - - public double getMinorTickIncrement() - { - return _minorTickIncrement; - } -// -------------------------------------------------------------------- - - public double getMinScaleValue() - { - return _minScaleValue; - } - -// -------------------------------------------------------------------- - - public void setNiceMajorIncrementArray(double[] niceMajorIncrementArray) - { - _niceMajorIncrementArray = niceMajorIncrementArray; - rescale(); - } - -// -------------------------------------------------------------------- - - public double[] getNiceMajorIncrementArray() - { - return _niceMajorIncrementArray; - } - -// -------------------------------------------------------------------- - - public void setNiceMinorIncrementArray(double[] niceMinorIncrementArray) - { - _niceMinorIncrementArray = niceMinorIncrementArray; - rescale(); - } - -// -------------------------------------------------------------------- - - public double[] getNiceMinorIncrementArray() - { - return _niceMinorIncrementArray; - } - -// -------------------------------------------------------------------- - private void rescale() - { - - - int multipleCount = (int) Math.floor(_minDataValue/ _niceLowerNumberFactor); - _minScaleValue = multipleCount * _niceLowerNumberFactor; - - - double baseFactor = _baseFactorStartingPoint; - - // find the right nice increment - - boolean done = false; - int i = 0; - - - double range = _maxDataValue - _minScaleValue; - - - //ensure that range is a sane value - - if (range < 1.0) - { - range = 1.0; - } - - - while (!done ) - { - double testIncrement = _niceMajorIncrementArray[i] * ( baseFactor); - - int testTickCount = (int) Math.ceil(range/testIncrement + 1); - - - //if there are a reasonable number of tickCounts, then stop - // if ((testTickCount >= _minMajorTickCount) && - // (testTickCount <= _maxMajorTickCount)) - if (testTickCount <= _maxMajorTickCount) - { - - _majorTickCount = testTickCount; - - _majorTickIncrement = testIncrement; - - _minorTickIncrement = _niceMinorIncrementArray[i] * baseFactor; - _minorTickCount = (int) (_niceMajorIncrementArray[i]/ _niceMinorIncrementArray[i]) - 1; - - //first tick counts as a tick, so subtract 1 - _maxScaleValue = _minScaleValue + ( (_majorTickCount-1) * _majorTickIncrement); - - done = true; - } - - i++; - - if ((i >= _niceMajorIncrementArray.length) || - (i >= _niceMinorIncrementArray.length)) - { - i = 0; - baseFactor *= 10.0; - } - - } //end while !done - - - - return; - } - -// -------------------------------------------------------------------- - public String toString() - { - String outString = " minDataValue = " + getMinDataValue() + - " maxDataValue = " + getMaxDataValue() + "\n" + - " minScaleValue = " + getMinScaleValue() + - " maxScaleValue = " + getMaxScaleValue() + "\n" + - " majorTickCount = " + getMajorTickCount() + - " minorTickCount = " + getMinorTickCount() + "\n" + - " majorTickIncrement = " + getMajorTickIncrement() + - " minorTickIncrement = " + getMinorTickIncrement(); - - return outString; - } - - -// -------------------------------------------------------------------- - public static void main(String[] argArray) - { - double minValue = 87.6; - double maxValue = 123.5; - ScalingHelper scaler = new ScalingHelper(minValue, maxValue); - - System.out.println(scaler.toString()); - - } - - /** - * @param baseFactorStartingPoint The baseFactorStartingPoint to set. - */ - public void setBaseFactorStartingPoint(double baseFactorStartingPoint) - { - _baseFactorStartingPoint = baseFactorStartingPoint; - } - - /** - * @return Returns the baseFactorStartingPoint. - */ - public double getBaseFactorStartingPoint() - { - return _baseFactorStartingPoint; - } - - -// -------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasEvent.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasEvent.java deleted file mode 100644 index 2aabcd7352..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Created on Oct 7, 2003 - * - * This class is for events related to clicking on - * a TimeSeriesCanvas - */ - -package ohd.hseb.util.gui.drawing; - - -import ohd.hseb.measurement.*; - -/** - * @author Chip Gobs - * - * - */ -public class TsCanvasEvent -{ - - private AbsTimeMeasurement _measurement = null; - -// ----------------------------------------------------------------------- - public TsCanvasEvent(TsCanvasEvent event) - { - this(event._measurement); - - return; - } -// ----------------------------------------------------------------------- - - public TsCanvasEvent(AbsTimeMeasurement measurement) - { - _measurement = new AbsTimeMeasurement(measurement); - - return; - } - -//----------------------------------------------------------------------- - - public AbsTimeMeasurement getMeasurement() - { - return _measurement; - } -// ----------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasEventListener.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasEventListener.java deleted file mode 100644 index 6f1256c0b4..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasEventListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Created on Oct 7, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -/** - * @author GobsC - * - * - */ -public interface TsCanvasEventListener -{ - - public void handleTsCanvasEvent(TsCanvasEvent event); - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasPainter.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasPainter.java deleted file mode 100644 index 7b961a18fb..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsCanvasPainter.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -//import ohd.hseb.util.gui.*; -import ohd.hseb.measurement.*; - -/** - * @author GobsC - * - * This interface is an extension of CanvasPainter - * and specializes the CanvasPainter in that it deals with - * the maximum and minimum measurements, which - * usually come from TimeSeries - * - **/ -public interface TsCanvasPainter extends CanvasPainter -{ - - public Measurement getMaxMeasurement(); - public Measurement getMinMeasurement(); - public void setShouldPaint(boolean shouldPaint); - - -} //end of TsCanvasPainter diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsPaintableCanvas.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsPaintableCanvas.java deleted file mode 100644 index cd3458a021..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/TsPaintableCanvas.java +++ /dev/null @@ -1,589 +0,0 @@ -/* - * Created on Oct 7, 2003 - * - * - */ -package ohd.hseb.util.gui.drawing; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import java.util.List; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -//import ohd.hseb.util.gui.*; - -/** - * @author Chip Gobs - * - * - */ -public class TsPaintableCanvas extends PaintableCanvas -{ - - private MeasuringUnit _displayedMeasuringUnit = null; - private Viewport _viewport = null; - - - private List _tsCanvasPainterList = new ArrayList(); - private List _eventListeners = new ArrayList(); - - private int _intervalInHours = 1; - - private int _leftMargin = 50; - private int _rightMargin = 50; - private int _topMargin = 40; - private int _bottomMargin = 50; - - //time constant - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - - // the default viewing window for the timeSeries - //private long _defaultTimeWindowInHours = 72; - private long _defaultTimeWindowInHours = 72; - - private long _startTime = (System.currentTimeMillis()/MILLIS_PER_HOUR)*MILLIS_PER_HOUR; - private long _endTime = _startTime + - (_defaultTimeWindowInHours * MILLIS_PER_HOUR); - - - - private String _title = null; - - //testing only - private int _showCount = 0; - -//---constructor------------------------------------------------ - - public TsPaintableCanvas(MeasuringUnit displayedMeasuringUnit, - int x, int y, - int width, int height) - { - super(x, y, width, height); - - _displayedMeasuringUnit = displayedMeasuringUnit; - - addListeners(); - - setVisible(true); - - - repaint(); - - } //TsPaintableCanvas - -// -------------------------------------------------------- - public void addTsCanvasPainterAfter(TsCanvasPainter painterToAdd, TsCanvasPainter painterToAddAfter) - { - int index = -1; - - index = _tsCanvasPainterList.indexOf(painterToAddAfter); - - if (index != -1) - { - addTsCanvasPainter(painterToAdd, index + 1); - } - else - { - throw (new Error("Error: Attempted to add after a painter that does not exist")); - } - - return; - } -// -------------------------------------------------------- - - public void addTsCanvasPainter(TsCanvasPainter painter, int index) - { - // String header = "TsPaintableCanvas.addTsCanvasPainter(2 arg): "; - - _tsCanvasPainterList.add(index, painter); - addCanvasPainter(index, painter); - - // System.out.println(header + " _tsCanvasPainterList has " + _tsCanvasPainterList.size() + " elements."); - - return; - } - - public void addTsCanvasPainter(TsCanvasPainter painter) - { - // String header = "TsPaintableCanvas.addTsCanvasPainter(1 arg): "; - _tsCanvasPainterList.add(painter); - addCanvasPainter(painter); - - // System.out.println(header + " _tsCanvasPainterList has " + _tsCanvasPainterList.size() + " elements."); - - return; - } - -// -------------------------------------------------------- - public void removeTsCanvasPaintersBetweenExclusive(TsCanvasPainter firstPainter, TsCanvasPainter lastPainter) - { - // String header = "TsPaintableCanvas.removeTsCanvasPaintersBetweenExclusive() "; - boolean haveFoundFirst = false; - boolean done = false; - - List paintersToRemoveList = new ArrayList(); - - //determine which painters to remove - for (int i = 0; i < _tsCanvasPainterList.size(); i++) - { - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - // System.out.println(header + "at top of loop, painter = " + painter); - - - if (haveFoundFirst) - { - if (painter != lastPainter) - { - //System.out.println(header + "adding painter to the removal list."); - paintersToRemoveList.add(painter); - } - else //we are done - { - // System.out.println(header + "found last painter."); - done = true; - break; - } - } - else if (painter == firstPainter) //keep looking for the first painter - { - haveFoundFirst = true; - // System.out.println(header + "found first painter."); - } - } //end for - - // System.out.println(header + "removing " + paintersToRemoveList.size() + " painters."); - //actually remove the painters - for (TsCanvasPainter painter : paintersToRemoveList) - { - removeTsCanvasPainter(painter); - } - } - -// -------------------------------------------------------- - public void removeTsCanvasPaintersBetweenInclusive(TsCanvasPainter firstPainter, TsCanvasPainter lastPainter) - { - String header = "TsPaintableCanvas.removeTsCanvasPaintersBetweenInclusive() "; - boolean haveFoundFirst = false; - boolean done = false; - - List paintersToRemoveList = new ArrayList(); - - //determine which painters to remove - for (int i = 0; i < _tsCanvasPainterList.size(); i++) - { - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - // System.out.println(header + "at top of loop, painter = " + painter); - - - if (haveFoundFirst) - { - if (painter != lastPainter) - { - //System.out.println(header + "adding painter to the removal list."); - paintersToRemoveList.add(painter); - } - else //we are done - { - paintersToRemoveList.add(painter); - // System.out.println(header + "found last painter."); - done = true; - break; - } - } - else if (painter == firstPainter) //keep looking for the first painter - { - haveFoundFirst = true; - paintersToRemoveList.add(painter); - // System.out.println(header + "found first painter."); - } - } //end for - - System.out.println(header + "removing " + paintersToRemoveList.size() + " painters."); - //actually remove the painters - for (TsCanvasPainter painter : paintersToRemoveList) - { - removeTsCanvasPainter(painter); - } - } - -// -------------------------------------------------------- - - - - public void removeTsCanvasPainter(TsCanvasPainter painter) - { - _tsCanvasPainterList.remove(painter); - removeCanvasPainter(painter); - return; - } -// -------------------------------------------------------- - public void setTitle(String graphTitleText) - { - _title = graphTitleText; - return; - } - -// -------------------------------------------------------- - - public long getStartTime() - { - return _startTime; - } - -// -------------------------------------------------------- - public long getEndTime() - { - return _endTime; - } - -// -------------------------------------------------------- - - public int getLeftMargin() - { - return _leftMargin; - } - -// -------------------------------------------------------- - - public void setLeftMargin(int leftMargin) - { - _leftMargin = leftMargin; - adjustViewport(); - } - -// -------------------------------------------------------- - public int getRightMargin() - { - return _rightMargin; - } -// -------------------------------------------------------- - public void setRightMargin(int rightMargin) - { - _rightMargin = rightMargin; - adjustViewport(); - } -// -------------------------------------------------------- - public int getTopMargin() - { - return _topMargin; - } -// -------------------------------------------------------- - public void setTopMargin(int topMargin) - { - _topMargin = topMargin; - adjustViewport(); - } -// -------------------------------------------------------- - - public String getTitle() - { - return _title; - } - -// -------------------------------------------------------- - public void setTimeWindow(long startTime, long endTime) - { - _startTime = startTime; - _endTime = endTime; - - adjustViewport(); - - } - -// -------------------------------------------------------- - - - public void slideTimeWindow(int hoursToShift) - { - - long millisToShift = hoursToShift * MILLIS_PER_HOUR; - - setTimeWindow(_startTime + millisToShift, - _endTime + millisToShift); - } - -// -------------------------------------------------------- - - public void draw(Graphics g) - { - //System.out.println("TsPaintableCanvas.draw()"); - - //drawBackground(g); - - //draw the stuff from all the custom painters - super.draw(g); - - - } - -// -------------------------------------------------------- - - - -// -------------------------------------------------------- - - public void setDisplayedMeasuringUnit(MeasuringUnit measuringUnit) - { - String header = "TsPaintableCanvas.setDisplayedMeasuringUnit()"; - - //System.out.println("displayed Measuring Unit is changing from " + - // _displayedMeasuringUnit + " to " + measuringUnit); - - _displayedMeasuringUnit = measuringUnit; - - - } - -// -------------------------------------------------------- - - public MeasuringUnit getDisplayedMeasuringUnit() - { - return _displayedMeasuringUnit; - } - -// ------------------------------------------------------- - - public Viewport getViewport() - { - return _viewport; - } - -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------ - - private void addListeners() - { - - //the resize listener - addComponentListener - ( - new ComponentAdapter() - { - public void componentResized(ComponentEvent event) - { - resize(); - } - } - ); - - - } //end addListeners() - -// ------------------------------------------------------------------------------ - - public AbsTimeMeasurement getAbsTimeMeasurementByTruncation(Point point) - { - - DataPoint dataPoint = _viewport.getDataPoint(point); - MeasuringUnit unit = getDisplayedMeasuringUnit(); - - //System.out.println("TsPaintableCanvas.mouseListener() unit = " + unit); - - double clickedValue = dataPoint.getY(); - double value = MathHelper.roundToNDecimalPlaces(clickedValue, 2); - - - - long clickedTime = (long)dataPoint.getX(); - long time = TimeHelper.truncateTimeInMillisToNearestHour(clickedTime, - _intervalInHours); - - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, time, unit); - - return measurement; - } - -// ------------------------------------------------------------------------------ - - public AbsTimeMeasurement getAbsTimeMeasurementByRounding(Point point) - { - - DataPoint dataPoint = _viewport.getDataPoint(point); - MeasuringUnit unit = getDisplayedMeasuringUnit(); - - //System.out.println("TsPaintableCanvas.mouseListener() unit = " + unit); - - double clickedValue = dataPoint.getY(); - double value = MathHelper.roundToNDecimalPlaces(clickedValue, 2); - - - long clickedTime = (long)dataPoint.getX(); - long time = TimeHelper.roundTimeInMillisToNearestHour(clickedTime); - - - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, time, unit); - - return measurement; - } -// ------------------------------------------------------------------------------ - public void refresh() - { - // String header = "TsPaintableCanvas.refresh(): "; - - // System.out.println(header); - adjustViewport(); - } -// ------------------------------------------------------------------------------ - - private void adjustViewport() - { - //String header = "TsPaintableCanvas.adjustViewport(): "; - //System.out.println(header); - - int minUseableX = 0 + _leftMargin; - int minUseableY = 0 + _topMargin; - - int maxUseableX = getWidth() - _rightMargin; - int maxUseableY = getHeight() - _bottomMargin; - - Point minScreenPoint = new Point(minUseableX, minUseableY); - Point maxScreenPoint = new Point(maxUseableX, maxUseableY); - - long minTime = _startTime; - long maxTime = _endTime; - - Measurement minMeasurement = getMinMeasurementForPainters(); - Measurement maxMeasurement = getMaxMeasurementForPainters(); - - double minValue = 0.0; - double maxValue = 1.0; - - if (minMeasurement != null) - { - minValue = minMeasurement.getValue(); - } - else - { - minValue = 0.0; - } - - - if (maxMeasurement != null) - { - maxValue = maxMeasurement.getValue(); - } - - if (maxValue <= 0.0) - { - maxValue = 1.0; - } - - ScalingHelper scalingHelper = new ScalingHelper(minValue, maxValue); - - minValue = scalingHelper.getMinScaleValue(); - maxValue = scalingHelper.getMaxScaleValue(); - - //System.out.println(header + "minValue = " + minValue); - // System.out.println(header + "maxValue = " + maxValue); - - DataPoint minDataPoint = new DataPoint(minTime, minValue); - DataPoint maxDataPoint = new DataPoint(maxTime, maxValue); - - if (_viewport == null) - { - _viewport = new Viewport(minScreenPoint, - maxScreenPoint, - minDataPoint, - maxDataPoint); - _viewport.setFlipYOrientation(true); - } - - else //_viewport != null - { - _viewport.setMinScreenPoint(minScreenPoint); - _viewport.setMaxScreenPoint(maxScreenPoint); - _viewport.setMinDataPoint(minDataPoint); - _viewport.setMaxDataPoint(maxDataPoint); - - _viewport.setFlipYOrientation(true); - } - - - repaint(); - - } //end adjustViewport - -//----------------------------------------------------------------- - private Measurement getMinMeasurementForPainters() - { - Measurement minMeasurement = null; - - - // check each TsCanvasPainter for its max and min - for (int i = 0 ; _tsCanvasPainterList != null && i <_tsCanvasPainterList.size() ; i++) - { - - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - MeasuringUnit unit = getDisplayedMeasuringUnit(); - Measurement tempMin = Measurement.getConvertedCopy(painter.getMinMeasurement(), unit) ; - - if (tempMin != null) - { - - if ( (minMeasurement == null) || - (tempMin.getValue() < minMeasurement.getValue()) - ) - { - minMeasurement = tempMin; - } - - //System.out.println("TsPaintableCanvas.getMinMeasurement(): tempMin is NOT null"); - } - - } //end for - - //System.out.println("TsPaintableCanvas.getMinMeasurement(): minMeasurement = " + minMeasurement); - - - return minMeasurement; - } -// ----------------------------------------------------------------- - private Measurement getMaxMeasurementForPainters() - { - Measurement maxMeasurement = null; - - // check each TsCanvasPainter for its max and min - for (int i = 0 ; _tsCanvasPainterList != null && i < _tsCanvasPainterList.size() ; i++) - { - TsCanvasPainter painter = (TsCanvasPainter) _tsCanvasPainterList.get(i); - - MeasuringUnit unit = getDisplayedMeasuringUnit(); - Measurement tempMax = Measurement.getConvertedCopy(painter.getMaxMeasurement(), unit); - - if (tempMax != null) - { - - if ( (maxMeasurement == null) || - (tempMax.getValue() > maxMeasurement.getValue()) - ) - { - maxMeasurement = tempMax; - } - - //System.out.println("TsPaintableCanvas.getMaxMeasurement(): tempMax is NOT null"); - } - - } //end for - - //System.out.println("TsPaintableCanvas.getMaxMeasurement(): maxMeasurement = " + maxMeasurement); - - return maxMeasurement; - } // end getMaxMeasurementForPainters() -//----------------------------------------------------------------- - - private void resize() - { - adjustViewport(); - } //end resize() -//-------------------------------------------------------------------------- - -} //end TsPaintableCanvas - - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/Viewport.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/Viewport.java deleted file mode 100644 index e8efda8529..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/drawing/Viewport.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Created on Jul 16, 2003 - * - * Viewport provides the tools for translating between - * data coordinates and screen coordinates. - */ -package ohd.hseb.util.gui.drawing; - -import ohd.hseb.util.*; -import java.awt.*; - -/** - * @author Chip Gobs - * - * This class provides a mapping between screen coordinates and - * data coordinates. - */ -public class Viewport -{ - private Point _minScreenPoint = null; - private Point _maxScreenPoint = null; - - private DataPoint _minDataPoint = null; - private DataPoint _maxDataPoint = null; - - private boolean _flipYOrientation = false; - private boolean _flipXOrientation = false; - -// ---------------------------------------------------------------------------- - public Viewport(Point minScreenPoint, - Point maxScreenPoint, - DataPoint minDataPoint, - DataPoint maxDataPoint) - { - _minScreenPoint = minScreenPoint; - _maxScreenPoint = maxScreenPoint; - - _minDataPoint = minDataPoint; - _maxDataPoint = maxDataPoint; - - return; - } - - // ---------------------------------------------------------------------------- - - - public Viewport(Viewport viewport) - { - _minScreenPoint = viewport.getMinScreenPoint(); - _maxScreenPoint = viewport.getMaxScreenPoint(); - - _minDataPoint = viewport.getMinDataPoint(); - _maxDataPoint = viewport.getMaxDataPoint(); - - _flipXOrientation = viewport._flipXOrientation; - _flipYOrientation = viewport._flipYOrientation; - - return; - - } - - // ---------------------------------------------------------------------------- - - public boolean isViewable(DataPoint dataPoint) - { - boolean result = false; - - if ( - (dataPoint.getX() >= _minDataPoint.getX()) && - (dataPoint.getX() <= _maxDataPoint.getX()) && - (dataPoint.getY() >= _minDataPoint.getY()) && - (dataPoint.getY() <= _maxDataPoint.getY()) - ) - { - result = true; - } - - return result; - - } - - // ---------------------------------------------------------------------------- - - public void setFlipYOrientation(boolean flip) - { - _flipYOrientation = flip; - } - - // ---------------------------------------------------------------------------- - - public void setFlipXOrientation(boolean flip) - { - _flipXOrientation = flip; - } - - // ---------------------------------------------------------------------------- - - public DataPoint getDataPoint(Point screenPoint) - { - DataPoint dataPoint = new DataPoint(); - - - double x = calcDataCoord(screenPoint.x, - _minScreenPoint.x, - _maxScreenPoint.x, - _minDataPoint.getX(), - _maxDataPoint.getX(), - _flipXOrientation); - - double y = calcDataCoord(screenPoint.y, - _minScreenPoint.y, - _maxScreenPoint.y, - _minDataPoint.getY(), - _maxDataPoint.getY(), - _flipYOrientation); - - dataPoint.setX(x); - dataPoint.setY(y); - - return dataPoint; - } - - // ---------------------------------------------------------------------------- - - public Point getScreenPoint(DataPoint dataPoint) - { - Point screenPoint = new Point(); - - int x = calcScreenCoord(dataPoint.getX(), - _minScreenPoint.x, - _maxScreenPoint.x, - _minDataPoint.getX(), - _maxDataPoint.getX(), - _flipXOrientation); - - int y = calcScreenCoord(dataPoint.getY(), - _minScreenPoint.y, - _maxScreenPoint.y, - _minDataPoint.getY(), - _maxDataPoint.getY(), - _flipYOrientation); - - screenPoint.x = x; - screenPoint.y = y; - - return screenPoint; - } - - //---------------------------------------------------------------------------- - - private double calcDataCoord(int screenCoord, - int minScreenCoord, - int maxScreenCoord, - double minDataCoord, - double maxDataCoord, - boolean flipOrientation) - { - double dataCoord = 0.0; - int lengthDrawn = 0; - - int useableScreenLength = Math.abs(maxScreenCoord - minScreenCoord); - double maxDataDiff = maxDataCoord - minDataCoord; - - double fractionalDistance = 0.0; - - /* - * avoid possible divide by 0 - */ - if (useableScreenLength == 0) - { - return 0.0; - } - - // determine how far from the appropriate edge the coordinate is - if (flipOrientation) - { - //lengthDrawn = Math.abs(screenCoord - maxScreenCoord); - lengthDrawn = maxScreenCoord - screenCoord; - } - else - { - lengthDrawn = screenCoord - minScreenCoord; - //lengthDrawn = Math.abs(screenCoord - minScreenCoord); - } - - //figure out the proportion of the screen distance the coordinate is - fractionalDistance = (double) lengthDrawn/ - (double) useableScreenLength; - - // get the dataCoord from the fractionalDistance - dataCoord = (fractionalDistance * maxDataDiff) + minDataCoord; - - return dataCoord; - } - // ---------------------------------------------------------------------------- - - private int calcScreenCoord(double dataCoord, - int minScreenCoord, - int maxScreenCoord, - double minDataCoord, - double maxDataCoord, - boolean flipOrientation) - { - int screenCoord = 0; - - int useableScreenLength = Math.abs(maxScreenCoord - minScreenCoord); - double maxDataDiff = maxDataCoord - minDataCoord; - - double curDataDiff = dataCoord - minDataCoord; - - - // avoid possible divided by 0 - if (maxDataDiff == 0) - { - return 0; - } - - - // Rounding - double fractionDrawn = ((double)curDataDiff /(double) maxDataDiff); - int lengthDrawn = (int) Math.round(fractionDrawn * useableScreenLength); - - if (flipOrientation) - { - screenCoord = maxScreenCoord - lengthDrawn; - } - else - { - screenCoord = minScreenCoord + lengthDrawn; - } - - return screenCoord; - - } //end calcScreenCoord - - // ---------------------------------------------------------------------------- - - - public void setMinScreenPoint(Point minScreenPoint) - { - _minScreenPoint = minScreenPoint; - } - - // ---------------------------------------------------------------------------- - - public Point getMinScreenPoint() - { - return _minScreenPoint; - } - - // ---------------------------------------------------------------------------- - - - public void setMaxScreenPoint(Point maxScreenPoint) - { - _maxScreenPoint = maxScreenPoint; - } - - // ---------------------------------------------------------------------------- - - - public Point getMaxScreenPoint() - { - return _maxScreenPoint; - } - - // ---------------------------------------------------------------------------- - - - public void setMinDataPoint(DataPoint minDataPoint) - { - _minDataPoint = minDataPoint; - } - // ---------------------------------------------------------------------------- - - public DataPoint getMinDataPoint() - { - return _minDataPoint; - } - // ---------------------------------------------------------------------------- - - public void setMaxDataPoint(DataPoint maxDataPoint) - { - _maxDataPoint = maxDataPoint; - } - // ---------------------------------------------------------------------------- - - public DataPoint getMaxDataPoint() - { - return _maxDataPoint; - } - -// ---------------------------------------------------------------------------- - -// ---------------------------------------------------------------------------- - - public static void main(String[] args) - { - Point minScreenPoint = new Point(0,0); - Point maxScreenPoint = new Point(500, 500); - - DataPoint minDataPoint = new DataPoint(0.0, 0.0); - DataPoint maxDataPoint = new DataPoint(100, 100); - - Viewport vp = new Viewport(minScreenPoint, - maxScreenPoint, - minDataPoint, - maxDataPoint); - - for (int i = 0; i <= 500; i+=100) - { - for (int j = 0; j <= 500; j+=100) - { - Viewport.test(vp, i, j); - } - } - - - } //end main - - // ---------------------------------------------------------------------------- - - public static void test(Viewport viewport, int x, int y) - { - Point screenPoint = new Point(x, y); - DataPoint currentDataPoint = null; - Point newPoint = null; - - currentDataPoint = viewport.getDataPoint(screenPoint); - - newPoint = viewport.getScreenPoint(currentDataPoint); - - System.out.println("orig screenPoint = " + screenPoint); - System.out.println("data Point = " + currentDataPoint); - System.out.println("converted point " + newPoint); - - return; - } //end test - -} //end class ViewPort diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeCellRenderer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeCellRenderer.java deleted file mode 100644 index 9e67f7ecf3..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeCellRenderer.java +++ /dev/null @@ -1,247 +0,0 @@ -package ohd.hseb.util.gui.jchecktree; - -import javax.swing.*; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.ActionMapUIResource; -import java.awt.event.*; - -import java.awt.BorderLayout; -import java.awt.Component; - -import javax.swing.Icon; -import javax.swing.JPanel; -import javax.swing.JTree; -import javax.swing.tree.TreeCellRenderer; -import javax.swing.tree.TreePath; - -public class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer -{ - /** This is a type-safe enumerated type */ - public static class State { private State() { } } - public static final State NOT_SELECTED = new State(); - public static final State SELECTED = new State(); - public static final State DONT_CARE = new State(); - - private CheckTreeSelectionModel selectionModel; - private TreeCellRenderer delegate; - private TristateCheckBox checkBox = new TristateCheckBox(); - - public CheckTreeCellRenderer(TreeCellRenderer delegate, CheckTreeSelectionModel selectionModel) - { - this.delegate = delegate; - this.selectionModel = selectionModel; - setLayout(new BorderLayout()); - setOpaque(false); - checkBox.setOpaque(false); - } - - - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) - { - Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); - TreePath path = tree.getPathForRow(row); - - if(path!=null) - { - if(selectionModel.isPathSelected(path, true)) - { - //checkBox.setState(Boolean.TRUE); - checkBox.setState(SELECTED); - } - else - { - // checkBox.setState(selectionModel.isPartiallySelected(path) ? null : Boolean.FALSE); - checkBox.setState(selectionModel.isPartiallySelected(path) ? null : NOT_SELECTED); - } - } - removeAll(); - add(checkBox, BorderLayout.WEST); - add(renderer, BorderLayout.CENTER); - return this; - } - - - /** - * Maintenance tip - There were some tricks to getting this code - * working: - * - * 1. You have to overwite addMouseListener() to do nothing - * 2. You have to add a mouse event on mousePressed by calling - * super.addMouseListener() - * 3. You have to replace the UIActionMap for the keyboard event - * "pressed" with your own one. - * 4. You have to remove the UIActionMap for the keyboard event - * "released". - * 5. You have to grab focus when the next state is entered, - * otherwise clicking on the component won't get the focus. - * 6. You have to make a TristateDecorator as a button model that - * wraps the original button model and does state management. - */ - public class TristateCheckBox extends JCheckBox { - - private final TristateDecorator model; - - public TristateCheckBox(String text, Icon icon, State initial){ - super(text, icon); - // Add a listener for when the mouse is pressed - super.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e) { - grabFocus(); - model.nextState(); - } - }); - // Reset the keyboard action map - ActionMap map = new ActionMapUIResource(); - map.put("pressed", new AbstractAction() { - public void actionPerformed(ActionEvent e) { - grabFocus(); - model.nextState(); - } - }); - map.put("released", null); - SwingUtilities.replaceUIActionMap(this, map); - // set the model to the adapted model - model = new TristateDecorator(getModel()); - setModel(model); - setState(initial); - } - public TristateCheckBox(String text, State initial) { - this(text, null, initial); - } - public TristateCheckBox(String text) { - this(text, DONT_CARE); - } - public TristateCheckBox() { - this(null); - } - - /** No one may add mouse listeners, not even Swing! */ - public void addMouseListener(MouseListener l) { } - /** - * Set the new state to either SELECTED, NOT_SELECTED or - * DONT_CARE. If state == null, it is treated as DONT_CARE. - */ - public void setState(State state) { model.setState(state); } - /** Return the current state, which is determined by the - * selection status of the model. */ - public State getState() { return model.getState(); } - public void setSelected(boolean b) { - if (b) { - setState(SELECTED); - } else { - setState(NOT_SELECTED); - } - } - /** - * Exactly which Design Pattern is this? Is it an Adapter, - * a Proxy or a Decorator? In this case, my vote lies with the - * Decorator, because we are extending functionality and - * "decorating" the original model with a more powerful model. - */ - private class TristateDecorator implements ButtonModel { - private final ButtonModel other; - private TristateDecorator(ButtonModel other) { - this.other = other; - } - private void setState(State state) { - if (state == NOT_SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(false); - } else if (state == SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(true); - } else { // either "null" or DONT_CARE - other.setArmed(true); - setPressed(true); - setSelected(true); - } - } - /** - * The current state is embedded in the selection / armed - * state of the model. - * - * We return the SELECTED state when the checkbox is selected - * but not armed, DONT_CARE state when the checkbox is - * selected and armed (grey) and NOT_SELECTED when the - * checkbox is deselected. - */ - private State getState() { - if (isSelected() && !isArmed()) { - // normal black tick - return SELECTED; - } else if (isSelected() && isArmed()) { - // don't care grey tick - return DONT_CARE; - } else { - // normal deselected - return NOT_SELECTED; - } - } - /** We rotate between NOT_SELECTED, SELECTED and DONT_CARE.*/ - private void nextState() { - State current = getState(); - if (current == NOT_SELECTED) { - setState(SELECTED); - } else if (current == SELECTED) { - setState(DONT_CARE); - } else if (current == DONT_CARE) { - setState(NOT_SELECTED); - } - } - /** Filter: No one may change the armed status except us. */ - public void setArmed(boolean b) { - } - /** We disable focusing on the component when it is not - * enabled. */ - public void setEnabled(boolean b) { - setFocusable(b); - other.setEnabled(b); - } - /** All these methods simply delegate to the "other" model - * that is being decorated. */ - public boolean isArmed() { return other.isArmed(); } - public boolean isSelected() { return other.isSelected(); } - public boolean isEnabled() { return other.isEnabled(); } - public boolean isPressed() { return other.isPressed(); } - public boolean isRollover() { return other.isRollover(); } - public void setSelected(boolean b) { other.setSelected(b); } - public void setPressed(boolean b) { other.setPressed(b); } - public void setRollover(boolean b) { other.setRollover(b); } - public void setMnemonic(int key) { other.setMnemonic(key); } - public int getMnemonic() { return other.getMnemonic(); } - public void setActionCommand(String s) { - other.setActionCommand(s); - } - public String getActionCommand() { - return other.getActionCommand(); - } - public void setGroup(ButtonGroup group) { - other.setGroup(group); - } - public void addActionListener(ActionListener l) { - other.addActionListener(l); - } - public void removeActionListener(ActionListener l) { - other.removeActionListener(l); - } - public void addItemListener(ItemListener l) { - other.addItemListener(l); - } - public void removeItemListener(ItemListener l) { - other.removeItemListener(l); - } - public void addChangeListener(ChangeListener l) { - other.addChangeListener(l); - } - public void removeChangeListener(ChangeListener l) { - other.removeChangeListener(l); - } - public Object[] getSelectedObjects() { - return other.getSelectedObjects(); - } - } - } -} - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeManager.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeManager.java deleted file mode 100644 index 7100296f56..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeManager.java +++ /dev/null @@ -1,62 +0,0 @@ -package ohd.hseb.util.gui.jchecktree; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.JCheckBox; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreePath; - -public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener -{ - private CheckTreeSelectionModel selectionModel; - private JTree tree = new JTree(); - int hotspot = new JCheckBox().getPreferredSize().width; - - public CheckTreeManager(JTree tree) - { - this.tree = tree; - selectionModel = new CheckTreeSelectionModel(tree.getModel()); - tree.setCellRenderer(new CheckTreeCellRenderer(tree.getCellRenderer(), selectionModel)); - tree.addMouseListener(this); - selectionModel.addTreeSelectionListener(this); - } - - public void mouseClicked(MouseEvent me) - { - TreePath path = tree.getPathForLocation(me.getX(), me.getY()); - if(path==null) - return; - if(me.getX()>tree.getPathBounds(path).x+hotspot) - return; - - boolean selected = selectionModel.isPathSelected(path, true); - selectionModel.removeTreeSelectionListener(this); - - try - { - if(selected) - selectionModel.removeSelectionPath(path); - else - selectionModel.addSelectionPath(path); - } - finally - { - selectionModel.addTreeSelectionListener(this); - tree.treeDidChange(); - } - } - - public CheckTreeSelectionModel getSelectionModel() - { - return selectionModel; - } - - public void valueChanged(TreeSelectionEvent e) - { - // TODO Auto-generated method stub - } -} - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeSelectionModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeSelectionModel.java deleted file mode 100644 index 6e7ee2d06f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jchecktree/CheckTreeSelectionModel.java +++ /dev/null @@ -1,185 +0,0 @@ -package ohd.hseb.util.gui.jchecktree; - -import java.util.ArrayList; -import java.util.Stack; - -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -public class CheckTreeSelectionModel extends DefaultTreeSelectionModel -{ - private TreeModel model; - - public CheckTreeSelectionModel(TreeModel model) - { - this.model = model; - setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - } - - // tests whether there is any unselected node in the subtree of given path - public boolean isPartiallySelected(TreePath path) - { - if(isPathSelected(path, true)) - return false; - TreePath[] selectionPaths = getSelectionPaths(); - if(selectionPaths==null) - return false; - for(int j = 0; j _allRowDataList = null; - private JTableSortHelper _sortHelper; - private JTableColumnDescriptorManager _columnDescriptorManager; - private ScrollableJTable _scrollableJTable = null; - - private Dimension _columnHeaderPreferredSize = null; - - - public ComplexJTableManager(List columnDescriptorList, List rowDataList, Dimension columnHeaderPreferredSize) - { - - _columnHeaderPreferredSize = columnHeaderPreferredSize; - - _allRowDataList = rowDataList; - _columnDescriptorManager = new JTableColumnDescriptorManager( - columnDescriptorList); - _scrollableJTable = new ScrollableJTable(this, _columnHeaderPreferredSize); - String columnNamesToDisplay[] = getColumnNamesThatAreCurrentlyDisplayed(); - if(columnNamesToDisplay != null) - { - setDisplayableColumns(getColumnNamesThatAreCurrentlyDisplayed(), true, true); - } - - } - - public ComplexJTableManager(List columnDescriptorList, List rowDataList) - { - this (columnDescriptorList, rowDataList, null); - } - - - public ComplexJTableManager(List columnDescriptorList, List rowDataList, int tableRowSelectionMode) - { - _allRowDataList = rowDataList; - _columnDescriptorManager = new JTableColumnDescriptorManager( - columnDescriptorList); - _scrollableJTable = new ScrollableJTable(this, tableRowSelectionMode); - } - - public void setColumnHeaderPreferredSize(Dimension columnHeaderPreferredSize) - { - _columnHeaderPreferredSize = columnHeaderPreferredSize; - if (_scrollableJTable != null) - { - _scrollableJTable.setColumnHeaderPreferredSize(columnHeaderPreferredSize); - } - } - - public void resetSortHelper() - { - _sortHelper = null; - } - - public void setChangedAllRowDataList(List allRowDataList) - { - _allRowDataList = allRowDataList; - } - - public List getAllRowDataList() - { - return _allRowDataList; - } - - public void setColumnsForDisplay(String columnNamesSelected[]) - { - _columnDescriptorManager.setDisplayableColumns(columnNamesSelected); - } - - public void setCellEditors(JTable table) - { - String[] columnNames = getColumnNamesThatAreCurrentlyDisplayed(); - int columnCount = columnNames.length; - JTableColumnDescriptorManager mgr = _columnDescriptorManager; - - for (int i = 0; i < columnCount ; i++) - { - String columnName = columnNames[i]; - JTableColumnDescriptor columnDescriptor = mgr.getColumnDescriptorByName(columnName); - //for each displayed column, set the cell editor - //get the cell editor out of the descriptorlist - - if (columnDescriptor.isEditable()) - { - setEditor(table, i, columnDescriptor.getCellEditor()); - } - } - - return; - } - - private void setEditor(JTable table, int columnIndex, TableCellEditor cellEditor) - { - //set the CellEditor - table.getColumnModel().getColumn(columnIndex).setCellEditor(cellEditor); - - //set the toggle value to true within JTableModel - JTableModel model = (JTableModel) table.getModel(); - model.setIsCellColumnEditable(true, columnIndex); - } - - //------------------------------------------------------------------------------ - - - public void setDisplayableColumns(String columnNamesSelected[], - boolean changeSortOrder,boolean firstDraw) - { - _columnDescriptorManager.setDisplayableColumns(columnNamesSelected); - - boolean columnSortOrderArray[] = null; - - if(changeSortOrder) - { - columnSortOrderArray = _columnDescriptorManager.getSortOrderOfAllColumns(); - } - - String[] allColumnNamesInColumnDescriptorManager = _columnDescriptorManager.getAllColumnNamesInColumnDescriptorManager(); - _sortHelper = new JTableSortHelper(allColumnNamesInColumnDescriptorManager); - if(columnSortOrderArray != null) - { - _sortHelper.setChangedSortOrderArray(columnSortOrderArray); - } - - _scrollableJTable.createTable(firstDraw); - } - - public String[] getColumnNamesThatAreCurrentlyDisplayed() - { - String columnNames[] = _columnDescriptorManager. - getColumnNamesThatAreCurrentlyDisplayed(); - return columnNames; - } - - public void swapColumns(String columnName1, String columnName2) - { - _columnDescriptorManager.swapColumnsInList(columnName1, columnName2); - - } - - public String[][] getDisplayRowDataArray() - { - // CodeTimer timer = new CodeTimer(); - // timer.start(); - List columnDescriptorList = _columnDescriptorManager.getColumnDescriptorList(); - String colNamesSelected[] = _columnDescriptorManager.getColumnNamesThatAreCurrentlyDisplayed(); - - _rowDataForCurrentDisplayedRows = new String[_allRowDataList.size()] - [colNamesSelected.length]; - _cellBackgroundColorsForCurrentDisplayedRows = new Color[_allRowDataList.size()] - [colNamesSelected.length]; - _cellForegroundColorsForCurrentDisplayedRows = new Color[_allRowDataList.size()] - [colNamesSelected.length]; - int col = 0; - - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - for(int row=0; row < _allRowDataList.size(); row++) - { - JTableRowData infoRecord = (JTableRowData) _allRowDataList.get(row); - col = 0; - for(int j =0; j =0; i--) - { - boolean isAscending = _columnDescriptorManager.getSortDirectionForColumn(columnNamesForSortingToBeDone[i]); - // System.out.println("ComplexJTableManager.sort(): "+ columnNamesForSortingToBeDone[i]+"|"+ isAscending); - sort(columnNamesForSortingToBeDone[i], isAUserClick, isAscending); - } - } - } - - public void sort(String columnName, boolean isAUserClick, boolean isAscending) - { - // System.out.println("ComplexJTableManager.sort(,,):" + columnName); - _sortHelper.sortList(_allRowDataList, columnName, isAUserClick, isAscending); - } - - public boolean isColumnAsc(String columnName) - { - return _sortHelper.isColumnAsc(columnName); - } - - public JTableRowData getRowData(int rowIndex) - { - JTableRowData rowData = (JTableRowData) _allRowDataList.get(rowIndex); - return rowData; - } - - public Color getCellBackgroundColor(int row, int column) - { - Color newBackgroundColor = _cellBackgroundColorsForCurrentDisplayedRows[row][column]; - return newBackgroundColor; - } - - public Color getCellForegroundColor(int row, int column) - { - Color newForegroundColor = _cellForegroundColorsForCurrentDisplayedRows[row][column]; - return newForegroundColor; - } - - public void setSortInfoNotBasedOnUserClicks(String columnNamesToSort[], boolean columnSortOrder[], int columnSortNumber[]) - { - _columnDescriptorManager.setSortInfoNotBasedOnUserClicks(columnNamesToSort, columnSortOrder, columnSortNumber); - _scrollableJTable.sort(); - } - - public void clearSort() - { - _columnDescriptorManager.clearSort(); - _scrollableJTable.sort(); - } - - public String[] getColumnNamesForSortToBeDone() - { - String columnNamesForSorting[] = _columnDescriptorManager.getColumnNamesForSortToBeDone(); - - return columnNamesForSorting; - } - - public int[] getSortOrderForSortedColumnNames() - { - int sortOrderForSortedColumns[] = _columnDescriptorManager.getSortOrderForSortedColumnNames(); - - return sortOrderForSortedColumns; - } - - public int[] getWidthOfDisplayedColumns() - { - int columnWidths[] = _columnDescriptorManager.getWidthOfDisplayedColumns(); - return columnWidths; - } - - public String[] getAlignmentOfDisplayedColumns() - { - String columnAligments[] = _columnDescriptorManager.getAlignmentOfDisplayedColumns(); - return columnAligments; - } - - public boolean[] getIsEditableArray() - { - boolean[] isEditableArray = _columnDescriptorManager.getIsEditableArray(); - return isEditableArray; - } - - public void setWidthOfDisplayedColumns(int columnWidths[]) - { - _columnDescriptorManager.setWidthOfDisplayedColumns(columnWidths); - } - - public void setAlignmentOfDisplayedColumns(String columnAlignments[]) - { - _columnDescriptorManager.setAlignmentOfDisplayedColumns(columnAlignments); - } - - public void selectColumnForSorting(String columnName) - { - boolean isAscending = _columnDescriptorManager.getSortDirectionForColumn(columnName); - _columnDescriptorManager.selectColumnForSorting(columnName, isAscending, -1, true); - } - - public JTableColumnDisplaySettings getTableSettings() - { - JTableColumnDisplaySettings columnDisplaySettings = _columnDescriptorManager.getTableColumnSettings(); - return columnDisplaySettings; - } - - public void addTableListener(EventListener eventListener) - { - _scrollableJTable.addTableListeners(eventListener); - } - - public void removeTableListener(EventListener eventListener) - { - _scrollableJTable.removeTableListener(eventListener); - } - - public JScrollPane getJScrollPane() - { - return(_scrollableJTable.getJScrollPane()); - } - - public void setPreferredSizeForJScrollPane(Dimension dimension) - { - _scrollableJTable.setPreferredSizeForJScrollPane(dimension); - } - - public int[] getSelectedRowIndices() - { - int selectedRowIndices[] =_scrollableJTable.getSelectedRowIndices(); - - return selectedRowIndices; - } - - public List getSelectedRowsData() - { - int selectedRowIndices[] = getSelectedRowIndices(); - List selectedRowDataList = new ArrayList(); - for(int loopCnt=0; loopCnt columnClass, DefaultCellEditor defaultCellEditor) - { - _scrollableJTable.setTableCellEditor(columnClass, defaultCellEditor); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableCellRenderer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableCellRenderer.java deleted file mode 100644 index 187374130a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableCellRenderer.java +++ /dev/null @@ -1,78 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; -import java.awt.Component; - -import javax.swing.BorderFactory; -import javax.swing.JTable; -import javax.swing.border.Border; -import javax.swing.table.DefaultTableCellRenderer; - -public class JTableCellRenderer extends DefaultTableCellRenderer -{ - - private JTableManager _manager = null; - private Color _origForeGroundColor = null; - private Color _highLightForeGroundColor = null; - private Color _highLightBackGroundColor = null; - - public JTableCellRenderer() - { - _origForeGroundColor = getForeground(); - _highLightBackGroundColor = Color.BLUE; - _highLightForeGroundColor = Color.YELLOW; - setOpaque(true); //MUST do this for background to show up. - } - - public void setTableManager(JTableManager manager) - { - _manager = manager; - } - - public Component getTableCellRendererComponent(JTable table, - Object color, boolean isSelected, - boolean hasFocus, int row, int column) - { - - Color newBackgroundColor = _manager.getCellBackgroundColor(row, column); - Color newForegroundColor = _manager.getCellForegroundColor(row, column); - String align = _manager.getAlignment(table.getColumnName(column)); - this.setValue(table.getValueAt(row, column)); - - if(align.equalsIgnoreCase("right")) - { - this.setHorizontalAlignment(RIGHT); - } - else if(align.equalsIgnoreCase("left")) - { - this.setHorizontalAlignment(LEFT); - } - else - { - this.setHorizontalAlignment(CENTER); - } - - // this.setText("" +table.getValueAt(row,column)); - - this.setBackground(newBackgroundColor); - this.setForeground(newForegroundColor); - - Border border = BorderFactory.createLineBorder(Color.BLACK); - if(isSelected) - { - this.setBackground(_highLightBackGroundColor); - this.setForeground(_highLightForeGroundColor); - this.setBorder(border); - } - else - { - if(newForegroundColor != null) - this.setForeground(newForegroundColor); - else - this.setForeground(_origForeGroundColor); - this.setBorder(null); - } - return this; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnComparator.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnComparator.java deleted file mode 100644 index a34c8189dd..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnComparator.java +++ /dev/null @@ -1,32 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.util.Comparator; - -public class JTableColumnComparator implements Comparator -{ - protected String _columnName = null; - protected boolean _isAscending; - - public int compare(Object obj1, Object obj2) - { - JTableRowData rowData1, rowData2; - - rowData1 = (JTableRowData) obj1; - rowData2 = (JTableRowData) obj2; - int ret = rowData1.compare(_columnName, rowData2); - if (! _isAscending) - { - ret *= -1; - } - return ret; - } - - public void initColumnInfo( String columnName, boolean isAscending ) - { - _columnName = columnName; - _isAscending = isAscending; - } - -} - - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDescriptor.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDescriptor.java deleted file mode 100644 index 98ed3e5d1e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDescriptor.java +++ /dev/null @@ -1,416 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import javax.swing.CellEditor; -import javax.swing.table.TableCellEditor; - -/** - * @author RajaramV - * - */ -public class JTableColumnDescriptor -{ - private String _name; - private boolean _display; - private static final int _defaultWidth = 65; - private int _width; - private boolean _isAscending; - private int _sortOrder; - private String _alignment = null; - private static final String _defaultAlignment = "left"; - private boolean _defaultDisplay = false; - private String _toolTipText = null; // column header tool tip - - - private boolean _isEditable; - private TableCellEditor _cellEditor; - - - public JTableColumnDescriptor() - { - - } - - /** - * Constructor - * @param columnName - name of the column - * @param display - true ----column should be displayed , false ---- column should not be displayed - * Assumes column's - * width = 65, sortOrder = -1, isAscending = false, alignment = left - */ - public JTableColumnDescriptor(String columnName, - boolean display) - { - setColumnDetails(columnName, display); - } - - /** - * Constructor - * @param columnName- name of the column - * @param columnWidth- width of the column - * Assumes column's - * sortOrder = -1, isAscending = false, alignment = left, display = false - */ - public JTableColumnDescriptor(String columnName, - int columnWidth) - { - int colWidth = columnWidth; - int sortOrder = -1; - boolean isAscending = false; - String alignment = _defaultAlignment; - boolean display = _defaultDisplay; - setColumnDetails(columnName, colWidth, display, isAscending, sortOrder, alignment); - } - - /** - * Constructor - * @param columnName- name of the column - * Assumes column's - * width = 65, , sortOrder = -1, isAscending = false, alignment = left, display = true - */ - public JTableColumnDescriptor(String columnName) - { - this(columnName, true); - } - - /** - * Constructor - * @param columnName- name of the column - * @param alignment- alignment(left/center/right) of the column - * By default column's - * width = 65, , sortOrder = -1, isAscending = false, display = false - */ - public JTableColumnDescriptor(String columnName, String alignment) - { - setColumnDetails(columnName, _defaultDisplay, alignment); - } - - /** - * Constructor - * @param columnName- name of the column - * @param alignment- alignment(left/center/right) of the column - * @param columnHeaderToolTipText- tooltip of column header - * By default column's - * width = 65, sortOrder = -1, isAscending = false, display = false - */ - public JTableColumnDescriptor(String columnName, String alignment, String columnHeaderToolTipText) - { - setColumnDetails(columnName, _defaultDisplay, alignment, columnHeaderToolTipText); - } - - /** - * Constructor - * @param columnName- name of the column - * @param display - true ----column should be displayed , false ---- column should not be displayed - * @param isAscending - true (ascending order sort) , false (descending order sort) - * @param sortOrder - order that says which column to be sorted first, second up untill fourth - * @param alignment- alignment(left/center/right) of the column - * @param columnHeaderToolTipText- tooltip of column header - * @param width- width of the column - */ - public JTableColumnDescriptor(String columnName, int width, - boolean display, boolean isAscending, - int sortOrder, String alignment, String columnHeaderToolTipText) - { - setColumnDetails(columnName, width, display, isAscending, sortOrder, alignment, columnHeaderToolTipText); - } - - /** - * Constructor - * @param columnName- name of the column - * @param display- true ----column should be displayed , false ---- column should not be displayed - * @param colWidth- width of the column - * By default column's - * sortOrder = -1, isAscending = false, display = false, alignment = left - */ - public JTableColumnDescriptor(String colName, - boolean display, int colWidth) - { - int sortOrder = -1; - boolean isAscending = false; - String alignment = _defaultAlignment; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment); - } - - /** - * Constructor - * @param columnName- name of the column - * @param display- true ----column should be displayed , false ---- column should not be displayed - * @param colWidth- width of the column - * @param alignment- alignment(left/center/right) of the column - * By default column's - * sortOrder = -1, isAscending = false - */ - public JTableColumnDescriptor(String colName, - boolean display, int colWidth, String alignment) - { - int sortOrder = -1; - boolean isAscending = false; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment); - } - - /** - * Constructor - * @param columnName- name of the column - * @param display - true ----column should be displayed , false ---- column should not be displayed - * @param width- width of the column - * @param alignment- alignment(left/center/right) of the column - * @param sortOrder - order that says which column to be sorted first, second up untill fourth - * By default column's - * sortOrder = -1, isAscending = false - */ - public JTableColumnDescriptor(String colName, - boolean display, int colWidth, String alignment, String columnHeaderToolTipText) - { - int sortOrder = -1; - boolean isAscending = false; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment, columnHeaderToolTipText); - } - - /** - * Constructor - * @param columnName- name of the column - * @param colWidth- width of the column - * @param alignment- alignment(left/center/right) of the column - * @param columnHeaderToolTipText- tooltip of column header - * By default column's - * sortOrder = -1, isAscending = false , display = false - */ - public JTableColumnDescriptor(String colName, - int colWidth, String alignment, String columnHeaderToolTipText) - { - int sortOrder = -1; - boolean isAscending = false; - boolean display = true; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment, columnHeaderToolTipText); - } - - - public JTableColumnDescriptor(JTableColumnDescriptor origRecord) - { - this(origRecord.getColumnName(), - origRecord.getDisplay()); - } - - /** - * Set the column details for specified column - * @param colName- name of the column - * By default column's - * width = 65, sortOrder = -1, isAscending = false, display = false, alignment = left - */ - public void setColumnDetails(String colName) - { - boolean display = _defaultDisplay; - setColumnDetails(colName,display); - } - - /** - * Set the column details for specified column - * @param colName- name of the column - * @param display - true ----column should be displayed , false ---- column should not be displayed - * By default column's - * width = 65, sortOrder = -1, isAscending = false, display = false, alignment = left - */ - public void setColumnDetails(String colName, - boolean display) - { - int colWidth = _defaultWidth; - int sortOrder = -1; - boolean isAscending = false; - String alignment = _defaultAlignment; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment); - } - - /** - * Set the column details for specified column - * @param colName- name of the column - * @param display - true ----column should be displayed , false ---- column should not be displayed - * @param alignment- alignment(left/center/right) of the column - * @param columnHeaderToolTipText- tooltip of column header - * By default column's - * width = 65, sortOrder = -1, isAscending = false - */ - public void setColumnDetails(String colName, - boolean display, String alignment, String columnHeaderToolTipText) - { - int colWidth = _defaultWidth; - int sortOrder = -1; - boolean isAscending = false; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment, columnHeaderToolTipText); - } - - /** - * Set the column details for specified column - * @param colName- name of the column - * @param display - true ----column should be displayed , false ---- column should not be displayed - * @param alignment- alignment(left/center/right) of the column - * By default column's - * width = 65, sortOrder = -1, isAscending = false - */ - public void setColumnDetails(String colName, - boolean display, String alignment) - { - int colWidth = _defaultWidth; - int sortOrder = -1; - boolean isAscending = false; - setColumnDetails(colName, colWidth, display, isAscending, sortOrder, alignment); - } - - /** - * Set the column details for specified column to default - * width = 65, sortOrder = -1, isAscending = false , display = false, alignment = left - */ - - public void setDefaultColumnDetails() - { - _display = _defaultDisplay; - _isAscending = false; - _sortOrder = -1; - _width = _defaultWidth; - _alignment = _defaultAlignment; - _isEditable = false; - } - - - public void setColumnDetails(String colName, - int colWidth, boolean display, - boolean isAscending, - int sortOrder, String alignment, String columnHeaderToolTipText, boolean isEditable) - { - _name = colName; - _display = display; - _width = colWidth; - _isAscending = isAscending; - _sortOrder = sortOrder; - _alignment = alignment; - _toolTipText = columnHeaderToolTipText; - _isEditable = isEditable; - } - - - public void setColumnDetails(String colName, - int colWidth, boolean display, - boolean isAscending, - int sortOrder, String alignment, String columnHeaderToolTipText) - { - _name = colName; - _display = display; - _width = colWidth; - _isAscending = isAscending; - _sortOrder = sortOrder; - _alignment = alignment; - _toolTipText = columnHeaderToolTipText; - } - - public void setColumnDetails(String colName, - int colWidth, boolean display, - boolean isAscending, - int sortOrder, String alignment) - { - _name = colName; - _display = display; - _width = colWidth; - _isAscending = isAscending; - _sortOrder = sortOrder; - _alignment = alignment; - _toolTipText = null; - } - - public void turnOnCellEditing(TableCellEditor cellEditor) - { - setCellEditor(cellEditor); - setIsEditable(true); - } - - public void turnOffCellEditing(TableCellEditor cellEditor) - { - setCellEditor(null); - setIsEditable(false); - } - - public String getColumnName() - { - String columnName = _name; - return columnName; - } - - public void setDisplay(boolean display) - { - _display = display; - } - - public boolean getDisplay() - { - return _display; - } - - public void setWidth(int width) - { - _width = width; - } - - public int getWidth() - { - return _width; - } - - public void setSortAsc(boolean isAscending) - { - _isAscending = isAscending; - } - - public boolean getSortAsc() - { - return _isAscending; - } - - public void setSortOrder(int sortOrder) - { - _sortOrder = sortOrder; - } - - public int getSortOrder() - { - return _sortOrder; - } - - public String getAlignment() - { - return _alignment; - } - - public void setAlignment(String alignment) - { - _alignment = alignment; - } - - public String getToolTipText() - { - return _toolTipText; - } - - public void setToolTip(String columnHeaderToolTipText) - { - _toolTipText = columnHeaderToolTipText; - } - - public void setIsEditable(boolean isEditable) - { - _isEditable = isEditable; - } - - public boolean isEditable() - { - return _isEditable; - } - - public void setCellEditor(TableCellEditor cellEditor) - { - _cellEditor = cellEditor; - } - - public TableCellEditor getCellEditor() - { - return _cellEditor; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDescriptorManager.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDescriptorManager.java deleted file mode 100644 index eefec1c6eb..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDescriptorManager.java +++ /dev/null @@ -1,716 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.util.*; - -public class JTableColumnDescriptorManager implements JTableColumnDisplaySettings -{ - private List _columnDescriptorList = null; - private Map _columnDescriptorMap = null; - private List _columnDescriptorForSortInfoList = null; - private static final int _totalSortToRecord = 4; - private Map _columnSettingMap = null; - - - public JTableColumnDescriptorManager(List columnDescriptorList) - { - _columnDescriptorList = columnDescriptorList; - _columnDescriptorMap = new HashMap(); - for(int i =0 ; i < _columnDescriptorList.size(); i++) - { - JTableColumnDescriptor columnDescription = (JTableColumnDescriptor) - _columnDescriptorList.get(i); - _columnDescriptorMap.put(columnDescription.getColumnName(), - columnDescription); - } - - _columnDescriptorForSortInfoList = new ArrayList(_totalSortToRecord); - - } - - public String getSettingsString() - { - String columnDisplaySetting[] = getDisplayedColumnSettings(); - String columnSortSetting[] = getColumnSortSettings(); - String settings = null; - - settings = "#COLUMN:Column Name|Column Width".concat("\n"); - if(columnDisplaySetting != null) - { - for(int i=0 ; i < columnDisplaySetting.length; i++) - { - settings = settings.concat(columnDisplaySetting[i]).concat("\n"); - } - } - settings = settings.concat("\n").concat("#SORT:Column Name|IsAscending|Sort Order").concat("\n"); - if(columnSortSetting != null) - { - for(int i=0; i < columnSortSetting.length; i++) - { - settings = settings.concat(columnSortSetting[i]).concat("\n"); - } - } - return settings; - } - - public List getSettingsListFromSettingsString(String settings) - { - List returnList = new ArrayList(); - int begIndex = 0; - while(settings != null) - { - int indexOfNewLine = settings.indexOf("\n"); - if(indexOfNewLine != -1) - { - String line = settings.subSequence(begIndex, indexOfNewLine).toString(); - returnList.add(line); - settings = settings.subSequence(indexOfNewLine+1, settings.length()).toString(); - } - else - { - break; - } - } - - return returnList; - } - - public List getTableSettingsForTokenMentioned(List settingsList, String tokenName) - { - List settingsListForTokenMentioned = new ArrayList (); - if(settingsList != null) - { - for(int i=0; i < settingsList.size(); i++) - { - String tempStr = settingsList.get(i).toString(); - if(!(tempStr.equals(""))) - { - String str = tempStr.subSequence(0,tokenName.length()).toString(); - if(str.compareTo(tokenName) == 0) - { - settingsListForTokenMentioned.add(settingsList.get(i)); - } - } - } - - } - return settingsListForTokenMentioned; - } - - public void setSettingsFromString(String settings) - { - String header = "JTableColumnDescriptorManager.setSettingsFromString(): "; - - if(settings != null) - { - _columnDescriptorForSortInfoList.clear(); //make the list empty - - List settingsList = getSettingsListFromSettingsString(settings); - - boolean isColumnDisplayTokenReadAndSet = readColumnDisplayToken(settingsList); - if(isColumnDisplayTokenReadAndSet) - { - readColumnSortToken(settingsList); - } - } - } - - private void readColumnSortToken(List settingsList) - { - String columnSortToken = "SORT:"; - String str; - - List columnNamesToSortList = new ArrayList(); - List columnSortDirectionList = new ArrayList(); - List columnSortOrderList = new ArrayList(); - - List stringListForSortToken = getTableSettingsForTokenMentioned(settingsList, columnSortToken); - - if(stringListForSortToken != null) - { - for(int i =0; i < stringListForSortToken.size(); i++) - { - str = stringListForSortToken.get(i).toString(); - str = str.substring(columnSortToken.length(), str.length()).trim(); - - String[] splitStr = str.split("\\|"); - if(splitStr != null && splitStr.length == 3) - { - if(isValidColumn(splitStr[0])) - { - columnNamesToSortList.add(splitStr[0]); - - boolean columnSortAsc = Boolean.parseBoolean(splitStr[1]); - columnSortDirectionList.add(columnSortAsc); - - columnSortOrderList.add(Integer.parseInt(splitStr[2])); - } - } - } - - for(int i=0; i < columnNamesToSortList.size(); i++) - { - selectColumnForSorting(columnNamesToSortList.get(i), columnSortDirectionList.get(i), - i, false); - } - } - } - - private boolean readColumnDisplayToken(List settingsList) - { - String columnDisplayToken = "COLUMN:"; - String str; - boolean isColumnDisplayTokenReadAndSet = false; - - List columnNamesToDisplayList = new ArrayList(); - List columnWidthList = new ArrayList(); - - String columnNamesToDisplay[] = null; - int columnWidths[] = null; - - List stringListForColumnDisplayToken = getTableSettingsForTokenMentioned(settingsList, columnDisplayToken); - - if(stringListForColumnDisplayToken != null) - { - for(int i =0; i < stringListForColumnDisplayToken.size(); i++) - { - str = stringListForColumnDisplayToken.get(i).toString(); - str = str.substring(columnDisplayToken.length(), str.length()).trim(); - String[] splitStr = str.split("\\|"); - if(splitStr != null && splitStr.length == 2) - { - if(isValidColumn(splitStr[0])) - { - columnNamesToDisplayList.add(splitStr[0]); - int columnWidth = Integer.parseInt(splitStr[1]); - columnWidthList.add(columnWidth); - } - } - } - columnNamesToDisplay = new String[columnNamesToDisplayList.size()]; - columnWidths = new int[columnNamesToDisplayList.size()]; - - for(int i=0; i < columnNamesToDisplayList.size(); i++) - { - columnNamesToDisplay[i] = columnNamesToDisplayList.get(i); - columnWidths[i] = columnWidthList.get(i); - } - } - - if(columnNamesToDisplay!= null ) - { - setDisplayableColumns(columnNamesToDisplay); - setWidthOfDisplayedColumns(columnWidths); - isColumnDisplayTokenReadAndSet = true; - } - - return isColumnDisplayTokenReadAndSet; - } - - protected boolean isValidColumn(String columnName) - { - boolean isValidColumn = false; - Set validColumnNamesSet = getSetOfValidColumnNames(); - - if( validColumnNamesSet.contains(columnName) ) - { - isValidColumn = true; - } - - if( ! isValidColumn) - { - System.out.println("Invalid column name ["+ columnName +"] in settings file"); - System.out.println("Check the settings file..."); - } - return isValidColumn; - } - - protected String[] getAllowedColumnNamesArray() - { - String[] allowedColNames = new String[_columnDescriptorList.size()]; - - for(int i = 0; i < allowedColNames.length ; i++) - { - JTableColumnDescriptor columnDescriptor; - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - allowedColNames[i] = columnDescriptor.getColumnName(); - } - - return allowedColNames; - } - - protected Set getSetOfValidColumnNames() - { - // String header = "JTableColumnDescriptorManager.getSetOfValidColumnNames(): "; - Set validColumnNamesSet = new HashSet(); - - JTableColumnDescriptor columnDescription = null; - for(int j=0; j < _columnDescriptorList.size() ;j++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(j); - validColumnNamesSet.add(columnDescription.getColumnName()); - // System.out.println(header + "columnName[" + j +"] = " + columnDescription.getColumnName()); - } - return validColumnNamesSet; - } - - - protected JTableColumnDescriptor getColumnDescriptorByName(String columName) - { - return _columnDescriptorMap.get(columName); - } - - protected void setDisplayableColumns(String columnNamesSelected[]) - { - for(int i=0;i < _columnDescriptorList.size(); i++) - { - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - columnDescription.setDisplay(false); - for(int j=0; j < columnNamesSelected.length ;j++) - { - if( columnDescription.getColumnName().compareTo(columnNamesSelected[j]) == 0 ) - { - columnDescription.setDisplay(true); - } - } - } - - //Rearrange the list in such a way that the descriptor of selected column names - //Appear in the top of the list, and they are added in the same order as - //the selected column names - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - - for(int i = 0 ; i < columnNamesSelected.length; i++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorMap. - get(columnNamesSelected[i]); - if(columnDescription != null) - { - _columnDescriptorList.remove(columnDescription); - _columnDescriptorList.add(i, columnDescription); - } - } - - } - - protected List getColumnDescriptorList() - { - return _columnDescriptorList; - } - - protected String[] getAllColumnNamesInColumnDescriptorManager() - { - String columnNames[] = new String[_columnDescriptorList.size()]; - if(_columnDescriptorList.size() > 0) - { - columnNames = new String[_columnDescriptorList.size()]; - for(int i=0;i < _columnDescriptorList.size(); i++) - { - JTableColumnDescriptor columnDescription = new JTableColumnDescriptor(); - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - columnNames[i] = columnDescription.getColumnName(); - } - } - - return columnNames; - } - - protected String[] getColumnNamesThatAreCurrentlyDisplayed() - { - String columnNames[] = null; - int cnt=0; - JTableColumnDescriptor columnDescription; - - for(int i=0;i < _columnDescriptorList.size(); i++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - if ( columnDescription.getDisplay()) - cnt++; - } - if(cnt > 0) - { - columnNames = new String[cnt]; - int j=0; - for(int i=0;i < _columnDescriptorList.size(); i++) - { - columnDescription = (JTableColumnDescriptor) _columnDescriptorList.get(i); - if ( columnDescription.getDisplay()) - { - columnNames[j++] = columnDescription.getColumnName(); - - } - } - } - return columnNames; - } - - protected void swapColumnsInList(String columnName1, String columnName2) - { - JTableColumnDescriptor columnDescriptor1, columnDescriptor2; - columnDescriptor1 = (JTableColumnDescriptor) _columnDescriptorMap. - get(columnName1); - columnDescriptor2 = (JTableColumnDescriptor) _columnDescriptorMap. - get(columnName2); - - int index1 = _columnDescriptorList.indexOf(columnDescriptor1); - int index2 = _columnDescriptorList.indexOf(columnDescriptor2); - - _columnDescriptorList.set(index1, columnDescriptor2); - _columnDescriptorList.set(index2, columnDescriptor1); - - } - - protected JTableColumnDisplaySettings getTableColumnSettings() - { - return this; - } - - protected void clearSort() - { - String header = "JTableColumnDescriptorManager.clearSort(): "; - if(_columnDescriptorForSortInfoList != null) - { - _columnDescriptorForSortInfoList.clear(); - } - } - - protected void setSortInfoNotBasedOnUserClicks(String columnNamesToSort[], boolean columnSortOrder[], int columnSortNumber[]) - { - setSortOrderOfColumns(columnSortOrder, columnNamesToSort, columnSortNumber); - - for(int i=0; i < columnSortNumber.length; i++) - { - if(columnSortNumber[i] != -1) - { - selectColumnForSorting(columnNamesToSort[i], columnSortOrder[i], - columnSortNumber[i], false); - } - } - - } - - protected String[] getDisplayedColumnSettings() - { - String columnNamesInDisplay[] = getColumnNamesThatAreCurrentlyDisplayed(); - - String columnSetting[] = new String[columnNamesInDisplay.length]; - - JTableColumnDescriptor columnDescriptor; - int cnt=0; - for(int i=0 ; i < _columnDescriptorList.size(); i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - if(columnDescriptor.getDisplay()) - { - String columnName = columnDescriptor.getColumnName(); - int columnWidth = columnDescriptor.getWidth(); - columnSetting[cnt++] = "COLUMN:"+columnName+"|"+columnWidth; - } - } - - return columnSetting; - } - - protected int[] getWidthOfDisplayedColumns() - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - int columnWidths[] = new int[columnsDisplayed.length]; - - - JTableColumnDescriptor columnDescriptor = null; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorMap.get(columnsDisplayed[i]); - columnWidths[i] = columnDescriptor.getWidth(); - } - - return columnWidths; - } - - protected boolean[] getIsEditableArray() - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - boolean[] isEditableArray = new boolean[columnsDisplayed.length]; - - JTableColumnDescriptor columnDescriptor = null; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorMap.get(columnsDisplayed[i]); - isEditableArray[i] = columnDescriptor.isEditable(); - } - - return isEditableArray; - } - - protected String[] getAlignmentOfDisplayedColumns() - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - String columnAlignments[] = new String[columnsDisplayed.length]; - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnAlignments[i] = columnDescriptor.getAlignment(); - } - - return columnAlignments; - } - - protected boolean[] getSortOrderOfAllColumns() - { - String allColumns[] = getAllColumnNamesInColumnDescriptorManager(); - - boolean columnsAscOrDescArray[] = new boolean[allColumns.length]; - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < allColumns.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(allColumns[i]); - columnsAscOrDescArray[i] = columnDescriptor.getSortAsc(); - } - return columnsAscOrDescArray; - } - - protected int getSortOrderNumberForColumn(String columnName) - { - int columnSortOrder = -1; - - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnName); - columnSortOrder = columnDescriptor.getSortOrder(); - return columnSortOrder; - } - - protected boolean getSortDirectionForColumn(String columnName) - { - boolean isAscending = false; - - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) _columnDescriptorMap.get(columnName); - isAscending = columnDescriptor.getSortAsc(); - - return isAscending; - } - - protected void setWidthOfDisplayedColumns(int columnWidths[]) - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnDescriptor.setWidth(columnWidths[i]); - } - } - - protected void setAlignmentOfDisplayedColumns(String columnAlignments[]) - { - String columnsDisplayed[] = getColumnNamesThatAreCurrentlyDisplayed(); - - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < columnsDisplayed.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorMap.get(columnsDisplayed[i]); - columnDescriptor.setAlignment(columnAlignments[i]); - } - } - - - // ----------------------------------------------------------------------------------------------------------------------- - protected void selectColumnForSorting(String columnName, boolean isAscending, int positionToInsert, - boolean shouldReverseAscOrDescOrder) - { - // String header = "JTableColumnDescriptorManager.selectColumnForSorting() [new]: "; - - //printColumnsToSortBy("before " + header); - - JTableColumnDescriptor columnDescription = (JTableColumnDescriptor) _columnDescriptorMap.get(columnName); - - if(shouldReverseAscOrDescOrder) //flip the sort order of this column - { - isAscending = columnDescription.getSortAsc(); // get prev sort direction (asc or desc) - columnDescription.setSortAsc( ! isAscending ); // reverse the prev asc to desc or vice versa - } - else - { - columnDescription.setSortAsc( isAscending );// set the sort direction passed as argument to this method - } - - columnDescription.setSortOrder(positionToInsert); - - //put in the correct order relative to other columns - int index = 0; - - index = _columnDescriptorForSortInfoList.indexOf(columnDescription); - - if(index != -1) //the column is already in the list - { - _columnDescriptorForSortInfoList.remove(index); // remove it - _columnDescriptorForSortInfoList.add(0, columnDescription); //add it to the front of the list - } - else //it is not already in the list - { - if (_columnDescriptorForSortInfoList.size() >= _totalSortToRecord) //if we need to dump a sort column, because we have too many - { - int lastIndex = _columnDescriptorForSortInfoList.size()-1; - _columnDescriptorForSortInfoList.remove(lastIndex); - } - - if( positionToInsert == -1) //we just want it at the front - { - _columnDescriptorForSortInfoList.add(0, columnDescription); - } - else //we want it at a specific position - { - _columnDescriptorForSortInfoList.add(positionToInsert, columnDescription); - } - - } //end of else it is not already in the list - - //reset the sort order integer value for the descriptors - for (int i = 0; i < _columnDescriptorForSortInfoList.size(); i++) - { - JTableColumnDescriptor desc = (JTableColumnDescriptor) _columnDescriptorForSortInfoList.get(i); - desc.setSortOrder(i); - } - - // printColumnsToSortBy("after " + header); - - } //end of selectColumnForSorting - - // ------------------------------------------------------------------------------------------------------ - - private void printColumnsToSortBy(String message) - { - String header = "JTableColumnDescriptorList.printColumnstoSortBy() "; - - System.out.println(message); - - for (int i = 0; i < _columnDescriptorForSortInfoList.size() ; i++) - { - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) _columnDescriptorForSortInfoList.get(i); - if (columnDescriptor != null) - { - String direction = "ASC"; - - if (! columnDescriptor.getSortAsc()) - { - direction = "DESC"; - } - System.out.println(i + " " + columnDescriptor.getColumnName() + - " " + columnDescriptor.getSortOrder() + " " + direction); - } - else - { - System.out.println(header + " column at index " + i + " is null"); - } - } - - System.out.println(); - - } - - // ------------------------------------------------------------------------------------------------------ - protected String[] getColumnNamesForSortToBeDone() - { - - String columnNamesForSorting[] = new String[_columnDescriptorForSortInfoList.size()]; - - for(int i=0; i < columnNamesForSorting.length; i++) - { - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorForSortInfoList.get(i); - columnNamesForSorting[i] = columnDescriptor.getColumnName(); - } - return columnNamesForSorting; - - } - - // ------------------------------------------------------------------------------------------------------ - protected int[] getSortOrderForSortedColumnNames() - { - - int sortOrderForSortedColumns[] = new int[_columnDescriptorForSortInfoList.size()]; - - for(int i=0; i < sortOrderForSortedColumns.length; i++) - { - JTableColumnDescriptor columnDescriptor = (JTableColumnDescriptor) - _columnDescriptorForSortInfoList.get(i); - sortOrderForSortedColumns[i] = columnDescriptor.getSortOrder(); - } - return sortOrderForSortedColumns; - - } - -// ------------------------------------------------------------------------------------------------------ - - private String[] getColumnSortSettings() - { - String columnSortSetting[] = null; - JTableColumnDescriptor columnDescriptor; - - String header = "JTableColumnDescriptorManager.getColumnSortSettings(): "; - if (_columnDescriptorForSortInfoList.size() > 0) - { - int j=0; - columnSortSetting = new String[_columnDescriptorForSortInfoList.size()]; - _columnSettingMap = new HashMap(); - for(int i=0 ; i < _columnDescriptorList.size(); i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - - String columnName = columnDescriptor.getColumnName(); - boolean isAscending = columnDescriptor.getSortAsc(); - - int columnSortOrder = -1; - int index = _columnDescriptorForSortInfoList.indexOf(columnDescriptor); - columnSortOrder = index; - - - if(columnSortOrder != -1) //if this column is to be sorted by - { - _columnSettingMap.put(new Integer(columnSortOrder).toString() , columnDescriptor); - columnSortSetting[j++] = "SORT:"+columnName+"|"+ isAscending+"|"+columnSortOrder; - } - } - } - String finalSortSetting[]= null; - if(columnSortSetting != null) - { - if(columnSortSetting.length > _totalSortToRecord) - finalSortSetting = new String[_totalSortToRecord]; - else - finalSortSetting = new String[columnSortSetting.length]; - for(int i=0; i < finalSortSetting.length; i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnSettingMap.get(new Integer(i).toString()); - finalSortSetting[i] = "SORT:"+columnDescriptor.getColumnName()+"|"+ columnDescriptor.getSortAsc()+"|"+i; - } - } - return finalSortSetting; - } - - private void setSortOrderOfColumns(boolean columnSortOrders[], String columnNamesToSort[], int columnSortOrderNumber[]) - { - JTableColumnDescriptor columnDescriptor; - for(int i=0; i < _columnDescriptorList.size(); i++) - { - columnDescriptor = (JTableColumnDescriptor) _columnDescriptorList.get(i); - for(int j=0; j< columnNamesToSort.length ; j++) - { - //check if the column name is chosen for sort and then set the sort info - if(columnDescriptor.getColumnName().compareTo(columnNamesToSort[j]) == 0) - { - columnDescriptor.setSortAsc(columnSortOrders[j]); - columnDescriptor.setSortOrder(columnSortOrderNumber[j]); - } - } - } - } - -} //end of JTableColumnDescriptor diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDisplaySettings.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDisplaySettings.java deleted file mode 100644 index 3c669a904e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableColumnDisplaySettings.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -public interface JTableColumnDisplaySettings -{ - String getSettingsString(); - - void setSettingsFromString(String settings); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableHeaderRenderer.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableHeaderRenderer.java deleted file mode 100644 index 6e5962035a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableHeaderRenderer.java +++ /dev/null @@ -1,92 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Component; -import java.awt.Dimension; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.JTable; -import javax.swing.SwingConstants; -import javax.swing.UIManager; - -public class JTableHeaderRenderer extends JTableCellRenderer -{ - private JTableManager _tableManager = null; - private Map _sortedColumnsAndTheirOrdersMap = null; - - public JTableHeaderRenderer(JTableManager tableManager, Dimension columnHeaderPreferredSize) - { - _tableManager = tableManager; - determineColumnSortDetails(); - setHorizontalAlignment(SwingConstants.CENTER); - setVerticalAlignment(SwingConstants.TOP); - - if (columnHeaderPreferredSize != null) - { - setPreferredSize(columnHeaderPreferredSize); - } - - setOpaque(true); - - // This call is needed because DefaultTableCellRenderer calls setBorder() - // in its constructor, which is executed after updateUI() - setBorder(UIManager.getBorder("TableHeader.cellBorder")); - } - - public void setTableManager(JTableManager manager) - { - _tableManager = manager; - determineColumnSortDetails(); - } - - public void determineColumnSortDetails() - { - _sortedColumnsAndTheirOrdersMap = new HashMap(); - String[] columnNamesForSortToBeDone = _tableManager.getColumnNamesForSortToBeDone(); - int[] sortOrderForSortedColumns = _tableManager.getSortOrderForSortedColumnNames(); - for(int i=0; i < columnNamesForSortToBeDone.length; i++) - { - _sortedColumnsAndTheirOrdersMap.put(columnNamesForSortToBeDone[i], sortOrderForSortedColumns[i]); - } - } - - public void updateUI() - { - super.updateUI(); - } - - public Component getTableCellRendererComponent(JTable table, Object value, - boolean selected, boolean focused, int row, int column) - { - - // String header = "JTableHeaderRenderer.getTableCellRendererComponent()"; - // System.out.println(header + "called."); - - final String upArrowString = "\u25BC"; //upArrow unicode for Times New Roman font - final String downArrowString = "\u25B2";//downArrow unicode for Times New Roman font - String arrowString = downArrowString; - - String str = value.toString(); - String columnHeaderString = value.toString(); - Integer columnSortOrder = (Integer) _sortedColumnsAndTheirOrdersMap.get(columnHeaderString); - if(columnSortOrder != null) - { - // System.out.println(columnHeaderString + "|"+ columnSortOrder); - if ( _tableManager.isColumnAsc(columnHeaderString) ) - { - arrowString = upArrowString; - } - - str = "" + value + " " + arrowString + "" + - (columnSortOrder.intValue() + 1) +""; - - } - else - { - str = "" + value +""; - } - setValue(str); - return this; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableManager.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableManager.java deleted file mode 100644 index ac6f3c9cbf..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableManager.java +++ /dev/null @@ -1,129 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.util.EventListener; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; -import javax.swing.JTable; - -public interface JTableManager -{ - - void sort(String columnName, boolean isAUserClick, boolean isAscending); - - void sort(boolean isAUserClick); - - String[][] getDisplayRowDataArray(); - - JTableRowData getRowData(int i); - - String[] getColumnNamesThatAreCurrentlyDisplayed(); - - Color getCellBackgroundColor(int row, int column); - - Color getCellForegroundColor(int row, int column); - - Dimension getSizeForJScrollPane(); - - void swapColumns(String columnName1, String columnName2); - - int[] getWidthOfDisplayedColumns(); - - boolean[] getIsEditableArray(); - - String[] getAlignmentOfDisplayedColumns(); - - void setWidthOfDisplayedColumns(int columnWidths[]); - - void setAlignmentOfDisplayedColumns(String columnAlignments[]); - - void setColumnsForDisplay(String columnNamesSelected[]); - - void setDisplayableColumns(String columnNamesSelected[], - boolean changeSortOrder, boolean firstDraw); - - void selectColumnForSorting(String columnName); - - String[] getColumnNamesForSortToBeDone(); - - public int[] getSortOrderForSortedColumnNames(); - - public void setCellEditors(JTable table); - - void setChangedAllRowDataList(List allRowDataList); - - void resetSortHelper(); - - void setSortInfoNotBasedOnUserClicks(String columnNamesToSort[], boolean columnSortOrder[], int columnSortNumber[]); - - void clearSort(); - - JTableColumnDisplaySettings getTableSettings(); - - public void addTableListener(EventListener eventListener); - - public void removeTableListener(EventListener eventListener); - - public JScrollPane getJScrollPane(); - - public void setPreferredSizeForJScrollPane(Dimension dimension); - - public int[] getSelectedRowIndices(); - - public List getSelectedRowsData(); - - public int getMousePointedRowIndex(Point p); - - public int getMousePointedColumnIndex(Point p); - - public String getColumnNameAtIndex(int columnIndex) ; - - public JTableRowData getSelectedRowData(int rowIndex); - - public void setRowToolTipText(String str); - - public void refreshDisplay(); - - public List getAllRowDataList(); - - public String[] getAllowedColumnNamesArray(); - - /** - * Find the index of the first row containing the value - * @param uniqueValueForRow - * @return index - */ - public int getTheRowIndexToHighLightBasedOnValue(String uniqueValueForRow); - - /** - * Find the index of the first row containing the value - * in the columnName specified - * @param uniqueValueForRow - * @param columnName - * @return index - */ - public int getTheRowIndexToHighLightBasedOnValue(String uniqueValueForRow, String columnName); - - public void selectRows(int initialRowToSelect, int finalRowToSelect); - - public void selectRows(int rowIndices[]); - - public void deselectRows(int rowIndices[]); - - public void deselectRows(int initialRowToRemoveSelection, int finalRowToRemoveSelection); - - public void setVerifyInputWhenFocusTarget(boolean verify); - - public String getAlignment(String columnName); - - public String getColumnHeaderToolTipText(String columnName); - - public boolean isColumnAsc(String columnName); - - public void invokeColumnSelector(JFrame frame); - - } diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableModel.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableModel.java deleted file mode 100644 index 909d160bc4..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableModel.java +++ /dev/null @@ -1,148 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import javax.swing.table.DefaultTableModel; - -public class JTableModel extends DefaultTableModel -{ - private String[] _columnNames = null; - - private Object[][] _data = null; - private int[] _columnWidths = null; - private String[] _columnAlignments = null; - private boolean[] _isEditableArray = null; - - - public JTableModel( String[] colNames, String[][] dataStringArray, - int[] columnWidth, String[] columnAlignment) - { - _columnNames = colNames; - _data = dataStringArray; - _columnWidths = columnWidth; - _columnAlignments = columnAlignment; - _isEditableArray = new boolean[colNames.length]; - } - - public void setChangedColumnNames(String colNames[]) - { - _columnNames = colNames; - } - - public void setChangedColumnWidths(int columnWidths[]) - { - _columnWidths = columnWidths; - } - - public void setChangedColumnAlignments(String columnAlignments[]) - { - _columnAlignments = columnAlignments; - } - - public void setChangedIsEditableArray(boolean[] isEditableArray) - { - _isEditableArray = isEditableArray; - } - - - public void updateData( String[][] dataStringArray ) - { - _data = dataStringArray; - } - - public int getColumnCount() - { - return _columnNames.length; - } - - public int getRowCount() - { - if ( _data != null ) - { - return _data.length; - } - else - { - return 0; - } - } - - public String getColumnName(int col) - { - return _columnNames[col]; - } - - public int getColumnNumber(String columnName) - { - int index = -1; - for(int i=0; i < _columnNames.length; i++) - { - if(_columnNames[i].equals(columnName)) - { - index =i; - break; - } - } - return index; - } - - public String getColumnAlignment(String columnName) - { - String alignment = null; - int index = -1; - for(int i=0; i <_columnNames.length; i++) - { - if(_columnNames[i].equals(columnName)) - { - index =i; - break; - } - } - - alignment = _columnAlignments[index]; - return alignment; - } - - public int getColumnWidth(String columnName) - { - int width = -1; - int index = -1; - for(int i=0; i <_columnNames.length; i++) - { - if(_columnNames[i].equals(columnName)) - { - index =i; - break; - } - } - - width = _columnWidths[index]; - return width; - } - - public Object getValueAt(int row, int col) - { - return _data[row][col]; - } - - public void setValueAt(Object object, int row, int col) - { - _data[row][col] = object; - fireTableCellUpdated(row, col); - } - - public void setIsCellColumnEditable(boolean value, int col) - { - _isEditableArray[col] = value; - } - - public boolean isCellEditable(int row, int col) - { - if ( ( row == 1) && ( col == 1) ) - { - System.out.println ( _isEditableArray[col]); - - } - return _isEditableArray[col]; - // return false; - } -} - diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableRowData.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableRowData.java deleted file mode 100644 index d0aa71b48f..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableRowData.java +++ /dev/null @@ -1,18 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; - -public interface JTableRowData -{ - int compare(String columnName, JTableRowData object); - - String getDataValue(String ColumnName); - - Color getCellBackgroundColor(String columnName); - - Color getCellForegroundColor(String columnName); - - void addCell(BaseTableCell cell); - - BaseTableCell getCell(String columnName); -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableSortHelper.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableSortHelper.java deleted file mode 100644 index 18f44323d7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/JTableSortHelper.java +++ /dev/null @@ -1,120 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class JTableSortHelper -{ - private String[] _columnNameArray = null; - private List _sortColumnOrderList = new ArrayList(); - private boolean[] _isSortAscOrDescArray = null; - private int _columnCount = 0; - private JTableColumnComparator _columnComparator = new JTableColumnComparator(); - - public JTableSortHelper(String[] columnNameArray ) - { - _columnNameArray = columnNameArray; - _columnCount = _columnNameArray.length; - _isSortAscOrDescArray = new boolean[ _columnCount ]; - initialize(); - } - - public void setChangedColumns(String[] columnNameArray) - { - _columnNameArray = columnNameArray; - _columnCount = _columnNameArray.length; - } - - public void setChangedSortOrderArray(boolean sortOrderArray[]) - { - _isSortAscOrDescArray = sortOrderArray; - } - - public boolean[] getsortOrderArray() - { - return _isSortAscOrDescArray; - } - - private void initialize() - { - initLinkedListAndOrderArray(); - } - - public void sortList( List listToSort, String columnName, boolean isAUserClick , boolean isAscending) - { - int index = -1; - for(int i=0; i < _columnNameArray.length; i++) - { - if(_columnNameArray[i].compareTo(columnName) == 0 ) - { - index = i; - break; - } - } - _columnComparator.initColumnInfo( columnName, isAscending ); - - Collections.sort( listToSort, _columnComparator ); - - if (isAUserClick) - { - _isSortAscOrDescArray[ index ] = ! isAscending; - } - - } - - public boolean determineAscOrDescForColumnName(String columnName) - { - boolean result; - int matchIndex = findIndexOfColumnNameInColumnNamesArray(columnName); - if(matchIndex != -1) - result = _isSortAscOrDescArray[matchIndex]; - else - result = false; //default is desc - - return result; - } - - public boolean isColumnAsc(String columnName) - { - boolean result = false;//default is desc - int matchIndex = findIndexOfColumnNameInColumnNamesArray(columnName); - if(matchIndex != -1) - result = _isSortAscOrDescArray[matchIndex]; - - return result; - } - - private int findIndexOfColumnNameInColumnNamesArray(String columnName) - { - int matchIndex = -1; - for(int i=0; i < _columnNameArray.length; i++) - { - if(_columnNameArray[i].equals(columnName)) - { - matchIndex = i; - break; - } - } - return matchIndex; - } - - public void sortWithoutMemory( List listToSort, int column, boolean isAscendingOrder ) - { - String columnName = _columnNameArray[ column ]; - boolean sortAscOrder = isAscendingOrder; - - _columnComparator.initColumnInfo( columnName, sortAscOrder ); - Collections.sort( listToSort, _columnComparator ); - } - - private void initLinkedListAndOrderArray() - { - for ( int i = 0; i < _columnCount; i++ ) - { - _isSortAscOrDescArray[ i ] = true; - _sortColumnOrderList.add( i, new Integer( i ) ); - } - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/ScrollableJTable.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/ScrollableJTable.java deleted file mode 100644 index bead42b7fa..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/ScrollableJTable.java +++ /dev/null @@ -1,640 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.event.*; -import java.util.ArrayList; -import java.util.EventListener; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.awt.*; - -import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TableColumnModelEvent; -import javax.swing.event.TableColumnModelListener; -import javax.swing.event.TableModelListener; -import javax.swing.table.TableCellEditor; -import javax.swing.table.TableColumn; - -/** - * @author RajaramV - * - */ - -public class ScrollableJTable -{ - private JTable _table; - private JTableManager _tableManager; - private JTableModel _tableModel; - private JTableCellRenderer _cellRenderer = null; - private JScrollPane _tableScrollPane = null; - private boolean _sortFlag = false; - private boolean _moveFlag = false; - private boolean _firstDraw = false; - - private Dimension _columnHeaderPreferredSize = null; - - private Set _listenerSet = new HashSet(); - private int _tableRowSelectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION; - - /* - public ScrollableJTable(JTableManager tableManager) - { - _tableManager = tableManager; - _cellRenderer = new JTableCellRenderer(); - _cellRenderer.setTableManager(_tableManager); - } - */ - - public ScrollableJTable(JTableManager tableManager, Dimension columnHeaderPreferredSize) - { - _columnHeaderPreferredSize = columnHeaderPreferredSize; - - _tableManager = tableManager; - _cellRenderer = new JTableCellRenderer(); - _cellRenderer.setTableManager(_tableManager); - } - - public ScrollableJTable(JTableManager tableManager, int tableRowSelectionMode) - { - _tableManager = tableManager; - _cellRenderer = new JTableCellRenderer(); - _cellRenderer.setTableManager(_tableManager); - _tableRowSelectionMode = tableRowSelectionMode; - } - - - public JScrollPane getJScrollPane() - { - return _tableScrollPane; - } - - protected void setPreferredSizeForJScrollPane(Dimension dimension) - { - _tableScrollPane.setPreferredSize(dimension); - } - - protected Dimension getSizeForJScrollPane() - { - return _tableScrollPane.getSize(); - } - - protected void createTable(boolean firstDraw) - { - _firstDraw = firstDraw; - _tableModel = null; - Container scrollPaneContainer = null; - JScrollPane oldTableScrollPane = _tableScrollPane; - Dimension oldPreferredSizeForTableScrollPane = null; - Point oldPosition = null; - if(_tableScrollPane != null) - { - oldPreferredSizeForTableScrollPane = _tableScrollPane.getPreferredSize(); - oldPosition = _tableScrollPane.getViewport().getViewPosition(); - } - - String columnNamesToBeDisplayed[] = _tableManager.getColumnNamesThatAreCurrentlyDisplayed(); - - String rowData[][] = _tableManager.getDisplayRowDataArray(); - - int widthOfColumnsDisplayed[] = _tableManager.getWidthOfDisplayedColumns(); - - String[] alignmentOfColumnsDisplayed = _tableManager.getAlignmentOfDisplayedColumns(); - - _tableModel = new JTableModel(columnNamesToBeDisplayed, rowData, - widthOfColumnsDisplayed, alignmentOfColumnsDisplayed); - - _table = new JTable(_tableModel); - _table.setSelectionMode(_tableRowSelectionMode); - - // make the user's edits stored without need for type "return" key or click - //on JTable - _table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); - - - - int cnt=0; - Iterator it = _listenerSet.iterator(); - while(it.hasNext() && cnt++ < _listenerSet.size()) - { - addTableListeners((EventListener)it.next()); - } - - _table.setOpaque(false); - _table.setDefaultRenderer(Object.class, _cellRenderer); - - _table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - - setColumnListeners(); - - _tableManager.setCellEditors(_table); - - _tableScrollPane = new JScrollPane(_table); - - if(oldTableScrollPane !=null) - { - scrollPaneContainer = oldTableScrollPane.getParent(); - } - - if (scrollPaneContainer != null) - { - scrollPaneContainer.setVisible(false); - scrollPaneContainer.remove(oldTableScrollPane); - _tableScrollPane.setPreferredSize(oldPreferredSizeForTableScrollPane); - _tableScrollPane.getViewport().setViewPosition(oldPosition); - scrollPaneContainer.add(_tableScrollPane); - scrollPaneContainer.setVisible(true); - } - - sort(); - - for(int i=0; i < columnNamesToBeDisplayed.length; i++) - { - setWidth(columnNamesToBeDisplayed[i], widthOfColumnsDisplayed[i]); - } - } - //------------------------------------------------------------------------------ - protected void sort() - { - _tableManager.sort(true); - refreshAfterSort(); - } - //------------------------------------------------------------------------------ - - protected void setVerifyInputWhenFocusTarget(boolean verify) - { - _table.setVerifyInputWhenFocusTarget(verify); - } - - //------------------------------------------------------------------------------ - /** - * Select the rows that are passed in as argument and - * set the view port to the first selected row if setViewPort is true - */ - protected void selectRows(int rowIndices[], boolean setViewPort) - { - Color highLightBackGroundColor = Color.BLUE; - Color highLightForeGroundColor = Color.YELLOW; - for(int i=0; i < rowIndices.length; i++) - { - _table.getSelectionModel().addSelectionInterval(rowIndices[i], rowIndices[i]); - _table.setSelectionBackground(highLightBackGroundColor); - _table.setSelectionForeground(highLightForeGroundColor); - if(setViewPort) - { - Rectangle rect = _table.getCellRect(rowIndices[0], 0, true); - _tableScrollPane.getViewport().setViewPosition(rect.getLocation()); - } - } - } - - //------------------------------------------------------------------------------ - /** - * Select the rows that are passed in as argument and set the view port to the first selected row - */ - protected void selectRows(int rowIndices[]) - { - selectRows(rowIndices, true); - } - - //------------------------------------------------------------------------------ - /** - * Deselect the rows that are passed in as argument - */ - protected void deselectRows(int rowIndices[]) - { - for(int i=0; i < rowIndices.length; i++) - { - _table.getSelectionModel().removeSelectionInterval(rowIndices[i], rowIndices[i]); - } - } - - //------------------------------------------------------------------------------ - /** - * Deselect the previously selected rows - */ - protected void deselectRows(int initialRowToRemoveSelection, int finalRowToRemoveSelection) - { - _table.getSelectionModel().removeSelectionInterval(initialRowToRemoveSelection, finalRowToRemoveSelection); - } - - //------------------------------------------------------------------------------ - /** - * Select the rows from initialRowToSelect till finalRowToSelect - * that are passed in as argument and set the view port to the first selected row - */ - protected void selectRows(int initialRowToSelect, int finalRowToSelect) - { - selectRows( initialRowToSelect, finalRowToSelect, true); - } - - //------------------------------------------------------------------------------ - /** - * Select the rows from initialRowToSelect till finalRowToSelect - * that are passed in as argument and set the view port to the first selected row if setViewPort is true - */ - protected void selectRows(int initialRowToSelect, int finalRowToSelect, boolean setViewPort) - { - Color highLightBackGroundColor = Color.BLUE; - Color highLightForeGroundColor = Color.YELLOW; - _table.setRowSelectionInterval(initialRowToSelect, finalRowToSelect); - _table.setSelectionBackground(highLightBackGroundColor); - _table.setSelectionForeground(highLightForeGroundColor); - if(setViewPort) - { - Rectangle rect = _table.getCellRect(initialRowToSelect, 0, true); - _tableScrollPane.getViewport().setViewPosition(rect.getLocation()); - } - } - //------------------------------------------------------------------------------ - private void setColumnWidths() - { - //String header = "ScrollableJTable.setColumnWidths(); "; - //System.out.println(header + "called." ); - - if(_table!=null) - { - int numOfCols = _table.getColumnCount(); - for(int i=0; i < numOfCols; i++) - { - String columnName = _tableModel.getColumnName(i); - int columnWidth = _tableModel.getColumnWidth(columnName); - int columnIndex = _tableModel.getColumnNumber(columnName); - - TableColumn column = _table.getColumnModel().getColumn(columnIndex); - int prevWidth = column.getWidth(); - if(prevWidth != columnWidth) - { - column.setWidth(columnWidth); - } - } - } - } - - private void setWidth(String columnName, int columnWidth) - { - int columnIndex = _tableModel.getColumnNumber(columnName); - TableColumn column = _table.getColumnModel().getColumn(columnIndex); - _table.getColumnModel().getColumn(columnIndex).setHeaderRenderer(new JTableHeaderRenderer(_tableManager, _columnHeaderPreferredSize)); - column.setWidth(columnWidth); - column.setPreferredWidth(columnWidth); - } - - public void setColumnHeaderPreferredSize(Dimension columnHeaderPreferredSize) - { - _columnHeaderPreferredSize = columnHeaderPreferredSize; - } - - protected void addTableListeners(EventListener eventListener) - { - if(eventListener != null) - { - _listenerSet.add(eventListener); - Class[] classArray = eventListener.getClass().getInterfaces(); - - for(int i=0; i < classArray.length; i++) - { - String splitStr[] = classArray[i].toString().split(" "); - String className = splitStr[1]; - if(className.equals("javax.swing.event.ListSelectionListener")) - { - _table.getSelectionModel().addListSelectionListener((ListSelectionListener)eventListener); - } - else if(className.equals("java.awt.event.MouseListener")) - { - _table.addMouseListener((MouseListener)eventListener); - } - else if(className.equals("java.awt.event.MouseMotionListener")) - { - _table.addMouseMotionListener((MouseMotionListener)eventListener); - } - else if(className.equals("javax.swing.event.TableModelListener")) - { - _tableModel.addTableModelListener((TableModelListener)eventListener); - } - else - { - System.out.println ("I don't know what " + className + " is."); - } - } - } - } - - protected void removeTableListener(EventListener eventListener) - { - if(eventListener != null) - { - Class[] classArray = eventListener.getClass().getInterfaces(); - for(int i=0; i < classArray.length; i++) - { - String splitStr[] = classArray[i].toString().split(" "); - String className = splitStr[1]; - if(className.equals("javax.swing.event.ListSelectionListener")) - { - _table.getSelectionModel().removeListSelectionListener((ListSelectionListener)eventListener); - } - else if(className.equals("java.awt.event.MouseListener")) - { - _table.removeMouseListener((MouseListener)eventListener); - } - else if(className.equals("java.awt.event.MouseMotionListener")) - { - _table.removeMouseMotionListener((MouseMotionListener)eventListener); - } - } - } - } - - protected int[] getSelectedRowIndices() - { - java.util.List rowsSelectedList = new ArrayList(); - ListSelectionModel jtableListSelectionModel = _table.getSelectionModel(); - int firstIndex = jtableListSelectionModel.getMinSelectionIndex(); - int lastIndex = jtableListSelectionModel.getMaxSelectionIndex(); - for(int i=firstIndex ; i<=lastIndex ; i++) - { - if(jtableListSelectionModel.isSelectedIndex(i)) - { - rowsSelectedList.add(new Integer(i).toString()); - } - } - int rowsSelected[] = new int[rowsSelectedList.size()]; - for(int i=0; i columnClass, DefaultCellEditor defaultCellEditor) - { - _table.setDefaultEditor(columnClass, defaultCellEditor); - } - - class TableColumnHeaderMouseMotionListener extends MouseMotionAdapter - { - TableColumn _currentColumn; - public void mouseMoved(MouseEvent e) - { - int columnIndexPointedByMouse = _table.getColumnModel().getColumnIndexAtX(e.getX()); - if(columnIndexPointedByMouse != -1) - { - String columnNamePointedByMouse = _table.getColumnName(columnIndexPointedByMouse); - String headerToolTip = _tableManager.getColumnHeaderToolTipText(columnNamePointedByMouse); - TableColumn pointedColumn = _table.getColumnModel().getColumn(columnIndexPointedByMouse); - - if(_currentColumn != pointedColumn) - { - if(headerToolTip != null) - { - _table.getTableHeader().setToolTipText(headerToolTip); - } - _currentColumn = pointedColumn; - } - } - } - } - - class TableColumnHeaderMouseListener extends MouseAdapter - { - public void mouseClicked(MouseEvent e) - { - Point point = e.getPoint(); - - int column; - String columnNames[] = _tableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _tableModel.setChangedColumnNames(columnNames); - - int columnWidths[] = _tableManager.getWidthOfDisplayedColumns(); - _tableModel.setChangedColumnWidths(columnWidths); - - String columnAlignments[] = _tableManager.getAlignmentOfDisplayedColumns(); - _tableModel.setChangedColumnAlignments(columnAlignments); - - column = _table.getTableHeader().columnAtPoint( point ); - - if(column != -1) - { - String columnName = _tableModel.getColumnName(column); - - //System.out.println("Setting column for sorting:"+ columnName); - _tableManager.selectColumnForSorting(columnName); - sort(); - // OLD _tableManager.sort(_tableModel.getColumnName(column)); - - - int columnWidth = _tableModel.getColumnWidth(columnName); - setWidth(columnName, columnWidth); - - // _tableManager.setColumnSortInformation(columnName); OLD - - setColumnWidths(); - } - } - - public void mousePressed(MouseEvent e) - { - } - - public void mouseReleased(MouseEvent e) - { - if(_moveFlag) - { - Point point = e.getPoint(); - int column = _table.getTableHeader().columnAtPoint( point ); - - String rowData[][] = _tableManager.getDisplayRowDataArray(); - _sortFlag = true; - refresh(rowData); - if(column != -1) - { - - String columnName = _tableModel.getColumnName(column); - int columnWidth = _tableModel.getColumnWidth(columnName); - setWidth(columnName, columnWidth); - - //_tableManager.setColumnSortInformation(columnName); - } - setColumnWidths(); - - } - } - - } - - class TableColumnChangeListener implements TableColumnModelListener - { - String rowData[][]; - boolean marginChanged = false; - - public void columnMoved(TableColumnModelEvent e) - { - - if(e.getFromIndex() != e.getToIndex()) - { - String columnNames[] = _tableManager. - getColumnNamesThatAreCurrentlyDisplayed(); - - _tableModel.setChangedColumnNames(columnNames); - - String columnName1 = _tableModel.getColumnName(e.getFromIndex()); - String columnName2 = _tableModel.getColumnName(e.getToIndex()); - - _tableManager.swapColumns(columnName1, columnName2); - - columnNames = _tableManager. - getColumnNamesThatAreCurrentlyDisplayed(); - _tableModel.setChangedColumnNames(columnNames); - - int columnWidths[] = _tableManager.getWidthOfDisplayedColumns(); - _tableModel.setChangedColumnWidths(columnWidths); - - String columnAlignments[] = _tableManager.getAlignmentOfDisplayedColumns(); - _tableModel.setChangedColumnAlignments(columnAlignments); - - boolean isEditableArray[] = _tableManager.getIsEditableArray(); - _tableModel.setChangedIsEditableArray(isEditableArray); - - _moveFlag = true; - } - } - - public void columnMarginChanged(ChangeEvent e) - { - marginChanged = true; - int numOfCols = _tableModel.getColumnCount(); - int columnWidthsMatchingTheOrderOfColumnNames[] = new int[numOfCols]; - String columnAlignmentsMatchingTheOrderOfColumnNames[] = new String[numOfCols]; - - for(int i=0; i < numOfCols; i++) - { - String columnName; - columnName = _tableModel.getColumnName(i); - int columnWidth; - String columnAlignment; - if( _sortFlag || _moveFlag || _firstDraw) - { - columnWidth = _tableModel.getColumnWidth(columnName); - } - else - { - columnWidth = _table.getColumnModel().getColumn(i).getWidth(); - - } - columnAlignment = _tableManager.getAlignment(columnName); - columnWidthsMatchingTheOrderOfColumnNames[i] = columnWidth; - columnAlignmentsMatchingTheOrderOfColumnNames[i] = columnAlignment; - setWidth(columnName, columnWidth); - } - _sortFlag = false; - _moveFlag = false; - _firstDraw = false; - - _tableModel.setChangedColumnWidths( - columnWidthsMatchingTheOrderOfColumnNames); - _tableManager.setWidthOfDisplayedColumns( - columnWidthsMatchingTheOrderOfColumnNames); - - _tableModel.setChangedColumnAlignments(columnAlignmentsMatchingTheOrderOfColumnNames); - _tableManager.setAlignmentOfDisplayedColumns(columnAlignmentsMatchingTheOrderOfColumnNames); - } - - public void columnSelectionChanged(ListSelectionEvent e) - { - if(marginChanged == true) - { - String columnNames[] = _tableManager. - getColumnNamesThatAreCurrentlyDisplayed(); - - _tableModel.setChangedColumnNames(columnNames); - - rowData = _tableManager.getDisplayRowDataArray(); - refresh(rowData); - marginChanged = false; - } - } - - public void columnAdded(TableColumnModelEvent e) - { - } - - public void columnRemoved(TableColumnModelEvent e) - { - } - - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/TableCellInterface.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/TableCellInterface.java deleted file mode 100644 index b5fa8877c8..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/TableCellInterface.java +++ /dev/null @@ -1,24 +0,0 @@ -package ohd.hseb.util.gui.jtable; - -import java.awt.Color; - -public interface TableCellInterface -{ - - Object getValue(); - String getDisplayString(); - - - String getColumnName(); - - int compare(TableCellInterface cell); - - Color getCellBackgroundColor(); - void setCellBackgroundColor(Color color); - - - Color getCellForegroundColor(); - void setCellForegroundColor(Color color); - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/ExampleData.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/ExampleData.java deleted file mode 100644 index 0f23ddf876..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/ExampleData.java +++ /dev/null @@ -1,126 +0,0 @@ -package ohd.hseb.util.gui.jtable.example; - -/** - * Creates example data for use in the jtable example application - * - * @author rajaramv - * - */ -public class ExampleData -{ - private int _numOfRows = 10; - private static int _count = 0; - - protected int[] getExampleIdValues() - { - - int[] result = new int[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - result [i] = i + _count ++; - } - - return result; - } - - protected short[] getExampleAgeValues() - { - - short[] result = new short[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - result [i] =(short) i; - } - - return result; - } - - protected long[] getExampleDateOfBirthValues() - { - - long[] result = new long[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - result [i] = (long) i*10000; - } - - return result; - } - - protected long[] getExampleSalaryValues() - { - - long[] result = new long[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - result [i] = (long) i*10000; - } - - return result; - } - - protected float[] getExampleHeightValues() - { - - float[] result = new float[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - result [i] = (float) i; - } - - return result; - } - - - protected double[] getExampleWeightValues() - { - - double[] result = new double[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - result [i] = (double) i; - } - - return result; - } - - - protected boolean[] getExampleMaritalStatusValues() - { - - boolean[] result = new boolean[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - if((i / 2) == 0) - result [i] = true; - else - result [i] = false; - } - - return result; - } - - protected String[] getExampleNameValues() - { - - String[] result = new String[_numOfRows]; - - for(int i=0; i < _numOfRows; i++) - { - if((i / 2) == 0) - result [i] = "Hello" + i; - else - result [i] = "Hello" + 1 + (i +1); - } - - return result; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/ExampleJTableRowData.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/ExampleJTableRowData.java deleted file mode 100644 index a2d13942b3..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/ExampleJTableRowData.java +++ /dev/null @@ -1,110 +0,0 @@ -package ohd.hseb.util.gui.jtable.example; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -/** - * This class is mandate for any application trying to use JTable Framework. - * It should extend AbstractJTableRowData class from common project's jtable pacakge. - * It contains the getters and setters for each column in the table. - * It specifies the cell level details for each column in the table. - * It should have a method similar to the addAllCellsToMap() shown here, which will create the - * cells and map the details to the cells like its value, data type etc. - * - * @author rajaramv - * - */ -public class ExampleJTableRowData extends AbstractJTableRowData -{ - String _missingRepresentation = " "; - private int _id; - private short _age; - private long _dateOfBirth; - private long _salary; - private float _height; - private double _weight; - private String _name; - private boolean _maritalStatus; - - public void setMaritalStatus(boolean value) - { - _maritalStatus = value; - } - public boolean getMaritalStatus() - { - return _maritalStatus; - } - public double getWeight() - { - return _weight; - } - public void setWeight(double value) - { - _weight = value; - } - public float getHeight() - { - return _height; - } - public void setHeight(float value) - { - _height = value; - } - public int getId() - { - return _id; - } - public void setId(int value) - { - _id = value; - } - public long getBirthDate() - { - return _dateOfBirth; - } - public void setBirthDate(long value) - { - _dateOfBirth = value; - } - public short getAge() - { - return _age; - } - public void setAge(short value) - { - _age = value; - } - public long getSalary() - { - return _salary; - } - public void setSalary(long value) - { - _salary = value; - } - public String getName() - { - return _name; - } - public void setName(String value) - { - _name = value; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Id", CellType.INTEGER, getId(), _missingRepresentation)); - addCell(new BaseTableCell("Age", CellType.SHORT, getAge(), _missingRepresentation)); - addCell(new BaseTableCell("BirthDate", CellType.DATE, getBirthDate(), _missingRepresentation)); - addCell(new BaseTableCell("Height", CellType.FLOAT, getHeight(), _missingRepresentation)); - addCell(new BaseTableCell("Weight", CellType.DOUBLE, getWeight(), _missingRepresentation)); - addCell(new BaseTableCell("Name", CellType.STRING, getName(), _missingRepresentation)); - addCell(new BaseTableCell("Married", CellType.BOOLEAN, getMaritalStatus(), _missingRepresentation)); - addCell(new BaseTableCell("Salary", CellType.LONG, getSalary(), _missingRepresentation)); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/JTableExampleApp.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/JTableExampleApp.java deleted file mode 100644 index 223c2af456..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/JTableExampleApp.java +++ /dev/null @@ -1,146 +0,0 @@ -package ohd.hseb.util.gui.jtable.example; - -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JScrollPane; - -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -/** - *

- * JTableExampApp - Class containing the main method for JTable Example. - * This class shows the basic methods to be called in JTable Framework to perform the following: - *

- *

  • Display a JTable, - *
  • Refresh a JTable, - *
  • Column Selection Feature - * - * @author rajaramv - * - * - */ - -public class JTableExampleApp extends JFrame -{ - JFrame _frame ; - JTableManager _tableManager; - - public void showApp() - { - _frame = new JFrame("JTable Framework Example"); - _frame.setLayout(new GridBagLayout()); - - JTableExampleDataManager dataManager = new JTableExampleDataManager(); - - List rowDataList = dataManager.readData(); - List columnDescriptorList = createColumnDescriptorList(); - - JScrollPane tableScrollPane = createJTable(columnDescriptorList, rowDataList); - createMenus(); - - _frame.getContentPane().add(tableScrollPane); - _frame.pack(); - _frame.setVisible(true); - } - - /** - * Creates a JTable using the columnDescriptorList and rowDataList - * @param columnDescriptorList - column descriptor list containing JTableColumnDescriptor for each column in the table - * @param rowDataList - list of JTableRowData each representing a row - * @return JScrollPane - JScrollPane containing the JTable - */ - public JScrollPane createJTable(List columnDescriptorList, List rowDataList) - { - _tableManager = new ComplexJTableManager(columnDescriptorList, rowDataList); - _tableManager.setPreferredSizeForJScrollPane(new Dimension(680, 320)); - JScrollPane tableScrollPane = _tableManager.getJScrollPane(); - return tableScrollPane; - } - - /** - * Creates the JTableColumnDescriptor for each column in the table and returns it. - * @return List - columnDescriptorList - */ - public List createColumnDescriptorList() - { - List columnDescriptorList = new ArrayList(); - - columnDescriptorList.add( new JTableColumnDescriptor("Id")); - columnDescriptorList.add( new JTableColumnDescriptor("Age")); - columnDescriptorList.add( new JTableColumnDescriptor("BirthDate", 60, "center", "Date Of Birth")); - columnDescriptorList.add( new JTableColumnDescriptor("Height")); - columnDescriptorList.add( new JTableColumnDescriptor("Weight")); - columnDescriptorList.add( new JTableColumnDescriptor("Name")); - columnDescriptorList.add( new JTableColumnDescriptor("Married")); - columnDescriptorList.add( new JTableColumnDescriptor("Salary", 75, "right", "Annual Salary")); - - return columnDescriptorList; - } - - /** - * Create the menus for column selection and refresh. - * This is to demonstrate the column selection and refresh ability of the jtable framework. - * - */ - public void createMenus() - { - JMenuBar menuBar = new JMenuBar(); - _frame.setJMenuBar(menuBar); - - JMenu fileMenu = new JMenu("File"); - fileMenu.setMnemonic('F'); - JMenuItem columnSelectionMenuItem = new JMenuItem("Column Selection"); - columnSelectionMenuItem.setMnemonic('C'); - fileMenu.add(columnSelectionMenuItem); - - JMenuItem refreshMenuItem = new JMenuItem("Refresh"); - refreshMenuItem.setMnemonic('R'); - fileMenu.add(refreshMenuItem); - - ChangeColumnsDisplayedMenuListener changeMenuListener = new - ChangeColumnsDisplayedMenuListener(); - columnSelectionMenuItem.addActionListener(changeMenuListener); - - RefreshMenuListener RefreshMenuListener = new - RefreshMenuListener(); - refreshMenuItem.addActionListener(RefreshMenuListener); - - menuBar.add(fileMenu); - - } - - private class ChangeColumnsDisplayedMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _tableManager.invokeColumnSelector(_frame); - } - } - - private class RefreshMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - List rowDataList = new JTableExampleDataManager().readData(); - _tableManager.setChangedAllRowDataList(rowDataList); - - _tableManager.refreshDisplay(); - } - } - - public static void main(String args[]) - { - new JTableExampleApp().showApp(); - } -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/JTableExampleDataManager.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/JTableExampleDataManager.java deleted file mode 100644 index de1fe1b76d..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/gui/jtable/example/JTableExampleDataManager.java +++ /dev/null @@ -1,50 +0,0 @@ -package ohd.hseb.util.gui.jtable.example; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class's primary repsonsibility is the create the list of rowdata objects, - * and call addAllCellsToMap() method (Declared in ExampleJTableRowData.java) - * for each row data object. - * - * @author rajaramv - * - */ -public class JTableExampleDataManager -{ - - private int _numOfRows = 10; - private ExampleData _exampleData = new ExampleData(); - - public List readData() - { - List rowDataList = new ArrayList(); - - int ids[] = _exampleData.getExampleIdValues(); - short ages[] = _exampleData.getExampleAgeValues(); - long dateOfBirths[] = _exampleData.getExampleDateOfBirthValues(); - long salaries[] = _exampleData.getExampleSalaryValues(); - float heights[] = _exampleData.getExampleHeightValues(); - double weights[] = _exampleData.getExampleWeightValues(); - boolean maritalStatus[] = _exampleData.getExampleMaritalStatusValues(); - String names[] = _exampleData.getExampleNameValues(); - - for(int i=0; i < _numOfRows ; i++) - { - ExampleJTableRowData rowData = new ExampleJTableRowData(); - rowData.setId(ids[i]); - rowData.setAge(ages[i]); - rowData.setHeight(heights[i]); - rowData.setWeight(weights[i]); - rowData.setBirthDate(dateOfBirths[i]); - rowData.setMaritalStatus(maritalStatus[i]); - rowData.setName(names[i]); - rowData.setSalary(salaries[i]); - rowData.addAllCellsToMap(); - rowDataList.add(rowData); - } - return rowDataList; - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/io/RGBTextFileReader.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/io/RGBTextFileReader.java deleted file mode 100644 index 1c4b93d67e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/io/RGBTextFileReader.java +++ /dev/null @@ -1,88 +0,0 @@ -package ohd.hseb.util.io; - -import java.awt.Color; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.util.StringParser; - -public class RGBTextFileReader -{ - - - - public RGBTextFileReader() - { - - } - -// --------------------------------------------------------------------------------------------------- - - public Map read(String rgbColorFilePath ) - { - String header = "RGBTextFileReader(). read() "; - - File rgbColorFile = null; - BufferedReader reader = null; - String line = null; - String[] tokenizedString = null; - String colorName = null; - rgbColorFile = new File( rgbColorFilePath ); - Map colorMap = new HashMap(); - - try - { - reader = new BufferedReader( new FileReader( rgbColorFile ) ); - line = reader.readLine(); //discard the first line - line = reader.readLine(); - while ( line != null ) - { - tokenizedString = StringParser.tokenize( line ); - colorName = getRGBColorName( tokenizedString ); - -// if the read in RGB color name exists in the ColorName table, then add to the _rgbColorMap - - Color color = new Color(Integer.parseInt( tokenizedString[ 0 ] ), - Integer.parseInt( tokenizedString[ 1 ] ), - Integer.parseInt( tokenizedString[ 2 ] ) ); - - - - colorMap.put( colorName.toUpperCase(), color ); - - // System.out.println(header + "colorName = " + colorName + " color = " + color); - - line = reader.readLine(); - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - - return colorMap; - } - // --------------------------------------------------------------------------------------------------- - - private String getRGBColorName( String[] tokenizedName ) - { - StringBuffer rgbColorName = new StringBuffer(); - - for ( int i = 3; i < tokenizedName.length;i++ ) - { - rgbColorName.append( tokenizedName[ i ] ); - - if ( i != ( tokenizedName.length - 1 ) ) - { - rgbColorName.append( " " ); - } - } - - return rgbColorName.toString(); - } - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/EnvTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/EnvTest.java deleted file mode 100644 index a1acb3bb6a..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/EnvTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package ohd.hseb.util.test; - -import java.util.*; -import ohd.hseb.util.*; - - -public class EnvTest -{ - - private long _envTotal = 0; - - - public static void main(String[] args) - { - EnvTest test = new EnvTest(); - CodeTimer timer = new CodeTimer(); - - - int iterationCount = 10; - long pureJavaTotalTime = 0; - - - timer.start(); - test.envTest(iterationCount); - timer.stop("intTest time for " + iterationCount + " iterations "); - - return; - - } - - - public void envTest(int iterationCount) - { - - Properties props = System.getProperties(); - - props.list(System.out); - } - - - - -} //end class EnvTest diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/JniTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/JniTest.java deleted file mode 100644 index 5025910f93..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/JniTest.java +++ /dev/null @@ -1,97 +0,0 @@ - -package ohd.hseb.util.test; - - -public class JniTest -{ - - static - { - try - { - System.loadLibrary("JniTest"); - } - catch(Throwable t) - { - System.out.println("Unable to loadLibrary."); - } - } - - public static void main(String[] args) - { - JniTest test = new JniTest(); - System.out.println("I am calling jniMethod from java"); - test.jniMethod("Chip", 10); - - int iterationCount = 10000; - long nativeTotalTime = 0; - long pureJavaTotalTime = 0; - - pureJavaTotalTime = test.jTest("Chip", 10, iterationCount); - - nativeTotalTime = test.nativeTest("Chip", 10, iterationCount); - - System.out.println("Java calling C native time = " + nativeTotalTime + " millis. for " + iterationCount + " iterations"); - System.out.println("Pure Java time = " + pureJavaTotalTime + " millis. for " + iterationCount + " iterations"); - - return; - - - } - - public long jTest(String name, int age, int iterationCount) - { - - - long totalTime = 0; - long time1 = 0; - long time2 = 0; - - time1 = System.currentTimeMillis(); - for (int i = 0; i < iterationCount; i++) - { - - jMethod(name, age); - - - } - time2 = System.currentTimeMillis(); - totalTime = (time2 - time1); - - return totalTime; - - } - - public long nativeTest(String name, int age, int iterationCount) - { - - - long totalTime = 0; - long time1 = 0; - long time2 = 0; - - time1 = System.currentTimeMillis(); - for (int i = 0; i < iterationCount; i++) - { - - jniMethod(name, age); - - - } - time2 = System.currentTimeMillis(); - totalTime = (time2 - time1); - - return totalTime; - - } - - public void jMethod(String name, int age) - { - System.out.println("My name = " + name + " and my age = " + age + "."); - } - - - public native void jniMethod(String name, int age); - - -} //end class Test diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/TimeTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/TimeTest.java deleted file mode 100644 index 8694274ad7..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/TimeTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.util.test; - -import ohd.hseb.db.DbTimeHelper; -import junit.framework.TestCase; - -public class TimeTest extends TestCase -{ - - - public void testTime() - { - long timeLong = 0; - String resultDateTimeString = null; - - String epochDateTimeString = "1970-01-01 00:00:00"; - String epochDateTimeToMinutesString = "1970-01-01 00:00"; - - String epochDateTimePlusOneMinuteString = "1970-01-01 00:01:00"; - - String epochDateTimeToMinutesPlusOneMinuteString = "1970-01-01 00:01"; - - - //first moment in epoch to seconds - timeLong = DbTimeHelper.getLongTimeFromDateTimeString(epochDateTimeString); - assertEquals(0, timeLong); - - resultDateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(0); - assertEquals(epochDateTimeString, resultDateTimeString); - - - //first moment in epoch to minutes - timeLong = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(epochDateTimeToMinutesString); - assertEquals(0, timeLong); - - - resultDateTimeString = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(timeLong); - assertEquals(epochDateTimeToMinutesString, resultDateTimeString); - - //one minute after the epoch, to seconds - timeLong = DbTimeHelper.getLongTimeFromDateTimeString(epochDateTimePlusOneMinuteString); - assertEquals(60000, timeLong); - - - //one minute after the epoch, in minutes - timeLong = DbTimeHelper.getLongTimeFromDateTimeToMinutesString(epochDateTimeToMinutesPlusOneMinuteString); - assertEquals(60000, timeLong); - - - - return; - - - } - - - -} diff --git a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/TimingTest.java b/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/TimingTest.java deleted file mode 100644 index 886e7ff45e..0000000000 --- a/javaUtilities/hydro/ohd.common/src/ohd/hseb/util/test/TimingTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package ohd.hseb.util.test; - -import ohd.hseb.util.*; - -public class TimingTest -{ - - private long _longTotal = 0; - private double _doubleTotal = 0.0; - - - public static void main(String[] args) - { - TimingTest test = new TimingTest(); - CodeTimer timer = new CodeTimer(); - - int iterationCount = 1000000; - long pureJavaTotalTime = 0; - - //timer.start(); - //test.outputTest("Chip", 10, iterationCount); - // timer.stop("Pure Java output time for " + iterationCount + " iterations "); - - timer.start(); - test.intTest(iterationCount); - timer.stop("intTest time for " + iterationCount + " iterations "); - - - timer.start(); - test.floatTest(iterationCount); - timer.stop("floatTest time for " + iterationCount + " iterations "); - - - test.showResults(); - - return; - - - } - - public void showResults() - { - System.out.println("longTotal = " + _longTotal); - System.out.println("doubleTotal = " + _doubleTotal); - } - - - //--------test loop methods --------------------------------------------------------- - - //------------------------------------------------------------------- - - public void outputTest(String name, int age, int iterationCount) - { - - for (int i = 0; i < iterationCount; i++) - { - - outputMethod(name, age); - - } - - return; - - } - - //------------------------------------------------------------------- - - public void intTest(int iterationCount) - { - - int j = 0; - int k = 0; - - - for (int i = 0; i < iterationCount; i++) - { - j = i + 2; - - k = intComputeMethod(i, j); - _longTotal += k; - - } - - - - - return; - - } - - //------------------------------------------------------------------- - - public void floatTest(int iterationCount) - { - - - long totalTime = 0; - int j; - float k = 0f; - - - for (int i = 0; i < iterationCount; i++) - { - j = i + 2; - - k = floatComputeMethod( (float)i, (float)j ); - - _doubleTotal += k; - } - - - return; - - } - - - //------work methods -------------------------------------------- - - public void outputMethod(String name, int age) - { - System.out.println("My name = " + name + " and my age = " + age + "."); - } - - - public int intComputeMethod(int i, int j) - { - return i + j; - } - - - public float floatComputeMethod(float i, float j) - { - return i + j; - } - - -} //end class TimingTest diff --git a/javaUtilities/hydro/ohd.damcrest/.classpath b/javaUtilities/hydro/ohd.damcrest/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.damcrest/.project b/javaUtilities/hydro/ohd.damcrest/.project deleted file mode 100644 index b8ce03ad51..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.damcrest - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.damcrest/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.damcrest/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index c4f432ead6..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:15:07 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.damcrest/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.damcrest/META-INF/MANIFEST.MF deleted file mode 100644 index cb46ab68b6..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/META-INF/MANIFEST.MF +++ /dev/null @@ -1,13 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Damcrest -Bundle-SymbolicName: ohd.damcrest -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.db;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" -Export-Package: gov.dambreak.menu, - gov.dambreak.smpdbk, - gov.dambreak.util, - gov.damcat.data, - ohd.hseb.util diff --git a/javaUtilities/hydro/ohd.damcrest/build.properties b/javaUtilities/hydro/ohd.damcrest/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.damcrest/build.xml b/javaUtilities/hydro/ohd.damcrest/build.xml deleted file mode 100644 index 1e798d1408..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/build.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.damcrest/ohd.damcrest.ecl b/javaUtilities/hydro/ohd.damcrest/ohd.damcrest.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.damcrest/scripts/run_damcrest b/javaUtilities/hydro/ohd.damcrest/scripts/run_damcrest deleted file mode 100644 index f6cc1d55dc..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/scripts/run_damcrest +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/ksh - -# File name: run_damcrest -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - - -export CONNECTION_STRING=$DAMCREST_JDBCURL - -#get java dir -export SYS_JAVA_DIR=$($GAD_DIR/get_apps_defaults$OS_SUFFIX sys_java_dir) -export SYS_JAVA_BIN_DIR=$SYS_JAVA_DIR/bin - -# set java classpath - -export CLASSPATH=.:$SYS_JAVA_DIR\ -:$SYS_JAVA_BIN_DIR\ -:$SYS_JAVA_DIR/JClassDesktopViews/lib/jcchart.jar\ -:$DB_DRIVER_PATH\ -:$WHFS_BIN_DIR/damcrest.jar\ -:$WHFS_BIN_DIR/fldat.jar - -export DBDRIVER=org.postgresql.Driver -export DAMCREST_HOME=$WHFS_BIN_DIR - -# set up an X Terminal window to write stdout and run the DamCrest -# application using java -xterm -T "DamCrest standard output window" -iconic \ --e "$SYS_JAVA_BIN_DIR/java -Ddamcrest.home=$DAMCREST_HOME gov.dambreak.menu.Launcher $1" diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/menu/Launcher.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/menu/Launcher.java deleted file mode 100644 index eb1b67b5ca..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/menu/Launcher.java +++ /dev/null @@ -1,267 +0,0 @@ -package gov.dambreak.menu; - -import java.io.File; -import javax.swing.*; - -import gov.damcat.data.DBAccess; -import gov.damcat.data.DamInfo; -import gov.dambreak.util.AnalysisData; -import gov.dambreak.smpdbk.ModelGUI; -import gov.dambreak.smpdbk.OutputManager; -import gov.damcat.data.Search; - -/** - * This class represents the starting point for the Dambreak - * Analysis application. - * Creation date: (7/30/2003 2:22:34 PM) - * @author: - */ -public class Launcher -{ - private boolean bDBMSActive; - public static boolean closeFlag = false; - - /** - * Make calls to read database, and process dam with nidid passed in via command line - * Creation date: (4/1/2004 10:43:09 AM) - */ - private void connOutMan(String nidid) - { - boolean hasDatabase; - closeFlag = true; - - DBAccess dbAccess = new gov.damcat.data.DBAccess(); - - DamInfo damInfo = dbAccess.fillCompletely(nidid); - - AnalysisData currentData = damInfo.getAnalysisData(); - - String oError = currentData.verifyOutput(); - - if( !oError.equalsIgnoreCase( "" ) ) - { - hasDatabase = true; - - JOptionPane.showMessageDialog(null,oError,"Could Not Display Stored Forecast",JOptionPane.ERROR_MESSAGE); - ModelGUI smpdbkInputEditor = new ModelGUI( hasDatabase, damInfo.nidid,damInfo.getAnalysisData(),dbAccess); - smpdbkInputEditor.handleMenuRun_SMPDBK(); - - //hasSpawned = true; //??? - - return; - } - - OutputManager outMan = new OutputManager(currentData); - //closeFlag = false; //??? - } - /** - * Insert the method's description here. - * Creation date: (10/3/2003 5:20:08 PM) - * @return boolean - */ - public boolean isDBMSActive() - { - return bDBMSActive; - } - /** - * This is the starting point of the Dambreak Analysis application. - * Creation date: (7/30/2003 2:22:39 PM) - * @param args java.lang.String[] - */ - public static void main(String[] args) - { - ////////////////////////////////////////////////////////////////////////////////// - // Dambreak Analysis v1.0 - Craig Austin - // v2.0 - Gang Of Five : Campbell, Hsu, Momo, Shebsovich, Urban - // v3.0 - Dan Urban & Moria Shebsovich - ///////////////////////////////////////////////////////////////////////////////// - - Launcher launcher = new Launcher(); - - System.out.println( "Initializing Dambreak Analysis..." ); - - boolean bHasModel = false; - - String filePath = ""; - String modelFileName = ""; - - String osName = System.getProperty( "os.name" ); - String osNameLowerCase = osName.toLowerCase(); - - // *** First, find damcrest.home to determine where the resources.txt and sdbj.exe files are located - - if ( ( filePath = System.getProperty( "damcrest.home" ) ) == null ) - { - JOptionPane.showMessageDialog(null,"Error -- damcrest.home property missing\n", "Error", JOptionPane.ERROR_MESSAGE); - return; - } - if ( !filePath.endsWith( System.getProperty("file.separator" ) ) ) - { - filePath = filePath.concat( System.getProperty("file.separator" ) ); - } - - String resourcesFileName = filePath.concat( "resources.txt" ); - File fileresources = new File( resourcesFileName ); - System.out.println( "osNameLowerCase = " + osNameLowerCase ); - if( osNameLowerCase.indexOf( "linux" ) > -1 ) - { - if ( !fileresources.exists() ) - { - System.out.println ("OS Linux, all settings are taken from tokens or environmental variables\n"); - } - else - { - System.out.println ("OS Linux, resourses.txt esists\n"); - } - } - else - { - if ( !fileresources.exists() ) - { - JOptionPane.showMessageDialog(null,"Error -- no/bad resources.txt file found in\n" + filePath, "Error", JOptionPane.ERROR_MESSAGE); - return; - } - } - if ( osNameLowerCase.indexOf( "windows" ) > -1 ) - { - modelFileName = filePath.concat("sdbj.exe"); // *** is this the same in Linux ??? - } - else if (osNameLowerCase.indexOf("linux") > -1) - { - modelFileName = filePath.concat("sdbj.LX"); - } - - File fileModel = new File(modelFileName); - if ( fileModel.exists() ) - { - bHasModel = true; - } - - // *** Next, make sure that we have access to the .jar file with the JClass libraries - - boolean bHasJClasses = false; - try - { - Class.forName("com.klg.jclass.chart.data.JCEditableDataSource"); - Class.forName("com.klg.jclass.chart.JCChart"); - bHasJClasses = true; - } - catch (ClassNotFoundException ex) - { - bHasJClasses = false; - } - - // *** And, the .jar file with necessary FLDAT components - - boolean bHasFLDAT = false; - try - { - Class.forName("gov.noaa.FloodWav.Component.ElevationStationManager"); - bHasFLDAT = true; - } - catch (ClassNotFoundException ex) - { - bHasFLDAT = false; - } - - // *** Now, find out if the user has a database. - boolean bHasDatabase = DBAccess.isDBEnabled(); - // set private static variable so everyone can find the value - launcher.setDBMSActive( bHasDatabase ); - - // *** If the variable "damcat.hasListAllDams is set in resource.txt file, - // the list of all dams in the databse will be displayed - // when the Search tool is opened initially - boolean bHasListAllDams = DBAccess.hasListAllDams(); - - // We have all the data we need, decide where to start the user and alert them of - // any missing components. - - if ( bHasDatabase ) - { - System.out.println( "User has DAMCAT." ); - } - else - { - System.out.println("User does not have DAMCAT."); - } - - if ( osNameLowerCase.indexOf( "windows" ) > -1) - { - if (bHasModel) - { - System.out.println( "Found sdbj.exe." ); - } - else - { - System.out.println("!!! Could not find sdbj.exe !!!"); - } - } - - if (osNameLowerCase.indexOf("linux") > -1) - { - if (bHasModel) - { - System.out.println("Found sdbj.LX."); - } - else - { - System.out.println("!!! Could not find sdbj.LX !!!"); - } - } - if ( bHasJClasses ) - { - System.out.println("Found JClass components."); - } - else - { - System.out.println("!!! Could not find JClass components !!!"); - } - - if ( bHasFLDAT ) - { - System.out.println("Found FLDAT components."); - } - else - { - System.out.println("!!! Could not find FLDAT components !!!"); - } - - // If the user has a database, display the DAMCAT search tool - if ( ( bHasDatabase ) && ( args.length == 0 ) ) - { - Search searchTool = new Search(bHasModel); - // If the option to display all dams is set - if ( bHasListAllDams ) - { - searchTool.handleListAllDams(); - } - } - // If the user has a database, and NIDID is passed from the command line - else if ( ( bHasDatabase ) && ( args.length != 0 ) ) - { - String nidid = args[0]; - launcher.connOutMan(nidid); - } - // If the user does not have a database, display the SMPDBK model input editor - else - { - boolean hasDatabase = false; - String strWorkingDamNIDID = null; - AnalysisData currentData = null; - DBAccess dbAccess = null; - - ModelGUI modelInputEditor = new ModelGUI( hasDatabase, strWorkingDamNIDID, currentData, dbAccess ); - } - - } - /** - * Set value of private method from within Launcher. - * Creation date: (10/3/2003 5:20:08 PM) - * @param newBDBMSActive boolean - */ - private void setDBMSActive( boolean newBDBMSActive ) - { - bDBMSActive = newBDBMSActive; - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/DisplayGraphicsPanel.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/DisplayGraphicsPanel.java deleted file mode 100644 index 2ffcc46964..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/DisplayGraphicsPanel.java +++ /dev/null @@ -1,552 +0,0 @@ -package gov.dambreak.smpdbk; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import gov.dambreak.util.*; - -/** - * This class represents a panel which contains a visualization of - * SMPDBK output data. - */ -public class DisplayGraphicsPanel extends javax.swing.JPanel implements ActionListener, MouseListener -{ - - private ModelOutput outputFile; - private JLabel longitudinalTitle; - private JComboBox xsChooser; - private int selectedXS; - private Rectangle[] sectionBoxes; - - public DisplayGraphicsPanel(ModelOutput _outputFile) { - - super(); - initialize(); - outputFile = _outputFile; - longitudinalTitle = new JLabel(""); - longitudinalTitle.setHorizontalAlignment(JLabel.CENTER); - longitudinalTitle.setVerticalAlignment(JLabel.TOP); - longitudinalTitle.setFont(new Font("SansSerif", Font.BOLD, 16)); - longitudinalTitle.setBounds(0,0,800,25); - add(longitudinalTitle); - - // create drop-down box - - String[] items = new String[outputFile.inputDownstream.size()]; - - // System.out.println("DisplayGraphicsPanel- size = " + outputFile.inputDownstream.size()); - - for (int i=0; i= 0; i--) - { - soilPolyX[count] = (int)(Xx1+((Xwidth/2) - (((bs[selectedXS][i] - minBS) / widthBS) * Xwidth) / 2)); - soilPolyY[count++] = (int)(Xy1+Xheight-(((hs[selectedXS][i] - minHS) / widthHS) * Xheight)); - } - soilPolyX[count] = Xx1 + (Xwidth/2); - soilPolyY[count++] = Xy1+Xheight; - for (int i = 0; i < nElevations; i++) - { - soilPolyX[count] = (int)(Xx1+((Xwidth/2) + (((bs[selectedXS][i] - minBS) / widthBS) * Xwidth) / 2)); - soilPolyY[count++] = (int)(Xy1+Xheight-(((hs[selectedXS][i] - minHS) / widthHS) * Xheight)); - } - g.setColor(new Color(150,83,82)); - g.fillPolygon(soilPolyX,soilPolyY,2*nElevations+5); - - // draw max elevation text - g.setColor(Color.black); - Font f4 = new Font("Serif",Font.PLAIN, 13); - g.setFont(f4); - FontMetrics fm = g.getFontMetrics(); - int junk1y = Xy1+(Xheight-yMaxFloodPos); - String strMaxFloodElev = "Max Flood Elevation: " + df.format(outputFile.maxElevation[selectedXS]) + " ft"; - g.drawString(strMaxFloodElev, Xx1+(Xwidth/2)-(fm.stringWidth(strMaxFloodElev)/2), (Xy1-2)+(Xheight-yMaxFloodPos)-2); - - // draw max depth - g.drawString("Max Flood Depth:", Xx1+Xwidth+21, Xy1+(Xheight-(yMaxFloodPos/2))); - g.drawString(df.format(outputFile.maxDepth[selectedXS]) + " ft", Xx1+Xwidth+21, Xy1+(Xheight-(yMaxFloodPos/2))+13); - g.drawLine(Xx1+Xwidth+5,Xy1+(Xheight-yMaxFloodPos),Xx1+Xwidth+21,Xy1+(Xheight-yMaxFloodPos)); - g.drawLine(Xx1+Xwidth,Xy1+Xheight,Xx1+Xwidth+21,Xy1+Xheight); - g.drawLine(Xx1+Xwidth+19,Xy1+Xheight,Xx1+Xwidth+19,Xy1+(Xheight-yMaxFloodPos)); - g.drawLine(Xx1+Xwidth+21,Xy1+Xheight+2,Xx1+Xwidth+17,Xy1+Xheight-2); // bottom corner cross - g.drawLine(Xx1+Xwidth+21,Xy1+(Xheight-yMaxFloodPos)+2,Xx1+Xwidth+17,Xy1+(Xheight-yMaxFloodPos)-2); // top corner cross - - // draw flood depth elevation - double floodElevation = outputFile.maxElevation[selectedXS]+((DownstreamPoint)outputFile.inputDownstream.get(selectedXS)).floodDepth-outputFile.maxDepth[selectedXS]; - String strFloodDepthElevation = df.format(floodElevation) + " ft"; - if (Math.abs((Xy1+(Xheight-yMaxFloodPos)-2) - (Xy1+yFloodDepthPos-2)) >= fm.getAscent()) - g.drawString(strFloodDepthElevation, Xx1+(Xwidth/2)-(fm.stringWidth(strFloodDepthElevation)/2), Xy1+yFloodDepthPos-2); - g.setColor(new Color(150,83,82)); - g.drawLine(Xx1,Xy1+yFloodDepthPos,Xx1+Xwidth,Xy1+yFloodDepthPos); - g.setColor(Color.black); - - // draw flood depth - /* - System.out.println("Xx1- " + Xx1); - System.out.println("Xy1- " + Xy1); - System.out.println("yFloodDepthPos- " + yFloodDepthPos); - System.out.println("Xheight- " + Xheight); - */ - - g.drawString("Flood Stage:",Xx1-90,Xy1+yFloodDepthPos+(Xheight-yFloodDepthPos)/2); - g.drawString(df.format(((DownstreamPoint)outputFile.inputDownstream.get(selectedXS)).floodDepth) + " ft", Xx1-90, Xy1+yFloodDepthPos+(Xheight-yFloodDepthPos)/2+13); - g.drawLine(Xx1-18,Xy1+Xheight,Xx1,Xy1+Xheight); - g.drawLine(Xx1-18,Xy1+Xheight+2,Xx1-14,Xy1+Xheight-2); // bottom corner cross - g.drawLine(Xx1-18,Xy1+yFloodDepthPos,Xx1,Xy1+yFloodDepthPos); - g.drawLine(Xx1-17,Xy1+Xheight,Xx1-17,Xy1+yFloodDepthPos); - g.drawLine(Xx1-19,Xy1+yFloodDepthPos+2,Xx1-15,Xy1+yFloodDepthPos-2); // top corner cross - } catch (Throwable e) { - System.out.println ("Exception indrawCrossSection()"); - e.printStackTrace(); - } - } - private void drawRiverView(Graphics g, int x1, int y1, int x2, int y2) { - - // System.out.println("draw RiverView"); - try { - double minHS = Integer.MAX_VALUE; - double maxHS = Integer.MIN_VALUE; - double minRM = Integer.MAX_VALUE; - double maxRM = Integer.MIN_VALUE; - int Xwidth = (int)((x2-x1)*0.9); // cross section dimensions - int Xheight = y2-y1-60; - int Xx1 = x1+((x2-x1-Xwidth)/2); // cross section starting coordinates - int Xy1 = y1+20; - int nSections = outputFile.inputDownstream.size(), nElevations = AnalysisData.getNumPairs(outputFile.inputDownstream); - int selectedXS = xsChooser.getSelectedIndex(); - - // find maximum and minimum river mile and land elevation - for (int j=0; j=0; i--) { - waterPolyX[count] = (int)(((((DownstreamPoint)outputFile.inputDownstream.get(i)).distanceToSection-minRM)/widthRM)*(Xwidth-(Xwidth/5))+Xx1+(Xwidth/5)); - double height = outputFile.maxElevation[i];//-outputFile.maxDepth[i]; - waterPolyY[count++] = (int)(Xy1+Xheight-((height-minWHS)/widthWHS)*(Xheight*0.7));//(Xheight*0.4)); - } - g.setColor(new Color(190,255,255)); - g.fillPolygon(waterPolyX,waterPolyY,nSections+3); - - //////////////////////////////////// - // create soil polygon - //////////////////////////////////// - int[] soilPolyX = new int[nSections+2], - soilPolyY = new int[nSections+2]; - count=0; - - double damLandHeight = outputFile.maxElevation[0]-outputFile.maxDepth[0]; - soilPolyX[count] = Xx1+(Xwidth/5); - soilPolyY[count++] = (int)(Xy1+Xheight-((damLandHeight-minWHS)/widthWHS)*((Xheight*0.7)));//(int)(Xy1+(Xheight*0.3)); - soilPolyX[count] = Xx1; - soilPolyY[count++] = (int)(Xy1+Xheight-((damLandHeight-minWHS)/widthWHS)*((Xheight*0.7)));//(int)(Xy1+(Xheight*0.3)); - soilPolyX[count] = Xx1; - soilPolyY[count++] = Xy1+Xheight; - soilPolyX[count] = Xx1+Xwidth; - soilPolyY[count++] = Xy1+Xheight; - - - - for (int i=nSections-2; i>=1; i--) { - - soilPolyX[count] = (int)(((((DownstreamPoint)outputFile.inputDownstream.get(i)).distanceToSection-minRM)/widthRM)*(Xwidth-(Xwidth/5))+Xx1+(Xwidth/5)); - double height = outputFile.maxElevation[i]-outputFile.maxDepth[i]; - soilPolyY[count++] = (int)(Xy1+Xheight-((height-minWHS)/widthWHS)*((Xheight*0.7)));//(Xheight*0.4)); - - } - g.setColor(new Color(150,83,82)); - - g.fillPolygon(soilPolyX,soilPolyY,nSections+2); - - ///////////////////////////////////////////// - // draw xs markers and set selected to yellow - - g.setColor(new Color(0,0,0)); - sectionBoxes = new Rectangle[nSections]; - for (int i=0; i Xx1+Xwidth) { // right justify - left = Xx1+Xwidth-fm.stringWidth(townMaxElevation); - int which = 0; - if (nSections > 3) { - while ((which < nSections-1) && sectionBoxes[which].x < left) - which++; - } - bottom = waterPolyY[nSections+2-which]; - } - else { - - left = cX; - bottom = cY; - } - */ - - // **** always right justify ! - left = Xx1+Xwidth-fm.stringWidth(townMaxElevation); - bottom = waterPolyY[nSections+2]; - - g.drawString(townPeakFlow, left, bottom-3*fm.getAscent()-5); - g.drawString(townMaxElevation, left, bottom-2*fm.getAscent()-5); - g.drawString(townMaxDepth, left, bottom-1*fm.getAscent()-5); - } catch (Throwable e) { - System.out.println("Exception in drawRiverView()"); - e.printStackTrace(); - } - } - /** - * Initialize the class. - */ - private void initialize() { - try { - setName("DisplayGraphicsPanel"); - setLayout(null); - setSize(657, 450); - addMouseListener(this); - } catch (java.lang.Throwable ivjExc) { - System.out.println("Throwable caught In DisplayGraphicsPanel.initialize"); - ivjExc.printStackTrace(); - } - } - public void mouseClicked(MouseEvent event) {} - public void mouseEntered(MouseEvent event) {} - public void mouseExited(MouseEvent event) {} - public void mousePressed(MouseEvent event) - { - int i; - try { - for (i=0; iGenerate FLDVIEW Files (.xy, .fcs)"); - generateFilesButton.addActionListener(this); - panelBottom.add(generateFilesButton); - add(panelBottom, BorderLayout.SOUTH); - } catch (Throwable e) { - JOptionPane.showMessageDialog(this, "Exception caught: " + e.getMessage()); - } - } - public void actionPerformed(ActionEvent evt) { - String osName = System.getProperty("os.name"); - String lowerCaseName = osName.toLowerCase(); - String tempPath = ""; - - // get selected cross sections - int[] selections = xsChooser.getSelectedIndices(); - if (selections.length == 0) { - JOptionPane.showMessageDialog(this, "No cross sections selected.", "Error", JOptionPane.ERROR_MESSAGE); - return; - } - - // verify that the endpoints have lat / lon coordinates - - double epsilon = 0.001; - int minSel = xsChooser.getMinSelectionIndex(), - maxSel = xsChooser.getMaxSelectionIndex(); - - /* - if ( (inputFile.sectionData[maxSel].getLatitude() < epsilon) - || (inputFile.sectionData[maxSel].getLongitude() < epsilon) - || (inputFile.sectionData[minSel].getLatitude() < epsilon) - || (inputFile.sectionData[minSel].getLongitude() < epsilon)) - */ - DownstreamPoint maxPoint = (DownstreamPoint) outputData.inputDownstream.get(maxSel); - DownstreamPoint minPoint = (DownstreamPoint) outputData.inputDownstream.get(minSel); - - if ( (Math.abs(maxPoint.latitude) < epsilon) - || (Math.abs(maxPoint.longitude) < epsilon) - || (Math.abs(minPoint.latitude) < epsilon) - || (Math.abs(minPoint.longitude) < epsilon)) - { - - JOptionPane.showMessageDialog(this, "The cross sections at the endpoints of the selection range must have non-zero latitude and longitude.", "Error", JOptionPane.ERROR_MESSAGE); - return; - } - - - // write .xy and .fcs files - float[] XSWidth = new float[50]; - - int nSections = outputData.inputDownstream.size(), nPairs = AnalysisData.getNumPairs(outputData.inputDownstream); - // System.out.println("Number of Sections = " + nSections + " Number of Pairs = " + nPairs); - // calculate XSWidth - for (int i=0; i -1) - tempPath = PropertyReader.getProperty("TEMPPATH"); - else if(lowerCaseName.indexOf("linux") > -1) - tempPath = PropertyReader.getProperty("DAMCREST_DATA_DIR"); - - if (!tempPath.endsWith(System.getProperty("file.separator"))) - tempPath = tempPath.concat(System.getProperty("file.separator")); - - - - ////////////////////////////////////////////////////////////////////// - // NOTE: The user should choose where the FLDVIEW files are exported - ////////////////////// /////////////////////////////////////////////// - - File fileName; - - String strLastOpenPath = tempPath; // OK for starters - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setDialogTitle("Select File Name For FLDVIEW .xy and .fcs Output"); - - fileChooser.setFileFilter(new DamInputFileFilter(DamInputFileFilter.FLDVIEW_OUTPUT)); - int result = fileChooser.showSaveDialog(this); - FileWriter output; - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return; - - fileName = fileChooser.getSelectedFile(); - if (fileName == null || fileName.getName().equals("")) - { - JOptionPane.showMessageDialog(this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE); - return; - } - - // set the 'last file opened' path // (currently not implemented) - // strLastOpenPath = fileName.getPath(); - - String strPathName = fileName.getAbsolutePath(); - - String s = strPathName; - - String strChosenRootName = strPathName; - - int ix = s.lastIndexOf('.'); - if (ix > 0 && ix < s.length() - 1) - { - if(lowerCaseName.indexOf("windows") > -1) - strChosenRootName = s.substring(0, ix).toLowerCase(); - else if(lowerCaseName.indexOf("linux") > -1) - strChosenRootName = s.substring(0, ix); - } - - /////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////// - - - String strExtendedFileName = strChosenRootName + ".xy"; - try { - output = new FileWriter(strExtendedFileName); - output.write(" 1\n"); - - int riverSectionCount = 1; - boolean incremented = true; - - for (int i=0; i 0) - getcomboBestXS().setSelectedIndex(0); - - getlistModelXS().clear(); - getListXS().clearSelection(); - - clearXSFields(); - - getcomboXSType().setSelectedIndex(0); - gettableXSData().clearSelection(); - - /* - * while (gettableModelXSGeom().getRowCount() != 0) - * gettableModelXSGeom().removeRow(0); - */ - - nDownstreamEditing = -1; - - } - - /** - * Initialize ModelGUI for Input Scenario fields Creation date: (7/29/2003 - * 10:14:27 AM) - */ - private void clearScenarioFields() - { - - gettextSource().setText(""); - getcomboScenario().setSelectedIndex(0); - getcomboTypeOfDam().setSelectedIndex(0); - getcomboDBUG().setSelectedIndex(0); - gettextHDE().setText(""); - gettextBME().setText(""); - gettextVOL().setText(""); - gettextSA().setText(""); - gettextBW().setText(""); - gettextTFM().setText(""); - gettextQO().setText(""); - gettextDISTTN().setText(""); - gettextCMS().setText(""); - - nScenarioEditing = -1; - - } - - /** - * Insert the method's description here. Creation date: (7/29/2003 3:25:56 - * PM) - */ - private void clearXSFields() - { - - getcomboXSType().setSelectedIndex(0); - stopTableEditing(); - gettableXSData().clearSelection(); - - int rowLimiter = gettableModelXSGeom().getRowCount(); - for (int i = 0; i < rowLimiter; i++) - { - gettableModelXSGeom().setValueAt("", i, 0); - gettableModelXSGeom().setValueAt("", i, 1); - gettableModelXSGeom().setValueAt("", i, 2); - gettableModelXSGeom().setValueAt("", i, 3); - } - - nXSEditing = -1; - } - - /** - * connEtoC1: - * (ListScenario.listSelection.valueChanged(javax.swing.event.ListSelectionEvent) - * --> ModelGUI.handleScenarioListSelection()V) - * - * @param arg1 - * javax.swing.event.ListSelectionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC1( ListSelectionEvent arg1 ) - { - try - { - // user code begin {1} - // user code end - this.handleScenarioListSelection(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC10: (textName.focus.focusLost(java.awt.event.FocusEvent) --> - * ModelGUI.handleDownstreamKeyLostFocus()V) - * - * @param arg1 - * java.awt.event.FocusEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC10(java.awt.event.FocusEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleDownstreamKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC11: (textDistance.focus.focusLost(java.awt.event.FocusEvent) --> - * ModelGUI.handleDownstreamKeyLostFocus()V) - * - * @param arg1 - * java.awt.event.FocusEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC11(java.awt.event.FocusEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleDownstreamKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC12: - * (ListXS.listSelection.valueChanged(javax.swing.event.ListSelectionEvent) - * --> - * ModelGUI.handleXSListSelection(Ljavax.swing.event.ListSelectionEvent;)V) - * - * @param arg1 - * javax.swing.event.ListSelectionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC12( ListSelectionEvent arg1 ) - { - try - { - // user code begin {1} - // user code end - this.handleXSListSelection(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC13: - * (comboXSType.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleXSKeyLostFocus()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC13(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleXSKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC14: (ListXS.mouse.mouseClicked(java.awt.event.MouseEvent) --> - * ModelGUI.handleXSListClick(Ljava.awt.event.MouseEvent;)V) - * - * @param arg1 - * java.awt.event.MouseEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC14(java.awt.event.MouseEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleXSListClick(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC15: (ModelGUI.window.windowClosing(java.awt.event.WindowEvent) - * --> ModelGUI.handleWindowClosing()V) - * - * @param arg1 - * java.awt.event.WindowEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC15(java.awt.event.WindowEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleWindowClosing(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC16: (menuClose.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuClose()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC16(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuClose(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC17: (comboBestXS.action. --> - * ModelGUI.handleDownstreamKeyLostFocus()V) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC17() - { - try - { - // user code begin {1} - // user code end - this.handleDownstreamKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC18: (menuAbout.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuAbout()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC18(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuAbout(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC19: - * (menuImportDAT.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleMenuImportFromDAT()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC19(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuImportFromDAT(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC2: - * (ListDown.listSelection.valueChanged(javax.swing.event.ListSelectionEvent) - * --> ModelGUI.handleDownstreamListSelection()V) - * - * @param arg1 - * javax.swing.event.ListSelectionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC2( ListSelectionEvent arg1 ) - { - try - { - // user code begin {1} - // user code end - this.handleDownstreamListSelection(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC20: - * (menuImportFLDXS.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleMenuImportFromFLDXS()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC20(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuImportFromFLDXS(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC21: - * (menuUpdateDatabase.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuUpdateDatabase(Z)Z) - * - * @return boolean - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private boolean connEtoC21(java.awt.event.ActionEvent arg1) - { - boolean connEtoC21Result = false; - try - { - // user code begin {1} - // user code end - connEtoC21Result = this.handleMenuUpdateDatabase(true); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - return connEtoC21Result; - } - - /** - * connEtoC22: (menuSave.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuSave()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC22(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuSave(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC23: (menuOpen.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuOpen()Z) - * - * @return boolean - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private boolean connEtoC23(java.awt.event.ActionEvent arg1) - { - boolean connEtoC23Result = false; - try - { - // user code begin {1} - // user code end - connEtoC23Result = this.handleMenuOpen(); - // user code begin {2} - // System.out.println("The connEtoC23Result is:" + - // connEtoC23Result); - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - System.out.println("Throwable of connEtoC23"); - // user code end - handleException(ivjExc); - } - return connEtoC23Result; - } - - /** - * connEtoC24: - * (menuSaveAs.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleMenuSaveAs()Z) - * - * @return boolean - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private boolean connEtoC24(java.awt.event.ActionEvent arg1) - { - boolean connEtoC24Result = false; - try - { - // user code begin {1} - // user code end - connEtoC24Result = this.handleMenuSaveAs(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - return connEtoC24Result; - } - - /** - * connEtoC25: - * (menuEditText.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleMenuEditText()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC25(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuEditText(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC26: - * (menuDisplayOutput.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleDisplayOutput()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC26(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuDisplayOutput(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC27: - * (menuRun_SMPDBK.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleMenuRun_SMPDBK()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC27(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuRun_SMPDBK(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC3: (ListXS.key.keyPressed(java.awt.event.KeyEvent) --> - * ModelGUI.handleXSListKey(Ljava.awt.event.KeyEvent;)V) - * - * @param arg1 - * java.awt.event.KeyEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC3(java.awt.event.KeyEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleXSListKey(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC4: (menuQuit.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuQuit()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC4(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuQuit(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC5: (ListScenario.key.keyPressed(java.awt.event.KeyEvent) --> - * ModelGUI.handleScenarioListKey(Ljava.awt.event.KeyEvent;)V) - * - * @param arg1 - * java.awt.event.KeyEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC5(java.awt.event.KeyEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleScenarioListKey(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC6: - * (comboScenario.action.actionPerformed(java.awt.event.ActionEvent) --> - * ModelGUI.handleScenarioKeyFocusLost()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC6(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleScenarioKeyFocusLost(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC7: (textSource.focus.focusLost(java.awt.event.FocusEvent) --> - * ModelGUI.handleScenarioKeyFocusLost()V) - * - * @param arg1 - * java.awt.event.FocusEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC7(java.awt.event.FocusEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleScenarioKeyFocusLost(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC8: (menuNew.action.actionPerformed(java.awt.event.ActionEvent) - * --> ModelGUI.handleMenuNew()V) - * - * @param arg1 - * java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC8(java.awt.event.ActionEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleMenuNew(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connEtoC9: (ListDown.key.keyPressed(java.awt.event.KeyEvent) --> - * ModelGUI.handleDownListKey(Ljava.awt.event.KeyEvent;)V) - * - * @param arg1 - * java.awt.event.KeyEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC9(java.awt.event.KeyEvent arg1) - { - try - { - // user code begin {1} - // user code end - this.handleDownListKey(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connPtoP1SetTarget: (listModelXS.this <-->ListXSList.model) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connPtoP1SetTarget() - { - /* Set the target from the source */ - try - { - getListXS().setModel(getlistModelXS()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connPtoP2SetTarget: (listModelDown.this <-->ListDownList.model) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connPtoP2SetTarget() - { - /* Set the target from the source */ - try - { - getListDown().setModel(getlistModelDown()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connPtoP3SetTarget: (listModelScenario.this <-->ListScenarioList.model) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connPtoP3SetTarget() - { - /* Set the target from the source */ - try - { - getListScenario().setModel(getlistModelScenario()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * connPtoP4SetTarget: (tableModelXSGeom.this <-->tableXSData.model) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connPtoP4SetTarget() - { - /* Set the target from the source */ - try - { - gettableXSData().setModel(gettableModelXSGeom()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - - /** - * Creates a new downstream point with default data and makes it the current - * selection Creation date: (7/29/2003 9:06:27 AM) - */ - private void createNewDownstreamPoint(int selectedIndex) - { - - DownstreamPoint newDownstream = new DownstreamPoint(); - - newDownstream.changeFlag = 2; // *** indicate that DownstreamPoint needs - // inserted ! - - currentData.downstream.add(selectedIndex, newDownstream); - - updateDownstreamList(); - } - - /** - * Creates a new scenario with default data and makes it the current - * selection Creation date: (7/29/2003 9:06:27 AM) - */ - private void createNewScenario() - { - - ModelScenario newScenario = new ModelScenario(); - - currentData.scenarios.add(newScenario); // *** this is at bottom - - updateScenarioList(); - - bHasDataToSave = true; - } - - /** - * Create new SectionGeometry for particular DownstreamPoint Creation date: - * (7/30/2003 8:02:24 AM) - */ - private void createNewXS(int whichDownstreamPoint) - { - - if (whichDownstreamPoint == -1) - return; - - SectionGeometry newSection = new SectionGeometry(); - DownstreamPoint downEditing = (DownstreamPoint) currentData.downstream - .get(whichDownstreamPoint); - - // *** add newSection to back of ArrayList - downEditing.xsections.add(newSection); - - // make this the "best" cross section if it is the only one - if (downEditing.xsections.size() == 1) - downEditing.bestXS = 0; - - updateXSList(); - } - - /** - * Insert the method's description here. Creation date: (7/29/2003 12:10:26 - * PM) - * - * @param bEnable - * boolean - */ - private void enableDownstreamEditors(boolean bEnable) - { - gettextName().setEnabled(bEnable); - gettextDistance().setEnabled(bEnable); - gettextFloodDepth().setEnabled(bEnable); - gettextFloodFlow().setEnabled(bEnable); - gettextLatitude().setEnabled(bEnable); - gettextLongitude().setEnabled(bEnable); - getcomboBestXS().setEnabled(bEnable); - getListXS().setEnabled(bEnable); - } - - /** - * Insert the method's description here. Creation date: (7/29/2003 10:17:09 - * AM) - * - * @param bEnable - * boolean - */ - private void enableScenarioEditors(boolean bEnable) - { - gettextSource().setEnabled(bEnable); - getcomboScenario().setEnabled(bEnable); - getcomboTypeOfDam().setEnabled(bEnable); - getcomboDBUG().setEnabled(bEnable); - gettextHDE().setEnabled(bEnable); - gettextBME().setEnabled(bEnable); - gettextVOL().setEnabled(bEnable); - gettextSA().setEnabled(bEnable); - gettextBW().setEnabled(bEnable); - gettextTFM().setEnabled(bEnable); - gettextQO().setEnabled(bEnable); - gettextDISTTN().setEnabled(bEnable); - gettextCMS().setEnabled(bEnable); - } - - /** - * Insert the method's description here. Creation date: (7/30/2003 8:01:34 - * AM) - * - * @param bEnable - * boolean - */ - private void enableXSEditors(boolean bEnable) - { - gettableXSData().setEnabled(bEnable); - getcomboXSType().setEnabled(bEnable); - } - - /** - * This method attempts to fill the output fields of each scenario with - * updated model output. - * - * If the model fails to run, any existing output is kept as it was. - * - * NOTE: In order to keep input and output synchronized, This should be - * changed to clear the output if the model fails to run. - * - * Creation date: (7/31/2003 11:00:39 AM) - */ - private boolean generateOutput() - { - - boolean generationResult; - if (_DEBUG) - System.out.print("Generating output..."); - generationResult = currentData.generateOutput(); - if (_DEBUG) - System.out.println("Finished."); - return generationResult; - - } - - /** - * Return the columnBS property value. - * - * @return javax.swing.table.TableColumn - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.table.TableColumn getcolumnBS() - { - if (ivjcolumnBS == null) - { - try - { - ivjcolumnBS = new javax.swing.table.TableColumn(); - ivjcolumnBS.setModelIndex(1); - ivjcolumnBS.setHeaderValue("Channel Width"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnBS; - } - - /** - * Return the columnBSS property value. - * - * @return javax.swing.table.TableColumn - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.table.TableColumn getcolumnBSS() - { - if (ivjcolumnBSS == null) - { - try - { - ivjcolumnBSS = new javax.swing.table.TableColumn(); - ivjcolumnBSS.setModelIndex(2); - ivjcolumnBSS.setHeaderValue("Inactive Width"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnBSS; - } - - /** - * Return the columnElevation property value. - * - * @return javax.swing.table.TableColumn - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.table.TableColumn getcolumnElevation() - { - if (ivjcolumnElevation == null) - { - try - { - ivjcolumnElevation = new javax.swing.table.TableColumn(); - ivjcolumnElevation.setHeaderValue("Elevation"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnElevation; - } - - /** - * Return the columnMannN property value. - * - * @return javax.swing.table.TableColumn - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.table.TableColumn getcolumnMannN() - { - if (ivjcolumnMannN == null) - { - try - { - ivjcolumnMannN = new javax.swing.table.TableColumn(); - ivjcolumnMannN.setModelIndex(3); - ivjcolumnMannN.setHeaderValue("Manning N"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnMannN; - } - - /** - * Return the comboBestXS property value. - * - * @return javax.swing.JComboBox - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JComboBox getcomboBestXS() - { - if (ivjcomboBestXS == null) - { - try - { - ivjcomboBestXS = new javax.swing.JComboBox(); - ivjcomboBestXS.setName("comboBestXS"); - ivjcomboBestXS.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboBestXS.setBackground(new java.awt.Color(255, 255, 249)); - ivjcomboBestXS.setBounds(234, 297, 143, 22); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboBestXS; - } - - /** - * Return the comboDBUG property value. - * - * @return javax.swing.JComboBox - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JComboBox getcomboDBUG() - { - if (ivjcomboDBUG == null) - { - try - { - ivjcomboDBUG = new javax.swing.JComboBox(); - ivjcomboDBUG.setName("comboDBUG"); - ivjcomboDBUG.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboDBUG.setBackground(new java.awt.Color(255, 255, 255)); - ivjcomboDBUG.setBounds(269, 437, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboDBUG; - } - - /** - * Return the comboScenario property value. - * - * @return javax.swing.JComboBox - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JComboBox getcomboScenario() - { - if (ivjcomboScenario == null) - { - try - { - ivjcomboScenario = new javax.swing.JComboBox(); - ivjcomboScenario.setName("comboScenario"); - ivjcomboScenario.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboScenario - .setBackground(new java.awt.Color(255, 255, 255)); - ivjcomboScenario.setBounds(269, 144, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboScenario; - } - - /** - * Return the comboTypeOfDam property value. - * - * @return javax.swing.JComboBox - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JComboBox getcomboTypeOfDam() - { - if (ivjcomboTypeOfDam == null) - { - try - { - ivjcomboTypeOfDam = new javax.swing.JComboBox(); - ivjcomboTypeOfDam.setName("comboTypeOfDam"); - ivjcomboTypeOfDam.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboTypeOfDam.setBackground(new java.awt.Color(255, 255, - 255)); - ivjcomboTypeOfDam.setBounds(269, 168, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboTypeOfDam; - } - - /** - * Return the comboXSType property value. - * - * @return javax.swing.JComboBox - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JComboBox getcomboXSType() - { - if (ivjcomboXSType == null) - { - try - { - ivjcomboXSType = new javax.swing.JComboBox(); - ivjcomboXSType.setName("comboXSType"); - ivjcomboXSType.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboXSType.setBackground(new java.awt.Color(255, 255, 255)); - ivjcomboXSType.setBounds(138, 94, 209, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboXSType; - } - - /** - * Return the JFrameContentPane property value. - * - * @return javax.swing.JPanel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private JPanel getJFrameContentPane() - { - if (ivjJFrameContentPane == null) - { - try - { - ivjJFrameContentPane = new javax.swing.JPanel(); - ivjJFrameContentPane.setName("JFrameContentPane"); - ivjJFrameContentPane.setLayout(null); - getJFrameContentPane().add(getpanelNameInfo(), - getpanelNameInfo().getName()); - getJFrameContentPane().add(getpanelDamInfo(), - getpanelDamInfo().getName()); - getJFrameContentPane().add(getpanelDownstreamInfo(), - getpanelDownstreamInfo().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJFrameContentPane; - } - - /** - * Return the JSeparator1 property value. - * - * @return javax.swing.JSeparator - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JSeparator getJSeparator1() - { - if (ivjJSeparator1 == null) - { - try - { - ivjJSeparator1 = new javax.swing.JSeparator(); - ivjJSeparator1.setName("JSeparator1"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJSeparator1; - } - - /** - * Return the JSeparator2 property value. - * - * @return javax.swing.JSeparator - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JSeparator getJSeparator2() - { - if (ivjJSeparator2 == null) - { - try - { - ivjJSeparator2 = new javax.swing.JSeparator(); - ivjJSeparator2.setName("JSeparator2"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJSeparator2; - } - - /** - * Return the labelBestXS property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - /* - * private javax.swing.JLabel getlabelBestXS() { if (ivjlabelBestXS == null) { - * try { ivjlabelBestXS = new javax.swing.JLabel(); - * ivjlabelBestXS.setName("labelBestXS"); ivjlabelBestXS.setFont(new - * java.awt.Font("Arial", 1, 10)); ivjlabelBestXS.setText(""); - * ivjlabelBestXS.setBounds(312, 10, 24, 14); - * ivjlabelBestXS.setForeground(java.awt.Color.black); // user code begin - * {1} // user code end } catch (java.lang.Throwable ivjExc) { // user code - * begin {2} // user code end handleException(ivjExc); } } return - * ivjlabelBestXS; } - */ - /** - * Return the labelBME property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelBME() - { - if (ivjlabelBME == null) - { - try - { - ivjlabelBME = new javax.swing.JLabel(); - ivjlabelBME.setName("labelBME"); - ivjlabelBME.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelBME.setText("* Final Breach Elevation (BME in FT MSL)"); - ivjlabelBME.setBounds(13, 227, 230, 14); - ivjlabelBME.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelBME; - } - - /** - * Return the labelBW property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelBW() - { - if (ivjlabelBW == null) - { - try - { - ivjlabelBW = new javax.swing.JLabel(); - ivjlabelBW.setName("labelBW"); - ivjlabelBW.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelBW.setText("Final Breach Width (BW in FT)"); - ivjlabelBW.setBounds(13, 307, 226, 14); - ivjlabelBW.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelBW; - } - - /** - * Return the labelCMS property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelCMS() - { - if (ivjlabelCMS == null) - { - try - { - ivjlabelCMS = new javax.swing.JLabel(); - ivjlabelCMS.setName("labelCMS"); - ivjlabelCMS.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelCMS.setText("Dead Storage Equivalent Mann. N (CMS)"); - ivjlabelCMS.setBounds(13, 413, 226, 14); - ivjlabelCMS.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelCMS; - } - - /** - * Return the labelDamName property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelDamName() - { - if (ivjlabelDamName == null) - { - try - { - ivjlabelDamName = new javax.swing.JLabel(); - ivjlabelDamName.setName("labelDamName"); - ivjlabelDamName.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelDamName.setText("* Dam Name"); - ivjlabelDamName.setBounds(17, 15, 124, 14); - ivjlabelDamName.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelDamName; - } - - /** - * Return the labelDBUG property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelDBUG() - { - if (ivjlabelDBUG == null) - { - try - { - ivjlabelDBUG = new javax.swing.JLabel(); - ivjlabelDBUG.setName("labelDBUG"); - ivjlabelDBUG.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelDBUG.setText("SMPDBK Debug Option"); - ivjlabelDBUG.setBounds(13, 440, 226, 14); - ivjlabelDBUG.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelDBUG; - } - - /** - * Return the labelDISTTN property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelDISTTN() - { - if (ivjlabelDISTTN == null) - { - try - { - ivjlabelDISTTN = new javax.swing.JLabel(); - ivjlabelDISTTN.setName("labelDISTTN"); - ivjlabelDISTTN.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelDISTTN - .setText("Distance to PT of Interest (DISTTN in MILES)"); - ivjlabelDISTTN.setBounds(13, 386, 253, 14); - ivjlabelDISTTN.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelDISTTN; - } - - /** - * Return the labelHDE property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelHDE() - { - if (ivjlabelHDE == null) - { - try - { - ivjlabelHDE = new javax.swing.JLabel(); - ivjlabelHDE.setName("labelHDE"); - ivjlabelHDE.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelHDE.setText("* Dam Breach Elevation (HDE in FT MSL)"); - ivjlabelHDE.setBounds(13, 199, 231, 14); - ivjlabelHDE.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelHDE; - } - - /** - * Return the labelPPOI property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelPPOI() - { - if (ivjlabelPPOI == null) - { - try - { - ivjlabelPPOI = new javax.swing.JLabel(); - ivjlabelPPOI.setName("labelPPOI"); - ivjlabelPPOI.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelPPOI.setText("Primary Point of Interest"); - ivjlabelPPOI.setBounds(17, 68, 143, 14); - ivjlabelPPOI.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelPPOI; - } - - /** - * Return the labelQO property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelQO() - { - if (ivjlabelQO == null) - { - try - { - ivjlabelQO = new javax.swing.JLabel(); - ivjlabelQO.setName("labelQO"); - ivjlabelQO.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelQO.setText("* Non Breach Flow (QO in CFS)"); - ivjlabelQO.setBounds(13, 361, 226, 14); - ivjlabelQO.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelQO; - } - - /** - * Return the labelRequiredFieldsNotice property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelRequiredFieldsNotice() - { - if (ivjlabelRequiredFieldsNotice == null) - { - try - { - ivjlabelRequiredFieldsNotice = new javax.swing.JLabel(); - ivjlabelRequiredFieldsNotice - .setName("labelRequiredFieldsNotice"); - ivjlabelRequiredFieldsNotice.setFont(new java.awt.Font("Arial", - 1, 10)); - ivjlabelRequiredFieldsNotice - .setText("Fields with a (*) are required. Also, either VOL or SA must be filled in."); - ivjlabelRequiredFieldsNotice.setBounds(12, 464, 402, 14); - ivjlabelRequiredFieldsNotice.setForeground(java.awt.Color.red); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelRequiredFieldsNotice; - } - - /** - * Return the labelRiverName property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelRiverName() - { - if (ivjlabelRiverName == null) - { - try - { - ivjlabelRiverName = new javax.swing.JLabel(); - ivjlabelRiverName.setName("labelRiverName"); - ivjlabelRiverName.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelRiverName.setText("* River Name"); - ivjlabelRiverName.setBounds(17, 42, 124, 14); - ivjlabelRiverName.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelRiverName; - } - - /** - * Return the labelSA property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelSA() - { - if (ivjlabelSA == null) - { - try - { - ivjlabelSA = new javax.swing.JLabel(); - ivjlabelSA.setName("labelSA"); - ivjlabelSA.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelSA.setText("Surface Area of Reservoir (SA in ACRES)"); - ivjlabelSA.setBounds(13, 280, 226, 14); - ivjlabelSA.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelSA; - } - - /** - * Return the labelScenario property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelScenario() - { - if (ivjlabelScenario == null) - { - try - { - ivjlabelScenario = new javax.swing.JLabel(); - ivjlabelScenario.setName("labelScenario"); - ivjlabelScenario.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelScenario.setText("* Scenario"); - ivjlabelScenario.setBounds(12, 145, 80, 14); - ivjlabelScenario.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelScenario; - } - - /** - * Return the labelScenarioList property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelScenarioList() - { - if (ivjlabelScenarioList == null) - { - try - { - ivjlabelScenarioList = new javax.swing.JLabel(); - ivjlabelScenarioList.setName("labelScenarioList"); - ivjlabelScenarioList.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelScenarioList.setText("Scenario List:"); - ivjlabelScenarioList.setBounds(14, 12, 116, 14); - ivjlabelScenarioList.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelScenarioList; - } - - /** - * Return the labelFloodFlow1 property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelSectionType() - { - if (ivjlabelSectionType == null) - { - try - { - ivjlabelSectionType = new javax.swing.JLabel(); - ivjlabelSectionType.setName("labelSectionType"); - ivjlabelSectionType.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelSectionType.setText("Cross Section Type"); - ivjlabelSectionType.setBounds(13, 97, 112, 14); - ivjlabelSectionType.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelSectionType; - } - - /** - * Return the labelSource property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelSource() - { - if (ivjlabelSource == null) - { - try - { - ivjlabelSource = new javax.swing.JLabel(); - ivjlabelSource.setName("labelSource"); - ivjlabelSource.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelSource.setText("* Source"); - ivjlabelSource.setBounds(12, 119, 80, 14); - ivjlabelSource.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelSource; - } - - /** - * Return the labelTFM property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelTFM() - { - if (ivjlabelTFM == null) - { - try - { - ivjlabelTFM = new javax.swing.JLabel(); - ivjlabelTFM.setName("labelTFM"); - ivjlabelTFM.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelTFM.setText("Time of Dam Failure (TFM in MINUTES)"); - ivjlabelTFM.setBounds(13, 333, 226, 14); - ivjlabelTFM.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelTFM; - } - - /** - * Return the labelTypeOfDam property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelTypeOfDam() - { - if (ivjlabelTypeOfDam == null) - { - try - { - ivjlabelTypeOfDam = new javax.swing.JLabel(); - ivjlabelTypeOfDam.setName("labelTypeOfDam"); - ivjlabelTypeOfDam.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelTypeOfDam.setText("* Type Of Dam"); - ivjlabelTypeOfDam.setBounds(13, 172, 226, 14); - ivjlabelTypeOfDam.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelTypeOfDam; - } - - /** - * Return the labelVolume property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelVolume() - { - if (ivjlabelVolume == null) - { - try - { - ivjlabelVolume = new javax.swing.JLabel(); - ivjlabelVolume.setName("labelVolume"); - ivjlabelVolume.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelVolume.setText("Volume of Reservoir (VOL in ACRE-FT)"); - ivjlabelVolume.setBounds(13, 253, 226, 14); - ivjlabelVolume.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelVolume; - } - - /** - * Return the labelXSDistance property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSDistance() - { - if (ivjlabelXSDistance == null) - { - try - { - ivjlabelXSDistance = new javax.swing.JLabel(); - ivjlabelXSDistance.setName("labelXSDistance"); - ivjlabelXSDistance.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSDistance - .setText("Distance From Dam to Section (MILES)"); - ivjlabelXSDistance.setBounds(19, 154, 213, 14); - ivjlabelXSDistance.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSDistance; - } - - /** - * Return the labelXSFloodDepth property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSFloodDepth() - { - if (ivjlabelXSFloodDepth == null) - { - try - { - ivjlabelXSFloodDepth = new javax.swing.JLabel(); - ivjlabelXSFloodDepth.setName("labelXSFloodDepth"); - ivjlabelXSFloodDepth.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSFloodDepth.setText("Flood Depth (FT)"); - ivjlabelXSFloodDepth.setBounds(20, 183, 132, 14); - ivjlabelXSFloodDepth.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSFloodDepth; - } - - /** - * Return the labelFloodFlow property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSFloodFlow() - { - if (ivjlabelXSFloodFlow == null) - { - try - { - ivjlabelXSFloodFlow = new javax.swing.JLabel(); - ivjlabelXSFloodFlow.setName("labelXSFloodFlow"); - ivjlabelXSFloodFlow.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSFloodFlow.setText("Flow At Flood Stage (CFS)"); - ivjlabelXSFloodFlow.setBounds(19, 214, 201, 14); - ivjlabelXSFloodFlow.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSFloodFlow; - } - - /** - * Return the labelXSLatitutde property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSLatitutde() - { - if (ivjlabelXSLatitutde == null) - { - try - { - ivjlabelXSLatitutde = new javax.swing.JLabel(); - ivjlabelXSLatitutde.setName("labelXSLatitutde"); - ivjlabelXSLatitutde.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSLatitutde.setText("Latitude"); - ivjlabelXSLatitutde.setBounds(20, 244, 58, 14); - ivjlabelXSLatitutde.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSLatitutde; - } - - /** - * Return the labelXSList property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSList() - { - if (ivjlabelXSList == null) - { - try - { - ivjlabelXSList = new javax.swing.JLabel(); - ivjlabelXSList.setName("labelXSList"); - ivjlabelXSList.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSList.setText("Downstream Point List:"); - ivjlabelXSList.setBounds(13, 10, 162, 14); - ivjlabelXSList.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSList; - } - - /** - * Return the labelXSList1 property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSList1() - { - if (ivjlabelXSList1 == null) - { - try - { - ivjlabelXSList1 = new javax.swing.JLabel(); - ivjlabelXSList1.setName("labelXSList1"); - ivjlabelXSList1.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSList1.setText("Cross Section List:"); - ivjlabelXSList1.setBounds(8, 9, 142, 14); - ivjlabelXSList1.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSList1; - } - - /** - * Return the labelXSList11 property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSList11() - { - if (ivjlabelXSList11 == null) - { - try - { - ivjlabelXSList11 = new javax.swing.JLabel(); - ivjlabelXSList11.setName("labelXSList11"); - ivjlabelXSList11.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSList11.setText("Best Section Type: "); - ivjlabelXSList11.setBounds(19, 300, 118, 14); - ivjlabelXSList11.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSList11; - } - - /** - * Return the labelXSLongitude property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSLongitude() - { - if (ivjlabelXSLongitude == null) - { - try - { - ivjlabelXSLongitude = new javax.swing.JLabel(); - ivjlabelXSLongitude.setName("labelXSLongitude"); - ivjlabelXSLongitude.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSLongitude.setText("Longitude"); - ivjlabelXSLongitude.setBounds(19, 274, 66, 14); - ivjlabelXSLongitude.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSLongitude; - } - - /** - * Return the labelXSName property value. - * - * @return javax.swing.JLabel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JLabel getlabelXSName() - { - if (ivjlabelXSName == null) - { - try - { - ivjlabelXSName = new javax.swing.JLabel(); - ivjlabelXSName.setName("labelXSName"); - ivjlabelXSName.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSName.setText("Downstream Point Name"); - ivjlabelXSName.setBounds(18, 125, 198, 14); - ivjlabelXSName.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSName; - } - - /** - * Return the listXSList property value. - * - * @return javax.swing.JList - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JList getListDown() - { - if (ivjListDown == null) - { - try - { - ivjListDown = new javax.swing.JList(); - ivjListDown.setName("ListDown"); - ivjListDown.setBounds(0, 0, 186, 120); - ivjListDown - .setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjListDown; - } - - /** - * Return the listModelDown property value. - * - * @return javax.swing.DefaultListModel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.DefaultListModel getlistModelDown() - { - if (ivjlistModelDown == null) - { - try - { - ivjlistModelDown = new javax.swing.DefaultListModel(); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlistModelDown; - } - - /** - * Return the listModelScenario property value. - * - * @return javax.swing.DefaultListModel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.DefaultListModel getlistModelScenario() - { - if (ivjlistModelScenario == null) - { - try - { - ivjlistModelScenario = new javax.swing.DefaultListModel(); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlistModelScenario; - } - - /** - * Return the listModelXS property value. - * - * @return javax.swing.DefaultListModel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.DefaultListModel getlistModelXS() - { - if (ivjlistModelXS == null) - { - try - { - ivjlistModelXS = new javax.swing.DefaultListModel(); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlistModelXS; - } - - /** - * Return the listScenarioList property value. - * - * @return javax.swing.JList - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JList getListScenario() - { - if (ivjListScenario == null) - { - try - { - ivjListScenario = new javax.swing.JList(); - ivjListScenario.setName("ListScenario"); - ivjListScenario.setBounds(0, 0, 192, 120); - ivjListScenario - .setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjListScenario; - } - - /** - * Return the listXSList1 property value. - * - * @return javax.swing.JList - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JList getListXS() - { - if (ivjListXS == null) - { - try - { - ivjListXS = new javax.swing.JList(); - ivjListXS.setName("ListXS"); - ivjListXS.setBounds(0, 0, 177, 120); - ivjListXS - .setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjListXS; - } - - /** - * Return the menuAbout property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuAbout() - { - if (ivjmenuAbout == null) - { - try - { - ivjmenuAbout = new javax.swing.JMenuItem(); - ivjmenuAbout.setName("menuAbout"); - ivjmenuAbout.setMnemonic('a'); - ivjmenuAbout.setText("About SMPDBK..."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuAbout; - } - - /** - * Return the menuClose property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuClose() - { - if (ivjmenuClose == null) - { - try - { - ivjmenuClose = new javax.swing.JMenuItem(); - ivjmenuClose.setName("menuClose"); - ivjmenuClose.setMnemonic('c'); - ivjmenuClose.setText("Close"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuClose; - } - - /** - * Return the menuDatabase property value. - * - * @return javax.swing.JMenu - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenu getmenuDatabase() - { - if (ivjmenuDatabase == null) - { - try - { - ivjmenuDatabase = new javax.swing.JMenu(); - ivjmenuDatabase.setName("menuDatabase"); - ivjmenuDatabase.setMnemonic('d'); - ivjmenuDatabase.setText("Database"); - ivjmenuDatabase.add(getmenuUpdateDatabase()); - ivjmenuDatabase.add(getmenuClose()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuDatabase; - } - - /** - * Return the menuDisplayOutput property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuDisplayOutput() - { - if (ivjmenuDisplayOutput == null) - { - try - { - ivjmenuDisplayOutput = new javax.swing.JMenuItem(); - ivjmenuDisplayOutput.setName("menuDisplayOutput"); - ivjmenuDisplayOutput.setMnemonic('D'); - ivjmenuDisplayOutput.setText("Display SMPDBK Output"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuDisplayOutput; - } - - /** - * Return the menuEdit property value. - * - * @return javax.swing.JMenu - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenu getmenuEdit() - { - if (ivjmenuEdit == null) - { - try - { - ivjmenuEdit = new javax.swing.JMenu(); - ivjmenuEdit.setName("menuEdit"); - ivjmenuEdit.setMnemonic('e'); - ivjmenuEdit.setText("Edit"); - ivjmenuEdit.add(getmenuEditText()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuEdit; - } - - /** - * Return the menuEditText property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuEditText() - { - if (ivjmenuEditText == null) - { - try - { - ivjmenuEditText = new javax.swing.JMenuItem(); - ivjmenuEditText.setName("menuEditText"); - ivjmenuEditText.setMnemonic('e'); - ivjmenuEditText.setText("Edit Text File"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuEditText; - } - - /** - * Return the menuFile property value. - * - * @return javax.swing.JMenu - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenu getmenuFile() - { - if (ivjmenuFile == null) - { - try - { - ivjmenuFile = new javax.swing.JMenu(); - ivjmenuFile.setName("menuFile"); - ivjmenuFile.setMnemonic('f'); - ivjmenuFile.setText("File"); - ivjmenuFile.add(getmenuNew()); - ivjmenuFile.add(getmenuOpen()); - ivjmenuFile.add(getmenuSave()); - ivjmenuFile.add(getmenuSaveAs()); - ivjmenuFile.add(getJSeparator1()); - ivjmenuFile.add(getmenuImportFLDXS()); - ivjmenuFile.add(getmenuImportDAT()); - ivjmenuFile.add(getJSeparator2()); - ivjmenuFile.add(getmenuQuit()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuFile; - } - - /** - * Return the menuHelp property value. - * - * @return javax.swing.JMenu - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenu getmenuHelp() - { - if (ivjmenuHelp == null) - { - try - { - ivjmenuHelp = new javax.swing.JMenu(); - ivjmenuHelp.setName("menuHelp"); - ivjmenuHelp.setMnemonic('h'); - ivjmenuHelp.setText("Help"); - ivjmenuHelp.add(getmenuAbout()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuHelp; - } - - /** - * Return the menuImportDAT property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuImportDAT() - { - if (ivjmenuImportDAT == null) - { - try - { - ivjmenuImportDAT = new javax.swing.JMenuItem(); - ivjmenuImportDAT.setName("menuImportDAT"); - ivjmenuImportDAT.setMnemonic('d'); - ivjmenuImportDAT.setText("Import SMPDBK input file"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuImportDAT; - } - - /** - * Return the menuImportFLDXS property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuImportFLDXS() - { - if (ivjmenuImportFLDXS == null) - { - try - { - ivjmenuImportFLDXS = new javax.swing.JMenuItem(); - ivjmenuImportFLDXS.setName("menuImportFLDXS"); - ivjmenuImportFLDXS.setMnemonic('X'); - ivjmenuImportFLDXS.setText("Import FLDXS Cross Sections"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuImportFLDXS; - } - - /** - * Return the menuNew property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuNew() - { - if (ivjmenuNew == null) - { - try - { - ivjmenuNew = new javax.swing.JMenuItem(); - ivjmenuNew.setName("menuNew"); - ivjmenuNew.setMnemonic('n'); - ivjmenuNew.setText("New"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuNew; - } - - /** - * Return the menuOpen property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuOpen() - { - if (ivjmenuOpen == null) - { - try - { - ivjmenuOpen = new javax.swing.JMenuItem(); - ivjmenuOpen.setName("menuOpen"); - ivjmenuOpen.setMnemonic('o'); - ivjmenuOpen.setText("Open..."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuOpen; - } - - /** - * Return the menuQuit property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuQuit() - { - if (ivjmenuQuit == null) - { - try - { - ivjmenuQuit = new javax.swing.JMenuItem(); - ivjmenuQuit.setName("menuQuit"); - ivjmenuQuit.setMnemonic('q'); - ivjmenuQuit.setText("Quit"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuQuit; - } - - /** - * Insert the method's description here. Creation date: (9/8/2003 9:10:37 - * AM) - * - * @return javax.swing.JMenuItem - */ - private JMenuItem getmenuRun_Scenario() - { - return null; - } - - /** - * Return the menuOutputManager property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - public javax.swing.JMenuItem getmenuRun_SMPDBK() - { - if (ivjmenuRun_SMPDBK == null) - { - try - { - ivjmenuRun_SMPDBK = new javax.swing.JMenuItem(); - ivjmenuRun_SMPDBK.setName("menuRun_SMPDBK"); - ivjmenuRun_SMPDBK.setMnemonic('R'); - ivjmenuRun_SMPDBK.setText("Run SMPDBK"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuRun_SMPDBK; - } - - /** - * Return the menuSave property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuSave() - { - if (ivjmenuSave == null) - { - try - { - ivjmenuSave = new javax.swing.JMenuItem(); - ivjmenuSave.setName("menuSave"); - ivjmenuSave.setMnemonic('s'); - ivjmenuSave.setText("Save"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuSave; - } - - /** - * Return the menuSaveAs property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuSaveAs() - { - if (ivjmenuSaveAs == null) - { - try - { - ivjmenuSaveAs = new javax.swing.JMenuItem(); - ivjmenuSaveAs.setName("menuSaveAs"); - ivjmenuSaveAs.setMnemonic('a'); - ivjmenuSaveAs.setText("Save As..."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuSaveAs; - } - - /** - * Return the menuSMPDBK property value. - * - * @return javax.swing.JMenu - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenu getmenuSMPDBK() - { - if (ivjmenuSMPDBK == null) - { - try - { - ivjmenuSMPDBK = new javax.swing.JMenu(); - ivjmenuSMPDBK.setName("menuSMPDBK"); - ivjmenuSMPDBK.setMnemonic('m'); - ivjmenuSMPDBK.setText("Model"); - ivjmenuSMPDBK.add(getmenuRun_SMPDBK()); - ivjmenuSMPDBK.add(getmenuDisplayOutput()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuSMPDBK; - } - - /** - * Return the menuUpdateDatabase property value. - * - * @return javax.swing.JMenuItem - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuItem getmenuUpdateDatabase() - { - if (ivjmenuUpdateDatabase == null) - { - try - { - ivjmenuUpdateDatabase = new javax.swing.JMenuItem(); - ivjmenuUpdateDatabase.setName("menuUpdateDatabase"); - ivjmenuUpdateDatabase.setMnemonic('u'); - ivjmenuUpdateDatabase.setText("Update Database"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuUpdateDatabase; - } - - /** - * Return the ModelGUIJMenuBar property value. - * - * @return javax.swing.JMenuBar - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JMenuBar getModelGUIJMenuBar() - { - if (ivjModelGUIJMenuBar == null) - { - try - { - ivjModelGUIJMenuBar = new javax.swing.JMenuBar(); - ivjModelGUIJMenuBar.setName("ModelGUIJMenuBar"); - ivjModelGUIJMenuBar.add(getmenuFile()); - ivjModelGUIJMenuBar.add(getmenuDatabase()); - ivjModelGUIJMenuBar.add(getmenuSMPDBK()); - ivjModelGUIJMenuBar.add(getmenuEdit()); - ivjModelGUIJMenuBar.add(getmenuHelp()); - // user code begin {1} - if (bHasDatabase) - ivjModelGUIJMenuBar.remove(getmenuFile()); - else - ivjModelGUIJMenuBar.remove(getmenuDatabase()); - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjModelGUIJMenuBar; - } - - /** - * Return the panelDamInfo property value. - * - * @return javax.swing.JPanel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JPanel getpanelDamInfo() - { - if (ivjpanelDamInfo == null) - { - try - { - ivjpanelDamInfo = new javax.swing.JPanel(); - ivjpanelDamInfo.setName("panelDamInfo"); - ivjpanelDamInfo.setBorder(new EtchedBorder()); - ivjpanelDamInfo.setLayout(null); - ivjpanelDamInfo.setBackground(new java.awt.Color(234, 223, 246)); - ivjpanelDamInfo.setBounds(1, 103, 420, 488); - getpanelDamInfo().add(getlabelScenarioList(), - getlabelScenarioList().getName()); - getpanelDamInfo().add(getscrollScenarioList(), - getscrollScenarioList().getName()); - getpanelDamInfo().add(getlabelSource(), - getlabelSource().getName()); - getpanelDamInfo().add(getlabelScenario(), - getlabelScenario().getName()); - getpanelDamInfo().add(getlabelTypeOfDam(), - getlabelTypeOfDam().getName()); - getpanelDamInfo().add(getlabelHDE(), getlabelHDE().getName()); - getpanelDamInfo().add(getlabelBME(), getlabelBME().getName()); - getpanelDamInfo().add(getlabelVolume(), - getlabelVolume().getName()); - getpanelDamInfo().add(getlabelSA(), getlabelSA().getName()); - getpanelDamInfo().add(getlabelBW(), getlabelBW().getName()); - getpanelDamInfo().add(getlabelTFM(), getlabelTFM().getName()); - getpanelDamInfo().add(getlabelQO(), getlabelQO().getName()); - getpanelDamInfo().add(getlabelDISTTN(), - getlabelDISTTN().getName()); - getpanelDamInfo().add(getlabelCMS(), getlabelCMS().getName()); - getpanelDamInfo().add(getlabelRequiredFieldsNotice(), - getlabelRequiredFieldsNotice().getName()); - getpanelDamInfo().add(gettextSource(), - gettextSource().getName()); - getpanelDamInfo().add(getcomboScenario(), - getcomboScenario().getName()); - getpanelDamInfo().add(getcomboTypeOfDam(), - getcomboTypeOfDam().getName()); - getpanelDamInfo().add(gettextHDE(), gettextHDE().getName()); - getpanelDamInfo().add(gettextBME(), gettextBME().getName()); - getpanelDamInfo().add(gettextVOL(), gettextVOL().getName()); - getpanelDamInfo().add(gettextSA(), gettextSA().getName()); - getpanelDamInfo().add(gettextBW(), gettextBW().getName()); - getpanelDamInfo().add(gettextTFM(), gettextTFM().getName()); - getpanelDamInfo().add(gettextQO(), gettextQO().getName()); - getpanelDamInfo().add(gettextDISTTN(), - gettextDISTTN().getName()); - getpanelDamInfo().add(gettextCMS(), gettextCMS().getName()); - getpanelDamInfo().add(getlabelDBUG(), getlabelDBUG().getName()); - getpanelDamInfo().add(getcomboDBUG(), getcomboDBUG().getName()); - // user code begin {1} - // user code end - } - catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelDamInfo; - } - - /** - * Return the panelXSInfo property value. - * - * @return javax.swing.JPanel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JPanel getpanelDownstreamInfo() - { - if (ivjpanelDownstreamInfo == null) - { - try - { - ivjpanelDownstreamInfo = new javax.swing.JPanel(); - ivjpanelDownstreamInfo.setName("panelDownstreamInfo"); - ivjpanelDownstreamInfo - .setBorder(new EtchedBorder()); - ivjpanelDownstreamInfo.setLayout(null); - ivjpanelDownstreamInfo.setBackground(new java.awt.Color(236, - 243, 255)); - ivjpanelDownstreamInfo.setBounds(422, 4, 395, 590); - getpanelDownstreamInfo().add(getlabelXSList(), - getlabelXSList().getName()); - getpanelDownstreamInfo().add(getscrollXSList(), - getscrollXSList().getName()); - getpanelDownstreamInfo().add(getlabelXSName(), - getlabelXSName().getName()); - getpanelDownstreamInfo().add(getlabelXSDistance(), - getlabelXSDistance().getName()); - getpanelDownstreamInfo().add(getlabelXSFloodDepth(), - getlabelXSFloodDepth().getName()); - getpanelDownstreamInfo().add(getlabelXSFloodFlow(), - getlabelXSFloodFlow().getName()); - getpanelDownstreamInfo().add(getlabelXSLatitutde(), - getlabelXSLatitutde().getName()); - getpanelDownstreamInfo().add(getlabelXSLongitude(), - getlabelXSLongitude().getName()); - getpanelDownstreamInfo().add(gettextName(), - gettextName().getName()); - getpanelDownstreamInfo().add(gettextDistance(), - gettextDistance().getName()); - getpanelDownstreamInfo().add(gettextFloodDepth(), - gettextFloodDepth().getName()); - getpanelDownstreamInfo().add(gettextFloodFlow(), - gettextFloodFlow().getName()); - getpanelDownstreamInfo().add(gettextLatitude(), - gettextLatitude().getName()); - getpanelDownstreamInfo().add(gettextLongitude(), - gettextLongitude().getName()); - getpanelDownstreamInfo().add(getpanelXS(), - getpanelXS().getName()); - getpanelDownstreamInfo().add(getlabelXSList11(), - getlabelXSList11().getName()); - getpanelDownstreamInfo().add(getcomboBestXS(), - getcomboBestXS().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelDownstreamInfo; - } - - /** - * Return the panelDamInfo1 property value. - * - * @return javax.swing.JPanel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JPanel getpanelNameInfo() - { - if (ivjpanelNameInfo == null) - { - try - { - ivjpanelNameInfo = new javax.swing.JPanel(); - ivjpanelNameInfo.setName("panelNameInfo"); - ivjpanelNameInfo - .setBorder(new EtchedBorder()); - ivjpanelNameInfo.setLayout(null); - ivjpanelNameInfo - .setBackground(new java.awt.Color(227, 228, 235)); - ivjpanelNameInfo.setBounds(1, 5, 419, 97); - getpanelNameInfo().add(getlabelDamName(), - getlabelDamName().getName()); - getpanelNameInfo().add(getlabelRiverName(), - getlabelRiverName().getName()); - getpanelNameInfo() - .add(getlabelPPOI(), getlabelPPOI().getName()); - getpanelNameInfo().add(gettextDamName(), - gettextDamName().getName()); - getpanelNameInfo().add(gettextRiverName(), - gettextRiverName().getName()); - getpanelNameInfo().add(gettextPPOI(), gettextPPOI().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelNameInfo; - } - - /** - * Return the JPanel1 property value. - * - * @return javax.swing.JPanel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JPanel getpanelXS() - { - if (ivjpanelXS == null) - { - try - { - ivjpanelXS = new javax.swing.JPanel(); - ivjpanelXS.setName("panelXS"); - ivjpanelXS.setBorder(new EtchedBorder()); - ivjpanelXS.setLayout(null); - ivjpanelXS.setBackground(new java.awt.Color(164, 218, 204)); - ivjpanelXS.setBounds(18, 329, 359, 257); - getpanelXS() - .add(getlabelXSList1(), getlabelXSList1().getName()); - getpanelXS().add(getscrollXSList1(), - getscrollXSList1().getName()); - getpanelXS().add(getlabelSectionType(), - getlabelSectionType().getName()); - getpanelXS().add(getcomboXSType(), getcomboXSType().getName()); - getpanelXS() - .add(getscrollXSData(), getscrollXSData().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelXS; - } - - /** - * Return the scrollScenarioList property value. - * - * @return javax.swing.JScrollPane - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JScrollPane getscrollScenarioList() - { - if (ivjscrollScenarioList == null) - { - try - { - ivjscrollScenarioList = new javax.swing.JScrollPane(); - ivjscrollScenarioList.setName("scrollScenarioList"); - ivjscrollScenarioList.setBounds(16, 34, 377, 77); - getscrollScenarioList().setViewportView(getListScenario()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollScenarioList; - } - - /** - * Return the scrollXSData property value. - * - * @return javax.swing.JScrollPane - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JScrollPane getscrollXSData() - { - if (ivjscrollXSData == null) - { - try - { - ivjscrollXSData = new javax.swing.JScrollPane(); - ivjscrollXSData.setName("scrollXSData"); - ivjscrollXSData.setBounds(7, 124, 342, 130); - ivjscrollXSData.setEnabled(false); - getscrollXSData().setViewportView(gettableXSData()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollXSData; - } - - /** - * Return the scrollXSList property value. - * - * @return javax.swing.JScrollPane - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JScrollPane getscrollXSList() - { - if (ivjscrollXSList == null) - { - try - { - ivjscrollXSList = new javax.swing.JScrollPane(); - ivjscrollXSList.setName("scrollXSList"); - ivjscrollXSList.setBounds(15, 32, 364, 74); - getscrollXSList().setViewportView(getListDown()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollXSList; - } - - /** - * Return the scrollXSList1 property value. - * - * @return javax.swing.JScrollPane - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JScrollPane getscrollXSList1() - { - if (ivjscrollXSList1 == null) - { - try - { - ivjscrollXSList1 = new javax.swing.JScrollPane(); - ivjscrollXSList1.setName("scrollXSList1"); - ivjscrollXSList1.setBounds(10, 28, 337, 57); - getscrollXSList1().setViewportView(getListXS()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollXSList1; - } - - /** - * Return the tableModelXSGeom property value. - * - * @return javax.swing.table.DefaultTableModel - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.table.DefaultTableModel gettableModelXSGeom() - { - if (ivjtableModelXSGeom == null) - { - try - { - ivjtableModelXSGeom = new javax.swing.table.DefaultTableModel(); - // user code begin {1} - ivjtableModelXSGeom = new javax.swing.table.DefaultTableModel( - 8, 4); - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtableModelXSGeom; - } - - /** - * Return the tableXSData property value. - * - * @return javax.swing.JTable - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTable gettableXSData() - { - if (ivjtableXSData == null) - { - try - { - ivjtableXSData = new javax.swing.JTable(); - ivjtableXSData.setName("tableXSData"); - getscrollXSData().setColumnHeaderView( - ivjtableXSData.getTableHeader()); - getscrollXSData().getViewport().setBackingStoreEnabled(true); - ivjtableXSData.setBounds(0, 0, 332, 136); - ivjtableXSData.setEnabled(false); - ivjtableXSData.setAutoCreateColumnsFromModel(false); - ivjtableXSData.addColumn(getcolumnElevation()); - ivjtableXSData.addColumn(getcolumnBS()); - ivjtableXSData.addColumn(getcolumnBSS()); - ivjtableXSData.addColumn(getcolumnMannN()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtableXSData; - } - - /** - * Return the textBME property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextBME() - { - if (ivjtextBME == null) - { - try - { - ivjtextBME = new javax.swing.JTextField(); - ivjtextBME.setName("textBME"); - ivjtextBME.setBounds(269, 222, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextBME; - } - - /** - * Return the textBW property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextBW() - { - if (ivjtextBW == null) - { - try - { - ivjtextBW = new javax.swing.JTextField(); - ivjtextBW.setName("textBW"); - ivjtextBW.setBounds(269, 303, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextBW; - } - - /** - * Return the textCMS property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextCMS() - { - if (ivjtextCMS == null) - { - try - { - ivjtextCMS = new javax.swing.JTextField(); - ivjtextCMS.setName("textCMS"); - ivjtextCMS.setBounds(269, 411, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextCMS; - } - - /** - * Return the textDamName property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextDamName() - { - if (ivjtextDamName == null) - { - try - { - ivjtextDamName = new javax.swing.JTextField(); - ivjtextDamName.setName("textDamName"); - ivjtextDamName.setDocument(new MaxLengthDocument(40)); - ivjtextDamName.setBounds(164, 12, 229, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextDamName; - } - - /** - * Return the textXSDistance property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextDistance() - { - if (ivjtextDistance == null) - { - try - { - ivjtextDistance = new javax.swing.JTextField(); - ivjtextDistance.setName("textDistance"); - ivjtextDistance.setBounds(234, 152, 143, 20); - ivjtextDistance.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextDistance; - } - - /** - * Return the textDISTTN property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextDISTTN() - { - if (ivjtextDISTTN == null) - { - try - { - ivjtextDISTTN = new javax.swing.JTextField(); - ivjtextDISTTN.setName("textDISTTN"); - ivjtextDISTTN.setBounds(269, 384, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextDISTTN; - } - - /** - * Return the textXSFloodDepth property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextFloodDepth() - { - if (ivjtextFloodDepth == null) - { - try - { - ivjtextFloodDepth = new javax.swing.JTextField(); - ivjtextFloodDepth.setName("textFloodDepth"); - ivjtextFloodDepth.setBounds(234, 180, 143, 20); - ivjtextFloodDepth.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextFloodDepth; - } - - /** - * Return the textFloodFlow property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextFloodFlow() - { - if (ivjtextFloodFlow == null) - { - try - { - ivjtextFloodFlow = new javax.swing.JTextField(); - ivjtextFloodFlow.setName("textFloodFlow"); - ivjtextFloodFlow.setBounds(234, 210, 143, 20); - ivjtextFloodFlow.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextFloodFlow; - } - - /** - * Return the textHDE property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextHDE() - { - if (ivjtextHDE == null) - { - try - { - ivjtextHDE = new javax.swing.JTextField(); - ivjtextHDE.setName("textHDE"); - ivjtextHDE.setBounds(269, 195, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextHDE; - } - - /** - * Return the textXSLatitude property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextLatitude() - { - if (ivjtextLatitude == null) - { - try - { - ivjtextLatitude = new javax.swing.JTextField(); - ivjtextLatitude.setName("textLatitude"); - ivjtextLatitude.setBounds(234, 241, 143, 20); - ivjtextLatitude.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextLatitude; - } - - /** - * Return the textXSLongitude property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextLongitude() - { - if (ivjtextLongitude == null) - { - try - { - ivjtextLongitude = new javax.swing.JTextField(); - ivjtextLongitude.setName("textLongitude"); - ivjtextLongitude.setBounds(234, 270, 143, 20); - ivjtextLongitude.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextLongitude; - } - - /** - * Return the textXSName property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextName() - { - if (ivjtextName == null) - { - try - { - ivjtextName = new javax.swing.JTextField(); - ivjtextName.setName("textName"); - ivjtextName.setBounds(234, 122, 143, 20); - ivjtextName.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextName; - } - - /** - * Return the textPPOI property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextPPOI() - { - if (ivjtextPPOI == null) - { - try - { - ivjtextPPOI = new javax.swing.JTextField(); - ivjtextPPOI.setName("textPPOI"); - ivjtextPPOI.setDocument(new MaxLengthDocument(25)); - ivjtextPPOI.setBounds(164, 68, 229, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextPPOI; - } - - /** - * Return the textQO property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextQO() - { - if (ivjtextQO == null) - { - try - { - ivjtextQO = new javax.swing.JTextField(); - ivjtextQO.setName("textQO"); - ivjtextQO.setBounds(269, 357, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextQO; - } - - /** - * Return the textRiverName property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextRiverName() - { - if (ivjtextRiverName == null) - { - try - { - ivjtextRiverName = new javax.swing.JTextField(); - ivjtextRiverName.setName("textRiverName"); - ivjtextRiverName.setDocument(new MaxLengthDocument(40)); - ivjtextRiverName.setBounds(164, 39, 229, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextRiverName; - } - - /** - * Return the textSA property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextSA() - { - if (ivjtextSA == null) - { - try - { - ivjtextSA = new javax.swing.JTextField(); - ivjtextSA.setName("textSA"); - ivjtextSA.setBounds(269, 276, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextSA; - } - - /** - * Return the textSource property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextSource() - { - if (ivjtextSource == null) - { - try - { - ivjtextSource = new javax.swing.JTextField(); - ivjtextSource.setName("textSource"); - ivjtextSource.setDocument(new MaxLengthDocument(40)); - ivjtextSource.setBounds(269, 120, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextSource; - } - - /** - * Return the textTFM property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextTFM() - { - if (ivjtextTFM == null) - { - try - { - ivjtextTFM = new javax.swing.JTextField(); - ivjtextTFM.setName("textTFM"); - ivjtextTFM.setBounds(269, 330, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextTFM; - } - - /** - * Return the textVOL property value. - * - * @return javax.swing.JTextField - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private javax.swing.JTextField gettextVOL() - { - if (ivjtextVOL == null) - { - try - { - ivjtextVOL = new javax.swing.JTextField(); - ivjtextVOL.setName("textVOL"); - ivjtextVOL.setBounds(269, 249, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) - { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextVOL; - } - - /** - * For DownstreamPoints: - * - * Handle INSERT Key - * - * Handle DELETE or <- (backspace) - */ - private void handleDownListKey(java.awt.event.KeyEvent keyEvent) - { - - if (getListDown().getSelectedIndex() == -1 || bHandlingEvent) - { - return; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE - || keyEvent.getKeyCode() == KeyEvent.VK_DELETE) - { - bHandlingEvent = true; - - int oldSelection = getListDown().getSelectedIndex(); - - getListDown().clearSelection(); - - // *** move selected DownstreamPoint to deleted ArrayList - DownstreamPoint delDP = (DownstreamPoint) currentData.downstream - .get(oldSelection); - currentData.deletedDownstream.add(delDP); - - // *** now remove from primary ArrayList - currentData.downstream.remove(oldSelection); - - updateDownstreamList(); - - clearDownstreamFields(); - enableDownstreamEditors(false); - - bHandlingEvent = false; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_INSERT) - { - bHandlingEvent = true; - - int oldSelection = getListDown().getSelectedIndex() + 1; - - getListDown().clearSelection(); - - createNewDownstreamPoint(oldSelection); - - clearDownstreamFields(); - - enableDownstreamEditors(false); - - bHandlingEvent = false; - } - - return; - } - - /** - * invoke updateDownstreamFields if focus lost on key fields - */ - private void handleDownstreamKeyLostFocus() - { - - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - if (nDownstreamEditing != -1) - { - updateDownstreamFields(true); - } - - bHandlingEvent = false; - return; - } - - /** - * This method is similar to handleScenarioListSelection and - * handleXSListSelection - */ - private void handleDownstreamListSelection( ListSelectionEvent listSelectionEvent) - { - - // only process event if the selection is final and no other event is - // being handled - if (listSelectionEvent.getValueIsAdjusting() || bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - int selectedIndex = getListDown().getSelectedIndex(); - _selectedDownstreamPoint = selectedIndex; - - // save downstream data if data is currently being edited - - // if the data is invalid, stop handling event - if (!updateDownstreamFields(true)) - { - JOptionPane - .showMessageDialog( - this, - "The downstream point name and distance pair must be unique.", - "Error", JOptionPane.ERROR_MESSAGE); - bHandlingEvent = false; - getListDown().setSelectedIndex(nDownstreamEditing); - _selectedDownstreamPoint = nDownstreamEditing; - return; - } - - // if the selection is being cleared, clear the downstream editors - if (selectedIndex == -1) - { - clearDownstreamFields(); - enableDownstreamEditors(false); - bHandlingEvent = false; - return; - } - - // if "Create a new downstream point..." was clicked, create a new - // downstream point and select it for editing - // if (_DEBUG) System.out.println("Selected D/S Station/point Index: " + - // getListDown().getSelectedIndex()); - if (selectedIndex == getlistModelDown().getSize() - 1) - { - - // the SMPDBK model allows a maximum of 50 downstream locations - if (currentData.downstream.size() >= 50) - { - Toolkit.getDefaultToolkit().beep(); - bHandlingEvent = false; - getListDown().setSelectedIndex(nDownstreamEditing); - _selectedDownstreamPoint = nDownstreamEditing; - return; - } - - createNewDownstreamPoint(selectedIndex); - } - - // load data for selected downstream point into GUI - updateDownstreamFields(false); - enableDownstreamEditors(true); - - bHandlingEvent = false; // *** selecting XSList will fire new event ! - // *** so turn off bHandlingEvent first ! - - // if there is an XS chosen, select it ! - if (_selectedXSType != -1) - { - getListXS().clearSelection(); - getListXS().setSelectedIndex(_selectedXSType); - } - - } - - /** - * Called whenever the part throws an exception. - * - * @param exception - * java.lang.Throwable - */ - private void handleException(java.lang.Throwable exception) - { - - /* Uncomment the following lines to print uncaught exceptions to stdout */ - System.out - .println("--------- UNCAUGHT EXCEPTION in ModelGUI ---------"); - exception.printStackTrace(System.out); - } - - /** - * Comment - */ - private void handleMenuAbout() - { - // JOptionPane.showMessageDialog(this,"Dambreak Analysis v1.0 (build - // 2)\nCraig Austin","About Dambreak - // Analysis",JOptionPane.INFORMATION_MESSAGE); - JOptionPane - .showMessageDialog( - this, - "Dambreak Analysis v1.0 (Build 5.3 - 06/01/2004)\nby National Weather Service, \n - Office of Hydrologic Development", - "About Dambreak Analysis", - JOptionPane.INFORMATION_MESSAGE); - return; - } - - /** - * Comment - */ - private void handleMenuClose() - { - handleWindowClosing(); - return; - } - - /** - * Insert the method's description here. Creation date: (10/3/2003 3:40:14 - * PM) - */ - public void handleMenuDisplayOutput() - { - - JFileChooser fileChooser2 = new JFileChooser(strLastOpenPath); - fileChooser2.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser2.setFileFilter(new DamInputFileFilter( - DamInputFileFilter.OUTPUT)); - fileChooser2.setDialogTitle("Select Dambreak Analysis Output File"); - int result = fileChooser2.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return; - - File fileName = fileChooser2.getSelectedFile(); - - if (fileName == null || fileName.getName().equals("")) - JOptionPane.showMessageDialog(this, "Invalid File Name", - "Invalid File Name", JOptionPane.ERROR_MESSAGE); - else - { - // set our last opened path - strLastOpenPath = fileName.getPath(); - - if (_DEBUG) - System.out.print("in handleMenuDisplayOutput Opening " - + fileName.getAbsolutePath() + "...\n"); - - strOpenedFilename = fileName.getAbsolutePath(); - - if (strOpenedFilename == null) - JOptionPane.showMessageDialog(this, - "Error opening dambreak output file.\n" - + fileName.getAbsolutePath(), "Error", - JOptionPane.ERROR_MESSAGE); - else - { - ModelOutput outFile = ModelOutput.readOUT(fileName - .getAbsolutePath()); - if (outFile == null) - JOptionPane.showMessageDialog(this, - "Attempt to open not SMPDBK formatted file.\n" - + fileName.getAbsolutePath(), "Error", - JOptionPane.ERROR_MESSAGE); - else - { - // instantiate Analysis Data and copy data from ModelOutput - // change currentData to outputOnlyData - - outputOnlyData = new AnalysisData(); - currentData.importModelOutput(outFile); - - // generateOutput(); // not needed ! - - OutputManager outMan = new OutputManager(this, currentData); - outMan.setTitle("Output Manager - " - + fileName.getAbsolutePath()); - - System.out.println("Finished displaying out file."); - - return; - } - } - } - return; - } - - /** - * This method needed for editing file via GUI. Creation date: (9/26/2003 - * 1:53:13 PM) - */ - private void handleMenuEditText() throws Exception - { - String osName = System.getProperty("os.name"); - String lowerCaseName = osName.toLowerCase(); - Runtime rt = Runtime.getRuntime(); - String dbaEditor = ""; - String runThis = ""; - - JFileChooser fileChooser1 = new JFileChooser(strLastOpenPath); - fileChooser1.setDialogTitle("Select the File to edit"); - int result1 = fileChooser1.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result1 != JFileChooser.APPROVE_OPTION) - return; - - File fileName1 = fileChooser1.getSelectedFile(); - - if (fileName1 == null || fileName1.getName().equals("")) - { - JOptionPane.showMessageDialog(this, "Invalid File Name", - "Invalid File Name", JOptionPane.ERROR_MESSAGE); - } else - { - runThis = fileName1.getAbsolutePath(); - } - - try - { - dbaEditor = PropertyReader.getProperty("damcrest.editor"); - if (lowerCaseName.indexOf("windows") > -1) - { - // System.out.println("Editing a file with " + dbaEditor + " \"" - // + runThis + "\""); - rt.exec(dbaEditor + " \"" + runThis + "\""); - } else if (lowerCaseName.indexOf("linux") > -1) - { - // System.out.println("Editing a file with " + dbaEditor + " " + - // runThis); - rt.exec(dbaEditor + " " + runThis); - } - } catch (IOException e) - { - // Problem editing the file - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "Cannot edit the file", - "Cannot edit the file", JOptionPane.ERROR_MESSAGE); - - } - - return; - } - - /** - * This method reads information from a *.DAT file. assumed to be in SMPDBK - * format - */ - private void handleMenuImportFromDAT() - { - - handleMenuNew(); - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setFileFilter(new DamInputFileFilter( - DamInputFileFilter.DAT_INPUT)); - fileChooser.setDialogTitle("Select SMPDBK Input File"); - int result = fileChooser.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return; - - File fileName = fileChooser.getSelectedFile(); - - if (fileName == null || fileName.getName().equals("")) - JOptionPane.showMessageDialog(this, "Invalid File Name", - "Invalid File Name", JOptionPane.ERROR_MESSAGE); - else - { - // set our last opened path - strLastOpenPath = fileName.getPath(); - - try - { - if (_DEBUG) - System.out.print("in handleMenuImportFromDAT opening " - + fileName.getAbsolutePath() + "...\n"); - if (!currentData.importDAT(fileName.getAbsolutePath())) - { - JOptionPane.showMessageDialog(this, - "Error importing -- wrong data or file type used for DAT file!\n" - + fileName.getAbsolutePath(), "Error", - JOptionPane.ERROR_MESSAGE); - return; - } - if (_DEBUG) - System.out.println("Finished import .DAT"); - - // update GUI to show newly imported data - updateNameFields(false); - updateScenarioList(); - updateDownstreamList(); - updateXSList(); - bHasDataToSave = true; - } catch (Exception e) - { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, - "Error importing -- bad DAT file!", "Error", - JOptionPane.ERROR_MESSAGE); - return; - } - } - } - - /** - * Read Data from .xs file format (created by FLDXS) - */ - private boolean handleMenuImportFromFLDXS() - { - - handleMenuNew(); - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setDialogTitle("Select FldXS Output File"); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setFileFilter(new DamInputFileFilter( - DamInputFileFilter.TXT_INPUT)); - fileChooser.setDialogTitle("Select FLDXS cross section to import"); - int result = fileChooser.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return false; - - // user sets path - File fileName = fileChooser.getSelectedFile(); - strLastOpenPath = fileName.getPath(); - - try - { - if (_DEBUG) - System.out.print("in handleMenuImportFromFLDXS opening " - + fileName.getAbsolutePath() + "...\n"); - - if (!currentData.importFLDXS(fileName.getAbsolutePath())) - JOptionPane.showMessageDialog(this, - "Error importing -- wrong data or file type used for FLDXS file!\n" - + fileName.getAbsolutePath(), "Error", - JOptionPane.ERROR_MESSAGE); - - if (_DEBUG) - System.out.println("Finished import FLDXS."); - - // update GUI to show newly imported data - updateDownstreamList(); - updateXSList(); - - bHasDataToSave = true; - bChangedData = false; - - } catch (Exception e) - { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, - "Error importing -- bad FLDXS file!", "Error", - JOptionPane.ERROR_MESSAGE); - return false; - } - return true; - } - - /** - * User has hit "New" menu option on "File" or "Database" menu - */ - private void handleMenuNew() - { - - // Ask the user if they want to save before clearing the GUI. - // If the save fails, don't clear. - - if (bHasDataToSave && bChangedData) - { - saveGUI(); - if (!checkForSaveChanges()) - return; - } - - bHandlingEvent = false; - currentData = new AnalysisData(); - strOpenedFilename = null; - updateGUI(); - bHasDataToSave = false; - return; - - } - - /** - * opens .DAM file format - */ - private boolean handleMenuOpen() - { - - handleMenuNew(); // *** clear GUI - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setFileFilter(new DamInputFileFilter( - DamInputFileFilter.DAM_INPUT)); - fileChooser.setDialogTitle("Select Dambreak Analysis Input File"); - int result = fileChooser.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return false; - - File fileName = fileChooser.getSelectedFile(); - - if (fileName == null || fileName.getName().equals("")) - JOptionPane.showMessageDialog(this, "Invalid File Name", - "Invalid File Name", JOptionPane.ERROR_MESSAGE); - else - { - // set our last opened path - strLastOpenPath = fileName.getPath(); - - if (_DEBUG) - System.out.print("In handleMenuOpen Opening " - + fileName.getAbsolutePath() + "...\n"); - - AnalysisData newData; - if ((newData = AnalysisData.readDAM(fileName.getAbsolutePath())) == null) - JOptionPane.showMessageDialog(this, - "Error opening dambreak input DAM file.\n" - + fileName.getAbsolutePath(), "Error", - JOptionPane.ERROR_MESSAGE); - else - currentData = newData; - - strOpenedFilename = fileName.getAbsolutePath(); - - if (_DEBUG) - System.out.println("Finished opening dam file."); - - // update GUI to show newly imported data - updateNameFields(false); - updateScenarioList(); - updateDownstreamList(); - updateXSList(); - bHasDataToSave = true; - bChangedData = false; - } - return true; - } - - /** - * Comment - */ - private void handleMenuQuit() - { - handleWindowClosing(); - return; - } - - /** - * Handle when "Run SMPDBK" menu item chosen - */ - public void handleMenuRun_SMPDBK() - { - - // save any data currently being edited in the GUI back to the - // AnalysisData structure - saveGUI(); - - // update all input data in case any input data was changed to their - // default values - updateNameFields(false); - if (nScenarioEditing != -1) - updateScenarioFields(false); - - // verify that the model can be run on this input - String error = currentData.verifyInput(); - - if (error != null) - { - JOptionPane.showMessageDialog(this, error, - "Errors in Data - Can Not Run SMPDBK Model", - JOptionPane.ERROR_MESSAGE); - return; - } - - // update all the output structures - if (generateOutput() == true) - { - // to get the prerun result from the database - String oError = currentData.verifyOutput(); // what's done with this - // string ? - - OutputManager outMan = new OutputManager(this, currentData); - outMan.setTitle("Output Manager - " + "(most recent model run)"); - //outMan.show() - } else - { - JOptionPane.showMessageDialog(this, "Output Generation Failed", - "SMPDBK Model Run Was Unsuccessful", - JOptionPane.ERROR_MESSAGE); - } - return; - } - - /** - * If a file is open already, this replaces it with updated data. If there - * is no open file, "Save As..." is automatically called. - */ - private boolean handleMenuSave() - { - // save any data currently being edited in the GUI back to the - // AnalysisData structure - saveGUI(); - - if (strOpenedFilename == null) - return handleMenuSaveAs(); - else - return AnalysisData.writeDAM(currentData, strOpenedFilename); - } - - /** - * NOTE: - */ - private boolean handleMenuSaveAs() - { - File fileName; - - // save any data currently being edited in the GUI back to the - // AnalysisData structure - saveGUI(); - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setDialogTitle("Select File Name To Save To"); - fileChooser.setFileFilter(new DamInputFileFilter( - DamInputFileFilter.DAM_INPUT)); - int result = fileChooser.showSaveDialog(this); - FileWriter output; - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return false; - - fileName = fileChooser.getSelectedFile(); - if (fileName == null || fileName.getName().equals("")) - { - JOptionPane.showMessageDialog(this, "Invalid File Name", - "Invalid File Name", JOptionPane.ERROR_MESSAGE); - return false; - } - - // set the 'last file opened' path - strLastOpenPath = fileName.getPath(); - - String strFileName = fileName.getAbsolutePath(); - if (!strFileName.toLowerCase().endsWith(".dam")) - strFileName = strFileName.concat(".DAM"); - - if (!AnalysisData.writeDAM(currentData, strFileName)) - { - JOptionPane.showMessageDialog(this, "Error writing file.", "Error", - JOptionPane.ERROR_MESSAGE); - return false; - } - - strOpenedFilename = fileName.getAbsolutePath(); - bChangedData = false; - - return true; - } - - /** - * This writes all the data in the ModelGUI AnalysisData structure back to - * the tables of the DAMCAT database. - */ - private boolean handleMenuUpdateDatabase(boolean bConfirmMessage) - { - - String methodName = "*** handleMenuUpdateDatabase"; - // if (_DEBUG) System.out.println(methodName); - - int selectedIndex = getListScenario().getSelectedIndex(); - - // save any data currently being edited in the GUI back into the - // AnalysisData structure - - saveGUI(); - - int confirmOption; - - if (bConfirmMessage) - confirmOption = JOptionPane.showConfirmDialog(this, - "All data in the DAMCAT database entry for dam \"" - + strWorkingDamNIDID - + "\" will be replaced.\nContinue?", "Confirm", - JOptionPane.YES_NO_OPTION); - else - { - confirmOption = JOptionPane.YES_OPTION; - } - - if (confirmOption == JOptionPane.NO_OPTION) - // return false; // *** perhaps this should be true ! - return true; - - // First, verify that the model can be run on this input - String error = currentData.verifyInput(); - - // update all input data in case any input data was changed to their - // default values - updateNameFields(false); - - if (nScenarioEditing != -1) - updateScenarioFields(false); - - if (error != null) - { - JOptionPane.showMessageDialog(this, error, - "Could Not Run SMPDBK Model", JOptionPane.ERROR_MESSAGE); - return false; - } - - // update all the output structures - if (generateOutput() == true) - { - try - { - dbAccess.updateModelData(strWorkingDamNIDID, currentData); - JOptionPane.showMessageDialog(this, - "Successfully updated database entry \"" - + strWorkingDamNIDID.trim() + "\".", "Success", - JOptionPane.INFORMATION_MESSAGE); - - } catch (Exception e) - { - - JOptionPane.showMessageDialog(this, - "Could not update DAMCAT entry!", "Error", - JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - return false; - } - } else - { - JOptionPane.showMessageDialog(this, - "The Database was not updated!", - "SMPDBK Model Run Was Unsuccessful", - JOptionPane.ERROR_MESSAGE); - return false; - } - - bChangedData = false; - - return true; - } - - /** - * Comment - */ - private void handleScenarioKeyFocusLost() - { - - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - if (nScenarioEditing != -1) - { - updateScenarioFields(true); - } - - bHandlingEvent = false; - return; - - } - - /** - * For Input Scenarios: - * - * Handle INSERT Key - * - * Handle DELETE or <- (backspace) - */ - private void handleScenarioListKey(java.awt.event.KeyEvent keyEvent) - { - - if (getListScenario().getSelectedIndex() == -1 || bHandlingEvent) - { - return; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE - || keyEvent.getKeyCode() == KeyEvent.VK_DELETE) - { - bHandlingEvent = true; - - int oldSelection = getListScenario().getSelectedIndex(); - - getListScenario().clearSelection(); - - // *** move selected ModelScenario to deleted ArrayList - ModelScenario delMS = (ModelScenario) currentData.scenarios - .get(oldSelection); - currentData.deletedScenarios.add(delMS); - - // *** now remove from primary ArrayList - currentData.scenarios.remove(oldSelection); - - updateScenarioList(); - - clearScenarioFields(); - - enableScenarioEditors(false); - - bHandlingEvent = false; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_INSERT) - { - bHandlingEvent = true; - - int newSelection = getListScenario().getSelectedIndex() + 1; - - getListScenario().clearSelection(); - - ModelScenario newScenario = new ModelScenario(); - - currentData.scenarios.add(newSelection, newScenario); - - updateScenarioList(); - - getListScenario().setSelectedIndex(newSelection); - _selectedScenario = newSelection; - - clearScenarioFields(); - - updateScenarioFields(false); - - enableScenarioEditors(true); - - bHandlingEvent = false; - - } - return; - } - - /** - * Handle Selection of New List - */ - private void handleScenarioListSelection(ListSelectionEvent listSelectionEvent) - { - - // only process event if the selection is final and no other event is being handled - if (listSelectionEvent.getValueIsAdjusting() || bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - int selectedIndex = getListScenario().getSelectedIndex(); - - // save scenario data if data is currently being edited - - // - // *** if the data is invalid, stop handling event ! - if (!updateScenarioFields(true)) - { - JOptionPane.showMessageDialog(this, - "The scenario name and source pair must be unique.", - "Error", JOptionPane.ERROR_MESSAGE); - bHandlingEvent = false; - getListScenario().setSelectedIndex(nScenarioEditing); - _selectedScenario = nScenarioEditing; - return; - } - - // if the selection is being cleared, clear the scenario editors - if (selectedIndex == -1) - { - clearScenarioFields(); - enableScenarioEditors(false); - bHandlingEvent = false; - return; - } - - // if "Highlight me to create a new scenario..." was clicked, create a new scenario and select it for editing - if (selectedIndex == getlistModelScenario().getSize() - 1) - { - - createNewScenario(); - int idx = currentData.scenarios.size() - 1; - getListScenario().setSelectedIndex(idx); - _selectedScenario = (idx); - - } - - // load data for selected scenario into GUI - - updateScenarioFields(false); - - enableScenarioEditors(true); - - bHandlingEvent = false; - } - - /** - * Close Window and Exit to Op Sys. - */ - private void handleWindowClosing() - { - - if (bHasDataToSave || bChangedData) // was && - { - saveGUI(); - if (!checkForSaveChanges()) - return; - } - - dispose(); - - if ((!bHasDatabase) || (Launcher.closeFlag)) - { - System.exit(0); - } - return; - - } - - /** - * Lost Focus Event fired for which fields ??? - */ - private void handleXSKeyLostFocus() - { - - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - if (nXSEditing != -1) - { - updateXSFields(true); - } - - bHandlingEvent = false; - return; - } - - /** - * Comment - */ - private void handleXSListClick(java.awt.event.MouseEvent mouseEvent) - { - - // only handle double clicks - if (mouseEvent.getClickCount() < 2 - || nDownstreamEditing == -1 - || getListXS().getSelectedIndex() == -1 - || getListXS().getSelectedIndex() == getlistModelXS().getSize() - 1) - { - return; - } - - bHandlingEvent = true; - - // *** should this be here ??? - // DownstreamPoint downEditing = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - // downEditing.bestXS = getListXS().getSelectedIndex(); - - updateXSList(); - - bHandlingEvent = false; - return; - } - - /** - * For XS Types - * - * Handle INSERT Key - * - * Handle DELETE or <- (backspace) - */ - private void handleXSListKey(java.awt.event.KeyEvent keyEvent) - { - - if (getListXS().getSelectedIndex() == -1 || bHandlingEvent) - { - return; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE - || keyEvent.getKeyCode() == KeyEvent.VK_DELETE) - { - bHandlingEvent = true; - - int oldSelection = getListXS().getSelectedIndex(); - - DownstreamPoint down = (DownstreamPoint) currentData.downstream - .get(nDownstreamEditing); - - // if this is the only XS, do not let the user remove it - // *** Why ???? - if (down.xsections.size() == 1) - { - Toolkit.getDefaultToolkit().beep(); - bHandlingEvent = false; - return; - } - - // *** move selected XS to deleted ArrayList - SectionGeometry delXS = (SectionGeometry) down.xsections - .get(oldSelection); - down.deletedXsections.add(delXS); - - // *** now remove from primary ArrayList - down.xsections.remove(oldSelection); - - if (down.bestXS == oldSelection && down.xsections.size() > 0) - down.bestXS = 0; - else if (down.bestXS == oldSelection) - down.bestXS = -1; - - getListXS().clearSelection(); - updateXSList(); - - clearXSFields(); - enableXSEditors(false); - - bHandlingEvent = false; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_INSERT) - { - if (_DEBUG) - System.out.println("Insert XS key pressed: " - + getListXS().getSelectedIndex()); - - bHandlingEvent = true; - - int oldSelection = getListXS().getSelectedIndex(); - - DownstreamPoint down = (DownstreamPoint) currentData.downstream - .get(nDownstreamEditing); - - getListXS().clearSelection(); - - SectionGeometry newSection = new SectionGeometry(); - - down.xsections.add(newSection); - - updateXSList(); - - clearXSFields(); - - enableXSEditors(false); - - bHandlingEvent = false; - - } - - return; - } - - /** - * Comment - */ - private void handleXSListSelection(ListSelectionEvent listSelectionEvent) - { - - // only process event if the selection is final - if (listSelectionEvent.getValueIsAdjusting()) - { - return; - } - // and no other event is being handled - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - int selectedIndex = getListXS().getSelectedIndex(); - - // save section data if data is currently being edited - if the data is invalid, stop handling event - if (!updateXSFields(true)) - { - JOptionPane.showMessageDialog(this, - "The cross section type must be unique.", "Error", - JOptionPane.ERROR_MESSAGE); - bHandlingEvent = false; - getListXS().setSelectedIndex(nXSEditing); - _selectedXSType = nXSEditing; - return; - } - - // updateXSFields(true); // *** this only needs done once ! - - // if the selection is being cleared, clear the section editors - if (selectedIndex == -1) - { - clearXSFields(); - enableXSEditors(false); - bHandlingEvent = false; - return; - } - - // if "Create a section..." was clicked, create a new section and select it for editing - // if (_DEBUG) System.out.println("Selected Cross Section Type Index: " + getListXS().getSelectedIndex()); - - if (selectedIndex == getlistModelXS().getSize() - 1) - { - createNewXS(nDownstreamEditing); - } - - // load data for selected section into GUI - updateXSFields(false); - - enableXSEditors(true); - - bHandlingEvent = false; - } - - /** - * Initializes the combo boxes for the restricted fields (enumerated types). - * Creation date: (7/29/2003 9:41:54 AM) - */ - private void initComboBoxes() - { - //DownstreamPoint selectedPoint = (DownstreamPoint)currentData.downstream.get(selectedIndex); - - int count = 0; //to count scenarios where source starts with '#' - - String[] damTypes = EnumeratedTypes - .getEnglishChoices(EnumeratedTypes.FIELD_DAMTYPE); - for (int i = 0; i < damTypes.length; i++) - getcomboTypeOfDam().addItem(damTypes[i]); - - String[] scenarios = EnumeratedTypes - .getEnglishChoices(EnumeratedTypes.FIELD_SCENARIO); - for (int i = 0; i < scenarios.length; i++) - getcomboScenario().addItem(scenarios[i]); - - String[] xsTypes = EnumeratedTypes - .getEnglishChoices(EnumeratedTypes.FIELD_XSTYPE); - for (int i = 0; i < xsTypes.length; i++) - getcomboXSType().addItem(xsTypes[i]); - - String[] dbugTypes = EnumeratedTypes - .getEnglishChoices(EnumeratedTypes.FIELD_DBUG); - for (int i = 0; i < dbugTypes.length; i++) - getcomboDBUG().addItem(dbugTypes[i]); - - //initialize the Best Xsec Type combobox to an empty string - getcomboBestXS().addItem(""); - } - - /** - * Initializes connections - * @exception java.lang.Exception The exception description. - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void initConnections() throws java.lang.Exception - { - // user code begin {1} - // user code end - getListScenario().addListSelectionListener( - new javax.swing.event.ListSelectionListener() - { - public void valueChanged( - javax.swing.event.ListSelectionEvent e) - { - connEtoC1(e); - }; - }); - getListDown().addListSelectionListener( - new javax.swing.event.ListSelectionListener() - { - public void valueChanged( - javax.swing.event.ListSelectionEvent e) - { - connEtoC2(e); - }; - }); - getListXS().addKeyListener(new java.awt.event.KeyAdapter() - { - public void keyPressed(java.awt.event.KeyEvent e) - { - connEtoC3(e); - }; - }); - getmenuQuit().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC4(e); - }; - }); - getListScenario().addKeyListener(new java.awt.event.KeyAdapter() - { - public void keyPressed(java.awt.event.KeyEvent e) - { - connEtoC5(e); - }; - }); - getmenuNew().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC8(e); - }; - }); - getcomboScenario().addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC6(e); - }; - }); - gettextSource().addFocusListener(new java.awt.event.FocusAdapter() - { - public void focusLost(java.awt.event.FocusEvent e) - { - connEtoC7(e); - }; - }); - getListDown().addKeyListener(new java.awt.event.KeyAdapter() - { - public void keyPressed(java.awt.event.KeyEvent e) - { - connEtoC9(e); - }; - }); - gettextName().addFocusListener(new java.awt.event.FocusAdapter() - { - public void focusLost(java.awt.event.FocusEvent e) - { - connEtoC10(e); - }; - }); - gettextDistance().addFocusListener(new java.awt.event.FocusAdapter() - { - public void focusLost(java.awt.event.FocusEvent e) - { - connEtoC11(e); - }; - }); - getListXS().addListSelectionListener( - new javax.swing.event.ListSelectionListener() - { - public void valueChanged( - javax.swing.event.ListSelectionEvent e) - { - connEtoC12(e); - }; - }); - getcomboXSType().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC13(e); - }; - }); - getListXS().addMouseListener(new java.awt.event.MouseAdapter() - { - public void mouseClicked(java.awt.event.MouseEvent e) - { - connEtoC14(e); - }; - }); - this.addWindowListener(new java.awt.event.WindowAdapter() - { - public void windowClosing(java.awt.event.WindowEvent e) - { - connEtoC15(e); - }; - }); - getmenuClose().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC16(e); - }; - }); - getmenuAbout().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC18(e); - }; - }); - getmenuImportDAT().addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC19(e); - }; - }); - getmenuImportFLDXS().addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC20(e); - }; - }); - getmenuUpdateDatabase().addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC21(e); - }; - }); - getmenuSave().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC22(e); - }; - }); - getmenuOpen().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC23(e); - }; - }); - getmenuSaveAs().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC24(e); - }; - }); - getmenuEditText().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC25(e); - }; - }); - getmenuDisplayOutput().addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC26(e); - }; - }); - getmenuRun_SMPDBK().addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC27(e); - }; - }); - getcomboBestXS().addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - connEtoC17(); - }; - }); - connPtoP1SetTarget(); - connPtoP2SetTarget(); - connPtoP3SetTarget(); - connPtoP4SetTarget(); - } - - /** - * Insert the method's description here. - * Creation date: (7/29/2003 10:39:10 AM) - */ - private void initDocuments() - { - gettextHDE().setDocument(new NumbersOnlyDocument()); - gettextBME().setDocument(new NumbersOnlyDocument()); - gettextVOL().setDocument(new NumbersOnlyDocument()); - gettextTFM().setDocument(new NumbersOnlyDocument()); - gettextSA().setDocument(new NumbersOnlyDocument()); - gettextQO().setDocument(new NumbersOnlyDocument()); - gettextBW().setDocument(new NumbersOnlyDocument()); - gettextDISTTN().setDocument(new NumbersOnlyDocument()); - gettextCMS().setDocument(new NumbersOnlyDocument()); - - gettextDistance().setDocument(new NumbersOnlyDocument()); - gettextFloodDepth().setDocument(new NumbersOnlyDocument()); - gettextFloodFlow().setDocument(new NumbersOnlyDocument()); - gettextLatitude().setDocument(new NumbersOnlyDocument()); - gettextLongitude().setDocument(new NumbersOnlyDocument()); - - gettextDamName().setDocument(new MaxLengthDocument(40)); - gettextRiverName().setDocument(new MaxLengthDocument(40)); - gettextPPOI().setDocument(new MaxLengthDocument(25)); - } - - /** - * Initialize the class. - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void initialize() - { - try - { - // user code begin {1} - // user code end - setName("ModelGUI"); - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setJMenuBar(getModelGUIJMenuBar()); - setResizable(false); - setSize(817, 612); - setTitle("Simplified Dambreak Model (SMPDBK)"); - setContentPane(getJFrameContentPane()); - initConnections(); - } catch (java.lang.Throwable ivjExc) - { - handleException(ivjExc); - } - // user code begin {2} - - initComboBoxes(); - initDocuments(); - - enableScenarioEditors(false); - updateScenarioList(); - - enableDownstreamEditors(false); - updateDownstreamList(); - - enableXSEditors(false); - updateXSList(); - - updateNameFields(false); - - bChangedData = false; - - // user code end - } - - /** - * main entrypoint - starts the part when it is run as an application - * @param args java.lang.String[] - */ - public static void main(java.lang.String[] args) - { - try - { - ModelGUI aModelGUI; - aModelGUI = new ModelGUI(false, null, null, null); - aModelGUI.addWindowListener(new java.awt.event.WindowAdapter() - { - public void windowClosing(java.awt.event.WindowEvent e) - { - System.exit(0); - }; - }); -// aModelGUI.show(); - aModelGUI.setVisible( true ); - java.awt.Insets insets = aModelGUI.getInsets(); - aModelGUI.setSize( - aModelGUI.getWidth() + insets.left + insets.right, - aModelGUI.getHeight() + insets.top + insets.bottom); - aModelGUI.setVisible(true); - } catch (Throwable exception) - { - System.err - .println("Exception occurred in main() of javax.swing.JFrame"); - exception.printStackTrace(System.out); - } - } - - /** - * Save any data currently being edited in the GUI back to the AnalysisData structure - * - * Creation date: (8/1/2003 5:19:19 PM) - */ - private void saveGUI() - { - - updateNameFields(true); - - if (nScenarioEditing != -1) - { - updateScenarioFields(true); - } - - if (nDownstreamEditing != -1) - { - updateDownstreamFields(true); - } - - if (nXSEditing != -1) - { - updateXSFields(true); - } - - } - - /** - * Insert the method's description here. - * Creation date: (12/19/2003 11:38:55 AM) - */ - public void setBestXSectionsCombo() - { - - String methodName = "*** In ModelGUI.setBestXSSectionsCombo"; - // if (_DEBUG) System.out.println(methodName); - - int selectedIndex = getListDown().getSelectedIndex(); - - DownstreamPoint selectedPoint = (DownstreamPoint) currentData.downstream - .get(selectedIndex); - nDownstreamEditing = selectedIndex; - - if (selectedPoint.xsecBestType == null) - selectedPoint.xsecBestType = ""; - /* - if (_DEBUG) - { - System.out.println("xsecBestType " +":" + selectedPoint.xsecBestType +":"); - } - */ - - ComboBoxModel model = getcomboBestXS().getModel(); - for (int i = 0; i < model.getSize(); i++) - { - String bestStr = (String) model.getElementAt(i); - if (bestStr == null) - bestStr = ""; - // if (_DEBUG) System.out.println("Each element: " + i + " :" + bestStr + ":"); - if (bestStr.equals(selectedPoint.xsecBestType)) - { - // if (_DEBUG) System.out.println("xsec_types are equal: " + bestStr + "=" + selectedPoint.xsecBestType); - getcomboBestXS().setSelectedIndex(i); - int realSelectedIndex = getcomboBestXS().getSelectedIndex(); - // if (_DEBUG) System.out.println ("realSelectedIndex: " + realSelectedIndex); - getcomboBestXS().repaint(); - break; - } - } - } - - /** - * Insert the method's description here. - * Creation date: (7/30/2003 10:26:59 AM) - */ - private void stopTableEditing() - { - try - { - int column = gettableXSData().getEditingColumn(); - if (column > -1) - { - TableCellEditor cellEditor = gettableXSData().getColumnModel() - .getColumn(column).getCellEditor(); - if (cellEditor == null) - { - cellEditor = gettableXSData().getDefaultEditor( - gettableXSData().getColumnClass(column)); - } - if (cellEditor != null) - { - cellEditor.stopCellEditing(); - } - } - } catch (Exception e) - { - } - } - - private void trace() - { - try - { - throw (new Exception("just tracing , not a real error")); - } catch (Exception e) - { - e.printStackTrace(); - } - } - - /** - * Synchronizes the GUI and the data structures backing them up. - * - * If the input parameter is true, the data in the GUI is - * saved to the data structures; - * - * If the input parameter is false, the data in the GUI is - * replaced by the data in the structures. - * - * Creation date: (7/29/2003 10:20:53 AM) - * @param bSaveFields boolean - */ - private boolean updateDownstreamFields(boolean bSaveFields) - { - - String methodName = "*** updateDownstreamFields"; - //if (_DEBUG) System.out.println(methodName); - - int selectedDS = getListDown().getSelectedIndex(); - - if (selectedDS == -1 - || (selectedDS == getlistModelDown().getSize() - 1 && nDownstreamEditing == -1)) - { - return true; - } - - if (bSaveFields == true && nDownstreamEditing != -1) // Move data from GUI to Logical Data Structure - // (bSaveFields == true && nDownstreamEditing != -1 && !(nDownstreamEditing > currentData.downstream.size())) - { - DownstreamPoint editedPoint = (DownstreamPoint) currentData.downstream - .get(nDownstreamEditing); - - // check to see if keys (data listed in DownstreamPoint List) have changed, if so, update the list - boolean bKeysEdited = false; - if (!editedPoint.name.equals(gettextName().getText()) - || editedPoint.distanceToSection != NumFormat - .toFloat(gettextDistance().getText())) - { - bKeysEdited = true; - - // are the new keys unique? - boolean bUniqueKeys = true; - - for (int i = 0; i < currentData.downstream.size(); i++) - { - if (i == nDownstreamEditing) - continue; - DownstreamPoint d = (DownstreamPoint) currentData.downstream - .get(i); - if (gettextName().getText().equals(d.name) - && NumFormat.toFloat(gettextDistance().getText()) == d.distanceToSection) - bUniqueKeys = false; - } - if (!bUniqueKeys) - return false; - } - - // *** test to see if anything was changed in the GUI - String testString = gettextName().getText().trim(); - if (!editedPoint.name.equalsIgnoreCase(testString)) - { - editedPoint.name = testString; - editedPoint.changeFlag = 1; - bChangedData = true; - } - if (editedPoint.distanceToSection != NumFormat - .toFloat(gettextDistance().getText())) - { - editedPoint.distanceToSection = NumFormat - .toFloat(gettextDistance().getText()); - editedPoint.changeFlag = 1; - bChangedData = true; - } - if (editedPoint.floodDepth != NumFormat.toFloat(gettextFloodDepth() - .getText())) - { - editedPoint.floodDepth = NumFormat.toFloat(gettextFloodDepth() - .getText()); - editedPoint.changeFlag = 1; - bChangedData = true; - } - if (editedPoint.floodFlow != NumFormat.toFloat(gettextFloodFlow() - .getText())) - { - editedPoint.floodFlow = NumFormat.toFloat(gettextFloodFlow() - .getText()); - editedPoint.changeFlag = 1; - bChangedData = true; - } - if (editedPoint.latitude != NumFormat.toFloat(gettextLatitude() - .getText())) - { - editedPoint.latitude = NumFormat.toFloat(gettextLatitude() - .getText()); - editedPoint.changeFlag = 1; - bChangedData = true; - } - if (editedPoint.longitude != NumFormat.toFloat(gettextLongitude() - .getText())) - { - editedPoint.longitude = NumFormat.toFloat(gettextLongitude() - .getText()); - editedPoint.changeFlag = 1; - bChangedData = true; - } - int bestIndex = getcomboBestXS().getSelectedIndex(); - if (bestIndex > -1) - { - String bestString = (String) getcomboBestXS().getItemAt( - bestIndex); - if (!editedPoint.xsecBestType.equalsIgnoreCase(bestString)) - { - editedPoint.xsecBestType = bestString; - editedPoint.changeFlag = 1; - bChangedData = true; - } - } - - // *** set best index - for (int x = 0; x < editedPoint.xsections.size(); x++) - { - SectionGeometry sg = (SectionGeometry) editedPoint.xsections - .get(x); - if (sg.getXSType().equalsIgnoreCase(editedPoint.xsecBestType)) - { - editedPoint.bestXS = x; - break; - } - } - - // *** save any section being edited ??? - updateXSFields(true); - - // update the downstream list if the keys have been edited - if (bKeysEdited) - updateDownstreamList(); - - } else if (bSaveFields == false) - { // *** Move data from Logical Data Structure to GUI - - // *** first save associated XS fields in case anything changed there and wasn't recorded - updateXSFields(true); - clearXSFields(); - - DownstreamPoint selectedPoint = (DownstreamPoint) currentData.downstream - .get(selectedDS); - nDownstreamEditing = selectedDS; - - gettextName().setText(selectedPoint.name); - gettextDistance().setText( - NumFormat.format(selectedPoint.distanceToSection, 4)); - gettextFloodDepth().setText( - NumFormat.format(selectedPoint.floodDepth, 4)); - gettextFloodFlow().setText( - NumFormat.format(selectedPoint.floodFlow, 4)); - gettextLatitude().setText( - NumFormat.format(selectedPoint.latitude, 4)); - gettextLongitude().setText( - NumFormat.format(selectedPoint.longitude, 4)); - - // clear combo box - getcomboBestXS().setSelectedIndex(-1); - getcomboBestXS().removeAllItems(); - - for (int i = 0; i < selectedPoint.xsections.size(); i++) - { - SectionGeometry sg = (SectionGeometry) selectedPoint.xsections - .get(i); - String xst = sg.getXSType(); - - // add to combo box - getcomboBestXS().addItem(xst); - } - - setBestXSectionsCombo(); - - // refresh the cross section type list - getListXS().clearSelection(); - updateXSList(); - enableXSEditors(false); - } - return true; - } - - /** - * Synchronizes the DownstreamPoint data structures with the DefaultListModel. - * Preserves the selected downstream point. - * Creation date: (7/29/2003 9:32:06 AM) - */ - private void updateDownstreamList() - { - - int oldSelection = getListDown().getSelectedIndex(); - - int interestPoint = 0; - - getlistModelDown().clear(); - - DownstreamPoint dpEditing = null; - float distanceEditing = 1000000.0f; // A million miles - - // *** Save info for DownstreamPoint whereever nDownstreamEditing is focused - - if (nDownstreamEditing > -1) - { - - dpEditing = (DownstreamPoint) currentData.downstream - .get(nDownstreamEditing); - distanceEditing = dpEditing.distanceToSection; - - } - - currentData.sortDownstreamByDistance(); - - for (int i = 0; i < currentData.downstream.size(); i++) - { - DownstreamPoint down = (DownstreamPoint) currentData.downstream - .get(i); - if (distanceEditing == down.distanceToSection) - { - // System.out.println("*** Changing nDownstreamEditing from " + nDownstreamEditing + " to " + i); - nDownstreamEditing = i; - } - getlistModelDown().addElement( - down.name + " - Distance: " - + NumFormat.format(down.distanceToSection, 4)); - // *** determine which DownstreamPoint is of most interest - if (down.distanceToSection == currentData.pointOfInterestDistance) - interestPoint = i; - } - - getlistModelDown().addElement( - "Highlight me to append a new cross section location"); - - if (oldSelection == -1 && getlistModelDown().size() > 1) // test if more than the "Highlight me " entry - oldSelection = interestPoint; // if so, set to point of interest, or first one - - if (nDownstreamEditing > -1) // however, if we were updating one of the points - oldSelection = nDownstreamEditing; // make that one the choice - - getListDown().setSelectedIndex(oldSelection); - _selectedDownstreamPoint = oldSelection; - } - - /** - * Clear Fields In GUI - * Creation date: (7/29/2003 11:55:11 AM) - */ - private void updateGUI() - { - - updateNameFields(false); - - getListScenario().clearSelection(); - updateScenarioList(); - clearScenarioFields(); - enableScenarioEditors(false); - - getListDown().clearSelection(); - updateDownstreamList(); - clearDownstreamFields(); - enableDownstreamEditors(false); - } - - /** - * Transfer data between ModelGUI and AnalysisData structure - * - * If the parameter is true, the data in the GUI is - * saved to the data structure; if the parameter is false, - * the data in the GUI is replaced by the data in the - * structure. - * - * Creation date: (8/1/2003 9:45:06 AM) - * @param bSaveFields boolean - */ - private void updateNameFields(boolean bSaveFields) - { - - //String methodName = "*** updateNameFields"; - //if (_DEBUG) System.out.println(methodName); - - if (bSaveFields) - { - if (currentData.damName != gettextDamName().getText()) - { - currentData.damName = gettextDamName().getText(); - currentData.changeFlag = 1; - bChangedData = true; - } - if (currentData.riverName != gettextRiverName().getText()) - { - currentData.riverName = gettextRiverName().getText(); - currentData.changeFlag = 1; - bChangedData = true; - } - if (currentData.pointOfInterestName != gettextPPOI().getText()) - { - currentData.pointOfInterestName = gettextPPOI().getText(); - currentData.changeFlag = 1; - bChangedData = true; - } - } else - { - gettextDamName().setText(currentData.damName); - gettextRiverName().setText(currentData.riverName); - gettextPPOI().setText(currentData.pointOfInterestName); - } - } - - /** - * Synchronizes the editors and the data backing them up. - * - * If the parameter is true, the data in the editors is saved to the data structure; - * - * if the parameter is false, data in the editors is replaced by data in the structure. - * - * Creation date: (7/29/2003 10:20:53 AM) - * @param bSaveFields boolean - * @return boolean - true if successful - */ - private boolean updateScenarioFields(boolean bSaveFields) - { - - //String methodName = "*** updateScenarioFields"; - //if (_DEBUG) System.out.println(methodName); - - int selectedIndex = getListScenario().getSelectedIndex(); - - // *** return immediately if nothing selected or last one selected && no editing done - if (selectedIndex == -1 - || (selectedIndex == getlistModelScenario().getSize() - 1 && nScenarioEditing == -1)) - return true; - - if (bSaveFields == true && nScenarioEditing != -1) - { - // if (bSaveFields == true && nScenarioEditing != -1 && !(nScenarioEditing > currentData.scenarios.size())) { - // *** transfer data from GUI to correct ModelScenario structure - - ModelScenario editedScenario = (ModelScenario) currentData.scenarios - .get(nScenarioEditing); - - // check to see if keys (data listed in Scenario List) have changed, if so, update the list - boolean bKeysEdited = false; // initialize - if (!editedScenario.source.equals(gettextSource().getText()) - || !editedScenario.name.equals(EnumeratedTypes.getCode( - EnumeratedTypes.FIELD_SCENARIO, - (String) getcomboScenario().getSelectedItem()))) - { - bKeysEdited = true; - - // are the new keys unique? - boolean bUniqueKeys = true; - for (int i = 0; i < currentData.scenarios.size(); i++) - { - if (i == nScenarioEditing) - continue; - ModelScenario s = (ModelScenario) currentData.scenarios - .get(i); - if (gettextSource().getText().equals(s.source) - && s.name.equals(EnumeratedTypes.getCode( - EnumeratedTypes.FIELD_SCENARIO, - (String) getcomboScenario() - .getSelectedItem()))) - bUniqueKeys = false; - } - if (!bUniqueKeys) - return false; - } - String testString = gettextSource().getText().trim(); - if (!editedScenario.source.equalsIgnoreCase(testString)) - { - editedScenario.source = testString; - editedScenario.changeFlag = 1; - bChangedData = true; - } - testString = EnumeratedTypes.getCode( - EnumeratedTypes.FIELD_SCENARIO, (String) getcomboScenario() - .getSelectedItem()); - if (!editedScenario.name.equalsIgnoreCase(testString)) - { - editedScenario.name = testString; - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.damType != getcomboTypeOfDam() - .getSelectedIndex()) - { - editedScenario.damType = getcomboTypeOfDam().getSelectedIndex(); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.HDE != NumFormat.toFloat(gettextHDE().getText())) - { - editedScenario.HDE = NumFormat.toFloat(gettextHDE().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.BME != NumFormat.toFloat(gettextBME().getText())) - { - editedScenario.BME = NumFormat.toFloat(gettextBME().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.VOL != NumFormat.toFloat(gettextVOL().getText())) - { - editedScenario.VOL = NumFormat.toFloat(gettextVOL().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.SA != NumFormat.toFloat(gettextSA().getText())) - { - editedScenario.SA = NumFormat.toFloat(gettextSA().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.BW != NumFormat.toFloat(gettextBW().getText())) - { - editedScenario.BW = NumFormat.toFloat(gettextBW().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.TFM != NumFormat.toFloat(gettextTFM().getText())) - { - editedScenario.TFM = NumFormat.toFloat(gettextTFM().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.QO != NumFormat.toFloat(gettextQO().getText())) - { - editedScenario.QO = NumFormat.toFloat(gettextQO().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.DISTTN != NumFormat.toFloat(gettextDISTTN() - .getText())) - { - editedScenario.DISTTN = NumFormat.toFloat(gettextDISTTN() - .getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.CMS != NumFormat.toFloat(gettextCMS().getText())) - { - editedScenario.CMS = NumFormat.toFloat(gettextCMS().getText()); - editedScenario.changeFlag = 1; - bChangedData = true; - } - if (editedScenario.dbugType != getcomboDBUG().getSelectedIndex()) - { - editedScenario.dbugType = getcomboDBUG().getSelectedIndex(); - editedScenario.changeFlag = 1; - bChangedData = true; - } - // update the scenario list if the keys have been edited - if (bKeysEdited) - updateScenarioList(); - - } else if (bSaveFields == false) - { - // *** Move data from Logical Data Structure to GUI - - ModelScenario selectedScenario = (ModelScenario) currentData.scenarios - .get(selectedIndex); - - nScenarioEditing = selectedIndex; - - gettextSource().setText(selectedScenario.source); - getcomboScenario().setSelectedItem( - EnumeratedTypes.getEnglish(EnumeratedTypes.FIELD_SCENARIO, - selectedScenario.name)); - getcomboTypeOfDam().setSelectedIndex(selectedScenario.damType); - gettextHDE().setText(NumFormat.format(selectedScenario.HDE, 4)); - gettextBME().setText(NumFormat.format(selectedScenario.BME, 4)); - gettextVOL().setText(NumFormat.format(selectedScenario.VOL, 4)); - gettextSA().setText(NumFormat.format(selectedScenario.SA, 4)); - gettextBW().setText(NumFormat.format(selectedScenario.BW, 4)); - gettextTFM().setText(NumFormat.format(selectedScenario.TFM, 4)); - gettextQO().setText(NumFormat.format(selectedScenario.QO, 4)); - gettextDISTTN().setText( - NumFormat.format(selectedScenario.DISTTN, 4)); - gettextCMS().setText(NumFormat.format(selectedScenario.CMS, 4)); - getcomboDBUG().setSelectedIndex(selectedScenario.dbugType); - } - return true; - } - - /** - * Synchronizes the scenario data structures with the list. - * Preserves the selected scenario; - * (if nothing selected defaults to first one) - * - * Creation date: (7/29/2003 9:32:06 AM) - */ - private void updateScenarioList() - { - - int count = 0; - - int oldSelection = getListScenario().getSelectedIndex(); - - getlistModelScenario().clear(); - - for (int i = 0; i < currentData.scenarios.size(); i++) - { - ModelScenario scenario = (ModelScenario) currentData.scenarios - .get(i); - getlistModelScenario().addElement( - scenario.source - + " - " - + EnumeratedTypes.getEnglish( - EnumeratedTypes.FIELD_SCENARIO, - scenario.name)); - // *** set pointOfInterestDistance to max found in all scenarios - if (scenario.DISTTN > currentData.pointOfInterestDistance) - currentData.pointOfInterestDistance = scenario.DISTTN; - - String changedSource = scenario.source; // skip scenarios started with '#' when scenario is highlighted initially - if (changedSource.startsWith("#")) - { - count++; - } - } - - getlistModelScenario().addElement( - "Highlight me to append a new scenario"); - - if (oldSelection == -1 && getlistModelScenario().size() > 1) // test if more than the "Highlight me " entry - oldSelection = count; // if so, set to first one - - getListScenario().setSelectedIndex(oldSelection); - _selectedScenario = oldSelection; - - } - - /** - * Update Cross Section - * Synchronizes the editors and the data backing them up. - * - * If the parameter is true, the data in the editors is saved to the data structure; - * - * if the parameter is false, data in the editors is replaced by data in the structure. - * - * Creation date: (7/30/2003 7:51:19 AM) - * @param bSaveFields boolean - */ - private boolean updateXSFields(boolean bSaveFields) - { - - String methodName = "*** updateXSFields"; - //if (_DEBUG) System.out.println(methodName); - - // *** this assumes JLists in GUI matches ArrayLists maintained within AnalysisData structure - int selectedDS = getListDown().getSelectedIndex(); - int selectedXS = getListXS().getSelectedIndex(); - - if (selectedXS == -1 - || (selectedXS == getlistModelXS().getSize() - 1 && nXSEditing == -1)) - { - return true; - } - - DownstreamPoint editedDown = (DownstreamPoint) currentData.downstream - .get(nDownstreamEditing); - - if (bSaveFields == true && nXSEditing != -1) // *** Move data from GUI to Logical Data Structure - { - SectionGeometry editedSection = (SectionGeometry) editedDown.xsections - .get(nXSEditing); - - // check to see if keys (data listed in Cross Section Type List) have changed, if so, update the list later - boolean bKeysEdited = false; - - if (!editedSection.getXSType().equals( - EnumeratedTypes.getCode(EnumeratedTypes.FIELD_XSTYPE, - (String) getcomboXSType().getSelectedItem()))) - { - bKeysEdited = true; - - // are the new keys unique? - boolean bUniqueKeys = true; - for (int i = 0; i < editedDown.xsections.size(); i++) - { - if (i == nXSEditing) - continue; - SectionGeometry sg = (SectionGeometry) editedDown.xsections - .get(i); - if (sg.getXSType().equals( - EnumeratedTypes - .getCode(EnumeratedTypes.FIELD_XSTYPE, - (String) getcomboXSType() - .getSelectedItem()))) - bUniqueKeys = false; - } - if (!bUniqueKeys) - return false; - } - String testString = EnumeratedTypes.getCode( - EnumeratedTypes.FIELD_XSTYPE, (String) getcomboXSType() - .getSelectedItem()); - if (!editedSection.getXSType().equalsIgnoreCase(testString)) - { - editedSection.setXSType(testString); - editedSection.setChangeFlag(1); - bChangedData = true; - } - - // Save geometry table - stopTableEditing(); - for (int i = 0; i < 8; i++) - { - if (((String) gettableModelXSGeom().getValueAt(i, 0)) - .equals("")) - { - editedSection.setElevationData(i, 0, -999.0f); - editedSection.setElevationData(i, 1, 0.0f); - editedSection.setElevationData(i, 2, 0.0f); - editedSection.setElevationData(i, 3, 0.0f); - continue; - } - editedSection.setLastRowUsed(i); - float elevData = NumFormat - .toFloat((String) gettableModelXSGeom() - .getValueAt(i, 0)); - if (editedSection.getElevationData(i, 0) != elevData) - { - editedSection.setElevationData(i, 0, NumFormat - .toFloat((String) gettableModelXSGeom().getValueAt( - i, 0))); - editedSection.setChangeFlag(1); - bChangedData = true; - } - elevData = NumFormat.toFloat((String) gettableModelXSGeom() - .getValueAt(i, 1)); - if (editedSection.getElevationData(i, 1) != elevData) - { - editedSection.setElevationData(i, 1, NumFormat - .toFloat((String) gettableModelXSGeom().getValueAt( - i, 1))); - editedSection.setChangeFlag(1); - bChangedData = true; - } - elevData = NumFormat.toFloat((String) gettableModelXSGeom() - .getValueAt(i, 2)); - if (editedSection.getElevationData(i, 2) != elevData) - { - editedSection.setElevationData(i, 2, NumFormat - .toFloat((String) gettableModelXSGeom().getValueAt( - i, 2))); - editedSection.setChangeFlag(1); - bChangedData = true; - } - elevData = NumFormat.toFloat((String) gettableModelXSGeom() - .getValueAt(i, 3)); - if (editedSection.getElevationData(i, 3) != elevData) - { - editedSection.setElevationData(i, 3, NumFormat - .toFloat((String) gettableModelXSGeom().getValueAt( - i, 3))); - editedSection.setChangeFlag(1); - bChangedData = true; - } - } - - // if the keys have been edited update the cross section type list - if (bKeysEdited) - updateXSList(); - - } else if (bSaveFields == false) - { - // *** Move data from Logical Data Structure To GUI - - SectionGeometry selectedSection = (SectionGeometry) editedDown.xsections - .get(selectedXS); - - nXSEditing = selectedXS; - - getcomboXSType().setSelectedItem( - EnumeratedTypes.getEnglish(EnumeratedTypes.FIELD_XSTYPE, - selectedSection.getXSType())); - - // Load geometry table - stopTableEditing(); - for (int i = 0; i < 8; i++) - { - if (selectedSection.getElevationData(i, 0) == -999.0f) - { - gettableModelXSGeom().setValueAt("", i, 0); - gettableModelXSGeom().setValueAt("", i, 1); - gettableModelXSGeom().setValueAt("", i, 2); - gettableModelXSGeom().setValueAt("", i, 3); // was set to 0.05 - } else - { - gettableModelXSGeom().setValueAt( - NumFormat.format(selectedSection.getElevationData( - i, 0), 4), i, 0); - gettableModelXSGeom().setValueAt( - NumFormat.format(selectedSection.getElevationData( - i, 1), 4), i, 1); - gettableModelXSGeom().setValueAt( - NumFormat.format(selectedSection.getElevationData( - i, 2), 4), i, 2); - gettableModelXSGeom().setValueAt( - NumFormat.format(selectedSection.getElevationData( - i, 3), 4), i, 3); - } - } - } - - return true; - - } - - /** - * Synchronizes the xs data structure for the chosen - * downstream point with the list. Preserves the - * selected cross section. - * - * Creation date: (7/29/2003 9:32:06 AM) - */ - private void updateXSList() - { - - // *** check to see if DownstreamPoint is selected - // _selectedDownstreamPoint = getListDown().getSelectedIndex(); - int selectedDS = getListDown().getSelectedIndex(); - - // if (nDownstreamEditing == -1) - if (selectedDS == -1) - { - return; - } - - int oldSelection = getListXS().getSelectedIndex(); - - getlistModelXS().clear(); - - // DownstreamPoint down = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - DownstreamPoint down = (DownstreamPoint) currentData.downstream - .get(selectedDS); - int bestXS = -1; - - // *** this recomputes best XS index ! - // *** is this necessary ? - for (int i = 0; i < down.xsections.size(); i++) - { - SectionGeometry xs = (SectionGeometry) down.xsections.get(i); - getlistModelXS().addElement( - "Type: " - + EnumeratedTypes.getEnglish( - EnumeratedTypes.FIELD_XSTYPE, xs - .getXSType())); - // if (_DEBUG) System.out.println("XSType = " + xs.getXSType()); - // if (_DEBUG) System.out.println("down.xsecBestType = " + down.xsecBestType); - if (xs.getXSType().equalsIgnoreCase(down.xsecBestType)) - { - bestXS = i; - } - } - getlistModelXS().addElement( - "Highlight me to append a new set of elevations"); - - if (oldSelection == -1 && bestXS > -1) - { - oldSelection = bestXS; - } - - _selectedXSType = oldSelection; - - getListXS().setSelectedIndex(_selectedXSType); - - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/ModelGUI.java_prev b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/ModelGUI.java_prev deleted file mode 100644 index 8aa8fb59fb..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/ModelGUI.java_prev +++ /dev/null @@ -1,5133 +0,0 @@ -package gov.dambreak.smpdbk; - -import java.util.*; -import java.io.*; -import java.awt.*; -import java.awt.event.*; -import javax.swing.border.*; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.table.*; -import gov.dambreak.util.*; -import gov.dambreak.menu.*; -import gov.damcat.data.*; - -/** - * GUI For Model Manipulation - * Creation date: (7/29/2003 8:26:32 AM) - * @author: - */ -public class ModelGUI extends JFrame { - // GUI Data Fields - private AnalysisData currentData = new AnalysisData(); - private String strOpenedFilename; - private String strLastOpenPath; -// private boolean _DEBUG = false; - private boolean _DEBUG = true; - private int nScenarioEditing = -1; - private int nDownstreamEditing = -1; - private int nXSEditing = -1; - private boolean bHandlingEvent = false; // prevents multiple Events from firing - private boolean bHasDatabase = false; // passed in to constructor; indicates whether DBMS is in use - private String strWorkingDamNIDID; - private DBAccess dbAccess; - private JComboBox ivjcomboScenario = null; - private JComboBox ivjcomboTypeOfDam = null; - private JComboBox ivjcomboXSType = null; - private JPanel ivjJFrameContentPane = null; - private JSeparator ivjJSeparator1 = null; - private JSeparator ivjJSeparator2 = null; - private JLabel ivjlabelBME = null; - private JLabel ivjlabelBW = null; - private JLabel ivjlabelCMS = null; - private JLabel ivjlabelDamName = null; - private JLabel ivjlabelDISTTN = null; - private JLabel ivjlabelHDE = null; - private JLabel ivjlabelPPOI = null; - private JLabel ivjlabelQO = null; - private JLabel ivjlabelRequiredFieldsNotice = null; - private JLabel ivjlabelRiverName = null; - private JLabel ivjlabelSA = null; - private JLabel ivjlabelScenario = null; - private JLabel ivjlabelScenarioList = null; - private JLabel ivjlabelSource = null; - private JLabel ivjlabelTFM = null; - private JLabel ivjlabelTypeOfDam = null; - private JLabel ivjlabelVolume = null; - private JLabel ivjlabelXSDistance = null; - private JLabel ivjlabelXSFloodDepth = null; - private JLabel ivjlabelXSLatitutde = null; - private JLabel ivjlabelXSList = null; - private JLabel ivjlabelXSList1 = null; - private JLabel ivjlabelXSLongitude = null; - private JLabel ivjlabelXSName = null; - private JMenuItem ivjmenuAbout = null; - private JMenu ivjmenuFile = null; - private JMenu ivjmenuHelp = null; - private JMenuItem ivjmenuImportDAT = null; - private JMenuItem ivjmenuImportFLDXS = null; - private JMenuItem ivjmenuNew = null; - private JMenuItem ivjmenuOpen = null; - private JMenuItem ivjmenuQuit = null; - private JMenuItem ivjmenuSave = null; - private JMenuItem ivjmenuSaveAs = null; - private JMenu ivjmenuSMPDBK = null; - private JMenuBar ivjModelGUIJMenuBar = null; - private JPanel ivjpanelDamInfo = null; - private JScrollPane ivjscrollScenarioList = null; - private JScrollPane ivjscrollXSData = null; - private JScrollPane ivjscrollXSList = null; - private JScrollPane ivjscrollXSList1 = null; - private JTable ivjtableXSData = null; - private JTextField ivjtextBME = null; - private JTextField ivjtextBW = null; - private JTextField ivjtextCMS = null; - private JTextField ivjtextDamName = null; - private JTextField ivjtextDISTTN = null; - private JTextField ivjtextFloodFlow = null; - private JTextField ivjtextHDE = null; - private JTextField ivjtextPPOI = null; - private JTextField ivjtextQO = null; - private JTextField ivjtextRiverName = null; - private JTextField ivjtextSA = null; - private JTextField ivjtextSource = null; - private JTextField ivjtextTFM = null; - private JTextField ivjtextVOL = null; - private DefaultListModel ivjlistModelDown = null; - private DefaultListModel ivjlistModelScenario = null; - private DefaultListModel ivjlistModelXS = null; - private JList ivjListDown = null; - private JList ivjListScenario = null; - private JList ivjListXS = null; - private JTextField ivjtextDistance = null; - private JTextField ivjtextFloodDepth = null; - private JTextField ivjtextLatitude = null; - private JTextField ivjtextLongitude = null; - private JTextField ivjtextName = null; - private TableColumn ivjcolumnBS = null; - private TableColumn ivjcolumnBSS = null; - private TableColumn ivjcolumnElevation = null; - private TableColumn ivjcolumnMannN = null; - private DefaultTableModel ivjtableModelXSGeom = null; - private JLabel ivjlabelXSList11 = null; - private JMenuItem ivjmenuClose = null; - private JMenu ivjmenuDatabase = null; - private JMenuItem ivjmenuUpdateDatabase = null; - private JLabel ivjlabelSectionType = null; - private JLabel ivjlabelXSFloodFlow = null; - private JPanel ivjpanelDownstreamInfo = null; - private JPanel ivjpanelNameInfo = null; - private JPanel ivjpanelXS = null; - private JMenu ivjmenuEdit = null; - private JMenuItem ivjmenuEditText = null; - private JMenuItem ivjmenuDisplayOutput = null; - private JMenuItem ivjmenuRun_SMPDBK = null; - private JComboBox ivjcomboDBUG = null; - private JLabel ivjlabelDBUG = null; - private boolean bHasDataToSave = false; - private JComboBox ivjcomboBestXS = null; - private int _selectedScenario = -1; - private int _selectedDownstreamPoint = -1; - private int _selectedXSType = -1; - private Search searchTool; - private boolean bChangedData = false; - //private JTextField ivjBestTypeText = null; -/** - * Constructor - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -public ModelGUI() { - super(); - initialize(); -} -/** - * Insert the method's description here. - * Creation date: (7/30/2003 1:25:47 PM) - * @param dbData util.AnalysisData - */ -public ModelGUI(boolean _bHasDatabase, String _strWorkingDamNIDID, AnalysisData _currentData, DBAccess _dbAccess) { - - super(); - - /* - try { - throw new Exception("Forced Exception To Trace Call"); - } - catch (Exception e) { - e.printStackTrace(); - } - */ - - - System.out.println("Initializing SMPDBK model input editor..."); - - currentData = _currentData; - if (currentData == null) - { - currentData = new AnalysisData(); - bHasDataToSave = false; - } - else - { - bHasDataToSave = true; - } - strWorkingDamNIDID = _strWorkingDamNIDID; - strOpenedFilename = null; - strLastOpenPath = ""; - bHasDatabase = _bHasDatabase; - dbAccess = _dbAccess; - - initialize(); - - if (bHasDatabase) - setTitle("Model Input Editor - Database Mode - Editing DAMCAT Entry: " + _strWorkingDamNIDID); - else - setTitle("Model Input Editor - File Mode"); - - show(); - java.awt.Insets insets = getInsets(); - setSize(getWidth() + insets.left + insets.right, getHeight() + insets.top + insets.bottom); - setVisible(true); -} -/** - * Provide dialogs to ask user if he wants to save - * Creation date: (8/1/2003 12:09:47 PM) - * @return boolean - */ -private boolean checkForSaveChanges() { - - int confirmOption; - - if(bChangedData == true) - { - if (bHasDatabase) { - - // ask the user if they would like to save before exiting - - confirmOption = JOptionPane.showConfirmDialog(this, "Do you want to save changes to the database ?", "Confirm", JOptionPane.YES_NO_OPTION); - - if (confirmOption == JOptionPane.YES_OPTION) { - // If the database update fails, return false - if (handleMenuUpdateDatabase(false) == false) - return false; - } - - } else { - - // ask the user if they would like to save before exiting - - confirmOption = JOptionPane.showConfirmDialog(this, "Do you want to save any changes to a file ?", "Confirm", JOptionPane.YES_NO_OPTION); - - if (confirmOption == JOptionPane.YES_OPTION) { - // If the save fails, return false to let the calling method know that - // the user's wish was not granted - if (handleMenuSave() == false) - return false; - } - - } - } - - bChangedData = false; - - return true; -} -/** - * Initialize GUI for Downstream Point - */ -private void clearDownstreamFields() { - - gettextName().setText(""); - gettextDistance().setText(""); - gettextFloodDepth().setText(""); - gettextFloodFlow().setText(""); - gettextLatitude().setText(""); - gettextLongitude().setText(""); - // if (_DEBUG) System.out.println("Item Count is: " + getcomboBestXS().getItemCount()); - if(getcomboBestXS().getItemCount() > 0) - getcomboBestXS().setSelectedIndex(0); - - getlistModelXS().clear(); - getListXS().clearSelection(); - - clearXSFields(); - - getcomboXSType().setSelectedIndex(0); - gettableXSData().clearSelection(); - - /*while (gettableModelXSGeom().getRowCount() != 0) - gettableModelXSGeom().removeRow(0);*/ - - nDownstreamEditing = -1; - -} -/** - * Initialize ModelGUI for Input Scenario fields - * Creation date: (7/29/2003 10:14:27 AM) - */ -private void clearScenarioFields() { - - gettextSource().setText(""); - getcomboScenario().setSelectedIndex(0); - getcomboTypeOfDam().setSelectedIndex(0); - getcomboDBUG().setSelectedIndex(0); - gettextHDE().setText(""); - gettextBME().setText(""); - gettextVOL().setText(""); - gettextSA().setText(""); - gettextBW().setText(""); - gettextTFM().setText(""); - gettextQO().setText(""); - gettextDISTTN().setText(""); - gettextCMS().setText(""); - - nScenarioEditing = -1; - -} -/** - * Insert the method's description here. - * Creation date: (7/29/2003 3:25:56 PM) - */ -private void clearXSFields() { - - getcomboXSType().setSelectedIndex(0); - stopTableEditing(); - gettableXSData().clearSelection(); - - int rowLimiter = gettableModelXSGeom().getRowCount(); - for (int i=0; i ModelGUI.handleScenarioListSelection()V) - * @param arg1 javax.swing.event.ListSelectionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC1(javax.swing.event.ListSelectionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleScenarioListSelection(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC10: (textName.focus.focusLost(java.awt.event.FocusEvent) --> ModelGUI.handleDownstreamKeyLostFocus()V) - * @param arg1 java.awt.event.FocusEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC10(java.awt.event.FocusEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleDownstreamKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC11: (textDistance.focus.focusLost(java.awt.event.FocusEvent) --> ModelGUI.handleDownstreamKeyLostFocus()V) - * @param arg1 java.awt.event.FocusEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC11(java.awt.event.FocusEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleDownstreamKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC12: (ListXS.listSelection.valueChanged(javax.swing.event.ListSelectionEvent) --> ModelGUI.handleXSListSelection(Ljavax.swing.event.ListSelectionEvent;)V) - * @param arg1 javax.swing.event.ListSelectionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC12(javax.swing.event.ListSelectionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleXSListSelection(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC13: (comboXSType.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleXSKeyLostFocus()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC13(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleXSKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC14: (ListXS.mouse.mouseClicked(java.awt.event.MouseEvent) --> ModelGUI.handleXSListClick(Ljava.awt.event.MouseEvent;)V) - * @param arg1 java.awt.event.MouseEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC14(java.awt.event.MouseEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleXSListClick(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC15: (ModelGUI.window.windowClosing(java.awt.event.WindowEvent) --> ModelGUI.handleWindowClosing()V) - * @param arg1 java.awt.event.WindowEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC15(java.awt.event.WindowEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleWindowClosing(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC16: (menuClose.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuClose()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC16(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuClose(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC17: (comboBestXS.action. --> ModelGUI.handleDownstreamKeyLostFocus()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC17() { - try { - // user code begin {1} - // user code end - this.handleDownstreamKeyLostFocus(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC18: (menuAbout.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuAbout()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC18(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuAbout(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC19: (menuImportDAT.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuImportFromDAT()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC19(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuImportFromDAT(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC2: (ListDown.listSelection.valueChanged(javax.swing.event.ListSelectionEvent) --> ModelGUI.handleDownstreamListSelection()V) - * @param arg1 javax.swing.event.ListSelectionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC2(javax.swing.event.ListSelectionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleDownstreamListSelection(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC20: (menuImportFLDXS.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuImportFromFLDXS()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC20(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuImportFromFLDXS(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC21: (menuUpdateDatabase.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuUpdateDatabase(Z)Z) - * @return boolean - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private boolean connEtoC21(java.awt.event.ActionEvent arg1) { - boolean connEtoC21Result = false; - try { - // user code begin {1} - // user code end - connEtoC21Result = this.handleMenuUpdateDatabase(true); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - return connEtoC21Result; -} -/** - * connEtoC22: (menuSave.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuSave()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC22(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuSave(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC23: (menuOpen.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuOpen()Z) - * @return boolean - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private boolean connEtoC23(java.awt.event.ActionEvent arg1) { - boolean connEtoC23Result = false; - try { - // user code begin {1} - // user code end - connEtoC23Result = this.handleMenuOpen(); - // user code begin {2} - // System.out.println("The connEtoC23Result is:" + connEtoC23Result); - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - System.out.println("Throwable of connEtoC23"); - // user code end - handleException(ivjExc); - } - return connEtoC23Result; -} -/** - * connEtoC24: (menuSaveAs.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuSaveAs()Z) - * @return boolean - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private boolean connEtoC24(java.awt.event.ActionEvent arg1) { - boolean connEtoC24Result = false; - try { - // user code begin {1} - // user code end - connEtoC24Result = this.handleMenuSaveAs(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - return connEtoC24Result; -} -/** - * connEtoC25: (menuEditText.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuEditText()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC25(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuEditText(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC26: (menuDisplayOutput.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleDisplayOutput()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC26(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuDisplayOutput(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC27: (menuRun_SMPDBK.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuRun_SMPDBK()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC27(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuRun_SMPDBK(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC3: (ListXS.key.keyPressed(java.awt.event.KeyEvent) --> ModelGUI.handleXSListKey(Ljava.awt.event.KeyEvent;)V) - * @param arg1 java.awt.event.KeyEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC3(java.awt.event.KeyEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleXSListKey(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC4: (menuQuit.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuQuit()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC4(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuQuit(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC5: (ListScenario.key.keyPressed(java.awt.event.KeyEvent) --> ModelGUI.handleScenarioListKey(Ljava.awt.event.KeyEvent;)V) - * @param arg1 java.awt.event.KeyEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC5(java.awt.event.KeyEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleScenarioListKey(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC6: (comboScenario.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleScenarioKeyFocusLost()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC6(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleScenarioKeyFocusLost(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC7: (textSource.focus.focusLost(java.awt.event.FocusEvent) --> ModelGUI.handleScenarioKeyFocusLost()V) - * @param arg1 java.awt.event.FocusEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC7(java.awt.event.FocusEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleScenarioKeyFocusLost(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC8: (menuNew.action.actionPerformed(java.awt.event.ActionEvent) --> ModelGUI.handleMenuNew()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC8(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleMenuNew(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC9: (ListDown.key.keyPressed(java.awt.event.KeyEvent) --> ModelGUI.handleDownListKey(Ljava.awt.event.KeyEvent;)V) - * @param arg1 java.awt.event.KeyEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC9(java.awt.event.KeyEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleDownListKey(arg1); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connPtoP1SetTarget: (listModelXS.this <--> ListXSList.model) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connPtoP1SetTarget() { - /* Set the target from the source */ - try { - getListXS().setModel(getlistModelXS()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connPtoP2SetTarget: (listModelDown.this <--> ListDownList.model) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connPtoP2SetTarget() { - /* Set the target from the source */ - try { - getListDown().setModel(getlistModelDown()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connPtoP3SetTarget: (listModelScenario.this <--> ListScenarioList.model) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connPtoP3SetTarget() { - /* Set the target from the source */ - try { - getListScenario().setModel(getlistModelScenario()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connPtoP4SetTarget: (tableModelXSGeom.this <--> tableXSData.model) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connPtoP4SetTarget() { - /* Set the target from the source */ - try { - gettableXSData().setModel(gettableModelXSGeom()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * Creates a new downstream point with default data and makes it the current selection - * Creation date: (7/29/2003 9:06:27 AM) - */ -private void createNewDownstreamPoint(int selectedIndex) { - - DownstreamPoint newDownstream = new DownstreamPoint(); - - newDownstream.changeFlag = 2; // *** indicate that DownstreamPoint needs inserted ! - - currentData.downstream.add(selectedIndex, newDownstream); - - updateDownstreamList(); -} -/** - * Creates a new scenario with default data and makes it the current selection - * Creation date: (7/29/2003 9:06:27 AM) - */ -private void createNewScenario() { - - ModelScenario newScenario = new ModelScenario(); - - currentData.scenarios.add(newScenario); // *** this is at bottom - - updateScenarioList(); - - bHasDataToSave = true; -} -/** - * Create new SectionGeometry for particular DownstreamPoint - * Creation date: (7/30/2003 8:02:24 AM) - */ -private void createNewXS(int whichDownstreamPoint) { - - if (whichDownstreamPoint == -1) - return; - - SectionGeometry newSection = new SectionGeometry(); - DownstreamPoint downEditing = (DownstreamPoint)currentData.downstream.get(whichDownstreamPoint); - - // *** add newSection to back of ArrayList - downEditing.xsections.add(newSection); - - // make this the "best" cross section if it is the only one - if (downEditing.xsections.size() == 1) - downEditing.bestXS = 0; - - updateXSList(); -} -/** - * Insert the method's description here. - * Creation date: (7/29/2003 12:10:26 PM) - * @param bEnable boolean - */ -private void enableDownstreamEditors(boolean bEnable) { - gettextName().setEnabled(bEnable); - gettextDistance().setEnabled(bEnable); - gettextFloodDepth().setEnabled(bEnable); - gettextFloodFlow().setEnabled(bEnable); - gettextLatitude().setEnabled(bEnable); - gettextLongitude().setEnabled(bEnable); - getcomboBestXS().setEnabled(bEnable); - getListXS().setEnabled(bEnable); -} -/** - * Insert the method's description here. - * Creation date: (7/29/2003 10:17:09 AM) - * @param bEnable boolean - */ -private void enableScenarioEditors(boolean bEnable) { - gettextSource().setEnabled(bEnable); - getcomboScenario().setEnabled(bEnable); - getcomboTypeOfDam().setEnabled(bEnable); - getcomboDBUG().setEnabled(bEnable); - gettextHDE().setEnabled(bEnable); - gettextBME().setEnabled(bEnable); - gettextVOL().setEnabled(bEnable); - gettextSA().setEnabled(bEnable); - gettextBW().setEnabled(bEnable); - gettextTFM().setEnabled(bEnable); - gettextQO().setEnabled(bEnable); - gettextDISTTN().setEnabled(bEnable); - gettextCMS().setEnabled(bEnable); -} -/** - * Insert the method's description here. - * Creation date: (7/30/2003 8:01:34 AM) - * @param bEnable boolean - */ -private void enableXSEditors(boolean bEnable) { - gettableXSData().setEnabled(bEnable); - getcomboXSType().setEnabled(bEnable); -} -/** - * This method attempts to fill the output fields - * of each scenario with updated model output. - * - * If the model fails to run, any existing output is - * kept as it was. - * - * NOTE: In order to keep input and output synchronized, - * This should be changed to clear the output if - * the model fails to run. - * - * Creation date: (7/31/2003 11:00:39 AM) - */ -private boolean generateOutput() { - - boolean generationResult; - if (_DEBUG) System.out.print("Generating output..."); - generationResult = currentData.generateOutput(); - if (_DEBUG) System.out.println("Finished."); - return generationResult; - -} -/** - * Return the columnBS property value. - * @return javax.swing.table.TableColumn - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.table.TableColumn getcolumnBS() { - if (ivjcolumnBS == null) { - try { - ivjcolumnBS = new javax.swing.table.TableColumn(); - ivjcolumnBS.setModelIndex(1); - ivjcolumnBS.setHeaderValue("Channel Width"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnBS; -} -/** - * Return the columnBSS property value. - * @return javax.swing.table.TableColumn - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.table.TableColumn getcolumnBSS() { - if (ivjcolumnBSS == null) { - try { - ivjcolumnBSS = new javax.swing.table.TableColumn(); - ivjcolumnBSS.setModelIndex(2); - ivjcolumnBSS.setHeaderValue("Inactive Width"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnBSS; -} -/** - * Return the columnElevation property value. - * @return javax.swing.table.TableColumn - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.table.TableColumn getcolumnElevation() { - if (ivjcolumnElevation == null) { - try { - ivjcolumnElevation = new javax.swing.table.TableColumn(); - ivjcolumnElevation.setHeaderValue("Elevation"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnElevation; -} -/** - * Return the columnMannN property value. - * @return javax.swing.table.TableColumn - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.table.TableColumn getcolumnMannN() { - if (ivjcolumnMannN == null) { - try { - ivjcolumnMannN = new javax.swing.table.TableColumn(); - ivjcolumnMannN.setModelIndex(3); - ivjcolumnMannN.setHeaderValue("Manning N"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcolumnMannN; -} -/** - * Return the comboBestXS property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboBestXS() { - if (ivjcomboBestXS == null) { - try { - ivjcomboBestXS = new javax.swing.JComboBox(); - ivjcomboBestXS.setName("comboBestXS"); - ivjcomboBestXS.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboBestXS.setBackground(new java.awt.Color(255,255,249)); - ivjcomboBestXS.setBounds(221, 297, 130, 22); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboBestXS; -} -/** - * Return the comboDBUG property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboDBUG() { - if (ivjcomboDBUG == null) { - try { - ivjcomboDBUG = new javax.swing.JComboBox(); - ivjcomboDBUG.setName("comboDBUG"); - ivjcomboDBUG.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboDBUG.setBackground(new java.awt.Color(255,255,255)); - ivjcomboDBUG.setBounds(245, 437, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboDBUG; -} -/** - * Return the comboScenario property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboScenario() { - if (ivjcomboScenario == null) { - try { - ivjcomboScenario = new javax.swing.JComboBox(); - ivjcomboScenario.setName("comboScenario"); - ivjcomboScenario.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboScenario.setBackground(new java.awt.Color(255,255,255)); - ivjcomboScenario.setBounds(244, 144, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboScenario; -} -/** - * Return the comboTypeOfDam property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboTypeOfDam() { - if (ivjcomboTypeOfDam == null) { - try { - ivjcomboTypeOfDam = new javax.swing.JComboBox(); - ivjcomboTypeOfDam.setName("comboTypeOfDam"); - ivjcomboTypeOfDam.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboTypeOfDam.setBackground(new java.awt.Color(255,255,255)); - ivjcomboTypeOfDam.setBounds(245, 168, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboTypeOfDam; -} -/** - * Return the comboXSType property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboXSType() { - if (ivjcomboXSType == null) { - try { - ivjcomboXSType = new javax.swing.JComboBox(); - ivjcomboXSType.setName("comboXSType"); - ivjcomboXSType.setFont(new java.awt.Font("dialog", 0, 12)); - ivjcomboXSType.setBackground(new java.awt.Color(255,255,255)); - ivjcomboXSType.setBounds(129, 94, 203, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboXSType; -} -/** - * Return the JFrameContentPane property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJFrameContentPane() { - if (ivjJFrameContentPane == null) { - try { - ivjJFrameContentPane = new javax.swing.JPanel(); - ivjJFrameContentPane.setName("JFrameContentPane"); - ivjJFrameContentPane.setLayout(null); - getJFrameContentPane().add(getpanelNameInfo(), getpanelNameInfo().getName()); - getJFrameContentPane().add(getpanelDamInfo(), getpanelDamInfo().getName()); - getJFrameContentPane().add(getpanelDownstreamInfo(), getpanelDownstreamInfo().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJFrameContentPane; -} -/** - * Return the JSeparator1 property value. - * @return javax.swing.JSeparator - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JSeparator getJSeparator1() { - if (ivjJSeparator1 == null) { - try { - ivjJSeparator1 = new javax.swing.JSeparator(); - ivjJSeparator1.setName("JSeparator1"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJSeparator1; -} -/** - * Return the JSeparator2 property value. - * @return javax.swing.JSeparator - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JSeparator getJSeparator2() { - if (ivjJSeparator2 == null) { - try { - ivjJSeparator2 = new javax.swing.JSeparator(); - ivjJSeparator2.setName("JSeparator2"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJSeparator2; -} -/** - * Return the labelBestXS property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -/*private javax.swing.JLabel getlabelBestXS() { - if (ivjlabelBestXS == null) { - try { - ivjlabelBestXS = new javax.swing.JLabel(); - ivjlabelBestXS.setName("labelBestXS"); - ivjlabelBestXS.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelBestXS.setText(""); - ivjlabelBestXS.setBounds(312, 10, 24, 14); - ivjlabelBestXS.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelBestXS; -}*/ -/** - * Return the labelBME property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelBME() { - if (ivjlabelBME == null) { - try { - ivjlabelBME = new javax.swing.JLabel(); - ivjlabelBME.setName("labelBME"); - ivjlabelBME.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelBME.setText("* Final Breach Elevation (BME in FT MSL)"); - ivjlabelBME.setBounds(13, 227, 226, 14); - ivjlabelBME.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelBME; -} -/** - * Return the labelBW property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelBW() { - if (ivjlabelBW == null) { - try { - ivjlabelBW = new javax.swing.JLabel(); - ivjlabelBW.setName("labelBW"); - ivjlabelBW.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelBW.setText("Final Breach Width (BW in FT)"); - ivjlabelBW.setBounds(13, 307, 226, 14); - ivjlabelBW.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelBW; -} -/** - * Return the labelCMS property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelCMS() { - if (ivjlabelCMS == null) { - try { - ivjlabelCMS = new javax.swing.JLabel(); - ivjlabelCMS.setName("labelCMS"); - ivjlabelCMS.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelCMS.setText("Dead Storage Equivalent Mann. N (CMS)"); - ivjlabelCMS.setBounds(13, 413, 226, 14); - ivjlabelCMS.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelCMS; -} -/** - * Return the labelDamName property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelDamName() { - if (ivjlabelDamName == null) { - try { - ivjlabelDamName = new javax.swing.JLabel(); - ivjlabelDamName.setName("labelDamName"); - ivjlabelDamName.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelDamName.setText("* Dam Name"); - ivjlabelDamName.setBounds(17, 15, 124, 14); - ivjlabelDamName.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelDamName; -} -/** - * Return the labelDBUG property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelDBUG() { - if (ivjlabelDBUG == null) { - try { - ivjlabelDBUG = new javax.swing.JLabel(); - ivjlabelDBUG.setName("labelDBUG"); - ivjlabelDBUG.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelDBUG.setText("SMPDBK Debug Option"); - ivjlabelDBUG.setBounds(13, 440, 226, 14); - ivjlabelDBUG.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelDBUG; -} -/** - * Return the labelDISTTN property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelDISTTN() { - if (ivjlabelDISTTN == null) { - try { - ivjlabelDISTTN = new javax.swing.JLabel(); - ivjlabelDISTTN.setName("labelDISTTN"); - ivjlabelDISTTN.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelDISTTN.setText("Distance to PT of Interest (DISTTN in MILES)"); - ivjlabelDISTTN.setBounds(13, 386, 226, 14); - ivjlabelDISTTN.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelDISTTN; -} -/** - * Return the labelHDE property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelHDE() { - if (ivjlabelHDE == null) { - try { - ivjlabelHDE = new javax.swing.JLabel(); - ivjlabelHDE.setName("labelHDE"); - ivjlabelHDE.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelHDE.setText("* Dam Breach Elevation (HDE in FT MSL)"); - ivjlabelHDE.setBounds(13, 199, 226, 14); - ivjlabelHDE.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelHDE; -} -/** - * Return the labelPPOI property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelPPOI() { - if (ivjlabelPPOI == null) { - try { - ivjlabelPPOI = new javax.swing.JLabel(); - ivjlabelPPOI.setName("labelPPOI"); - ivjlabelPPOI.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelPPOI.setText("Primary Point of Interest"); - ivjlabelPPOI.setBounds(17, 68, 124, 14); - ivjlabelPPOI.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelPPOI; -} -/** - * Return the labelQO property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelQO() { - if (ivjlabelQO == null) { - try { - ivjlabelQO = new javax.swing.JLabel(); - ivjlabelQO.setName("labelQO"); - ivjlabelQO.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelQO.setText("* Non Breach Flow (QO in CFS)"); - ivjlabelQO.setBounds(13, 361, 226, 14); - ivjlabelQO.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelQO; -} -/** - * Return the labelRequiredFieldsNotice property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelRequiredFieldsNotice() { - if (ivjlabelRequiredFieldsNotice == null) { - try { - ivjlabelRequiredFieldsNotice = new javax.swing.JLabel(); - ivjlabelRequiredFieldsNotice.setName("labelRequiredFieldsNotice"); - ivjlabelRequiredFieldsNotice.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelRequiredFieldsNotice.setText("Fields with a (*) are required. Also, either VOL or SA must be filled in."); - ivjlabelRequiredFieldsNotice.setBounds(17, 464, 352, 14); - ivjlabelRequiredFieldsNotice.setForeground(java.awt.Color.red); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelRequiredFieldsNotice; -} -/** - * Return the labelRiverName property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelRiverName() { - if (ivjlabelRiverName == null) { - try { - ivjlabelRiverName = new javax.swing.JLabel(); - ivjlabelRiverName.setName("labelRiverName"); - ivjlabelRiverName.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelRiverName.setText("* River Name"); - ivjlabelRiverName.setBounds(17, 42, 124, 14); - ivjlabelRiverName.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelRiverName; -} -/** - * Return the labelSA property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelSA() { - if (ivjlabelSA == null) { - try { - ivjlabelSA = new javax.swing.JLabel(); - ivjlabelSA.setName("labelSA"); - ivjlabelSA.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelSA.setText("Surface Area of Reservoir (SA in ACRES)"); - ivjlabelSA.setBounds(13, 280, 226, 14); - ivjlabelSA.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelSA; -} -/** - * Return the labelScenario property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelScenario() { - if (ivjlabelScenario == null) { - try { - ivjlabelScenario = new javax.swing.JLabel(); - ivjlabelScenario.setName("labelScenario"); - ivjlabelScenario.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelScenario.setText("* Scenario"); - ivjlabelScenario.setBounds(12, 145, 80, 14); - ivjlabelScenario.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelScenario; -} -/** - * Return the labelScenarioList property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelScenarioList() { - if (ivjlabelScenarioList == null) { - try { - ivjlabelScenarioList = new javax.swing.JLabel(); - ivjlabelScenarioList.setName("labelScenarioList"); - ivjlabelScenarioList.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelScenarioList.setText("Scenario List:"); - ivjlabelScenarioList.setBounds(14, 12, 116, 14); - ivjlabelScenarioList.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelScenarioList; -} -/** - * Return the labelFloodFlow1 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelSectionType() { - if (ivjlabelSectionType == null) { - try { - ivjlabelSectionType = new javax.swing.JLabel(); - ivjlabelSectionType.setName("labelSectionType"); - ivjlabelSectionType.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelSectionType.setText("Cross Section Type"); - ivjlabelSectionType.setBounds(13, 97, 112, 14); - ivjlabelSectionType.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelSectionType; -} -/** - * Return the labelSource property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelSource() { - if (ivjlabelSource == null) { - try { - ivjlabelSource = new javax.swing.JLabel(); - ivjlabelSource.setName("labelSource"); - ivjlabelSource.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelSource.setText("* Source"); - ivjlabelSource.setBounds(12, 119, 80, 14); - ivjlabelSource.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelSource; -} -/** - * Return the labelTFM property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelTFM() { - if (ivjlabelTFM == null) { - try { - ivjlabelTFM = new javax.swing.JLabel(); - ivjlabelTFM.setName("labelTFM"); - ivjlabelTFM.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelTFM.setText("Time of Dam Failure (TFM in MINUTES)"); - ivjlabelTFM.setBounds(13, 333, 226, 14); - ivjlabelTFM.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelTFM; -} -/** - * Return the labelTypeOfDam property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelTypeOfDam() { - if (ivjlabelTypeOfDam == null) { - try { - ivjlabelTypeOfDam = new javax.swing.JLabel(); - ivjlabelTypeOfDam.setName("labelTypeOfDam"); - ivjlabelTypeOfDam.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelTypeOfDam.setText("* Type Of Dam"); - ivjlabelTypeOfDam.setBounds(13, 172, 226, 14); - ivjlabelTypeOfDam.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelTypeOfDam; -} -/** - * Return the labelVolume property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelVolume() { - if (ivjlabelVolume == null) { - try { - ivjlabelVolume = new javax.swing.JLabel(); - ivjlabelVolume.setName("labelVolume"); - ivjlabelVolume.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelVolume.setText("Volume of Reservoir (VOL in ACRE-FT)"); - ivjlabelVolume.setBounds(13, 253, 226, 14); - ivjlabelVolume.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelVolume; -} -/** - * Return the labelXSDistance property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSDistance() { - if (ivjlabelXSDistance == null) { - try { - ivjlabelXSDistance = new javax.swing.JLabel(); - ivjlabelXSDistance.setName("labelXSDistance"); - ivjlabelXSDistance.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSDistance.setText("Distance From Dam to Section (MILES)"); - ivjlabelXSDistance.setBounds(19, 154, 198, 14); - ivjlabelXSDistance.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSDistance; -} -/** - * Return the labelXSFloodDepth property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSFloodDepth() { - if (ivjlabelXSFloodDepth == null) { - try { - ivjlabelXSFloodDepth = new javax.swing.JLabel(); - ivjlabelXSFloodDepth.setName("labelXSFloodDepth"); - ivjlabelXSFloodDepth.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSFloodDepth.setText("Flood Depth (FT)"); - ivjlabelXSFloodDepth.setBounds(20, 183, 132, 14); - ivjlabelXSFloodDepth.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSFloodDepth; -} -/** - * Return the labelFloodFlow property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSFloodFlow() { - if (ivjlabelXSFloodFlow == null) { - try { - ivjlabelXSFloodFlow = new javax.swing.JLabel(); - ivjlabelXSFloodFlow.setName("labelXSFloodFlow"); - ivjlabelXSFloodFlow.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSFloodFlow.setText("Flow At Flood Stage (CFS)"); - ivjlabelXSFloodFlow.setBounds(19, 214, 135, 14); - ivjlabelXSFloodFlow.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSFloodFlow; -} -/** - * Return the labelXSLatitutde property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSLatitutde() { - if (ivjlabelXSLatitutde == null) { - try { - ivjlabelXSLatitutde = new javax.swing.JLabel(); - ivjlabelXSLatitutde.setName("labelXSLatitutde"); - ivjlabelXSLatitutde.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSLatitutde.setText("Latitude"); - ivjlabelXSLatitutde.setBounds(20, 244, 58, 14); - ivjlabelXSLatitutde.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSLatitutde; -} -/** - * Return the labelXSList property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSList() { - if (ivjlabelXSList == null) { - try { - ivjlabelXSList = new javax.swing.JLabel(); - ivjlabelXSList.setName("labelXSList"); - ivjlabelXSList.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSList.setText("Downstream Point List:"); - ivjlabelXSList.setBounds(13, 10, 116, 14); - ivjlabelXSList.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSList; -} -/** - * Return the labelXSList1 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSList1() { - if (ivjlabelXSList1 == null) { - try { - ivjlabelXSList1 = new javax.swing.JLabel(); - ivjlabelXSList1.setName("labelXSList1"); - ivjlabelXSList1.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSList1.setText("Cross Section List:"); - ivjlabelXSList1.setBounds(8, 9, 142, 14); - ivjlabelXSList1.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSList1; -} -/** - * Return the labelXSList11 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSList11() { - if (ivjlabelXSList11 == null) { - try { - ivjlabelXSList11 = new javax.swing.JLabel(); - ivjlabelXSList11.setName("labelXSList11"); - ivjlabelXSList11.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSList11.setText("Best Section Type: "); - ivjlabelXSList11.setBounds(19, 300, 118, 14); - ivjlabelXSList11.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSList11; -} -/** - * Return the labelXSLongitude property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSLongitude() { - if (ivjlabelXSLongitude == null) { - try { - ivjlabelXSLongitude = new javax.swing.JLabel(); - ivjlabelXSLongitude.setName("labelXSLongitude"); - ivjlabelXSLongitude.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSLongitude.setText("Longitude"); - ivjlabelXSLongitude.setBounds(19, 274, 66, 14); - ivjlabelXSLongitude.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSLongitude; -} -/** - * Return the labelXSName property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getlabelXSName() { - if (ivjlabelXSName == null) { - try { - ivjlabelXSName = new javax.swing.JLabel(); - ivjlabelXSName.setName("labelXSName"); - ivjlabelXSName.setFont(new java.awt.Font("Arial", 1, 10)); - ivjlabelXSName.setText("Downstream Point Name"); - ivjlabelXSName.setBounds(18, 125, 198, 14); - ivjlabelXSName.setForeground(java.awt.Color.black); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlabelXSName; -} -/** - * Return the listXSList property value. - * @return javax.swing.JList - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JList getListDown() { - if (ivjListDown == null) { - try { - ivjListDown = new javax.swing.JList(); - ivjListDown.setName("ListDown"); - ivjListDown.setBounds(0, 0, 160, 120); - ivjListDown.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjListDown; -} -/** - * Return the listModelDown property value. - * @return javax.swing.DefaultListModel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.DefaultListModel getlistModelDown() { - if (ivjlistModelDown == null) { - try { - ivjlistModelDown = new javax.swing.DefaultListModel(); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlistModelDown; -} -/** - * Return the listModelScenario property value. - * @return javax.swing.DefaultListModel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.DefaultListModel getlistModelScenario() { - if (ivjlistModelScenario == null) { - try { - ivjlistModelScenario = new javax.swing.DefaultListModel(); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlistModelScenario; -} -/** - * Return the listModelXS property value. - * @return javax.swing.DefaultListModel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.DefaultListModel getlistModelXS() { - if (ivjlistModelXS == null) { - try { - ivjlistModelXS = new javax.swing.DefaultListModel(); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjlistModelXS; -} -/** - * Return the listScenarioList property value. - * @return javax.swing.JList - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JList getListScenario() { - if (ivjListScenario == null) { - try { - ivjListScenario = new javax.swing.JList(); - ivjListScenario.setName("ListScenario"); - ivjListScenario.setBounds(0, 0, 160, 120); - ivjListScenario.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjListScenario; -} -/** - * Return the listXSList1 property value. - * @return javax.swing.JList - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JList getListXS() { - if (ivjListXS == null) { - try { - ivjListXS = new javax.swing.JList(); - ivjListXS.setName("ListXS"); - ivjListXS.setBounds(0, 0, 160, 120); - ivjListXS.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjListXS; -} -/** - * Return the menuAbout property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuAbout() { - if (ivjmenuAbout == null) { - try { - ivjmenuAbout = new javax.swing.JMenuItem(); - ivjmenuAbout.setName("menuAbout"); - ivjmenuAbout.setMnemonic('a'); - ivjmenuAbout.setText("About SMPDBK..."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuAbout; -} -/** - * Return the menuClose property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuClose() { - if (ivjmenuClose == null) { - try { - ivjmenuClose = new javax.swing.JMenuItem(); - ivjmenuClose.setName("menuClose"); - ivjmenuClose.setMnemonic('c'); - ivjmenuClose.setText("Close"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuClose; -} -/** - * Return the menuDatabase property value. - * @return javax.swing.JMenu - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenu getmenuDatabase() { - if (ivjmenuDatabase == null) { - try { - ivjmenuDatabase = new javax.swing.JMenu(); - ivjmenuDatabase.setName("menuDatabase"); - ivjmenuDatabase.setMnemonic('d'); - ivjmenuDatabase.setText("Database"); - ivjmenuDatabase.add(getmenuUpdateDatabase()); - ivjmenuDatabase.add(getmenuClose()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuDatabase; -} -/** - * Return the menuDisplayOutput property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuDisplayOutput() { - if (ivjmenuDisplayOutput == null) { - try { - ivjmenuDisplayOutput = new javax.swing.JMenuItem(); - ivjmenuDisplayOutput.setName("menuDisplayOutput"); - ivjmenuDisplayOutput.setMnemonic('D'); - ivjmenuDisplayOutput.setText("Display SMPDBK Output"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuDisplayOutput; -} -/** - * Return the menuEdit property value. - * @return javax.swing.JMenu - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenu getmenuEdit() { - if (ivjmenuEdit == null) { - try { - ivjmenuEdit = new javax.swing.JMenu(); - ivjmenuEdit.setName("menuEdit"); - ivjmenuEdit.setMnemonic('e'); - ivjmenuEdit.setText("Edit"); - ivjmenuEdit.add(getmenuEditText()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuEdit; -} -/** - * Return the menuEditText property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuEditText() { - if (ivjmenuEditText == null) { - try { - ivjmenuEditText = new javax.swing.JMenuItem(); - ivjmenuEditText.setName("menuEditText"); - ivjmenuEditText.setMnemonic('e'); - ivjmenuEditText.setText("Edit Text File"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuEditText; -} -/** - * Return the menuFile property value. - * @return javax.swing.JMenu - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenu getmenuFile() { - if (ivjmenuFile == null) { - try { - ivjmenuFile = new javax.swing.JMenu(); - ivjmenuFile.setName("menuFile"); - ivjmenuFile.setMnemonic('f'); - ivjmenuFile.setText("File"); - ivjmenuFile.add(getmenuNew()); - ivjmenuFile.add(getmenuOpen()); - ivjmenuFile.add(getmenuSave()); - ivjmenuFile.add(getmenuSaveAs()); - ivjmenuFile.add(getJSeparator1()); - ivjmenuFile.add(getmenuImportFLDXS()); - ivjmenuFile.add(getmenuImportDAT()); - ivjmenuFile.add(getJSeparator2()); - ivjmenuFile.add(getmenuQuit()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuFile; -} -/** - * Return the menuHelp property value. - * @return javax.swing.JMenu - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenu getmenuHelp() { - if (ivjmenuHelp == null) { - try { - ivjmenuHelp = new javax.swing.JMenu(); - ivjmenuHelp.setName("menuHelp"); - ivjmenuHelp.setMnemonic('h'); - ivjmenuHelp.setText("Help"); - ivjmenuHelp.add(getmenuAbout()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuHelp; -} -/** - * Return the menuImportDAT property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuImportDAT() { - if (ivjmenuImportDAT == null) { - try { - ivjmenuImportDAT = new javax.swing.JMenuItem(); - ivjmenuImportDAT.setName("menuImportDAT"); - ivjmenuImportDAT.setMnemonic('d'); - ivjmenuImportDAT.setText("Import SMPDBK input file"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuImportDAT; -} -/** - * Return the menuImportFLDXS property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuImportFLDXS() { - if (ivjmenuImportFLDXS == null) { - try { - ivjmenuImportFLDXS = new javax.swing.JMenuItem(); - ivjmenuImportFLDXS.setName("menuImportFLDXS"); - ivjmenuImportFLDXS.setMnemonic('X'); - ivjmenuImportFLDXS.setText("Import FLDXS Cross Sections"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuImportFLDXS; -} -/** - * Return the menuNew property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuNew() { - if (ivjmenuNew == null) { - try { - ivjmenuNew = new javax.swing.JMenuItem(); - ivjmenuNew.setName("menuNew"); - ivjmenuNew.setMnemonic('n'); - ivjmenuNew.setText("New"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuNew; -} -/** - * Return the menuOpen property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuOpen() { - if (ivjmenuOpen == null) { - try { - ivjmenuOpen = new javax.swing.JMenuItem(); - ivjmenuOpen.setName("menuOpen"); - ivjmenuOpen.setMnemonic('o'); - ivjmenuOpen.setText("Open..."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuOpen; -} -/** - * Return the menuQuit property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuQuit() { - if (ivjmenuQuit == null) { - try { - ivjmenuQuit = new javax.swing.JMenuItem(); - ivjmenuQuit.setName("menuQuit"); - ivjmenuQuit.setMnemonic('q'); - ivjmenuQuit.setText("Quit"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuQuit; -} -/** - * Insert the method's description here. - * Creation date: (9/8/2003 9:10:37 AM) - * @return javax.swing.JMenuItem - */ -private JMenuItem getmenuRun_Scenario() { - return null; -} -/** - * Return the menuOutputManager property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -public javax.swing.JMenuItem getmenuRun_SMPDBK() { - if (ivjmenuRun_SMPDBK == null) { - try { - ivjmenuRun_SMPDBK = new javax.swing.JMenuItem(); - ivjmenuRun_SMPDBK.setName("menuRun_SMPDBK"); - ivjmenuRun_SMPDBK.setMnemonic('R'); - ivjmenuRun_SMPDBK.setText("Run SMPDBK"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuRun_SMPDBK; -} -/** - * Return the menuSave property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuSave() { - if (ivjmenuSave == null) { - try { - ivjmenuSave = new javax.swing.JMenuItem(); - ivjmenuSave.setName("menuSave"); - ivjmenuSave.setMnemonic('s'); - ivjmenuSave.setText("Save"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuSave; -} -/** - * Return the menuSaveAs property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuSaveAs() { - if (ivjmenuSaveAs == null) { - try { - ivjmenuSaveAs = new javax.swing.JMenuItem(); - ivjmenuSaveAs.setName("menuSaveAs"); - ivjmenuSaveAs.setMnemonic('a'); - ivjmenuSaveAs.setText("Save As..."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuSaveAs; -} -/** - * Return the menuSMPDBK property value. - * @return javax.swing.JMenu - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenu getmenuSMPDBK() { - if (ivjmenuSMPDBK == null) { - try { - ivjmenuSMPDBK = new javax.swing.JMenu(); - ivjmenuSMPDBK.setName("menuSMPDBK"); - ivjmenuSMPDBK.setMnemonic('m'); - ivjmenuSMPDBK.setText("Model"); - ivjmenuSMPDBK.add(getmenuRun_SMPDBK()); - ivjmenuSMPDBK.add(getmenuDisplayOutput()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuSMPDBK; -} -/** - * Return the menuUpdateDatabase property value. - * @return javax.swing.JMenuItem - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuItem getmenuUpdateDatabase() { - if (ivjmenuUpdateDatabase == null) { - try { - ivjmenuUpdateDatabase = new javax.swing.JMenuItem(); - ivjmenuUpdateDatabase.setName("menuUpdateDatabase"); - ivjmenuUpdateDatabase.setMnemonic('u'); - ivjmenuUpdateDatabase.setText("Update Database"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjmenuUpdateDatabase; -} -/** - * Return the ModelGUIJMenuBar property value. - * @return javax.swing.JMenuBar - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JMenuBar getModelGUIJMenuBar() { - if (ivjModelGUIJMenuBar == null) { - try { - ivjModelGUIJMenuBar = new javax.swing.JMenuBar(); - ivjModelGUIJMenuBar.setName("ModelGUIJMenuBar"); - ivjModelGUIJMenuBar.add(getmenuFile()); - ivjModelGUIJMenuBar.add(getmenuDatabase()); - ivjModelGUIJMenuBar.add(getmenuSMPDBK()); - ivjModelGUIJMenuBar.add(getmenuEdit()); - ivjModelGUIJMenuBar.add(getmenuHelp()); - // user code begin {1} - if (bHasDatabase) - ivjModelGUIJMenuBar.remove(getmenuFile()); - else - ivjModelGUIJMenuBar.remove(getmenuDatabase()); - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjModelGUIJMenuBar; -} -/** - * Return the panelDamInfo property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getpanelDamInfo() { - if (ivjpanelDamInfo == null) { - try { - ivjpanelDamInfo = new javax.swing.JPanel(); - ivjpanelDamInfo.setName("panelDamInfo"); - ivjpanelDamInfo.setBorder(new javax.swing.border.EtchedBorder()); - ivjpanelDamInfo.setLayout(null); - ivjpanelDamInfo.setBackground(new java.awt.Color(234,223,246)); - ivjpanelDamInfo.setBounds(1, 103, 387, 488); - getpanelDamInfo().add(getlabelScenarioList(), getlabelScenarioList().getName()); - getpanelDamInfo().add(getscrollScenarioList(), getscrollScenarioList().getName()); - getpanelDamInfo().add(getlabelSource(), getlabelSource().getName()); - getpanelDamInfo().add(getlabelScenario(), getlabelScenario().getName()); - getpanelDamInfo().add(getlabelTypeOfDam(), getlabelTypeOfDam().getName()); - getpanelDamInfo().add(getlabelHDE(), getlabelHDE().getName()); - getpanelDamInfo().add(getlabelBME(), getlabelBME().getName()); - getpanelDamInfo().add(getlabelVolume(), getlabelVolume().getName()); - getpanelDamInfo().add(getlabelSA(), getlabelSA().getName()); - getpanelDamInfo().add(getlabelBW(), getlabelBW().getName()); - getpanelDamInfo().add(getlabelTFM(), getlabelTFM().getName()); - getpanelDamInfo().add(getlabelQO(), getlabelQO().getName()); - getpanelDamInfo().add(getlabelDISTTN(), getlabelDISTTN().getName()); - getpanelDamInfo().add(getlabelCMS(), getlabelCMS().getName()); - getpanelDamInfo().add(getlabelRequiredFieldsNotice(), getlabelRequiredFieldsNotice().getName()); - getpanelDamInfo().add(gettextSource(), gettextSource().getName()); - getpanelDamInfo().add(getcomboScenario(), getcomboScenario().getName()); - getpanelDamInfo().add(getcomboTypeOfDam(), getcomboTypeOfDam().getName()); - getpanelDamInfo().add(gettextHDE(), gettextHDE().getName()); - getpanelDamInfo().add(gettextBME(), gettextBME().getName()); - getpanelDamInfo().add(gettextVOL(), gettextVOL().getName()); - getpanelDamInfo().add(gettextSA(), gettextSA().getName()); - getpanelDamInfo().add(gettextBW(), gettextBW().getName()); - getpanelDamInfo().add(gettextTFM(), gettextTFM().getName()); - getpanelDamInfo().add(gettextQO(), gettextQO().getName()); - getpanelDamInfo().add(gettextDISTTN(), gettextDISTTN().getName()); - getpanelDamInfo().add(gettextCMS(), gettextCMS().getName()); - getpanelDamInfo().add(getlabelDBUG(), getlabelDBUG().getName()); - getpanelDamInfo().add(getcomboDBUG(), getcomboDBUG().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelDamInfo; -} -/** - * Return the panelXSInfo property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getpanelDownstreamInfo() { - if (ivjpanelDownstreamInfo == null) { - try { - ivjpanelDownstreamInfo = new javax.swing.JPanel(); - ivjpanelDownstreamInfo.setName("panelDownstreamInfo"); - ivjpanelDownstreamInfo.setBorder(new javax.swing.border.EtchedBorder()); - ivjpanelDownstreamInfo.setLayout(null); - ivjpanelDownstreamInfo.setBackground(new java.awt.Color(236,243,255)); - ivjpanelDownstreamInfo.setBounds(389, 5, 368, 586); - getpanelDownstreamInfo().add(getlabelXSList(), getlabelXSList().getName()); - getpanelDownstreamInfo().add(getscrollXSList(), getscrollXSList().getName()); - getpanelDownstreamInfo().add(getlabelXSName(), getlabelXSName().getName()); - getpanelDownstreamInfo().add(getlabelXSDistance(), getlabelXSDistance().getName()); - getpanelDownstreamInfo().add(getlabelXSFloodDepth(), getlabelXSFloodDepth().getName()); - getpanelDownstreamInfo().add(getlabelXSFloodFlow(), getlabelXSFloodFlow().getName()); - getpanelDownstreamInfo().add(getlabelXSLatitutde(), getlabelXSLatitutde().getName()); - getpanelDownstreamInfo().add(getlabelXSLongitude(), getlabelXSLongitude().getName()); - getpanelDownstreamInfo().add(gettextName(), gettextName().getName()); - getpanelDownstreamInfo().add(gettextDistance(), gettextDistance().getName()); - getpanelDownstreamInfo().add(gettextFloodDepth(), gettextFloodDepth().getName()); - getpanelDownstreamInfo().add(gettextFloodFlow(), gettextFloodFlow().getName()); - getpanelDownstreamInfo().add(gettextLatitude(), gettextLatitude().getName()); - getpanelDownstreamInfo().add(gettextLongitude(), gettextLongitude().getName()); - getpanelDownstreamInfo().add(getpanelXS(), getpanelXS().getName()); - getpanelDownstreamInfo().add(getlabelXSList11(), getlabelXSList11().getName()); - getpanelDownstreamInfo().add(getcomboBestXS(), getcomboBestXS().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelDownstreamInfo; -} -/** - * Return the panelDamInfo1 property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getpanelNameInfo() { - if (ivjpanelNameInfo == null) { - try { - ivjpanelNameInfo = new javax.swing.JPanel(); - ivjpanelNameInfo.setName("panelNameInfo"); - ivjpanelNameInfo.setBorder(new javax.swing.border.EtchedBorder()); - ivjpanelNameInfo.setLayout(null); - ivjpanelNameInfo.setBackground(new java.awt.Color(227,228,235)); - ivjpanelNameInfo.setBounds(1, 5, 387, 97); - getpanelNameInfo().add(getlabelDamName(), getlabelDamName().getName()); - getpanelNameInfo().add(getlabelRiverName(), getlabelRiverName().getName()); - getpanelNameInfo().add(getlabelPPOI(), getlabelPPOI().getName()); - getpanelNameInfo().add(gettextDamName(), gettextDamName().getName()); - getpanelNameInfo().add(gettextRiverName(), gettextRiverName().getName()); - getpanelNameInfo().add(gettextPPOI(), gettextPPOI().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelNameInfo; -} -/** - * Return the JPanel1 property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getpanelXS() { - if (ivjpanelXS == null) { - try { - ivjpanelXS = new javax.swing.JPanel(); - ivjpanelXS.setName("panelXS"); - ivjpanelXS.setBorder(new javax.swing.border.EtchedBorder()); - ivjpanelXS.setLayout(null); - ivjpanelXS.setBackground(new java.awt.Color(164,218,204)); - ivjpanelXS.setBounds(10, 324, 347, 255); - getpanelXS().add(getlabelXSList1(), getlabelXSList1().getName()); - getpanelXS().add(getscrollXSList1(), getscrollXSList1().getName()); - getpanelXS().add(getlabelSectionType(), getlabelSectionType().getName()); - getpanelXS().add(getcomboXSType(), getcomboXSType().getName()); - getpanelXS().add(getscrollXSData(), getscrollXSData().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelXS; -} -/** - * Return the scrollScenarioList property value. - * @return javax.swing.JScrollPane - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JScrollPane getscrollScenarioList() { - if (ivjscrollScenarioList == null) { - try { - ivjscrollScenarioList = new javax.swing.JScrollPane(); - ivjscrollScenarioList.setName("scrollScenarioList"); - ivjscrollScenarioList.setBounds(16, 34, 354, 77); - getscrollScenarioList().setViewportView(getListScenario()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollScenarioList; -} -/** - * Return the scrollXSData property value. - * @return javax.swing.JScrollPane - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JScrollPane getscrollXSData() { - if (ivjscrollXSData == null) { - try { - ivjscrollXSData = new javax.swing.JScrollPane(); - ivjscrollXSData.setName("scrollXSData"); - ivjscrollXSData.setBounds(7, 124, 333, 138); - ivjscrollXSData.setEnabled(false); - getscrollXSData().setViewportView(gettableXSData()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollXSData; -} -/** - * Return the scrollXSList property value. - * @return javax.swing.JScrollPane - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JScrollPane getscrollXSList() { - if (ivjscrollXSList == null) { - try { - ivjscrollXSList = new javax.swing.JScrollPane(); - ivjscrollXSList.setName("scrollXSList"); - ivjscrollXSList.setBounds(15, 32, 340, 74); - getscrollXSList().setViewportView(getListDown()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollXSList; -} -/** - * Return the scrollXSList1 property value. - * @return javax.swing.JScrollPane - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JScrollPane getscrollXSList1() { - if (ivjscrollXSList1 == null) { - try { - ivjscrollXSList1 = new javax.swing.JScrollPane(); - ivjscrollXSList1.setName("scrollXSList1"); - ivjscrollXSList1.setBounds(10, 28, 326, 57); - getscrollXSList1().setViewportView(getListXS()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjscrollXSList1; -} -/** - * Return the tableModelXSGeom property value. - * @return javax.swing.table.DefaultTableModel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.table.DefaultTableModel gettableModelXSGeom() { - if (ivjtableModelXSGeom == null) { - try { - ivjtableModelXSGeom = new javax.swing.table.DefaultTableModel(); - // user code begin {1} - ivjtableModelXSGeom = new javax.swing.table.DefaultTableModel(8,4); - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtableModelXSGeom; -} -/** - * Return the tableXSData property value. - * @return javax.swing.JTable - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTable gettableXSData() { - if (ivjtableXSData == null) { - try { - ivjtableXSData = new javax.swing.JTable(); - ivjtableXSData.setName("tableXSData"); - getscrollXSData().setColumnHeaderView(ivjtableXSData.getTableHeader()); - getscrollXSData().getViewport().setBackingStoreEnabled(true); - ivjtableXSData.setBounds(0, 0, 332, 136); - ivjtableXSData.setEnabled(false); - ivjtableXSData.setAutoCreateColumnsFromModel(false); - ivjtableXSData.addColumn(getcolumnElevation()); - ivjtableXSData.addColumn(getcolumnBS()); - ivjtableXSData.addColumn(getcolumnBSS()); - ivjtableXSData.addColumn(getcolumnMannN()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtableXSData; -} -/** - * Return the textBME property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextBME() { - if (ivjtextBME == null) { - try { - ivjtextBME = new javax.swing.JTextField(); - ivjtextBME.setName("textBME"); - ivjtextBME.setBounds(245, 222, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextBME; -} -/** - * Return the textBW property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextBW() { - if (ivjtextBW == null) { - try { - ivjtextBW = new javax.swing.JTextField(); - ivjtextBW.setName("textBW"); - ivjtextBW.setBounds(245, 303, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextBW; -} -/** - * Return the textCMS property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextCMS() { - if (ivjtextCMS == null) { - try { - ivjtextCMS = new javax.swing.JTextField(); - ivjtextCMS.setName("textCMS"); - ivjtextCMS.setBounds(245, 411, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextCMS; -} -/** - * Return the textDamName property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextDamName() { - if (ivjtextDamName == null) { - try { - ivjtextDamName = new javax.swing.JTextField(); - ivjtextDamName.setName("textDamName"); - ivjtextDamName.setDocument(new MaxLengthDocument(40)); - ivjtextDamName.setBounds(145, 12, 229, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextDamName; -} -/** - * Return the textXSDistance property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextDistance() { - if (ivjtextDistance == null) { - try { - ivjtextDistance = new javax.swing.JTextField(); - ivjtextDistance.setName("textDistance"); - ivjtextDistance.setBounds(221, 152, 128, 20); - ivjtextDistance.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextDistance; -} -/** - * Return the textDISTTN property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextDISTTN() { - if (ivjtextDISTTN == null) { - try { - ivjtextDISTTN = new javax.swing.JTextField(); - ivjtextDISTTN.setName("textDISTTN"); - ivjtextDISTTN.setBounds(245, 384, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextDISTTN; -} -/** - * Return the textXSFloodDepth property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextFloodDepth() { - if (ivjtextFloodDepth == null) { - try { - ivjtextFloodDepth = new javax.swing.JTextField(); - ivjtextFloodDepth.setName("textFloodDepth"); - ivjtextFloodDepth.setBounds(222, 180, 128, 20); - ivjtextFloodDepth.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextFloodDepth; -} -/** - * Return the textFloodFlow property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextFloodFlow() { - if (ivjtextFloodFlow == null) { - try { - ivjtextFloodFlow = new javax.swing.JTextField(); - ivjtextFloodFlow.setName("textFloodFlow"); - ivjtextFloodFlow.setBounds(221, 210, 128, 20); - ivjtextFloodFlow.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextFloodFlow; -} -/** - * Return the textHDE property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextHDE() { - if (ivjtextHDE == null) { - try { - ivjtextHDE = new javax.swing.JTextField(); - ivjtextHDE.setName("textHDE"); - ivjtextHDE.setBounds(245, 195, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextHDE; -} -/** - * Return the textXSLatitude property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextLatitude() { - if (ivjtextLatitude == null) { - try { - ivjtextLatitude = new javax.swing.JTextField(); - ivjtextLatitude.setName("textLatitude"); - ivjtextLatitude.setBounds(222, 241, 128, 20); - ivjtextLatitude.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextLatitude; -} -/** - * Return the textXSLongitude property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextLongitude() { - if (ivjtextLongitude == null) { - try { - ivjtextLongitude = new javax.swing.JTextField(); - ivjtextLongitude.setName("textLongitude"); - ivjtextLongitude.setBounds(221, 270, 128, 20); - ivjtextLongitude.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextLongitude; -} -/** - * Return the textXSName property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextName() { - if (ivjtextName == null) { - try { - ivjtextName = new javax.swing.JTextField(); - ivjtextName.setName("textName"); - ivjtextName.setBounds(220, 123, 128, 20); - ivjtextName.setEnabled(false); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextName; -} -/** - * Return the textPPOI property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextPPOI() { - if (ivjtextPPOI == null) { - try { - ivjtextPPOI = new javax.swing.JTextField(); - ivjtextPPOI.setName("textPPOI"); - ivjtextPPOI.setDocument(new MaxLengthDocument(25)); - ivjtextPPOI.setBounds(145, 66, 229, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextPPOI; -} -/** - * Return the textQO property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextQO() { - if (ivjtextQO == null) { - try { - ivjtextQO = new javax.swing.JTextField(); - ivjtextQO.setName("textQO"); - ivjtextQO.setBounds(245, 357, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextQO; -} -/** - * Return the textRiverName property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextRiverName() { - if (ivjtextRiverName == null) { - try { - ivjtextRiverName = new javax.swing.JTextField(); - ivjtextRiverName.setName("textRiverName"); - ivjtextRiverName.setDocument(new MaxLengthDocument(40)); - ivjtextRiverName.setBounds(145, 39, 229, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextRiverName; -} -/** - * Return the textSA property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextSA() { - if (ivjtextSA == null) { - try { - ivjtextSA = new javax.swing.JTextField(); - ivjtextSA.setName("textSA"); - ivjtextSA.setBounds(245, 276, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextSA; -} -/** - * Return the textSource property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextSource() { - if (ivjtextSource == null) { - try { - ivjtextSource = new javax.swing.JTextField(); - ivjtextSource.setName("textSource"); - ivjtextSource.setDocument(new MaxLengthDocument(40)); - ivjtextSource.setBounds(244, 120, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextSource; -} -/** - * Return the textTFM property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextTFM() { - if (ivjtextTFM == null) { - try { - ivjtextTFM = new javax.swing.JTextField(); - ivjtextTFM.setName("textTFM"); - ivjtextTFM.setBounds(245, 330, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextTFM; -} -/** - * Return the textVOL property value. - * @return javax.swing.JTextField - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTextField gettextVOL() { - if (ivjtextVOL == null) { - try { - ivjtextVOL = new javax.swing.JTextField(); - ivjtextVOL.setName("textVOL"); - ivjtextVOL.setBounds(245, 249, 125, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtextVOL; -} -/** - * For DownstreamPoints: - * - * Handle INSERT Key - * - * Handle DELETE or <- (backspace) - */ -private void handleDownListKey(java.awt.event.KeyEvent keyEvent) { - - if (getListDown().getSelectedIndex() == -1 || bHandlingEvent) - { - return; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE || keyEvent.getKeyCode() == KeyEvent.VK_DELETE) - { - bHandlingEvent = true; - - int oldSelection = getListDown().getSelectedIndex(); - - getListDown().clearSelection(); - - // *** move selected DownstreamPoint to deleted ArrayList - DownstreamPoint delDP = (DownstreamPoint) currentData.downstream.get(oldSelection); - currentData.deletedDownstream.add(delDP); - - // *** now remove from primary ArrayList - currentData.downstream.remove(oldSelection); - - updateDownstreamList(); - - clearDownstreamFields(); - enableDownstreamEditors(false); - - bHandlingEvent = false; - } - - - if (keyEvent.getKeyCode() == KeyEvent.VK_INSERT ) - { - bHandlingEvent = true; - - int oldSelection = getListDown().getSelectedIndex() + 1; - - getListDown().clearSelection(); - - createNewDownstreamPoint(oldSelection); - - clearDownstreamFields(); - - enableDownstreamEditors(false); - - bHandlingEvent = false; - } - - return; -} -/** - * invoke updateDownstreamFields if focus lost on key fields - */ -private void handleDownstreamKeyLostFocus() { - - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - if (nDownstreamEditing != -1) - { - updateDownstreamFields(true); - } - - bHandlingEvent = false; - return; -} -/** - * This method is similar to handleScenarioListSelection and handleXSListSelection - */ -private void handleDownstreamListSelection(javax.swing.event.ListSelectionEvent listSelectionEvent) { - - // only process event if the selection is final and no other event is being handled - if (listSelectionEvent.getValueIsAdjusting() || bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - int selectedIndex = getListDown().getSelectedIndex(); - _selectedDownstreamPoint = selectedIndex; - - // save downstream data if data is currently being edited - - // if the data is invalid, stop handling event - if (!updateDownstreamFields(true)) { - JOptionPane.showMessageDialog(this,"The downstream point name and distance pair must be unique.", "Error", JOptionPane.ERROR_MESSAGE); - bHandlingEvent = false; - getListDown().setSelectedIndex(nDownstreamEditing); - _selectedDownstreamPoint = nDownstreamEditing; - return; - } - - // if the selection is being cleared, clear the downstream editors - if (selectedIndex == -1) { - clearDownstreamFields(); - enableDownstreamEditors(false); - bHandlingEvent = false; - return; - } - - // if "Create a new downstream point..." was clicked, create a new downstream point and select it for editing - // if (_DEBUG) System.out.println("Selected D/S Station/point Index: " + getListDown().getSelectedIndex()); - if (selectedIndex == getlistModelDown().getSize()-1) { - - // the SMPDBK model allows a maximum of 50 downstream locations - if (currentData.downstream.size() >= 50) { - Toolkit.getDefaultToolkit().beep(); - bHandlingEvent = false; - getListDown().setSelectedIndex(nDownstreamEditing); - _selectedDownstreamPoint = nDownstreamEditing; - return; - } - - createNewDownstreamPoint(selectedIndex); - } - - // load data for selected downstream point into GUI - updateDownstreamFields(false); - enableDownstreamEditors(true); - - bHandlingEvent = false; // *** selecting XSList will fire new event ! - // *** so turn off bHandlingEvent first ! - - // if there is an XS chosen, select it ! - if (_selectedXSType != -1) - { - getListXS().clearSelection(); - getListXS().setSelectedIndex(_selectedXSType); - } - - -} -/** - * Called whenever the part throws an exception. - * @param exception java.lang.Throwable - */ -private void handleException(java.lang.Throwable exception) { - - /* Uncomment the following lines to print uncaught exceptions to stdout */ - System.out.println("--------- UNCAUGHT EXCEPTION in ModelGUI ---------"); - exception.printStackTrace(System.out); -} -/** - * Comment - */ -private void handleMenuAbout() { - // JOptionPane.showMessageDialog(this,"Dambreak Analysis v1.0 (build 2)\nCraig Austin","About Dambreak Analysis",JOptionPane.INFORMATION_MESSAGE); - JOptionPane.showMessageDialog(this,"Dambreak Analysis v1.0 (Build 5.3 - 06/01/2004)\nby National Weather Service, \n - Office of Hydrologic Development","About Dambreak Analysis",JOptionPane.INFORMATION_MESSAGE); - return; -} -/** - * Comment - */ -private void handleMenuClose() { - handleWindowClosing(); - return; -} -/** - * Insert the method's description here. - * Creation date: (10/3/2003 3:40:14 PM) - */ - public void handleMenuDisplayOutput() { - - JFileChooser fileChooser2 = new JFileChooser(strLastOpenPath); - fileChooser2.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser2.setFileFilter(new DamInputFileFilter(DamInputFileFilter.OUTPUT)); - fileChooser2.setDialogTitle("Select Dambreak Analysis Output File"); - int result = fileChooser2.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return; - - File fileName = fileChooser2.getSelectedFile(); - - if (fileName == null || fileName.getName().equals("")) - JOptionPane.showMessageDialog(this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE); - else { - // set our last opened path - strLastOpenPath = fileName.getPath(); - - if (_DEBUG) System.out.print("in handleMenuDisplayOutput Opening " + fileName.getAbsolutePath() + "...\n"); - - - ModelOutput outFile = ModelOutput.readOUT(fileName.getAbsolutePath()); - if (outFile == null) - JOptionPane.showMessageDialog(this,"Error opening dambreak output file.\n" - + fileName.getAbsolutePath(), "Error", JOptionPane.ERROR_MESSAGE); - else - - // instantiate Analysis Data and copy data from ModelOutput - - currentData = new AnalysisData(); - currentData.importModelOutput(outFile); - - // generateOutput(); // not needed ! - - OutputManager outMan = new OutputManager(this,currentData); - outMan.setTitle("Output Manager - " + fileName.getAbsolutePath()); - - System.out.println("Finished displaying out file."); - - return; - - } - return; -} -/** - * This method needed for editing file via GUI. - * Creation date: (9/26/2003 1:53:13 PM) - */ -private void handleMenuEditText() throws Exception { - Runtime rt = Runtime.getRuntime(); - String dbaEditor = ""; - String runThis = ""; - - JFileChooser fileChooser1 = new JFileChooser(strLastOpenPath); - fileChooser1.setDialogTitle("Select the File to edit"); - int result1 = fileChooser1.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result1 != JFileChooser.APPROVE_OPTION) - return; - - File fileName1 = fileChooser1.getSelectedFile(); - - if (fileName1 == null || fileName1.getName().equals("")) - { - JOptionPane.showMessageDialog(this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE); - } - else - { - runThis = fileName1.getAbsolutePath(); - } - - try - { - dbaEditor = PropertyReader.getProperty("damcrest.editor"); - // System.out.println("Editing a file with " + dbaEditor + " \"" + runThis + "\""); - rt.exec(dbaEditor + " \"" + runThis + "\""); - } - catch (IOException e) - { - // Problem editing the file - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "Cannot edit the file", "Cannot edit the file", JOptionPane.ERROR_MESSAGE); - - } - - return; -} -/** - * This method reads information from a *.DAT file. - * assumed to be in SMPDBK format - */ -private void handleMenuImportFromDAT() { - - handleMenuNew(); - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setFileFilter(new DamInputFileFilter(DamInputFileFilter.DAT_INPUT)); - fileChooser.setDialogTitle("Select SMPDBK Input File"); - int result = fileChooser.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return; - - File fileName = fileChooser.getSelectedFile(); - - if (fileName == null || fileName.getName().equals("")) - JOptionPane.showMessageDialog(this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE); - else { - // set our last opened path - strLastOpenPath = fileName.getPath(); - - try { - if (_DEBUG) System.out.print("in handleMenuImportFromDAT opening " + fileName.getAbsolutePath() + "...\n"); - if (!currentData.importDAT(fileName.getAbsolutePath())){ - JOptionPane.showMessageDialog(this,"Error importing -- wrong data or file type used for DAT file!\n" - + fileName.getAbsolutePath(), "Error", JOptionPane.ERROR_MESSAGE); - return; - } - if (_DEBUG) System.out.println("Finished import .DAT"); - - // update GUI to show newly imported data - updateNameFields(false); - updateScenarioList(); - updateDownstreamList(); - updateXSList(); - bHasDataToSave = true; - } catch (Exception e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "Error importing -- bad DAT file!", "Error", JOptionPane.ERROR_MESSAGE); - return; - } - } -} -/** - * Read Data from .xs file format (created by FLDXS) - */ -private boolean handleMenuImportFromFLDXS() { - - handleMenuNew(); - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setDialogTitle("Select FldXS Output File"); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setFileFilter(new DamInputFileFilter(DamInputFileFilter.TXT_INPUT)); - fileChooser.setDialogTitle("Select FLDXS cross section to import"); - int result = fileChooser.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return false; - - // user sets path - File fileName = fileChooser.getSelectedFile(); - strLastOpenPath = fileName.getPath(); - - try { - if (_DEBUG) System.out.print("in handleMenuImportFromFLDXS opening " + fileName.getAbsolutePath() + "...\n"); - - if (!currentData.importFLDXS(fileName.getAbsolutePath())) - JOptionPane.showMessageDialog(this,"Error importing -- wrong data or file type used for FLDXS file!\n" - + fileName.getAbsolutePath(), "Error", JOptionPane.ERROR_MESSAGE); - - if (_DEBUG) System.out.println("Finished import FLDXS."); - - // update GUI to show newly imported data - updateDownstreamList(); - updateXSList(); - - bHasDataToSave = true; - bChangedData = false; - - } catch (Exception e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "Error importing -- bad FLDXS file!", "Error", JOptionPane.ERROR_MESSAGE); - return false; - } - return true; -} -/** - * User has hit "New" menu option on "File" or "Database" menu - */ -private void handleMenuNew() { - - // Ask the user if they want to save before clearing the GUI. - // If the save fails, don't clear. - - - if (bHasDataToSave && bChangedData) - { - saveGUI(); - if (!checkForSaveChanges()) - return; - } - - bHandlingEvent = false; - currentData = new AnalysisData(); - strOpenedFilename = null; - updateGUI(); - bHasDataToSave = false; - return; - -} -/** - * opens .DAM file format - */ -private boolean handleMenuOpen() { - - handleMenuNew(); // *** clear GUI - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setFileFilter(new DamInputFileFilter(DamInputFileFilter.DAM_INPUT)); - fileChooser.setDialogTitle("Select Dambreak Analysis Input File"); - int result = fileChooser.showOpenDialog(this); - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return false; - - File fileName = fileChooser.getSelectedFile(); - - if (fileName == null || fileName.getName().equals("")) - JOptionPane.showMessageDialog(this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE); - else { - // set our last opened path - strLastOpenPath = fileName.getPath(); - - if (_DEBUG) System.out.print("In handleMenuOpen Opening " + fileName.getAbsolutePath() + "...\n"); - - AnalysisData newData; - if ((newData = AnalysisData.readDAM(fileName.getAbsolutePath())) == null) - JOptionPane.showMessageDialog(this,"Error opening dambreak input DAM file.\n" - + fileName.getAbsolutePath(), "Error", JOptionPane.ERROR_MESSAGE); - else - currentData = newData; - - strOpenedFilename = fileName.getAbsolutePath(); - - if (_DEBUG) System.out.println("Finished opening dam file."); - - // update GUI to show newly imported data - updateNameFields(false); - updateScenarioList(); - updateDownstreamList(); - updateXSList(); - bHasDataToSave = true; - bChangedData = false; - } - return true; -} -/** - * Comment - */ -private void handleMenuQuit() { - handleWindowClosing(); - return; -} -/** - * Handle when "Run SMPDBK" menu item chosen - */ -public void handleMenuRun_SMPDBK() { - - // save any data currently being edited in the GUI back to the AnalysisData structure - saveGUI(); - - // update all input data in case any input data was changed to their default values - updateNameFields(false); - if (nScenarioEditing != -1) - updateScenarioFields(false); - - // verify that the model can be run on this input - String error = currentData.verifyInput(); - - if (error != null) { - JOptionPane.showMessageDialog(this, error, "Errors in Data - Can Not Run SMPDBK Model",JOptionPane.ERROR_MESSAGE); - return; - } - - // update all the output structures - if (generateOutput() == true) - { - // to get the prerun result from the database - String oError = currentData.verifyOutput(); // what's done with this string ? - - OutputManager outMan = new OutputManager(this,currentData); - outMan.setTitle("Output Manager - " + "(most recent model run)"); - //outMan.show() - } else - { - JOptionPane.showMessageDialog(this,"Output Generation Failed","SMPDBK Model Run Was Unsuccessful",JOptionPane.ERROR_MESSAGE); - } - return; -} -/** - * If a file is open already, this replaces it with updated data. - * If there is no open file, "Save As..." is automatically called. - */ -private boolean handleMenuSave() { - // save any data currently being edited in the GUI back to the AnalysisData structure - saveGUI(); - - if (strOpenedFilename == null) - return handleMenuSaveAs(); - else - return AnalysisData.writeDAM(currentData,strOpenedFilename); -} -/** - * NOTE: - */ -private boolean handleMenuSaveAs() { - File fileName; - - // save any data currently being edited in the GUI back to the AnalysisData structure - saveGUI(); - - JFileChooser fileChooser = new JFileChooser(strLastOpenPath); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - fileChooser.setDialogTitle("Select File Name To Save To"); - fileChooser.setFileFilter(new DamInputFileFilter(DamInputFileFilter.DAM_INPUT)); - int result = fileChooser.showSaveDialog(this); - FileWriter output; - - // user clicked Cancel button on dialog - if (result != JFileChooser.APPROVE_OPTION) - return false; - - fileName = fileChooser.getSelectedFile(); - if (fileName == null || fileName.getName().equals("")) - { - JOptionPane.showMessageDialog(this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE); - return false; - } - - // set the 'last file opened' path - strLastOpenPath = fileName.getPath(); - - String strFileName = fileName.getAbsolutePath(); - if (!strFileName.toLowerCase().endsWith(".dam")) - strFileName = strFileName.concat(".DAM"); - - if (!AnalysisData.writeDAM(currentData,strFileName)) { - JOptionPane.showMessageDialog(this, "Error writing file.", "Error", JOptionPane.ERROR_MESSAGE); - return false; - } - - strOpenedFilename = fileName.getAbsolutePath(); - bChangedData = false; - - return true; -} -/** - * This writes all the data in the ModelGUI AnalysisData structure back to - * the tables of the DAMCAT database. - */ -private boolean handleMenuUpdateDatabase(boolean bConfirmMessage) { - - String methodName = "*** handleMenuUpdateDatabase"; - // if (_DEBUG) System.out.println(methodName); - - int selectedIndex = getListScenario().getSelectedIndex(); - - // save any data currently being edited in the GUI back into the AnalysisData structure - - saveGUI(); - - int confirmOption; - - if (bConfirmMessage) - confirmOption = JOptionPane.showConfirmDialog(this, "All data in the DAMCAT database entry for dam \"" + strWorkingDamNIDID + "\" will be replaced.\nContinue?", "Confirm", JOptionPane.YES_NO_OPTION); - else - { - confirmOption = JOptionPane.YES_OPTION; - } - - if (confirmOption == JOptionPane.NO_OPTION) - // return false; // *** perhaps this should be true ! - return true; - - // First, verify that the model can be run on this input - String error = currentData.verifyInput(); - - // update all input data in case any input data was changed to their default values - updateNameFields(false); - - if (nScenarioEditing != -1) - updateScenarioFields(false); - - if (error != null) { - JOptionPane.showMessageDialog(this,error,"Could Not Run SMPDBK Model",JOptionPane.ERROR_MESSAGE); - return false; - } - - // update all the output structures - if (generateOutput() == true) - { - try { - dbAccess.updateModelData(strWorkingDamNIDID, currentData); - JOptionPane.showMessageDialog(this,"Successfully updated database entry \"" + strWorkingDamNIDID.trim() + "\".", "Success", JOptionPane.INFORMATION_MESSAGE); - - } catch (Exception e) { - - JOptionPane.showMessageDialog(this,"Could not update DAMCAT entry!", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - return false; - } - } else - { - JOptionPane.showMessageDialog(this,"The Database was not updated!","SMPDBK Model Run Was Unsuccessful",JOptionPane.ERROR_MESSAGE); - return false; - } - - bChangedData = false; - - return true; -} -/** - * Comment - */ -private void handleScenarioKeyFocusLost() { - - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - if (nScenarioEditing != -1) - { - updateScenarioFields(true); - } - - bHandlingEvent = false; - return; - -} -/** - * For Input Scenarios: - * - * Handle INSERT Key - * - * Handle DELETE or <- (backspace) - */ -private void handleScenarioListKey(java.awt.event.KeyEvent keyEvent) { - - if (getListScenario().getSelectedIndex() == -1 || bHandlingEvent) - { - return; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE || keyEvent.getKeyCode() == KeyEvent.VK_DELETE) - { - bHandlingEvent = true; - - int oldSelection = getListScenario().getSelectedIndex(); - - getListScenario().clearSelection(); - - // *** move selected ModelScenario to deleted ArrayList - ModelScenario delMS = (ModelScenario) currentData.scenarios.get(oldSelection); - currentData.deletedScenarios.add(delMS); - - // *** now remove from primary ArrayList - currentData.scenarios.remove(oldSelection); - - updateScenarioList(); - - clearScenarioFields(); - - enableScenarioEditors(false); - - bHandlingEvent = false; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_INSERT) - { - bHandlingEvent = true; - - int newSelection = getListScenario().getSelectedIndex() + 1; - - getListScenario().clearSelection(); - - ModelScenario newScenario = new ModelScenario(); - - currentData.scenarios.add(newSelection, newScenario); - - updateScenarioList(); - - getListScenario().setSelectedIndex(newSelection); - _selectedScenario = newSelection; - - clearScenarioFields(); - - updateScenarioFields(false); - - enableScenarioEditors(true); - - bHandlingEvent = false; - - } - return; -} -/** - * Handle Selection of New List - */ -private void handleScenarioListSelection(javax.swing.event.ListSelectionEvent listSelectionEvent) { - - // only process event if the selection is final and no other event is being handled - if (listSelectionEvent.getValueIsAdjusting() || bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - int selectedIndex = getListScenario().getSelectedIndex(); - - // save scenario data if data is currently being edited - - // - // *** if the data is invalid, stop handling event ! - if (!updateScenarioFields(true)) { - JOptionPane.showMessageDialog(this,"The scenario name and source pair must be unique.", "Error", JOptionPane.ERROR_MESSAGE); - bHandlingEvent = false; - getListScenario().setSelectedIndex(nScenarioEditing); - _selectedScenario = nScenarioEditing; - return; - } - - // if the selection is being cleared, clear the scenario editors - if (selectedIndex == -1) { - clearScenarioFields(); - enableScenarioEditors(false); - bHandlingEvent = false; - return; - } - - - // if "Highlight me to create a new scenario..." was clicked, create a new scenario and select it for editing - if (selectedIndex == getlistModelScenario().getSize()-1) { - - createNewScenario(); - int idx = currentData.scenarios.size()-1; - getListScenario().setSelectedIndex( idx ); - _selectedScenario = ( idx ); - - } - - // load data for selected scenario into GUI - - updateScenarioFields(false); - - enableScenarioEditors(true); - - bHandlingEvent = false; -} -/** - * Close Window and Exit to Op Sys. - */ -private void handleWindowClosing() { - - - - if (bHasDataToSave || bChangedData) // was && - { - saveGUI(); - if (!checkForSaveChanges()) - return; - } - - dispose(); - - if ((!bHasDatabase) || (Launcher.closeFlag)) - { - System.exit(0); - } - return; - -} -/** - * Lost Focus Event fired for which fields ??? - */ -private void handleXSKeyLostFocus() { - - if (bHandlingEvent) - { - return; - } - - bHandlingEvent = true; - - if (nXSEditing != -1) - { - updateXSFields(true); - } - - bHandlingEvent = false; - return; -} -/** - * Comment - */ -private void handleXSListClick(java.awt.event.MouseEvent mouseEvent) { - - // only handle double clicks - if (mouseEvent.getClickCount() < 2 || nDownstreamEditing == -1 || getListXS().getSelectedIndex() == -1 || getListXS().getSelectedIndex() == getlistModelXS().getSize()-1) - { - return; - } - - bHandlingEvent = true; - - // *** should this be here ??? - // DownstreamPoint downEditing = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - // downEditing.bestXS = getListXS().getSelectedIndex(); - - updateXSList(); - - bHandlingEvent = false; - return; -} -/** - * For XS Types - * - * Handle INSERT Key - * - * Handle DELETE or <- (backspace) - */ -private void handleXSListKey(java.awt.event.KeyEvent keyEvent) { - - if (getListXS().getSelectedIndex() == -1 || bHandlingEvent) - { - return; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE || keyEvent.getKeyCode() == KeyEvent.VK_DELETE) - { - bHandlingEvent = true; - - int oldSelection = getListXS().getSelectedIndex(); - - DownstreamPoint down = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - - // if this is the only XS, do not let the user remove it - // *** Why ???? - if (down.xsections.size() == 1) { - Toolkit.getDefaultToolkit().beep(); - bHandlingEvent = false; - return; - } - - // *** move selected XS to deleted ArrayList - SectionGeometry delXS = (SectionGeometry) down.xsections.get(oldSelection); - down.deletedXsections.add(delXS); - - // *** now remove from primary ArrayList - down.xsections.remove(oldSelection); - - if (down.bestXS == oldSelection && down.xsections.size() > 0) - down.bestXS = 0; - else if (down.bestXS == oldSelection) - down.bestXS = -1; - - getListXS().clearSelection(); - updateXSList(); - - clearXSFields(); - enableXSEditors(false); - - bHandlingEvent = false; - } - - if (keyEvent.getKeyCode() == KeyEvent.VK_INSERT) - { - if (_DEBUG) System.out.println("Insert XS key pressed: " + getListXS().getSelectedIndex()); - - bHandlingEvent = true; - - int oldSelection = getListXS().getSelectedIndex(); - - DownstreamPoint down = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - - getListXS().clearSelection(); - - SectionGeometry newSection = new SectionGeometry(); - - down.xsections.add(newSection); - - updateXSList(); - - clearXSFields(); - - enableXSEditors(false); - - bHandlingEvent = false; - - } - - return; -} -/** - * Comment - */ -private void handleXSListSelection(javax.swing.event.ListSelectionEvent listSelectionEvent) { - - // only process event if the selection is final - if (listSelectionEvent.getValueIsAdjusting()) - { - return; - } - // and no other event is being handled - if (bHandlingEvent) - { - return; - } - - - bHandlingEvent = true; - - int selectedIndex = getListXS().getSelectedIndex(); - - // save section data if data is currently being edited - if the data is invalid, stop handling event - if (!updateXSFields(true)) { - JOptionPane.showMessageDialog(this,"The cross section type must be unique.", "Error", JOptionPane.ERROR_MESSAGE); - bHandlingEvent = false; - getListXS().setSelectedIndex(nXSEditing); - _selectedXSType = nXSEditing; - return; - } - - // updateXSFields(true); // *** this only needs done once ! - - // if the selection is being cleared, clear the section editors - if (selectedIndex == -1) { - clearXSFields(); - enableXSEditors(false); - bHandlingEvent = false; - return; - } - - // if "Create a section..." was clicked, create a new section and select it for editing - // if (_DEBUG) System.out.println("Selected Cross Section Type Index: " + getListXS().getSelectedIndex()); - - if (selectedIndex == getlistModelXS().getSize()-1) { - createNewXS(nDownstreamEditing); - } - - // load data for selected section into GUI - updateXSFields(false); - - enableXSEditors(true); - - bHandlingEvent = false; -} -/** - * Initializes the combo boxes for the restricted fields (enumerated types). - * Creation date: (7/29/2003 9:41:54 AM) - */ -private void initComboBoxes() { - //DownstreamPoint selectedPoint = (DownstreamPoint)currentData.downstream.get(selectedIndex); - - int count = 0; //to count scenarios where source starts with '#' - - String[] damTypes = EnumeratedTypes.getEnglishChoices(EnumeratedTypes.FIELD_DAMTYPE); - for (int i=0; i -1) { - TableCellEditor cellEditor = gettableXSData().getColumnModel().getColumn(column).getCellEditor(); - if (cellEditor == null) { - cellEditor = gettableXSData().getDefaultEditor(gettableXSData().getColumnClass(column)); - } - if (cellEditor != null) { - cellEditor.stopCellEditing(); - } - } - } catch (Exception e) { - } -} -/** - * Synchronizes the GUI and the data structures backing them up. - * - * If the input parameter is true, the data in the GUI is - * saved to the data structures; - * - * If the input parameter is false, the data in the GUI is - * replaced by the data in the structures. - * - * Creation date: (7/29/2003 10:20:53 AM) - * @param bSaveFields boolean - */ -private boolean updateDownstreamFields(boolean bSaveFields) { - - String methodName = "*** updateDownstreamFields"; - //if (_DEBUG) System.out.println(methodName); - - int selectedDS = getListDown().getSelectedIndex(); - - if (selectedDS == -1 || (selectedDS == getlistModelDown().getSize()-1 && nDownstreamEditing == -1)) - { - return true; - } - - - if (bSaveFields == true && nDownstreamEditing != -1) // *** Move data from GUI to Logical Data Structure - { - DownstreamPoint editedPoint = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - - // check to see if keys (data listed in DownstreamPoint List) have changed, if so, update the list - boolean bKeysEdited = false; - if (!editedPoint.name.equals(gettextName().getText()) || editedPoint.distanceToSection != NumFormat.toFloat(gettextDistance().getText() )) { - bKeysEdited = true; - - // are the new keys unique? - boolean bUniqueKeys = true; - - for (int i=0; i -1) - { - String bestString = (String) getcomboBestXS().getItemAt(bestIndex); - if (! editedPoint.xsecBestType.equalsIgnoreCase(bestString)) - { - editedPoint.xsecBestType = bestString; - editedPoint.changeFlag = 1; - bChangedData = true; - } - } - - // *** set best index - for (int x = 0; x < editedPoint.xsections.size(); x++) - { - SectionGeometry sg = (SectionGeometry) editedPoint.xsections.get(x); - if (sg.getXSType().equalsIgnoreCase(editedPoint.xsecBestType)) - { - editedPoint.bestXS = x; - break; - } - } - - // *** save any section being edited ??? - updateXSFields(true); - - // update the downstream list if the keys have been edited - if (bKeysEdited) - updateDownstreamList(); - - } else if (bSaveFields == false) { // *** Move data from Logical Data Structure to GUI - - - // *** first save associated XS fields in case anything changed there and wasn't recorded - updateXSFields(true); - clearXSFields(); - - DownstreamPoint selectedPoint = (DownstreamPoint)currentData.downstream.get(selectedDS); - nDownstreamEditing = selectedDS; - - gettextName().setText(selectedPoint.name); - gettextDistance().setText(NumFormat.format(selectedPoint.distanceToSection,4)); - gettextFloodDepth().setText(NumFormat.format(selectedPoint.floodDepth,4)); - gettextFloodFlow().setText(NumFormat.format(selectedPoint.floodFlow,4)); - gettextLatitude().setText(NumFormat.format(selectedPoint.latitude,4)); - gettextLongitude().setText(NumFormat.format(selectedPoint.longitude,4)); - - - // clear combo box - getcomboBestXS().setSelectedIndex(-1); - getcomboBestXS().removeAllItems(); - - for (int i = 0; i < selectedPoint.xsections.size(); i++) - { - SectionGeometry sg = (SectionGeometry)selectedPoint.xsections.get(i); - String xst = sg.getXSType(); - - // add to combo box - getcomboBestXS().addItem(xst); - } - - setBestXSectionsCombo(); - - // refresh the cross section type list - getListXS().clearSelection(); - updateXSList(); - enableXSEditors(false); - } - return true; -} -/** - * Synchronizes the DownstreamPoint data structures with the DefaultListModel. - * Preserves the selected downstream point. - * Creation date: (7/29/2003 9:32:06 AM) - */ -private void updateDownstreamList() { - - int oldSelection = getListDown().getSelectedIndex(); - - int interestPoint = 0; - - getlistModelDown().clear(); - - DownstreamPoint dpEditing = null; - float distanceEditing = 1000000.0f; // A million miles - - // *** Save info for DownstreamPoint whereever nDownstreamEditing is focused - - if (nDownstreamEditing > -1) - { - - dpEditing = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - distanceEditing = dpEditing.distanceToSection; - - } - - - currentData.sortDownstreamByDistance(); - - for (int i=0; i 1) // test if more than the "Highlight me " entry - oldSelection = interestPoint; // if so, set to point of interest, or first one - - if (nDownstreamEditing > -1) // however, if we were updating one of the points - oldSelection = nDownstreamEditing; // make that one the choice - - getListDown().setSelectedIndex(oldSelection); - _selectedDownstreamPoint = oldSelection; -} -/** - * Clear Fields In GUI - * Creation date: (7/29/2003 11:55:11 AM) - */ -private void updateGUI() { - - updateNameFields(false); - - getListScenario().clearSelection(); - updateScenarioList(); - clearScenarioFields(); - enableScenarioEditors(false); - - getListDown().clearSelection(); - updateDownstreamList(); - clearDownstreamFields(); - enableDownstreamEditors(false); -} -/** - * Transfer data between ModelGUI and AnalysisData structure - * - * If the parameter is true, the data in the GUI is - * saved to the data structure; if the parameter is false, - * the data in the GUI is replaced by the data in the - * structure. - * - * Creation date: (8/1/2003 9:45:06 AM) - * @param bSaveFields boolean - */ -private void updateNameFields(boolean bSaveFields) { - - //String methodName = "*** updateNameFields"; - //if (_DEBUG) System.out.println(methodName); - - if (bSaveFields) { - if (currentData.damName != gettextDamName().getText()) - { - currentData.damName = gettextDamName().getText(); - currentData.changeFlag = 1; - bChangedData = true; - } - if (currentData.riverName != gettextRiverName().getText()) - { - currentData.riverName = gettextRiverName().getText(); - currentData.changeFlag = 1; - bChangedData = true; - } - if (currentData.pointOfInterestName != gettextPPOI().getText()) - { - currentData.pointOfInterestName = gettextPPOI().getText(); - currentData.changeFlag = 1; - bChangedData = true; - } - } else { - gettextDamName().setText(currentData.damName); - gettextRiverName().setText(currentData.riverName); - gettextPPOI().setText(currentData.pointOfInterestName); - } -} -/** - * Synchronizes the editors and the data backing them up. - * - * If the parameter is true, the data in the editors is saved to the data structure; - * - * if the parameter is false, data in the editors is replaced by data in the structure. - * - * Creation date: (7/29/2003 10:20:53 AM) - * @param bSaveFields boolean - * @return boolean - true if successful - */ -private boolean updateScenarioFields(boolean bSaveFields) { - - //String methodName = "*** updateScenarioFields"; - //if (_DEBUG) System.out.println(methodName); - - int selectedIndex = getListScenario().getSelectedIndex(); - - // *** return immediately if nothing selected or last one selected && no editing done - if (selectedIndex == -1 || (selectedIndex == getlistModelScenario().getSize()-1 && nScenarioEditing == -1)) - return true; - - if (bSaveFields == true && nScenarioEditing != -1) { - // *** transfer data from GUI to correct ModelScenario structure - - ModelScenario editedScenario = (ModelScenario)currentData.scenarios.get(nScenarioEditing); - - // check to see if keys (data listed in Scenario List) have changed, if so, update the list - boolean bKeysEdited = false; // initialize - if (!editedScenario.source.equals(gettextSource().getText()) || !editedScenario.name.equals(EnumeratedTypes.getCode(EnumeratedTypes.FIELD_SCENARIO,(String)getcomboScenario().getSelectedItem()))) { - bKeysEdited = true; - - // are the new keys unique? - boolean bUniqueKeys = true; - for (int i=0; i currentData.pointOfInterestDistance) - currentData.pointOfInterestDistance = scenario.DISTTN; - - String changedSource = scenario.source; // skip scenarios started with '#' when scenario is highlighted initially - if(changedSource.startsWith("#")) - { - count++; - } - } - - getlistModelScenario().addElement("Highlight me to append a new scenario"); - - if (oldSelection == -1 && getlistModelScenario().size() > 1) // test if more than the "Highlight me " entry - oldSelection = count; // if so, set to first one - - getListScenario().setSelectedIndex(oldSelection); - _selectedScenario = oldSelection; - -} -/** - * Update Cross Section - * Synchronizes the editors and the data backing them up. - * - * If the parameter is true, the data in the editors is saved to the data structure; - * - * if the parameter is false, data in the editors is replaced by data in the structure. - * - * Creation date: (7/30/2003 7:51:19 AM) - * @param bSaveFields boolean - */ -private boolean updateXSFields(boolean bSaveFields) { - - String methodName = "*** updateXSFields"; - //if (_DEBUG) System.out.println(methodName); - - // *** this assumes JLists in GUI matches ArrayLists maintained within AnalysisData structure - int selectedDS = getListDown().getSelectedIndex(); - int selectedXS = getListXS().getSelectedIndex(); - - if (selectedXS == -1 || (selectedXS == getlistModelXS().getSize()-1 && nXSEditing == -1)) - { - return true; - } - - - DownstreamPoint editedDown = (DownstreamPoint)currentData.downstream.get(nDownstreamEditing); - - if (bSaveFields == true && nXSEditing != -1) // *** Move data from GUI to Logical Data Structure - { - SectionGeometry editedSection = (SectionGeometry)editedDown.xsections.get(nXSEditing); - - // check to see if keys (data listed in Cross Section Type List) have changed, if so, update the list later - boolean bKeysEdited = false; - - if (!editedSection.getXSType().equals(EnumeratedTypes.getCode(EnumeratedTypes.FIELD_XSTYPE,(String)getcomboXSType().getSelectedItem()))) { - bKeysEdited = true; - - // are the new keys unique? - boolean bUniqueKeys = true; - for (int i=0; i -1) - { - oldSelection = bestXS; - } - - _selectedXSType = oldSelection; - - getListXS().setSelectedIndex(_selectedXSType); - - -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/OutputManager.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/OutputManager.java deleted file mode 100644 index 2187c407f2..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/smpdbk/OutputManager.java +++ /dev/null @@ -1,1264 +0,0 @@ -package gov.dambreak.smpdbk; - -import java.awt.*; -import java.io.*; -import java.awt.event.*; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.table.*; -import gov.dambreak.util.*; -import gov.dambreak.menu.*; -import gov.damcat.data.*; - -/** - * This class should NOT be regenerated from the VAJ Visual Composition Editor (VCE) - * since a number of manual changes have been made to the code that bypassed the VCE - * - * Creation date: (7/31/2003 8:35:05 AM) - * @author: - */ -public class OutputManager extends JDialog implements ActionListener { - private AnalysisData currentData; - private JPanel ivjJDialogContentPane = null; - private JLabel ivjJLabel1 = null; - private JPanel ivjpanelButtons = null; - private JTabbedPane ivjtabbedOutput = null; - private String strLastOpenPath; - private String strOpenedFilename; - private JPanel ivjJPanel = null; - private JPanel ivjJPanel2 = null; - private JLabel ivjJLabel2 = null; - private JPanel ivjtabNoOutput = null; - private JButton ivjButtonPrint = null; - private JComboBox ivjcomboScenario = null; - private JPanel ivjcloseOutput = null; - private JButton ivjButtonClose = null; - private JButton ivjButtonViewSave = null; - private JTable jt = null; - private JTextPane fullText = null; - private JTextPane prerunText = null; - private JTextPane warningText = null; - private boolean prerunFlag = false; - private boolean bNoArgs = false; - private DBAccess dbAccess = null; - - public static boolean bEmptyDataset = false; - - IvjEventHandler ivjEventHandler = new IvjEventHandler(); - - class IvjEventHandler implements java.awt.event.ActionListener { - public void actionPerformed(java.awt.event.ActionEvent e) { - if (e.getSource() == OutputManager.this.getButtonPrint()) - connEtoC1(e); - if (e.getSource() == OutputManager.this.getButtonClose()) - connOutput(e); - if (e.getSource() == OutputManager.this.getButtonViewSave()) - connViewSave(e); - }; - }; -/** - * OutputManager constructor comment. - */ -public OutputManager() { - super(); - initialize(); -} -/** - * Insert the method's description here. - * Creation date: (4/1/2004 11:13:19 AM) - * @param _currentData gov.dambreak.util.AnalysisData - */ -public OutputManager(AnalysisData _currentData) -{ - prerunFlag = true; - - currentData = _currentData; - - initialize(); - -// show(); - this.setVisible( true ); -} -/** - * OutputManager constructor comment. - * @param owner java.awt.Dialog - */ -public OutputManager(Frame owner, AnalysisData _currentData) { - super(owner,true); - - String outOwner = owner.toString(); - if(outOwner.startsWith("gov.damcat.data.Search")) - { - prerunFlag = true; - bNoArgs = true; - } - currentData = _currentData; - - initialize(); - -// show(); - this.setVisible( true ); -} -/** - * This method is called when the user selects a scenario. - * Creation date: (7/31/2003 11:45:30 AM) - * @param e java.awt.event.ActionEvent - */ -public void actionPerformed(ActionEvent e) { - handleScenarioSelection(); -} -/** - * Insert the method's description here. - * Creation date: (7/31/2003 3:41:10 PM) - */ -private void addRiverProfileCharts(ModelOutput outputFile) { - - try { - //Output Data Table - String[] columnName = {new String("River Mile"), new String("Max Flow (cfs)"),new String("Max Elevation (ft MSL)"), - new String("Max Depth (ft)"), new String("Max Depth Time (hrs)"),new String("Flood Time (hrs)"), - new String("De-flood Time (hrs)"), new String("Flood Depth (ft)")}; - - int nSections = outputFile.inputDownstream.size(); - - String[][] tableValue = new String[nSections][]; - for (int i=0; i< nSections; i++) - { - tableValue[i] = new String[] {NumFormat.format(((DownstreamPoint)outputFile.inputDownstream.get(i)).distanceToSection,4),NumFormat.format(outputFile.maxFlow[i],4), NumFormat.format(outputFile.maxElevation[i],4), - NumFormat.format(outputFile.maxDepth[i],4), NumFormat.format(outputFile.timeMaxDepth[i],4), NumFormat.format(outputFile.timeFlood[i],4), NumFormat.format(outputFile.timeDeflood[i],4), NumFormat.format(((DownstreamPoint)outputFile.inputDownstream.get(i)).floodDepth,4)}; - } - //javax.swing.JTable - jt = new javax.swing.JTable(); - jt.setModel(new UneditableJTableModel(tableValue,columnName)); - setColumnAlignment(jt.getColumnModel()); - gettabbedOutput().addTab("Output Data Table", new javax.swing.JScrollPane(jt)); - - //Water Surface Profile Chart - double[] xValue = new double[nSections]; - for (int j=0; j OutputManager.handlePrintResults()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC1(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handlePrintResults(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** -/*connOutput -*/ -private void connOutput(java.awt.event.ActionEvent arg1) { - try { - this.handleWindowClosing(); - } catch (java.lang.Throwable ivjExc){ - handleException(ivjExc); - } -} -/** - * connOutput: (closeOutput.action.actionPerformed(java.awt.event.ActionEvent) --> OutputManager.handleCloseOutput()) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connOutput(java.awt.event.WindowEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleWindowClosing(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connViewSave: (ViewSaveOutput.action.actionPerformed(java.awt.event.ActionEvent) --> OutputManager.handleViewSaveOutput()) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connViewSave(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleViewSaveOutput(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private static void getBuilderData() { -/*V1.1 -**start of data** - D0CB838494G88G88GB1DCBDAFGGGGGGGGGGGG8CGGGE2F5E9ECE4E5F2A0E4E1F4E13DBC8BD4D4D712CE96E7CC629AB2B19BA7A1B3A61A8C9B5D8C33E3B21CDDF246E41C44CC4CD93347C94C2E49BA891398E3A2C6B498C9FCB42008080D48C7C0E824792840C0641CE588AABF7936CA14A049A27A201F505AF4375D8F4144C9366AFEDEBF3ADF731BB81CD3673D2A7B2BDB372AEE553D2F9176654C0D0D526D930428D8017D7DEF14A024378AC2FF5DC33BB82D726D8B71026AAF97A0C9F836 - A9861E4DD0B6D256932F97DA0E46815E8DF8C4E9CFFC9A3CA78B270F7AB7410B0FF186204CF540785D5863742770F1F6907C412A84F8A682DC821A9F40F2G3D70C4D5BA2387821E485E9122F4B0569A2CF3BEA7DDC55F3706562B06E7BBC04DBBD8E7F9D596AB8F825AD200C8EC7B8E2DDB844F1D043B69D5152CDE775D3305705F776AF663D82A7EB94CE0ED973227C1D8CB8491AD7C72AF99B8FE7B557E632EC1073977EAD55519A159B1A41F92EDE23F6494042C354853DFF362C8FDC18805BE8289EDD38E4A - 61923C0FG782F65FC3D343B1A0DBB7B6AECE1753CAFFC7235EEAD65C77F2E1B2F180F6669963F0B7DEFA1F246F66D004FG20BCD71A8AB94F7D766B25E6F13057A909D7CB35A7C0792F7D0C739F330E731FF6G7B2F863C83402A50DFA7F4BF4083G962D6373BAD6486755754DBCA122F73AEE0F0FF9ADDBC767933E4EBD2F65EB676976937D59180ABAD0769E0C8BB0GB093E0A140B200CC22370F279C06E7ED2FDCEF9F9C345BEA9D0EBA2B59F94AEE162C70DED585A50CF6D66A33BB4D02C0F573361CE28D - FEB8043EB7DAAF91685C4E8BDC17961E3DDF1065EFF4319AF3DB748733AE027511703EFBEEB56F235CAC8614DBB13CE3BBECCF69B2217B2968F4FD37927DC1FC8E14C53E4F655C1548F9B1454C927465BF526D5060E54EB3B7F51756D39EC6563BF921B2FEB19DE5BC9F680B81D68204816843AE441705F199C7249C9DCF46ADB6D9F25AC46B3921DE0768146B06ACD6B368941575362A31E42D85345D6E4FA65B0E4AA57028FA0DD67D6A071AF2D995F8D5E78A2372B0073965C247EE74B936DF1837EEA4AAEBF8 - A73109B9E1F48D23957A3D049E28225335BDC0680887C3D9568670ED247E59EC24CF5B6059CFB7217BEF706CA7D469E7AE1445FCF0A11E2E6F758C741183007B8184GAC82D88190869033112FF1FD6A1FA7E8C76D2A7525EDA3D3D361A90D48CE31456612C5DB1F54A9BAADE22FD5F2892CCEEC9A4A35F7D43B78B4543DBE9823C932C9CED13658ED503BB8A801B239E81D6434A42C83FE8BCBBBAC03928CB06890F83F19E94970340AAE798B07D914A5F78DDA1E1706BAF1DD6C049E2183F86F5808727A897153 - C6F82F5948E5B5AF93E9F3G8FD2647253343D70EC8365162CD5D58D16BEE4C3F45E60BAEAB7E01BA558E7B8374B773B387EB56C7E09D07C07691A7AC7761BF02ACBF343BD756FEB526FD2202F89677BE914214B07CE6278635906BEFC6CBAF40C8C1FE3C4CF407EE247A927F2CEA23A9A3769C23C9120E19317752BE9862A03F522CB62DAF746898AA3195D1227F5DFCE47BDC53AAE59648649A1594C7062E2EB7EDA7ACE37BEDE36AB3A72A62123FF2A8705F1A974F75213A89D7AD0EBB7AF5FC04AC5D9F6DAFA - 07E4691CA44B96DB3F3B7D96420BEB146BF33139A693FB6D06B94AGFE4ADCEF5B1F2C52AB135DFEF54851019643747382590767C07D20CDFC7D6FBE0071558A85FF00606E723C833E56EEBC40BEA766132B27BC46C474070E51150D730AD270DE0207A973DCCBF85032276F8368985159DD9364F9AAC0F5E0DA06EF9D7ED106368E7FE306368E5F13B1360EBE10212523346C618C34DB7B30CD2573BF4FC03F57E73759A4E2F8CA930146166FF760BCACB60BFC5EE26E1764F3162FA55823B6236E86915F1A8E6F - 451B39CF9C4E63BE5178753D42620B17B46326B90FFC27735BCCF5F14EE637CF24BC85E622ADC9D6E99084D5EF9F3249AC86A4FE1B51DD5104A69FBD01ED0B6A06E499F6952745A6970BE4A6250612126306D131EF7100E8B3DBA5D26B2C649A324A2E22C31D074A845A57734295DFFD51C73B643CECF78ECA6622AB62F531D49C16CB492A165612621378FEE89243B25F51C8623EE01043B200504D5CF79C4E42F26EBB18032C37DB2DF429202C7BC3DC070506FDAA59C6EE26B9D8B314517212DC2D72799F72F1 - 528E68D1E724EBC392EC69681C5A249BECDF4EBE3057232CD3348E39777B02831814DAD5FE0D5277E7EB2FE18E31712BCA7FF9595B855C37E91FD46702C46C5361348C42B6000E1A650A72E76ADCB19878473CF2B5BC43BF6439508BA318DBF924ECC2E084363FA71B671189009B819AA2E89FFE91ACBFA1751ED3F23BBFAB345789ED7D8E1AB1D3DDBF25D7671BE65708262EA3D4EE217D1B36F846655F107D5F8A741BDB78FABC182D5EB3EADDAEFB1F0504C5CC36269C359DD05A67B91828DF36B8DD90231B25 - 913EBE67F310D70C1B981949F84111E302F79CF852EC116DCE3EA5578F930D6E3057C368568CCBDC2F3809CE0BB4AC70DC78CD8317177F966E877E5A284EF9C3768C6AF679104DD2A613B5AA594C065C1076ED4E65FD97FD4457786CB5149D49F7518EC7CADD4360832B2ADA9BAC22555E2F7075BA59DB111FCB9F71DC766E63A4EE87BC88E0A9G0D2BC332F96E359AE869DB396D1C2FD55BCEBB50C7G82G284F484B79947D71243D84DF0797772540D353C188DC4F9ECE2EE163AFFBFC16D07D5DE94DBCFB46 - 1EAEDD50D6AA4315DB5D32ECFEE0DDCCB7G4BEBBFD56B6C6255D61FBAEB0C24FDD4C6FA6A6C4503A8578E208FC4F21D7D4F1CA4154EC28E8E69C1BFF883E58FB4C4D33BE7381FA1165B3D407762B506496401B7A3F9BC9F1007EB648F78C200A5G2BGA2955EF6650E1B571E9C99A32F3564CE062F2C0FF97C72A649AD4BBE560E399A983D0BBD2D9F731CB076844989BF764C8977903A7F471EB961FD47151C904AE2BE6163BF136D497740A723F9717340E93B65DE6DCABD70C00FF6D417771C73E117F4C395 - 78195FA6075A0FAF063EC2816236C1DE0CC06CF4D6ED9C6327E29BDF677379683F2D004FG188B9082309AA09240A07430757EAAD74B370DDEEFDF0E4D1D9350B16FABC0BEEA206FF6257FDF676ED669FA3B9D2CD651F373C15C4F6CCECB3F4546E996C26B33BBC960C5637EED44E7DE02BEEFAA7D4E4F739DA7AE48530E93FF19279DA77EBAEF6CDC67B7F93E62C84A5F34DC4E1FBFG25FDC47C69FC4017AA344F2B11368A70F005367C98098B23FA620B23B8ED7FF1A2C74481281E6DBA013140A585CFA178B4 - 85FF7078D4F390DF00E30D5675A73F77B15439448102BF1F3A072C054BA5390862B50832484A5E16D3840D787B34B8A8313EA06F4C5E496A1C146D75650A3DEDBC142EEDEF6DA2E8A63535E7DBBDED8D65BB9FA098005ADA4935B85667F22051FD72619A123B6BFA628DG15BA3EA67754FA7A06F6A8B36B28DCC7F4BDDE3E0E6A1B186FDB37877235F55B160FF666328FB97BA4CF7D9D4ACFD74A5C565BA2CB03A8BADA67DB52DE961D1037F8361FCE5A53B2DF6DE7650F1DEB8594209F9ED17039843F212C0FD4 - 1B280CF152E6E60E02461329443EDE050AAFC6F15AFD0436GE8BF0B62EB1FD40D7AE116AE0B909554DB6DAE690C039D2181FD098E6FF90A2B797A4D841C5DE38CE33CF559A98E824B679CD21F90900DF5872A39BE44811E85D08D508DF093000E7976B16CE350EE962D4A981F9CD36EBB14FAE547311EEC1149BE9F8EF4D84592C1515BDA91F38796150110E5620BEC925F879ACFF86AA61EF1D44674441BE238EEFE524A7781F38C574D0F1BD1B783GDF8430AC066B662757BCF5B3B4462D0F91B15E3AC97755 - 54DA6CAFA13647E33FB590FA160ACE775B409A3E5F96C319FFAC77F10F11BDAB9C70386D1C36115032GAFD6E8DDF55CE7D6EE67322C2FC65ED5E6DCFA5EE2B35B07C1ECF852AA3BCA9BDA4E351FB9F772621953976BCD70C2633939436AF82EB25E69B31E6B5ECE676FE04FA5CFE530B8F996519FEC9388E52B3763FAE79CD3473D48E3F48C0D83E839E9D4B95A8904342A72EFC715A32F195B5565C1234AE3D56D693CDE486779C3648B8102758959671DD9518EBA9F93FBF64D4C90D6DD1E2F23F2CDB90EFB0A - 6C9C12E83F7F71FFEAF9696F6F56C57968570F75674F1E987FD2F9D554F0FBDB32036B641ED65409C840774541DA47F11D0CEE63BA599047780BF36B21B54E17CEDEEBA1B1E09C553D1D8A7DDBC28FD05129CEC693BA6241D01635136BDA8B716D53G1F2D506EF2F27D8B5E49794C2AC5B94545F33C006018A3D37C711A496E135857C46B52B11E1B749813B937237A70B43147C11B840121250F7A36150476C7DC63F8EE0F71F5C4EFE0D322FE6D9BBC8AE0BE54DE477DD69954EFGB08378814C8720F1E3D199 - 39AFGFCF5BC0F6F9EABB9824FCE710AF7368D44F6279DBC3BFC03D249A98B134B066A295D0FBD3D035B5022FF7BA7A1780795BEF3F0E19753F1768C3BA3035069DCFEDC0E73ED07B2AB00BFC0A0C088400ADDFCEE11A548A3C65640FE2DAC0BFD8364F402875CF8E060A66306C47BFE8253E736FF5615667B128F74508A3E71CC6F955828BB44FEC5E77ED263A91BB53B5CFA97394B17FD7D8331D7FDC20F475D6CACC2B72A68543ED2DA7979C0A51485A4F0DB4AE843F596F6034D6D66344AA62415815E20507E - 35195B5C40EEEEE343ADF86EB69B70C000A5GAB15B2BFD2368E7004C470A7GF86EC04BF636201DE07D7174A010751948461938AD9EA4E36C18C07DD826EF1331C7EAE3172EE1DEE495EF5807A0AEDA140836B5FC0D5BD6BB6083091467GB67F06BDD867D1E783DF5FC46FB971BB38E886FAE8E384C8E1F8A53CCB2ABA490269AB348B5529AF232F2F45E72123106D13775671FDF2669E3ECF7E364EF31F9C3D8FEE2A735CA723C7159756FB6E135BC615FFD96F39CFFE414A294D1414A1DD09D1295BE0E595E5 - 58964F6EA18233FCCD0246F3D05156CFED6F1923D83E84678290236F09CF87A856F31B8EAEBBA8901B5630671366FE0947A64A5DC3396F987F6172716F0E97146399E62F9D56E1907BD7F25CF2DCD3596EA0C4CAFB329CE585E97600CC2BB2FAC8B9B9CF15AE93B2353D769AEE0F4DFAEE0F2F35F0FB346A394D5DCEE2CDFF4083955AECC2437309458AAD33156FD3D8F7B2FEB9F082756998954A98133D1B9A6FEE56EDFF65ED98D3B91C52E54969144C74EA07457B2D442F05823FE1FA3EA77657F85B2B58446D - B5AB29A73E82209B408100B28BC842BA4FB79B4660E5C69215899D639719B87FD61358ABD94B996D51B264334FBE58EBBF57A759C0ED6C824F31D27B10A71A7172BE7CF76CD0E81F32BB126096359D05B27E62767630F35E3BC759E956DEDA5EGCF1A2B4C4A57BA336A02F2ABG5DA3FEF60DFF1F658734103DBC976BBF087B9A4953E19225165E4152216B0325E22FDCAA4196D7D5F5FA48EAB5B1318AB41EDCC57A8A07BE921241FF8150BDFD24006F698B9F1DA518267DD0B3AEDE5DB1282BCE26F23D146C0E - DFC315F375D71CBC068D00729CA2B70859847E97F6C20BC6E32107CC08D1FE7E18407949DAF0175070CA05AECF039F04950C8F63BEB7BF151031D2FD3F3FEE32B18E35775F9F756DF3DEBABA3E4F79AF720D24043E620603657D7FF3141C61DD3E6C12945F96FAD42F50DADC6DF617853DA935019FB4F35D68063949G81GC1GF85632F49F5689EFC99FE3AE6CAEF3872E39835516EEC66C0EB34908F4D96C6D154C74E60B6A64670D6ABE75A9F43CEAF8368350355A57A2A87D17B4611913CD9AB6A897938D96 - 706A7841CCD1D93161E8996EDDD417EFEF623ABCGFD4DCD613ADCFEA9CBD01DB9E1A7D5D5CDCE0B39CE6C27AACC756B25A63ED72ECC61B952B65227BE35A73E8820A6157B15371A316F53F627BC2068553024562B2C1CB2DD128F3D6ACA257A64176A56AB6E8723050D17FD1C11918FC3F97D220D5BC2F02AE23356CC6DF67568066A6CA3ACA6D8DA474FC542D279194533793C3F22B4BE77BA8779B6947091G7FB43E17BC62F5E6B1317D61D713EEC7635BF6A779BEAD0D4637D18A7DCBC2DF2422D3BDF8C371 - E90B214C184E731BEAF22EB8837079GA1GABG4281747BF97CF02322CC98679C3E436EB00171DAD5C754F4FE2B1C6A7999214F4A7DE36F1D142F075AB0B6B4C15D810019G7381028116830482C4GA4E440DCG2A815A814CGA3GB3G82G02B2789C9EECC21B701533B145A70110D32477GD4EE7F5C4C6536847A0A4C60FA75D669A83D2276D3E7473BFD3683D09D5A504C6D27A2136BD08E49712D007B8184E472BD614AD5352D207E7BBAABD914C9E538B2D34BD60E449D5056798E62FA68519D636F76 - C62E7769D91C3F30C6642F9D708100E9D9DC476FEA1A1A0EBFB845F6AFCF3A9D358197D933B9D91E36F1135067E7F95AC62C3246C1D0366FG370DBBCE9960B98278EC00E00065G21G11G7AEC70FF59DC3F3ADA0A4650AF2A98EE7522737B2ACDEBFE8D596CFCA9DBBBA7CA92DE9CF30F357AEC77C23EE73BE92A3A33B55AD139BDC9FCDEE03627BCFFC3680B32BD65596CD0FC8D1499F3387EF46231BD6365226AFD4D356F7B6E46FB6ED14EDBB9865501132D3EE398D32B765D4859D66DFB3F2E56316FACAE - 357A7EBE2C3FD57DFD98BB3FA6F1620C9C3AD61496C1E8F3990D36FD224D779CC25A460F43FE57261D7B3D50661D7BADEF534E7DDEEED367FE14765FEDB827FE7053DDCA3D558A6DCB0576A752A7524EDB4CA48E2174F789DFC8EF16F0C065DBD14257B021F5B15AE6956DCBC65B5A0631A4CCF9406E64ED85931EADDE36D82D940FB1E19D0B8DC2CBC59EBBCD482345A12A78CED4E8DFAA7A790B66297948272658EE73245BD11B7FA9593BC2F2BCFD414F89FDE90E27AF48EF613EE08514D59A38EF7D60B4469D - 810087832C828887084B6D09B764F21F7A10893F777065D34F5A6D64968AAF2440272A5DAB1B632C463166D8116B4B5F19C9FC5B1C6BF90FE4A3742EDC4FFB244D0D7C9EE9G4A1665F2FFF723D9D064FD1B6AFDD7732D77F746DBBA86DD1FFBCF79769581274677950F1C5276958BCEF97B0A20D35A3E6249D35E3E625FD93FCE65821E521FBE057194BD77F0FFD3C8FD61B562F34A8EC2BEF3101FADD1BF04E7CBA605962A5C7985A834B7C81E308EF0A10F530A8AF9BDE39E57079007DB87FE27FABF6D38757A - 50FFCB4720F127D800F6404EA9097B2574AC72ADA723F3774B781A5F6216433F285E0F345CFA191C3925E330FD6334EF9B511D995FC6F61D51361124B35EB612FAC65BC6324EF81F25BE524875D3D674738A795D69DC8517899E2C60110D5F173CF08C6DB5C9E97A3E4650BAEF256794B35AC65F895E590EFAC76FA45EEB63F7922BB4F844766ABB09B02803104268B1C6777EC77B5BDA477B539B3D7B0B75684FE8F477C76E28D47D31EF08723D4FEE75857C7C2841683EEB69B6527BA64A4709C24E072C41C714 - 879FB320CE0051FD5792E4F45F3550336010C64398328FB12A4F0237DB71DEC696FBCF5B6931977BEE6411A64F33D8BC1BDF8EEDC30D7C8CA65B444FE0A20DDA671B7CFB1547BF47F75A26381E37294857BE9325ED5EBA0B985D43AB8BF81CE205B67373F9AEBCC4682BG8F87C8A860FCB98A79984602491E3B6E6C9094593C5A086BD9AF616FB1B97F2FB571EFE53A8BB89F3B483D65EC409782ACA960B619E7D247B82B009ED6B076798AEDD7DE2FEE97D358931FDEB811F6478B2696EF1AA65D0E46DC6F9079 - 9797FA461B9F90FAE521E73C790D320E8DD096D84865B4D4289EBF2188624C22094C778D2FB3088AD53BE60FBE3A81277CFDC7564BD16499C35ECE68530ABCE34824D69EC37AC3D9F8910FA32ACC5EF95B8913BAEF233466FA6FFA276A557568FC5697884AFB046A7D878537FE3F3D7F160EC167BC3350DB8EF797FA4BEB0BF2375FF5084B5A255CA55ED4E877905ADC40979D623AB43D95770F458AFE9741D7A8F8DA6B5FBACF6CFBECD9167D4DE30CF59FC97715034AFDC878A1FAA718F0986C86GE3024A43D8 - 670E895C07BCC6E4887E3F83BFB124BE70B93C7EE66547EC6E3BC2FE4F373855731E8F471CF6185F5135AAE7F63301366CB0774BBFD64EDBE30EF05F3918542D863C8340FA041F37AE3D207EB64DF06404669DDC4405ABBA3FA3F4BD820F384FDBCD42CCF68777E1AB5F8BD69D61BA50BE453C3CE70A6D6E1BE2BEDFC17273FD451E7E7598219B0ABD7D6B330A5C0B214C3F186773EFF5229E04832EAF81DD81B081DC8298A961797C2E4E314EC86931396799E9E42B563CE61650F518DB62AB0E2CD26592752A77 - E5FF075C7BCFFF075CFBFD276F3CE2F36778F94536CE6D3CA2763CF7DE91FFDEBB2F501F774EAB1215BCFAD18977213212C7AFAE61771961A8A296A35F29445C7A5271E3D34F185BD86A56D1EA0FA14ABDE0D9A99FAF6DAB378EBCBD6A5CFDG6A5C5498D78DF49EAB5B3C7716575A54FB8B7D5FBCC50DAEC0963EA7444AC2A20DF88D6C3CC196F613AF138C6C67E1AE2730C73944EDA1A7072B2F9F2D0AFEF3DE34CE08E991365395EA91E2D04CADC2ACD90596A19AD6E8840F90E254G3D6D753E922E1D756AAB - 8BAFB66C5389BA68F0C022BD448EE302CE7A48C6514842CE7ED1C6156B1A702D20736AFD92D4D9C8BEEDE73F1EB554DE97ADD654BED9E82A378FD94D861BDDB6B807EC86F9C0B28C62BDE2294150E2433AE6D1968D9617C132C01953B0E8F139AC36FE035DE930587A40B7D8DC7875F92976286C4E7950F76AEF03A3261F7379ADF5C899DD7765E5EE3FCE7D59D3E49FC9A86F09AFAA677EEBF7B3FE946F6B3B46F3032255AA0B562B35B6B3FE63D8F7C3165C67754FB4E37FAEDE07955232671B116FAB2AB67F8F - D0CB8788641039235698GGC0CAGGD0CB818294G94G88G88GB1DCBDAF641039235698GGC0CAGG8CGGGGGGGGGGGGGGGGGE2F5E9ECE4E5F2A0E4E1F4E1D0CB8586GGGG81G81GBAGGG9099GGGG -**end of data**/ -} -/** - * Return the JButton1 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JButton getButtonClose() { - if (ivjButtonClose == null) { - try { - ivjButtonClose = new javax.swing.JButton(); - ivjButtonClose.setName("ButtonClose"); - ivjButtonClose.setMnemonic('c'); - ivjButtonClose.setText(" Close "); - - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjButtonClose; -} -/** - * Return the ButtonPrint property value. - * @return javax.swing.JButton - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JButton getButtonPrint() { - if (ivjButtonPrint == null) { - try { - ivjButtonPrint = new javax.swing.JButton(); - ivjButtonPrint.setName("ButtonPrint"); - ivjButtonPrint.setMnemonic('p'); - ivjButtonPrint.setText("Print Screen"); - // ivjButtonPrint.setBounds(42, 1, 127, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjButtonPrint; -} -/** - * Return the ButtonViewSave property value. - * @return javax.swing.JButton - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JButton getButtonViewSave() { - if (ivjButtonViewSave == null) { - try { - ivjButtonViewSave = new javax.swing.JButton(); - ivjButtonViewSave.setName("ButtonViewSave"); - ivjButtonViewSave.setMnemonic('s'); - ivjButtonViewSave.setText("View/Save/Print Output File"); - ivjButtonViewSave.setEnabled(false); - // ivjButtonPrint.setBounds(42, 1, 127, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjButtonViewSave; -} -/** - * Return the closeOutput property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getcloseOutput() { - if (ivjcloseOutput == null) { - try { - ivjcloseOutput = new javax.swing.JPanel(); - ivjcloseOutput.setName("closeOutput"); - ivjcloseOutput.setPreferredSize(new java.awt.Dimension(0, 30)); - ivjcloseOutput.setLayout(new java.awt.GridBagLayout()); - - java.awt.GridBagConstraints constraints = new java.awt.GridBagConstraints(); - // constraints.gridx = 1; constraints.gridy = 0; - // constraints.insets = new java.awt.Insets(4, 4, 4, 4); - - constraints.insets = new java.awt.Insets(0, 100, 0, 100); - getcloseOutput().add(getButtonViewSave(),constraints); - - constraints.insets = new java.awt.Insets(0, 100, 0, 100); - getcloseOutput().add(getButtonPrint(), constraints); - - constraints.insets = new java.awt.Insets(0, 100, 0, 100); - getcloseOutput().add(getButtonClose(), constraints); - - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcloseOutput; -} -/** - * Return the JComboBox1 property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboScenario() { - if (ivjcomboScenario == null) { - try { - ivjcomboScenario = new javax.swing.JComboBox(); - ivjcomboScenario.setName("comboScenario"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboScenario; -} -/** - * Return the JDialogContentPane property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJDialogContentPane() { - if (ivjJDialogContentPane == null) { - try { - ivjJDialogContentPane = new javax.swing.JPanel(); - ivjJDialogContentPane.setName("JDialogContentPane"); - ivjJDialogContentPane.setLayout(new java.awt.BorderLayout()); - getJDialogContentPane().add(getpanelButtons(), "North"); - // user code begin {1} - getJDialogContentPane().add(gettabbedOutput(), "Center"); - getJDialogContentPane().add(getcloseOutput(), "South"); - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJDialogContentPane; -} -/** - * Return the JLabel1 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getJLabel1() { - if (ivjJLabel1 == null) { - try { - ivjJLabel1 = new javax.swing.JLabel(); - ivjJLabel1.setName("JLabel1"); - ivjJLabel1.setText("Scenario:"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJLabel1; -} -/** - * Return the JLabel2 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getJLabel2() { - if (ivjJLabel2 == null) { - try { - ivjJLabel2 = new javax.swing.JLabel(); - ivjJLabel2.setName("JLabel2"); - ivjJLabel2.setText("Could not run the model. Input data is either missing or inconsistent."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJLabel2; -} -/** - * Return the JPanel property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJPanel() { - if (ivjJPanel == null) { - try { - ivjJPanel = new javax.swing.JPanel(); - ivjJPanel.setName("JPanel"); - ivjJPanel.setLayout(null); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJPanel; -} -/** - * Return the JPanel2 property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJPanel2() { - if (ivjJPanel2 == null) { - try { - ivjJPanel2 = new javax.swing.JPanel(); - ivjJPanel2.setName("JPanel2"); - ivjJPanel2.setLayout(null); - // getJPanel2().add(getButtonPrint(), getButtonPrint().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJPanel2; -} -/** - * Return the panelButtons property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getpanelButtons() { - if (ivjpanelButtons == null) { - try { - ivjpanelButtons = new javax.swing.JPanel(); - ivjpanelButtons.setName("panelButtons"); - ivjpanelButtons.setPreferredSize(new java.awt.Dimension(0, 30)); - ivjpanelButtons.setLayout(new java.awt.GridBagLayout()); - - java.awt.GridBagConstraints constraintsJLabel1 = new java.awt.GridBagConstraints(); - constraintsJLabel1.gridx = 1; constraintsJLabel1.gridy = 0; - constraintsJLabel1.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getJLabel1(), constraintsJLabel1); - - java.awt.GridBagConstraints constraintscomboScenario = new java.awt.GridBagConstraints(); - constraintscomboScenario.gridx = 2; constraintscomboScenario.gridy = 0; - constraintscomboScenario.fill = java.awt.GridBagConstraints.HORIZONTAL; - constraintscomboScenario.weightx = 1.0; - constraintscomboScenario.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getcomboScenario(), constraintscomboScenario); - - java.awt.GridBagConstraints constraintsJPanel = new java.awt.GridBagConstraints(); - constraintsJPanel.gridx = 0; constraintsJPanel.gridy = 0; - constraintsJPanel.fill = java.awt.GridBagConstraints.BOTH; - constraintsJPanel.weightx = 1.0; - constraintsJPanel.weighty = 1.0; - constraintsJPanel.ipadx = 50; - constraintsJPanel.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getJPanel(), constraintsJPanel); - - java.awt.GridBagConstraints constraintsJPanel2 = new java.awt.GridBagConstraints(); - constraintsJPanel2.gridx = 3; constraintsJPanel2.gridy = 0; - constraintsJPanel2.fill = java.awt.GridBagConstraints.BOTH; - constraintsJPanel2.weightx = 1.0; - constraintsJPanel2.weighty = 1.0; - constraintsJPanel2.ipadx = 50; - constraintsJPanel2.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getJPanel2(), constraintsJPanel2); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelButtons; -} -/** - * Return the tabbedOutput property value. - * @return javax.swing.JTabbedPane - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTabbedPane gettabbedOutput() { - if (ivjtabbedOutput == null) { - try { - ivjtabbedOutput = new javax.swing.JTabbedPane(); - ivjtabbedOutput.setName("tabbedOutput"); - ivjtabbedOutput.insertTab("No Output Available", null, gettabNoOutput(), null, 0); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtabbedOutput; -} -/** - * Return the Page property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel gettabNoOutput() { - if (ivjtabNoOutput == null) { - try { - ivjtabNoOutput = new javax.swing.JPanel(); - ivjtabNoOutput.setName("tabNoOutput"); - ivjtabNoOutput.setLayout(new java.awt.GridBagLayout()); - - java.awt.GridBagConstraints constraintsJLabel2 = new java.awt.GridBagConstraints(); - constraintsJLabel2.gridx = 0; constraintsJLabel2.gridy = 0; - constraintsJLabel2.insets = new java.awt.Insets(4, 4, 4, 4); - gettabNoOutput().add(getJLabel2(), constraintsJLabel2); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtabNoOutput; -} -/** - * Called whenever the part throws an exception. - * @param exception java.lang.Throwable - */ -private void handleException(java.lang.Throwable exception) { - - /* Uncomment the following lines to print uncaught exceptions to stdout */ - // System.out.println("--------- UNCAUGHT EXCEPTION ---------"); - // exception.printStackTrace(System.out); -} -/** - * This method is called when "Print Results" is clicked. - */ -private void handlePrintResults() { - TabbedPrinter tp = new TabbedPrinter(gettabbedOutput(),jt); - return; -} -/** - * Insert the method's description here. - * Creation date: (7/31/2003 11:46:07 AM) - */ -private void handleScenarioSelection() { - - try { - - ModelScenario selectedScenario = (ModelScenario)currentData.scenarios.get(getcomboScenario().getSelectedIndex()); - - if (selectedScenario == null) - { - selectedScenario = (ModelScenario)currentData.scenarios.get(0); - } - gettabbedOutput().removeAll(); - if (selectedScenario.bOutputAvailable) { - - /****************************************************************************** - * NOTE: This is where a dambreak forecast generator could be inserted. - * You could create a new class extending JPanel (like FldViewPanel). - ******************************************************************************/ - gettabbedOutput().addTab("Graphic", new DisplayGraphicsPanel(selectedScenario.output)); - addRiverProfileCharts(selectedScenario.output); - gettabbedOutput().addTab("Export to FLDVIEW", new FldViewPanel(selectedScenario.output)); - if (selectedScenario.output.bHasWarning) { - //JTextPane - warningText = new JTextPane(); - warningText.setEditable(false); - warningText.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); - warningText.setContentType("text/html"); - warningText.setText("WARNING

    "+selectedScenario.output.warning); - gettabbedOutput().add("Warnings", new JScrollPane(warningText)); - } - - if (selectedScenario.output.bHasFullText) { - //JTextPane - fullText = new JTextPane(); - fullText.setEditable(false); - fullText.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); - // fullText.setContentType("text/html"); - fullText.setText(selectedScenario.output.fullText); - fullText.setCaretPosition(0); - //if title on the tab is changed here, it must be changed in handleViewSaveOutput() also - gettabbedOutput().add("SMPDBK Output Text", new JScrollPane(fullText)); - } - if (selectedScenario.output.bHasPrerunText) { - //JTextPane - prerunText = new JTextPane(); - prerunText.setFont(new java.awt.Font("Courier", Font.PLAIN, 14)); - prerunText.setEditable(false); - prerunText.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); - // fullText.setContentType("text/html"); - prerunText.setText(selectedScenario.output.prerunText); - - int indPrerun = ivjcomboScenario.getSelectedIndex(); - //System.out.println("Scenario index prerun: " + indPrerun + prerunText.getText()); - - prerunText.setCaretPosition(0); - //if title on the tab is changed here, it must be changed in handleViewSaveOutput() also - gettabbedOutput().addTab("Stored Forecast Text", new JScrollPane(prerunText)); - } - - // set the "Stored ForecastText" tab to be a default in the "View Forecast Info" button - // is clicked in the "Search" window - if(prerunFlag) - { - int indexDefaultPrerun = gettabbedOutput().indexOfTab("Stored Forecast Text"); - gettabbedOutput().setSelectedIndex(indexDefaultPrerun); - } - - } else { - ivjtabbedOutput.insertTab("No Output Available", null, gettabNoOutput(), null, 0); - gettabNoOutput().setVisible(true); - } - gettabbedOutput().addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent ev) - { - if(gettabbedOutput().getSelectedIndex() == 5) - { - if(gettabbedOutput().getTitleAt(5).equalsIgnoreCase("SMPDBK Output Text")) - { - getButtonViewSave().setEnabled(true); - } - else if(gettabbedOutput().getTitleAt(5).equalsIgnoreCase("Warnings")) - { - getButtonViewSave().setEnabled(false); - } - } - else if (gettabbedOutput().getSelectedIndex() == 6) - { - getButtonViewSave().setEnabled(true); - } - else if (gettabbedOutput().getSelectedIndex() == 7) - { - getButtonViewSave().setEnabled(true); - } - else if(gettabbedOutput().getSelectedIndex() == 0) - { - getButtonViewSave().setEnabled(false); - } - else if(gettabbedOutput().getSelectedIndex() == 1) - { - getButtonViewSave().setEnabled(false); - } - else if(gettabbedOutput().getSelectedIndex() == 2) - { - getButtonViewSave().setEnabled(false); - } - else if(gettabbedOutput().getSelectedIndex() == 3) - { - getButtonViewSave().setEnabled(false); - } - else if(gettabbedOutput().getSelectedIndex() == 4) - { - getButtonViewSave().setEnabled(false); - } - } - - }); - } catch (Exception e) { - System.out.println("caught in handleScenarioSelection"); - e.printStackTrace(); - } -} -/** - * This method is called when "ViewSave Output File" is clicked. - */ -private void handleViewSaveOutput(){ - String directory = ""; - String tmp = ""; - - String osName = System.getProperty("os.name"); - String lowerCaseName = osName.toLowerCase(); - if(lowerCaseName.indexOf("windows") > -1) - { - System.out.println("OS Name: " + osName); - // to view the content of the created output file when "View/Save/Print Output File" button - // is chosen the wordPad editor should be used - - String dbaEditor = PropertyReader.getProperty("damcrest.editor"); - System.out.println("Editor: " + dbaEditor); - - if ((directory = System.getProperty("damcrest.home")) == null) - directory = ""; - - if (!directory.endsWith(System.getProperty("file.separator"))) - directory = directory.concat(System.getProperty("file.separator")); - tmp = directory.concat("_tmp.txt"); - - File out = new File(tmp); - - try - { - out.createNewFile(); - System.out.println("Out file is: " + out); - } catch (IOException io) { - System.out.println ("A new file cannot be created"); - io.printStackTrace(); - } - - if (!out.exists()){ - System.out.println("In OutputManager.handleViewSaveOutput() - Output Does Not Exist" + out); - return; - } - - ModelScenario selectedScenario = (ModelScenario)currentData.scenarios.get(getcomboScenario().getSelectedIndex()); - String runThis = ""; - BufferedWriter saveOutput = null; - - try { - if(gettabbedOutput().getSelectedIndex() == 5) - { - if(gettabbedOutput().getTitleAt(5).equalsIgnoreCase("SMPDBK Output Text")) - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - System.out.println("SMPDBK Output Text"); - - - int sizeText = selectedScenario.output.fullText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is: " + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.fullText); - } - else - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - // System.out.println("Stored Forecast Text"); - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } - if(gettabbedOutput().getSelectedIndex() == 6) - { - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error writing file.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return ; - - } - - try { - saveOutput.newLine(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in newline() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - saveOutput.flush(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in flush() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - saveOutput.close(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in close() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - System.out.println("Editing a file with " + dbaEditor); - - Runtime rt = Runtime.getRuntime(); - Process ps = rt.exec(dbaEditor + " " + "\"" + runThis + "\""); - ps.waitFor(); - // System.out.println("Process exit code is: " + ps.exitValue()); - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process exit code is: " + ps.exitValue() + " - Process Failed!"); - - } catch (IOException io) { - io.printStackTrace(); - JOptionPane.showMessageDialog(this, "Cannot view the file", "Cannot view the file", JOptionPane.ERROR_MESSAGE); - } catch(InterruptedException ie) { - ie.printStackTrace(); - System.out.println("Interrupted waiting for process!"); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Exception in handleViewSaveOutput!"); - } - - // System.out.print("ViewSaving output file finished" ); - - out.deleteOnExit(); - } - else if(lowerCaseName.indexOf("linux") > -1) - { - System.out.println("OS Name: " + osName); - String dbaEditor = PropertyReader.getProperty("damcrest.editor"); - // String [] commandArray = new String[3]; - // commandArray[0] = dbaEditor.trim(); - // commandArray[1] = "+\"set popt=portrait:n\" "; - - if ((directory = System.getProperty("damcrest.home")) == null) - directory = ""; - - if (!directory.endsWith(System.getProperty("file.separator"))) - directory = directory.concat(System.getProperty("file.separator")); - - tmp = directory.concat("_tmp.txt"); - - File out = new File(tmp); - - try - { - System.out.println("Out file is: " + out); - out.createNewFile(); - } catch (IOException io) { - System.out.println ("A new file cannot be created"); - io.printStackTrace(); - } - - if (!out.exists()){ - System.out.println("In OutputManager.handleViewSaveOutput() - Output Does Not Exist" + out); - return; - } - ModelScenario selectedScenario = (ModelScenario)currentData.scenarios.get(getcomboScenario().getSelectedIndex()); - String runThis = ""; - BufferedWriter saveOutput = null; - try { - if(gettabbedOutput().getSelectedIndex() == 5) - { - if(gettabbedOutput().getTitleAt(5).equalsIgnoreCase("SMPDBK Output Text")) - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - System.out.println("SMPDBK Output Text"); - int sizeText = selectedScenario.output.fullText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.fullText); - } - else - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - System.out.println("Stored Forecast Text"); - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } - if(gettabbedOutput().getSelectedIndex() == 6) - { - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is: " + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error writing file.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return ; - - } - - try { - saveOutput.newLine(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in newline() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - saveOutput.flush(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in flush() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - try { - saveOutput.close(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in close() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try - { - System.out.println("Editing a file with " + dbaEditor); - int dbaEditorNameLength = dbaEditor.length() - 4; - String dbaEditorName = dbaEditor.substring(dbaEditorNameLength); - if (dbaEditorName.equalsIgnoreCase("gvim")) - { - // TEMPPATH variable is renamed on the Linux side to DAMCREST_RES_DIR - // for better readability - String tempPath = PropertyReader.getProperty("DAMCREST_RES_DIR"); - - if (!tempPath.endsWith(System.getProperty("file.separator"))) - tempPath = tempPath.concat(System.getProperty("file.separator")); - - // commandArray[2] = runThis; - // Process ps = rt.exec(commandArray);// + " " + runThis); - // System.out.println("process: " + commandArray[0] + " " + commandArray[1] + " " + commandArray[2]); - - String vimRes = tempPath.concat(".vimrc"); - - Runtime rt = Runtime.getRuntime(); - String commandLine = dbaEditor + " -u " + vimRes + " " + runThis; - Process ps = rt.exec(commandLine); - ps.waitFor(); - - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process Failed!"); - } - else if (dbaEditorName.equalsIgnoreCase("edit")) //for nedit - { - Runtime rt = Runtime.getRuntime(); - Process ps = rt.exec(dbaEditor + " " + runThis); //" fs/hseb/ob5/wfo_rfc/HP/whfs/bin/_tmp.txt"); - ps.waitFor(); - // System.out.println("Process exit code is: " + ps.exitValue()); - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process exit code is: " + ps.exitValue() + " - Process Failed!"); - } - else if (dbaEditorName.equalsIgnoreCase("rite")) //for "KWrite" editor - { - Runtime rt = Runtime.getRuntime(); - Process ps = rt.exec(dbaEditor + " " + runThis); - ps.waitFor(); - //System.out.println("Process exit code is: " + ps.exitValue()); - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process exit code is: " + ps.exitValue() + " - Process Failed!"); - } - } - catch (IOException io) - { - JOptionPane.showMessageDialog(this, "Cannot view the file", "Cannot view the file", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - } - catch(InterruptedException ie) - { - System.out.println("Interrupted, waiting for process!"); - ie.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Exception in handleViewSaveOutput!"); - e.printStackTrace(); - } - - // System.out.print("ViewSaving output file finished" ); - - out.deleteOnExit(); - } -} -/** - * Comment - */ -private void handleWindowClosing() { - - dispose(); - //to exit application when the "Output Manager" window was closed - //if command line argument was supplied - if(Launcher.closeFlag) - { - System.exit(0); - } - return; -} -private void initCloseOutput() throws java.lang.Exception { - - ivjButtonClose.addActionListener(ivjEventHandler); -} -/** - * Initializes connections - * @exception java.lang.Exception The exception description. - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void initConnections() throws java.lang.Exception { - // user code begin {1} - // user code end - /*getButtonPrint().addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - connEtoC1(e); - }; - });*/ - ivjButtonPrint.addActionListener(ivjEventHandler); - ivjButtonViewSave.addActionListener(ivjEventHandler); -} -/** - * Initialize the class. - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void initialize() { - try { - // user code begin {1} - // user code end - setName("OutputManager"); - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setResizable(false); - setSize(911, 513); - setModal(false); - setTitle("Output Manager"); - setContentPane(getJDialogContentPane()); - initConnections(); - initCloseOutput(); - } catch (java.lang.Throwable ivjExc) { - handleException(ivjExc); - } - // user code begin {2} - initializeScenarioChooser(bNoArgs); - - // user code end -} -/** - * Insert the method's description here. - * Creation date: (7/31/2003 11:27:54 AM) - */ -private void initializeScenarioChooser(boolean bNoArgs) { - - int count = 0; //to count scenarios - - String nidid = currentData.damNidid; - - if (currentData.scenarios.size() == 0) //the dam has empty dataset or not existing in the database NIDID was inserted from the command line as an argument - { - if(bNoArgs == true) - { - bEmptyDataset = true; //if there is no command line arguments - } - else - { - DBAccess dbAccess = new DBAccess(); - boolean bHasDam = dbAccess.doesDamExist(nidid); - - if(bHasDam) - { - JOptionPane.showMessageDialog(null,"The dam with NIDID = " + nidid + " has empty dataset." + - "\nMinimum one scenario must be added to create prerun results.", "Error", JOptionPane.ERROR_MESSAGE); - System.exit(0); - } - else - { - JOptionPane.showMessageDialog(null,"The dam with NIDID = " + nidid + " \ndoesn't exist in the database.", "Error", JOptionPane.ERROR_MESSAGE); - System.exit(0); - } - } - } - else - { - for (int i=0; i OutputManager.handlePrintResults()V) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC1(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handlePrintResults(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** -/*connOutput -*/ -private void connOutput(java.awt.event.ActionEvent arg1) { - try { - this.handleWindowClosing(); - } catch (java.lang.Throwable ivjExc){ - handleException(ivjExc); - } -} -/** - * connOutput: (closeOutput.action.actionPerformed(java.awt.event.ActionEvent) --> OutputManager.handleCloseOutput()) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connOutput(java.awt.event.WindowEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleWindowClosing(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connViewSave: (ViewSaveOutput.action.actionPerformed(java.awt.event.ActionEvent) --> OutputManager.handleViewSaveOutput()) - * @param arg1 java.awt.event.ActionEvent - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connViewSave(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleViewSaveOutput(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private static void getBuilderData() { -/*V1.1 -**start of data** - D0CB838494G88G88GB1DCBDAFGGGGGGGGGGGG8CGGGE2F5E9ECE4E5F2A0E4E1F4E13DBC8BD4D4D712CE96E7CC629AB2B19BA7A1B3A61A8C9B5D8C33E3B21CDDF246E41C44CC4CD93347C94C2E49BA891398E3A2C6B498C9FCB42008080D48C7C0E824792840C0641CE588AABF7936CA14A049A27A201F505AF4375D8F4144C9366AFEDEBF3ADF731BB81CD3673D2A7B2BDB372AEE553D2F9176654C0D0D526D930428D8017D7DEF14A024378AC2FF5DC33BB82D726D8B71026AAF97A0C9F836 - A9861E4DD0B6D256932F97DA0E46815E8DF8C4E9CFFC9A3CA78B270F7AB7410B0FF186204CF540785D5863742770F1F6907C412A84F8A682DC821A9F40F2G3D70C4D5BA2387821E485E9122F4B0569A2CF3BEA7DDC55F3706562B06E7BBC04DBBD8E7F9D596AB8F825AD200C8EC7B8E2DDB844F1D043B69D5152CDE775D3305705F776AF663D82A7EB94CE0ED973227C1D8CB8491AD7C72AF99B8FE7B557E632EC1073977EAD55519A159B1A41F92EDE23F6494042C354853DFF362C8FDC18805BE8289EDD38E4A - 61923C0FG782F65FC3D343B1A0DBB7B6AECE1753CAFFC7235EEAD65C77F2E1B2F180F6669963F0B7DEFA1F246F66D004FG20BCD71A8AB94F7D766B25E6F13057A909D7CB35A7C0792F7D0C739F330E731FF6G7B2F863C83402A50DFA7F4BF4083G962D6373BAD6486755754DBCA122F73AEE0F0FF9ADDBC767933E4EBD2F65EB676976937D59180ABAD0769E0C8BB0GB093E0A140B200CC22370F279C06E7ED2FDCEF9F9C345BEA9D0EBA2B59F94AEE162C70DED585A50CF6D66A33BB4D02C0F573361CE28D - FEB8043EB7DAAF91685C4E8BDC17961E3DDF1065EFF4319AF3DB748733AE027511703EFBEEB56F235CAC8614DBB13CE3BBECCF69B2217B2968F4FD37927DC1FC8E14C53E4F655C1548F9B1454C927465BF526D5060E54EB3B7F51756D39EC6563BF921B2FEB19DE5BC9F680B81D68204816843AE441705F199C7249C9DCF46ADB6D9F25AC46B3921DE0768146B06ACD6B368941575362A31E42D85345D6E4FA65B0E4AA57028FA0DD67D6A071AF2D995F8D5E78A2372B0073965C247EE74B936DF1837EEA4AAEBF8 - A73109B9E1F48D23957A3D049E28225335BDC0680887C3D9568670ED247E59EC24CF5B6059CFB7217BEF706CA7D469E7AE1445FCF0A11E2E6F758C741183007B8184GAC82D88190869033112FF1FD6A1FA7E8C76D2A7525EDA3D3D361A90D48CE31456612C5DB1F54A9BAADE22FD5F2892CCEEC9A4A35F7D43B78B4543DBE9823C932C9CED13658ED503BB8A801B239E81D6434A42C83FE8BCBBBAC03928CB06890F83F19E94970340AAE798B07D914A5F78DDA1E1706BAF1DD6C049E2183F86F5808727A897153 - C6F82F5948E5B5AF93E9F3G8FD2647253343D70EC8365162CD5D58D16BEE4C3F45E60BAEAB7E01BA558E7B8374B773B387EB56C7E09D07C07691A7AC7761BF02ACBF343BD756FEB526FD2202F89677BE914214B07CE6278635906BEFC6CBAF40C8C1FE3C4CF407EE247A927F2CEA23A9A3769C23C9120E19317752BE9862A03F522CB62DAF746898AA3195D1227F5DFCE47BDC53AAE59648649A1594C7062E2EB7EDA7ACE37BEDE36AB3A72A62123FF2A8705F1A974F75213A89D7AD0EBB7AF5FC04AC5D9F6DAFA - 07E4691CA44B96DB3F3B7D96420BEB146BF33139A693FB6D06B94AGFE4ADCEF5B1F2C52AB135DFEF54851019643747382590767C07D20CDFC7D6FBE0071558A85FF00606E723C833E56EEBC40BEA766132B27BC46C474070E51150D730AD270DE0207A973DCCBF85032276F8368985159DD9364F9AAC0F5E0DA06EF9D7ED106368E7FE306368E5F13B1360EBE10212523346C618C34DB7B30CD2573BF4FC03F57E73759A4E2F8CA930146166FF760BCACB60BFC5EE26E1764F3162FA55823B6236E86915F1A8E6F - 451B39CF9C4E63BE5178753D42620B17B46326B90FFC27735BCCF5F14EE637CF24BC85E622ADC9D6E99084D5EF9F3249AC86A4FE1B51DD5104A69FBD01ED0B6A06E499F6952745A6970BE4A6250612126306D131EF7100E8B3DBA5D26B2C649A324A2E22C31D074A845A57734295DFFD51C73B643CECF78ECA6622AB62F531D49C16CB492A165612621378FEE89243B25F51C8623EE01043B200504D5CF79C4E42F26EBB18032C37DB2DF429202C7BC3DC070506FDAA59C6EE26B9D8B314517212DC2D72799F72F1 - 528E68D1E724EBC392EC69681C5A249BECDF4EBE3057232CD3348E39777B02831814DAD5FE0D5277E7EB2FE18E31712BCA7FF9595B855C37E91FD46702C46C5361348C42B6000E1A650A72E76ADCB19878473CF2B5BC43BF6439508BA318DBF924ECC2E084363FA71B671189009B819AA2E89FFE91ACBFA1751ED3F23BBFAB345789ED7D8E1AB1D3DDBF25D7671BE65708262EA3D4EE217D1B36F846655F107D5F8A741BDB78FABC182D5EB3EADDAEFB1F0504C5CC36269C359DD05A67B91828DF36B8DD90231B25 - 913EBE67F310D70C1B981949F84111E302F79CF852EC116DCE3EA5578F930D6E3057C368568CCBDC2F3809CE0BB4AC70DC78CD8317177F966E877E5A284EF9C3768C6AF679104DD2A613B5AA594C065C1076ED4E65FD97FD4457786CB5149D49F7518EC7CADD4360832B2ADA9BAC22555E2F7075BA59DB111FCB9F71DC766E63A4EE87BC88E0A9G0D2BC332F96E359AE869DB396D1C2FD55BCEBB50C7G82G284F484B79947D71243D84DF0797772540D353C188DC4F9ECE2EE163AFFBFC16D07D5DE94DBCFB46 - 1EAEDD50D6AA4315DB5D32ECFEE0DDCCB7G4BEBBFD56B6C6255D61FBAEB0C24FDD4C6FA6A6C4503A8578E208FC4F21D7D4F1CA4154EC28E8E69C1BFF883E58FB4C4D33BE7381FA1165B3D407762B506496401B7A3F9BC9F1007EB648F78C200A5G2BGA2955EF6650E1B571E9C99A32F3564CE062F2C0FF97C72A649AD4BBE560E399A983D0BBD2D9F731CB076844989BF764C8977903A7F471EB961FD47151C904AE2BE6163BF136D497740A723F9717340E93B65DE6DCABD70C00FF6D417771C73E117F4C395 - 78195FA6075A0FAF063EC2816236C1DE0CC06CF4D6ED9C6327E29BDF677379683F2D004FG188B9082309AA09240A07430757EAAD74B370DDEEFDF0E4D1D9350B16FABC0BEEA206FF6257FDF676ED669FA3B9D2CD651F373C15C4F6CCECB3F4546E996C26B33BBC960C5637EED44E7DE02BEEFAA7D4E4F739DA7AE48530E93FF19279DA77EBAEF6CDC67B7F93E62C84A5F34DC4E1FBFG25FDC47C69FC4017AA344F2B11368A70F005367C98098B23FA620B23B8ED7FF1A2C74481281E6DBA013140A585CFA178B4 - 85FF7078D4F390DF00E30D5675A73F77B15439448102BF1F3A072C054BA5390862B50832484A5E16D3840D787B34B8A8313EA06F4C5E496A1C146D75650A3DEDBC142EEDEF6DA2E8A63535E7DBBDED8D65BB9FA098005ADA4935B85667F22051FD72619A123B6BFA628DG15BA3EA67754FA7A06F6A8B36B28DCC7F4BDDE3E0E6A1B186FDB37877235F55B160FF666328FB97BA4CF7D9D4ACFD74A5C565BA2CB03A8BADA67DB52DE961D1037F8361FCE5A53B2DF6DE7650F1DEB8594209F9ED17039843F212C0FD4 - 1B280CF152E6E60E02461329443EDE050AAFC6F15AFD0436GE8BF0B62EB1FD40D7AE116AE0B909554DB6DAE690C039D2181FD098E6FF90A2B797A4D841C5DE38CE33CF559A98E824B679CD21F90900DF5872A39BE44811E85D08D508DF093000E7976B16CE350EE962D4A981F9CD36EBB14FAE547311EEC1149BE9F8EF4D84592C1515BDA91F38796150110E5620BEC925F879ACFF86AA61EF1D44674441BE238EEFE524A7781F38C574D0F1BD1B783GDF8430AC066B662757BCF5B3B4462D0F91B15E3AC97755 - 54DA6CAFA13647E33FB590FA160ACE775B409A3E5F96C319FFAC77F10F11BDAB9C70386D1C36115032GAFD6E8DDF55CE7D6EE67322C2FC65ED5E6DCFA5EE2B35B07C1ECF852AA3BCA9BDA4E351FB9F772621953976BCD70C2633939436AF82EB25E69B31E6B5ECE676FE04FA5CFE530B8F996519FEC9388E52B3763FAE79CD3473D48E3F48C0D83E839E9D4B95A8904342A72EFC715A32F195B5565C1234AE3D56D693CDE486779C3648B8102758959671DD9518EBA9F93FBF64D4C90D6DD1E2F23F2CDB90EFB0A - 6C9C12E83F7F71FFEAF9696F6F56C57968570F75674F1E987FD2F9D554F0FBDB32036B641ED65409C840774541DA47F11D0CEE63BA599047780BF36B21B54E17CEDEEBA1B1E09C553D1D8A7DDBC28FD05129CEC693BA6241D01635136BDA8B716D53G1F2D506EF2F27D8B5E49794C2AC5B94545F33C006018A3D37C711A496E135857C46B52B11E1B749813B937237A70B43147C11B840121250F7A36150476C7DC63F8EE0F71F5C4EFE0D322FE6D9BBC8AE0BE54DE477DD69954EFGB08378814C8720F1E3D199 - 39AFGFCF5BC0F6F9EABB9824FCE710AF7368D44F6279DBC3BFC03D249A98B134B066A295D0FBD3D035B5022FF7BA7A1780795BEF3F0E19753F1768C3BA3035069DCFEDC0E73ED07B2AB00BFC0A0C088400ADDFCEE11A548A3C65640FE2DAC0BFD8364F402875CF8E060A66306C47BFE8253E736FF5615667B128F74508A3E71CC6F955828BB44FEC5E77ED263A91BB53B5CFA97394B17FD7D8331D7FDC20F475D6CACC2B72A68543ED2DA7979C0A51485A4F0DB4AE843F596F6034D6D66344AA62415815E20507E - 35195B5C40EEEEE343ADF86EB69B70C000A5GAB15B2BFD2368E7004C470A7GF86EC04BF636201DE07D7174A010751948461938AD9EA4E36C18C07DD826EF1331C7EAE3172EE1DEE495EF5807A0AEDA140836B5FC0D5BD6BB6083091467GB67F06BDD867D1E783DF5FC46FB971BB38E886FAE8E384C8E1F8A53CCB2ABA490269AB348B5529AF232F2F45E72123106D13775671FDF2669E3ECF7E364EF31F9C3D8FEE2A735CA723C7159756FB6E135BC615FFD96F39CFFE414A294D1414A1DD09D1295BE0E595E5 - 58964F6EA18233FCCD0246F3D05156CFED6F1923D83E84678290236F09CF87A856F31B8EAEBBA8901B5630671366FE0947A64A5DC3396F987F6172716F0E97146399E62F9D56E1907BD7F25CF2DCD3596EA0C4CAFB329CE585E97600CC2BB2FAC8B9B9CF15AE93B2353D769AEE0F4DFAEE0F2F35F0FB346A394D5DCEE2CDFF4083955AECC2437309458AAD33156FD3D8F7B2FEB9F082756998954A98133D1B9A6FEE56EDFF65ED98D3B91C52E54969144C74EA07457B2D442F05823FE1FA3EA77657F85B2B58446D - B5AB29A73E82209B408100B28BC842BA4FB79B4660E5C69215899D639719B87FD61358ABD94B996D51B264334FBE58EBBF57A759C0ED6C824F31D27B10A71A7172BE7CF76CD0E81F32BB126096359D05B27E62767630F35E3BC759E956DEDA5EGCF1A2B4C4A57BA336A02F2ABG5DA3FEF60DFF1F658734103DBC976BBF087B9A4953E19225165E4152216B0325E22FDCAA4196D7D5F5FA48EAB5B1318AB41EDCC57A8A07BE921241FF8150BDFD24006F698B9F1DA518267DD0B3AEDE5DB1282BCE26F23D146C0E - DFC315F375D71CBC068D00729CA2B70859847E97F6C20BC6E32107CC08D1FE7E18407949DAF0175070CA05AECF039F04950C8F63BEB7BF151031D2FD3F3FEE32B18E35775F9F756DF3DEBABA3E4F79AF720D24043E620603657D7FF3141C61DD3E6C12945F96FAD42F50DADC6DF617853DA935019FB4F35D68063949G81GC1GF85632F49F5689EFC99FE3AE6CAEF3872E39835516EEC66C0EB34908F4D96C6D154C74E60B6A64670D6ABE75A9F43CEAF8368350355A57A2A87D17B4611913CD9AB6A897938D96 - 706A7841CCD1D93161E8996EDDD417EFEF623ABCGFD4DCD613ADCFEA9CBD01DB9E1A7D5D5CDCE0B39CE6C27AACC756B25A63ED72ECC61B952B65227BE35A73E8820A6157B15371A316F53F627BC2068553024562B2C1CB2DD128F3D6ACA257A64176A56AB6E8723050D17FD1C11918FC3F97D220D5BC2F02AE23356CC6DF67568066A6CA3ACA6D8DA474FC542D279194533793C3F22B4BE77BA8779B6947091G7FB43E17BC62F5E6B1317D61D713EEC7635BF6A779BEAD0D4637D18A7DCBC2DF2422D3BDF8C371 - E90B214C184E731BEAF22EB8837079GA1GABG4281747BF97CF02322CC98679C3E436EB00171DAD5C754F4FE2B1C6A7999214F4A7DE36F1D142F075AB0B6B4C15D810019G7381028116830482C4GA4E440DCG2A815A814CGA3GB3G82G02B2789C9EECC21B701533B145A70110D32477GD4EE7F5C4C6536847A0A4C60FA75D669A83D2276D3E7473BFD3683D09D5A504C6D27A2136BD08E49712D007B8184E472BD614AD5352D207E7BBAABD914C9E538B2D34BD60E449D5056798E62FA68519D636F76 - C62E7769D91C3F30C6642F9D708100E9D9DC476FEA1A1A0EBFB845F6AFCF3A9D358197D933B9D91E36F1135067E7F95AC62C3246C1D0366FG370DBBCE9960B98278EC00E00065G21G11G7AEC70FF59DC3F3ADA0A4650AF2A98EE7522737B2ACDEBFE8D596CFCA9DBBBA7CA92DE9CF30F357AEC77C23EE73BE92A3A33B55AD139BDC9FCDEE03627BCFFC3680B32BD65596CD0FC8D1499F3387EF46231BD6365226AFD4D356F7B6E46FB6ED14EDBB9865501132D3EE398D32B765D4859D66DFB3F2E56316FACAE - 357A7EBE2C3FD57DFD98BB3FA6F1620C9C3AD61496C1E8F3990D36FD224D779CC25A460F43FE57261D7B3D50661D7BADEF534E7DDEEED367FE14765FEDB827FE7053DDCA3D558A6DCB0576A752A7524EDB4CA48E2174F789DFC8EF16F0C065DBD14257B021F5B15AE6956DCBC65B5A0631A4CCF9406E64ED85931EADDE36D82D940FB1E19D0B8DC2CBC59EBBCD482345A12A78CED4E8DFAA7A790B66297948272658EE73245BD11B7FA9593BC2F2BCFD414F89FDE90E27AF48EF613EE08514D59A38EF7D60B4469D - 810087832C828887084B6D09B764F21F7A10893F777065D34F5A6D64968AAF2440272A5DAB1B632C463166D8116B4B5F19C9FC5B1C6BF90FE4A3742EDC4FFB244D0D7C9EE9G4A1665F2FFF723D9D064FD1B6AFDD7732D77F746DBBA86DD1FFBCF79769581274677950F1C5276958BCEF97B0A20D35A3E6249D35E3E625FD93FCE65821E521FBE057194BD77F0FFD3C8FD61B562F34A8EC2BEF3101FADD1BF04E7CBA605962A5C7985A834B7C81E308EF0A10F530A8AF9BDE39E57079007DB87FE27FABF6D38757A - 50FFCB4720F127D800F6404EA9097B2574AC72ADA723F3774B781A5F6216433F285E0F345CFA191C3925E330FD6334EF9B511D995FC6F61D51361124B35EB612FAC65BC6324EF81F25BE524875D3D674738A795D69DC8517899E2C60110D5F173CF08C6DB5C9E97A3E4650BAEF256794B35AC65F895E590EFAC76FA45EEB63F7922BB4F844766ABB09B02803104268B1C6777EC77B5BDA477B539B3D7B0B75684FE8F477C76E28D47D31EF08723D4FEE75857C7C2841683EEB69B6527BA64A4709C24E072C41C714 - 879FB320CE0051FD5792E4F45F3550336010C64398328FB12A4F0237DB71DEC696FBCF5B6931977BEE6411A64F33D8BC1BDF8EEDC30D7C8CA65B444FE0A20DDA671B7CFB1547BF47F75A26381E37294857BE9325ED5EBA0B985D43AB8BF81CE205B67373F9AEBCC4682BG8F87C8A860FCB98A79984602491E3B6E6C9094593C5A086BD9AF616FB1B97F2FB571EFE53A8BB89F3B483D65EC409782ACA960B619E7D247B82B009ED6B076798AEDD7DE2FEE97D358931FDEB811F6478B2696EF1AA65D0E46DC6F9079 - 9797FA461B9F90FAE521E73C790D320E8DD096D84865B4D4289EBF2188624C22094C778D2FB3088AD53BE60FBE3A81277CFDC7564BD16499C35ECE68530ABCE34824D69EC37AC3D9F8910FA32ACC5EF95B8913BAEF233466FA6FFA276A557568FC5697884AFB046A7D878537FE3F3D7F160EC167BC3350DB8EF797FA4BEB0BF2375FF5084B5A255CA55ED4E877905ADC40979D623AB43D95770F458AFE9741D7A8F8DA6B5FBACF6CFBECD9167D4DE30CF59FC97715034AFDC878A1FAA718F0986C86GE3024A43D8 - 670E895C07BCC6E4887E3F83BFB124BE70B93C7EE66547EC6E3BC2FE4F373855731E8F471CF6185F5135AAE7F63301366CB0774BBFD64EDBE30EF05F3918542D863C8340FA041F37AE3D207EB64DF06404669DDC4405ABBA3FA3F4BD820F384FDBCD42CCF68777E1AB5F8BD69D61BA50BE453C3CE70A6D6E1BE2BEDFC17273FD451E7E7598219B0ABD7D6B330A5C0B214C3F186773EFF5229E04832EAF81DD81B081DC8298A961797C2E4E314EC86931396799E9E42B563CE61650F518DB62AB0E2CD26592752A77 - E5FF075C7BCFFF075CFBFD276F3CE2F36778F94536CE6D3CA2763CF7DE91FFDEBB2F501F774EAB1215BCFAD18977213212C7AFAE61771961A8A296A35F29445C7A5271E3D34F185BD86A56D1EA0FA14ABDE0D9A99FAF6DAB378EBCBD6A5CFDG6A5C5498D78DF49EAB5B3C7716575A54FB8B7D5FBCC50DAEC0963EA7444AC2A20DF88D6C3CC196F613AF138C6C67E1AE2730C73944EDA1A7072B2F9F2D0AFEF3DE34CE08E991365395EA91E2D04CADC2ACD90596A19AD6E8840F90E254G3D6D753E922E1D756AAB - 8BAFB66C5389BA68F0C022BD448EE302CE7A48C6514842CE7ED1C6156B1A702D20736AFD92D4D9C8BEEDE73F1EB554DE97ADD654BED9E82A378FD94D861BDDB6B807EC86F9C0B28C62BDE2294150E2433AE6D1968D9617C132C01953B0E8F139AC36FE035DE930587A40B7D8DC7875F92976286C4E7950F76AEF03A3261F7379ADF5C899DD7765E5EE3FCE7D59D3E49FC9A86F09AFAA677EEBF7B3FE946F6B3B46F3032255AA0B562B35B6B3FE63D8F7C3165C67754FB4E37FAEDE07955232671B116FAB2AB67F8F - D0CB8788641039235698GGC0CAGGD0CB818294G94G88G88GB1DCBDAF641039235698GGC0CAGG8CGGGGGGGGGGGGGGGGGE2F5E9ECE4E5F2A0E4E1F4E1D0CB8586GGGG81G81GBAGGG9099GGGG -**end of data**/ -} -/** - * Return the JButton1 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JButton getButtonClose() { - if (ivjButtonClose == null) { - try { - ivjButtonClose = new javax.swing.JButton(); - ivjButtonClose.setName("ButtonClose"); - ivjButtonClose.setMnemonic('c'); - ivjButtonClose.setText(" Close "); - - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjButtonClose; -} -/** - * Return the ButtonPrint property value. - * @return javax.swing.JButton - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JButton getButtonPrint() { - if (ivjButtonPrint == null) { - try { - ivjButtonPrint = new javax.swing.JButton(); - ivjButtonPrint.setName("ButtonPrint"); - ivjButtonPrint.setMnemonic('p'); - ivjButtonPrint.setText("Print Screen"); - // ivjButtonPrint.setBounds(42, 1, 127, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjButtonPrint; -} -/** - * Return the ButtonViewSave property value. - * @return javax.swing.JButton - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JButton getButtonViewSave() { - if (ivjButtonViewSave == null) { - try { - ivjButtonViewSave = new javax.swing.JButton(); - ivjButtonViewSave.setName("ButtonViewSave"); - ivjButtonViewSave.setMnemonic('s'); - ivjButtonViewSave.setText("View/Save/Print Output File"); - ivjButtonViewSave.setEnabled(false); - // ivjButtonPrint.setBounds(42, 1, 127, 20); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjButtonViewSave; -} -/** - * Return the closeOutput property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getcloseOutput() { - if (ivjcloseOutput == null) { - try { - ivjcloseOutput = new javax.swing.JPanel(); - ivjcloseOutput.setName("closeOutput"); - ivjcloseOutput.setPreferredSize(new java.awt.Dimension(0, 30)); - ivjcloseOutput.setLayout(new java.awt.GridBagLayout()); - - java.awt.GridBagConstraints constraints = new java.awt.GridBagConstraints(); - // constraints.gridx = 1; constraints.gridy = 0; - // constraints.insets = new java.awt.Insets(4, 4, 4, 4); - - constraints.insets = new java.awt.Insets(0, 100, 0, 100); - getcloseOutput().add(getButtonViewSave(),constraints); - - constraints.insets = new java.awt.Insets(0, 100, 0, 100); - getcloseOutput().add(getButtonPrint(), constraints); - - constraints.insets = new java.awt.Insets(0, 100, 0, 100); - getcloseOutput().add(getButtonClose(), constraints); - - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcloseOutput; -} -/** - * Return the JComboBox1 property value. - * @return javax.swing.JComboBox - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JComboBox getcomboScenario() { - if (ivjcomboScenario == null) { - try { - ivjcomboScenario = new javax.swing.JComboBox(); - ivjcomboScenario.setName("comboScenario"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjcomboScenario; -} -/** - * Return the JDialogContentPane property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJDialogContentPane() { - if (ivjJDialogContentPane == null) { - try { - ivjJDialogContentPane = new javax.swing.JPanel(); - ivjJDialogContentPane.setName("JDialogContentPane"); - ivjJDialogContentPane.setLayout(new java.awt.BorderLayout()); - getJDialogContentPane().add(getpanelButtons(), "North"); - // user code begin {1} - getJDialogContentPane().add(gettabbedOutput(), "Center"); - getJDialogContentPane().add(getcloseOutput(), "South"); - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJDialogContentPane; -} -/** - * Return the JLabel1 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getJLabel1() { - if (ivjJLabel1 == null) { - try { - ivjJLabel1 = new javax.swing.JLabel(); - ivjJLabel1.setName("JLabel1"); - ivjJLabel1.setText("Scenario:"); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJLabel1; -} -/** - * Return the JLabel2 property value. - * @return javax.swing.JLabel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JLabel getJLabel2() { - if (ivjJLabel2 == null) { - try { - ivjJLabel2 = new javax.swing.JLabel(); - ivjJLabel2.setName("JLabel2"); - ivjJLabel2.setText("Could not run the model. Input data is either missing or inconsistent."); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJLabel2; -} -/** - * Return the JPanel property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJPanel() { - if (ivjJPanel == null) { - try { - ivjJPanel = new javax.swing.JPanel(); - ivjJPanel.setName("JPanel"); - ivjJPanel.setLayout(null); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJPanel; -} -/** - * Return the JPanel2 property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getJPanel2() { - if (ivjJPanel2 == null) { - try { - ivjJPanel2 = new javax.swing.JPanel(); - ivjJPanel2.setName("JPanel2"); - ivjJPanel2.setLayout(null); - // getJPanel2().add(getButtonPrint(), getButtonPrint().getName()); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjJPanel2; -} -/** - * Return the panelButtons property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel getpanelButtons() { - if (ivjpanelButtons == null) { - try { - ivjpanelButtons = new javax.swing.JPanel(); - ivjpanelButtons.setName("panelButtons"); - ivjpanelButtons.setPreferredSize(new java.awt.Dimension(0, 30)); - ivjpanelButtons.setLayout(new java.awt.GridBagLayout()); - - java.awt.GridBagConstraints constraintsJLabel1 = new java.awt.GridBagConstraints(); - constraintsJLabel1.gridx = 1; constraintsJLabel1.gridy = 0; - constraintsJLabel1.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getJLabel1(), constraintsJLabel1); - - java.awt.GridBagConstraints constraintscomboScenario = new java.awt.GridBagConstraints(); - constraintscomboScenario.gridx = 2; constraintscomboScenario.gridy = 0; - constraintscomboScenario.fill = java.awt.GridBagConstraints.HORIZONTAL; - constraintscomboScenario.weightx = 1.0; - constraintscomboScenario.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getcomboScenario(), constraintscomboScenario); - - java.awt.GridBagConstraints constraintsJPanel = new java.awt.GridBagConstraints(); - constraintsJPanel.gridx = 0; constraintsJPanel.gridy = 0; - constraintsJPanel.fill = java.awt.GridBagConstraints.BOTH; - constraintsJPanel.weightx = 1.0; - constraintsJPanel.weighty = 1.0; - constraintsJPanel.ipadx = 50; - constraintsJPanel.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getJPanel(), constraintsJPanel); - - java.awt.GridBagConstraints constraintsJPanel2 = new java.awt.GridBagConstraints(); - constraintsJPanel2.gridx = 3; constraintsJPanel2.gridy = 0; - constraintsJPanel2.fill = java.awt.GridBagConstraints.BOTH; - constraintsJPanel2.weightx = 1.0; - constraintsJPanel2.weighty = 1.0; - constraintsJPanel2.ipadx = 50; - constraintsJPanel2.insets = new java.awt.Insets(4, 4, 4, 4); - getpanelButtons().add(getJPanel2(), constraintsJPanel2); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjpanelButtons; -} -/** - * Return the tabbedOutput property value. - * @return javax.swing.JTabbedPane - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JTabbedPane gettabbedOutput() { - if (ivjtabbedOutput == null) { - try { - ivjtabbedOutput = new javax.swing.JTabbedPane(); - ivjtabbedOutput.setName("tabbedOutput"); - ivjtabbedOutput.insertTab("No Output Available", null, gettabNoOutput(), null, 0); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtabbedOutput; -} -/** - * Return the Page property value. - * @return javax.swing.JPanel - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private javax.swing.JPanel gettabNoOutput() { - if (ivjtabNoOutput == null) { - try { - ivjtabNoOutput = new javax.swing.JPanel(); - ivjtabNoOutput.setName("tabNoOutput"); - ivjtabNoOutput.setLayout(new java.awt.GridBagLayout()); - - java.awt.GridBagConstraints constraintsJLabel2 = new java.awt.GridBagConstraints(); - constraintsJLabel2.gridx = 0; constraintsJLabel2.gridy = 0; - constraintsJLabel2.insets = new java.awt.Insets(4, 4, 4, 4); - gettabNoOutput().add(getJLabel2(), constraintsJLabel2); - // user code begin {1} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {2} - // user code end - handleException(ivjExc); - } - } - return ivjtabNoOutput; -} -/** - * Called whenever the part throws an exception. - * @param exception java.lang.Throwable - */ -private void handleException(java.lang.Throwable exception) { - - /* Uncomment the following lines to print uncaught exceptions to stdout */ - // System.out.println("--------- UNCAUGHT EXCEPTION ---------"); - // exception.printStackTrace(System.out); -} -/** - * This method is called when "Print Results" is clicked. - */ -private void handlePrintResults() { - TabbedPrinter tp = new TabbedPrinter(gettabbedOutput(),jt); - return; -} -/** - * Insert the method's description here. - * Creation date: (7/31/2003 11:46:07 AM) - */ -private void handleScenarioSelection() { - - try { - - ModelScenario selectedScenario = (ModelScenario)currentData.scenarios.get(getcomboScenario().getSelectedIndex()); - - if (selectedScenario == null) - { - selectedScenario = (ModelScenario)currentData.scenarios.get(0); - } - - gettabbedOutput().removeAll(); - if (selectedScenario.bOutputAvailable) { - - /****************************************************************************** - * NOTE: This is where a dambreak forecast generator could be inserted. - * You could create a new class extending JPanel (like FldViewPanel). - ******************************************************************************/ - gettabbedOutput().addTab("Graphic", new DisplayGraphicsPanel(selectedScenario.output)); - addRiverProfileCharts(selectedScenario.output); - gettabbedOutput().addTab("Export to FLDVIEW", new FldViewPanel(selectedScenario.output)); - if (selectedScenario.output.bHasWarning) { - //JTextPane - warningText = new JTextPane(); - warningText.setEditable(false); - warningText.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); - warningText.setContentType("text/html"); - warningText.setText("WARNING

    "+selectedScenario.output.warning); - gettabbedOutput().add("Warnings", new JScrollPane(warningText)); - } - - if (selectedScenario.output.bHasFullText) { - getButtonViewSave().setEnabled(true); - //JTextPane - fullText = new JTextPane(); - fullText.setEditable(false); - fullText.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); - // fullText.setContentType("text/html"); - fullText.setText(selectedScenario.output.fullText); - fullText.setCaretPosition(0); - //if title on the tab is changed here, it must be changed in handleViewSaveOutput() also - gettabbedOutput().add("SMPDBK Output Text", new JScrollPane(fullText)); - } - if (selectedScenario.output.bHasPrerunText) { - getButtonViewSave().setEnabled(true); - //JTextPane - prerunText = new JTextPane(); - prerunText.setFont(new java.awt.Font("Courier", Font.PLAIN, 14)); - prerunText.setEditable(false); - prerunText.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); - // fullText.setContentType("text/html"); - prerunText.setText(selectedScenario.output.prerunText); - - int indPrerun = ivjcomboScenario.getSelectedIndex(); - //System.out.println("Scenario index prerun: " + indPrerun + prerunText.getText()); - - prerunText.setCaretPosition(0); - //if title on the tab is changed here, it must be changed in handleViewSaveOutput() also - gettabbedOutput().addTab("Stored Forecast Text", new JScrollPane(prerunText)); - } - - // set the "Stored ForecastText" tab to be a default in the "View Forecast Info" button - // is clicked in the "Search" window - if(prerunFlag) - { - int indexDefaultPrerun = gettabbedOutput().indexOfTab("Stored Forecast Text"); - gettabbedOutput().setSelectedIndex(indexDefaultPrerun); - } - - } else { - ivjtabbedOutput.insertTab("No Output Available", null, gettabNoOutput(), null, 0); - gettabNoOutput().setVisible(true); - } - } catch (Exception e) { - System.out.println("caught in handleScenarioSelection"); - e.printStackTrace(); - } -} -/** - * This method is called when "ViewSave Output File" is clicked. - */ -private void handleViewSaveOutput(){ - String directory = ""; - String tmp = ""; - - String osName = System.getProperty("os.name"); - String lowerCaseName = osName.toLowerCase(); - if(lowerCaseName.indexOf("windows") > -1) - { - System.out.println("OS Name: " + osName); - // to view the content of the created output file when "View/Save/Print Output File" button - // is chosen the wordPad editor should be used - - String dbaEditor = PropertyReader.getProperty("damcrest.editor"); - System.out.println("Editor: " + dbaEditor); - - if ((directory = System.getProperty("damcrest.home")) == null) - directory = ""; - - if (!directory.endsWith(System.getProperty("file.separator"))) - directory = directory.concat(System.getProperty("file.separator")); - tmp = directory.concat("_tmp.txt"); - - File out = new File(tmp); - - try - { - out.createNewFile(); - System.out.println("Out file is: " + out); - } catch (IOException io) { - System.out.println ("A new file cannot be created"); - io.printStackTrace(); - } - - if (!out.exists()){ - System.out.println("In OutputManager.handleViewSaveOutput() - Output Does Not Exist" + out); - return; - } - - ModelScenario selectedScenario = (ModelScenario)currentData.scenarios.get(getcomboScenario().getSelectedIndex()); - String runThis = ""; - BufferedWriter saveOutput = null; - - try { - if(gettabbedOutput().getSelectedIndex() == 5) - { - if(gettabbedOutput().getTitleAt(5).equalsIgnoreCase("SMPDBK Output Text")) - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - System.out.println("SMPDBK Output Text"); - int sizeText = selectedScenario.output.fullText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is: " + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.fullText); - } - else - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - // System.out.println("Stored Forecast Text"); - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } - if(gettabbedOutput().getSelectedIndex() == 6) - { - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error writing file.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return ; - - } - - try { - saveOutput.newLine(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in newline() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - saveOutput.flush(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in flush() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - saveOutput.close(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in close() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - System.out.println("Editing a file with " + dbaEditor); - - Runtime rt = Runtime.getRuntime(); - Process ps = rt.exec(dbaEditor + " " + "\"" + runThis + "\""); - ps.waitFor(); - // System.out.println("Process exit code is: " + ps.exitValue()); - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process exit code is: " + ps.exitValue() + " - Process Failed!"); - - } catch (IOException io) { - io.printStackTrace(); - JOptionPane.showMessageDialog(this, "Cannot view the file", "Cannot view the file", JOptionPane.ERROR_MESSAGE); - } catch(InterruptedException ie) { - ie.printStackTrace(); - System.out.println("Interrupted waiting for process!"); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Exception in handleViewSaveOutput!"); - } - - // System.out.print("ViewSaving output file finished" ); - - out.deleteOnExit(); - } - else if(lowerCaseName.indexOf("linux") > -1) - { - System.out.println("OS Name: " + osName); - String dbaEditor = PropertyReader.getProperty("damcrest.editor"); - // String [] commandArray = new String[3]; - // commandArray[0] = dbaEditor.trim(); - // commandArray[1] = "+\"set popt=portrait:n\" "; - - if ((directory = System.getProperty("damcrest.home")) == null) - directory = ""; - - if (!directory.endsWith(System.getProperty("file.separator"))) - directory = directory.concat(System.getProperty("file.separator")); - - tmp = directory.concat("_tmp.txt"); - - File out = new File(tmp); - - try - { - System.out.println("Out file is: " + out); - out.createNewFile(); - } catch (IOException io) { - System.out.println ("A new file cannot be created"); - io.printStackTrace(); - } - - if (!out.exists()){ - System.out.println("In OutputManager.handleViewSaveOutput() - Output Does Not Exist" + out); - return; - } - ModelScenario selectedScenario = (ModelScenario)currentData.scenarios.get(getcomboScenario().getSelectedIndex()); - String runThis = ""; - BufferedWriter saveOutput = null; - try { - if(gettabbedOutput().getSelectedIndex() == 5) - { - if(gettabbedOutput().getTitleAt(5).equalsIgnoreCase("SMPDBK Output Text")) - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - System.out.println("SMPDBK Output Text"); - int sizeText = selectedScenario.output.fullText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.fullText); - } - else - { - //if title on the tab is changed in the handleScenarioSelected(), it must be changed here also - System.out.println("Stored Forecast Text"); - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is :" + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } - if(gettabbedOutput().getSelectedIndex() == 6) - { - int sizeText = selectedScenario.output.prerunText.length(); - runThis = out.getAbsolutePath(); - System.out.println("In OutputManager, runThis is: " + runThis); - saveOutput = new BufferedWriter(new FileWriter(runThis), sizeText); - saveOutput.write(selectedScenario.output.prerunText); - } - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error writing file.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return ; - - } - - try { - saveOutput.newLine(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in newline() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try { - saveOutput.flush(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in flush() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - try { - saveOutput.close(); - } catch (IOException io) { - JOptionPane.showMessageDialog(this, "Error in close() function.", - "Error", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - return; - } - - try - { - System.out.println("Editing a file with " + dbaEditor); - int dbaEditorNameLength = dbaEditor.length() - 4; - String dbaEditorName = dbaEditor.substring(dbaEditorNameLength); - if (dbaEditorName.equalsIgnoreCase("gvim")) - { - String tempPath = PropertyReader.getProperty("TEMPPATH"); - - if (!tempPath.endsWith(System.getProperty("file.separator"))) - tempPath = tempPath.concat(System.getProperty("file.separator")); - - // commandArray[2] = runThis; - // Process ps = rt.exec(commandArray); - // System.out.println("process: " + commandArray[0] + " " + commandArray[1] + " " + commandArray[2]); - - String vimRes = tempPath.concat(".vimrc"); - - Runtime rt = Runtime.getRuntime(); - String commandLine = dbaEditor + " -u " + vimRes + " " + runThis; - Process ps = rt.exec(commandLine); - ps.waitFor(); - - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process Failed!"); - } - else if (dbaEditorName.equalsIgnoreCase("edit")) //for nedit - { - Runtime rt = Runtime.getRuntime(); - Process ps = rt.exec(dbaEditor + " " + runThis); //" /fs/hseb/ob5/wfo_rfc/HP/whfs/bin/_tmp.txt"); - // System.out.println("in OutputManager runThis: " + runThis); - ps.waitFor(); - // System.out.println("Process exit code is: " + ps.exitValue()); - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process exit code is: " + ps.exitValue() + " - Process Failed!"); - } - else if (dbaEditorName.equalsIgnoreCase("rite")) //for "KWrite" editor - { - Runtime rt = Runtime.getRuntime(); - Process ps = rt.exec(dbaEditor + " " + runThis); - ps.waitFor(); - // System.out.println("Process exit code is: " + ps.exitValue()); - if (ps.exitValue() != 0) - throw new Exception("View/Save " + runThis + " Process exit code is: " + ps.exitValue() + " - Process Failed!"); - } - } - catch (IOException io) - { - JOptionPane.showMessageDialog(this, "Cannot view the file", "Cannot view the file", JOptionPane.ERROR_MESSAGE); - io.printStackTrace(); - } - catch(InterruptedException ie) - { - System.out.println("Interrupted, waiting for process!"); - ie.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Exception in handleViewSaveOutput!"); - e.printStackTrace(); - } - - // System.out.print("ViewSaving output file finished" ); - - out.deleteOnExit(); - } -} -/** - * Comment - */ -private void handleWindowClosing() { - - dispose(); - //to exit application when the "Output Manager" window was closed - //if command line argument was supplied - if(Launcher.closeFlag) - { - System.exit(0); - } - return; -} -private void initCloseOutput() throws java.lang.Exception { - - ivjButtonClose.addActionListener(ivjEventHandler); -} -/** - * Initializes connections - * @exception java.lang.Exception The exception description. - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void initConnections() throws java.lang.Exception { - // user code begin {1} - // user code end - /*getButtonPrint().addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - connEtoC1(e); - }; - });*/ - ivjButtonPrint.addActionListener(ivjEventHandler); - ivjButtonViewSave.addActionListener(ivjEventHandler); -} -/** - * Initialize the class. - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void initialize() { - try { - // user code begin {1} - // user code end - setName("OutputManager"); - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setResizable(false); - setSize(911, 513); - setModal(false); - setTitle("Output Manager"); - setContentPane(getJDialogContentPane()); - initConnections(); - initCloseOutput(); - } catch (java.lang.Throwable ivjExc) { - handleException(ivjExc); - } - // user code begin {2} - initializeScenarioChooser(bNoArgs); - - // user code end -} -/** - * Insert the method's description here. - * Creation date: (7/31/2003 11:27:54 AM) - */ -private void initializeScenarioChooser(boolean bNoArgs) { - - int count = 0; //to count scenarios - - String nidid = currentData.damNidid; - - if (currentData.scenarios.size() == 0) //the dam has empty dataset or not existing in the database NIDID was inserted from the command line as an argument - { - if(bNoArgs == true) - { - bEmptyDataset = true; //if there is no command line arguments - } - else - { - DBAccess dbAccess = new DBAccess(); - boolean bHasDam = dbAccess.doesDamExist(nidid); - - if(bHasDam) - { - JOptionPane.showMessageDialog(null,"The dam with NIDID = " + nidid + " has empty dataset." + - "\nMinimum one scenario must be added to create prerun results.", "Error", JOptionPane.ERROR_MESSAGE); - System.exit(0); - } - else - { - JOptionPane.showMessageDialog(null,"The dam with NIDID = " + nidid + " \ndoesn't exist in the database.", "Error", JOptionPane.ERROR_MESSAGE); - System.exit(0); - } - } - } - else - { - for (int i=0; i -1) { - System.out.println ("OS Windows"); - lineEnd = "\r\n"; // The model needs this windows-style line break - } - else if(lowerCaseName.indexOf("linux") > -1) { - System.out.println ("OS Linux"); - lineEnd = "\n"; - } - else - lineEnd = "\n"; - - FileWriter output; - - ModelScenario scenario = (ModelScenario)scenarios.get(nScenario); - - try { - // open the file - output = new FileWriter(filename); - - damName.trim(); - output.write("C1 " + damName + lineEnd); - riverName.trim(); - output.write("C2 " + riverName); - for (int i=0; i < 45-riverName.length(); i++) - output.write(" "); - pointOfInterestName.trim(); - output.write(pointOfInterestName + lineEnd); - output.write("C3 " + " 0 " - + scenario.dbugType + " " - + scenario.damType + " 1 0" - + lineEnd); - output.write("C4 " + - floatToString10(2, scenario.HDE) + - floatToString10(2, scenario.BME) + - floatToString10(0, scenario.VOL) + - floatToString10(2, scenario.SA) + - floatToString10(2, scenario.BW) + - floatToString10(2, scenario.TFM) + - floatToString10(2, scenario.QO) + lineEnd); - - int elevationCount = 0; - - DownstreamPoint firstDown = (DownstreamPoint)downstream.get(0); - SectionGeometry firstSection = firstDown.getBestSection(); - for ( int i = 0; i< 8; i++) // *** assumes 8 ! - { - if (firstSection.getElevationData(i,0) != -999.0) // *** was > -900.0 - elevationCount++; - } - - int numberXSections = downstream.size(); - - if (numberXSections < 10) // *** why 10 ? - output.write("C5 " + " " + numberXSections + " " + elevationCount + - floatToString10(2, scenario.CMS) + - floatToString10(2, scenario.DISTTN) + lineEnd); - else - output.write("C5 " + " " + numberXSections + " " + elevationCount + - floatToString10(2, scenario.CMS) + - floatToString10(2, scenario.DISTTN) + lineEnd); - for ( int j=0; j -990.0f - { - count++; - output.write("C7-" + count + " " + - floatToString10(2, section.getElevationData(k, 0)) + - floatToString10(2, section.getElevationData(k, 1)) + - floatToString10(2, section.getElevationData(k, 2)) + - floatToString10(3, section.getElevationData(k, 3)) + lineEnd); - } - } - } - - // close the file - output.close(); - - } catch (IOException e) { - System.out.println("Caught IOException in AnalysisData.exportDAT"); - e.printStackTrace(); - return false; - } - catch (Exception ex) { - System.out.println("Caught Exception in AnalysisData.exportDAT"); - ex.printStackTrace(); - return false; - } - return true; -} - private static String floatToString10(int decimals, float value) { - if (value == -999.0f) - return " .00"; - - java.text.DecimalFormat df; - - if (decimals == 0) - df = new java.text.DecimalFormat("#########."); - else if (decimals == 2) - df = new java.text.DecimalFormat("#######.00"); - else if (decimals == 3) - df = new java.text.DecimalFormat("######.000"); - else if (decimals == 4) - df = new java.text.DecimalFormat("#####.0000"); - else - return ""; - - StringBuffer result = new StringBuffer(df.format(value)); - - while (result.length() < 10) - result.insert(0, ' '); - - return result.toString(); - } -/** - * This method runs the model on all - * scenarios stored in this data structure. - */ -public boolean generateOutput() -{ - for (int i=0; i -1) - tempPath = PropertyReader.getProperty("TEMPPATH"); - else if(lowerCaseName.indexOf("linux") > -1) - tempPath = PropertyReader.getProperty("DAMCREST_DATA_DIR"); - - if (!tempPath.endsWith(System.getProperty("file.separator"))) - tempPath = tempPath.concat(System.getProperty("file.separator")); - - // write the scenario input out to a SMPDBK input file located in the specified TEMP directory - - - if (!exportDAT(scenario, tempPath + "damin")) - { - System.out.println("In AnalysisData.generateOutput(i) -- false return from exportDAT"); - return false; - } - - // attempt to run the model - try { - - // System.out.println("In AnalysisData.generateOutput: input file is:" + tempPath + "damin"); - - theScenario.output = runModel(tempPath + "damout", tempPath + "damin"); - - theScenario.bOutputAvailable = true; - - // NOTE: the downstream points in the output structure are missing latitude and - // longitude data because when the model is run, this data is lost (the fortran - // code was not built to handle lat and lon data so it is not included in the - // .OUT file). - // Here, we get around this by repopulating the downstream point structure - // with latitude and longitude data after the output file has been parsed. - - // *** This is also true of other data found in DownstreamPoint !!! - - // System.out.println(methodName + " - downstream size = " + downstream.size()); - - for (int i=0; i < downstream.size(); i++) { - - // *** Copy data from DownstreamPoints attached to AnalysisData structure - DownstreamPoint dx = (DownstreamPoint)downstream.get(i); - - // *** to DownstreamPoints attached to ModelOutput structure - DownstreamPoint dp = (DownstreamPoint)theScenario.output.inputDownstream.get(i); - - dp.name = dx.name; - dp.xsecBestType = dx.xsecBestType; - dp.comments = dx.comments; - // dp.distanceToSection = - // dp.floodDepth = dp.floodDepth + dx.elevation; // ??? - // System.out.println("i = " + i); - // System.out.println("dp.floodDepth = " + dp.floodDepth); - // System.out.println("dx.elevation = " + dx.elevation); - dp.floodWidth = dx.floodWidth; - dp.floodFlow = dx.floodFlow; - dp.elevation = dx.elevation; - dp.mann_oc = dx.mann_oc; - dp.latitude = dx.latitude; - dp.longitude = dx.longitude; - dp.bestXS = dx.bestXS; - // dp.bestXS = 0; // there is only one SectionGeometry in DownstreamPoint parsed from Output ! - - dp.changeFlag = 1; - - } - - } catch (Exception e) { - System.out.println("Exception While Running Model In AnalysisData.generateOutput"); - e.printStackTrace(); - return false; - } - } catch (Exception ex) { - System.out.println("Exception While Trying to set up Model Run In AnalysisData.generateOutput"); - ex.printStackTrace(); - return false; - } - return true; -} -/** - * Retrieve ModelScenario from ArrayList - * Creation date: (7/30/2003 12:53:56 PM) - * @param scenario int - */ -public ModelOutput getModelOutput(int scenario) { - - ModelScenario theScenario = (ModelScenario)scenarios.get(scenario); - - return theScenario.output; -} -/** - * This method verifies that all the cross sections - * marked "Best" at each point in the array of DownstreamPoints - * has the same number of B-vs-H pairs. - * - * If so, it returns that number (> 0) - * - * If not, it returns -2 - * - * If no downstream points exist, it returns -1 - */ -public static int getNumPairs(ArrayList downstreamPts) { - - int nPairs = -1; - - try { - - String methodName = "*** AnalysisData.getNumPairs"; - - for (int i=0; i < downstreamPts.size(); i++) { - - // System.out.println(">>>>>>>>>>>>> " + "getDown " + i); - - DownstreamPoint down = (DownstreamPoint)downstreamPts.get(i); - - SectionGeometry xs; - - // System.out.println(">>>>>>>>>>>>> " + "getXS " + i); - if (down.xsections.size() == 0) - continue; - else if (down.bestXS == -1) - xs = (SectionGeometry)down.xsections.get(0); - else if (down.bestXS >= down.xsections.size()) - xs = (SectionGeometry)down.xsections.get(0); - else - xs = (SectionGeometry)down.xsections.get(down.bestXS); - - // System.out.println("Best XS is " + xs.getXSType()); - // System.out.println("Last Row Used Is " + xs.getLastRowUsed()); - - int j; - for (j=0; j < xs.getLastRowUsed(); j++) // *** this formerly assumeD always 8 pairs of B/H ! - { - // System.out.println(">>>>>>>>>>>>> " + "getElev " + j); - if (xs.getElevationData(j,0) == -999.0) // *** was < -900.0 == -999.0 - { - break; - } - } - - int jPairs = j + 1; // nPairs is an actual count, NOT the index ! - - if (nPairs == -1) - nPairs = jPairs; - else if (nPairs == jPairs) - continue; - else - return -2; - } - - return nPairs; - } catch (Throwable t) { - System.out.println("caught in AnalysisData.getNumPairs"); - t.printStackTrace(); - } - return nPairs; - - -} -/** - * This method creates a new scenario for the - * input data stored in the given DAT file. - * It also creates new downstream points for - * every cross section in the DAT file. - */ -public boolean importDAT(String filename) { - if (!(new File(filename).exists())) - { - System.out.println("In AnalysisData.importDAT - existence test failed for " + filename); - return false; - } - - ModelScenario scenario = new ModelScenario(); - - // name the scenario with some default values - scenario.source = "DAT"; - scenario.name = "MF"; - - BufferedReader input; - String line = ""; - String lineData[]; - - try { - // attempt to open the file - input = new BufferedReader(new FileReader(filename)); - - // Read C1 - line = input.readLine(); - - // *** just assume that first line of file contains dam name - /* - if (line.charAt(0) != 'C' || line.charAt(1) != '1') - return false; - damName = line.substring(10,line.length()); - damName = damName.trim(); - */ - damName = line.substring(10,line.length()); - damName = damName.trim(); - - // Read C2 - line = input.readLine(); - if (line.length() > 55) - { - riverName = line.substring(10,55); - pointOfInterestName = line.substring(55,line.length()); - } - else // no point of interest - { - riverName = line.substring(10,line.length()); - pointOfInterestName = ""; - } - riverName = riverName.trim(); - pointOfInterestName = pointOfInterestName.trim(); - - // Read C3 = IBC, ISH, JNK, IDAM, IPLT, IREC - line = input.readLine(); - lineData = parseLine(line); - scenario.dbugType = Integer.parseInt(lineData[2]); - scenario.damType = Integer.parseInt(lineData[3]); - - // Read C4 = HDE, BME, VOL, SA, BW, IFM, QO - line = input.readLine(); - lineData = parseLine(line); - scenario.HDE = Float.parseFloat(lineData[1]); - scenario.BME = Float.parseFloat(lineData[2]); - scenario.VOL = Float.parseFloat(lineData[3]); - scenario.SA = Float.parseFloat(lineData[4]); - scenario.BW = Float.parseFloat(lineData[5]); - scenario.TFM = Float.parseFloat(lineData[6]); - scenario.QO = Float.parseFloat(lineData[7]); - - // Read C5 - line = input.readLine(); - lineData = parseLine(line); - int numberNewDowns = Integer.parseInt(lineData[1]); - int numberPairs = Integer.parseInt(lineData[2]); - scenario.CMS = Float.parseFloat(lineData[3]); - scenario.DISTTN = Float.parseFloat(lineData[4]); - - // add this new scenario to the list - scenarios.add(scenario); - - for (int i=0; i 80 ){ - JOptionPane.showMessageDialog(null,"Error data exceeds 80 columns in DAT file on line: \n" - + line, "Error", JOptionPane.ERROR_MESSAGE); - return null; -// return result; - } - - String result[] = new String[8]; // assumes max of 8 values on line ! - for (int i=0; i < 8; i++) - result[i] = new String(); - - while (position < line.length()) - { - if ((position % 10) == 0) - colCount++; - - if (line.charAt(position) != ' ') - result[colCount] += line.charAt(position); - - position++; - } - - return result; - } - public static AnalysisData readDAM(String filename) { - - if (!(new File(filename).exists())) - { - System.out.println("In AnalysisData.readDAM - file failed existence test !"); - return null; - } - - AnalysisData data = new AnalysisData(); - BufferedReader input; - String line = ""; - String lineData[]; - int numberElevations; - - try { - - // attempt to open the file - input = new BufferedReader(new FileReader(filename)); - - StringTokenizer st; - - // read the type/version line - line = input.readLine(); - st = new StringTokenizer(line,"|"); - try { - if (!st.nextToken().equals("Dambreak Analysis")) - return null; - if (Integer.parseInt(st.nextToken()) != 1) - return null; - } catch (Exception ex) { - return null; - } - - // read the name line - line = input.readLine(); - st = new StringTokenizer(line,"|"); - data.damName = st.nextToken().trim(); - data.riverName = st.nextToken().trim(); - data.pointOfInterestName = st.nextToken().trim(); - - // read the number of input scenarios - line = input.readLine(); - st = new StringTokenizer(line,"|"); - int numScenarios = Integer.parseInt(st.nextToken()); - - // read in the input scenarios - for (int i=0; i -1) { - modelFileName = modelFileName.concat("sdbj.exe"); - } - else if(lowerCaseName.indexOf("linux") > -1) { - modelFileName = modelFileName.concat("sdbj.LX"); - } - - File fileModel = new File(modelFileName); - if (!fileModel.exists()){ - System.out.println("In AnalysisData.runModel -- File Does Not Exist" + modelFileName); - JOptionPane.showMessageDialog(null,"Error -- no SMPDBK model found in\n" + modelFileName, "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - //String runThis = modelFileName + " \"" + outputFilename + "\" \"" + inputFilename + "\""; - String runThis = modelFileName + " " + outputFilename + " " + inputFilename; - System.out.println("In AnalysisData::runModel, runThis is :" + runThis); - - - ModelOutput outFile = null; - - try { - Process ps = rt.exec(runThis); - // wait for the output file to be generated - ps.waitFor(); - - if (ps.exitValue() != 0) - { - - throw new Exception("sdbj execution Process Failed with ExitValue of " + ps.exitValue()); - } - - outFile = ModelOutput.readOUT(outputFilename); - - outFile.changeFlag = 1; // set change flag so output is written - - if (!ModelOutput.verify(outputFilename)) - throw new Exception("False return from ModelOutput.verify"); - - } catch (IOException e) { - System.out.println("In AnalysisData.runModel -- Caught IOException"); - e.printStackTrace(); - // throw new IOException("IOException Rethrown In AnalysisData.runModel"); - - - } /* catch (Exception e) { - System.out.println("In AnalysisData.runModel -- Caught Exception"); - e.printStackTrace(); - throw new Exception("Generic Exception rethrown In AnalysisData.runModel"); - - }*/ - - return outFile; -} -/** - * Modify ArrayList of Downstream Points by sorting by Distance From Dam - * Creation date: (5/24/2004 1:37:00 PM) - */ -public void sortDownstreamByDistance() { - - int toGo = downstream.size(); // determine size of unsorted ArrayList - ArrayList sortedList = new ArrayList(toGo); // and build new ArrayList of same size - - float closestDistance = 1000000.0f; // Assume all will be less than a million miles away - int closestIndex = -1; // none selected at first - - DownstreamPoint dp = null; // reference object - - while (toGo > 0) // loop until we've found them all - { - for (int j = 0; j < downstream.size(); j++) - { - dp = (DownstreamPoint) downstream.get(j); - - if (dp.distanceToSection < closestDistance) // find closest - - { - closestDistance = dp.distanceToSection; // save distance - closestIndex = j; // and location in ArrayList - } - - } - - if (closestIndex > -1) - { - dp = (DownstreamPoint) downstream.get(closestIndex); - sortedList.add(dp); // add to sorted ArrayList - downstream.remove(closestIndex); // remove from unsortedArrayList; - closestIndex = -1; // reset index - closestDistance = 1000000.0f; // and closest distance - toGo--; // decrement counter - - } - } // end while - - downstream = sortedList; // replace with sortedList -} -/** - * This method verifies that the data contained in this AnalysisData - * structure is ready to be run through the model. - * - * NOTE: If a field is empty and a default value may be calculated, - * the data will be changed to reflect the default values. - * - * This may need to be changed because it assumes that some - * values the user enters are incorrect and replaces them. - * - * It returns null if the data is ready or a String containing - * error messages if it is not. - * - */ -public String verifyInput() { - - String strError = ""; - float botElev; - - if (downstream.size() < 1) - { - strError = "Insufficient data to run model - downstream points must be added."; - return strError; - } - - - DownstreamPoint d = (DownstreamPoint)downstream.get(0); // closest to dam - SectionGeometry sg = (SectionGeometry)d.xsections.get(0); // lowest elevation - - // Get lowest elevation at closest downstream point to serve as channel bottom - if (sg.getElevationData(0,1) < 1.0f){ // testing topwidth < 1 foot - botElev = sg.getElevationData(0,0); // storing elevation of first BvsH pair as bottom - } - else - { - botElev = 2.0f * sg.getElevationData(0,0) - sg.getElevationData(1,0); // storing calculation as bottom ??? - } - - float previousUpstreamElevation = 100000000.0f; // start above the Himalayas - - // Examine geometry of each downstream point - for ( int j=0; j < downstream.size(); j++) - { - DownstreamPoint down = (DownstreamPoint)downstream.get(j); - - SectionGeometry section = down.getBestSection(); // only interested in 'best' geometry - if (section == null || down.xsections.size() == 0) { - strError += "There must be at least two elevation-topwidth pairs per downstream point.\n"; - break; - } - - int countEqualElevations = 0; - int countZeroWidth = 0; - int countNegativeWidth = 0; - int countAscendingElevations = 0; - - for (int k=0; k < section.getLastRowUsed(); k++) // only to last non-blank row in array - { - float elev = section.getElevationData(k, 0); // retrieve elevation - if(k == 0) // but only test if first one - { - - if (elev > previousUpstreamElevation) - { - countAscendingElevations++; // increment if any first elevation ascends - } - previousUpstreamElevation = elev; - } - else - { - elev = section.getElevationData(k, 0); - - if(elev == previousUpstreamElevation) - { - countEqualElevations++; // increment if elevations are equal - } - previousUpstreamElevation = elev; - } - float channelWidth = section.getElevationData(k, 1); // retrieve topwidth - - if(channelWidth == 0.0f) - { - countZeroWidth++; // only 1 will be allowed - } - - if(channelWidth < 0.0f) - { - countNegativeWidth++; // no negative topwidths allowed - } - - } - if (countAscendingElevations > 0) - { - strError += "Elevations of the Cross Section must be in descending order to run model \n"; - } - - if (countEqualElevations >= 2) - { - strError += "Not more than two Elevations of the Cross Section can be equal to run model \n"; - } - - if(countZeroWidth > 1) - { - strError += "More than one channel width cannot be 0.0 to run model.\n"; - } - - if(countNegativeWidth > 0) - { - strError += "Channel width(s) cannot be negative to run model.\n"; - } - } - - // Now check the downstream points themselves - if (downstream.size() < 2) - strError += "There must be at least two downstream points\n with at least two elevation-topwidth pairs in each.\n"; - else { - int j; - int j1; - for (j=0; j < downstream.size(); j++) { - j1 = j+1; // j1 points to next downstream point - if (j1 < downstream.size()) { - - if ( ((DownstreamPoint)downstream.get(j)).distanceToSection >= ((DownstreamPoint)downstream.get(j1)).distanceToSection ){ - - strError += "River stations must be in descending order toward downstream.\n"; - strError += "Distance to sections:\n"; - strError += ((DownstreamPoint)downstream.get(j)).distanceToSection; - strError += "\n"; - strError += ((DownstreamPoint)downstream.get(j1)).distanceToSection; - strError += "\n"; - } - } - - if ( ((DownstreamPoint)downstream.get(j)).xsections.size() == 0 ) - { - strError += "Each downstream point must have\n the same number of elevation / width pairs (at least 2).\n"; - // break; - } - - } - - // if (j == downstream.size()) { // this can never be true here !!! - - } - - int howManyPairs = AnalysisData.getNumPairs(downstream); - - if (howManyPairs == -2) - { - strError += "Each of the cross sections marked \"Best\" must have\n the same number of elevation / width pairs (at least 2).\n"; - } - else if (howManyPairs < 2) - { - strError += "There must be at least two cross sections per downstream point.\n"; - } - - // check for at least one scenario - if (scenarios.size() == 0) - strError += "There must be at least one scenario for model to run. \n"; - else { - // check scenarios - for (int i=0; i ((DownstreamPoint)downstream.get(downstream.size()-1)).distanceToSection ){ - - strError += "Scenario "; - strError += scenario.name; - strError += "\nPoint of interest station= "; - strError += scenario.DISTTN; - strError += " exceeds last river station= "; - strError += ((DownstreamPoint)downstream.get(downstream.size()-1)).distanceToSection; - strError += "\n"; - } - - if (pointOfInterestName.compareTo("") == 0) - pointOfInterestName = "Town"; - - if (scenario.CMS <= 0.00f) - scenario.CMS = 0.5f; - } //for loop - } - - if (strError.length() == 0) - return null; - else - return strError; -} -/** - * Insert the method's description here. - * Creation date: (3/1/2004 3:06:06 PM) - * @return java.lang.String - */ -public String verifyOutput() { - String strError = ""; - String rvrName = ""; - - DamInfo damInfo = new DamInfo(); - if (rootDamInfo.size() > 0) - damInfo = (DamInfo) this.rootDamInfo.get(0); - - java.text.DecimalFormat df; - df = new java.text.DecimalFormat("#####0.00"); - - if(scenarios.size() == 0) - bEmptyDataset = true; - else - bEmptyDataset = false; - - for (int j=0; j 0) - { - prerunTextBufferFive.append(" Dam Information:\n"); - prerunTextBufferFive.append(" NID ID: " + damInfo.nidid + "\n"); - prerunTextBufferFive.append(" Latitude: " + damInfo.latitude_dam + "\n"); - prerunTextBufferFive.append(" Longitude: " + damInfo.longitude_dam + "\n"); - prerunTextBufferFive.append(" State ID: " + damInfo.stateid + "\n"); - prerunTextBufferFive.append(" County: " + damInfo.county +"\n\n"); - } - - prerunTextBufferFive.append(" Inputs for this Forecast:\n"); - prerunTextBufferFive.append(" Source: " + scenario.source + "\n"); - prerunTextBufferFive.append(" Scenario: " + scenario.name + "\n"); - prerunTextBufferFive.append(" Starting Water Surface [HDE] (ft MSL): " + scenario.HDE + "\n"); - prerunTextBufferFive.append(" Bottom of Breach Width [BME] (ft MSL): " + scenario.BME + "\n"); - prerunTextBufferFive.append(" Starting Volume [VOL] (acre-ft): " + scenario.VOL + "\n"); - prerunTextBufferFive.append(" Starting Surface Area [SA] (acre): " + scenario.SA + "\n"); - prerunTextBufferFive.append(" Time to Failure (min): " + scenario.TFM + "\n"); - prerunTextBufferFive.append(" Additional Flow to Add [QO] (cfs): " + scenario.QO + "\n"); - prerunTextBufferFive.append(" Final Breach Width [BW] (ft): " + scenario.BW + "\n"); - prerunTextBufferFive.append(" Dam Type Code: " + scenario.damType + "\n"); - - prerunGenericBuffer.append(prerunTextBufferFive.toString()); - - - scenario.output.prerunText = prerunGenericBuffer.toString(); - - //scenario.output.prerunText.setFont(new java.awt.Font("Courier", Font.PLAIN, 14)); - - scenario.output.bHasPrerunText = true; - - //scenario.output.fullText = prerunGenericBuffer.toString(); - //scenario.output.bHasFullText = true; - } catch (Exception e) { - System.out.println("Exception in AnalysisData.verifyOutput()"); - e.printStackTrace(); - } - } - - return strError; -} - public static boolean writeDAM(AnalysisData data, String filename) { - if (filename == null) - return false; - - String lineEnd = "\n"; - FileWriter output; - try { - - // open the file - output = new FileWriter(filename); - - // write out type/version information - output.write("Dambreak Analysis|1|"+lineEnd); - - // write out name information - output.write(data.damName+" |"+data.riverName+" |"+data.pointOfInterestName+" |"+lineEnd); - - // write out the number of input scenarios - output.write(data.scenarios.size()+"|"+lineEnd); - - // write out input scenarios - for (int i=0; i 0 && i < s.length() - 1) - return s.substring(i+1).toLowerCase(); - return ""; - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/DamMapper.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/DamMapper.java deleted file mode 100644 index d6485de828..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/DamMapper.java +++ /dev/null @@ -1,72 +0,0 @@ -package gov.dambreak.util; - -// import com.bbn.openmap.layer.shape.*; -// import com.bbn.openmap.*; -// import com.bbn.openmap.layer.*; -// import com.bbn.openmap.layer.location.*; -import javax.swing.*; -/** - * Class to encapsulate interface to OpenMap software package - * Creation date: (8/5/2003 9:29:21 AM) - * @author: - */ -public class DamMapper extends JFrame { - /** - * DamMapper constructor comment. - * @param title java.lang.String - */ - public DamMapper(String title) { - super(title); - initialize(); - setSize(400,400); - setLocation(616,150); - setVisible(true); - } - /** - * Initialize for OpenMap interface - * Creation date: (8/5/2003 9:29:43 AM) - */ - private void initialize() { - - // Create a MapBean - - /* - MapBean mapBean = new MapBean(); - */ - - // Create a ShapeLayer to show world political boundaries. - // Set the properties of the layer. This assumes that the - // datafiles "dcwpo-browse.shp" and "dcwpo-browse.ssx" are in - // a path specified in the CLASSPATH variable. These files - // are distributed with OpenMap and reside in the toplevel - // "share" subdirectory. - - /* - ShapeLayer shapeLayer = new ShapeLayer(); - Properties shapeLayerProps = new Properties(); - shapeLayerProps.put("prettyName", "Political Solid"); - shapeLayerProps.put("lineColor", "000000"); - shapeLayerProps.put("fillColor", "BDDE83"); - shapeLayerProps.put("shapeFile", "D:/openMap/openmap-4.5.4/share/data/shape/dcwpo-browse.shp"); - shapeLayerProps.put("spatialIndex", "D:/openMap/openmap-4.5.4/share/data/shape/dcwpo-browse.ssx"); - shapeLayer.setProperties(shapeLayerProps); - */ - - // Add the political layer to the map - /* - mapBean.add(shapeLayer); - - LocationLayer loc = new LocationLayer(); - - - loc.setLocationHandlers( new LocationHandler[] { new BasicLocationHandler() } ); - - mapBean.add(loc); - */ - - // Add the map to the frame - /* - getContentPane().add(mapBean); - */ - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/DownstreamPoint.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/DownstreamPoint.java deleted file mode 100644 index 8f3f2459fe..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/DownstreamPoint.java +++ /dev/null @@ -1,54 +0,0 @@ -package gov.dambreak.util; - -/** - * Logical Model Representation Of Downstream Point - * Creation date: (7/29/2003 8:01:02 AM) - * @author: - */ -import java.util.ArrayList; - -public class DownstreamPoint { - public String name; - public String xsecBestType; - public String comments; - public float distanceToSection; - public float floodDepth; - public float floodWidth; - public float floodFlow; - public float latitude; - public float longitude; - public float elevation; - public float mann_oc; - public int bestXS; // index pointing to best XS - public int changeFlag = 0; // 0 = no changes; 1 = updated; 2 = inserted; 3 = deleted - public ArrayList xsections = new ArrayList(); // SectionGeometry - - public ArrayList deletedXsections = new ArrayList(); // SectionGeometry -/** - * DownstreamPoint constructor comment. - */ -public DownstreamPoint() { - name = "NotSpecified"; - distanceToSection = 100.0f; - bestXS = -1; -} -/** - * Method assumes that bestXS index points to proper instance in ArrayList - * Creation date: (7/31/2003 1:24:11 PM) - * @return util.SectionGeometry - */ -public SectionGeometry getBestSection() { - - if (xsections.size() == 0) - return null; - - if (bestXS == -1) - return (SectionGeometry)xsections.get(0); - - if (bestXS >= xsections.size()) - return (SectionGeometry)xsections.get(0); - - return (SectionGeometry)xsections.get(bestXS); - -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/EnumeratedTypes.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/EnumeratedTypes.java deleted file mode 100644 index bad37e70ff..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/EnumeratedTypes.java +++ /dev/null @@ -1,130 +0,0 @@ -package gov.dambreak.util; - -/** - * Insert the type's description here. - * Creation date: (7/28/2003 10:15:58 AM) - * @author: - */ -public class EnumeratedTypes { - //////////////////////////////////////////////// - // NOTE: Please enter all code's in UPPER CASE - //////////////////////////////////////////////// - private static String[] scenario = new String[] { "HF", "HN", "HS", - "MF", "MN", "MS", - "LF", "LN", "LS", - "NS" }; - private static String[] scenario_english = new String[] { "High Fast (HF)", "High Normal (HN)", "High Slow (HS)", - "Medium Fast (MF)", "Medium Normal (MN)", "Medium Slow (MS)", - "Low Fast (LF)", "Low Normal (LN)", "Low Slow (LS)", - "Not Specified"}; - - private static String[] damType = new String[] { "0", "1", "2" }; - private static String[] damType_english = new String[] { "Earth", "Concrete Gravity", "Concrete Arch" }; - - private static String[] xsType = new String[] { "G1","G2","G3","G4", - "M1","M2", - "S1","S2", - "P1", - "R1" }; - private static String[] xsType_english = new String[] { "G1 - GIS: 90 meter data","G2 - GIS: 30 meter data","G3 - GIS: 10 meter data","G4 - GIS: 1 meter data", - "M1 - Manual: 7.5 degree minute","M2 - Manual: 30 x 60 minute", - "S1 - Field: Direct Leveling","S2 - Field: GPS", - "P1 - Parabolic", - "R1 - Prismoidal" }; - - // field type enumeration - public static int FIELD_SCENARIO = 0; - public static int FIELD_DAMTYPE = 1; - public static int FIELD_XSTYPE = 2; - public static int FIELD_DBUG = 3; - private static java.lang.String[] dbug = new String[] { "0", "1", "2" }; - private static java.lang.String[] dbug_english = new String[] { "Off", "On", "System Level" }; -/** - * Given English Description, Return Code - * Creation date: (7/28/2003 10:27:57 AM) - * @return java.lang.String - * @param english java.lang.String - */ -public static String getCode(int field, String english) { - - int found; - if (field == FIELD_SCENARIO) { - for (int i=0; i0 && numPts != numPtsOld) { - JOptionPane.showMessageDialog(null,"Error -- Elev-topwidth messed up? " - + "different number of points detected on line:\n" + line - + " numPtsOld= " + numPtsOld, "Error", JOptionPane.ERROR_MESSAGE); - return false; - } - */ - - distancesForXS[i] = new float[numPts]; - elevationsForXS[i] = new float[numPts]; - - // *** next line contains longitude of Cross Section - line = input.readLine(); - st = new StringTokenizer(line, ",\n\r"); - float lon = Float.parseFloat(st.nextToken()); - - // *** next line contains latitude of Cross Section - line = input.readLine(); - st = new StringTokenizer(line, ",\n\r"); - float lat = Float.parseFloat(st.nextToken()); - - latlons[i] = new Point2D.Float(lat,lon); - - float rmOld = 0.0f; - - for (int k=0; k < numPts; k++) { - line = input.readLine(); - st = new StringTokenizer(line, ",\n\r"); - if (metric) { - riverMiles[i] = Float.parseFloat(st.nextToken()) * 0.62f; - distancesForXS[i][k] = Float.parseFloat(st.nextToken()) * 3.28f; - elevationsForXS[i][k] = Float.parseFloat(st.nextToken()) * 3.28f; - } else { - riverMiles[i] = Float.parseFloat(st.nextToken()); - distancesForXS[i][k] = Float.parseFloat(st.nextToken()); - elevationsForXS[i][k] = Float.parseFloat(st.nextToken()); - } - - if (k>0 && riverMiles[i] != rmOld) { - JOptionPane.showMessageDialog(null,"Error -- Elev-topwidth messed up? " - + "wrong number of points detected on line:\n" + line - + " Old rivermile= " + rmOld, "Error", JOptionPane.ERROR_MESSAGE); - return false; - } - rmOld = riverMiles[i]; - - - - } - - if (line == null) - return true; - } - } catch (NumberFormatException nfe) { - nfe.printStackTrace(); - JOptionPane.showMessageDialog(null,"Error -- bad data in fldxs TXT file on line:\n" - + line, "Error", JOptionPane.ERROR_MESSAGE); - return false; - } catch (Exception e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(null,"Error -- bad data/file in fldxs TXT file on line:\n", - "Error", JOptionPane.ERROR_MESSAGE); - System.out.println("Exception thrown FLDXS txt file: " + e.getMessage()); - return false; - } - return true; - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/MaxLengthDocument.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/MaxLengthDocument.java deleted file mode 100644 index 9ca6020479..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/MaxLengthDocument.java +++ /dev/null @@ -1,32 +0,0 @@ -package gov.dambreak.util; - -import javax.swing.text.*; -import java.awt.Toolkit; - -/** - * This custom document is used by the SMPDBK GUI to restrict the length of the - * DamName, RiverName, and PointOfInterestName text fields. - */ -public class MaxLengthDocument extends DefaultStyledDocument { - - int maxCharacters; - - public MaxLengthDocument(int maxChars) { - maxCharacters = maxChars; - } - public void insertString(int offs, String str, AttributeSet a) - throws BadLocationException - { - - // This rejects the entire insertion if it would make - // the contents too long. - - if (str == null) - System.out.println("The text field value is null"); - - if ((getLength() + str.length()) <= maxCharacters) - super.insertString(offs, str, a); - else - Toolkit.getDefaultToolkit().beep(); - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/ModelOutput.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/ModelOutput.java deleted file mode 100644 index eaf66b222f..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/ModelOutput.java +++ /dev/null @@ -1,459 +0,0 @@ -package gov.dambreak.util; - -import java.io.*; -import java.util.*; -import javax.swing.*; - -/** - * This class allows for the reading of SMPDBK output files. - */ -public class ModelOutput { - - // public fields - public ModelScenario inputScenario = new ModelScenario(); - public ArrayList inputDownstream = new ArrayList(); // DownstreamPoint - - public String source; - public String modelScenario; - public String xsectionType; - - public String damName; - public String riverName; - public String pointOfInterestName; - - public boolean bHasWarning; - public String warning; - public boolean bHasFullText; - public String fullText; - public boolean bHasPrerunText; - public String prerunText; - - public int changeFlag = 0; // 0 = no changes; 1 = updated; 2 = inserted; 3 = deleted - - // output data - public int numberXSections = 0; - - public float outSlope = 0.0f; - public float maxFl = 0.0f; - public float maxEl = 0.0f; - public float maxDep = 0.0f; - public float timeMaxDep = 0.0f; - public float timeFl = 0.0f; - public float timeDefl = 0.0f; - - public float[] maxFlow = new float[50]; - public float[] maxElevation = new float[50]; - public float[] maxDepth = new float[50]; - public float[] timeMaxDepth = new float[50]; - public float[] timeFlood = new float[50]; - public float[] timeDeflood = new float[50]; -/** - * Insert the method's description here. - * Creation date: (7/22/2003 9:00:35 AM) - */ -public ModelOutput() { - bHasFullText = false; - bHasPrerunText = false; - bHasWarning = false; - numberXSections = 0; - - damName = ""; - riverName = ""; - pointOfInterestName = ""; - warning = ""; - fullText = ""; -} -/** - * Insert the method's description here. - * Creation date: (7/23/2003 2:20:43 PM) - * @return int - */ -public int getPointOfInterestXS() { - int count = 0; - try { - if (inputScenario.DISTTN == 0.0) - return inputDownstream.size()-1; - - count = 0; - - // find XS just past DISTTN -//System.out.print("junk getPointOfInterestXS: " + count + "!!!!!\n"); -//System.out.print("junk getPointOfInterestXS: " + inputScenario.DISTTN + "!!!!!\n"); -//System.out.print("junk getPointOfInterestXS: " + ((DownstreamPoint)inputDownstream.get(count)).distanceToSection + "!!!!!\n"); - while ( count < inputDownstream.size() && - inputScenario.DISTTN > ((DownstreamPoint)inputDownstream.get(count)).distanceToSection) - count++; - } catch (Exception e) { - System.out.println("Exception in ModelOutput.getPointOfInterest()"); - e.printStackTrace(); - } - return count; -} - // private methods - private static String[] parseLine(String line) { - int colCount = -1; - int position = 0; - - String result[] = new String[8]; - for (int i=0; i<8; i++) - result[i] = new String(); - - while (position < line.length()) - { - if ((position % 10) == 0) - colCount++; - - if (line.charAt(position) != ' ') - result[colCount] += line.charAt(position); - - position++; - } - return result; - } - private static String[] parseLine2(String line) { - int colCount = -1; - int position = 2; - - String result[] = new String[9]; - for (int i=0; i<9; i++) - result[i] = new String(); - - while (position < line.length()) - { - if (((position-2) % 8) == 0) - colCount++; - - if (line.charAt(position) != ' ') - result[colCount] += line.charAt(position); - - position++; - } - return result; - } - /** - * This method reads the input portion of the *.OUT file. - */ - public static void readInputData(BufferedReader reader, ModelOutput retVal) throws IOException - { - String line; - String[] lineData; - - //read dam name - line = reader.readLine(); - retVal.inputScenario = new ModelScenario(); - retVal.damName = line.substring(13,line.length()); - retVal.damName = retVal.damName.trim(); - - //read river name and point of interest name - line = reader.readLine(); - if (line.length() > 55) - { - retVal.riverName = line.substring(13,55); - retVal.pointOfInterestName = line.substring(55,line.length()); - } - else // no point of interest - { - retVal.riverName = line.substring(13,line.length()); - retVal.pointOfInterestName = ""; - } - - retVal.riverName = retVal.riverName.trim(); - retVal.pointOfInterestName = retVal.pointOfInterestName.trim(); - - //read through next 4 lines - for (int i=0; i<4; i++) - line = reader.readLine(); - - // parse unique data line - retVal.inputScenario.HDE = Float.parseFloat(line.substring(15,23).trim()); - retVal.inputScenario.BME = Float.parseFloat(line.substring(23,31).trim()); - retVal.inputScenario.VOL = Float.parseFloat(line.substring(31,41).trim()); - retVal.inputScenario.SA = Float.parseFloat(line.substring(41,49).trim()); - retVal.inputScenario.BW = Float.parseFloat(line.substring(49,57).trim()); - retVal.inputScenario.TFM = Float.parseFloat(line.substring(57,65).trim()); - retVal.inputScenario.QO = Float.parseFloat(line.substring(65,73).trim()); - } - public static ModelOutput readOUT(String filename) { - - BufferedReader reader; - String line; - ModelOutput retVal = new ModelOutput(); - - try { - // first read in the entire file - reader = new BufferedReader(new FileReader(filename)); - StringBuffer fileTextBuffer = new StringBuffer(); - while ((line = reader.readLine()) != null) - fileTextBuffer.append(line + "\n"); - retVal.fullText = fileTextBuffer.toString(); - retVal.bHasFullText = true; - reader.close(); - - // next read and parse the file - reader = new BufferedReader(new FileReader(filename)); - - // skip past header lines in output file - // " - // SIMPLIFIED DAMBR... - // BY D.L. FREAD, J.M LEWIS... - // NWS HYDROLOGIC RESEA... - // - // " - for (int i=0; i<6; i++) - line = reader.readLine(); - - // read input data into fields - readInputData(reader,retVal); - - // read section elevation data into double type [][] - readSectionElevations(reader,retVal); - - // look for output data table and any possible warnings - do { - line = reader.readLine(); - - // check for a warning - if (line.indexOf("W A R N I N G") != -1) { - reader.readLine(); - for (int i=0; i<5; i++) - retVal.warning += reader.readLine().trim() + "\n"; - retVal.warning += "\n"; - retVal.bHasWarning = true; - } - } while (line.compareTo(" ******** ******** ******** ******** ******** ******** ******** ********") != 0); - - // read output data into fields - if (!readOutputData(reader,retVal)) - return null; - - } catch (Exception e) { - System.out.println("Exception in OutputFileParser::parse()"); - e.printStackTrace(); - return null; - } - return retVal; - } - /** - * This method reads the output portion of the *.OUT file. - */ - public static boolean readOutputData(BufferedReader reader, ModelOutput retVal) throws IOException { - String line; - String lineSave = ""; - StringBuffer warningNan = new StringBuffer(); - - String[] lineData; - int count=0; - - line = reader.readLine(); - if (line == null) - { - System.out.println("In ModelOutput.readOutputData -- null line read !"); - return false; - } - while (line != null) { - - if (line.trim().compareTo("") == 0) { - line = reader.readLine(); - continue; - } - - - if (line.trim().startsWith("ANALYSIS IS COMPLETE")) { - line = reader.readLine(); - continue; - } - - if (line.trim().startsWith("CANNOT CONVERGE")) { - retVal.bHasWarning = true; - retVal.warning += line + "\n"; - line = reader.readLine(); - continue; - } - - if (line.trim().startsWith("(Q=")) { - retVal.warning += line + "\n"; - line = reader.readLine(); - continue; - } - - // *** These Lines are generated by SMPDBK whenever JNK > 0 - - if (line.trim().startsWith("F1=")) { - line = reader.readLine(); - continue; - } - - if (line.trim().startsWith("QS=")) { - line = reader.readLine(); - continue; - } - - - if (line.trim().startsWith("QA=")) { - line = reader.readLine(); - continue; - } - - - if (line.trim().startsWith("XX=")) { - line = reader.readLine(); - continue; - } - - - if (line.trim().startsWith("K=")) { - line = reader.readLine(); - continue; - } - - - if (line.trim().startsWith("SUB=")) { - line = reader.readLine(); - continue; - } - - - try { - - lineData = parseLine(line); - - retVal.maxFlow[count] = Float.parseFloat(lineData[1]); - retVal.maxElevation[count] = Float.parseFloat(lineData[2]); - retVal.maxDepth[count] = Float.parseFloat(lineData[3]); - retVal.timeMaxDepth[count] = Float.parseFloat(lineData[4]); - retVal.timeFlood[count] = Float.parseFloat(lineData[5]); - retVal.timeDeflood[count] = Float.parseFloat(lineData[6]); - count++; - - } catch (NumberFormatException ex) { - System.out.println("In ModelOutput.readOutputData - Number Format Exception on this line: "); - System.out.println(line); - warningNan.append(line + "\n"); - - ex.printStackTrace(); - if (line.trim().compareTo("ANALYSIS IS COMPLETE") != 0) { - // stuff other than output data was included in the model results - // we will show this "stuff" to the user in the "Warnings" tab of the - // output viewer - retVal.bHasWarning = true; - retVal.warning += line + "\n"; - } - } - catch (Exception e) { - System.out.println("In ModelOutput.readOutputData - generic Exception on this line ;"); - System.out.println(line); - e.printStackTrace(); - - } - line = reader.readLine(); - } - - if (retVal.bHasWarning) { - if(retVal.warning.startsWith("ORIGINAL BREACH WIDTH")) - JOptionPane.showMessageDialog(null,"Warning Warning Warning: \n\n" - + retVal.warning, "Warning", JOptionPane.WARNING_MESSAGE); - else - { - retVal.warning = "The Model Output Results are Incomplete, See Details in the Model Run Output File.\n\n"; - JOptionPane.showMessageDialog(null,"Warning Warning Warning: \n\n" - + retVal.warning + warningNan + "\n", "Warning", JOptionPane.WARNING_MESSAGE); - } - } - - return true; - } - /** - * This method reads cross section elevations,tWidthsBS,inactiveTwBss from *.OUT file. - */ - public static void readSectionElevations(BufferedReader reader, ModelOutput retVal) throws IOException { - String line; - String[] lineData; - - // read how many sections from file *.OUT. - line = reader.readLine(); - - int numberXSections = Integer.parseInt(line.substring(18,21).trim()); - - // read how many elevations in each section from file *.OUT. - int numberXSectionElevations = Integer.parseInt(line.substring(30,32).trim()); - - // get DISTTN - retVal.inputScenario.DISTTN = Float.parseFloat(line.substring(56,line.length()).trim()); - - // read elevations,tWidthsBS,inactiveTwBss from *.OUT file - for (int j = 0; j < numberXSections; j++) { - line = reader.readLine(); - line = reader.readLine(); - - DownstreamPoint down = new DownstreamPoint(); - SectionGeometry sg = new SectionGeometry(); - - // C6-j line : Downstream point information - down.distanceToSection = NumFormat.toFloat(line.substring(17,26).trim()); - if (down.distanceToSection == 0) - down.name = "Dam"; - else - down.name = "Town"; // *** This needs to be replaced with original names ! - // down.floodDepth = NumFormat.toFloat(line.substring(34,line.length()).trim()); - down.floodDepth = NumFormat.toFloat(line.substring(34,41).trim()); - - //down.latitude = NumFormat.toFloat(line.substring(52,61).trim()); - //down.longitude = NumFormat.toFloat(line.substring(71,80).trim()); - - - for (int k = 0; k < 8; k++) { - // C7-k : B-vs-H pairs - if (k < numberXSectionElevations) - { - line = reader.readLine(); - lineData = parseLine2(line); - sg.setElevationData(k, 0, NumFormat.toFloat(lineData[2])); - sg.setElevationData(k, 1, NumFormat.toFloat(lineData[4])); - sg.setElevationData(k, 2, NumFormat.toFloat(lineData[6])); - sg.setElevationData(k, 3, NumFormat.toFloat(lineData[8])); - sg.setLastRowUsed(k); - } - else - { - // -999.0 is used to represent a nonexistent pair - sg.setElevationData(k, 0, -999.0f); - sg.setElevationData(k, 1, -999.0f); - sg.setElevationData(k, 2, -999.0f); - sg.setElevationData(k, 3, -999.0f); - } - } - - down.bestXS = 0; - down.xsections.add(sg); - retVal.inputDownstream.add(down); - } - } - public static boolean verify(String filename) { - - if (!(new File(filename).exists())) - { - System.out.println("In ModelOutput.verify - " + filename + " failed existence test"); - return false; - } - BufferedReader input; - String line; - try { - input = new BufferedReader(new FileReader(filename)); - - line = input.readLine(); - while (line != null && line.compareTo(" ******** ******** ******** ******** ******** ******** ******** ********") != 0) { - line = input.readLine(); - } - if (input.readLine() == null) - { - System.out.println("In ModelOutput.verify - null line read"); - return false; - } - } catch (Exception e) { - System.out.println("Exception Caught In ModelOutput.verify"); - e.printStackTrace(); - return false; - } - return true; - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/ModelScenario.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/ModelScenario.java deleted file mode 100644 index c392cddd86..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/ModelScenario.java +++ /dev/null @@ -1,37 +0,0 @@ -package gov.dambreak.util; - -/** - * Insert the type's description here. - * Creation date: (7/28/2003 10:39:30 AM) - * @author: - */ -public class ModelScenario { - // public fields - public String source; - public String name; - public int damType; - public float HDE; - public float BME; - public float VOL; - public float SA; - public float BW; - public float TFM; - public float QO; - public float DISTTN; - public float CMS; - - public int dbugType; - public int changeFlag = 0; // 0 = no changes; 1 = updated; 2 = inserted; 3 = deleted - - public ModelOutput output; - public boolean bOutputAvailable; -/** - * ModelScenario constructor comment. - */ -public ModelScenario() { -// source = "DEF"; - source = "Not Specified"; - name = "NS"; //type of scenario -- set to not specified - bOutputAvailable = false; -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/NumFormat.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/NumFormat.java deleted file mode 100644 index 32d3d3b48e..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/NumFormat.java +++ /dev/null @@ -1,53 +0,0 @@ -package gov.dambreak.util; - -/** - * Insert the type's description here. - * Creation date: (7/23/2003 2:54:28 PM) - * @author: - */ -public class NumFormat { - -/** - * Format a float as a string the given number of decimal places. - * Creation date: (7/23/2003 2:55:12 PM) - * @return java.lang.String - * @param value float - * @param numDecimals int - */ -public static String format(float value, int numDecimals) { - java.text.DecimalFormat df; - - if (numDecimals == 0) - df = new java.text.DecimalFormat("########0."); - else if (numDecimals == 2) - df = new java.text.DecimalFormat("######0.00"); - else if (numDecimals == 3) - df = new java.text.DecimalFormat("#####0.000"); - else - df = new java.text.DecimalFormat("####0.0000"); - - String retVal = null; - try { - retVal = df.format(value); - } catch (Exception e) { - retVal = "NaN"; - } - return retVal; -} -/** - * Insert the method's description here. - * Creation date: (7/29/2003 10:36:23 AM) - * @return float - * @param str java.lang.String - */ -public static float toFloat(String str) { - float retVal; - - try { - retVal = Float.parseFloat(str); - } catch (NumberFormatException e) { - retVal = -999.0f; - } - return retVal; -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/NumbersOnlyDocument.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/NumbersOnlyDocument.java deleted file mode 100644 index 26ce6c654c..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/NumbersOnlyDocument.java +++ /dev/null @@ -1,74 +0,0 @@ -package gov.dambreak.util; - -import javax.swing.text.*; -import java.awt.Toolkit; - -/** - * Derived Class - * Creation date: (7/15/2003 1:07:45 PM) - * @author: - */ -public class NumbersOnlyDocument extends DefaultStyledDocument -{ - /** - * NumbersOnlyDocument constructor comment. - */ - public NumbersOnlyDocument() - { - super(); - } - /** - * NumbersOnlyDocument constructor comment. - * @param c javax.swing.text.AbstractDocument.Content - * @param styles javax.swing.text.StyleContext - */ - public NumbersOnlyDocument(javax.swing.text.AbstractDocument.Content c, javax.swing.text.StyleContext styles) - { - super(c, styles); - } - /** - * NumbersOnlyDocument constructor comment. - * @param styles javax.swing.text.StyleContext - */ - public NumbersOnlyDocument(javax.swing.text.StyleContext styles) - { - super(styles); - } - /** - * Insert the method's description here. - * Creation date: (7/15/2003 1:08:41 PM) - * @param offs int - * @param str java.lang.String - * @param a javax.swing.text.AttributeSet - */ - public void insertString(int offs, String str, AttributeSet a) - throws BadLocationException - { - - // This rejects the entire insertion if it causes - // the text to not remain a number. - String strResult = getText(0,offs) + str + getText(offs,getLength()-offs); - - if (strResult.endsWith("f")) - { - Toolkit.getDefaultToolkit().beep(); - return; - } - - if (getLength() == 0 && str.length() == 1 && (str.charAt(0) == '-' || str.charAt(0) == '+' || str.charAt(0) == '.')) - { - super.insertString(offs, str, a); - return; - } - try - { - if (!str.equals("")) - Double.parseDouble(strResult); - super.insertString(offs, str, a); - } - catch (NumberFormatException e) { - System.out.println("!" + str + "!"); - Toolkit.getDefaultToolkit().beep(); - } - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/PropertyReader.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/PropertyReader.java deleted file mode 100644 index deb319cdf8..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/PropertyReader.java +++ /dev/null @@ -1,192 +0,0 @@ -package gov.dambreak.util; - -/** - * This class is used to get properties from the - * Dambreak Analysis 'resources' file. - */ -import java.util.*; -import java.io.*; - -import ohd.hseb.util.*; - -public class PropertyReader -{ - - private static Properties env = null; - - /** - * This method returns the value of the property contained - * in the Dambreak Analysis 'resources' file or null if the - * property is not found. - * Creation date: (8/4/2003 11:02:25 AM) - */ - public static String getProperty(String strName) - { - if (env == null) - { - String fileName; - String osName = System.getProperty("os.name"); - String lowerCaseName = osName.toLowerCase(); - - if ((fileName = System.getProperty("damcrest.home")) == null) - { - return null; - } - if(lowerCaseName.indexOf("windows") > -1) - { - - if (!fileName.endsWith(System.getProperty("file.separator"))) - { - fileName = fileName.concat(System.getProperty("file.separator")); - } - - fileName = fileName.concat("resources.txt"); - - // Create an InputStream from the file - InputStream stream = null; - env = new Properties(); - try - { - stream = new FileInputStream(new File(fileName)); - if (stream != null) - { - // Read the file into the env Properties - env.load(stream); - stream.close(); - } - - } - catch(Exception e) - { - System.err.println("Could not open resource file \"" + fileName + "\""); - return null; - } - } - else - { - if(lowerCaseName.indexOf("linux") > -1) - { - if (!fileName.endsWith(System.getProperty("file.separator"))) - { - fileName = fileName.concat(System.getProperty("file.separator")); - } - - String resourcesFileName = fileName.concat("resources.txt"); - File fileresources = new File(resourcesFileName); - - if (!fileresources.exists()) - { - ohd.hseb.util.AppsDefaults appsDef = new ohd.hseb.util.AppsDefaults(); - ohd.hseb.util.EnvHelper envHelper = new EnvHelper(); - env = new Properties(); - - String DBConnectionName = "CONNECTION_STRING"; - String DBConnectionString = envHelper.getProperty(DBConnectionName); - if (DBConnectionString != null) - { - DBConnectionString = DBConnectionString.trim(); - env.setProperty(DBConnectionName, DBConnectionString); - } - else - { - System.out.println("DBConnectionString is not set\n"); - } - String DBDriverName = "DBDRIVER"; - String DBDriver = envHelper.getProperty(DBDriverName); - - if (DBDriver != null) - { - DBDriver = DBDriver.trim(); - env.setProperty(DBDriverName, DBDriver); - } - else - { - System.out.println("DBDriver is not set\n"); - } - // TEMPPATH variable is renamed to DAMCREST_DATA_DIR for - // better readability - String tempPathName = "DAMCREST_DATA_DIR"; - String tempPath = envHelper.getProperty(tempPathName); - if (tempPath != null) - { - tempPath = tempPath.trim(); - env.setProperty(tempPathName, tempPath); - } - else - { - System.out.println("DAMCREST_DATA_DIR is not set\n"); - } - String tokenEnabled = "damcrest.db_enabled"; - String strEnabled = appsDef.getToken(tokenEnabled); - if(strEnabled != null) - { - strEnabled = strEnabled.trim(); - env.setProperty(tokenEnabled, strEnabled); - } - else - { - System.out.println("damcrest.db_enabled is not set\n"); - } - String tokenHasListAllDams = "damcrest.hasListAllDams"; - String strHasListAllDams = appsDef.getToken(tokenHasListAllDams); - if(tokenHasListAllDams != null) - { - tokenHasListAllDams = tokenHasListAllDams.trim(); - env.setProperty(tokenHasListAllDams, strHasListAllDams); - } - else - { - System.out.println("damcrest.hasListAllDams is not set\n"); - } - // There is stored gvim resource file .vimrc - String damcrestAppDirPath = "DAMCREST_RES_DIR"; - String damcrestAppDir = envHelper.getProperty(damcrestAppDirPath); - if (damcrestAppDir != null) - { - damcrestAppDir = damcrestAppDir.trim(); - env.setProperty(damcrestAppDirPath, damcrestAppDir); - } - else - { - System.out.println("DAMCREST_RES_DIR is not set\n"); - } - String tokenEditor = "damcrest.editor"; - String strEditor = appsDef.getToken(tokenEditor); - if(strEditor != null) - { - strEditor = strEditor.trim(); - env.setProperty(tokenEditor, strEditor); - } - else - { - System.out.println("damcrest.editor is not set\n"); - } - } - else - { - System.out.println("File \"resources.txt\" exists.\n"); - // Create an InputStream from the file - InputStream stream = null; - env = new Properties(); - try - { - stream = new FileInputStream(fileresources); - if (stream != null) - { - // Read the file into the env Properties - env.load(stream); - stream.close(); - } - } - catch(Exception e) - { - System.err.println("Could not open resource file \"" + fileresources + "\""); - return null; - } - } - } - } - } - return env.getProperty(strName); - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/SectionGeometry.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/SectionGeometry.java deleted file mode 100644 index 605130ccfd..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/SectionGeometry.java +++ /dev/null @@ -1,99 +0,0 @@ -package gov.dambreak.util; - -/** - * Logically encapsulates both a Cross Section Type and it's set of Topwidth-Elevation "pairs" - * Creation date: (7/28/2003 3:54:09 PM) - * @author: - */ -public class SectionGeometry { - private String xsType = null; - private float[][] elevations = new float[8][4]; - - - private int changeFlag = 0; // 0 = no changes; 1 = updated;; 2 = inserted; 3 = deleted - private int lastRowUsed = -1; // used to indicate last Row in array with valid data -/** - * Constructor - */ -public SectionGeometry() { - - xsType = "M1"; - - for (int i=0; i<8; i++) - { - setElevationData(i,0,-999.0f); - setElevationData(i,1,-999.0f); - setElevationData(i,2,-999.0f); - setElevationData(i,3,-999.0f); - } -} -/** - * Insert the method's description here. - * Creation date: (1/7/2004 2:08:15 PM) - * @return int - */ -public int getChangeFlag() { - return changeFlag; -} -/** - * Insert the method's description here. - * Creation date: (7/28/2003 4:02:59 PM) - * @return float - * @param elevation int - * @param type int - */ -public float getElevationData(int elevation, int type) { - return elevations[elevation][type]; -} -/** - * Insert the method's description here. - * Creation date: (1/7/2004 3:35:26 PM) - * @return int - */ -public int getLastRowUsed() { - return lastRowUsed; -} -/** - * Insert the method's description here. - * Creation date: (7/28/2003 4:04:44 PM) - */ -public String getXSType() { - - return xsType; - -} -/** - * Insert the method's description here. - * Creation date: (1/7/2004 2:08:15 PM) - * @param newChangeFlag int - */ -public void setChangeFlag(int newChangeFlag) { - changeFlag = newChangeFlag; -} -/** - * Insert the method's description here. - * Creation date: (7/28/2003 4:03:31 PM) - * @param elevation int - * @param type int - * @param value float - */ -public void setElevationData(int elevation, int type, float value) { - elevations[elevation][type] = value; -} -/** - * Insert the method's description here. - * Creation date: (1/7/2004 3:35:26 PM) - * @param newLastRowUsed int - */ -public void setLastRowUsed(int newLastRowUsed) { - lastRowUsed = newLastRowUsed; -} -/** - * Insert the method's description here. - * Creation date: (7/28/2003 4:05:11 PM) - * @param value java.lang.String - */ -public void setXSType(String value) { - xsType = value; -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/StreamDirector.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/StreamDirector.java deleted file mode 100644 index cbe06118a8..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/StreamDirector.java +++ /dev/null @@ -1,86 +0,0 @@ -package gov.dambreak.util; - -import java.io.*; -/** - * Class to redirect I/O streams to Process(es) invoked via Runtime.exec() - * Creation date: (10/31/02 3:42:35 PM) - * @author: Daniel Urban - */ -public class StreamDirector extends Thread -{ - - java.io.InputStream is; - java.lang.String type; - public java.io.OutputStream os; - - /** - * Abbreviated constructor - * Creation date: (10/31/02 3:54:16 PM) - * @param inStream java.io.InputStream - * @param inType java.lang.String - */ - public StreamDirector(InputStream inStream, String inType) - { - - // Call Alternate constructor - this ( inStream, inType, null ); - - } - /** - * Primary Constructor, currently left private - * until OutputStream logic is verified - * Creation date: (10/31/02 3:57:54 PM) - * @param inStream java.io.InputStream - * @param inType java.lang.String - * @param outStream java.io.OutputStream - */ - StreamDirector(InputStream inStream, String inType, OutputStream outStream) - { - this.is = inStream; - this.type = inType; - this.os = outStream; - } - /** - * automatically invoked by overloaded run() method in - */ - protected void doWork() - { - try - { - PrintWriter pw = null; - if (os != null) - { - pw = new PrintWriter (os); - } - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - String line=null; - - while ( (line=br.readLine()) != null) - { - if (pw != null) - { - pw.println(line); - } - System.out.println(type + ">" + line); - } - if (pw != null) - { - pw.flush(); - } - } - catch (IOException ioe) - { - ioe.printStackTrace(); - } - } - /** - * Overloaded method from Thread - * Creation date: (10/9/2003 2:10:47 PM) - */ - public void run() - { - this.doWork(); - - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TabbedPrinter.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TabbedPrinter.java deleted file mode 100644 index 86f44ab6a0..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TabbedPrinter.java +++ /dev/null @@ -1,253 +0,0 @@ -package gov.dambreak.util; - -/** - * Class to encapsulate printing from Output Manager. - * Creation date: (9/22/2003 11:53:09 AM) - * @author: - */ -import javax.swing.*; -import java.awt.print.*; -import java.awt.*; - - -public class TabbedPrinter implements Printable -{ - private JTabbedPane tabbed; - private JTable jt; - private Component c; - - - - public TabbedPrinter(JTabbedPane _tabbed, JTable _jt) - { - tabbed = _tabbed; - jt = _jt; - int index; - - PrinterJob pj = PrinterJob.getPrinterJob(); - PageFormat format = pj.pageDialog(pj.defaultPage()); - - int indexWarnings = tabbed.indexOfTab("Warnings"); - index = tabbed.getSelectedIndex(); - - // check if the "Warnings" tab appears - if(indexWarnings == -1) - { - if((index == 5) || (index == 6)) - { - try - { - format.setOrientation(PageFormat.PORTRAIT); - } - catch (IllegalArgumentException ia) - { - System.out.println("Error in format.setOrientation"); - ia.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Error in TabbedPrinter constructor"); - e.printStackTrace(); - } - } - else - { - try - { - format.setOrientation(PageFormat.LANDSCAPE); - } - catch (IllegalArgumentException ia) - { - System.out.println("Error in format.setOrientation"); - ia.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Error in TabbedPrinter constructor"); - e.printStackTrace(); - } - } - } - else - { - if((index == 6) || (index == 7)) - { - try - { - format.setOrientation(PageFormat.PORTRAIT); - } - catch (IllegalArgumentException ia) - { - System.out.println("Error in format.setOrientation"); - ia.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Error in TabbedPrinter constructor"); - e.printStackTrace(); - } - } - else - { - try - { - format.setOrientation(PageFormat.LANDSCAPE); - } - catch (IllegalArgumentException ia) - { - System.out.println("Error in format.setOrientation"); - ia.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Error in TabbedPrinter constructor"); - e.printStackTrace(); - } - } - } - - pj.setPrintable(this, format); - if (!pj.printDialog()) - { - System.out.println("Error in pj.printDialog"); - return; - } - try - { - pj.print(); - } - catch (PrinterException pe) - { - System.out.println("Error in pj.print"); - pe.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Error in TabbedPrinter constructor"); - e.printStackTrace(); - } - } - /** - * Insert the method's description here. - */ - public int print(Graphics g, PageFormat format, int pagenum) throws java.awt.print.PrinterException - { - - String osName = System.getProperty("os.name"); - String lowerCaseName = osName.toLowerCase(); - - double scale = 1.0; - int pageIndex = pagenum ; - int index; - index = tabbed.getSelectedIndex(); - - Graphics2D g2 = (Graphics2D) g; - g2.setColor(Color.black); - - if(index == 1) //Output Table is printed in the landscape mode - { - int fontHeight=g2.getFontMetrics().getHeight(); - int fontDesent=g2.getFontMetrics().getDescent(); - - - double pageHeight = format.getImageableHeight()-fontHeight; - double pageWidth = format.getImageableWidth(); - double tableWidth = (double) jt.getColumnModel().getTotalColumnWidth(); - - if (tableWidth >= pageWidth) - { - scale = pageWidth / tableWidth; - } - - double headerHeightOnPage= - jt.getTableHeader().getHeight()*scale; - - double tableWidthOnPage=tableWidth*scale; - - double oneRowHeight=(jt.getRowHeight()+ - jt.getRowMargin())*scale; - int numRowsOnAPage= - (int)((pageHeight-headerHeightOnPage)/oneRowHeight); - double pageHeightForTable=oneRowHeight*numRowsOnAPage; - int totalNumPages= (int)Math.ceil(( - (double)jt.getRowCount())/numRowsOnAPage); - - if(pageIndex >= totalNumPages) - { - return NO_SUCH_PAGE; - } - - if (pageIndex + 1 == totalNumPages) - { - int lastRowPrinted = numRowsOnAPage * pageIndex; - int numRowsLeft = jt.getRowCount() - lastRowPrinted; - /* g2.setClip(0, (int)(pageHeightForTable * pageIndex), - (int) Math.ceil(tableWidthOnPage), - (int) Math.ceil(oneRowHeight * numRowsLeft));*/ - - g2.setClip(50, 50,648,160); - - } - //else clip to the entire area available. - else - { - g2.setClip(0, (int)(pageHeightForTable*pageIndex), - (int) Math.ceil(tableWidthOnPage), - (int) Math.ceil(pageHeightForTable)); - } - - g2.scale(scale,scale); - - g2.translate(72.0, 72.0); - - jt.paint(g2); - - /* g2.scale(1/scale,1/scale); - g2.translate(0f,pageIndex*pageHeightForTable); - g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage), - (int)Math.ceil(headerHeightOnPage)); - g2.scale(scale,scale);*/ - - g2.translate(0.0, -headerHeightOnPage); - jt.getTableHeader().paint(g2); - return Printable.PAGE_EXISTS; - } - else - { - if (pagenum > 0) - { - return Printable.NO_SUCH_PAGE; - } - - int fontHeight=g2.getFontMetrics().getHeight(); - int fontDesent=g2.getFontMetrics().getDescent(); - - - double pageHeight = format.getImageableHeight()-fontHeight; - double pageWidth = format.getImageableWidth(); - double tableWidth = (double) jt.getColumnModel().getTotalColumnWidth(); - - if (tableWidth >= pageWidth) - { - scale = (pageWidth * 0.95) / tableWidth; - } - if(lowerCaseName.indexOf("linux") > -1) - { - if((index == 0) || (index == 4)) - { - g2.scale(1.0, 0.95); // print GUI under tab "Graphics" or - // GUI under tab "Export to FLDVIEW" on the - // Linux - portrait mode - } - } - g2.scale(scale, 0.95); - - // g2.scale(0.73, 0.95); - g2.translate((format.getImageableX() + tableWidth * 0.03), format.getImageableY()); - tabbed.paint(g2); - } - - return Printable.PAGE_EXISTS; - } - -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TableMap.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TableMap.java deleted file mode 100644 index 911e3949d5..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TableMap.java +++ /dev/null @@ -1,63 +0,0 @@ -package gov.dambreak.util; - -/** - * In a chain of data manipulators some behaviour is common. TableMap - * provides most of this behavour and can be subclassed by filters - * that only need to override a handful of specific methods. TableMap - * implements TableModel by routing all requests to its model, and - * TableModelListener by routing all events to its listeners. Inserting - * a TableMap which has not been subclassed into a chain of table filters - * should have no effect. - * - * @version 1.4 12/17/97 - * @author Philip Milne */ - -import javax.swing.table.*; -import javax.swing.event.TableModelListener; -import javax.swing.event.TableModelEvent; - -public class TableMap extends DefaultTableModel // *** was extends AbstractTableModel - implements TableModelListener { - protected TableModel model; - - public Class getColumnClass(int aColumn) { - return model.getColumnClass(aColumn); - } - public int getColumnCount() { - return (model == null) ? 0 : model.getColumnCount(); - } - public String getColumnName(int aColumn) { - return model.getColumnName(aColumn); - } - public TableModel getModel() { - return model; - } - public int getRowCount() { - return (model == null) ? 0 : model.getRowCount(); - } - // By default, implement TableModel by forwarding all messages - // to the model. - - public Object getValueAt(int aRow, int aColumn) { - return model.getValueAt(aRow, aColumn); - } - public boolean isCellEditable(int row, int column) { - return false; //model.isCellEditable(row, column); - } - public void setModel(TableModel model) { - this.model = model; - model.addTableModelListener(this); - } - public void setValueAt(Object aValue, int aRow, int aColumn) { - model.setValueAt(aValue, aRow, aColumn); - } -// -// Implementation of the TableModelListener interface, -// - // By default forward all events to all the listeners. - public void tableChanged(TableModelEvent e) { - - fireTableChanged(e); - - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TablePrinter.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TablePrinter.java deleted file mode 100644 index 01ed513db9..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TablePrinter.java +++ /dev/null @@ -1,106 +0,0 @@ -package gov.dambreak.util; - -/** - * Insert the type's description here. - * Creation date: (8/4/2003 11:53:09 AM) - * @author: - */ -import javax.swing.*; -import java.awt.print.*; -import java.awt.*; - -public class TablePrinter implements Printable -{ - private JTable table; - /** - * Insert the method's description here. - * Creation date: (8/4/2003 11:58:23 AM) - * @param table javax.swing.JTable - * @param tm javax.swing.table.TableModel - */ - public TablePrinter(JTable _table) - { - table = _table; - - PrinterJob pj = PrinterJob.getPrinterJob(); - pj.setPrintable(TablePrinter.this); - if (!pj.printDialog()) - return; - try { - pj.print(); - } catch (Exception PrintException) {} - } - /** - * Insert the method's description here. - */ - public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws java.awt.print.PrinterException - { - - Graphics2D g2 = (Graphics2D) g; - g2.setColor(Color.black); - int fontHeight=g2.getFontMetrics().getHeight(); - int fontDesent=g2.getFontMetrics().getDescent(); - - //leave room for page number - double pageHeight = pageFormat.getImageableHeight()-fontHeight; - double pageWidth = pageFormat.getImageableWidth(); - double tableWidth = (double) table.getColumnModel().getTotalColumnWidth(); - double scale = 1; - if (tableWidth >= pageWidth) - { - scale = pageWidth / tableWidth; - } - - double headerHeightOnPage = table.getTableHeader().getHeight() * scale; - double tableWidthOnPage=tableWidth*scale; - - double oneRowHeight=(table.getRowHeight() + table.getRowMargin())*scale; - int numRowsOnAPage= - (int)((pageHeight-headerHeightOnPage)/oneRowHeight); - double pageHeightForTable=oneRowHeight*numRowsOnAPage; - int totalNumPages= (int)Math.ceil(( - (double)table.getRowCount())/numRowsOnAPage); - if(pageIndex>=totalNumPages) - { - return Printable.NO_SUCH_PAGE; - } - - g2.translate(pageFormat.getImageableX(), - pageFormat.getImageableY()); - g2.drawString("Page: "+(pageIndex+1),(int)pageWidth/2-35, - (int)(pageHeight+fontHeight-fontDesent));//bottom center - - g2.translate(0f,headerHeightOnPage); - g2.translate(0f,-pageIndex*pageHeightForTable); - - //If this piece of the table is smaller than the size available, - //clip to the appropriate bounds. - if (pageIndex + 1 == totalNumPages) - { - int lastRowPrinted = numRowsOnAPage * pageIndex; - int numRowsLeft = table.getRowCount() - lastRowPrinted; - g2.setClip(0, (int)(pageHeightForTable * pageIndex), - (int) Math.ceil(tableWidthOnPage), - (int) Math.ceil(oneRowHeight * numRowsLeft)); - } - //else clip to the entire area available. - else - { - g2.setClip(0, (int)(pageHeightForTable*pageIndex), - (int) Math.ceil(tableWidthOnPage), - (int) Math.ceil(pageHeightForTable)); - } - - g2.scale(scale,scale); - table.paint(g2); - g2.scale(1/scale,1/scale); - g2.translate(0f,pageIndex*pageHeightForTable); - g2.translate(0f, -headerHeightOnPage); - g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage), - (int)Math.ceil(headerHeightOnPage)); - g2.scale(scale,scale); - table.getTableHeader().paint(g2);//paint header at top - - return Printable.PAGE_EXISTS; - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TableSorter.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TableSorter.java deleted file mode 100644 index 3dab1ac2a2..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/TableSorter.java +++ /dev/null @@ -1,312 +0,0 @@ -package gov.dambreak.util; - -/** - * A sorter for TableModels. The sorter has a model (conforming to TableModel) - * and itself implements TableModel. TableSorter does not store or copy - * the data in the TableModel, instead it maintains an array of - * integers which it keeps the same size as the number of rows in its - * model. When the model changes it notifies the sorter that something - * has changed eg. "rowsAdded" so that its internal array of integers - * can be reallocated. As requests are made of the sorter (like - * getValueAt(row, col) it redirects them to its model via the mapping - * array. That way the TableSorter appears to hold another copy of the table - * with the rows in a different order. The sorting algorthm used is stable - * which means that it does not move around rows when its comparison - * function returns 0 to denote that they are equivalent. - * - * @version 1.5 12/17/97 - * @author Philip Milne - */ - -import java.util.*; - -import javax.swing.table.TableModel; -import javax.swing.event.TableModelEvent; - -// Imports for picking up mouse events from the JTable. - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.InputEvent; -import javax.swing.JTable; -import javax.swing.table.JTableHeader; -import javax.swing.table.TableColumnModel; - -public class TableSorter extends TableMap { - int indexes[]; - Vector sortingColumns = new Vector(); - boolean ascending = true; - int compares; - - public TableSorter() { - indexes = new int[0]; // for consistency - } - public TableSorter(TableModel model) { - setModel(model); - } - // There is no-where else to put this. - // Add a mouse listener to the Table to trigger a table sort - // when a column heading is clicked in the JTable. - public void addMouseListenerToHeaderInTable(JTable table) { - final TableSorter sorter = this; - final JTable tableView = table; - tableView.setColumnSelectionAllowed(false); - MouseAdapter listMouseListener = new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - TableColumnModel columnModel = tableView.getColumnModel(); - int viewColumn = columnModel.getColumnIndexAtX(e.getX()); - int column = tableView.convertColumnIndexToModel(viewColumn); - if (e.getClickCount() == 1 && column != -1) { - //System.out.println("Sorting ..."); - int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK; - boolean ascending = (shiftPressed == 0); - sorter.sortByColumn(column, ascending); - } - } - }; - JTableHeader th = tableView.getTableHeader(); - th.addMouseListener(listMouseListener); - } - public void checkModel() { - if (indexes.length != model.getRowCount()) { - System.err.println("Sorter not informed of a change in model."); - } - } - public int compare(int row1, int row2) { - compares++; - for (int level = 0; level < sortingColumns.size(); level++) { - Integer column = (Integer)sortingColumns.elementAt(level); - int result = compareRowsByColumn(row1, row2, column.intValue()); - if (result != 0) { - return ascending ? result : -result; - } - } - return 0; - } - public int compareRowsByColumn(int row1, int row2, int column) { - Class type = model.getColumnClass(column); - TableModel data = model; - - // Check for nulls. - - Object o1 = data.getValueAt(row1, column); - Object o2 = data.getValueAt(row2, column); - - // If both values are null, return 0. - if (o1 == null && o2 == null) { - return 0; - } else if (o1 == null) { // Define null less than everything. - return -1; - } else if (o2 == null) { - return 1; - } - - /* - * We copy all returned values from the getValue call in case - * an optimised model is reusing one object to return many - * values. The Number subclasses in the JDK are immutable and - * so will not be used in this way but other subclasses of - * Number might want to do this to save space and avoid - * unnecessary heap allocation. - */ - - if (type.getSuperclass() == java.lang.Number.class) { - Number n1 = (Number)data.getValueAt(row1, column); - double d1 = n1.doubleValue(); - Number n2 = (Number)data.getValueAt(row2, column); - double d2 = n2.doubleValue(); - - if (d1 < d2) { - return -1; - } else if (d1 > d2) { - return 1; - } else { - return 0; - } - } else if (type == java.util.Date.class) { - Date d1 = (Date)data.getValueAt(row1, column); - long n1 = d1.getTime(); - Date d2 = (Date)data.getValueAt(row2, column); - long n2 = d2.getTime(); - - if (n1 < n2) { - return -1; - } else if (n1 > n2) { - return 1; - } else { - return 0; - } - } else if (type == String.class) { - String s1 = (String)data.getValueAt(row1, column); - String s2 = (String)data.getValueAt(row2, column); - int result = s1.compareTo(s2); - - if (result < 0) { - return -1; - } else if (result > 0) { - return 1; - } else { - return 0; - } - } else if (type == Boolean.class) { - Boolean bool1 = (Boolean)data.getValueAt(row1, column); - boolean b1 = bool1.booleanValue(); - Boolean bool2 = (Boolean)data.getValueAt(row2, column); - boolean b2 = bool2.booleanValue(); - - if (b1 == b2) { - return 0; - } else if (b1) { // Define false < true - return 1; - } else { - return -1; - } - } else { - Object v1 = data.getValueAt(row1, column); - String s1 = v1.toString(); - Object v2 = data.getValueAt(row2, column); - String s2 = v2.toString(); - int result = s1.compareTo(s2); - if (column == 0) { // *** only our first column is integer - try { - Integer i1 = Integer.decode(s1); - Integer i2 = Integer.decode(s2); - if (i1.intValue() > i2.intValue()) { - return 1; - } else if (i1.intValue() < i2.intValue()) { - return -1; - } else { - return 0; - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - if (result < 0) { - return -1; - } else if (result > 0) { - return 1; - } else { - return 0; - } - } - } - // The mapping only affects the contents of the data rows. - // Pass all requests to these rows through the mapping array: "indexes". - - public Object getValueAt(int aRow, int aColumn) { - checkModel(); - return model.getValueAt(indexes[aRow], aColumn); - } - public void n2sort() { - for (int i = 0; i < getRowCount(); i++) { - for (int j = i+1; j < getRowCount(); j++) { - if (compare(indexes[i], indexes[j]) == -1) { - swap(i, j); - } - } - } - } - public void reallocateIndexes() { - int rowCount = model.getRowCount(); - - // Set up a new array of indexes with the right number of elements - // for the new data model. - indexes = new int[rowCount]; - - // Initialise with the identity mapping. - for (int row = 0; row < rowCount; row++) { - indexes[row] = row; - } - } - public void setModel(TableModel model) { - super.setModel(model); - reallocateIndexes(); - } - public void setValueAt(Object aValue, int aRow, int aColumn) { - checkModel(); - model.setValueAt(aValue, indexes[aRow], aColumn); - } - // This is a home-grown implementation which we have not had time - // to research - it may perform poorly in some circumstances. It - // requires twice the space of an in-place algorithm and makes - // NlogN assigments shuttling the values between the two - // arrays. The number of compares appears to vary between N-1 and - // NlogN depending on the initial order but the main reason for - // using it here is that, unlike qsort, it is stable. - public void shuttlesort(int from[], int to[], int low, int high) { - if (high - low < 2) { - return; - } - int middle = (low + high)/2; - shuttlesort(to, from, low, middle); - shuttlesort(to, from, middle, high); - - int p = low; - int q = middle; - - /* This is an optional short-cut; at each recursive call, - check to see if the elements in this subset are already - ordered. If so, no further comparisons are needed; the - sub-array can just be copied. The array must be copied rather - than assigned otherwise sister calls in the recursion might - get out of sinc. When the number of elements is three they - are partitioned so that the first set, [low, mid), has one - element and and the second, [mid, high), has two. We skip the - optimisation when the number of elements is three or less as - the first compare in the normal merge will produce the same - sequence of steps. This optimisation seems to be worthwhile - for partially ordered lists but some analysis is needed to - find out how the performance drops to Nlog(N) as the initial - order diminishes - it may drop very quickly. */ - - if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) { - for (int i = low; i < high; i++) { - to[i] = from[i]; - } - return; - } - - // A normal merge. - - for (int i = low; i < high; i++) { - if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) { - to[i] = from[p++]; - } - else { - to[i] = from[q++]; - } - } - } - public void sort(Object sender) { - checkModel(); - - compares = 0; - // n2sort(); - // qsort(0, indexes.length-1); - shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length); - //System.out.println("Compares: "+compares); - } - public void sortByColumn(int column) { - sortByColumn(column, true); - } - public void sortByColumn(int column, boolean ascending) { - this.ascending = ascending; - sortingColumns.removeAllElements(); - sortingColumns.addElement(new Integer(column)); - sort(this); - super.tableChanged(new TableModelEvent(this)); - } - public void swap(int i, int j) { - int tmp = indexes[i]; - indexes[i] = indexes[j]; - indexes[j] = tmp; - } - public void tableChanged(TableModelEvent e) { - //System.out.println("Sorter: tableChanged"); - reallocateIndexes(); - - super.tableChanged(e); - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/UneditableJTableModel.java b/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/UneditableJTableModel.java deleted file mode 100644 index afe789a4ee..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/dambreak/util/UneditableJTableModel.java +++ /dev/null @@ -1,98 +0,0 @@ -package gov.dambreak.util; - -import java.util.*; - -/** - * This cutom table model is used in the output viewer to disallow editing of - * the output table. - */ -public class UneditableJTableModel extends javax.swing.table.DefaultTableModel { - - private int uneditableAfterRow; - private int fromToPairs; - private Vector uneditableColumns; - - // constuctor - public UneditableJTableModel(java.lang.Object[][] arg1, java.lang.Object[] arg2) { - super(arg1, arg2); - } - // constuctor - public UneditableJTableModel(String[] arg1, int arg2) { - super(arg1, arg2); - } -// constructor -public UneditableJTableModel(int rows, int cols) { - super(rows,cols); - uneditableAfterRow = -1; - fromToPairs = 0; -} -// constructor -public UneditableJTableModel(int rows, int cols, int _uneditableFromCol, int _uneditableToCol) { - super(rows,cols); - int uneditableFromCol, uneditableToCol; - uneditableColumns = new Vector (1); - uneditableFromCol = Math.min(_uneditableFromCol,_uneditableToCol); - uneditableToCol = Math.max(_uneditableFromCol,_uneditableToCol); - uneditableColumns.addElement(new UneditablePairs (_uneditableFromCol, _uneditableToCol)); - fromToPairs = uneditableColumns.size(); - uneditableAfterRow = -1; - // uneditableAfterRow = rows-1; -} - -public UneditableJTableModel(int rows, int cols, int [] _uneditableFromCol, int [] _uneditableToCol) { - super(rows,cols); - int uneditableSize = _uneditableFromCol.length; - uneditableColumns = new Vector (uneditableSize); - - for (int i = 0; i < uneditableSize; i++) - { - uneditableColumns.addElement(new UneditablePairs (_uneditableFromCol[i], _uneditableToCol[i])); - } - fromToPairs = uneditableColumns.size(); - uneditableAfterRow = -1; -} - -public boolean isCellEditable(int row, int col) { - - if (fromToPairs == 0) - return false; - else if (uneditableAfterRow != -1 && row > uneditableAfterRow) - { - return false; - } - else if (fromToPairs > 0) - { - for (int i = 0; i < fromToPairs; i++) - { - UneditablePairs pairs = (UneditablePairs) uneditableColumns.get(i); - if(((col >= pairs.getFromCol()) && (col <= pairs.getToCol()))) - { - return false; - } - } - return true; - } - - return false; -} - - private class UneditablePairs { - private int fromCol; - private int toCol; - - public UneditablePairs (int _fromCol, int _toCol){ - fromCol = Math.min(_fromCol,_toCol); - toCol = Math.max(_fromCol,_toCol); - } - - public int getFromCol() - { - return fromCol; - } - - public int getToCol() - { - return toCol; - } - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/CrossSectionEntryInfo.java b/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/CrossSectionEntryInfo.java deleted file mode 100644 index 7710acd112..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/CrossSectionEntryInfo.java +++ /dev/null @@ -1,171 +0,0 @@ -package gov.damcat.data; - -/** - * This class holds information from the damcat_pair table. - */ -class CrossSectionEntryInfo { - - public String down_name,xsec_type,updated; - public Float elev,tw,mann_n,inactive_width; - public Integer pair_num; - //public java.sql.Date updated; - -/** - * DAMCAT_CrossSectionEntryInfo constructor comment. - */ -public CrossSectionEntryInfo() { - super(); - down_name = ""; - xsec_type = ""; - updated = ""; - elev = new Float(0.0f); - inactive_width = new Float(0.0f); - mann_n = new Float(0.0f); - tw = new Float(0.0f); - pair_num = new Integer(0); -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.String - */ -public java.lang.String getDown_name() { - return down_name; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.Float - */ -public java.lang.Float getElev() { - return elev; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.Float - */ -public java.lang.Float getInactive_width() { - return inactive_width; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.Float - */ -public java.lang.Float getMann_n() { - return mann_n; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.Integer - */ -public java.lang.Integer getPair_num() { - return pair_num; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.Float - */ -public java.lang.Float getTw() { - return tw; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.String - */ -public java.lang.String getUpdated() { - return updated; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @return java.lang.String - */ -public java.lang.String getXsec_type() { - return xsec_type; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newDown_name java.lang.String - */ -public void setDown_name(java.lang.String newDown_name) { - down_name = newDown_name; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newElev java.lang.Float - */ -public void setElev(java.lang.Float newElev) { - elev = newElev; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newInactive_width java.lang.Float - */ -public void setInactive_width(java.lang.Float newInactive_width) { - inactive_width = newInactive_width; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newMann_n java.lang.Float - */ -public void setMann_n(java.lang.Float newMann_n) { - mann_n = newMann_n; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newPair_num java.lang.Integer - */ -public void setPair_num(java.lang.Integer newPair_num) { - pair_num = newPair_num; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newTw java.lang.Float - */ -public void setTw(java.lang.Float newTw) { - tw = newTw; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newUpdated java.lang.String - */ -public void setUpdated(java.lang.String newUpdated) { - updated = newUpdated; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 3:00:37 PM) - * @param newXsec_type java.lang.String - */ -public void setXsec_type(java.lang.String newXsec_type) { - xsec_type = newXsec_type; -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/DBAccess.java b/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/DBAccess.java deleted file mode 100644 index a6687ff333..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/DBAccess.java +++ /dev/null @@ -1,2698 +0,0 @@ -package gov.damcat.data; - -import java.sql.*; -import java.util.*; -import java.util.Date; -import javax.swing.*; -import gov.dambreak.util.*; -import ohd.hseb.db.*; -import gov.damcat.db.*; - - -/** - * This class allows data in the damcat database to be read, edited, and exported - * to/from the SMPDBK GUI. - */ - -public class DBAccess -{ - private java.sql.Connection conn = null; - private String DBDriver, DBConnectionString; - private boolean bConnected = false; - - private ohd.hseb.db.Database _db = null; // to interface with JDBGen - - /** - * Constructor for DBAccess Class - * - * Creation date: (7/14/2003 12:46:52 PM) - */ - public DBAccess() { - bConnected = connect(); - } - /** - * Calculate slope using same formula used in Simplified DamBreak program - * as revised on 10/29/1996 - * - * Creation date: (1/20/2004 2:14:23 PM) - * @return float - * @param dam gov.damcat.data.DamInfo - */ - private float calculateSlope(DamInfo dam) { - - String header = "DBAccess.calculateSlope()"; - // System.out.println(header); - - // first set default value for slope - - float slope = 0.5f; - - // next set constant variables - - double m = 0.5; - double mPlus1 = m + 1.0; - - // then set intermediate results in calculation of xl (Length of Reservoir) - // where xl = (xlFactor1 / xlFactor2) * 6.0 / xlFactor3 - // - // xlFactor1 = ((mPlus1)*volume*43560) - // xlFactor2 = k*pow(height, mPlus1) - // xlFactor3 = (1.0 + 4*pow(m, mPlus1)) - // - // k = crestLength / (sqrt(height)) - - double xl = 0.0; // length of reservoir in feet - double xlMiles = 0.0; // length of reservoir in miles - double xlFactor1 = 0.0; - double xlFactor2 = 0.0; - double xlFactor3 = 0.0; - double k = 0.0; - - // then initialize dam measurements - - double height = 0.0; // Height of Dam in ft - double storage = 0.0; // Storage volume of Dam in Acre-ft - double crestLength = 0.0; // Length of Dam in ft - - // locate actual dam measurements : - - // for height - if (dam.nid_height.floatValue() > 0.0f) - { - height = dam.nid_height.floatValue(); - } - else - if (dam.dam_height.floatValue() > 0.0f) - { - height = dam.dam_height.floatValue(); - } - else - if (dam.structural_height.floatValue() > 0.0f) - { - height = dam.structural_height.floatValue(); - } - else - if (dam.hydraulic_height.floatValue() > 0.0f) - { - height = dam.hydraulic_height.floatValue(); - } - - // for storage - if (dam.nid_storage.floatValue() > 0.0f) - { - storage = dam.nid_storage.floatValue(); - } - else - if (dam.max_storage.floatValue() > 0.0f) - { - storage = dam.max_storage.floatValue(); - } - else - if (dam.normal_storage.floatValue() > 0.0f) - { - storage = dam.normal_storage.floatValue(); - } - - // for crestLength - if (dam.dam_length.floatValue() > 0.0f) - { - crestLength = dam.dam_length.floatValue(); - } - - - // if insufficient measurements, don't bother with calculation, just return default value - if (height == 0.0 || storage == 0.0 || crestLength == 0.0) - { - return slope; - } - - // System.out.println("height = " + height + " storage = " + storage + " crestLength = " + crestLength); - - // calculate k = crestLength / (sqrt(height)) - k = crestLength / (Math.sqrt(height)); - // System.out.println("k = " + k); - - // calculate xlFactor1 = ((mPlus1)*storage*43560) - // NOTE: 43560 is conversion factor from acre-ft to cubic feet - xlFactor1 = mPlus1 * storage * 43560.0; - // System.out.println("xlFactor1 = " + xlFactor1); - - // calculate xlFactor2 = k*pow(height, mPlus1) - xlFactor2 = k * Math.pow(height, mPlus1); - // System.out.println("xlFactor2 = " + xlFactor2); - - // calculate xlFactor3 = (1.0 + 4*pow(m, mPlus1)) - xlFactor3 = 1.0 + (4.0 * Math.pow(m, mPlus1)); - // System.out.println("xlFactor3 = " + xlFactor3); - - // calculate xl= (xlFactor1 / xlFactor2) * 6.0 / xlFactor3 - xl = ((xlFactor1 / xlFactor2) * 6.0) / xlFactor3; - // System.out.println("xl = " + xl); - - // convert from feet to miles - xlMiles = xl / 5280.0; - // System.out.println("xlMiles = " + xlMiles); - - // calculate slope as ft / mile - double dSlope = height / xlMiles; - // System.out.println("dSlope = " + dSlope); - - // cast from double to float - Double doubleSlope = new Double(dSlope); - slope = doubleSlope.floatValue(); - - return slope; - } - /** - * - * Transitioned to JDBGen Structures - * - * Creation date: (7/14/2003 12:50:08 PM) - */ - private boolean connect() { - - getConfigInfo(); - - if (DBDriver == null || DBConnectionString == null) - return false; - - - // **** JDBGen Logic Goes Here - try { - - _db = new ohd.hseb.db.Database(); - _db.setDriverClassName(DBDriver); - _db.connect(DBConnectionString); - conn = _db.getConnection(); - - } catch (Exception ex) { - System.out.println("ERROR: Could not connect. (" + DBDriver + ")"); - ex.printStackTrace(); - return false; - } - - return true; - } - /** - * Insert the method's description here. - * Creation date: (8/13/2004 4:01:35 PM) - * @return boolean - * @param damInfo gov.damcat.data.DamInfo - */ - public boolean deleteDamFeatures(DamInfo damInfo) { - String header = "DBAccess.deleteDamFeatures() "; - - boolean bError = false; - - // JDBGen Code Here - - DamFeaturesRecord featuresRow = new DamFeaturesRecord() ; - DamFeaturesTable featuresTable = new DamFeaturesTable(_db) ; - - try { - featuresRow.setNidid(damInfo.getNidid()); - featuresRow.setOther_dam_name(damInfo.getOther_dam_name()); - featuresRow.setDam_former_name(damInfo.getDam_former_name()); - featuresRow.setStateid(damInfo.getStateid()); - featuresRow.setSection_t_r(damInfo.getSection_t_r()); - featuresRow.setOwner_name(damInfo.getOwner_name()); - featuresRow.setOwner_type(damInfo.getOwner_type()); - featuresRow.setDam_designer(damInfo.getDam_designer()); - featuresRow.setPrivate_on_federal(damInfo.getPrivate_on_federal()); - featuresRow.setDam_type(damInfo.getDam_type()); - featuresRow.setCore(damInfo.getCore()); - featuresRow.setFoundation(damInfo.getFoundation()); - featuresRow.setPurposes(damInfo.getPurposes()); - featuresRow.setYear_completed(damInfo.getYear_completed()); - featuresRow.setYear_modified(damInfo.getYear_modified()); - featuresRow.setEmerg_action_plan(damInfo.getEmerg_action_plan()); - featuresRow.setInspection_date(damInfo.getInspection_date()); - featuresRow.setInspection_freq(damInfo.getInspection_freq()); - featuresRow.setSt_reg_dam(damInfo.getSt_reg_dam()); - featuresRow.setSt_reg_agency(damInfo.getSt_reg_agency()); - featuresRow.setSpillway_type(damInfo.getSpillway_type()); - featuresRow.setOutlet_gates(damInfo.getOutlet_gates()); - featuresRow.setFed_funding(damInfo.getFed_funding()); - featuresRow.setFed_design(damInfo.getFed_design()); - featuresRow.setFed_construction(damInfo.getFed_construction()); - featuresRow.setFed_regulatory(damInfo.getFed_regulatory()); - featuresRow.setFed_inspection(damInfo.getFed_inspection()); - featuresRow.setFed_operation(damInfo.getFed_operation()); - featuresRow.setFed_owner(damInfo.getFed_owner()); - featuresRow.setFed_other(damInfo.getFed_other()); - featuresRow.setSource_agency(damInfo.getSource_agency()); - featuresRow.setTopo_map(damInfo.getTopo_map()); - featuresRow.setComments(damInfo.getComments()); - featuresRow.setPrebreak_avail(damInfo.getPrebreak_avail()); - - String updatedString = getCurrentTime(); - long updated = DbTimeHelper.getLongTimeFromDateTimeString(updatedString); - featuresRow.setUpdated(updated); - - featuresRow.setSpillway_width(damInfo.getSpillway_width().doubleValue()); - featuresRow.setNumber_locks(damInfo.getNumber_locks().doubleValue()); - featuresRow.setLength_locks(damInfo.getLength_locks().doubleValue()); - featuresRow.setWidth_locks(damInfo.getWidth_locks().doubleValue()); - featuresRow.setDrainage_area(damInfo.getDrainage_area().doubleValue()); - featuresRow.setDam_length(damInfo.getDam_length().doubleValue()); - featuresRow.setDam_height(damInfo.getDam_height().doubleValue()); - - featuresRow.setStructural_height(damInfo.getStructural_height().doubleValue()); - - featuresRow.setHydraulic_height(damInfo.getHydraulic_height().doubleValue()); - featuresRow.setNid_height(damInfo.getNid_height().doubleValue()); - featuresRow.setMax_discharge(damInfo.getMax_discharge().doubleValue()); - featuresRow.setVolume_dam(damInfo.getVolume_dam().doubleValue()); - featuresRow.setNormal_storage(damInfo.getNormal_storage().doubleValue()); - featuresRow.setNid_storage(damInfo.getNid_storage().doubleValue()); - featuresRow.setSurface_area(damInfo.getSurface_area().doubleValue()); - featuresRow.setElev(damInfo.getElev().doubleValue()); - - featuresRow.setReturn_flow_region(damInfo.getReturn_flow_region().intValue()); - - featuresTable.delete(featuresRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not delete DamFeatures database table."); - e.printStackTrace(); - bError = true; - } - return !bError; - } - /** - * Delete only the row in the DamMaster table - * Creation date: (1/27/2004 12:16:53 PM) - * @return boolean - * @param damInfo gov.damcat.data.DamInfo - */ - public boolean deleteDamMaster(DamInfo damInfo) { - - String header = "DBAccess.deleteDamMaster table() "; - - boolean bError = false; - - - - // JDBGen Code Here - - DamMasterRecord masterRow = new DamMasterRecord() ; - DamMasterTable masterTable = new DamMasterTable(_db); - - try { - masterRow.setNidid(damInfo.getNidid()); - masterRow.setDam_name(damInfo.getDam_name()); - masterRow.setCounty(damInfo.getCounty()); - masterRow.setRiver(damInfo.getRiver()); - masterRow.setDownstream_hazard(damInfo.getDownstream_hazard()); - masterRow.setHsa(damInfo.getHsa()); - masterRow.setRfc(damInfo.getRfc()); - masterRow.setMax_storage(damInfo.getMax_storage().doubleValue()); - masterRow.setLongitude_dam(damInfo.getLongitude_dam().doubleValue()); - masterRow.setLatitude_dam(damInfo.getLatitude_dam().doubleValue()); - - masterTable.delete(masterRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not delete DamMaster database table."); - e.printStackTrace(); - bError = true; - } - return !bError; - } - /** - * Delete row from damcat_down table - * Creation date: (1/27/2004 12:30:16 PM) - * @return boolean - * @param damID java.lang.String - * @param downEntry gov.damcat.data.DownstreamEntryInfo - */ - public boolean deleteDownstream(String damID, DownstreamEntryInfo downEntry) { - - String header = "DBAccess.deleteDownstream() "; - // System.out.println(header); - - boolean bError = false; - - // JDBGen Code Here - - DownStreamRecord downRow = new DownStreamRecord(); - DownStreamTable downTable = new DownStreamTable(_db); - - try { - - DownstreamEntryInfo down = downEntry; - - downRow.setNidid(damID); - - downRow.setDown_name(down.getDown_name()); - downRow.setComments(down.getComments()); - downRow.setXsec_best_type(down.getXsec_best_type()); - - String updatedString = getCurrentTime(); - long updated = DbTimeHelper.getLongTimeFromDateTimeString(updatedString); - downRow.setUpdated(updated); - - downRow.setLongitude(down.getLongitude().doubleValue()); - downRow.setLatitude (down.getLatitude().doubleValue()); - downRow.setElevation(down.getElevation().doubleValue()); - downRow.setDistance_from_dam(down.getDistance_from_dam().doubleValue()); - downRow.setFlood_flow(down.getFlood_flow().doubleValue()); - downRow.setFlood_depth(down.getFlood_depth().doubleValue()); - downRow.setFlood_width(down.getFlood_width().doubleValue()); - downRow.setMann_oc (down.getMann_oc().doubleValue()); - - downTable.delete(downRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not delete Downstream database table."); - e.printStackTrace(); - bError = true; - } - return !bError; - } - /** - * Delete Dam from damcat_dam table and all dependent tables - * - * Navigate DamInfo structure to determine which specific rows - * are to be deleted from dependent tables - * - * Creation date: (1/22/2004 6:05:00 PM) - * @return boolean - * @param damInfo gov.damcat.data.DamInfo - */ - public boolean deleteEntireDam(DamInfo damInfo) { - - String damID = damInfo.getNidid(); - - for (int j=0; j -1)) - { - String pairString = String.valueOf(pairNum); - String pairClause = " AND pair_num = '" + pairString + "'"; - whereClause = whereClause + pairClause; - } - - try { - - pairTable.delete(whereClause); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not delete selected damcat_pair rows."); - e.printStackTrace(); - bError = true; - } - - return !bError; - } - /** - * Build where clause to delete from damcat_down table based on parameters passed - * To delete ALL downNames, set downName to null - * - * NOTE: The delete rules will also be cascaded to damcat_pair and damcat_out tables - * - * Creation date: (1/27/2004 3:01:01 PM) - * @return boolean - * @param damID java.lang.String - * @param downName java.lang.String - */ - public boolean deleteSelectedPoints(String damID, String downName) { - - String header = "DBAccess.deleteSelectedPoints():"; - boolean bError = false; - - // System.out.println(header); - - DownStreamRecord downRow = new DownStreamRecord(); - DownStreamTable downTable = new DownStreamTable(_db); - - - String whereClause = "WHERE nidid = '" + damID.trim() + "'"; - - if ((downName != null)) - { - String downClause = " AND down_name = '" + downName.trim() + "'"; - whereClause = whereClause + downClause; - } - - try { - - // *** first delete damcat_out and damcat_pair entries - - deleteSelectedOutputs(damID, null, null, downName); - - deleteSelectedPairs(damID, downName, null, -1); - - downTable.delete(whereClause); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not delete selected Downstream rows."); - e.printStackTrace(); - bError = true; - } - return !bError; - } - /** - * Returns true if the dam exists in the damcat_dam table. - */ - public boolean doesDamExist(String strNIDID) { - - // *** JDBGen Code Here - - DamMasterRecord masterRow = null; - DamMasterTable masterTable = new DamMasterTable(_db); - - try { - - String whereClause = "WHERE nidid='" + strNIDID + "'"; - List rowList = masterTable.select(whereClause); - - if (rowList.size() > 0) - { - masterRow = (DamMasterRecord) rowList.get(0); - return true; - } else - { - return false; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:doesDamExist"); - ex.printStackTrace(); - return false; - } - } - /** - * Returns true if the scenario exists in the damcat_in table. - */ - private boolean doesScenarioExist(String strNIDID, String src, String scenario) { - - // *** JDBGen Code Here - - SdbInRecord inRow = null; - SdbInTable inTable = new SdbInTable(_db); - - try { - - String whereClause = "WHERE nidid='" + strNIDID + "' AND src='" + src + "' AND scenario='" + scenario + "'"; - List rowList = inTable.select(whereClause); - - if (rowList.size() > 0) - { - inRow = (SdbInRecord) rowList.get(0); - return true; - - } else - { - return false; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:doesScenarioExist"); - ex.printStackTrace(); - return false; - } - - // *** Pre-JDBGen Code Below - - /* - - Statement stmt = null; - ResultSet rs = null; - boolean bError = false; - boolean bExists = false; - - try { - - stmt = conn.createStatement(); - String query; - - query = "SELECT hde " + - "FROM damcat_in WHERE nidid='" + strNIDID + "' AND src='" + src + "' AND scenario='" + scenario + "'"; - - rs = stmt.executeQuery(query); - - bExists = rs.next(); - - } catch (SQLException ex) { - bError = true; - System.out.println("ERROR: Could not query database."); - System.out.println("SQLException: " + ex.getMessage()); - System.out.println("SQLState: " + ex.getSQLState()); - System.out.println("VendorError: " + ex.getErrorCode()); - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - } - rs = null; - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - } - stmt = null; - } - } - return bExists; - */ - } - /** - * This method will return a full DamInfo structure. - * Creation date: (7/15/2003 3:03:08 PM) - * @param dam DamInfo - */ - public DamInfo fillCompletely(String NIDID) { - - DamInfo ret = new DamInfo(); - - // store NIDID - ret.nidid = NIDID; - - if (!fillDamInfo(ret) || !fillInput(ret) || !fillDownstream(ret) || !fillCrossSection(ret) || !fillOutput(ret)) - ret._nFilled = 0; - else - ret._nFilled = 2; - - return ret; - } - /** - * Retrieve rows from damcat_pair table and transfer data to CrossSectionEntryInfo structure - * Creation date: (7/15/2003 4:14:10 PM) - * @param ret DamInfo - */ - private boolean fillCrossSection(DamInfo ret) { - - // *** JDBGen Code Here - - - String whereClause = "WHERE nidid='" + ret.nidid + "'" + - " ORDER BY down_name, xsec_type, pair_num"; - - SectionPairRecord pairRow = null; - SectionPairTable pairTable = new SectionPairTable(_db); - - try { - - List rowList = pairTable.select(whereClause); - - if (rowList.size() > 0) - { - ret._crossSectionEntries = new ArrayList(); - - for (int r = 0; r < rowList.size(); r++) { - - pairRow = (SectionPairRecord) rowList.get(r); - CrossSectionEntryInfo xsEntry = new CrossSectionEntryInfo(); - - - xsEntry.down_name = pairRow.getDown_name(); - xsEntry.xsec_type = pairRow.getXsec_type(); - - long updatedLong = pairRow.getUpdated(); - xsEntry.updated = DbTimeHelper.getDateTimeStringFromLongTime(updatedLong); - - xsEntry.elev = new Float(pairRow.getElev()); - xsEntry.tw = new Float(pairRow.getTw()); - xsEntry.mann_n = new Float(pairRow.getMann_n()); - xsEntry.inactive_width = new Float(pairRow.getInactive_width()); - - xsEntry.pair_num = new Integer(pairRow.getPair_num()); - - // System.out.println("DBAccess.fillCrossSection: " + xsEntry.down_name + "-" + xsEntry.xsec_type + "-" + xsEntry.pair_num); - // System.out.println(" VALUES = " + pairRow.getElev() + "," + pairRow.getTw() + "," + pairRow.getMann_n() + "," + pairRow.getInactive_width()); - ret._crossSectionEntries.add(xsEntry); - - } - - return true; - - } else - { - return true; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:fillOutput"); - ex.printStackTrace(); - return false; - } - } - /** - * Retrieve rows from damcat_dam table and transfer data to DamInfo structure - * Creation date: (7/15/2003 4:15:24 PM) - * @param ret DamInfo - */ - private boolean fillDamInfo(DamInfo ret) { - - // *** JDBGen Code Here - - String whereClause = "WHERE nidid='" + ret.nidid + "'"; - - DamMasterRecord masterRow = null; - DamMasterTable masterTable = new DamMasterTable(_db); - - DamFeaturesRecord featuresRow = null; - DamFeaturesTable featuresTable = new DamFeaturesTable(_db); - - try { - - List rowMasterList = masterTable.select(whereClause); - - if (rowMasterList.size() > 0) - { - masterRow = (DamMasterRecord) rowMasterList.get(0); - ret.nidid = masterRow.getNidid().trim(); - ret.dam_name = masterRow.getDam_name(); - ret.county = masterRow.getCounty(); - ret.river = masterRow.getRiver(); - ret.downstream_hazard = masterRow.getDownstream_hazard(); - ret.hsa = masterRow.getHsa(); - ret.rfc = masterRow.getRfc(); - ret.max_storage = new Float(masterRow.getMax_storage()); - ret.longitude_dam = new Float(masterRow.getLongitude_dam()); - ret.latitude_dam = new Float(masterRow.getLatitude_dam()); - } - List rowFeaturesList = featuresTable.select(whereClause); - - if (rowFeaturesList.size() > 0) - { - featuresRow = (DamFeaturesRecord) rowFeaturesList.get(0); - ret.nidid = featuresRow.getNidid().trim(); - ret.other_dam_name = featuresRow.getOther_dam_name(); - ret.dam_former_name = featuresRow.getDam_former_name(); - ret.stateid = featuresRow.getStateid(); - ret.section_t_r = featuresRow.getSection_t_r(); - ret.owner_name = featuresRow.getOwner_name(); - ret.owner_type = featuresRow.getOwner_type(); - ret.dam_designer = featuresRow.getDam_designer(); - ret.private_on_federal = featuresRow.getPrivate_on_federal(); - ret.dam_type = featuresRow.getDam_type(); - ret.core = featuresRow.getCore(); - ret.foundation = featuresRow.getFoundation(); - ret.purposes = featuresRow.getPurposes(); - ret.year_completed = featuresRow.getYear_completed(); - ret.year_modified = featuresRow.getYear_modified(); - ret.emerg_action_plan = featuresRow.getEmerg_action_plan(); - ret.inspection_date = featuresRow.getInspection_date(); - ret.inspection_freq = featuresRow.getInspection_freq(); - ret.st_reg_dam = featuresRow.getSt_reg_dam(); - ret.st_reg_agency = featuresRow.getSt_reg_agency(); - ret.spillway_type = featuresRow.getSpillway_type(); - ret.outlet_gates = featuresRow.getOutlet_gates(); - ret.fed_funding = featuresRow.getFed_funding(); - ret.fed_design = featuresRow.getFed_design(); - ret.fed_construction = featuresRow.getFed_construction(); - ret.fed_regulatory = featuresRow.getFed_regulatory(); - ret.fed_inspection = featuresRow.getFed_inspection(); - ret.fed_operation = featuresRow.getFed_operation(); - ret.fed_owner = featuresRow.getFed_owner(); - ret.fed_other = featuresRow.getFed_other(); - ret.source_agency = featuresRow.getSource_agency(); - ret.topo_map = featuresRow.getTopo_map(); - ret.comments = featuresRow.getComments(); - ret.prebreak_avail = featuresRow.getPrebreak_avail(); - - long updatedLong = featuresRow.getUpdated(); - ret.updated = DbTimeHelper.getDateTimeStringFromLongTime(updatedLong); - - ret.spillway_width = new Float(featuresRow.getSpillway_width()); - ret.number_locks = new Float(featuresRow.getNumber_locks()); - ret.length_locks = new Float(featuresRow.getLength_locks()); - ret.width_locks = new Float(featuresRow.getWidth_locks()); - ret.drainage_area = new Float(featuresRow.getDrainage_area()); - ret.dam_length = new Float(featuresRow.getDam_length()); - ret.dam_height = new Float(featuresRow.getDam_height()); - ret.structural_height = new Float(featuresRow.getStructural_height()); - ret.hydraulic_height = new Float(featuresRow.getHydraulic_height()); - ret.nid_height = new Float(featuresRow.getNid_height()); - ret.max_discharge = new Float(featuresRow.getMax_discharge()); - ret.volume_dam = new Float(featuresRow.getVolume_dam()); - ret.normal_storage = new Float(featuresRow.getNormal_storage()); - ret.nid_storage = new Float(featuresRow.getNid_storage()); - ret.surface_area = new Float(featuresRow.getSurface_area()); - ret.elev = new Float(featuresRow.getElev()); - - ret.return_flow_region = new Integer(featuresRow.getReturn_flow_region()); - - return true; - } else - { - return false; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:fillDamInfo"); - ex.printStackTrace(); - return false; - } - } - /** - * Read damcat_down table and transfer data to DownstreamEntryInfo structures - * Creation date: (7/15/2003 4:13:54 PM) - * @param ret DamInfo - */ - private boolean fillDownstream(DamInfo ret) { - - // *** JDBGen Code Here - - String whereClause = "WHERE nidid='" + ret.nidid + "'" + - " ORDER BY distance_from_dam"; - - - DownStreamRecord downRow = null; - DownStreamTable downTable = new DownStreamTable(_db); - - try { - - List rowList = downTable.select(whereClause); - - if (rowList.size() > 0) - { - ret._downstreamEntries = new ArrayList(); - - for (int r = 0; r < rowList.size(); r++) { - - downRow = (DownStreamRecord) rowList.get(r); - DownstreamEntryInfo downEntry = new DownstreamEntryInfo(); - - downEntry.down_name = downRow.getDown_name(); - downEntry.comments = downRow.getComments(); - downEntry.xsec_best_type = downRow.getXsec_best_type(); - - long updatedLong = downRow.getUpdated(); - downEntry.updated = DbTimeHelper.getDateTimeStringFromLongTime(updatedLong); - - downEntry.longitude = new Float(downRow.getLongitude()); - downEntry.latitude = new Float(downRow.getLatitude()); - downEntry.elevation = new Float(downRow.getElevation()); - downEntry.distance_from_dam = new Float(downRow.getDistance_from_dam()); - downEntry.flood_flow = new Float(downRow.getFlood_flow()); - downEntry.flood_depth = new Float(downRow.getFlood_depth()); - downEntry.flood_width = new Float(downRow.getFlood_width()); - downEntry.mann_oc = new Float(downRow.getMann_oc()); - - ret._downstreamEntries.add(downEntry); - - } - - return true; - - } else - { - return true; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:fillDownstream"); - ex.printStackTrace(); - return false; - } - } - /** - * Read damcat_in table and transfer data to InputEntryInfo structures - * Creation date: (7/15/2003 4:14:27 PM) - * @param ret DamInfo - */ - private boolean fillInput(DamInfo ret) { - - - // *** JDBGen Code Here - - String whereClause = "WHERE nidid='" + ret.nidid + "'" + - " ORDER BY src, scenario"; - - SdbInRecord inRow = null; - SdbInTable inTable = new SdbInTable(_db); - - try { - - List rowList = inTable.select(whereClause); - - if (rowList.size() > 0) - { - ret._inputEntries = new ArrayList(); - - for (int r = 0; r < rowList.size(); r++) { - - inRow = (SdbInRecord) rowList.get(r); - InputEntryInfo inEntry = new InputEntryInfo(); - - inEntry.src = inRow.getSrc(); - inEntry.scenario = inRow.getScenario(); - inEntry.comments = inRow.getComments(); - - long updatedLong = inRow.getUpdated(); - inEntry.updated = DbTimeHelper.getDateTimeStringFromLongTime(updatedLong); - - inEntry.hde = new Float(inRow.getHde()); - inEntry.bme = new Float(inRow.getBme()); - inEntry.vol = new Float(inRow.getVol()); - inEntry.sa = new Float(inRow.getSa()); - inEntry.tfm = new Float(inRow.getTfm()); - inEntry.qo = new Float(inRow.getQo()); - inEntry.bw = new Float(inRow.getBw()); - - inEntry.idam = new Integer(inRow.getIdam()); - - ret._inputEntries.add(inEntry); - - } - - return true; - - } else - { - return true; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:fillInput"); - ex.printStackTrace(); - return false; - } - } - /** - * Read damcat_out table and transfer data to OutputEntryInfo structures - * Creation date: (7/15/2003 4:14:20 PM) - * @param ret DamInfo - */ - private boolean fillOutput(DamInfo ret) { - - // *** JDBGen Code Here - - - String whereClause = "WHERE nidid='" + ret.nidid + "'" + - " ORDER BY src, scenario, down_name "; // ???? check this !!!! - - SdbOutRecord outRow = null; - SdbOutTable outTable = new SdbOutTable(_db); - - try { - - List rowList = outTable.select(whereClause); - - if (rowList.size() > 0) - { - ret._outputEntries = new ArrayList(); - - for (int r = 0; r < rowList.size(); r++) { - - outRow = (SdbOutRecord) rowList.get(r); - OutputEntryInfo outEntry = new OutputEntryInfo(); - - outEntry.src = outRow.getSrc(); - outEntry.scenario = outRow.getScenario(); - outEntry.down_name = outRow.getDown_name(); - outEntry.comments = outRow.getComments(); - - long updatedLong = outRow.getUpdated(); - outEntry.updated = DbTimeHelper.getDateTimeStringFromLongTime(updatedLong); - - outEntry.slope = new Float(outRow.getSlope()); - outEntry.max_flow = new Float(outRow.getMax_flow()); - outEntry.max_depth = new Float(outRow.getMax_depth()); - outEntry.time_max_depth = new Float(outRow.getTime_max_depth()); - outEntry.time_flood = new Float(outRow.getTime_flood()); - outEntry.time_deflood = new Float(outRow.getTime_deflood()); - - - ret._outputEntries.add(outEntry); - - } - - return true; - - } else - { - return true; - } - - } catch (Exception ex) { - System.out.println("In DBAccess:fillOutput"); - ex.printStackTrace(); - return false; - } - } - /** - * Find highest "manually" added nidid within given state - * and return next available unique nidid - * - * Creation date: (1/22/2004 6:03:20 PM) - * @return java.lang.String - * @param stateID java.lang.String - */ - public String findNextID(String stateID) { - - String statePlus99 = stateID + "99"; // user defined nidid's are assigned this range - - String whereClause = "where nidid like '" - + statePlus99 - + "%'" - + " order by nidid desc"; - - String highKey = null; - String highKeyNumeric = null; - - int nextKeyNumber = 0; - int indexNumeric = 0; - - String nextKey = null; - - DamMasterRecord masterRow = null; - DamMasterTable masterTable = new DamMasterTable(_db); - - try { - - List rowList = masterTable.selectNRecords(whereClause, 10); // just select highest row - - if (rowList.size() > 0) - { - masterRow = (DamMasterRecord) rowList.get(0); - - highKey = masterRow.getNidid(); // get ID - highKeyNumeric = highKey.substring(2).trim(); // isolate numeric portion - nextKeyNumber = Integer.parseInt(highKeyNumeric) + 1; // convert to int and add 1 - nextKey = stateID + Integer.toString(nextKeyNumber); // convert back to String - } - else - { - nextKey = statePlus99 + "001"; // first user-defined nidid in this state - } - - } catch (Exception ex) { - System.out.println("In DBAccess:findNextID"); - ex.printStackTrace(); - return null; - } - - return nextKey; - } - /** - * Retrieve ConnectionString and JDBC Driver strings - * Creation date: (7/14/2003 12:51:55 PM) - */ - private void getConfigInfo() { - - DBConnectionString = PropertyReader.getProperty("CONNECTION_STRING"); - if (DBConnectionString != null) - DBConnectionString = DBConnectionString.trim(); - - DBDriver = PropertyReader.getProperty("DBDRIVER"); - if (DBDriver != null) - DBDriver = DBDriver.trim(); - } - /** - * Insert the method's description here. - * Creation date: (11/7/2003 5:55:29 PM) - * @return java.lang.String - */ - public static String getCurrentTime() { - Timestamp timeSt; - String curTime = ""; - String curTimeSubstr = ""; - - timeSt = new Timestamp (new Date().getTime()); - curTime = timeSt.toString(); - int index = curTime.indexOf('.'); - curTimeSubstr = curTime.substring(0, index); - // System.out.println("Timestamp is: " + curTimeSubstr); - return curTimeSubstr; - } - /** - * Insert the method's description here. - * Creation date: (3/23/2004 2:40:38 PM) - * @return boolean - */ - public static boolean hasListAllDams() { - - // *** The value of "damcrest.hasListAllDams" could be stored - // in the resources.txt or set as apps defaults token - String strHasListAllDams = PropertyReader.getProperty("damcrest.hasListAllDams"); - - if (strHasListAllDams == null) - return false; - - return strHasListAllDams.trim().equalsIgnoreCase("true"); - } - /** - * Insert DamCatDam - * Creation date: (1/22/2004 4:58:37 PM) - * @return boolean - * @param damInfo gov.damcat.data.DamInfo - */ - public boolean insertDamFeatures(DamInfo damInfo) { - - String header = "DBAccess.insertDamFeatures() "; - //System.out.println(header); - - boolean bError = false; - - DamFeaturesRecord featuresRow = new DamFeaturesRecord() ; - DamFeaturesTable featuresTable = new DamFeaturesTable(_db); - - try { - featuresRow.setNidid(damInfo.getNidid()); - featuresRow.setOther_dam_name(damInfo.getOther_dam_name()); - featuresRow.setDam_former_name(damInfo.getDam_former_name()); - featuresRow.setStateid(damInfo.getStateid()); featuresRow.setSection_t_r(damInfo.getSection_t_r()); - featuresRow.setOwner_name(damInfo.getOwner_name()); - featuresRow.setOwner_type(damInfo.getOwner_type()); - featuresRow.setDam_designer(damInfo.getDam_designer()); - featuresRow.setPrivate_on_federal(damInfo.getPrivate_on_federal()); - featuresRow.setDam_type(damInfo.getDam_type()); - featuresRow.setCore(damInfo.getCore()); - featuresRow.setFoundation(damInfo.getFoundation()); - featuresRow.setPurposes(damInfo.getPurposes()); - featuresRow.setYear_completed(damInfo.getYear_completed()); - featuresRow.setYear_modified(damInfo.getYear_modified()); - featuresRow.setEmerg_action_plan(damInfo.getEmerg_action_plan()); - featuresRow.setInspection_date(damInfo.getInspection_date()); - featuresRow.setInspection_freq(damInfo.getInspection_freq()); - featuresRow.setSt_reg_dam(damInfo.getSt_reg_dam()); - featuresRow.setSt_reg_agency(damInfo.getSt_reg_agency()); - featuresRow.setSpillway_type(damInfo.getSpillway_type()); - featuresRow.setOutlet_gates(damInfo.getOutlet_gates()); - featuresRow.setVolume_dam(damInfo.getVolume_dam().doubleValue()); - featuresRow.setFed_funding(damInfo.getFed_funding()); - featuresRow.setFed_design(damInfo.getFed_design()); - featuresRow.setFed_construction(damInfo.getFed_construction()); - featuresRow.setFed_regulatory(damInfo.getFed_regulatory()); - featuresRow.setFed_inspection(damInfo.getFed_inspection()); - featuresRow.setFed_operation(damInfo.getFed_operation()); - featuresRow.setFed_owner(damInfo.getFed_owner()); - featuresRow.setFed_other(damInfo.getFed_other()); - featuresRow.setSource_agency(damInfo.getSource_agency()); - featuresRow.setTopo_map(damInfo.getTopo_map()); - featuresRow.setComments(damInfo.getComments()); - featuresRow.setPrebreak_avail(damInfo.getPrebreak_avail()); - - String updatedString = getCurrentTime(); - long updated = DbTimeHelper.getLongTimeFromDateTimeString(updatedString); - featuresRow.setUpdated(updated); - - featuresRow.setSpillway_width(damInfo.getSpillway_width().doubleValue()); - featuresRow.setNumber_locks(damInfo.getNumber_locks().doubleValue()); - featuresRow.setLength_locks(damInfo.getLength_locks().doubleValue()); - featuresRow.setWidth_locks(damInfo.getWidth_locks().doubleValue()); - featuresRow.setDrainage_area(damInfo.getDrainage_area().doubleValue()); - featuresRow.setDam_height(damInfo.getDam_height().doubleValue()); - featuresRow.setDam_length(damInfo.getDam_length().doubleValue()); - featuresRow.setStructural_height(damInfo.getStructural_height().doubleValue()); - featuresRow.setHydraulic_height(damInfo.getHydraulic_height().doubleValue()); - featuresRow.setNid_height(damInfo.getNid_height().doubleValue()); - featuresRow.setMax_discharge(damInfo.getMax_discharge().doubleValue()); - featuresRow.setNormal_storage(damInfo.getNormal_storage().doubleValue()); - featuresRow.setNid_storage(damInfo.getNid_storage().doubleValue()); - featuresRow.setSurface_area(damInfo.getSurface_area().doubleValue()); - featuresRow.setElev(damInfo.getElev().doubleValue()); - - featuresRow.setReturn_flow_region(damInfo.getReturn_flow_region().intValue()); - - featuresTable.insert(featuresRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not insert into DamFeatures database table\nCheck for duplicate keys."); - e.printStackTrace(); - bError = true; - return false; - } - return true; - } - /** - * InsertDamMaster - * Creation date: (5/4/2004 4:58:37 PM) - * @return boolean - * @param damInfo gov.damcat.data.DamInfo - */ - - public boolean insertDamMaster(DamInfo damInfo) { - - String header = "DBAccess.insertDamMaster() "; - System.out.println(header); - - boolean bError = false; - - DamMasterRecord masterRow = new DamMasterRecord() ; - DamMasterTable masterTable = new DamMasterTable(_db); - - try { - masterRow.setNidid(damInfo.getNidid()); - masterRow.setDam_name(damInfo.getDam_name()); - masterRow.setRiver(damInfo.getRiver()); - masterRow.setCounty(damInfo.getCounty()); - masterRow.setHsa(damInfo.getHsa()); - masterRow.setRfc(damInfo.getRfc()); - masterRow.setLongitude_dam(damInfo.getLongitude_dam().doubleValue()); - masterRow.setLatitude_dam(damInfo.getLatitude_dam().doubleValue()); - masterRow.setMax_storage(damInfo.getMax_storage().doubleValue()); - masterRow.setDownstream_hazard(damInfo.getDownstream_hazard()); - - masterTable.insert(masterRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not insert into DamMaster database table\nCheck for duplicate keys."); - e.printStackTrace(); - bError = true; - return false; - } - return true; - } - /** - * Insert the method's description here. - * Creation date: (1/22/2004 5:01:55 PM) - * @return boolean - * @param downEntry gov.damcat.data.DownstreamEntryInfo - */ - public boolean insertDownstream(String damID, DownstreamEntryInfo downEntry) { - - String header = "DBAccess.insertDownstream() "; - // System.out.println(header); - - boolean bError = false; - - // JDBGen Code Here - - DownStreamRecord downRow = new DownStreamRecord(); - DownStreamTable downTable = new DownStreamTable(_db); - - try { - - DownstreamEntryInfo down = downEntry; - - downRow.setNidid(damID); - - downRow.setDown_name(down.getDown_name()); - downRow.setComments(down.getComments()); - downRow.setXsec_best_type(down.getXsec_best_type()); - - String updatedString = getCurrentTime(); - long updated = DbTimeHelper.getLongTimeFromDateTimeString(updatedString); - downRow.setUpdated(updated); - - downRow.setLongitude(down.getLongitude().doubleValue()); - downRow.setLatitude (down.getLatitude().doubleValue()); - downRow.setElevation(down.getElevation().doubleValue()); - downRow.setDistance_from_dam(down.getDistance_from_dam().doubleValue()); - downRow.setFlood_flow(down.getFlood_flow().doubleValue()); - downRow.setFlood_depth(down.getFlood_depth().doubleValue()); - downRow.setFlood_width(down.getFlood_width().doubleValue()); - downRow.setMann_oc (down.getMann_oc().doubleValue()); - - downTable.insert(downRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not insert into Downstream database table.\nCheck for duplicate keys."); - e.printStackTrace(); - bError = true; - } - return !bError; - } - /** - * parse DamInfo structure and insert all rows into DBMS - * Creation date: (1/22/2004 5:06:46 PM) - * @return boolean - * @param damInfo gov.damcat.data.DamInfo - */ - public boolean insertEntireDam(DamInfo damInfo) { - - String header = "DBAccess.insertEntireDam()"; - //System.out.println(header); - - boolean bError = false; - - String damID = damInfo.getNidid(); - - try { - insertDamMaster(damInfo); - insertDamFeatures(damInfo); - - for (int j=0; j= 2 && !whereClause.substring(whereClause.length()-4,whereClause.length()).equals("AND")) - whereClause = whereClause.substring(0,whereClause.length()-4); - - whereClause += " order by dam_name"; - } - - // System.out.println("whereClause: " + whereClause); - - List rowList = masterTable.select(whereClause); - - // List rowList = damTable.select(whereClause); - - - if (rowList.size() > 0) - - for (int r = 0; r < rowList.size(); r++) - { - masterRow = (DamMasterRecord) rowList.get(r); - - searchResults.add(new DamInfo(masterRow.getDam_name(),masterRow.getRiver(),masterRow.getCounty(),masterRow.getNidid(),masterRow.getHsa(),masterRow.getRfc(),masterRow.getDownstream_hazard(),new Float(masterRow.getMax_storage()),new Float(masterRow.getLatitude_dam()),new Float(masterRow.getLongitude_dam()))); - } - - } catch (Exception ex) { - System.out.println("In DBAccess:search()"); - ex.printStackTrace(); - } - - return searchResults; - } - /** - * Insert the method's description here. - * Creation date: (3/31/2004 4:52:51 PM) - */ - public DamInfo searchCommandLine(String nidid) - { - DamInfo damInfo = new DamInfo(); - - String whereClause = ""; - - DamMasterRecord masterRow = null; - DamMasterTable masterTable = new DamMasterTable(_db); - - try { - whereClause = "WHERE nidid = '" + nidid + "'"; - - System.out.println("DBAccess.searchCommandLine() whereClause: " + whereClause); - List rowList = masterTable.select(whereClause); - - if (rowList.size() > 0) - - for (int r = 0; r < rowList.size(); r++) - { - masterRow = (DamMasterRecord) rowList.get(r); - damInfo.setNidid(masterRow.getNidid()); - damInfo.setRiver(masterRow.getRiver()); - damInfo.setCounty(masterRow.getCounty()); - } - - } catch (Exception ex) { - System.out.println("In DBAccess:searchCommandLine()"); - ex.printStackTrace(); - } - - return damInfo; - - } - private void trace() - { - try - { - throw new Exception("trace"); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - /** - * @param damInfo - * @return - */ - /** - * This method writes the relevant data contained in the - * given damInfo structure to the DamFeatures database table. - * Creation date: (7/21/2003 8:00:09 AM) - * @param damInfo DamInfo - */ - public boolean updateDamFeatures(DamInfo damInfo) { - String header = "DBAccess.updateDamFeatures() "; - //System.out.println(header); - - boolean bError = false; - - // JDBGen Code Here - - DamFeaturesRecord featuresRow = new DamFeaturesRecord() ; - DamFeaturesTable featuresTable = new DamFeaturesTable(_db); - - try { - featuresRow.setNidid(damInfo.getNidid().trim()); - featuresRow.setOther_dam_name(damInfo.getOther_dam_name()); - featuresRow.setDam_former_name(damInfo.getDam_former_name()); - featuresRow.setStateid(damInfo.getStateid()); - featuresRow.setSection_t_r(damInfo.getSection_t_r()); - featuresRow.setOwner_name(damInfo.getOwner_name()); - featuresRow.setOwner_type(damInfo.getOwner_type()); - featuresRow.setDam_designer(damInfo.getDam_designer()); - featuresRow.setPrivate_on_federal(damInfo.getPrivate_on_federal()); - featuresRow.setDam_type(damInfo.getDam_type()); - featuresRow.setCore(damInfo.getCore()); - featuresRow.setFoundation(damInfo.getFoundation()); - featuresRow.setPurposes(damInfo.getPurposes()); - featuresRow.setYear_completed(damInfo.getYear_completed()); - featuresRow.setYear_modified(damInfo.getYear_modified()); - featuresRow.setEmerg_action_plan(damInfo.getEmerg_action_plan()); - featuresRow.setInspection_date(damInfo.getInspection_date()); - featuresRow.setInspection_freq(damInfo.getInspection_freq()); - featuresRow.setSt_reg_dam(damInfo.getSt_reg_dam()); - featuresRow.setSt_reg_agency(damInfo.getSt_reg_agency()); - featuresRow.setSpillway_type(damInfo.getSpillway_type()); - featuresRow.setOutlet_gates(damInfo.getOutlet_gates()); - featuresRow.setVolume_dam(damInfo.getVolume_dam().doubleValue()); - featuresRow.setFed_funding(damInfo.getFed_funding()); - featuresRow.setFed_design(damInfo.getFed_design()); - featuresRow.setFed_construction(damInfo.getFed_construction()); - featuresRow.setFed_regulatory(damInfo.getFed_regulatory()); - featuresRow.setFed_inspection(damInfo.getFed_inspection()); - featuresRow.setFed_operation(damInfo.getFed_operation()); - featuresRow.setFed_owner(damInfo.getFed_owner()); - featuresRow.setFed_other(damInfo.getFed_other()); - featuresRow.setSource_agency(damInfo.getSource_agency()); - featuresRow.setTopo_map(damInfo.getTopo_map()); - featuresRow.setComments(damInfo.getComments()); - featuresRow.setPrebreak_avail(damInfo.getPrebreak_avail()); - - String updatedString = getCurrentTime(); - long updated = DbTimeHelper.getLongTimeFromDateTimeString(updatedString); - featuresRow.setUpdated(updated); - - featuresRow.setSpillway_width(damInfo.getSpillway_width().doubleValue()); - featuresRow.setNumber_locks(damInfo.getNumber_locks().doubleValue()); - featuresRow.setLength_locks(damInfo.getLength_locks().doubleValue()); - featuresRow.setWidth_locks(damInfo.getWidth_locks().doubleValue()); - featuresRow.setDrainage_area(damInfo.getDrainage_area().doubleValue()); - featuresRow.setDam_length(damInfo.getDam_length().doubleValue()); - featuresRow.setDam_height(damInfo.getDam_height().doubleValue()); - featuresRow.setStructural_height(damInfo.getStructural_height().doubleValue()); - featuresRow.setHydraulic_height(damInfo.getHydraulic_height().doubleValue()); - featuresRow.setNid_height(damInfo.getNid_height().doubleValue()); - featuresRow.setMax_discharge(damInfo.getMax_discharge().doubleValue()); - featuresRow.setNormal_storage(damInfo.getNormal_storage().doubleValue()); - featuresRow.setNid_storage(damInfo.getNid_storage().doubleValue()); - featuresRow.setSurface_area(damInfo.getSurface_area().doubleValue()); - featuresRow.setElev(damInfo.getElev().doubleValue()); - - featuresRow.setReturn_flow_region(damInfo.getReturn_flow_region().intValue()); - - featuresTable.insertOrUpdate(featuresRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not update DamFeatures database table."); - e.printStackTrace(); - bError = true; - } - - return !bError; - } - /** - * This method writes the relevant data contained in the - * given damInfo structure to the DamMaster database table. - * Creation date: (5/4/2003 4:00:09 PM) - * @param damInfo DamInfo - */ - public boolean updateDamMaster(DamInfo damInfo) { - String header = "DBAccess.updateDamMaster() "; - //System.out.println(header); - - boolean bError = false; - - // JDBGen Code Here - - DamMasterRecord masterRow = new DamMasterRecord() ; - DamMasterTable masterTable = new DamMasterTable(_db); - - try { - masterRow.setNidid(damInfo.getNidid().trim()); - masterRow.setDam_name(damInfo.getDam_name()); - masterRow.setCounty(damInfo.getCounty()); - masterRow.setRiver(damInfo.getRiver()); - masterRow.setDownstream_hazard(damInfo.getDownstream_hazard()); - masterRow.setHsa(damInfo.getHsa()); - masterRow.setRfc(damInfo.getRfc()); - masterRow.setMax_storage(damInfo.getMax_storage().doubleValue()); - masterRow.setLongitude_dam(damInfo.getLongitude_dam().doubleValue()); - masterRow.setLatitude_dam(damInfo.getLatitude_dam().doubleValue()); - - masterTable.insertOrUpdate(masterRow); - - } catch (Exception e) { - JOptionPane.showMessageDialog(null,"Error: Could not update DamMaster database table."); - e.printStackTrace(); - bError = true; - } - - return !bError; - } - /** - * This method writes the relevant data contained in the - * given damInfo structure to the damcat_down database. - * Creation date: (7/22/2003 7:51:29 AM) - * @return boolean - * @param damInfo damcat.DamInfo - */ - public boolean updateDownstream(DamInfo damInfo, boolean [] changedArray) { - - String header = "DBAccess.updateDownstream() "; - //System.out.println(header); - - boolean bError = false; - - // JDBGen Code Here - - DownStreamRecord downRow = new DownStreamRecord(); - DownStreamTable downTable = new DownStreamTable(_db); - - try { - for (int j=0; j 0) - { - updatedDam = (DamInfo) newData.rootDamInfo.get(0); - } - else - { - updatedDam = new DamInfo(); - } - - updatedDam.nidid = strNIDID; - updatedDam.dam_name = newData.damName; - updatedDam.river = newData.riverName; - - if (!updateDamMaster(updatedDam)) - throw new Exception("Failed to update DamMaster table."); - - // *** make new ArrayLists - - updatedDam._inputEntries = new ArrayList(); - updatedDam._downstreamEntries = new ArrayList(); - updatedDam._crossSectionEntries = new ArrayList(); - updatedDam._outputEntries = new ArrayList(); - - // update SdbIn table - - int scenarioCount = newData.scenarios.size(); - - boolean [] changedScenarios = new boolean [scenarioCount]; - - for (int i=0; i 0) changedScenarios[i] = true; - - in.src = scenario.source; - in.scenario = scenario.name; - in.hde = new Float(scenario.HDE); - in.bme = new Float(scenario.BME); - in.vol = new Float(scenario.VOL); - in.sa = new Float(scenario.SA); - in.qo = new Float(scenario.QO); - in.bw = new Float(scenario.BW); - in.tfm = new Float(scenario.TFM); - in.idam = new Integer(scenario.damType); - - updatedDam._inputEntries.add(in); - } - - if (!updateSdbIn(updatedDam, changedScenarios)) - { System.out.println(header + "updateSdbIn failed"); - throw new Exception("Failed to update SdbIn table."); - } - - // handle any deleted ModelScenarios - - for (int i=0; i 0) changedDownstreamPoints[i] = true; - - down.down_name = dp.name; - down.comments = dp.comments; - down.xsec_best_type = dp.xsecBestType; - down.distance_from_dam = new Float(dp.distanceToSection); - - // *** note that "flood depth" is changed to "flood elevation" before storing in database ! - down.flood_depth = new Float(dp.floodDepth + dp.elevation); - - down.flood_width = new Float(dp.floodWidth); - down.flood_flow = new Float(dp.floodFlow); - down.latitude = new Float(dp.latitude); - down.longitude = new Float(dp.longitude); - down.elevation = new Float(dp.elevation); - down.mann_oc = new Float(dp.mann_oc); - - updatedDam._downstreamEntries.add(down); - - } - - if (!updateDownstream(updatedDam, changedDownstreamPoints)) - { System.out.println(header + "updateDownstream failed"); - throw new Exception("Failed to update Downstream table."); - } - - // handle any deleted DownstreamPoints - - for (int i=0; i 0) - { - changedPairs[p] = true; - //System.out.println(p + " is changed"); - } else - { - changedPairs[p] = false; - //System.out.println(p + " is not"); - } - } - - if (!updateSectionPair(updatedDam, changedPairs)) - { System.out.println(header + "updateSectionPair failed"); - throw new Exception("Failed to update SectionPair table."); - } - - // *** handle any deleted SectionGeometries - - for (int i=0; i < newData.downstream.size(); i++) - { - - DownstreamPoint dpx = (DownstreamPoint) newData.downstream.get(i); // first get DownstreamPoint - - for (int j = 0; j < dpx.deletedXsections.size(); j++) - { - - SectionGeometry sg = (SectionGeometry) dpx.xsections.get(j); - - if (!deleteSelectedPairs(strNIDID, dpx.name, sg.getXSType(), -1)) - { - System.out.println(header + "deleteSectionPair failed"); - throw new Exception("Failed to delete SectionPair table."); - } - - } - - } - - // *** Finally update SdbOut table - - ArrayList changedOutputArrayList = new ArrayList(); - - for (int s=0; s < newData.scenarios.size(); s++) // for each model scenario - { - - ModelScenario scenario = (ModelScenario)newData.scenarios.get(s); - ModelOutput out = scenario.output; - - - int nSections = out.inputDownstream.size(); // for each downstream point - - for (int i=0; i< nSections; i++) - { - - DownstreamPoint down = (DownstreamPoint) out.inputDownstream.get(i); - OutputEntryInfo outEntry = new OutputEntryInfo(); - - Integer changedOutput = new Integer(out.changeFlag); - changedOutputArrayList.add(changedOutput); // each Output needs its own flag, - // although they should always be changed in sets - - outEntry.src = scenario.source; - outEntry.scenario = scenario.name; - outEntry.down_name = down.name; - outEntry.comments = ""; - - outEntry.slope = new Float(calculateSlope(updatedDam)); - outEntry.max_flow = new Float(out.maxFlow[i]); - // = out.maxDepth[i]; // NOT USED - // **** NOTE that maxElevation is stored in database under maxDepth column name !!! **** - outEntry.max_depth = new Float(out.maxElevation[i]); - outEntry.time_max_depth = new Float(out.timeMaxDepth[i]); - outEntry.time_flood = new Float(out.timeFlood[i]); - outEntry.time_deflood = new Float(out.timeDeflood[i]); - - updatedDam._outputEntries.add(outEntry); - } - - - } - - // *** convert ArrayList of Integers to array of booleans - - int outputCount = changedOutputArrayList.size(); - boolean [] changedOutputs = new boolean [outputCount]; - - for (int a = 0; a < changedOutputArrayList.size(); a++) - { - Integer thisInteger = (Integer) changedOutputArrayList.get(a); - int thisValue = thisInteger.intValue(); - if (thisValue > 0) - { - changedOutputs[a] = true; - // System.out.println(a + " is changed"); - } else - { - changedOutputs[a] = false; - // System.out.println(a + " is not"); - } - } - - if (!updateSdbOut(updatedDam, changedOutputs)) - { System.out.println(header + "updateSdbOut failed"); - throw new Exception("Failed to update SdbOut table."); - } - } - /** - * This method writes the relevant data contained in the - * given damInfo strucutre to the damcat_in database. - * - * NOTE: Currently, it will only update existing scenarios - * in the table. If the given DamInfo structure has a scenario - * that is not currently in the database, the method will return - * false. The method should be changed to add any new scenario - * that is not currently represented in the database. This is - * the same for all the DBAccess::updateDamcat*(DamInfo) methods. - * - */ - public boolean updateSdbIn(DamInfo damInfo, boolean[] changedArray) { - - String header = "DBAccess.updateSdbIn():"; - //System.out.println(header); - - boolean bError = false; - - // JDBGen Code Here - - SdbInRecord inRow = new SdbInRecord(); - SdbInTable inTable = new SdbInTable(_db); - - try { - for (int j=0; j 0) - { - s.DISTTN = ((DownstreamEntryInfo)_downstreamEntries.get(_downstreamEntries.size()-1)).distance_from_dam.floatValue(); - s.CMS = ((DownstreamEntryInfo)_downstreamEntries.get(_downstreamEntries.size()-1)).mann_oc.floatValue(); - } else - { - s.DISTTN = 1.0f; - s.CMS = 0.05f; - } - - // build ModelOutput and DownStreamPoint structures for this ModelScenario - s.output = getModelOutput(i); - - if (s.output == null) - { - s.bOutputAvailable = false; - } - else - { - s.bOutputAvailable= true; - // assign reference from OutputModel back to ModelScenario - s.output.inputScenario = s; - } - - retVal.scenarios.add(s); - } - - // if DownstreamPoints exist use the name of the last one as the 'point of interest name' - if (_downstreamEntries.size() > 0) - retVal.pointOfInterestName = ((DownstreamEntryInfo)_downstreamEntries.get(_downstreamEntries.size()-1)).down_name; - else - retVal.pointOfInterestName = "Town"; - - // create DownstreamPoints from the DownstreamEntryInfo structures - for (int i=0; i<_downstreamEntries.size(); i++) { - - DownstreamPoint d = new DownstreamPoint(); - - DownstreamEntryInfo down = (DownstreamEntryInfo)_downstreamEntries.get(i); - - d.name = down.getDown_name(); - - // System.out.println(i + " Point = " + d.name); - - d.comments = down.getComments(); - d.xsecBestType = down.getXsec_best_type(); - - d.distanceToSection = down.getDistance_from_dam().floatValue(); - - /* - * flood depths in DAMCAT are actually flood elevations - * SMPDBK expects actual flood "depth" - */ - // *** note that "flood depth" is actually stored in database as "flood elevation" ! - // d.floodDepth = down.getFlood_depth().floatValue(); - //float fix = 100.0f; - - d.floodDepth = down.getFlood_depth().floatValue() - down.getElevation().floatValue(); - //System.out.println("in getAnalysisData() floodDepth: " + d.floodDepth); - d.floodWidth = down.getFlood_width().floatValue(); - d.floodFlow = down.getFlood_flow().floatValue(); - d.latitude = down.getLatitude().floatValue(); - d.longitude = down.getLongitude().floatValue(); - d.elevation = down.getElevation().floatValue(); - - d.mann_oc = down.getMann_oc().floatValue(); - - d.bestXS = -1; // initially unknown - - String lastXsecType = ""; - int countXsecType = 0; - - // *** Assign Section Geometry - - SectionGeometry xsection = new SectionGeometry(); - - for (int j=0; j<_crossSectionEntries.size(); j++) { - - CrossSectionEntryInfo cross = (CrossSectionEntryInfo)_crossSectionEntries.get(j); - - if (!cross.down_name.trim().equalsIgnoreCase(down.down_name.trim())) - { - continue; // *** disregard if not associated with this downstream point !!! - } - - if (!lastXsecType.equalsIgnoreCase(cross.xsec_type)) // test for first occurrence of xsec_type - { - if (d.xsecBestType.equalsIgnoreCase(cross.xsec_type)) // test if xsec_type is same as best - { - d.bestXS = countXsecType; // set best index - } - - countXsecType = countXsecType + 1; // increment index - - if (lastXsecType != "") - { - d.xsections.add(xsection); // if not the first - } - xsection = new SectionGeometry(); - lastXsecType = cross.xsec_type; - } - - xsection.setXSType(cross.xsec_type); - - // *** Note order of columns : elev, tw, inactive_width, mann_n - - xsection.setElevationData(cross.pair_num.intValue(),0,cross.elev.floatValue()); - xsection.setElevationData(cross.pair_num.intValue(),1,cross.tw.floatValue()); - xsection.setElevationData(cross.pair_num.intValue(),2,cross.inactive_width.floatValue()); - xsection.setElevationData(cross.pair_num.intValue(),3,cross.mann_n.floatValue()); - - xsection.setLastRowUsed(cross.pair_num.intValue()); // keep track of how many rows in array are filled - - } - - if (xsection.getLastRowUsed() == -1 || xsection.getXSType() == null) - { - ; - } else { - d.xsections.add(xsection); // add last xsection as long as it's not empty - } - - retVal.downstream.add(d); - } - - // *** Add logic to attach ModelOutput and DownstreamPoint structures to appropriate - // *** ModelScenario structure - - for (int k = 0; k < _outputEntries.size(); k++) - { - OutputEntryInfo outEntry = (OutputEntryInfo)_outputEntries.get(k); - continue; - /* - OutputEntryInfo outEntry = new OutputEntryInfo(); - - outEntry.src - outEntry.scenario - outEntry.down_name = outRow.getDown_name(); - outEntry.comments = outRow.getComments(); - - long updatedLong = outRow.getUpdated(); - outEntry.updated = DbTimeHelper.getDateTimeStringFromLongTime(updatedLong); - - outEntry.slope = new Float(outRow.getSlope()); - outEntry.max_flow = new Float(outRow.getMax_flow()); - outEntry.max_depth = new Float(outRow.getMax_depth()); - outEntry.time_max_depth = new Float(outRow.getTime_max_depth()); - outEntry.time_flood = new Float(outRow.getTime_flood()); - outEntry.time_deflood = new Float(outRow.getTime_deflood()); - - */ - } - - - retVal.rootDamInfo.add(this); // finally provide reference to DamInfo so original dam data is preserved - - return retVal; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getComments() { - return comments; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getCore() { - return core; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getCounty() { - return county; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getDam_designer() { - return dam_designer; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getDam_former_name() { - return dam_former_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getDam_height() { - return dam_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getDam_length() { - return dam_length; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getDam_name() { - return dam_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getDam_type() { - return dam_type; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getDownstream_hazard() { - return downstream_hazard; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getDrainage_area() { - return drainage_area; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getElev() { - return elev; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getEmerg_action_plan() { - return emerg_action_plan; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_construction() { - return fed_construction; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_design() { - return fed_design; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_funding() { - return fed_funding; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_inspection() { - return fed_inspection; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_operation() { - return fed_operation; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_other() { - return fed_other; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_owner() { - return fed_owner; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFed_regulatory() { - return fed_regulatory; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getFoundation() { - return foundation; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getHsa() { - return hsa; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getHydraulic_height() { - return hydraulic_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getInspection_date() { - return inspection_date; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getInspection_freq() { - return inspection_freq; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getLatitude_dam() { - return latitude_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getLength_locks() { - return length_locks; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getLongitude_dam() { - return longitude_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getMax_discharge() { - return max_discharge; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.Float - */ -public java.lang.Float getMax_storage() { - return max_storage; -} -/** - * Builds a ModelOutput structure from OutputEntryInfo classes and - * appropriate DownStreamPoint and SectionGeometry structures - * from DownstreamEntryInfo and CrossSectionEntryInfo classes - * - * Creation date: (7/22/2003 8:59:36 AM) - * @return ModelOutput - * @param scenario int - */ -public ModelOutput getModelOutput(int scenario) { - - String methodName = "*** DamInfo.getModelOutput()"; - // System.out.println(methodName + " " + scenario); - - ModelOutput ret = new ModelOutput(); - - try { - // return empty ModelOutput structure if database was not read properly - if (_nFilled != 2) { - ret = null; - return ret; - } - - // retrieve appropriate damcat_in fields and - // COPY to new ModelScenario referenced inside ModelOutput structure - // *** is this still necessary ??? - - InputEntryInfo in = (InputEntryInfo)_inputEntries.get(scenario); - - ret.inputScenario.source = in.src; - ret.inputScenario.name = in.scenario; - // System.out.println( "src-scenario = " + in.src +" " + in.scenario); - - ret.inputScenario.damType = in.idam.intValue(); - - String strScenario = in.scenario; - - ret.inputScenario.BME = in.bme.floatValue(); - ret.inputScenario.BW = in.bw.floatValue(); - ret.inputScenario.HDE = in.hde.floatValue(); - ret.inputScenario.QO = in.qo.floatValue(); - ret.inputScenario.SA = in.sa.floatValue(); - ret.inputScenario.TFM = in.tfm.floatValue(); - ret.inputScenario.VOL = in.vol.floatValue(); - - ret.inputScenario.dbugType = 0; // dbugType is not part of InputEntryInfo - ret.inputScenario.changeFlag = 0; // set to no changes - ret.inputScenario.bOutputAvailable = false; - - // get point of interest data from last Downstream Point - ret.pointOfInterestName = ((DownstreamEntryInfo)_downstreamEntries.get(_downstreamEntries.size()-1)).getDown_name(); - - ret.inputScenario.CMS = 0.5f; - ret.inputScenario.DISTTN = ((DownstreamEntryInfo)_downstreamEntries.get(_downstreamEntries.size()-1)).getDistance_from_dam().floatValue(); - - // determine how many points and how many pairs - int nDownPts = _downstreamEntries.size(); - int nPairs = _crossSectionEntries.size() / nDownPts; // don't use, this appears to be a bad assumption !!! - - // create DownstreamPoints from the DownstreamEntryInfo structures - for (int i=0; i < nDownPts; i++) { - - DownstreamEntryInfo down = (DownstreamEntryInfo)_downstreamEntries.get(i); - DownstreamPoint dp = new DownstreamPoint(); - - dp.name = down.getDown_name(); - dp.comments = down.getComments(); - dp.xsecBestType = down.getXsec_best_type(); - dp.distanceToSection = down.getDistance_from_dam().floatValue(); - /* - * DAMCAT stores "flood depth" as "flood elevation" in database - * SMPDBK expects actual "flood depth" - */ - // dp.floodDepth = down.getFlood_depth().floatValue(); - - //float fix = 100.0f; - dp.floodDepth = down.getFlood_depth().floatValue() - down.getElevation().floatValue(); - dp.floodWidth = down.getFlood_width().floatValue(); - dp.floodFlow = down.getFlood_flow().floatValue(); - dp.latitude = down.getLatitude().floatValue(); - dp.longitude = down.getLongitude().floatValue(); - dp.elevation = down.getElevation().floatValue(); - dp.mann_oc = down.getMann_oc().floatValue(); - - dp.bestXS = -1; // index pointing to best XS - dp.changeFlag = 0; // 0 = no changes; 1 = updated; 2 = inserted; 3 = deleted - - // dp.xsections = new ArrayList(); // initialized in ModelOutput constructor - - // *** Assign Section Geometry to DownstreamPoints by examining CrossSectionEntryInfo structures - String prevXsecType = ""; - int countXsecType = 0; - - SectionGeometry xsection = new SectionGeometry(); - - for (int j=0; j < _crossSectionEntries.size(); j++) { - - CrossSectionEntryInfo cross = (CrossSectionEntryInfo)_crossSectionEntries.get(j); - - if (!cross.down_name.trim().equalsIgnoreCase(down.down_name.trim())) - { - continue; // *** disregard if not associated with this downstream point - } - - if (!prevXsecType.equalsIgnoreCase(cross.xsec_type)) // test for change in xsec_type - { - if (dp.xsecBestType.equalsIgnoreCase(cross.xsec_type)) // test if xsec_type is same as best - { - dp.bestXS = countXsecType; // if so, set best index - } - - countXsecType = countXsecType + 1; // increment index - - if (prevXsecType != "") // if not the first - { - dp.xsections.add(xsection); // add previous - } - - xsection = new SectionGeometry(); // instantiate new structure - prevXsecType = cross.xsec_type; // save previous xsec_type - } - - xsection.setXSType(cross.xsec_type); - - // *** Note order of columns : elev, tw, inactive_width, mann_n - xsection.setElevationData(cross.pair_num.intValue(),0,cross.elev.floatValue()); - xsection.setElevationData(cross.pair_num.intValue(),1,cross.tw.floatValue()); - xsection.setElevationData(cross.pair_num.intValue(),2,cross.inactive_width.floatValue()); - xsection.setElevationData(cross.pair_num.intValue(),3,cross.mann_n.floatValue()); - - xsection.setLastRowUsed(cross.pair_num.intValue()); // keep track of how many rows in array are filled - - } - - dp.xsections.add(xsection); // add last xsection - - ret.inputDownstream.add(dp); - - } - - // get damcat_out fields - - int row = 0; - - for (int j=0; j < _outputEntries.size(); j++) - { - OutputEntryInfo out = (OutputEntryInfo)_outputEntries.get(j); - // find only rows which contain output for the given src and scenario - if ((out.src.equalsIgnoreCase(in.src)) && (out.scenario.equalsIgnoreCase(in.scenario))) - { - - ret.source = out.src; - ret.modelScenario = out.scenario; - ret.outSlope = out.slope.floatValue(); - - ret.maxFlow[row] = out.max_flow.floatValue(); - // *** watch max_depth and max_elevation definitions !!! - ret.maxDepth[row] = out.max_depth.floatValue() - ((DownstreamEntryInfo)_downstreamEntries.get(row)).elevation.floatValue(); - ret.maxElevation[row] = out.max_depth.floatValue(); - ret.timeDeflood[row] = out.time_deflood.floatValue(); - ret.timeFlood[row] = out.time_flood.floatValue(); - ret.timeMaxDepth[row] = out.time_max_depth.floatValue(); - - if (ret.maxFlow[row] > ret.maxFl) - { - ret.maxFl = ret.maxFlow[row]; - } - if (ret.maxElevation[row] > ret.maxEl) - { - ret.maxEl = ret.maxElevation[row]; - } - if (ret.maxDepth[row] > ret.maxDep) - { - ret.maxDep = ret.maxDepth[row]; - } - - // *** Note these fields from database are not passed to OutputModel - - // = out.down_name - // = out.comments - // = out.updated - - row = row + 1; - } - } - - ret.damName = dam_name; - ret.riverName = river; - - ret.bHasWarning = false; - ret.warning = null; - ret.bHasFullText = false; - ret.fullText = null; - ret.bHasPrerunText = false; - ret.prerunText = null; - - ret.changeFlag = 0; - - // *** Are any of these fields below being used ??? - ret.xsectionType = ""; - ret.numberXSections = row; // count of number of entries in arrays (relative to 1) - // ret.maxFl = 0.0f; - // ret.maxEl = 0.0f; - // ret.maxDep = 0.0f; - ret.timeMaxDep = 0.0f; - ret.timeFl = 0.0f; - ret.timeDefl = 0.0f; - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - return ret; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getNid_height() { - return nid_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getNid_storage() { - return nid_storage; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getNidid() { - return nidid; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getNormal_storage() { - return normal_storage; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Float - */ -public java.lang.Float getNumber_locks() { - return number_locks; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getOther_dam_name() { - return other_dam_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getOutlet_gates() { - return outlet_gates; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getOwner_name() { - return owner_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getOwner_type() { - return owner_type; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getPrebreak_avail() { - return prebreak_avail; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getPrivate_on_federal() { - return private_on_federal; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getPurposes() { - return purposes; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.Integer - */ -public java.lang.Integer getReturn_flow_region() { - return return_flow_region; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getRfc() { - return rfc; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getRiver() { - return river; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getSection_t_r() { - return section_t_r; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @return java.lang.String - */ -public java.lang.String getSource_agency() { - return source_agency; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getSpillway_type() { - return spillway_type; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.Float - */ -public java.lang.Float getSpillway_width() { - return spillway_width; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getSt_reg_agency() { - return st_reg_agency; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getSt_reg_dam() { - return st_reg_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getStateid() { - return stateid; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.Float - */ -public java.lang.Float getStructural_height() { - return structural_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.Float - */ -public java.lang.Float getSurface_area() { - return surface_area; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getTopo_map() { - return topo_map; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getUpdated() { - return updated; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.Float - */ -public java.lang.Float getVolume_dam() { - return volume_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.Float - */ -public java.lang.Float getWidth_locks() { - return width_locks; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getYear_completed() { - return year_completed; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @return java.lang.String - */ -public java.lang.String getYear_modified() { - return year_modified; -} -/** - * This method finds correct place in downstream ArrayList for insertion of downstream point - * Creation date: (1/29/2004 2:18:38 PM) - */ -public boolean insertDown(DownstreamEntryInfo down) -{ - String compareKey = down.down_name; - float compareDistance = down.distance_from_dam.floatValue(); - float oldDistance = 0.0f; - - int j; - - for (j = 0 ; j < _downstreamEntries.size(); j++) - { - DownstreamEntryInfo oldDown = (DownstreamEntryInfo)_downstreamEntries.get(j); - - oldDistance = oldDown.distance_from_dam.floatValue(); - - - if (compareDistance > oldDistance) - // if(compareKey.compareToIgnoreCase(oldDown.down_name) > 0 ) - { - continue; - } - else - { - break; - } - - } - _downstreamEntries.add(j, down); - return false; -} -/** - * This method finds place in input ArraList for insertion source and scenatio. - * Creation date: (1/29/2004 2:18:38 PM) - */ -public boolean insertInput(InputEntryInfo in) -{ - String compareKey = in.src.concat(in.scenario); - int j; - for (j = 0 ; j < _inputEntries.size(); j++) - { - InputEntryInfo oldInput = (InputEntryInfo)_inputEntries.get(j); - String oldKey = oldInput.src.concat(oldInput.scenario); - if(compareKey.compareToIgnoreCase(oldKey) > 0 ) - { - continue; - } - else - { - break; - } - - } - _inputEntries.add(j, in); - return false; -} -/** - * This method finds place in output ArrayList for insertion source, scenario and down_name, - * checks integrity with damcat_down and input tables. - * Creation date: (1/29/2004 2:18:38 PM) - */ -public boolean insertOutput(DamInfo damInfo, OutputEntryInfo out) -{ - int j; - boolean compareFlag = false; - boolean compareDown = false; - boolean compareSrc = false; - boolean compareScenario = false; - int countFalse = 0; - - String compareKey = out.src.concat(out.scenario).concat(out.down_name); - - if (out.src.startsWith("#")) - { - compareFlag = true; - for (j = 0 ; j < _outputEntries.size(); j++) - { - OutputEntryInfo oldOutput = (OutputEntryInfo)_outputEntries.get(j); - String oldKey = oldOutput.src.concat(oldOutput.scenario).concat(oldOutput.down_name); - if(compareKey.compareToIgnoreCase(oldKey) > 0 ) - { - continue; - } - else - { - break; - } - - } - _outputEntries.add(j, out); - - for (int i=0; i 0 ) - { - continue; - } - else - { - break; - } - - } - _outputEntries.add(j, out); - - System.out.println("flags in else:" + compareSrc + compareScenario + compareDown); - compareFlag = false; - if (compareSrc == false) - { - JOptionPane.showMessageDialog(null,"Error: Could not insert a new output -\nsource must be added to the damcat_in table first."); - } - if (compareScenario == false) - { - JOptionPane.showMessageDialog(null,"Error: Could not insert a new output -\nscenario must be added to the damcat_in table first."); - } - if (compareDown == false) - { - JOptionPane.showMessageDialog(null,"Error: Could not insert a new output -\ndownstream point must be added to the damcat_down table first."); - } - } - } - //System.out.println("compareFlag " + compareFlag); - return compareFlag; -} -/** - * This method finds place in cross-section ArraList for insertion pair_name and pair_num, - * checks integrity with damcat_down table. - * Creation date: (1/29/2004 2:18:38 PM) - */ -public boolean insertPair(DamInfo damInfo, CrossSectionEntryInfo pair) -{ - int j; - boolean compareFlag = false; - String compareKey = pair.down_name.concat(pair.xsec_type).concat(pair.pair_num.toString()); - - for (int i=0; i 0 ) - { - continue; - } - else - { - break; - } - } - - _crossSectionEntries.add(j, pair); - } - else - { - JOptionPane.showMessageDialog(null,"Error: Could not insert a new cross-section -\ndownstream point must be added to the damcat_down table first ."); - } - return compareFlag; -} -/** - * Insert the method's description here. - * Creation date: (7/22/2003 7:31:23 AM) - * @return java.lang.Float - * @param s java.lang.String - */ -public static Float safeParseFloat(String s) { - try { - return Float.valueOf(s); - } catch (Exception e) { - return new Float(0.0f); - } -} -/** - * Insert the method's description here. - * Creation date: (7/22/2003 7:31:23 AM) - * @return java.lang.Float - * @param s java.lang.String - */ -public static Integer safeParseInteger(String s) { - try { - return Integer.valueOf(s); - } catch (Exception e) { - return new Integer(-1); - } -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newComments java.lang.String - */ -public void setComments(java.lang.String newComments) { - comments = newComments; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newCore java.lang.String - */ -public void setCore(java.lang.String newCore) { - core = newCore; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newCounty java.lang.String - */ -public void setCounty(java.lang.String newCounty) { - county = newCounty; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDam_designer java.lang.String - */ -public void setDam_designer(java.lang.String newDam_designer) { - dam_designer = newDam_designer; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDam_former_name java.lang.String - */ -public void setDam_former_name(java.lang.String newDam_former_name) { - dam_former_name = newDam_former_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDam_height java.lang.Float - */ -public void setDam_height(java.lang.Float newDam_height) { - dam_height = newDam_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDam_length java.lang.Float - */ -public void setDam_length(java.lang.Float newDam_length) { - dam_length = newDam_length; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDam_name java.lang.String - */ -public void setDam_name(java.lang.String newDam_name) { - dam_name = newDam_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDam_type java.lang.String - */ -public void setDam_type(java.lang.String newDam_type) { - dam_type = newDam_type; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDownstream_hazard java.lang.String - */ -public void setDownstream_hazard(java.lang.String newDownstream_hazard) { - downstream_hazard = newDownstream_hazard; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newDrainage_area java.lang.Float - */ -public void setDrainage_area(java.lang.Float newDrainage_area) { - drainage_area = newDrainage_area; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newElev java.lang.Float - */ -public void setElev(java.lang.Float newElev) { - elev = newElev; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newEmerg_action_plan java.lang.String - */ -public void setEmerg_action_plan(java.lang.String newEmerg_action_plan) { - emerg_action_plan = newEmerg_action_plan; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_construction java.lang.String - */ -public void setFed_construction(java.lang.String newFed_construction) { - fed_construction = newFed_construction; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_design java.lang.String - */ -public void setFed_design(java.lang.String newFed_design) { - fed_design = newFed_design; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_funding java.lang.String - */ -public void setFed_funding(java.lang.String newFed_funding) { - fed_funding = newFed_funding; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_inspection java.lang.String - */ -public void setFed_inspection(java.lang.String newFed_inspection) { - fed_inspection = newFed_inspection; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_operation java.lang.String - */ -public void setFed_operation(java.lang.String newFed_operation) { - fed_operation = newFed_operation; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_other java.lang.String - */ -public void setFed_other(java.lang.String newFed_other) { - fed_other = newFed_other; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_owner java.lang.String - */ -public void setFed_owner(java.lang.String newFed_owner) { - fed_owner = newFed_owner; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFed_regulatory java.lang.String - */ -public void setFed_regulatory(java.lang.String newFed_regulatory) { - fed_regulatory = newFed_regulatory; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newFoundation java.lang.String - */ -public void setFoundation(java.lang.String newFoundation) { - foundation = newFoundation; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newHsa java.lang.String - */ -public void setHsa(java.lang.String newHsa) { - hsa = newHsa; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newHydraulic_height java.lang.Float - */ -public void setHydraulic_height(java.lang.Float newHydraulic_height) { - hydraulic_height = newHydraulic_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newInspection_date java.lang.String - */ -public void setInspection_date(java.lang.String newInspection_date) { - inspection_date = newInspection_date; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newInspection_freq java.lang.String - */ -public void setInspection_freq(java.lang.String newInspection_freq) { - inspection_freq = newInspection_freq; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newLatitude_dam java.lang.Float - */ -public void setLatitude_dam(java.lang.Float newLatitude_dam) { - latitude_dam = newLatitude_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newLength_locks java.lang.Float - */ -public void setLength_locks(java.lang.Float newLength_locks) { - length_locks = newLength_locks; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newLongitude_dam java.lang.Float - */ -public void setLongitude_dam(java.lang.Float newLongitude_dam) { - longitude_dam = newLongitude_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newMax_discharge java.lang.Float - */ -public void setMax_discharge(java.lang.Float newMax_discharge) { - max_discharge = newMax_discharge; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newMax_storage java.lang.Float - */ -public void setMax_storage(java.lang.Float newMax_storage) { - max_storage = newMax_storage; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newNid_height java.lang.Float - */ -public void setNid_height(java.lang.Float newNid_height) { - nid_height = newNid_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newNid_storage java.lang.Float - */ -public void setNid_storage(java.lang.Float newNid_storage) { - nid_storage = newNid_storage; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newNidid java.lang.String - */ -public void setNidid(java.lang.String newNidid) { - nidid = newNidid; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newNormal_storage java.lang.Float - */ -public void setNormal_storage(java.lang.Float newNormal_storage) { - normal_storage = newNormal_storage; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newNumber_locks java.lang.Float - */ -public void setNumber_locks(java.lang.Float newNumber_locks) { - number_locks = newNumber_locks; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newOther_dam_name java.lang.String - */ -public void setOther_dam_name(java.lang.String newOther_dam_name) { - other_dam_name = newOther_dam_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newOutlet_gates java.lang.String - */ -public void setOutlet_gates(java.lang.String newOutlet_gates) { - outlet_gates = newOutlet_gates; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newOwner_name java.lang.String - */ -public void setOwner_name(java.lang.String newOwner_name) { - owner_name = newOwner_name; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newOwner_type java.lang.String - */ -public void setOwner_type(java.lang.String newOwner_type) { - owner_type = newOwner_type; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newPrebreak_avail java.lang.String - */ -public void setPrebreak_avail(java.lang.String newPrebreak_avail) { - prebreak_avail = newPrebreak_avail; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newPrivate_on_federal java.lang.String - */ -public void setPrivate_on_federal(java.lang.String newPrivate_on_federal) { - private_on_federal = newPrivate_on_federal; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newPurposes java.lang.String - */ -public void setPurposes(java.lang.String newPurposes) { - purposes = newPurposes; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newReturn_flow_region java.lang.Integer - */ -public void setReturn_flow_region(java.lang.Integer newReturn_flow_region) { - return_flow_region = newReturn_flow_region; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newRfc java.lang.String - */ -public void setRfc(java.lang.String newRfc) { - rfc = newRfc; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newRiver java.lang.String - */ -public void setRiver(java.lang.String newRiver) { - river = newRiver; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newSection_t_r java.lang.String - */ -public void setSection_t_r(java.lang.String newSection_t_r) { - section_t_r = newSection_t_r; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:07 PM) - * @param newSource_agency java.lang.String - */ -public void setSource_agency(java.lang.String newSource_agency) { - source_agency = newSource_agency; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newSpillway_type java.lang.String - */ -public void setSpillway_type(java.lang.String newSpillway_type) { - spillway_type = newSpillway_type; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newSpillway_width java.lang.Float - */ -public void setSpillway_width(java.lang.Float newSpillway_width) { - spillway_width = newSpillway_width; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newSt_reg_agency java.lang.String - */ -public void setSt_reg_agency(java.lang.String newSt_reg_agency) { - st_reg_agency = newSt_reg_agency; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newSt_reg_dam java.lang.String - */ -public void setSt_reg_dam(java.lang.String newSt_reg_dam) { - st_reg_dam = newSt_reg_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newStateid java.lang.String - */ -public void setStateid(java.lang.String newStateid) { - stateid = newStateid; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newStructural_height java.lang.Float - */ -public void setStructural_height(java.lang.Float newStructural_height) { - structural_height = newStructural_height; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newSurface_area java.lang.Float - */ -public void setSurface_area(java.lang.Float newSurface_area) { - surface_area = newSurface_area; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newTopo_map java.lang.String - */ -public void setTopo_map(java.lang.String newTopo_map) { - topo_map = newTopo_map; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newUpdated java.lang.String - */ -public void setUpdated(java.lang.String newUpdated) { - updated = newUpdated; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newVolume_dam java.lang.Float - */ -public void setVolume_dam(java.lang.Float newVolume_dam) { - volume_dam = newVolume_dam; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newWidth_locks java.lang.Float - */ -public void setWidth_locks(java.lang.Float newWidth_locks) { - width_locks = newWidth_locks; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newYear_completed java.lang.String - */ -public void setYear_completed(java.lang.String newYear_completed) { - year_completed = newYear_completed; -} -/** - * Insert the method's description here. - * Creation date: (1/5/2004 1:38:08 PM) - * @param newYear_modified java.lang.String - */ -public void setYear_modified(java.lang.String newYear_modified) { - year_modified = newYear_modified; -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/DownstreamEntryInfo.java b/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/DownstreamEntryInfo.java deleted file mode 100644 index 218d44b4e7..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/DownstreamEntryInfo.java +++ /dev/null @@ -1,246 +0,0 @@ -package gov.damcat.data; - -/** - * This class holds information from the damcat_down table. - */ -class DownstreamEntryInfo { - - public String down_name,comments,xsec_best_type,updated; - public Float longitude,latitude,elevation,distance_from_dam,flood_flow,flood_depth,flood_width,mann_oc; - //public java.sql.Date updated; - -/** - * DAMCAT_DownstreamEntryInfo constructor comment. - */ -public DownstreamEntryInfo() { - super(); - down_name = ""; - comments = ""; - xsec_best_type = ""; - updated = ""; - longitude = new Float(0.0f); - latitude = new Float(0.0f); - elevation = new Float(0.0f); - distance_from_dam = new Float(0.0f); - flood_flow = new Float(0.0f); - flood_depth = new Float(0.0f); - flood_width = new Float(0.0f); - mann_oc = new Float(0.0f); -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.String - */ -public java.lang.String getComments() { - return comments; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getDistance_from_dam() { - return distance_from_dam; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.String - */ -public java.lang.String getDown_name() { - return down_name; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getElevation() { - return elevation; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getFlood_depth() { - return flood_depth; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getFlood_flow() { - return flood_flow; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getFlood_width() { - return flood_width; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getLatitude() { - return latitude; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getLongitude() { - return longitude; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.Float - */ -public java.lang.Float getMann_oc() { - return mann_oc; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.String - */ -public java.lang.String getUpdated() { - return updated; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @return java.lang.String - */ -public java.lang.String getXsec_best_type() { - return xsec_best_type; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newComments java.lang.String - */ -public void setComments(java.lang.String newComments) { - comments = newComments; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newDistance_from_dam java.lang.Float - */ -public void setDistance_from_dam(java.lang.Float newDistance_from_dam) { - distance_from_dam = newDistance_from_dam; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newDown_name java.lang.String - */ -public void setDown_name(java.lang.String newDown_name) { - down_name = newDown_name; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newElevation java.lang.Float - */ -public void setElevation(java.lang.Float newElevation) { - elevation = newElevation; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newFlood_depth java.lang.Float - */ -public void setFlood_depth(java.lang.Float newFlood_depth) { - flood_depth = newFlood_depth; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newFlood_flow java.lang.Float - */ -public void setFlood_flow(java.lang.Float newFlood_flow) { - flood_flow = newFlood_flow; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newFlood_width java.lang.Float - */ -public void setFlood_width(java.lang.Float newFlood_width) { - flood_width = newFlood_width; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newLatitude java.lang.Float - */ -public void setLatitude(java.lang.Float newLatitude) { - latitude = newLatitude; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newLongitude java.lang.Float - */ -public void setLongitude(java.lang.Float newLongitude) { - longitude = newLongitude; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newMann_oc java.lang.Float - */ -public void setMann_oc(java.lang.Float newMann_oc) { - mann_oc = newMann_oc; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newUpdated java.lang.String - */ -public void setUpdated(java.lang.String newUpdated) { - updated = newUpdated; -} - -/** - * Insert the method's description here. - * Creation date: (1/5/2004 2:48:49 PM) - * @param newXsec_best_type java.lang.String - */ -public void setXsec_best_type(java.lang.String newXsec_best_type) { - xsec_best_type = newXsec_best_type; -} -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/EditDam.java b/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/EditDam.java deleted file mode 100644 index d016394b79..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/gov/damcat/data/EditDam.java +++ /dev/null @@ -1,6658 +0,0 @@ -package gov.damcat.data; - -import java.lang.reflect.*; -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.table.*; -import gov.dambreak.util.*; - -/** - * This class allows the user to view and edit all the data stored in DAMCAT for a specific dam. - */ - -class EditDam extends JFrame implements ActionListener, FocusListener, DocumentListener, TableModelListener { - -class EditDamCellRenderer extends DefaultTableCellRenderer { - private Component component; - Color background = new Color( 230, 230, 230 ); - - public Component getTableCellRendererComponent( JTable table, - Object value, boolean isSelected, boolean hasFocus, - int row, int col) - { - component = super.getTableCellRendererComponent(table, value,isSelected, hasFocus, row, col); - component.setBackground(background); - return component; - } -} - -class NewDamDownKeys extends JFrame implements ActionListener -{ - private JTextField downName; - private JTextField distanceText; - private JTextField distance; - private JButton okButton; - private JButton cancelButton; - - public void actionPerformed(ActionEvent evt) - { - boolean _tableChanged = false; - - - if (evt.getSource() == cancelButton) - { - setVisible(false); - } - if (evt.getSource() == okButton) - { - downName.grabFocus(); - DownstreamEntryInfo downEntry = new DownstreamEntryInfo(); - String damID = damInfo.getNidid(); - String downKey = downName.getText().trim(); - String distanceKey = distanceText.getText().trim(); - float distanceNumKey = 0.0f; - - if(downKey.equals("")) - { - downName.grabFocus(); - JOptionPane.showMessageDialog(this, "Downstream name is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - - if(distanceKey.equals("")) - { - distanceText.grabFocus(); - JOptionPane.showMessageDialog(this, "Distance from dam must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - - try - { - distanceNumKey = Float.parseFloat(distanceKey); - - } catch (NumberFormatException e) - { - distanceText.grabFocus(); - JOptionPane.showMessageDialog(this, "Distance from dam must be numeric","Error", JOptionPane.ERROR_MESSAGE); - return; - } - - - downEntry.down_name = downKey; - downName.setText(""); - - downEntry.distance_from_dam = new Float(distanceNumKey); - distanceText.setText(""); - - boolean bError = dbAccess.insertDownstream(damID, downEntry); - - if(bError == true) - { - damInfo.insertDown(downEntry); - - refresh(); - - } - setVisible(false); - } - } - public NewDamDownKeys() - { - setTitle("Insert Downstream Table Keys"); - setSize(350, 280); // was setSize(350, 150); - setLocation(400, 200); - setResizable(false); - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints constr = new GridBagConstraints(); - - Container c = getContentPane(); - c.setLayout(gbl); - JLabel lb1 = new JLabel("Downstream Point Name: "); - lb1.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 1; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb1, constr); - - c.add(lb1); - - downName = new JTextField(20); - - constr.gridx = 0; - constr.gridy = 2; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(downName, constr); - - c.add(downName); - downName.addActionListener(this); - - // additions start from here - JLabel lb2 = new JLabel("Distance From Dam: "); - lb2.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 3; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb2, constr); - - c.add(lb2); - - distanceText = new JTextField(20); - constr.gridx = 0; - constr.gridy = 4; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(distanceText, constr); - - c.add(distanceText); - distanceText.addActionListener(this); - - - // to here - - okButton = new JButton(" OK "); - okButton.setForeground(Color.black); - - cancelButton = new JButton("Cancel"); - cancelButton.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 5; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - // constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(okButton, constr); - c.add(okButton); - okButton.addActionListener(this); - - constr.gridx = 1; - constr.gridy = 5; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - // constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.CENTER; - gbl.setConstraints(cancelButton, constr); - c.add(cancelButton); - cancelButton.addActionListener(this); - -// show(); - this.setVisible( true ); - - } - -} - -class NewDamPairKeys extends JFrame implements ActionListener -{ - private JTextField downName; - private JTextField xsecType; - private JTextField pairNum; - private JButton okButton; - private JButton cancelButton; - - public void actionPerformed(ActionEvent evt) - { - if (evt.getSource() == cancelButton) - { - setVisible(false); - } - if (evt.getSource() == okButton) - { - - downName.grabFocus(); - CrossSectionEntryInfo pairEntry = new CrossSectionEntryInfo(); - String damID = damInfo.getNidid(); - String downNameKey = downName.getText().trim(); - if(downNameKey.equals("")) - { - JOptionPane.showMessageDialog(this, "Downstream name is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - pairEntry.down_name = downNameKey; - String xsecTypeKey = xsecType.getText().trim().toUpperCase(); - if(xsecTypeKey.equals("")) - { - xsecType.grabFocus(); - JOptionPane.showMessageDialog(this, "Cross-section type is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - pairEntry.xsec_type = xsecTypeKey; - try - { - int pairNumKey = Integer.parseInt(pairNum.getText().trim()); - pairEntry.pair_num = new Integer(pairNumKey); - } catch (NumberFormatException e) - - { - pairNum.grabFocus(); - JOptionPane.showMessageDialog(this, "Pair number is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - downName.setText(""); - xsecType.setText(""); - pairNum.setText(""); - - boolean compareFlag = damInfo.insertPair(damInfo,pairEntry); - if(compareFlag == true) - { - boolean bError = dbAccess.insertSectionPair(damID, pairEntry); - - if(bError == true) - { - refresh(); - } - } - setVisible(false); - } - } - public NewDamPairKeys() - { - setTitle("Insert Cross-Section Table Keys"); - setSize(350, 350); - setLocation(400, 200); - setResizable(false); - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints constr = new GridBagConstraints(); - - Container c = getContentPane(); - c.setLayout(gbl); - JLabel lb1 = new JLabel("Downstream Point Name: "); - lb1.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 1; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb1, constr); - - c.add(lb1); - - downName = new JTextField(20); - - constr.gridx = 0; - constr.gridy = 2; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(downName, constr); - - c.add(downName); - downName.addActionListener(this); - - JLabel lb2 = new JLabel("Cross-Section Type: "); - lb2.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 3; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb2, constr); - - c.add(lb2); - - xsecType = new JTextField(20); - constr.gridx = 0; - constr.gridy = 4; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(xsecType, constr); - - c.add(xsecType); - xsecType.addActionListener(this); - - JLabel lb3 = new JLabel("Pair Number: "); - lb3.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 5; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb3, constr); - - c.add(lb3); - - pairNum = new JTextField(20); - constr.gridx = 0; - constr.gridy = 6; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(pairNum, constr); - - c.add(pairNum); - pairNum.addActionListener(this); - - - okButton = new JButton(" OK "); - okButton.setForeground(Color.black); - - cancelButton = new JButton("Cancel"); - cancelButton.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 7; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - // constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(okButton, constr); - c.add(okButton); - okButton.addActionListener(this); - - constr.gridx = 1; - constr.gridy = 7; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - // constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.CENTER; - gbl.setConstraints(cancelButton, constr); - c.add(cancelButton); - cancelButton.addActionListener(this); - -// show(); - this.setVisible( true ); - - } -} - -class NewDamInKeys extends JFrame implements ActionListener -{ - private JTextField src; - private JTextField scenario; - private JButton okButton; - private JButton cancelButton; - - public void actionPerformed(ActionEvent evt) - { - if (evt.getSource() == cancelButton) - { - setVisible(false); - } - if (evt.getSource() == okButton) - { - src.grabFocus(); - InputEntryInfo inEntry = new InputEntryInfo(); - String damID = damInfo.getNidid(); - String srcKey = src.getText().trim(); - if(srcKey.equals("")) - { - JOptionPane.showMessageDialog(this, "Source is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - inEntry.src = srcKey; - String scenarioKey = scenario.getText().trim(); - if(scenarioKey.equals("")) - { - scenario.grabFocus(); - JOptionPane.showMessageDialog(this, "Scenario is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - inEntry.scenario = scenarioKey; - src.setText(""); - scenario.setText(""); - - boolean bError = dbAccess.insertSdbIn(damID,inEntry); - - if(bError == true) - { - damInfo.insertInput(inEntry); - - refresh(); - - } - // System.out.println("nidid in insertDamcatIn " + damID); - - setVisible(false); - } - } - public NewDamInKeys() - { - setTitle("Insert Input Table Keys"); - setSize(350, 280); - setLocation(400, 200); - setResizable(false); - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints constr = new GridBagConstraints(); - - Container c = getContentPane(); - c.setLayout(gbl); - JLabel lb1 = new JLabel("Source: "); - lb1.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 1; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb1, constr); - - c.add(lb1); - - src = new JTextField(20); - - constr.gridx = 0; - constr.gridy = 2; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(src, constr); - - c.add(src); - src.addActionListener(this); - - JLabel lb2 = new JLabel("Scenario: "); - lb2.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 3; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb2, constr); - - c.add(lb2); - - scenario = new JTextField(20); - constr.gridx = 0; - constr.gridy = 4; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(scenario, constr); - - c.add(scenario); - scenario.addActionListener(this); - - okButton = new JButton(" OK "); - okButton.setForeground(Color.black); - - cancelButton = new JButton("Cancel"); - cancelButton.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 5; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - //constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(okButton, constr); - c.add(okButton); - okButton.addActionListener(this); - - constr.gridx = 1; - constr.gridy = 5; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,70,0,0); - constr.anchor = GridBagConstraints.EAST; - gbl.setConstraints(cancelButton, constr); - c.add(cancelButton); - cancelButton.addActionListener(this); - -// show(); - this.setVisible( true ); - - } -} - -class NewDamOutKeys extends JFrame implements ActionListener -{ - private JTextField src; - private JTextField scenario; - private JTextField downName; - private JButton okButton; - private JButton cancelButton; - - public void actionPerformed(ActionEvent evt) - { - if (evt.getSource() == cancelButton) - { - setVisible(false); - } - if (evt.getSource() == okButton) - { - src.grabFocus(); - OutputEntryInfo outEntry = new OutputEntryInfo(); - String damID = damInfo.getNidid(); - String srcKey = src.getText().trim(); - if(srcKey.equals("")) - { - JOptionPane.showMessageDialog(this, "Source is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - outEntry.src = srcKey; - String scenarioKey = scenario.getText().trim(); - if(scenarioKey.equals("")) - { - scenario.grabFocus(); - JOptionPane.showMessageDialog(this, "Scenario is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - outEntry.scenario = scenarioKey; - String downNameKey = downName.getText().trim(); - if(downNameKey.equals("")) - { - downName.grabFocus(); - JOptionPane.showMessageDialog(this, "Downstream name is a part of the key, must be supplied","Error", JOptionPane.ERROR_MESSAGE); - return; - } - outEntry.down_name = downNameKey; - src.setText(""); - scenario.setText(""); - downName.setText(""); - - boolean compareFlag = damInfo.insertOutput(damInfo,outEntry); - if(compareFlag == true) - { - boolean bError = dbAccess.insertSdbOut(damID, outEntry); - - if(bError == true) - { - refresh(); - } - } - /*boolean bError = dbAccess.insertDamcatOut(damID,outEntry); - - if(bError == true) - { - damInfo.insertOutput(damInfo, outEntry); - - initialize(); - }*/ - System.out.println("nidid in insertDamcatOut " + damID); - - setVisible(false); - } - } - public NewDamOutKeys() - { - setTitle("Insert Output Table Keys"); - setSize(350, 350); - setLocation(400, 200); - setResizable(false); - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints constr = new GridBagConstraints(); - - Container c = getContentPane(); - c.setLayout(gbl); - JLabel lb1 = new JLabel("Source: "); - lb1.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 1; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb1, constr); - - c.add(lb1); - - src = new JTextField(20); - - constr.gridx = 0; - constr.gridy = 2; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(src, constr); - - c.add(src); - src.addActionListener(this); - - JLabel lb2 = new JLabel("Scenario: "); - lb2.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 3; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb2, constr); - - c.add(lb2); - - scenario = new JTextField(20); - constr.gridx = 0; - constr.gridy = 4; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(scenario, constr); - - c.add(scenario); - scenario.addActionListener(this); - - JLabel lb3 = new JLabel("Downstream Point Name: "); - lb3.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 5; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(lb3, constr); - - c.add(lb3); - - downName = new JTextField(20); - - constr.gridx = 0; - constr.gridy = 6; - constr.gridwidth = 3; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - constr.insets = new Insets(20,0,0,0); - gbl.setConstraints(downName, constr); - - c.add(downName); - downName.addActionListener(this); - - okButton = new JButton(" OK "); - okButton.setForeground(Color.black); - - cancelButton = new JButton("Cancel"); - cancelButton.setForeground(Color.black); - - constr.gridx = 0; - constr.gridy = 7; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - // constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.WEST; - gbl.setConstraints(okButton, constr); - c.add(okButton); - okButton.addActionListener(this); - - constr.gridx = 1; - constr.gridy = 7; - constr.gridwidth = 1; - constr.gridheight = 1; - constr.weightx = 0; - constr.weighty = 0; - // constr.insets = new Insets(20,0,0,0); - constr.anchor = GridBagConstraints.CENTER; - gbl.setConstraints(cancelButton, constr); - c.add(cancelButton); - cancelButton.addActionListener(this); - -// show(); - this.setVisible( true ); - - } -} - private JPanel ivjJFrameContentPane = null; - private DamInfo damInfo; - private InputEntryInfo inInfo; - private JPanel ivjPanelConstruction = null; - private JPanel ivjPanelDownstream = null; - private JPanel ivjPanelInputs = null; - private JPanel ivjPanelOutput = null; - private JPanel ivjPanelPairs = null; - private JPanel ivjPanelRegulatory = null; - private JLabel ivjJLabel1 = null; - private JLabel ivjJLabel10 = null; - private JLabel ivjJLabel11 = null; - private JLabel ivjJLabel12 = null; - private JLabel ivjJLabel13 = null; - private JLabel ivjJLabel14 = null; - private JLabel ivjJLabel15 = null; - private JLabel ivjJLabel16 = null; - private JLabel ivjJLabel17 = null; - private JLabel ivjJLabel18 = null; - private JLabel ivjJLabel2 = null; - private JLabel ivjJLabel3 = null; - private JLabel ivjJLabel4 = null; - private JLabel ivjJLabel5 = null; - private JLabel ivjJLabel6 = null; - private JLabel ivjJLabel7 = null; - private JLabel ivjJLabel8 = null; - private JLabel ivjJLabel9 = null; - private JPanel ivjPanelGeneral = null; - private JTextField ivjTextComments = null; - private JTextField ivjTextCounty = null; - private JTextField ivjTextDamName = null; - private JTextField ivjTextDrainageArea = null; - private JTextField ivjTextElevation = null; - private JTextField ivjTextFormerDamName = null; - private JTextField ivjTextHSA = null; - private JTextField ivjTextLatitude = null; - private JTextField ivjTextLongitude = null; - private JTextField ivjTextNIDID = null; - private JTextField ivjTextOtherDamName = null; - private JTextField ivjTextPrebreakAvailable = null; - private JTextField ivjTextReturnFlowRegion = null; - private JTextField ivjTextRFC = null; - private JTextField ivjTextRiver = null; - private JTextField ivjTextStateID = null; - private JTextField ivjTextTopoMap = null; - private JTextField ivjTextUpdated = null; - private JLabel ivjJLabel19 = null; - private JLabel ivjJLabel191 = null; - private JLabel ivjJLabel20 = null; - private JLabel ivjJLabel201 = null; - private JLabel ivjJLabel21 = null; - private JLabel ivjJLabel211 = null; - private JLabel ivjJLabel22 = null; - private JLabel ivjJLabel221 = null; - private JLabel ivjJLabel23 = null; - private JLabel ivjJLabel231 = null; - private JLabel ivjJLabel24 = null; - private JLabel ivjJLabel241 = null; - private JLabel ivjJLabel25 = null; - private JLabel ivjJLabel251 = null; - private JLabel ivjJLabel26 = null; - private JLabel ivjJLabel261 = null; - private JLabel ivjJLabel27 = null; - private JLabel ivjJLabel271 = null; - private JLabel ivjJLabel272 = null; - private JLabel ivjJLabel273 = null; - private JLabel ivjJLabel28 = null; - private JLabel ivjJLabel29 = null; - private JLabel ivjJLabel30 = null; - private JLabel ivjJLabel31 = null; - private JLabel ivjJLabel32 = null; - private JLabel ivjJLabel33 = null; - private JLabel ivjJLabel34 = null; - private JLabel ivjJLabel35 = null; - private JLabel ivjJLabel36 = null; - private JLabel ivjJLabel37 = null; - private JLabel ivjJLabel38 = null; - private JLabel ivjJLabel39 = null; - private JLabel ivjJLabel40 = null; - private JLabel ivjJLabel41 = null; - private JLabel ivjJLabel42 = null; - private JLabel ivjJLabel43 = null; - private JLabel ivjJLabel44 = null; - private JLabel ivjJLabel45 = null; - private JLabel ivjJLabel46 = null; - private JLabel ivjJLabel47 = null; - private JLabel ivjJLabel48 = null; - private JLabel ivjJLabel49 = null; - private JLabel ivjJLabel50 = null; - private JTextField ivjTextCore = null; - private JTextField ivjTextDamDesigner = null; - private JTextField ivjTextDamHeight = null; - private JTextField ivjTextDamLength = null; - private JTextField ivjTextDamType = null; - private JTextField ivjTextDownstreamHazard = null; - private JTextField ivjTextEmergencyAction = null; - private JTextField ivjTextFederalConstruction = null; - private JTextField ivjTextFederalDesign = null; - private JTextField ivjTextFederalFunding = null; - private JTextField ivjTextFederalInspection = null; - private JTextField ivjTextFederalOperation = null; - private JTextField ivjTextFederalOther = null; - private JTextField ivjTextFederalOwner = null; - private JTextField ivjTextFederalRegulatoryAgency = null; - private JTextField ivjTextFoundation = null; - private JTextField ivjTextHydraulicHeight = null; - private JTextField ivjTextInspectionDate = null; - private JTextField ivjTextInspectionFrequency = null; - private JTextField ivjTextLengthOfLocks = null; - private JTextField ivjTextMaxDischarge = null; - private JTextField ivjTextMaxStorage = null; - private JTextField ivjTextNIDHeight = null; - private JTextField ivjTextNIDStorage = null; - private JTextField ivjTextNormalStorage = null; - private JTextField ivjTextNumberOfLocks = null; - private JTextField ivjTextOutletGates = null; - private JTextField ivjTextOwnerName = null; - private JTextField ivjTextOwnerType = null; - private JTextField ivjTextPrivateOnFederalLand = null; - private JTextField ivjTextPurposes = null; - private JTextField ivjTextSectionTR = null; - private JTextField ivjTextSourceAgency = null; - private JTextField ivjTextSpillwayType = null; - private JTextField ivjTextSpillwayWidth = null; - private JTextField ivjTextStateRegulated = null; - private JTextField ivjTextStateRegulatoryAgency = null; - private JTextField ivjTextStructuralHeight = null; - private JTextField ivjTextSurfaceArea = null; - private JTextField ivjTextVolumeMaterial = null; - private JTextField ivjTextWidthOfLocks = null; - private JTextField ivjTextYearCompleted = null; - private JTextField ivjTextYearModified = null; - private JScrollPane ivjScrollDownstream = null; - private TableColumn ivjTableColumn1 = null; - private TableColumn ivjTableColumn2 = null; - private TableColumn ivjTableColumn3 = null; - private TableColumn ivjTableColumn4 = null; - private TableColumn ivjTableColumn5 = null; - private TableColumn ivjTableColumn6 = null; - private TableColumn ivjTableColumn7 = null; - private TableColumn ivjTableColumn8 = null; - private TableColumn ivjTableColumn9 = null; - private TableColumn ivjTableColumn10 = null; - private TableColumn ivjTableColumn11 = null; - private TableColumn ivjTableColumn12 = null; - private JTable ivjTableDownstream = null; - private JScrollPane ivjScrollCrossSection = null; - private TableColumn ivjTableColumn15 = null; - private TableColumn ivjTableColumn16 = null; - private TableColumn ivjTableColumn17 = null; - private TableColumn ivjTableColumn18 = null; - private TableColumn ivjTableColumn19 = null; - private TableColumn ivjTableColumn20 = null; - private TableColumn ivjTableColumn21 = null; - private TableColumn ivjTableColumn22 = null; - private JTable ivjTableCrossSection = null; - private JScrollPane ivjJScrollPane1 = null; - private TableColumn ivjTableColumn24 = null; - private TableColumn ivjTableColumn25 = null; - private TableColumn ivjTableColumn26 = null; - private TableColumn ivjTableColumn28 = null; - private TableColumn ivjTableColumn30 = null; - private TableColumn ivjTableColumn32 = null; - private TableColumn ivjTableColumn33 = null; - private TableColumn ivjTableColumn34 = null; - private TableColumn ivjTableColumn35 = null; - private TableColumn ivjTableColumn36 = null; - private TableColumn ivjTableColumn37 = null; - private TableColumn ivjTableColumn38 = null; - private HashMap dbFieldRelations; - private UneditableJTableModel modelCrossSections,modelInput,modelOutput,modelDownstream; - private JTable ivjTableInput = null; - private JScrollPane ivjJScrollPane2 = null; - private TableColumn ivjTableColumn27 = null; - private TableColumn ivjTableColumn29 = null; - private TableColumn ivjTableColumn31 = null; - private TableColumn ivjTableColumn39 = null; - private TableColumn ivjTableColumn40 = null; - private TableColumn ivjTableColumn41 = null; - private TableColumn ivjTableColumn42 = null; - private TableColumn ivjTableColumn43 = null; - private TableColumn ivjTableColumn44 = null; - private TableColumn ivjTableColumn45 = null; - private TableColumn ivjTableColumn46 = null; - private JTable ivjTableOutput = null; - private JButton ivjButtonExport = null; - private JTabbedPane ivjTabData = null; - IvjEventHandler ivjEventHandler = new IvjEventHandler(); - private JButton ivjButtonClose = null; - private boolean bUpdateMaster,bUpdateFeatures,bUpdateDown,bUpdatePair,bUpdateIn,bUpdateOut; - private JButton ivjButtonSave = null; - private DBAccess dbAccess; - private javax.swing.JComboBox scenarioCombo; - private JPanel ivjPanelButtons = null; - private boolean[] _tableRowChangedArray = null; - private boolean[] _tableDownRowChangedArray = null; - private boolean[] _tableInRowChangedArray = null; - private boolean[] _tableOutRowChangedArray = null; - private boolean[] _tablePairRowChangedArray = null; - private JButton ivjButtonDeleteDam = null; - private int _indexTab; - private JFrame insertDownKeys = null; - private JFrame insertPairKeys = null; - private JFrame insertInKeys = null; - private JFrame insertOutKeys = null; - private JButton ivjButtonNewDam = null; - private int _searchSelection = -1; - int [] xsColFrom = {0, 7}; - int [] xsColTo = {2, 7}; - int [] inColFrom = {0, 11}; - int [] inColTo = {1, 11}; - int [] outColFrom = {0, 10}; - int [] outColTo = {2, 10}; - int [] downColFrom = {0, 11}; - int [] downColTo = {0, 11}; - private Search searchScreen = null; - -class IvjEventHandler implements java.awt.event.ActionListener { - public void actionPerformed(java.awt.event.ActionEvent e) { - if (e.getSource() == EditDam.this.getButtonExport()) - connEtoC1(); - if (e.getSource() == EditDam.this.getButtonSave()) - connEtoC3(); - if (e.getSource() == EditDam.this.getButtonClose()) - connEtoC2(); - if (e.getSource() == EditDam.this.getButtonNewDam()) - connEtoC5(); - if (e.getSource() == EditDam.this.getButtonNewDam()) - connEtoC4(); - if (e.getSource() == EditDam.this.getButtonNewDam()) - connEtoC6(); - if (e.getSource() == EditDam.this.getButtonNewDam()) - connEtoC7(); - if (e.getSource() == EditDam.this.getButtonDeleteDam()) - connEtoC8(); - }; - }; -/** - * Constructor - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -public EditDam() { - super(); - initialize(); -} -public EditDam(DamInfo _damInfo, DBAccess _dbAccess) { - super(); - - damInfo = _damInfo; - - dbAccess = _dbAccess; - - initialize(); -} -/** - * Insert the method's description here. - * Creation date: (2/18/2004 5:13:14 PM) - * @param _damInfo gov.damcat.data.DamInfo - * @param _dbAccess gov.damcat.data.DBAccess - * @param _searchScreen gov.damcat.data.Search - */ -public EditDam(DamInfo _damInfo, DBAccess _dbAccess, Search _searchScreen) -{ - super(); - - damInfo = _damInfo; - - dbAccess = _dbAccess; - - searchScreen = _searchScreen; - - initialize(); -} - /** - * Invoked when an action occurs. - */ -public void actionPerformed(ActionEvent e) {} -/** - * Insert the method's description here. - * Creation date: (7/18/2003 8:36:21 AM) - * @param e javax.swing.event.DocumentEvent - */ -public void changedUpdate(DocumentEvent e) {} -/** - * Insert the method's description here. - * Creation date: (2/17/2004 1:45:34 PM) - * @param changedArray boolean[] - */ -public void clearRowChanged(boolean[] changedArray) -{ - for (int i = 0; i < changedArray.length; i++) - { - changedArray[i] = false; - - } -} -/** - * connEtoC1: (ButtonExport.action. --> DAMCAT_EditDam.handleExportToSMPDBK()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC1() { - try { - // user code begin {1} - // user code end - - this.handleExportToSMPDBK(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC2: (ButtonClose.action. --> DAMCAT_EditDam.handleClose()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC2() { - try { - // user code begin {1} - // user code end - this.handleClose(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC3: (ButtonSave.action. --> DAMCAT_EditDam.handleSave()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC3() { - try { - // user code begin {1} - // user code end - this.handleSave(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC4: (ButtonNewDam.action. --> EditDam.handleNewDamInKeys()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC4() { - try { - // user code begin {1} - // user code end - this.handleNewDamInKeys(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC5: (ButtonNewDam.action. --> EditDam.handleNewDamDownKeys()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC5() { - try { - // user code begin {1} - // user code end - this.handleNewDamDownKeys(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC6: (ButtonNewDam.action. --> EditDam.handleNewDamOutKeys()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC6() { - try { - // user code begin {1} - // user code end - this.handleNewDamOutKeys(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC7: (ButtonNewDam.action. --> EditDam.handleNewDamPairKeys()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC7() { - try { - // user code begin {1} - // user code end - this.handleNewDamPairKeys(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * connEtoC8: (ButtonDeleteDam.action. --> EditDam.handleDeleteDamcatDam()V) - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void connEtoC8() { - try { - // user code begin {1} - // user code end - this.handleDeleteDamcatDam(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } -} -/** - * Insert the method's description here. - * Creation date: (7/15/2003 4:55:25 PM) - */ -private void fillGUI() { - Iterator it = dbFieldRelations.entrySet().iterator(); - int size; - - try { - // Fill text fields - while (it.hasNext()) { - Map.Entry entry = (Map.Entry)it.next(); - JTextField guiField = (JTextField)(entry.getKey()); - - if (((Field)entry.getValue()).get(damInfo) == null) continue; - - if (((Field)entry.getValue()).getType().equals(Float.class)) - guiField.setText(DamInfo.formatIfPossible((Float)(((Field)entry.getValue()).get(damInfo)))); - else - guiField.setText(((Field)entry.getValue()).get(damInfo).toString()); - } - - // Fill cross section table - modelCrossSections = new UneditableJTableModel(0,9,xsColFrom,xsColTo); - if (damInfo._crossSectionEntries != null) { - - size = damInfo._crossSectionEntries.size(); - _tablePairRowChangedArray = new boolean[size]; - clearRowChanged(_tablePairRowChangedArray); - - for (int i=0; i 0) - { - if (selectedDown.length == 1) - { - JOptionPane.showMessageDialog(null,"Selected downstream point was deleted"); - } - else - { - JOptionPane.showMessageDialog(null,"Selected downstream points were deleted"); - } - for (int i= 0; i < selectedDown.length; i++) - { - // get Downstream table data - String downName = (String)getTableDownstream().getModel().getValueAt(selectedDown[i],0); - dbAccess.deleteSelectedPoints(damID,downName); - } - dispose(); - } - - else - JOptionPane.showMessageDialog(null,"No rows was selected to delete."); - } - else if (confirmOption == 1) - return; - break; - case 4: - - //confirmOption = JOptionPane.showOptionDialog(null, "Do you want to delete selected cross-section\n from the database?", "Confirm Delete", JOptionPane.WARNING_MESSAGE,0,null,buttons,buttons[1]); - confirmOption = JOptionPane.showOptionDialog(null, "Do you want to delete selected cross-section(s)\n from the database?", "Confirm Delete", JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, - null,buttons, buttons[1]); - if (confirmOption == 0) - { - /*int selectedCross = getTableCrossSection().getSelectedRow(); - int rowCount = getTableCrossSection().getRowCount(); - if (selectedCross != -1) - { - JOptionPane.showMessageDialog(null,"Selected cross-section will be deleted"); - String downName = (String)getTableCrossSection().getModel().getValueAt(selectedCross,0); - String xsType = (String)getTableCrossSection().getModel().getValueAt(selectedCross,1); - Integer pairInteger = (Integer)getTableCrossSection().getModel().getValueAt(selectedCross,2); - int pairNum = pairInteger.intValue(); - // int pairNum = Integer.parseInt(pairString.trim()); - dbAccess.deleteSelectedPairs(damID,downName, xsType,pairNum); - dispose(); - }*/ - - int [] selectedCross; - selectedCross = getTableCrossSection().getSelectedRows(); - - if (selectedCross.length > 0) - { - if (selectedCross.length == 1) - { - JOptionPane.showMessageDialog(null,"Selected cross-section was deleted"); - } - else - { - JOptionPane.showMessageDialog(null,"Selected cross-sections were deleted"); - } - for (int i= 0; i < selectedCross.length; i++) - { - // get Cross-Section table data - String downName = (String)getTableCrossSection().getModel().getValueAt(selectedCross[i],0); - String xsType = (String)getTableCrossSection().getModel().getValueAt(selectedCross[i],1); - Integer pairInteger = (Integer)getTableCrossSection().getModel().getValueAt(selectedCross[i],2); - int pairNum = pairInteger.intValue(); - dbAccess.deleteSelectedPairs(damID,downName, xsType,pairNum); - } - dispose(); - } - - else - JOptionPane.showMessageDialog(null,"No rows was selected to delete."); - - } - else if (confirmOption == 1) - return; - break; - case 5: - - //confirmOption = JOptionPane.showOptionDialog(null, "Do you want to delete the input table record\n from the database?", "Confirm Delete", JOptionPane.WARNING_MESSAGE,0,null,buttons,buttons[1]); - confirmOption = JOptionPane.showOptionDialog(null, "Do you want to delete the input table record\n from the database?", "Confirm Delete", JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, - null,buttons, buttons[1]); - if (confirmOption == 0) - { - int selectedIn = getTableInput().getSelectedRow(); - if (selectedIn != -1) - { - JOptionPane.showMessageDialog(null,"The input table record was deleted"); - String src = (String)getTableInput().getModel().getValueAt(selectedIn,0); - String scenario = (String)getTableInput().getModel().getValueAt(selectedIn,1); - dbAccess.deleteSelectedInputs(damID,src,scenario); - dispose(); - } - else - JOptionPane.showMessageDialog(null,"No rows was selected to delete."); - - } - else if (confirmOption == 1) - return; - break; - case 6: - - //confirmOption = JOptionPane.showOptionDialog(null, "Do you want to delete the output table record from database?", "Confirm Delete", JOptionPane.WARNING_MESSAGE,0,null,buttons,buttons[1]); - confirmOption = JOptionPane.showOptionDialog(null, "Do you want to delete the output table record\n from the database?", "Confirm Delete", JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, - null,buttons, buttons[1]); - if (confirmOption == 0) - { - int selectedOut = getTableOutput().getSelectedRow(); - if (selectedOut != -1) - { - JOptionPane.showMessageDialog(null,"The dam output table record was deleted"); - String src = (String)getTableOutput().getModel().getValueAt(selectedOut,0); - String scenario = (String)getTableOutput().getModel().getValueAt(selectedOut,1); - String downName = (String)getTableOutput().getModel().getValueAt(selectedOut,2); - - - dbAccess.deleteSelectedOutputs(damID,src,scenario,downName); - - if(src.startsWith("#")) - { - // System.out.println("In EditDam.handleDeleteDamcatDam, src starts with #"); - - for (int i = 0; i < getTableOutput().getRowCount(); i++) - { - String srcOut = (String)getTableOutput().getModel().getValueAt(i,0); - String scenarioOut = (String)getTableOutput().getModel().getValueAt(i,1); - - if(src.equals(srcOut) && scenario.equals(scenarioOut)) - { - // System.out.println("Equal: " + src + " = " + srcOut + " " + scenario + " = " +scenarioOut); - count++; - } - } - if(count < 2) - { - // System.out.println("The row in input table was deleted"); - dbAccess.deleteSelectedInputs(damID,src,scenario); - } - } - dispose(); - } - else - JOptionPane.showMessageDialog(null,"No rows was selected to delete."); - } - else if (confirmOption == 1) - return; - break; - default: - System.out.println("indexTab is not set correctly"); - } - } catch (Exception e){ - - - } -} -/** - * Called whenever the part throws an exception. - * @param exception java.lang.Throwable - */ -private void handleException(java.lang.Throwable exception) { - - /* Uncomment the following lines to print uncaught exceptions to stdout */ - // System.out.println("--------- UNCAUGHT EXCEPTION ---------"); - // exception.printStackTrace(System.out); -} -/** - * Called when "Export to SMPDBK" is clicked - */ -private void handleExportToSMPDBK() { - - gov.dambreak.smpdbk.ModelGUI smpdbkInputEditor = new gov.dambreak.smpdbk.ModelGUI(true,damInfo.nidid,damInfo.getAnalysisData(),dbAccess); - - return; -} -/** - * Called when the user clicks "New Dam" - */ - -private void handleNewDamDownKeys() -{ - int i = get_indexTab(); - - saveUpdatesOnInsert(); // call was added on 11/30/2004 - - if(i == 3) - - if(insertDownKeys == null) - { - insertDownKeys = new NewDamDownKeys(); - } - else - { - insertDownKeys.setVisible(true); - } - - return; - -} -private void handleNewDamInKeys() -{ - int i = get_indexTab(); - - saveUpdatesOnInsert(); // call was added on 11/30/2004 - - if(i == 5) - { - if(insertInKeys == null) - { - insertInKeys = new NewDamInKeys(); - } - else - { - insertInKeys.setVisible(true); - } - } - - return; - -} -private void handleNewDamOutKeys() -{ - int i = get_indexTab(); - - saveUpdatesOnInsert(); // call was added on 11/30/2004 - - if(i == 6) - { - if(insertOutKeys == null) - { - insertOutKeys = new NewDamOutKeys(); - } - else - { - insertOutKeys.setVisible(true); - } - } - return; - -} -private void handleNewDamPairKeys() -{ - int i = get_indexTab(); - - saveUpdatesOnInsert(); // call was added on 11/30/2004 - - if(i == 4) - if(insertPairKeys == null) - { - insertPairKeys = new NewDamPairKeys(); - } - else - { - insertPairKeys.setVisible(true); - } - - return; - -} -/** - * Called when the user clicks "Save" - */ -private boolean handleSave() { - boolean _tableChanged = false; - - if (!saveGUI()) - return false; - - if (bUpdateMaster) - { - dbAccess.updateDamMaster(damInfo); // update the DamMaster table with data from the gui - } - - if (bUpdateFeatures) - { - dbAccess.updateDamFeatures(damInfo); // update the DamFeatures table with data from the gui - } - if (bUpdateDown) - { - dbAccess.updateDownstream(damInfo, _tableDownRowChangedArray); // update the Downstream table with data from the gui - clearRowChanged(_tableDownRowChangedArray); - } - if (bUpdateIn) - { - dbAccess.updateSdbIn(damInfo, _tableInRowChangedArray); // update the SdbIn table with data from the gui - clearRowChanged(_tableInRowChangedArray); - } - if (bUpdateOut) - { - dbAccess.updateSdbOut(damInfo, _tableOutRowChangedArray); // update the SdbOut table with data from the gui - clearRowChanged(_tableOutRowChangedArray); - } - if (bUpdatePair) - { - dbAccess.updateSectionPair(damInfo, _tablePairRowChangedArray); // update the SectionPair table with data from the gui - clearRowChanged(_tablePairRowChangedArray); - } - - if ((bUpdateMaster) || (bUpdateFeatures)) - getButtonNewDam().setEnabled(false); - else - getButtonNewDam().setEnabled(true); - - bUpdateMaster = bUpdateFeatures = bUpdateDown = bUpdateIn = bUpdateOut = bUpdatePair = false; - - getButtonSave().setEnabled(false); - - return true; -} -/** - * Initializes connections - * @exception java.lang.Exception The exception description. - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void initConnections() throws java.lang.Exception { - // user code begin {1} - // user code end - getButtonExport().addActionListener(ivjEventHandler); - getButtonSave().addActionListener(ivjEventHandler); - getButtonClose().addActionListener(ivjEventHandler); - getButtonNewDam().addActionListener(ivjEventHandler); - getButtonDeleteDam().addActionListener(ivjEventHandler); -} -/** - * Initialize the class. - */ -/* WARNING: THIS METHOD WILL BE REGENERATED. */ -private void initialize() { - try { - // user code begin {1} - // user code end - setName("DAMCAT_EditDam"); - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setResizable(true); - setSize(724, 553); - setTitle("DAMCAT - Dam View"); - setContentPane(getJFrameContentPane()); - initConnections(); - } catch (java.lang.Throwable ivjExc) { - handleException(ivjExc); - } - // user code begin {2} - setTitle(getTitle()+" - "+damInfo.nidid); - initializeDBFieldRelations(); - fillGUI(); - bUpdateMaster = bUpdateFeatures = bUpdateDown = bUpdateIn = bUpdateOut = bUpdatePair = false; - - /** - * Add listeners to `JTextField`s - */ - for (int i=0; i DAMCAT_Search.handleRestriction(Z)V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC1(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleRestriction(true); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC10: (ButtonPrint.action.actionPerformed(java.awt.event.ActionEvent) --> Search.handlePrintResultTable()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC10(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handlePrintResultTable(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC11: (ButtonCloneDam.action. --> Search.handleCloneADam()V) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC11() { - try { - // user code begin {1} - // user code end - this.handleCloneADam(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC12: (ButtonDeleteADam.action. --> Search.handleDeleteADam()V) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC12() { - try { - // user code begin {1} - // user code end - this.handleDeleteADam(new gov.damcat.data.DamInfo()); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - System.out.println("Exception in Search.connEtoC12()"); - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC13: (ButtonPrerun.action. --> Search.handleDisplayPrerunResults()V) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC13() { - try { - // user code begin {1} - // user code end - this.handleDisplayPrerunResults(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC2: (ButtonRemoveRestriction.action.actionPerformed(java.awt.event.ActionEvent) --> DAMCAT_Search.handleRestriction(Z)V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC2(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleRestriction(false); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC3: (ButtonClose.action.actionPerformed(java.awt.event.ActionEvent) --> DAMCAT_Search.handleClose()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC3(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleClose(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC4: (ButtonSearch.action.actionPerformed(java.awt.event.ActionEvent) --> DAMCAT_Search.handleSearch()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC4(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleSearch(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC5: (ButtonClear.action.actionPerformed(java.awt.event.ActionEvent) --> DAMCAT_Search.handleClear()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC5(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleClear(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC6: (ButtonExport.action.actionPerformed(java.awt.event.ActionEvent) --> Search.handleExportToSMPDBK()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC6(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleExportToSMPDBK(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC7: (ButtonViewEdit.action. --> DAMCAT_Search.handleViewEdit()V) - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC7() { - try { - // user code begin {1} - // user code end - this.handleViewEdit(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC8: (ButtonListAll.action.actionPerformed(java.awt.event.ActionEvent) --> Search.handleListAllDams()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC8(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleListAllDams(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - /** - * connEtoC9: (ButtonCreateDam.action.actionPerformed(java.awt.event.ActionEvent) --> Search.handleCreateNewDam()V) - * @param arg1 java.awt.event.ActionEvent - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void connEtoC9(java.awt.event.ActionEvent arg1) { - try { - // user code begin {1} - // user code end - this.handleCreateNewDam(); - // user code begin {2} - // user code end - } catch (java.lang.Throwable ivjExc) { - // user code begin {3} - // user code end - handleException(ivjExc); - } - } - //String inputValue = ""; - //boolean bDone = false; - - - //frame.show(); - - /*do { - inputValue = JOptionPane.showInputDialog("New Dam:"); - - if (inputValue.length() > 10 || inputValue.length() == 0) - JOptionPane.showMessageDialog(this,"The NID ID must be between 1 and 10 characters.", "Could Not Create Dam", JOptionPane.ERROR_MESSAGE ); - else if (dbAccess.doesDamExist(inputValue)) { // already exists - JOptionPane.showMessageDialog(this,"Dam with NID ID \"" + inputValue + "\" already exists.", "Could Not Create Dam", JOptionPane.ERROR_MESSAGE ); - ///////////////// - // NOTE: Check to see if the NIDID already exists and alert the user if it does. - } else - bDone = true; - } while(!bDone); - - ////////////// - // NOTE: Create a row for the new NIDID in the damcat_dam table here - - newDamInfo.nidid = inputValue; - - EditDam edit = new EditDam(newDamInfo,dbAccess); - edit.show(); - edit.setVisible(true); - return;*/ - //} - - private void fillClonedDam() { - - int selection = Integer.parseInt((String)getTableDam().getModel().getValueAt(getTableDam().getSelectedRow(),0)) - 1; - - DamInfo selectedDam = (DamInfo)searchResults.get(selection); - - DamInfo fullDamInfo = dbAccess.fillCompletely(selectedDam.nidid); - if (fullDamInfo._nFilled != 2) { - JOptionPane.showMessageDialog(this,"Error reading data for dam " + selectedDam.nidid + " from DAMCAT database.", "Error", JOptionPane.ERROR_MESSAGE); - } - - // *** to test the new nidid creation where a dam is cloned - String stateCode = inputState; - String nextID = dbAccess.findNextID(stateCode); - System.out.println("Search.fillClonedDam - returned " + nextID + " from " + stateCode); - - fullDamInfo.nidid = nextID; - dbAccess.insertEntireDam(fullDamInfo); - // *** end test - - // *** set EditDam.srchScreen reference to this ! - EditDam edit = new EditDam(fullDamInfo, dbAccess, this); - //edit.set_searchSelection(selection); -// edit.show(); - edit.setVisible(true); - - return; - } - private void fillCreatedDam() { - - DamInfo newDamInfo = new DamInfo(); - newDamInfo.nidid = inputState; - - // *** to test the new nidid creation where a dam is cloned - String stateCode = inputState; - String nextID = dbAccess.findNextID(stateCode); - System.out.println("Search.fillCreatedDam - returned " + nextID + " from " + stateCode); - - newDamInfo.nidid = nextID; - dbAccess.insertEntireDam(newDamInfo); - // *** end test - - // *** set EditDam.srchScreen reference to this ! - EditDam edit = new EditDam(newDamInfo,dbAccess, this); - //edit.set_searchSelection(selection); -// edit.show(); - edit.setVisible(true); - return; - } - /** - * After a search has been completed, this method fills the JTable - * with information about the returned dams. - * Creation date: (7/14/2003 1:26:23 PM) - */ - private void fillResultTable() { - // use searchResults to fill the JTable - UneditableJTableModel tm = new UneditableJTableModel(0,12); - TableSorter ts = new TableSorter(tm); - - for (int i=0; i= 1) { - field[0] = (String)getComboRestriction1().getSelectedItem(); - oper[0] = (String)getComboOperator1().getSelectedItem(); - if (oper[0].equals("is between")) { - data1[0] = getTextRestrictionBetween1_1().getText().toUpperCase(); - data2[0] = getTextRestrictionBetween1_2().getText().toUpperCase(); - } - else - { - data1[0] = getTextRestriction1().getText().toUpperCase(); - } - } - if (numRestrictions >= 2) { - field[1] = (String)getComboRestriction2().getSelectedItem(); - oper[1] = (String)getComboOperator2().getSelectedItem(); - if (oper[1].equals("is between")) { - data1[1] = getTextRestrictionBetween2_1().getText().toUpperCase(); - data2[1] = getTextRestrictionBetween2_2().getText().toUpperCase(); - } - else - { - data1[1] = getTextRestriction2().getText().toUpperCase(); - } - } - if (numRestrictions >= 3) { - field[2] = (String)getComboRestriction3().getSelectedItem(); - oper[2] = (String)getComboOperator3().getSelectedItem(); - if (oper[2].equals("is between")) { - data1[2] = getTextRestrictionBetween3_1().getText().toUpperCase(); - data2[2] = getTextRestrictionBetween3_2().getText().toUpperCase(); - } - else - { - data1[2] = getTextRestriction3().getText().toUpperCase(); - } - } - - try { - searchResults = dbAccess.search(field,oper,data1,data2); - - Collections.sort(searchResults, new Comparator() { - public int compare(Object a, Object b) { - DamInfo damInfo_a = (DamInfo)a; - DamInfo damInfo_b = (DamInfo)b; - return damInfo_a.getDam_name().compareToIgnoreCase(damInfo_b.getDam_name()); - } - }); - - } catch (Exception e) { - JOptionPane.showMessageDialog(this,"Error searching DAMCAT. Invalid parameters.", "Error",JOptionPane.ERROR_MESSAGE); - } - fillResultTable(); - - // switch back to arrow cursor - setCursor(null); - return; - } - /** - * Handle clicks to "View / Edit Dam Data" button. - */ - private void handleViewEdit() { - - int selection = Integer.parseInt((String)getTableDam().getModel().getValueAt(getTableDam().getSelectedRow(),0)) - 1; - - DamInfo selectedDam = (DamInfo)searchResults.get(selection); - - DamInfo fullDamInfo = dbAccess.fillCompletely(selectedDam.nidid); - if (fullDamInfo._nFilled != 2) { - JOptionPane.showMessageDialog(this,"Error reading data for dam " + selectedDam.nidid + " from DAMCAT database.", "Error", JOptionPane.ERROR_MESSAGE); - } - - EditDam edit = new EditDam(fullDamInfo, dbAccess, this); - edit.set_searchSelection(selection); -// edit.show(); - edit.setVisible(true); - return; - } - /** - * Initializes connections - * @exception java.lang.Exception The exception description. - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void initConnections() throws java.lang.Exception { - // user code begin {1} - // user code end - getButtonMore().addActionListener(ivjEventHandler); - getButtonFewer().addActionListener(ivjEventHandler); - getButtonClose().addActionListener(ivjEventHandler); - getButtonSearch().addActionListener(ivjEventHandler); - getButtonClear().addActionListener(ivjEventHandler); - getButtonViewEdit().addActionListener(ivjEventHandler); - getButtonExport().addActionListener(ivjEventHandler); - getButtonListAll().addActionListener(ivjEventHandler); - getButtonCreateDam().addActionListener(ivjEventHandler); - getButtonPrint().addActionListener(ivjEventHandler); - getButtonCloneDam().addActionListener(ivjEventHandler); - getButtonDeleteADam().addActionListener(ivjEventHandler); - getButtonPrerun().addActionListener(ivjEventHandler); - } - /** - * Initialize the class. - */ - /* WARNING: THIS METHOD WILL BE REGENERATED. */ - private void initialize() { - try { - // user code begin {1} - // user code end - setName("DAMCAT_Search"); - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setResizable(true); - setSize(745, 523); - setTitle("DAMCAT - Search Tool"); - setContentPane(getJFrameContentPane()); - initConnections(); - } catch (java.lang.Throwable ivjExc) { - handleException(ivjExc); - } - // user code begin {2} - - /** - * Initialize restriction combo boxes. - */ - - /* ShapeLayer shapeLayer = new ShapeLayer(); - Properties shapeLayerProps = new Properties(); - shapeLayerProps.put("prettyName", "Political Solid"); - shapeLayerProps.put("lineColor", "000000"); - shapeLayerProps.put("fillColor", "BDDE83"); - shapeLayerProps.put("shapeFile", "D:/openMap/openmap-4.5.4/share/data/shape/dcwpo-browse.shp"); - shapeLayerProps.put("spatialIndex", "D:/openMap/openmap-4.5.4/share/data/shape/dcwpo-browse.ssx"); - shapeLayer.setProperties(shapeLayerProps); - getmapBean().add(shapeLayer); - - LocationLayer loc = new LocationLayer(); - loc.setLocationHandlers( new LocationHandler[] { new BasicLocationHandler() } ); - getmapBean().add(loc);*/ - //DamMapper map = new DamMapper("Dam Map"); - - // store all three in an array for easy access - JComboBox restrictions[] = new JComboBox[3]; - restrictions[0] = getComboRestriction1(); restrictions[1] = getComboRestriction2(); restrictions[2] = getComboRestriction3(); - - // add key listeners to the restriction boxes to handle "Enter" presses - ivjPanelTop.getRootPane().setDefaultButton(ivjButtonSearch); - ivjTextRestriction1.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == e.VK_ENTER) - ivjButtonSearch.doClick(); - } - }); - ivjTextRestriction2.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == e.VK_ENTER) - ivjButtonSearch.doClick(); - } - }); - ivjTextRestriction3.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == e.VK_ENTER) - ivjButtonSearch.doClick(); - } - }); - - // initialize the items in the restriction boxes - for (int i=0; i<3; i++) { - restrictions[i].addItem("Dam Name"); - restrictions[i].addItem("River Name"); - restrictions[i].addItem("County Name"); - restrictions[i].addItem("NIDID"); - restrictions[i].addItem("HSA"); - restrictions[i].addItem("RFC"); - restrictions[i].addItem("DH"); - restrictions[i].addItem("Max Storage"); - restrictions[i].addItem("Longitude"); - restrictions[i].addItem("Latitude"); - restrictions[i].setSelectedIndex(i); - } - - getTextRestrictionBetween1_1().setVisible(false); - getTextRestrictionBetween1_1().setDocument(new NumbersOnlyDocument()); - getTextRestrictionBetween1_2().setVisible(false); - getTextRestrictionBetween1_2().setDocument(new NumbersOnlyDocument()); - getLabelBetween1().setVisible(false); - - getTextRestrictionBetween2_1().setVisible(false); - getTextRestrictionBetween2_1().setDocument(new NumbersOnlyDocument()); - getTextRestrictionBetween2_2().setVisible(false); - getTextRestrictionBetween2_2().setDocument(new NumbersOnlyDocument()); - getLabelBetween2().setVisible(false); - - getTextRestrictionBetween3_1().setVisible(false); - getTextRestrictionBetween3_1().setDocument(new NumbersOnlyDocument()); - getTextRestrictionBetween3_2().setVisible(false); - getTextRestrictionBetween3_2().setDocument(new NumbersOnlyDocument()); - getLabelBetween3().setVisible(false); - - /** - * Manage restriction boxes - */ - updateRestrictions(); - - /** - * Attempt to connect to the database. - */ - dbAccess = new DBAccess(); - if (!dbAccess.isConnected()) { - JOptionPane.showMessageDialog(this,"Could not connect to DAMCAT database. Check resources file.", "Error", JOptionPane.ERROR_MESSAGE); - getButtonSearch().setEnabled(false); - System.exit(0); - } - - getTableDam().addMouseListener(this); - - // user code end - } - /** - * Makes sure the operator list corresponds to the type of field. - * Creation date: (7/15/2003 7:02:45 AM) - */ - private void loadOperators() { - /** - * The code below could be shortened if all the components were stored in an array - */ - - // If the restriciton field is a number, load in the number operators, if it is a string load the string operators - // (restriction #1) - if (getComboRestriction1().getSelectedItem().equals("Longitude") || getComboRestriction1().getSelectedItem().equals("Latitude") || getComboRestriction1().getSelectedItem().equals("Max Storage")) { - if (getComboOperator1().getItemCount() != 4) { - if (getComboOperator1().getItemCount() != 0) - getComboOperator1().removeAllItems(); - getTextRestriction1().setDocument(new NumbersOnlyDocument()); - getComboOperator1().addItem("equals"); - getComboOperator1().addItem("is greater than"); - getComboOperator1().addItem("is less than"); - getComboOperator1().addItem("is between"); - } - } else { - if (getComboOperator1().getItemCount() != 2) { - if (getComboOperator1().getItemCount() != 0) - getComboOperator1().removeAllItems(); - getTextRestriction1().setDocument(new PlainDocument()); - getComboOperator1().addItem("contains"); - getComboOperator1().addItem("equals"); - } - } - - // If the restriciton field is a number, load in the number operators, if it is a string load the string operators - // (restriction #2) - if (getComboRestriction2().getSelectedItem().equals("Longitude") || getComboRestriction2().getSelectedItem().equals("Latitude") || getComboRestriction2().getSelectedItem().equals("Max Storage")) { - if (getComboOperator2().getItemCount() != 4) { - if (getComboOperator2().getItemCount() != 0) - getComboOperator2().removeAllItems(); - getTextRestriction2().setDocument(new NumbersOnlyDocument()); - getComboOperator2().addItem("equals"); - getComboOperator2().addItem("is greater than"); - getComboOperator2().addItem("is less than"); - getComboOperator2().addItem("is between"); - } - } else { - if (getComboOperator2().getItemCount() != 2) { - if (getComboOperator2().getItemCount() != 0) - getComboOperator2().removeAllItems(); - getTextRestriction2().setDocument(new PlainDocument()); - getComboOperator2().addItem("contains"); - getComboOperator2().addItem("equals"); - } - } - - // If the restriciton field is a number, load in the number operators, if it is a string load the string operators - // (restriction #3) - if (getComboRestriction3().getSelectedItem().equals("Longitude") || getComboRestriction3().getSelectedItem().equals("Latitude") || getComboRestriction3().getSelectedItem().equals("Max Storage")) { - if (getComboOperator3().getItemCount() != 4) { - if (getComboOperator3().getItemCount() != 0) - getComboOperator3().removeAllItems(); - getTextRestriction3().setDocument(new NumbersOnlyDocument()); - getComboOperator3().addItem("equals"); - getComboOperator3().addItem("is greater than"); - getComboOperator3().addItem("is less than"); - getComboOperator3().addItem("is between"); - } - } else { - if (getComboOperator3().getItemCount() != 2) { - if (getComboOperator3().getItemCount() != 0) - getComboOperator3().removeAllItems(); - getTextRestriction3().setDocument(new PlainDocument()); - getComboOperator3().addItem("contains"); - getComboOperator3().addItem("equals"); - } - } - } - /** - * Invoke DAMCAT_Search as a standalone application. - * Creation date: (7/14/2003 11:04:59 AM) - * @param args java.lang.String[] - */ - public static void main(String[] args) { - System.out.println("Initializing DAMCAT_Search..."); - Search mainFrame = new Search(true); - mainFrame.setVisible(true); - } - /** - * Adds actionListeners to the combo boxes. - * Creation date: (7/15/2003 7:40:03 AM) - * @param bRemove boolean - */ - private void manageListeners(boolean bRemove) { - - if (bRemove) { - getComboRestriction1().removeActionListener(this); - getComboRestriction2().removeActionListener(this); - getComboRestriction3().removeActionListener(this); - getComboOperator1().removeActionListener(this); - getComboOperator2().removeActionListener(this); - getComboOperator3().removeActionListener(this); - } else { - getComboRestriction1().addActionListener(this); - getComboRestriction2().addActionListener(this); - getComboRestriction3().addActionListener(this); - getComboOperator1().addActionListener(this); - getComboOperator2().addActionListener(this); - getComboOperator3().addActionListener(this); - } - } - /** - * Allow the user to double click on a dam in the search results table in order to view - * its information. - * Creation date: (7/17/2003 1:49:25 PM) - * @param e java.awt.event.MouseEvent - */ - public void mouseClicked(MouseEvent e) { - // if this is a double click, see if the mouse is over a row - if (e.getClickCount() >= 2 && getTableDam().rowAtPoint(e.getPoint()) != -1) { - handleViewEdit(); - } - } - /** - * Insert the method's description here. - * Creation date: (7/17/2003 1:49:37 PM) - * @param e java.awt.event.MouseEvent - */ - public void mouseEntered(MouseEvent e) {} - /** - * Insert the method's description here. - * Creation date: (7/17/2003 1:49:44 PM) - * @param e java.awt.event.MouseEvent - */ - public void mouseExited(MouseEvent e) {} - /** - * Insert the method's description here. - * Creation date: (7/17/2003 1:49:52 PM) - * @param e java.awt.event.MouseEvent - */ - public void mousePressed(MouseEvent e) {} - /** - * Insert the method's description here. - * Creation date: (7/17/2003 1:50:00 PM) - * @param e java.awt.event.MouseEvent - */ - public void mouseReleased(MouseEvent e) {} - private void trace() - { - try - { - throw new Exception("trace"); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - /** - * Update the restriction entries to reflect user choices. - * Creation date: (7/14/2003 11:30:44 AM) - */ - private void updateRestrictions() { - - // turn off combo box action listeners for now - manageListeners(true); - - // position "More" and "Fewer" buttons - if (numRestrictions == 1) { - getButtonMore().setLocation(317,60); - getButtonFewer().setLocation(407,60); - } else if (numRestrictions == 2) { - getButtonMore().setLocation(317,90); - getButtonFewer().setLocation(407,90); - } else { - getButtonMore().setLocation(317,120); - getButtonFewer().setLocation(407,120); - } - - // enable / disable "More" and "Fewer" buttons - if (numRestrictions == 3) - getButtonMore().setEnabled(false); - else - getButtonMore().setEnabled(true); - - if (numRestrictions == 1) - getButtonFewer().setEnabled(false); - else - getButtonFewer().setEnabled(true); - - // enable / disable editors for the restrictions - if (numRestrictions == 1) { - - // disable #2 - getComboRestriction2().setVisible(false); - getComboOperator2().setVisible(false); - getTextRestrictionBetween2_1().setVisible(false); - getTextRestrictionBetween2_2().setVisible(false); - getLabelBetween2().setVisible(false); - getTextRestriction2().setVisible(false); - - // disable #3 - getComboRestriction3().setVisible(false); - getComboOperator3().setVisible(false); - getTextRestrictionBetween3_1().setVisible(false); - getTextRestrictionBetween3_2().setVisible(false); - getLabelBetween3().setVisible(false); - getTextRestriction3().setVisible(false); - - } else if (numRestrictions == 2) { - - // enable #2 - getComboRestriction2().setVisible(true); - getComboOperator2().setVisible(true); - getTextRestriction2().setVisible(true); - - // disable #3 - getComboRestriction3().setVisible(false); - getComboOperator3().setVisible(false); - getTextRestrictionBetween3_1().setVisible(false); - getTextRestrictionBetween3_2().setVisible(false); - getLabelBetween3().setVisible(false); - getTextRestriction3().setVisible(false); - - } else if (numRestrictions == 3) { - - // enable #2 - getComboRestriction2().setVisible(true); - getComboOperator3().setVisible(true); - getTextRestriction2().setVisible(true); - - // enable #3 - getComboRestriction3().setVisible(true); - getComboOperator3().setVisible(true); - getTextRestriction3().setVisible(true); - - } - - // handle the different search methods for strings and numbers - loadOperators(); - - // enable / disable the "between" text fields (restriction #1) - if (getComboOperator1().getSelectedItem().equals("is between")) { - getTextRestriction1().setVisible(false); - getLabelBetween1().setVisible(true); - getTextRestrictionBetween1_1().setVisible(true); - getTextRestrictionBetween1_2().setVisible(true); - } else { - getTextRestriction1().setVisible(true); - getLabelBetween1().setVisible(false); - getTextRestrictionBetween1_1().setVisible(false); - getTextRestrictionBetween1_2().setVisible(false); - } - - // enable / disable the "between" text fields (restriction #2) - if (getComboOperator2().getSelectedItem().equals("is between") && numRestrictions >= 2) { - getTextRestriction2().setVisible(false); - getLabelBetween2().setVisible(true); - getTextRestrictionBetween2_1().setVisible(true); - getTextRestrictionBetween2_2().setVisible(true); - } else if (numRestrictions >= 2) { - getTextRestriction2().setVisible(true); - getLabelBetween2().setVisible(false); - getTextRestrictionBetween2_1().setVisible(false); - getTextRestrictionBetween2_2().setVisible(false); - } - - // enable / disable the "between" text fields (restriction #3) - if (getComboOperator3().getSelectedItem().equals("is between") && numRestrictions >= 3) { - getTextRestriction3().setVisible(false); - getLabelBetween3().setVisible(true); - getTextRestrictionBetween3_1().setVisible(true); - getTextRestrictionBetween3_2().setVisible(true); - } else if (numRestrictions >= 3) { - getTextRestriction3().setVisible(true); - getLabelBetween3().setVisible(false); - getTextRestrictionBetween3_1().setVisible(false); - getTextRestrictionBetween3_2().setVisible(false); - } - - // turn combo box action listeners back on - manageListeners(false); - } - /** - * Listenes for dam info click. - * Creation date: (7/15/2003 11:22:19 AM) - */ - public void valueChanged(ListSelectionEvent e) { - if (!e.getValueIsAdjusting()) { - if (getTableDam().getSelectedRow() == -1) { - getButtonViewEdit().setEnabled(false); - getButtonExport().setEnabled(false); - getButtonCloneDam().setEnabled(false); - getButtonDeleteADam().setEnabled(false); - getButtonPrerun().setEnabled(false); - } - else { - getButtonViewEdit().setEnabled(true); - getButtonExport().setEnabled(true); - getButtonCloneDam().setEnabled(true); - getButtonDeleteADam().setEnabled(true); - getButtonPrerun().setEnabled(true); - } - } - } -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/AppsDefaults.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/AppsDefaults.java deleted file mode 100644 index 486bb17749..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/AppsDefaults.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Created on Jul 10, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.util; - -import java.util.*; -import java.io.*; - -/** - * @author gobsc - * - * This is the Java version of get_apps_defaults.c - */ -public class AppsDefaults -{ - - - private static final String APPS_DEFAULTS_USER = "APPS_DEFAULTS_USER"; - private static final String APPS_DEFAULTS_PROG = "APPS_DEFAULTS_PROG"; - private static final String APPS_DEFAULTS_SITE = "APPS_DEFAULTS_SITE"; - private static final String APPS_DEFAULTS = "APPS_DEFAULTS"; - - private static final String RFR_OPEN= "$("; - private static final String RFR_CLOSE = ")"; - - private static final char DELIM = ':'; - private static final char COMMENT = '#'; - - private static final char DOUBLE_QUOTE = '\"'; - private static final char SINGLE_QUOTE = '\''; - - private static final int RECUR_LIMIT = 40; - private int _recursionCount = 0; - - private Properties _envProperties = new Properties(); - - private String _appsDefaultsUserFilePath = null; - private String _appsDefaultsProgramFilePath = null; - private String _appsDefaultsSiteFilePath = null; - private String _appsDefaultsNationalFilePath = null; - - private BufferedReader _reader = null; - -//-------------------------------------------------------------- - public AppsDefaults() - { - EnvHelper envHelper = new EnvHelper(); - - _envProperties = envHelper.getProperties(); - - _appsDefaultsUserFilePath = _envProperties.getProperty(APPS_DEFAULTS_USER); - _appsDefaultsProgramFilePath = _envProperties.getProperty(APPS_DEFAULTS_PROG); - _appsDefaultsSiteFilePath = _envProperties.getProperty(APPS_DEFAULTS_SITE); - _appsDefaultsNationalFilePath = _envProperties.getProperty(APPS_DEFAULTS); - - return; - } -// ----------------------------------------------------- - public String getToken(String tokenName) - { - String tokenValue = null; - - //System.out.println("recursion count = " + _recursionCount); - - String envValue = _envProperties.getProperty(tokenName); - - // if token is available as an environment variable, use its value - if (envValue != null) - { - tokenValue = envValue; - } - else // look for the token in each the files (if they are defined), until - // find the token, then stop looking as soon as it is found - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsUserFilePath); - if (tokenValue == null) - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsProgramFilePath); - if (tokenValue == null) - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsSiteFilePath); - if (tokenValue == null) - { - tokenValue = getTokenFromFile(tokenName, _appsDefaultsNationalFilePath); - } - } - } - } //end else - - tokenValue = expandReferBacks(tokenValue); - - return tokenValue; - - } //end getToken() - -// -------------------------------------------------------------- - - private String getTokenFromFile(String tokenName, String filePath) - { - String tokenValue = null; - boolean tokenFound = false; - String line = ""; - - NameValuePair nameValuePair = null; - - if (filePath != null) - { - - try - { - _reader = new BufferedReader (new FileReader(filePath)); - - while ((! tokenFound) && (line != null) ) - { - line = getLine(); - if (line == null) - { - break; - } - nameValuePair = parseLine(line); - - if (nameValuePair != null) - { - // System.out.println("nameValuePair.getName() = |" + - // nameValuePair.getName() + "|" ); - - // System.out.println("nameValuePair.getValue() = |" + - // nameValuePair.getValue() + "|" ); - - if ( (nameValuePair.getName().equals(tokenName)) ) - - { - tokenFound = true; - tokenValue = nameValuePair.getValue(); - } - } - } - - _reader.close(); - - } - catch (java.io.IOException e) - { - - } - - } - return tokenValue; - } - -// ----------------------------------------------------- - private String expandReferBacks(String tokenValue) - { - if (tokenValue != null) - { - while (thereAreReferBacks(tokenValue)) - { - //System.out.println("tokenValue before expandFirstReferBack = " + tokenValue); - tokenValue = expandFirstReferBack(tokenValue); - //System.out.println("tokenValue after expandFirstReferBack = " + tokenValue); - } - } - - return tokenValue; - } - -// ----------------------------------------------------- - - private boolean thereAreReferBacks(String tokenValue) - { - boolean result = false; - - if (tokenValue.indexOf(RFR_OPEN) > -1) - { - result = true; - } - - return result; - } - -// ----------------------------------------------------- - - private String expandFirstReferBack(String tokenValue) - { - - int referBackStartIndex = tokenValue.indexOf(RFR_OPEN); - int referBackEndIndex = tokenValue.indexOf(RFR_CLOSE); - String beginning = ""; - String middle = null; - String newTokenName = null; - String end = ""; - - if ((referBackStartIndex > -1) && (referBackEndIndex > -1)) - { - if (referBackStartIndex > 0) - { - beginning = tokenValue.substring(0, referBackStartIndex); - } - - newTokenName = tokenValue.substring(referBackStartIndex + RFR_OPEN.length(), - referBackEndIndex); - - _recursionCount++; - - if (_recursionCount <= RECUR_LIMIT) - { - middle = getToken(newTokenName); - _recursionCount--; - } - else - { - middle = "ERROR_ERROR_ERROR"; - System.err.println("You probably have a cycle in your Apps Defaults File's refer backs, please check it"); - } - if ( (referBackEndIndex + RFR_CLOSE.length()) < tokenValue.length() ) - { - end = tokenValue.substring(referBackEndIndex + RFR_CLOSE.length(), - tokenValue.length()); - } - - - tokenValue = beginning + middle + end; - } - - return tokenValue; - } - -// ----------------------------------------------------- - private String getLine() throws java.io.IOException - { - String line = null; - - line = _reader.readLine(); - - // System.out.println("line = " + line); - - return line; - } -// ----------------------------------------------------- - private NameValuePair parseLine(String line) - { - NameValuePair pair = null; - int delimiterIndex = -1; - - String tokenName = null; - String tokenValue = null; - - //find delimiter - - delimiterIndex = line.indexOf(DELIM); - - - if (delimiterIndex > -1) //there is a delimiter character on the line - { - //find tokenName - tokenName = findTokenName(line, delimiterIndex); - - if (tokenName != null) - { - tokenValue = findTokenValue(line, delimiterIndex); - if (tokenValue != null) - { - pair = new NameValuePair(tokenName, tokenValue); - } - } - } // end if found a delimiter - else //there is no delimiter, so can't read a pair from this line - { - pair = null; - } - - return pair; - } - -// ----------------------------------------------------- - private String findTokenName(String line, int delimiterIndex) - { - String tokenName = null; - boolean foundTokenName = false; - boolean foundStartOfTokenName = false; - boolean foundComment = false; - StringBuffer tokenNameBuffer = new StringBuffer(); - - - for (int i = 0; ((i < delimiterIndex) && - (! foundTokenName)) && - (! foundComment) ; i++) - { - char c = line.charAt(i); - if (isWhiteSpace(c)) - { - // check to see if this is white space at the beginning or the end - // of the tokenName - if (! foundStartOfTokenName) //this must beginning whitespace - { - // so ignore the whitespace - } - else //must be trailing whitespace - { - // the token is done; - tokenName = tokenNameBuffer.toString(); - foundTokenName = true; - } - } //end if isWhiteSpace - - else if (isCommentStarter(c)) - { - //There can't be a valid tokenName, tokenValue pair here, then - foundComment = true; - - //clear out the tokenNameVariables - tokenName = null; - - // works in >= java 1.2, - //tokenNameBuffer.delete(0, tokenNameBuffer.length()); - - //works in java < 1.2, but the previous line is prefered - tokenNameBuffer = new StringBuffer(); - - foundStartOfTokenName = false; - break; //exit loop - - } //end isCommentStarter - - else //part of the tokenName - { - tokenNameBuffer.append(c); - foundStartOfTokenName = true; - } - - } //end for - - if (foundStartOfTokenName) - { - tokenName = tokenNameBuffer.toString(); - } - - return tokenName; - } - - //---------------------------------------------------------------------- - - private String findTokenValue(String line, int delimiterIndex) - { - String tokenValue = null; - - boolean foundTokenValue = false; - boolean foundStartOfTokenValue = false; - boolean foundComment = false; - - boolean foundSingleOpenQuote = false; - boolean foundSingleCloseQuote = false; - - boolean foundDoubleOpenQuote = false; - boolean foundDoubleCloseQuote = false; - - boolean error = false; - - StringBuffer tokenValueBuffer = new StringBuffer(); - - for (int i = delimiterIndex + 1 ; ((i < line.length()) && - (! foundTokenValue)) && - (! foundComment) ; i++) - { - char c = line.charAt(i); - if (isWhiteSpace(c)) - { - // check to see if this is white space at the beginning or the end - // of the tokenValue - if (! foundStartOfTokenValue) //this must be beginning whitespace - { - // so ignore the whitespace - } - else if ((foundSingleOpenQuote) && (!foundSingleCloseQuote)) - { - tokenValueBuffer.append(c); - foundStartOfTokenValue = true; - } - else if ((foundDoubleOpenQuote) && (!foundDoubleCloseQuote)) - { - tokenValueBuffer.append(c); - foundStartOfTokenValue = true; - } - else //must be trailing whitespace - { - // the token value reading is done; - tokenValue = tokenValueBuffer.toString(); - foundTokenValue = true; - } - } //end if isWhiteSpace - - else if (isCommentStarter(c)) - { - if (foundStartOfTokenValue ) - { - //this character is allowed in a tokenValue - tokenValueBuffer.append(c); - } - else - { //error, there can't be a valid tokenValue - foundComment = true; - - //clear out the tokenNameVariables - tokenValue = null; - - // works in >= java 1.2, - //tokenValueBuffer.delete(0, tokenValueBuffer.length()); - - //works in java < 1.2, but the previous line is prefered - tokenValueBuffer = new StringBuffer(); - - - error = true; - } - } //end isCommentStarter - - else if (isDelimiter(c)) - { - if (foundStartOfTokenValue ) - { - //this character is allowed in a tokenValue - tokenValueBuffer.append(c); - } - else - { //error, there can't be a valid tokenValue - - //clear out the tokenNameVariables - tokenValue = null; - - // works in >= java 1.2, - //tokenValueBuffer.delete(0, tokenValueBuffer.length()); - - //works in java < 1.2, but the previous line is prefered - tokenValueBuffer = new StringBuffer(); - - error = true; - break; //exit loop - } - - } - else if (isSingleQuote(c)) - { - if (foundSingleOpenQuote) - { - foundSingleCloseQuote = true; - foundTokenValue = true; //done - } - else - { - foundSingleOpenQuote = true; - } - } - - else if (isDoubleQuote(c)) - { - if (foundDoubleOpenQuote) - { - foundDoubleCloseQuote = true; - foundTokenValue = true; //done - } - else - { - foundDoubleOpenQuote = true; - } - } - - else //part of the tokenValue - { - tokenValueBuffer.append(c); - // System.out.println("tokenValueBuffer =" + tokenValueBuffer.toString()); - foundStartOfTokenValue = true; - } - - } //end for - - if ( (foundStartOfTokenValue) && (!error)) - { - tokenValue = tokenValueBuffer.toString(); - } - - return tokenValue; - } - // ----------------------------------------------------- - - -// ----------------------------------------------------- - - - // - private static boolean isWhiteSpace(char c) - { - boolean result = false; - - if ( (c == ' ') || (c== '\t') ) - { - result = true; - } - - return result; - - } //isWhiteSpace - -// ----------------------------------------------------- - private static boolean isCommentStarter(char c) - { - boolean result = false; - - if (c == COMMENT) - { - result = true; - } - - return result; - } //isCommentStarter - - //------------------------------------------------------------- - private static boolean isDelimiter(char c) - { - boolean result = false; - - if (c == DELIM) - { - result = true; - - } - - return result; - } //isDelimiter - - //----------------------------------------------------------- - - private static boolean isSingleQuote(char c) - { - boolean result = false; - - if (c == SINGLE_QUOTE) - { - result = true; - } - - return result; - } //isSingleQuote - -// ----------------------------------------------------- - - private static boolean isDoubleQuote(char c) - { - boolean result = false; - - if (c == DOUBLE_QUOTE) - { - result = true; - } - - return result; - - } //isDoubleQuote - - -// ----------------------------------------------------- - public static void main(String[] args) - { - AppsDefaults ad = new AppsDefaults(); - String tokenName = null; - String tokenValue = null; - - // tokenName = "shef_procobs"; - // tokenValue = ad.getToken(tokenName); - - // System.out.println("tokenName = " + tokenName + - // " tokenValue = " + tokenValue); - - tokenName = "ffg_out_dir"; - tokenValue = ad.getToken(tokenName); - - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - - tokenName = "testToken1"; - //tokenRawValue = "#hank:me:'llhank' " - tokenValue = ad.getToken(tokenName); - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - tokenName = "testToken2"; - //tokenRawValue = "dd#hank:me:'llhank' " - tokenValue = ad.getToken(tokenName); - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - - tokenName = "testToken3"; - //tokenRawValue = 'dd#hank:me:"llhank" ' - tokenValue = ad.getToken(tokenName); - System.out.println("tokenName = " + tokenName + - " tokenValue = " + tokenValue); - - } - - -} // end class AppsDefaults diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/Apps_defaults_test_user.txt b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/Apps_defaults_test_user.txt deleted file mode 100644 index 7d0394ecc3..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/Apps_defaults_test_user.txt +++ /dev/null @@ -1,134 +0,0 @@ -# -# Official .Apps_defaults_site file for OHD/HL for AWIPS Release 5.2.1 -# Also see National .Apps_defaults file for other settings -# Revised: 30 October 2001 -# ==================================================================== - -# --------TOKENS THAT SHOULD BE AT ALL SITES----------- - -# database selection tokens -db_name : hd5_12ounx # IHFS database name - -# =========================================================================== -# WHFS Local Customization -# =========================================================================== -hv_center_lat : 35.0 # HydroView center latitude -hv_center_lon : -97.8 # HydroView center longitude -hv_map_width : 650 # HydroView map width (nautical miles) -whfs_primary_radar : TLX # WHFS primary radar id, for Stage II -whfs_tz : CST6CDT # WHFS time zone for local time -hv_refresh_minutes : 10 # HydroView auto refresh time (minutes) -hv_pets : PRIMARY # initial shef PE-TS point data display - # value either: PRIMARY, PCPP, , -hv_riverbasis : obs # initial river basis for river characteristics - # values either obs, fcst, maxobsfcst -hv_durhours : 36 # initial hour duration for point data display - -# shefdecode tokens -shef_perflog : OFF # ON/OFF - create a separate performance log file to - # save internal decoder timing messages for - # monitoring performance - -shef_load_ingest : ON # ON/OFF - automatically load the IngestFilter table or not - # with (station id-PEDTSE) combinations as they - # arrive in the input data flow -shef_storetext : ON # ON/OFF - post/don't post raw encoded SHEF text messages - # to the TextProduct table -shef_post_unk : IDS_ONLY # NONE - do not post to the UnkStn nor UnkStnValue tables - # IDS_ONLY - post only location identifiers for unknown - # stations to the UnkStn table - # IDS_AND_DATA - post all data from unknown stations to - # the UnkStnValue table -shef_post_baddata : REJECT # PE/REJECT - post data that have failed the gross range - # check to the physical element data tables (=PE) OR - # to the RejectedData table (=REJECT) -shef_procobs : OFF # ON/OFF - post Processed data values (i.e., TS=P*) to - # the observation data tables (=ON) or to - # the ProcValue table (=OFF) -shef_post_latest : VALID_ONLY # ON/OFF - post/don't post data to the LatestObsValue table - # VALID_ONLY - post data to the LatestObsValue table - # ONLY if the gross range check is passed -shef_post_link : ON # ON/OFF - post/don't post data to the ProductLink table -shef_load_maxfcst : ON # ON/OFF - after each product that resulted in forecast - # height or discharge data being posted, load - # the maximum forecast data into the RiverStatus table -shef_alertalarm : ON # ON/OFF - causes shefdecoder to screen data against - # alert and alarm thresholds - -# ----END TOKENS THAT SHOULD BE AT ALL SITES------------ - -# --------TOKENS THAT SHOULD BE AT EACH RFC SITE-------- - -#tokens for ifp -ifp_rfc : ofstest # name of RFC to run for IFP - -#tokens for stageiii -st3_rfc : oun -awips_rfc_id : OUN # 3 char AWIPS RFC identifier - # must be all upper case - -#tokens for auto_stageiii -st3_auto_graphic_scale : 2.4 - -# defaults for stageiii netCDF output -st3_netcdf_loc : arkansas_red_basin_river_forecast_center_tulsa_ok - # underscores needed between words -st3_netcdf_swlat : 33.603 -st3_netcdf_swlon : 106.456 -st3_netcdf_selat : 32.433 -st3_netcdf_selon : 92.322 -st3_netcdf_nelat : 38.027 -st3_netcdf_nelon : 90.678 -st3_netcdf_nwlat : 39.420 -st3_netcdf_nwlon : 106.652 - -# ----END TOKENS THAT SHOULD BE AT EACH RFC SITE------- - -# ------- TOKENS THAT ARE OHD/HL SPECIFIC-------------- - -cm_database : programs # CM database - -# NWSRFS tokens - -home_files_workstation : ds1-nhdr # hostname of machine for home files - -ofs_level : ofstest -ofs_reor_lvl : test -ofs_inpt_grp : ofstest - -# ds tokens -ds_system : $(apps_dir)/devl_sys -ds_system_lvl_dirs : "src inc ctl lib obj mak log rls" -ds_system_levels1 : "ofs util calb my ifp mgr ffg grib st1 icp oli" -ds_system_levels2 : "esp cmdb hdb precip_proc pproc_rfcdb" - -my_dir : /home/$(LOGNAME)/devl -my_rls : $(my_dir)/bin -my_bin : $(my_dir)/bin -mgr_dir : $(apps_dir)/mgr -mgr_rls : $(mgr_dir)/bin/RELEASE - -my_src : $(my_dir)/src -ofs_src : $(ofs_dir)/src -util_src : $(util_dir)/src -calb_src : $(calb_dir)/src - -ofs_server : apwk01g2 # OFS "slave" server - -oli_source : $(oli_dir)/source - -# ffg program control -ffg_level : ofstest -ffg_out_dir : $(ffg_dir)/output/$(ffg_level) - -# mpe tokens - -rfcw_rfcname : oun -awips_rfc_id : OUN -st3_rfc : oun -rfcwide_xmrg_dir : "D:\Data\code\SiteSpecific\input\mpe" -st3_auto_graphic_scale : 2.4 - -#siipp tokens - -siipp_table_post : procp diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/CodeTimer.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/CodeTimer.java deleted file mode 100644 index b59a83b58b..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/CodeTimer.java +++ /dev/null @@ -1,110 +0,0 @@ -package ohd.hseb.util; - -// create a Logger class. Give to Gautam for java practice purposes. - -public class CodeTimer -{ - - private boolean _isRunning = false; - private long _startTime = 0; - private long _endTime = 0; - private long _elapsedTime = 0; - private Logger _logger = null; - - //----------------------------------------------- - - public CodeTimer() - { - - - } - //----------------------------------------------- - - public CodeTimer(Logger logger) - { - _logger = logger; - } - - //----------------------------------------------- - - public void start() - { - _isRunning = true; - _startTime = System.currentTimeMillis(); - _elapsedTime = 0; - - return; - } - - //----------------------------------------------- - - public long stop() - { - return this.stop(""); - } - - //----------------------------------------------- - - public long stop(String message) - { - _endTime = System.currentTimeMillis(); - _elapsedTime += (_endTime - _startTime); - - _isRunning = false; - - if ( (message != null) && (message.length() > 0) ) - { - log(message + " " + _elapsedTime + " millis."); - } - - if (_logger != null) - { - _logger.close(); - } - - return _elapsedTime; - } - - //----------------------------------------------- - - public void restart() - { - _isRunning = true; - _startTime = System.currentTimeMillis(); - } - - //----------------------------------------------- - - // reset all the state variables - public void clear() - { - _isRunning = false; - _startTime = 0; - _endTime = 0; - _elapsedTime = 0; - } - - //----------------------------------------------- - - private void log(String message) - { - if (_logger != null) - { - _logger.log(message); - } - else - { - System.out.println(message); - } - return; - } - - //----------------------------------------------- - - public long getElapsedTime() - { - return _elapsedTime; - } - - -} //end class CodeTimer diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/EnvHelper.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/EnvHelper.java deleted file mode 100644 index e083cdfa57..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/EnvHelper.java +++ /dev/null @@ -1,125 +0,0 @@ - -package ohd.hseb.util; - -import java.util.*; -import java.io.*; - -public class EnvHelper -{ - - private Properties _props = null; - //-------------------------------------------------------------- - private String getEnvCommandString() - { - String OS = System.getProperty("os.name").toLowerCase(); - String commandString = ""; - - if (OS.indexOf("windows 9") > -1) - { - commandString = "command.com /c set " ; - } - else if ( (OS.indexOf("nt") > -1) - || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1) ) - { - // thanks to JuanFran for the xp fix! - commandString = "cmd.exe /c set " ; - } - else //assume unix - { - commandString = "env"; - } - - return commandString; - } - //-------------------------------------------------------------- - public Properties getProperties() - { - if (_props == null) - { - _props = new Properties(); - - Process process = null; - - String commandString = this.getEnvCommandString(); - Runtime runtime = Runtime.getRuntime(); - - try - { - - process = runtime.exec(commandString); - - InputStream inStream = process.getInputStream(); - - - BufferedReader br = new BufferedReader - ( new InputStreamReader( inStream) ); - String line; - while( (line = br.readLine()) != null ) - { - int index = line.indexOf( '=' ); - if (index < 0) - { - //something is wrong with the line, - // ignore it and read the next line - continue; - } - - String key = line.substring( 0, index ); - String value = line.substring( index+1 ); - - // works in java >= 1.2 - //_props.setProperty( key, value ); - - // works in java < 1.2, and later, but is not prefered. - _props.put(key, value); - - // System.out.println( key + " = " + value ); - } - } - catch (java.io.IOException e) - { - e.printStackTrace(); - return _props; - } - - - } //end if - - return _props; - } - - //-------------------------------------------------------------- - public String getProperty(String key) - { - Properties props = this.getProperties(); - return props.getProperty(key); - } - - //-------------------------------------------------------------- - public static void main(String[] args) - { - EnvHelper envHelper = new EnvHelper(); - - - Properties env = envHelper.getProperties(); - - if (env == null) - { - System.out.println("dude, env is null"); - } - else - { - System.out.println("------------------"); - env.list(System.out); - } - - String tempVar = envHelper.getProperty("TEMP"); - - System.out.println("TEMP = " + tempVar); - - - return; - } - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/Logger.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/Logger.java deleted file mode 100644 index 6f386f48ed..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/Logger.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Created on Jul 9, 2003 - * - * - */ -package ohd.hseb.util; - -import java.io.*; - -/** - * @author Chip Gobs - * - * - */ -public interface Logger -{ - public void log(String message); - public void close(); - public PrintWriter getPrintWriter(); -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/NameValuePair.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/NameValuePair.java deleted file mode 100644 index a0e8820c8f..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/NameValuePair.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Created on Jul 11, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.util; - -/** - * @author gobsc - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class NameValuePair -{ - private String _name; - private String _value; - - public NameValuePair() - { - - } - - public NameValuePair(String name, String value) - { - setName(name); - setValue(value); - } - - public void setName(String name) - { - this._name = name; - } - - public String getName() - { - return _name; - } - - public void setValue(String value) - { - this._value = value; - } - - public String getValue() - { - return _value; - } - -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/TimeHelper.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/TimeHelper.java deleted file mode 100644 index d54234c3d1..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/TimeHelper.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on Oct 8, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author GobsC - * - */ - -public class TimeHelper -{ - - public static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - public static long roundTimeInMillisToNearestHour(long timeInMillis, - int hoursToRound) - { - long roundingAmount = hoursToRound * MILLIS_PER_HOUR; - long roundedTime = timeInMillis; - roundedTime /= roundingAmount; - roundedTime *= roundingAmount; - - return roundedTime; - } -// -------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/TimeHolder.java b/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/TimeHolder.java deleted file mode 100644 index 544cafce9d..0000000000 --- a/javaUtilities/hydro/ohd.damcrest/src/ohd/hseb/util/TimeHolder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Created on Oct 31, 2003 - * - * - */ -package ohd.hseb.util; - -/** - * @author Chip Gobs - * - * This class is intended to be used as a way for - * other objects to point to something that is always used - * to maintain a time. Multiple objects may wish to set - * or get the time contained herein. They can do this to - * remain in synch about a particular time concept. - Example: various objects need to know what the model run time is - without explicitly know who is maintaining it, so they just have a reference - to the same timeholder, which they can access. - **/ -public class TimeHolder -{ - private long _time = 0; - - public void setTime(long time) - { - _time = time; - } - - public long getTime() - { - return _time; - } - -} diff --git a/javaUtilities/hydro/ohd.damcrestdb/.classpath b/javaUtilities/hydro/ohd.damcrestdb/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.damcrestdb/.project b/javaUtilities/hydro/ohd.damcrestdb/.project deleted file mode 100644 index 8dd6c0e48c..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.damcrestdb - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.damcrestdb/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.damcrestdb/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index e583d9bdf5..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:19:14 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.damcrestdb/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.damcrestdb/META-INF/MANIFEST.MF deleted file mode 100644 index a0d7912376..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/META-INF/MANIFEST.MF +++ /dev/null @@ -1,6 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Damcrestdb -Bundle-SymbolicName: ohd.damcrestdb -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/javaUtilities/hydro/ohd.damcrestdb/build.properties b/javaUtilities/hydro/ohd.damcrestdb/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.damcrestdb/build.xml b/javaUtilities/hydro/ohd.damcrestdb/build.xml deleted file mode 100644 index e01e6ae12b..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.damcrestdb/ohd.damcrestdb.ecl b/javaUtilities/hydro/ohd.damcrestdb/ohd.damcrestdb.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.damcrestdb/scripts/create_table_names_file b/javaUtilities/hydro/ohd.damcrestdb/scripts/create_table_names_file deleted file mode 100644 index 02b9347c00..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/scripts/create_table_names_file +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/ksh - -export HOME_DIR=/fs/hseb/${DS_BUILD}/ohd -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. - -export IHFS_TABLE_DIR=$HOME_DIR/whfs/schema/DamCrest/tables -export VIEW_DIR=$HOME_DIR/whfs/schema/DamCrest/views - -export TABLE_FILE_TEMP=$PROJECTS_DIR/damcrestdb/scripts/PreferredTableNames.txt.temp -export TABLE_IHFS_FILE=$PROJECTS_DIR/damcrestdb/scripts/PreferredTableNames.txt -export LS="ls" -export CAT="cat" - -$LS $IHFS_TABLE_DIR $VIEW_DIR > $TABLE_FILE_TEMP -$CAT $TABLE_FILE_TEMP | grep -v '^s\.' | grep '\.t' |/usr/bin/cut -d. -f1 > $TABLE_IHFS_FILE -echo TABLE_IHFS_FILE = $TABLE_IHFS_FILE diff --git a/javaUtilities/hydro/ohd.damcrestdb/scripts/make_table_names.txt b/javaUtilities/hydro/ohd.damcrestdb/scripts/make_table_names.txt deleted file mode 100644 index 6cfa22597f..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/scripts/make_table_names.txt +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - $(LS) $(IHFS_TABLE_DIR) $(VIEW_DIR) > $(TABLE_FILE_TEMP) - $(CAT) $(TABLE_FILE_TEMP) | grep -v '^s\.' | grep '\.t' |/usr/bin/cut -d. -f1 > $(TABLE_IHFS_FILE) - - - -ls $IHFS_TABLE_DIR $VIEW_DIR > table_file_temp.dat - - -cat table_file_temp | grep -v '^s\.' | grep '\.t' | /usr/bin/cut -d. -f1 > -PreferredIHFSTableNames.txt - - - - -dump generated .pgc files to -/fs/hseb/ob81/ohd/whfs/src/dbmsgen/TEXT - -dump .h files to -/fs/hseb/ob81/ohd/whfs/inc/lib/dbms/ diff --git a/javaUtilities/hydro/ohd.damcrestdb/scripts/run_damcrest_cdbgen b/javaUtilities/hydro/ohd.damcrestdb/scripts/run_damcrest_cdbgen deleted file mode 100644 index e509de2b32..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/scripts/run_damcrest_cdbgen +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/ksh - -export JAVA_BIN_DIR=/usr/local/java//bin - -export DRIVERPATH=/usr/lib/postgresql-8.2-506.jdbc3.jar -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. -export DAMCRESTDB_DIR=$PROJECTS_DIR/damcrestdb -export DB_DIR=$PROJECTS_DIR/db - - -#export JAVA_VM_DIR=/fs/hseb/${DS_BUILD}/ohd/java/ohd-common/projects -#export DAMCRESTDB_DIR=$JAVA_VM_DIR/damcrestdb -#export DB_DIR=$JAVA_VM_DIR/db - -export BASEPATH=$DB_DIR/classes - -export CLASSPATH=./:$BASEPATH/:$DRIVERPATH -echo "CLASSPATH =" $CLASSPATH - -#The connection string -connecturl="jdbc:postgresql://genessee:5432/dc_ob7empty?user=pguser" - - -#The location of the PreferredTableNames.txt file. -namingfile=$DAMCRESTDB_DIR/scripts/PreferredTableNames.txt - -#The destination of the generated source files -targetdir=/fs/hseb/${DS_BUILD}/ohd/whfs_lib/src/DamCrestDBGenerated/TEXT - -#db name -dbname=dc_ob7empty - -#package name -- NONE means no packaging -# Note: this does NOT affect directly in which the generated class is placed -package=ohd.hseb.ihfsdb.generated - -db_driver_class_name=org.postgresql.Driver - -rm -f /fs/hseb/${DS_BUILD}/ohd/whfs_lib/src/DamCrestDBGenerated/TEXT/*.pgc -rm -f /fs/hseb/${DS_BUILD}/ohd/whfs_lib/src/DamCrestDBGenerated/TEXT/*.h -$JAVA_BIN_DIR/java ohd.hseb.dbgen.CDbGen $connecturl $namingfile $dbname $targetdir $db_driver_class_name - -mv $targetdir/*.h /fs/hseb/${DS_BUILD}/ohd/whfs_lib/inc/dbms/ -#cd - -return $? diff --git a/javaUtilities/hydro/ohd.damcrestdb/scripts/run_damcrest_jdbgen b/javaUtilities/hydro/ohd.damcrestdb/scripts/run_damcrest_jdbgen deleted file mode 100644 index 4ede05ddef..0000000000 --- a/javaUtilities/hydro/ohd.damcrestdb/scripts/run_damcrest_jdbgen +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/ksh - -export DRIVERPATH=/usr/lib/postgresql-8.2-506.jdbc3.jar -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. - -export DAMCRESTDB_DIR=$PROJECTS_DIR/damcrestdb -export DB_DIR=$PROJECTS_DIR/db - -export BASEPATH=$DB_DIR/classes - -export CLASSPATH=./:$BASEPATH/:$DRIVERPATH -echo "CLASSPATH =" $CLASSPATH - -#The connection string -connecturl="jdbc:postgresql://genessee:5432/dc_ob7empty?user=pguser" - -#The location of the PreferredTableNames.txt file. -namingfile=$DAMCRESTDB_DIR/scripts/PreferredTableNames.txt - -#The destination of the generated source files -targetdir=$DAMCRESTDB_DIR/src/gov/damcat/db - -#db name -dbname=dc_ob7empty - -#package name -- NONE means no packaging -# Note: this does NOT affect directly in which the generated class is placed -package=gov.damcat.db - -db_driver_class_name=org.postgresql.Driver - -$JAVADIR/bin/java ohd.hseb.dbgen.JDbGen $connecturl $namingfile $dbname $package $targetdir $db_driver_class_name - -return $? diff --git a/javaUtilities/hydro/ohd.db/.classpath b/javaUtilities/hydro/ohd.db/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.db/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.db/.project b/javaUtilities/hydro/ohd.db/.project deleted file mode 100644 index 6c9c3fe59c..0000000000 --- a/javaUtilities/hydro/ohd.db/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.db - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.db/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.db/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index a9083da262..0000000000 --- a/javaUtilities/hydro/ohd.db/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:05:31 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.db/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.db/META-INF/MANIFEST.MF deleted file mode 100644 index 5979efe248..0000000000 --- a/javaUtilities/hydro/ohd.db/META-INF/MANIFEST.MF +++ /dev/null @@ -1,8 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Db -Bundle-SymbolicName: ohd.db -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Export-Package: ohd.hseb.db, - ohd.hseb.dbgen diff --git a/javaUtilities/hydro/ohd.db/build.properties b/javaUtilities/hydro/ohd.db/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.db/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.db/build.xml b/javaUtilities/hydro/ohd.db/build.xml deleted file mode 100644 index 4c427829fd..0000000000 --- a/javaUtilities/hydro/ohd.db/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.db/ohd.db.ecl b/javaUtilities/hydro/ohd.db/ohd.db.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/Database.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/Database.java deleted file mode 100644 index b4818b8cfe..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/Database.java +++ /dev/null @@ -1,251 +0,0 @@ -package ohd.hseb.db; - -import java.sql.*; - -/** - * - *
    - * 
    - * SOFTWARE HISTORY
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------
    - * Nov 13, 2000             R. Erb     Original Creation
    - * Aug 06, 2003             C. Gobs    Class Overhaul
    - * May 13, 2011  8079       jnjanga    added method newStmtForScrollableRset()
    - * 
    - * 
    - * - * @author R. Erb - */ - -public class Database { - // ***************************************************************************** - // Private data - // ***************************************************************************** - - // the jdbc url is passed in through the connectTo method - private String _urlConnectionString = null; - - // define data types to be used to connect to the database - // and store the SQL statement - private Connection _conn = null; - - private Statement _stmt = null; - - private String _defaultDriverClassName = "org.postgresql.Driver"; - - private String _driverClassName = _defaultDriverClassName; - - // private String[] _driverNameArray = {"org.postgresql.Driver", - // "com.informix.jdbc.IfxDriver" }; - private String[] _driverNameArray = { "org.postgresql.Driver" }; - - private DbType _dbType = DbType.PostgreSQL; - - // private DbType _dbType = DbType.Informix; - - // ***************************************************************************** - // IhfsDatabase() - No argument constructor to initialize data - // ***************************************************************************** - public Database() { - - } - - // ***************************************************************************** - - public Database(String connectionString) { - connect(connectionString); - } - - // ***************************************************************************** - - public void setDriverClassName(String driverClassName) { - _driverClassName = driverClassName; - - if (_driverClassName.indexOf("informix") > 0) { - setDbType(DbType.Informix); - } else if (_driverClassName.indexOf("postgresql") > 0) { - setDbType(DbType.PostgreSQL); - } - return; - } - - // ***************************************************************************** - - public String getDriverClassName() { - return _driverClassName; - } - - // ***************************************************************************** - - public void setDbType(DbType dbType) { - _dbType = dbType; - } - - // ***************************************************************************** - - public DbType getDbType() { - return _dbType; - } - - // --------------------------------------------------------------------------------- - - private void loadDbDriver(String driverClassName) { - // Load the JDBC driver - try { - Class.forName(driverClassName); - } catch (Exception e) { - e.printStackTrace(System.err); - System.err.println("ERROR: failed to load JDBC driver named " - + driverClassName + "\n Shutting down."); - System.exit(1); - } - - } - - // --------------------------------------------------------------------------------- - - // --------------------------------------------------------------------------------- - - public void connect(String connectionString) { - _urlConnectionString = connectionString; - - loadDbDriver(getDriverClassName()); - - // Establish a connection to the database and create a statement - try { - _conn = DriverManager.getConnection(_urlConnectionString); - _stmt = _conn.createStatement(); - } catch (SQLException e) { - e.printStackTrace(); - System.err.println("ERROR: failed to connect!"); - System.err.println("ERROR: " + e.getMessage()); - // chip change - System.err.println("ERROR: error code = " + e.getErrorCode()); - System.err.println("ERROR: SQL STATE = " + e.getSQLState()); - - System.exit(1); - } - - } // end of method connectTo - - // ***************************************************************************** - - public void connectWithDriverSearch(String connectionString) { - _urlConnectionString = connectionString; - - try { - connectWithDriverAttempts(0); - } catch (SQLException e) { - e.printStackTrace(); - System.err.println("ERROR: failed to connect!"); - System.err.println("ERROR: " + e.getMessage()); - System.err.println("ERROR: error code = " + e.getErrorCode()); - System.err.println("ERROR: SQL STATE = " + e.getSQLState()); - - System.exit(1); - } - - return; - - } - - // ***************************************************************************** - - private void connectWithDriverAttempts(int attemptCount) - throws SQLException { - - try { - String driverClassName = _driverNameArray[attemptCount]; - setDriverClassName(driverClassName); - loadDbDriver(driverClassName); - - // System.out.println("attempting to load driver " + - // driverClassName); - attemptCount++; // this must occur after the use of attempCount - // above - - _conn = DriverManager.getConnection(_urlConnectionString); - _stmt = _conn.createStatement(); - } catch (SQLException e) { - if (attemptCount < _driverNameArray.length) { - connectWithDriverAttempts(attemptCount); - } else { - throw e; - } - } - - return; - } - - // ***************************************************************************** - // getConnection() - // ***************************************************************************** - public Connection getConnection() { - - return _conn; - } - - // ***************************************************************************** - // getStatement() - // ***************************************************************************** - public Statement getStatement() { - return _stmt; - } - - public Statement newStmtForScrollableRset() throws SQLException { - return getConnection().createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - } - - // ***************************************************************************** - // getDatabaseName() - // ***************************************************************************** - public String getDatabaseName() { - int lastSlashIndex = _urlConnectionString.lastIndexOf("/"); - - String dbName = "Unknown"; - - if (lastSlashIndex > -1) { - String slashSubString = _urlConnectionString - .substring(lastSlashIndex); - int colonIndex = slashSubString.indexOf(":"); - - if (colonIndex > -1) { - dbName = slashSubString.substring(1, colonIndex); - } else { - int qIndex = slashSubString.indexOf("?"); - if (qIndex > -1) { - dbName = slashSubString.substring(1, qIndex); - } - } - - } - - return dbName; - - } // end of method getDatabaseName - - // ***************************************************************************** - // disconnectFrom() - // ***************************************************************************** - public void disconnect() { - // Close the statement and connection to the database - try { - _stmt.close(); - _conn.close(); - - } catch (SQLException e) { - System.err.println("ERROR: failed to close the connection!"); - System.err.println("ERROR: " + e.getMessage()); - System.err.println("ERROR: error code = " + e.getErrorCode()); - e.printStackTrace(); - System.err.println("Shutting Down."); - System.exit(1); - } catch (NullPointerException e) { - System.err.println("ERROR: " + e.getMessage()); - e.printStackTrace(); - } - } // end of method disconnect - -} // end of class Database \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbArrayColumn.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbArrayColumn.java deleted file mode 100644 index 0e487b34e9..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbArrayColumn.java +++ /dev/null @@ -1,89 +0,0 @@ -package ohd.hseb.db; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; - -public class DbArrayColumn implements java.sql.Array -{ - - private String _arrayString = null; - private double[][] _array = null; - - public DbArrayColumn(String arrayString) - { - _arrayString = arrayString; - double[][] newArray = { {1.0, 2.0 }, {2.0, 8.0 }, {3.0, 27.0 } }; - _array = newArray; - } - - public Object getArray() throws SQLException - { - - return _array ; - - } - - public Object getArray(Map> arg0) throws SQLException - { - return _array; - } - - public Object getArray(long index, int count) throws SQLException - { - return _array[(int)index][0]; - } - - public Object getArray(long arg0, int arg1, Map> arg2) throws SQLException - { - return _array; - - } - - public int getBaseType() throws SQLException - { - - return java.sql.Types.DOUBLE; - } - - public String getBaseTypeName() throws SQLException - { - return "double[]"; - } - - public String toString() - { - return _arrayString; - } - - public ResultSet getResultSet() throws SQLException - { - // TODO Auto-generated method stub - return null; - } - - public ResultSet getResultSet(Map> arg0) throws SQLException - { - // TODO Auto-generated method stub - return null; - } - - public ResultSet getResultSet(long index, int count) throws SQLException - { - // TODO Auto-generated method stub - return null; - } - - public ResultSet getResultSet(long arg0, int arg1, Map> arg2) throws SQLException - { - // TODO Auto-generated method stub - return null; - } - - @Override - public void free() throws SQLException { - // TODO Auto-generated method stub - - } - -} diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbConnectionHelper.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbConnectionHelper.java deleted file mode 100644 index 3b65f6d3e5..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbConnectionHelper.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Created on Oct 8, 2003 - * - * - */ -package ohd.hseb.db; - - -/** - * @author Chip Gobs - * - * - */ -public class DbConnectionHelper -{ - String _baseConnectionString = null; - String _propertiesFilePath = null; - -// ------------------------------------------------------------------------ - - public DbConnectionHelper(String baseConnectionString) - { - _baseConnectionString = baseConnectionString; - } - -// ------------------------------------------------------------------------ - - public DbConnectionHelper(String baseConnectionString, String propertiesFilePath) - { - _baseConnectionString = baseConnectionString; - _propertiesFilePath = propertiesFilePath; - } -// ------------------------------------------------------------------------ - public String getConnectionString() - { - String connectionString = _baseConnectionString; - - - return connectionString; - } //end getConnectionString - - // ------------------------------------------------------------------------ -/* private String getConnectionStringByGui() - { - String connectionStringBase = _baseConnectionString; - - String connectionString = null; - - - PasswordDialog dialog = new PasswordDialog(); - - String message = "Enter your user name and password for the HP"; - boolean success = dialog.requestPasswordByDialog(message); - - String userName = dialog.getUserName(); - String password = dialog.getPassword(); - - connectionString = connectionStringBase + - "user="+ userName + - ";password=" + password +";"; - - - return connectionString; - } //end getConnectionStringByGui - - // ------------------------------------------------------------------------ - - private String getDecryptedConnectionString() - { - // - //String url ="jdbc:informix-sqli:" + "//ds1:" + - // "1530/hd_ob3ounx:" + "informixserver=ONLINE"; - - String connectionURLPart = _baseConnectionString; - String connectionString = null; - - String encryptedUserName = null; - String encryptedPassword = null; - - String userName = null; - String password = null; - - Properties props = new Properties(); - try - { - props.load(new FileInputStream(_propertiesFilePath)); - encryptedUserName = props.getProperty("un"); - encryptedPassword = props.getProperty("pw"); - - userName = Cryptor.decrypt(encryptedUserName); - password = Cryptor.decrypt(encryptedPassword); - - connectionString = connectionURLPart + - "user="+ userName + - ";password=" + password +";"; - - } - catch (FileNotFoundException e) - { - //System.err.println("You need a properties file named Data.props"); - //e.printStackTrace(); - } - catch(IOException e) - { - //e.printStackTrace(); - } - - return connectionString; - } //end getDecryptedConnectionString() -*/ - -} diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbRecord.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbRecord.java deleted file mode 100644 index 404f1d78e3..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Created on Aug 6, 2003 - * - * - */ -package ohd.hseb.db; - -import java.sql.*; - -/** - * @author Chip Gobs - * - * This class is the abstract superclass of all of the xxxRecord classes. - * xxx represents the name of the table or view. This class - * provides some utility methods and acts as a nice way of unifying all of the - * subclasses under one umbrella. - */ -public abstract class DbRecord -{ - public abstract String toString(); - - //------------------------------------------------------- - - public Timestamp copyTimestamp(Timestamp origTimestamp) - { - Timestamp newTimestamp = new Timestamp(origTimestamp.getTime()); - return newTimestamp; - } - - // ------------------------------------------------------- - - public java.sql.Date copyDate(java.sql.Date origDate) - { - java.sql.Date newDate = new java.sql.Date(origDate.getTime()); - return newDate; - } - - // ------------------------------------------------------- - - public String getStringFromTimestamp(Timestamp timestamp) - { - return DbTimeHelper.getStringFromTimestamp(timestamp); - } -// ------------------------------------------------------- - - public String getStringFromDate(java.sql.Date date) - { - - return DbTimeHelper.getStringFromDate(date); - } - //--------------------------------------------------------- - public long getLongTimeFromDateTimeString(String timeString) - { - return DbTimeHelper.getLongTimeFromDateTimeString(timeString); - } - //------------------------------------------------------- - - public String getDateTimeStringFromLongTime(long time) - { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } -//------------------------------------------------------- - - public String getDateStringFromLongTime(long time) - { - return DbTimeHelper.getDateStringFromLongTime(time); - - } - //------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbTable.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbTable.java deleted file mode 100644 index cbf5281525..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbTable.java +++ /dev/null @@ -1,716 +0,0 @@ -/* - * Created on Aug 6, 2003 - * Chip Gobs - */ -package ohd.hseb.db; - -import java.sql.*; -import java.util.*; -import java.util.Date; - -/** - * This class is the abstract super class of all generated subclasses. It - * provides some common methods that do not need to be implemented by each - * generated class - * - *
    - * 
    - * SOFTWARE HISTORY
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------------------------
    - * May 13, 2011  8079       jnjanga    added method executeQuery(Statement,String)
    - *                                     for running arbitrary SQL queries.
    - * 
    - * 
    - * - * @author Chip Gobs - */ -public abstract class DbTable { - private String _tableName; - - private Database _database; - - public abstract List select(String where) throws SQLException; - - protected DbTable(Database database) { - _database = database; - } - - protected Database getDatabase() { - return _database; - } - - protected Statement getStatement() { - return _database.getStatement(); - } - - protected Connection getConnection() { - return _database.getConnection(); - } - - protected void setDatabase(Database database) { - _database = database; - } - - public String getTableName() { - return _tableName; - } - - public void setTableName(String tableName) { - _tableName = tableName; - } - - // ***************************************************************************** - // printRecordList() - this method is called with a List of CurPrecipRecord - // objects and prints them to standard out - // ***************************************************************************** - - public void printRecordList(List recordList) { - DbRecord record = null; - - for (int ctr = 0; ctr < recordList.size(); ctr++) { - record = (DbRecord) recordList.get(ctr); - System.out.println(record.toString()); - } - - System.out.println(recordList.size() - + " record(s) returned from printRecord. "); - - } // end of printRecordList method - - // --------------------------------------------------------- - public String getStringFromDate(java.sql.Date date) { - return DbTimeHelper.getStringFromDate(date); - } - - // ------------------------------------------------------- - public long getLongTimeFromDateTimeString(String timeString) { - return DbTimeHelper.getLongTimeFromDateTimeString(timeString); - } - - // --------------------------------------------------------- - public long getLongTimeFromDateString(String timeString) { - return DbTimeHelper.getLongTimeFromDateString(timeString); - } - - // -------------------------------------------------------- - public long getLongTimeFromTimeToSecondsString(String timeString) { - return DbTimeHelper.getLongTimeFromTimeToSecondsString(timeString); - } - - // --------------------------------------------------------- - - public String getDateTimeStringFromLongTime(long time) { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } - - // --------------------------------------------------------- - public String getDateStringFromLongTime(long time) { - return DbTimeHelper.getDateStringFromLongTime(time); - } - - // --------------------------------------------------------- - - public String getStringFromTimestamp(Timestamp timestamp) { - return DbTimeHelper.getStringFromTimestamp(timestamp); - } - - // --------------------------------------------------------- - - public String getTrimmedString(String string) { - if (string != null) { - string = string.trim(); - } - - return string; - } - - // ***************************************************************************** - // getTimeStampFromString() is used to convert DateTime year to sec - // variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the - // database - // already stores it as. - // ***************************************************************************** - public Date getDateTimeFromString(String timeString) { - return DbTimeHelper.getDateTimeFromString(timeString); - } - - // ***************************************************************************** - // getDateFromString() is used to convert Date year to day variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the - // database - // already stores it as. - // ***************************************************************************** - public Date getDateFromString(String timeString) { - return DbTimeHelper.getDateFromString(timeString); - } - - // ***************************************************************************** - // selectCount returns the count of records in the database - // that meet the select criteria in the where clause. - // ***************************************************************************** - - public int selectCount(String where) throws SQLException { - int recordCount = -1; - - // Create the SQL statement and issue it - - // construct the select statment - String selectStatement = "SELECT count(*) FROM " + getTableName() + " " - + where; - - // get the result set back from the query to the database - ResultSet rs = _database.getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) { - // store the recordCount - recordCount = rs.getInt(1); - } - // Close the result set - rs.close(); - - // return a List which holds the CurPrecipRecord objects - return recordCount; - - } // end of selectCount method - - // ------------------------------------------------------------------------------------------- - - public String getString(ResultSet rs, int index) throws SQLException { - String value = getTrimmedString(rs.getString(index)); - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public long getDate(ResultSet rs, int index) throws SQLException { - long date = getNullDate(); - String stringValue = rs.getString(index); - - if (!rs.wasNull()) { - date = getLongTimeFromDateString(stringValue); - } else { - date = getNullDate(); - } - - return date; - } - - // ------------------------------------------------------------------------------------------- - - public long getTimeStamp(ResultSet rs, int index) throws SQLException { - long datetime = getNullTimeStamp(); - String value = rs.getString(index); - - if (!rs.wasNull()) { - datetime = getLongTimeFromDateTimeString(value); - } - - return datetime; - } - - // ------------------------------------------------------------------------------------------- - - public long getTime(ResultSet rs, int index) throws SQLException { - long time = getNullTime(); - String value = rs.getString(index); - - if (!rs.wasNull()) { - time = getLongTimeFromTimeToSecondsString(value); - } - - return time; - } - - // ------------------------------------------------------------------------------------------- - - public double getDouble(ResultSet rs, int index) throws SQLException { - double value = rs.getDouble(index); - - if (rs.wasNull()) { - value = getNullDouble(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public float getFloat(ResultSet rs, int index) throws SQLException { - float value = rs.getFloat(index); - - if (rs.wasNull()) { - value = getNullFloat(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public float getReal(ResultSet rs, int index) throws SQLException { - float value = rs.getFloat(index); - - if (rs.wasNull()) { - value = getNullReal(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public int getInt(ResultSet rs, int index) throws SQLException { - int value = rs.getInt(index); - - if (rs.wasNull()) { - value = getNullInt(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - public long getLong(ResultSet rs, int index) throws SQLException { - long value = rs.getLong(index); - - if (rs.wasNull()) { - value = getNullLong(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - public short getShort(ResultSet rs, int index) throws SQLException { - short value = rs.getShort(index); - - if (rs.wasNull()) { - value = getNullShort(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - - public byte[] getBytes(ResultSet rs, int index) throws SQLException { - byte[] value = rs.getBytes(index); - - if (rs.wasNull()) { - value = getNullBytes(); - } - - return value; - } - - // ------------------------------------------------------------------------------------------- - public void setDateOld(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.DATE); - } else { - statement.setString(index, getDateStringFromLongTime(value)); - } - - return; - } - - public void setDate(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.DATE); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - cal.setTimeInMillis(value); - statement.setDate(index, new java.sql.Date(value), cal); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setTimeStamp(PreparedStatement statement, int index, long value) - throws SQLException { - - // passes unit test - // setTimeStampByString(statement, index, value); - - // passes unit test - // setTimeStampByValueWithCalendar(statement, index, value); - - // passes unit test - setTimeStampByValueWithCalendarButWithoutSettingCalendarTime(statement, - index, value); - - // Bad one below fails JUnit test - - // setTimeStampByValueWithoutCalendar(statement, index, value); - } - - private void setTimeStampByString(PreparedStatement statement, int index, - long value) throws SQLException { - String header = "DbTable.setTimeStampByString(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - String dateTimeString = DbTimeHelper - .getDateTimeStringFromLongTime(value); - Timestamp timestamp = Timestamp.valueOf(dateTimeString); - - System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp); - } - - return; - } - - private void setTimeStampByValueWithoutCalendar( - PreparedStatement statement, int index, long value) - throws SQLException { - String header = "DbTable.setTimeStampByValueWithoutCalendar(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - Timestamp timestamp = new Timestamp(value); - System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp); - } - - return; - } - - private void setTimeStampByValueWithCalendar(PreparedStatement statement, - int index, long value) throws SQLException { - String header = "DbTable.setTimeStampByValueWithCalendar(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - cal.setTimeInMillis(value); - Timestamp timestamp = new Timestamp(value); - - // System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp, cal); - - } - - return; - } - - private void setTimeStampByValueWithCalendarButWithoutSettingCalendarTime( - PreparedStatement statement, int index, long value) - throws SQLException { - String header = "DbTable.setTimeStampByValueWithCalendarButWithoutSettingCalendarTime(): "; - if (isNull(value)) { - statement.setNull(index, Types.TIMESTAMP); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - Timestamp timestamp = new Timestamp(value); - - // System.out.println(header + "timestamp = " + timestamp); - statement.setTimestamp(index, timestamp, cal); - - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setTime(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.TIME); - } else { - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(tz); - - cal.setTimeInMillis(value); - - java.sql.Time time = new java.sql.Time(value); - - statement.setTime(index, time, cal); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setString(PreparedStatement statement, int index, String value) - throws SQLException { - statement.setString(index, value); - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setArray(PreparedStatement statement, int index, String value) - throws SQLException { - // statement.setString(index, value); - - DbArrayColumn arrayColumn = new DbArrayColumn(stripSingleQuotes(value)); - - statement.setArray(index, arrayColumn); - return; - } - - private String stripSingleQuotes(String origString) { - int length = origString.length(); - int indexNotToInclude = length - 1; - - String newString = origString.substring(1, indexNotToInclude); - - return newString; - } - - // ------------------------------------------------------------------------------------------- - - public void setBytes(PreparedStatement statement, int index, byte[] value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.LONGVARBINARY); - } else { - statement.setBytes(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public void setInt(PreparedStatement statement, int index, int value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.INTEGER); - } else { - statement.setInt(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - public void setLong(PreparedStatement statement, int index, long value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.BIGINT); - } else { - statement.setLong(index, value); - } - return; - } - - // ------------------------------------------------------------------------------------------- - public void setShort(PreparedStatement statement, int index, short value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.SMALLINT); - } else { - statement.setShort(index, value); - } - return; - } - - // ------------------------------------------------------------------------------------------- - public void setDouble(PreparedStatement statement, int index, double value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.DOUBLE); - } else { - statement.setDouble(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - public void setFloat(PreparedStatement statement, int index, float value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.FLOAT); - } else { - statement.setFloat(index, value); - } - - return; - } - - // ------------------------------------------------------------------------------------------- - public void setReal(PreparedStatement statement, int index, float value) - throws SQLException { - if (isNull(value)) { - statement.setNull(index, Types.REAL); - } else { - statement.setFloat(index, value); // intentionally set to setFloat, - // since setReal does not exist - } - - return; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(String value) { - boolean result = false; - - if (value == null) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(byte[] value) { - boolean result = false; - - if (value == null) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - public static boolean isNull(long value) { - boolean result = false; - - if (value == getNullLong()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - public static boolean isNull(int value) { - boolean result = false; - - if (value == getNullInt()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(short value) { - boolean result = false; - - if (value == getNullShort()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(double value) { - boolean result = false; - - if (value == getNullDouble()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - public static boolean isNull(float value) { - boolean result = false; - - if (value == getNullFloat()) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------------- - - public static int getNullInt() { - return Integer.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static long getNullLong() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - public static short getNullShort() { - return Short.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static float getNullFloat() { - return -Float.MAX_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static float getNullReal() { - return -Float.MAX_VALUE; // real maps to float - } - - // ------------------------------------------------------------------------------------------- - - public static double getNullDouble() { - return -Double.MAX_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static String getNullString() { - return null; - } - - // ------------------------------------------------------------------------------------------- - - public static long getNullDate() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - public static long getNullTimeStamp() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - - public static long getNullTime() { - return Long.MIN_VALUE; - } - - // ------------------------------------------------------------------------------------------- - public static byte[] getNullBytes() { - return null; - - } - - public ResultSet executeQuery(Statement stmt, String sql) - throws SQLException { - return stmt.executeQuery(sql); - } - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbTimeHelper.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbTimeHelper.java deleted file mode 100644 index 3f58bfe6f3..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbTimeHelper.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Created on Sep 16, 2003 - * - * - */ -package ohd.hseb.db; - -import java.util.*; -import java.util.Date; -import java.text.*; -import java.sql.*; - -/** - * @author GobsC - * - * - */ -public class DbTimeHelper -{ -// --------------------------------------------------------- - - public static String getStringFromDate(java.sql.Date date) - { - String dateString = null; - - if (date != null) - { - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - - dateString = utcSdf2.format(date); - } - return dateString; - } -// --------------------------------------------------------- - - // ***************************************************************************** - // getTimeStampFromString() is used to convert DateTime year to sec variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getDateTimeFromString(String timeString) - { - Date shiftedDate = null; - - if (timeString != null) - { - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedDate = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - } - - return shiftedDate; - } - - // ***************************************************************************** - // getTimeFromString() is used to convert DateTime year to sec variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getTimeToSecondsFromString(String timeString) - { - Date shiftedTime = null; - - if (timeString != null) - { - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedTime = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - } - - return shiftedTime; - } - - // ***************************************************************************** - - // ***************************************************************************** - // getTimeStampFromString() is used to convert DateTime year to sec variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getDateTimeToMinutesFromString(String timeString) - { - Date shiftedDate = null; - - if (timeString != null) - { - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedDate = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - } - - return shiftedDate; - } - - // getDateFromString() is used to convert Date year to day variables - // It is typically called from a concrete generated class to - // get the time in the database in UTC - which is to say, the time the database - // already stores it as. - // ***************************************************************************** - public static Date getDateFromString(String timeString) - { - Date shiftedDate = null; - - if (timeString == null) - return shiftedDate; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - try - { - shiftedDate = new Date(utcSdf2.parse(timeString).getTime()); - } - catch(ParseException e) - { - e.printStackTrace(); - } - - return shiftedDate; - } -// ------------------------------------------------------- - public static long getLongTimeFromDateTimeString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getDateTimeFromString(timeString); - - time = date.getTime(); - } - return time; - } -// ------------------------------------------------------- - public static long getLongTimeFromDateTimeToMinutesString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getDateTimeToMinutesFromString(timeString); - - time = date.getTime(); - } - return time; - } - -// ------------------------------------------------------- - - public static long getLongTimeFromDateString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getDateFromString(timeString); - - time = date.getTime(); - } - return time; - } - -// ------------------------------------------------------- - - public static long getLongTimeFromTimeToSecondsString(String timeString) - { - long time = 0; - if (timeString != null) - { - Date date = getTimeToSecondsFromString(timeString); - - time = date.getTime(); - } - return time; - } -// ------------------------------------------------------- - -// ------------------------------------------------------- - public static String getStringFromTimestamp(Timestamp timestamp) - { - String timeString = null; - - if (timestamp != null) - { - SimpleDateFormat utcSdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(timestamp); - } - - //System.out.println("timeString = !" + timeString + "!"); - - return timeString; - } -// ------------------------------------------------------- - public static String getTimeToSecondsStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "HH:mm:ss"); - - return timeString; - } - //------------------------------------------------------- - - public static String getDateTimeStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy-MM-dd HH:mm:ss"); - - return timeString; - } - - //------------------------------------------------------- - - public static String getDateTimeToMinutesStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy-MM-dd HH:mm"); - - return timeString; - } - - // ------------------------------------------------------- - - - - public static String getDateStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy-MM-dd"); - - return timeString; - } - - //------------------------------------------------------- - - public static String getStringFromLongTime(long time, String dateFormat) - { - String timeString = null; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat(dateFormat); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(new java.util.Date(time)); - - return timeString; - } - - - - -// ------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbType.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbType.java deleted file mode 100644 index 1091d41132..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/db/DbType.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Created on Sep 17, 2004 - * - * - */ -package ohd.hseb.db; - -/** - * @author GobsC - * - * - */ -public class DbType -{ - public static final DbType Informix = new DbType("Informix"); - public static final DbType PostgreSQL = new DbType("PostgreSQL"); - - private static final DbType[] DBTypeArray = { Informix, PostgreSQL }; - - private String _name = null; - // ----------------------------------------------------------------------- - private DbType(String name) - { - _name = name; - - return; - - } - -// ----------------------------------------------------------------------- - public boolean equals(Object object) - { - boolean result = false; - - DbType type = (DbType) object; - - if (this._name.equals(type._name)) - { - result = true; - } - - return result; - } - -// ----------------------------------------------------------------------- - - public String toString() - { - return _name; - } -// ----------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/CDbGen.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/CDbGen.java deleted file mode 100644 index 8f11822e79..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/CDbGen.java +++ /dev/null @@ -1,2553 +0,0 @@ -// -// // File: CDbGen.java -//Orig Author: Chip Gobs 10/6/04 -//Spawned from JDbGen - -//This is a rewrite of dbgen in Java. It generates -//PostgreSQL-compatible esqlc code. - -package ohd.hseb.dbgen; - -//import ohd.hseb.util.*; - -import java.util.*; // needed for List and Map classes and others -import java.util.Date; // needed for Date class, resolves ambiguity with - // java.sql.Date -import java.io.*; // needed for file I/O -import java.sql.*; - -import ohd.hseb.db.Database; - - -public class CDbGen -{ - private static final boolean _usingNewDateCode = true; - private static final boolean _usingNewDateAndTimeCode = false; - private static final boolean _usingIndicators = true; - - - // --------------------------------------------------------------- - // private data - //--------------------------------------------------------------- - - private Map _cDataTypeIntegerMap = null; //maps from sqlType integer to cDataType String - private Map _sqlTypeToNullTypeMap = null; - private Map _keywordMap = null; - - private String _targetDirName = null; - - private DataOutputStream _dos = null; - - private List _tableDescriptorList = null; - - - private CodeIndenter _indenter = null; - - private final String _indentString = " "; - - private static final String _sectionSeparator = - "\n/* ------------------------------------------------------------------------- */\n"; - - - // ----------------------------------------------------------------------- - public CDbGen() - { - initCDataTypeIntegerMap(); - initSqlTypeToNullTypeMap(); - initKeywordMap(); - - } - // ------------------------------------------------------------------------------------- - private void initKeywordMap() - { - _keywordMap = new HashMap(); - - _keywordMap.put("value", "\\\"value\\\""); - _keywordMap.put("reference", "\\\"reference\\\""); - } - - // ------------------------------------------------------------------------------------- - - private void addCDataTypeIntegerMapEntry(int sqlType, String cType) - { - _cDataTypeIntegerMap.put(new Integer(sqlType), cType); - } - - // ------------------------------------------------------------------------------------- - private void initCDataTypeIntegerMap() - { - - _cDataTypeIntegerMap = new HashMap(); - - //special code handles the difference between internal and external structures - //for the DATE type, see getCDataTypeByInt() - addCDataTypeIntegerMapEntry(Types.DATE, "date"); - - - if (_usingNewDateAndTimeCode) - { - addCDataTypeIntegerMapEntry(Types.TIMESTAMP, "time_t"); - } - else - { - addCDataTypeIntegerMapEntry(Types.TIMESTAMP, "dtime_t"); - } - addCDataTypeIntegerMapEntry(Types.REAL, "float"); - addCDataTypeIntegerMapEntry(Types.FLOAT, "double"); - addCDataTypeIntegerMapEntry(Types.DOUBLE, "double"); - addCDataTypeIntegerMapEntry(Types.SMALLINT, "short"); - addCDataTypeIntegerMapEntry(Types.INTEGER, "long"); - addCDataTypeIntegerMapEntry(Types.BIGINT, "long"); - addCDataTypeIntegerMapEntry(Types.LONGVARBINARY, "char *"); - addCDataTypeIntegerMapEntry(Types.LONGVARCHAR, "char *"); // ? instead of byte[] - addCDataTypeIntegerMapEntry(Types.VARCHAR, "char"); - addCDataTypeIntegerMapEntry(Types.CHAR, "char"); - - - } - // ------------------------------------------------------------------------------------- - private String wrapInQuotesIfNeeded(String colName, boolean needsEscapes) - { - String newColName = colName; - - String value = (String) _keywordMap.get(colName); - - if (value != null) - { - if (needsEscapes) - { - newColName = "\\\"" + colName + "\\\""; - } - else - { - newColName = "\"" + colName + "\""; - } - } - - return newColName; - } - - // ------------------------------------------------------------------------------------- - - private String getCDataTypeByInt(int sqlType, boolean isPublicType) - { - String cDataType = null; - - cDataType = (String) _cDataTypeIntegerMap.get(new Integer(sqlType)); - - //one of few cases in which the public type differs from the internal type - if (_usingNewDateCode) - { - if ( (sqlType == Types.DATE) && (isPublicType) ) - { - cDataType = "date_t"; - } - } - - if (cDataType == null) - { - cDataType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return cDataType; - } - - // ------------------------------------------------------------------------------------- - - private void addSqlTypeToNullTypeMapEntry(int sqlType, String cType) - { - _sqlTypeToNullTypeMap.put(new Integer(sqlType), cType); - } - - // ------------------------------------------------------------------------------------- - private void initSqlTypeToNullTypeMap() - { - _sqlTypeToNullTypeMap = new HashMap(); - - addSqlTypeToNullTypeMapEntry(Types.CHAR, "CHAR"); - addSqlTypeToNullTypeMapEntry(Types.FLOAT, "FLOAT"); - addSqlTypeToNullTypeMapEntry(Types.REAL, "FLOAT"); - addSqlTypeToNullTypeMapEntry(Types.SMALLINT, "SHORT"); - addSqlTypeToNullTypeMapEntry(Types.INTEGER, "INT"); - addSqlTypeToNullTypeMapEntry(Types.BIGINT, "LONG"); - addSqlTypeToNullTypeMapEntry(Types.DOUBLE , "DOUBLE"); - addSqlTypeToNullTypeMapEntry(Types.DATE, "INT"); //not DATE because our public struct is a long - addSqlTypeToNullTypeMapEntry(Types.TIMESTAMP, "DATETIME"); - addSqlTypeToNullTypeMapEntry(Types.VARCHAR, "CHAR"); - addSqlTypeToNullTypeMapEntry(Types.LONGVARCHAR, "CHAR"); - } - - //------------------------------------------------------------------------------------- - - private String getNullTypeByInt(int sqlType) - { - String nullType = null; - - nullType = (String) _sqlTypeToNullTypeMap.get(new Integer(sqlType)); - - - if (nullType == null) - { - nullType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return nullType; - } - - // --------------------------------------------------------------------------------- - - private void write(String line, boolean useIndentation) throws IOException - { - //--------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - - if (useIndentation) - { - String totalIndentString = _indenter.getTotalIndentString(); - - _dos.writeBytes(totalIndentString + line); - } - else - { - _dos.writeBytes(line); - } - } - - // ----------------------------------------------------------------- - private void write(String line) throws IOException - { -// --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - write(line, false); //by default, do not use indentation - - return; - } - - // ----------------------------------------------------------------- - - private void writeLine(String line) throws IOException - { -// --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - boolean useIndentation = true; - write(line + "\n", useIndentation); - - return; - } - - // ----------------------------------------------------------------- - - private void writeNewLine() throws IOException - { -// --------------------------------------------------------------- - // write and writeLine are used to write out nicely indented code - //--------------------------------------------------------------- - boolean useIndentation = false; - write("\n", useIndentation); - - return; - } - // ----------------------------------------------------------------- - - private void logError(IOException e) - { - System.err.println("Error trying to write to "); - e.printStackTrace(); - - return; - } - - - // -------------------------------------------------------------------------- - // read the list of preferred table names from a text file with the - // preferred name of the Tables and Views , 1 per line, no spaces in the - // name - // -------------------------------------------------------------------------- - private Map getMapOfPreferredTableNames(String filePath) - { - Map tableNameMap = new HashMap(); - - try - { - - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - String line = null; - - line = reader.readLine(); - - while (line != null) - { - // System.out.println("line = " + line + ":"); - - String preferredTableName = line.trim(); - String lowercaseTableName = preferredTableName.toLowerCase(); - - tableNameMap.put(lowercaseTableName, preferredTableName); - - System.out.println("CDbGen.getMapOfPreferredTableNames(): " - + lowercaseTableName + " -> " + preferredTableName); - - line = reader.readLine(); - } //end while - - reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - - return tableNameMap; - } - - // ----------------------------------------------------------------- - private void buildHeaderSrcFiles(String dbName) - { - try - { - // Strings to hold Table name and File name - String tableName = new String(); - String fileName = new String(); - - // loop through all the table names and build source files - for (int ctr = 0; ctr < _tableDescriptorList.size(); ctr++) - { - TableDescriptor tableDesc = (TableDescriptor) _tableDescriptorList - .get(ctr); - tableName = tableDesc.getName(); - - fileName = tableName + ".h"; - - System.out.println("building source code for " + fileName); - - - FileOutputStream fos = new FileOutputStream(_targetDirName - + "/" + fileName); - _dos = new DataOutputStream(fos); - - createHeaderFile(tableName, fileName, dbName, tableDesc); - - if ((!tableDesc.isView()) && (tableDesc.hasPrimaryKey())) - { - // createRecordGetWhereString(tableDesc); - } - - _indenter.setLevel(0); - - _dos.close(); - } - } - catch (IOException e) - { - logError(e); - } - - } // end of buildRecordSrcFiles method - - - //----------------------------------------------------------------- - private void createHeaderFile(String tableName, String fileName, - String dbName, TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - if (tableDesc.isView()) - { - writeLine("// This is a view record !"); - } - - writeLine("/*"); - _indenter.incLevel(); - writeLine("File: " + fileName); - writeLine("Author : CDBGEN"); - writeLine("Created : " + currentTime + " using database " + dbName); - writeLine("Description: This header file is associated with its .pgc file "); - _indenter.incLevel(2); - writeLine("and defines functions and the table's record structure."); - _indenter.decLevel(2); - _indenter.decLevel(); - writeLine("*/"); - - - writeLine("#ifndef " + tableName + "_h"); - writeLine("#define " + tableName + "_h"); - write("\n\n"); - - - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include \"DbmsAccess.h\""); - writeLine("#include \"DbmsUtils.h\""); - writeLine("#include \"List.h\""); - writeLine("#include \"GeneralUtil.h\""); - writeLine("#include \"dbmserrs.h\""); - writeLine("#include \"datetime.h\""); - writeLine("#include \"time_convert.h\""); - - writeNewLine(); - - - write("\n\n"); - - writeLine("typedef struct _" + tableName); - writeLine("{"); - _indenter.incLevel(); - - writeLine("Node\t\tnode;"); - - createStructureContents(tableName, tableDesc, true); - - writeLine("List\t\tlist;"); - _indenter.decLevel(); - writeLine("} " + tableName + ";"); - - - writeLine("/*"); - _indenter.incLevel(); - writeLine("Function Prototypes"); - _indenter.decLevel(); - writeLine("*/"); - - _indenter.incLevel(); - writeLine(tableName + "* Get" + tableName + "(const char * where);"); - writeLine(tableName + "* Select" + tableName + "(const char * where);"); - writeLine("int Select" + tableName + "Count(const char * where);"); - - if (!tableDesc.isView()) - { - writeLine("int Put" + tableName + "(const " + tableName - + " * structPtr);"); - writeLine("int Insert" + tableName + "(const " + tableName - + " * structPtr);"); - - writeLine("int Update" + tableName + "(const " + tableName + - "* structPtr, const char *where);"); - writeLine("int Delete" + tableName + "(const char *where);"); - - - if (tableDesc.hasPrimaryKey()) - { - writeLine("int Update" + tableName + "ByRecord (const " + tableName + - " * newStructPtr, const " + tableName + " * oldStructPtr);"); - - writeLine("int InsertOrUpdate" + tableName + "(const " + tableName + " * structPtr);"); - - writeLine("int InsertIfUnique" + tableName + "(const " + tableName + " * structPtr, bool *isUnique);"); - writeLine("bool " + tableName +"Exists(const " + tableName + " * structPtr);"); - - writeLine("int Delete" + tableName + "ByRecord(const " + tableName + " * structPtr);"); - - writeLine("void Get" + tableName + "PrimaryKeyWhereString " + - "(const " + tableName + " * structPtr, char returnWhereString[] );"); - - } - } - writeLine("void Free" + tableName + "(" + tableName - + " * structPtr);"); - - writeLine("DbStatus * Get" + tableName + "DbStatus();"); - writeLine("void Set" + tableName +"ErrorLogging(int value);"); - - - _indenter.decLevel(); - writeLine("#endif"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createRecordFileBanner method - - //---------------------------------------------------------------------------------------- - - private void buildEsqlCSourceFiles(String dbName) - { - try - { - // Strings to hold Table name and File name - String tableName = new String(); - String fileName = new String(); - String cursorName = "tcur"; - - // loop through all the table names and build source files - for (int ctr = 0; ctr < _tableDescriptorList.size(); ctr++) - { - TableDescriptor tableDesc = - (TableDescriptor) _tableDescriptorList.get(ctr); - - tableName = tableDesc.getName(); - - fileName = tableName + ".pgc"; - - System.out.println("building source code for " + fileName); - - FileOutputStream fos = - new FileOutputStream(_targetDirName + "/" + fileName); - _dos = new DataOutputStream(fos); - - createEsqlCCommentSection(tableName, fileName, dbName,tableDesc); - createEsqlCIncludeSection(tableName, fileName, dbName); - createStructSection(tableName, tableDesc); - - createMiscDeclarations(tableName); - writeLine(_sectionSeparator); - - - createSelectFunction("Get", tableName, tableDesc, cursorName+"1"); - writeLine(_sectionSeparator); - - createSelectFunction("Select", tableName, tableDesc, cursorName+"2"); - writeLine(_sectionSeparator); - - createSelectCountFunction("Select", tableName, tableDesc, cursorName+"3"); - writeLine(_sectionSeparator); - - if (!tableDesc.isView()) - { - createInsertFunction("Put", tableName, tableDesc); - writeLine(_sectionSeparator); - - createInsertFunction("Insert", tableName, tableDesc); - writeLine(_sectionSeparator); - - createUpdateFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createDeleteFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - - if (tableDesc.hasPrimaryKey()) - { - createUpdateByRecordFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createInsertOrUpdateFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createInsertIfUniqueFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createDeleteByRecordFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createExistsFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createGetPrimaryWhereString(tableName, tableDesc); - writeLine(_sectionSeparator); - } - - } - - - - createFreeFunction(tableName, tableDesc); - writeLine(_sectionSeparator); - - createGetDbStatusFunction(tableName); - writeLine(_sectionSeparator); - - createSetErrorLogging(tableName); - writeLine(_sectionSeparator); - - _indenter.setLevel(0); - - _dos.close(); - } - } - catch (IOException e) - { - logError(e); - - } - - } // end of buildRecordSrcFiles method - //------------------------------------------------------------------------------------ - - private void createEsqlCCommentSection(String tableName, String fileName, - String dbName, - TableDescriptor tableDesc) - { - - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - if (tableDesc.isView()) - { - writeLine("/* This is a view record ! */"); - } - - writeLine("/*"); - _indenter.incLevel(); - writeLine("File: " + fileName); - writeLine("Author : CDBGEN"); - writeLine("Created : " + currentTime + " using database " + dbName); - writeLine("Description: This .pgc file has an associated header file. "); - _indenter.incLevel(2); - writeLine("and defines all functions and the table's INTERNAL record structure."); - _indenter.decLevel(2); - _indenter.decLevel(); - writeLine("*/"); - writeNewLine(); - } - catch (java.io.IOException e) - { - logError(e); - } - - } - - //---------------------------------------------------------------------------------------- - - private void createEsqlCIncludeSection(String tableName, String fileName, - String dbName) - { - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - writeLine("#include \"" + tableName + ".h\""); - - /* - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include "); - writeLine("#include \"DbmsAccess.h\""); - writeLine("#include \"dbmserrs.h\""); - writeLine("#include \"List.h\""); - */ - writeNewLine(); - writeLine("EXEC SQL include sqlda;"); - writeLine("EXEC SQL include sqltypes;"); - writeLine("EXEC SQL include sql3types;"); - writeLine("EXEC SQL include pgtypes_timestamp;"); - writeLine("EXEC SQL include pgtypes_date;"); - writeLine("EXEC SQL include pgtypes_interval;"); - writeLine("EXEC SQL include pgtypes_numeric;"); - writeNewLine(); - - } - catch (java.io.IOException e) - { - logError(e); - } - - - } - - //--------------------------------------------------------------------------------------- - private void createStructSection(String tableName, TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeLine("struct " + tableName + "_t"); - writeLine("{"); - _indenter.incLevel(); - createStructureContents(tableName, tableDesc, false); - _indenter.decLevel(); - writeLine("} " + tableName + "_rec;"); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - } - catch (java.io.IOException e) - { - logError(e); - } - } - //---------------------------------------------------------------------------------------- - - - private void createMiscDeclarations(String tableName) - { - try - { - _indenter.setLevel(0); - - writeLine("#define QUERY_LEN 9999"); - writeLine("static int errorLoggingOn = 1;"); - writeNewLine(); - writeLine("static DbStatus dbStatus;"); - writeNewLine(); - - } - catch (java.io.IOException e) - { - logError(e); - } - } -// ---------------------------------------------------------------------------------------- - - - private void createSetErrorLogging(String tableName) - { - - try - { - _indenter.setLevel(0); - - writeLine("void Set" + tableName +"ErrorLogging(int value)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("errorLoggingOn = value;"); - writeLine("return;"); - - _indenter.decLevel(); - writeLine("}"); - - - writeNewLine(); - - } - catch (java.io.IOException e) - { - logError(e); - } - } -//---------------------------------------------------------------------------------------- - - private void createStructureContents(String tableName, - TableDescriptor tableDesc, - boolean isPublicStructure) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - - String columnName = colDesc.getName(); - int sqlTypeInt = colDesc.getSqlTypeInt(); - String cType = getCDataTypeByInt(sqlTypeInt, isPublicStructure); - - String firstChar = String.valueOf(columnName.charAt(0)); - // String newName = firstChar.toUpperCase() - // + columnName.substring(1); - - - - if ((sqlTypeInt == Types.CHAR) || (sqlTypeInt == Types.VARCHAR) ) - { - int size = colDesc.getSize() + 1; - writeLine(cType + "\t\t" + columnName + "[" + size + "];"); - } - else - //non-character type - { - writeLine(cType + "\t\t" + columnName + ";"); - } - } //end for each column - - - if ((_usingIndicators) && (! isPublicStructure) ) // declare indicator variables - { - writeNewLine(); - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.isNullable()) - { - String columnName = colDesc.getName(); - writeLine("int" +"\t\t" + getIndicatorColumnName(columnName) +";"); - } - - } //end for each column - - } - } - catch (IOException e) - { - logError(e); - } - - } // end of createRecordCopyConstructor method - //------------------------------------------------------------------------------------------- - private String getIndicatorColumnName(String columnName) - { - return "ind_" + columnName; - } - //------------------------------------------------------------------------------------------- - private void createSelectFunction(String functionPrefix, - String tableName, - TableDescriptor tableDesc, - String cursorName) - { - - try - { - _indenter.setLevel(0); - writeLine(tableName + " * " + functionPrefix + tableName + "(const char * where)"); - writeLine("{"); - _indenter.incLevel(); - - writeNewLine(); - writeLine(tableName + " * listPtr = NULL;"); - writeLine(tableName + " * structPtr = NULL;"); - writeLine("char selectStatement[] = \"SELECT * FROM " + tableName + " \";"); - writeNewLine(); - - writeLine("int rowCount = 0;"); - writeLine("int first = 1;"); - writeNewLine(); - - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("struct " + tableName + "_t dbs;"); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, SELECT);"); - writeNewLine(); - - writeLine("strcpy(queryBuffer, selectStatement);"); - writeNewLine(); - - writeLine("if ( ( where != NULL ) && ( * where != '\\0' ) ) "); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("strcat(queryBuffer, where);"); - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("EXEC SQL PREPARE tid FROM :queryBuffer;"); - createErrorChecking(tableName, functionPrefix, "Prepare section", "return (NULL);"); - writeNewLine(); - - writeLine("EXEC SQL DECLARE " + cursorName + " CURSOR WITH HOLD FOR tid;"); - createErrorChecking(tableName, functionPrefix, "Declare cursor section", "return (NULL);"); - writeNewLine(); - - writeLine("EXEC SQL OPEN " + cursorName + ";"); - createErrorChecking(tableName, functionPrefix, "Open cursor section", "return (NULL);"); - writeNewLine(); - - writeLine("listPtr = NULL;"); - writeLine("memset(&dbs, '\\0', sizeof(dbs));"); - writeNewLine(); - - if (_usingIndicators) - { - createFetch(tableDesc, cursorName); - } - else - { - writeLine("EXEC SQL FETCH " + cursorName + " INTO :dbs;"); - } - createErrorChecking(tableName, functionPrefix, "Initial FETCH section", "return (NULL);"); - writeNewLine(); - - writeLine("while (SQLCODE == 0) "); - writeLine("{"); - _indenter.incLevel(); - - writeLine("rowCount++;"); - - writeLine("if ((structPtr = (" + tableName + " *) malloc(sizeof(" + tableName +"))) != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeNewLine(); - createCopyDbStructToCStruct(tableName, tableDesc); - writeNewLine(); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - writeLine("break;"); - _indenter.decLevel(); - writeLine("}"); - - writeNewLine(); - - writeLine("if (first)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("listPtr = structPtr;"); - writeLine("ListInit(&listPtr->list);"); - writeLine("first = 0;"); - - - _indenter.decLevel(); - writeLine("}"); //end of if (first) - writeNewLine(); - - writeLine("ListAdd(&listPtr->list, &structPtr->node);"); - writeLine("memset(&dbs, '\\0', sizeof(dbs));"); - writeNewLine(); - - if (_usingIndicators) - { - createFetch(tableDesc, cursorName); - } - else - { - writeLine("EXEC SQL FETCH " + cursorName + " INTO :dbs;"); - } - createErrorChecking(tableName, functionPrefix, "Nth fetch section", "return (NULL);"); - - - _indenter.decLevel(); - writeLine("}"); //end of while loop - writeNewLine(); - - - writeLine("initDbStatus(&dbStatus);"); - writeLine("setDbStatusRowsAffected(&dbStatus, rowCount);"); - writeNewLine(); - - writeLine("EXEC SQL CLOSE " + cursorName + ";"); - writeLine("return(listPtr);"); - - _indenter.decLevel(); - writeLine("}"); //end of SelectXXX or GetXXX - - } - catch (IOException e) - { - logError(e); - } - - } // end of createSelectFunction() - - // ---------------------------------------------------------------------------------- - private void createSelectCountFunction(String functionPrefix, - String tableName, - TableDescriptor tableDesc, - String cursorName) - { - - try - { - String functionName = functionPrefix + "Count"; - - _indenter.setLevel(0); - writeLine("int " + functionPrefix + tableName + "Count(const char * where)"); - writeLine("{"); - _indenter.incLevel(); - - writeNewLine(); - writeLine("char selectStatement[] = \"SELECT COUNT(*) FROM " + tableName + " \";"); - writeNewLine(); - - - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("int rowCount = 0;"); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, SELECT);"); - writeNewLine(); - - writeLine("strcpy(queryBuffer, selectStatement);"); - writeNewLine(); - - writeLine("if ( ( where != NULL ) && ( * where != '\\0' ) ) "); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("strcat(queryBuffer, where);"); - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("EXEC SQL PREPARE tid FROM :queryBuffer;"); - createErrorChecking(tableName, functionName, "Prepare section", "return (-1);"); - writeNewLine(); - - writeLine("EXEC SQL DECLARE " + cursorName + " CURSOR WITH HOLD FOR tid;"); - createErrorChecking(tableName, functionName, "Declare cursor section", "return (-1);"); - writeNewLine(); - - writeLine("EXEC SQL OPEN " + cursorName + ";"); - createErrorChecking(tableName, functionName, "Open cursor section", "return (-1);"); - writeNewLine(); - - - writeNewLine(); - - writeLine("EXEC SQL FETCH " + cursorName + " INTO :rowCount;"); - - createErrorChecking(tableName, functionName, "Initial FETCH section", "return (-1);"); - writeNewLine(); - - writeLine("initDbStatus(&dbStatus);"); - writeLine("setDbStatusRowsAffected(&dbStatus, rowCount);"); - writeNewLine(); - - writeLine("EXEC SQL CLOSE " + cursorName + ";"); - writeLine("return(rowCount);"); - - _indenter.decLevel(); - writeLine("}"); //end of SelectXXXCount or GetXXXCount - - } - catch (IOException e) - { - logError(e); - } - - } // end of createSelectCountFunction() - - // -------------------------------------------------------------------------------------- - private void createInsertOrUpdateFunction(String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("int InsertOrUpdate" + tableName + "(const " + tableName + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - - writeLine("Update"+ tableName + "ByRecord(structPtr, structPtr);"); - writeLine("setDbStatusSqlCommand(&dbStatus, UPDATE);"); - - writeNewLine(); - - writeLine("if ( (SQLCODE < 0) || (SQLCODE == 100) )"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("Insert" + tableName + "(structPtr);"); - writeLine("setDbStatusSqlCommand(&dbStatus, INSERT);"); - - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("initDbStatus(&dbStatus);"); - - writeLine("return(SQLCODE);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertOrUpdateFunction method - - // ---------------------------------------------------------------------------------- - private void createExistsFunction(String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("bool " + tableName +"Exists(const " + tableName + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("int result = false;"); - writeLine("int rowCount = 0;"); - - writeLine("char whereString[QUERY_LEN];"); - writeNewLine(); - - writeLine("Get" + tableName + "PrimaryKeyWhereString(structPtr, whereString);"); - writeLine("rowCount = Select" + tableName + "Count(whereString);"); - writeNewLine(); - - writeLine("if (rowCount > 0)"); - writeLine("{"); - _indenter.incLevel(); - writeLine("result = true;"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - writeLine("result = false;"); - _indenter.decLevel(); - writeLine("}"); - - writeNewLine(); - writeLine("return(result);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertIfUniqueFunction method - - // ---------------------------------------------------------------------------------- - private void createInsertIfUniqueFunction(String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("int InsertIfUnique" + tableName + "(const " + tableName + " * structPtr, bool *isUnique)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("int resultCode = 0;"); - - writeLine("if (" + tableName + "Exists(structPtr))"); - writeLine("{"); - _indenter.incLevel(); - writeLine("setDbStatusSqlCommand(&dbStatus, SELECT);"); - writeLine("*isUnique = false;"); - writeLine("resultCode = dbStatus.sql_code;"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("resultCode = dbStatus.sql_code;"); - - writeLine("if (resultCode == 0)"); - writeLine("{"); - _indenter.incLevel(); - writeLine("Insert" + tableName + "(structPtr);"); - writeLine("setDbStatusSqlCommand(&dbStatus, INSERT);"); - writeLine("*isUnique = true;"); - writeLine("resultCode = dbStatus.sql_code;"); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - writeLine("*isUnique = false;"); - _indenter.decLevel(); - writeLine("}"); - - - _indenter.decLevel(); - writeLine("}"); - - writeLine("initDbStatus(&dbStatus);"); - writeNewLine(); - writeLine("return(resultCode);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertIfUniqueFunction method - - // ---------------------------------------------------------------------------------- - private void createInsertFunction(String functionPrefix, - String tableName, - TableDescriptor tableDesc) - { - int dbColumnsPerLine = 3; - - try - { - _indenter.setLevel(0); - writeLine("int " + functionPrefix + tableName + "(const " + tableName + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("struct " + tableName + "_t dbs;"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, INSERT);"); - writeNewLine(); - - writeLine("if (structPtr == NULL)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("return(ERR_BAD_ARGS);"); - - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - - writeLine("memset(&dbs, '\\0', sizeof(dbs));"); - writeNewLine(); - - createCopyCStructToDbStruct(tableName, tableDesc); - writeNewLine(); - - - if (_usingIndicators) - { - createInsertStatement(tableDesc, dbColumnsPerLine); - } - else - { - writeLine("EXEC SQL INSERT INTO " + tableName + " VALUES " + "(:dbs);"); - } - - createFreeTextColumnDbsStructFragment(tableName, tableDesc); - - createErrorChecking(tableName, functionPrefix, "Insert section","return (SQLCODE);"); - writeNewLine(); - - //writeLine("EXEC SQL COMMIT WORK;"); - - writeLine("initDbStatus(&dbStatus);"); - - writeLine("return(ERR_OK);"); - - _indenter.decLevel(); - writeLine("}"); - - } - catch (IOException e) - { - logError(e); - } - - } // end of createInsertFunction method - - - // ---------------------------------------------------------------------------------- - private void createUpdateFunction(String tableName, - TableDescriptor tableDesc) - { - - _indenter.setLevel(0); - final int dbColumnsPerLine = 5; - - try - { - writeLine("int Update" + tableName + "(const " + tableName + " *structPtr, const char *where)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("struct " + tableName + "_t dbs;"); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("setDbStatusSqlCommand(&dbStatus, UPDATE);"); - writeNewLine(); - - createCopyCStructToDbStruct(tableName, tableDesc); - writeNewLine(); - - writeLine("sprintf(queryBuffer, \" UPDATE " + tableName + " SET \" );"); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - int columnCount = columnDescriptorList.size(); - - //write out the query with ? in it - write("strcat(queryBuffer, \"", true); - - //for each column, put in colName = ?, - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String colName = colDesc.getName(); - - colName = wrapInQuotesIfNeeded(colName, true); - - write(colName + " = ? "); - - if (i < columnCount -1) - { - write(", "); - - // only put a number of columns on a line at a time - // so go to a newline and indent - if ((i+1) % dbColumnsPerLine == 0) - { - writeLine("\");"); - write("strcat(queryBuffer, \"", true); - } - } - } - write("\");"); //close the strcat statement - write("\n"); - writeNewLine(); - - //append the where clause to the query - writeLine("if ( (where != NULL) && (*where != '\\0'))"); - writeLine("{"); - _indenter.incLevel(); - writeLine("strcat(queryBuffer, where);"); - _indenter.decLevel(); - writeLine("}"); - writeNewLine(); - - writeLine("EXEC SQL PREPARE uid FROM :queryBuffer;"); - createErrorChecking(tableName, "Update", "Prepare section", "return(SQLCODE);"); - writeNewLine(); - - //create the execute statement - -// write out the execute statement - createExecuteUsing(tableDesc, dbColumnsPerLine); - - // free any special TEXT column data - createFreeTextColumnDbsStructFragment(tableName, tableDesc); - - - createErrorChecking(tableName, "Update", "Execute section", "return(SQLCODE);"); - writeNewLine(); - - // writeLine("/* need to verify that this works in postgresql! */"); - // writeLine("num_rows_updated = sqlca.sqlerrd[2];"); - - // writeLine("/* why do we have both lines? */"); - // writeLine("sqlca.sqlerrd[2] = num_rows_updated;"); - - - // writeLine("EXEC SQL COMMIT;"); - writeLine("initDbStatus(&dbStatus);"); - writeLine("return(ERR_OK);"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - - } - - - // ---------------------------------------------------------------------------------- - - private void createUpdateByRecordFunction(String tableName, - TableDescriptor tableDesc) - { - - _indenter.setLevel(0); - final int dbColumnsPerLine = 5; - - try - { - writeLine("int Update" + tableName + "ByRecord (const " + tableName + - " * newStructPtr, const " + tableName + " * oldStructPtr)"); - - _indenter.setLevel(0); - - - writeLine("{"); - _indenter.incLevel(); - - writeLine("char whereClause[BUFSIZ];"); - - writeLine("Get" + tableName + "PrimaryKeyWhereString(oldStructPtr, whereClause);"); - - writeLine("return (Update" + tableName + "(newStructPtr, whereClause));"); - - _indenter.decLevel(); - writeLine("}"); - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - private void createDeleteFunction(String tableName, - TableDescriptor tableDesc) - { - _indenter.setLevel(0); - - try - { - writeLine("int Delete" + tableName + "(const char *where)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("char deleteStatement[] = \"DELETE FROM " + tableName + " \";"); - - writeLine("EXEC SQL BEGIN DECLARE SECTION;"); - writeNewLine(); - writeLine("char queryBuffer[QUERY_LEN];"); - writeNewLine(); - writeLine("EXEC SQL END DECLARE SECTION;"); - writeNewLine(); - - writeLine("strcpy(queryBuffer, deleteStatement);"); - -// append the where clause to the query - writeLine("if ( (where != NULL) && (*where != '\\0'))"); - writeLine("{"); - _indenter.incLevel(); - writeLine("strcat(queryBuffer, where);"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("EXEC SQL EXECUTE IMMEDIATE :queryBuffer;"); - createErrorChecking(tableName, "Delete", "Execute Immediate section", "return(SQLCODE);"); - writeNewLine(); - - writeLine("initDbStatus(&dbStatus);"); - writeLine("return(ERR_OK);"); - - _indenter.decLevel(); - writeLine("}"); - - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - - private void createDeleteByRecordFunction(String tableName, - TableDescriptor tableDesc) - { - - _indenter.setLevel(0); - - try - { - writeLine("int Delete" + tableName + "ByRecord(const " + tableName + " * structPtr)"); - - writeLine("{"); - _indenter.incLevel(); - - writeLine("char whereClause[BUFSIZ];"); - - writeLine("Get" + tableName + "PrimaryKeyWhereString(structPtr, whereClause);"); - - writeLine("return (Delete" + tableName + "(whereClause));"); - - _indenter.decLevel(); - writeLine("}"); - - - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - private void createFreeTextColumnStructFragment(String tablename, TableDescriptor tableDesc) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - - try - { - - // do a special free for any TEXT fields - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (columnDesc.getSqlTypeInt() == Types.LONGVARCHAR) - { - writeLine("if (structPtr->" + columnDesc.getName() + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("free(structPtr->" + columnDesc.getName() + ");"); - - _indenter.decLevel(); - writeLine("}"); - } - } - - } - catch (IOException e) - { - logError(e); - } - } - - // ---------------------------------------------------------------------------------- - - private void createFreeTextColumnDbsStructFragment(String tablename, TableDescriptor tableDesc) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - // do a special free for any TEXT fields - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (columnDesc.getSqlTypeInt() == Types.LONGVARCHAR) - { - writeLine("if (dbs." + columnDesc.getName() + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("free(dbs." + columnDesc.getName() + ");"); - - _indenter.decLevel(); - writeLine("}"); - } - } - - } - catch (IOException e) - { - logError(e); - } - } - - // ---------------------------------------------------------------------------------- - private void createFreeFunction(String tableName, TableDescriptor tableDesc) - { - _indenter.setLevel(0); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - - - try - { - - writeLine("void Free" + tableName + "( " + tableName - + " * structPtr)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine(tableName + "* nextPtr = NULL;"); - writeNewLine(); - - writeLine("while (structPtr != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("nextPtr = ( " + tableName - + " * ) ListNext ( &structPtr->node );"); - - -// do a special free for any TEXT fields - createFreeTextColumnStructFragment(tableName, tableDesc); - - /* - // do a special free for any TEXT fields - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (columnDesc.getSqlTypeInt() == Types.LONGVARCHAR) - { - writeLine("if (structPtr->" + columnDesc.getName() + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("free (structPtr->" + columnDesc.getName() + ");"); - - _indenter.decLevel(); - writeLine("}"); - } - } - */ - writeLine("free (structPtr);"); - writeLine("structPtr = nextPtr;"); - - _indenter.decLevel(); - writeLine("}"); //close the while loop - - writeLine("return;"); - - _indenter.decLevel(); - writeLine("}"); // close the function - - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - private void createGetDbStatusFunction(String tableName) - { - _indenter.setLevel(0); - - try - { - writeLine("DbStatus * Get" + tableName + "DbStatus()"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("return &dbStatus;"); - - _indenter.decLevel(); - writeLine("}"); // close the function - } - - catch (IOException e) - { - logError(e); - } - - } - // ---------------------------------------------------------------------------------- - private List getKeyColumnDescriptorList(TableDescriptor tableDesc) - { - List keyColDescList = new ArrayList(); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - int columnCount = columnDescriptorList.size(); - -// for each key column, check if it is a key column, and, if so, then insert it into the list - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.isKeyColumn()) - { - keyColDescList.add(colDesc); - } - } - - return keyColDescList; - } - // ---------------------------------------------------------------------------------- - private int getDateColumnCount(List columnDescriptorList) - { - - int dateColumnCount = 0; - int columnCount = columnDescriptorList.size(); - - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.getSqlTypeInt() == Types.DATE) - { - dateColumnCount++; - } - } - - return dateColumnCount; - } - - // ---------------------------------------------------------------------------------- - private int getTimeColumnCount(List columnDescriptorList) - { - - int timeColumnCount = 0; - int columnCount = columnDescriptorList.size(); - - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - if (colDesc.getSqlTypeInt() == Types.TIMESTAMP) - { - timeColumnCount++; - } - } - - return timeColumnCount; - } - - // ---------------------------------------------------------------------------------- - - - private void createGetPrimaryWhereString(String tableName, TableDescriptor tableDesc) - { - /* - generate the following type of statement - sprintf(returnWhereString, "WHERE lid = '%s' AND pe = '%s' AND dur = %d AND ts = '%s' AND extremum = %d AND obstime = '%s' ", - structPtr->lid, structPtr->pe, structPtr->dur, - structPtr->ts, structPtr->extremum, structPtr->obsTime); - - */ - String header = "CDbGen.createGetPrimaryWhereString(): "; - final int dbColumnsPerLine = 5; - _indenter.setLevel(0); - - int dateColumnCount = 0; - int timeColumnCount = 0; - - try - { - - writeLine("void Get" + tableName + "PrimaryKeyWhereString " + "(const " + tableName + " * structPtr, char returnWhereString[] )"); - writeLine("{"); - _indenter.incLevel(); - - List keyColumnDescriptorList = tableDesc.getKeyColumnDescriptorList(); - int columnCount = keyColumnDescriptorList.size(); - - - dateColumnCount = getDateColumnCount(keyColumnDescriptorList); - timeColumnCount = getTimeColumnCount(keyColumnDescriptorList); - - for (int i = 0; i < dateColumnCount; i++) - { - writeLine("char date_buffer" + i + "[40];"); - } - - - for (int i = 0; i < timeColumnCount; i++) - { - writeLine("char time_buffer" + i + "[40];"); - } - - write("sprintf(returnWhereString, \"WHERE ", true); - -// for each key column, insert the lid = '%s' part of the sprintf statement - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) keyColumnDescriptorList.get(i); - int sqlType = colDesc.getSqlTypeInt(); - - - switch (sqlType) - { - case Types.CHAR: - case Types.VARCHAR: - { - write(colDesc.getName() + " = '%s' " ); - break; - } - case Types.SMALLINT: - { - write(colDesc.getName() + " = %d "); - break; - } - case Types.INTEGER: - { - write(colDesc.getName() + " = %ld "); - break; - } - - case Types.FLOAT: - case Types.REAL: - { - write(colDesc.getName() + " = %f "); - break; - } - - - case Types.DOUBLE: - { - write(colDesc.getName() + " = %lf "); - break; - } - - case Types.DATE: - { - //this case will have a corresponding - //conversion to SQL string from date - - if (_usingNewDateCode) - { - write(colDesc.getName() + " = '%s' "); - } - else - { - write(colDesc.getName() + " = '%ld' "); - } - break; - } - - case Types.TIMESTAMP: - { - - //this case will have a corresponding - //conversion to SQL string from timestamp - write(colDesc.getName() + " = '%s' "); - - break; - } - default: - { - System.out.println(header + "type = " + sqlType); - break; - } - - } - - - //if not the last column - if (i < columnCount - 1) - { - write(" AND "); - } - else //last one before parameter list - { - write("\",\n"); - } - - - } - - - //indent 3 times - write("", true); - write("", true); - write("", true); - - //for each key column, insert the ,sPtr->lid, sPtr->pe - int dateBufferCount = 0; - int timeBufferCount = 0; - - for (int i = 0 ; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) keyColumnDescriptorList.get(i); - int sqlType = colDesc.getSqlTypeInt(); - - switch (sqlType) - { - case Types.DATE: - { - //this case will have a corresponding - //conversion to SQL string from timestamp - if (_usingNewDateCode) - { - - write("date_t_to_ansi_date(structPtr->" + colDesc.getName()+ ", date_buffer"+ dateBufferCount + ")"); - dateBufferCount++; - } - else - { - write("structPtr->" + colDesc.getName()); - } - break; - } - case Types.TIMESTAMP: - { - //this case will have a corresponding - //conversion to SQL string from timestamp - if (_usingNewDateAndTimeCode) - { - write("timet_to_ansi(structPtr->" + colDesc.getName() + ", time_buffer" + timeBufferCount + ")"); - timeBufferCount++; - } - else - { - write("dtimet_to_ansi(structPtr->" + colDesc.getName() + ", time_buffer" + timeBufferCount + ")"); - timeBufferCount++; - } - break; - } - default: - { - write("structPtr->" + colDesc.getName()); - break; - } - - } - - - //if not the last column - if (i < columnCount - 1) - { - write(", "); - - if ((i+1) % dbColumnsPerLine == 0) - { - write("\n"); - write("", true); - write("", true); - write("", true); - } - - } - - } - - - write(");\n"); //close sprintf statement - - - _indenter.decLevel(); - writeLine("}"); - - - } - catch (IOException e) - { - logError(e); - } - - } - // ---------------------------------------------------------------------------------- - - private void createCopyDbStructToCStruct(String tableName, TableDescriptor tableDesc) - { - - int columnCount = tableDesc.getColumnDescriptorList().size(); - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - for (int i = 0; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - - int sqlType = colDesc.getSqlTypeInt(); - boolean isNullable = colDesc.isNullable(); - - String indicatorType = getNullTypeByInt(sqlType); - - switch(sqlType) - { - case Types.CHAR: - case Types.VARCHAR: - { - writeLine("strcpy(structPtr->" + colName + - ", dbs." + colName + ");"); - break; - } - case Types.LONGVARCHAR: - { - - //make sure I free any automatically allocated space in the dbs structure - writeLine("if (dbs." + colName + " != NULL)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("structPtr->" + colName + - " = malloc(strlen(dbs." + colName + ") + 1);") ; - writeLine("memset(structPtr->" + colName + ", '\\0', strlen(dbs." + colName + ") +1); "); - writeLine("strcpy(structPtr->" + colName + - ", dbs." + colName + ");"); - - writeLine("free(dbs." + colName +");"); - - _indenter.decLevel(); - writeLine("}"); - - - break; - } - - case Types.DATE: - { - if (_usingNewDateCode) - { - writeLine("structPtr->" + colName + - " = pg_date_to_date_t(dbs." + colName + ");"); - } - else - { - writeLine("structPtr->" + colName + - " = dbs." + colName + ";"); - } - break; - } - - - case Types.TIMESTAMP: - { - if (_usingNewDateAndTimeCode) - { - writeLine("structPtr->" + colName + - " = timestamp_to_timet(dbs." + colName + ");"); - } - else - { - writeLine("structPtr->" + colName + - " = dbs." + colName + ";"); - } - break; - } - - default: - { - writeLine("structPtr->" + colName + - " = dbs." + colName + ";"); - } - - } //end switch - - if (_usingIndicators) - { - String reference = ""; //puts in a "&" if not a string - if (! indicatorType.equals("CHAR")) - { - reference = "&"; - } - - if (isNullable) - { - writeLine("setNullIfIndicated(dbs." + indName + - ", " + indicatorType +", " + reference + "structPtr->" + colName +");"); - } - - //space out the copying so that pairs of setNullIfIndicated and - // data copying are placed together for each column - writeNewLine(); - } - - } //end for - - } //end try - catch (IOException e) - { - logError(e); - } - return; - } - - // ---------------------------------------------------------------------------------- - private void createExecuteUsing(TableDescriptor tableDesc, int dbColumnsPerLine) - { - try - { - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int size = columnDescriptorList.size(); - write("EXEC SQL EXECUTE uid USING ", true); - - //for each column, substitute, - for (int i = 0 ; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - - String indName = getIndicatorColumnName(colName); - - if (_usingIndicators) - { - if (colDesc.isNullable()) - { - write(" :dbs." + colName + ":dbs." + indName); - } - else - { - write(" :dbs." + colName); - - } - } - else - { - write(" :dbs." + colName); - } - - //if not the last column - if (i < size -1) - { - write(","); - - //only put a number of columns on a line at a time - // so go to a newline and indent - if ( (i+1) % dbColumnsPerLine == 0) - { - write("\n"); // newline - write("", true); //indent again - } - } - } - write(";\n"); //close the strcat statement - writeNewLine(); - } - catch (IOException e) - { - logError(e); - } - } - - // ---------------------------------------------------------------------------------- - private void createInsertStatement(TableDescriptor tableDesc, int dbColumnsPerLine) - { - final int numColumnsPerLine = 3; - - try - { - String tableName = tableDesc.getName(); - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int size = columnDescriptorList.size(); - write("EXEC SQL INSERT INTO " + tableName + " (", true); - - _indenter.incLevel(); - - for (int i = 0 ; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - - colName = wrapInQuotesIfNeeded(colName, false); - - write(colName); - - //if not the last column - if (i < size -1) - { - - write(","); - if ( ((i-1) % numColumnsPerLine) == 0) - { - // put in a new line - writeNewLine(); - - // indent - write("", true); - } - } - else //last column - { - //put in the closing parenthesis - writeLine(")"); - } - } - - writeLine("VALUES ("); - - //for each column, substitute, - for (int i = 0 ; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - - if(i == 0) - { - write("", true); //make it indent - } - - if (_usingIndicators) - { - if (colDesc.isNullable()) - { - write(" :dbs." + colName + ":dbs." + indName); - } - else - { - write(" :dbs." + colName); - - } - } - else - { - write(" :dbs." + colName); - } - - //if not the last column - if (i < size -1) - { - write(","); - - //only put a number of columns on a line at a time - // so go to a newline and indent - if ( (i+1) % dbColumnsPerLine == 0) - { - write("\n"); // newline - write("", true); //indent again - } - } - } - write(");\n"); //close VALUES phrase - writeNewLine(); - - - _indenter.decLevel(); - } - catch (IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - - private void createFetch(TableDescriptor tableDesc, String cursorName) - { - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int size = columnDescriptorList.size(); - - try - { - - writeLine("EXEC SQL FETCH " + cursorName + " INTO "); - - for (int i = 0; i < size; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - boolean isNullable = colDesc.isNullable(); - - if (i == 0) - { - write("", true); - } - - if (isNullable) - { - write(":dbs." + colName + ":dbs."+indName); - } - else - { - write(":dbs." + colName); - } - - //if not last column - if (i < size - 1) - { - // add comma - write(", ", false); - - // every 2 columns, start using a new line - // and then indent in anticipation of next line - if ( ( (i-1) % 2) == 0) - { - writeNewLine(); - write("", true); - } - } - else //last column - { - writeLine(";"); - writeNewLine(); - } - - } //end for - - } - catch (IOException e) - { - logError(e); - } - - } - // ---------------------------------------------------------------------------------- - private void createCopyCStructToDbStruct(String tableName, TableDescriptor tableDesc) - { - - int columnCount = tableDesc.getColumnDescriptorList().size(); - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - - for (int i = 0; i < columnCount; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - int sqlType = colDesc.getSqlTypeInt(); - String colName = colDesc.getName(); - String indName = getIndicatorColumnName(colName); - boolean isNullable = colDesc.isNullable(); - - String indicatorType = getNullTypeByInt(sqlType); - - switch(sqlType) - { - case Types.CHAR: - case Types.VARCHAR: - { - writeLine("strcpy(dbs." + colName + - ", structPtr->" + colName + ");"); - - - - break; - } - - //text field - case Types.LONGVARCHAR: - { - - writeLine("dbs." + colName + - " = malloc(strlen(structPtr->" + colName + ") + 1);") ; - writeLine("memset(dbs." + colName + ", '\\0', strlen(structPtr->" + colName + ") +1); "); - writeLine("strcpy(dbs." + colName + - ", structPtr->" + colName + ");"); - - - break; - } - - case Types.DATE: - { - if (_usingNewDateCode) - { - writeLine("dbs." + colName + - " = date_t_to_pg_date(structPtr->" + colName + ");"); - } - else - { - writeLine("dbs." + colName + - " = structPtr->" + colName + ";"); - } - - break; - } - - - case Types.TIMESTAMP: - { - if (_usingNewDateAndTimeCode) - { - writeLine("dbs." + colName + - " = timet_to_timestamp(structPtr->" + colName + ");"); - } - else - { - writeLine("dbs." + colName + - " = structPtr->" + colName + ";"); - } - - - break; - } - - - - default: - { - writeLine("dbs." + colName + - " = structPtr->" + colName + ";"); - break; - } - - } //end switch - - //add the indicator checking - if (_usingIndicators) - { - - String reference = ""; //puts in a "&" if not a string - - if (! indicatorType.equals("CHAR")) - { - reference = "&"; - } - - if (isNullable) - { - writeLine("dbs." + indName + - " = getIndicator(" + - indicatorType + - ", (void *)" + reference + "structPtr->" + colName + ");"); - } - - //space out the copying so that pairs of setNullIfIndicated and - // data copying are placed together for each column - writeNewLine(); - } - - } //end for - - - - } //end try - - catch (IOException e) - { - logError(e); - } - - - - return; - } - // ---------------------------------------------------------------------------------- - private void createErrorChecking(String tableName, String functionName, String functionSection, String returnValueString) - { - try - { - writeLine("if (SQLCODE < 0)"); - writeLine("{"); - _indenter.incLevel(); - - - writeLine("if (errorLoggingOn)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("fprintf(stderr, \"" + functionName + tableName + "() in " + functionSection + " --- ERROR\\n\");"); - writeLine("fprintf(stderr, \"SQLCODE = (%ld) sql state = (%s)\\n\", SQLCODE, sqlca.sqlstate);"); - writeLine("fprintf(stderr, \"Error Message (%s)\\n\", sqlca.sqlerrm.sqlerrmc);"); - writeLine("fflush(stderr);"); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("initDbStatus(&dbStatus);"); - - if (returnValueString != null) - { - writeLine(returnValueString); - } - - _indenter.decLevel(); - writeLine("}"); - - - } - catch(IOException e) - { - logError(e); - } - } - // ---------------------------------------------------------------------------------- - - - public void generate(String connectionURL, String preferredTableNameFilePath, - String dbName, String targetDir, String driverName) - { - - - // define an instance of a the IHFS database class - Database currentDatabase = new Database(); - - if (driverName != null) - { - currentDatabase.setDriverClassName(driverName); - } - - // call the method to connect to the database - currentDatabase.connect(connectionURL); - - - //store the path of the target directory for the generated files - _targetDirName = targetDir; - - //reads a list of Preferred table names from the directory indicated by - //schemaDirName - Map preferredTableNameMap = - getMapOfPreferredTableNames(preferredTableNameFilePath); - - // returns a list of the TableDescriptors which contain metadata about - // the tables and columns. - SchemaDescriber finder = new SchemaDescriber(currentDatabase); - - - _tableDescriptorList = finder.getTableDescriptorList(preferredTableNameMap); - - - _indenter = new CodeIndenter(_indentString); - - //generate all the XXXRecord.java files - buildHeaderSrcFiles(dbName); - - //generate all the XXXTable.jar files - buildEsqlCSourceFiles(dbName); - - // disconnect from the database - currentDatabase.disconnect(); - - } //end generate - - //--------------------------------------------------------------- - // - //--------------------------------------------------------------- - public static void main(String args[]) - { - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - - String connectionURL = null; - String preferredTableNameFilePath = null; - // the database name is passed in as the third command line argument - String dbName = null; - String packageName = null; - String targetDir = null; - String driverName = null; - - - if (args.length < 5) - { - System.err.println("Usage: java CDbGen connectionURL preferredTableNameFilePath dbName targetDir driverClassName"); - } - else - // the argument count looks good - { - connectionURL = args[0]; - preferredTableNameFilePath = args[1]; - - // the database name is passed in as the third command line argument - dbName = args[2]; - - targetDir = args[3]; - - driverName = args[4]; - - // create a JDbGen object named dbgen - CDbGen dbgen = new CDbGen(); - - dbgen.generate(connectionURL, preferredTableNameFilePath, dbName, targetDir, driverName); - - System.out.println("CDBGEN completed!"); - //timer.stop("CDbGen took"); - } - - return; - - } // end of main - -} // end of JDbGen class diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/CodeIndenter.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/CodeIndenter.java deleted file mode 100644 index 47e01d97f4..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/CodeIndenter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Created on Oct 6, 2004 - * - * - */ -package ohd.hseb.dbgen; - -/** - * @author Chip Gobs - * - * This class encapsulates the indentation of code but providing access - * indentation levels and an indentation string based on those levels. - */ -public class CodeIndenter -{ - - private int _indentLevel = 0; - private String _indentString = null; - private String _totalIndentString = null; - - // --------------------------------------------------------------- - - public CodeIndenter(String indentString) - { - _indentString = indentString; - _indentLevel = 0; - } - - // --------------------------------------------------------------- - - public void incLevel() - { - incLevel(1); - } - - - // --------------------------------------------------------------- - - public void incLevel(int amount) - { - _indentLevel += amount; - _totalIndentString = null; - } - - // ---------------------------------------------------------------- - - public void decLevel(int amount) - { - _indentLevel -= amount; - - if (_indentLevel < 0) - { - _indentLevel = 0; - } - - _totalIndentString = null; - } - - // ---------------------------------------------------------------- - - public void decLevel() - { - decLevel(1); - } - - // --------------------------------------------------------------- - - public void setLevel(int level) - { - _indentLevel = level; - _totalIndentString = null; - } - - // --------------------------------------------------------------- - - public String getTotalIndentString() - { - - if (_totalIndentString == null) - { - StringBuffer indentBuffer = new StringBuffer(); - for (int i = 0; i < _indentLevel; i++) - { - indentBuffer.append(_indentString); - } - _totalIndentString = indentBuffer.toString(); - } - return _totalIndentString; - - } - - // --------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/ColumnDescriptor.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/ColumnDescriptor.java deleted file mode 100644 index d7b3dbef22..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/ColumnDescriptor.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Created on Aug 13, 2003 - * - * - */ -package ohd.hseb.dbgen; - -/** - * @author Chip Gobs - * - * This class encapsulates information about table columns, for the purpose of - * code generation. - */ -public class ColumnDescriptor -{ - private String _name = null; - - private int _sqlTypeInt = -1; - private String _sqlTypeString = null; - private int _size = 0; //useful for char types - - private boolean _keyColumn = false; - private boolean _nullable = true; - - public void setName(String name) - { - _name = name; - } - - public String getName() - { - return _name; - } - - - public void setSqlTypeString(String sqlTypeString) - { - _sqlTypeString = sqlTypeString; - } - /* - - public String getSqlTypeString() - { - return _sqlTypeString; - } - */ -/* - public void setResultSetType(String resultSetType) - { - _resultSetType = resultSetType; - } - - public String getResultSetType() - { - return _resultSetType; - } - - public void setJavaType(String javaType) - { - _javaType = javaType; - } - - public String getJavaType() - { - return _javaType; - } -*/ - public void setKeyColumn(boolean keyColumn) - { - _keyColumn = keyColumn; - } - - public boolean isKeyColumn() - { - return _keyColumn; - } - - /** - * @param sqlTypeInt The sqlTypeInt to set. - */ - public void setSqlTypeInt(int sqlTypeInt) - { - _sqlTypeInt = sqlTypeInt; - } - - /** - * @return Returns the sqlTypeInt. - */ - public int getSqlTypeInt() - { - return _sqlTypeInt; - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("Name = " + _name + "\n"); - buffer.append("SQL Type (Int) = " + _sqlTypeInt + "\n"); - buffer.append("SQL Type (String) = " + _sqlTypeString + "\n"); - buffer.append("size = " + _size + "\n"); - buffer.append("Is Key Column? = " + _keyColumn + "\n"); - - - return buffer.toString(); - } - - /** - * @param size The size to set. - */ - public void setSize(int size) - { - _size = size; - } - - /** - * @return Returns the size. - */ - public int getSize() - { - return _size; - } - - /** - * @param nullable The nullable to set. - */ - public void setNullable(boolean nullable) - { - _nullable = nullable; - } - - /** - * @return Returns the nullable. - */ - public boolean isNullable() - { - return _nullable; - } - - - - -} //end class ColumnDescriptor diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/JDbGen.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/JDbGen.java deleted file mode 100644 index a27c02576c..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/JDbGen.java +++ /dev/null @@ -1,1598 +0,0 @@ -// -// File: JDbGen.java -// Orig Author: Russell Erb 12/18/2000 -// Modified by: Russell Erb 03/30/2001 -// Russell Erb 02/27/2002 - check that lastPeriod is > 0 -// Chip Gobs 08/2003 - a number of changes including: -// using List instead of Vector -// and subclassing from DbTable and DbRecord, -// no-conversion-needed handling of the Timestamp data -// The ability to be expanded for use with other -// database types. -// Chip Gobs 9/2004 - Modified to allow it to work with PostgreSQL or Informix. - -package ohd.hseb.dbgen; - -//import ohd.hseb.util.*; - -import java.util.*; // needed for List and Map classes and others -import java.util.Date; // needed for Date class, resolves ambiguity with java.sql.Date -import java.io.*; // needed for file I/O -import java.sql.*; - -import ohd.hseb.db.Database; - - -public class JDbGen -{ -// --------------------------------------------------------------- -// private data -//--------------------------------------------------------------- - - private String _generatedPackageName = null; - private String _targetDirName = null; - private DataOutputStream _dos = null; - private List _tableDescriptorList = null; - - - private CodeIndenter _indenter = null; - private final String _indentString = " "; - - - //for Informix mode - // private Map _javaDataTypeStringMap = null; //maps from sqlType String to javaDataType - // private Map _rsInterfaceTypeStringMap = null;//maps from sqlTypeString to result set dataType - - - //for PostgreSQL and other generation modes - private Map _javaDataTypeIntegerMap = null; //maps from sqlType integer to javaDataType String - private Map _rsInterfaceTypeIntegerMap = null; //maps from sqlType integer to result set dataType - - - // --------------------------------------------------------------------------------- - - public JDbGen() - { - initJavaDataTypeIntegerMap(); - initResultSetDataTypeIntegerMap();; - } - - // --------------------------------------------------------------------------------- - - private void addJavaDataTypeIntegerMapEntry(int sqlType, String javaType) - { - _javaDataTypeIntegerMap.put(new Integer(sqlType), javaType); - } - // ------------------------------------------------------------------------------------- - private void initJavaDataTypeIntegerMap() - { - - _javaDataTypeIntegerMap = new HashMap(); - - addJavaDataTypeIntegerMapEntry(Types.DATE, "long"); - addJavaDataTypeIntegerMapEntry(Types.TIMESTAMP, "long"); - addJavaDataTypeIntegerMapEntry(Types.TIME, "long");// new one - - addJavaDataTypeIntegerMapEntry(Types.REAL, "float"); - addJavaDataTypeIntegerMapEntry(Types.FLOAT, "float"); //changed from double in OB7.2 - addJavaDataTypeIntegerMapEntry(Types.DOUBLE, "double"); - - addJavaDataTypeIntegerMapEntry(Types.NUMERIC, "double");// new one - - addJavaDataTypeIntegerMapEntry(Types.SMALLINT, "short"); - addJavaDataTypeIntegerMapEntry(Types.INTEGER, "int"); - addJavaDataTypeIntegerMapEntry(Types.BIGINT, "long"); - - addJavaDataTypeIntegerMapEntry(Types.LONGVARBINARY, "byte[]"); - addJavaDataTypeIntegerMapEntry(Types.LONGVARCHAR, "String"); // ? instead of byte[] - addJavaDataTypeIntegerMapEntry(Types.VARCHAR, "String"); - addJavaDataTypeIntegerMapEntry(Types.CHAR, "String"); - - addJavaDataTypeIntegerMapEntry(Types.ARRAY, "String");// new one - - } - - //------------------------------------------------------------------------------------- - private void addResultSetTypeIntegerMapEntry(int sqlType, String resultSetType) - { - _rsInterfaceTypeIntegerMap.put(new Integer(sqlType), resultSetType); - } - // --------------------------STAMP----------------------------------------------------------- - private void initResultSetDataTypeIntegerMap() - { - _rsInterfaceTypeIntegerMap = new HashMap(); - - addResultSetTypeIntegerMapEntry(Types.DATE, "Date"); - addResultSetTypeIntegerMapEntry(Types.TIMESTAMP, "TimeStamp"); - addResultSetTypeIntegerMapEntry(Types.TIME, "Time"); //new one - - addResultSetTypeIntegerMapEntry(Types.REAL, "Real"); - addResultSetTypeIntegerMapEntry(Types.FLOAT, "Float"); - addResultSetTypeIntegerMapEntry(Types.DOUBLE, "Double"); - addResultSetTypeIntegerMapEntry(Types.NUMERIC, "Double"); //new one - - addResultSetTypeIntegerMapEntry(Types.SMALLINT, "Short"); - addResultSetTypeIntegerMapEntry(Types.INTEGER, "Int"); - addResultSetTypeIntegerMapEntry(Types.BIGINT, "Long"); - - addResultSetTypeIntegerMapEntry(Types.LONGVARBINARY, "Bytes"); - addResultSetTypeIntegerMapEntry(Types.LONGVARCHAR, "String"); - addResultSetTypeIntegerMapEntry(Types.VARCHAR, "String"); - addResultSetTypeIntegerMapEntry(Types.CHAR, "String"); - - addResultSetTypeIntegerMapEntry(Types.ARRAY, "String"); //new one - } - - //------------------------------------------------------------------------------------- - - //--------------------------------------------------------------- -// write and writeLine are used to write out nicely indented code -//--------------------------------------------------------------- - private void write(String line, boolean useIndentation) throws IOException - { - if (useIndentation) - { - String totalIndentString = _indenter.getTotalIndentString(); - - _dos.writeBytes(totalIndentString + line); - } - else - { - _dos.writeBytes(line); - } - } -// ----------------------------------------------------------------- - private void write(String line) throws IOException - { - write(line, false); //by default, do not use indentation - - return; - } -// ----------------------------------------------------------------- - - private void writeLine(String line) throws IOException - { - boolean useIndentation = true; - write(line + "\n", useIndentation); - - return; - } - - -// -------------------------------------------------------------------------- - // read the list of preferred table names from a text file with the - // preferred name of the Tables and Views , 1 per line, no spaces in the name -// -------------------------------------------------------------------------- - private Map getMapOfPreferredTableNames(String filePath) - { - Map tableNameMap = new HashMap(); - - try - { - - BufferedReader reader = new BufferedReader (new FileReader(filePath)); - String line = null; - - line = reader.readLine(); - - String preferredTableName = null; - String lowercaseTableName = null; - - while (line != null) - { - preferredTableName = null; - lowercaseTableName = null; - - // System.out.println("line = " + line + ":"); - int separatorIndex = line.indexOf('='); - - if (separatorIndex > -1) - { - lowercaseTableName = line.substring(0, separatorIndex).trim().toLowerCase(); - preferredTableName = line.substring(separatorIndex + 1).trim(); - } - else //only one line item - { - preferredTableName = line.trim(); - lowercaseTableName = preferredTableName.toLowerCase(); - } - - - tableNameMap.put(lowercaseTableName, preferredTableName); - - System.out.println("JDbGen.getMapOfPreferredTableNames(): " + - lowercaseTableName + " -> " + preferredTableName); - - line = reader.readLine(); - } //end while - - reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - - return tableNameMap; - } - - - // --------------------------------------------------------------------------------- - private Map getMapOfPreferredTableNames_old(String filePath) - { - Map tableNameMap = new HashMap(); - - try - { - - BufferedReader reader = new BufferedReader (new FileReader(filePath)); - String line = null; - - line = reader.readLine(); - - while (line != null) - { - // System.out.println("line = " + line + ":"); - - String preferredTableName = line.trim(); - String lowercaseTableName = preferredTableName.toLowerCase(); - - tableNameMap.put(lowercaseTableName, preferredTableName); - - System.out.println("JDbGen.getMapOfPreferredTableNames(): " + - lowercaseTableName + " -> " + preferredTableName); - - line = reader.readLine(); - } //end while - - reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - - return tableNameMap; - } - - - // --------------------------------------------------------------------------------- - - private String getJavaDataTypeByInt(int sqlType) - { - String javaDataType = null; - - javaDataType = (String) _javaDataTypeIntegerMap.get(new Integer(sqlType)); - if (javaDataType == null) - { - javaDataType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return javaDataType; - } - // --------------------------------------------------------------------------------- - - private String getRSInterfaceTypeByInt(int sqlType) - { - String resultSetDataType = null; - - resultSetDataType = (String) _rsInterfaceTypeIntegerMap.get(new Integer(sqlType)); - if (resultSetDataType == null) - { - resultSetDataType = "UNKNOWN_SQL_TYPE_" + sqlType; - } - - return resultSetDataType; - - } - - // --------------------------------------------------------------------------------- - // buildRecordSrcFiles - - private void buildRecordSrcFiles(String dbName) - { - try - { - // Strings to hold Table name and File name - String tableName = null; - String fileName = null; - - // loop through all the table names and build source files - for (int ctr=0; ctr < _tableDescriptorList.size(); ctr++) - { - TableDescriptor tableDesc = (TableDescriptor) _tableDescriptorList.get(ctr); - tableName = tableDesc.getName(); - - fileName = tableName + "Record.java"; - - FileOutputStream fos = new FileOutputStream(_targetDirName + "/" + fileName); - _dos = new DataOutputStream(fos); - - createRecordFileBanner(tableName, fileName, dbName, tableDesc); - createRecordPrivateData(tableDesc); - createRecordEmptyConstructor(tableName); - createRecordCopyConstructor(tableName, tableDesc); - createRecordSetGet(tableName, tableDesc); - - if ( (! tableDesc.isView()) && (tableDesc.hasPrimaryKey()) ) - { - createRecordGetWhereString(tableDesc); - } - createRecordToString(tableDesc); - - _indenter.setLevel(0); - writeLine("} // end of " + tableName +"Record class\n"); - - _dos.close(); - //fos.close(); - } - } - catch(IOException ioe) - { - System.err.println( "buildRecordSrcFiles(): Something went wrong trying to write " + ioe); - } - - } // end of buildRecordSrcFiles method - - -// ----------------------------------------------------------------- -// createRecordFileBanner -// ----------------------------------------------------------------- - private void createRecordFileBanner(String tableName, - String fileName, - String dbName, - TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - // current time - Date currentTime = new Date(); - - System.out.println("building source code for " + fileName); - - if (tableDesc.isView()) - { - writeLine("// This is a view record !"); - } - - writeLine("// filename: " + fileName); - writeLine("// author : DBGEN"); - writeLine("// created : " + currentTime + " using database " + dbName); - writeLine("// description: This class is used to get data from and put data into a"); - writeLine("// " + tableName + " table record format"); - writeLine("//\n"); - - if (_generatedPackageName.length() > 0) - { - writeLine("package " + _generatedPackageName + ";\n"); - } - - writeLine("import ohd.hseb.db.*;\n"); - writeLine("public class " + tableName +"Record extends DbRecord"); - writeLine("{"); - } - catch(IOException ioe) - { - System.out.println( "createRecordFileBanner(): Something went wrong trying to write " + ioe); - } - - } // end of createRecordFileBanner method - - - -// ----------------------------------------------------------------- -// createRecordPrivateData -// ----------------------------------------------------------------- - private void createRecordPrivateData(TableDescriptor tableDesc) - { - try - { - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - _indenter.setLevel(1); - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String javaDataType = getJavaDataTypeByInt(columnDesc.getSqlTypeInt()); - String columnName = columnDesc.getName(); - - writeLine("private " + javaDataType + " " + columnName + ";\n"); - } - - } - catch(IOException ioe) - { - System.err.println( "createRecordPrivateData(): Something went wrong trying to write " + ioe); - } - - } // end of createRecordPrivateData method - -// --------------------------------------------------------- -// createRecordEmptyConstructor -// -------------------------------------------------------- - private void createRecordEmptyConstructor(String tableName) - { - - try - { - writeLine("//---------------------------------------------------------------"); - writeLine("// Empty constructor"); - writeLine("//---------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public " + tableName +"Record()"); - writeLine("{"); - writeLine("}\n"); - - } - catch(IOException ioe) - { - System.err.println( "createRecordEmptyConstructor(): Something went wrong trying to write " + ioe); - } - - } // end of createRecordEmptyConstructor method - - -// --------------------------------------------------------- -// createRecordCopyConstructor -// -------------------------------------------------------- - private void createRecordCopyConstructor(String tableName, - TableDescriptor tableDesc) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - writeLine("//-----------------------------------------------------------------"); - writeLine("// Copy constructor"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public " + tableName +"Record(" + tableName + "Record origRecord)"); - writeLine("{"); - _indenter.incLevel(); - - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - String columnName = colDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() + columnName.substring(1); - - writeLine("set" + newName + "(origRecord.get" + newName + "());"); - - } //end for each column - - _indenter.decLevel(); - writeLine("}\n"); - - } - catch(IOException ioe) - { - System.err.println( "createRecordCopyConstructor(): Something went wrong trying to write " + ioe); - } - - } // end of createRecordCopyConstructor method - -// --------------------------------------------------------------- -// createRecordSetGet -// --------------------------------------------------------------- - private void createRecordSetGet(String tableName, - TableDescriptor tableDesc) - { - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - try - { - writeLine("//-----------------------------------------------------------------"); - writeLine("// get and set methods for all data items in a " + tableName + " record\n"); - writeLine("//-----------------------------------------------------------------"); - - - for (int i = 0; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String javaDataType = getJavaDataTypeByInt(colDesc.getSqlTypeInt()); - String columnName = colDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() + columnName.substring(1); - - - //create the getter - writeLine("public " + javaDataType + " get" + newName + "()"); - - writeLine("{"); - - _indenter.incLevel(); - writeLine("return " + columnName + ";" ); - - _indenter.decLevel(); - writeLine("}\n"); - - //create the setter - writeLine("public void set" + newName + "(" + javaDataType + " " + columnName + ")"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("this." + columnName + " = " + columnName + " ;"); - - _indenter.decLevel(); - writeLine("}\n"); - - } - - } - catch(IOException ioe) - { - System.err.println( "createRecordSetGet(): Something went wrong trying to write " + ioe); - } - - } // end of createRecordSetGet method - -// --------------------------------------------------------------- -// createRecordGetWhereString -// --------------------------------------------------------------- - private void createRecordGetWhereString(TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// getWhereString() - this method is called with no arguments"); - writeLine("// and returns a String that contains a valid where clause containing all the"); - writeLine("// primary key fields."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public String getWhereString()"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("String outString = "); - - _indenter.incLevel(); - _indenter.incLevel(); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - write("\"WHERE ", true); - - int keyColumnCount = 0; - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - // String sqlDataType = columnDesc.getSqlTypeString(); - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - - //String javaDataType = columnDesc.getJavaType(); - String columnName = columnDesc.getName(); - - boolean isKeyColumn = columnDesc.isKeyColumn(); - - //append the pieces to the WHERE clause - if (isKeyColumn) - { - keyColumnCount++; - if (keyColumnCount != 1) //not first one - { - write(" + \" AND ", true); - } - - - /* - if (sqlDataType.equalsIgnoreCase("DateTime")) - { - write(columnName + " = '\" + getDateTimeStringFromLongTime(" + columnName + ")" + " + \"'\" \n"); - } - else if (sqlDataType.equalsIgnoreCase("Date")) - { - write(columnName + " = '\" + getDateStringFromLongTime(" + columnName + ")" + " + \"'\" \n"); - } - */ - if (sqlDataTypeInt == Types.TIMESTAMP) - { - write(columnName + " = '\" + getDateTimeStringFromLongTime(" + columnName + ")" + " + \"'\" \n"); - } - else if (sqlDataTypeInt == Types.DATE) - { - write(columnName + " = '\" + getDateStringFromLongTime(" + columnName + ")" + " + \"'\" \n"); - } - - else //the usual - { - write(columnName + " = '\" + " + columnName + " + \"'\" \n"); - } - - - } //end isKeyColumn - - }//end for loop - - writeLine(";"); - - - //writeLine("\"\" ;"); - - //get rid of extra indents - _indenter.decLevel(); - _indenter.decLevel(); - - writeLine("return outString;"); - - _indenter.decLevel(); - writeLine("} // end toString()"); - - } - catch(IOException ioe) - { - System.err.println( "createRecordGetWhereString(): Something went wrong trying to write " + ioe); - } - - } // end of CreateRecordGetWhereString method - - - -// --------------------------------------------------------------- -// createRecordToString -// --------------------------------------------------------------- - private void createRecordToString(TableDescriptor tableDesc) - { - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// toString() - this method is called with no arguments"); - writeLine("// and returns a String of the internal values"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public String toString()"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("String outString = "); - - _indenter.incLevel(); - _indenter.incLevel(); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - // String sqlDataType = columnDesc.getSqlTypeString(); - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - //String javaDataType = columnDesc.getJavaType(); - String columnName = columnDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() + columnName.substring(1); - - /* - if (sqlDataType.equalsIgnoreCase("DateTime")) - { - writeLine("getDateTimeStringFromLongTime(get" + newName + "()) + \" \" +"); - } - else if (sqlDataType.equalsIgnoreCase("Date")) - { - writeLine("getDateStringFromLongTime(get" + newName + "()) + \" \" +"); - } - */ - - if (sqlDataTypeInt == Types.TIMESTAMP) - { - writeLine("getDateTimeStringFromLongTime(get" + newName + "()) + \" \" +"); - } - else if (sqlDataTypeInt == Types.DATE) - { - writeLine("getDateStringFromLongTime(get" + newName + "()) + \" \" +"); - } - else - { - writeLine("get" + newName + "() + \" \" +"); - } - } - - writeLine("\"\" ;"); - - //get rid of extra indents - _indenter.decLevel(); - _indenter.decLevel(); - - writeLine("return outString;"); - - _indenter.decLevel(); - writeLine("} // end toString()"); - - } - catch(IOException ioe) - { - System.err.println( "createRecordToString(): Something went wrong trying to write " + ioe); - } - - } // end of CreateRecordToString method - - -// --------------------------------------------------------------- -// buildTableSrcFiles -// --------------------------------------------------------------- - private void buildTableSrcFiles(String dbName) - { - - try - { - // Strings to hold Table name and File name - String tableName = null; - String originalTableName = null; - String fileName = null; - - // loop through all the table names and build source files - for (int ctr=0; ctr < _tableDescriptorList.size(); ctr++) - { - TableDescriptor tableDesc = (TableDescriptor) _tableDescriptorList.get(ctr); - tableName = tableDesc.getName(); - originalTableName = tableDesc.getOriginalCaseTableName(); - - if (tableDesc.isView()) - { - fileName = tableName + "View.java"; - } - else - { - fileName = tableName + "Table.java"; - } - - FileOutputStream fos = new FileOutputStream(_targetDirName + "/" + fileName); - _dos = new DataOutputStream(fos); - - createTableFileBanner(tableName, fileName, dbName, tableDesc); - createTableData(); - - createTableConstructor(tableName, tableDesc); - createTableSelect(tableName, originalTableName, tableDesc); - createTableSelectNRecords(tableName, originalTableName, tableDesc); - - if (! tableDesc.isView()) //is a regular table - { - createTableInsert(tableName, tableDesc); - - //all regular tables have this - createTableDelete1(tableName, originalTableName); - createTableUpdate1(tableName, originalTableName, tableDesc); - - // only regular tables with primary keys also have this - if (tableDesc.hasPrimaryKey()) - { - createTableDelete2(tableName, originalTableName); - createTableUpdate2(tableName, originalTableName, tableDesc); - createTableInsertOrUpdate(tableName); - } - - } - - _indenter.setLevel(0); - writeLine("} // end of " + tableName +"Table class"); - - _dos.close(); - //fos.close(); - } - } - catch(IOException ioe) - { - System.out.println( "buildTableSrcFiles(): Something went wrong trying to write " + ioe); - } - - } // end of buildTableSrcFiles method - - -// --------------------------------------------------------------- -// createTableFileBanner -// --------------------------------------------------------------- - private void createTableFileBanner(String tableName, - String fileName, - String dbName, - TableDescriptor tableDesc) - { - try - { - // current time - Date currentTime = new Date(); - - System.out.println("building source code for " + fileName); - - _indenter.setLevel(0); - - writeLine("// filename: " + fileName); - writeLine("// author : DBGEN"); - writeLine("// created : " + currentTime + " using database " + dbName); - writeLine("// description: This class is used to get data from and put data into the"); - writeLine("// " + tableDesc.getOriginalCaseTableName() + " table of an IHFS database"); - writeLine("//"); - - if (_generatedPackageName.length() > 0) - { - writeLine("package " + _generatedPackageName + ";\n"); - } - - writeLine("import java.sql.*;\n"); - writeLine("import java.util.*;\n"); - writeLine("import ohd.hseb.db.*;\n"); - - if (tableDesc.isView()) - { - writeLine("public class " + tableName +"View extends DbTable"); - } - else //regular table - { - writeLine("public class " + tableName +"Table extends DbTable"); - } - - writeLine("{"); - } - catch(IOException ioe) - { - System.out.println( "createTableFileBanner(): Something went wrong trying to write " + ioe); - } - - } // end of createTableFileBanner method - - -// --------------------------------------------------------------- -// createTableConstructors -// --------------------------------------------------------------- - private void createTableData() - { - try - { - - writeLine("//-----------------------------------------------------------------"); - writeLine("// Private data"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("private int _recordsFound = -1;"); - - - } - catch(IOException ioe) - { - System.err.println( "createTableData(): Something went wrong trying to write " + ioe); - } - - } // end of createTableData method - -//--------------------------------------------------------------- -//createTableConstructor -//--------------------------------------------------------------- - private void createTableConstructor(String tableName, TableDescriptor tableDesc) - { - - String originalTableName = tableDesc.getOriginalCaseTableName(); - - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// " + tableName + "Table() - constructor to set statement variable and initialize"); - writeLine("//\t\tnumber of records found to zero"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - - if (tableDesc.isView()) - { - writeLine("public " + tableName + "View(Database database) "); - } - else - { - writeLine("public " + tableName + "Table(Database database) "); - } - - writeLine("{"); - - _indenter.incLevel(); - writeLine("//Constructor calls DbTable's constructor"); - writeLine("super(database);"); - writeLine("setTableName(\"" + tableDesc.getOriginalCaseTableName() + "\");"); - - _indenter.decLevel(); - writeLine("}\n\n"); - - } - catch (IOException e) - { - e.printStackTrace(); - } - } //end createTableConstructor -//--------------------------------------------------------------- -// createTableSelect -//--------------------------------------------------------------- - private void createTableSelect(String tableName, String originalTableName, TableDescriptor tableDesc) - { - - try - { - writeLine("//-----------------------------------------------------------------"); - writeLine("// select() - this method is called with a where clause and returns"); - writeLine("//\t\ta List of " + tableName + "Record objects"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public List select(String where) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine(tableName + "Record record = null;\n"); - writeLine("// create a List to hold " + tableName + " Records"); - writeLine("List recordList = new ArrayList();\n"); - writeLine("// set number of records found to zero"); - writeLine("_recordsFound = 0;\n"); - writeLine("// Create the SQL statement and issue it"); - - writeLine("// construct the select statment"); - writeLine("String selectStatement = \"SELECT * FROM " + originalTableName + " \" + where;\n"); - writeLine("// get the result set back from the query to the database"); - writeLine("ResultSet rs = getStatement().executeQuery(selectStatement);\n"); - writeLine("// loop through the result set"); - writeLine("while (rs.next())"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("// create an instance of a " + tableName +"Record"); - writeLine("// and store its address in oneRecord"); - writeLine("record = new " + tableName +"Record();\n"); - writeLine("// increment the number of records found"); - writeLine("_recordsFound++;\n"); - writeLine("// assign the data returned to the result set for one"); - writeLine("// record in the database to a " + tableName +"Record object\n"); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int index = -1; - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - index = i + 1; - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - //String sqlDataType = columnDesc.getSqlTypeString(); - - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - - - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - - String columnName = columnDesc.getName(); - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() + columnName.substring(1); - - writeLine("record.set" + newName + "(get" + rsInterfaceType + "(rs, " + index + "));"); - - } //end for - - writeLine(""); - - writeLine("// add this " + tableName +"Record object to the list"); - writeLine("recordList.add(record);"); - - _indenter.decLevel(); - writeLine("}"); - writeLine("// Close the result set"); - writeLine("rs.close();\n"); - - //create the code to return the recordList - writeLine("// return a List which holds the " + tableName +"Record objects"); - - writeLine("return recordList;\n"); - - _indenter.decLevel(); - writeLine("} // end of select method\n"); - } - catch(IOException ioe) - { - System.err.println( "createTableSelect(): Something went wrong trying to write " + ioe); - } - - } // end of createTableSelect method - -// --------------------------------------------------------------- -// createTableSelect -// --------------------------------------------------------------- - private void createTableSelectNRecords(String tableName, String originalTableName, TableDescriptor tableDesc) - { - try - { - writeLine("//-----------------------------------------------------------------"); - writeLine("// selectNRecords() - this method is called with a where clause and returns"); - writeLine("//\t\ta List filled with a maximum of maxRecordCount of " + tableName + "Record objects "); - writeLine("//-----------------------------------------------------------------"); - - _indenter.setLevel(1); - writeLine("public List selectNRecords(String where, int maxRecordCount) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine(tableName + "Record record = null;\n"); - writeLine("// create a List to hold " + tableName + " Records"); - writeLine("List recordList = new ArrayList();\n"); - writeLine("// set number of records found to zero"); - writeLine("_recordsFound = 0;\n"); - writeLine("// Create the SQL statement and issue it"); - - writeLine("// construct the select statment"); - writeLine("String selectStatement = \"SELECT * FROM " + originalTableName + " \" + where;\n"); - writeLine("// get the result set back from the query to the database"); - writeLine("ResultSet rs = getStatement().executeQuery(selectStatement);\n"); - writeLine("// loop through the result set"); - writeLine("while (rs.next())"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("// create an instance of a " + tableName +"Record"); - writeLine("// and store its address in oneRecord"); - writeLine("record = new " + tableName +"Record();\n"); - writeLine("// increment the number of records found"); - writeLine("_recordsFound++;\n"); - writeLine("// assign the data returned to the result set for one"); - writeLine("// record in the database to a " + tableName +"Record object\n"); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - int index = -1; - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - index = i + 1; - ColumnDescriptor columnDesc = (ColumnDescriptor) columnDescriptorList.get(i); - //String sqlDataType = columnDesc.getSqlTypeString(); - int sqlDataTypeInt = columnDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - //String javaDataType = columnDesc.getJavaType(); - String columnName = columnDesc.getName(); - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() + columnName.substring(1); - - writeLine("record.set" + newName + "(get" + rsInterfaceType + "(rs, " + index + "));"); - - } //end for - - writeLine(""); - - writeLine("// add this " + tableName +"Record object to the list"); - writeLine("recordList.add(record);"); - - writeLine("if (_recordsFound >= maxRecordCount)"); - writeLine("{"); - _indenter.incLevel(); - - writeLine("break;"); - - _indenter.decLevel(); - writeLine("}"); - - _indenter.decLevel(); - writeLine("}"); - - writeLine("// Close the result set"); - writeLine("rs.close();\n"); - - //create the code to return the recordList - writeLine("// return a List which holds the " + tableName +"Record objects"); - - writeLine("return recordList;\n"); - - _indenter.decLevel(); - writeLine("} // end of selectNRecords method\n"); - } - catch(IOException ioe) - { - System.err.println( "createTableSelectNRecords(): Something went wrong trying to write " + ioe); - } - - } // end of createTableSelectNRecords method -// --------------------------------------------------------------- -// createTableInsert -// --------------------------------------------------------------- - private void createTableInsert(String tableName, TableDescriptor tableDescriptor) - { - String originalTableName = tableDescriptor.getOriginalCaseTableName(); - - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// insert() - this method is called with a " + tableName + "Record object and.."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int insert(" + tableName + "Record record) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;\n"); - writeLine("// Create a SQL insert statement and issue it"); - - - writeLine("// construct the insert statement"); - writeLine("PreparedStatement insertStatement = getConnection().prepareStatement("); - write("\" INSERT INTO " + originalTableName + " VALUES ("); - - List columnDescriptorList = tableDescriptor.getColumnDescriptorList(); - - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - if (i == 0) - { - write("?"); - } - else - { - write(", ?"); - } - } - - writeLine(")\");\n"); - - int index = -1; - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - index = i+1; - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - - int sqlDataTypeInt = colDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - //String sqlDataType = colDesc.getSqlTypeString(); - - String columnName = colDesc.getName(); - - String firstChar = String.valueOf(columnName.charAt(0)); - String newName = firstChar.toUpperCase() + columnName.substring(1); - - writeLine("set" + rsInterfaceType + "(insertStatement, " + index + ", record.get" + newName + "());"); - - } - - writeLine(""); - - writeLine("// get the number of records processed by the insert"); - writeLine("returnCode = insertStatement.executeUpdate();\n"); - //writeLine("System.out.println(\"returnCode from putRecord = \" + returnCode);"); - - writeLine("return returnCode;\n"); - - _indenter.decLevel(); - writeLine("} // end of insert method\n"); - } - catch(IOException ioe) - { - System.err.println( "createTableInsert(): Something went wrong trying to write " + ioe); - } - - } // end of createTableInsert method - - -// --------------------------------------------------------------- -// createTableDelete1 -// --------------------------------------------------------------- - private void createTableDelete1(String tableName, String originalTableName) - { - - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// delete() - this method is called with a where clause and returns"); - writeLine("// the number of records deleted"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int delete(String where) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;\n"); - writeLine("// Create a SQL delete statement and issue it"); - - writeLine("// construct the delete statement"); - writeLine("String deleteStatement = \"DELETE FROM " + originalTableName + " \" + where;\n"); - writeLine("// get the number of records processed by the delete"); - writeLine("returnCode = getStatement().executeUpdate(deleteStatement);\n"); - - //writeLine("System.out.println(\"returnCode from delete = \" + returnCode);"); - - writeLine("return returnCode;"); - - _indenter.decLevel(); - writeLine("} // end of delete method \n"); - } - catch(IOException ioe) - { - System.err.println( "createTableDelete1(): Something went wrong trying to write " + ioe); - } - - } // end of createDelete1 method - -// --------------------------------------------------------------- -// createTableDelete2 -// --------------------------------------------------------------- - private void createTableDelete2(String tableName, String originalTableName) - { - - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// delete() - this method is called with a where clause and returns"); - writeLine("// the number of records deleted"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int delete(" + tableName + "Record record) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;\n"); - writeLine("// Create a SQL delete statement and issue it"); - - writeLine("// construct the delete statement"); - writeLine("String deleteStatement = \"DELETE FROM " + originalTableName + " \" + record.getWhereString();\n"); - writeLine("// get the number of records processed by the delete"); - writeLine("returnCode = getStatement().executeUpdate(deleteStatement);\n"); - - //writeLine("System.out.println(\"returnCode from delete = \" + returnCode);"); - - writeLine("return returnCode;"); - - _indenter.decLevel(); - writeLine("} // end of delete method \n"); - } - catch(IOException ioe) - { - System.err.println( "createTableDelete2(): Something went wrong trying to write " + ioe); - } - - } // end of createDelete2 method - - -// --------------------------------------------------------------- -// createTableUpdate1 -// --------------------------------------------------------------- - private void createTableUpdate1(String tableName, String originalTableName, TableDescriptor tableDesc) - { - - try - { - _indenter.setLevel(0); - - - writeLine("//-----------------------------------------------------------------"); - writeLine("// update() - this method is called with a " + tableName + "Record object and a where clause.."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int update(" + tableName + - "Record record, String where) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;"); - writeLine("// Create a SQL update statement and issue it"); - - writeLine("// construct the update statement"); - writeLine("PreparedStatement updateStatement = getConnection().prepareStatement("); - write("\" UPDATE " + originalTableName + " SET "); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String columnName = colDesc.getName(); - - if (i == 0) - { - write(columnName + " = ?"); - - } - else - { - write(", " + columnName + " = ?"); - } - - } //end for - - writeLine("\" + where );\n"); - int index = -1; - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - index = i+1; - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String columnName = colDesc.getName(); - - //String sqlDataType = colDesc.getSqlTypeString(); - int sqlDataTypeInt = colDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - String firstChar = String.valueOf(columnName.charAt(0)); - - String newName = firstChar.toUpperCase() + columnName.substring(1); - - writeLine("set" + rsInterfaceType + "(updateStatement, " + index + ", record.get" + newName + "());"); - - } //end for - - - writeLine("// get the number of records processed by the update"); - writeLine("returnCode = updateStatement.executeUpdate();\n"); - //writeLine("System.out.println(\"returnCode from updateRecord = \" + returnCode);"); - - writeLine("return returnCode;\n"); - - _indenter.decLevel(); - writeLine("} // end of updateRecord method\n"); - } - - catch(IOException ioe) - { - System.err.println( "createTableUpdate1(): Something went wrong trying to write " + ioe); - } - - } // end of createTableUpdate1 method - -// --------------------------------------------------------------- -// createTableUpdate2 -// --------------------------------------------------------------- - private void createTableUpdate2(String tableName, String originalTableName, TableDescriptor tableDesc) - { - - try - { - _indenter.setLevel(0); - - - writeLine("//-----------------------------------------------------------------"); - writeLine("// update() - this method is called with a " + tableName + "Record object and a where clause.."); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int update(" + tableName + "Record oldRecord, " + - tableName + "Record newRecord) throws SQLException"); - writeLine("{"); - - _indenter.incLevel(); - writeLine("int returnCode=-999;"); - writeLine("// Create a SQL update statement and issue it"); - - writeLine("// construct the update statement"); - writeLine("PreparedStatement updateStatement = getConnection().prepareStatement("); - write("\" UPDATE " + originalTableName + " SET "); - - List columnDescriptorList = tableDesc.getColumnDescriptorList(); - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String columnName = colDesc.getName(); - - if (i == 0) - { - write(columnName + " = ?"); - - } - else - { - write(", " + columnName + " = ?"); - } - - } //end for - - writeLine("\" + oldRecord.getWhereString() );\n"); - int index = -1; - - for (int i = 0 ; i < columnDescriptorList.size(); i++) - { - index = i+1; - ColumnDescriptor colDesc = (ColumnDescriptor) columnDescriptorList.get(i); - String columnName = colDesc.getName(); - //String sqlDataType = colDesc.getSqlTypeString(); - int sqlDataTypeInt = colDesc.getSqlTypeInt(); - String rsInterfaceType = getRSInterfaceTypeByInt(sqlDataTypeInt); - String firstChar = String.valueOf(columnName.charAt(0)); - - String newName = firstChar.toUpperCase() + columnName.substring(1); - - writeLine("set" + rsInterfaceType + "(updateStatement, " + index + ", newRecord.get" + newName + "());"); - - } //end for - - - writeLine("// get the number of records processed by the update"); - writeLine("returnCode = updateStatement.executeUpdate();\n"); - //writeLine("System.out.println(\"returnCode from updateRecord = \" + returnCode);"); - - writeLine("return returnCode;\n"); - - _indenter.decLevel(); - writeLine("} // end of updateRecord method\n"); - } - - catch(IOException ioe) - { - System.err.println( "createTableUpdate2(): Something went wrong trying to write " + ioe); - } - - } // end of createTableUpdate2 method - - private void createTableInsertOrUpdate(String tableName) - { - - try - { - _indenter.setLevel(0); - writeLine("//-----------------------------------------------------------------"); - writeLine("// insertOrUpdate() - this method is call with a " + tableName + "Record object."); - writeLine("// the number of records inserted or updated"); - writeLine("//-----------------------------------------------------------------"); - - _indenter.incLevel(); - writeLine("public int insertOrUpdate(" + tableName + "Record record) throws SQLException"); - writeLine("{"); - _indenter.incLevel(); - writeLine("int returnCode=-999;"); - writeLine("List recordList = select(record.getWhereString());\n"); - - writeLine("if (recordList.size() < 1)"); - writeLine("{"); - _indenter.incLevel(); - writeLine("returnCode = insert(record);"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("else"); - writeLine("{"); - _indenter.incLevel(); - - writeLine(tableName + "Record oldRecord = (" + tableName + "Record) recordList.get(0);"); - writeLine("returnCode = update(oldRecord, record);"); - _indenter.decLevel(); - writeLine("}"); - - writeLine("return returnCode;"); - - _indenter.decLevel(); - writeLine("} // end of insertOrUpdate() "); - } - catch(IOException ioe) - { - System.err.println( "createTableInsertOrUpdate(): Something went wrong trying to write " + ioe); - } - } //end of createTableInsertOrUpdate() - - - -// --------------------------------------------------------------- -// generate - calls all the methods to cause code to be generated -// --------------------------------------------------------------- - - - public void generate(String connectionURL, String preferredTableNameFilePath, - String dbName, String generatedPackageName, - String targetDir, String driverName) - { - - -// define an instance of a the IHFS database class - Database currentDatabase = new Database(); - - if (driverName != null) - { - currentDatabase.setDriverClassName(driverName); - } - - // call the method to connect to the database - currentDatabase.connect(connectionURL); - - // store the name of the package to which the generated classes will belong - _generatedPackageName = generatedPackageName; - - //store the path of the target directory for the generated files - _targetDirName = targetDir; - - //reads a list of Preferred table names from the directory indicated by - //schemaDirName - Map preferredTableNameMap = - getMapOfPreferredTableNames(preferredTableNameFilePath); - - // returns a list of the TableDescriptor which contains metadata about the - // tables and columns. This is the method that needs to be overridden when - // a database driver requires a custom way of extracting the metadata. - SchemaDescriber finder = new SchemaDescriber(currentDatabase); - - - _tableDescriptorList = - finder.getTableDescriptorList(preferredTableNameMap); - - - _indenter = new CodeIndenter(_indentString); - - //generate all the XXXRecord.java files - buildRecordSrcFiles(dbName); - - //generate all the XXXTable.jar files - buildTableSrcFiles(dbName); - - // disconnect from the database - currentDatabase.disconnect(); - - } //end generate - -// --------------------------------------------------------------- - -// --------------------------------------------------------------- - public static void main(String args[]) - { - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - - String connectionURL = null; - String preferredTableNameFilePath = null; - // the database name is passed in as the third command line argument - String dbName = null; - String packageName = null; - String targetDir = null; - String driverName = null; - - - if (args.length < 5) - { - System.err.println("Usage: java JDbGen connectionURL preferredTableNameFilePath dbName packageName targetDir [driverClassName]"); - } - else // the argument count looks good - { - connectionURL = args[0]; - preferredTableNameFilePath = args[1]; - - // the database name is passed in as the third command line argument - dbName = args[2]; - - packageName = args[3]; - if (packageName.equals("NONE")) - { - packageName = ""; - } - - targetDir = args[4]; - - if (args.length > 5) - { - driverName = args[5]; - - } - - // create a JDbGen object named dbgen - JDbGen dbgen = new JDbGen(); - - dbgen.generate(connectionURL, preferredTableNameFilePath, dbName, packageName, targetDir, driverName); - - System.out.println( "JDBGEN completed!"); - //timer.stop("JDbGen took"); - } - - return; - - } // end of main - -} // end of JDbGen class diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/SchemaDescriber.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/SchemaDescriber.java deleted file mode 100644 index d58806e1ee..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/SchemaDescriber.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Created on Sep 16, 2004 - * - * - */ -package ohd.hseb.dbgen; - - -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbType; - -/** - * @author GobsC - * - * This class encapsulates the discovery of the database schema for code generation purposes. - */ -public class SchemaDescriber -{ - - private Database _db; - private DbType _dbType = null; - - - // --------------------------------------------------------------------------------- - - public SchemaDescriber(Database database) - { - _db = database; - _dbType = _db.getDbType(); - } - //------------------------------------------------------------------------------------- - - public List getTableDescriptorList(Map preferredTableNameMap) - { - List descriptorList = null; - - - if (_dbType == DbType.Informix) - { - descriptorList = getInformixTableDescriptorList(preferredTableNameMap); - } - else //use the PostgreSQL way, which we assume to be more standard - { - descriptorList = getPostgreSQLTableDescriptorList(preferredTableNameMap); - } - - return descriptorList; - - } - - - //------------------------------------------------------------------------------------- - - - public List getPostgreSQLTableDescriptorList(Map preferredTableNameMap) - { - String header = "getPostgreSQLTableDescriptorList(): "; - List tdList = new ArrayList(); - - try - { - - // Database Meta Data object - DatabaseMetaData dbmd = _db.getConnection().getMetaData(); - - - //get all the info on regular tables - - boolean isView = false; - - // get the basic info on all the true tables - // added capitalized "TABLE" for postgresql - String[] tableTypesStringArray = { "table", "TABLE" }; - isView = false; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray, tdList); - - // get the basic info on all the views - String[] tableTypesStringArray2 = { "view", "VIEW" }; - // added capitalized "VIEW" for postgresql - isView = true; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray2, tdList); - - - - // create column descriptors for each table or view - for (int i = 0; i < tdList.size(); i++) - { - TableDescriptor tableDesc = (TableDescriptor) tdList.get(i); - String origCaseTableName = tableDesc.getOriginalCaseTableName(); - - // get the column info for all tables and views - // ResultSet rsForColumn = dbmd.getColumns("", "", tableName, - // "%"); - ResultSet rsForColumn = dbmd.getColumns(null, null, - origCaseTableName, "%"); - - // get the primary keys for this particular table - // and store them in a set - // ResultSet rsForKeys = dbmd.getPrimaryKeys("", "", tableName); - ResultSet rsForKeys = dbmd.getPrimaryKeys(null, null, - origCaseTableName); - - Set keySet = new HashSet(); - while (rsForKeys.next()) - { - String keyColumnName = rsForKeys.getString(4); - keySet.add(keyColumnName.toLowerCase()); - } - - if (keySet.size() > 0) - { - tableDesc.setHasPrimaryKey(true); - } - else - { - tableDesc.setHasPrimaryKey(false); - } - - - // for each column, make a corresponding ColumnDescriptor and - // add it to the list contained by the TableDescriptor - while (rsForColumn.next()) - { - String columnName = rsForColumn.getString(4).trim(); - - int sqlTypeInt = rsForColumn.getInt(5); - String sqlTypeString = rsForColumn.getString(6).trim(); - - boolean isNullable = false; - int nullableCode = rsForColumn.getInt(11); - if ( (nullableCode == DatabaseMetaData.columnNullable) || - (nullableCode == DatabaseMetaData.columnNullableUnknown) - ) - { - isNullable = true; - } - else - { - isNullable = false; - - /* - System.out.println("DatabaseMetaData.columnNoNulls = " + - DatabaseMetaData.columnNoNulls); - System.out.println("************ nullablecode = " + - nullableCode + " for " + columnName + - " in " + tableDesc.getName()); - */ - } - - - - //special case for PostgreSQL text field - // needed because it comes out as Types.VARCHAR - if (sqlTypeString.equals("text")) - { - sqlTypeInt = Types.LONGVARCHAR; - } - - int colSize = rsForColumn.getInt(7); - - - ColumnDescriptor colDesc = new ColumnDescriptor(); - colDesc.setName(columnName); - colDesc.setSqlTypeInt(sqlTypeInt); - colDesc.setSqlTypeString(sqlTypeString); - colDesc.setSize(colSize); - colDesc.setNullable(isNullable); - - // set the KeyColumn boolean field as appropriate - if (keySet.contains(columnName.toLowerCase())) - { - colDesc.setKeyColumn(true); - } - else - { - colDesc.setKeyColumn(false); - } - - // add the columnDescriptor to the tableDescriptor's list - tableDesc.getColumnDescriptorList().add(colDesc); - - - } //end while - - //System.out.println(header + "tableDesc = " + tableDesc); - - - } //end for - - - - } - catch (SQLException e) - { - System.out.println(this.getClass().getName() - + ".getTableDescriptorList():" + " Problem with SQL " - + e.getMessage()); - e.printStackTrace(); - } - return tdList; - - } //end getPostgreSQLTableDescriptorList - - //------------------------------------------------------------------------------------- - public List getInformixTableDescriptorList(Map preferredTableNameMap) - { - List tdList = new ArrayList(); - System.out.println("getInformixTableDescriptorList(): begin"); - try - { - - // Database Meta Data object - DatabaseMetaData dbmd = _db.getConnection().getMetaData(); - - - //get all the info on regular tables - - boolean isView = false; - - // get the basic info on all the true tables - String[] tableTypesStringArray = { "table"}; - isView = false; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray, tdList); - - // get the basic info on all the views - String[] tableTypesStringArray2 = { "view"}; - isView = true; - addToRawTableDescriptorList(dbmd, preferredTableNameMap, isView, - tableTypesStringArray2, tdList); - - - - // create column descriptors for each table or view - for (int i = 0; i < tdList.size(); i++) - { - TableDescriptor tableDesc = (TableDescriptor) tdList.get(i); - String origCaseTableName = tableDesc.getOriginalCaseTableName(); - - // get the column info for all tables and views - ResultSet rsForColumn = dbmd.getColumns("", "", origCaseTableName, "%"); - - // get the primary keys for this particular table - // and store them in a set - ResultSet rsForKeys = dbmd.getPrimaryKeys("", "", origCaseTableName); - - - Set keySet = new HashSet(); - while (rsForKeys.next()) - { - String keyColumnName = rsForKeys.getString(4); - keySet.add(keyColumnName.toLowerCase()); - } - - if (keySet.size() > 0) - { - tableDesc.setHasPrimaryKey(true); - } - else - { - tableDesc.setHasPrimaryKey(false); - } - - - - // for each column, make a corresponding ColumnDescriptor and - // add it to the list contained by the TableDescriptor - while (rsForColumn.next()) - { - String columnName = rsForColumn.getString(4).trim(); - - String sqlTypeString = rsForColumn.getString(6).trim(); - - int sqlTypeInt = rsForColumn.getInt(5); - - ColumnDescriptor colDesc = new ColumnDescriptor(); - colDesc.setName(columnName); - colDesc.setSqlTypeInt(sqlTypeInt); - colDesc.setSqlTypeString(sqlTypeString); - - - // set the KeyColumn boolean field as appropriate - if (keySet.contains(columnName.toLowerCase())) - { - colDesc.setKeyColumn(true); - } - else - { - colDesc.setKeyColumn(false); - } - - - // add the columnDescriptor to the tableDescriptor's list - tableDesc.getColumnDescriptorList().add(colDesc); - - } //end while - - - - } //end for - - } - catch (SQLException e) - { - System.out.println(this.getClass().getName() - + ".getTableDescriptorList():" + " Problem with SQL " - + e.getMessage()); - e.printStackTrace(); - } - return tdList; - - } //getInformixTableDescriptorList - - //------------------------------------------------------------------------------------- - - - // sub method of getTableDescriptorList - // broken out to reduce duplicate code for tables and views - private void addToRawTableDescriptorList(DatabaseMetaData dbmd, - Map preferredTableNameMap, - boolean isView, - String[] tableTypeNameArray, - List rawTableDescriptorList) - throws SQLException - { - //ResultSet rsForTables = dbmd.getTables("", "", "%", - // tableTypeNameArray ); - ResultSet rsForTables = dbmd.getTables(null, null, "%", - tableTypeNameArray); - - - - while (rsForTables.next()) - { - TableDescriptor tableDesc = new TableDescriptor(); - - String originalCaseName = rsForTables.getString(3); - String lowerCaseName = originalCaseName.toLowerCase(); - String mixedCaseName = (String) preferredTableNameMap.get(lowerCaseName); - if (mixedCaseName == null) - { - mixedCaseName = lowerCaseName; - } - - tableDesc.setOriginalCaseTableName(originalCaseName); - tableDesc.setName(mixedCaseName); - - /* - System.out.println("addToRawTableDescriptorList(): original case of table name = " + - originalCaseName + - " mixed case table name = " + - mixedCaseName); - */ - - tableDesc.setView(isView); - rawTableDescriptorList.add(tableDesc); - } - - rsForTables.close(); - - return; - } - - - - - - -} //end SchemaDescriber diff --git a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/TableDescriptor.java b/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/TableDescriptor.java deleted file mode 100644 index 7afc15a08d..0000000000 --- a/javaUtilities/hydro/ohd.db/src/ohd/hseb/dbgen/TableDescriptor.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Created on Aug 13, 2003 - * - * This class encapsulates information about a table, including a list - * of column descriptors. - */ -package ohd.hseb.dbgen; - -import java.util.*; - - -/** - * - */ -public class TableDescriptor -{ - private String _name = null; - private String _originalCaseTableName = null; - private boolean _isView = false; - private boolean _hasPrimaryKey = false; - - - private List _columnDescList = new ArrayList(); - private List _keyColumnDescList = null; - - // --------------------------------------------------------------------------------------------- - - public TableDescriptor() - { - - } - - // --------------------------------------------------------------------------------------------- - - public void setName(String name) - { - this._name = name; - } - - // --------------------------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - // --------------------------------------------------------------------------------------------- - - /** - * @param originalTableName The originalTableName to set. - */ - public void setOriginalCaseTableName(String originalTableName) - { - _originalCaseTableName = originalTableName; - } - // --------------------------------------------------------------------------------------------- - - /** - * @return Returns the originalTableName. - */ - public String getOriginalCaseTableName() - { - return _originalCaseTableName; - } - - // --------------------------------------------------------------------------------------------- - - public void setView(boolean isView) - { - this._isView = isView; - } - - // --------------------------------------------------------------------------------------------- - - public boolean isView() - { - return _isView; - } - - // --------------------------------------------------------------------------------------------- - - public void setHasPrimaryKey(boolean hasPrimaryKey) - { - _hasPrimaryKey = hasPrimaryKey; - } - - // --------------------------------------------------------------------------------------------- - - public boolean hasPrimaryKey() - { - return _hasPrimaryKey; - } - - // --------------------------------------------------------------------------------------------- - - - public List getColumnDescriptorList() - { - return _columnDescList; - } - - // --------------------------------------------------------------------------------------------- - - public List getKeyColumnDescriptorList() - { - - if (_keyColumnDescList == null) - { - _keyColumnDescList = new ArrayList(); - - // for each key column, check if it is a key column, and, if so, then insert it into the list - for (int i = 0 ; i < _columnDescList.size() ; i++) - { - ColumnDescriptor colDesc = (ColumnDescriptor) _columnDescList.get(i); - - if (colDesc.isKeyColumn()) - { - _keyColumnDescList.add(colDesc); - } - } - } - - return _keyColumnDescList; - } - - // --------------------------------------------------------------------------------------------- - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("Name = " + _name); - - buffer.append(" Original Case Table name = " + _originalCaseTableName + "\n"); - buffer.append(" Mixed Case Table name = " + _name + "\n"); - buffer.append(" Is View? = " + _isView + "\n"); - - buffer.append("Columns:\n"); - for (int i = 0; i < _columnDescList.size(); i++) - { - ColumnDescriptor descriptor = (ColumnDescriptor) _columnDescList - .get(i); - - buffer.append("Column " + i + "\n" + - descriptor.toString() + "\n"); - - } - - - return buffer.toString(); - } - - // --------------------------------------------------------------------------------------------- - -} //end class TableDescriptor diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/.classpath b/javaUtilities/hydro/ohd.dimensions_file_uploader/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/.project b/javaUtilities/hydro/ohd.dimensions_file_uploader/.project deleted file mode 100644 index 677a70de6e..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.dimensions_file_uploader - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.dimensions_file_uploader/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 07143b5b6c..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 08:41:34 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.dimensions_file_uploader/META-INF/MANIFEST.MF deleted file mode 100644 index f8ba1fd381..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/META-INF/MANIFEST.MF +++ /dev/null @@ -1,8 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Dimensions_file_uploader -Bundle-SymbolicName: ohd.dimensions_file_uploader -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/build.properties b/javaUtilities/hydro/ohd.dimensions_file_uploader/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/build.xml b/javaUtilities/hydro/ohd.dimensions_file_uploader/build.xml deleted file mode 100644 index 8c641b99e1..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/ohd.dimensions_file_uploader.ecl b/javaUtilities/hydro/ohd.dimensions_file_uploader/ohd.dimensions_file_uploader.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/scripts/run_dimensions_file_uploader b/javaUtilities/hydro/ohd.dimensions_file_uploader/scripts/run_dimensions_file_uploader deleted file mode 100644 index 39606517b1..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/scripts/run_dimensions_file_uploader +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/ksh -# file name: run_pvcs_file_uploader -# Created: 11/09/2006 - -# need to add a path to the jar file for this application -umask 006 - -export CLASSPATH=$CLASSPATH:/awips/hydroapps/PVCSFileQueue/dimensions_file_uploader.jar - -date=`date +%Y%m%d` -LOGFILE=log/upload_file_to_dimensions.log.${DR_DCS_NUMBER} - -machine_name=`uname -n` - -if [[ $machine_name != dx1-nhdr ]] -then - echo "You must be logged onto DX1-nhdr in order to use this script" - exit -fi -# Keeps the last 1200 lines of the log file - -LOGFILE=log/dimensions_file_uploader.log - -echo "\nIs this for a DR or DCS? Enter 'DR' for DR or 'DCS' for DCS: " -read Ans -Ans=$(echo $Ans | tr a-z A-Z) -while [[ $Ans != "DR" && $Ans != "DCS" ]]; do - echo "\n ERROR: Bad DR/DCS character identifier given! Please try again." - echo "\nIs this for a DR or DCS? Enter 'DR' for DR or 'DCS' for DCS:" - read Ans - Ans=$(echo $Ans | tr a-z A-Z) -done - -PREFIX=$Ans - - -echo "\nEnter the DR/DCS number (or hit enter to quit): " -read Ans -while [[ $Ans != [0-9] && - $Ans != [0-9][0-9] && - $Ans != [0-9][0-9][0-9] && - $Ans != [0-9][0-9][0-9][0-9] && - $Ans != [0-9][0-9][0-9][0-9][0-9] ]]; do - echo "\n ERROR: Bad DR/DCS number given! Please try again." - echo "\nEnter the DR/DCS number." - read Ans -done - -DRDCSNUM=$Ans - -LOGFILE=log/upload_file_to_dimensions.log.${DRDCSNUM} - -INPUT_DIR_NAME=$PREFIX"_"$DRDCSNUM - -echo "=================================================" >>$LOGFILE -echo "==== Starting run_dimensions_file_uploader at ${date}" >> $LOGFILE -echo "=================================================" >>$LOGFILE - -java ohd.hseb.dimensions_file_uploader.Dimensions_File_Uploader $INPUT_DIR_NAME 1>>$LOGFILE 2>&1 -#java ohd.hseb.dimensions_file_uploader.Dimensions_File_Uploader $INPUT_DIR_NAME diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/scripts/upload_file_to_dimensions b/javaUtilities/hydro/ohd.dimensions_file_uploader/scripts/upload_file_to_dimensions deleted file mode 100644 index 2846a47f35..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/scripts/upload_file_to_dimensions +++ /dev/null @@ -1,66 +0,0 @@ -# ============================================================================ -# pgm: upload_file_to_pvcs .. Uploads the file to PVCS using the PCMS command -# line tool -# -# use: upload_file_to_pvcs CI/UI command -# -# in: UI/CI command ..... The PCMS CI/UI command created by the PVCS_File_Uploader -# application in java. It is passed in by the java application -# -# -# -# ver: 20061109 -# ============================================================================ - type dd_help 1>/dev/null 2>&1 && . dd_help 2>/dev/null - - -# Keeps the last 1200 lines of the log file - -umask 006 - -#date=`date +%Y%m%d` -#LOGFILE=log/upload_file_to_pvcs.log.$date - -FILE_TO_BE_UPLOADED=$1 -DIM_USERNAME=$2 -DIM_PASSWORD=$3 -DR_DCS_NUMBER=$4 - -LOGFILE=log/upload_file_to_dimensions.log.${DR_DCS_NUMBER} - -# Shifting since argument 1 = file name to upload -# argument 2 = Dimensions username -# argument 3 = Dimensions password -# argument 4 = DR/DCS # -shift 4 - -#. /opt/pvcs/dimensions9_1/serena/changeman/dimensions/9.1/dmprofile On previous DX1 build -. /usr/local/dimensions/serena/serena/changeman/dimensions/9.1/dmprofile -export PCMSDB=AWIPS - -#PCMS_COMMAND_STRING="dmcli -user $DIM_USERNAME -pass "$DIM_PASSWORD" -host dim9 -con dim9 -dbname awips '$*'" -#LOG_PCMS_COMMAND_STRING="dmcli -user $DIM_USERNAME -pass ******** -host dim9 -con dim9 -dbname awips '$*'" -#PCMS_COMMAND_STRING="dmcli -user dsa -pass "password" -host dim9 -con dim9 -dbname awips '$*'" -PCMS_COMMAND_STRING="dmcli -user $DIM_USERNAME -pass "$DIM_PASSWORD" -host dim9 -dsn dim9 -dbname awips '$*'" -LOG_PCMS_COMMAND_STRING="dmcli -user $DIM_USERNAME -pass ******** -host dim9 -dbname awips '$*'" - - -echo "=================================================" >>$LOGFILE -echo "Uploading file: " $FILE_TO_BE_UPLOADED >>$LOGFILE -echo $LOG_PCMS_COMMAND_STRING >>$LOGFILE -echo "" >>$LOGFILE -eval $PCMS_COMMAND_STRING >>$LOGFILE 2>&1 -Status=$? -echo >> $LOGFILE -echo $PCMS_COMMAND_STRING - -# Check the status returned by the eval above. -if [[ $Status == 0 ]] -then - echo "SUCCESS: File $FILE_TO_BE_UPLOADED has been successfully uploaded at $(date)." >>$LOGFILE - exit 0 -else - echo "ERROR: Unable to upload the file $FILE_TO_BE_UPLOADED at $(date). Check log file $LOGFILE." >>$LOGFILE - exit 1 -fi -echo "=================================================" >>$LOGFILE diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/Dimensions_File_Uploader.java b/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/Dimensions_File_Uploader.java deleted file mode 100644 index 97418fef90..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/Dimensions_File_Uploader.java +++ /dev/null @@ -1,241 +0,0 @@ -package ohd.hseb.dimensions_file_uploader; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; - -public class Dimensions_File_Uploader -{ - private String _attributesDir = ""; - private String _fileToBeUploadedString = ""; - private String _drNumberString = ""; - private String _buildString = ""; - private String _username = null; - private String _password = null; - private static final String OB8_1_WORKSET = "AWIPS:OHD-OB8.1"; - private static final String OB8_2_WORKSET = "AWIPS:OHD-OB8.2"; - private static final String OB8_3_WORKSET = "AWIPS:OHD-OB8.3"; - private static final String OB8_1_1_WORKSET = "AWIPS:OHD-OB8.1.1"; - private String _workset = null; - - public Dimensions_File_Uploader( String attributesDir, String[] args ) - { - _attributesDir = attributesDir; - _drNumberString = args[ 0 ]; - - } - - private void processAttributesFileDir() - { - File attributesDirFile = new File( _attributesDir ); - File[] attributesFileArray = attributesDirFile.listFiles(); - getUserNamePassword(); - - for ( int i = 0; i < attributesFileArray.length; i++ ) - { - File attributeFile = attributesFileArray[ i ]; - - processAttributeFile( attributeFile ); - } - attributesDirFile.delete(); - } - - private void processAttributeFile( File attributeFile ) - { - FileReader fileReader = null; - BufferedReader bufferedReader = null; - String line = null; - String relativeFilePath = null; - String DRDCSNumberString = null; - String fileStatusString = null; - String commentsString = null; - String PCMScommandString = null; - - if ( ! attributeFile.isDirectory() ) // Checks if the local file is a directory - { - try - { - fileReader = new FileReader( attributeFile ); - bufferedReader = new BufferedReader( fileReader ); - - line = bufferedReader.readLine(); //read the relateive filepath of the source file - relativeFilePath = line.substring( 1 ); - _fileToBeUploadedString = relativeFilePath; - - line = bufferedReader.readLine(); //read the DR/DCS # - DRDCSNumberString = line; - - line = bufferedReader.readLine(); //read the status of the file. - fileStatusString = line; - - line = bufferedReader.readLine(); //read the build level - _buildString = line; - setWorkset(); - - line = bufferedReader.readLine(); //read the comments for the file - commentsString = line; - } - - catch (FileNotFoundException e) - { - - } - catch (IOException e) - { - - } - - if ( fileStatusString.equalsIgnoreCase( "OLD" ) ) - { - PCMScommandString = GetUpdateItemString(relativeFilePath, DRDCSNumberString, commentsString ); - } - else - { - PCMScommandString = GetCreateItemString(relativeFilePath, DRDCSNumberString, commentsString ); - } - - RunPCMSCommandLineTool( PCMScommandString, attributeFile, DRDCSNumberString ); - } - } - - private void setWorkset() - { - if ( _buildString.equalsIgnoreCase( "ob81" ) ) - { - _workset = OB8_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob811" ) ) - { - _workset = OB8_1_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob82" ) ) - { - _workset = OB8_2_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob83" ) ) - { - _workset = OB8_3_WORKSET; - } - } - private void RunPCMSCommandLineTool( String PCMSCommandString, File attributeFile, String DRDCSNumberString ) - { - String drDCSString = DRDCSNumberString.replaceAll( "AWIPS_", "" ); - String commandString = "/awips/hydroapps/PVCSFileQueue/upload_file_to_dimensions " + _fileToBeUploadedString + - " " + _username + " " + _password + " " + drDCSString + " " + PCMSCommandString; - String successfulFilePath = "/awips/hydroapps/PVCSFileQueue/filelist.success/" + _drNumberString; - String failureFilePath = "/awips/hydroapps/PVCSFileQueue/filelist.failed/" + _drNumberString; - File successfulFilePathFile = new File( successfulFilePath ); - File failureFilePathFile = new File( failureFilePath ); - - System.out.println( "commandString: " + commandString ); - System.out.println( "PCMSCommandString: " + PCMSCommandString ); - InputStream inputStream = null; - - try - { - Process process = Runtime.getRuntime().exec(commandString); - inputStream = new BufferedInputStream( process.getInputStream() ); - process.waitFor(); - int ic = inputStream.read(); - while (ic != -1 ) - { - char c = (char ) ic; - System.out.print( c ); - ic = inputStream.read(); - } - - - if ( process.exitValue() == 0 ) - { - if ( ! successfulFilePathFile.exists() ) - { - successfulFilePathFile.mkdir(); - } - attributeFile.renameTo( new File( successfulFilePath + "/" + attributeFile.getName() ) ); - } - else - { - if ( ! failureFilePathFile.exists() ) - { - failureFilePathFile.mkdir(); - } - attributeFile.renameTo( new File( failureFilePath + "/" + attributeFile.getName() ) ); - } - - } - - catch (InterruptedException e) - { - e.printStackTrace(); - } - catch (IOException e) { - e.printStackTrace(); - } - } - - private void getUserNamePassword() - { - PasswordDialog passwordDialog = new PasswordDialog(); - passwordDialog.requestPasswordByDialog( "Please enter your Dimensions username/password" ); - - _username = passwordDialog.getUserName(); - _password = passwordDialog.getPassword(); - } - - private String GetCreateItemString( String relativeString, String DRDCSNumberString, String commentsString ) - { - String CIString = null; - -// CI "AWIPS:.AAAA-DEVSRC;1" /PART="AWIPS:SOFTWARE.AAAA;1" /FILENAME="fs/hseb/ob81/ohd/whfs/TEST_EMPTY_FILE.txt" /KEEP -// /FORMAT="DEVSRC" /WORKSET="AWIPS:OHD-OB8.1" /CHANGE_DOC_IDS="AWIPS_DR_18222" - - CIString = "CI \"AWIPS:.AAAA-DEVSRC;1\" /PART=\"AWIPS:SOFTWARE.AAAA;1\" /FILENAME=\"" + relativeString + - "\" /STATUS=\"REVIEW\" /USER_FILENAME=\"" + relativeString + "\" /KEEP /COMMENT=\"" + commentsString + "\" /FORMAT=\"DEVSRC\" /WORKSET=\"" + _workset + "\" " + - " /CHANGE_DOC_IDS=\"" + DRDCSNumberString + "\""; - - return CIString; - } - - private String GetUpdateItemString( String relativeString, String DRDCSNumberString, String commentsString ) - { - String UIString = null; - -// UI AWIPS:; /FILENAME="fs/hseb/bld/devl_sys/cmd/update_ticket_no" /KEEP /CHANGE_DOC_IDS="AWIPS_DR_18222" -// /COMMENT="TESTING checkin script" /WORKSET="AWIPS:OHD-OB8.1" - - UIString = "UI AWIPS:; /FILENAME=\"" + relativeString + "\" /USER_FILENAME=\"" + relativeString + "\" /CHANGE_DOC_IDS=\"" + DRDCSNumberString + - "\" /STATUS=\"REVIEW\" /KEEP /COMMENT=\"" + commentsString + "\" /WORKSET=\"" + _workset + "\""; - - return UIString; - } - - public static String validateDir( String[] args ) - { - String inputDirString; - File inputDirStringFile = null; - - inputDirString = "/awips/hydroapps/PVCSFileQueue/filelist/" + args[ 0 ]; - - inputDirStringFile = new File( inputDirString); - - if ( ! inputDirStringFile.isDirectory() ) - { - System.out.println( "Invalid DR #" ); - System.exit( 0 ); - } - - return inputDirString; - } - - public static void main(String[] args) - { - String uploadDirString = Dimensions_File_Uploader.validateDir( args ); - Dimensions_File_Uploader dimensions_file_uploader = new Dimensions_File_Uploader( uploadDirString, args ); - dimensions_file_uploader.processAttributesFileDir(); - } - -} diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/LogViewer.java b/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/LogViewer.java deleted file mode 100644 index 86e9758bb7..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/LogViewer.java +++ /dev/null @@ -1,207 +0,0 @@ -package ohd.hseb.dimensions_file_uploader; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FilenameFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.LabeledComboBox; - -public class LogViewer extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private LabeledComboBox _logSelectionComboBox = new LabeledComboBox( "Select DR/DCS Log to View:" ); - - private String _logFileListDir = "/awips/hydroapps/PVCSFileQueue/log/"; - - private JTextArea _drInfoTextArea = new JTextArea(); - private JScrollPane _scrollPane = new JScrollPane( _drInfoTextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); - private Map _drNumToLogFileMap = new HashMap(); - - private LogSelectionCBListener _logSelectionCBListener = new LogSelectionCBListener(); - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _closeButton = new JButton( "Close" ); - - public LogViewer( JFrame frame ) - { - super( frame, "Log Viewer", true ); - } - - public void displayGUI() - { - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initSelectionComboBox(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - setPreferredSize( new Dimension( 1100, 768 ) ); - pack(); - setVisible( true ); - } - - protected void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _buttonPanel, _closeButton, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectionComboBox() - { - File filelistDir = new File( _logFileListDir ); - File[] filelistDirFileArray = filelistDir.listFiles( new LogFileFilter() ); - List drList = new ArrayList(); - - for ( int i = 0; i < filelistDirFileArray.length; i++ ) - { - File drDir = filelistDirFileArray[ i ]; - String fileName = getDRFromFileName( drDir.getName() ); - drList.add( fileName ); - _drNumToLogFileMap.put( fileName, drDir ); - } - Collections.sort( drList ); - _logSelectionComboBox.setComboBox( drList ); - } - - private String getDRFromFileName( String fileName ) - { - String drNum = null; - - drNum = fileName.substring( 30 ); - - return drNum; - } - - private void initFrameComponents() - { - _drInfoTextArea.setEditable( false ); -// _drInfoTextArea.setPreferredSize( new Dimension( 20, 50 ) ); - setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _logSelectionComboBox, 0, 0, 4, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _scrollPane, 0, 1, 4, 1, 1,10, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 2, 4, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void refreshLog() - { - FileReader fileReader = null; - BufferedReader bufferedReader = null; - File logFile = (File) _drNumToLogFileMap.get( _logSelectionComboBox.getSelectedCBItem() ); - StringBuffer stringBuffer = new StringBuffer(); - String line = null; - - try - { - fileReader = new FileReader( logFile ); - bufferedReader = new BufferedReader( fileReader ); - - line = bufferedReader.readLine(); - - while ( line != null ) - { - stringBuffer.append( line + "\n" ); - line = bufferedReader.readLine(); - } - - _drInfoTextArea.setText( stringBuffer.toString() ); - } - catch( FileNotFoundException f ) - { - - } - catch( IOException e ) - { - - } - - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _logSelectionComboBox.addComboBoxActionListener( _logSelectionCBListener ); - _closeButton.addActionListener( windowCloser ); - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - - private class LogSelectionCBListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - refreshLog(); - } - } - - public class LogFileFilter implements FilenameFilter - { - public boolean accept( File dir, String name ) - { - boolean valid = false; - if ( ( name.startsWith( "upload_file_to_dimensions.log.DR" ) ) || ( name.startsWith( "upload_file_to_dimensions.log.DCS" ) ) ) - { - valid = true; - } - return valid; - } - } - - public static void main(String[] args) - { - LogViewer logViewer = new LogViewer( new JFrame() ); -// dimensions_file_uploader.processAttributesFileDir(); - logViewer.initGUI(); - } - - -} diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/NewDimensions_File_Uploader.java b/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/NewDimensions_File_Uploader.java deleted file mode 100644 index bf63648814..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/NewDimensions_File_Uploader.java +++ /dev/null @@ -1,1188 +0,0 @@ -package ohd.hseb.dimensions_file_uploader; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JSplitPane; -import javax.swing.JTextArea; -import javax.swing.KeyStroke; -import javax.swing.border.BevelBorder; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.rfc.util.listpanels.JListPanel; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; - -public class NewDimensions_File_Uploader extends JFrame -{ - private static final String OB8_1_WORKSET = "AWIPS:OHD-OB8.1"; - private static final String OB8_2_WORKSET = "AWIPS:OHD-OB8.2"; - private static final String OB8_3_WORKSET = "AWIPS:OHD-OB8.3"; - private static final String OB9_0_WORKSET = "AWIPS:OHD-OB9"; - private static final String OB9_1_WORKSET = "AWIPS:OHD-OB9.1"; - private static final String OB9_2_WORKSET = "AWIPS:OHD-OB9.2"; - private static final String OB8_1_1_WORKSET = "AWIPS:OHD-OB8.1.1"; - private static final String OB8_2_1_WORKSET = "AWIPS:OHD-OB8.2.1"; - private static final String OB8_3_1_WORKSET = "AWIPS:OHD-OB8.3.1"; - private static final String OB9_0_1_WORKSET = "AWIPS:OHD-OB9.0.1"; - private static final String OB9_0_2_WORKSET = "AWIPS:OHD-OB9.0.2"; - - - private String _dimensionsFileQueueBaseDir = "/awips/hydroapps/PVCSFileQueue/"; - private String _queuedFileListDir = _dimensionsFileQueueBaseDir + "filelist/"; - private String _failedFileListDir = _dimensionsFileQueueBaseDir + "filelist.failed/"; - private String _successFileListDir = _dimensionsFileQueueBaseDir + "filelist.success/"; - private String _dimensionsMirrorBaseDir = "/awips/hydroapps/DimensionsMirror/ob83/"; - private String _attributesDir = ""; - private String _fileToBeUploadedString = ""; - private String _drNumberString = ""; - private String _buildString = ""; - private String _username = null; - private String _password = null; - private String _workset = null; - private boolean _drUploadSuccess = true; - private boolean _validUsernamePassword = false; - - private JPanel _queuedDRDCSPanel = new JPanel( new GridBagLayout() ); - private LabeledComboBox _DRDCSSelectionCB = new LabeledComboBox( "Select DR/DCS: " ); - private Container _frameContentPane = getContentPane(); - protected JListPanel _fileListPanel = null; - private JTextArea _drInfoTextArea = new JTextArea( 20, 30 ); - - private JPanel _failedDRPanel = new JPanel( new GridBagLayout() ); - private LabeledComboBox _failedDRDCSSelectionCB = new LabeledComboBox( "Select Failed DR/DCS: " ); - private JButton _resetButton = new JButton( "Reset DR/DCS" ); - private JListPanel _failedFileListPanel = null; - - private JPanel _successDRPanel = new JPanel( new GridBagLayout() ); - private LabeledComboBox _successDRDCSSelectionCB = new LabeledComboBox( "Select Successful DR/DCS: " ); - private JListPanel _successFileListPanel = null; - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _uploadButton = new JButton( "Upload Selected DR/DCS" ); - private JButton _resetGUIButton = new JButton( "Reset GUI" ); - private JButton _closeButton = new JButton( "Close" ); - - private ActionListener _queuedSelectionComboBoxListener = new QueuedSelectionComboBoxListener(); - private ActionListener _failedDRDCSSelectionComboBoxListener = new FailedDRDCSSelectionComboBoxListener(); - private ActionListener _successDRDCSSelectionComboBoxListener = new SuccessDRDCSSelectionComboBoxListener(); - private JMenuBar _menuBar = null; - - private JPanel _drInfoPanel = new JPanel( new GridBagLayout() ); - - private JSplitPane _splitPane = null; - private JSplitPane _leftSplitPane = null; - private JSplitPane _rightSplitPane = null; - - private JPopupMenu _popupMenu = new JPopupMenu(); - - private String _dateString = "July 14, 2008"; - private String _verString = "1.22"; - private String _versionString = "Application: Dimensions File Uploader" + - "\nVersion: " + _verString + - "\nDate: " + _dateString + - "\nDeveloped By: Your friendly neighborhood DSA"; - - public NewDimensions_File_Uploader() - { - setTitle( "Dimensions_File_Uploader - " + _dateString ); - setPreferredSize( new Dimension( 1200, 900 ) ); - } - - private void initGUI() - { - initDRList(); - updateQueuedFileJList(); - updateFailedSuccededFileJList( _failedDRDCSSelectionCB, true ); - updateFailedSuccededFileJList( _successDRDCSSelectionCB, false ); - initButtonPanel(); - initQueuedPanel(); - initFailedPanel(); - initSuccessPanel(); - initSplitPane(); - initFrameComponents(); - initMenuBar(); - refreshPopupMenu(); - addListeners(); - setJMenuBar( _menuBar ); - pack(); - setVisible( true ); - _splitPane.setDividerLocation( .50 ); // 50% - _leftSplitPane.setDividerLocation( .50 ); // 50% - _rightSplitPane.setDividerLocation( .50 ); // 50% - } - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - - menu = new JMenu( "File" ); - menu.setMnemonic( KeyEvent.VK_F ); - menu.getAccessibleContext().setAccessibleDescription( "Access File Menus" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Log Viewer" ); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_L, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Open Log Viewer" ); - menu.add( menuItem ); - menuItem.addActionListener( new LogViewerListener() ); - - menuItem = new JMenuItem("Exit Application"); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_E, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Exit the Application" ); - menu.add(menuItem); - menuItem.addActionListener( new WindowCloserListener() ); - - //acts as a separator to move the Help menu all the way to the right - menuItem = new JMenuItem(""); - menuItem.setEnabled(false); - _menuBar.add(menuItem); - - - // Help Menu - - menu = new JMenu("Help"); - menu.setMnemonic(KeyEvent.VK_H); - menu.getAccessibleContext().setAccessibleDescription( "Access help menu items." ); - _menuBar.add(menu); - - menuItem = new JMenuItem( "Common Dimensions Error Messages" ); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_E, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Display common Dimensions Error Messages" ); - menu.add( menuItem ); - menuItem.addActionListener( new DisplayDimensionsErrorMessages() ); - - menuItem = new JMenuItem("About..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_B, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Display the About Dialog." ); - menu.add(menuItem); - menuItem.addActionListener( new DisplayAboutDialog() ); - } - - private class DisplayAboutDialog implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - DialogHelper.displayMessageDialog( NewDimensions_File_Uploader.this, _versionString, "About" ); - } - } - - private class DisplayDimensionsErrorMessages implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - DialogHelper.displayMessageDialog( NewDimensions_File_Uploader.this, getDimensionsErrors(), "Common Dimensions Error Messages" ); - } - } - - private String getDimensionsErrors() - { - String errorString = null; - - errorString = "1128-You do not have the change document AWIPS_DR_##### in your pending list\n" + - "1128-You do not have the change document AWIPS_DCS_##### in your pending list\n" + - "The DR/DCS has not been delegated to the user. The GUI will show who the DR/DCS is assigned to. See who is designated as the “DEV MGR”.\n" + - "The user will have to contact this individual to have the DR/DCS delegated to them.\n\n" + - "2261-Error: You do not have a role to create this Work Set Directory\n" + - "2385-Error: The specified item is not in the workset AWIPS:OHD-OB9\n" + - "The attributes file for the specific failed file has the file designated as an OLD file.\n" + - "The attributes file will need to be modified so the file is designated as a NEW file.\n\n" + - "i.e.\n" + - "/fs/hseb/ob83/ohd/pproc_lib/inc/polygon_RFCW.h\n" + - "AWIPS_DR_20077\n" + - "OLD\n" + - "ob83\n" + - "becomes:\n" + - "/fs/hseb/ob83/ohd/pproc_lib/inc/polygon_RFCW.h\n" + - "AWIPS_DR_20077\n" + - "NEW\n" + - "ob83\n\n" + - "2210-Error: The Work Set filename is not unique in the Work Set Directory\n" + - "2229-Error: Filename ######### is already used for another Item in the same library, please specify a different filename\n" + - "The attributes file for the specific failed file has the file designated as a NEW file.\n" + - "The attributes file will need to be modified so the file is designated as an OLD file.\n\n" + - "Error: User authentication failed\n" + - "The username/password entered is incorrect.\n"; - - return errorString; - } - - - private void refreshPopupMenu() - { - _popupMenu.removeAll(); - - _popupMenu.setBorder( BorderFactory.createTitledBorder( BorderFactory.createBevelBorder( BevelBorder.RAISED, Color.GRAY, Color.BLACK ), "File Options" ) ); - JMenuItem menuItem = null; - - menuItem = new JMenuItem( "Compare to Dimensions version" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchXDiffListener() ); - menuItem = new JMenuItem( "View File" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new ViewFileListener() ); - menuItem = new JMenuItem( "Edit Attributes File" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new EditAttributesFileListener() ); - } - - private void initQueuedPanel() - { - _queuedDRDCSPanel.setBorder( BorderFactory.createTitledBorder( "Queued DR/DCSs" ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _queuedDRDCSPanel, _DRDCSSelectionCB, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _queuedDRDCSPanel, _uploadButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _queuedDRDCSPanel, _fileListPanel, 0, 1, 2, 1, 1, 5, GridBagConstraints.BOTH ); - } - - private void initFailedPanel() - { - _failedDRPanel.setBackground( Color.RED ); - _failedDRDCSSelectionCB.setBackground( Color.RED ); - - _failedDRPanel.setBorder( BorderFactory.createTitledBorder( "Failed DR/DCSs" ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _failedDRPanel, _failedDRDCSSelectionCB, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _failedDRPanel, _resetButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _failedDRPanel, _failedFileListPanel, 0, 1, 2, 1, 1, 10, GridBagConstraints.BOTH ); - } - - private void initSuccessPanel() - { - _successDRPanel.setBackground( Color.GREEN ); - _successDRDCSSelectionCB.setBackground( Color.GREEN ); - - _successDRPanel.setBorder( BorderFactory.createTitledBorder( "Succeeded DR/DCSs" ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _successDRPanel, _successDRDCSSelectionCB, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _successDRPanel, _successFileListPanel, 0, 1, 1, 1, 1, 10, GridBagConstraints.BOTH ); - } - - protected void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _buttonPanel, _resetGUIButton,0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _buttonPanel, _closeButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSplitPane() - { - _drInfoTextArea.setEditable( false ); - _drInfoTextArea.setPreferredSize( new Dimension( 20, 50 ) ); - -// _drInfoPanel.setBorder( BorderFactory.createTitledBorder( "DR Information (from Dimensions)" ) ); - - ComponentHelper.addPanelComponent( _drInfoPanel, _drInfoTextArea, 0, 0, 1, 1, 1, 1, GridBagConstraints.BOTH ); - - _leftSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, _queuedDRDCSPanel, _failedDRPanel ); - _rightSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, _drInfoPanel, _successDRPanel ); - _splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, _leftSplitPane, _rightSplitPane ); - } - - private void initFrameComponents() - { - setLayout( new GridBagLayout() ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _splitPane, 0, 0, 10, 1, 1, 10, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 4, 1, 2, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void launchLogViewer() - { - LogViewer logViewer = new LogViewer( this ); - logViewer.displayGUI(); - } - - private class LogViewerListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - launchLogViewer(); - } - } - - private void initDRList() - { - String[] noEntries = { "No Entries Found" }; - File filelistDir = new File( _queuedFileListDir ); - File[] filelistDirFileArray = filelistDir.listFiles(); - List drList = new ArrayList(); - - for ( int i = 0; i < filelistDirFileArray.length; i++ ) - { - File drDir = filelistDirFileArray[ i ]; - drList.add( drDir.getName() ); - } - Collections.sort( drList ); - if ( ! drList.isEmpty() ) - { - _DRDCSSelectionCB.setComboBox( drList ); - } - else - { - _DRDCSSelectionCB.setComboBox( noEntries ); - } - - - filelistDir = new File( _failedFileListDir ); - filelistDirFileArray = filelistDir.listFiles(); - drList = new ArrayList(); - - for ( int i = 0; i < filelistDirFileArray.length; i++ ) - { - File drDir = filelistDirFileArray[ i ]; - drList.add( drDir.getName() ); - } - Collections.sort( drList ); - if ( ! drList.isEmpty() ) - { - _failedDRDCSSelectionCB.setComboBox( drList ); - } - else - { - _failedDRDCSSelectionCB.setComboBox( noEntries ); - } - - filelistDir = new File( _successFileListDir ); - filelistDirFileArray = filelistDir.listFiles(); - drList = new ArrayList(); - - for ( int i = 0; i < filelistDirFileArray.length; i++ ) - { - File drDir = filelistDirFileArray[ i ] ; - drList.add( drDir.getName() ); - } - - Collections.sort( drList ); - if ( ! drList.isEmpty() ) - { - _successDRDCSSelectionCB.setComboBox( drList ); - } - else - { - _successDRDCSSelectionCB.setComboBox( noEntries ); - } - } - - private void updateDRList() - { - _DRDCSSelectionCB.removeComboBoxActionListener( _queuedSelectionComboBoxListener ); - _failedDRDCSSelectionCB.removeComboBoxActionListener( _failedDRDCSSelectionComboBoxListener ); - _successDRDCSSelectionCB.removeComboBoxActionListener( _successDRDCSSelectionComboBoxListener ); - - initDRList(); - - _DRDCSSelectionCB.addComboBoxActionListener( _queuedSelectionComboBoxListener ); - _failedDRDCSSelectionCB.addComboBoxActionListener( _failedDRDCSSelectionComboBoxListener ); - _successDRDCSSelectionCB.addComboBoxActionListener( _successDRDCSSelectionComboBoxListener ); - - _DRDCSSelectionCB.setSelectedIndex( 0 ); - _failedDRDCSSelectionCB.setSelectedIndex( 0 ); - _successDRDCSSelectionCB.setSelectedIndex( 0 ); - } - - - private void uploadDR() - { - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to upload " + _DRDCSSelectionCB.getSelectedCBItem(), "Upload DR/DCS" ) ) - { - processAttributesFileDir(); - } - } - - private void resetDRDCS() - { - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to reset " + _failedDRDCSSelectionCB.getSelectedCBItem(), "Reset DR/DCS" ) ) - { - String queuedFilePath = _queuedFileListDir + _failedDRDCSSelectionCB.getSelectedCBItem(); - String failedFilePath = _failedFileListDir + _failedDRDCSSelectionCB.getSelectedCBItem(); - File queuedDRFile = new File( queuedFilePath ); - File failedDRFile = new File( failedFilePath ); - - if ( ! queuedDRFile.exists() ) - { - boolean success = failedDRFile.renameTo( queuedDRFile ); - updateDRList(); - } - } - } - - private String getAttributeFile( String selectedFile ) - { - String returnString = _queuedFileListDir + _drNumberString; - - String attributeFileString = selectedFile.replace( "/", ":" ); - attributeFileString = attributeFileString.substring( 1 ); - returnString = returnString + "/" + attributeFileString + ".attributes"; - - return returnString; - } - - private void editAttributesFile() - { - String selectedFile = (String) _fileListPanel.getTheJList().getSelectedValue(); - - String attributesFileString = getAttributeFile( selectedFile ); - - String commandString = "nedit " + attributesFileString; - - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to edit the Attributes file?", "Edit Attributes File" ) ) - { - if ( attributesFileString != null ) - { - try - { - Process process = Runtime.getRuntime().exec( commandString ); - - process.waitFor(); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a file first", "View File Error" ); - } - } - } - - private void launchNEdit() - { - String selectedFile = (String) _fileListPanel.getTheJList().getSelectedValue(); - String queuedFileString = _dimensionsFileQueueBaseDir + selectedFile; - - String commandString = "nedit -read " + queuedFileString; - - if ( selectedFile != null ) - { - try - { - Process process = Runtime.getRuntime().exec(commandString); - - process.waitFor(); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a file first", "View File Error" ); - } - } - - - private void launchXDiff() - { - String selectedFile = (String) _fileListPanel.getTheJList().getSelectedValue(); - String queuedFileString = _dimensionsFileQueueBaseDir + selectedFile; - String dimensionsMirrorFileString = _dimensionsMirrorBaseDir + selectedFile; - String commandString = "xdiff " + queuedFileString + " " + dimensionsMirrorFileString; - - File queuedFile = new File( queuedFileString ); - File dimensionsMirrorFile = new File( dimensionsMirrorFileString ); - - if ( selectedFile != null ) - { - if ( ! dimensionsMirrorFile.exists() ) - { - DialogHelper.displayErrorDialog( this, selectedFile + " does not exist in the Dimensions Mirror", "Compare File Error" ); - } - else - { - try - { - Process process = Runtime.getRuntime().exec(commandString); - - process.waitFor(); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a file first", "Compare File Error" ); - } - } - - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _DRDCSSelectionCB.addComboBoxActionListener( _queuedSelectionComboBoxListener ); - _failedDRDCSSelectionCB.addComboBoxActionListener( _failedDRDCSSelectionComboBoxListener ); - _successDRDCSSelectionCB.addComboBoxActionListener( _successDRDCSSelectionComboBoxListener ); - _uploadButton.addActionListener( new UploadButtonListener() ); - _resetGUIButton.addActionListener( new ResetGUIButtonListener() ); - _closeButton.addActionListener( windowCloser ); - _resetButton.addActionListener( new ResetButtonListener() ); - _fileListPanel.getTheJList().addMouseListener( new FileListPanelListener() ); - } - - private class LaunchXDiffListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - launchXDiff(); - } - } - - private class ViewFileListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - launchNEdit(); - } - } - - private class EditAttributesFileListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - editAttributesFile(); - } - } - - private class FileListPanelListener extends MouseAdapter implements MouseListener - { - public void mousePressed(MouseEvent e) - { - maybeShowPopup(e); - } - - public void mouseReleased(MouseEvent e) {} - - private void maybeShowPopup(MouseEvent e) - { - if ( ( e.getClickCount() == 2 ) && ( e.getButton() == MouseEvent.BUTTON1 ) ) - { - launchNEdit(); - } - if ( e.isPopupTrigger() ) - { - refreshPopupMenu(); - _popupMenu.show( e.getComponent(), e.getX(), e.getY() ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - private class ResetButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - resetDRDCS(); - } - } - - private class ResetGUIButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _splitPane.setDividerLocation( .50 ); // 50% - _leftSplitPane.setDividerLocation( .50 ); // 50% - _rightSplitPane.setDividerLocation( .50 ); // 50% - } - } - - private class UploadButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - uploadDR(); - - if ( _validUsernamePassword ) - { - if ( _drUploadSuccess ) - { - DialogHelper.displayMessageDialog( null, "DR/DCS uploaded successfully.", "Upload DR/DCS" ); - } - else - { - DialogHelper.displayErrorDialog( null, "Error occurred while uploading DR/DCS. Check the log for more details.", "Upload DR/DCS" ); - } - } - _validUsernamePassword = false; - _drUploadSuccess = true; - updateDRList(); - } - } - - private void updateFailedSuccededFileJList( LabeledComboBox lcb, boolean failed ) - { - try - { - FileReader fileReader = null; - BufferedReader bufferedReader = null; - List fileList = new ArrayList(); - File drFile = null; - String headerString = null; - - String selectedItem = lcb.getSelectedCBItem(); - if ( failed ) - { - drFile = new File( _failedFileListDir + "/" + selectedItem ); - if ( selectedItem != null ) - { - headerString = "Files that failed for " + selectedItem; - } - else - { - headerString = "Files that failed"; - } - } - else - { - drFile = new File( _successFileListDir + "/" + selectedItem ); - headerString = "Files that succeeded for " + selectedItem; - } - - File[] attributesFileList = drFile.listFiles(); - - if ( attributesFileList != null ) - { - for ( int i = 0; i < attributesFileList.length; i++ ) - { - File attributeFile = attributesFileList[ i ]; - fileReader = new FileReader( attributeFile ); - bufferedReader = new BufferedReader( fileReader ); - String line = bufferedReader.readLine(); - fileList.add( line ); - } - } - - Color panelColor = null; - - if ( failed ) - { - panelColor = Color.RED; - } - else - { - panelColor = Color.GREEN; - } - - if ( failed ) - { - if ( _failedFileListPanel == null ) - { - _failedFileListPanel = new JListPanel( "", fileList, false, panelColor, - false, false, null ); - _failedFileListPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _failedFileListPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _failedFileListPanel.updateListData( fileList ); - _failedFileListPanel.refreshJList(); - } - } - else - { - if ( _successFileListPanel == null ) - { - _successFileListPanel = new JListPanel( "", fileList, false, panelColor, - false, false, null ); - _successFileListPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _successFileListPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _successFileListPanel.updateListData( fileList ); - _successFileListPanel.refreshJList(); - } - } - - refreshDrInfoPanel( selectedItem ); - } - -// _attributesDir = _queuedFileListDir + "/" + selectedItem; -// _drNumberString = selectedItem; - - catch ( FileNotFoundException f ) - { - } - catch ( IOException g ) - { - - } - } - - private String getStandardError( Process p ) - { - StreamDrainer drainer = new StreamDrainer(p.getErrorStream()); - return drainer.drain(); - - } - // ----------------------------------------------------------------------- - - private String getStandardOutput( Process p ) - { - StreamDrainer drainer = new StreamDrainer( p.getInputStream() ); - return drainer.drain(); - } - - public String getPaddedString( String str ) - { - String blankString = ""; - int strLength = 0; - - strLength = str.length(); - - for ( int i = 0; i < ( 9 - strLength); i++ ) - { - blankString += " "; - } - - return ( str + blankString ); - } - - - private void refreshDrInfoPanel( String drNumberString ) - { - InputStream inputStream = null; - - String commandString = " /awips/hydroapps/PVCSFileQueue/scripts/dc_drinfo " + drNumberString; - String line = null; - - try - { - Process process = Runtime.getRuntime().exec(commandString); -// BufferedReader input = new BufferedReader( new InputStreamReader( process.getInputStream() ) ); -// inputStream = new BufferedInputStream( process.getInputStream() ); -// String stdErrText = getStandardError( process ); - String stdOutText = getStandardOutput( process ); - - process.waitFor(); -// int ic = inputStream.read(); -// StringBuffer stringBuffer = new StringBuffer(); -// while (ic != -1 ) -// { -// char c = (char ) ic; -// stringBuffer.append( c ); -// System.out.print( c ); -// ic = inputStream.read(); -// } - _drInfoPanel.setBorder( BorderFactory.createTitledBorder( drNumberString + " DR Information (from Dimensions)" ) ); - - _drInfoTextArea.setText( stdOutText ); - _drInfoTextArea.setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - } - catch ( InterruptedException e ){} - catch ( IOException e ){} - catch ( IllegalMonitorStateException e ) - { - e.printStackTrace(); - } - } - - - private void updateQueuedFileJList() - { - try - { - FileReader fileReader = null; - BufferedReader bufferedReader = null; - List fileList = new ArrayList(); - String headerString = "Files that are currently queued up for " + _DRDCSSelectionCB.getSelectedCBItem(); - - String selectedItem = _DRDCSSelectionCB.getSelectedCBItem(); - File drFile = new File( _queuedFileListDir + "/" + selectedItem ); - File[] attributesFileList = drFile.listFiles(); - if ( attributesFileList != null ) - { - for ( int i = 0; i < attributesFileList.length; i++ ) - { - File attributeFile = attributesFileList[ i ]; - fileReader = new FileReader( attributeFile ); - bufferedReader = new BufferedReader( fileReader ); - String line = bufferedReader.readLine(); - fileList.add( line ); - } - } - if ( _fileListPanel == null ) - { - _fileListPanel = new JListPanel( "", fileList, false, Color.LIGHT_GRAY, - false, false, null ); - _fileListPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _fileListPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _fileListPanel.updateListData( fileList ); - _fileListPanel.refreshJList(); - } - - _attributesDir = _queuedFileListDir + "/" + selectedItem; - _drNumberString = selectedItem; - - refreshDrInfoPanel( selectedItem ); - } - catch ( FileNotFoundException f ) - { - } - catch ( IOException g ) - { - - } - } - - private class FailedDRDCSSelectionComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateFailedSuccededFileJList( _failedDRDCSSelectionCB, true ); - } - } - - private class SuccessDRDCSSelectionComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateFailedSuccededFileJList( _successDRDCSSelectionCB, false ); - } - } - - private class QueuedSelectionComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateQueuedFileJList(); - } - } - - private void processAttributesFileDir() - { - File attributesDirFile = new File( _attributesDir ); - File[] attributesFileArray = attributesDirFile.listFiles(); - - getUserNamePassword(); - - if ( _validUsernamePassword ) - { - for ( int i = 0; i < attributesFileArray.length; i++ ) - { - File attributeFile = attributesFileArray[ i ]; - - processAttributeFile( attributeFile ); - } - attributesDirFile.delete(); - updateDRList(); - } - else - { - DialogHelper.displayErrorDialog( this, "Invalid username/password", "Invalid Username/Password" ); - } - } - - private void processAttributeFile( File attributeFile ) - { - FileReader fileReader = null; - BufferedReader bufferedReader = null; - String line = null; - String relativeFilePath = null; - String DRDCSNumberString = null; - String fileStatusString = null; - String commentsString = null; - String PCMScommandString = null; - - if ( ! attributeFile.isDirectory() ) // Checks if the local file is a directory - { - try - { - fileReader = new FileReader( attributeFile ); - bufferedReader = new BufferedReader( fileReader ); - - line = bufferedReader.readLine(); //read the relateive filepath of the source file - relativeFilePath = line.substring( 1 ); - _fileToBeUploadedString = relativeFilePath; - - line = bufferedReader.readLine(); //read the DR/DCS # - DRDCSNumberString = line; - - line = bufferedReader.readLine(); //read the status of the file. - fileStatusString = line; - - line = bufferedReader.readLine(); //read the build level - _buildString = line; - setWorkset(); - - line = bufferedReader.readLine(); //read the comments for the file - commentsString = line; - } - - catch (FileNotFoundException e) - { - - } - catch (IOException e) - { - - } - - if ( fileStatusString.equalsIgnoreCase( "OLD" ) ) - { - PCMScommandString = GetUpdateItemString( relativeFilePath, DRDCSNumberString, commentsString ); - } - else - { - PCMScommandString = GetCreateItemString( relativeFilePath, DRDCSNumberString, commentsString ); - } - - RunPCMSCommandLineTool( PCMScommandString, attributeFile, DRDCSNumberString ); - } - } - - private void setWorkset() - { - if ( _buildString.equalsIgnoreCase( "ob81" ) ) - { - _workset = OB8_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob811" ) ) - { - _workset = OB8_1_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob82" ) ) - { - _workset = OB8_2_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob821" ) ) - { - _workset = OB8_2_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob83" ) ) - { - _workset = OB8_3_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob831" ) ) - { - _workset = OB8_3_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob90" ) ) - { - _workset = OB9_0_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob901" ) ) - { - _workset = OB9_0_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob902" ) ) - { - _workset = OB9_0_2_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob91" ) ) - { - _workset = OB9_1_WORKSET; - } - else if ( _buildString.equalsIgnoreCase( "ob92" ) ) - { - _workset = OB9_2_WORKSET; - } - else - { - _workset = "INVALID WORKSET"; - } - } - - private void RunPCMSCommandLineTool( String PCMSCommandString, File attributeFile, String DRDCSNumberString ) - { - String drDCSString = DRDCSNumberString.replaceAll( "AWIPS_", "" ); - String commandString = "/awips/hydroapps/PVCSFileQueue/upload_file_to_dimensions " + _fileToBeUploadedString + - " " + _username + " " + _password + " " + drDCSString + " " + PCMSCommandString; - String successfulFilePath = "/awips/hydroapps/PVCSFileQueue/filelist.success/" + _drNumberString; - String failureFilePath = "/awips/hydroapps/PVCSFileQueue/filelist.failed/" + _drNumberString; - File successfulFilePathFile = new File( successfulFilePath ); - File failureFilePathFile = new File( failureFilePath ); - - System.out.println( "commandString: " + commandString ); - System.out.println( "PCMSCommandString: " + PCMSCommandString ); - InputStream inputStream = null; - - try - { - Process process = Runtime.getRuntime().exec(commandString); - inputStream = new BufferedInputStream( process.getInputStream() ); - process.waitFor(); - int ic = inputStream.read(); - while (ic != -1 ) - { - char c = (char ) ic; - System.out.print( c ); - ic = inputStream.read(); - } - - - if ( process.exitValue() == 0 ) - { - if ( ! successfulFilePathFile.exists() ) - { - successfulFilePathFile.mkdir(); - } - attributeFile.renameTo( new File( successfulFilePath + "/" + attributeFile.getName() ) ); - } - else - { - if ( ! failureFilePathFile.exists() ) - { - failureFilePathFile.mkdir(); - } - attributeFile.renameTo( new File( failureFilePath + "/" + attributeFile.getName() ) ); - _drUploadSuccess = false; - } - - } - - catch (InterruptedException e) - { - e.printStackTrace(); - } - catch (IOException e) { - e.printStackTrace(); - } - } - - private void getUserNamePassword() - { - Process process = null; - String commandString = null; - - PasswordDialog passwordDialog = new PasswordDialog(); - passwordDialog.requestPasswordByDialog( "Please enter your Dimensions username/password" ); - - _username = passwordDialog.getUserName(); - _password = passwordDialog.getPassword(); - - commandString = "/awips/hydroapps/PVCSFileQueue/scripts/check_login_info " + _username + " " + _password; - try - { - process = Runtime.getRuntime().exec(commandString); - int exitValue = process.waitFor(); - - System.out.println( "ExitValue = " + exitValue ); - if ( exitValue == 0 ) - { - _validUsernamePassword = true; - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - catch( InterruptedException e ) - { - e.printStackTrace(); - } - } - - private String GetCreateItemString( String relativeString, String DRDCSNumberString, String commentsString ) - { - String CIString = null; - -// CI "AWIPS:.AAAA-DEVSRC;1" /PART="AWIPS:SOFTWARE.AAAA;1" /FILENAME="fs/hseb/ob81/ohd/whfs/TEST_EMPTY_FILE.txt" /KEEP -// /FORMAT="DEVSRC" /WORKSET="AWIPS:OHD-OB8.1" /CHANGE_DOC_IDS="AWIPS_DR_18222" - - CIString = "CI \"AWIPS:.AAAA-DEVSRC;1\" /PART=\"AWIPS:SOFTWARE.AAAA;1\" /FILENAME=\"" + relativeString + - "\" /STATUS=\"REVIEW\" /USER_FILENAME=\"" + relativeString + "\" /KEEP /COMMENT=\"" + commentsString + "\" /FORMAT=\"DEVSRC\" /WORKSET=\"" + _workset + "\" " + - " /CHANGE_DOC_IDS=\"" + DRDCSNumberString + "\""; - - return CIString; - } - - private String GetUpdateItemString( String relativeString, String DRDCSNumberString, String commentsString ) - { - String UIString = null; - -// UI AWIPS:; /FILENAME="fs/hseb/bld/devl_sys/cmd/update_ticket_no" /KEEP /CHANGE_DOC_IDS="AWIPS_DR_18222" -// /COMMENT="TESTING checkin script" /WORKSET="AWIPS:OHD-OB8.1" - - UIString = "UI AWIPS:; /FILENAME=\"" + relativeString + "\" /USER_FILENAME=\"" + relativeString + "\" /CHANGE_DOC_IDS=\"" + DRDCSNumberString + - "\" /STATUS=\"REVIEW\" /KEEP /COMMENT=\"" + commentsString + "\" /WORKSET=\"" + _workset + "\""; - - return UIString; - } - - public static void main(String[] args) - { - NewDimensions_File_Uploader dimensions_file_uploader = new NewDimensions_File_Uploader(); - dimensions_file_uploader.initGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/PasswordDialog.java b/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/PasswordDialog.java deleted file mode 100644 index efc8df0084..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/PasswordDialog.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Created on Aug 29, 2003 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.dimensions_file_uploader; - -import javax.swing.*; - - -/** - * @author Chip Gobs - * - * This class lets the user request a password and obscures it - * as it is being typed in. - */ -public class PasswordDialog -{ - - private String _userName = null; - private String _password = null; - - //--------------------------------------------------- - - public PasswordDialog() - { - - } - //--------------------------------------------------- - - public void setUserName(String userName) - { - _userName = userName; - } - - public String getUserName() - { - return _userName; - } - - public void setPassword(String password) - { - _password = password; - } - - public String getPassword() - { - return _password; - } - - //--------------------------------------------------- - - - public boolean requestPasswordByDialog(String textMessage) - { - String password = null; - JTextField userNameField = new JTextField(""); - JPasswordField passwordField = new JPasswordField(""); - - Object[] messageObjectArray = - { textMessage, - "User Name:", userNameField, - "Password:", passwordField - }; - - //_userName = JOptionPane.showInputDialog(null, messageObjectArray); - - - JOptionPane optionPane = new JOptionPane(); - - optionPane.setMessage( messageObjectArray ); - - optionPane.setMessageType( JOptionPane.QUESTION_MESSAGE ); - - JDialog dialog = optionPane.createDialog( null, "Password" ); - - dialog.show(); - - dialog.dispose(); - - - _userName = new String(userNameField.getText()); - _password = new String(passwordField.getPassword()); - - - - return true; - } - - - - //--------------------------------------------------- - public static void main(String[] args) - { - - PasswordDialog dialog = new PasswordDialog(); - - dialog.requestPasswordByDialog("Please enter your username and password, dude!"); - - System.out.println("username = " + dialog.getUserName()); - System.out.println("password = " + dialog.getPassword()); - - } - - - // --------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/StreamDrainer.java b/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/StreamDrainer.java deleted file mode 100644 index d61b651739..0000000000 --- a/javaUtilities/hydro/ohd.dimensions_file_uploader/src/ohd/hseb/dimensions_file_uploader/StreamDrainer.java +++ /dev/null @@ -1,84 +0,0 @@ -package ohd.hseb.dimensions_file_uploader; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; - -public class StreamDrainer implements Runnable -{ - private InputStream _inputStream; - private StringBuffer _buffer = null; - // ------------------------------------------------------------------------------------ - - public StreamDrainer(InputStream inputStream) - { - _inputStream = inputStream; - _buffer = new StringBuffer(); - } -// ------------------------------------------------------------------------------------ - - - public void run() - { - try - { - drainInputStream(_inputStream); - } - catch (Exception e) - { - e.printStackTrace(); - } - - } -// ------------------------------------------------------------------------------------ - - public String drain() - { - Thread thread = new Thread(this); - thread.start(); - - - while ( thread.isAlive() ) - { - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException e ){} - } - - return getString(); - } - -// ------------------------------------------------------------------------------------ - - public String getString() - { - return _buffer.toString(); - } - - // ------------------------------------------------------------------------------------ - - private void drainInputStream(InputStream stream) throws IOException - { - String header = "StreamDrainer.drainInputStream(): "; - StringWriter stringWriter = new StringWriter(); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - String s = null; - - while ((s = reader.readLine()) != null) - { - // stringWriter.write(s + "\n"); - _buffer.append(s + "\n"); - //System.out.println(header + s + "\n"); - } - - stringWriter.flush(); - - return; - } - - -} diff --git a/javaUtilities/hydro/ohd.fcstservice/.classpath b/javaUtilities/hydro/ohd.fcstservice/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.fcstservice/.project b/javaUtilities/hydro/ohd.fcstservice/.project deleted file mode 100644 index 068e9f068a..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.fcstservice - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.fcstservice/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.fcstservice/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bbd411e11c..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:29:27 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.fcstservice/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.fcstservice/META-INF/MANIFEST.MF deleted file mode 100644 index 69693f61d5..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Fcstservice -Bundle-SymbolicName: ohd.fcstservice -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.db;bundle-version="1.0.0", - ohd.common;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.fcstservice/build.properties b/javaUtilities/hydro/ohd.fcstservice/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.fcstservice/build.xml b/javaUtilities/hydro/ohd.fcstservice/build.xml deleted file mode 100644 index 41d8b44ee8..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.fcstservice/ohd.fcstservice.ecl b/javaUtilities/hydro/ohd.fcstservice/ohd.fcstservice.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.fcstservice/scripts/start_fcstservice b/javaUtilities/hydro/ohd.fcstservice/scripts/start_fcstservice deleted file mode 100644 index d936e86157..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/scripts/start_fcstservice +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/ksh - -# File name: start_fcstservice -# Author : Ram Varma - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS -. $RUN_FROM_DIR/../../set_hydro_env - -#LHVM_LOG=$LHVM_LOG_DIR/fcstservice - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/fcstservice.jar - -#Execute Lhvm -xterm -T "fcstservice" -iconic \ --e $SYS_JAVA_DIR/bin/java ohd.hseb.fcstservice.LhvmApplicationWindow $JDBCURL & diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/DataServicesGlobals.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/DataServicesGlobals.java deleted file mode 100644 index b6b4c1af96..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/DataServicesGlobals.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.util.ArrayList; - -public class DataServicesGlobals //This is a singleton class -{ - private static int count = 0; - private static DataServicesGlobals dataServicesGlobals = null; - private static String missingRepresentation = "-"; - - public static ArrayList dataServiceObservers = null; - public static ArrayList dataDetermObservers = null; - public static ArrayList dataWatSupObservers = null; - public static ArrayList dataEnsembleObservers = null; - - private DataServicesGlobals() - { - } - - public static synchronized DataServicesGlobals getSingleInstanceOfDataServicesGlobals() - { - if(dataServicesGlobals == null) - { - dataServicesGlobals = new DataServicesGlobals(); - } - - dataServiceObservers = new ArrayList(); - dataDetermObservers = new ArrayList(); - dataWatSupObservers = new ArrayList(); - dataEnsembleObservers = new ArrayList(); - - return dataServicesGlobals; - } - - public String getMissingRepresentation() { - return missingRepresentation; - } - - public void setMissingRepresentation(String missingRepresentation) { - DataServicesGlobals.missingRepresentation = missingRepresentation; - } - - public synchronized void incrementCount() - { - count++; - } - - public synchronized void decrementCount() - { - count--; - } - public synchronized int getCount() - { - return count; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/FcstDataDetermWindow.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/FcstDataDetermWindow.java deleted file mode 100644 index 7adfc096b4..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/FcstDataDetermWindow.java +++ /dev/null @@ -1,1323 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.util.*; -import java.awt.*; -import java.awt.event.*; - -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.text.*; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.*; -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.util.gui.*; - -public class FcstDataDetermWindow implements Subject -{ - private DataServicesGlobals dataServicesGlobals = null; - private java.util.List lhvmRowDataList = null; - private LhvmDataManager lhvmDataManager = null; - private LhvmLogger lhvmLogger = null; - private JTableManager jtm = null; - private JFrame lhvm = null; - - private FcstPtDetermJTableRowData selectedFcstPtDetermJTableRowData = null; - private ArrayList selectedFcstPtDetermJTableRowsDataList = null; - - private JTextField locationTextField = null; - private JComboBox snowMethodTextField = null; - private JComboBox hydrolTextField = null; - private JComboBox hydraulTextField = null; - private JComboBox issueCriteriaTextField = null; - private JComboBox floodTextField = null; - private JComboBox droughtTextField = null; - private JComboBox horizonTextField = null; - private JTextField qpfTextField = null; - private JTextField qtfTextField = null; - private JTextField qzfTextField = null; - private JComboBox normalTextField = null; - private JTextField upstreamSegTextField = null; - private JComboBox reservoirModelTextField = null; - private JComboBox genMethodTextField = null; - private JTextField consumptiveUseTextField = null; - private JTextField channelLossTextField = null; - private JTextField varUsageTextField = null; - private JTextField numElevZonesTextField = null; - - private JButton insertButton = null; - private JButton deleteButton = null; - private JButton clearButton = null; - private JButton closeButton = null; - private JButton refreshButton = null; - - private JTextField stationSearchTextField = null; - - private JScrollPane tableScrollPane = null; - private JPanel tableScrollPanePanel = null; - - private DateTextField implDateTextField = null; - private DateTextField webDateTextField = null; - - private int numRows; - private JLabel numRowsLabel = null; - private JTextArea consoleTextArea = null; - private int origNumRows; - - private java.util.List lhvmRowDataList1 = null; - private java.util.List lhvmRowDataList2 = null; - private java.util.List lhvmRowDataList3 = null; - private java.util.List lhvmRowDataList4 = null; - private java.util.List lhvmRowDataList5 = null; - private java.util.List lhvmRowDataList7 = null; - private java.util.List lhvmRowDataList8 = null; - private java.util.List lhvmRowDataList9 = null; - - private String str1[] = null; - private String str2[] = null; - private String str3[] = null; - private String str4[] = null; - private String str5[] = null; - private String str7[] = null; - private String str8[] = null; - private String str9[] = null; - - private ArrayList observers = null; - - private JButton filterOptionsButton; - - public void addObserver(Observer observer) - { - if(observers != null) - { - observers.add(observer); - } - } - public void removeObserver(Observer observer) - { - if(observers != null) - { - observers.remove(observer); - } - } - - public void letKnowOfChanges() - { - if(observers != null) - { - for(int i=0;i= 0 && !upstreamSegTextField.getText().equals("XXXXX")) || - (qpfTextField.getText().length() >= 0 && !qpfTextField.getText().equals("-")) || - (numElevZonesTextField.getText().length() >= 0 && !numElevZonesTextField.getText().equals("1"))) - { - activateClearButton(); - either++; - } - if(qtfTextField.getText().length() > 0 || qzfTextField.getText().length() > 0) - { - activateClearButton(); - either++; - } - if(either == 0) - { - deActivateClearButton(); - } - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtDetermJTableRowsDataList != null && selectedFcstPtDetermJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtDetermJTableRowsDataList != null && selectedFcstPtDetermJTableRowsDataList.size() == 1) - { - selectedFcstPtDetermJTableRowData = (FcstPtDetermJTableRowData) selectedFcstPtDetermJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtDetermJTableRowsDataList != null && selectedFcstPtDetermJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtDetermJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtDetermJTableRowsDataList.size() == 1) - { - selectedFcstPtDetermJTableRowData = (FcstPtDetermJTableRowData) selectedFcstPtDetermJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtDetermJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtDetermJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - int numRowsTemp = -1; - String currentLidFromRowsInsideLoop = null; - String currentHydrolMethodFromRowsInsideLoop = null; - String currentHydraulMethodFromRowsInsideLoop = null; - String currentSnowMethodFromRowsInsideLoop = null; - String currentIssueCritFromRowsInsideLoop = null; - String currentUpstreamSegFromRowsInsideLoop = null; - String currentReservoirModelFromRowsInsideLoop = null; - int currentHoursQpfFromRowsInsideLoop; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtDetermRecord record = new FcstPtDetermRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - Object[] options = { "YES", "NO" }; - - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - record.setSnow_method(str4[snowMethodTextField.getSelectedIndex()]); - record.setFrequpd_normal(str5[normalTextField.getSelectedIndex()]); - record.setFrequpd_flood(str5[floodTextField.getSelectedIndex()]); - record.setFrequpd_drought(str5[droughtTextField.getSelectedIndex()]); - record.setUpstream_seg(upstreamSegTextField.getText().toUpperCase()); - record.setReservoir_model(str7[reservoirModelTextField.getSelectedIndex()]); - record.setFcst_gen_method(str8[genMethodTextField.getSelectedIndex()]); - record.setFcst_horizon(str9[horizonTextField.getSelectedIndex()]); - if(consumptiveUseTextField.getText().length() > 0 && !consumptiveUseTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setConsumptive_use(consumptiveUseTextField.getText()); - } - else - { - record.setConsumptive_use("N"); - } - if(varUsageTextField.getText().length() > 0 && !varUsageTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setVar_usage(varUsageTextField.getText()); - } - else - { - record.setVar_usage("N"); - } - if(channelLossTextField.getText().length() > 0 && !channelLossTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setChannel_loss(channelLossTextField.getText()); - } - else - { - record.setChannel_loss("N"); - } - try - { - if(numElevZonesTextField.getText().length() > 0) - { - if(Short.valueOf(numElevZonesTextField.getText().trim()) > 0) - { - record.setNum_elev_zones(Short.valueOf(numElevZonesTextField.getText().trim())); - } - else - { - JOptionPane.showMessageDialog(null, "'Num Elev Zones' should be '1' or greater. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Elev Zones text box; It must be a number. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - try - { - if(qpfTextField.getText().length() > 0) - { - record.setHours_qpf(Short.valueOf(qpfTextField.getText().trim())); - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the QPF text box; It must be a number. Aborting insert."); - return; - } - try - { - if(qtfTextField.getText().length() > 0 && !qtfTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setHours_qtf(Short.valueOf(qtfTextField.getText().trim())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the QTF text box; It must be a number. Aborting insert."); - return; - } - try - { - if(qzfTextField.getText().length() > 0 && !qzfTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setHours_qzf(Short.valueOf(qzfTextField.getText().trim())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the QZF text box; It must be a number. Aborting insert."); - return; - } - record.setHydrol_method(str2[hydrolTextField.getSelectedIndex()]); - record.setHydraul_method(str3[hydraulTextField.getSelectedIndex()]); - if(record.getHydraul_method().equalsIgnoreCase("None")) - { - if(!record.getLid().equalsIgnoreCase(record.getUpstream_seg()) && !record.getUpstream_seg().equalsIgnoreCase("xxxxx")) - { - JOptionPane.showMessageDialog(null, "Routing Method can be 'None' only if LID and Upstream Segment are the same or Upstream Segment is 'XXXXX'. Aborting insert."); - return; - } - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } - record.setDef_issue_crit(str1[issueCriteriaTextField.getSelectedIndex()]); -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - - lhvmRowDataList = lhvmDataManager.readDataFromPtDeterm(); - numRows = lhvmRowDataList.size(); - - int success = lhvmDataManager.insertOrUpdateDetermTable(record); - - //lhvmRowDataList = lhvmDataManager.readDataFromPtDeterm(); - numRowsTemp = lhvmRowDataList.size(); - - if(success != -1) - { - getSelectedRows(); - if(selectedFcstPtDetermJTableRowsDataList.size() == 1 && ((numRows+1) == numRowsTemp)) - { - record = new FcstPtDetermRecord(); - String lid = ((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getLid(); - record.setLid(lid); - record.setHydrol_method(((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getHydrolMethod()); - record.setHydraul_method(((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getHydraulMethod()); - record.setDef_issue_crit(((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getIssueCriteria()); - record.setSnow_method(((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getSnowMethod()); - record.setUpstream_seg(((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getUpstreamSeg()); - record.setReservoir_model(((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getReservoirModel()); - record.setHours_qpf((short) (((FcstPtDetermJTableRowData)selectedFcstPtDetermJTableRowsDataList.get(0)).getQpf())); - lhvmDataManager.deleteFromDetermTable(record); - - appendToConsoleMessageReplace(locationTextField.getText()); - } - else if(selectedFcstPtDetermJTableRowsDataList.size() == 1 && numRows == numRowsTemp) - { - appendToConsoleMessageReplace(locationTextField.getText()); - } - else if(selectedFcstPtDetermJTableRowsDataList.size() == 0 && ((numRows+1) == numRowsTemp)) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtDeterm(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - - for(i=0;i= 0) - { - jtm.selectRows(rowIndex[0], rowIndex[0]); - } - letKnowOfChanges(); - } - } - - private class RefreshActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - lhvmRowDataList = lhvmDataManager.readDataFromPtDeterm(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - jtm.refreshDisplay(); - deActivateDeleteButton(); - deActivateClearButton(); - deActivateSaveButton(); - clearForm(); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - } - } - - private class DeleteActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int i, size; - origNumRows = lhvmRowDataList.size(); - size = selectedFcstPtDetermJTableRowsDataList.size(); - Object[] options = { "YES", "NO" }; - int yes_or_no = JOptionPane.showOptionDialog(null, "Are you sure to delete row(s)?", "About To Delete Rows!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - else - { - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i= 0 && !upstreamSegTextField.getText().equals("XXXXX")) || - (numElevZonesTextField.getText().length() >= 0 && !numElevZonesTextField.getText().equals("1"))) - { - activateClearButton(); - either++; - } - if(numMonClimTextField.getText().length() > 0 || numDayHydTextField.getText().length() > 0) - { - activateClearButton(); - either++; - } - if(either == 0) - { - deActivateClearButton(); - } - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtEnsembleJTableRowsDataList != null && selectedFcstPtEnsembleJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList != null && selectedFcstPtEnsembleJTableRowsDataList.size() == 1) - { - selectedFcstPtEnsembleJTableRowData = (FcstPtEnsembleJTableRowData) selectedFcstPtEnsembleJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList != null && selectedFcstPtEnsembleJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtEnsembleJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList.size() == 1) - { - selectedFcstPtEnsembleJTableRowData = (FcstPtEnsembleJTableRowData) selectedFcstPtEnsembleJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtEnsembleJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtEnsembleJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - int numRowsTemp = -1; - String currentLidFromRowsInsideLoop = null; - String currentHydrolMethodFromRowsInsideLoop = null; - String currentHydraulMethodFromRowsInsideLoop = null; - String currentSnowMethodFromRowsInsideLoop = null; - String currentFcstTypeFromRowsInsideLoop = null; - String currentFlowTypeFromRowsInsideLoop = null; - String currentUpstreamSegFromRowsInsideLoop = null; - String currentReservoirModelFromRowsInsideLoop = null; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtESPRecord record = new FcstPtESPRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - Object[] options = { "YES", "NO" }; - - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - if(!externalDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !externalDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setExternal_date(DbTimeHelper.getLongTimeFromDateString(externalDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setExternal_date(Long.MIN_VALUE); - } - record.setFrequpd_normal(str6[normalTextField.getSelectedIndex()]); - record.setFrequpd_flood(str6[floodTextField.getSelectedIndex()]); - record.setFrequpd_drought(str6[droughtTextField.getSelectedIndex()]); - record.setPost_processor(str7[postProcessingTextField.getSelectedIndex()]); - record.setUpstream_seg(upstreamSegTextField.getText().toUpperCase()); - record.setReservoir_model(str9[reservoirModelTextField.getSelectedIndex()]); - record.setFcst_horizon(str10[horizonTextField.getSelectedIndex()]); - if(consumptiveUseTextField.getText().length() > 0 && !consumptiveUseTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setConsumptive_use(consumptiveUseTextField.getText()); - } - else - { - record.setConsumptive_use("N"); - } - if(varUsageTextField.getText().length() > 0 && !varUsageTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setVar_usage(varUsageTextField.getText()); - } - else - { - record.setVar_usage("N"); - } - if(channelLossTextField.getText().length() > 0 && !channelLossTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setChannel_loss(channelLossTextField.getText()); - } - else - { - record.setChannel_loss("N"); - } - try - { - if(numElevZonesTextField.getText().length() > 0) - { - if(Short.valueOf(numElevZonesTextField.getText().trim()) > 0) - { - record.setNum_elev_zones(Short.valueOf(numElevZonesTextField.getText().trim())); - } - else - { - JOptionPane.showMessageDialog(null, "'Num Elev Zones' should be '1' or greater. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - } - else - { - record.setNum_elev_zones(Short.MIN_VALUE); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Elev Zones text box; It must be a number. Aborting insert."); - numElevZonesTextField.setText("1"); - return; - } - try - { - if(numMonClimTextField.getText().length() > 0 && !numMonClimTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setNummonclim(Short.valueOf(numMonClimTextField.getText().trim())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Mon Clim text box; It must be a number. Aborting insert."); - return; - } - try - { - if(numDayHydTextField.getText().length() > 0 && !numDayHydTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setNumdayhyd(Short.valueOf(numDayHydTextField.getText().trim())); - } - else - { - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Num Day Hyd text box; It must be a number. Aborting insert."); - return; - } - record.setHydrol_method(str4[hydrolTextField.getSelectedIndex()]); - record.setHydraul_method(str5[hydraulTextField.getSelectedIndex()]); - if(record.getHydraul_method().equalsIgnoreCase("None")) - { - if(!record.getLid().equalsIgnoreCase(record.getUpstream_seg()) && !record.getUpstream_seg().equalsIgnoreCase("xxxxx")) - { - JOptionPane.showMessageDialog(null, "Routing Method can be 'None' only if LID and Upstream Segment are the same or Upstream Segment is 'XXXXX'. Aborting insert."); - return; - } - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } - record.setSnow_method(str3[snowMethodTextField.getSelectedIndex()]); - record.setFlowtype(str2[flowTypeTextField.getSelectedIndex()]); - record.setFcsttype(str1[fcstTypeTextField.getSelectedIndex()]); -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - - lhvmRowDataList = lhvmDataManager.readDataFromPtEnsemble(); - numRows = lhvmRowDataList.size(); - - int success = lhvmDataManager.insertOrUpdateEnsembleTable(record); - - //lhvmRowDataList = lhvmDataManager.readDataFromPtEnsemble(); - numRowsTemp = lhvmRowDataList.size(); - - if(success != -1) - { - getSelectedRows(); - if(selectedFcstPtEnsembleJTableRowsDataList.size() == 1 && ((numRows+1) == numRowsTemp)) - { - record = new FcstPtESPRecord(); - String lid = ((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getLid(); - record.setLid(lid); - record.setHydrol_method(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getHydrolMethod()); - record.setHydraul_method(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getHydraulMethod()); - record.setSnow_method(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getSnowMethod()); - record.setFcsttype(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getFcstType()); - record.setFlowtype(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getFlowType()); - record.setUpstream_seg(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getUpstreamSeg()); - record.setReservoir_model(((FcstPtEnsembleJTableRowData)selectedFcstPtEnsembleJTableRowsDataList.get(0)).getReservoirModel()); - lhvmDataManager.deleteFromEnsembleTable(record); - - appendToConsoleMessageReplace(locationTextField.getText()); - } - else if(selectedFcstPtEnsembleJTableRowsDataList.size() == 1 && numRows == numRowsTemp) - { - appendToConsoleMessageReplace(locationTextField.getText()); - } - else if(selectedFcstPtEnsembleJTableRowsDataList.size() == 0 && ((numRows+1) == numRowsTemp)) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtEnsemble(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - - for(i=0;i= 0) - { - jtm.selectRows(rowIndex[0], rowIndex[0]); - } - letKnowOfChanges(); - } - } - - - private class DeleteActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int i, size; - origNumRows = lhvmRowDataList.size(); - size = selectedFcstPtEnsembleJTableRowsDataList.size(); - Object[] options = { "YES", "NO" }; - int yes_or_no = JOptionPane.showOptionDialog(null, "Are you sure to delete row(s)?", "About To Delete Rows!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - else - { - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0 || drainageAreaTextField.getText().length() > 0 || exceedProbTextField.getText().length() > 0) - { - activateClearButton(); - either++; - } - if(either == 0) - { - deActivateClearButton(); - } - - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtServiceJTableRowsDataList != null && selectedFcstPtServiceJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtServiceJTableRowsDataList != null && selectedFcstPtServiceJTableRowsDataList.size() == 1) - { - selectedFcstPtServiceJTableRowData = (FcstPtServiceJTableRowData) selectedFcstPtServiceJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtServiceJTableRowsDataList != null && selectedFcstPtServiceJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtServiceJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtServiceJTableRowsDataList.size() == 1) - { - selectedFcstPtServiceJTableRowData = (FcstPtServiceJTableRowData) selectedFcstPtServiceJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtServiceJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtServiceJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - String currentLidFromRowsInsideLoop = null; - int i, null_or_not = 0; - rowIndex[0] = -1; - - FcstPtServiceRecord record = new FcstPtServiceRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - record.setService_type(str1[serviceTypeTextField.getSelectedIndex()]); - record.setVerif_resp_type(str2[verifRespTypeTextField.getSelectedIndex()]); - try - { - if(floodThersholdTextField.getText().length() > 0 && !floodThersholdTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setFlood_thres(Double.parseDouble(floodThersholdTextField.getText().trim())); - } - else - { - record.setFlood_thres(Double.POSITIVE_INFINITY); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Flood Threshold text box; It must be a number. Aborting insert."); - return; - } - try - { - if(!drainageAreaTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setDrainage_area(Double.parseDouble(drainageAreaTextField.getText().trim())); - } - else - { - record.setDrainage_area(Double.POSITIVE_INFINITY); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Drainage Area text box; It must be a number. Aborting insert."); - return; - } - try - { - if(exceedProbTextField.getText().length() > 0 && !exceedProbTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setExceed_prob(Short.parseShort(exceedProbTextField.getText().trim())); - } - else - { - record.setExceed_prob(Short.MIN_VALUE); - null_or_not = 1; - } - } - catch(NumberFormatException ne) - { - JOptionPane.showMessageDialog(null, "Not a valid value in the Exceed Probability text box; It must be a number. Aborting insert."); - return; - } - Object[] options = { "YES", "NO" }; - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - if(!startDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !startDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setAnal_start_date(DbTimeHelper.getLongTimeFromDateString(startDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setAnal_start_date(Long.MIN_VALUE); - } - if(!endDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !endDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setAnal_end_date(DbTimeHelper.getLongTimeFromDateString(endDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setAnal_end_date(Long.MIN_VALUE); - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - int success = lhvmDataManager.insertOrUpdateServiceTable(record); - if(success != -1) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtService(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - for(i=0;i= 0) - { - jtm.selectRows(rowIndex[0], rowIndex[0]); - } - letKnowOfChanges(); - } - } - - - private class DeleteActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int i, size; - origNumRows = lhvmRowDataList.size(); - size = selectedFcstPtServiceJTableRowsDataList.size(); - Object[] options = { "YES", "NO" }; - int yes_or_no = JOptionPane.showOptionDialog(null, "Are you sure to delete row(s)?", "About To Delete Rows!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - else - { - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - activateClearButton(); - } - else - { - deActivateClearButton(); - } - if(locationTextField.getText().length() > 0) - { - activateSaveButton(); - activateClearButton(); - } - else - { - deActivateSaveButton(); - } - } - - public void buttonsActivateWhenSearched() - { - if(selectedFcstPtWatsupJTableRowsDataList != null && selectedFcstPtWatsupJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtWatsupJTableRowsDataList != null && selectedFcstPtWatsupJTableRowsDataList.size() == 1) - { - selectedFcstPtWatsupJTableRowData = (FcstPtWatSupJTableRowData) selectedFcstPtWatsupJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtWatsupJTableRowsDataList != null && selectedFcstPtWatsupJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedFcstPtWatsupJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - else if(selectedFcstPtWatsupJTableRowsDataList.size() == 1) - { - selectedFcstPtWatsupJTableRowData = (FcstPtWatSupJTableRowData) selectedFcstPtWatsupJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - activateSaveButton(); - activateClearButton(); - } - else if(selectedFcstPtWatsupJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - deActivateSaveButton(); - deActivateClearButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedFcstPtWatsupJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class SaveActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int[] rowIndex = new int[1]; - int numRowsTemp = -1; - String currentLidFromRowsInsideLoop = null; - String currentwatsupMethodFromRowsInsideLoop = null; - String currentwatsupCoordAgencyFromRowsInsideLoop = null; - String currentNormalFromRowsInsideLoop = null; - String currentPeriodReqFromRowsInsideLoop = null; - String currentWatsupCritFromRowsInsideLoop = null; - int i, null_or_not = 0; - rowIndex[0] = -1; - FcstPtWatSupRecord record = new FcstPtWatSupRecord(); - record.setLid(locationTextField.getText().toUpperCase()); - Object[] options = { "YES", "NO" }; - if(!implDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !implDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setImpl_date(DbTimeHelper.getLongTimeFromDateString(implDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setImpl_date(Long.MIN_VALUE); - } - if(!webDateTextField.getText().equalsIgnoreCase("yyyy-mm-dd") && !webDateTextField.getText().equalsIgnoreCase(dataServicesGlobals.getMissingRepresentation())) - { - record.setWeb_date(DbTimeHelper.getLongTimeFromDateString(webDateTextField.getText())); - } - else - { - null_or_not = 1; - record.setWeb_date(Long.MIN_VALUE); - } - if(customerDescTextField.getText().length() > 0 && !customerDescTextField.getText().equals(lhvmDataManager.getMissingRepresentation())) - { - record.setCustomer_desc(customerDescTextField.getText()); - } - else - { - null_or_not = 1; - } - if(null_or_not == 1) - { - int yes_or_no = JOptionPane.showOptionDialog(null, "At least one field has no value defined...continue??", "Not All Fields Defined!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - null_or_not = 0; - } - record.setFrequpd_normal(str4[normalTextField.getSelectedIndex()]); - record.setWatsup_method(str5[watsupMethodTextField.getSelectedIndex()]); - record.setWatsup_coord_agency(str3[watsupCoordAgencyTextField.getSelectedIndex()]); - record.setWatsup_crit(str2[watsupCritTextField.getSelectedIndex()]); - record.setPeriod_req(str1[periodReqTextField.getSelectedIndex()]); - record.setWatsup_resp_agency(str6[respAgencyTextField.getSelectedIndex()]); -// lhvmLogger.log(" Delete record"+ record.toString()); - LhvmDataManager.databaseMessage = null; - - lhvmRowDataList = lhvmDataManager.readDataFromPtWatsup(); - numRows = lhvmRowDataList.size(); - - int success = lhvmDataManager.insertOrUpdateWatsupTable(record); - - //lhvmRowDataList = lhvmDataManager.readDataFromPtWatsup(); - numRowsTemp = lhvmRowDataList.size(); - - if(success != -1) - { - getSelectedRows(); - if(selectedFcstPtWatsupJTableRowsDataList.size() == 1 && ((numRows+1) == numRowsTemp)) - { - record = new FcstPtWatSupRecord(); - String lid = ((FcstPtWatSupJTableRowData)selectedFcstPtWatsupJTableRowsDataList.get(0)).getLid(); - record.setLid(lid); - record.setWatsup_method(((FcstPtWatSupJTableRowData)selectedFcstPtWatsupJTableRowsDataList.get(0)).getWatsupMethod()); - record.setWatsup_coord_agency(((FcstPtWatSupJTableRowData)selectedFcstPtWatsupJTableRowsDataList.get(0)).getWatsupCoordAgency()); - record.setFrequpd_normal(((FcstPtWatSupJTableRowData)selectedFcstPtWatsupJTableRowsDataList.get(0)).getNormal()); - record.setPeriod_req(((FcstPtWatSupJTableRowData)selectedFcstPtWatsupJTableRowsDataList.get(0)).getPeriodReq()); - record.setWatsup_crit(((FcstPtWatSupJTableRowData)selectedFcstPtWatsupJTableRowsDataList.get(0)).getWatsupCrit()); - lhvmDataManager.deleteFromWatsupTable(record); - - appendToConsoleMessageReplace(locationTextField.getText()); - } - else if(selectedFcstPtWatsupJTableRowsDataList.size() == 1 && numRows == numRowsTemp) - { - appendToConsoleMessageReplace(locationTextField.getText()); - } - else if(selectedFcstPtWatsupJTableRowsDataList.size() == 0 && ((numRows+1) == numRowsTemp)) - { - appendToConsoleMessageInsert(locationTextField.getText()); - } - } - else - { - JOptionPane.showMessageDialog(null, "Oops: Problem inserting, please check console"); - setDatabaseMessage(); - } - lhvmRowDataList = lhvmDataManager.readDataFromPtWatsup(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - jtm.refreshDisplay(); - - for(i=0;i= 0) - { - jtm.selectRows(rowIndex[0], rowIndex[0]); - } - letKnowOfChanges(); - } - } - - private class RefreshActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - lhvmRowDataList = lhvmDataManager.readDataFromPtWatsup(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - jtm.refreshDisplay(); - deActivateDeleteButton(); - deActivateClearButton(); - deActivateSaveButton(); - clearForm(); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - } - } - - private class DeleteActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int i, size; - origNumRows = lhvmRowDataList.size(); - size = selectedFcstPtWatsupJTableRowsDataList.size(); - Object[] options = { "YES", "NO" }; - int yes_or_no = JOptionPane.showOptionDialog(null, "Are you sure to delete row(s)?", "About To Delete Rows!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]); - if(yes_or_no == JOptionPane.NO_OPTION) - { - return; - } - else - { - for(i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - selectedServiceTableViewViewJTableRowData = (ServiceTableViewViewJTableRowData) selectedServiceTableViewViewJTableRowsDataList.get(0); - showCurrentRowData(); - } - else if(selectedServiceTableViewViewJTableRowsDataList == null) - { - lhvmRowDataList = lhvmDataManager.readDataFromPtServiceView(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - jtm.refreshDisplay(); - deActivateDeleteButton(); - clearForm(); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - } - } - - private void appendToConsoleMessage(String lid) - { - String valueToBeSet = new String(consoleTextArea.getText() + "\n" + "Exception getting number of entries from database for lid: " + lid + " "); - consoleTextArea.insert("", 0); - consoleTextArea.insert(valueToBeSet, 0); - } - - public LhvmApplicationWindow() - { - lhvmAppWindow = this; - dataServicesGlobals = DataServicesGlobals.getSingleInstanceOfDataServicesGlobals(); - dataServicesGlobals.incrementCount(); - - lhvm = new JFrame("Forecast Services"); - lhvm.setSize(1100, 780); - lhvm.setLocation(20,50); - - //Fix the dimensions of this window i.e. dis-allow window resizing - Dimension d = new Dimension(1195, 775); - new WindowResizingManager(lhvm, d, d); - - lhvm.setResizable(false); - //lhvm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - GridBagLayout gbl = new GridBagLayout(); - lhvm.setLayout(gbl); - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.HORIZONTAL; - - - JMenuBar menuBar = new JMenuBar(); - - JMenu fileMenu = new JMenu("File"); - menuBar.add(fileMenu); - //JMenuItem importItem = new JMenuItem("Import from file"); - //importItem.setEnabled(false); - //JMenuItem exportItem = new JMenuItem("Export to file"); - //exportItem.setEnabled(false); - closeItem = new JMenuItem("Close Application"); - //closeItem.addActionListener(ActionListener); - //fileMenu.add(importItem); - //fileMenu.add(exportItem); - fileMenu.add(closeItem); - closeItem.addActionListener(new MenuSelectActionListener()); - - setupTableMenu = new JMenu("Setup"); - fcstRefTablesItem = new JMenuItem("RefTables"); - fcstRefTablesItem.addActionListener(new MenuSelectActionListener()); - //stationsFilterOptionsItem.addActionListener(ActionListener); - setupTableMenu.add(fcstRefTablesItem); - - JMenu tablesMenu = new JMenu("ServiceTypes"); - menuBar.add(tablesMenu); - menuBar.add(setupTableMenu); - fcstPtServiceItem = new JMenuItem("Data Service"); - fcstPtWatsUpItem = new JMenuItem("Water Supply Forecast"); - fcstPtDetermItem = new JMenuItem("Deterministic Forecast"); - fcstPtESPItem = new JMenuItem("Ensemble Forecast"); - fcstPtServiceItem.addActionListener(new MenuSelectActionListener()); - fcstPtDetermItem.addActionListener(new MenuSelectActionListener()); - fcstPtESPItem.addActionListener(new MenuSelectActionListener()); - fcstPtWatsUpItem.addActionListener(new MenuSelectActionListener()); - //stationsFilterOptionsItem.addActionListener(ActionListener); - tablesMenu.add(fcstPtServiceItem); - tablesMenu.add(fcstPtWatsUpItem); - tablesMenu.add(fcstPtDetermItem); - tablesMenu.add(fcstPtESPItem); - - JMenu aboutMenu = new JMenu("Help"); - menuBar.add(aboutMenu); - aboutItem = new JMenuItem("About Forecast Services"); - aboutMenu.add(aboutItem); - aboutItem.addActionListener(new MenuSelectActionListener()); - - - // Install the menu bar in the frame - lhvm.setJMenuBar(menuBar); - - - - - - JLabel consoleLabel = new JLabel("-----Database Messages-----"); - consoleLabel.setForeground(Color.red); - consoleTextArea = new JTextArea(2,50); - - //Font font = new Font("Serif", Font.BOLD, 20); - //consoleTextArea.setFont(font); - consoleTextArea.setForeground(Color.green); - consoleTextArea.setBackground(Color.black); - consoleTextArea.setCaretColor(Color.red); - consoleTextArea.setBorder(BorderFactory.createEtchedBorder() ); - consoleTextArea.setLineWrap(true); - - - String[] columnsToBeDisplayed = {"Location ID","Name", "Stream", "State","County","Hsa"}; - lhvmLogger = new LhvmLogger(); - lhvmDataManager = LhvmDataManager.getSingleInstanceOfDataManager(jdbcUrl, lhvmLogger,dataServicesGlobals.getMissingRepresentation()); - java.util.List lhvmColumnDescriptorList = new ArrayList(); - lhvmRowDataList = lhvmDataManager.readDataFromPtServiceView(); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Location ID", true, 150, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Name", true, 250, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Stream", true, 200, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("State", true, 125, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("County", true, 200, "center")); - lhvmColumnDescriptorList.add(new JTableColumnDescriptor("Hsa", true, 125, "center")); - jtm = new ComplexJTableManager(lhvmColumnDescriptorList, lhvmRowDataList); - jtm.setDisplayableColumns(columnsToBeDisplayed, false, true); - jtm.setPreferredSizeForJScrollPane(new Dimension(1100, 500)); - jtm.addTableListener(new ServiceTableViewListSelectListener()); - tableScrollPane = jtm.getJScrollPane(); - //jtm.setTableToolTipText("str"); - tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(tableScrollPane); - - String tempStr = null; - if(LhvmDataManager.displayedMessageLhvmWindow != null) - { - tempStr = new String(LhvmDataManager.displayedMessageLhvmWindow); - } - LhvmDataManager.displayedMessageLhvmWindow = new StringBuffer(); - LhvmDataManager.displayedMessageLhvmWindow.append(LhvmDataManager.databaseMessage); - if(tempStr != null) - { - LhvmDataManager.displayedMessageLhvmWindow.append(tempStr); - } - consoleTextArea.insert(new String(LhvmDataManager.displayedMessageLhvmWindow), 0); - - // Get paragraph element - Element paragraph = consoleTextArea.getDocument().getDefaultRootElement(); - - // Get number of content elements - int contentCount = paragraph.getElementCount(); - - // Get index ranges for each content element. - // Each content element represents one line. - // Each line includes the terminating newline. - for (int i=0; i 1) - { - activateDeleteButton(); - clearForm(); - } - } - - public void buttonsActivateWhenSelected() - { - getSelectedRows(); - if(selectedServiceTableViewViewJTableRowsDataList.size() < 1) - { - deActivateDeleteButton(); - clearForm(); - } - else if(selectedServiceTableViewViewJTableRowsDataList.size() == 1) - { - selectedServiceTableViewViewJTableRowData = (ServiceTableViewViewJTableRowData) selectedServiceTableViewViewJTableRowsDataList.get(0); - showCurrentRowData(); - activateDeleteButton(); - } - else if(selectedServiceTableViewViewJTableRowsDataList.size() > 1) - { - activateDeleteButton(); - clearForm(); - } - } - - private void getSelectedRows() - { - selectedServiceTableViewViewJTableRowsDataList = (ArrayList) jtm.getSelectedRowsData(); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class MenuSelectActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - if(e.getSource().equals(fcstPtServiceItem)) - { - FcstDataServiceWindow fcstDataServiceWindow = new FcstDataServiceWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataServiceWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstPtWatsUpItem)) - { - FcstDataWatSupWindow fcstDataWatSupWindow = new FcstDataWatSupWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataWatSupWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstPtDetermItem)) - { - FcstDataDetermWindow fcstDataDetermWindow = new FcstDataDetermWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataDetermWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstPtESPItem)) - { - FcstDataEnsembleWindow fcstDataEnsembleWindow = new FcstDataEnsembleWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - fcstDataEnsembleWindow.addObserver(lhvmAppWindow); - } - else if(e.getSource().equals(fcstRefTablesItem)) - { - new ReferenceTablesWindow(jdbcUrl); - dataServicesGlobals.incrementCount(); - } - else if(e.getSource().equals(closeItem)) - { - System.exit(0); - } - else if(e.getSource().equals(aboutItem)) - { - JOptionPane.showMessageDialog(null, "Application: Forecast Services\n\n" + - "Version: Awips Release OB9.0\n\n" + "Date: May 1'st, 2008\n\n" + - "Developed by: National Weather Service,\n Office of Hydrologic development, \n Hydrology Laboratory\n\n", - "Forecast Services", JOptionPane.INFORMATION_MESSAGE); - } - } - } - - private class DeleteActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - } - } - - private class RefreshActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - lhvmRowDataList = lhvmDataManager.readDataFromPtServiceView(); - jtm.setChangedAllRowDataList(lhvmRowDataList); - jtm.refreshDisplay(); - deActivateDeleteButton(); - clearForm(); - numRows = lhvmRowDataList.size(); - numRowsLabel.setText(numRows + " Rows"); - } - } - - private class CloseActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - operationCloseWindow(); - } - } - - private class ServiceTableViewListSelectListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent e) - { - buttonsActivateWhenSelected(); - } - } - - private class SearchTextTypedActionListener implements KeyListener - { - String currentLidFromRowsInsideLoop; - int[] rowIndices; - int index; - - public void init() - { - index = -1; - rowIndices = new int[lhvmRowDataList.size()]; - - for(int i=0;i 0 && lhvmRowDataList.size() > 0) - { - int count = 0, i; - for(i=0;i 0) - { - for(int i=0;i < serviceTableViewInfmList.size(); i++) - { - serviceTableViewRecord = (ServiceTableViewRecord) serviceTableViewInfmList.get(i); - ServiceTableViewViewJTableRowData rowData = new ServiceTableViewViewJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(serviceTableViewRecord.getLid().toString()); - if(serviceTableViewRecord.getState() != null) - { - rowData.setState(serviceTableViewRecord.getState().toString()); - } - else - { - rowData.setState(missingRepresentation); - } - if(serviceTableViewRecord.getCounty() != null) - { - rowData.setCounty(serviceTableViewRecord.getCounty().toString()); - } - else - { - rowData.setCounty(missingRepresentation); - } - if(serviceTableViewRecord.getName() != null) - { - rowData.setLocName(serviceTableViewRecord.getName().toString()); - } - else - { - rowData.setLocName(missingRepresentation); - } - if(serviceTableViewRecord.getStream() != null) - { - rowData.setStream(serviceTableViewRecord.getStream().toString()); - } - else - { - rowData.setStream(missingRepresentation); - } - if(serviceTableViewRecord.getHsa() != null) - { - rowData.setHsa(serviceTableViewRecord.getHsa().toString()); - } - else - { - rowData.setHsa(missingRepresentation); - } - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the Service table view"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the Service table view"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Service table view"; - } - return dataList; - } - - public List readDataFromPtService() - { - List serviceTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtServiceTable serviceTable = new FcstPtServiceTable(db); - FcstPtServiceRecord serviceTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - serviceTableInfmList = serviceTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(serviceTableInfmList != null && serviceTableInfmList.size() >0) - { - for(int i=0;i < serviceTableInfmList.size(); i++) - { - serviceTableRecord = (FcstPtServiceRecord) serviceTableInfmList.get(i); - FcstPtServiceJTableRowData rowData = new FcstPtServiceJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(serviceTableRecord.getLid()); - rowData.setServiceType(serviceTableRecord.getService_type()); - rowData.setVerifRespType(serviceTableRecord.getVerif_resp_type()); - if(serviceTableRecord.getFlood_thres() > Double.MIN_VALUE && serviceTableRecord.getFlood_thres() < Double.MAX_VALUE) - { - Double val = new Double(serviceTableRecord.getFlood_thres()); - rowData.setFloodTher(val); - } - else - { - rowData.setFloodTher(DbTable.getNullDouble()); - } - if(serviceTableRecord.getDrainage_area() > Double.MIN_VALUE && serviceTableRecord.getDrainage_area() < Double.MAX_VALUE) - { - Double val = new Double(serviceTableRecord.getDrainage_area()); - rowData.setDrainageArea(val); - } - else - { - rowData.setDrainageArea(DbTable.getNullDouble()); - } - if(serviceTableRecord.getExceed_prob() >= 0 && serviceTableRecord.getExceed_prob() <= 100) - { - Integer val1 = new Integer(serviceTableRecord.getExceed_prob()); - rowData.setExceedProb(val1); - } - else - { - rowData.setExceedProb(DbTable.getNullInt()); - } - if(DbTable.isNull(serviceTableRecord.getImpl_date()) || serviceTableRecord.getImpl_date() < Long.MIN_VALUE || serviceTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - //rowData.setImplDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getImpl_date())); - rowData.setImplDate(serviceTableRecord.getImpl_date()); - } - if(DbTable.isNull(serviceTableRecord.getWeb_date()) || serviceTableRecord.getWeb_date() < Long.MIN_VALUE || serviceTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - //rowData.setWebDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getWeb_date())); - rowData.setWebDate(serviceTableRecord.getWeb_date()); - } - if(DbTable.isNull(serviceTableRecord.getAnal_start_date()) || serviceTableRecord.getAnal_start_date() < Long.MIN_VALUE || serviceTableRecord.getAnal_start_date() > Long.MAX_VALUE) - { - rowData.setStartDate(DbTable.getNullLong()); - } - else - { - //rowData.setStartDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getAnal_start_date())); - rowData.setStartDate(serviceTableRecord.getAnal_start_date()); - } - if(DbTable.isNull(serviceTableRecord.getAnal_end_date()) || serviceTableRecord.getAnal_end_date() < Long.MIN_VALUE || serviceTableRecord.getAnal_end_date() > Long.MAX_VALUE) - { - rowData.setEndDate(DbTable.getNullLong()); - } - else - { - //rowData.setEndDate(DbTimeHelper.getDateStringFromLongTime(serviceTableRecord.getAnal_end_date())); - rowData.setEndDate(serviceTableRecord.getAnal_end_date()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in service table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Service table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Service table"; - } - return dataList; - } - - public List readDataFromPtDeterm() - { - List determTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtDetermTable determTable = new FcstPtDetermTable(db); - FcstPtDetermRecord determTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - determTableInfmList = determTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(determTableInfmList != null && determTableInfmList.size() >0) - { - for(int i=0;i < determTableInfmList.size(); i++) - { - determTableRecord = (FcstPtDetermRecord) determTableInfmList.get(i); - FcstPtDetermJTableRowData rowData = new FcstPtDetermJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(determTableRecord.getLid()); - rowData.setHydraulMethod(determTableRecord.getHydraul_method()); - rowData.setHydrolMethod(determTableRecord.getHydrol_method()); - rowData.setSnowMethod(determTableRecord.getSnow_method()); - rowData.setIssueCriteria(determTableRecord.getDef_issue_crit()); - rowData.setUpstreamSeg(determTableRecord.getUpstream_seg()); - rowData.setReservoirModel(determTableRecord.getReservoir_model()); - rowData.setGenMethod(determTableRecord.getFcst_gen_method()); - if(determTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(determTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(DbTable.getNullString()); - } - if(determTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(determTableRecord.getConsumptive_use().toString()); - } - else - { - rowData.setConsumptiveUse(DbTable.getNullString()); - } - if(determTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(determTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(DbTable.getNullString()); - } - if(determTableRecord.getNum_elev_zones() < Short.MIN_VALUE || determTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setNumElevZones(DbTable.getNullInt()); - } - else - { - rowData.setNumElevZones(determTableRecord.getNum_elev_zones()); - } - if(DbTable.isNull(determTableRecord.getImpl_date()) || determTableRecord.getImpl_date() < Long.MIN_VALUE || determTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(determTableRecord.getImpl_date()); - } - if(DbTable.isNull(determTableRecord.getWeb_date()) || determTableRecord.getWeb_date() < Long.MIN_VALUE || determTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(determTableRecord.getWeb_date()); - } - if(determTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(determTableRecord.getFrequpd_normal()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(determTableRecord.getFrequpd_flood()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - - if(determTableRecord.getVar_usage() != null) - { - rowData.setVarUsage(determTableRecord.getVar_usage()); - } - else - { - rowData.setVarUsage(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(determTableRecord.getFrequpd_drought()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(determTableRecord.getHours_qpf() < Integer.MIN_VALUE || determTableRecord.getHours_qpf() > Integer.MAX_VALUE) - { - rowData.setQpf(DbTable.getNullInt()); - } - else - { - rowData.setQpf(determTableRecord.getHours_qpf()); - } - if(determTableRecord.getHours_qtf() < Integer.MIN_VALUE || determTableRecord.getHours_qtf() > Integer.MAX_VALUE) - { - rowData.setQtf(DbTable.getNullInt()); - } - else - { - rowData.setQtf(determTableRecord.getHours_qtf()); - } - if(determTableRecord.getHours_qzf() < Integer.MIN_VALUE || determTableRecord.getHours_qzf() > Integer.MAX_VALUE) - { - rowData.setQzf(DbTable.getNullInt()); - } - else - { - rowData.setQzf(determTableRecord.getHours_qzf()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in determ table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Determ table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Determ table"; - } - return dataList; - } - - public List readReservoirsFromPtDeterm() - { - List determTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtDetermTable determTable = new FcstPtDetermTable(db); - FcstPtDetermRecord determTableRecord = null; - String whereClause = null; - - try - { - whereClause = "WHERE reservoir_model NOT IN ('None') order by lid"; - determTableInfmList = determTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(determTableInfmList != null && determTableInfmList.size() >0) - { - for(int i=0;i < determTableInfmList.size(); i++) - { - determTableRecord = (FcstPtDetermRecord) determTableInfmList.get(i); - FcstPtDetermJTableRowData rowData = new FcstPtDetermJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(determTableRecord.getLid().toString()); - rowData.setHydraulMethod(determTableRecord.getHydraul_method().toString()); - rowData.setHydrolMethod(determTableRecord.getHydrol_method().toString()); - rowData.setSnowMethod(determTableRecord.getSnow_method().toString()); - rowData.setIssueCriteria(determTableRecord.getDef_issue_crit().toString()); - rowData.setUpstreamSeg(determTableRecord.getUpstream_seg().toString()); - rowData.setReservoirModel(determTableRecord.getReservoir_model().toString()); - rowData.setGenMethod(determTableRecord.getFcst_gen_method().toString()); - if(determTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(determTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(DbTable.getNullString()); - } - if(determTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(determTableRecord.getConsumptive_use().toString()); - } - else - { - rowData.setConsumptiveUse(missingRepresentation); - } - if(determTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(determTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(missingRepresentation); - } - if(determTableRecord.getNum_elev_zones() < Short.MIN_VALUE || determTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setNumElevZones(DbTable.getNullInt()); - } - else - { - rowData.setNumElevZones(determTableRecord.getNum_elev_zones()); - } - if(DbTable.isNull(determTableRecord.getImpl_date()) || determTableRecord.getImpl_date() < Long.MIN_VALUE || determTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(determTableRecord.getImpl_date()); - } - if(DbTable.isNull(determTableRecord.getWeb_date()) || determTableRecord.getWeb_date() < Long.MIN_VALUE || determTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(determTableRecord.getWeb_date()); - } - if(determTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(determTableRecord.getFrequpd_normal()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(determTableRecord.getFrequpd_flood()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(determTableRecord.getVar_usage() != null) - { - rowData.setVarUsage(determTableRecord.getVar_usage()); - } - else - { - rowData.setVarUsage(DbTable.getNullString()); - } - if(determTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(determTableRecord.getFrequpd_drought()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(determTableRecord.getHours_qpf() < Integer.MIN_VALUE || determTableRecord.getHours_qpf() > Integer.MAX_VALUE) - { - rowData.setQpf(DbTable.getNullInt()); - } - else - { - rowData.setQpf(determTableRecord.getHours_qpf()); - } - if(determTableRecord.getHours_qtf() < Integer.MIN_VALUE || determTableRecord.getHours_qtf() > Integer.MAX_VALUE) - { - rowData.setQtf(DbTable.getNullInt()); - } - else - { - rowData.setQtf(determTableRecord.getHours_qtf()); - } - if(determTableRecord.getHours_qzf() < Integer.MIN_VALUE || determTableRecord.getHours_qzf() > Integer.MAX_VALUE) - { - rowData.setQzf(DbTable.getNullInt()); - } - else - { - rowData.setQzf(determTableRecord.getHours_qzf()); - } - dataList.add(rowData); - rowData.addAllCellsToMap(); - } - LhvmDataManager.databaseMessage = "Records found in determ table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Determ table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Determ table"; - } - return dataList; - } - - public List readDataFromPtWatsup() - { - List watsupTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtWatSupTable watsupTable = new FcstPtWatSupTable(db); - FcstPtWatSupRecord watsupTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - watsupTableInfmList = watsupTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupTableInfmList != null && watsupTableInfmList.size() > 0) - { - for(int i=0;i < watsupTableInfmList.size(); i++) - { - watsupTableRecord = (FcstPtWatSupRecord) watsupTableInfmList.get(i); - FcstPtWatSupJTableRowData rowData = new FcstPtWatSupJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(watsupTableRecord.getLid().toString()); - rowData.setNormal(watsupTableRecord.getFrequpd_normal().toString()); - rowData.setWatsupMethod(watsupTableRecord.getWatsup_method().toString()); - rowData.setWatsupCoordAgency(watsupTableRecord.getWatsup_coord_agency().toString()); - rowData.setPeriodReq(watsupTableRecord.getPeriod_req().toString()); - rowData.setWatsupCrit(watsupTableRecord.getWatsup_crit().toString()); - rowData.setRespAgency(watsupTableRecord.getWatsup_resp_agency().toString()); - if(watsupTableRecord.getCustomer_desc() != null) - { - rowData.setCustomerDesc(watsupTableRecord.getCustomer_desc().toString()); - } - else - { - rowData.setCustomerDesc(missingRepresentation); - } - if(DbTable.isNull(watsupTableRecord.getImpl_date()) || watsupTableRecord.getImpl_date() < Long.MIN_VALUE || watsupTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(watsupTableRecord.getImpl_date()); - } - if(DbTable.isNull(watsupTableRecord.getWeb_date()) || watsupTableRecord.getWeb_date() < Long.MIN_VALUE || watsupTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(watsupTableRecord.getWeb_date()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in Watsup table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Watsup table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Watsup table"; - } - return dataList; - } - - public List readDataFromPtEnsemble() - { - List ensembleTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtESPTable ensembleTable = new FcstPtESPTable(db); - FcstPtESPRecord ensembleTableRecord = null; - String whereClause = null; - - try - { - whereClause = "order by lid"; - ensembleTableInfmList = ensembleTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(ensembleTableInfmList != null && ensembleTableInfmList.size() >0) - { - for(int i=0;i < ensembleTableInfmList.size(); i++) - { - ensembleTableRecord = (FcstPtESPRecord) ensembleTableInfmList.get(i); - FcstPtEnsembleJTableRowData rowData = new FcstPtEnsembleJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(ensembleTableRecord.getLid().toString()); - rowData.setHydraulMethod(ensembleTableRecord.getHydraul_method().toString()); - rowData.setHydrolMethod(ensembleTableRecord.getHydrol_method().toString()); - rowData.setSnowMethod(ensembleTableRecord.getSnow_method().toString()); - rowData.setUpstreamSeg(ensembleTableRecord.getUpstream_seg().toString()); - rowData.setReservoirModel(ensembleTableRecord.getReservoir_model().toString()); - if(ensembleTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(ensembleTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(missingRepresentation); - } - if(ensembleTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(ensembleTableRecord.getConsumptive_use().toString()); - } - else - { - rowData.setConsumptiveUse(missingRepresentation); - } - if(ensembleTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(ensembleTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(missingRepresentation); - } - if(ensembleTableRecord.getPost_processor() != null) - { - rowData.setPostProcessing(ensembleTableRecord.getPost_processor().toString()); - } - else - { - rowData.setPostProcessing(missingRepresentation); - } - rowData.setFlowType(ensembleTableRecord.getFlowtype().toString()); - rowData.setFcstType(ensembleTableRecord.getFcsttype().toString()); - if(DbTable.isNull(ensembleTableRecord.getImpl_date()) || ensembleTableRecord.getImpl_date() < Long.MIN_VALUE || ensembleTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(ensembleTableRecord.getImpl_date()); - } - if(DbTable.isNull(ensembleTableRecord.getWeb_date()) || ensembleTableRecord.getWeb_date() < Long.MIN_VALUE || ensembleTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(ensembleTableRecord.getWeb_date()); - } - if(DbTable.isNull(ensembleTableRecord.getExternal_date()) || ensembleTableRecord.getExternal_date() < Long.MIN_VALUE || ensembleTableRecord.getExternal_date() > Long.MAX_VALUE) - { - rowData.setExternalDate(DbTable.getNullLong()); - } - else - { - rowData.setExternalDate(ensembleTableRecord.getExternal_date()); - } - if(ensembleTableRecord.getNum_elev_zones() < 0 || ensembleTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setNumElevZones(ensembleTableRecord.getNum_elev_zones()); - } - if(ensembleTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(ensembleTableRecord.getFrequpd_normal().toString()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(ensembleTableRecord.getFrequpd_flood().toString()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(ensembleTableRecord.getVar_usage() != null) - { - rowData.setVarUsage(ensembleTableRecord.getVar_usage()); - } - else - { - rowData.setVarUsage(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(ensembleTableRecord.getFrequpd_drought().toString()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(ensembleTableRecord.getNummonclim() < Integer.MIN_VALUE || ensembleTableRecord.getNummonclim() > Integer.MAX_VALUE) - { - rowData.setNumMonClim(DbTable.getNullInt()); - } - else - { - rowData.setNumMonClim(ensembleTableRecord.getNummonclim()); - } - if(ensembleTableRecord.getNumdayhyd() < Integer.MIN_VALUE || ensembleTableRecord.getNumdayhyd() > Integer.MAX_VALUE) - { - rowData.setNumDayHyd(DbTable.getNullInt()); - } - else - { - rowData.setNumDayHyd(ensembleTableRecord.getNumdayhyd()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in ensemble table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Ensemble table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Ensemble table"; - } - return dataList; - } - - public List readReservoirsFromPtEnsemble() - { - List ensembleTableInfmList = null; - List dataList = new ArrayList(); - - FcstPtESPTable ensembleTable = new FcstPtESPTable(db); - FcstPtESPRecord ensembleTableRecord = null; - String whereClause = null; - - try - { - whereClause = "WHERE reservoir_model NOT IN ('None') order by lid"; - ensembleTableInfmList = ensembleTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(ensembleTableInfmList != null && ensembleTableInfmList.size() > 0) - { - for(int i=0;i < ensembleTableInfmList.size(); i++) - { - ensembleTableRecord = (FcstPtESPRecord) ensembleTableInfmList.get(i); - FcstPtEnsembleJTableRowData rowData = new FcstPtEnsembleJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setLid(ensembleTableRecord.getLid()); - rowData.setHydraulMethod(ensembleTableRecord.getHydraul_method()); - rowData.setHydrolMethod(ensembleTableRecord.getHydrol_method()); - rowData.setSnowMethod(ensembleTableRecord.getSnow_method()); - rowData.setUpstreamSeg(ensembleTableRecord.getUpstream_seg()); - rowData.setReservoirModel(ensembleTableRecord.getReservoir_model()); - if(ensembleTableRecord.getFcst_horizon() != null) - { - rowData.setHorizon(ensembleTableRecord.getFcst_horizon()); - } - else - { - rowData.setHorizon(DbTable.getNullString()); - } - if(ensembleTableRecord.getConsumptive_use() != null) - { - rowData.setConsumptiveUse(ensembleTableRecord.getConsumptive_use()); - } - else - { - rowData.setConsumptiveUse(DbTable.getNullString()); - } - if(ensembleTableRecord.getChannel_loss() != null) - { - rowData.setChannelLoss(ensembleTableRecord.getChannel_loss()); - } - else - { - rowData.setChannelLoss(DbTable.getNullString()); - } - if(ensembleTableRecord.getPost_processor() != null) - { - rowData.setPostProcessing(ensembleTableRecord.getPost_processor()); - } - else - { - rowData.setPostProcessing(DbTable.getNullString()); - } - rowData.setFlowType(ensembleTableRecord.getFlowtype()); - rowData.setFcstType(ensembleTableRecord.getFcsttype()); - if(DbTable.isNull(ensembleTableRecord.getImpl_date()) || ensembleTableRecord.getImpl_date() < Long.MIN_VALUE || ensembleTableRecord.getImpl_date() > Long.MAX_VALUE) - { - rowData.setImplDate(DbTable.getNullLong()); - } - else - { - rowData.setImplDate(ensembleTableRecord.getImpl_date()); - } - if(DbTable.isNull(ensembleTableRecord.getWeb_date()) || ensembleTableRecord.getWeb_date() < Long.MIN_VALUE || ensembleTableRecord.getWeb_date() > Long.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setWebDate(ensembleTableRecord.getWeb_date()); - } - if(DbTable.isNull(ensembleTableRecord.getExternal_date()) || ensembleTableRecord.getExternal_date() < Long.MIN_VALUE || ensembleTableRecord.getExternal_date() > Long.MAX_VALUE) - { - rowData.setExternalDate(DbTable.getNullLong()); - } - else - { - rowData.setExternalDate(ensembleTableRecord.getExternal_date()); - } - if(ensembleTableRecord.getNum_elev_zones() < 0 || ensembleTableRecord.getNum_elev_zones() > Short.MAX_VALUE) - { - rowData.setWebDate(DbTable.getNullLong()); - } - else - { - rowData.setNumElevZones(ensembleTableRecord.getNum_elev_zones()); - } - if(ensembleTableRecord.getFrequpd_normal() != null) - { - rowData.setNormal(ensembleTableRecord.getFrequpd_normal()); - } - else - { - rowData.setNormal(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_flood() != null) - { - rowData.setFlood(ensembleTableRecord.getFrequpd_flood()); - } - else - { - rowData.setFlood(DbTable.getNullString()); - } - if(ensembleTableRecord.getVar_usage() != null) - { - rowData.setVarUsage(ensembleTableRecord.getVar_usage()); - } - else - { - rowData.setVarUsage(DbTable.getNullString()); - } - if(ensembleTableRecord.getFrequpd_drought() != null) - { - rowData.setDraught(ensembleTableRecord.getFrequpd_drought()); - } - else - { - rowData.setDraught(DbTable.getNullString()); - } - if(ensembleTableRecord.getNummonclim() < Integer.MIN_VALUE || ensembleTableRecord.getNummonclim() > Integer.MAX_VALUE) - { - rowData.setNumMonClim(DbTable.getNullInt()); - } - else - { - rowData.setNumMonClim(ensembleTableRecord.getNummonclim()); - } - if(ensembleTableRecord.getNumdayhyd() < Integer.MIN_VALUE || ensembleTableRecord.getNumdayhyd() > Integer.MAX_VALUE) - { - rowData.setNumDayHyd(DbTable.getNullInt()); - } - else - { - rowData.setNumDayHyd(ensembleTableRecord.getNumdayhyd()); - } - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in ensemble table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in Ensemble table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Ensemble table"; - } - return dataList; - } - - public List readDataFromFcstType() - { - List fcstTypeInfmList = null; - List dataList = new ArrayList(); - - FcstTypeTable fcstTypeTable = new FcstTypeTable(db); - FcstTypeRecord fcstTypeJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - fcstTypeInfmList = fcstTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(fcstTypeInfmList != null && fcstTypeInfmList.size() > 0) - { - for(int i=0;i < fcstTypeInfmList.size(); i++) - { - fcstTypeJTableRecord = (FcstTypeRecord) fcstTypeInfmList.get(i); - FcstTypeJTableRowData rowData = new FcstTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFcstType(fcstTypeJTableRecord.getFcsttype().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FcstType table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FcstType table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FcstType table"; - } - return dataList; - } - - public List readDataFromFlowType() - { - List flowTypeInfmList = null; - List dataList = new ArrayList(); - - FlowTypeTable flowTypeTable = new FlowTypeTable(db); - FlowTypeRecord flowTypeJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - flowTypeInfmList = flowTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(flowTypeInfmList != null && flowTypeInfmList.size() > 0) - { - for(int i=0;i < flowTypeInfmList.size(); i++) - { - flowTypeJTableRecord = (FlowTypeRecord) flowTypeInfmList.get(i); - FlowTypeJTableRowData rowData = new FlowTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFlowType(flowTypeJTableRecord.getFlowtype().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FlowType table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FlowType table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FlowType table"; - } - return dataList; - } - - public List readDataFromHydrologicMethod() - { - List hydrologicMethodInfmList = null; - List dataList = new ArrayList(); - - HydrologicMethodTable hydrologicMethodTable = new HydrologicMethodTable(db); - HydrologicMethodRecord hydrologicMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - hydrologicMethodInfmList = hydrologicMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(hydrologicMethodInfmList != null && hydrologicMethodInfmList.size() > 0) - { - for(int i=0;i < hydrologicMethodInfmList.size(); i++) - { - hydrologicMethodJTableRecord = (HydrologicMethodRecord) hydrologicMethodInfmList.get(i); - HydrologicMethodJTableRowData rowData = new HydrologicMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setHydrologicMethod(hydrologicMethodJTableRecord.getHydrol_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the HydrologicMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the HydrologicMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the HydrologicMethod table"; - } - return dataList; - } - - public List readDataFromRoutingMethod() - { - List routingMethodInfmList = null; - List dataList = new ArrayList(); - - RoutingMethodTable routingMethodTable = new RoutingMethodTable(db); - RoutingMethodRecord routingMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - routingMethodInfmList = routingMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(routingMethodInfmList != null && routingMethodInfmList.size() > 0) - { - for(int i=0;i < routingMethodInfmList.size(); i++) - { - routingMethodJTableRecord = (RoutingMethodRecord) routingMethodInfmList.get(i); - RoutingMethodJTableRowData rowData = new RoutingMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setRoutingMethod(routingMethodJTableRecord.getHydraul_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the RoutingMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the RoutingMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the RoutingMethod table"; - } - return dataList; - } - - public List readDataFromIssueCriteria() - { - List issueCriteriaInfmList = null; - List dataList = new ArrayList(); - - DefiningIssueCriteriaTable issueCriteriaTable = new DefiningIssueCriteriaTable(db); - DefiningIssueCriteriaRecord issueCriteriaJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - issueCriteriaInfmList = issueCriteriaTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(issueCriteriaInfmList != null && issueCriteriaInfmList.size() > 0) - { - for(int i=0;i < issueCriteriaInfmList.size(); i++) - { - issueCriteriaJTableRecord = (DefiningIssueCriteriaRecord) issueCriteriaInfmList.get(i); - IssueCriteriaJTableRowData rowData = new IssueCriteriaJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setIssueCriteria(issueCriteriaJTableRecord.getDef_issue_crit().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the IssueCriteria table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the IssueCriteria table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the IssueCriteria table"; - } - return dataList; - } - - public List readDataFromSnowMethod() - { - List snowMethodInfmList = null; - List dataList = new ArrayList(); - - SnowMethodTable snowMethodTable = new SnowMethodTable(db); - SnowMethodRecord snowMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - snowMethodInfmList = snowMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(snowMethodInfmList != null && snowMethodInfmList.size() > 0) - { - for(int i=0;i < snowMethodInfmList.size(); i++) - { - snowMethodJTableRecord = (SnowMethodRecord) snowMethodInfmList.get(i); - SnowMethodJTableRowData rowData = new SnowMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setSnowMethod(snowMethodJTableRecord.getSnow_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the SnowMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the SnowMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the SnowMethod table"; - } - return dataList; - } - - public List readDataFromWatsupCoordAgency() - { - List watsupCoordAgencyInfmList = null; - List dataList = new ArrayList(); - - WatSupCoordAgencyTable watsupCoordAgencyTable = new WatSupCoordAgencyTable(db); - WatSupCoordAgencyRecord watsupCoordAgencyJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - watsupCoordAgencyInfmList = watsupCoordAgencyTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupCoordAgencyInfmList != null && watsupCoordAgencyInfmList.size() > 0) - { - for(int i=0;i < watsupCoordAgencyInfmList.size(); i++) - { - watsupCoordAgencyJTableRecord = (WatSupCoordAgencyRecord) watsupCoordAgencyInfmList.get(i); - WatSupCoordAgencyJTableRowData rowData = new WatSupCoordAgencyJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setWatsupCoordAgency(watsupCoordAgencyJTableRecord.getWatsup_coord_agency().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatsupCoordAgency table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatsupCoordAgency table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatsupCoordAgency table"; - } - return dataList; - } - - public List readDataFromWatsupCriterion() - { - List watsupCriterionInfmList = null; - List dataList = new ArrayList(); - - WatSupCriterionTable watsupCriterionTable = new WatSupCriterionTable(db); - WatSupCriterionRecord watsupCriterionJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - watsupCriterionInfmList = watsupCriterionTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupCriterionInfmList != null && watsupCriterionInfmList.size() > 0) - { - for(int i=0;i < watsupCriterionInfmList.size(); i++) - { - watsupCriterionJTableRecord = (WatSupCriterionRecord) watsupCriterionInfmList.get(i); - WatSupCriterionJTableRowData rowData = new WatSupCriterionJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setWatsupCriterion(watsupCriterionJTableRecord.getWatsup_criterion().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatsupCriterion table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatsupCriterion table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatsupCriterion table"; - } - return dataList; - } - - public List readDataFromWatsupMethod() - { - List watsupMethodInfmList = null; - List dataList = new ArrayList(); - - WatSupMethodTable watsupMethodTable = new WatSupMethodTable(db); - WatSupMethodRecord watsupMethodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - watsupMethodInfmList = watsupMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(watsupMethodInfmList != null && watsupMethodInfmList.size() > 0) - { - for(int i=0;i < watsupMethodInfmList.size(); i++) - { - watsupMethodJTableRecord = (WatSupMethodRecord) watsupMethodInfmList.get(i); - WatSupMethodJTableRowData rowData = new WatSupMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setWatsupMethod(watsupMethodJTableRecord.getWatsup_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatsupMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatsupMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatsupMethod table"; - } - return dataList; - } - - public List readDataFromFrequencyUpdate() - { - List frequencyUpdateInfmList = null; - List dataList = new ArrayList(); - - FrequencyUpdateTable frequencyUpdateTable = new FrequencyUpdateTable(db); - FrequencyUpdateRecord frequencyUpdateRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - frequencyUpdateInfmList = frequencyUpdateTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(frequencyUpdateInfmList != null && frequencyUpdateInfmList.size() > 0) - { - for(int i=0;i < frequencyUpdateInfmList.size(); i++) - { - frequencyUpdateRecord = (FrequencyUpdateRecord) frequencyUpdateInfmList.get(i); - FrequencyUpdateJTableRowData rowData = new FrequencyUpdateJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFrequencyUpdate(frequencyUpdateRecord.getFrequency_update().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FrequencyUpdate table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FrequencyUpdate table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FrequencyUpdate table"; - } - return dataList; - } - - public List readDataFromRequiredPeriod() - { - List requiredPeriodInfmList = null; - List dataList = new ArrayList(); - - RequiredPeriodTable requiredPeriodTable = new RequiredPeriodTable(db); - RequiredPeriodRecord requiredPeriodJTableRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - requiredPeriodInfmList = requiredPeriodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(requiredPeriodInfmList != null && requiredPeriodInfmList.size() > 0) - { - for(int i=0;i < requiredPeriodInfmList.size(); i++) - { - requiredPeriodJTableRecord = (RequiredPeriodRecord) requiredPeriodInfmList.get(i); - RequiredPeriodJTableRowData rowData = new RequiredPeriodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setRequiredPeriod(requiredPeriodJTableRecord.getPeriod_req().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the RequiredPeriod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the RequiredPeriod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the RequiredPeriod table"; - } - return dataList; - } - - public List readDataFromPostProcessing() - { - List postProcessingInfmList = null; - List dataList = new ArrayList(); - - PostProcessorTable postProcessingTable = new PostProcessorTable(db); - PostProcessorRecord postProcessingRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - postProcessingInfmList = postProcessingTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(postProcessingInfmList != null && postProcessingInfmList.size() > 0) - { - for(int i=0;i < postProcessingInfmList.size(); i++) - { - postProcessingRecord = (PostProcessorRecord) postProcessingInfmList.get(i); - PostProcessingJTableRowData rowData = new PostProcessingJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setPostProcessing(postProcessingRecord.getPost_processor().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the PostProcessor table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the PostProcessor table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the PostProcessor table"; - } - return dataList; - } - - public List readDataFromHorizon() - { - List horizonInfmList = null; - List dataList = new ArrayList(); - - FcstHorizonTable horizonTable = new FcstHorizonTable(db); - FcstHorizonRecord horizonRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - horizonInfmList = horizonTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(horizonInfmList != null && horizonInfmList.size() > 0) - { - for(int i=0;i < horizonInfmList.size(); i++) - { - horizonRecord = (FcstHorizonRecord) horizonInfmList.get(i); - FcstHorizonJTableRowData rowData = new FcstHorizonJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setFcstHorizon(horizonRecord.getFcst_horizon().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FcstHorizon table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FcstHorizon table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FcstHorizon table"; - } - return dataList; - } - - public List readDataFromGenMethod() - { - List genMethodInfmList = null; - List dataList = new ArrayList(); - - FcstGenMethodTable genMethodTable = new FcstGenMethodTable(db); - FcstGenMethodRecord genMethodRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - genMethodInfmList = genMethodTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(genMethodInfmList != null && genMethodInfmList.size() > 0) - { - for(int i=0;i < genMethodInfmList.size(); i++) - { - genMethodRecord = (FcstGenMethodRecord) genMethodInfmList.get(i); - FcstGenMethodJTableRowData rowData = new FcstGenMethodJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setGenMethod(genMethodRecord.getFcst_gen_method().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the FcstGenMethod table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the FcstGenMethod table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the FcstGenMethod table"; - } - return dataList; - } - - public List readDataFromReservoirModel() - { - List reservoirModelInfmList = null; - List dataList = new ArrayList(); - - ReservoirModelTable reservoirModelTable = new ReservoirModelTable(db); - ReservoirModelRecord reservoirModelRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - reservoirModelInfmList = reservoirModelTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(reservoirModelInfmList != null && reservoirModelInfmList.size() > 0) - { - for(int i=0;i < reservoirModelInfmList.size(); i++) - { - reservoirModelRecord = (ReservoirModelRecord) reservoirModelInfmList.get(i); - ReservoirModelJTableRowData rowData = new ReservoirModelJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setReservoirModel(reservoirModelRecord.getReservoir_model().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the ReservoirModel table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the ReservoirModel table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the ReservoirModel table"; - } - return dataList; - } - - public List readDataFromServiceType() - { - List serviceTypeInfmList = null; - List dataList = new ArrayList(); - - ServiceTypeTable serviceTypeTable = new ServiceTypeTable(db); - ServiceTypeRecord serviceTypeRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - serviceTypeInfmList = serviceTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(serviceTypeInfmList != null && serviceTypeInfmList.size() > 0) - { - for(int i=0;i < serviceTypeInfmList.size(); i++) - { - serviceTypeRecord = (ServiceTypeRecord) serviceTypeInfmList.get(i); - ServiceTypeJTableRowData rowData = new ServiceTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setServiceType(serviceTypeRecord.getService_type().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the ServiceType table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the ServiceType table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the ServiceType table"; - } - return dataList; - } - - public List readDataFromRespAgency() - { - List respAgencyInfmList = null; - List dataList = new ArrayList(); - - WatSupRespAgencyTable respAgencyTable = new WatSupRespAgencyTable(db); - WatSupRespAgencyRecord respAgencyRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - respAgencyInfmList = respAgencyTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(respAgencyInfmList != null && respAgencyInfmList.size() > 0) - { - for(int i=0;i < respAgencyInfmList.size(); i++) - { - respAgencyRecord = (WatSupRespAgencyRecord) respAgencyInfmList.get(i); - RespAgencyJTableRowData rowData = new RespAgencyJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setRespAgency(respAgencyRecord.getWatsup_resp_agency().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the WatSupRespAgency table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the WatSupRespAgency table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the WatSupRespAgency table"; - } - return dataList; - } - - public List readDataFromVerificationResponseType() - { - List verifRespInfmList = null; - List dataList = new ArrayList(); - - VerifRespTypeTable verifRespTypeTable = new VerifRespTypeTable(db); - VerifRespTypeRecord verifRespTypeRecord = null; - String whereClause = null; - - try - { - whereClause = ""; - verifRespInfmList = verifRespTypeTable.select(whereClause); - //lhvmLogger.log(header+" Where Clause:"+ whereClause); - if(verifRespInfmList != null && verifRespInfmList.size() > 0) - { - for(int i=0;i < verifRespInfmList.size(); i++) - { - verifRespTypeRecord = (VerifRespTypeRecord) verifRespInfmList.get(i); - VerificationResponseTypeJTableRowData rowData = new VerificationResponseTypeJTableRowData(LhvmDataManager.missingRepresentation); - rowData.setVerifRespType(verifRespTypeRecord.getVerif_resp_type().toString()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - LhvmDataManager.databaseMessage = "Records found in the Verification Response Type table"; - } - else - { - //lhvmLogger.log(header+" Officeinfm list is null"); - LhvmDataManager.databaseMessage = "No records in the Verification Response Type table"; - } - } - catch(SQLException e) - { - logSQLException(e); - LhvmDataManager.databaseMessage = "Encountered an exception reading records from the Verification Response Type table"; - } - return dataList; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/LhvmLogger.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/LhvmLogger.java deleted file mode 100644 index 573253c828..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/LhvmLogger.java +++ /dev/null @@ -1,240 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.util.Logger; - -public class LhvmLogger implements Logger -{ - private String _fileName = null; - private OutputStream _outputStream = null; - private PrintWriter _writer = null; - private boolean _usingRealFile = false; - private boolean _fileIsOpen = false; - private int _sessionId; - - private static final String dateFormatString = - "yyyyMMdd"; - private static final SimpleDateFormat _dateFormatter = - new SimpleDateFormat(dateFormatString); - - private static final String timeFormatString = - "HH:mm:ss"; - private static final SimpleDateFormat _timeFormatter = - new SimpleDateFormat(timeFormatString); - - private boolean _appendDateTime = false; - private boolean _keepFileOpen = true; - private String _messageId; - - static - { - _dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - public LhvmLogger(String fileName, boolean keepFileOpen, boolean appendDateTime, String messageId) - { - _keepFileOpen = true; - _appendDateTime = true; - _messageId = messageId; - _fileName = fileName; - } - - public LhvmLogger() - { - } - - public int getSessionId() - { - return _sessionId; - } - - public void log(String message) - { - boolean isCreatedNow = false; - if (!isOpen() || message == null) - { - openFile(_fileName, false); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - else - { - String splitStr[] = _fileName.split("\\."); - String dateTimeStampInFileName = splitStr[2]; - if(!(getDateTimeStamp().equalsIgnoreCase(dateTimeStampInFileName))) - { - openFile(_fileName, true); - isCreatedNow = true; - _writer = new PrintWriter(_outputStream); - } - } - - if(isCreatedNow) - { - if(_messageId == null) - _messageId = new Integer(_sessionId).toString(); - _writer.println(_messageId); - _writer.println("**************************************"); - } - - if (_appendDateTime) - { - if(message != null) - _writer.println( getTimeStamp() + ": " + message); - } - else - { - if(message != null) - _writer.println(message); - } - _writer.flush(); - if (!_keepFileOpen) - { - close(); - } - } - - private void determineSessionId(String fileName) - { - int sessionId = -1; - String dirName; - int index = fileName.lastIndexOf("/"); - dirName = fileName.substring(0, index); - File dir = new File(dirName); - int leastPossibleNumber = 1; - if(dir.exists()) - { - if(dir.isDirectory()) - { - String files[] = dir.list(); - if(files != null) - { - if(files.length == 0) - { - sessionId = 1; - } - else - { - int existingIds[] = new int[files.length]; - for(int i=0; i < files.length; i++) - { - String str = files[i]; - String splitStr[] = str.split("\\."); - if(splitStr == null) - continue; - else if(splitStr.length != 3) - continue; - else if(!(splitStr[0].equals("RiverMonitor"))) - continue; - else if(splitStr[2].length() != 8) - continue; - try - { - existingIds[i] = Integer.parseInt(splitStr[1]); - Integer.parseInt(splitStr[2]);// To make sure the last portion is a data (number) - } - catch(Exception e) - { - continue; - } - } - Arrays.sort(existingIds); - while(true) - { - if(Arrays.binarySearch(existingIds, leastPossibleNumber) < 0) - { - sessionId = leastPossibleNumber; - break; - } - else - leastPossibleNumber++; - } - } - } - } - else - { - System.out.println("RiverMonitorLogger:["+dir+"] isn't a directory"); - } - } - else - { - System.out.println("RiverMonitorLogger:Directory ["+dir+"] doesn't exist"); - } - - _sessionId = sessionId; - } - - public PrintWriter getPrintWriter() - { - return _writer; - } - - private String getDateTimeStamp() - { - Date date = new Date(); - return _dateFormatter.format(date); - } - - private String getTimeStamp() - { - Date date = new Date(); - return _timeFormatter.format(date); - } - - private void openFile(String fileName, boolean isExistingSession) - { - try - { - if (fileName != null) - { - if(!isExistingSession) - { - determineSessionId(_fileName); - } - if(_sessionId != -1) - { - _fileName = _fileName +"."+ _sessionId + "."+getDateTimeStamp(); - _outputStream = new FileOutputStream(_fileName, true); - _usingRealFile = true; - _fileIsOpen = true; - } - else - { - _outputStream = System.out; - } - } - else //fileName == null - { - _outputStream = System.out; - } - _writer = new PrintWriter(_outputStream); - } - catch (java.io.IOException e) - { - e.printStackTrace(); - } - } - - public void close() - { - if (isOpen() && _usingRealFile) - { - _fileIsOpen = false; - _writer.close(); - } - } - - private boolean isOpen() - { - return _fileIsOpen; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/LocationJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/LocationJTableRowData.java deleted file mode 100644 index 920483be14..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/LocationJTableRowData.java +++ /dev/null @@ -1,49 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class LocationJTableRowData extends AbstractJTableRowData -{ - private String locId; - - public LocationJTableRowData() - { - } - - public LocationJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String toString() - { - String str = getLocId(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - LocationJTableRowData riverstatRecord = (LocationJTableRowData) rowData; - if(columnName.equals("Upstream Segment")) - ret = compareStrings(getLocId(), riverstatRecord.getLocId()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Upstream Segment")) - dataValue = getStringValue(getLocId()); - return dataValue; - } - - public String getLocId() { - return locId; - } - - public void setLocId(String locId) { - this.locId = locId; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/Observer.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/Observer.java deleted file mode 100644 index 79daef97c3..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/Observer.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.fcstservice; - -public interface Observer //Observer of the observer pattern -{ - //There is no need of pasing the subject as regardless of the subject, all the tables will be read - //Just in case we might need independent subject behaviour in the future, design doesn't have to be changed. - public void update(Subject sub); -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/PostProcessingJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/PostProcessingJTableRowData.java deleted file mode 100644 index 9525fc15b0..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/PostProcessingJTableRowData.java +++ /dev/null @@ -1,58 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class PostProcessingJTableRowData extends AbstractJTableRowData -{ - private String postProcessing; - private String missingRep = null; - - public PostProcessingJTableRowData() - { - } - - public PostProcessingJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getPostProcessing(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - PostProcessingJTableRowData postProcessingRecord = (PostProcessingJTableRowData) rowData; - if(columnName.equals("Post Processing")) - ret = compareStrings(getPostProcessing(), postProcessingRecord.getPostProcessing()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Post Processing")) - dataValue = getStringValue(getPostProcessing()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Post Processing", CellType.STRING, getPostProcessing(), missingRep)); - } - - public String getPostProcessing() { - return postProcessing; - } - - public void setPostProcessing(String postProcessing) { - this.postProcessing = postProcessing; - } - -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ReferenceTablesWindow.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ReferenceTablesWindow.java deleted file mode 100644 index 8c0ccfe3a6..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ReferenceTablesWindow.java +++ /dev/null @@ -1,558 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import javax.swing.*; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.util.gui.*; - -public class ReferenceTablesWindow -{ - private DataServicesGlobals dataServicesGlobals = null; - private java.util.List lhvmRowDataList1 = null; - private java.util.List lhvmRowDataList2 = null; - private java.util.List lhvmRowDataList3 = null; - private java.util.List lhvmRowDataList4 = null; - private java.util.List lhvmRowDataList5 = null; - private java.util.List lhvmRowDataList6 = null; - private java.util.List lhvmRowDataList7 = null; - private java.util.List lhvmRowDataList8 = null; - private java.util.List lhvmRowDataList9 = null; - private java.util.List lhvmRowDataList10 = null; - private java.util.List lhvmRowDataList11 = null; - private java.util.List lhvmRowDataList12 = null; - private java.util.List lhvmRowDataList13 = null; - private java.util.List lhvmRowDataList14 = null; - private java.util.List lhvmRowDataList15 = null; - private java.util.List lhvmRowDataList16 = null; - private java.util.List lhvmRowDataList17 = null; - private java.util.List lhvmRowDataList18 = null; - - private LhvmDataManager lhvmDataManager = null; - private LhvmLogger lhvmLogger = null; - private JFrame lhvm = null; - - private JTableManager jtm1 = null; - private JTableManager jtm2 = null; - private JTableManager jtm3 = null; - private JTableManager jtm4 = null; - private JTableManager jtm5 = null; - private JTableManager jtm6 = null; - private JTableManager jtm7 = null; - private JTableManager jtm8 = null; - private JTableManager jtm9 = null; - private JTableManager jtm10 = null; - private JTableManager jtm11 = null; - private JTableManager jtm12 = null; - private JTableManager jtm13 = null; - private JTableManager jtm14 = null; - private JTableManager jtm15 = null; - private JTableManager jtm16 = null; - private JTableManager jtm17 = null; - private JTableManager jtm18 = null; - - private JScrollPane tableScrollPane1 = null; - private JPanel tableScrollPanePanel1 = null; - private JScrollPane tableScrollPane2 = null; - private JPanel tableScrollPanePanel2 = null; - private JScrollPane tableScrollPane3 = null; - private JPanel tableScrollPanePanel3 = null; - private JScrollPane tableScrollPane4 = null; - private JPanel tableScrollPanePanel4 = null; - private JScrollPane tableScrollPane5 = null; - private JPanel tableScrollPanePanel5 = null; - private JScrollPane tableScrollPane6 = null; - private JPanel tableScrollPanePanel6 = null; - private JScrollPane tableScrollPane7 = null; - private JPanel tableScrollPanePanel7 = null; - private JScrollPane tableScrollPane8 = null; - private JPanel tableScrollPanePanel8 = null; - private JScrollPane tableScrollPane9 = null; - private JPanel tableScrollPanePanel9 = null; - private JScrollPane tableScrollPane10 = null; - private JPanel tableScrollPanePanel10 = null; - private JScrollPane tableScrollPane11 = null; - private JPanel tableScrollPanePanel11 = null; - private JScrollPane tableScrollPane12 = null; - private JPanel tableScrollPanePanel12 = null; - private JScrollPane tableScrollPane13 = null; - private JPanel tableScrollPanePanel13 = null; - private JScrollPane tableScrollPane14 = null; - private JPanel tableScrollPanePanel14 = null; - private JScrollPane tableScrollPane15 = null; - private JPanel tableScrollPanePanel15 = null; - private JScrollPane tableScrollPane16 = null; - private JPanel tableScrollPanePanel16 = null; - private JScrollPane tableScrollPane17 = null; - private JPanel tableScrollPanePanel17 = null; - private JScrollPane tableScrollPane18 = null; - private JPanel tableScrollPanePanel18 = null; - - private JButton closeButton = null; - - private void setDatabaseMessage() - { - String tempStr = null; - if(LhvmDataManager.displayedMessageReferencesWindow != null) - { - tempStr = new String(LhvmDataManager.displayedMessageReferencesWindow); - } - LhvmDataManager.displayedMessageReferencesWindow = new StringBuffer(); - LhvmDataManager.displayedMessageReferencesWindow.append(LhvmDataManager.databaseMessage); - if(tempStr != null) - { - LhvmDataManager.displayedMessageReferencesWindow.append("\n").append(tempStr); - } - } - - public ReferenceTablesWindow(String jdbcUrl) - { - dataServicesGlobals = DataServicesGlobals.getSingleInstanceOfDataServicesGlobals(); - - lhvm = new JFrame("Forecast Services Reference Tables"); - lhvm.setSize(1000, 500); - lhvm.setLocation(20,50); - lhvm.setLayout(new SpringLayout()); - - //Fix the dimensions of this window i.e. dis-allow window resizing - Dimension d = new Dimension(980, 850); - new WindowResizingManager(lhvm, d, d); - - lhvm.setResizable(false); - - JLabel consoleLabel = new JLabel("-----Database Messages-----"); - consoleLabel.setForeground(Color.red); - - JLabel separatorLabel1 = new JLabel("=================================================================================================="); - separatorLabel1.setForeground(Color.red); - JLabel separatorLabel2 = new JLabel("=================================================================================================="); - separatorLabel2.setForeground(Color.red); - JLabel separatorLabel3 = new JLabel("=================================================================================================="); - separatorLabel3.setForeground(Color.red); - - closeButton = new JButton("Close Window"); - closeButton.addActionListener(new CloseActionListener()); - closeButton.setEnabled(true); - - JTextArea consoleTextArea = new JTextArea(1,50); - //Font font = new Font("Serif", Font.BOLD, 15); - //consoleTextArea.setFont(font); - consoleTextArea.setForeground(Color.green); - consoleTextArea.setBackground(Color.black); - consoleTextArea.setCaretColor(Color.red); - consoleTextArea.setBorder(BorderFactory.createEtchedBorder() ); - consoleTextArea.setLineWrap(true); - - String[] columnsToBeDisplayed1 = {"Fcst Type"}; - String[] columnsToBeDisplayed2 = {"Flow Type"}; - String[] columnsToBeDisplayed3 = {"Hydrologic Method"}; - String[] columnsToBeDisplayed4 = {"Def Issue Criteria"}; - String[] columnsToBeDisplayed5 = {"Routing Method"}; - String[] columnsToBeDisplayed6 = {"Snow Method"}; - String[] columnsToBeDisplayed7 = {"Wat Sup Coord Agency"}; - String[] columnsToBeDisplayed8 = {"Wat Sup Criterion"}; - String[] columnsToBeDisplayed9 = {"Wat Sup Method"}; - String[] columnsToBeDisplayed10 = {"Frequency Update"}; - String[] columnsToBeDisplayed11 = {"Required Period"}; - String[] columnsToBeDisplayed12 = {"Post Processing"}; - String[] columnsToBeDisplayed13 = {"Horizon"}; - String[] columnsToBeDisplayed14 = {"Typical Fcst Gen Method"}; - String[] columnsToBeDisplayed15 = {"Reservoir Model"}; - String[] columnsToBeDisplayed16 = {"Wat Sup Resp Agency"}; - String[] columnsToBeDisplayed17 = {"Service Type"}; - String[] columnsToBeDisplayed18 = {"Verification Response Type"}; - - JLabel fcstTypeLabel = new JLabel(" Fcst Type"); - JLabel flowTypeLabel = new JLabel(" Flow Type"); - JLabel hydrologicMethodLabel = new JLabel(" Hydrologic Method"); - JLabel issueCriteriaLabel = new JLabel(" Def Issue Criteria"); - JLabel routingMethodLabel = new JLabel(" Routing Method"); - JLabel snowMethodLabel = new JLabel(" Snow Type"); - JLabel watsupCoordAgencyLabel = new JLabel(" Wat Sup Coord Agency"); - JLabel watsupCriterionLabel = new JLabel(" Wat Sup Criterion"); - JLabel watsupMethodLabel = new JLabel(" Wat Sup Method"); - JLabel frequencyUpdateLabel = new JLabel(" Frequency Update"); - JLabel requiredPeriodLabel = new JLabel(" Required Period"); - JLabel postProcessingLabel = new JLabel(" Post Processing"); - JLabel horizonLabel = new JLabel(" Horizon"); - JLabel genMethodLabel = new JLabel(" Typical Fcst Gen Method"); - JLabel reservoirModelLabel = new JLabel(" Reservoir Model"); - JLabel serviceTypeLabel = new JLabel(" Service Type"); - JLabel respAgencyLabel = new JLabel(" Wat Sup Resp Agency"); - JLabel verifRespTypeLabel = new JLabel(" Verification Response Type"); - - java.util.List lhvmColumnDescriptorList1 = new ArrayList(); - java.util.List lhvmColumnDescriptorList2 = new ArrayList(); - java.util.List lhvmColumnDescriptorList3 = new ArrayList(); - java.util.List lhvmColumnDescriptorList4 = new ArrayList(); - java.util.List lhvmColumnDescriptorList5 = new ArrayList(); - java.util.List lhvmColumnDescriptorList6 = new ArrayList(); - java.util.List lhvmColumnDescriptorList7 = new ArrayList(); - java.util.List lhvmColumnDescriptorList8 = new ArrayList(); - java.util.List lhvmColumnDescriptorList9 = new ArrayList(); - java.util.List lhvmColumnDescriptorList10 = new ArrayList(); - java.util.List lhvmColumnDescriptorList11 = new ArrayList(); - java.util.List lhvmColumnDescriptorList12 = new ArrayList(); - java.util.List lhvmColumnDescriptorList13 = new ArrayList(); - java.util.List lhvmColumnDescriptorList14 = new ArrayList(); - java.util.List lhvmColumnDescriptorList15 = new ArrayList(); - java.util.List lhvmColumnDescriptorList16 = new ArrayList(); - java.util.List lhvmColumnDescriptorList17 = new ArrayList(); - java.util.List lhvmColumnDescriptorList18 = new ArrayList(); - - lhvmLogger = new LhvmLogger(); - lhvmDataManager = LhvmDataManager.getSingleInstanceOfDataManager(jdbcUrl, lhvmLogger,"-"); - - lhvmRowDataList1 = lhvmDataManager.readDataFromFcstType(); - lhvmColumnDescriptorList1.add(new JTableColumnDescriptor("Fcst Type", true, 150, "center")); - jtm1 = new ComplexJTableManager(lhvmColumnDescriptorList1, lhvmRowDataList1); - jtm1.setDisplayableColumns(columnsToBeDisplayed1, false, true); - jtm1.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane1 = jtm1.getJScrollPane(); - //jtm1.setTableToolTipText("str"); - tableScrollPanePanel1 = new JPanel(); - tableScrollPanePanel1.add(tableScrollPane1); - setDatabaseMessage(); - - lhvmRowDataList2 = lhvmDataManager.readDataFromFlowType(); - lhvmColumnDescriptorList2.add(new JTableColumnDescriptor("Flow Type", true, 150, "center")); - jtm2 = new ComplexJTableManager(lhvmColumnDescriptorList2, lhvmRowDataList2); - jtm2.setDisplayableColumns(columnsToBeDisplayed2, false, true); - jtm2.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane2 = jtm2.getJScrollPane(); - //jtm2.setTableToolTipText("str"); - tableScrollPanePanel2 = new JPanel(); - tableScrollPanePanel2.add(tableScrollPane2); - setDatabaseMessage(); - - lhvmRowDataList3 = lhvmDataManager.readDataFromHydrologicMethod(); - lhvmColumnDescriptorList3.add(new JTableColumnDescriptor("Hydrologic Method", true, 150, "center")); - jtm3 = new ComplexJTableManager(lhvmColumnDescriptorList3, lhvmRowDataList3); - jtm3.setDisplayableColumns(columnsToBeDisplayed3, false, true); - jtm3.setPreferredSizeForJScrollPane(new Dimension(150,125)); - tableScrollPane3 = jtm3.getJScrollPane(); - //jtm3.setTableToolTipText("str"); - tableScrollPanePanel3 = new JPanel(); - tableScrollPanePanel3.add(tableScrollPane3); - setDatabaseMessage(); - - lhvmRowDataList4 = lhvmDataManager.readDataFromIssueCriteria(); - lhvmColumnDescriptorList4.add(new JTableColumnDescriptor("Def Issue Criteria", true, 150, "center")); - jtm4 = new ComplexJTableManager(lhvmColumnDescriptorList4, lhvmRowDataList4); - jtm4.setDisplayableColumns(columnsToBeDisplayed4, false, true); - jtm4.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane4 = jtm4.getJScrollPane(); - //jtm4.setTableToolTipText("str"); - tableScrollPanePanel4 = new JPanel(); - tableScrollPanePanel4.add(tableScrollPane4); - setDatabaseMessage(); - - lhvmRowDataList5 = lhvmDataManager.readDataFromRoutingMethod(); - lhvmColumnDescriptorList5.add(new JTableColumnDescriptor("Routing Method", true, 150, "center")); - jtm5 = new ComplexJTableManager(lhvmColumnDescriptorList5, lhvmRowDataList5); - jtm5.setDisplayableColumns(columnsToBeDisplayed5, false, true); - jtm5.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane5 = jtm5.getJScrollPane(); - //jtm5.setTableToolTipText("str"); - tableScrollPanePanel5 = new JPanel(); - tableScrollPanePanel5.add(tableScrollPane5); - setDatabaseMessage(); - - lhvmRowDataList6 = lhvmDataManager.readDataFromSnowMethod(); - lhvmColumnDescriptorList6.add(new JTableColumnDescriptor("Snow Method", true, 150, "center")); - jtm6 = new ComplexJTableManager(lhvmColumnDescriptorList6, lhvmRowDataList6); - jtm6.setDisplayableColumns(columnsToBeDisplayed6, false, true); - jtm6.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane6 = jtm6.getJScrollPane(); - //jtm6.setTableToolTipText("str"); - tableScrollPanePanel6 = new JPanel(); - tableScrollPanePanel6.add(tableScrollPane6); - setDatabaseMessage(); - - lhvmRowDataList7 = lhvmDataManager.readDataFromWatsupCoordAgency(); - lhvmColumnDescriptorList7.add(new JTableColumnDescriptor("Wat Sup Coord Agency", true, 150, "center")); - jtm7 = new ComplexJTableManager(lhvmColumnDescriptorList7, lhvmRowDataList7); - jtm7.setDisplayableColumns(columnsToBeDisplayed7, false, true); - jtm7.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane7 = jtm7.getJScrollPane(); - //jtm7.setTableToolTipText("str"); - tableScrollPanePanel7 = new JPanel(); - tableScrollPanePanel7.add(tableScrollPane7); - setDatabaseMessage(); - - lhvmRowDataList8 = lhvmDataManager.readDataFromWatsupCriterion(); - lhvmColumnDescriptorList8.add(new JTableColumnDescriptor("Wat Sup Criterion", true, 150, "center")); - jtm8 = new ComplexJTableManager(lhvmColumnDescriptorList8, lhvmRowDataList8); - jtm8.setDisplayableColumns(columnsToBeDisplayed8, false, true); - jtm8.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane8 = jtm8.getJScrollPane(); - //jtm8.setTableToolTipText("str"); - tableScrollPanePanel8 = new JPanel(); - tableScrollPanePanel8.add(tableScrollPane8); - setDatabaseMessage(); - - lhvmRowDataList9 = lhvmDataManager.readDataFromWatsupMethod(); - lhvmColumnDescriptorList9.add(new JTableColumnDescriptor("Wat Sup Method", true, 150, "center")); - jtm9 = new ComplexJTableManager(lhvmColumnDescriptorList9, lhvmRowDataList9); - jtm9.setDisplayableColumns(columnsToBeDisplayed9, false, true); - jtm9.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane9 = jtm9.getJScrollPane(); - //jtm9.setTableToolTipText("str"); - tableScrollPanePanel9 = new JPanel(); - tableScrollPanePanel9.add(tableScrollPane9); - setDatabaseMessage(); - - lhvmRowDataList10 = lhvmDataManager.readDataFromFrequencyUpdate(); - lhvmColumnDescriptorList10.add(new JTableColumnDescriptor("Frequency Update", true, 150, "center")); - jtm10 = new ComplexJTableManager(lhvmColumnDescriptorList10, lhvmRowDataList10); - jtm10.setDisplayableColumns(columnsToBeDisplayed10, false, true); - jtm10.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane10 = jtm10.getJScrollPane(); - //jtm10.setTableToolTipText("str"); - tableScrollPanePanel10 = new JPanel(); - tableScrollPanePanel10.add(tableScrollPane10); - setDatabaseMessage(); - - lhvmRowDataList11 = lhvmDataManager.readDataFromRequiredPeriod(); - lhvmColumnDescriptorList11.add(new JTableColumnDescriptor("Required Period", true, 150, "center")); - jtm11 = new ComplexJTableManager(lhvmColumnDescriptorList11, lhvmRowDataList11); - jtm11.setDisplayableColumns(columnsToBeDisplayed11, false, true); - jtm11.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane11 = jtm11.getJScrollPane(); - //jtm11.setTableToolTipText("str"); - tableScrollPanePanel11 = new JPanel(); - tableScrollPanePanel11.add(tableScrollPane11); - setDatabaseMessage(); - - lhvmRowDataList12 = lhvmDataManager.readDataFromPostProcessing(); - lhvmColumnDescriptorList12.add(new JTableColumnDescriptor("Post Processing", true, 150, "center")); - jtm12 = new ComplexJTableManager(lhvmColumnDescriptorList12, lhvmRowDataList12); - jtm12.setDisplayableColumns(columnsToBeDisplayed12, false, true); - jtm12.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane12 = jtm12.getJScrollPane(); - //jtm12.setTableToolTipText("str"); - tableScrollPanePanel12 = new JPanel(); - tableScrollPanePanel12.add(tableScrollPane12); - setDatabaseMessage(); - - lhvmRowDataList13 = lhvmDataManager.readDataFromHorizon(); - lhvmColumnDescriptorList13.add(new JTableColumnDescriptor("Horizon", true, 150, "center")); - jtm13 = new ComplexJTableManager(lhvmColumnDescriptorList13, lhvmRowDataList13); - jtm13.setDisplayableColumns(columnsToBeDisplayed13, false, true); - jtm13.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane13 = jtm13.getJScrollPane(); - //jtm13.setTableToolTipText("str"); - tableScrollPanePanel13 = new JPanel(); - tableScrollPanePanel13.add(tableScrollPane13); - setDatabaseMessage(); - - lhvmRowDataList14 = lhvmDataManager.readDataFromGenMethod(); - lhvmColumnDescriptorList14.add(new JTableColumnDescriptor("Typical Fcst Gen Method", true, 150, "center")); - jtm14 = new ComplexJTableManager(lhvmColumnDescriptorList14, lhvmRowDataList14); - jtm14.setDisplayableColumns(columnsToBeDisplayed14, false, true); - jtm14.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane14 = jtm14.getJScrollPane(); - //jtm14.setTableToolTipText("str"); - tableScrollPanePanel14 = new JPanel(); - tableScrollPanePanel14.add(tableScrollPane14); - setDatabaseMessage(); - - lhvmRowDataList15 = lhvmDataManager.readDataFromReservoirModel(); - lhvmColumnDescriptorList15.add(new JTableColumnDescriptor("Reservoir Model", true, 150, "center")); - jtm15 = new ComplexJTableManager(lhvmColumnDescriptorList15, lhvmRowDataList15); - jtm15.setDisplayableColumns(columnsToBeDisplayed15, false, true); - jtm15.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane15 = jtm15.getJScrollPane(); - //jtm15.setTableToolTipText("str"); - tableScrollPanePanel15 = new JPanel(); - tableScrollPanePanel15.add(tableScrollPane15); - setDatabaseMessage(); - - lhvmRowDataList16 = lhvmDataManager.readDataFromRespAgency(); - lhvmColumnDescriptorList16.add(new JTableColumnDescriptor("Wat Sup Resp Agency", true, 150, "center")); - jtm16 = new ComplexJTableManager(lhvmColumnDescriptorList16, lhvmRowDataList16); - jtm16.setDisplayableColumns(columnsToBeDisplayed16, false, true); - jtm16.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane16 = jtm16.getJScrollPane(); - //jtm16.setTableToolTipText("str"); - tableScrollPanePanel16 = new JPanel(); - tableScrollPanePanel16.add(tableScrollPane16); - setDatabaseMessage(); - - lhvmRowDataList17 = lhvmDataManager.readDataFromServiceType(); - lhvmColumnDescriptorList17.add(new JTableColumnDescriptor("Service Type", true, 150, "center")); - jtm17 = new ComplexJTableManager(lhvmColumnDescriptorList17, lhvmRowDataList17); - jtm17.setDisplayableColumns(columnsToBeDisplayed17, false, true); - jtm17.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane17 = jtm17.getJScrollPane(); - //jtm17.setTableToolTipText("str"); - tableScrollPanePanel17 = new JPanel(); - tableScrollPanePanel17.add(tableScrollPane17); - setDatabaseMessage(); - - lhvmRowDataList18 = lhvmDataManager.readDataFromVerificationResponseType(); - lhvmColumnDescriptorList18.add(new JTableColumnDescriptor("Verification Response Type", true, 150, "center")); - jtm18 = new ComplexJTableManager(lhvmColumnDescriptorList18, lhvmRowDataList18); - jtm18.setDisplayableColumns(columnsToBeDisplayed18, false, true); - jtm18.setPreferredSizeForJScrollPane(new Dimension(150, 125)); - tableScrollPane18 = jtm18.getJScrollPane(); - //jtm17.setTableToolTipText("str"); - tableScrollPanePanel18 = new JPanel(); - tableScrollPanePanel18.add(tableScrollPane18); - setDatabaseMessage(); - - consoleTextArea.insert(new String(LhvmDataManager.displayedMessageReferencesWindow), 0); - JScrollPane scrollableTextAreaForConsole = new JScrollPane(consoleTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - - int numRows1 = lhvmRowDataList1.size(); - JLabel numRowsLabel1 = new JLabel(" " + numRows1 + " Rows"); - int numRows2 = lhvmRowDataList2.size(); - JLabel numRowsLabel2 = new JLabel(" " + numRows2 + " Rows"); - int numRows3 = lhvmRowDataList3.size(); - JLabel numRowsLabel3 = new JLabel(" " + numRows3 + " Rows"); - int numRows4 = lhvmRowDataList4.size(); - JLabel numRowsLabel4 = new JLabel(" " + numRows4 + " Rows"); - int numRows5 = lhvmRowDataList5.size(); - JLabel numRowsLabel5 = new JLabel(" " + numRows5 + " Rows"); - int numRows6 = lhvmRowDataList6.size(); - JLabel numRowsLabel6 = new JLabel(" " + numRows6 + " Rows"); - int numRows7 = lhvmRowDataList7.size(); - JLabel numRowsLabel7 = new JLabel(" " + numRows7 + " Rows"); - int numRows8 = lhvmRowDataList8.size(); - JLabel numRowsLabel8 = new JLabel(" " + numRows8 + " Rows"); - int numRows9 = lhvmRowDataList9.size(); - JLabel numRowsLabel9 = new JLabel(" " + numRows9 + " Rows"); - int numRows10 = lhvmRowDataList10.size(); - JLabel numRowsLabel10 = new JLabel(" " + numRows10 + " Rows"); - int numRows11 = lhvmRowDataList11.size(); - JLabel numRowsLabel11 = new JLabel(" " + numRows11 + " Rows"); - int numRows12 = lhvmRowDataList12.size(); - JLabel numRowsLabel12 = new JLabel(" " + numRows12 + " Rows"); - int numRows13 = lhvmRowDataList13.size(); - JLabel numRowsLabel13 = new JLabel(" " + numRows13 + " Rows"); - int numRows14 = lhvmRowDataList14.size(); - JLabel numRowsLabel14 = new JLabel(" " + numRows14 + " Rows"); - int numRows15 = lhvmRowDataList15.size(); - JLabel numRowsLabel15 = new JLabel(" " + numRows15 + " Rows"); - int numRows16 = lhvmRowDataList16.size(); - JLabel numRowsLabel16 = new JLabel(" " + numRows16 + " Rows"); - int numRows17 = lhvmRowDataList17.size(); - JLabel numRowsLabel17 = new JLabel(" " + numRows17 + " Rows"); - int numRows18 = lhvmRowDataList18.size(); - JLabel numRowsLabel18 = new JLabel(" " + numRows18 + " Rows"); - - JFrame tablesPanel = new JFrame(); - tablesPanel.setLayout(new SpringLayout()); - tablesPanel.add(numRowsLabel1); - tablesPanel.add(numRowsLabel2); - tablesPanel.add(numRowsLabel3); - tablesPanel.add(numRowsLabel4); - tablesPanel.add(numRowsLabel5); - tablesPanel.add(fcstTypeLabel); - tablesPanel.add(flowTypeLabel); - tablesPanel.add(hydrologicMethodLabel); - tablesPanel.add(issueCriteriaLabel); - tablesPanel.add(routingMethodLabel); - tablesPanel.add(tableScrollPanePanel1); - tablesPanel.add(tableScrollPanePanel2); - tablesPanel.add(tableScrollPanePanel3); - tablesPanel.add(tableScrollPanePanel4); - tablesPanel.add(tableScrollPanePanel5); - SpringUtilities.makeCompactGrid(tablesPanel.getContentPane(), 3, 5, 0, 0, 0, 0); - - JFrame tablesPanel1 = new JFrame(); - tablesPanel1.setLayout(new SpringLayout()); - tablesPanel1.add(numRowsLabel6); - tablesPanel1.add(numRowsLabel7); - tablesPanel1.add(numRowsLabel8); - tablesPanel1.add(numRowsLabel9); - tablesPanel1.add(numRowsLabel10); - tablesPanel1.add(snowMethodLabel); - tablesPanel1.add(watsupCoordAgencyLabel); - tablesPanel1.add(watsupCriterionLabel); - tablesPanel1.add(watsupMethodLabel); - tablesPanel1.add(frequencyUpdateLabel); - tablesPanel1.add(tableScrollPanePanel6); - tablesPanel1.add(tableScrollPanePanel7); - tablesPanel1.add(tableScrollPanePanel8); - tablesPanel1.add(tableScrollPanePanel9); - tablesPanel1.add(tableScrollPanePanel10); - SpringUtilities.makeCompactGrid(tablesPanel1.getContentPane(), 3, 5, 0, 0, 0, 0); - - JFrame tablesPanel2 = new JFrame(); - tablesPanel2.setLayout(new SpringLayout()); - tablesPanel2.add(numRowsLabel11); - tablesPanel2.add(numRowsLabel12); - tablesPanel2.add(numRowsLabel13); - tablesPanel2.add(numRowsLabel14); - tablesPanel2.add(numRowsLabel15); - tablesPanel2.add(requiredPeriodLabel); - tablesPanel2.add(postProcessingLabel); - tablesPanel2.add(horizonLabel); - tablesPanel2.add(genMethodLabel); - tablesPanel2.add(reservoirModelLabel); - tablesPanel2.add(tableScrollPanePanel11); - tablesPanel2.add(tableScrollPanePanel12); - tablesPanel2.add(tableScrollPanePanel13); - tablesPanel2.add(tableScrollPanePanel14); - tablesPanel2.add(tableScrollPanePanel15); - SpringUtilities.makeCompactGrid(tablesPanel2.getContentPane(), 3, 5, 0, 0, 0, 0); - - JFrame tablesPanel3 = new JFrame(); - tablesPanel3.setLayout(new SpringLayout()); - tablesPanel3.add(numRowsLabel16); - tablesPanel3.add(numRowsLabel17); - tablesPanel3.add(numRowsLabel18); - tablesPanel3.add(respAgencyLabel); - tablesPanel3.add(serviceTypeLabel); - tablesPanel3.add(verifRespTypeLabel); - tablesPanel3.add(tableScrollPanePanel16); - tablesPanel3.add(tableScrollPanePanel17); - tablesPanel3.add(tableScrollPanePanel18); - SpringUtilities.makeCompactGrid(tablesPanel3.getContentPane(), 3, 3, 0, 0, 0, 0); - - lhvm.getContentPane().add(tablesPanel.getContentPane()); - lhvm.getContentPane ().add(separatorLabel1); - lhvm.getContentPane().add(tablesPanel1.getContentPane()); - lhvm.getContentPane ().add(separatorLabel2); - lhvm.getContentPane().add(tablesPanel2.getContentPane()); - lhvm.getContentPane ().add(separatorLabel3); - lhvm.getContentPane().add(tablesPanel3.getContentPane()); - lhvm.getContentPane ().add(closeButton); - lhvm.getContentPane().add(consoleLabel); - lhvm.getContentPane().add(scrollableTextAreaForConsole); - SpringUtilities.makeCompactGrid(lhvm.getContentPane(), 10, 1, 0, 0, 6, 6); - - lhvm.addWindowListener(new ServicesDbWindowAdapter()); - - lhvm.pack(); - //Show the JFrame - lhvm.setVisible (true); - } - - private void operationCloseWindow() - { - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - lhvm.dispose(); - } - } - - private class CloseActionListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - operationCloseWindow(); - } - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RequiredPeriodJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RequiredPeriodJTableRowData.java deleted file mode 100644 index f3ef983e1d..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RequiredPeriodJTableRowData.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class RequiredPeriodJTableRowData extends AbstractJTableRowData -{ - private String requiredPeriod; - private String missingRep = null; - - public RequiredPeriodJTableRowData() - { - } - - public RequiredPeriodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getRequiredPeriod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - RequiredPeriodJTableRowData requiredPeriodMethodRecord = (RequiredPeriodJTableRowData) rowData; - if(columnName.equals("Required Period")) - ret = compareStrings(getRequiredPeriod(), requiredPeriodMethodRecord.getRequiredPeriod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Required Period")) - dataValue = getStringValue(getRequiredPeriod()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Required Period", CellType.STRING, getRequiredPeriod(), missingRep)); - } - - public String getRequiredPeriod() { - return requiredPeriod; - } - - public void setRequiredPeriod(String requiredPeriod) { - this.requiredPeriod = requiredPeriod; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ReservoirModelJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ReservoirModelJTableRowData.java deleted file mode 100644 index bb97569212..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ReservoirModelJTableRowData.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class ReservoirModelJTableRowData extends AbstractJTableRowData -{ - private String reservoirModel; - private String missingRep = null; - - public ReservoirModelJTableRowData() - { - } - - public ReservoirModelJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getReservoirModel(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - ReservoirModelJTableRowData reservoirModelRecord = (ReservoirModelJTableRowData) rowData; - if(columnName.equals("Reservoir Model")) - ret = compareStrings(getReservoirModel(), reservoirModelRecord.getReservoirModel()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Reservoir Model")) - dataValue = getStringValue(getReservoirModel()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Reservoir Model", CellType.STRING, getReservoirModel(), missingRep)); - } - - public String getReservoirModel() { - return reservoirModel; - } - - public void setReservoirModel(String reservoirModel) { - this.reservoirModel = reservoirModel; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RespAgencyJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RespAgencyJTableRowData.java deleted file mode 100644 index 9e16cdc90f..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RespAgencyJTableRowData.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class RespAgencyJTableRowData extends AbstractJTableRowData -{ - private String respAgency; - private String missingRep = null; - - public RespAgencyJTableRowData() - { - } - - public RespAgencyJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getRespAgency(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - RespAgencyJTableRowData respAgencyRecord = (RespAgencyJTableRowData) rowData; - if(columnName.equals("Wat Sup Resp Agency")) - ret = compareStrings(getRespAgency(), respAgencyRecord.getRespAgency()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Resp Agency")) - dataValue = getStringValue(getRespAgency()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Resp Agency", CellType.STRING, getRespAgency(), missingRep)); - } - - public String getRespAgency() { - return respAgency; - } - - public void setRespAgency(String respAgency) { - this.respAgency = respAgency; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RoutingMethodJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RoutingMethodJTableRowData.java deleted file mode 100644 index d1ba4e18e0..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/RoutingMethodJTableRowData.java +++ /dev/null @@ -1,58 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class RoutingMethodJTableRowData extends AbstractJTableRowData -{ - private String routingMethod; - private String missingRep = null; - - public RoutingMethodJTableRowData() - { - } - - public RoutingMethodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getRoutingMethod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - RoutingMethodJTableRowData routingMethodRecord = (RoutingMethodJTableRowData) rowData; - if(columnName.equals("Routing Method")) - ret = compareStrings(getRoutingMethod(), routingMethodRecord.getRoutingMethod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Routing Method")) - dataValue = getStringValue(getRoutingMethod()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Routing Method", CellType.STRING, getRoutingMethod(), missingRep)); - } - - public String getRoutingMethod() { - return routingMethod; - } - - public void setRoutingMethod(String routingMethod) { - this.routingMethod = routingMethod; - } - -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServiceTableViewViewJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServiceTableViewViewJTableRowData.java deleted file mode 100644 index 91da25f465..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServiceTableViewViewJTableRowData.java +++ /dev/null @@ -1,127 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class ServiceTableViewViewJTableRowData extends AbstractJTableRowData -{ - private String lid; - private String state; - private String county; - private String hsa; - private String locName; - private String stream; - - public ServiceTableViewViewJTableRowData() - { - } - - public void setServiceTableViewRecord(ServiceTableViewRecord serviceTableViewRecord) - { - setLid(serviceTableViewRecord.getLid()); - setState(serviceTableViewRecord.getState()); - setCounty(serviceTableViewRecord.getCounty()); - setHsa(serviceTableViewRecord.getHsa()); - setLocName(serviceTableViewRecord.getName()); - setStream(serviceTableViewRecord.getStream()); - } - - public ServiceTableViewViewJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String toString() - { - String str = getLid()+" "+ - getState()+" "+ - getCounty()+" "+ - getHsa(); - return str; - } - - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - ServiceTableViewViewJTableRowData serviceTableViewRecord = (ServiceTableViewViewJTableRowData) rowData; - if(columnName.equals("Location ID")) - ret = compareStrings(getLid(), serviceTableViewRecord.getLid()); - else if(columnName.equals("State")) - ret = compareStrings(getState(), serviceTableViewRecord.getState()); - else if (columnName.equals("County")) - ret = compareStrings(getCounty(), serviceTableViewRecord.getCounty()); - else if (columnName.equals("Hsa")) - ret = compareStrings(getHsa(), serviceTableViewRecord.getHsa()); - else if (columnName.equals("Name")) - ret = compareStrings(getLocName(), serviceTableViewRecord.getLocName()); - else if (columnName.equals("Stream")) - ret = compareStrings(getStream(), serviceTableViewRecord.getStream()); - return ret; - } - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Location ID")) - dataValue = getStringValue(getLid()); - else if (columnName.equals("State")) - dataValue = getStringValue(getState()); - else if (columnName.equals("County")) - dataValue = getStringValue(getCounty()); - else if (columnName.equals("Hsa")) - dataValue = getStringValue(getHsa()); - else if (columnName.equals("Name")) - dataValue = getStringValue(getLocName()); - else if (columnName.equals("Stream")) - dataValue = getStringValue(getStream()); - return dataValue; - } - - public String getCounty() { - return county; - } - - public void setCounty(String county) { - this.county = county; - } - - public String getHsa() { - return hsa; - } - - public void setHsa(String hsa) { - this.hsa = hsa; - } - - public String getLid() { - return lid; - } - - public void setLid(String lid) { - this.lid = lid; - } - - public String getLocName() { - return locName; - } - - public void setLocName(String locName) { - this.locName = locName; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getStream() { - return stream; - } - - public void setStream(String stream) { - this.stream = stream; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServiceTypeJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServiceTypeJTableRowData.java deleted file mode 100644 index ffe7b36edb..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServiceTypeJTableRowData.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class ServiceTypeJTableRowData extends AbstractJTableRowData -{ - private String serviceType; - private String missingRep = null; - - public ServiceTypeJTableRowData() - { - } - - public ServiceTypeJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getServiceType(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - ServiceTypeJTableRowData serviceTypeRecord = (ServiceTypeJTableRowData) rowData; - if(columnName.equals("Service Type")) - ret = compareStrings(getServiceType(), serviceTypeRecord.getServiceType()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Service Type")) - dataValue = getStringValue(getServiceType()); - return dataValue; - } -*/ - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Service Type", CellType.STRING, getServiceType(), missingRep)); - } - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServicesDbWindowAdapter.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServicesDbWindowAdapter.java deleted file mode 100644 index 1ea27eecf1..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/ServicesDbWindowAdapter.java +++ /dev/null @@ -1,35 +0,0 @@ -package ohd.hseb.fcstservice; - -import java.awt.event.*; -import javax.swing.*; - -public class ServicesDbWindowAdapter extends WindowAdapter -{ - private JFrame jf = null; - private DataServicesGlobals dataServicesGlobals = null; - - public ServicesDbWindowAdapter() - { - super(); - } - - public void windowClosing(WindowEvent e) - { - jf = (JFrame) e.getSource(); - operationCloseWindow(); - } - - private void operationCloseWindow() - { - dataServicesGlobals = DataServicesGlobals.getSingleInstanceOfDataServicesGlobals(); - if(dataServicesGlobals.getCount() <= 1) - { - System.exit(0); - } - else - { - dataServicesGlobals.decrementCount(); - jf.dispose(); - } - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/SnowMethodJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/SnowMethodJTableRowData.java deleted file mode 100644 index 45f496bbc2..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/SnowMethodJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class SnowMethodJTableRowData extends AbstractJTableRowData -{ - private String snowMethod; - private String missingRep = null; - - public SnowMethodJTableRowData() - { - } - - public SnowMethodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getSnowMethod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - SnowMethodJTableRowData snowMethodRecord = (SnowMethodJTableRowData) rowData; - if(columnName.equals("Snow Method")) - ret = compareStrings(getSnowMethod(), snowMethodRecord.getSnowMethod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Snow Method")) - dataValue = getStringValue(getSnowMethod()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Snow Method", CellType.STRING, getSnowMethod(), missingRep)); - } - - public String getSnowMethod() { - return snowMethod; - } - - public void setSnowMethod(String snowMethod) { - this.snowMethod = snowMethod; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/SpringUtilities.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/SpringUtilities.java deleted file mode 100644 index 8ee118a4d1..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/SpringUtilities.java +++ /dev/null @@ -1,193 +0,0 @@ -package ohd.hseb.fcstservice; - -import javax.swing.*; -import javax.swing.SpringLayout; -import java.awt.*; - -/** - * A 1.4 file that provides utility methods for - * creating form- or grid-style layouts with SpringLayout. - * These utilities are used by several programs, such as - * SpringBox and SpringCompactGrid. - */ -public class SpringUtilities -{ - /** - * A debugging utility that prints to stdout the component's - * minimum, preferred, and maximum sizes. - */ - public static void printSizes(Component c) { - System.out.println("minimumSize = " + c.getMinimumSize()); - System.out.println("preferredSize = " + c.getPreferredSize()); - System.out.println("maximumSize = " + c.getMaximumSize()); - } - - /** - * Aligns the first rows * cols - * components of parent in - * a grid. Each component is as big as the maximum - * preferred width and height of the components. - * The parent is made just big enough to fit them all. - * - * @param rows number of rows - * @param cols number of columns - * @param initialX x location to start the grid at - * @param initialY y location to start the grid at - * @param xPad x padding between cells - * @param yPad y padding between cells - */ - public static void makeGrid(Container parent, - int rows, int cols, - int initialX, int initialY, - int xPad, int yPad) { - SpringLayout layout; - try { - layout = (SpringLayout)parent.getLayout(); - } catch (ClassCastException exc) { - System.err.println("The first argument to makeGrid must use SpringLayout."); - return; - } - - Spring xPadSpring = Spring.constant(xPad); - Spring yPadSpring = Spring.constant(yPad); - Spring initialXSpring = Spring.constant(initialX); - Spring initialYSpring = Spring.constant(initialY); - int max = rows * cols; - - //Calculate Springs that are the max of the width/height so that all - //cells have the same size. - Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). - getWidth(); - Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). - getWidth(); - for (int i = 1; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - - maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); - maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); - } - - //Apply the new width/height Spring. This forces all the - //components to have the same size. - for (int i = 0; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - - cons.setWidth(maxWidthSpring); - cons.setHeight(maxHeightSpring); - } - - //Then adjust the x/y constraints of all the cells so that they - //are aligned in a grid. - SpringLayout.Constraints lastCons = null; - SpringLayout.Constraints lastRowCons = null; - for (int i = 0; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - if (i % cols == 0) { //start of new row - lastRowCons = lastCons; - cons.setX(initialXSpring); - } else { //x position depends on previous component - cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), - xPadSpring)); - } - - if (i / cols == 0) { //first row - cons.setY(initialYSpring); - } else { //y position depends on previous row - cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), - yPadSpring)); - } - lastCons = cons; - } - - //Set the parent's size. - SpringLayout.Constraints pCons = layout.getConstraints(parent); - pCons.setConstraint(SpringLayout.SOUTH, - Spring.sum( - Spring.constant(yPad), - lastCons.getConstraint(SpringLayout.SOUTH))); - pCons.setConstraint(SpringLayout.EAST, - Spring.sum( - Spring.constant(xPad), - lastCons.getConstraint(SpringLayout.EAST))); - } - - /* Used by makeCompactGrid. */ - private static SpringLayout.Constraints getConstraintsForCell( - int row, int col, - Container parent, - int cols) { - SpringLayout layout = (SpringLayout) parent.getLayout(); - Component c = parent.getComponent(row * cols + col); - return layout.getConstraints(c); - } - - /** - * Aligns the first rows * cols - * components of parent in - * a grid. Each component in a column is as wide as the maximum - * preferred width of the components in that column; - * height is similarly determined for each row. - * The parent is made just big enough to fit them all. - * - * @param rows number of rows - * @param cols number of columns - * @param initialX x location to start the grid at - * @param initialY y location to start the grid at - * @param xPad x padding between cells - * @param yPad y padding between cells - */ - public static void makeCompactGrid(Container parent, - int rows, int cols, - int initialX, int initialY, - int xPad, int yPad) { - SpringLayout layout; - try { - layout = (SpringLayout)parent.getLayout(); - } catch (ClassCastException exc) { - System.err.println("The first argument to makeCompactGrid must use SpringLayout."); - return; - } - - //Align all cells in each column and make them the same width. - Spring x = Spring.constant(initialX); - for (int c = 0; c < cols; c++) { - Spring width = Spring.constant(0); - for (int r = 0; r < rows; r++) { - width = Spring.max(width,getConstraintsForCell(r, c, parent, cols).getWidth()); - } - for (int r = 0; r < rows; r++) { - SpringLayout.Constraints constraints = - getConstraintsForCell(r, c, parent, cols); - constraints.setX(x); - constraints.setWidth(width); - } - x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); - } - - //Align all cells in each row and make them the same height. - Spring y = Spring.constant(initialY); - for (int r = 0; r < rows; r++) { - Spring height = Spring.constant(0); - for (int c = 0; c < cols; c++) { - height = Spring.max(height, - getConstraintsForCell(r, c, parent, cols). - getHeight()); - } - for (int c = 0; c < cols; c++) { - SpringLayout.Constraints constraints = - getConstraintsForCell(r, c, parent, cols); - constraints.setY(y); - constraints.setHeight(height); - } - y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); - } - - //Set the parent's size. - SpringLayout.Constraints pCons = layout.getConstraints(parent); - pCons.setConstraint(SpringLayout.SOUTH, y); - pCons.setConstraint(SpringLayout.EAST, x); - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/Subject.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/Subject.java deleted file mode 100644 index b37367bc96..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/Subject.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.fcstservice; - -public interface Subject //Subject of the observer pattern -{ - public void addObserver(Observer observer); - public void removeObserver(Observer observer); - public void letKnowOfChanges(); -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/VerificationResponseTypeJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/VerificationResponseTypeJTableRowData.java deleted file mode 100644 index cb15e691db..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/VerificationResponseTypeJTableRowData.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class VerificationResponseTypeJTableRowData extends AbstractJTableRowData -{ - private String verifRespType; - private String missingRep = null; - - public VerificationResponseTypeJTableRowData() - { - } - - public VerificationResponseTypeJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Verification Response Type", CellType.STRING, getVerifRespType(), missingRep)); - } - - public String getVerifRespType() { - return verifRespType; - } - - public void setVerifRespType(String verifRespType) { - this.verifRespType = verifRespType; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupCoordAgencyJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupCoordAgencyJTableRowData.java deleted file mode 100644 index 155804cf56..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupCoordAgencyJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class WatSupCoordAgencyJTableRowData extends AbstractJTableRowData -{ - private String watsupCoordAgency; - private String missingRep = null; - - public WatSupCoordAgencyJTableRowData() - { - } - - public WatSupCoordAgencyJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getWatsupCoordAgency(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - WatSupCoordAgencyJTableRowData watsupCoordAgencyRecord = (WatSupCoordAgencyJTableRowData) rowData; - if(columnName.equals("Wat Sup Coord Agency")) - ret = compareStrings(getWatsupCoordAgency(), watsupCoordAgencyRecord.getWatsupCoordAgency()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Coord Agency")) - dataValue = getStringValue(getWatsupCoordAgency()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Coord Agency", CellType.STRING, getWatsupCoordAgency(), missingRep)); - } - - public String getWatsupCoordAgency() { - return watsupCoordAgency; - } - - public void setWatsupCoordAgency(String watsupCoordAgency) { - this.watsupCoordAgency = watsupCoordAgency; - } -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupCriterionJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupCriterionJTableRowData.java deleted file mode 100644 index f9882a6f77..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupCriterionJTableRowData.java +++ /dev/null @@ -1,58 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class WatSupCriterionJTableRowData extends AbstractJTableRowData -{ - private String watsupCriterion; - private String missingRep = null; - - public WatSupCriterionJTableRowData() - { - } - - public WatSupCriterionJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getWatsupCriterion(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - WatSupCriterionJTableRowData watsupCriterionRecord = (WatSupCriterionJTableRowData) rowData; - if(columnName.equals("Wat Sup Criterion")) - ret = compareStrings(getWatsupCriterion(), watsupCriterionRecord.getWatsupCriterion()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Criterion")) - dataValue = getStringValue(getWatsupCriterion()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Criterion", CellType.STRING, getWatsupCriterion(), missingRep)); - } - - public String getWatsupCriterion() { - return watsupCriterion; - } - - public void setWatsupCriterion(String watsupCriterion) { - this.watsupCriterion = watsupCriterion; - } - -} diff --git a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupMethodJTableRowData.java b/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupMethodJTableRowData.java deleted file mode 100644 index 6e389971f1..0000000000 --- a/javaUtilities/hydro/ohd.fcstservice/src/ohd/hseb/fcstservice/WatSupMethodJTableRowData.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.fcstservice; - -import ohd.hseb.util.gui.jtable.*; -import ohd.hseb.ihfsdb.generated.*; - -public class WatSupMethodJTableRowData extends AbstractJTableRowData -{ - private String watsupMethod; - private String missingRep = null; - - public WatSupMethodJTableRowData() - { - } - - public WatSupMethodJTableRowData(String missingRepresentation) - { - //setMissingRepresentation(missingRepresentation); - missingRep = missingRepresentation; - } - -/* public String toString() - { - String str = getWatsupMethod(); - return str; - } - - public int compare(String columnName, JTableRowData rowData) - { - int ret = 0; - WatSupMethodJTableRowData watsupMethodRecord = (WatSupMethodJTableRowData) rowData; - if(columnName.equals("Wat Sup Method")) - ret = compareStrings(getWatsupMethod(), watsupMethodRecord.getWatsupMethod()); - return ret; - } - - public String getDataValue(String columnName) - { - String dataValue = null; - if(columnName.equals("Wat Sup Method")) - dataValue = getStringValue(getWatsupMethod()); - return dataValue; - } -*/ - - public void addAllCellsToMap() - { - addCell(new BaseTableCell("Wat Sup Method", CellType.STRING, getWatsupMethod(), missingRep)); - } - - public String getWatsupMethod() { - return watsupMethod; - } - - public void setWatsupMethod(String watsupMethod) { - this.watsupMethod = watsupMethod; - } -} diff --git a/javaUtilities/hydro/ohd.ihfsdb/.classpath b/javaUtilities/hydro/ohd.ihfsdb/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.ihfsdb/.project b/javaUtilities/hydro/ohd.ihfsdb/.project deleted file mode 100644 index 1147b9d296..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.ihfsdb - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.ihfsdb/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.ihfsdb/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index c221916070..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 23 19:35:22 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.ihfsdb/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.ihfsdb/META-INF/MANIFEST.MF deleted file mode 100644 index 60a093617c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/META-INF/MANIFEST.MF +++ /dev/null @@ -1,8 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Ihfsdb -Bundle-SymbolicName: ohd.ihfsdb -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.db;bundle-version="1.0.0" -Export-Package: ohd.hseb.ihfsdb.generated diff --git a/javaUtilities/hydro/ohd.ihfsdb/PreferredTableNames.txt b/javaUtilities/hydro/ohd.ihfsdb/PreferredTableNames.txt deleted file mode 100644 index c94b90780b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/PreferredTableNames.txt +++ /dev/null @@ -1,195 +0,0 @@ -AdjustFactor -Admin -Agricultural -AlertAlarmVal -ArealFcst -ArealObs -Benchmark -City -ColorName -ColorOverlay -ColorValue -CommentValue -Contacts -ContingencyValue -CoopComms -CoopRecip -CoopSpons -Counties -CountyTransmit -Countynum -Crest -CurPC -CurPP -DPARadar -DailyPP -DamTypes -DataLimits -Datum -Dcp -DcpOwner -Descrip -DefiningIssueCriteria -Discharge -DpaAdapt -Eligzon -Evaporation -FcstDischarge -FcstGenMethod -FcstHeight -FcstHorizon -FcstOther -FcstPrecip -FcstPtDeterm -FcstPtESP -FcstPtService -FcstTemperature -FcstPtWatSup -FcstType -FishCount -Flood -FloodTs -Floodcat -Floodstmt -FlowType -FpPrevProd -FpPrevProdPractice -FrequencyUpdate -Gage -GageMaint -GageOwner -GageType -GateDam -GeoArea -Ground -Height -HgStation -HourlyPC -HourlyPP -Hsa -HydrologicMethod -Ice -IngestFilter -LWstmt -Lake -LatestObsValue -Lightning -LineSegs -LocArea -LocDataLimits -LocExtAgency -LocImage -Location -Lowwater -Moisture -MonthlyValues -NWRTransmitter -Network -OFSDataTrans -OFSStnTrans -Observer -OfficeNotes -PairedValue -PerfLog -PointDataPresets -PostProcessor -Power -Pressure -ProcValue -ProductLink -Proximity -PseudoGageVal -Pub -PurgeDynData -PurgeProduct -RequiredPeriod -RWBiasDyn -RWBiasStat -RWParams -RWPrefs -RWRadarResult -RWResult -RadarLoc -RadarResp -Radiation -Rating -RatingShift -RawPC -RawPP -RawPother -Refer -RejectedData -ResOwner -Rescap -Reservoir -ReservoirModel -Rfc -RiverMonGroup -RiverMonLocation -RiverStatus -Riverstat -RoutingMethod -RpfFcstGroup -RpfFcstPoint -RpfParams -S3PostAnalParams -S3PostAnalPrefs -SacSmaParams -SacSmaState -ServiceTableView -ServiceType -ShefDur -ShefEx -ShefPETrans -ShefPe -ShefProb -ShefQc -ShefTs -Snow -SnowMethod -SshpConfig -State -StnClass -Telem -TelmOwner -TelmPayor -TelmType -Temperature -TextProduct -TimeZone -UnitGraph -UnkStn -UnkStnValue -UserPrefs -VTECaction -VTECcause -VTECevent -VTECphenom -VTECpractice -VTECrecord -VTECsever -VTECsignif -WaterQuality -WatSupCoordAgency -WatSupMethod -WatSupCriterion -WatSupRespAgency -Weather -Wind -YUnique -Zonenum -AgencyOfficeUnique -CountyInfo -FpInfo -HvStation -HwStages -LocClass -LocPDC -LocRiverMon -LocTransmit -LocView -LocWfo -PrevProd -StatProf -StationList -ZoneInfo \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.ihfsdb/REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar b/javaUtilities/hydro/ohd.ihfsdb/REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar deleted file mode 100644 index a9156e958b..0000000000 Binary files a/javaUtilities/hydro/ohd.ihfsdb/REQUIRED_JARS/postgresql-8.3-603.jdbc3.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.ihfsdb/build.properties b/javaUtilities/hydro/ohd.ihfsdb/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.ihfsdb/build.xml b/javaUtilities/hydro/ohd.ihfsdb/build.xml deleted file mode 100644 index aaa8cab4d7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.ihfsdb/generate.xml b/javaUtilities/hydro/ohd.ihfsdb/generate.xml deleted file mode 100644 index acbd5bdcdf..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/generate.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.ihfsdb/ohd.ihfsdb.ecl b/javaUtilities/hydro/ohd.ihfsdb/ohd.ihfsdb.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.ihfsdb/scripts/create_table_names_file b/javaUtilities/hydro/ohd.ihfsdb/scripts/create_table_names_file deleted file mode 100644 index 3fb305e0aa..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/scripts/create_table_names_file +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/ksh - -export HOME_DIR=/fs/hseb/${DS_BUILD}/ohd -#export JAVA_DEV_DIR=$HOME_DIR/java/ohd-common/ -#export JAVA_DEV_DIR=$OHD_COMMON_JAVA_PROJECTS_BASE_DIR/.. -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. - -export IHFS_TABLE_DIR=$HOME_DIR/whfs/schema/IHFS/tables -export VIEW_DIR=$HOME_DIR/whfs/schema/IHFS/views - -export TABLE_FILE_TEMP=$PROJECTS_DIR/ihfsdb/scripts/PreferredTableNames.txt.temp -export TABLE_IHFS_FILE=$PROJECTS_DIR/ihfsdb/scripts/PreferredTableNames.txt -export LS="ls" -export CAT="cat" - -$LS $IHFS_TABLE_DIR $VIEW_DIR > $TABLE_FILE_TEMP -$CAT $TABLE_FILE_TEMP | grep -v '^s\.' | grep '\.t' |/usr/bin/cut -d. -f1 > $TABLE_IHFS_FILE -echo TABLE_IHFS_FILE = $TABLE_IHFS_FILE diff --git a/javaUtilities/hydro/ohd.ihfsdb/scripts/make_table_names.txt b/javaUtilities/hydro/ohd.ihfsdb/scripts/make_table_names.txt deleted file mode 100644 index 6cfa22597f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/scripts/make_table_names.txt +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - $(LS) $(IHFS_TABLE_DIR) $(VIEW_DIR) > $(TABLE_FILE_TEMP) - $(CAT) $(TABLE_FILE_TEMP) | grep -v '^s\.' | grep '\.t' |/usr/bin/cut -d. -f1 > $(TABLE_IHFS_FILE) - - - -ls $IHFS_TABLE_DIR $VIEW_DIR > table_file_temp.dat - - -cat table_file_temp | grep -v '^s\.' | grep '\.t' | /usr/bin/cut -d. -f1 > -PreferredIHFSTableNames.txt - - - - -dump generated .pgc files to -/fs/hseb/ob81/ohd/whfs/src/dbmsgen/TEXT - -dump .h files to -/fs/hseb/ob81/ohd/whfs/inc/lib/dbms/ diff --git a/javaUtilities/hydro/ohd.ihfsdb/scripts/run_ihfs_cdbgen b/javaUtilities/hydro/ohd.ihfsdb/scripts/run_ihfs_cdbgen deleted file mode 100644 index ec34f23919..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/scripts/run_ihfs_cdbgen +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/ksh - -if [ $LOGNAME != dsa ] -then - print "\nSkipping generation of IHFS DB C code...\n" - exit 0 -else - export JAVA_BIN_DIR=/usr/local/java//bin - - export DRIVERPATH=/usr/lib/postgresql-8.2-506.jdbc3.jar - export JAVA_VM_DIR=/fs/hseb/${DS_BUILD}/ohd/java/ohd-common/projects - export IHFSDB_DIR=$JAVA_VM_DIR/ihfsdb - export DB_DIR=$JAVA_VM_DIR/db - - export BASEPATH=$DB_DIR/classes - - export CLASSPATH=./:$BASEPATH/:$DRIVERPATH - echo "CLASSPATH =" $CLASSPATH - - #The connection string - connecturl="jdbc:postgresql://genessee:5432/hd_${DS_BUILD}empty?user=pguser" - - #The location of the PreferredTableNames.txt file. - namingfile=$IHFSDB_DIR/scripts/PreferredTableNames.txt - - #The destination of the generated source files - targetdir=/fs/hseb/${DS_BUILD}/ohd/whfs_lib/src/IHFSDbGenerated/TEXT - - #db name - dbname=hd_${DS_BUILD}empty - - #package name -- NONE means no packaging - # Note: this does NOT affect directly in which the generated class is placed - package=ohd.hseb.ihfsdb.generated - - db_driver_class_name=org.postgresql.Driver - - rm -f /fs/hseb/${DS_BUILD}/ohd/whfs_lib/src/IHFSDbGenerated/TEXT/*.pgc - rm -f /fs/hseb/${DS_BUILD}/ohd/whfs_lib/src/IHFSDbGenerated/TEXT/*.h - $JAVA_BIN_DIR/java ohd.hseb.dbgen.CDbGen $connecturl $namingfile $dbname $targetdir $db_driver_class_name - - mv $targetdir/*.h /fs/hseb/${DS_BUILD}/ohd/whfs_lib/inc/dbms/ - #cd - - return $? -fi diff --git a/javaUtilities/hydro/ohd.ihfsdb/scripts/run_ihfs_jdbgen b/javaUtilities/hydro/ohd.ihfsdb/scripts/run_ihfs_jdbgen deleted file mode 100644 index 1ee973f4c6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/scripts/run_ihfs_jdbgen +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/ksh - -export DRIVERPATH=/usr/lib/postgresql-8.2-506.jdbc3.jar -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. - -export IHFSDB_DIR=$PROJECTS_DIR/ihfsdb -export DB_DIR=$PROJECTS_DIR/db - -export BASEPATH=$DB_DIR/classes - -export CLASSPATH=./:$BASEPATH/:$DRIVERPATH -echo "CLASSPATH =" $CLASSPATH - -#The connection string -connecturl="jdbc:postgresql://genessee:5432/hd_${DS_BUILD}empty?user=pguser" - -#The location of the PreferredTableNames.txt file. -namingfile=$IHFSDB_DIR/scripts/PreferredTableNames.txt - -#The destination of the generated source files -targetdir=$IHFSDB_DIR/src/ohd/hseb/ihfsdb/generated - -#db name -dbname=hd_${DS_BUILD}empty - -#package name -- NONE means no packaging -# Note: this does NOT affect directly in which the generated class is placed -package=ohd.hseb.ihfsdb.generated - -db_driver_class_name=org.postgresql.Driver - -$JAVADIR/bin/java ohd.hseb.dbgen.JDbGen $connecturl $namingfile $dbname $package $targetdir $db_driver_class_name - -return $? diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdjustFactorRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdjustFactorRecord.java deleted file mode 100644 index bb90fa8623..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdjustFactorRecord.java +++ /dev/null @@ -1,185 +0,0 @@ -// filename: AdjustFactorRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// AdjustFactor table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class AdjustFactorRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private double divisor; - - private double base; - - private double multiplier; - - private double adder; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public AdjustFactorRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public AdjustFactorRecord(AdjustFactorRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setDivisor(origRecord.getDivisor()); - setBase(origRecord.getBase()); - setMultiplier(origRecord.getMultiplier()); - setAdder(origRecord.getAdder()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a AdjustFactor record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public double getDivisor() - { - return divisor; - } - - public void setDivisor(double divisor) - { - this.divisor = divisor ; - } - - public double getBase() - { - return base; - } - - public void setBase(double base) - { - this.base = base ; - } - - public double getMultiplier() - { - return multiplier; - } - - public void setMultiplier(double multiplier) - { - this.multiplier = multiplier ; - } - - public double getAdder() - { - return adder; - } - - public void setAdder(double adder) - { - this.adder = adder ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDivisor() + " " + - getBase() + " " + - getMultiplier() + " " + - getAdder() + " " + - "" ; - return outString; - } // end toString() -} // end of AdjustFactorRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdjustFactorTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdjustFactorTable.java deleted file mode 100644 index 861de06f66..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdjustFactorTable.java +++ /dev/null @@ -1,286 +0,0 @@ -// filename: AdjustFactorTable.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// adjustfactor table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class AdjustFactorTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// AdjustFactorTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public AdjustFactorTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("adjustfactor"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of AdjustFactorRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - AdjustFactorRecord record = null; - - // create a List to hold AdjustFactor Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM adjustfactor " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AdjustFactorRecord - // and store its address in oneRecord - record = new AdjustFactorRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AdjustFactorRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setDivisor(getDouble(rs, 6)); - record.setBase(getDouble(rs, 7)); - record.setMultiplier(getDouble(rs, 8)); - record.setAdder(getDouble(rs, 9)); - - // add this AdjustFactorRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the AdjustFactorRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of AdjustFactorRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - AdjustFactorRecord record = null; - - // create a List to hold AdjustFactor Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM adjustfactor " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AdjustFactorRecord - // and store its address in oneRecord - record = new AdjustFactorRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AdjustFactorRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setDivisor(getDouble(rs, 6)); - record.setBase(getDouble(rs, 7)); - record.setMultiplier(getDouble(rs, 8)); - record.setAdder(getDouble(rs, 9)); - - // add this AdjustFactorRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the AdjustFactorRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a AdjustFactorRecord object and.. -//----------------------------------------------------------------- - public int insert(AdjustFactorRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO adjustfactor VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setDouble(insertStatement, 6, record.getDivisor()); - setDouble(insertStatement, 7, record.getBase()); - setDouble(insertStatement, 8, record.getMultiplier()); - setDouble(insertStatement, 9, record.getAdder()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM adjustfactor " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AdjustFactorRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AdjustFactorRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE adjustfactor SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, divisor = ?, base = ?, multiplier = ?, adder = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setDouble(updateStatement, 6, record.getDivisor()); - setDouble(updateStatement, 7, record.getBase()); - setDouble(updateStatement, 8, record.getMultiplier()); - setDouble(updateStatement, 9, record.getAdder()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(AdjustFactorRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM adjustfactor " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AdjustFactorRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AdjustFactorRecord oldRecord, AdjustFactorRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE adjustfactor SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, divisor = ?, base = ?, multiplier = ?, adder = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setDouble(updateStatement, 6, newRecord.getDivisor()); - setDouble(updateStatement, 7, newRecord.getBase()); - setDouble(updateStatement, 8, newRecord.getMultiplier()); - setDouble(updateStatement, 9, newRecord.getAdder()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a AdjustFactorRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(AdjustFactorRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - AdjustFactorRecord oldRecord = (AdjustFactorRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of AdjustFactorTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdminRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdminRecord.java deleted file mode 100644 index 2856a22d1e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdminRecord.java +++ /dev/null @@ -1,209 +0,0 @@ -// filename: AdminRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Admin table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class AdminRecord extends DbRecord -{ - private String focalpoint; - - private String ofc; - - private String phone; - - private String region; - - private String regno; - - private String cd404; - - private long tenyr; - - private long oneyr; - - private String hsa; - - private short hsa_num; - - private String hb_password; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public AdminRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public AdminRecord(AdminRecord origRecord) - { - setFocalpoint(origRecord.getFocalpoint()); - setOfc(origRecord.getOfc()); - setPhone(origRecord.getPhone()); - setRegion(origRecord.getRegion()); - setRegno(origRecord.getRegno()); - setCd404(origRecord.getCd404()); - setTenyr(origRecord.getTenyr()); - setOneyr(origRecord.getOneyr()); - setHsa(origRecord.getHsa()); - setHsa_num(origRecord.getHsa_num()); - setHb_password(origRecord.getHb_password()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Admin record - - //----------------------------------------------------------------- - public String getFocalpoint() - { - return focalpoint; - } - - public void setFocalpoint(String focalpoint) - { - this.focalpoint = focalpoint ; - } - - public String getOfc() - { - return ofc; - } - - public void setOfc(String ofc) - { - this.ofc = ofc ; - } - - public String getPhone() - { - return phone; - } - - public void setPhone(String phone) - { - this.phone = phone ; - } - - public String getRegion() - { - return region; - } - - public void setRegion(String region) - { - this.region = region ; - } - - public String getRegno() - { - return regno; - } - - public void setRegno(String regno) - { - this.regno = regno ; - } - - public String getCd404() - { - return cd404; - } - - public void setCd404(String cd404) - { - this.cd404 = cd404 ; - } - - public long getTenyr() - { - return tenyr; - } - - public void setTenyr(long tenyr) - { - this.tenyr = tenyr ; - } - - public long getOneyr() - { - return oneyr; - } - - public void setOneyr(long oneyr) - { - this.oneyr = oneyr ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public short getHsa_num() - { - return hsa_num; - } - - public void setHsa_num(short hsa_num) - { - this.hsa_num = hsa_num ; - } - - public String getHb_password() - { - return hb_password; - } - - public void setHb_password(String hb_password) - { - this.hb_password = hb_password ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE hsa = '" + hsa + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getFocalpoint() + " " + - getOfc() + " " + - getPhone() + " " + - getRegion() + " " + - getRegno() + " " + - getCd404() + " " + - getDateStringFromLongTime(getTenyr()) + " " + - getDateStringFromLongTime(getOneyr()) + " " + - getHsa() + " " + - getHsa_num() + " " + - getHb_password() + " " + - "" ; - return outString; - } // end toString() -} // end of AdminRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdminTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdminTable.java deleted file mode 100644 index 9a95526ff6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AdminTable.java +++ /dev/null @@ -1,296 +0,0 @@ -// filename: AdminTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// admin table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class AdminTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// AdminTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public AdminTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("admin"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of AdminRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - AdminRecord record = null; - - // create a List to hold Admin Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM admin " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AdminRecord - // and store its address in oneRecord - record = new AdminRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AdminRecord object - - record.setFocalpoint(getString(rs, 1)); - record.setOfc(getString(rs, 2)); - record.setPhone(getString(rs, 3)); - record.setRegion(getString(rs, 4)); - record.setRegno(getString(rs, 5)); - record.setCd404(getString(rs, 6)); - record.setTenyr(getDate(rs, 7)); - record.setOneyr(getDate(rs, 8)); - record.setHsa(getString(rs, 9)); - record.setHsa_num(getShort(rs, 10)); - record.setHb_password(getString(rs, 11)); - - // add this AdminRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the AdminRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of AdminRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - AdminRecord record = null; - - // create a List to hold Admin Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM admin " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AdminRecord - // and store its address in oneRecord - record = new AdminRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AdminRecord object - - record.setFocalpoint(getString(rs, 1)); - record.setOfc(getString(rs, 2)); - record.setPhone(getString(rs, 3)); - record.setRegion(getString(rs, 4)); - record.setRegno(getString(rs, 5)); - record.setCd404(getString(rs, 6)); - record.setTenyr(getDate(rs, 7)); - record.setOneyr(getDate(rs, 8)); - record.setHsa(getString(rs, 9)); - record.setHsa_num(getShort(rs, 10)); - record.setHb_password(getString(rs, 11)); - - // add this AdminRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the AdminRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a AdminRecord object and.. -//----------------------------------------------------------------- - public int insert(AdminRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO admin VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getFocalpoint()); - setString(insertStatement, 2, record.getOfc()); - setString(insertStatement, 3, record.getPhone()); - setString(insertStatement, 4, record.getRegion()); - setString(insertStatement, 5, record.getRegno()); - setString(insertStatement, 6, record.getCd404()); - setDate(insertStatement, 7, record.getTenyr()); - setDate(insertStatement, 8, record.getOneyr()); - setString(insertStatement, 9, record.getHsa()); - setShort(insertStatement, 10, record.getHsa_num()); - setString(insertStatement, 11, record.getHb_password()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM admin " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AdminRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AdminRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE admin SET focalpoint = ?, ofc = ?, phone = ?, region = ?, regno = ?, cd404 = ?, tenyr = ?, oneyr = ?, hsa = ?, hsa_num = ?, hb_password = ? " + where ); - - setString(updateStatement, 1, record.getFocalpoint()); - setString(updateStatement, 2, record.getOfc()); - setString(updateStatement, 3, record.getPhone()); - setString(updateStatement, 4, record.getRegion()); - setString(updateStatement, 5, record.getRegno()); - setString(updateStatement, 6, record.getCd404()); - setDate(updateStatement, 7, record.getTenyr()); - setDate(updateStatement, 8, record.getOneyr()); - setString(updateStatement, 9, record.getHsa()); - setShort(updateStatement, 10, record.getHsa_num()); - setString(updateStatement, 11, record.getHb_password()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(AdminRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM admin " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AdminRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AdminRecord oldRecord, AdminRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE admin SET focalpoint = ?, ofc = ?, phone = ?, region = ?, regno = ?, cd404 = ?, tenyr = ?, oneyr = ?, hsa = ?, hsa_num = ?, hb_password = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getFocalpoint()); - setString(updateStatement, 2, newRecord.getOfc()); - setString(updateStatement, 3, newRecord.getPhone()); - setString(updateStatement, 4, newRecord.getRegion()); - setString(updateStatement, 5, newRecord.getRegno()); - setString(updateStatement, 6, newRecord.getCd404()); - setDate(updateStatement, 7, newRecord.getTenyr()); - setDate(updateStatement, 8, newRecord.getOneyr()); - setString(updateStatement, 9, newRecord.getHsa()); - setShort(updateStatement, 10, newRecord.getHsa_num()); - setString(updateStatement, 11, newRecord.getHb_password()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a AdminRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(AdminRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - AdminRecord oldRecord = (AdminRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of AdminTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgencyOfficeUniqueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgencyOfficeUniqueRecord.java deleted file mode 100644 index bea80b05d8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgencyOfficeUniqueRecord.java +++ /dev/null @@ -1,72 +0,0 @@ -// This is a view record ! -// filename: AgencyOfficeUniqueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// AgencyOfficeUnique table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class AgencyOfficeUniqueRecord extends DbRecord -{ - private String agency_code; - - private String office; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public AgencyOfficeUniqueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public AgencyOfficeUniqueRecord(AgencyOfficeUniqueRecord origRecord) - { - setAgency_code(origRecord.getAgency_code()); - setOffice(origRecord.getOffice()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a AgencyOfficeUnique record - - //----------------------------------------------------------------- - public String getAgency_code() - { - return agency_code; - } - - public void setAgency_code(String agency_code) - { - this.agency_code = agency_code ; - } - - public String getOffice() - { - return office; - } - - public void setOffice(String office) - { - this.office = office ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getAgency_code() + " " + - getOffice() + " " + - "" ; - return outString; - } // end toString() -} // end of AgencyOfficeUniqueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgencyOfficeUniqueView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgencyOfficeUniqueView.java deleted file mode 100644 index 05dfe01c09..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgencyOfficeUniqueView.java +++ /dev/null @@ -1,133 +0,0 @@ -// filename: AgencyOfficeUniqueView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// agencyofficeunique table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class AgencyOfficeUniqueView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// AgencyOfficeUniqueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public AgencyOfficeUniqueView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("agencyofficeunique"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of AgencyOfficeUniqueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - AgencyOfficeUniqueRecord record = null; - - // create a List to hold AgencyOfficeUnique Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM agencyofficeunique " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AgencyOfficeUniqueRecord - // and store its address in oneRecord - record = new AgencyOfficeUniqueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AgencyOfficeUniqueRecord object - - record.setAgency_code(getString(rs, 1)); - record.setOffice(getString(rs, 2)); - - // add this AgencyOfficeUniqueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the AgencyOfficeUniqueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of AgencyOfficeUniqueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - AgencyOfficeUniqueRecord record = null; - - // create a List to hold AgencyOfficeUnique Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM agencyofficeunique " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AgencyOfficeUniqueRecord - // and store its address in oneRecord - record = new AgencyOfficeUniqueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AgencyOfficeUniqueRecord object - - record.setAgency_code(getString(rs, 1)); - record.setOffice(getString(rs, 2)); - - // add this AgencyOfficeUniqueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the AgencyOfficeUniqueRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of AgencyOfficeUniqueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgriculturalRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgriculturalRecord.java deleted file mode 100644 index eb9617865c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgriculturalRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: AgriculturalRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Agricultural table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class AgriculturalRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public AgriculturalRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public AgriculturalRecord(AgriculturalRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Agricultural record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of AgriculturalRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgriculturalTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgriculturalTable.java deleted file mode 100644 index 7091010c21..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AgriculturalTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: AgriculturalTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// agricultural table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class AgriculturalTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// AgriculturalTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public AgriculturalTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("agricultural"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of AgriculturalRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - AgriculturalRecord record = null; - - // create a List to hold Agricultural Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM agricultural " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AgriculturalRecord - // and store its address in oneRecord - record = new AgriculturalRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AgriculturalRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this AgriculturalRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the AgriculturalRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of AgriculturalRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - AgriculturalRecord record = null; - - // create a List to hold Agricultural Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM agricultural " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AgriculturalRecord - // and store its address in oneRecord - record = new AgriculturalRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AgriculturalRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this AgriculturalRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the AgriculturalRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a AgriculturalRecord object and.. -//----------------------------------------------------------------- - public int insert(AgriculturalRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO agricultural VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM agricultural " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AgriculturalRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AgriculturalRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE agricultural SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(AgriculturalRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM agricultural " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AgriculturalRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AgriculturalRecord oldRecord, AgriculturalRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE agricultural SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a AgriculturalRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(AgriculturalRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - AgriculturalRecord oldRecord = (AgriculturalRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of AgriculturalTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AlertAlarmValRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AlertAlarmValRecord.java deleted file mode 100644 index 84979e5d97..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AlertAlarmValRecord.java +++ /dev/null @@ -1,330 +0,0 @@ -// filename: AlertAlarmValRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// AlertAlarmVal table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class AlertAlarmValRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private double suppl_value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - private long action_time; - - private String aa_categ; - - private String aa_check; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public AlertAlarmValRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public AlertAlarmValRecord(AlertAlarmValRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setSuppl_value(origRecord.getSuppl_value()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - setAction_time(origRecord.getAction_time()); - setAa_categ(origRecord.getAa_categ()); - setAa_check(origRecord.getAa_check()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a AlertAlarmVal record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public double getSuppl_value() - { - return suppl_value; - } - - public void setSuppl_value(double suppl_value) - { - this.suppl_value = suppl_value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public long getAction_time() - { - return action_time; - } - - public void setAction_time(long action_time) - { - this.action_time = action_time ; - } - - public String getAa_categ() - { - return aa_categ; - } - - public void setAa_categ(String aa_categ) - { - this.aa_categ = aa_categ ; - } - - public String getAa_check() - { - return aa_check; - } - - public void setAa_check(String aa_check) - { - this.aa_check = aa_check ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - + " AND aa_categ = '" + aa_categ + "'" - + " AND aa_check = '" + aa_check + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getSuppl_value() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getDateTimeStringFromLongTime(getAction_time()) + " " + - getAa_categ() + " " + - getAa_check() + " " + - "" ; - return outString; - } // end toString() -} // end of AlertAlarmValRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AlertAlarmValTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AlertAlarmValTable.java deleted file mode 100644 index e80325311e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/AlertAlarmValTable.java +++ /dev/null @@ -1,336 +0,0 @@ -// filename: AlertAlarmValTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// alertalarmval table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class AlertAlarmValTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// AlertAlarmValTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public AlertAlarmValTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("alertalarmval"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of AlertAlarmValRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - AlertAlarmValRecord record = null; - - // create a List to hold AlertAlarmVal Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM alertalarmval " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AlertAlarmValRecord - // and store its address in oneRecord - record = new AlertAlarmValRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AlertAlarmValRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setSuppl_value(getDouble(rs, 10)); - record.setShef_qual_code(getString(rs, 11)); - record.setQuality_code(getInt(rs, 12)); - record.setRevision(getShort(rs, 13)); - record.setProduct_id(getString(rs, 14)); - record.setProducttime(getTimeStamp(rs, 15)); - record.setPostingtime(getTimeStamp(rs, 16)); - record.setAction_time(getTimeStamp(rs, 17)); - record.setAa_categ(getString(rs, 18)); - record.setAa_check(getString(rs, 19)); - - // add this AlertAlarmValRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the AlertAlarmValRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of AlertAlarmValRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - AlertAlarmValRecord record = null; - - // create a List to hold AlertAlarmVal Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM alertalarmval " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a AlertAlarmValRecord - // and store its address in oneRecord - record = new AlertAlarmValRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a AlertAlarmValRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setSuppl_value(getDouble(rs, 10)); - record.setShef_qual_code(getString(rs, 11)); - record.setQuality_code(getInt(rs, 12)); - record.setRevision(getShort(rs, 13)); - record.setProduct_id(getString(rs, 14)); - record.setProducttime(getTimeStamp(rs, 15)); - record.setPostingtime(getTimeStamp(rs, 16)); - record.setAction_time(getTimeStamp(rs, 17)); - record.setAa_categ(getString(rs, 18)); - record.setAa_check(getString(rs, 19)); - - // add this AlertAlarmValRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the AlertAlarmValRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a AlertAlarmValRecord object and.. -//----------------------------------------------------------------- - public int insert(AlertAlarmValRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO alertalarmval VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setDouble(insertStatement, 10, record.getSuppl_value()); - setString(insertStatement, 11, record.getShef_qual_code()); - setInt(insertStatement, 12, record.getQuality_code()); - setShort(insertStatement, 13, record.getRevision()); - setString(insertStatement, 14, record.getProduct_id()); - setTimeStamp(insertStatement, 15, record.getProducttime()); - setTimeStamp(insertStatement, 16, record.getPostingtime()); - setTimeStamp(insertStatement, 17, record.getAction_time()); - setString(insertStatement, 18, record.getAa_categ()); - setString(insertStatement, 19, record.getAa_check()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM alertalarmval " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AlertAlarmValRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AlertAlarmValRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE alertalarmval SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, suppl_value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ?, action_time = ?, aa_categ = ?, aa_check = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setDouble(updateStatement, 10, record.getSuppl_value()); - setString(updateStatement, 11, record.getShef_qual_code()); - setInt(updateStatement, 12, record.getQuality_code()); - setShort(updateStatement, 13, record.getRevision()); - setString(updateStatement, 14, record.getProduct_id()); - setTimeStamp(updateStatement, 15, record.getProducttime()); - setTimeStamp(updateStatement, 16, record.getPostingtime()); - setTimeStamp(updateStatement, 17, record.getAction_time()); - setString(updateStatement, 18, record.getAa_categ()); - setString(updateStatement, 19, record.getAa_check()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(AlertAlarmValRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM alertalarmval " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a AlertAlarmValRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(AlertAlarmValRecord oldRecord, AlertAlarmValRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE alertalarmval SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, suppl_value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ?, action_time = ?, aa_categ = ?, aa_check = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setDouble(updateStatement, 10, newRecord.getSuppl_value()); - setString(updateStatement, 11, newRecord.getShef_qual_code()); - setInt(updateStatement, 12, newRecord.getQuality_code()); - setShort(updateStatement, 13, newRecord.getRevision()); - setString(updateStatement, 14, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 15, newRecord.getProducttime()); - setTimeStamp(updateStatement, 16, newRecord.getPostingtime()); - setTimeStamp(updateStatement, 17, newRecord.getAction_time()); - setString(updateStatement, 18, newRecord.getAa_categ()); - setString(updateStatement, 19, newRecord.getAa_check()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a AlertAlarmValRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(AlertAlarmValRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - AlertAlarmValRecord oldRecord = (AlertAlarmValRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of AlertAlarmValTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealFcstRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealFcstRecord.java deleted file mode 100644 index d83a3925db..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealFcstRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: ArealFcstRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ArealFcst table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ArealFcstRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ArealFcstRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ArealFcstRecord(ArealFcstRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ArealFcst record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of ArealFcstRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealFcstTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealFcstTable.java deleted file mode 100644 index 2ca914b952..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealFcstTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: ArealFcstTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// arealfcst table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ArealFcstTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ArealFcstTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ArealFcstTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("arealfcst"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ArealFcstRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ArealFcstRecord record = null; - - // create a List to hold ArealFcst Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM arealfcst " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ArealFcstRecord - // and store its address in oneRecord - record = new ArealFcstRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ArealFcstRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this ArealFcstRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ArealFcstRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ArealFcstRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ArealFcstRecord record = null; - - // create a List to hold ArealFcst Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM arealfcst " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ArealFcstRecord - // and store its address in oneRecord - record = new ArealFcstRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ArealFcstRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this ArealFcstRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ArealFcstRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ArealFcstRecord object and.. -//----------------------------------------------------------------- - public int insert(ArealFcstRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO arealfcst VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM arealfcst " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ArealFcstRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ArealFcstRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE arealfcst SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ArealFcstRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM arealfcst " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ArealFcstRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ArealFcstRecord oldRecord, ArealFcstRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE arealfcst SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ArealFcstRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ArealFcstRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ArealFcstRecord oldRecord = (ArealFcstRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ArealFcstTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealObsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealObsRecord.java deleted file mode 100644 index abf3ee4ea1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealObsRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: ArealObsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ArealObs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ArealObsRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ArealObsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ArealObsRecord(ArealObsRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ArealObs record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of ArealObsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealObsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealObsTable.java deleted file mode 100644 index fd2d3d3bc8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ArealObsTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: ArealObsTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// arealobs table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ArealObsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ArealObsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ArealObsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("arealobs"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ArealObsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ArealObsRecord record = null; - - // create a List to hold ArealObs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM arealobs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ArealObsRecord - // and store its address in oneRecord - record = new ArealObsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ArealObsRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this ArealObsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ArealObsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ArealObsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ArealObsRecord record = null; - - // create a List to hold ArealObs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM arealobs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ArealObsRecord - // and store its address in oneRecord - record = new ArealObsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ArealObsRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this ArealObsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ArealObsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ArealObsRecord object and.. -//----------------------------------------------------------------- - public int insert(ArealObsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO arealobs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM arealobs " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ArealObsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ArealObsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE arealobs SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ArealObsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM arealobs " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ArealObsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ArealObsRecord oldRecord, ArealObsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE arealobs SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ArealObsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ArealObsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ArealObsRecord oldRecord = (ArealObsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ArealObsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/BenchmarkRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/BenchmarkRecord.java deleted file mode 100644 index 01737a5e88..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/BenchmarkRecord.java +++ /dev/null @@ -1,112 +0,0 @@ -// filename: BenchmarkRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Benchmark table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class BenchmarkRecord extends DbRecord -{ - private String lid; - - private String bnum; - - private double elev; - - private String remark; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public BenchmarkRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public BenchmarkRecord(BenchmarkRecord origRecord) - { - setLid(origRecord.getLid()); - setBnum(origRecord.getBnum()); - setElev(origRecord.getElev()); - setRemark(origRecord.getRemark()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Benchmark record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getBnum() - { - return bnum; - } - - public void setBnum(String bnum) - { - this.bnum = bnum ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - - public String getRemark() - { - return remark; - } - - public void setRemark(String remark) - { - this.remark = remark ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND bnum = '" + bnum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getBnum() + " " + - getElev() + " " + - getRemark() + " " + - "" ; - return outString; - } // end toString() -} // end of BenchmarkRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/BenchmarkTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/BenchmarkTable.java deleted file mode 100644 index 09bec2f34b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/BenchmarkTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: BenchmarkTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// benchmark table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class BenchmarkTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// BenchmarkTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public BenchmarkTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("benchmark"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of BenchmarkRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - BenchmarkRecord record = null; - - // create a List to hold Benchmark Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM benchmark " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a BenchmarkRecord - // and store its address in oneRecord - record = new BenchmarkRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a BenchmarkRecord object - - record.setLid(getString(rs, 1)); - record.setBnum(getString(rs, 2)); - record.setElev(getDouble(rs, 3)); - record.setRemark(getString(rs, 4)); - - // add this BenchmarkRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the BenchmarkRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of BenchmarkRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - BenchmarkRecord record = null; - - // create a List to hold Benchmark Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM benchmark " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a BenchmarkRecord - // and store its address in oneRecord - record = new BenchmarkRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a BenchmarkRecord object - - record.setLid(getString(rs, 1)); - record.setBnum(getString(rs, 2)); - record.setElev(getDouble(rs, 3)); - record.setRemark(getString(rs, 4)); - - // add this BenchmarkRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the BenchmarkRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a BenchmarkRecord object and.. -//----------------------------------------------------------------- - public int insert(BenchmarkRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO benchmark VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getBnum()); - setDouble(insertStatement, 3, record.getElev()); - setString(insertStatement, 4, record.getRemark()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM benchmark " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a BenchmarkRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(BenchmarkRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE benchmark SET lid = ?, bnum = ?, elev = ?, remark = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getBnum()); - setDouble(updateStatement, 3, record.getElev()); - setString(updateStatement, 4, record.getRemark()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(BenchmarkRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM benchmark " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a BenchmarkRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(BenchmarkRecord oldRecord, BenchmarkRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE benchmark SET lid = ?, bnum = ?, elev = ?, remark = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getBnum()); - setDouble(updateStatement, 3, newRecord.getElev()); - setString(updateStatement, 4, newRecord.getRemark()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a BenchmarkRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(BenchmarkRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - BenchmarkRecord oldRecord = (BenchmarkRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of BenchmarkTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CityRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CityRecord.java deleted file mode 100644 index d2f795eea3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CityRecord.java +++ /dev/null @@ -1,127 +0,0 @@ -// filename: CityRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// City table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CityRecord extends DbRecord -{ - private String name; - - private String state; - - private double lat; - - private double lon; - - private int disp_precedence; - - private int population; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CityRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CityRecord(CityRecord origRecord) - { - setName(origRecord.getName()); - setState(origRecord.getState()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setDisp_precedence(origRecord.getDisp_precedence()); - setPopulation(origRecord.getPopulation()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a City record - - //----------------------------------------------------------------- - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public int getDisp_precedence() - { - return disp_precedence; - } - - public void setDisp_precedence(int disp_precedence) - { - this.disp_precedence = disp_precedence ; - } - - public int getPopulation() - { - return population; - } - - public void setPopulation(int population) - { - this.population = population ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getName() + " " + - getState() + " " + - getLat() + " " + - getLon() + " " + - getDisp_precedence() + " " + - getPopulation() + " " + - "" ; - return outString; - } // end toString() -} // end of CityRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CityTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CityTable.java deleted file mode 100644 index 419f6699f1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CityTable.java +++ /dev/null @@ -1,209 +0,0 @@ -// filename: CityTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// city table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CityTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CityTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CityTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("city"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CityRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CityRecord record = null; - - // create a List to hold City Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM city " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CityRecord - // and store its address in oneRecord - record = new CityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CityRecord object - - record.setName(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setDisp_precedence(getInt(rs, 5)); - record.setPopulation(getInt(rs, 6)); - - // add this CityRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CityRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CityRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CityRecord record = null; - - // create a List to hold City Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM city " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CityRecord - // and store its address in oneRecord - record = new CityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CityRecord object - - record.setName(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setDisp_precedence(getInt(rs, 5)); - record.setPopulation(getInt(rs, 6)); - - // add this CityRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CityRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CityRecord object and.. -//----------------------------------------------------------------- - public int insert(CityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO city VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getName()); - setString(insertStatement, 2, record.getState()); - setDouble(insertStatement, 3, record.getLat()); - setDouble(insertStatement, 4, record.getLon()); - setInt(insertStatement, 5, record.getDisp_precedence()); - setInt(insertStatement, 6, record.getPopulation()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM city " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CityRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE city SET name = ?, state = ?, lat = ?, lon = ?, disp_precedence = ?, population = ? " + where ); - - setString(updateStatement, 1, record.getName()); - setString(updateStatement, 2, record.getState()); - setDouble(updateStatement, 3, record.getLat()); - setDouble(updateStatement, 4, record.getLon()); - setInt(updateStatement, 5, record.getDisp_precedence()); - setInt(updateStatement, 6, record.getPopulation()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -} // end of CityTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorNameRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorNameRecord.java deleted file mode 100644 index dc0307b4e9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorNameRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: ColorNameRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ColorName table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ColorNameRecord extends DbRecord -{ - private String color_name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ColorNameRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ColorNameRecord(ColorNameRecord origRecord) - { - setColor_name(origRecord.getColor_name()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ColorName record - - //----------------------------------------------------------------- - public String getColor_name() - { - return color_name; - } - - public void setColor_name(String color_name) - { - this.color_name = color_name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE color_name = '" + color_name + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getColor_name() + " " + - "" ; - return outString; - } // end toString() -} // end of ColorNameRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorNameTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorNameTable.java deleted file mode 100644 index a268d73e64..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorNameTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: ColorNameTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// colorname table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ColorNameTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ColorNameTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ColorNameTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("colorname"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ColorNameRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ColorNameRecord record = null; - - // create a List to hold ColorName Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM colorname " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ColorNameRecord - // and store its address in oneRecord - record = new ColorNameRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ColorNameRecord object - - record.setColor_name(getString(rs, 1)); - - // add this ColorNameRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ColorNameRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ColorNameRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ColorNameRecord record = null; - - // create a List to hold ColorName Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM colorname " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ColorNameRecord - // and store its address in oneRecord - record = new ColorNameRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ColorNameRecord object - - record.setColor_name(getString(rs, 1)); - - // add this ColorNameRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ColorNameRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ColorNameRecord object and.. -//----------------------------------------------------------------- - public int insert(ColorNameRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO colorname VALUES (? )"); - - setString(insertStatement, 1, record.getColor_name()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM colorname " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ColorNameRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ColorNameRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE colorname SET color_name = ? " + where ); - - setString(updateStatement, 1, record.getColor_name()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ColorNameRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM colorname " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ColorNameRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ColorNameRecord oldRecord, ColorNameRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE colorname SET color_name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getColor_name()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ColorNameRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ColorNameRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ColorNameRecord oldRecord = (ColorNameRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ColorNameTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorOverlayRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorOverlayRecord.java deleted file mode 100644 index b9c6566d83..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorOverlayRecord.java +++ /dev/null @@ -1,113 +0,0 @@ -// filename: ColorOverlayRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ColorOverlay table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ColorOverlayRecord extends DbRecord -{ - private String userid; - - private String application_name; - - private String overlay_type; - - private String color_name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ColorOverlayRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ColorOverlayRecord(ColorOverlayRecord origRecord) - { - setUserid(origRecord.getUserid()); - setApplication_name(origRecord.getApplication_name()); - setOverlay_type(origRecord.getOverlay_type()); - setColor_name(origRecord.getColor_name()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ColorOverlay record - - //----------------------------------------------------------------- - public String getUserid() - { - return userid; - } - - public void setUserid(String userid) - { - this.userid = userid ; - } - - public String getApplication_name() - { - return application_name; - } - - public void setApplication_name(String application_name) - { - this.application_name = application_name ; - } - - public String getOverlay_type() - { - return overlay_type; - } - - public void setOverlay_type(String overlay_type) - { - this.overlay_type = overlay_type ; - } - - public String getColor_name() - { - return color_name; - } - - public void setColor_name(String color_name) - { - this.color_name = color_name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE userid = '" + userid + "'" - + " AND application_name = '" + application_name + "'" - + " AND overlay_type = '" + overlay_type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getUserid() + " " + - getApplication_name() + " " + - getOverlay_type() + " " + - getColor_name() + " " + - "" ; - return outString; - } // end toString() -} // end of ColorOverlayRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorOverlayTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorOverlayTable.java deleted file mode 100644 index 2374d828a7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorOverlayTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: ColorOverlayTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// coloroverlay table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ColorOverlayTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ColorOverlayTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ColorOverlayTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("coloroverlay"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ColorOverlayRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ColorOverlayRecord record = null; - - // create a List to hold ColorOverlay Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM coloroverlay " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ColorOverlayRecord - // and store its address in oneRecord - record = new ColorOverlayRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ColorOverlayRecord object - - record.setUserid(getString(rs, 1)); - record.setApplication_name(getString(rs, 2)); - record.setOverlay_type(getString(rs, 3)); - record.setColor_name(getString(rs, 4)); - - // add this ColorOverlayRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ColorOverlayRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ColorOverlayRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ColorOverlayRecord record = null; - - // create a List to hold ColorOverlay Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM coloroverlay " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ColorOverlayRecord - // and store its address in oneRecord - record = new ColorOverlayRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ColorOverlayRecord object - - record.setUserid(getString(rs, 1)); - record.setApplication_name(getString(rs, 2)); - record.setOverlay_type(getString(rs, 3)); - record.setColor_name(getString(rs, 4)); - - // add this ColorOverlayRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ColorOverlayRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ColorOverlayRecord object and.. -//----------------------------------------------------------------- - public int insert(ColorOverlayRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO coloroverlay VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getUserid()); - setString(insertStatement, 2, record.getApplication_name()); - setString(insertStatement, 3, record.getOverlay_type()); - setString(insertStatement, 4, record.getColor_name()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM coloroverlay " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ColorOverlayRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ColorOverlayRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE coloroverlay SET userid = ?, application_name = ?, overlay_type = ?, color_name = ? " + where ); - - setString(updateStatement, 1, record.getUserid()); - setString(updateStatement, 2, record.getApplication_name()); - setString(updateStatement, 3, record.getOverlay_type()); - setString(updateStatement, 4, record.getColor_name()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ColorOverlayRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM coloroverlay " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ColorOverlayRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ColorOverlayRecord oldRecord, ColorOverlayRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE coloroverlay SET userid = ?, application_name = ?, overlay_type = ?, color_name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getUserid()); - setString(updateStatement, 2, newRecord.getApplication_name()); - setString(updateStatement, 3, newRecord.getOverlay_type()); - setString(updateStatement, 4, newRecord.getColor_name()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ColorOverlayRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ColorOverlayRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ColorOverlayRecord oldRecord = (ColorOverlayRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ColorOverlayTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorValueRecord.java deleted file mode 100644 index f5d344f269..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorValueRecord.java +++ /dev/null @@ -1,158 +0,0 @@ -// filename: ColorValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ColorValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ColorValueRecord extends DbRecord -{ - private String userid; - - private String application_name; - - private String color_use_name; - - private int duration; - - private double threshold_value; - - private String threshold_unit; - - private String color_name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ColorValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ColorValueRecord(ColorValueRecord origRecord) - { - setUserid(origRecord.getUserid()); - setApplication_name(origRecord.getApplication_name()); - setColor_use_name(origRecord.getColor_use_name()); - setDuration(origRecord.getDuration()); - setThreshold_value(origRecord.getThreshold_value()); - setThreshold_unit(origRecord.getThreshold_unit()); - setColor_name(origRecord.getColor_name()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ColorValue record - - //----------------------------------------------------------------- - public String getUserid() - { - return userid; - } - - public void setUserid(String userid) - { - this.userid = userid ; - } - - public String getApplication_name() - { - return application_name; - } - - public void setApplication_name(String application_name) - { - this.application_name = application_name ; - } - - public String getColor_use_name() - { - return color_use_name; - } - - public void setColor_use_name(String color_use_name) - { - this.color_use_name = color_use_name ; - } - - public int getDuration() - { - return duration; - } - - public void setDuration(int duration) - { - this.duration = duration ; - } - - public double getThreshold_value() - { - return threshold_value; - } - - public void setThreshold_value(double threshold_value) - { - this.threshold_value = threshold_value ; - } - - public String getThreshold_unit() - { - return threshold_unit; - } - - public void setThreshold_unit(String threshold_unit) - { - this.threshold_unit = threshold_unit ; - } - - public String getColor_name() - { - return color_name; - } - - public void setColor_name(String color_name) - { - this.color_name = color_name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE userid = '" + userid + "'" - + " AND application_name = '" + application_name + "'" - + " AND color_use_name = '" + color_use_name + "'" - + " AND duration = '" + duration + "'" - + " AND threshold_value = '" + threshold_value + "'" - + " AND threshold_unit = '" + threshold_unit + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getUserid() + " " + - getApplication_name() + " " + - getColor_use_name() + " " + - getDuration() + " " + - getThreshold_value() + " " + - getThreshold_unit() + " " + - getColor_name() + " " + - "" ; - return outString; - } // end toString() -} // end of ColorValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorValueTable.java deleted file mode 100644 index df33becc7f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ColorValueTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: ColorValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// colorvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ColorValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ColorValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ColorValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("colorvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ColorValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ColorValueRecord record = null; - - // create a List to hold ColorValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM colorvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ColorValueRecord - // and store its address in oneRecord - record = new ColorValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ColorValueRecord object - - record.setUserid(getString(rs, 1)); - record.setApplication_name(getString(rs, 2)); - record.setColor_use_name(getString(rs, 3)); - record.setDuration(getInt(rs, 4)); - record.setThreshold_value(getDouble(rs, 5)); - record.setThreshold_unit(getString(rs, 6)); - record.setColor_name(getString(rs, 7)); - - // add this ColorValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ColorValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ColorValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ColorValueRecord record = null; - - // create a List to hold ColorValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM colorvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ColorValueRecord - // and store its address in oneRecord - record = new ColorValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ColorValueRecord object - - record.setUserid(getString(rs, 1)); - record.setApplication_name(getString(rs, 2)); - record.setColor_use_name(getString(rs, 3)); - record.setDuration(getInt(rs, 4)); - record.setThreshold_value(getDouble(rs, 5)); - record.setThreshold_unit(getString(rs, 6)); - record.setColor_name(getString(rs, 7)); - - // add this ColorValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ColorValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ColorValueRecord object and.. -//----------------------------------------------------------------- - public int insert(ColorValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO colorvalue VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getUserid()); - setString(insertStatement, 2, record.getApplication_name()); - setString(insertStatement, 3, record.getColor_use_name()); - setInt(insertStatement, 4, record.getDuration()); - setDouble(insertStatement, 5, record.getThreshold_value()); - setString(insertStatement, 6, record.getThreshold_unit()); - setString(insertStatement, 7, record.getColor_name()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM colorvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ColorValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ColorValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE colorvalue SET userid = ?, application_name = ?, color_use_name = ?, duration = ?, threshold_value = ?, threshold_unit = ?, color_name = ? " + where ); - - setString(updateStatement, 1, record.getUserid()); - setString(updateStatement, 2, record.getApplication_name()); - setString(updateStatement, 3, record.getColor_use_name()); - setInt(updateStatement, 4, record.getDuration()); - setDouble(updateStatement, 5, record.getThreshold_value()); - setString(updateStatement, 6, record.getThreshold_unit()); - setString(updateStatement, 7, record.getColor_name()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ColorValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM colorvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ColorValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ColorValueRecord oldRecord, ColorValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE colorvalue SET userid = ?, application_name = ?, color_use_name = ?, duration = ?, threshold_value = ?, threshold_unit = ?, color_name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getUserid()); - setString(updateStatement, 2, newRecord.getApplication_name()); - setString(updateStatement, 3, newRecord.getColor_use_name()); - setInt(updateStatement, 4, newRecord.getDuration()); - setDouble(updateStatement, 5, newRecord.getThreshold_value()); - setString(updateStatement, 6, newRecord.getThreshold_unit()); - setString(updateStatement, 7, newRecord.getColor_name()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ColorValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ColorValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ColorValueRecord oldRecord = (ColorValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ColorValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CommentValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CommentValueRecord.java deleted file mode 100644 index 7bc56898f6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CommentValueRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: CommentValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CommentValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CommentValueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - private String shef_comment; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CommentValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CommentValueRecord(CommentValueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - setShef_comment(origRecord.getShef_comment()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CommentValue record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public String getShef_comment() - { - return shef_comment; - } - - public void setShef_comment(String shef_comment) - { - this.shef_comment = shef_comment ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getShef_comment() + " " + - "" ; - return outString; - } // end toString() -} // end of CommentValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CommentValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CommentValueTable.java deleted file mode 100644 index a8dda1a5a5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CommentValueTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: CommentValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// commentvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CommentValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CommentValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CommentValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("commentvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CommentValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CommentValueRecord record = null; - - // create a List to hold CommentValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM commentvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CommentValueRecord - // and store its address in oneRecord - record = new CommentValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CommentValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setRevision(getShort(rs, 11)); - record.setProduct_id(getString(rs, 12)); - record.setProducttime(getTimeStamp(rs, 13)); - record.setPostingtime(getTimeStamp(rs, 14)); - record.setShef_comment(getString(rs, 15)); - - // add this CommentValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CommentValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CommentValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CommentValueRecord record = null; - - // create a List to hold CommentValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM commentvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CommentValueRecord - // and store its address in oneRecord - record = new CommentValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CommentValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setRevision(getShort(rs, 11)); - record.setProduct_id(getString(rs, 12)); - record.setProducttime(getTimeStamp(rs, 13)); - record.setPostingtime(getTimeStamp(rs, 14)); - record.setShef_comment(getString(rs, 15)); - - // add this CommentValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CommentValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CommentValueRecord object and.. -//----------------------------------------------------------------- - public int insert(CommentValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO commentvalue VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setShort(insertStatement, 11, record.getRevision()); - setString(insertStatement, 12, record.getProduct_id()); - setTimeStamp(insertStatement, 13, record.getProducttime()); - setTimeStamp(insertStatement, 14, record.getPostingtime()); - setString(insertStatement, 15, record.getShef_comment()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM commentvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CommentValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CommentValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE commentvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ?, shef_comment = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setShort(updateStatement, 11, record.getRevision()); - setString(updateStatement, 12, record.getProduct_id()); - setTimeStamp(updateStatement, 13, record.getProducttime()); - setTimeStamp(updateStatement, 14, record.getPostingtime()); - setString(updateStatement, 15, record.getShef_comment()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CommentValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM commentvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CommentValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CommentValueRecord oldRecord, CommentValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE commentvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ?, shef_comment = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setShort(updateStatement, 11, newRecord.getRevision()); - setString(updateStatement, 12, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 13, newRecord.getProducttime()); - setTimeStamp(updateStatement, 14, newRecord.getPostingtime()); - setString(updateStatement, 15, newRecord.getShef_comment()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CommentValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CommentValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CommentValueRecord oldRecord = (CommentValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CommentValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContactsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContactsRecord.java deleted file mode 100644 index 65ac460db4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContactsRecord.java +++ /dev/null @@ -1,140 +0,0 @@ -// filename: ContactsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Contacts table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ContactsRecord extends DbRecord -{ - private String lid; - - private String contact; - - private String phone; - - private String email; - - private String remark; - - private int priority; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ContactsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ContactsRecord(ContactsRecord origRecord) - { - setLid(origRecord.getLid()); - setContact(origRecord.getContact()); - setPhone(origRecord.getPhone()); - setEmail(origRecord.getEmail()); - setRemark(origRecord.getRemark()); - setPriority(origRecord.getPriority()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Contacts record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getContact() - { - return contact; - } - - public void setContact(String contact) - { - this.contact = contact ; - } - - public String getPhone() - { - return phone; - } - - public void setPhone(String phone) - { - this.phone = phone ; - } - - public String getEmail() - { - return email; - } - - public void setEmail(String email) - { - this.email = email ; - } - - public String getRemark() - { - return remark; - } - - public void setRemark(String remark) - { - this.remark = remark ; - } - - public int getPriority() - { - return priority; - } - - public void setPriority(int priority) - { - this.priority = priority ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND contact = '" + contact + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getContact() + " " + - getPhone() + " " + - getEmail() + " " + - getRemark() + " " + - getPriority() + " " + - "" ; - return outString; - } // end toString() -} // end of ContactsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContactsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContactsTable.java deleted file mode 100644 index 39ccd60d32..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContactsTable.java +++ /dev/null @@ -1,271 +0,0 @@ -// filename: ContactsTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// contacts table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ContactsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ContactsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ContactsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("contacts"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ContactsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ContactsRecord record = null; - - // create a List to hold Contacts Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM contacts " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ContactsRecord - // and store its address in oneRecord - record = new ContactsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ContactsRecord object - - record.setLid(getString(rs, 1)); - record.setContact(getString(rs, 2)); - record.setPhone(getString(rs, 3)); - record.setEmail(getString(rs, 4)); - record.setRemark(getString(rs, 5)); - record.setPriority(getInt(rs, 6)); - - // add this ContactsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ContactsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ContactsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ContactsRecord record = null; - - // create a List to hold Contacts Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM contacts " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ContactsRecord - // and store its address in oneRecord - record = new ContactsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ContactsRecord object - - record.setLid(getString(rs, 1)); - record.setContact(getString(rs, 2)); - record.setPhone(getString(rs, 3)); - record.setEmail(getString(rs, 4)); - record.setRemark(getString(rs, 5)); - record.setPriority(getInt(rs, 6)); - - // add this ContactsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ContactsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ContactsRecord object and.. -//----------------------------------------------------------------- - public int insert(ContactsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO contacts VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getContact()); - setString(insertStatement, 3, record.getPhone()); - setString(insertStatement, 4, record.getEmail()); - setString(insertStatement, 5, record.getRemark()); - setInt(insertStatement, 6, record.getPriority()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM contacts " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ContactsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ContactsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE contacts SET lid = ?, contact = ?, phone = ?, email = ?, remark = ?, priority = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getContact()); - setString(updateStatement, 3, record.getPhone()); - setString(updateStatement, 4, record.getEmail()); - setString(updateStatement, 5, record.getRemark()); - setInt(updateStatement, 6, record.getPriority()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ContactsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM contacts " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ContactsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ContactsRecord oldRecord, ContactsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE contacts SET lid = ?, contact = ?, phone = ?, email = ?, remark = ?, priority = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getContact()); - setString(updateStatement, 3, newRecord.getPhone()); - setString(updateStatement, 4, newRecord.getEmail()); - setString(updateStatement, 5, newRecord.getRemark()); - setInt(updateStatement, 6, newRecord.getPriority()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ContactsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ContactsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ContactsRecord oldRecord = (ContactsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ContactsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContingencyValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContingencyValueRecord.java deleted file mode 100644 index 484827ee91..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContingencyValueRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: ContingencyValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ContingencyValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ContingencyValueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ContingencyValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ContingencyValueRecord(ContingencyValueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ContingencyValue record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of ContingencyValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContingencyValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContingencyValueTable.java deleted file mode 100644 index a83b0e21a1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ContingencyValueTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: ContingencyValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// contingencyvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ContingencyValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ContingencyValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ContingencyValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("contingencyvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ContingencyValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ContingencyValueRecord record = null; - - // create a List to hold ContingencyValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM contingencyvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ContingencyValueRecord - // and store its address in oneRecord - record = new ContingencyValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ContingencyValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this ContingencyValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ContingencyValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ContingencyValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ContingencyValueRecord record = null; - - // create a List to hold ContingencyValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM contingencyvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ContingencyValueRecord - // and store its address in oneRecord - record = new ContingencyValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ContingencyValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this ContingencyValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ContingencyValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ContingencyValueRecord object and.. -//----------------------------------------------------------------- - public int insert(ContingencyValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO contingencyvalue VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM contingencyvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ContingencyValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ContingencyValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE contingencyvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ContingencyValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM contingencyvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ContingencyValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ContingencyValueRecord oldRecord, ContingencyValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE contingencyvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ContingencyValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ContingencyValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ContingencyValueRecord oldRecord = (ContingencyValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ContingencyValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopCommsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopCommsRecord.java deleted file mode 100644 index 0021b38149..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopCommsRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: CoopCommsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CoopComms table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CoopCommsRecord extends DbRecord -{ - private String comm; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CoopCommsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CoopCommsRecord(CoopCommsRecord origRecord) - { - setComm(origRecord.getComm()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CoopComms record - - //----------------------------------------------------------------- - public String getComm() - { - return comm; - } - - public void setComm(String comm) - { - this.comm = comm ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE comm = '" + comm + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getComm() + " " + - "" ; - return outString; - } // end toString() -} // end of CoopCommsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopCommsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopCommsTable.java deleted file mode 100644 index 76041b0d0e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopCommsTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: CoopCommsTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// coopcomms table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CoopCommsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CoopCommsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CoopCommsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("coopcomms"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CoopCommsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CoopCommsRecord record = null; - - // create a List to hold CoopComms Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM coopcomms " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CoopCommsRecord - // and store its address in oneRecord - record = new CoopCommsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CoopCommsRecord object - - record.setComm(getString(rs, 1)); - - // add this CoopCommsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CoopCommsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CoopCommsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CoopCommsRecord record = null; - - // create a List to hold CoopComms Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM coopcomms " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CoopCommsRecord - // and store its address in oneRecord - record = new CoopCommsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CoopCommsRecord object - - record.setComm(getString(rs, 1)); - - // add this CoopCommsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CoopCommsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CoopCommsRecord object and.. -//----------------------------------------------------------------- - public int insert(CoopCommsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO coopcomms VALUES (? )"); - - setString(insertStatement, 1, record.getComm()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM coopcomms " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CoopCommsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CoopCommsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE coopcomms SET comm = ? " + where ); - - setString(updateStatement, 1, record.getComm()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CoopCommsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM coopcomms " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CoopCommsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CoopCommsRecord oldRecord, CoopCommsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE coopcomms SET comm = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getComm()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CoopCommsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CoopCommsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CoopCommsRecord oldRecord = (CoopCommsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CoopCommsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopRecipRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopRecipRecord.java deleted file mode 100644 index c6c3ecd04e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopRecipRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: CoopRecipRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CoopRecip table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CoopRecipRecord extends DbRecord -{ - private String recip; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CoopRecipRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CoopRecipRecord(CoopRecipRecord origRecord) - { - setRecip(origRecord.getRecip()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CoopRecip record - - //----------------------------------------------------------------- - public String getRecip() - { - return recip; - } - - public void setRecip(String recip) - { - this.recip = recip ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE recip = '" + recip + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRecip() + " " + - "" ; - return outString; - } // end toString() -} // end of CoopRecipRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopRecipTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopRecipTable.java deleted file mode 100644 index 130962cd70..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopRecipTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: CoopRecipTable.java -// author : DBGEN -// created : Tue May 31 17:52:19 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// cooprecip table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CoopRecipTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CoopRecipTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CoopRecipTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("cooprecip"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CoopRecipRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CoopRecipRecord record = null; - - // create a List to hold CoopRecip Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM cooprecip " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CoopRecipRecord - // and store its address in oneRecord - record = new CoopRecipRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CoopRecipRecord object - - record.setRecip(getString(rs, 1)); - - // add this CoopRecipRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CoopRecipRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CoopRecipRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CoopRecipRecord record = null; - - // create a List to hold CoopRecip Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM cooprecip " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CoopRecipRecord - // and store its address in oneRecord - record = new CoopRecipRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CoopRecipRecord object - - record.setRecip(getString(rs, 1)); - - // add this CoopRecipRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CoopRecipRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CoopRecipRecord object and.. -//----------------------------------------------------------------- - public int insert(CoopRecipRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO cooprecip VALUES (? )"); - - setString(insertStatement, 1, record.getRecip()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM cooprecip " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CoopRecipRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CoopRecipRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE cooprecip SET recip = ? " + where ); - - setString(updateStatement, 1, record.getRecip()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CoopRecipRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM cooprecip " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CoopRecipRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CoopRecipRecord oldRecord, CoopRecipRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE cooprecip SET recip = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRecip()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CoopRecipRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CoopRecipRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CoopRecipRecord oldRecord = (CoopRecipRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CoopRecipTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopSponsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopSponsRecord.java deleted file mode 100644 index 242a46fc96..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopSponsRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: CoopSponsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CoopSpons table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CoopSponsRecord extends DbRecord -{ - private String spons; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CoopSponsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CoopSponsRecord(CoopSponsRecord origRecord) - { - setSpons(origRecord.getSpons()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CoopSpons record - - //----------------------------------------------------------------- - public String getSpons() - { - return spons; - } - - public void setSpons(String spons) - { - this.spons = spons ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE spons = '" + spons + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getSpons() + " " + - "" ; - return outString; - } // end toString() -} // end of CoopSponsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopSponsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopSponsTable.java deleted file mode 100644 index c16249a293..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CoopSponsTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: CoopSponsTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// coopspons table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CoopSponsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CoopSponsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CoopSponsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("coopspons"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CoopSponsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CoopSponsRecord record = null; - - // create a List to hold CoopSpons Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM coopspons " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CoopSponsRecord - // and store its address in oneRecord - record = new CoopSponsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CoopSponsRecord object - - record.setSpons(getString(rs, 1)); - - // add this CoopSponsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CoopSponsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CoopSponsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CoopSponsRecord record = null; - - // create a List to hold CoopSpons Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM coopspons " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CoopSponsRecord - // and store its address in oneRecord - record = new CoopSponsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CoopSponsRecord object - - record.setSpons(getString(rs, 1)); - - // add this CoopSponsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CoopSponsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CoopSponsRecord object and.. -//----------------------------------------------------------------- - public int insert(CoopSponsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO coopspons VALUES (? )"); - - setString(insertStatement, 1, record.getSpons()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM coopspons " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CoopSponsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CoopSponsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE coopspons SET spons = ? " + where ); - - setString(updateStatement, 1, record.getSpons()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CoopSponsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM coopspons " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CoopSponsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CoopSponsRecord oldRecord, CoopSponsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE coopspons SET spons = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getSpons()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CoopSponsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CoopSponsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CoopSponsRecord oldRecord = (CoopSponsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CoopSponsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountiesRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountiesRecord.java deleted file mode 100644 index 9db93899c0..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountiesRecord.java +++ /dev/null @@ -1,140 +0,0 @@ -// filename: CountiesRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Counties table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CountiesRecord extends DbRecord -{ - private String county; - - private String state; - - private String countynum; - - private String wfo; - - private String primary_back; - - private String secondary_back; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CountiesRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CountiesRecord(CountiesRecord origRecord) - { - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setCountynum(origRecord.getCountynum()); - setWfo(origRecord.getWfo()); - setPrimary_back(origRecord.getPrimary_back()); - setSecondary_back(origRecord.getSecondary_back()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Counties record - - //----------------------------------------------------------------- - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getCountynum() - { - return countynum; - } - - public void setCountynum(String countynum) - { - this.countynum = countynum ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getPrimary_back() - { - return primary_back; - } - - public void setPrimary_back(String primary_back) - { - this.primary_back = primary_back ; - } - - public String getSecondary_back() - { - return secondary_back; - } - - public void setSecondary_back(String secondary_back) - { - this.secondary_back = secondary_back ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE county = '" + county + "'" - + " AND state = '" + state + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getCounty() + " " + - getState() + " " + - getCountynum() + " " + - getWfo() + " " + - getPrimary_back() + " " + - getSecondary_back() + " " + - "" ; - return outString; - } // end toString() -} // end of CountiesRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountiesTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountiesTable.java deleted file mode 100644 index 3d891f4a4c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountiesTable.java +++ /dev/null @@ -1,271 +0,0 @@ -// filename: CountiesTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// counties table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CountiesTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CountiesTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CountiesTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("counties"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CountiesRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CountiesRecord record = null; - - // create a List to hold Counties Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM counties " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountiesRecord - // and store its address in oneRecord - record = new CountiesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountiesRecord object - - record.setCounty(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setCountynum(getString(rs, 3)); - record.setWfo(getString(rs, 4)); - record.setPrimary_back(getString(rs, 5)); - record.setSecondary_back(getString(rs, 6)); - - // add this CountiesRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CountiesRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CountiesRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CountiesRecord record = null; - - // create a List to hold Counties Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM counties " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountiesRecord - // and store its address in oneRecord - record = new CountiesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountiesRecord object - - record.setCounty(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setCountynum(getString(rs, 3)); - record.setWfo(getString(rs, 4)); - record.setPrimary_back(getString(rs, 5)); - record.setSecondary_back(getString(rs, 6)); - - // add this CountiesRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CountiesRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CountiesRecord object and.. -//----------------------------------------------------------------- - public int insert(CountiesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO counties VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getCounty()); - setString(insertStatement, 2, record.getState()); - setString(insertStatement, 3, record.getCountynum()); - setString(insertStatement, 4, record.getWfo()); - setString(insertStatement, 5, record.getPrimary_back()); - setString(insertStatement, 6, record.getSecondary_back()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM counties " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CountiesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CountiesRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE counties SET county = ?, state = ?, countynum = ?, wfo = ?, primary_back = ?, secondary_back = ? " + where ); - - setString(updateStatement, 1, record.getCounty()); - setString(updateStatement, 2, record.getState()); - setString(updateStatement, 3, record.getCountynum()); - setString(updateStatement, 4, record.getWfo()); - setString(updateStatement, 5, record.getPrimary_back()); - setString(updateStatement, 6, record.getSecondary_back()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CountiesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM counties " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CountiesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CountiesRecord oldRecord, CountiesRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE counties SET county = ?, state = ?, countynum = ?, wfo = ?, primary_back = ?, secondary_back = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getCounty()); - setString(updateStatement, 2, newRecord.getState()); - setString(updateStatement, 3, newRecord.getCountynum()); - setString(updateStatement, 4, newRecord.getWfo()); - setString(updateStatement, 5, newRecord.getPrimary_back()); - setString(updateStatement, 6, newRecord.getSecondary_back()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CountiesRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CountiesRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CountiesRecord oldRecord = (CountiesRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CountiesTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyInfoRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyInfoRecord.java deleted file mode 100644 index 834877f269..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyInfoRecord.java +++ /dev/null @@ -1,100 +0,0 @@ -// This is a view record ! -// filename: CountyInfoRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CountyInfo table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CountyInfoRecord extends DbRecord -{ - private String lid; - - private String state; - - private String county; - - private String countynum; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CountyInfoRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CountyInfoRecord(CountyInfoRecord origRecord) - { - setLid(origRecord.getLid()); - setState(origRecord.getState()); - setCounty(origRecord.getCounty()); - setCountynum(origRecord.getCountynum()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CountyInfo record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getCountynum() - { - return countynum; - } - - public void setCountynum(String countynum) - { - this.countynum = countynum ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getState() + " " + - getCounty() + " " + - getCountynum() + " " + - "" ; - return outString; - } // end toString() -} // end of CountyInfoRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyInfoView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyInfoView.java deleted file mode 100644 index 883e46bb3f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyInfoView.java +++ /dev/null @@ -1,137 +0,0 @@ -// filename: CountyInfoView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// countyinfo table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CountyInfoView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CountyInfoTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CountyInfoView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("countyinfo"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CountyInfoRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CountyInfoRecord record = null; - - // create a List to hold CountyInfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM countyinfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountyInfoRecord - // and store its address in oneRecord - record = new CountyInfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountyInfoRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - record.setCountynum(getString(rs, 4)); - - // add this CountyInfoRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CountyInfoRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CountyInfoRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CountyInfoRecord record = null; - - // create a List to hold CountyInfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM countyinfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountyInfoRecord - // and store its address in oneRecord - record = new CountyInfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountyInfoRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - record.setCountynum(getString(rs, 4)); - - // add this CountyInfoRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CountyInfoRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of CountyInfoTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyTransmitRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyTransmitRecord.java deleted file mode 100644 index 70c0541100..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyTransmitRecord.java +++ /dev/null @@ -1,99 +0,0 @@ -// filename: CountyTransmitRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CountyTransmit table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CountyTransmitRecord extends DbRecord -{ - private String call_sign; - - private String county; - - private String state; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CountyTransmitRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CountyTransmitRecord(CountyTransmitRecord origRecord) - { - setCall_sign(origRecord.getCall_sign()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CountyTransmit record - - //----------------------------------------------------------------- - public String getCall_sign() - { - return call_sign; - } - - public void setCall_sign(String call_sign) - { - this.call_sign = call_sign ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE call_sign = '" + call_sign + "'" - + " AND county = '" + county + "'" - + " AND state = '" + state + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getCall_sign() + " " + - getCounty() + " " + - getState() + " " + - "" ; - return outString; - } // end toString() -} // end of CountyTransmitRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyTransmitTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyTransmitTable.java deleted file mode 100644 index 6c6c2ff47b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountyTransmitTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: CountyTransmitTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// countytransmit table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CountyTransmitTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CountyTransmitTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CountyTransmitTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("countytransmit"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CountyTransmitRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CountyTransmitRecord record = null; - - // create a List to hold CountyTransmit Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM countytransmit " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountyTransmitRecord - // and store its address in oneRecord - record = new CountyTransmitRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountyTransmitRecord object - - record.setCall_sign(getString(rs, 1)); - record.setCounty(getString(rs, 2)); - record.setState(getString(rs, 3)); - - // add this CountyTransmitRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CountyTransmitRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CountyTransmitRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CountyTransmitRecord record = null; - - // create a List to hold CountyTransmit Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM countytransmit " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountyTransmitRecord - // and store its address in oneRecord - record = new CountyTransmitRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountyTransmitRecord object - - record.setCall_sign(getString(rs, 1)); - record.setCounty(getString(rs, 2)); - record.setState(getString(rs, 3)); - - // add this CountyTransmitRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CountyTransmitRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CountyTransmitRecord object and.. -//----------------------------------------------------------------- - public int insert(CountyTransmitRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO countytransmit VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getCall_sign()); - setString(insertStatement, 2, record.getCounty()); - setString(insertStatement, 3, record.getState()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM countytransmit " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CountyTransmitRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CountyTransmitRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE countytransmit SET call_sign = ?, county = ?, state = ? " + where ); - - setString(updateStatement, 1, record.getCall_sign()); - setString(updateStatement, 2, record.getCounty()); - setString(updateStatement, 3, record.getState()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CountyTransmitRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM countytransmit " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CountyTransmitRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CountyTransmitRecord oldRecord, CountyTransmitRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE countytransmit SET call_sign = ?, county = ?, state = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getCall_sign()); - setString(updateStatement, 2, newRecord.getCounty()); - setString(updateStatement, 3, newRecord.getState()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CountyTransmitRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CountyTransmitRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CountyTransmitRecord oldRecord = (CountyTransmitRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CountyTransmitTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountynumRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountynumRecord.java deleted file mode 100644 index 325dbb546a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountynumRecord.java +++ /dev/null @@ -1,99 +0,0 @@ -// filename: CountynumRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Countynum table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CountynumRecord extends DbRecord -{ - private String lid; - - private String state; - - private String county; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CountynumRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CountynumRecord(CountynumRecord origRecord) - { - setLid(origRecord.getLid()); - setState(origRecord.getState()); - setCounty(origRecord.getCounty()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Countynum record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND state = '" + state + "'" - + " AND county = '" + county + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getState() + " " + - getCounty() + " " + - "" ; - return outString; - } // end toString() -} // end of CountynumRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountynumTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountynumTable.java deleted file mode 100644 index 013eb00db1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CountynumTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: CountynumTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// countynum table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CountynumTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CountynumTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CountynumTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("countynum"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CountynumRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CountynumRecord record = null; - - // create a List to hold Countynum Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM countynum " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountynumRecord - // and store its address in oneRecord - record = new CountynumRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountynumRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - - // add this CountynumRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CountynumRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CountynumRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CountynumRecord record = null; - - // create a List to hold Countynum Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM countynum " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CountynumRecord - // and store its address in oneRecord - record = new CountynumRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CountynumRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - - // add this CountynumRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CountynumRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CountynumRecord object and.. -//----------------------------------------------------------------- - public int insert(CountynumRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO countynum VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getState()); - setString(insertStatement, 3, record.getCounty()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM countynum " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CountynumRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CountynumRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE countynum SET lid = ?, state = ?, county = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getState()); - setString(updateStatement, 3, record.getCounty()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CountynumRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM countynum " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CountynumRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CountynumRecord oldRecord, CountynumRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE countynum SET lid = ?, state = ?, county = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getState()); - setString(updateStatement, 3, newRecord.getCounty()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CountynumRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CountynumRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CountynumRecord oldRecord = (CountynumRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CountynumTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CrestRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CrestRecord.java deleted file mode 100644 index c926514730..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CrestRecord.java +++ /dev/null @@ -1,211 +0,0 @@ -// filename: CrestRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Crest table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CrestRecord extends DbRecord -{ - private String lid; - - private long datcrst; - - private String cremark; - - private String hw; - - private String jam; - - private String olddatum; - - private int q; - - private double stage; - - private String suppress; - - private String timcrst; - - private String prelim; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CrestRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CrestRecord(CrestRecord origRecord) - { - setLid(origRecord.getLid()); - setDatcrst(origRecord.getDatcrst()); - setCremark(origRecord.getCremark()); - setHw(origRecord.getHw()); - setJam(origRecord.getJam()); - setOlddatum(origRecord.getOlddatum()); - setQ(origRecord.getQ()); - setStage(origRecord.getStage()); - setSuppress(origRecord.getSuppress()); - setTimcrst(origRecord.getTimcrst()); - setPrelim(origRecord.getPrelim()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Crest record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getDatcrst() - { - return datcrst; - } - - public void setDatcrst(long datcrst) - { - this.datcrst = datcrst ; - } - - public String getCremark() - { - return cremark; - } - - public void setCremark(String cremark) - { - this.cremark = cremark ; - } - - public String getHw() - { - return hw; - } - - public void setHw(String hw) - { - this.hw = hw ; - } - - public String getJam() - { - return jam; - } - - public void setJam(String jam) - { - this.jam = jam ; - } - - public String getOlddatum() - { - return olddatum; - } - - public void setOlddatum(String olddatum) - { - this.olddatum = olddatum ; - } - - public int getQ() - { - return q; - } - - public void setQ(int q) - { - this.q = q ; - } - - public double getStage() - { - return stage; - } - - public void setStage(double stage) - { - this.stage = stage ; - } - - public String getSuppress() - { - return suppress; - } - - public void setSuppress(String suppress) - { - this.suppress = suppress ; - } - - public String getTimcrst() - { - return timcrst; - } - - public void setTimcrst(String timcrst) - { - this.timcrst = timcrst ; - } - - public String getPrelim() - { - return prelim; - } - - public void setPrelim(String prelim) - { - this.prelim = prelim ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND datcrst = '" + getDateStringFromLongTime(datcrst) + "'" - + " AND timcrst = '" + timcrst + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateStringFromLongTime(getDatcrst()) + " " + - getCremark() + " " + - getHw() + " " + - getJam() + " " + - getOlddatum() + " " + - getQ() + " " + - getStage() + " " + - getSuppress() + " " + - getTimcrst() + " " + - getPrelim() + " " + - "" ; - return outString; - } // end toString() -} // end of CrestRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CrestTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CrestTable.java deleted file mode 100644 index aa87f7a355..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CrestTable.java +++ /dev/null @@ -1,296 +0,0 @@ -// filename: CrestTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// crest table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CrestTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CrestTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CrestTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("crest"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CrestRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CrestRecord record = null; - - // create a List to hold Crest Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM crest " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CrestRecord - // and store its address in oneRecord - record = new CrestRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CrestRecord object - - record.setLid(getString(rs, 1)); - record.setDatcrst(getDate(rs, 2)); - record.setCremark(getString(rs, 3)); - record.setHw(getString(rs, 4)); - record.setJam(getString(rs, 5)); - record.setOlddatum(getString(rs, 6)); - record.setQ(getInt(rs, 7)); - record.setStage(getDouble(rs, 8)); - record.setSuppress(getString(rs, 9)); - record.setTimcrst(getString(rs, 10)); - record.setPrelim(getString(rs, 11)); - - // add this CrestRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CrestRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CrestRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CrestRecord record = null; - - // create a List to hold Crest Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM crest " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CrestRecord - // and store its address in oneRecord - record = new CrestRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CrestRecord object - - record.setLid(getString(rs, 1)); - record.setDatcrst(getDate(rs, 2)); - record.setCremark(getString(rs, 3)); - record.setHw(getString(rs, 4)); - record.setJam(getString(rs, 5)); - record.setOlddatum(getString(rs, 6)); - record.setQ(getInt(rs, 7)); - record.setStage(getDouble(rs, 8)); - record.setSuppress(getString(rs, 9)); - record.setTimcrst(getString(rs, 10)); - record.setPrelim(getString(rs, 11)); - - // add this CrestRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CrestRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CrestRecord object and.. -//----------------------------------------------------------------- - public int insert(CrestRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO crest VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDate(insertStatement, 2, record.getDatcrst()); - setString(insertStatement, 3, record.getCremark()); - setString(insertStatement, 4, record.getHw()); - setString(insertStatement, 5, record.getJam()); - setString(insertStatement, 6, record.getOlddatum()); - setInt(insertStatement, 7, record.getQ()); - setDouble(insertStatement, 8, record.getStage()); - setString(insertStatement, 9, record.getSuppress()); - setString(insertStatement, 10, record.getTimcrst()); - setString(insertStatement, 11, record.getPrelim()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM crest " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CrestRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CrestRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE crest SET lid = ?, datcrst = ?, cremark = ?, hw = ?, jam = ?, olddatum = ?, q = ?, stage = ?, suppress = ?, timcrst = ?, prelim = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDate(updateStatement, 2, record.getDatcrst()); - setString(updateStatement, 3, record.getCremark()); - setString(updateStatement, 4, record.getHw()); - setString(updateStatement, 5, record.getJam()); - setString(updateStatement, 6, record.getOlddatum()); - setInt(updateStatement, 7, record.getQ()); - setDouble(updateStatement, 8, record.getStage()); - setString(updateStatement, 9, record.getSuppress()); - setString(updateStatement, 10, record.getTimcrst()); - setString(updateStatement, 11, record.getPrelim()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CrestRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM crest " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CrestRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CrestRecord oldRecord, CrestRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE crest SET lid = ?, datcrst = ?, cremark = ?, hw = ?, jam = ?, olddatum = ?, q = ?, stage = ?, suppress = ?, timcrst = ?, prelim = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDate(updateStatement, 2, newRecord.getDatcrst()); - setString(updateStatement, 3, newRecord.getCremark()); - setString(updateStatement, 4, newRecord.getHw()); - setString(updateStatement, 5, newRecord.getJam()); - setString(updateStatement, 6, newRecord.getOlddatum()); - setInt(updateStatement, 7, newRecord.getQ()); - setDouble(updateStatement, 8, newRecord.getStage()); - setString(updateStatement, 9, newRecord.getSuppress()); - setString(updateStatement, 10, newRecord.getTimcrst()); - setString(updateStatement, 11, newRecord.getPrelim()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CrestRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CrestRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CrestRecord oldRecord = (CrestRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CrestTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPCRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPCRecord.java deleted file mode 100644 index 1991fd61c7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPCRecord.java +++ /dev/null @@ -1,240 +0,0 @@ -// filename: CurPCRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CurPC table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CurPCRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CurPCRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CurPCRecord(CurPCRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CurPC record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of CurPCRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPCTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPCTable.java deleted file mode 100644 index da78f4e242..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPCTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: CurPCTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// curpc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CurPCTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CurPCTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CurPCTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("curpc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CurPCRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CurPCRecord record = null; - - // create a List to hold CurPC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM curpc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CurPCRecord - // and store its address in oneRecord - record = new CurPCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CurPCRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this CurPCRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CurPCRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CurPCRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CurPCRecord record = null; - - // create a List to hold CurPC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM curpc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CurPCRecord - // and store its address in oneRecord - record = new CurPCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CurPCRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this CurPCRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CurPCRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CurPCRecord object and.. -//----------------------------------------------------------------- - public int insert(CurPCRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO curpc VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM curpc " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CurPCRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CurPCRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE curpc SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CurPCRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM curpc " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CurPCRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CurPCRecord oldRecord, CurPCRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE curpc SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CurPCRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CurPCRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CurPCRecord oldRecord = (CurPCRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CurPCTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPPRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPPRecord.java deleted file mode 100644 index a3bbceb750..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPPRecord.java +++ /dev/null @@ -1,241 +0,0 @@ -// filename: CurPPRecord.java -// author : DBGEN -// created : Tue May 31 17:52:13 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// CurPP table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class CurPPRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public CurPPRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public CurPPRecord(CurPPRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a CurPP record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of CurPPRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPPTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPPTable.java deleted file mode 100644 index df07048f54..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/CurPPTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: CurPPTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// curpp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class CurPPTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// CurPPTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CurPPTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("curpp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of CurPPRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - CurPPRecord record = null; - - // create a List to hold CurPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM curpp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CurPPRecord - // and store its address in oneRecord - record = new CurPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CurPPRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this CurPPRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the CurPPRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of CurPPRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - CurPPRecord record = null; - - // create a List to hold CurPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM curpp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a CurPPRecord - // and store its address in oneRecord - record = new CurPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a CurPPRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this CurPPRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the CurPPRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a CurPPRecord object and.. -//----------------------------------------------------------------- - public int insert(CurPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO curpp VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM curpp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CurPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CurPPRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE curpp SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(CurPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM curpp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a CurPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(CurPPRecord oldRecord, CurPPRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE curpp SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a CurPPRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(CurPPRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - CurPPRecord oldRecord = (CurPPRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of CurPPTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DPARadarRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DPARadarRecord.java deleted file mode 100644 index 3bd1d50f68..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DPARadarRecord.java +++ /dev/null @@ -1,406 +0,0 @@ -// filename: DPARadarRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DPARadar table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DPARadarRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private short minoff; - - private float maxvalh; - - private float maxvald; - - private float s1_bias_value; - - private long producttime; - - private short nisolbin; - - private short noutint; - - private short noutrep; - - private float areared; - - private float biscanr; - - private int block_bins_reject; - - private int clutter_bins_rej; - - private int bins_smoothed; - - private float scan_bins_filled; - - private float high_elev_angle; - - private float scan_rain_area; - - private short nbadscan; - - private short nhourout; - - private short volcovpat; - - private short opermode; - - private String missper; - - private short supplmess; - - private String grid_filename; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DPARadarRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DPARadarRecord(DPARadarRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setMinoff(origRecord.getMinoff()); - setMaxvalh(origRecord.getMaxvalh()); - setMaxvald(origRecord.getMaxvald()); - setS1_bias_value(origRecord.getS1_bias_value()); - setProducttime(origRecord.getProducttime()); - setNisolbin(origRecord.getNisolbin()); - setNoutint(origRecord.getNoutint()); - setNoutrep(origRecord.getNoutrep()); - setAreared(origRecord.getAreared()); - setBiscanr(origRecord.getBiscanr()); - setBlock_bins_reject(origRecord.getBlock_bins_reject()); - setClutter_bins_rej(origRecord.getClutter_bins_rej()); - setBins_smoothed(origRecord.getBins_smoothed()); - setScan_bins_filled(origRecord.getScan_bins_filled()); - setHigh_elev_angle(origRecord.getHigh_elev_angle()); - setScan_rain_area(origRecord.getScan_rain_area()); - setNbadscan(origRecord.getNbadscan()); - setNhourout(origRecord.getNhourout()); - setVolcovpat(origRecord.getVolcovpat()); - setOpermode(origRecord.getOpermode()); - setMissper(origRecord.getMissper()); - setSupplmess(origRecord.getSupplmess()); - setGrid_filename(origRecord.getGrid_filename()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DPARadar record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getMinoff() - { - return minoff; - } - - public void setMinoff(short minoff) - { - this.minoff = minoff ; - } - - public float getMaxvalh() - { - return maxvalh; - } - - public void setMaxvalh(float maxvalh) - { - this.maxvalh = maxvalh ; - } - - public float getMaxvald() - { - return maxvald; - } - - public void setMaxvald(float maxvald) - { - this.maxvald = maxvald ; - } - - public float getS1_bias_value() - { - return s1_bias_value; - } - - public void setS1_bias_value(float s1_bias_value) - { - this.s1_bias_value = s1_bias_value ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public short getNisolbin() - { - return nisolbin; - } - - public void setNisolbin(short nisolbin) - { - this.nisolbin = nisolbin ; - } - - public short getNoutint() - { - return noutint; - } - - public void setNoutint(short noutint) - { - this.noutint = noutint ; - } - - public short getNoutrep() - { - return noutrep; - } - - public void setNoutrep(short noutrep) - { - this.noutrep = noutrep ; - } - - public float getAreared() - { - return areared; - } - - public void setAreared(float areared) - { - this.areared = areared ; - } - - public float getBiscanr() - { - return biscanr; - } - - public void setBiscanr(float biscanr) - { - this.biscanr = biscanr ; - } - - public int getBlock_bins_reject() - { - return block_bins_reject; - } - - public void setBlock_bins_reject(int block_bins_reject) - { - this.block_bins_reject = block_bins_reject ; - } - - public int getClutter_bins_rej() - { - return clutter_bins_rej; - } - - public void setClutter_bins_rej(int clutter_bins_rej) - { - this.clutter_bins_rej = clutter_bins_rej ; - } - - public int getBins_smoothed() - { - return bins_smoothed; - } - - public void setBins_smoothed(int bins_smoothed) - { - this.bins_smoothed = bins_smoothed ; - } - - public float getScan_bins_filled() - { - return scan_bins_filled; - } - - public void setScan_bins_filled(float scan_bins_filled) - { - this.scan_bins_filled = scan_bins_filled ; - } - - public float getHigh_elev_angle() - { - return high_elev_angle; - } - - public void setHigh_elev_angle(float high_elev_angle) - { - this.high_elev_angle = high_elev_angle ; - } - - public float getScan_rain_area() - { - return scan_rain_area; - } - - public void setScan_rain_area(float scan_rain_area) - { - this.scan_rain_area = scan_rain_area ; - } - - public short getNbadscan() - { - return nbadscan; - } - - public void setNbadscan(short nbadscan) - { - this.nbadscan = nbadscan ; - } - - public short getNhourout() - { - return nhourout; - } - - public void setNhourout(short nhourout) - { - this.nhourout = nhourout ; - } - - public short getVolcovpat() - { - return volcovpat; - } - - public void setVolcovpat(short volcovpat) - { - this.volcovpat = volcovpat ; - } - - public short getOpermode() - { - return opermode; - } - - public void setOpermode(short opermode) - { - this.opermode = opermode ; - } - - public String getMissper() - { - return missper; - } - - public void setMissper(String missper) - { - this.missper = missper ; - } - - public short getSupplmess() - { - return supplmess; - } - - public void setSupplmess(short supplmess) - { - this.supplmess = supplmess ; - } - - public String getGrid_filename() - { - return grid_filename; - } - - public void setGrid_filename(String grid_filename) - { - this.grid_filename = grid_filename ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMinoff() + " " + - getMaxvalh() + " " + - getMaxvald() + " " + - getS1_bias_value() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getNisolbin() + " " + - getNoutint() + " " + - getNoutrep() + " " + - getAreared() + " " + - getBiscanr() + " " + - getBlock_bins_reject() + " " + - getClutter_bins_rej() + " " + - getBins_smoothed() + " " + - getScan_bins_filled() + " " + - getHigh_elev_angle() + " " + - getScan_rain_area() + " " + - getNbadscan() + " " + - getNhourout() + " " + - getVolcovpat() + " " + - getOpermode() + " " + - getMissper() + " " + - getSupplmess() + " " + - getGrid_filename() + " " + - "" ; - return outString; - } // end toString() -} // end of DPARadarRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DPARadarTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DPARadarTable.java deleted file mode 100644 index a5d4f364f3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DPARadarTable.java +++ /dev/null @@ -1,366 +0,0 @@ -// filename: DPARadarTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dparadar table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DPARadarTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DPARadarTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DPARadarTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dparadar"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DPARadarRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DPARadarRecord record = null; - - // create a List to hold DPARadar Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dparadar " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DPARadarRecord - // and store its address in oneRecord - record = new DPARadarRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DPARadarRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMinoff(getShort(rs, 3)); - record.setMaxvalh(getReal(rs, 4)); - record.setMaxvald(getReal(rs, 5)); - record.setS1_bias_value(getReal(rs, 6)); - record.setProducttime(getTimeStamp(rs, 7)); - record.setNisolbin(getShort(rs, 8)); - record.setNoutint(getShort(rs, 9)); - record.setNoutrep(getShort(rs, 10)); - record.setAreared(getReal(rs, 11)); - record.setBiscanr(getReal(rs, 12)); - record.setBlock_bins_reject(getInt(rs, 13)); - record.setClutter_bins_rej(getInt(rs, 14)); - record.setBins_smoothed(getInt(rs, 15)); - record.setScan_bins_filled(getReal(rs, 16)); - record.setHigh_elev_angle(getReal(rs, 17)); - record.setScan_rain_area(getReal(rs, 18)); - record.setNbadscan(getShort(rs, 19)); - record.setNhourout(getShort(rs, 20)); - record.setVolcovpat(getShort(rs, 21)); - record.setOpermode(getShort(rs, 22)); - record.setMissper(getString(rs, 23)); - record.setSupplmess(getShort(rs, 24)); - record.setGrid_filename(getString(rs, 25)); - - // add this DPARadarRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DPARadarRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DPARadarRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DPARadarRecord record = null; - - // create a List to hold DPARadar Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dparadar " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DPARadarRecord - // and store its address in oneRecord - record = new DPARadarRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DPARadarRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMinoff(getShort(rs, 3)); - record.setMaxvalh(getReal(rs, 4)); - record.setMaxvald(getReal(rs, 5)); - record.setS1_bias_value(getReal(rs, 6)); - record.setProducttime(getTimeStamp(rs, 7)); - record.setNisolbin(getShort(rs, 8)); - record.setNoutint(getShort(rs, 9)); - record.setNoutrep(getShort(rs, 10)); - record.setAreared(getReal(rs, 11)); - record.setBiscanr(getReal(rs, 12)); - record.setBlock_bins_reject(getInt(rs, 13)); - record.setClutter_bins_rej(getInt(rs, 14)); - record.setBins_smoothed(getInt(rs, 15)); - record.setScan_bins_filled(getReal(rs, 16)); - record.setHigh_elev_angle(getReal(rs, 17)); - record.setScan_rain_area(getReal(rs, 18)); - record.setNbadscan(getShort(rs, 19)); - record.setNhourout(getShort(rs, 20)); - record.setVolcovpat(getShort(rs, 21)); - record.setOpermode(getShort(rs, 22)); - record.setMissper(getString(rs, 23)); - record.setSupplmess(getShort(rs, 24)); - record.setGrid_filename(getString(rs, 25)); - - // add this DPARadarRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DPARadarRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DPARadarRecord object and.. -//----------------------------------------------------------------- - public int insert(DPARadarRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dparadar VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setShort(insertStatement, 3, record.getMinoff()); - setReal(insertStatement, 4, record.getMaxvalh()); - setReal(insertStatement, 5, record.getMaxvald()); - setReal(insertStatement, 6, record.getS1_bias_value()); - setTimeStamp(insertStatement, 7, record.getProducttime()); - setShort(insertStatement, 8, record.getNisolbin()); - setShort(insertStatement, 9, record.getNoutint()); - setShort(insertStatement, 10, record.getNoutrep()); - setReal(insertStatement, 11, record.getAreared()); - setReal(insertStatement, 12, record.getBiscanr()); - setInt(insertStatement, 13, record.getBlock_bins_reject()); - setInt(insertStatement, 14, record.getClutter_bins_rej()); - setInt(insertStatement, 15, record.getBins_smoothed()); - setReal(insertStatement, 16, record.getScan_bins_filled()); - setReal(insertStatement, 17, record.getHigh_elev_angle()); - setReal(insertStatement, 18, record.getScan_rain_area()); - setShort(insertStatement, 19, record.getNbadscan()); - setShort(insertStatement, 20, record.getNhourout()); - setShort(insertStatement, 21, record.getVolcovpat()); - setShort(insertStatement, 22, record.getOpermode()); - setString(insertStatement, 23, record.getMissper()); - setShort(insertStatement, 24, record.getSupplmess()); - setString(insertStatement, 25, record.getGrid_filename()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dparadar " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DPARadarRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DPARadarRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dparadar SET radid = ?, obstime = ?, minoff = ?, maxvalh = ?, maxvald = ?, s1_bias_value = ?, producttime = ?, nisolbin = ?, noutint = ?, noutrep = ?, areared = ?, biscanr = ?, block_bins_reject = ?, clutter_bins_rej = ?, bins_smoothed = ?, scan_bins_filled = ?, high_elev_angle = ?, scan_rain_area = ?, nbadscan = ?, nhourout = ?, volcovpat = ?, opermode = ?, missper = ?, supplmess = ?, grid_filename = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setShort(updateStatement, 3, record.getMinoff()); - setReal(updateStatement, 4, record.getMaxvalh()); - setReal(updateStatement, 5, record.getMaxvald()); - setReal(updateStatement, 6, record.getS1_bias_value()); - setTimeStamp(updateStatement, 7, record.getProducttime()); - setShort(updateStatement, 8, record.getNisolbin()); - setShort(updateStatement, 9, record.getNoutint()); - setShort(updateStatement, 10, record.getNoutrep()); - setReal(updateStatement, 11, record.getAreared()); - setReal(updateStatement, 12, record.getBiscanr()); - setInt(updateStatement, 13, record.getBlock_bins_reject()); - setInt(updateStatement, 14, record.getClutter_bins_rej()); - setInt(updateStatement, 15, record.getBins_smoothed()); - setReal(updateStatement, 16, record.getScan_bins_filled()); - setReal(updateStatement, 17, record.getHigh_elev_angle()); - setReal(updateStatement, 18, record.getScan_rain_area()); - setShort(updateStatement, 19, record.getNbadscan()); - setShort(updateStatement, 20, record.getNhourout()); - setShort(updateStatement, 21, record.getVolcovpat()); - setShort(updateStatement, 22, record.getOpermode()); - setString(updateStatement, 23, record.getMissper()); - setShort(updateStatement, 24, record.getSupplmess()); - setString(updateStatement, 25, record.getGrid_filename()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DPARadarRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dparadar " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DPARadarRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DPARadarRecord oldRecord, DPARadarRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dparadar SET radid = ?, obstime = ?, minoff = ?, maxvalh = ?, maxvald = ?, s1_bias_value = ?, producttime = ?, nisolbin = ?, noutint = ?, noutrep = ?, areared = ?, biscanr = ?, block_bins_reject = ?, clutter_bins_rej = ?, bins_smoothed = ?, scan_bins_filled = ?, high_elev_angle = ?, scan_rain_area = ?, nbadscan = ?, nhourout = ?, volcovpat = ?, opermode = ?, missper = ?, supplmess = ?, grid_filename = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setShort(updateStatement, 3, newRecord.getMinoff()); - setReal(updateStatement, 4, newRecord.getMaxvalh()); - setReal(updateStatement, 5, newRecord.getMaxvald()); - setReal(updateStatement, 6, newRecord.getS1_bias_value()); - setTimeStamp(updateStatement, 7, newRecord.getProducttime()); - setShort(updateStatement, 8, newRecord.getNisolbin()); - setShort(updateStatement, 9, newRecord.getNoutint()); - setShort(updateStatement, 10, newRecord.getNoutrep()); - setReal(updateStatement, 11, newRecord.getAreared()); - setReal(updateStatement, 12, newRecord.getBiscanr()); - setInt(updateStatement, 13, newRecord.getBlock_bins_reject()); - setInt(updateStatement, 14, newRecord.getClutter_bins_rej()); - setInt(updateStatement, 15, newRecord.getBins_smoothed()); - setReal(updateStatement, 16, newRecord.getScan_bins_filled()); - setReal(updateStatement, 17, newRecord.getHigh_elev_angle()); - setReal(updateStatement, 18, newRecord.getScan_rain_area()); - setShort(updateStatement, 19, newRecord.getNbadscan()); - setShort(updateStatement, 20, newRecord.getNhourout()); - setShort(updateStatement, 21, newRecord.getVolcovpat()); - setShort(updateStatement, 22, newRecord.getOpermode()); - setString(updateStatement, 23, newRecord.getMissper()); - setShort(updateStatement, 24, newRecord.getSupplmess()); - setString(updateStatement, 25, newRecord.getGrid_filename()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DPARadarRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DPARadarRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DPARadarRecord oldRecord = (DPARadarRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DPARadarTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DailyPPRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DailyPPRecord.java deleted file mode 100644 index f7b893e018..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DailyPPRecord.java +++ /dev/null @@ -1,141 +0,0 @@ -// filename: DailyPPRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DailyPP table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DailyPPRecord extends DbRecord -{ - private String lid; - - private String ts; - - private long obstime; - - private double value; - - private String qc; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DailyPPRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DailyPPRecord(DailyPPRecord origRecord) - { - setLid(origRecord.getLid()); - setTs(origRecord.getTs()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setQc(origRecord.getQc()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DailyPP record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getQc() - { - return qc; - } - - public void setQc(String qc) - { - this.qc = qc ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ts = '" + ts + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getTs() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getQc() + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of DailyPPRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DailyPPTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DailyPPTable.java deleted file mode 100644 index af97b74dd2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DailyPPTable.java +++ /dev/null @@ -1,271 +0,0 @@ -// filename: DailyPPTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dailypp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DailyPPTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DailyPPTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DailyPPTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dailypp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DailyPPRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DailyPPRecord record = null; - - // create a List to hold DailyPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dailypp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DailyPPRecord - // and store its address in oneRecord - record = new DailyPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DailyPPRecord object - - record.setLid(getString(rs, 1)); - record.setTs(getString(rs, 2)); - record.setObstime(getTimeStamp(rs, 3)); - record.setValue(getDouble(rs, 4)); - record.setQc(getString(rs, 5)); - record.setPostingtime(getTimeStamp(rs, 6)); - - // add this DailyPPRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DailyPPRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DailyPPRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DailyPPRecord record = null; - - // create a List to hold DailyPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dailypp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DailyPPRecord - // and store its address in oneRecord - record = new DailyPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DailyPPRecord object - - record.setLid(getString(rs, 1)); - record.setTs(getString(rs, 2)); - record.setObstime(getTimeStamp(rs, 3)); - record.setValue(getDouble(rs, 4)); - record.setQc(getString(rs, 5)); - record.setPostingtime(getTimeStamp(rs, 6)); - - // add this DailyPPRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DailyPPRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DailyPPRecord object and.. -//----------------------------------------------------------------- - public int insert(DailyPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dailypp VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getTs()); - setTimeStamp(insertStatement, 3, record.getObstime()); - setDouble(insertStatement, 4, record.getValue()); - setString(insertStatement, 5, record.getQc()); - setTimeStamp(insertStatement, 6, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dailypp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DailyPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DailyPPRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dailypp SET lid = ?, ts = ?, obstime = ?, value = ?, qc = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getTs()); - setTimeStamp(updateStatement, 3, record.getObstime()); - setDouble(updateStatement, 4, record.getValue()); - setString(updateStatement, 5, record.getQc()); - setTimeStamp(updateStatement, 6, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DailyPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dailypp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DailyPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DailyPPRecord oldRecord, DailyPPRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dailypp SET lid = ?, ts = ?, obstime = ?, value = ?, qc = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getTs()); - setTimeStamp(updateStatement, 3, newRecord.getObstime()); - setDouble(updateStatement, 4, newRecord.getValue()); - setString(updateStatement, 5, newRecord.getQc()); - setTimeStamp(updateStatement, 6, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DailyPPRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DailyPPRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DailyPPRecord oldRecord = (DailyPPRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DailyPPTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DamTypesRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DamTypesRecord.java deleted file mode 100644 index 711b483b88..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DamTypesRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: DamTypesRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DamTypes table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DamTypesRecord extends DbRecord -{ - private String type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DamTypesRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DamTypesRecord(DamTypesRecord origRecord) - { - setType(origRecord.getType()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DamTypes record - - //----------------------------------------------------------------- - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE type = '" + type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getType() + " " + - "" ; - return outString; - } // end toString() -} // end of DamTypesRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DamTypesTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DamTypesTable.java deleted file mode 100644 index a9f22ffa35..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DamTypesTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: DamTypesTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// damtypes table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DamTypesTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DamTypesTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DamTypesTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("damtypes"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DamTypesRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DamTypesRecord record = null; - - // create a List to hold DamTypes Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM damtypes " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DamTypesRecord - // and store its address in oneRecord - record = new DamTypesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DamTypesRecord object - - record.setType(getString(rs, 1)); - - // add this DamTypesRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DamTypesRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DamTypesRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DamTypesRecord record = null; - - // create a List to hold DamTypes Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM damtypes " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DamTypesRecord - // and store its address in oneRecord - record = new DamTypesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DamTypesRecord object - - record.setType(getString(rs, 1)); - - // add this DamTypesRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DamTypesRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DamTypesRecord object and.. -//----------------------------------------------------------------- - public int insert(DamTypesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO damtypes VALUES (? )"); - - setString(insertStatement, 1, record.getType()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM damtypes " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DamTypesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DamTypesRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE damtypes SET type = ? " + where ); - - setString(updateStatement, 1, record.getType()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DamTypesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM damtypes " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DamTypesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DamTypesRecord oldRecord, DamTypesRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE damtypes SET type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getType()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DamTypesRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DamTypesRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DamTypesRecord oldRecord = (DamTypesRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DamTypesTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DataLimitsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DataLimitsRecord.java deleted file mode 100644 index 0e00c18c70..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DataLimitsRecord.java +++ /dev/null @@ -1,295 +0,0 @@ -// filename: DataLimitsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DataLimits table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DataLimitsRecord extends DbRecord -{ - private String pe; - - private short dur; - - private String monthdaystart; - - private String monthdayend; - - private double gross_range_min; - - private double gross_range_max; - - private double reason_range_min; - - private double reason_range_max; - - private double roc_max; - - private double alert_upper_limit; - - private double alert_roc_limit; - - private double alarm_upper_limit; - - private double alarm_roc_limit; - - private double alert_lower_limit; - - private double alarm_lower_limit; - - private double alert_diff_limit; - - private double alarm_diff_limit; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DataLimitsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DataLimitsRecord(DataLimitsRecord origRecord) - { - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setMonthdaystart(origRecord.getMonthdaystart()); - setMonthdayend(origRecord.getMonthdayend()); - setGross_range_min(origRecord.getGross_range_min()); - setGross_range_max(origRecord.getGross_range_max()); - setReason_range_min(origRecord.getReason_range_min()); - setReason_range_max(origRecord.getReason_range_max()); - setRoc_max(origRecord.getRoc_max()); - setAlert_upper_limit(origRecord.getAlert_upper_limit()); - setAlert_roc_limit(origRecord.getAlert_roc_limit()); - setAlarm_upper_limit(origRecord.getAlarm_upper_limit()); - setAlarm_roc_limit(origRecord.getAlarm_roc_limit()); - setAlert_lower_limit(origRecord.getAlert_lower_limit()); - setAlarm_lower_limit(origRecord.getAlarm_lower_limit()); - setAlert_diff_limit(origRecord.getAlert_diff_limit()); - setAlarm_diff_limit(origRecord.getAlarm_diff_limit()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DataLimits record - - //----------------------------------------------------------------- - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getMonthdaystart() - { - return monthdaystart; - } - - public void setMonthdaystart(String monthdaystart) - { - this.monthdaystart = monthdaystart ; - } - - public String getMonthdayend() - { - return monthdayend; - } - - public void setMonthdayend(String monthdayend) - { - this.monthdayend = monthdayend ; - } - - public double getGross_range_min() - { - return gross_range_min; - } - - public void setGross_range_min(double gross_range_min) - { - this.gross_range_min = gross_range_min ; - } - - public double getGross_range_max() - { - return gross_range_max; - } - - public void setGross_range_max(double gross_range_max) - { - this.gross_range_max = gross_range_max ; - } - - public double getReason_range_min() - { - return reason_range_min; - } - - public void setReason_range_min(double reason_range_min) - { - this.reason_range_min = reason_range_min ; - } - - public double getReason_range_max() - { - return reason_range_max; - } - - public void setReason_range_max(double reason_range_max) - { - this.reason_range_max = reason_range_max ; - } - - public double getRoc_max() - { - return roc_max; - } - - public void setRoc_max(double roc_max) - { - this.roc_max = roc_max ; - } - - public double getAlert_upper_limit() - { - return alert_upper_limit; - } - - public void setAlert_upper_limit(double alert_upper_limit) - { - this.alert_upper_limit = alert_upper_limit ; - } - - public double getAlert_roc_limit() - { - return alert_roc_limit; - } - - public void setAlert_roc_limit(double alert_roc_limit) - { - this.alert_roc_limit = alert_roc_limit ; - } - - public double getAlarm_upper_limit() - { - return alarm_upper_limit; - } - - public void setAlarm_upper_limit(double alarm_upper_limit) - { - this.alarm_upper_limit = alarm_upper_limit ; - } - - public double getAlarm_roc_limit() - { - return alarm_roc_limit; - } - - public void setAlarm_roc_limit(double alarm_roc_limit) - { - this.alarm_roc_limit = alarm_roc_limit ; - } - - public double getAlert_lower_limit() - { - return alert_lower_limit; - } - - public void setAlert_lower_limit(double alert_lower_limit) - { - this.alert_lower_limit = alert_lower_limit ; - } - - public double getAlarm_lower_limit() - { - return alarm_lower_limit; - } - - public void setAlarm_lower_limit(double alarm_lower_limit) - { - this.alarm_lower_limit = alarm_lower_limit ; - } - - public double getAlert_diff_limit() - { - return alert_diff_limit; - } - - public void setAlert_diff_limit(double alert_diff_limit) - { - this.alert_diff_limit = alert_diff_limit ; - } - - public double getAlarm_diff_limit() - { - return alarm_diff_limit; - } - - public void setAlarm_diff_limit(double alarm_diff_limit) - { - this.alarm_diff_limit = alarm_diff_limit ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND monthdaystart = '" + monthdaystart + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPe() + " " + - getDur() + " " + - getMonthdaystart() + " " + - getMonthdayend() + " " + - getGross_range_min() + " " + - getGross_range_max() + " " + - getReason_range_min() + " " + - getReason_range_max() + " " + - getRoc_max() + " " + - getAlert_upper_limit() + " " + - getAlert_roc_limit() + " " + - getAlarm_upper_limit() + " " + - getAlarm_roc_limit() + " " + - getAlert_lower_limit() + " " + - getAlarm_lower_limit() + " " + - getAlert_diff_limit() + " " + - getAlarm_diff_limit() + " " + - "" ; - return outString; - } // end toString() -} // end of DataLimitsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DataLimitsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DataLimitsTable.java deleted file mode 100644 index 8d01f32b7a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DataLimitsTable.java +++ /dev/null @@ -1,326 +0,0 @@ -// filename: DataLimitsTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// datalimits table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DataLimitsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DataLimitsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DataLimitsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("datalimits"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DataLimitsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DataLimitsRecord record = null; - - // create a List to hold DataLimits Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM datalimits " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DataLimitsRecord - // and store its address in oneRecord - record = new DataLimitsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DataLimitsRecord object - - record.setPe(getString(rs, 1)); - record.setDur(getShort(rs, 2)); - record.setMonthdaystart(getString(rs, 3)); - record.setMonthdayend(getString(rs, 4)); - record.setGross_range_min(getDouble(rs, 5)); - record.setGross_range_max(getDouble(rs, 6)); - record.setReason_range_min(getDouble(rs, 7)); - record.setReason_range_max(getDouble(rs, 8)); - record.setRoc_max(getDouble(rs, 9)); - record.setAlert_upper_limit(getDouble(rs, 10)); - record.setAlert_roc_limit(getDouble(rs, 11)); - record.setAlarm_upper_limit(getDouble(rs, 12)); - record.setAlarm_roc_limit(getDouble(rs, 13)); - record.setAlert_lower_limit(getDouble(rs, 14)); - record.setAlarm_lower_limit(getDouble(rs, 15)); - record.setAlert_diff_limit(getDouble(rs, 16)); - record.setAlarm_diff_limit(getDouble(rs, 17)); - - // add this DataLimitsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DataLimitsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DataLimitsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DataLimitsRecord record = null; - - // create a List to hold DataLimits Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM datalimits " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DataLimitsRecord - // and store its address in oneRecord - record = new DataLimitsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DataLimitsRecord object - - record.setPe(getString(rs, 1)); - record.setDur(getShort(rs, 2)); - record.setMonthdaystart(getString(rs, 3)); - record.setMonthdayend(getString(rs, 4)); - record.setGross_range_min(getDouble(rs, 5)); - record.setGross_range_max(getDouble(rs, 6)); - record.setReason_range_min(getDouble(rs, 7)); - record.setReason_range_max(getDouble(rs, 8)); - record.setRoc_max(getDouble(rs, 9)); - record.setAlert_upper_limit(getDouble(rs, 10)); - record.setAlert_roc_limit(getDouble(rs, 11)); - record.setAlarm_upper_limit(getDouble(rs, 12)); - record.setAlarm_roc_limit(getDouble(rs, 13)); - record.setAlert_lower_limit(getDouble(rs, 14)); - record.setAlarm_lower_limit(getDouble(rs, 15)); - record.setAlert_diff_limit(getDouble(rs, 16)); - record.setAlarm_diff_limit(getDouble(rs, 17)); - - // add this DataLimitsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DataLimitsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DataLimitsRecord object and.. -//----------------------------------------------------------------- - public int insert(DataLimitsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO datalimits VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getPe()); - setShort(insertStatement, 2, record.getDur()); - setString(insertStatement, 3, record.getMonthdaystart()); - setString(insertStatement, 4, record.getMonthdayend()); - setDouble(insertStatement, 5, record.getGross_range_min()); - setDouble(insertStatement, 6, record.getGross_range_max()); - setDouble(insertStatement, 7, record.getReason_range_min()); - setDouble(insertStatement, 8, record.getReason_range_max()); - setDouble(insertStatement, 9, record.getRoc_max()); - setDouble(insertStatement, 10, record.getAlert_upper_limit()); - setDouble(insertStatement, 11, record.getAlert_roc_limit()); - setDouble(insertStatement, 12, record.getAlarm_upper_limit()); - setDouble(insertStatement, 13, record.getAlarm_roc_limit()); - setDouble(insertStatement, 14, record.getAlert_lower_limit()); - setDouble(insertStatement, 15, record.getAlarm_lower_limit()); - setDouble(insertStatement, 16, record.getAlert_diff_limit()); - setDouble(insertStatement, 17, record.getAlarm_diff_limit()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM datalimits " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DataLimitsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DataLimitsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE datalimits SET pe = ?, dur = ?, monthdaystart = ?, monthdayend = ?, gross_range_min = ?, gross_range_max = ?, reason_range_min = ?, reason_range_max = ?, roc_max = ?, alert_upper_limit = ?, alert_roc_limit = ?, alarm_upper_limit = ?, alarm_roc_limit = ?, alert_lower_limit = ?, alarm_lower_limit = ?, alert_diff_limit = ?, alarm_diff_limit = ? " + where ); - - setString(updateStatement, 1, record.getPe()); - setShort(updateStatement, 2, record.getDur()); - setString(updateStatement, 3, record.getMonthdaystart()); - setString(updateStatement, 4, record.getMonthdayend()); - setDouble(updateStatement, 5, record.getGross_range_min()); - setDouble(updateStatement, 6, record.getGross_range_max()); - setDouble(updateStatement, 7, record.getReason_range_min()); - setDouble(updateStatement, 8, record.getReason_range_max()); - setDouble(updateStatement, 9, record.getRoc_max()); - setDouble(updateStatement, 10, record.getAlert_upper_limit()); - setDouble(updateStatement, 11, record.getAlert_roc_limit()); - setDouble(updateStatement, 12, record.getAlarm_upper_limit()); - setDouble(updateStatement, 13, record.getAlarm_roc_limit()); - setDouble(updateStatement, 14, record.getAlert_lower_limit()); - setDouble(updateStatement, 15, record.getAlarm_lower_limit()); - setDouble(updateStatement, 16, record.getAlert_diff_limit()); - setDouble(updateStatement, 17, record.getAlarm_diff_limit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DataLimitsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM datalimits " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DataLimitsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DataLimitsRecord oldRecord, DataLimitsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE datalimits SET pe = ?, dur = ?, monthdaystart = ?, monthdayend = ?, gross_range_min = ?, gross_range_max = ?, reason_range_min = ?, reason_range_max = ?, roc_max = ?, alert_upper_limit = ?, alert_roc_limit = ?, alarm_upper_limit = ?, alarm_roc_limit = ?, alert_lower_limit = ?, alarm_lower_limit = ?, alert_diff_limit = ?, alarm_diff_limit = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPe()); - setShort(updateStatement, 2, newRecord.getDur()); - setString(updateStatement, 3, newRecord.getMonthdaystart()); - setString(updateStatement, 4, newRecord.getMonthdayend()); - setDouble(updateStatement, 5, newRecord.getGross_range_min()); - setDouble(updateStatement, 6, newRecord.getGross_range_max()); - setDouble(updateStatement, 7, newRecord.getReason_range_min()); - setDouble(updateStatement, 8, newRecord.getReason_range_max()); - setDouble(updateStatement, 9, newRecord.getRoc_max()); - setDouble(updateStatement, 10, newRecord.getAlert_upper_limit()); - setDouble(updateStatement, 11, newRecord.getAlert_roc_limit()); - setDouble(updateStatement, 12, newRecord.getAlarm_upper_limit()); - setDouble(updateStatement, 13, newRecord.getAlarm_roc_limit()); - setDouble(updateStatement, 14, newRecord.getAlert_lower_limit()); - setDouble(updateStatement, 15, newRecord.getAlarm_lower_limit()); - setDouble(updateStatement, 16, newRecord.getAlert_diff_limit()); - setDouble(updateStatement, 17, newRecord.getAlarm_diff_limit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DataLimitsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DataLimitsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DataLimitsRecord oldRecord = (DataLimitsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DataLimitsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DatumRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DatumRecord.java deleted file mode 100644 index 14d40df90b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DatumRecord.java +++ /dev/null @@ -1,98 +0,0 @@ -// filename: DatumRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Datum table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DatumRecord extends DbRecord -{ - private String lid; - - private long ddate; - - private double elev; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DatumRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DatumRecord(DatumRecord origRecord) - { - setLid(origRecord.getLid()); - setDdate(origRecord.getDdate()); - setElev(origRecord.getElev()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Datum record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getDdate() - { - return ddate; - } - - public void setDdate(long ddate) - { - this.ddate = ddate ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ddate = '" + getDateStringFromLongTime(ddate) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateStringFromLongTime(getDdate()) + " " + - getElev() + " " + - "" ; - return outString; - } // end toString() -} // end of DatumRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DatumTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DatumTable.java deleted file mode 100644 index f367f0d191..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DatumTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: DatumTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// datum table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DatumTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DatumTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DatumTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("datum"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DatumRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DatumRecord record = null; - - // create a List to hold Datum Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM datum " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DatumRecord - // and store its address in oneRecord - record = new DatumRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DatumRecord object - - record.setLid(getString(rs, 1)); - record.setDdate(getDate(rs, 2)); - record.setElev(getDouble(rs, 3)); - - // add this DatumRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DatumRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DatumRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DatumRecord record = null; - - // create a List to hold Datum Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM datum " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DatumRecord - // and store its address in oneRecord - record = new DatumRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DatumRecord object - - record.setLid(getString(rs, 1)); - record.setDdate(getDate(rs, 2)); - record.setElev(getDouble(rs, 3)); - - // add this DatumRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DatumRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DatumRecord object and.. -//----------------------------------------------------------------- - public int insert(DatumRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO datum VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDate(insertStatement, 2, record.getDdate()); - setDouble(insertStatement, 3, record.getElev()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM datum " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DatumRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DatumRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE datum SET lid = ?, ddate = ?, elev = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDate(updateStatement, 2, record.getDdate()); - setDouble(updateStatement, 3, record.getElev()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DatumRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM datum " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DatumRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DatumRecord oldRecord, DatumRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE datum SET lid = ?, ddate = ?, elev = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDate(updateStatement, 2, newRecord.getDdate()); - setDouble(updateStatement, 3, newRecord.getElev()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DatumRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DatumRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DatumRecord oldRecord = (DatumRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DatumTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpOwnerRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpOwnerRecord.java deleted file mode 100644 index e0728c6cbc..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpOwnerRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: DcpOwnerRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DcpOwner table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DcpOwnerRecord extends DbRecord -{ - private String owner; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DcpOwnerRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DcpOwnerRecord(DcpOwnerRecord origRecord) - { - setOwner(origRecord.getOwner()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DcpOwner record - - //----------------------------------------------------------------- - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE owner = '" + owner + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getOwner() + " " + - "" ; - return outString; - } // end toString() -} // end of DcpOwnerRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpOwnerTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpOwnerTable.java deleted file mode 100644 index 51a7bd66e5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpOwnerTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: DcpOwnerTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dcpowner table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DcpOwnerTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DcpOwnerTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DcpOwnerTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dcpowner"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DcpOwnerRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DcpOwnerRecord record = null; - - // create a List to hold DcpOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dcpowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DcpOwnerRecord - // and store its address in oneRecord - record = new DcpOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DcpOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this DcpOwnerRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DcpOwnerRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DcpOwnerRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DcpOwnerRecord record = null; - - // create a List to hold DcpOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dcpowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DcpOwnerRecord - // and store its address in oneRecord - record = new DcpOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DcpOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this DcpOwnerRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DcpOwnerRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DcpOwnerRecord object and.. -//----------------------------------------------------------------- - public int insert(DcpOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dcpowner VALUES (? )"); - - setString(insertStatement, 1, record.getOwner()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dcpowner " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DcpOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DcpOwnerRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dcpowner SET owner = ? " + where ); - - setString(updateStatement, 1, record.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DcpOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dcpowner " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DcpOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DcpOwnerRecord oldRecord, DcpOwnerRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dcpowner SET owner = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DcpOwnerRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DcpOwnerRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DcpOwnerRecord oldRecord = (DcpOwnerRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DcpOwnerTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpRecord.java deleted file mode 100644 index 5c8e53a8cb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpRecord.java +++ /dev/null @@ -1,181 +0,0 @@ -// filename: DcpRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Dcp table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DcpRecord extends DbRecord -{ - private String lid; - - private String criteria; - - private String owner; - - private String goes; - - private String rptfreq; - - private String rptime; - - private String notify; - - private String obsvfreq; - - private String randrept; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DcpRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DcpRecord(DcpRecord origRecord) - { - setLid(origRecord.getLid()); - setCriteria(origRecord.getCriteria()); - setOwner(origRecord.getOwner()); - setGoes(origRecord.getGoes()); - setRptfreq(origRecord.getRptfreq()); - setRptime(origRecord.getRptime()); - setNotify(origRecord.getNotify()); - setObsvfreq(origRecord.getObsvfreq()); - setRandrept(origRecord.getRandrept()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Dcp record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getCriteria() - { - return criteria; - } - - public void setCriteria(String criteria) - { - this.criteria = criteria ; - } - - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - - public String getGoes() - { - return goes; - } - - public void setGoes(String goes) - { - this.goes = goes ; - } - - public String getRptfreq() - { - return rptfreq; - } - - public void setRptfreq(String rptfreq) - { - this.rptfreq = rptfreq ; - } - - public String getRptime() - { - return rptime; - } - - public void setRptime(String rptime) - { - this.rptime = rptime ; - } - - public String getNotify() - { - return notify; - } - - public void setNotify(String notify) - { - this.notify = notify ; - } - - public String getObsvfreq() - { - return obsvfreq; - } - - public void setObsvfreq(String obsvfreq) - { - this.obsvfreq = obsvfreq ; - } - - public String getRandrept() - { - return randrept; - } - - public void setRandrept(String randrept) - { - this.randrept = randrept ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getCriteria() + " " + - getOwner() + " " + - getGoes() + " " + - getRptfreq() + " " + - getRptime() + " " + - getNotify() + " " + - getObsvfreq() + " " + - getRandrept() + " " + - "" ; - return outString; - } // end toString() -} // end of DcpRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpTable.java deleted file mode 100644 index d755811f6f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DcpTable.java +++ /dev/null @@ -1,286 +0,0 @@ -// filename: DcpTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dcp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DcpTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DcpTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DcpTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dcp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DcpRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DcpRecord record = null; - - // create a List to hold Dcp Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dcp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DcpRecord - // and store its address in oneRecord - record = new DcpRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DcpRecord object - - record.setLid(getString(rs, 1)); - record.setCriteria(getString(rs, 2)); - record.setOwner(getString(rs, 3)); - record.setGoes(getString(rs, 4)); - record.setRptfreq(getString(rs, 5)); - record.setRptime(getString(rs, 6)); - record.setNotify(getString(rs, 7)); - record.setObsvfreq(getString(rs, 8)); - record.setRandrept(getString(rs, 9)); - - // add this DcpRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DcpRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DcpRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DcpRecord record = null; - - // create a List to hold Dcp Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dcp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DcpRecord - // and store its address in oneRecord - record = new DcpRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DcpRecord object - - record.setLid(getString(rs, 1)); - record.setCriteria(getString(rs, 2)); - record.setOwner(getString(rs, 3)); - record.setGoes(getString(rs, 4)); - record.setRptfreq(getString(rs, 5)); - record.setRptime(getString(rs, 6)); - record.setNotify(getString(rs, 7)); - record.setObsvfreq(getString(rs, 8)); - record.setRandrept(getString(rs, 9)); - - // add this DcpRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DcpRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DcpRecord object and.. -//----------------------------------------------------------------- - public int insert(DcpRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dcp VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getCriteria()); - setString(insertStatement, 3, record.getOwner()); - setString(insertStatement, 4, record.getGoes()); - setString(insertStatement, 5, record.getRptfreq()); - setString(insertStatement, 6, record.getRptime()); - setString(insertStatement, 7, record.getNotify()); - setString(insertStatement, 8, record.getObsvfreq()); - setString(insertStatement, 9, record.getRandrept()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dcp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DcpRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DcpRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dcp SET lid = ?, criteria = ?, owner = ?, goes = ?, rptfreq = ?, rptime = ?, notify = ?, obsvfreq = ?, randrept = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getCriteria()); - setString(updateStatement, 3, record.getOwner()); - setString(updateStatement, 4, record.getGoes()); - setString(updateStatement, 5, record.getRptfreq()); - setString(updateStatement, 6, record.getRptime()); - setString(updateStatement, 7, record.getNotify()); - setString(updateStatement, 8, record.getObsvfreq()); - setString(updateStatement, 9, record.getRandrept()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DcpRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dcp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DcpRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DcpRecord oldRecord, DcpRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dcp SET lid = ?, criteria = ?, owner = ?, goes = ?, rptfreq = ?, rptime = ?, notify = ?, obsvfreq = ?, randrept = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getCriteria()); - setString(updateStatement, 3, newRecord.getOwner()); - setString(updateStatement, 4, newRecord.getGoes()); - setString(updateStatement, 5, newRecord.getRptfreq()); - setString(updateStatement, 6, newRecord.getRptime()); - setString(updateStatement, 7, newRecord.getNotify()); - setString(updateStatement, 8, newRecord.getObsvfreq()); - setString(updateStatement, 9, newRecord.getRandrept()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DcpRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DcpRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DcpRecord oldRecord = (DcpRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DcpTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DefiningIssueCriteriaRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DefiningIssueCriteriaRecord.java deleted file mode 100644 index e3705cf7b4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DefiningIssueCriteriaRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: DefiningIssueCriteriaRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DefiningIssueCriteria table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DefiningIssueCriteriaRecord extends DbRecord -{ - private String def_issue_crit; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DefiningIssueCriteriaRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DefiningIssueCriteriaRecord(DefiningIssueCriteriaRecord origRecord) - { - setDef_issue_crit(origRecord.getDef_issue_crit()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DefiningIssueCriteria record - - //----------------------------------------------------------------- - public String getDef_issue_crit() - { - return def_issue_crit; - } - - public void setDef_issue_crit(String def_issue_crit) - { - this.def_issue_crit = def_issue_crit ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE def_issue_crit = '" + def_issue_crit + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getDef_issue_crit() + " " + - "" ; - return outString; - } // end toString() -} // end of DefiningIssueCriteriaRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DefiningIssueCriteriaTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DefiningIssueCriteriaTable.java deleted file mode 100644 index ccaac473ea..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DefiningIssueCriteriaTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: DefiningIssueCriteriaTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// definingissuecriteria table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DefiningIssueCriteriaTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DefiningIssueCriteriaTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DefiningIssueCriteriaTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("definingissuecriteria"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DefiningIssueCriteriaRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DefiningIssueCriteriaRecord record = null; - - // create a List to hold DefiningIssueCriteria Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM definingissuecriteria " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DefiningIssueCriteriaRecord - // and store its address in oneRecord - record = new DefiningIssueCriteriaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DefiningIssueCriteriaRecord object - - record.setDef_issue_crit(getString(rs, 1)); - - // add this DefiningIssueCriteriaRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DefiningIssueCriteriaRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DefiningIssueCriteriaRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DefiningIssueCriteriaRecord record = null; - - // create a List to hold DefiningIssueCriteria Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM definingissuecriteria " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DefiningIssueCriteriaRecord - // and store its address in oneRecord - record = new DefiningIssueCriteriaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DefiningIssueCriteriaRecord object - - record.setDef_issue_crit(getString(rs, 1)); - - // add this DefiningIssueCriteriaRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DefiningIssueCriteriaRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DefiningIssueCriteriaRecord object and.. -//----------------------------------------------------------------- - public int insert(DefiningIssueCriteriaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO definingissuecriteria VALUES (? )"); - - setString(insertStatement, 1, record.getDef_issue_crit()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM definingissuecriteria " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DefiningIssueCriteriaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DefiningIssueCriteriaRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE definingissuecriteria SET def_issue_crit = ? " + where ); - - setString(updateStatement, 1, record.getDef_issue_crit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DefiningIssueCriteriaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM definingissuecriteria " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DefiningIssueCriteriaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DefiningIssueCriteriaRecord oldRecord, DefiningIssueCriteriaRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE definingissuecriteria SET def_issue_crit = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getDef_issue_crit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DefiningIssueCriteriaRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DefiningIssueCriteriaRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DefiningIssueCriteriaRecord oldRecord = (DefiningIssueCriteriaRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DefiningIssueCriteriaTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DescripRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DescripRecord.java deleted file mode 100644 index 302a4232b8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DescripRecord.java +++ /dev/null @@ -1,181 +0,0 @@ -// filename: DescripRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Descrip table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DescripRecord extends DbRecord -{ - private String lid; - - private String bed; - - private String divert; - - private String remark; - - private String ice; - - private String proximity; - - private String reach; - - private String res; - - private String topo; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DescripRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DescripRecord(DescripRecord origRecord) - { - setLid(origRecord.getLid()); - setBed(origRecord.getBed()); - setDivert(origRecord.getDivert()); - setRemark(origRecord.getRemark()); - setIce(origRecord.getIce()); - setProximity(origRecord.getProximity()); - setReach(origRecord.getReach()); - setRes(origRecord.getRes()); - setTopo(origRecord.getTopo()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Descrip record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getBed() - { - return bed; - } - - public void setBed(String bed) - { - this.bed = bed ; - } - - public String getDivert() - { - return divert; - } - - public void setDivert(String divert) - { - this.divert = divert ; - } - - public String getRemark() - { - return remark; - } - - public void setRemark(String remark) - { - this.remark = remark ; - } - - public String getIce() - { - return ice; - } - - public void setIce(String ice) - { - this.ice = ice ; - } - - public String getProximity() - { - return proximity; - } - - public void setProximity(String proximity) - { - this.proximity = proximity ; - } - - public String getReach() - { - return reach; - } - - public void setReach(String reach) - { - this.reach = reach ; - } - - public String getRes() - { - return res; - } - - public void setRes(String res) - { - this.res = res ; - } - - public String getTopo() - { - return topo; - } - - public void setTopo(String topo) - { - this.topo = topo ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getBed() + " " + - getDivert() + " " + - getRemark() + " " + - getIce() + " " + - getProximity() + " " + - getReach() + " " + - getRes() + " " + - getTopo() + " " + - "" ; - return outString; - } // end toString() -} // end of DescripRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DescripTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DescripTable.java deleted file mode 100644 index e767347ec0..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DescripTable.java +++ /dev/null @@ -1,286 +0,0 @@ -// filename: DescripTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// descrip table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DescripTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DescripTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DescripTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("descrip"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DescripRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DescripRecord record = null; - - // create a List to hold Descrip Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM descrip " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DescripRecord - // and store its address in oneRecord - record = new DescripRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DescripRecord object - - record.setLid(getString(rs, 1)); - record.setBed(getString(rs, 2)); - record.setDivert(getString(rs, 3)); - record.setRemark(getString(rs, 4)); - record.setIce(getString(rs, 5)); - record.setProximity(getString(rs, 6)); - record.setReach(getString(rs, 7)); - record.setRes(getString(rs, 8)); - record.setTopo(getString(rs, 9)); - - // add this DescripRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DescripRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DescripRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DescripRecord record = null; - - // create a List to hold Descrip Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM descrip " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DescripRecord - // and store its address in oneRecord - record = new DescripRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DescripRecord object - - record.setLid(getString(rs, 1)); - record.setBed(getString(rs, 2)); - record.setDivert(getString(rs, 3)); - record.setRemark(getString(rs, 4)); - record.setIce(getString(rs, 5)); - record.setProximity(getString(rs, 6)); - record.setReach(getString(rs, 7)); - record.setRes(getString(rs, 8)); - record.setTopo(getString(rs, 9)); - - // add this DescripRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DescripRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DescripRecord object and.. -//----------------------------------------------------------------- - public int insert(DescripRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO descrip VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getBed()); - setString(insertStatement, 3, record.getDivert()); - setString(insertStatement, 4, record.getRemark()); - setString(insertStatement, 5, record.getIce()); - setString(insertStatement, 6, record.getProximity()); - setString(insertStatement, 7, record.getReach()); - setString(insertStatement, 8, record.getRes()); - setString(insertStatement, 9, record.getTopo()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM descrip " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DescripRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DescripRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE descrip SET lid = ?, bed = ?, divert = ?, remark = ?, ice = ?, proximity = ?, reach = ?, res = ?, topo = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getBed()); - setString(updateStatement, 3, record.getDivert()); - setString(updateStatement, 4, record.getRemark()); - setString(updateStatement, 5, record.getIce()); - setString(updateStatement, 6, record.getProximity()); - setString(updateStatement, 7, record.getReach()); - setString(updateStatement, 8, record.getRes()); - setString(updateStatement, 9, record.getTopo()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DescripRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM descrip " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DescripRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DescripRecord oldRecord, DescripRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE descrip SET lid = ?, bed = ?, divert = ?, remark = ?, ice = ?, proximity = ?, reach = ?, res = ?, topo = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getBed()); - setString(updateStatement, 3, newRecord.getDivert()); - setString(updateStatement, 4, newRecord.getRemark()); - setString(updateStatement, 5, newRecord.getIce()); - setString(updateStatement, 6, newRecord.getProximity()); - setString(updateStatement, 7, newRecord.getReach()); - setString(updateStatement, 8, newRecord.getRes()); - setString(updateStatement, 9, newRecord.getTopo()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DescripRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DescripRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DescripRecord oldRecord = (DescripRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DescripTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DischargeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DischargeRecord.java deleted file mode 100644 index f331d5246a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DischargeRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: DischargeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Discharge table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DischargeRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DischargeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DischargeRecord(DischargeRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Discharge record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of DischargeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DischargeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DischargeTable.java deleted file mode 100644 index 1edef07754..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DischargeTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: DischargeTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// discharge table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DischargeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DischargeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DischargeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("discharge"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DischargeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DischargeRecord record = null; - - // create a List to hold Discharge Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM discharge " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DischargeRecord - // and store its address in oneRecord - record = new DischargeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DischargeRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this DischargeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DischargeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DischargeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DischargeRecord record = null; - - // create a List to hold Discharge Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM discharge " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DischargeRecord - // and store its address in oneRecord - record = new DischargeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DischargeRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this DischargeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DischargeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DischargeRecord object and.. -//----------------------------------------------------------------- - public int insert(DischargeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO discharge VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM discharge " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DischargeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DischargeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE discharge SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DischargeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM discharge " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DischargeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DischargeRecord oldRecord, DischargeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE discharge SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DischargeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DischargeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DischargeRecord oldRecord = (DischargeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DischargeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DpaAdaptRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DpaAdaptRecord.java deleted file mode 100644 index cae021555c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DpaAdaptRecord.java +++ /dev/null @@ -1,756 +0,0 @@ -// filename: DpaAdaptRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// DpaAdapt table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class DpaAdaptRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private float min_reflth; - - private float max_reflth; - - private float ref_tltest; - - private float rng_tltin; - - private float rng_tltout; - - private float max_birng; - - private float min_birng; - - private float min_echoar; - - private float min_awrefl; - - private float max_pctred; - - private float mlt_zrcoef; - - private float pwr_zrcoef; - - private float min_zrefl; - - private float max_zrefl; - - private float beam_width; - - private float blockage_thresh; - - private float clutter_thresh; - - private float weight_thresh; - - private float hybrid_scan_thresh; - - private float low_reflect_thresh; - - private float detect_reflect_thr; - - private float detect_area_thresh; - - private float detect_time_thresh; - - private float exclusion_zones; - - private float max_stmspd; - - private float max_timdif; - - private float min_artcon; - - private float tim_p1cont; - - private float tim_p2cont; - - private float max_ecarch; - - private float rng_cutoff; - - private float rng_e1coef; - - private float rng_e2coef; - - private float rng_e3coef; - - private float min_prate; - - private float max_prate; - - private float tim_restrt; - - private float max_timint; - - private float min_timprd; - - private float thr_hlyout; - - private float end_timgag; - - private float max_prdval; - - private float max_hlyval; - - private float tim_biest; - - private float thr_nosets; - - private float res_bias; - - private float longest_lag; - - private String bias_applied; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public DpaAdaptRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public DpaAdaptRecord(DpaAdaptRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setMin_reflth(origRecord.getMin_reflth()); - setMax_reflth(origRecord.getMax_reflth()); - setRef_tltest(origRecord.getRef_tltest()); - setRng_tltin(origRecord.getRng_tltin()); - setRng_tltout(origRecord.getRng_tltout()); - setMax_birng(origRecord.getMax_birng()); - setMin_birng(origRecord.getMin_birng()); - setMin_echoar(origRecord.getMin_echoar()); - setMin_awrefl(origRecord.getMin_awrefl()); - setMax_pctred(origRecord.getMax_pctred()); - setMlt_zrcoef(origRecord.getMlt_zrcoef()); - setPwr_zrcoef(origRecord.getPwr_zrcoef()); - setMin_zrefl(origRecord.getMin_zrefl()); - setMax_zrefl(origRecord.getMax_zrefl()); - setBeam_width(origRecord.getBeam_width()); - setBlockage_thresh(origRecord.getBlockage_thresh()); - setClutter_thresh(origRecord.getClutter_thresh()); - setWeight_thresh(origRecord.getWeight_thresh()); - setHybrid_scan_thresh(origRecord.getHybrid_scan_thresh()); - setLow_reflect_thresh(origRecord.getLow_reflect_thresh()); - setDetect_reflect_thr(origRecord.getDetect_reflect_thr()); - setDetect_area_thresh(origRecord.getDetect_area_thresh()); - setDetect_time_thresh(origRecord.getDetect_time_thresh()); - setExclusion_zones(origRecord.getExclusion_zones()); - setMax_stmspd(origRecord.getMax_stmspd()); - setMax_timdif(origRecord.getMax_timdif()); - setMin_artcon(origRecord.getMin_artcon()); - setTim_p1cont(origRecord.getTim_p1cont()); - setTim_p2cont(origRecord.getTim_p2cont()); - setMax_ecarch(origRecord.getMax_ecarch()); - setRng_cutoff(origRecord.getRng_cutoff()); - setRng_e1coef(origRecord.getRng_e1coef()); - setRng_e2coef(origRecord.getRng_e2coef()); - setRng_e3coef(origRecord.getRng_e3coef()); - setMin_prate(origRecord.getMin_prate()); - setMax_prate(origRecord.getMax_prate()); - setTim_restrt(origRecord.getTim_restrt()); - setMax_timint(origRecord.getMax_timint()); - setMin_timprd(origRecord.getMin_timprd()); - setThr_hlyout(origRecord.getThr_hlyout()); - setEnd_timgag(origRecord.getEnd_timgag()); - setMax_prdval(origRecord.getMax_prdval()); - setMax_hlyval(origRecord.getMax_hlyval()); - setTim_biest(origRecord.getTim_biest()); - setThr_nosets(origRecord.getThr_nosets()); - setRes_bias(origRecord.getRes_bias()); - setLongest_lag(origRecord.getLongest_lag()); - setBias_applied(origRecord.getBias_applied()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a DpaAdapt record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public float getMin_reflth() - { - return min_reflth; - } - - public void setMin_reflth(float min_reflth) - { - this.min_reflth = min_reflth ; - } - - public float getMax_reflth() - { - return max_reflth; - } - - public void setMax_reflth(float max_reflth) - { - this.max_reflth = max_reflth ; - } - - public float getRef_tltest() - { - return ref_tltest; - } - - public void setRef_tltest(float ref_tltest) - { - this.ref_tltest = ref_tltest ; - } - - public float getRng_tltin() - { - return rng_tltin; - } - - public void setRng_tltin(float rng_tltin) - { - this.rng_tltin = rng_tltin ; - } - - public float getRng_tltout() - { - return rng_tltout; - } - - public void setRng_tltout(float rng_tltout) - { - this.rng_tltout = rng_tltout ; - } - - public float getMax_birng() - { - return max_birng; - } - - public void setMax_birng(float max_birng) - { - this.max_birng = max_birng ; - } - - public float getMin_birng() - { - return min_birng; - } - - public void setMin_birng(float min_birng) - { - this.min_birng = min_birng ; - } - - public float getMin_echoar() - { - return min_echoar; - } - - public void setMin_echoar(float min_echoar) - { - this.min_echoar = min_echoar ; - } - - public float getMin_awrefl() - { - return min_awrefl; - } - - public void setMin_awrefl(float min_awrefl) - { - this.min_awrefl = min_awrefl ; - } - - public float getMax_pctred() - { - return max_pctred; - } - - public void setMax_pctred(float max_pctred) - { - this.max_pctred = max_pctred ; - } - - public float getMlt_zrcoef() - { - return mlt_zrcoef; - } - - public void setMlt_zrcoef(float mlt_zrcoef) - { - this.mlt_zrcoef = mlt_zrcoef ; - } - - public float getPwr_zrcoef() - { - return pwr_zrcoef; - } - - public void setPwr_zrcoef(float pwr_zrcoef) - { - this.pwr_zrcoef = pwr_zrcoef ; - } - - public float getMin_zrefl() - { - return min_zrefl; - } - - public void setMin_zrefl(float min_zrefl) - { - this.min_zrefl = min_zrefl ; - } - - public float getMax_zrefl() - { - return max_zrefl; - } - - public void setMax_zrefl(float max_zrefl) - { - this.max_zrefl = max_zrefl ; - } - - public float getBeam_width() - { - return beam_width; - } - - public void setBeam_width(float beam_width) - { - this.beam_width = beam_width ; - } - - public float getBlockage_thresh() - { - return blockage_thresh; - } - - public void setBlockage_thresh(float blockage_thresh) - { - this.blockage_thresh = blockage_thresh ; - } - - public float getClutter_thresh() - { - return clutter_thresh; - } - - public void setClutter_thresh(float clutter_thresh) - { - this.clutter_thresh = clutter_thresh ; - } - - public float getWeight_thresh() - { - return weight_thresh; - } - - public void setWeight_thresh(float weight_thresh) - { - this.weight_thresh = weight_thresh ; - } - - public float getHybrid_scan_thresh() - { - return hybrid_scan_thresh; - } - - public void setHybrid_scan_thresh(float hybrid_scan_thresh) - { - this.hybrid_scan_thresh = hybrid_scan_thresh ; - } - - public float getLow_reflect_thresh() - { - return low_reflect_thresh; - } - - public void setLow_reflect_thresh(float low_reflect_thresh) - { - this.low_reflect_thresh = low_reflect_thresh ; - } - - public float getDetect_reflect_thr() - { - return detect_reflect_thr; - } - - public void setDetect_reflect_thr(float detect_reflect_thr) - { - this.detect_reflect_thr = detect_reflect_thr ; - } - - public float getDetect_area_thresh() - { - return detect_area_thresh; - } - - public void setDetect_area_thresh(float detect_area_thresh) - { - this.detect_area_thresh = detect_area_thresh ; - } - - public float getDetect_time_thresh() - { - return detect_time_thresh; - } - - public void setDetect_time_thresh(float detect_time_thresh) - { - this.detect_time_thresh = detect_time_thresh ; - } - - public float getExclusion_zones() - { - return exclusion_zones; - } - - public void setExclusion_zones(float exclusion_zones) - { - this.exclusion_zones = exclusion_zones ; - } - - public float getMax_stmspd() - { - return max_stmspd; - } - - public void setMax_stmspd(float max_stmspd) - { - this.max_stmspd = max_stmspd ; - } - - public float getMax_timdif() - { - return max_timdif; - } - - public void setMax_timdif(float max_timdif) - { - this.max_timdif = max_timdif ; - } - - public float getMin_artcon() - { - return min_artcon; - } - - public void setMin_artcon(float min_artcon) - { - this.min_artcon = min_artcon ; - } - - public float getTim_p1cont() - { - return tim_p1cont; - } - - public void setTim_p1cont(float tim_p1cont) - { - this.tim_p1cont = tim_p1cont ; - } - - public float getTim_p2cont() - { - return tim_p2cont; - } - - public void setTim_p2cont(float tim_p2cont) - { - this.tim_p2cont = tim_p2cont ; - } - - public float getMax_ecarch() - { - return max_ecarch; - } - - public void setMax_ecarch(float max_ecarch) - { - this.max_ecarch = max_ecarch ; - } - - public float getRng_cutoff() - { - return rng_cutoff; - } - - public void setRng_cutoff(float rng_cutoff) - { - this.rng_cutoff = rng_cutoff ; - } - - public float getRng_e1coef() - { - return rng_e1coef; - } - - public void setRng_e1coef(float rng_e1coef) - { - this.rng_e1coef = rng_e1coef ; - } - - public float getRng_e2coef() - { - return rng_e2coef; - } - - public void setRng_e2coef(float rng_e2coef) - { - this.rng_e2coef = rng_e2coef ; - } - - public float getRng_e3coef() - { - return rng_e3coef; - } - - public void setRng_e3coef(float rng_e3coef) - { - this.rng_e3coef = rng_e3coef ; - } - - public float getMin_prate() - { - return min_prate; - } - - public void setMin_prate(float min_prate) - { - this.min_prate = min_prate ; - } - - public float getMax_prate() - { - return max_prate; - } - - public void setMax_prate(float max_prate) - { - this.max_prate = max_prate ; - } - - public float getTim_restrt() - { - return tim_restrt; - } - - public void setTim_restrt(float tim_restrt) - { - this.tim_restrt = tim_restrt ; - } - - public float getMax_timint() - { - return max_timint; - } - - public void setMax_timint(float max_timint) - { - this.max_timint = max_timint ; - } - - public float getMin_timprd() - { - return min_timprd; - } - - public void setMin_timprd(float min_timprd) - { - this.min_timprd = min_timprd ; - } - - public float getThr_hlyout() - { - return thr_hlyout; - } - - public void setThr_hlyout(float thr_hlyout) - { - this.thr_hlyout = thr_hlyout ; - } - - public float getEnd_timgag() - { - return end_timgag; - } - - public void setEnd_timgag(float end_timgag) - { - this.end_timgag = end_timgag ; - } - - public float getMax_prdval() - { - return max_prdval; - } - - public void setMax_prdval(float max_prdval) - { - this.max_prdval = max_prdval ; - } - - public float getMax_hlyval() - { - return max_hlyval; - } - - public void setMax_hlyval(float max_hlyval) - { - this.max_hlyval = max_hlyval ; - } - - public float getTim_biest() - { - return tim_biest; - } - - public void setTim_biest(float tim_biest) - { - this.tim_biest = tim_biest ; - } - - public float getThr_nosets() - { - return thr_nosets; - } - - public void setThr_nosets(float thr_nosets) - { - this.thr_nosets = thr_nosets ; - } - - public float getRes_bias() - { - return res_bias; - } - - public void setRes_bias(float res_bias) - { - this.res_bias = res_bias ; - } - - public float getLongest_lag() - { - return longest_lag; - } - - public void setLongest_lag(float longest_lag) - { - this.longest_lag = longest_lag ; - } - - public String getBias_applied() - { - return bias_applied; - } - - public void setBias_applied(String bias_applied) - { - this.bias_applied = bias_applied ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMin_reflth() + " " + - getMax_reflth() + " " + - getRef_tltest() + " " + - getRng_tltin() + " " + - getRng_tltout() + " " + - getMax_birng() + " " + - getMin_birng() + " " + - getMin_echoar() + " " + - getMin_awrefl() + " " + - getMax_pctred() + " " + - getMlt_zrcoef() + " " + - getPwr_zrcoef() + " " + - getMin_zrefl() + " " + - getMax_zrefl() + " " + - getBeam_width() + " " + - getBlockage_thresh() + " " + - getClutter_thresh() + " " + - getWeight_thresh() + " " + - getHybrid_scan_thresh() + " " + - getLow_reflect_thresh() + " " + - getDetect_reflect_thr() + " " + - getDetect_area_thresh() + " " + - getDetect_time_thresh() + " " + - getExclusion_zones() + " " + - getMax_stmspd() + " " + - getMax_timdif() + " " + - getMin_artcon() + " " + - getTim_p1cont() + " " + - getTim_p2cont() + " " + - getMax_ecarch() + " " + - getRng_cutoff() + " " + - getRng_e1coef() + " " + - getRng_e2coef() + " " + - getRng_e3coef() + " " + - getMin_prate() + " " + - getMax_prate() + " " + - getTim_restrt() + " " + - getMax_timint() + " " + - getMin_timprd() + " " + - getThr_hlyout() + " " + - getEnd_timgag() + " " + - getMax_prdval() + " " + - getMax_hlyval() + " " + - getTim_biest() + " " + - getThr_nosets() + " " + - getRes_bias() + " " + - getLongest_lag() + " " + - getBias_applied() + " " + - "" ; - return outString; - } // end toString() -} // end of DpaAdaptRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DpaAdaptTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DpaAdaptTable.java deleted file mode 100644 index d2072b68ab..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/DpaAdaptTable.java +++ /dev/null @@ -1,491 +0,0 @@ -// filename: DpaAdaptTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dpaadapt table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class DpaAdaptTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// DpaAdaptTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public DpaAdaptTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dpaadapt"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of DpaAdaptRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - DpaAdaptRecord record = null; - - // create a List to hold DpaAdapt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dpaadapt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DpaAdaptRecord - // and store its address in oneRecord - record = new DpaAdaptRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DpaAdaptRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMin_reflth(getReal(rs, 3)); - record.setMax_reflth(getReal(rs, 4)); - record.setRef_tltest(getReal(rs, 5)); - record.setRng_tltin(getReal(rs, 6)); - record.setRng_tltout(getReal(rs, 7)); - record.setMax_birng(getReal(rs, 8)); - record.setMin_birng(getReal(rs, 9)); - record.setMin_echoar(getReal(rs, 10)); - record.setMin_awrefl(getReal(rs, 11)); - record.setMax_pctred(getReal(rs, 12)); - record.setMlt_zrcoef(getReal(rs, 13)); - record.setPwr_zrcoef(getReal(rs, 14)); - record.setMin_zrefl(getReal(rs, 15)); - record.setMax_zrefl(getReal(rs, 16)); - record.setBeam_width(getReal(rs, 17)); - record.setBlockage_thresh(getReal(rs, 18)); - record.setClutter_thresh(getReal(rs, 19)); - record.setWeight_thresh(getReal(rs, 20)); - record.setHybrid_scan_thresh(getReal(rs, 21)); - record.setLow_reflect_thresh(getReal(rs, 22)); - record.setDetect_reflect_thr(getReal(rs, 23)); - record.setDetect_area_thresh(getReal(rs, 24)); - record.setDetect_time_thresh(getReal(rs, 25)); - record.setExclusion_zones(getReal(rs, 26)); - record.setMax_stmspd(getReal(rs, 27)); - record.setMax_timdif(getReal(rs, 28)); - record.setMin_artcon(getReal(rs, 29)); - record.setTim_p1cont(getReal(rs, 30)); - record.setTim_p2cont(getReal(rs, 31)); - record.setMax_ecarch(getReal(rs, 32)); - record.setRng_cutoff(getReal(rs, 33)); - record.setRng_e1coef(getReal(rs, 34)); - record.setRng_e2coef(getReal(rs, 35)); - record.setRng_e3coef(getReal(rs, 36)); - record.setMin_prate(getReal(rs, 37)); - record.setMax_prate(getReal(rs, 38)); - record.setTim_restrt(getReal(rs, 39)); - record.setMax_timint(getReal(rs, 40)); - record.setMin_timprd(getReal(rs, 41)); - record.setThr_hlyout(getReal(rs, 42)); - record.setEnd_timgag(getReal(rs, 43)); - record.setMax_prdval(getReal(rs, 44)); - record.setMax_hlyval(getReal(rs, 45)); - record.setTim_biest(getReal(rs, 46)); - record.setThr_nosets(getReal(rs, 47)); - record.setRes_bias(getReal(rs, 48)); - record.setLongest_lag(getReal(rs, 49)); - record.setBias_applied(getString(rs, 50)); - - // add this DpaAdaptRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the DpaAdaptRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of DpaAdaptRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - DpaAdaptRecord record = null; - - // create a List to hold DpaAdapt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dpaadapt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a DpaAdaptRecord - // and store its address in oneRecord - record = new DpaAdaptRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a DpaAdaptRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMin_reflth(getReal(rs, 3)); - record.setMax_reflth(getReal(rs, 4)); - record.setRef_tltest(getReal(rs, 5)); - record.setRng_tltin(getReal(rs, 6)); - record.setRng_tltout(getReal(rs, 7)); - record.setMax_birng(getReal(rs, 8)); - record.setMin_birng(getReal(rs, 9)); - record.setMin_echoar(getReal(rs, 10)); - record.setMin_awrefl(getReal(rs, 11)); - record.setMax_pctred(getReal(rs, 12)); - record.setMlt_zrcoef(getReal(rs, 13)); - record.setPwr_zrcoef(getReal(rs, 14)); - record.setMin_zrefl(getReal(rs, 15)); - record.setMax_zrefl(getReal(rs, 16)); - record.setBeam_width(getReal(rs, 17)); - record.setBlockage_thresh(getReal(rs, 18)); - record.setClutter_thresh(getReal(rs, 19)); - record.setWeight_thresh(getReal(rs, 20)); - record.setHybrid_scan_thresh(getReal(rs, 21)); - record.setLow_reflect_thresh(getReal(rs, 22)); - record.setDetect_reflect_thr(getReal(rs, 23)); - record.setDetect_area_thresh(getReal(rs, 24)); - record.setDetect_time_thresh(getReal(rs, 25)); - record.setExclusion_zones(getReal(rs, 26)); - record.setMax_stmspd(getReal(rs, 27)); - record.setMax_timdif(getReal(rs, 28)); - record.setMin_artcon(getReal(rs, 29)); - record.setTim_p1cont(getReal(rs, 30)); - record.setTim_p2cont(getReal(rs, 31)); - record.setMax_ecarch(getReal(rs, 32)); - record.setRng_cutoff(getReal(rs, 33)); - record.setRng_e1coef(getReal(rs, 34)); - record.setRng_e2coef(getReal(rs, 35)); - record.setRng_e3coef(getReal(rs, 36)); - record.setMin_prate(getReal(rs, 37)); - record.setMax_prate(getReal(rs, 38)); - record.setTim_restrt(getReal(rs, 39)); - record.setMax_timint(getReal(rs, 40)); - record.setMin_timprd(getReal(rs, 41)); - record.setThr_hlyout(getReal(rs, 42)); - record.setEnd_timgag(getReal(rs, 43)); - record.setMax_prdval(getReal(rs, 44)); - record.setMax_hlyval(getReal(rs, 45)); - record.setTim_biest(getReal(rs, 46)); - record.setThr_nosets(getReal(rs, 47)); - record.setRes_bias(getReal(rs, 48)); - record.setLongest_lag(getReal(rs, 49)); - record.setBias_applied(getString(rs, 50)); - - // add this DpaAdaptRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the DpaAdaptRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a DpaAdaptRecord object and.. -//----------------------------------------------------------------- - public int insert(DpaAdaptRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dpaadapt VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setReal(insertStatement, 3, record.getMin_reflth()); - setReal(insertStatement, 4, record.getMax_reflth()); - setReal(insertStatement, 5, record.getRef_tltest()); - setReal(insertStatement, 6, record.getRng_tltin()); - setReal(insertStatement, 7, record.getRng_tltout()); - setReal(insertStatement, 8, record.getMax_birng()); - setReal(insertStatement, 9, record.getMin_birng()); - setReal(insertStatement, 10, record.getMin_echoar()); - setReal(insertStatement, 11, record.getMin_awrefl()); - setReal(insertStatement, 12, record.getMax_pctred()); - setReal(insertStatement, 13, record.getMlt_zrcoef()); - setReal(insertStatement, 14, record.getPwr_zrcoef()); - setReal(insertStatement, 15, record.getMin_zrefl()); - setReal(insertStatement, 16, record.getMax_zrefl()); - setReal(insertStatement, 17, record.getBeam_width()); - setReal(insertStatement, 18, record.getBlockage_thresh()); - setReal(insertStatement, 19, record.getClutter_thresh()); - setReal(insertStatement, 20, record.getWeight_thresh()); - setReal(insertStatement, 21, record.getHybrid_scan_thresh()); - setReal(insertStatement, 22, record.getLow_reflect_thresh()); - setReal(insertStatement, 23, record.getDetect_reflect_thr()); - setReal(insertStatement, 24, record.getDetect_area_thresh()); - setReal(insertStatement, 25, record.getDetect_time_thresh()); - setReal(insertStatement, 26, record.getExclusion_zones()); - setReal(insertStatement, 27, record.getMax_stmspd()); - setReal(insertStatement, 28, record.getMax_timdif()); - setReal(insertStatement, 29, record.getMin_artcon()); - setReal(insertStatement, 30, record.getTim_p1cont()); - setReal(insertStatement, 31, record.getTim_p2cont()); - setReal(insertStatement, 32, record.getMax_ecarch()); - setReal(insertStatement, 33, record.getRng_cutoff()); - setReal(insertStatement, 34, record.getRng_e1coef()); - setReal(insertStatement, 35, record.getRng_e2coef()); - setReal(insertStatement, 36, record.getRng_e3coef()); - setReal(insertStatement, 37, record.getMin_prate()); - setReal(insertStatement, 38, record.getMax_prate()); - setReal(insertStatement, 39, record.getTim_restrt()); - setReal(insertStatement, 40, record.getMax_timint()); - setReal(insertStatement, 41, record.getMin_timprd()); - setReal(insertStatement, 42, record.getThr_hlyout()); - setReal(insertStatement, 43, record.getEnd_timgag()); - setReal(insertStatement, 44, record.getMax_prdval()); - setReal(insertStatement, 45, record.getMax_hlyval()); - setReal(insertStatement, 46, record.getTim_biest()); - setReal(insertStatement, 47, record.getThr_nosets()); - setReal(insertStatement, 48, record.getRes_bias()); - setReal(insertStatement, 49, record.getLongest_lag()); - setString(insertStatement, 50, record.getBias_applied()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dpaadapt " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DpaAdaptRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DpaAdaptRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dpaadapt SET radid = ?, obstime = ?, min_reflth = ?, max_reflth = ?, ref_tltest = ?, rng_tltin = ?, rng_tltout = ?, max_birng = ?, min_birng = ?, min_echoar = ?, min_awrefl = ?, max_pctred = ?, mlt_zrcoef = ?, pwr_zrcoef = ?, min_zrefl = ?, max_zrefl = ?, beam_width = ?, blockage_thresh = ?, clutter_thresh = ?, weight_thresh = ?, hybrid_scan_thresh = ?, low_reflect_thresh = ?, detect_reflect_thr = ?, detect_area_thresh = ?, detect_time_thresh = ?, exclusion_zones = ?, max_stmspd = ?, max_timdif = ?, min_artcon = ?, tim_p1cont = ?, tim_p2cont = ?, max_ecarch = ?, rng_cutoff = ?, rng_e1coef = ?, rng_e2coef = ?, rng_e3coef = ?, min_prate = ?, max_prate = ?, tim_restrt = ?, max_timint = ?, min_timprd = ?, thr_hlyout = ?, end_timgag = ?, max_prdval = ?, max_hlyval = ?, tim_biest = ?, thr_nosets = ?, res_bias = ?, longest_lag = ?, bias_applied = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setReal(updateStatement, 3, record.getMin_reflth()); - setReal(updateStatement, 4, record.getMax_reflth()); - setReal(updateStatement, 5, record.getRef_tltest()); - setReal(updateStatement, 6, record.getRng_tltin()); - setReal(updateStatement, 7, record.getRng_tltout()); - setReal(updateStatement, 8, record.getMax_birng()); - setReal(updateStatement, 9, record.getMin_birng()); - setReal(updateStatement, 10, record.getMin_echoar()); - setReal(updateStatement, 11, record.getMin_awrefl()); - setReal(updateStatement, 12, record.getMax_pctred()); - setReal(updateStatement, 13, record.getMlt_zrcoef()); - setReal(updateStatement, 14, record.getPwr_zrcoef()); - setReal(updateStatement, 15, record.getMin_zrefl()); - setReal(updateStatement, 16, record.getMax_zrefl()); - setReal(updateStatement, 17, record.getBeam_width()); - setReal(updateStatement, 18, record.getBlockage_thresh()); - setReal(updateStatement, 19, record.getClutter_thresh()); - setReal(updateStatement, 20, record.getWeight_thresh()); - setReal(updateStatement, 21, record.getHybrid_scan_thresh()); - setReal(updateStatement, 22, record.getLow_reflect_thresh()); - setReal(updateStatement, 23, record.getDetect_reflect_thr()); - setReal(updateStatement, 24, record.getDetect_area_thresh()); - setReal(updateStatement, 25, record.getDetect_time_thresh()); - setReal(updateStatement, 26, record.getExclusion_zones()); - setReal(updateStatement, 27, record.getMax_stmspd()); - setReal(updateStatement, 28, record.getMax_timdif()); - setReal(updateStatement, 29, record.getMin_artcon()); - setReal(updateStatement, 30, record.getTim_p1cont()); - setReal(updateStatement, 31, record.getTim_p2cont()); - setReal(updateStatement, 32, record.getMax_ecarch()); - setReal(updateStatement, 33, record.getRng_cutoff()); - setReal(updateStatement, 34, record.getRng_e1coef()); - setReal(updateStatement, 35, record.getRng_e2coef()); - setReal(updateStatement, 36, record.getRng_e3coef()); - setReal(updateStatement, 37, record.getMin_prate()); - setReal(updateStatement, 38, record.getMax_prate()); - setReal(updateStatement, 39, record.getTim_restrt()); - setReal(updateStatement, 40, record.getMax_timint()); - setReal(updateStatement, 41, record.getMin_timprd()); - setReal(updateStatement, 42, record.getThr_hlyout()); - setReal(updateStatement, 43, record.getEnd_timgag()); - setReal(updateStatement, 44, record.getMax_prdval()); - setReal(updateStatement, 45, record.getMax_hlyval()); - setReal(updateStatement, 46, record.getTim_biest()); - setReal(updateStatement, 47, record.getThr_nosets()); - setReal(updateStatement, 48, record.getRes_bias()); - setReal(updateStatement, 49, record.getLongest_lag()); - setString(updateStatement, 50, record.getBias_applied()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(DpaAdaptRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dpaadapt " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a DpaAdaptRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(DpaAdaptRecord oldRecord, DpaAdaptRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dpaadapt SET radid = ?, obstime = ?, min_reflth = ?, max_reflth = ?, ref_tltest = ?, rng_tltin = ?, rng_tltout = ?, max_birng = ?, min_birng = ?, min_echoar = ?, min_awrefl = ?, max_pctred = ?, mlt_zrcoef = ?, pwr_zrcoef = ?, min_zrefl = ?, max_zrefl = ?, beam_width = ?, blockage_thresh = ?, clutter_thresh = ?, weight_thresh = ?, hybrid_scan_thresh = ?, low_reflect_thresh = ?, detect_reflect_thr = ?, detect_area_thresh = ?, detect_time_thresh = ?, exclusion_zones = ?, max_stmspd = ?, max_timdif = ?, min_artcon = ?, tim_p1cont = ?, tim_p2cont = ?, max_ecarch = ?, rng_cutoff = ?, rng_e1coef = ?, rng_e2coef = ?, rng_e3coef = ?, min_prate = ?, max_prate = ?, tim_restrt = ?, max_timint = ?, min_timprd = ?, thr_hlyout = ?, end_timgag = ?, max_prdval = ?, max_hlyval = ?, tim_biest = ?, thr_nosets = ?, res_bias = ?, longest_lag = ?, bias_applied = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setReal(updateStatement, 3, newRecord.getMin_reflth()); - setReal(updateStatement, 4, newRecord.getMax_reflth()); - setReal(updateStatement, 5, newRecord.getRef_tltest()); - setReal(updateStatement, 6, newRecord.getRng_tltin()); - setReal(updateStatement, 7, newRecord.getRng_tltout()); - setReal(updateStatement, 8, newRecord.getMax_birng()); - setReal(updateStatement, 9, newRecord.getMin_birng()); - setReal(updateStatement, 10, newRecord.getMin_echoar()); - setReal(updateStatement, 11, newRecord.getMin_awrefl()); - setReal(updateStatement, 12, newRecord.getMax_pctred()); - setReal(updateStatement, 13, newRecord.getMlt_zrcoef()); - setReal(updateStatement, 14, newRecord.getPwr_zrcoef()); - setReal(updateStatement, 15, newRecord.getMin_zrefl()); - setReal(updateStatement, 16, newRecord.getMax_zrefl()); - setReal(updateStatement, 17, newRecord.getBeam_width()); - setReal(updateStatement, 18, newRecord.getBlockage_thresh()); - setReal(updateStatement, 19, newRecord.getClutter_thresh()); - setReal(updateStatement, 20, newRecord.getWeight_thresh()); - setReal(updateStatement, 21, newRecord.getHybrid_scan_thresh()); - setReal(updateStatement, 22, newRecord.getLow_reflect_thresh()); - setReal(updateStatement, 23, newRecord.getDetect_reflect_thr()); - setReal(updateStatement, 24, newRecord.getDetect_area_thresh()); - setReal(updateStatement, 25, newRecord.getDetect_time_thresh()); - setReal(updateStatement, 26, newRecord.getExclusion_zones()); - setReal(updateStatement, 27, newRecord.getMax_stmspd()); - setReal(updateStatement, 28, newRecord.getMax_timdif()); - setReal(updateStatement, 29, newRecord.getMin_artcon()); - setReal(updateStatement, 30, newRecord.getTim_p1cont()); - setReal(updateStatement, 31, newRecord.getTim_p2cont()); - setReal(updateStatement, 32, newRecord.getMax_ecarch()); - setReal(updateStatement, 33, newRecord.getRng_cutoff()); - setReal(updateStatement, 34, newRecord.getRng_e1coef()); - setReal(updateStatement, 35, newRecord.getRng_e2coef()); - setReal(updateStatement, 36, newRecord.getRng_e3coef()); - setReal(updateStatement, 37, newRecord.getMin_prate()); - setReal(updateStatement, 38, newRecord.getMax_prate()); - setReal(updateStatement, 39, newRecord.getTim_restrt()); - setReal(updateStatement, 40, newRecord.getMax_timint()); - setReal(updateStatement, 41, newRecord.getMin_timprd()); - setReal(updateStatement, 42, newRecord.getThr_hlyout()); - setReal(updateStatement, 43, newRecord.getEnd_timgag()); - setReal(updateStatement, 44, newRecord.getMax_prdval()); - setReal(updateStatement, 45, newRecord.getMax_hlyval()); - setReal(updateStatement, 46, newRecord.getTim_biest()); - setReal(updateStatement, 47, newRecord.getThr_nosets()); - setReal(updateStatement, 48, newRecord.getRes_bias()); - setReal(updateStatement, 49, newRecord.getLongest_lag()); - setString(updateStatement, 50, newRecord.getBias_applied()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a DpaAdaptRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(DpaAdaptRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - DpaAdaptRecord oldRecord = (DpaAdaptRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of DpaAdaptTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EligzonRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EligzonRecord.java deleted file mode 100644 index 8847776b6d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EligzonRecord.java +++ /dev/null @@ -1,98 +0,0 @@ -// filename: EligzonRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Eligzon table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class EligzonRecord extends DbRecord -{ - private String state; - - private String zonenum; - - private String descr; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public EligzonRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public EligzonRecord(EligzonRecord origRecord) - { - setState(origRecord.getState()); - setZonenum(origRecord.getZonenum()); - setDescr(origRecord.getDescr()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Eligzon record - - //----------------------------------------------------------------- - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getZonenum() - { - return zonenum; - } - - public void setZonenum(String zonenum) - { - this.zonenum = zonenum ; - } - - public String getDescr() - { - return descr; - } - - public void setDescr(String descr) - { - this.descr = descr ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE state = '" + state + "'" - + " AND zonenum = '" + zonenum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getState() + " " + - getZonenum() + " " + - getDescr() + " " + - "" ; - return outString; - } // end toString() -} // end of EligzonRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EligzonTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EligzonTable.java deleted file mode 100644 index 92a7e6d598..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EligzonTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: EligzonTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// eligzon table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class EligzonTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// EligzonTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public EligzonTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("eligzon"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of EligzonRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - EligzonRecord record = null; - - // create a List to hold Eligzon Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM eligzon " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a EligzonRecord - // and store its address in oneRecord - record = new EligzonRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a EligzonRecord object - - record.setState(getString(rs, 1)); - record.setZonenum(getString(rs, 2)); - record.setDescr(getString(rs, 3)); - - // add this EligzonRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the EligzonRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of EligzonRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - EligzonRecord record = null; - - // create a List to hold Eligzon Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM eligzon " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a EligzonRecord - // and store its address in oneRecord - record = new EligzonRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a EligzonRecord object - - record.setState(getString(rs, 1)); - record.setZonenum(getString(rs, 2)); - record.setDescr(getString(rs, 3)); - - // add this EligzonRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the EligzonRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a EligzonRecord object and.. -//----------------------------------------------------------------- - public int insert(EligzonRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO eligzon VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getState()); - setString(insertStatement, 2, record.getZonenum()); - setString(insertStatement, 3, record.getDescr()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM eligzon " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a EligzonRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(EligzonRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE eligzon SET state = ?, zonenum = ?, descr = ? " + where ); - - setString(updateStatement, 1, record.getState()); - setString(updateStatement, 2, record.getZonenum()); - setString(updateStatement, 3, record.getDescr()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(EligzonRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM eligzon " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a EligzonRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(EligzonRecord oldRecord, EligzonRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE eligzon SET state = ?, zonenum = ?, descr = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getState()); - setString(updateStatement, 2, newRecord.getZonenum()); - setString(updateStatement, 3, newRecord.getDescr()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a EligzonRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(EligzonRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - EligzonRecord oldRecord = (EligzonRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of EligzonTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EvaporationRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EvaporationRecord.java deleted file mode 100644 index f92c3ddeeb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EvaporationRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: EvaporationRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Evaporation table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class EvaporationRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public EvaporationRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public EvaporationRecord(EvaporationRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Evaporation record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of EvaporationRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EvaporationTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EvaporationTable.java deleted file mode 100644 index 8a3f1f94f4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/EvaporationTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: EvaporationTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// evaporation table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class EvaporationTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// EvaporationTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public EvaporationTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("evaporation"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of EvaporationRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - EvaporationRecord record = null; - - // create a List to hold Evaporation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM evaporation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a EvaporationRecord - // and store its address in oneRecord - record = new EvaporationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a EvaporationRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this EvaporationRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the EvaporationRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of EvaporationRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - EvaporationRecord record = null; - - // create a List to hold Evaporation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM evaporation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a EvaporationRecord - // and store its address in oneRecord - record = new EvaporationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a EvaporationRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this EvaporationRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the EvaporationRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a EvaporationRecord object and.. -//----------------------------------------------------------------- - public int insert(EvaporationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO evaporation VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM evaporation " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a EvaporationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(EvaporationRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE evaporation SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(EvaporationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM evaporation " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a EvaporationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(EvaporationRecord oldRecord, EvaporationRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE evaporation SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a EvaporationRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(EvaporationRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - EvaporationRecord oldRecord = (EvaporationRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of EvaporationTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstDischargeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstDischargeRecord.java deleted file mode 100644 index 44c2556c6e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstDischargeRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: FcstDischargeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstDischarge table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstDischargeRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstDischargeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstDischargeRecord(FcstDischargeRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstDischarge record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FcstDischargeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstDischargeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstDischargeTable.java deleted file mode 100644 index 13d977d8d5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstDischargeTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: FcstDischargeTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstdischarge table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstDischargeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstDischargeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstDischargeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstdischarge"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstDischargeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstDischargeRecord record = null; - - // create a List to hold FcstDischarge Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstdischarge " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstDischargeRecord - // and store its address in oneRecord - record = new FcstDischargeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstDischargeRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstDischargeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstDischargeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstDischargeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstDischargeRecord record = null; - - // create a List to hold FcstDischarge Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstdischarge " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstDischargeRecord - // and store its address in oneRecord - record = new FcstDischargeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstDischargeRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstDischargeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstDischargeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstDischargeRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstDischargeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstdischarge VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstdischarge " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstDischargeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstDischargeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstdischarge SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstDischargeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstdischarge " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstDischargeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstDischargeRecord oldRecord, FcstDischargeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstdischarge SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstDischargeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstDischargeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstDischargeRecord oldRecord = (FcstDischargeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstDischargeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstGenMethodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstGenMethodRecord.java deleted file mode 100644 index 6090df97b7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstGenMethodRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: FcstGenMethodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstGenMethod table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstGenMethodRecord extends DbRecord -{ - private String fcst_gen_method; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstGenMethodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstGenMethodRecord(FcstGenMethodRecord origRecord) - { - setFcst_gen_method(origRecord.getFcst_gen_method()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstGenMethod record - - //----------------------------------------------------------------- - public String getFcst_gen_method() - { - return fcst_gen_method; - } - - public void setFcst_gen_method(String fcst_gen_method) - { - this.fcst_gen_method = fcst_gen_method ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE fcst_gen_method = '" + fcst_gen_method + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getFcst_gen_method() + " " + - "" ; - return outString; - } // end toString() -} // end of FcstGenMethodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstGenMethodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstGenMethodTable.java deleted file mode 100644 index 1b9e7a6fc8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstGenMethodTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: FcstGenMethodTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstgenmethod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstGenMethodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstGenMethodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstGenMethodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstgenmethod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstGenMethodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstGenMethodRecord record = null; - - // create a List to hold FcstGenMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstgenmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstGenMethodRecord - // and store its address in oneRecord - record = new FcstGenMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstGenMethodRecord object - - record.setFcst_gen_method(getString(rs, 1)); - - // add this FcstGenMethodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstGenMethodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstGenMethodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstGenMethodRecord record = null; - - // create a List to hold FcstGenMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstgenmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstGenMethodRecord - // and store its address in oneRecord - record = new FcstGenMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstGenMethodRecord object - - record.setFcst_gen_method(getString(rs, 1)); - - // add this FcstGenMethodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstGenMethodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstGenMethodRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstGenMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstgenmethod VALUES (? )"); - - setString(insertStatement, 1, record.getFcst_gen_method()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstgenmethod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstGenMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstGenMethodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstgenmethod SET fcst_gen_method = ? " + where ); - - setString(updateStatement, 1, record.getFcst_gen_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstGenMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstgenmethod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstGenMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstGenMethodRecord oldRecord, FcstGenMethodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstgenmethod SET fcst_gen_method = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getFcst_gen_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstGenMethodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstGenMethodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstGenMethodRecord oldRecord = (FcstGenMethodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstGenMethodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHeightRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHeightRecord.java deleted file mode 100644 index b3e91411f6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHeightRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: FcstHeightRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstHeight table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstHeightRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstHeightRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstHeightRecord(FcstHeightRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstHeight record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FcstHeightRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHeightTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHeightTable.java deleted file mode 100644 index 51a8790a72..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHeightTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: FcstHeightTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstheight table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstHeightTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstHeightTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstHeightTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstheight"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstHeightRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstHeightRecord record = null; - - // create a List to hold FcstHeight Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstheight " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstHeightRecord - // and store its address in oneRecord - record = new FcstHeightRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstHeightRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstHeightRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstHeightRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstHeightRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstHeightRecord record = null; - - // create a List to hold FcstHeight Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstheight " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstHeightRecord - // and store its address in oneRecord - record = new FcstHeightRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstHeightRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstHeightRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstHeightRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstHeightRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstHeightRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstheight VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstheight " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstHeightRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstHeightRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstheight SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstHeightRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstheight " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstHeightRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstHeightRecord oldRecord, FcstHeightRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstheight SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstHeightRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstHeightRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstHeightRecord oldRecord = (FcstHeightRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstHeightTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHorizonRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHorizonRecord.java deleted file mode 100644 index 6d16346d24..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHorizonRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: FcstHorizonRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstHorizon table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstHorizonRecord extends DbRecord -{ - private String fcst_horizon; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstHorizonRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstHorizonRecord(FcstHorizonRecord origRecord) - { - setFcst_horizon(origRecord.getFcst_horizon()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstHorizon record - - //----------------------------------------------------------------- - public String getFcst_horizon() - { - return fcst_horizon; - } - - public void setFcst_horizon(String fcst_horizon) - { - this.fcst_horizon = fcst_horizon ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE fcst_horizon = '" + fcst_horizon + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getFcst_horizon() + " " + - "" ; - return outString; - } // end toString() -} // end of FcstHorizonRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHorizonTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHorizonTable.java deleted file mode 100644 index 521e4a3575..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstHorizonTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: FcstHorizonTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcsthorizon table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstHorizonTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstHorizonTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstHorizonTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcsthorizon"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstHorizonRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstHorizonRecord record = null; - - // create a List to hold FcstHorizon Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcsthorizon " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstHorizonRecord - // and store its address in oneRecord - record = new FcstHorizonRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstHorizonRecord object - - record.setFcst_horizon(getString(rs, 1)); - - // add this FcstHorizonRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstHorizonRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstHorizonRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstHorizonRecord record = null; - - // create a List to hold FcstHorizon Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcsthorizon " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstHorizonRecord - // and store its address in oneRecord - record = new FcstHorizonRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstHorizonRecord object - - record.setFcst_horizon(getString(rs, 1)); - - // add this FcstHorizonRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstHorizonRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstHorizonRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstHorizonRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcsthorizon VALUES (? )"); - - setString(insertStatement, 1, record.getFcst_horizon()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcsthorizon " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstHorizonRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstHorizonRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcsthorizon SET fcst_horizon = ? " + where ); - - setString(updateStatement, 1, record.getFcst_horizon()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstHorizonRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcsthorizon " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstHorizonRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstHorizonRecord oldRecord, FcstHorizonRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcsthorizon SET fcst_horizon = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getFcst_horizon()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstHorizonRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstHorizonRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstHorizonRecord oldRecord = (FcstHorizonRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstHorizonTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstOtherRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstOtherRecord.java deleted file mode 100644 index cdc2c21c67..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstOtherRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: FcstOtherRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstOther table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstOtherRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstOtherRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstOtherRecord(FcstOtherRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstOther record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FcstOtherRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstOtherTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstOtherTable.java deleted file mode 100644 index 91d70db9f7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstOtherTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: FcstOtherTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstother table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstOtherTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstOtherTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstOtherTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstother"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstOtherRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstOtherRecord record = null; - - // create a List to hold FcstOther Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstother " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstOtherRecord - // and store its address in oneRecord - record = new FcstOtherRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstOtherRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstOtherRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstOtherRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstOtherRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstOtherRecord record = null; - - // create a List to hold FcstOther Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstother " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstOtherRecord - // and store its address in oneRecord - record = new FcstOtherRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstOtherRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstOtherRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstOtherRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstOtherRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstOtherRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstother VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstother " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstOtherRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstOtherRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstother SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstOtherRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstother " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstOtherRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstOtherRecord oldRecord, FcstOtherRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstother SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstOtherRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstOtherRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstOtherRecord oldRecord = (FcstOtherRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstOtherTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPrecipRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPrecipRecord.java deleted file mode 100644 index 705088b34d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPrecipRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: FcstPrecipRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstPrecip table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstPrecipRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstPrecipRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstPrecipRecord(FcstPrecipRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstPrecip record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FcstPrecipRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPrecipTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPrecipTable.java deleted file mode 100644 index 4551eeb50e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPrecipTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: FcstPrecipTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstprecip table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstPrecipTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstPrecipTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstPrecipTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstprecip"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstPrecipRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstPrecipRecord record = null; - - // create a List to hold FcstPrecip Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstprecip " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPrecipRecord - // and store its address in oneRecord - record = new FcstPrecipRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPrecipRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstPrecipRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPrecipRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstPrecipRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstPrecipRecord record = null; - - // create a List to hold FcstPrecip Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstprecip " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPrecipRecord - // and store its address in oneRecord - record = new FcstPrecipRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPrecipRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstPrecipRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPrecipRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstPrecipRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstPrecipRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstprecip VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstprecip " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPrecipRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPrecipRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstprecip SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstPrecipRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstprecip " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPrecipRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPrecipRecord oldRecord, FcstPrecipRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstprecip SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstPrecipRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstPrecipRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstPrecipRecord oldRecord = (FcstPrecipRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstPrecipTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtDetermRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtDetermRecord.java deleted file mode 100644 index 6eccf5c842..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtDetermRecord.java +++ /dev/null @@ -1,356 +0,0 @@ -// filename: FcstPtDetermRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstPtDeterm table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstPtDetermRecord extends DbRecord -{ - private String lid; - - private String snow_method; - - private String hydrol_method; - - private String reservoir_model; - - private String upstream_seg; - - private String hydraul_method; - - private String def_issue_crit; - - private short hours_qpf; - - private String frequpd_normal; - - private String frequpd_flood; - - private String frequpd_drought; - - private String fcst_horizon; - - private short hours_qtf; - - private short hours_qzf; - - private short num_elev_zones; - - private String consumptive_use; - - private String channel_loss; - - private String fcst_gen_method; - - private long impl_date; - - private long web_date; - - private String var_usage; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstPtDetermRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstPtDetermRecord(FcstPtDetermRecord origRecord) - { - setLid(origRecord.getLid()); - setSnow_method(origRecord.getSnow_method()); - setHydrol_method(origRecord.getHydrol_method()); - setReservoir_model(origRecord.getReservoir_model()); - setUpstream_seg(origRecord.getUpstream_seg()); - setHydraul_method(origRecord.getHydraul_method()); - setDef_issue_crit(origRecord.getDef_issue_crit()); - setHours_qpf(origRecord.getHours_qpf()); - setFrequpd_normal(origRecord.getFrequpd_normal()); - setFrequpd_flood(origRecord.getFrequpd_flood()); - setFrequpd_drought(origRecord.getFrequpd_drought()); - setFcst_horizon(origRecord.getFcst_horizon()); - setHours_qtf(origRecord.getHours_qtf()); - setHours_qzf(origRecord.getHours_qzf()); - setNum_elev_zones(origRecord.getNum_elev_zones()); - setConsumptive_use(origRecord.getConsumptive_use()); - setChannel_loss(origRecord.getChannel_loss()); - setFcst_gen_method(origRecord.getFcst_gen_method()); - setImpl_date(origRecord.getImpl_date()); - setWeb_date(origRecord.getWeb_date()); - setVar_usage(origRecord.getVar_usage()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstPtDeterm record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getSnow_method() - { - return snow_method; - } - - public void setSnow_method(String snow_method) - { - this.snow_method = snow_method ; - } - - public String getHydrol_method() - { - return hydrol_method; - } - - public void setHydrol_method(String hydrol_method) - { - this.hydrol_method = hydrol_method ; - } - - public String getReservoir_model() - { - return reservoir_model; - } - - public void setReservoir_model(String reservoir_model) - { - this.reservoir_model = reservoir_model ; - } - - public String getUpstream_seg() - { - return upstream_seg; - } - - public void setUpstream_seg(String upstream_seg) - { - this.upstream_seg = upstream_seg ; - } - - public String getHydraul_method() - { - return hydraul_method; - } - - public void setHydraul_method(String hydraul_method) - { - this.hydraul_method = hydraul_method ; - } - - public String getDef_issue_crit() - { - return def_issue_crit; - } - - public void setDef_issue_crit(String def_issue_crit) - { - this.def_issue_crit = def_issue_crit ; - } - - public short getHours_qpf() - { - return hours_qpf; - } - - public void setHours_qpf(short hours_qpf) - { - this.hours_qpf = hours_qpf ; - } - - public String getFrequpd_normal() - { - return frequpd_normal; - } - - public void setFrequpd_normal(String frequpd_normal) - { - this.frequpd_normal = frequpd_normal ; - } - - public String getFrequpd_flood() - { - return frequpd_flood; - } - - public void setFrequpd_flood(String frequpd_flood) - { - this.frequpd_flood = frequpd_flood ; - } - - public String getFrequpd_drought() - { - return frequpd_drought; - } - - public void setFrequpd_drought(String frequpd_drought) - { - this.frequpd_drought = frequpd_drought ; - } - - public String getFcst_horizon() - { - return fcst_horizon; - } - - public void setFcst_horizon(String fcst_horizon) - { - this.fcst_horizon = fcst_horizon ; - } - - public short getHours_qtf() - { - return hours_qtf; - } - - public void setHours_qtf(short hours_qtf) - { - this.hours_qtf = hours_qtf ; - } - - public short getHours_qzf() - { - return hours_qzf; - } - - public void setHours_qzf(short hours_qzf) - { - this.hours_qzf = hours_qzf ; - } - - public short getNum_elev_zones() - { - return num_elev_zones; - } - - public void setNum_elev_zones(short num_elev_zones) - { - this.num_elev_zones = num_elev_zones ; - } - - public String getConsumptive_use() - { - return consumptive_use; - } - - public void setConsumptive_use(String consumptive_use) - { - this.consumptive_use = consumptive_use ; - } - - public String getChannel_loss() - { - return channel_loss; - } - - public void setChannel_loss(String channel_loss) - { - this.channel_loss = channel_loss ; - } - - public String getFcst_gen_method() - { - return fcst_gen_method; - } - - public void setFcst_gen_method(String fcst_gen_method) - { - this.fcst_gen_method = fcst_gen_method ; - } - - public long getImpl_date() - { - return impl_date; - } - - public void setImpl_date(long impl_date) - { - this.impl_date = impl_date ; - } - - public long getWeb_date() - { - return web_date; - } - - public void setWeb_date(long web_date) - { - this.web_date = web_date ; - } - - public String getVar_usage() - { - return var_usage; - } - - public void setVar_usage(String var_usage) - { - this.var_usage = var_usage ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND snow_method = '" + snow_method + "'" - + " AND hydrol_method = '" + hydrol_method + "'" - + " AND reservoir_model = '" + reservoir_model + "'" - + " AND upstream_seg = '" + upstream_seg + "'" - + " AND hydraul_method = '" + hydraul_method + "'" - + " AND def_issue_crit = '" + def_issue_crit + "'" - + " AND hours_qpf = '" + hours_qpf + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getSnow_method() + " " + - getHydrol_method() + " " + - getReservoir_model() + " " + - getUpstream_seg() + " " + - getHydraul_method() + " " + - getDef_issue_crit() + " " + - getHours_qpf() + " " + - getFrequpd_normal() + " " + - getFrequpd_flood() + " " + - getFrequpd_drought() + " " + - getFcst_horizon() + " " + - getHours_qtf() + " " + - getHours_qzf() + " " + - getNum_elev_zones() + " " + - getConsumptive_use() + " " + - getChannel_loss() + " " + - getFcst_gen_method() + " " + - getDateStringFromLongTime(getImpl_date()) + " " + - getDateStringFromLongTime(getWeb_date()) + " " + - getVar_usage() + " " + - "" ; - return outString; - } // end toString() -} // end of FcstPtDetermRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtDetermTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtDetermTable.java deleted file mode 100644 index 3eff826c8f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtDetermTable.java +++ /dev/null @@ -1,346 +0,0 @@ -// filename: FcstPtDetermTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstptdeterm table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstPtDetermTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstPtDetermTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstPtDetermTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstptdeterm"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstPtDetermRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstPtDetermRecord record = null; - - // create a List to hold FcstPtDeterm Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptdeterm " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtDetermRecord - // and store its address in oneRecord - record = new FcstPtDetermRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtDetermRecord object - - record.setLid(getString(rs, 1)); - record.setSnow_method(getString(rs, 2)); - record.setHydrol_method(getString(rs, 3)); - record.setReservoir_model(getString(rs, 4)); - record.setUpstream_seg(getString(rs, 5)); - record.setHydraul_method(getString(rs, 6)); - record.setDef_issue_crit(getString(rs, 7)); - record.setHours_qpf(getShort(rs, 8)); - record.setFrequpd_normal(getString(rs, 9)); - record.setFrequpd_flood(getString(rs, 10)); - record.setFrequpd_drought(getString(rs, 11)); - record.setFcst_horizon(getString(rs, 12)); - record.setHours_qtf(getShort(rs, 13)); - record.setHours_qzf(getShort(rs, 14)); - record.setNum_elev_zones(getShort(rs, 15)); - record.setConsumptive_use(getString(rs, 16)); - record.setChannel_loss(getString(rs, 17)); - record.setFcst_gen_method(getString(rs, 18)); - record.setImpl_date(getDate(rs, 19)); - record.setWeb_date(getDate(rs, 20)); - record.setVar_usage(getString(rs, 21)); - - // add this FcstPtDetermRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtDetermRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstPtDetermRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstPtDetermRecord record = null; - - // create a List to hold FcstPtDeterm Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptdeterm " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtDetermRecord - // and store its address in oneRecord - record = new FcstPtDetermRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtDetermRecord object - - record.setLid(getString(rs, 1)); - record.setSnow_method(getString(rs, 2)); - record.setHydrol_method(getString(rs, 3)); - record.setReservoir_model(getString(rs, 4)); - record.setUpstream_seg(getString(rs, 5)); - record.setHydraul_method(getString(rs, 6)); - record.setDef_issue_crit(getString(rs, 7)); - record.setHours_qpf(getShort(rs, 8)); - record.setFrequpd_normal(getString(rs, 9)); - record.setFrequpd_flood(getString(rs, 10)); - record.setFrequpd_drought(getString(rs, 11)); - record.setFcst_horizon(getString(rs, 12)); - record.setHours_qtf(getShort(rs, 13)); - record.setHours_qzf(getShort(rs, 14)); - record.setNum_elev_zones(getShort(rs, 15)); - record.setConsumptive_use(getString(rs, 16)); - record.setChannel_loss(getString(rs, 17)); - record.setFcst_gen_method(getString(rs, 18)); - record.setImpl_date(getDate(rs, 19)); - record.setWeb_date(getDate(rs, 20)); - record.setVar_usage(getString(rs, 21)); - - // add this FcstPtDetermRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtDetermRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstPtDetermRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstPtDetermRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstptdeterm VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getSnow_method()); - setString(insertStatement, 3, record.getHydrol_method()); - setString(insertStatement, 4, record.getReservoir_model()); - setString(insertStatement, 5, record.getUpstream_seg()); - setString(insertStatement, 6, record.getHydraul_method()); - setString(insertStatement, 7, record.getDef_issue_crit()); - setShort(insertStatement, 8, record.getHours_qpf()); - setString(insertStatement, 9, record.getFrequpd_normal()); - setString(insertStatement, 10, record.getFrequpd_flood()); - setString(insertStatement, 11, record.getFrequpd_drought()); - setString(insertStatement, 12, record.getFcst_horizon()); - setShort(insertStatement, 13, record.getHours_qtf()); - setShort(insertStatement, 14, record.getHours_qzf()); - setShort(insertStatement, 15, record.getNum_elev_zones()); - setString(insertStatement, 16, record.getConsumptive_use()); - setString(insertStatement, 17, record.getChannel_loss()); - setString(insertStatement, 18, record.getFcst_gen_method()); - setDate(insertStatement, 19, record.getImpl_date()); - setDate(insertStatement, 20, record.getWeb_date()); - setString(insertStatement, 21, record.getVar_usage()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptdeterm " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtDetermRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtDetermRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptdeterm SET lid = ?, snow_method = ?, hydrol_method = ?, reservoir_model = ?, upstream_seg = ?, hydraul_method = ?, def_issue_crit = ?, hours_qpf = ?, frequpd_normal = ?, frequpd_flood = ?, frequpd_drought = ?, fcst_horizon = ?, hours_qtf = ?, hours_qzf = ?, num_elev_zones = ?, consumptive_use = ?, channel_loss = ?, fcst_gen_method = ?, impl_date = ?, web_date = ?, var_usage = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getSnow_method()); - setString(updateStatement, 3, record.getHydrol_method()); - setString(updateStatement, 4, record.getReservoir_model()); - setString(updateStatement, 5, record.getUpstream_seg()); - setString(updateStatement, 6, record.getHydraul_method()); - setString(updateStatement, 7, record.getDef_issue_crit()); - setShort(updateStatement, 8, record.getHours_qpf()); - setString(updateStatement, 9, record.getFrequpd_normal()); - setString(updateStatement, 10, record.getFrequpd_flood()); - setString(updateStatement, 11, record.getFrequpd_drought()); - setString(updateStatement, 12, record.getFcst_horizon()); - setShort(updateStatement, 13, record.getHours_qtf()); - setShort(updateStatement, 14, record.getHours_qzf()); - setShort(updateStatement, 15, record.getNum_elev_zones()); - setString(updateStatement, 16, record.getConsumptive_use()); - setString(updateStatement, 17, record.getChannel_loss()); - setString(updateStatement, 18, record.getFcst_gen_method()); - setDate(updateStatement, 19, record.getImpl_date()); - setDate(updateStatement, 20, record.getWeb_date()); - setString(updateStatement, 21, record.getVar_usage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstPtDetermRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptdeterm " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtDetermRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtDetermRecord oldRecord, FcstPtDetermRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptdeterm SET lid = ?, snow_method = ?, hydrol_method = ?, reservoir_model = ?, upstream_seg = ?, hydraul_method = ?, def_issue_crit = ?, hours_qpf = ?, frequpd_normal = ?, frequpd_flood = ?, frequpd_drought = ?, fcst_horizon = ?, hours_qtf = ?, hours_qzf = ?, num_elev_zones = ?, consumptive_use = ?, channel_loss = ?, fcst_gen_method = ?, impl_date = ?, web_date = ?, var_usage = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getSnow_method()); - setString(updateStatement, 3, newRecord.getHydrol_method()); - setString(updateStatement, 4, newRecord.getReservoir_model()); - setString(updateStatement, 5, newRecord.getUpstream_seg()); - setString(updateStatement, 6, newRecord.getHydraul_method()); - setString(updateStatement, 7, newRecord.getDef_issue_crit()); - setShort(updateStatement, 8, newRecord.getHours_qpf()); - setString(updateStatement, 9, newRecord.getFrequpd_normal()); - setString(updateStatement, 10, newRecord.getFrequpd_flood()); - setString(updateStatement, 11, newRecord.getFrequpd_drought()); - setString(updateStatement, 12, newRecord.getFcst_horizon()); - setShort(updateStatement, 13, newRecord.getHours_qtf()); - setShort(updateStatement, 14, newRecord.getHours_qzf()); - setShort(updateStatement, 15, newRecord.getNum_elev_zones()); - setString(updateStatement, 16, newRecord.getConsumptive_use()); - setString(updateStatement, 17, newRecord.getChannel_loss()); - setString(updateStatement, 18, newRecord.getFcst_gen_method()); - setDate(updateStatement, 19, newRecord.getImpl_date()); - setDate(updateStatement, 20, newRecord.getWeb_date()); - setString(updateStatement, 21, newRecord.getVar_usage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstPtDetermRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstPtDetermRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstPtDetermRecord oldRecord = (FcstPtDetermRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstPtDetermTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtESPRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtESPRecord.java deleted file mode 100644 index c767f7a326..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtESPRecord.java +++ /dev/null @@ -1,370 +0,0 @@ -// filename: FcstPtESPRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstPtESP table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstPtESPRecord extends DbRecord -{ - private String lid; - - private String snow_method; - - private String hydrol_method; - - private String reservoir_model; - - private String upstream_seg; - - private String hydraul_method; - - private String flowtype; - - private String fcsttype; - - private String frequpd_normal; - - private String frequpd_flood; - - private String frequpd_drought; - - private String fcst_horizon; - - private short nummonclim; - - private short numdayhyd; - - private short num_elev_zones; - - private String consumptive_use; - - private String channel_loss; - - private String post_processor; - - private long impl_date; - - private long external_date; - - private long web_date; - - private String var_usage; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstPtESPRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstPtESPRecord(FcstPtESPRecord origRecord) - { - setLid(origRecord.getLid()); - setSnow_method(origRecord.getSnow_method()); - setHydrol_method(origRecord.getHydrol_method()); - setReservoir_model(origRecord.getReservoir_model()); - setUpstream_seg(origRecord.getUpstream_seg()); - setHydraul_method(origRecord.getHydraul_method()); - setFlowtype(origRecord.getFlowtype()); - setFcsttype(origRecord.getFcsttype()); - setFrequpd_normal(origRecord.getFrequpd_normal()); - setFrequpd_flood(origRecord.getFrequpd_flood()); - setFrequpd_drought(origRecord.getFrequpd_drought()); - setFcst_horizon(origRecord.getFcst_horizon()); - setNummonclim(origRecord.getNummonclim()); - setNumdayhyd(origRecord.getNumdayhyd()); - setNum_elev_zones(origRecord.getNum_elev_zones()); - setConsumptive_use(origRecord.getConsumptive_use()); - setChannel_loss(origRecord.getChannel_loss()); - setPost_processor(origRecord.getPost_processor()); - setImpl_date(origRecord.getImpl_date()); - setExternal_date(origRecord.getExternal_date()); - setWeb_date(origRecord.getWeb_date()); - setVar_usage(origRecord.getVar_usage()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstPtESP record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getSnow_method() - { - return snow_method; - } - - public void setSnow_method(String snow_method) - { - this.snow_method = snow_method ; - } - - public String getHydrol_method() - { - return hydrol_method; - } - - public void setHydrol_method(String hydrol_method) - { - this.hydrol_method = hydrol_method ; - } - - public String getReservoir_model() - { - return reservoir_model; - } - - public void setReservoir_model(String reservoir_model) - { - this.reservoir_model = reservoir_model ; - } - - public String getUpstream_seg() - { - return upstream_seg; - } - - public void setUpstream_seg(String upstream_seg) - { - this.upstream_seg = upstream_seg ; - } - - public String getHydraul_method() - { - return hydraul_method; - } - - public void setHydraul_method(String hydraul_method) - { - this.hydraul_method = hydraul_method ; - } - - public String getFlowtype() - { - return flowtype; - } - - public void setFlowtype(String flowtype) - { - this.flowtype = flowtype ; - } - - public String getFcsttype() - { - return fcsttype; - } - - public void setFcsttype(String fcsttype) - { - this.fcsttype = fcsttype ; - } - - public String getFrequpd_normal() - { - return frequpd_normal; - } - - public void setFrequpd_normal(String frequpd_normal) - { - this.frequpd_normal = frequpd_normal ; - } - - public String getFrequpd_flood() - { - return frequpd_flood; - } - - public void setFrequpd_flood(String frequpd_flood) - { - this.frequpd_flood = frequpd_flood ; - } - - public String getFrequpd_drought() - { - return frequpd_drought; - } - - public void setFrequpd_drought(String frequpd_drought) - { - this.frequpd_drought = frequpd_drought ; - } - - public String getFcst_horizon() - { - return fcst_horizon; - } - - public void setFcst_horizon(String fcst_horizon) - { - this.fcst_horizon = fcst_horizon ; - } - - public short getNummonclim() - { - return nummonclim; - } - - public void setNummonclim(short nummonclim) - { - this.nummonclim = nummonclim ; - } - - public short getNumdayhyd() - { - return numdayhyd; - } - - public void setNumdayhyd(short numdayhyd) - { - this.numdayhyd = numdayhyd ; - } - - public short getNum_elev_zones() - { - return num_elev_zones; - } - - public void setNum_elev_zones(short num_elev_zones) - { - this.num_elev_zones = num_elev_zones ; - } - - public String getConsumptive_use() - { - return consumptive_use; - } - - public void setConsumptive_use(String consumptive_use) - { - this.consumptive_use = consumptive_use ; - } - - public String getChannel_loss() - { - return channel_loss; - } - - public void setChannel_loss(String channel_loss) - { - this.channel_loss = channel_loss ; - } - - public String getPost_processor() - { - return post_processor; - } - - public void setPost_processor(String post_processor) - { - this.post_processor = post_processor ; - } - - public long getImpl_date() - { - return impl_date; - } - - public void setImpl_date(long impl_date) - { - this.impl_date = impl_date ; - } - - public long getExternal_date() - { - return external_date; - } - - public void setExternal_date(long external_date) - { - this.external_date = external_date ; - } - - public long getWeb_date() - { - return web_date; - } - - public void setWeb_date(long web_date) - { - this.web_date = web_date ; - } - - public String getVar_usage() - { - return var_usage; - } - - public void setVar_usage(String var_usage) - { - this.var_usage = var_usage ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND snow_method = '" + snow_method + "'" - + " AND hydrol_method = '" + hydrol_method + "'" - + " AND reservoir_model = '" + reservoir_model + "'" - + " AND upstream_seg = '" + upstream_seg + "'" - + " AND hydraul_method = '" + hydraul_method + "'" - + " AND flowtype = '" + flowtype + "'" - + " AND fcsttype = '" + fcsttype + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getSnow_method() + " " + - getHydrol_method() + " " + - getReservoir_model() + " " + - getUpstream_seg() + " " + - getHydraul_method() + " " + - getFlowtype() + " " + - getFcsttype() + " " + - getFrequpd_normal() + " " + - getFrequpd_flood() + " " + - getFrequpd_drought() + " " + - getFcst_horizon() + " " + - getNummonclim() + " " + - getNumdayhyd() + " " + - getNum_elev_zones() + " " + - getConsumptive_use() + " " + - getChannel_loss() + " " + - getPost_processor() + " " + - getDateStringFromLongTime(getImpl_date()) + " " + - getDateStringFromLongTime(getExternal_date()) + " " + - getDateStringFromLongTime(getWeb_date()) + " " + - getVar_usage() + " " + - "" ; - return outString; - } // end toString() -} // end of FcstPtESPRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtESPTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtESPTable.java deleted file mode 100644 index a6d836bea1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtESPTable.java +++ /dev/null @@ -1,351 +0,0 @@ -// filename: FcstPtESPTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstptesp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstPtESPTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstPtESPTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstPtESPTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstptesp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstPtESPRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstPtESPRecord record = null; - - // create a List to hold FcstPtESP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptesp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtESPRecord - // and store its address in oneRecord - record = new FcstPtESPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtESPRecord object - - record.setLid(getString(rs, 1)); - record.setSnow_method(getString(rs, 2)); - record.setHydrol_method(getString(rs, 3)); - record.setReservoir_model(getString(rs, 4)); - record.setUpstream_seg(getString(rs, 5)); - record.setHydraul_method(getString(rs, 6)); - record.setFlowtype(getString(rs, 7)); - record.setFcsttype(getString(rs, 8)); - record.setFrequpd_normal(getString(rs, 9)); - record.setFrequpd_flood(getString(rs, 10)); - record.setFrequpd_drought(getString(rs, 11)); - record.setFcst_horizon(getString(rs, 12)); - record.setNummonclim(getShort(rs, 13)); - record.setNumdayhyd(getShort(rs, 14)); - record.setNum_elev_zones(getShort(rs, 15)); - record.setConsumptive_use(getString(rs, 16)); - record.setChannel_loss(getString(rs, 17)); - record.setPost_processor(getString(rs, 18)); - record.setImpl_date(getDate(rs, 19)); - record.setExternal_date(getDate(rs, 20)); - record.setWeb_date(getDate(rs, 21)); - record.setVar_usage(getString(rs, 22)); - - // add this FcstPtESPRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtESPRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstPtESPRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstPtESPRecord record = null; - - // create a List to hold FcstPtESP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptesp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtESPRecord - // and store its address in oneRecord - record = new FcstPtESPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtESPRecord object - - record.setLid(getString(rs, 1)); - record.setSnow_method(getString(rs, 2)); - record.setHydrol_method(getString(rs, 3)); - record.setReservoir_model(getString(rs, 4)); - record.setUpstream_seg(getString(rs, 5)); - record.setHydraul_method(getString(rs, 6)); - record.setFlowtype(getString(rs, 7)); - record.setFcsttype(getString(rs, 8)); - record.setFrequpd_normal(getString(rs, 9)); - record.setFrequpd_flood(getString(rs, 10)); - record.setFrequpd_drought(getString(rs, 11)); - record.setFcst_horizon(getString(rs, 12)); - record.setNummonclim(getShort(rs, 13)); - record.setNumdayhyd(getShort(rs, 14)); - record.setNum_elev_zones(getShort(rs, 15)); - record.setConsumptive_use(getString(rs, 16)); - record.setChannel_loss(getString(rs, 17)); - record.setPost_processor(getString(rs, 18)); - record.setImpl_date(getDate(rs, 19)); - record.setExternal_date(getDate(rs, 20)); - record.setWeb_date(getDate(rs, 21)); - record.setVar_usage(getString(rs, 22)); - - // add this FcstPtESPRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtESPRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstPtESPRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstPtESPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstptesp VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getSnow_method()); - setString(insertStatement, 3, record.getHydrol_method()); - setString(insertStatement, 4, record.getReservoir_model()); - setString(insertStatement, 5, record.getUpstream_seg()); - setString(insertStatement, 6, record.getHydraul_method()); - setString(insertStatement, 7, record.getFlowtype()); - setString(insertStatement, 8, record.getFcsttype()); - setString(insertStatement, 9, record.getFrequpd_normal()); - setString(insertStatement, 10, record.getFrequpd_flood()); - setString(insertStatement, 11, record.getFrequpd_drought()); - setString(insertStatement, 12, record.getFcst_horizon()); - setShort(insertStatement, 13, record.getNummonclim()); - setShort(insertStatement, 14, record.getNumdayhyd()); - setShort(insertStatement, 15, record.getNum_elev_zones()); - setString(insertStatement, 16, record.getConsumptive_use()); - setString(insertStatement, 17, record.getChannel_loss()); - setString(insertStatement, 18, record.getPost_processor()); - setDate(insertStatement, 19, record.getImpl_date()); - setDate(insertStatement, 20, record.getExternal_date()); - setDate(insertStatement, 21, record.getWeb_date()); - setString(insertStatement, 22, record.getVar_usage()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptesp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtESPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtESPRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptesp SET lid = ?, snow_method = ?, hydrol_method = ?, reservoir_model = ?, upstream_seg = ?, hydraul_method = ?, flowtype = ?, fcsttype = ?, frequpd_normal = ?, frequpd_flood = ?, frequpd_drought = ?, fcst_horizon = ?, nummonclim = ?, numdayhyd = ?, num_elev_zones = ?, consumptive_use = ?, channel_loss = ?, post_processor = ?, impl_date = ?, external_date = ?, web_date = ?, var_usage = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getSnow_method()); - setString(updateStatement, 3, record.getHydrol_method()); - setString(updateStatement, 4, record.getReservoir_model()); - setString(updateStatement, 5, record.getUpstream_seg()); - setString(updateStatement, 6, record.getHydraul_method()); - setString(updateStatement, 7, record.getFlowtype()); - setString(updateStatement, 8, record.getFcsttype()); - setString(updateStatement, 9, record.getFrequpd_normal()); - setString(updateStatement, 10, record.getFrequpd_flood()); - setString(updateStatement, 11, record.getFrequpd_drought()); - setString(updateStatement, 12, record.getFcst_horizon()); - setShort(updateStatement, 13, record.getNummonclim()); - setShort(updateStatement, 14, record.getNumdayhyd()); - setShort(updateStatement, 15, record.getNum_elev_zones()); - setString(updateStatement, 16, record.getConsumptive_use()); - setString(updateStatement, 17, record.getChannel_loss()); - setString(updateStatement, 18, record.getPost_processor()); - setDate(updateStatement, 19, record.getImpl_date()); - setDate(updateStatement, 20, record.getExternal_date()); - setDate(updateStatement, 21, record.getWeb_date()); - setString(updateStatement, 22, record.getVar_usage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstPtESPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptesp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtESPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtESPRecord oldRecord, FcstPtESPRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptesp SET lid = ?, snow_method = ?, hydrol_method = ?, reservoir_model = ?, upstream_seg = ?, hydraul_method = ?, flowtype = ?, fcsttype = ?, frequpd_normal = ?, frequpd_flood = ?, frequpd_drought = ?, fcst_horizon = ?, nummonclim = ?, numdayhyd = ?, num_elev_zones = ?, consumptive_use = ?, channel_loss = ?, post_processor = ?, impl_date = ?, external_date = ?, web_date = ?, var_usage = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getSnow_method()); - setString(updateStatement, 3, newRecord.getHydrol_method()); - setString(updateStatement, 4, newRecord.getReservoir_model()); - setString(updateStatement, 5, newRecord.getUpstream_seg()); - setString(updateStatement, 6, newRecord.getHydraul_method()); - setString(updateStatement, 7, newRecord.getFlowtype()); - setString(updateStatement, 8, newRecord.getFcsttype()); - setString(updateStatement, 9, newRecord.getFrequpd_normal()); - setString(updateStatement, 10, newRecord.getFrequpd_flood()); - setString(updateStatement, 11, newRecord.getFrequpd_drought()); - setString(updateStatement, 12, newRecord.getFcst_horizon()); - setShort(updateStatement, 13, newRecord.getNummonclim()); - setShort(updateStatement, 14, newRecord.getNumdayhyd()); - setShort(updateStatement, 15, newRecord.getNum_elev_zones()); - setString(updateStatement, 16, newRecord.getConsumptive_use()); - setString(updateStatement, 17, newRecord.getChannel_loss()); - setString(updateStatement, 18, newRecord.getPost_processor()); - setDate(updateStatement, 19, newRecord.getImpl_date()); - setDate(updateStatement, 20, newRecord.getExternal_date()); - setDate(updateStatement, 21, newRecord.getWeb_date()); - setString(updateStatement, 22, newRecord.getVar_usage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstPtESPRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstPtESPRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstPtESPRecord oldRecord = (FcstPtESPRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstPtESPTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtServiceRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtServiceRecord.java deleted file mode 100644 index ac0dcbecbb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtServiceRecord.java +++ /dev/null @@ -1,195 +0,0 @@ -// filename: FcstPtServiceRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstPtService table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstPtServiceRecord extends DbRecord -{ - private String lid; - - private double flood_thres; - - private short exceed_prob; - - private String service_type; - - private long anal_start_date; - - private long anal_end_date; - - private long impl_date; - - private long web_date; - - private String verif_resp_type; - - private double drainage_area; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstPtServiceRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstPtServiceRecord(FcstPtServiceRecord origRecord) - { - setLid(origRecord.getLid()); - setFlood_thres(origRecord.getFlood_thres()); - setExceed_prob(origRecord.getExceed_prob()); - setService_type(origRecord.getService_type()); - setAnal_start_date(origRecord.getAnal_start_date()); - setAnal_end_date(origRecord.getAnal_end_date()); - setImpl_date(origRecord.getImpl_date()); - setWeb_date(origRecord.getWeb_date()); - setVerif_resp_type(origRecord.getVerif_resp_type()); - setDrainage_area(origRecord.getDrainage_area()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstPtService record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getFlood_thres() - { - return flood_thres; - } - - public void setFlood_thres(double flood_thres) - { - this.flood_thres = flood_thres ; - } - - public short getExceed_prob() - { - return exceed_prob; - } - - public void setExceed_prob(short exceed_prob) - { - this.exceed_prob = exceed_prob ; - } - - public String getService_type() - { - return service_type; - } - - public void setService_type(String service_type) - { - this.service_type = service_type ; - } - - public long getAnal_start_date() - { - return anal_start_date; - } - - public void setAnal_start_date(long anal_start_date) - { - this.anal_start_date = anal_start_date ; - } - - public long getAnal_end_date() - { - return anal_end_date; - } - - public void setAnal_end_date(long anal_end_date) - { - this.anal_end_date = anal_end_date ; - } - - public long getImpl_date() - { - return impl_date; - } - - public void setImpl_date(long impl_date) - { - this.impl_date = impl_date ; - } - - public long getWeb_date() - { - return web_date; - } - - public void setWeb_date(long web_date) - { - this.web_date = web_date ; - } - - public String getVerif_resp_type() - { - return verif_resp_type; - } - - public void setVerif_resp_type(String verif_resp_type) - { - this.verif_resp_type = verif_resp_type ; - } - - public double getDrainage_area() - { - return drainage_area; - } - - public void setDrainage_area(double drainage_area) - { - this.drainage_area = drainage_area ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getFlood_thres() + " " + - getExceed_prob() + " " + - getService_type() + " " + - getDateStringFromLongTime(getAnal_start_date()) + " " + - getDateStringFromLongTime(getAnal_end_date()) + " " + - getDateStringFromLongTime(getImpl_date()) + " " + - getDateStringFromLongTime(getWeb_date()) + " " + - getVerif_resp_type() + " " + - getDrainage_area() + " " + - "" ; - return outString; - } // end toString() -} // end of FcstPtServiceRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtServiceTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtServiceTable.java deleted file mode 100644 index 4d3b359cb3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtServiceTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: FcstPtServiceTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstptservice table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstPtServiceTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstPtServiceTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstPtServiceTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstptservice"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstPtServiceRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstPtServiceRecord record = null; - - // create a List to hold FcstPtService Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptservice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtServiceRecord - // and store its address in oneRecord - record = new FcstPtServiceRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtServiceRecord object - - record.setLid(getString(rs, 1)); - record.setFlood_thres(getDouble(rs, 2)); - record.setExceed_prob(getShort(rs, 3)); - record.setService_type(getString(rs, 4)); - record.setAnal_start_date(getDate(rs, 5)); - record.setAnal_end_date(getDate(rs, 6)); - record.setImpl_date(getDate(rs, 7)); - record.setWeb_date(getDate(rs, 8)); - record.setVerif_resp_type(getString(rs, 9)); - record.setDrainage_area(getDouble(rs, 10)); - - // add this FcstPtServiceRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtServiceRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstPtServiceRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstPtServiceRecord record = null; - - // create a List to hold FcstPtService Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptservice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtServiceRecord - // and store its address in oneRecord - record = new FcstPtServiceRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtServiceRecord object - - record.setLid(getString(rs, 1)); - record.setFlood_thres(getDouble(rs, 2)); - record.setExceed_prob(getShort(rs, 3)); - record.setService_type(getString(rs, 4)); - record.setAnal_start_date(getDate(rs, 5)); - record.setAnal_end_date(getDate(rs, 6)); - record.setImpl_date(getDate(rs, 7)); - record.setWeb_date(getDate(rs, 8)); - record.setVerif_resp_type(getString(rs, 9)); - record.setDrainage_area(getDouble(rs, 10)); - - // add this FcstPtServiceRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtServiceRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstPtServiceRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstPtServiceRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstptservice VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDouble(insertStatement, 2, record.getFlood_thres()); - setShort(insertStatement, 3, record.getExceed_prob()); - setString(insertStatement, 4, record.getService_type()); - setDate(insertStatement, 5, record.getAnal_start_date()); - setDate(insertStatement, 6, record.getAnal_end_date()); - setDate(insertStatement, 7, record.getImpl_date()); - setDate(insertStatement, 8, record.getWeb_date()); - setString(insertStatement, 9, record.getVerif_resp_type()); - setDouble(insertStatement, 10, record.getDrainage_area()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptservice " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtServiceRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtServiceRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptservice SET lid = ?, flood_thres = ?, exceed_prob = ?, service_type = ?, anal_start_date = ?, anal_end_date = ?, impl_date = ?, web_date = ?, verif_resp_type = ?, drainage_area = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDouble(updateStatement, 2, record.getFlood_thres()); - setShort(updateStatement, 3, record.getExceed_prob()); - setString(updateStatement, 4, record.getService_type()); - setDate(updateStatement, 5, record.getAnal_start_date()); - setDate(updateStatement, 6, record.getAnal_end_date()); - setDate(updateStatement, 7, record.getImpl_date()); - setDate(updateStatement, 8, record.getWeb_date()); - setString(updateStatement, 9, record.getVerif_resp_type()); - setDouble(updateStatement, 10, record.getDrainage_area()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstPtServiceRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptservice " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtServiceRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtServiceRecord oldRecord, FcstPtServiceRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptservice SET lid = ?, flood_thres = ?, exceed_prob = ?, service_type = ?, anal_start_date = ?, anal_end_date = ?, impl_date = ?, web_date = ?, verif_resp_type = ?, drainage_area = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDouble(updateStatement, 2, newRecord.getFlood_thres()); - setShort(updateStatement, 3, newRecord.getExceed_prob()); - setString(updateStatement, 4, newRecord.getService_type()); - setDate(updateStatement, 5, newRecord.getAnal_start_date()); - setDate(updateStatement, 6, newRecord.getAnal_end_date()); - setDate(updateStatement, 7, newRecord.getImpl_date()); - setDate(updateStatement, 8, newRecord.getWeb_date()); - setString(updateStatement, 9, newRecord.getVerif_resp_type()); - setDouble(updateStatement, 10, newRecord.getDrainage_area()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstPtServiceRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstPtServiceRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstPtServiceRecord oldRecord = (FcstPtServiceRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstPtServiceTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtWatSupRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtWatSupRecord.java deleted file mode 100644 index 7873ba39cf..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtWatSupRecord.java +++ /dev/null @@ -1,200 +0,0 @@ -// filename: FcstPtWatSupRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstPtWatSup table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstPtWatSupRecord extends DbRecord -{ - private String lid; - - private String watsup_method; - - private String watsup_coord_agency; - - private String frequpd_normal; - - private String period_req; - - private String watsup_crit; - - private String watsup_resp_agency; - - private String customer_desc; - - private long impl_date; - - private long web_date; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstPtWatSupRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstPtWatSupRecord(FcstPtWatSupRecord origRecord) - { - setLid(origRecord.getLid()); - setWatsup_method(origRecord.getWatsup_method()); - setWatsup_coord_agency(origRecord.getWatsup_coord_agency()); - setFrequpd_normal(origRecord.getFrequpd_normal()); - setPeriod_req(origRecord.getPeriod_req()); - setWatsup_crit(origRecord.getWatsup_crit()); - setWatsup_resp_agency(origRecord.getWatsup_resp_agency()); - setCustomer_desc(origRecord.getCustomer_desc()); - setImpl_date(origRecord.getImpl_date()); - setWeb_date(origRecord.getWeb_date()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstPtWatSup record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getWatsup_method() - { - return watsup_method; - } - - public void setWatsup_method(String watsup_method) - { - this.watsup_method = watsup_method ; - } - - public String getWatsup_coord_agency() - { - return watsup_coord_agency; - } - - public void setWatsup_coord_agency(String watsup_coord_agency) - { - this.watsup_coord_agency = watsup_coord_agency ; - } - - public String getFrequpd_normal() - { - return frequpd_normal; - } - - public void setFrequpd_normal(String frequpd_normal) - { - this.frequpd_normal = frequpd_normal ; - } - - public String getPeriod_req() - { - return period_req; - } - - public void setPeriod_req(String period_req) - { - this.period_req = period_req ; - } - - public String getWatsup_crit() - { - return watsup_crit; - } - - public void setWatsup_crit(String watsup_crit) - { - this.watsup_crit = watsup_crit ; - } - - public String getWatsup_resp_agency() - { - return watsup_resp_agency; - } - - public void setWatsup_resp_agency(String watsup_resp_agency) - { - this.watsup_resp_agency = watsup_resp_agency ; - } - - public String getCustomer_desc() - { - return customer_desc; - } - - public void setCustomer_desc(String customer_desc) - { - this.customer_desc = customer_desc ; - } - - public long getImpl_date() - { - return impl_date; - } - - public void setImpl_date(long impl_date) - { - this.impl_date = impl_date ; - } - - public long getWeb_date() - { - return web_date; - } - - public void setWeb_date(long web_date) - { - this.web_date = web_date ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND watsup_method = '" + watsup_method + "'" - + " AND watsup_coord_agency = '" + watsup_coord_agency + "'" - + " AND frequpd_normal = '" + frequpd_normal + "'" - + " AND period_req = '" + period_req + "'" - + " AND watsup_crit = '" + watsup_crit + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getWatsup_method() + " " + - getWatsup_coord_agency() + " " + - getFrequpd_normal() + " " + - getPeriod_req() + " " + - getWatsup_crit() + " " + - getWatsup_resp_agency() + " " + - getCustomer_desc() + " " + - getDateStringFromLongTime(getImpl_date()) + " " + - getDateStringFromLongTime(getWeb_date()) + " " + - "" ; - return outString; - } // end toString() -} // end of FcstPtWatSupRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtWatSupTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtWatSupTable.java deleted file mode 100644 index b40343b0c7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstPtWatSupTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: FcstPtWatSupTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcstptwatsup table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstPtWatSupTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstPtWatSupTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstPtWatSupTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcstptwatsup"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstPtWatSupRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstPtWatSupRecord record = null; - - // create a List to hold FcstPtWatSup Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptwatsup " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtWatSupRecord - // and store its address in oneRecord - record = new FcstPtWatSupRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtWatSupRecord object - - record.setLid(getString(rs, 1)); - record.setWatsup_method(getString(rs, 2)); - record.setWatsup_coord_agency(getString(rs, 3)); - record.setFrequpd_normal(getString(rs, 4)); - record.setPeriod_req(getString(rs, 5)); - record.setWatsup_crit(getString(rs, 6)); - record.setWatsup_resp_agency(getString(rs, 7)); - record.setCustomer_desc(getString(rs, 8)); - record.setImpl_date(getDate(rs, 9)); - record.setWeb_date(getDate(rs, 10)); - - // add this FcstPtWatSupRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtWatSupRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstPtWatSupRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstPtWatSupRecord record = null; - - // create a List to hold FcstPtWatSup Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcstptwatsup " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstPtWatSupRecord - // and store its address in oneRecord - record = new FcstPtWatSupRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstPtWatSupRecord object - - record.setLid(getString(rs, 1)); - record.setWatsup_method(getString(rs, 2)); - record.setWatsup_coord_agency(getString(rs, 3)); - record.setFrequpd_normal(getString(rs, 4)); - record.setPeriod_req(getString(rs, 5)); - record.setWatsup_crit(getString(rs, 6)); - record.setWatsup_resp_agency(getString(rs, 7)); - record.setCustomer_desc(getString(rs, 8)); - record.setImpl_date(getDate(rs, 9)); - record.setWeb_date(getDate(rs, 10)); - - // add this FcstPtWatSupRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstPtWatSupRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstPtWatSupRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstPtWatSupRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcstptwatsup VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getWatsup_method()); - setString(insertStatement, 3, record.getWatsup_coord_agency()); - setString(insertStatement, 4, record.getFrequpd_normal()); - setString(insertStatement, 5, record.getPeriod_req()); - setString(insertStatement, 6, record.getWatsup_crit()); - setString(insertStatement, 7, record.getWatsup_resp_agency()); - setString(insertStatement, 8, record.getCustomer_desc()); - setDate(insertStatement, 9, record.getImpl_date()); - setDate(insertStatement, 10, record.getWeb_date()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptwatsup " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtWatSupRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtWatSupRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptwatsup SET lid = ?, watsup_method = ?, watsup_coord_agency = ?, frequpd_normal = ?, period_req = ?, watsup_crit = ?, watsup_resp_agency = ?, customer_desc = ?, impl_date = ?, web_date = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getWatsup_method()); - setString(updateStatement, 3, record.getWatsup_coord_agency()); - setString(updateStatement, 4, record.getFrequpd_normal()); - setString(updateStatement, 5, record.getPeriod_req()); - setString(updateStatement, 6, record.getWatsup_crit()); - setString(updateStatement, 7, record.getWatsup_resp_agency()); - setString(updateStatement, 8, record.getCustomer_desc()); - setDate(updateStatement, 9, record.getImpl_date()); - setDate(updateStatement, 10, record.getWeb_date()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstPtWatSupRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcstptwatsup " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstPtWatSupRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstPtWatSupRecord oldRecord, FcstPtWatSupRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcstptwatsup SET lid = ?, watsup_method = ?, watsup_coord_agency = ?, frequpd_normal = ?, period_req = ?, watsup_crit = ?, watsup_resp_agency = ?, customer_desc = ?, impl_date = ?, web_date = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getWatsup_method()); - setString(updateStatement, 3, newRecord.getWatsup_coord_agency()); - setString(updateStatement, 4, newRecord.getFrequpd_normal()); - setString(updateStatement, 5, newRecord.getPeriod_req()); - setString(updateStatement, 6, newRecord.getWatsup_crit()); - setString(updateStatement, 7, newRecord.getWatsup_resp_agency()); - setString(updateStatement, 8, newRecord.getCustomer_desc()); - setDate(updateStatement, 9, newRecord.getImpl_date()); - setDate(updateStatement, 10, newRecord.getWeb_date()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstPtWatSupRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstPtWatSupRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstPtWatSupRecord oldRecord = (FcstPtWatSupRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstPtWatSupTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTemperatureRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTemperatureRecord.java deleted file mode 100644 index be072af00c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTemperatureRecord.java +++ /dev/null @@ -1,272 +0,0 @@ -// filename: FcstTemperatureRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstTemperature table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstTemperatureRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstTemperatureRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstTemperatureRecord(FcstTemperatureRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstTemperature record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FcstTemperatureRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTemperatureTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTemperatureTable.java deleted file mode 100644 index ea41ab15ab..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTemperatureTable.java +++ /dev/null @@ -1,316 +0,0 @@ -// filename: FcstTemperatureTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcsttemperature table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstTemperatureTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstTemperatureTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstTemperatureTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcsttemperature"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstTemperatureRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstTemperatureRecord record = null; - - // create a List to hold FcstTemperature Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcsttemperature " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstTemperatureRecord - // and store its address in oneRecord - record = new FcstTemperatureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstTemperatureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstTemperatureRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstTemperatureRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstTemperatureRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstTemperatureRecord record = null; - - // create a List to hold FcstTemperature Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcsttemperature " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstTemperatureRecord - // and store its address in oneRecord - record = new FcstTemperatureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstTemperatureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - record.setShef_qual_code(getString(rs, 10)); - record.setQuality_code(getInt(rs, 11)); - record.setRevision(getShort(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setPostingtime(getTimeStamp(rs, 15)); - - // add this FcstTemperatureRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstTemperatureRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstTemperatureRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstTemperatureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcsttemperature VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - setString(insertStatement, 10, record.getShef_qual_code()); - setInt(insertStatement, 11, record.getQuality_code()); - setShort(insertStatement, 12, record.getRevision()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setTimeStamp(insertStatement, 15, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcsttemperature " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstTemperatureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstTemperatureRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcsttemperature SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - setString(updateStatement, 10, record.getShef_qual_code()); - setInt(updateStatement, 11, record.getQuality_code()); - setShort(updateStatement, 12, record.getRevision()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setTimeStamp(updateStatement, 15, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstTemperatureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcsttemperature " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstTemperatureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstTemperatureRecord oldRecord, FcstTemperatureRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcsttemperature SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - setString(updateStatement, 10, newRecord.getShef_qual_code()); - setInt(updateStatement, 11, newRecord.getQuality_code()); - setShort(updateStatement, 12, newRecord.getRevision()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setTimeStamp(updateStatement, 15, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstTemperatureRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstTemperatureRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstTemperatureRecord oldRecord = (FcstTemperatureRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstTemperatureTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTypeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTypeRecord.java deleted file mode 100644 index edb518313a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTypeRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: FcstTypeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FcstType table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FcstTypeRecord extends DbRecord -{ - private String fcsttype; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FcstTypeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FcstTypeRecord(FcstTypeRecord origRecord) - { - setFcsttype(origRecord.getFcsttype()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FcstType record - - //----------------------------------------------------------------- - public String getFcsttype() - { - return fcsttype; - } - - public void setFcsttype(String fcsttype) - { - this.fcsttype = fcsttype ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE fcsttype = '" + fcsttype + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getFcsttype() + " " + - "" ; - return outString; - } // end toString() -} // end of FcstTypeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTypeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTypeTable.java deleted file mode 100644 index c037159184..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FcstTypeTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: FcstTypeTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fcsttype table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FcstTypeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FcstTypeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FcstTypeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fcsttype"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FcstTypeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FcstTypeRecord record = null; - - // create a List to hold FcstType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcsttype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstTypeRecord - // and store its address in oneRecord - record = new FcstTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstTypeRecord object - - record.setFcsttype(getString(rs, 1)); - - // add this FcstTypeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FcstTypeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FcstTypeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FcstTypeRecord record = null; - - // create a List to hold FcstType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fcsttype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FcstTypeRecord - // and store its address in oneRecord - record = new FcstTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FcstTypeRecord object - - record.setFcsttype(getString(rs, 1)); - - // add this FcstTypeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FcstTypeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FcstTypeRecord object and.. -//----------------------------------------------------------------- - public int insert(FcstTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fcsttype VALUES (? )"); - - setString(insertStatement, 1, record.getFcsttype()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcsttype " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstTypeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcsttype SET fcsttype = ? " + where ); - - setString(updateStatement, 1, record.getFcsttype()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FcstTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fcsttype " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FcstTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FcstTypeRecord oldRecord, FcstTypeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fcsttype SET fcsttype = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getFcsttype()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FcstTypeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FcstTypeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FcstTypeRecord oldRecord = (FcstTypeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FcstTypeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FishCountRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FishCountRecord.java deleted file mode 100644 index d407495e34..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FishCountRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: FishCountRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FishCount table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FishCountRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FishCountRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FishCountRecord(FishCountRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FishCount record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FishCountRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FishCountTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FishCountTable.java deleted file mode 100644 index 2f8777b60c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FishCountTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: FishCountTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fishcount table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FishCountTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FishCountTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FishCountTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fishcount"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FishCountRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FishCountRecord record = null; - - // create a List to hold FishCount Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fishcount " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FishCountRecord - // and store its address in oneRecord - record = new FishCountRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FishCountRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this FishCountRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FishCountRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FishCountRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FishCountRecord record = null; - - // create a List to hold FishCount Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fishcount " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FishCountRecord - // and store its address in oneRecord - record = new FishCountRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FishCountRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this FishCountRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FishCountRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FishCountRecord object and.. -//----------------------------------------------------------------- - public int insert(FishCountRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fishcount VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fishcount " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FishCountRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FishCountRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fishcount SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FishCountRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fishcount " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FishCountRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FishCountRecord oldRecord, FishCountRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fishcount SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FishCountRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FishCountRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FishCountRecord oldRecord = (FishCountRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FishCountTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodRecord.java deleted file mode 100644 index 256c362699..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodRecord.java +++ /dev/null @@ -1,112 +0,0 @@ -// filename: FloodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Flood table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FloodRecord extends DbRecord -{ - private String lid; - - private double stage; - - private String damage; - - private String dispstmt; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FloodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FloodRecord(FloodRecord origRecord) - { - setLid(origRecord.getLid()); - setStage(origRecord.getStage()); - setDamage(origRecord.getDamage()); - setDispstmt(origRecord.getDispstmt()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Flood record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getStage() - { - return stage; - } - - public void setStage(double stage) - { - this.stage = stage ; - } - - public String getDamage() - { - return damage; - } - - public void setDamage(String damage) - { - this.damage = damage ; - } - - public String getDispstmt() - { - return dispstmt; - } - - public void setDispstmt(String dispstmt) - { - this.dispstmt = dispstmt ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND stage = '" + stage + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getStage() + " " + - getDamage() + " " + - getDispstmt() + " " + - "" ; - return outString; - } // end toString() -} // end of FloodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTable.java deleted file mode 100644 index dd17c0e339..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: FloodTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// flood table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FloodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FloodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FloodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("flood"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FloodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FloodRecord record = null; - - // create a List to hold Flood Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM flood " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodRecord - // and store its address in oneRecord - record = new FloodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodRecord object - - record.setLid(getString(rs, 1)); - record.setStage(getDouble(rs, 2)); - record.setDamage(getString(rs, 3)); - record.setDispstmt(getString(rs, 4)); - - // add this FloodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FloodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FloodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FloodRecord record = null; - - // create a List to hold Flood Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM flood " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodRecord - // and store its address in oneRecord - record = new FloodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodRecord object - - record.setLid(getString(rs, 1)); - record.setStage(getDouble(rs, 2)); - record.setDamage(getString(rs, 3)); - record.setDispstmt(getString(rs, 4)); - - // add this FloodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FloodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FloodRecord object and.. -//----------------------------------------------------------------- - public int insert(FloodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO flood VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDouble(insertStatement, 2, record.getStage()); - setString(insertStatement, 3, record.getDamage()); - setString(insertStatement, 4, record.getDispstmt()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM flood " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE flood SET lid = ?, stage = ?, damage = ?, dispstmt = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDouble(updateStatement, 2, record.getStage()); - setString(updateStatement, 3, record.getDamage()); - setString(updateStatement, 4, record.getDispstmt()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FloodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM flood " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodRecord oldRecord, FloodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE flood SET lid = ?, stage = ?, damage = ?, dispstmt = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDouble(updateStatement, 2, newRecord.getStage()); - setString(updateStatement, 3, newRecord.getDamage()); - setString(updateStatement, 4, newRecord.getDispstmt()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FloodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FloodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FloodRecord oldRecord = (FloodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FloodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTsRecord.java deleted file mode 100644 index ca90e32e04..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTsRecord.java +++ /dev/null @@ -1,112 +0,0 @@ -// filename: FloodTsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FloodTs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FloodTsRecord extends DbRecord -{ - private String lid; - - private long obstime; - - private int flood_event_id; - - private double value; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FloodTsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FloodTsRecord(FloodTsRecord origRecord) - { - setLid(origRecord.getLid()); - setObstime(origRecord.getObstime()); - setFlood_event_id(origRecord.getFlood_event_id()); - setValue(origRecord.getValue()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FloodTs record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public int getFlood_event_id() - { - return flood_event_id; - } - - public void setFlood_event_id(int flood_event_id) - { - this.flood_event_id = flood_event_id ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getFlood_event_id() + " " + - getValue() + " " + - "" ; - return outString; - } // end toString() -} // end of FloodTsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTsTable.java deleted file mode 100644 index b504049680..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodTsTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: FloodTsTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// floodts table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FloodTsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FloodTsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FloodTsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("floodts"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FloodTsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FloodTsRecord record = null; - - // create a List to hold FloodTs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM floodts " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodTsRecord - // and store its address in oneRecord - record = new FloodTsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodTsRecord object - - record.setLid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setFlood_event_id(getInt(rs, 3)); - record.setValue(getDouble(rs, 4)); - - // add this FloodTsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FloodTsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FloodTsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FloodTsRecord record = null; - - // create a List to hold FloodTs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM floodts " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodTsRecord - // and store its address in oneRecord - record = new FloodTsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodTsRecord object - - record.setLid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setFlood_event_id(getInt(rs, 3)); - record.setValue(getDouble(rs, 4)); - - // add this FloodTsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FloodTsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FloodTsRecord object and.. -//----------------------------------------------------------------- - public int insert(FloodTsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO floodts VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setInt(insertStatement, 3, record.getFlood_event_id()); - setDouble(insertStatement, 4, record.getValue()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM floodts " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodTsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodTsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE floodts SET lid = ?, obstime = ?, flood_event_id = ?, value = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setInt(updateStatement, 3, record.getFlood_event_id()); - setDouble(updateStatement, 4, record.getValue()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FloodTsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM floodts " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodTsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodTsRecord oldRecord, FloodTsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE floodts SET lid = ?, obstime = ?, flood_event_id = ?, value = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setInt(updateStatement, 3, newRecord.getFlood_event_id()); - setDouble(updateStatement, 4, newRecord.getValue()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FloodTsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FloodTsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FloodTsRecord oldRecord = (FloodTsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FloodTsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodcatRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodcatRecord.java deleted file mode 100644 index b380588c55..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodcatRecord.java +++ /dev/null @@ -1,153 +0,0 @@ -// filename: FloodcatRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Floodcat table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FloodcatRecord extends DbRecord -{ - private String lid; - - private double minor_stage; - - private double moderate_stage; - - private double major_stage; - - private double minor_flow; - - private double moderate_flow; - - private double major_flow; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FloodcatRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FloodcatRecord(FloodcatRecord origRecord) - { - setLid(origRecord.getLid()); - setMinor_stage(origRecord.getMinor_stage()); - setModerate_stage(origRecord.getModerate_stage()); - setMajor_stage(origRecord.getMajor_stage()); - setMinor_flow(origRecord.getMinor_flow()); - setModerate_flow(origRecord.getModerate_flow()); - setMajor_flow(origRecord.getMajor_flow()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Floodcat record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getMinor_stage() - { - return minor_stage; - } - - public void setMinor_stage(double minor_stage) - { - this.minor_stage = minor_stage ; - } - - public double getModerate_stage() - { - return moderate_stage; - } - - public void setModerate_stage(double moderate_stage) - { - this.moderate_stage = moderate_stage ; - } - - public double getMajor_stage() - { - return major_stage; - } - - public void setMajor_stage(double major_stage) - { - this.major_stage = major_stage ; - } - - public double getMinor_flow() - { - return minor_flow; - } - - public void setMinor_flow(double minor_flow) - { - this.minor_flow = minor_flow ; - } - - public double getModerate_flow() - { - return moderate_flow; - } - - public void setModerate_flow(double moderate_flow) - { - this.moderate_flow = moderate_flow ; - } - - public double getMajor_flow() - { - return major_flow; - } - - public void setMajor_flow(double major_flow) - { - this.major_flow = major_flow ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getMinor_stage() + " " + - getModerate_stage() + " " + - getMajor_stage() + " " + - getMinor_flow() + " " + - getModerate_flow() + " " + - getMajor_flow() + " " + - "" ; - return outString; - } // end toString() -} // end of FloodcatRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodcatTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodcatTable.java deleted file mode 100644 index 7f8d0cb417..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodcatTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: FloodcatTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// floodcat table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FloodcatTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FloodcatTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FloodcatTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("floodcat"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FloodcatRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FloodcatRecord record = null; - - // create a List to hold Floodcat Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM floodcat " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodcatRecord - // and store its address in oneRecord - record = new FloodcatRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodcatRecord object - - record.setLid(getString(rs, 1)); - record.setMinor_stage(getDouble(rs, 2)); - record.setModerate_stage(getDouble(rs, 3)); - record.setMajor_stage(getDouble(rs, 4)); - record.setMinor_flow(getDouble(rs, 5)); - record.setModerate_flow(getDouble(rs, 6)); - record.setMajor_flow(getDouble(rs, 7)); - - // add this FloodcatRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FloodcatRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FloodcatRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FloodcatRecord record = null; - - // create a List to hold Floodcat Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM floodcat " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodcatRecord - // and store its address in oneRecord - record = new FloodcatRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodcatRecord object - - record.setLid(getString(rs, 1)); - record.setMinor_stage(getDouble(rs, 2)); - record.setModerate_stage(getDouble(rs, 3)); - record.setMajor_stage(getDouble(rs, 4)); - record.setMinor_flow(getDouble(rs, 5)); - record.setModerate_flow(getDouble(rs, 6)); - record.setMajor_flow(getDouble(rs, 7)); - - // add this FloodcatRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FloodcatRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FloodcatRecord object and.. -//----------------------------------------------------------------- - public int insert(FloodcatRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO floodcat VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDouble(insertStatement, 2, record.getMinor_stage()); - setDouble(insertStatement, 3, record.getModerate_stage()); - setDouble(insertStatement, 4, record.getMajor_stage()); - setDouble(insertStatement, 5, record.getMinor_flow()); - setDouble(insertStatement, 6, record.getModerate_flow()); - setDouble(insertStatement, 7, record.getMajor_flow()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM floodcat " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodcatRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodcatRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE floodcat SET lid = ?, minor_stage = ?, moderate_stage = ?, major_stage = ?, minor_flow = ?, moderate_flow = ?, major_flow = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDouble(updateStatement, 2, record.getMinor_stage()); - setDouble(updateStatement, 3, record.getModerate_stage()); - setDouble(updateStatement, 4, record.getMajor_stage()); - setDouble(updateStatement, 5, record.getMinor_flow()); - setDouble(updateStatement, 6, record.getModerate_flow()); - setDouble(updateStatement, 7, record.getMajor_flow()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FloodcatRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM floodcat " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodcatRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodcatRecord oldRecord, FloodcatRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE floodcat SET lid = ?, minor_stage = ?, moderate_stage = ?, major_stage = ?, minor_flow = ?, moderate_flow = ?, major_flow = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDouble(updateStatement, 2, newRecord.getMinor_stage()); - setDouble(updateStatement, 3, newRecord.getModerate_stage()); - setDouble(updateStatement, 4, newRecord.getMajor_stage()); - setDouble(updateStatement, 5, newRecord.getMinor_flow()); - setDouble(updateStatement, 6, newRecord.getModerate_flow()); - setDouble(updateStatement, 7, newRecord.getMajor_flow()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FloodcatRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FloodcatRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FloodcatRecord oldRecord = (FloodcatRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FloodcatTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodstmtRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodstmtRecord.java deleted file mode 100644 index 5cd33916a1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodstmtRecord.java +++ /dev/null @@ -1,157 +0,0 @@ -// filename: FloodstmtRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Floodstmt table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FloodstmtRecord extends DbRecord -{ - private String lid; - - private double impact_value; - - private String statement; - - private String rf; - - private String datestart; - - private String dateend; - - private String impact_pe; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FloodstmtRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FloodstmtRecord(FloodstmtRecord origRecord) - { - setLid(origRecord.getLid()); - setImpact_value(origRecord.getImpact_value()); - setStatement(origRecord.getStatement()); - setRf(origRecord.getRf()); - setDatestart(origRecord.getDatestart()); - setDateend(origRecord.getDateend()); - setImpact_pe(origRecord.getImpact_pe()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Floodstmt record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getImpact_value() - { - return impact_value; - } - - public void setImpact_value(double impact_value) - { - this.impact_value = impact_value ; - } - - public String getStatement() - { - return statement; - } - - public void setStatement(String statement) - { - this.statement = statement ; - } - - public String getRf() - { - return rf; - } - - public void setRf(String rf) - { - this.rf = rf ; - } - - public String getDatestart() - { - return datestart; - } - - public void setDatestart(String datestart) - { - this.datestart = datestart ; - } - - public String getDateend() - { - return dateend; - } - - public void setDateend(String dateend) - { - this.dateend = dateend ; - } - - public String getImpact_pe() - { - return impact_pe; - } - - public void setImpact_pe(String impact_pe) - { - this.impact_pe = impact_pe ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND impact_value = '" + impact_value + "'" - + " AND rf = '" + rf + "'" - + " AND datestart = '" + datestart + "'" - + " AND dateend = '" + dateend + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getImpact_value() + " " + - getStatement() + " " + - getRf() + " " + - getDatestart() + " " + - getDateend() + " " + - getImpact_pe() + " " + - "" ; - return outString; - } // end toString() -} // end of FloodstmtRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodstmtTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodstmtTable.java deleted file mode 100644 index 20f1be914a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FloodstmtTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: FloodstmtTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// floodstmt table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FloodstmtTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FloodstmtTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FloodstmtTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("floodstmt"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FloodstmtRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FloodstmtRecord record = null; - - // create a List to hold Floodstmt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM floodstmt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodstmtRecord - // and store its address in oneRecord - record = new FloodstmtRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodstmtRecord object - - record.setLid(getString(rs, 1)); - record.setImpact_value(getDouble(rs, 2)); - record.setStatement(getString(rs, 3)); - record.setRf(getString(rs, 4)); - record.setDatestart(getString(rs, 5)); - record.setDateend(getString(rs, 6)); - record.setImpact_pe(getString(rs, 7)); - - // add this FloodstmtRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FloodstmtRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FloodstmtRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FloodstmtRecord record = null; - - // create a List to hold Floodstmt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM floodstmt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FloodstmtRecord - // and store its address in oneRecord - record = new FloodstmtRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FloodstmtRecord object - - record.setLid(getString(rs, 1)); - record.setImpact_value(getDouble(rs, 2)); - record.setStatement(getString(rs, 3)); - record.setRf(getString(rs, 4)); - record.setDatestart(getString(rs, 5)); - record.setDateend(getString(rs, 6)); - record.setImpact_pe(getString(rs, 7)); - - // add this FloodstmtRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FloodstmtRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FloodstmtRecord object and.. -//----------------------------------------------------------------- - public int insert(FloodstmtRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO floodstmt VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDouble(insertStatement, 2, record.getImpact_value()); - setString(insertStatement, 3, record.getStatement()); - setString(insertStatement, 4, record.getRf()); - setString(insertStatement, 5, record.getDatestart()); - setString(insertStatement, 6, record.getDateend()); - setString(insertStatement, 7, record.getImpact_pe()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM floodstmt " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodstmtRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodstmtRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE floodstmt SET lid = ?, impact_value = ?, statement = ?, rf = ?, datestart = ?, dateend = ?, impact_pe = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDouble(updateStatement, 2, record.getImpact_value()); - setString(updateStatement, 3, record.getStatement()); - setString(updateStatement, 4, record.getRf()); - setString(updateStatement, 5, record.getDatestart()); - setString(updateStatement, 6, record.getDateend()); - setString(updateStatement, 7, record.getImpact_pe()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FloodstmtRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM floodstmt " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FloodstmtRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FloodstmtRecord oldRecord, FloodstmtRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE floodstmt SET lid = ?, impact_value = ?, statement = ?, rf = ?, datestart = ?, dateend = ?, impact_pe = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDouble(updateStatement, 2, newRecord.getImpact_value()); - setString(updateStatement, 3, newRecord.getStatement()); - setString(updateStatement, 4, newRecord.getRf()); - setString(updateStatement, 5, newRecord.getDatestart()); - setString(updateStatement, 6, newRecord.getDateend()); - setString(updateStatement, 7, newRecord.getImpact_pe()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FloodstmtRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FloodstmtRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FloodstmtRecord oldRecord = (FloodstmtRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FloodstmtTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FlowTypeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FlowTypeRecord.java deleted file mode 100644 index d9777768ca..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FlowTypeRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: FlowTypeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FlowType table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FlowTypeRecord extends DbRecord -{ - private String flowtype; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FlowTypeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FlowTypeRecord(FlowTypeRecord origRecord) - { - setFlowtype(origRecord.getFlowtype()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FlowType record - - //----------------------------------------------------------------- - public String getFlowtype() - { - return flowtype; - } - - public void setFlowtype(String flowtype) - { - this.flowtype = flowtype ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE flowtype = '" + flowtype + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getFlowtype() + " " + - "" ; - return outString; - } // end toString() -} // end of FlowTypeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FlowTypeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FlowTypeTable.java deleted file mode 100644 index 66ab111037..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FlowTypeTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: FlowTypeTable.java -// author : DBGEN -// created : Tue May 31 17:52:22 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// flowtype table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FlowTypeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FlowTypeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FlowTypeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("flowtype"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FlowTypeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FlowTypeRecord record = null; - - // create a List to hold FlowType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM flowtype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FlowTypeRecord - // and store its address in oneRecord - record = new FlowTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FlowTypeRecord object - - record.setFlowtype(getString(rs, 1)); - - // add this FlowTypeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FlowTypeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FlowTypeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FlowTypeRecord record = null; - - // create a List to hold FlowType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM flowtype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FlowTypeRecord - // and store its address in oneRecord - record = new FlowTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FlowTypeRecord object - - record.setFlowtype(getString(rs, 1)); - - // add this FlowTypeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FlowTypeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FlowTypeRecord object and.. -//----------------------------------------------------------------- - public int insert(FlowTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO flowtype VALUES (? )"); - - setString(insertStatement, 1, record.getFlowtype()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM flowtype " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FlowTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FlowTypeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE flowtype SET flowtype = ? " + where ); - - setString(updateStatement, 1, record.getFlowtype()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FlowTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM flowtype " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FlowTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FlowTypeRecord oldRecord, FlowTypeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE flowtype SET flowtype = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getFlowtype()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FlowTypeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FlowTypeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FlowTypeRecord oldRecord = (FlowTypeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FlowTypeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpInfoRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpInfoRecord.java deleted file mode 100644 index 1267d7f6e9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpInfoRecord.java +++ /dev/null @@ -1,464 +0,0 @@ -// This is a view record ! -// filename: FpInfoRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FpInfo table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FpInfoRecord extends DbRecord -{ - private String lid; - - private String name; - - private String county; - - private String state; - - private String hsa; - - private String primary_back; - - private String secondary_back; - - private String stream; - - private double bf; - - private double wstg; - - private double fs; - - private double fq; - - private double action_flow; - - private String pe; - - private String use_latest_fcst; - - private String proximity; - - private String reach; - - private String group_id; - - private int ordinal; - - private double chg_threshold; - - private String rec_type; - - private int backhrs; - - private int forwardhrs; - - private double adjustendhrs; - - private double minor_stage; - - private double moderate_stage; - - private double major_stage; - - private double minor_flow; - - private double moderate_flow; - - private double major_flow; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FpInfoRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FpInfoRecord(FpInfoRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setHsa(origRecord.getHsa()); - setPrimary_back(origRecord.getPrimary_back()); - setSecondary_back(origRecord.getSecondary_back()); - setStream(origRecord.getStream()); - setBf(origRecord.getBf()); - setWstg(origRecord.getWstg()); - setFs(origRecord.getFs()); - setFq(origRecord.getFq()); - setAction_flow(origRecord.getAction_flow()); - setPe(origRecord.getPe()); - setUse_latest_fcst(origRecord.getUse_latest_fcst()); - setProximity(origRecord.getProximity()); - setReach(origRecord.getReach()); - setGroup_id(origRecord.getGroup_id()); - setOrdinal(origRecord.getOrdinal()); - setChg_threshold(origRecord.getChg_threshold()); - setRec_type(origRecord.getRec_type()); - setBackhrs(origRecord.getBackhrs()); - setForwardhrs(origRecord.getForwardhrs()); - setAdjustendhrs(origRecord.getAdjustendhrs()); - setMinor_stage(origRecord.getMinor_stage()); - setModerate_stage(origRecord.getModerate_stage()); - setMajor_stage(origRecord.getMajor_stage()); - setMinor_flow(origRecord.getMinor_flow()); - setModerate_flow(origRecord.getModerate_flow()); - setMajor_flow(origRecord.getMajor_flow()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FpInfo record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public String getPrimary_back() - { - return primary_back; - } - - public void setPrimary_back(String primary_back) - { - this.primary_back = primary_back ; - } - - public String getSecondary_back() - { - return secondary_back; - } - - public void setSecondary_back(String secondary_back) - { - this.secondary_back = secondary_back ; - } - - public String getStream() - { - return stream; - } - - public void setStream(String stream) - { - this.stream = stream ; - } - - public double getBf() - { - return bf; - } - - public void setBf(double bf) - { - this.bf = bf ; - } - - public double getWstg() - { - return wstg; - } - - public void setWstg(double wstg) - { - this.wstg = wstg ; - } - - public double getFs() - { - return fs; - } - - public void setFs(double fs) - { - this.fs = fs ; - } - - public double getFq() - { - return fq; - } - - public void setFq(double fq) - { - this.fq = fq ; - } - - public double getAction_flow() - { - return action_flow; - } - - public void setAction_flow(double action_flow) - { - this.action_flow = action_flow ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public String getUse_latest_fcst() - { - return use_latest_fcst; - } - - public void setUse_latest_fcst(String use_latest_fcst) - { - this.use_latest_fcst = use_latest_fcst ; - } - - public String getProximity() - { - return proximity; - } - - public void setProximity(String proximity) - { - this.proximity = proximity ; - } - - public String getReach() - { - return reach; - } - - public void setReach(String reach) - { - this.reach = reach ; - } - - public String getGroup_id() - { - return group_id; - } - - public void setGroup_id(String group_id) - { - this.group_id = group_id ; - } - - public int getOrdinal() - { - return ordinal; - } - - public void setOrdinal(int ordinal) - { - this.ordinal = ordinal ; - } - - public double getChg_threshold() - { - return chg_threshold; - } - - public void setChg_threshold(double chg_threshold) - { - this.chg_threshold = chg_threshold ; - } - - public String getRec_type() - { - return rec_type; - } - - public void setRec_type(String rec_type) - { - this.rec_type = rec_type ; - } - - public int getBackhrs() - { - return backhrs; - } - - public void setBackhrs(int backhrs) - { - this.backhrs = backhrs ; - } - - public int getForwardhrs() - { - return forwardhrs; - } - - public void setForwardhrs(int forwardhrs) - { - this.forwardhrs = forwardhrs ; - } - - public double getAdjustendhrs() - { - return adjustendhrs; - } - - public void setAdjustendhrs(double adjustendhrs) - { - this.adjustendhrs = adjustendhrs ; - } - - public double getMinor_stage() - { - return minor_stage; - } - - public void setMinor_stage(double minor_stage) - { - this.minor_stage = minor_stage ; - } - - public double getModerate_stage() - { - return moderate_stage; - } - - public void setModerate_stage(double moderate_stage) - { - this.moderate_stage = moderate_stage ; - } - - public double getMajor_stage() - { - return major_stage; - } - - public void setMajor_stage(double major_stage) - { - this.major_stage = major_stage ; - } - - public double getMinor_flow() - { - return minor_flow; - } - - public void setMinor_flow(double minor_flow) - { - this.minor_flow = minor_flow ; - } - - public double getModerate_flow() - { - return moderate_flow; - } - - public void setModerate_flow(double moderate_flow) - { - this.moderate_flow = moderate_flow ; - } - - public double getMajor_flow() - { - return major_flow; - } - - public void setMajor_flow(double major_flow) - { - this.major_flow = major_flow ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getCounty() + " " + - getState() + " " + - getHsa() + " " + - getPrimary_back() + " " + - getSecondary_back() + " " + - getStream() + " " + - getBf() + " " + - getWstg() + " " + - getFs() + " " + - getFq() + " " + - getAction_flow() + " " + - getPe() + " " + - getUse_latest_fcst() + " " + - getProximity() + " " + - getReach() + " " + - getGroup_id() + " " + - getOrdinal() + " " + - getChg_threshold() + " " + - getRec_type() + " " + - getBackhrs() + " " + - getForwardhrs() + " " + - getAdjustendhrs() + " " + - getMinor_stage() + " " + - getModerate_stage() + " " + - getMajor_stage() + " " + - getMinor_flow() + " " + - getModerate_flow() + " " + - getMajor_flow() + " " + - "" ; - return outString; - } // end toString() -} // end of FpInfoRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpInfoView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpInfoView.java deleted file mode 100644 index b858e2f4e3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpInfoView.java +++ /dev/null @@ -1,189 +0,0 @@ -// filename: FpInfoView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fpinfo table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FpInfoView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FpInfoTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FpInfoView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fpinfo"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FpInfoRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FpInfoRecord record = null; - - // create a List to hold FpInfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fpinfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FpInfoRecord - // and store its address in oneRecord - record = new FpInfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FpInfoRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - record.setState(getString(rs, 4)); - record.setHsa(getString(rs, 5)); - record.setPrimary_back(getString(rs, 6)); - record.setSecondary_back(getString(rs, 7)); - record.setStream(getString(rs, 8)); - record.setBf(getDouble(rs, 9)); - record.setWstg(getDouble(rs, 10)); - record.setFs(getDouble(rs, 11)); - record.setFq(getDouble(rs, 12)); - record.setAction_flow(getDouble(rs, 13)); - record.setPe(getString(rs, 14)); - record.setUse_latest_fcst(getString(rs, 15)); - record.setProximity(getString(rs, 16)); - record.setReach(getString(rs, 17)); - record.setGroup_id(getString(rs, 18)); - record.setOrdinal(getInt(rs, 19)); - record.setChg_threshold(getDouble(rs, 20)); - record.setRec_type(getString(rs, 21)); - record.setBackhrs(getInt(rs, 22)); - record.setForwardhrs(getInt(rs, 23)); - record.setAdjustendhrs(getDouble(rs, 24)); - record.setMinor_stage(getDouble(rs, 25)); - record.setModerate_stage(getDouble(rs, 26)); - record.setMajor_stage(getDouble(rs, 27)); - record.setMinor_flow(getDouble(rs, 28)); - record.setModerate_flow(getDouble(rs, 29)); - record.setMajor_flow(getDouble(rs, 30)); - - // add this FpInfoRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FpInfoRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FpInfoRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FpInfoRecord record = null; - - // create a List to hold FpInfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fpinfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FpInfoRecord - // and store its address in oneRecord - record = new FpInfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FpInfoRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - record.setState(getString(rs, 4)); - record.setHsa(getString(rs, 5)); - record.setPrimary_back(getString(rs, 6)); - record.setSecondary_back(getString(rs, 7)); - record.setStream(getString(rs, 8)); - record.setBf(getDouble(rs, 9)); - record.setWstg(getDouble(rs, 10)); - record.setFs(getDouble(rs, 11)); - record.setFq(getDouble(rs, 12)); - record.setAction_flow(getDouble(rs, 13)); - record.setPe(getString(rs, 14)); - record.setUse_latest_fcst(getString(rs, 15)); - record.setProximity(getString(rs, 16)); - record.setReach(getString(rs, 17)); - record.setGroup_id(getString(rs, 18)); - record.setOrdinal(getInt(rs, 19)); - record.setChg_threshold(getDouble(rs, 20)); - record.setRec_type(getString(rs, 21)); - record.setBackhrs(getInt(rs, 22)); - record.setForwardhrs(getInt(rs, 23)); - record.setAdjustendhrs(getDouble(rs, 24)); - record.setMinor_stage(getDouble(rs, 25)); - record.setModerate_stage(getDouble(rs, 26)); - record.setMajor_stage(getDouble(rs, 27)); - record.setMinor_flow(getDouble(rs, 28)); - record.setModerate_flow(getDouble(rs, 29)); - record.setMajor_flow(getDouble(rs, 30)); - - // add this FpInfoRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FpInfoRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of FpInfoTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdPracticeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdPracticeRecord.java deleted file mode 100644 index 9ffdcc8e68..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdPracticeRecord.java +++ /dev/null @@ -1,196 +0,0 @@ -// filename: FpPrevProdPracticeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FpPrevProdPractice table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FpPrevProdPracticeRecord extends DbRecord -{ - private String lid; - - private String product_id; - - private String prod_categ; - - private long producttime; - - private String office_id; - - private double obsvalue; - - private long obstime; - - private double max_fcstvalue; - - private long validtime; - - private long basistime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FpPrevProdPracticeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FpPrevProdPracticeRecord(FpPrevProdPracticeRecord origRecord) - { - setLid(origRecord.getLid()); - setProduct_id(origRecord.getProduct_id()); - setProd_categ(origRecord.getProd_categ()); - setProducttime(origRecord.getProducttime()); - setOffice_id(origRecord.getOffice_id()); - setObsvalue(origRecord.getObsvalue()); - setObstime(origRecord.getObstime()); - setMax_fcstvalue(origRecord.getMax_fcstvalue()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FpPrevProdPractice record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public String getProd_categ() - { - return prod_categ; - } - - public void setProd_categ(String prod_categ) - { - this.prod_categ = prod_categ ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - - public double getObsvalue() - { - return obsvalue; - } - - public void setObsvalue(double obsvalue) - { - this.obsvalue = obsvalue ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getMax_fcstvalue() - { - return max_fcstvalue; - } - - public void setMax_fcstvalue(double max_fcstvalue) - { - this.max_fcstvalue = max_fcstvalue ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND producttime = '" + getDateTimeStringFromLongTime(producttime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getProduct_id() + " " + - getProd_categ() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getOffice_id() + " " + - getObsvalue() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMax_fcstvalue() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FpPrevProdPracticeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdPracticeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdPracticeTable.java deleted file mode 100644 index e513f295ca..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdPracticeTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: FpPrevProdPracticeTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fpprevprodpractice table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FpPrevProdPracticeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FpPrevProdPracticeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FpPrevProdPracticeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fpprevprodpractice"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FpPrevProdPracticeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FpPrevProdPracticeRecord record = null; - - // create a List to hold FpPrevProdPractice Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fpprevprodpractice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FpPrevProdPracticeRecord - // and store its address in oneRecord - record = new FpPrevProdPracticeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FpPrevProdPracticeRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProd_categ(getString(rs, 3)); - record.setProducttime(getTimeStamp(rs, 4)); - record.setOffice_id(getString(rs, 5)); - record.setObsvalue(getDouble(rs, 6)); - record.setObstime(getTimeStamp(rs, 7)); - record.setMax_fcstvalue(getDouble(rs, 8)); - record.setValidtime(getTimeStamp(rs, 9)); - record.setBasistime(getTimeStamp(rs, 10)); - - // add this FpPrevProdPracticeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FpPrevProdPracticeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FpPrevProdPracticeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FpPrevProdPracticeRecord record = null; - - // create a List to hold FpPrevProdPractice Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fpprevprodpractice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FpPrevProdPracticeRecord - // and store its address in oneRecord - record = new FpPrevProdPracticeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FpPrevProdPracticeRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProd_categ(getString(rs, 3)); - record.setProducttime(getTimeStamp(rs, 4)); - record.setOffice_id(getString(rs, 5)); - record.setObsvalue(getDouble(rs, 6)); - record.setObstime(getTimeStamp(rs, 7)); - record.setMax_fcstvalue(getDouble(rs, 8)); - record.setValidtime(getTimeStamp(rs, 9)); - record.setBasistime(getTimeStamp(rs, 10)); - - // add this FpPrevProdPracticeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FpPrevProdPracticeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FpPrevProdPracticeRecord object and.. -//----------------------------------------------------------------- - public int insert(FpPrevProdPracticeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fpprevprodpractice VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getProduct_id()); - setString(insertStatement, 3, record.getProd_categ()); - setTimeStamp(insertStatement, 4, record.getProducttime()); - setString(insertStatement, 5, record.getOffice_id()); - setDouble(insertStatement, 6, record.getObsvalue()); - setTimeStamp(insertStatement, 7, record.getObstime()); - setDouble(insertStatement, 8, record.getMax_fcstvalue()); - setTimeStamp(insertStatement, 9, record.getValidtime()); - setTimeStamp(insertStatement, 10, record.getBasistime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fpprevprodpractice " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FpPrevProdPracticeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FpPrevProdPracticeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fpprevprodpractice SET lid = ?, product_id = ?, prod_categ = ?, producttime = ?, office_id = ?, obsvalue = ?, obstime = ?, max_fcstvalue = ?, validtime = ?, basistime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getProduct_id()); - setString(updateStatement, 3, record.getProd_categ()); - setTimeStamp(updateStatement, 4, record.getProducttime()); - setString(updateStatement, 5, record.getOffice_id()); - setDouble(updateStatement, 6, record.getObsvalue()); - setTimeStamp(updateStatement, 7, record.getObstime()); - setDouble(updateStatement, 8, record.getMax_fcstvalue()); - setTimeStamp(updateStatement, 9, record.getValidtime()); - setTimeStamp(updateStatement, 10, record.getBasistime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FpPrevProdPracticeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fpprevprodpractice " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FpPrevProdPracticeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FpPrevProdPracticeRecord oldRecord, FpPrevProdPracticeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fpprevprodpractice SET lid = ?, product_id = ?, prod_categ = ?, producttime = ?, office_id = ?, obsvalue = ?, obstime = ?, max_fcstvalue = ?, validtime = ?, basistime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getProduct_id()); - setString(updateStatement, 3, newRecord.getProd_categ()); - setTimeStamp(updateStatement, 4, newRecord.getProducttime()); - setString(updateStatement, 5, newRecord.getOffice_id()); - setDouble(updateStatement, 6, newRecord.getObsvalue()); - setTimeStamp(updateStatement, 7, newRecord.getObstime()); - setDouble(updateStatement, 8, newRecord.getMax_fcstvalue()); - setTimeStamp(updateStatement, 9, newRecord.getValidtime()); - setTimeStamp(updateStatement, 10, newRecord.getBasistime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FpPrevProdPracticeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FpPrevProdPracticeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FpPrevProdPracticeRecord oldRecord = (FpPrevProdPracticeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FpPrevProdPracticeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdRecord.java deleted file mode 100644 index 8516e4aaff..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdRecord.java +++ /dev/null @@ -1,196 +0,0 @@ -// filename: FpPrevProdRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FpPrevProd table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FpPrevProdRecord extends DbRecord -{ - private String lid; - - private String product_id; - - private String prod_categ; - - private long producttime; - - private String office_id; - - private double obsvalue; - - private long obstime; - - private double max_fcstvalue; - - private long validtime; - - private long basistime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FpPrevProdRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FpPrevProdRecord(FpPrevProdRecord origRecord) - { - setLid(origRecord.getLid()); - setProduct_id(origRecord.getProduct_id()); - setProd_categ(origRecord.getProd_categ()); - setProducttime(origRecord.getProducttime()); - setOffice_id(origRecord.getOffice_id()); - setObsvalue(origRecord.getObsvalue()); - setObstime(origRecord.getObstime()); - setMax_fcstvalue(origRecord.getMax_fcstvalue()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FpPrevProd record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public String getProd_categ() - { - return prod_categ; - } - - public void setProd_categ(String prod_categ) - { - this.prod_categ = prod_categ ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - - public double getObsvalue() - { - return obsvalue; - } - - public void setObsvalue(double obsvalue) - { - this.obsvalue = obsvalue ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getMax_fcstvalue() - { - return max_fcstvalue; - } - - public void setMax_fcstvalue(double max_fcstvalue) - { - this.max_fcstvalue = max_fcstvalue ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND producttime = '" + getDateTimeStringFromLongTime(producttime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getProduct_id() + " " + - getProd_categ() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getOffice_id() + " " + - getObsvalue() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMax_fcstvalue() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - "" ; - return outString; - } // end toString() -} // end of FpPrevProdRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdTable.java deleted file mode 100644 index 602db1e34f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FpPrevProdTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: FpPrevProdTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// fpprevprod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FpPrevProdTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FpPrevProdTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FpPrevProdTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("fpprevprod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FpPrevProdRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FpPrevProdRecord record = null; - - // create a List to hold FpPrevProd Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fpprevprod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FpPrevProdRecord - // and store its address in oneRecord - record = new FpPrevProdRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FpPrevProdRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProd_categ(getString(rs, 3)); - record.setProducttime(getTimeStamp(rs, 4)); - record.setOffice_id(getString(rs, 5)); - record.setObsvalue(getDouble(rs, 6)); - record.setObstime(getTimeStamp(rs, 7)); - record.setMax_fcstvalue(getDouble(rs, 8)); - record.setValidtime(getTimeStamp(rs, 9)); - record.setBasistime(getTimeStamp(rs, 10)); - - // add this FpPrevProdRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FpPrevProdRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FpPrevProdRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FpPrevProdRecord record = null; - - // create a List to hold FpPrevProd Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM fpprevprod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FpPrevProdRecord - // and store its address in oneRecord - record = new FpPrevProdRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FpPrevProdRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProd_categ(getString(rs, 3)); - record.setProducttime(getTimeStamp(rs, 4)); - record.setOffice_id(getString(rs, 5)); - record.setObsvalue(getDouble(rs, 6)); - record.setObstime(getTimeStamp(rs, 7)); - record.setMax_fcstvalue(getDouble(rs, 8)); - record.setValidtime(getTimeStamp(rs, 9)); - record.setBasistime(getTimeStamp(rs, 10)); - - // add this FpPrevProdRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FpPrevProdRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FpPrevProdRecord object and.. -//----------------------------------------------------------------- - public int insert(FpPrevProdRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO fpprevprod VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getProduct_id()); - setString(insertStatement, 3, record.getProd_categ()); - setTimeStamp(insertStatement, 4, record.getProducttime()); - setString(insertStatement, 5, record.getOffice_id()); - setDouble(insertStatement, 6, record.getObsvalue()); - setTimeStamp(insertStatement, 7, record.getObstime()); - setDouble(insertStatement, 8, record.getMax_fcstvalue()); - setTimeStamp(insertStatement, 9, record.getValidtime()); - setTimeStamp(insertStatement, 10, record.getBasistime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fpprevprod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FpPrevProdRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FpPrevProdRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fpprevprod SET lid = ?, product_id = ?, prod_categ = ?, producttime = ?, office_id = ?, obsvalue = ?, obstime = ?, max_fcstvalue = ?, validtime = ?, basistime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getProduct_id()); - setString(updateStatement, 3, record.getProd_categ()); - setTimeStamp(updateStatement, 4, record.getProducttime()); - setString(updateStatement, 5, record.getOffice_id()); - setDouble(updateStatement, 6, record.getObsvalue()); - setTimeStamp(updateStatement, 7, record.getObstime()); - setDouble(updateStatement, 8, record.getMax_fcstvalue()); - setTimeStamp(updateStatement, 9, record.getValidtime()); - setTimeStamp(updateStatement, 10, record.getBasistime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FpPrevProdRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM fpprevprod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FpPrevProdRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FpPrevProdRecord oldRecord, FpPrevProdRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE fpprevprod SET lid = ?, product_id = ?, prod_categ = ?, producttime = ?, office_id = ?, obsvalue = ?, obstime = ?, max_fcstvalue = ?, validtime = ?, basistime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getProduct_id()); - setString(updateStatement, 3, newRecord.getProd_categ()); - setTimeStamp(updateStatement, 4, newRecord.getProducttime()); - setString(updateStatement, 5, newRecord.getOffice_id()); - setDouble(updateStatement, 6, newRecord.getObsvalue()); - setTimeStamp(updateStatement, 7, newRecord.getObstime()); - setDouble(updateStatement, 8, newRecord.getMax_fcstvalue()); - setTimeStamp(updateStatement, 9, newRecord.getValidtime()); - setTimeStamp(updateStatement, 10, newRecord.getBasistime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FpPrevProdRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FpPrevProdRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FpPrevProdRecord oldRecord = (FpPrevProdRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FpPrevProdTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FrequencyUpdateRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FrequencyUpdateRecord.java deleted file mode 100644 index 3a5b4de0fb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FrequencyUpdateRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: FrequencyUpdateRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// FrequencyUpdate table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class FrequencyUpdateRecord extends DbRecord -{ - private String frequency_update; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public FrequencyUpdateRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public FrequencyUpdateRecord(FrequencyUpdateRecord origRecord) - { - setFrequency_update(origRecord.getFrequency_update()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a FrequencyUpdate record - - //----------------------------------------------------------------- - public String getFrequency_update() - { - return frequency_update; - } - - public void setFrequency_update(String frequency_update) - { - this.frequency_update = frequency_update ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE frequency_update = '" + frequency_update + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getFrequency_update() + " " + - "" ; - return outString; - } // end toString() -} // end of FrequencyUpdateRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FrequencyUpdateTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FrequencyUpdateTable.java deleted file mode 100644 index eeb53e412e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/FrequencyUpdateTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: FrequencyUpdateTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// frequencyupdate table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class FrequencyUpdateTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// FrequencyUpdateTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public FrequencyUpdateTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("frequencyupdate"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of FrequencyUpdateRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - FrequencyUpdateRecord record = null; - - // create a List to hold FrequencyUpdate Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM frequencyupdate " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FrequencyUpdateRecord - // and store its address in oneRecord - record = new FrequencyUpdateRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FrequencyUpdateRecord object - - record.setFrequency_update(getString(rs, 1)); - - // add this FrequencyUpdateRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the FrequencyUpdateRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of FrequencyUpdateRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - FrequencyUpdateRecord record = null; - - // create a List to hold FrequencyUpdate Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM frequencyupdate " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a FrequencyUpdateRecord - // and store its address in oneRecord - record = new FrequencyUpdateRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a FrequencyUpdateRecord object - - record.setFrequency_update(getString(rs, 1)); - - // add this FrequencyUpdateRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the FrequencyUpdateRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a FrequencyUpdateRecord object and.. -//----------------------------------------------------------------- - public int insert(FrequencyUpdateRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO frequencyupdate VALUES (? )"); - - setString(insertStatement, 1, record.getFrequency_update()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM frequencyupdate " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FrequencyUpdateRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FrequencyUpdateRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE frequencyupdate SET frequency_update = ? " + where ); - - setString(updateStatement, 1, record.getFrequency_update()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(FrequencyUpdateRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM frequencyupdate " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a FrequencyUpdateRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(FrequencyUpdateRecord oldRecord, FrequencyUpdateRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE frequencyupdate SET frequency_update = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getFrequency_update()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a FrequencyUpdateRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(FrequencyUpdateRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - FrequencyUpdateRecord oldRecord = (FrequencyUpdateRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of FrequencyUpdateTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageMaintRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageMaintRecord.java deleted file mode 100644 index 3e2d531219..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageMaintRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: GageMaintRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// GageMaint table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GageMaintRecord extends DbRecord -{ - private String maint; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GageMaintRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GageMaintRecord(GageMaintRecord origRecord) - { - setMaint(origRecord.getMaint()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a GageMaint record - - //----------------------------------------------------------------- - public String getMaint() - { - return maint; - } - - public void setMaint(String maint) - { - this.maint = maint ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE maint = '" + maint + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getMaint() + " " + - "" ; - return outString; - } // end toString() -} // end of GageMaintRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageMaintTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageMaintTable.java deleted file mode 100644 index 8a266c32fa..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageMaintTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: GageMaintTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// gagemaint table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GageMaintTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GageMaintTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GageMaintTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("gagemaint"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GageMaintRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GageMaintRecord record = null; - - // create a List to hold GageMaint Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gagemaint " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageMaintRecord - // and store its address in oneRecord - record = new GageMaintRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageMaintRecord object - - record.setMaint(getString(rs, 1)); - - // add this GageMaintRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GageMaintRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GageMaintRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GageMaintRecord record = null; - - // create a List to hold GageMaint Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gagemaint " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageMaintRecord - // and store its address in oneRecord - record = new GageMaintRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageMaintRecord object - - record.setMaint(getString(rs, 1)); - - // add this GageMaintRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GageMaintRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GageMaintRecord object and.. -//----------------------------------------------------------------- - public int insert(GageMaintRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO gagemaint VALUES (? )"); - - setString(insertStatement, 1, record.getMaint()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gagemaint " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageMaintRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageMaintRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gagemaint SET maint = ? " + where ); - - setString(updateStatement, 1, record.getMaint()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GageMaintRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gagemaint " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageMaintRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageMaintRecord oldRecord, GageMaintRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gagemaint SET maint = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getMaint()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GageMaintRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GageMaintRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GageMaintRecord oldRecord = (GageMaintRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GageMaintTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageOwnerRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageOwnerRecord.java deleted file mode 100644 index eef031bbe9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageOwnerRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: GageOwnerRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// GageOwner table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GageOwnerRecord extends DbRecord -{ - private String owner; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GageOwnerRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GageOwnerRecord(GageOwnerRecord origRecord) - { - setOwner(origRecord.getOwner()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a GageOwner record - - //----------------------------------------------------------------- - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE owner = '" + owner + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getOwner() + " " + - "" ; - return outString; - } // end toString() -} // end of GageOwnerRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageOwnerTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageOwnerTable.java deleted file mode 100644 index 7138606f0f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageOwnerTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: GageOwnerTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// gageowner table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GageOwnerTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GageOwnerTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GageOwnerTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("gageowner"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GageOwnerRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GageOwnerRecord record = null; - - // create a List to hold GageOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gageowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageOwnerRecord - // and store its address in oneRecord - record = new GageOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this GageOwnerRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GageOwnerRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GageOwnerRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GageOwnerRecord record = null; - - // create a List to hold GageOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gageowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageOwnerRecord - // and store its address in oneRecord - record = new GageOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this GageOwnerRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GageOwnerRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GageOwnerRecord object and.. -//----------------------------------------------------------------- - public int insert(GageOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO gageowner VALUES (? )"); - - setString(insertStatement, 1, record.getOwner()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gageowner " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageOwnerRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gageowner SET owner = ? " + where ); - - setString(updateStatement, 1, record.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GageOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gageowner " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageOwnerRecord oldRecord, GageOwnerRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gageowner SET owner = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GageOwnerRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GageOwnerRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GageOwnerRecord oldRecord = (GageOwnerRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GageOwnerTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageRecord.java deleted file mode 100644 index 2789c10903..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageRecord.java +++ /dev/null @@ -1,155 +0,0 @@ -// filename: GageRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Gage table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GageRecord extends DbRecord -{ - private String lid; - - private long gbegin; - - private String type; - - private long gend; - - private String remark; - - private String maint; - - private String owner; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GageRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GageRecord(GageRecord origRecord) - { - setLid(origRecord.getLid()); - setGbegin(origRecord.getGbegin()); - setType(origRecord.getType()); - setGend(origRecord.getGend()); - setRemark(origRecord.getRemark()); - setMaint(origRecord.getMaint()); - setOwner(origRecord.getOwner()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Gage record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getGbegin() - { - return gbegin; - } - - public void setGbegin(long gbegin) - { - this.gbegin = gbegin ; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - - public long getGend() - { - return gend; - } - - public void setGend(long gend) - { - this.gend = gend ; - } - - public String getRemark() - { - return remark; - } - - public void setRemark(String remark) - { - this.remark = remark ; - } - - public String getMaint() - { - return maint; - } - - public void setMaint(String maint) - { - this.maint = maint ; - } - - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND gbegin = '" + getDateStringFromLongTime(gbegin) + "'" - + " AND type = '" + type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateStringFromLongTime(getGbegin()) + " " + - getType() + " " + - getDateStringFromLongTime(getGend()) + " " + - getRemark() + " " + - getMaint() + " " + - getOwner() + " " + - "" ; - return outString; - } // end toString() -} // end of GageRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTable.java deleted file mode 100644 index 6a63655f18..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: GageTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// gage table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GageTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GageTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GageTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("gage"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GageRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GageRecord record = null; - - // create a List to hold Gage Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gage " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageRecord - // and store its address in oneRecord - record = new GageRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageRecord object - - record.setLid(getString(rs, 1)); - record.setGbegin(getDate(rs, 2)); - record.setType(getString(rs, 3)); - record.setGend(getDate(rs, 4)); - record.setRemark(getString(rs, 5)); - record.setMaint(getString(rs, 6)); - record.setOwner(getString(rs, 7)); - - // add this GageRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GageRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GageRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GageRecord record = null; - - // create a List to hold Gage Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gage " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageRecord - // and store its address in oneRecord - record = new GageRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageRecord object - - record.setLid(getString(rs, 1)); - record.setGbegin(getDate(rs, 2)); - record.setType(getString(rs, 3)); - record.setGend(getDate(rs, 4)); - record.setRemark(getString(rs, 5)); - record.setMaint(getString(rs, 6)); - record.setOwner(getString(rs, 7)); - - // add this GageRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GageRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GageRecord object and.. -//----------------------------------------------------------------- - public int insert(GageRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO gage VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDate(insertStatement, 2, record.getGbegin()); - setString(insertStatement, 3, record.getType()); - setDate(insertStatement, 4, record.getGend()); - setString(insertStatement, 5, record.getRemark()); - setString(insertStatement, 6, record.getMaint()); - setString(insertStatement, 7, record.getOwner()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gage " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gage SET lid = ?, gbegin = ?, type = ?, gend = ?, remark = ?, maint = ?, owner = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDate(updateStatement, 2, record.getGbegin()); - setString(updateStatement, 3, record.getType()); - setDate(updateStatement, 4, record.getGend()); - setString(updateStatement, 5, record.getRemark()); - setString(updateStatement, 6, record.getMaint()); - setString(updateStatement, 7, record.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GageRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gage " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageRecord oldRecord, GageRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gage SET lid = ?, gbegin = ?, type = ?, gend = ?, remark = ?, maint = ?, owner = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDate(updateStatement, 2, newRecord.getGbegin()); - setString(updateStatement, 3, newRecord.getType()); - setDate(updateStatement, 4, newRecord.getGend()); - setString(updateStatement, 5, newRecord.getRemark()); - setString(updateStatement, 6, newRecord.getMaint()); - setString(updateStatement, 7, newRecord.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GageRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GageRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GageRecord oldRecord = (GageRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GageTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTypeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTypeRecord.java deleted file mode 100644 index 86b6fd2613..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTypeRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: GageTypeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// GageType table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GageTypeRecord extends DbRecord -{ - private String type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GageTypeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GageTypeRecord(GageTypeRecord origRecord) - { - setType(origRecord.getType()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a GageType record - - //----------------------------------------------------------------- - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE type = '" + type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getType() + " " + - "" ; - return outString; - } // end toString() -} // end of GageTypeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTypeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTypeTable.java deleted file mode 100644 index dc937f5b88..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GageTypeTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: GageTypeTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// gagetype table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GageTypeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GageTypeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GageTypeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("gagetype"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GageTypeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GageTypeRecord record = null; - - // create a List to hold GageType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gagetype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageTypeRecord - // and store its address in oneRecord - record = new GageTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageTypeRecord object - - record.setType(getString(rs, 1)); - - // add this GageTypeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GageTypeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GageTypeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GageTypeRecord record = null; - - // create a List to hold GageType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gagetype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GageTypeRecord - // and store its address in oneRecord - record = new GageTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GageTypeRecord object - - record.setType(getString(rs, 1)); - - // add this GageTypeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GageTypeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GageTypeRecord object and.. -//----------------------------------------------------------------- - public int insert(GageTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO gagetype VALUES (? )"); - - setString(insertStatement, 1, record.getType()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gagetype " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageTypeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gagetype SET type = ? " + where ); - - setString(updateStatement, 1, record.getType()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GageTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gagetype " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GageTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GageTypeRecord oldRecord, GageTypeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gagetype SET type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getType()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GageTypeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GageTypeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GageTypeRecord oldRecord = (GageTypeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GageTypeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GateDamRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GateDamRecord.java deleted file mode 100644 index e56e0bd851..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GateDamRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: GateDamRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// GateDam table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GateDamRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GateDamRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GateDamRecord(GateDamRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a GateDam record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of GateDamRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GateDamTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GateDamTable.java deleted file mode 100644 index e42e511e6c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GateDamTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: GateDamTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// gatedam table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GateDamTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GateDamTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GateDamTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("gatedam"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GateDamRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GateDamRecord record = null; - - // create a List to hold GateDam Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gatedam " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GateDamRecord - // and store its address in oneRecord - record = new GateDamRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GateDamRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this GateDamRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GateDamRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GateDamRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GateDamRecord record = null; - - // create a List to hold GateDam Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM gatedam " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GateDamRecord - // and store its address in oneRecord - record = new GateDamRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GateDamRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this GateDamRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GateDamRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GateDamRecord object and.. -//----------------------------------------------------------------- - public int insert(GateDamRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO gatedam VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gatedam " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GateDamRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GateDamRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gatedam SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GateDamRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM gatedam " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GateDamRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GateDamRecord oldRecord, GateDamRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE gatedam SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GateDamRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GateDamRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GateDamRecord oldRecord = (GateDamRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GateDamTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GeoAreaRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GeoAreaRecord.java deleted file mode 100644 index 9635710ab5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GeoAreaRecord.java +++ /dev/null @@ -1,125 +0,0 @@ -// filename: GeoAreaRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// GeoArea table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GeoAreaRecord extends DbRecord -{ - private String area_id; - - private String name; - - private String boundary_type; - - private double interior_lat; - - private double interior_lon; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GeoAreaRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GeoAreaRecord(GeoAreaRecord origRecord) - { - setArea_id(origRecord.getArea_id()); - setName(origRecord.getName()); - setBoundary_type(origRecord.getBoundary_type()); - setInterior_lat(origRecord.getInterior_lat()); - setInterior_lon(origRecord.getInterior_lon()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a GeoArea record - - //----------------------------------------------------------------- - public String getArea_id() - { - return area_id; - } - - public void setArea_id(String area_id) - { - this.area_id = area_id ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getBoundary_type() - { - return boundary_type; - } - - public void setBoundary_type(String boundary_type) - { - this.boundary_type = boundary_type ; - } - - public double getInterior_lat() - { - return interior_lat; - } - - public void setInterior_lat(double interior_lat) - { - this.interior_lat = interior_lat ; - } - - public double getInterior_lon() - { - return interior_lon; - } - - public void setInterior_lon(double interior_lon) - { - this.interior_lon = interior_lon ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE area_id = '" + area_id + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getArea_id() + " " + - getName() + " " + - getBoundary_type() + " " + - getInterior_lat() + " " + - getInterior_lon() + " " + - "" ; - return outString; - } // end toString() -} // end of GeoAreaRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GeoAreaTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GeoAreaTable.java deleted file mode 100644 index 9e62500d49..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GeoAreaTable.java +++ /dev/null @@ -1,266 +0,0 @@ -// filename: GeoAreaTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// geoarea table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GeoAreaTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GeoAreaTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GeoAreaTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("geoarea"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GeoAreaRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GeoAreaRecord record = null; - - // create a List to hold GeoArea Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM geoarea " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GeoAreaRecord - // and store its address in oneRecord - record = new GeoAreaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GeoAreaRecord object - - record.setArea_id(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setBoundary_type(getString(rs, 3)); - record.setInterior_lat(getDouble(rs, 4)); - record.setInterior_lon(getDouble(rs, 5)); - - // add this GeoAreaRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GeoAreaRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GeoAreaRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GeoAreaRecord record = null; - - // create a List to hold GeoArea Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM geoarea " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GeoAreaRecord - // and store its address in oneRecord - record = new GeoAreaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GeoAreaRecord object - - record.setArea_id(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setBoundary_type(getString(rs, 3)); - record.setInterior_lat(getDouble(rs, 4)); - record.setInterior_lon(getDouble(rs, 5)); - - // add this GeoAreaRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GeoAreaRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GeoAreaRecord object and.. -//----------------------------------------------------------------- - public int insert(GeoAreaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO geoarea VALUES (?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getArea_id()); - setString(insertStatement, 2, record.getName()); - setString(insertStatement, 3, record.getBoundary_type()); - setDouble(insertStatement, 4, record.getInterior_lat()); - setDouble(insertStatement, 5, record.getInterior_lon()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM geoarea " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GeoAreaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GeoAreaRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE geoarea SET area_id = ?, name = ?, boundary_type = ?, interior_lat = ?, interior_lon = ? " + where ); - - setString(updateStatement, 1, record.getArea_id()); - setString(updateStatement, 2, record.getName()); - setString(updateStatement, 3, record.getBoundary_type()); - setDouble(updateStatement, 4, record.getInterior_lat()); - setDouble(updateStatement, 5, record.getInterior_lon()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GeoAreaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM geoarea " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GeoAreaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GeoAreaRecord oldRecord, GeoAreaRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE geoarea SET area_id = ?, name = ?, boundary_type = ?, interior_lat = ?, interior_lon = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getArea_id()); - setString(updateStatement, 2, newRecord.getName()); - setString(updateStatement, 3, newRecord.getBoundary_type()); - setDouble(updateStatement, 4, newRecord.getInterior_lat()); - setDouble(updateStatement, 5, newRecord.getInterior_lon()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GeoAreaRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GeoAreaRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GeoAreaRecord oldRecord = (GeoAreaRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GeoAreaTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GroundRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GroundRecord.java deleted file mode 100644 index f199c8b00e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GroundRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: GroundRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Ground table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class GroundRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public GroundRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public GroundRecord(GroundRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Ground record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of GroundRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GroundTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GroundTable.java deleted file mode 100644 index ed283b5bf2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/GroundTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: GroundTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// ground table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class GroundTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// GroundTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public GroundTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("ground"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of GroundRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - GroundRecord record = null; - - // create a List to hold Ground Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ground " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GroundRecord - // and store its address in oneRecord - record = new GroundRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GroundRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this GroundRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the GroundRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of GroundRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - GroundRecord record = null; - - // create a List to hold Ground Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ground " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a GroundRecord - // and store its address in oneRecord - record = new GroundRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a GroundRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this GroundRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the GroundRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a GroundRecord object and.. -//----------------------------------------------------------------- - public int insert(GroundRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO ground VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ground " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GroundRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GroundRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ground SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(GroundRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ground " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a GroundRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(GroundRecord oldRecord, GroundRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ground SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a GroundRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(GroundRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - GroundRecord oldRecord = (GroundRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of GroundTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HeightRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HeightRecord.java deleted file mode 100644 index 8c0e8b48fe..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HeightRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: HeightRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Height table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HeightRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HeightRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HeightRecord(HeightRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Height record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of HeightRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HeightTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HeightTable.java deleted file mode 100644 index 57e6551725..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HeightTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: HeightTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// height table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HeightTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HeightTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HeightTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("height"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HeightRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HeightRecord record = null; - - // create a List to hold Height Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM height " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HeightRecord - // and store its address in oneRecord - record = new HeightRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HeightRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this HeightRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HeightRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HeightRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HeightRecord record = null; - - // create a List to hold Height Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM height " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HeightRecord - // and store its address in oneRecord - record = new HeightRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HeightRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this HeightRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HeightRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a HeightRecord object and.. -//----------------------------------------------------------------- - public int insert(HeightRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO height VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM height " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HeightRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HeightRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE height SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(HeightRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM height " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HeightRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HeightRecord oldRecord, HeightRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE height SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a HeightRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(HeightRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - HeightRecord oldRecord = (HeightRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of HeightTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HgStationRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HgStationRecord.java deleted file mode 100644 index b3ba9ce4e3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HgStationRecord.java +++ /dev/null @@ -1,113 +0,0 @@ -// filename: HgStationRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// HgStation table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HgStationRecord extends DbRecord -{ - private String lid; - - private String pe; - - private String ts; - - private String fcstts; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HgStationRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HgStationRecord(HgStationRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setTs(origRecord.getTs()); - setFcstts(origRecord.getFcstts()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a HgStation record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getFcstts() - { - return fcstts; - } - - public void setFcstts(String fcstts) - { - this.fcstts = fcstts ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND ts = '" + ts + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getTs() + " " + - getFcstts() + " " + - "" ; - return outString; - } // end toString() -} // end of HgStationRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HgStationTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HgStationTable.java deleted file mode 100644 index bcc468ac96..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HgStationTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: HgStationTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hgstation table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HgStationTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HgStationTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HgStationTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hgstation"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HgStationRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HgStationRecord record = null; - - // create a List to hold HgStation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hgstation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HgStationRecord - // and store its address in oneRecord - record = new HgStationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HgStationRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setTs(getString(rs, 3)); - record.setFcstts(getString(rs, 4)); - - // add this HgStationRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HgStationRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HgStationRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HgStationRecord record = null; - - // create a List to hold HgStation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hgstation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HgStationRecord - // and store its address in oneRecord - record = new HgStationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HgStationRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setTs(getString(rs, 3)); - record.setFcstts(getString(rs, 4)); - - // add this HgStationRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HgStationRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a HgStationRecord object and.. -//----------------------------------------------------------------- - public int insert(HgStationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO hgstation VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setString(insertStatement, 3, record.getTs()); - setString(insertStatement, 4, record.getFcstts()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hgstation " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HgStationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HgStationRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hgstation SET lid = ?, pe = ?, ts = ?, fcstts = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setString(updateStatement, 3, record.getTs()); - setString(updateStatement, 4, record.getFcstts()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(HgStationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hgstation " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HgStationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HgStationRecord oldRecord, HgStationRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hgstation SET lid = ?, pe = ?, ts = ?, fcstts = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setString(updateStatement, 3, newRecord.getTs()); - setString(updateStatement, 4, newRecord.getFcstts()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a HgStationRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(HgStationRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - HgStationRecord oldRecord = (HgStationRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of HgStationTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPCRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPCRecord.java deleted file mode 100644 index 46a06e91c8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPCRecord.java +++ /dev/null @@ -1,463 +0,0 @@ -// filename: HourlyPCRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// HourlyPC table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HourlyPCRecord extends DbRecord -{ - private String lid; - - private String ts; - - private long obsdate; - - private String minute_offset; - - private String hourly_qc; - - private short hour1; - - private short hour2; - - private short hour3; - - private short hour4; - - private short hour5; - - private short hour6; - - private short hour7; - - private short hour8; - - private short hour9; - - private short hour10; - - private short hour11; - - private short hour12; - - private short hour13; - - private short hour14; - - private short hour15; - - private short hour16; - - private short hour17; - - private short hour18; - - private short hour19; - - private short hour20; - - private short hour21; - - private short hour22; - - private short hour23; - - private short hour24; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HourlyPCRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HourlyPCRecord(HourlyPCRecord origRecord) - { - setLid(origRecord.getLid()); - setTs(origRecord.getTs()); - setObsdate(origRecord.getObsdate()); - setMinute_offset(origRecord.getMinute_offset()); - setHourly_qc(origRecord.getHourly_qc()); - setHour1(origRecord.getHour1()); - setHour2(origRecord.getHour2()); - setHour3(origRecord.getHour3()); - setHour4(origRecord.getHour4()); - setHour5(origRecord.getHour5()); - setHour6(origRecord.getHour6()); - setHour7(origRecord.getHour7()); - setHour8(origRecord.getHour8()); - setHour9(origRecord.getHour9()); - setHour10(origRecord.getHour10()); - setHour11(origRecord.getHour11()); - setHour12(origRecord.getHour12()); - setHour13(origRecord.getHour13()); - setHour14(origRecord.getHour14()); - setHour15(origRecord.getHour15()); - setHour16(origRecord.getHour16()); - setHour17(origRecord.getHour17()); - setHour18(origRecord.getHour18()); - setHour19(origRecord.getHour19()); - setHour20(origRecord.getHour20()); - setHour21(origRecord.getHour21()); - setHour22(origRecord.getHour22()); - setHour23(origRecord.getHour23()); - setHour24(origRecord.getHour24()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a HourlyPC record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public long getObsdate() - { - return obsdate; - } - - public void setObsdate(long obsdate) - { - this.obsdate = obsdate ; - } - - public String getMinute_offset() - { - return minute_offset; - } - - public void setMinute_offset(String minute_offset) - { - this.minute_offset = minute_offset ; - } - - public String getHourly_qc() - { - return hourly_qc; - } - - public void setHourly_qc(String hourly_qc) - { - this.hourly_qc = hourly_qc ; - } - - public short getHour1() - { - return hour1; - } - - public void setHour1(short hour1) - { - this.hour1 = hour1 ; - } - - public short getHour2() - { - return hour2; - } - - public void setHour2(short hour2) - { - this.hour2 = hour2 ; - } - - public short getHour3() - { - return hour3; - } - - public void setHour3(short hour3) - { - this.hour3 = hour3 ; - } - - public short getHour4() - { - return hour4; - } - - public void setHour4(short hour4) - { - this.hour4 = hour4 ; - } - - public short getHour5() - { - return hour5; - } - - public void setHour5(short hour5) - { - this.hour5 = hour5 ; - } - - public short getHour6() - { - return hour6; - } - - public void setHour6(short hour6) - { - this.hour6 = hour6 ; - } - - public short getHour7() - { - return hour7; - } - - public void setHour7(short hour7) - { - this.hour7 = hour7 ; - } - - public short getHour8() - { - return hour8; - } - - public void setHour8(short hour8) - { - this.hour8 = hour8 ; - } - - public short getHour9() - { - return hour9; - } - - public void setHour9(short hour9) - { - this.hour9 = hour9 ; - } - - public short getHour10() - { - return hour10; - } - - public void setHour10(short hour10) - { - this.hour10 = hour10 ; - } - - public short getHour11() - { - return hour11; - } - - public void setHour11(short hour11) - { - this.hour11 = hour11 ; - } - - public short getHour12() - { - return hour12; - } - - public void setHour12(short hour12) - { - this.hour12 = hour12 ; - } - - public short getHour13() - { - return hour13; - } - - public void setHour13(short hour13) - { - this.hour13 = hour13 ; - } - - public short getHour14() - { - return hour14; - } - - public void setHour14(short hour14) - { - this.hour14 = hour14 ; - } - - public short getHour15() - { - return hour15; - } - - public void setHour15(short hour15) - { - this.hour15 = hour15 ; - } - - public short getHour16() - { - return hour16; - } - - public void setHour16(short hour16) - { - this.hour16 = hour16 ; - } - - public short getHour17() - { - return hour17; - } - - public void setHour17(short hour17) - { - this.hour17 = hour17 ; - } - - public short getHour18() - { - return hour18; - } - - public void setHour18(short hour18) - { - this.hour18 = hour18 ; - } - - public short getHour19() - { - return hour19; - } - - public void setHour19(short hour19) - { - this.hour19 = hour19 ; - } - - public short getHour20() - { - return hour20; - } - - public void setHour20(short hour20) - { - this.hour20 = hour20 ; - } - - public short getHour21() - { - return hour21; - } - - public void setHour21(short hour21) - { - this.hour21 = hour21 ; - } - - public short getHour22() - { - return hour22; - } - - public void setHour22(short hour22) - { - this.hour22 = hour22 ; - } - - public short getHour23() - { - return hour23; - } - - public void setHour23(short hour23) - { - this.hour23 = hour23 ; - } - - public short getHour24() - { - return hour24; - } - - public void setHour24(short hour24) - { - this.hour24 = hour24 ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ts = '" + ts + "'" - + " AND obsdate = '" + getDateStringFromLongTime(obsdate) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getTs() + " " + - getDateStringFromLongTime(getObsdate()) + " " + - getMinute_offset() + " " + - getHourly_qc() + " " + - getHour1() + " " + - getHour2() + " " + - getHour3() + " " + - getHour4() + " " + - getHour5() + " " + - getHour6() + " " + - getHour7() + " " + - getHour8() + " " + - getHour9() + " " + - getHour10() + " " + - getHour11() + " " + - getHour12() + " " + - getHour13() + " " + - getHour14() + " " + - getHour15() + " " + - getHour16() + " " + - getHour17() + " " + - getHour18() + " " + - getHour19() + " " + - getHour20() + " " + - getHour21() + " " + - getHour22() + " " + - getHour23() + " " + - getHour24() + " " + - "" ; - return outString; - } // end toString() -} // end of HourlyPCRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPCTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPCTable.java deleted file mode 100644 index 6d56158645..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPCTable.java +++ /dev/null @@ -1,386 +0,0 @@ -// filename: HourlyPCTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hourlypc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HourlyPCTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HourlyPCTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HourlyPCTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hourlypc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HourlyPCRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HourlyPCRecord record = null; - - // create a List to hold HourlyPC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hourlypc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HourlyPCRecord - // and store its address in oneRecord - record = new HourlyPCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HourlyPCRecord object - - record.setLid(getString(rs, 1)); - record.setTs(getString(rs, 2)); - record.setObsdate(getDate(rs, 3)); - record.setMinute_offset(getString(rs, 4)); - record.setHourly_qc(getString(rs, 5)); - record.setHour1(getShort(rs, 6)); - record.setHour2(getShort(rs, 7)); - record.setHour3(getShort(rs, 8)); - record.setHour4(getShort(rs, 9)); - record.setHour5(getShort(rs, 10)); - record.setHour6(getShort(rs, 11)); - record.setHour7(getShort(rs, 12)); - record.setHour8(getShort(rs, 13)); - record.setHour9(getShort(rs, 14)); - record.setHour10(getShort(rs, 15)); - record.setHour11(getShort(rs, 16)); - record.setHour12(getShort(rs, 17)); - record.setHour13(getShort(rs, 18)); - record.setHour14(getShort(rs, 19)); - record.setHour15(getShort(rs, 20)); - record.setHour16(getShort(rs, 21)); - record.setHour17(getShort(rs, 22)); - record.setHour18(getShort(rs, 23)); - record.setHour19(getShort(rs, 24)); - record.setHour20(getShort(rs, 25)); - record.setHour21(getShort(rs, 26)); - record.setHour22(getShort(rs, 27)); - record.setHour23(getShort(rs, 28)); - record.setHour24(getShort(rs, 29)); - - // add this HourlyPCRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HourlyPCRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HourlyPCRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HourlyPCRecord record = null; - - // create a List to hold HourlyPC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hourlypc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HourlyPCRecord - // and store its address in oneRecord - record = new HourlyPCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HourlyPCRecord object - - record.setLid(getString(rs, 1)); - record.setTs(getString(rs, 2)); - record.setObsdate(getDate(rs, 3)); - record.setMinute_offset(getString(rs, 4)); - record.setHourly_qc(getString(rs, 5)); - record.setHour1(getShort(rs, 6)); - record.setHour2(getShort(rs, 7)); - record.setHour3(getShort(rs, 8)); - record.setHour4(getShort(rs, 9)); - record.setHour5(getShort(rs, 10)); - record.setHour6(getShort(rs, 11)); - record.setHour7(getShort(rs, 12)); - record.setHour8(getShort(rs, 13)); - record.setHour9(getShort(rs, 14)); - record.setHour10(getShort(rs, 15)); - record.setHour11(getShort(rs, 16)); - record.setHour12(getShort(rs, 17)); - record.setHour13(getShort(rs, 18)); - record.setHour14(getShort(rs, 19)); - record.setHour15(getShort(rs, 20)); - record.setHour16(getShort(rs, 21)); - record.setHour17(getShort(rs, 22)); - record.setHour18(getShort(rs, 23)); - record.setHour19(getShort(rs, 24)); - record.setHour20(getShort(rs, 25)); - record.setHour21(getShort(rs, 26)); - record.setHour22(getShort(rs, 27)); - record.setHour23(getShort(rs, 28)); - record.setHour24(getShort(rs, 29)); - - // add this HourlyPCRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HourlyPCRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a HourlyPCRecord object and.. -//----------------------------------------------------------------- - public int insert(HourlyPCRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO hourlypc VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getTs()); - setDate(insertStatement, 3, record.getObsdate()); - setString(insertStatement, 4, record.getMinute_offset()); - setString(insertStatement, 5, record.getHourly_qc()); - setShort(insertStatement, 6, record.getHour1()); - setShort(insertStatement, 7, record.getHour2()); - setShort(insertStatement, 8, record.getHour3()); - setShort(insertStatement, 9, record.getHour4()); - setShort(insertStatement, 10, record.getHour5()); - setShort(insertStatement, 11, record.getHour6()); - setShort(insertStatement, 12, record.getHour7()); - setShort(insertStatement, 13, record.getHour8()); - setShort(insertStatement, 14, record.getHour9()); - setShort(insertStatement, 15, record.getHour10()); - setShort(insertStatement, 16, record.getHour11()); - setShort(insertStatement, 17, record.getHour12()); - setShort(insertStatement, 18, record.getHour13()); - setShort(insertStatement, 19, record.getHour14()); - setShort(insertStatement, 20, record.getHour15()); - setShort(insertStatement, 21, record.getHour16()); - setShort(insertStatement, 22, record.getHour17()); - setShort(insertStatement, 23, record.getHour18()); - setShort(insertStatement, 24, record.getHour19()); - setShort(insertStatement, 25, record.getHour20()); - setShort(insertStatement, 26, record.getHour21()); - setShort(insertStatement, 27, record.getHour22()); - setShort(insertStatement, 28, record.getHour23()); - setShort(insertStatement, 29, record.getHour24()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hourlypc " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HourlyPCRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HourlyPCRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hourlypc SET lid = ?, ts = ?, obsdate = ?, minute_offset = ?, hourly_qc = ?, hour1 = ?, hour2 = ?, hour3 = ?, hour4 = ?, hour5 = ?, hour6 = ?, hour7 = ?, hour8 = ?, hour9 = ?, hour10 = ?, hour11 = ?, hour12 = ?, hour13 = ?, hour14 = ?, hour15 = ?, hour16 = ?, hour17 = ?, hour18 = ?, hour19 = ?, hour20 = ?, hour21 = ?, hour22 = ?, hour23 = ?, hour24 = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getTs()); - setDate(updateStatement, 3, record.getObsdate()); - setString(updateStatement, 4, record.getMinute_offset()); - setString(updateStatement, 5, record.getHourly_qc()); - setShort(updateStatement, 6, record.getHour1()); - setShort(updateStatement, 7, record.getHour2()); - setShort(updateStatement, 8, record.getHour3()); - setShort(updateStatement, 9, record.getHour4()); - setShort(updateStatement, 10, record.getHour5()); - setShort(updateStatement, 11, record.getHour6()); - setShort(updateStatement, 12, record.getHour7()); - setShort(updateStatement, 13, record.getHour8()); - setShort(updateStatement, 14, record.getHour9()); - setShort(updateStatement, 15, record.getHour10()); - setShort(updateStatement, 16, record.getHour11()); - setShort(updateStatement, 17, record.getHour12()); - setShort(updateStatement, 18, record.getHour13()); - setShort(updateStatement, 19, record.getHour14()); - setShort(updateStatement, 20, record.getHour15()); - setShort(updateStatement, 21, record.getHour16()); - setShort(updateStatement, 22, record.getHour17()); - setShort(updateStatement, 23, record.getHour18()); - setShort(updateStatement, 24, record.getHour19()); - setShort(updateStatement, 25, record.getHour20()); - setShort(updateStatement, 26, record.getHour21()); - setShort(updateStatement, 27, record.getHour22()); - setShort(updateStatement, 28, record.getHour23()); - setShort(updateStatement, 29, record.getHour24()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(HourlyPCRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hourlypc " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HourlyPCRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HourlyPCRecord oldRecord, HourlyPCRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hourlypc SET lid = ?, ts = ?, obsdate = ?, minute_offset = ?, hourly_qc = ?, hour1 = ?, hour2 = ?, hour3 = ?, hour4 = ?, hour5 = ?, hour6 = ?, hour7 = ?, hour8 = ?, hour9 = ?, hour10 = ?, hour11 = ?, hour12 = ?, hour13 = ?, hour14 = ?, hour15 = ?, hour16 = ?, hour17 = ?, hour18 = ?, hour19 = ?, hour20 = ?, hour21 = ?, hour22 = ?, hour23 = ?, hour24 = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getTs()); - setDate(updateStatement, 3, newRecord.getObsdate()); - setString(updateStatement, 4, newRecord.getMinute_offset()); - setString(updateStatement, 5, newRecord.getHourly_qc()); - setShort(updateStatement, 6, newRecord.getHour1()); - setShort(updateStatement, 7, newRecord.getHour2()); - setShort(updateStatement, 8, newRecord.getHour3()); - setShort(updateStatement, 9, newRecord.getHour4()); - setShort(updateStatement, 10, newRecord.getHour5()); - setShort(updateStatement, 11, newRecord.getHour6()); - setShort(updateStatement, 12, newRecord.getHour7()); - setShort(updateStatement, 13, newRecord.getHour8()); - setShort(updateStatement, 14, newRecord.getHour9()); - setShort(updateStatement, 15, newRecord.getHour10()); - setShort(updateStatement, 16, newRecord.getHour11()); - setShort(updateStatement, 17, newRecord.getHour12()); - setShort(updateStatement, 18, newRecord.getHour13()); - setShort(updateStatement, 19, newRecord.getHour14()); - setShort(updateStatement, 20, newRecord.getHour15()); - setShort(updateStatement, 21, newRecord.getHour16()); - setShort(updateStatement, 22, newRecord.getHour17()); - setShort(updateStatement, 23, newRecord.getHour18()); - setShort(updateStatement, 24, newRecord.getHour19()); - setShort(updateStatement, 25, newRecord.getHour20()); - setShort(updateStatement, 26, newRecord.getHour21()); - setShort(updateStatement, 27, newRecord.getHour22()); - setShort(updateStatement, 28, newRecord.getHour23()); - setShort(updateStatement, 29, newRecord.getHour24()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a HourlyPCRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(HourlyPCRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - HourlyPCRecord oldRecord = (HourlyPCRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of HourlyPCTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPPRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPPRecord.java deleted file mode 100644 index c078c467db..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPPRecord.java +++ /dev/null @@ -1,547 +0,0 @@ -// filename: HourlyPPRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// HourlyPP table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HourlyPPRecord extends DbRecord -{ - private String lid; - - private String ts; - - private long obsdate; - - private String minute_offset; - - private String hourly_qc; - - private short hour1; - - private short hour2; - - private short hour3; - - private short hour4; - - private short hour5; - - private short hour6; - - private short hour7; - - private short hour8; - - private short hour9; - - private short hour10; - - private short hour11; - - private short hour12; - - private short hour13; - - private short hour14; - - private short hour15; - - private short hour16; - - private short hour17; - - private short hour18; - - private short hour19; - - private short hour20; - - private short hour21; - - private short hour22; - - private short hour23; - - private short hour24; - - private short sixhr06; - - private short sixhr12; - - private short sixhr18; - - private short sixhr24; - - private String sixhrqc; - - private String sixhroffset; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HourlyPPRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HourlyPPRecord(HourlyPPRecord origRecord) - { - setLid(origRecord.getLid()); - setTs(origRecord.getTs()); - setObsdate(origRecord.getObsdate()); - setMinute_offset(origRecord.getMinute_offset()); - setHourly_qc(origRecord.getHourly_qc()); - setHour1(origRecord.getHour1()); - setHour2(origRecord.getHour2()); - setHour3(origRecord.getHour3()); - setHour4(origRecord.getHour4()); - setHour5(origRecord.getHour5()); - setHour6(origRecord.getHour6()); - setHour7(origRecord.getHour7()); - setHour8(origRecord.getHour8()); - setHour9(origRecord.getHour9()); - setHour10(origRecord.getHour10()); - setHour11(origRecord.getHour11()); - setHour12(origRecord.getHour12()); - setHour13(origRecord.getHour13()); - setHour14(origRecord.getHour14()); - setHour15(origRecord.getHour15()); - setHour16(origRecord.getHour16()); - setHour17(origRecord.getHour17()); - setHour18(origRecord.getHour18()); - setHour19(origRecord.getHour19()); - setHour20(origRecord.getHour20()); - setHour21(origRecord.getHour21()); - setHour22(origRecord.getHour22()); - setHour23(origRecord.getHour23()); - setHour24(origRecord.getHour24()); - setSixhr06(origRecord.getSixhr06()); - setSixhr12(origRecord.getSixhr12()); - setSixhr18(origRecord.getSixhr18()); - setSixhr24(origRecord.getSixhr24()); - setSixhrqc(origRecord.getSixhrqc()); - setSixhroffset(origRecord.getSixhroffset()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a HourlyPP record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public long getObsdate() - { - return obsdate; - } - - public void setObsdate(long obsdate) - { - this.obsdate = obsdate ; - } - - public String getMinute_offset() - { - return minute_offset; - } - - public void setMinute_offset(String minute_offset) - { - this.minute_offset = minute_offset ; - } - - public String getHourly_qc() - { - return hourly_qc; - } - - public void setHourly_qc(String hourly_qc) - { - this.hourly_qc = hourly_qc ; - } - - public short getHour1() - { - return hour1; - } - - public void setHour1(short hour1) - { - this.hour1 = hour1 ; - } - - public short getHour2() - { - return hour2; - } - - public void setHour2(short hour2) - { - this.hour2 = hour2 ; - } - - public short getHour3() - { - return hour3; - } - - public void setHour3(short hour3) - { - this.hour3 = hour3 ; - } - - public short getHour4() - { - return hour4; - } - - public void setHour4(short hour4) - { - this.hour4 = hour4 ; - } - - public short getHour5() - { - return hour5; - } - - public void setHour5(short hour5) - { - this.hour5 = hour5 ; - } - - public short getHour6() - { - return hour6; - } - - public void setHour6(short hour6) - { - this.hour6 = hour6 ; - } - - public short getHour7() - { - return hour7; - } - - public void setHour7(short hour7) - { - this.hour7 = hour7 ; - } - - public short getHour8() - { - return hour8; - } - - public void setHour8(short hour8) - { - this.hour8 = hour8 ; - } - - public short getHour9() - { - return hour9; - } - - public void setHour9(short hour9) - { - this.hour9 = hour9 ; - } - - public short getHour10() - { - return hour10; - } - - public void setHour10(short hour10) - { - this.hour10 = hour10 ; - } - - public short getHour11() - { - return hour11; - } - - public void setHour11(short hour11) - { - this.hour11 = hour11 ; - } - - public short getHour12() - { - return hour12; - } - - public void setHour12(short hour12) - { - this.hour12 = hour12 ; - } - - public short getHour13() - { - return hour13; - } - - public void setHour13(short hour13) - { - this.hour13 = hour13 ; - } - - public short getHour14() - { - return hour14; - } - - public void setHour14(short hour14) - { - this.hour14 = hour14 ; - } - - public short getHour15() - { - return hour15; - } - - public void setHour15(short hour15) - { - this.hour15 = hour15 ; - } - - public short getHour16() - { - return hour16; - } - - public void setHour16(short hour16) - { - this.hour16 = hour16 ; - } - - public short getHour17() - { - return hour17; - } - - public void setHour17(short hour17) - { - this.hour17 = hour17 ; - } - - public short getHour18() - { - return hour18; - } - - public void setHour18(short hour18) - { - this.hour18 = hour18 ; - } - - public short getHour19() - { - return hour19; - } - - public void setHour19(short hour19) - { - this.hour19 = hour19 ; - } - - public short getHour20() - { - return hour20; - } - - public void setHour20(short hour20) - { - this.hour20 = hour20 ; - } - - public short getHour21() - { - return hour21; - } - - public void setHour21(short hour21) - { - this.hour21 = hour21 ; - } - - public short getHour22() - { - return hour22; - } - - public void setHour22(short hour22) - { - this.hour22 = hour22 ; - } - - public short getHour23() - { - return hour23; - } - - public void setHour23(short hour23) - { - this.hour23 = hour23 ; - } - - public short getHour24() - { - return hour24; - } - - public void setHour24(short hour24) - { - this.hour24 = hour24 ; - } - - public short getSixhr06() - { - return sixhr06; - } - - public void setSixhr06(short sixhr06) - { - this.sixhr06 = sixhr06 ; - } - - public short getSixhr12() - { - return sixhr12; - } - - public void setSixhr12(short sixhr12) - { - this.sixhr12 = sixhr12 ; - } - - public short getSixhr18() - { - return sixhr18; - } - - public void setSixhr18(short sixhr18) - { - this.sixhr18 = sixhr18 ; - } - - public short getSixhr24() - { - return sixhr24; - } - - public void setSixhr24(short sixhr24) - { - this.sixhr24 = sixhr24 ; - } - - public String getSixhrqc() - { - return sixhrqc; - } - - public void setSixhrqc(String sixhrqc) - { - this.sixhrqc = sixhrqc ; - } - - public String getSixhroffset() - { - return sixhroffset; - } - - public void setSixhroffset(String sixhroffset) - { - this.sixhroffset = sixhroffset ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ts = '" + ts + "'" - + " AND obsdate = '" + getDateStringFromLongTime(obsdate) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getTs() + " " + - getDateStringFromLongTime(getObsdate()) + " " + - getMinute_offset() + " " + - getHourly_qc() + " " + - getHour1() + " " + - getHour2() + " " + - getHour3() + " " + - getHour4() + " " + - getHour5() + " " + - getHour6() + " " + - getHour7() + " " + - getHour8() + " " + - getHour9() + " " + - getHour10() + " " + - getHour11() + " " + - getHour12() + " " + - getHour13() + " " + - getHour14() + " " + - getHour15() + " " + - getHour16() + " " + - getHour17() + " " + - getHour18() + " " + - getHour19() + " " + - getHour20() + " " + - getHour21() + " " + - getHour22() + " " + - getHour23() + " " + - getHour24() + " " + - getSixhr06() + " " + - getSixhr12() + " " + - getSixhr18() + " " + - getSixhr24() + " " + - getSixhrqc() + " " + - getSixhroffset() + " " + - "" ; - return outString; - } // end toString() -} // end of HourlyPPRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPPTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPPTable.java deleted file mode 100644 index 819e1ee1ed..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HourlyPPTable.java +++ /dev/null @@ -1,416 +0,0 @@ -// filename: HourlyPPTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hourlypp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HourlyPPTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HourlyPPTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HourlyPPTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hourlypp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HourlyPPRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HourlyPPRecord record = null; - - // create a List to hold HourlyPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hourlypp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HourlyPPRecord - // and store its address in oneRecord - record = new HourlyPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HourlyPPRecord object - - record.setLid(getString(rs, 1)); - record.setTs(getString(rs, 2)); - record.setObsdate(getDate(rs, 3)); - record.setMinute_offset(getString(rs, 4)); - record.setHourly_qc(getString(rs, 5)); - record.setHour1(getShort(rs, 6)); - record.setHour2(getShort(rs, 7)); - record.setHour3(getShort(rs, 8)); - record.setHour4(getShort(rs, 9)); - record.setHour5(getShort(rs, 10)); - record.setHour6(getShort(rs, 11)); - record.setHour7(getShort(rs, 12)); - record.setHour8(getShort(rs, 13)); - record.setHour9(getShort(rs, 14)); - record.setHour10(getShort(rs, 15)); - record.setHour11(getShort(rs, 16)); - record.setHour12(getShort(rs, 17)); - record.setHour13(getShort(rs, 18)); - record.setHour14(getShort(rs, 19)); - record.setHour15(getShort(rs, 20)); - record.setHour16(getShort(rs, 21)); - record.setHour17(getShort(rs, 22)); - record.setHour18(getShort(rs, 23)); - record.setHour19(getShort(rs, 24)); - record.setHour20(getShort(rs, 25)); - record.setHour21(getShort(rs, 26)); - record.setHour22(getShort(rs, 27)); - record.setHour23(getShort(rs, 28)); - record.setHour24(getShort(rs, 29)); - record.setSixhr06(getShort(rs, 30)); - record.setSixhr12(getShort(rs, 31)); - record.setSixhr18(getShort(rs, 32)); - record.setSixhr24(getShort(rs, 33)); - record.setSixhrqc(getString(rs, 34)); - record.setSixhroffset(getString(rs, 35)); - - // add this HourlyPPRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HourlyPPRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HourlyPPRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HourlyPPRecord record = null; - - // create a List to hold HourlyPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hourlypp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HourlyPPRecord - // and store its address in oneRecord - record = new HourlyPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HourlyPPRecord object - - record.setLid(getString(rs, 1)); - record.setTs(getString(rs, 2)); - record.setObsdate(getDate(rs, 3)); - record.setMinute_offset(getString(rs, 4)); - record.setHourly_qc(getString(rs, 5)); - record.setHour1(getShort(rs, 6)); - record.setHour2(getShort(rs, 7)); - record.setHour3(getShort(rs, 8)); - record.setHour4(getShort(rs, 9)); - record.setHour5(getShort(rs, 10)); - record.setHour6(getShort(rs, 11)); - record.setHour7(getShort(rs, 12)); - record.setHour8(getShort(rs, 13)); - record.setHour9(getShort(rs, 14)); - record.setHour10(getShort(rs, 15)); - record.setHour11(getShort(rs, 16)); - record.setHour12(getShort(rs, 17)); - record.setHour13(getShort(rs, 18)); - record.setHour14(getShort(rs, 19)); - record.setHour15(getShort(rs, 20)); - record.setHour16(getShort(rs, 21)); - record.setHour17(getShort(rs, 22)); - record.setHour18(getShort(rs, 23)); - record.setHour19(getShort(rs, 24)); - record.setHour20(getShort(rs, 25)); - record.setHour21(getShort(rs, 26)); - record.setHour22(getShort(rs, 27)); - record.setHour23(getShort(rs, 28)); - record.setHour24(getShort(rs, 29)); - record.setSixhr06(getShort(rs, 30)); - record.setSixhr12(getShort(rs, 31)); - record.setSixhr18(getShort(rs, 32)); - record.setSixhr24(getShort(rs, 33)); - record.setSixhrqc(getString(rs, 34)); - record.setSixhroffset(getString(rs, 35)); - - // add this HourlyPPRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HourlyPPRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a HourlyPPRecord object and.. -//----------------------------------------------------------------- - public int insert(HourlyPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO hourlypp VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getTs()); - setDate(insertStatement, 3, record.getObsdate()); - setString(insertStatement, 4, record.getMinute_offset()); - setString(insertStatement, 5, record.getHourly_qc()); - setShort(insertStatement, 6, record.getHour1()); - setShort(insertStatement, 7, record.getHour2()); - setShort(insertStatement, 8, record.getHour3()); - setShort(insertStatement, 9, record.getHour4()); - setShort(insertStatement, 10, record.getHour5()); - setShort(insertStatement, 11, record.getHour6()); - setShort(insertStatement, 12, record.getHour7()); - setShort(insertStatement, 13, record.getHour8()); - setShort(insertStatement, 14, record.getHour9()); - setShort(insertStatement, 15, record.getHour10()); - setShort(insertStatement, 16, record.getHour11()); - setShort(insertStatement, 17, record.getHour12()); - setShort(insertStatement, 18, record.getHour13()); - setShort(insertStatement, 19, record.getHour14()); - setShort(insertStatement, 20, record.getHour15()); - setShort(insertStatement, 21, record.getHour16()); - setShort(insertStatement, 22, record.getHour17()); - setShort(insertStatement, 23, record.getHour18()); - setShort(insertStatement, 24, record.getHour19()); - setShort(insertStatement, 25, record.getHour20()); - setShort(insertStatement, 26, record.getHour21()); - setShort(insertStatement, 27, record.getHour22()); - setShort(insertStatement, 28, record.getHour23()); - setShort(insertStatement, 29, record.getHour24()); - setShort(insertStatement, 30, record.getSixhr06()); - setShort(insertStatement, 31, record.getSixhr12()); - setShort(insertStatement, 32, record.getSixhr18()); - setShort(insertStatement, 33, record.getSixhr24()); - setString(insertStatement, 34, record.getSixhrqc()); - setString(insertStatement, 35, record.getSixhroffset()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hourlypp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HourlyPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HourlyPPRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hourlypp SET lid = ?, ts = ?, obsdate = ?, minute_offset = ?, hourly_qc = ?, hour1 = ?, hour2 = ?, hour3 = ?, hour4 = ?, hour5 = ?, hour6 = ?, hour7 = ?, hour8 = ?, hour9 = ?, hour10 = ?, hour11 = ?, hour12 = ?, hour13 = ?, hour14 = ?, hour15 = ?, hour16 = ?, hour17 = ?, hour18 = ?, hour19 = ?, hour20 = ?, hour21 = ?, hour22 = ?, hour23 = ?, hour24 = ?, sixhr06 = ?, sixhr12 = ?, sixhr18 = ?, sixhr24 = ?, sixhrqc = ?, sixhroffset = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getTs()); - setDate(updateStatement, 3, record.getObsdate()); - setString(updateStatement, 4, record.getMinute_offset()); - setString(updateStatement, 5, record.getHourly_qc()); - setShort(updateStatement, 6, record.getHour1()); - setShort(updateStatement, 7, record.getHour2()); - setShort(updateStatement, 8, record.getHour3()); - setShort(updateStatement, 9, record.getHour4()); - setShort(updateStatement, 10, record.getHour5()); - setShort(updateStatement, 11, record.getHour6()); - setShort(updateStatement, 12, record.getHour7()); - setShort(updateStatement, 13, record.getHour8()); - setShort(updateStatement, 14, record.getHour9()); - setShort(updateStatement, 15, record.getHour10()); - setShort(updateStatement, 16, record.getHour11()); - setShort(updateStatement, 17, record.getHour12()); - setShort(updateStatement, 18, record.getHour13()); - setShort(updateStatement, 19, record.getHour14()); - setShort(updateStatement, 20, record.getHour15()); - setShort(updateStatement, 21, record.getHour16()); - setShort(updateStatement, 22, record.getHour17()); - setShort(updateStatement, 23, record.getHour18()); - setShort(updateStatement, 24, record.getHour19()); - setShort(updateStatement, 25, record.getHour20()); - setShort(updateStatement, 26, record.getHour21()); - setShort(updateStatement, 27, record.getHour22()); - setShort(updateStatement, 28, record.getHour23()); - setShort(updateStatement, 29, record.getHour24()); - setShort(updateStatement, 30, record.getSixhr06()); - setShort(updateStatement, 31, record.getSixhr12()); - setShort(updateStatement, 32, record.getSixhr18()); - setShort(updateStatement, 33, record.getSixhr24()); - setString(updateStatement, 34, record.getSixhrqc()); - setString(updateStatement, 35, record.getSixhroffset()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(HourlyPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hourlypp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HourlyPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HourlyPPRecord oldRecord, HourlyPPRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hourlypp SET lid = ?, ts = ?, obsdate = ?, minute_offset = ?, hourly_qc = ?, hour1 = ?, hour2 = ?, hour3 = ?, hour4 = ?, hour5 = ?, hour6 = ?, hour7 = ?, hour8 = ?, hour9 = ?, hour10 = ?, hour11 = ?, hour12 = ?, hour13 = ?, hour14 = ?, hour15 = ?, hour16 = ?, hour17 = ?, hour18 = ?, hour19 = ?, hour20 = ?, hour21 = ?, hour22 = ?, hour23 = ?, hour24 = ?, sixhr06 = ?, sixhr12 = ?, sixhr18 = ?, sixhr24 = ?, sixhrqc = ?, sixhroffset = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getTs()); - setDate(updateStatement, 3, newRecord.getObsdate()); - setString(updateStatement, 4, newRecord.getMinute_offset()); - setString(updateStatement, 5, newRecord.getHourly_qc()); - setShort(updateStatement, 6, newRecord.getHour1()); - setShort(updateStatement, 7, newRecord.getHour2()); - setShort(updateStatement, 8, newRecord.getHour3()); - setShort(updateStatement, 9, newRecord.getHour4()); - setShort(updateStatement, 10, newRecord.getHour5()); - setShort(updateStatement, 11, newRecord.getHour6()); - setShort(updateStatement, 12, newRecord.getHour7()); - setShort(updateStatement, 13, newRecord.getHour8()); - setShort(updateStatement, 14, newRecord.getHour9()); - setShort(updateStatement, 15, newRecord.getHour10()); - setShort(updateStatement, 16, newRecord.getHour11()); - setShort(updateStatement, 17, newRecord.getHour12()); - setShort(updateStatement, 18, newRecord.getHour13()); - setShort(updateStatement, 19, newRecord.getHour14()); - setShort(updateStatement, 20, newRecord.getHour15()); - setShort(updateStatement, 21, newRecord.getHour16()); - setShort(updateStatement, 22, newRecord.getHour17()); - setShort(updateStatement, 23, newRecord.getHour18()); - setShort(updateStatement, 24, newRecord.getHour19()); - setShort(updateStatement, 25, newRecord.getHour20()); - setShort(updateStatement, 26, newRecord.getHour21()); - setShort(updateStatement, 27, newRecord.getHour22()); - setShort(updateStatement, 28, newRecord.getHour23()); - setShort(updateStatement, 29, newRecord.getHour24()); - setShort(updateStatement, 30, newRecord.getSixhr06()); - setShort(updateStatement, 31, newRecord.getSixhr12()); - setShort(updateStatement, 32, newRecord.getSixhr18()); - setShort(updateStatement, 33, newRecord.getSixhr24()); - setString(updateStatement, 34, newRecord.getSixhrqc()); - setString(updateStatement, 35, newRecord.getSixhroffset()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a HourlyPPRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(HourlyPPRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - HourlyPPRecord oldRecord = (HourlyPPRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of HourlyPPTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HsaRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HsaRecord.java deleted file mode 100644 index 2e3f221d3d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HsaRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: HsaRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Hsa table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HsaRecord extends DbRecord -{ - private String hsa; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HsaRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HsaRecord(HsaRecord origRecord) - { - setHsa(origRecord.getHsa()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Hsa record - - //----------------------------------------------------------------- - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE hsa = '" + hsa + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getHsa() + " " + - "" ; - return outString; - } // end toString() -} // end of HsaRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HsaTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HsaTable.java deleted file mode 100644 index 3a8331b7bc..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HsaTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: HsaTable.java -// author : DBGEN -// created : Tue May 31 17:52:23 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hsa table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HsaTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HsaTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HsaTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hsa"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HsaRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HsaRecord record = null; - - // create a List to hold Hsa Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hsa " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HsaRecord - // and store its address in oneRecord - record = new HsaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HsaRecord object - - record.setHsa(getString(rs, 1)); - - // add this HsaRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HsaRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HsaRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HsaRecord record = null; - - // create a List to hold Hsa Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hsa " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HsaRecord - // and store its address in oneRecord - record = new HsaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HsaRecord object - - record.setHsa(getString(rs, 1)); - - // add this HsaRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HsaRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a HsaRecord object and.. -//----------------------------------------------------------------- - public int insert(HsaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO hsa VALUES (? )"); - - setString(insertStatement, 1, record.getHsa()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hsa " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HsaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HsaRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hsa SET hsa = ? " + where ); - - setString(updateStatement, 1, record.getHsa()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(HsaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hsa " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HsaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HsaRecord oldRecord, HsaRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hsa SET hsa = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getHsa()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a HsaRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(HsaRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - HsaRecord oldRecord = (HsaRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of HsaTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HvStationRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HvStationRecord.java deleted file mode 100644 index a9b3b62fae..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HvStationRecord.java +++ /dev/null @@ -1,240 +0,0 @@ -// This is a view record ! -// filename: HvStationRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// HvStation table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HvStationRecord extends DbRecord -{ - private String lid; - - private String name; - - private double lat; - - private double lon; - - private String stream_name; - - private String primary_pe; - - private double flood_stage; - - private double flood_flow; - - private double action_stage; - - private double action_flow; - - private String disp_class; - - private String is_dcp; - - private String is_observer; - - private String telem_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HvStationRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HvStationRecord(HvStationRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setStream_name(origRecord.getStream_name()); - setPrimary_pe(origRecord.getPrimary_pe()); - setFlood_stage(origRecord.getFlood_stage()); - setFlood_flow(origRecord.getFlood_flow()); - setAction_stage(origRecord.getAction_stage()); - setAction_flow(origRecord.getAction_flow()); - setDisp_class(origRecord.getDisp_class()); - setIs_dcp(origRecord.getIs_dcp()); - setIs_observer(origRecord.getIs_observer()); - setTelem_type(origRecord.getTelem_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a HvStation record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public String getStream_name() - { - return stream_name; - } - - public void setStream_name(String stream_name) - { - this.stream_name = stream_name ; - } - - public String getPrimary_pe() - { - return primary_pe; - } - - public void setPrimary_pe(String primary_pe) - { - this.primary_pe = primary_pe ; - } - - public double getFlood_stage() - { - return flood_stage; - } - - public void setFlood_stage(double flood_stage) - { - this.flood_stage = flood_stage ; - } - - public double getFlood_flow() - { - return flood_flow; - } - - public void setFlood_flow(double flood_flow) - { - this.flood_flow = flood_flow ; - } - - public double getAction_stage() - { - return action_stage; - } - - public void setAction_stage(double action_stage) - { - this.action_stage = action_stage ; - } - - public double getAction_flow() - { - return action_flow; - } - - public void setAction_flow(double action_flow) - { - this.action_flow = action_flow ; - } - - public String getDisp_class() - { - return disp_class; - } - - public void setDisp_class(String disp_class) - { - this.disp_class = disp_class ; - } - - public String getIs_dcp() - { - return is_dcp; - } - - public void setIs_dcp(String is_dcp) - { - this.is_dcp = is_dcp ; - } - - public String getIs_observer() - { - return is_observer; - } - - public void setIs_observer(String is_observer) - { - this.is_observer = is_observer ; - } - - public String getTelem_type() - { - return telem_type; - } - - public void setTelem_type(String telem_type) - { - this.telem_type = telem_type ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getLat() + " " + - getLon() + " " + - getStream_name() + " " + - getPrimary_pe() + " " + - getFlood_stage() + " " + - getFlood_flow() + " " + - getAction_stage() + " " + - getAction_flow() + " " + - getDisp_class() + " " + - getIs_dcp() + " " + - getIs_observer() + " " + - getTelem_type() + " " + - "" ; - return outString; - } // end toString() -} // end of HvStationRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HvStationView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HvStationView.java deleted file mode 100644 index 01049bed0d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HvStationView.java +++ /dev/null @@ -1,157 +0,0 @@ -// filename: HvStationView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hvstation table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HvStationView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HvStationTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HvStationView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hvstation"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HvStationRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HvStationRecord record = null; - - // create a List to hold HvStation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hvstation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HvStationRecord - // and store its address in oneRecord - record = new HvStationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HvStationRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setStream_name(getString(rs, 5)); - record.setPrimary_pe(getString(rs, 6)); - record.setFlood_stage(getDouble(rs, 7)); - record.setFlood_flow(getDouble(rs, 8)); - record.setAction_stage(getDouble(rs, 9)); - record.setAction_flow(getDouble(rs, 10)); - record.setDisp_class(getString(rs, 11)); - record.setIs_dcp(getString(rs, 12)); - record.setIs_observer(getString(rs, 13)); - record.setTelem_type(getString(rs, 14)); - - // add this HvStationRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HvStationRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HvStationRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HvStationRecord record = null; - - // create a List to hold HvStation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hvstation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HvStationRecord - // and store its address in oneRecord - record = new HvStationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HvStationRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setStream_name(getString(rs, 5)); - record.setPrimary_pe(getString(rs, 6)); - record.setFlood_stage(getDouble(rs, 7)); - record.setFlood_flow(getDouble(rs, 8)); - record.setAction_stage(getDouble(rs, 9)); - record.setAction_flow(getDouble(rs, 10)); - record.setDisp_class(getString(rs, 11)); - record.setIs_dcp(getString(rs, 12)); - record.setIs_observer(getString(rs, 13)); - record.setTelem_type(getString(rs, 14)); - - // add this HvStationRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HvStationRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of HvStationTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HwStagesRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HwStagesRecord.java deleted file mode 100644 index fdff58ada2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HwStagesRecord.java +++ /dev/null @@ -1,100 +0,0 @@ -// This is a view record ! -// filename: HwStagesRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// HwStages table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HwStagesRecord extends DbRecord -{ - private String lid; - - private double fs; - - private double wstg; - - private double ms; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HwStagesRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HwStagesRecord(HwStagesRecord origRecord) - { - setLid(origRecord.getLid()); - setFs(origRecord.getFs()); - setWstg(origRecord.getWstg()); - setMs(origRecord.getMs()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a HwStages record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getFs() - { - return fs; - } - - public void setFs(double fs) - { - this.fs = fs ; - } - - public double getWstg() - { - return wstg; - } - - public void setWstg(double wstg) - { - this.wstg = wstg ; - } - - public double getMs() - { - return ms; - } - - public void setMs(double ms) - { - this.ms = ms ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getFs() + " " + - getWstg() + " " + - getMs() + " " + - "" ; - return outString; - } // end toString() -} // end of HwStagesRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HwStagesView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HwStagesView.java deleted file mode 100644 index 7db6ca0966..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HwStagesView.java +++ /dev/null @@ -1,137 +0,0 @@ -// filename: HwStagesView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hwstages table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HwStagesView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HwStagesTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HwStagesView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hwstages"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HwStagesRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HwStagesRecord record = null; - - // create a List to hold HwStages Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hwstages " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HwStagesRecord - // and store its address in oneRecord - record = new HwStagesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HwStagesRecord object - - record.setLid(getString(rs, 1)); - record.setFs(getDouble(rs, 2)); - record.setWstg(getDouble(rs, 3)); - record.setMs(getDouble(rs, 4)); - - // add this HwStagesRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HwStagesRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HwStagesRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HwStagesRecord record = null; - - // create a List to hold HwStages Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hwstages " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HwStagesRecord - // and store its address in oneRecord - record = new HwStagesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HwStagesRecord object - - record.setLid(getString(rs, 1)); - record.setFs(getDouble(rs, 2)); - record.setWstg(getDouble(rs, 3)); - record.setMs(getDouble(rs, 4)); - - // add this HwStagesRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HwStagesRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of HwStagesTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HydrologicMethodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HydrologicMethodRecord.java deleted file mode 100644 index c0abdd463d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HydrologicMethodRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: HydrologicMethodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// HydrologicMethod table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class HydrologicMethodRecord extends DbRecord -{ - private String hydrol_method; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public HydrologicMethodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public HydrologicMethodRecord(HydrologicMethodRecord origRecord) - { - setHydrol_method(origRecord.getHydrol_method()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a HydrologicMethod record - - //----------------------------------------------------------------- - public String getHydrol_method() - { - return hydrol_method; - } - - public void setHydrol_method(String hydrol_method) - { - this.hydrol_method = hydrol_method ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE hydrol_method = '" + hydrol_method + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getHydrol_method() + " " + - "" ; - return outString; - } // end toString() -} // end of HydrologicMethodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HydrologicMethodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HydrologicMethodTable.java deleted file mode 100644 index 4c5ed8efb2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/HydrologicMethodTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: HydrologicMethodTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// hydrologicmethod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class HydrologicMethodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// HydrologicMethodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public HydrologicMethodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("hydrologicmethod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of HydrologicMethodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - HydrologicMethodRecord record = null; - - // create a List to hold HydrologicMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hydrologicmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HydrologicMethodRecord - // and store its address in oneRecord - record = new HydrologicMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HydrologicMethodRecord object - - record.setHydrol_method(getString(rs, 1)); - - // add this HydrologicMethodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the HydrologicMethodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of HydrologicMethodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - HydrologicMethodRecord record = null; - - // create a List to hold HydrologicMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM hydrologicmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a HydrologicMethodRecord - // and store its address in oneRecord - record = new HydrologicMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a HydrologicMethodRecord object - - record.setHydrol_method(getString(rs, 1)); - - // add this HydrologicMethodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the HydrologicMethodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a HydrologicMethodRecord object and.. -//----------------------------------------------------------------- - public int insert(HydrologicMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO hydrologicmethod VALUES (? )"); - - setString(insertStatement, 1, record.getHydrol_method()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hydrologicmethod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HydrologicMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HydrologicMethodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hydrologicmethod SET hydrol_method = ? " + where ); - - setString(updateStatement, 1, record.getHydrol_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(HydrologicMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM hydrologicmethod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a HydrologicMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(HydrologicMethodRecord oldRecord, HydrologicMethodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE hydrologicmethod SET hydrol_method = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getHydrol_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a HydrologicMethodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(HydrologicMethodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - HydrologicMethodRecord oldRecord = (HydrologicMethodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of HydrologicMethodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IceRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IceRecord.java deleted file mode 100644 index 935f1b2ded..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IceRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: IceRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Ice table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class IceRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public IceRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public IceRecord(IceRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Ice record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of IceRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IceTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IceTable.java deleted file mode 100644 index 0f89e37a61..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IceTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: IceTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// ice table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class IceTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// IceTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public IceTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("ice"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of IceRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - IceRecord record = null; - - // create a List to hold Ice Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a IceRecord - // and store its address in oneRecord - record = new IceRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a IceRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this IceRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the IceRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of IceRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - IceRecord record = null; - - // create a List to hold Ice Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a IceRecord - // and store its address in oneRecord - record = new IceRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a IceRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this IceRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the IceRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a IceRecord object and.. -//----------------------------------------------------------------- - public int insert(IceRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO ice VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ice " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a IceRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(IceRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ice SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(IceRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ice " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a IceRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(IceRecord oldRecord, IceRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ice SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a IceRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(IceRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - IceRecord oldRecord = (IceRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of IceTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IngestFilterRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IngestFilterRecord.java deleted file mode 100644 index 7c0ad926a6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IngestFilterRecord.java +++ /dev/null @@ -1,185 +0,0 @@ -// filename: IngestFilterRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// IngestFilter table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class IngestFilterRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private short ts_rank; - - private String ingest; - - private String ofs_input; - - private String stg2_input; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public IngestFilterRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public IngestFilterRecord(IngestFilterRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setTs_rank(origRecord.getTs_rank()); - setIngest(origRecord.getIngest()); - setOfs_input(origRecord.getOfs_input()); - setStg2_input(origRecord.getStg2_input()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a IngestFilter record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public short getTs_rank() - { - return ts_rank; - } - - public void setTs_rank(short ts_rank) - { - this.ts_rank = ts_rank ; - } - - public String getIngest() - { - return ingest; - } - - public void setIngest(String ingest) - { - this.ingest = ingest ; - } - - public String getOfs_input() - { - return ofs_input; - } - - public void setOfs_input(String ofs_input) - { - this.ofs_input = ofs_input ; - } - - public String getStg2_input() - { - return stg2_input; - } - - public void setStg2_input(String stg2_input) - { - this.stg2_input = stg2_input ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getTs_rank() + " " + - getIngest() + " " + - getOfs_input() + " " + - getStg2_input() + " " + - "" ; - return outString; - } // end toString() -} // end of IngestFilterRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IngestFilterTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IngestFilterTable.java deleted file mode 100644 index a315f1e48c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/IngestFilterTable.java +++ /dev/null @@ -1,286 +0,0 @@ -// filename: IngestFilterTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// ingestfilter table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class IngestFilterTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// IngestFilterTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public IngestFilterTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("ingestfilter"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of IngestFilterRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - IngestFilterRecord record = null; - - // create a List to hold IngestFilter Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ingestfilter " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a IngestFilterRecord - // and store its address in oneRecord - record = new IngestFilterRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a IngestFilterRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setTs_rank(getShort(rs, 6)); - record.setIngest(getString(rs, 7)); - record.setOfs_input(getString(rs, 8)); - record.setStg2_input(getString(rs, 9)); - - // add this IngestFilterRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the IngestFilterRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of IngestFilterRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - IngestFilterRecord record = null; - - // create a List to hold IngestFilter Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ingestfilter " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a IngestFilterRecord - // and store its address in oneRecord - record = new IngestFilterRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a IngestFilterRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setTs_rank(getShort(rs, 6)); - record.setIngest(getString(rs, 7)); - record.setOfs_input(getString(rs, 8)); - record.setStg2_input(getString(rs, 9)); - - // add this IngestFilterRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the IngestFilterRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a IngestFilterRecord object and.. -//----------------------------------------------------------------- - public int insert(IngestFilterRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO ingestfilter VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setShort(insertStatement, 6, record.getTs_rank()); - setString(insertStatement, 7, record.getIngest()); - setString(insertStatement, 8, record.getOfs_input()); - setString(insertStatement, 9, record.getStg2_input()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ingestfilter " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a IngestFilterRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(IngestFilterRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ingestfilter SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, ts_rank = ?, ingest = ?, ofs_input = ?, stg2_input = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setShort(updateStatement, 6, record.getTs_rank()); - setString(updateStatement, 7, record.getIngest()); - setString(updateStatement, 8, record.getOfs_input()); - setString(updateStatement, 9, record.getStg2_input()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(IngestFilterRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ingestfilter " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a IngestFilterRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(IngestFilterRecord oldRecord, IngestFilterRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ingestfilter SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, ts_rank = ?, ingest = ?, ofs_input = ?, stg2_input = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setShort(updateStatement, 6, newRecord.getTs_rank()); - setString(updateStatement, 7, newRecord.getIngest()); - setString(updateStatement, 8, newRecord.getOfs_input()); - setString(updateStatement, 9, newRecord.getStg2_input()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a IngestFilterRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(IngestFilterRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - IngestFilterRecord oldRecord = (IngestFilterRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of IngestFilterTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LWstmtRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LWstmtRecord.java deleted file mode 100644 index 9f1f780466..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LWstmtRecord.java +++ /dev/null @@ -1,170 +0,0 @@ -// filename: LWstmtRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LWstmt table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LWstmtRecord extends DbRecord -{ - private String lid; - - private String pe; - - private double lower_value; - - private double upper_value; - - private int criteria_rank; - - private String statement; - - private String lw_criteria; - - private String lw_source; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LWstmtRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LWstmtRecord(LWstmtRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setLower_value(origRecord.getLower_value()); - setUpper_value(origRecord.getUpper_value()); - setCriteria_rank(origRecord.getCriteria_rank()); - setStatement(origRecord.getStatement()); - setLw_criteria(origRecord.getLw_criteria()); - setLw_source(origRecord.getLw_source()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LWstmt record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public double getLower_value() - { - return lower_value; - } - - public void setLower_value(double lower_value) - { - this.lower_value = lower_value ; - } - - public double getUpper_value() - { - return upper_value; - } - - public void setUpper_value(double upper_value) - { - this.upper_value = upper_value ; - } - - public int getCriteria_rank() - { - return criteria_rank; - } - - public void setCriteria_rank(int criteria_rank) - { - this.criteria_rank = criteria_rank ; - } - - public String getStatement() - { - return statement; - } - - public void setStatement(String statement) - { - this.statement = statement ; - } - - public String getLw_criteria() - { - return lw_criteria; - } - - public void setLw_criteria(String lw_criteria) - { - this.lw_criteria = lw_criteria ; - } - - public String getLw_source() - { - return lw_source; - } - - public void setLw_source(String lw_source) - { - this.lw_source = lw_source ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND lower_value = '" + lower_value + "'" - + " AND criteria_rank = '" + criteria_rank + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getLower_value() + " " + - getUpper_value() + " " + - getCriteria_rank() + " " + - getStatement() + " " + - getLw_criteria() + " " + - getLw_source() + " " + - "" ; - return outString; - } // end toString() -} // end of LWstmtRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LWstmtTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LWstmtTable.java deleted file mode 100644 index 6dfac64da5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LWstmtTable.java +++ /dev/null @@ -1,281 +0,0 @@ -// filename: LWstmtTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// lwstmt table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LWstmtTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LWstmtTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LWstmtTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("lwstmt"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LWstmtRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LWstmtRecord record = null; - - // create a List to hold LWstmt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lwstmt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LWstmtRecord - // and store its address in oneRecord - record = new LWstmtRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LWstmtRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setLower_value(getDouble(rs, 3)); - record.setUpper_value(getDouble(rs, 4)); - record.setCriteria_rank(getInt(rs, 5)); - record.setStatement(getString(rs, 6)); - record.setLw_criteria(getString(rs, 7)); - record.setLw_source(getString(rs, 8)); - - // add this LWstmtRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LWstmtRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LWstmtRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LWstmtRecord record = null; - - // create a List to hold LWstmt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lwstmt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LWstmtRecord - // and store its address in oneRecord - record = new LWstmtRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LWstmtRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setLower_value(getDouble(rs, 3)); - record.setUpper_value(getDouble(rs, 4)); - record.setCriteria_rank(getInt(rs, 5)); - record.setStatement(getString(rs, 6)); - record.setLw_criteria(getString(rs, 7)); - record.setLw_source(getString(rs, 8)); - - // add this LWstmtRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LWstmtRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LWstmtRecord object and.. -//----------------------------------------------------------------- - public int insert(LWstmtRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO lwstmt VALUES (?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setDouble(insertStatement, 3, record.getLower_value()); - setDouble(insertStatement, 4, record.getUpper_value()); - setInt(insertStatement, 5, record.getCriteria_rank()); - setString(insertStatement, 6, record.getStatement()); - setString(insertStatement, 7, record.getLw_criteria()); - setString(insertStatement, 8, record.getLw_source()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lwstmt " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LWstmtRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LWstmtRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lwstmt SET lid = ?, pe = ?, lower_value = ?, upper_value = ?, criteria_rank = ?, statement = ?, lw_criteria = ?, lw_source = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setDouble(updateStatement, 3, record.getLower_value()); - setDouble(updateStatement, 4, record.getUpper_value()); - setInt(updateStatement, 5, record.getCriteria_rank()); - setString(updateStatement, 6, record.getStatement()); - setString(updateStatement, 7, record.getLw_criteria()); - setString(updateStatement, 8, record.getLw_source()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LWstmtRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lwstmt " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LWstmtRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LWstmtRecord oldRecord, LWstmtRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lwstmt SET lid = ?, pe = ?, lower_value = ?, upper_value = ?, criteria_rank = ?, statement = ?, lw_criteria = ?, lw_source = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setDouble(updateStatement, 3, newRecord.getLower_value()); - setDouble(updateStatement, 4, newRecord.getUpper_value()); - setInt(updateStatement, 5, newRecord.getCriteria_rank()); - setString(updateStatement, 6, newRecord.getStatement()); - setString(updateStatement, 7, newRecord.getLw_criteria()); - setString(updateStatement, 8, newRecord.getLw_source()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LWstmtRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LWstmtRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LWstmtRecord oldRecord = (LWstmtRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LWstmtTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LakeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LakeRecord.java deleted file mode 100644 index 6094272ad5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LakeRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: LakeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Lake table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LakeRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LakeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LakeRecord(LakeRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Lake record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of LakeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LakeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LakeTable.java deleted file mode 100644 index 639646466e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LakeTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: LakeTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// lake table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LakeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LakeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LakeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("lake"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LakeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LakeRecord record = null; - - // create a List to hold Lake Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lake " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LakeRecord - // and store its address in oneRecord - record = new LakeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LakeRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this LakeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LakeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LakeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LakeRecord record = null; - - // create a List to hold Lake Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lake " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LakeRecord - // and store its address in oneRecord - record = new LakeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LakeRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this LakeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LakeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LakeRecord object and.. -//----------------------------------------------------------------- - public int insert(LakeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO lake VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lake " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LakeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LakeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lake SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LakeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lake " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LakeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LakeRecord oldRecord, LakeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lake SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LakeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LakeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LakeRecord oldRecord = (LakeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LakeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LatestObsValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LatestObsValueRecord.java deleted file mode 100644 index b366a2c408..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LatestObsValueRecord.java +++ /dev/null @@ -1,241 +0,0 @@ -// filename: LatestObsValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LatestObsValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LatestObsValueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private short revision; - - private String shef_qual_code; - - private int quality_code; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LatestObsValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LatestObsValueRecord(LatestObsValueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setRevision(origRecord.getRevision()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LatestObsValue record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getRevision() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of LatestObsValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LatestObsValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LatestObsValueTable.java deleted file mode 100644 index c990c8767d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LatestObsValueTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: LatestObsValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// latestobsvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LatestObsValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LatestObsValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LatestObsValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("latestobsvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LatestObsValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LatestObsValueRecord record = null; - - // create a List to hold LatestObsValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM latestobsvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LatestObsValueRecord - // and store its address in oneRecord - record = new LatestObsValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LatestObsValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setRevision(getShort(rs, 8)); - record.setShef_qual_code(getString(rs, 9)); - record.setQuality_code(getInt(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this LatestObsValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LatestObsValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LatestObsValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LatestObsValueRecord record = null; - - // create a List to hold LatestObsValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM latestobsvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LatestObsValueRecord - // and store its address in oneRecord - record = new LatestObsValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LatestObsValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setRevision(getShort(rs, 8)); - record.setShef_qual_code(getString(rs, 9)); - record.setQuality_code(getInt(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this LatestObsValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LatestObsValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LatestObsValueRecord object and.. -//----------------------------------------------------------------- - public int insert(LatestObsValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO latestobsvalue VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setShort(insertStatement, 8, record.getRevision()); - setString(insertStatement, 9, record.getShef_qual_code()); - setInt(insertStatement, 10, record.getQuality_code()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM latestobsvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LatestObsValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LatestObsValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE latestobsvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, revision = ?, shef_qual_code = ?, quality_code = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setShort(updateStatement, 8, record.getRevision()); - setString(updateStatement, 9, record.getShef_qual_code()); - setInt(updateStatement, 10, record.getQuality_code()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LatestObsValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM latestobsvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LatestObsValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LatestObsValueRecord oldRecord, LatestObsValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE latestobsvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, revision = ?, shef_qual_code = ?, quality_code = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setShort(updateStatement, 8, newRecord.getRevision()); - setString(updateStatement, 9, newRecord.getShef_qual_code()); - setInt(updateStatement, 10, newRecord.getQuality_code()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LatestObsValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LatestObsValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LatestObsValueRecord oldRecord = (LatestObsValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LatestObsValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LightningRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LightningRecord.java deleted file mode 100644 index 69e53b71d4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LightningRecord.java +++ /dev/null @@ -1,113 +0,0 @@ -// filename: LightningRecord.java -// author : DBGEN -// created : Tue May 31 17:52:15 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Lightning table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LightningRecord extends DbRecord -{ - private short x_hgrid; - - private short y_hgrid; - - private long obstime; - - private short no_of_strike; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LightningRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LightningRecord(LightningRecord origRecord) - { - setX_hgrid(origRecord.getX_hgrid()); - setY_hgrid(origRecord.getY_hgrid()); - setObstime(origRecord.getObstime()); - setNo_of_strike(origRecord.getNo_of_strike()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Lightning record - - //----------------------------------------------------------------- - public short getX_hgrid() - { - return x_hgrid; - } - - public void setX_hgrid(short x_hgrid) - { - this.x_hgrid = x_hgrid ; - } - - public short getY_hgrid() - { - return y_hgrid; - } - - public void setY_hgrid(short y_hgrid) - { - this.y_hgrid = y_hgrid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getNo_of_strike() - { - return no_of_strike; - } - - public void setNo_of_strike(short no_of_strike) - { - this.no_of_strike = no_of_strike ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE x_hgrid = '" + x_hgrid + "'" - + " AND y_hgrid = '" + y_hgrid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getX_hgrid() + " " + - getY_hgrid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getNo_of_strike() + " " + - "" ; - return outString; - } // end toString() -} // end of LightningRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LightningTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LightningTable.java deleted file mode 100644 index ca3dc3db4f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LightningTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: LightningTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// lightning table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LightningTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LightningTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LightningTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("lightning"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LightningRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LightningRecord record = null; - - // create a List to hold Lightning Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lightning " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LightningRecord - // and store its address in oneRecord - record = new LightningRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LightningRecord object - - record.setX_hgrid(getShort(rs, 1)); - record.setY_hgrid(getShort(rs, 2)); - record.setObstime(getTimeStamp(rs, 3)); - record.setNo_of_strike(getShort(rs, 4)); - - // add this LightningRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LightningRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LightningRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LightningRecord record = null; - - // create a List to hold Lightning Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lightning " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LightningRecord - // and store its address in oneRecord - record = new LightningRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LightningRecord object - - record.setX_hgrid(getShort(rs, 1)); - record.setY_hgrid(getShort(rs, 2)); - record.setObstime(getTimeStamp(rs, 3)); - record.setNo_of_strike(getShort(rs, 4)); - - // add this LightningRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LightningRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LightningRecord object and.. -//----------------------------------------------------------------- - public int insert(LightningRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO lightning VALUES (?, ?, ?, ? )"); - - setShort(insertStatement, 1, record.getX_hgrid()); - setShort(insertStatement, 2, record.getY_hgrid()); - setTimeStamp(insertStatement, 3, record.getObstime()); - setShort(insertStatement, 4, record.getNo_of_strike()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lightning " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LightningRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LightningRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lightning SET x_hgrid = ?, y_hgrid = ?, obstime = ?, no_of_strike = ? " + where ); - - setShort(updateStatement, 1, record.getX_hgrid()); - setShort(updateStatement, 2, record.getY_hgrid()); - setTimeStamp(updateStatement, 3, record.getObstime()); - setShort(updateStatement, 4, record.getNo_of_strike()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LightningRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lightning " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LightningRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LightningRecord oldRecord, LightningRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lightning SET x_hgrid = ?, y_hgrid = ?, obstime = ?, no_of_strike = ? " + oldRecord.getWhereString() ); - - setShort(updateStatement, 1, newRecord.getX_hgrid()); - setShort(updateStatement, 2, newRecord.getY_hgrid()); - setTimeStamp(updateStatement, 3, newRecord.getObstime()); - setShort(updateStatement, 4, newRecord.getNo_of_strike()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LightningRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LightningRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LightningRecord oldRecord = (LightningRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LightningTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LineSegsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LineSegsRecord.java deleted file mode 100644 index 982ae4d2a9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LineSegsRecord.java +++ /dev/null @@ -1,127 +0,0 @@ -// filename: LineSegsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LineSegs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LineSegsRecord extends DbRecord -{ - private String area_id; - - private int hrap_row; - - private int hrap_beg_col; - - private int hrap_end_col; - - private double area; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LineSegsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LineSegsRecord(LineSegsRecord origRecord) - { - setArea_id(origRecord.getArea_id()); - setHrap_row(origRecord.getHrap_row()); - setHrap_beg_col(origRecord.getHrap_beg_col()); - setHrap_end_col(origRecord.getHrap_end_col()); - setArea(origRecord.getArea()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LineSegs record - - //----------------------------------------------------------------- - public String getArea_id() - { - return area_id; - } - - public void setArea_id(String area_id) - { - this.area_id = area_id ; - } - - public int getHrap_row() - { - return hrap_row; - } - - public void setHrap_row(int hrap_row) - { - this.hrap_row = hrap_row ; - } - - public int getHrap_beg_col() - { - return hrap_beg_col; - } - - public void setHrap_beg_col(int hrap_beg_col) - { - this.hrap_beg_col = hrap_beg_col ; - } - - public int getHrap_end_col() - { - return hrap_end_col; - } - - public void setHrap_end_col(int hrap_end_col) - { - this.hrap_end_col = hrap_end_col ; - } - - public double getArea() - { - return area; - } - - public void setArea(double area) - { - this.area = area ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE area_id = '" + area_id + "'" - + " AND hrap_row = '" + hrap_row + "'" - + " AND hrap_beg_col = '" + hrap_beg_col + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getArea_id() + " " + - getHrap_row() + " " + - getHrap_beg_col() + " " + - getHrap_end_col() + " " + - getArea() + " " + - "" ; - return outString; - } // end toString() -} // end of LineSegsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LineSegsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LineSegsTable.java deleted file mode 100644 index a8da41f724..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LineSegsTable.java +++ /dev/null @@ -1,266 +0,0 @@ -// filename: LineSegsTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// linesegs table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LineSegsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LineSegsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LineSegsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("linesegs"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LineSegsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LineSegsRecord record = null; - - // create a List to hold LineSegs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM linesegs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LineSegsRecord - // and store its address in oneRecord - record = new LineSegsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LineSegsRecord object - - record.setArea_id(getString(rs, 1)); - record.setHrap_row(getInt(rs, 2)); - record.setHrap_beg_col(getInt(rs, 3)); - record.setHrap_end_col(getInt(rs, 4)); - record.setArea(getDouble(rs, 5)); - - // add this LineSegsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LineSegsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LineSegsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LineSegsRecord record = null; - - // create a List to hold LineSegs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM linesegs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LineSegsRecord - // and store its address in oneRecord - record = new LineSegsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LineSegsRecord object - - record.setArea_id(getString(rs, 1)); - record.setHrap_row(getInt(rs, 2)); - record.setHrap_beg_col(getInt(rs, 3)); - record.setHrap_end_col(getInt(rs, 4)); - record.setArea(getDouble(rs, 5)); - - // add this LineSegsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LineSegsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LineSegsRecord object and.. -//----------------------------------------------------------------- - public int insert(LineSegsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO linesegs VALUES (?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getArea_id()); - setInt(insertStatement, 2, record.getHrap_row()); - setInt(insertStatement, 3, record.getHrap_beg_col()); - setInt(insertStatement, 4, record.getHrap_end_col()); - setDouble(insertStatement, 5, record.getArea()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM linesegs " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LineSegsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LineSegsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE linesegs SET area_id = ?, hrap_row = ?, hrap_beg_col = ?, hrap_end_col = ?, area = ? " + where ); - - setString(updateStatement, 1, record.getArea_id()); - setInt(updateStatement, 2, record.getHrap_row()); - setInt(updateStatement, 3, record.getHrap_beg_col()); - setInt(updateStatement, 4, record.getHrap_end_col()); - setDouble(updateStatement, 5, record.getArea()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LineSegsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM linesegs " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LineSegsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LineSegsRecord oldRecord, LineSegsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE linesegs SET area_id = ?, hrap_row = ?, hrap_beg_col = ?, hrap_end_col = ?, area = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getArea_id()); - setInt(updateStatement, 2, newRecord.getHrap_row()); - setInt(updateStatement, 3, newRecord.getHrap_beg_col()); - setInt(updateStatement, 4, newRecord.getHrap_end_col()); - setDouble(updateStatement, 5, newRecord.getArea()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LineSegsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LineSegsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LineSegsRecord oldRecord = (LineSegsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LineSegsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocAreaRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocAreaRecord.java deleted file mode 100644 index 58bf886192..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocAreaRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: LocAreaRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocArea table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocAreaRecord extends DbRecord -{ - private String lid; - - private String area; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocAreaRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocAreaRecord(LocAreaRecord origRecord) - { - setLid(origRecord.getLid()); - setArea(origRecord.getArea()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocArea record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getArea() - { - return area; - } - - public void setArea(String area) - { - this.area = area ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getArea() + " " + - "" ; - return outString; - } // end toString() -} // end of LocAreaRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocAreaTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocAreaTable.java deleted file mode 100644 index 18ec91b086..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocAreaTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: LocAreaTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locarea table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocAreaTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocAreaTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocAreaTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locarea"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocAreaRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocAreaRecord record = null; - - // create a List to hold LocArea Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locarea " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocAreaRecord - // and store its address in oneRecord - record = new LocAreaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocAreaRecord object - - record.setLid(getString(rs, 1)); - record.setArea(getString(rs, 2)); - - // add this LocAreaRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocAreaRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocAreaRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocAreaRecord record = null; - - // create a List to hold LocArea Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locarea " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocAreaRecord - // and store its address in oneRecord - record = new LocAreaRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocAreaRecord object - - record.setLid(getString(rs, 1)); - record.setArea(getString(rs, 2)); - - // add this LocAreaRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocAreaRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LocAreaRecord object and.. -//----------------------------------------------------------------- - public int insert(LocAreaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO locarea VALUES (?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getArea()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locarea " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocAreaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocAreaRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locarea SET lid = ?, area = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getArea()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LocAreaRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locarea " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocAreaRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocAreaRecord oldRecord, LocAreaRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locarea SET lid = ?, area = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getArea()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LocAreaRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LocAreaRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LocAreaRecord oldRecord = (LocAreaRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LocAreaTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocClassRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocClassRecord.java deleted file mode 100644 index 2ef755e916..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocClassRecord.java +++ /dev/null @@ -1,198 +0,0 @@ -// This is a view record ! -// filename: LocClassRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocClass table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocClassRecord extends DbRecord -{ - private String lid; - - private String name; - - private double lat; - - private double lon; - - private String wfo; - - private String hsa; - - private int post; - - private String disp_class; - - private String is_dcp; - - private String is_observer; - - private String telem_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocClassRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocClassRecord(LocClassRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setWfo(origRecord.getWfo()); - setHsa(origRecord.getHsa()); - setPost(origRecord.getPost()); - setDisp_class(origRecord.getDisp_class()); - setIs_dcp(origRecord.getIs_dcp()); - setIs_observer(origRecord.getIs_observer()); - setTelem_type(origRecord.getTelem_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocClass record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public int getPost() - { - return post; - } - - public void setPost(int post) - { - this.post = post ; - } - - public String getDisp_class() - { - return disp_class; - } - - public void setDisp_class(String disp_class) - { - this.disp_class = disp_class ; - } - - public String getIs_dcp() - { - return is_dcp; - } - - public void setIs_dcp(String is_dcp) - { - this.is_dcp = is_dcp ; - } - - public String getIs_observer() - { - return is_observer; - } - - public void setIs_observer(String is_observer) - { - this.is_observer = is_observer ; - } - - public String getTelem_type() - { - return telem_type; - } - - public void setTelem_type(String telem_type) - { - this.telem_type = telem_type ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getLat() + " " + - getLon() + " " + - getWfo() + " " + - getHsa() + " " + - getPost() + " " + - getDisp_class() + " " + - getIs_dcp() + " " + - getIs_observer() + " " + - getTelem_type() + " " + - "" ; - return outString; - } // end toString() -} // end of LocClassRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocClassView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocClassView.java deleted file mode 100644 index 04e00070c4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocClassView.java +++ /dev/null @@ -1,151 +0,0 @@ -// filename: LocClassView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locclass table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocClassView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocClassTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocClassView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locclass"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocClassRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocClassRecord record = null; - - // create a List to hold LocClass Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locclass " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocClassRecord - // and store its address in oneRecord - record = new LocClassRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocClassRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setWfo(getString(rs, 5)); - record.setHsa(getString(rs, 6)); - record.setPost(getInt(rs, 7)); - record.setDisp_class(getString(rs, 8)); - record.setIs_dcp(getString(rs, 9)); - record.setIs_observer(getString(rs, 10)); - record.setTelem_type(getString(rs, 11)); - - // add this LocClassRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocClassRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocClassRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocClassRecord record = null; - - // create a List to hold LocClass Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locclass " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocClassRecord - // and store its address in oneRecord - record = new LocClassRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocClassRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setWfo(getString(rs, 5)); - record.setHsa(getString(rs, 6)); - record.setPost(getInt(rs, 7)); - record.setDisp_class(getString(rs, 8)); - record.setIs_dcp(getString(rs, 9)); - record.setIs_observer(getString(rs, 10)); - record.setTelem_type(getString(rs, 11)); - - // add this LocClassRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocClassRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of LocClassTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocDataLimitsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocDataLimitsRecord.java deleted file mode 100644 index e6c6c503ae..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocDataLimitsRecord.java +++ /dev/null @@ -1,310 +0,0 @@ -// filename: LocDataLimitsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocDataLimits table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocDataLimitsRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String monthdaystart; - - private String monthdayend; - - private double gross_range_min; - - private double gross_range_max; - - private double reason_range_min; - - private double reason_range_max; - - private double roc_max; - - private double alert_upper_limit; - - private double alert_roc_limit; - - private double alarm_upper_limit; - - private double alarm_roc_limit; - - private double alert_lower_limit; - - private double alarm_lower_limit; - - private double alert_diff_limit; - - private double alarm_diff_limit; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocDataLimitsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocDataLimitsRecord(LocDataLimitsRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setMonthdaystart(origRecord.getMonthdaystart()); - setMonthdayend(origRecord.getMonthdayend()); - setGross_range_min(origRecord.getGross_range_min()); - setGross_range_max(origRecord.getGross_range_max()); - setReason_range_min(origRecord.getReason_range_min()); - setReason_range_max(origRecord.getReason_range_max()); - setRoc_max(origRecord.getRoc_max()); - setAlert_upper_limit(origRecord.getAlert_upper_limit()); - setAlert_roc_limit(origRecord.getAlert_roc_limit()); - setAlarm_upper_limit(origRecord.getAlarm_upper_limit()); - setAlarm_roc_limit(origRecord.getAlarm_roc_limit()); - setAlert_lower_limit(origRecord.getAlert_lower_limit()); - setAlarm_lower_limit(origRecord.getAlarm_lower_limit()); - setAlert_diff_limit(origRecord.getAlert_diff_limit()); - setAlarm_diff_limit(origRecord.getAlarm_diff_limit()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocDataLimits record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getMonthdaystart() - { - return monthdaystart; - } - - public void setMonthdaystart(String monthdaystart) - { - this.monthdaystart = monthdaystart ; - } - - public String getMonthdayend() - { - return monthdayend; - } - - public void setMonthdayend(String monthdayend) - { - this.monthdayend = monthdayend ; - } - - public double getGross_range_min() - { - return gross_range_min; - } - - public void setGross_range_min(double gross_range_min) - { - this.gross_range_min = gross_range_min ; - } - - public double getGross_range_max() - { - return gross_range_max; - } - - public void setGross_range_max(double gross_range_max) - { - this.gross_range_max = gross_range_max ; - } - - public double getReason_range_min() - { - return reason_range_min; - } - - public void setReason_range_min(double reason_range_min) - { - this.reason_range_min = reason_range_min ; - } - - public double getReason_range_max() - { - return reason_range_max; - } - - public void setReason_range_max(double reason_range_max) - { - this.reason_range_max = reason_range_max ; - } - - public double getRoc_max() - { - return roc_max; - } - - public void setRoc_max(double roc_max) - { - this.roc_max = roc_max ; - } - - public double getAlert_upper_limit() - { - return alert_upper_limit; - } - - public void setAlert_upper_limit(double alert_upper_limit) - { - this.alert_upper_limit = alert_upper_limit ; - } - - public double getAlert_roc_limit() - { - return alert_roc_limit; - } - - public void setAlert_roc_limit(double alert_roc_limit) - { - this.alert_roc_limit = alert_roc_limit ; - } - - public double getAlarm_upper_limit() - { - return alarm_upper_limit; - } - - public void setAlarm_upper_limit(double alarm_upper_limit) - { - this.alarm_upper_limit = alarm_upper_limit ; - } - - public double getAlarm_roc_limit() - { - return alarm_roc_limit; - } - - public void setAlarm_roc_limit(double alarm_roc_limit) - { - this.alarm_roc_limit = alarm_roc_limit ; - } - - public double getAlert_lower_limit() - { - return alert_lower_limit; - } - - public void setAlert_lower_limit(double alert_lower_limit) - { - this.alert_lower_limit = alert_lower_limit ; - } - - public double getAlarm_lower_limit() - { - return alarm_lower_limit; - } - - public void setAlarm_lower_limit(double alarm_lower_limit) - { - this.alarm_lower_limit = alarm_lower_limit ; - } - - public double getAlert_diff_limit() - { - return alert_diff_limit; - } - - public void setAlert_diff_limit(double alert_diff_limit) - { - this.alert_diff_limit = alert_diff_limit ; - } - - public double getAlarm_diff_limit() - { - return alarm_diff_limit; - } - - public void setAlarm_diff_limit(double alarm_diff_limit) - { - this.alarm_diff_limit = alarm_diff_limit ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND monthdaystart = '" + monthdaystart + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getMonthdaystart() + " " + - getMonthdayend() + " " + - getGross_range_min() + " " + - getGross_range_max() + " " + - getReason_range_min() + " " + - getReason_range_max() + " " + - getRoc_max() + " " + - getAlert_upper_limit() + " " + - getAlert_roc_limit() + " " + - getAlarm_upper_limit() + " " + - getAlarm_roc_limit() + " " + - getAlert_lower_limit() + " " + - getAlarm_lower_limit() + " " + - getAlert_diff_limit() + " " + - getAlarm_diff_limit() + " " + - "" ; - return outString; - } // end toString() -} // end of LocDataLimitsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocDataLimitsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocDataLimitsTable.java deleted file mode 100644 index 801f2e4da2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocDataLimitsTable.java +++ /dev/null @@ -1,331 +0,0 @@ -// filename: LocDataLimitsTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locdatalimits table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocDataLimitsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocDataLimitsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocDataLimitsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locdatalimits"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocDataLimitsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocDataLimitsRecord record = null; - - // create a List to hold LocDataLimits Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locdatalimits " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocDataLimitsRecord - // and store its address in oneRecord - record = new LocDataLimitsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocDataLimitsRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setMonthdaystart(getString(rs, 4)); - record.setMonthdayend(getString(rs, 5)); - record.setGross_range_min(getDouble(rs, 6)); - record.setGross_range_max(getDouble(rs, 7)); - record.setReason_range_min(getDouble(rs, 8)); - record.setReason_range_max(getDouble(rs, 9)); - record.setRoc_max(getDouble(rs, 10)); - record.setAlert_upper_limit(getDouble(rs, 11)); - record.setAlert_roc_limit(getDouble(rs, 12)); - record.setAlarm_upper_limit(getDouble(rs, 13)); - record.setAlarm_roc_limit(getDouble(rs, 14)); - record.setAlert_lower_limit(getDouble(rs, 15)); - record.setAlarm_lower_limit(getDouble(rs, 16)); - record.setAlert_diff_limit(getDouble(rs, 17)); - record.setAlarm_diff_limit(getDouble(rs, 18)); - - // add this LocDataLimitsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocDataLimitsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocDataLimitsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocDataLimitsRecord record = null; - - // create a List to hold LocDataLimits Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locdatalimits " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocDataLimitsRecord - // and store its address in oneRecord - record = new LocDataLimitsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocDataLimitsRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setMonthdaystart(getString(rs, 4)); - record.setMonthdayend(getString(rs, 5)); - record.setGross_range_min(getDouble(rs, 6)); - record.setGross_range_max(getDouble(rs, 7)); - record.setReason_range_min(getDouble(rs, 8)); - record.setReason_range_max(getDouble(rs, 9)); - record.setRoc_max(getDouble(rs, 10)); - record.setAlert_upper_limit(getDouble(rs, 11)); - record.setAlert_roc_limit(getDouble(rs, 12)); - record.setAlarm_upper_limit(getDouble(rs, 13)); - record.setAlarm_roc_limit(getDouble(rs, 14)); - record.setAlert_lower_limit(getDouble(rs, 15)); - record.setAlarm_lower_limit(getDouble(rs, 16)); - record.setAlert_diff_limit(getDouble(rs, 17)); - record.setAlarm_diff_limit(getDouble(rs, 18)); - - // add this LocDataLimitsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocDataLimitsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LocDataLimitsRecord object and.. -//----------------------------------------------------------------- - public int insert(LocDataLimitsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO locdatalimits VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getMonthdaystart()); - setString(insertStatement, 5, record.getMonthdayend()); - setDouble(insertStatement, 6, record.getGross_range_min()); - setDouble(insertStatement, 7, record.getGross_range_max()); - setDouble(insertStatement, 8, record.getReason_range_min()); - setDouble(insertStatement, 9, record.getReason_range_max()); - setDouble(insertStatement, 10, record.getRoc_max()); - setDouble(insertStatement, 11, record.getAlert_upper_limit()); - setDouble(insertStatement, 12, record.getAlert_roc_limit()); - setDouble(insertStatement, 13, record.getAlarm_upper_limit()); - setDouble(insertStatement, 14, record.getAlarm_roc_limit()); - setDouble(insertStatement, 15, record.getAlert_lower_limit()); - setDouble(insertStatement, 16, record.getAlarm_lower_limit()); - setDouble(insertStatement, 17, record.getAlert_diff_limit()); - setDouble(insertStatement, 18, record.getAlarm_diff_limit()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locdatalimits " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocDataLimitsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocDataLimitsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locdatalimits SET lid = ?, pe = ?, dur = ?, monthdaystart = ?, monthdayend = ?, gross_range_min = ?, gross_range_max = ?, reason_range_min = ?, reason_range_max = ?, roc_max = ?, alert_upper_limit = ?, alert_roc_limit = ?, alarm_upper_limit = ?, alarm_roc_limit = ?, alert_lower_limit = ?, alarm_lower_limit = ?, alert_diff_limit = ?, alarm_diff_limit = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getMonthdaystart()); - setString(updateStatement, 5, record.getMonthdayend()); - setDouble(updateStatement, 6, record.getGross_range_min()); - setDouble(updateStatement, 7, record.getGross_range_max()); - setDouble(updateStatement, 8, record.getReason_range_min()); - setDouble(updateStatement, 9, record.getReason_range_max()); - setDouble(updateStatement, 10, record.getRoc_max()); - setDouble(updateStatement, 11, record.getAlert_upper_limit()); - setDouble(updateStatement, 12, record.getAlert_roc_limit()); - setDouble(updateStatement, 13, record.getAlarm_upper_limit()); - setDouble(updateStatement, 14, record.getAlarm_roc_limit()); - setDouble(updateStatement, 15, record.getAlert_lower_limit()); - setDouble(updateStatement, 16, record.getAlarm_lower_limit()); - setDouble(updateStatement, 17, record.getAlert_diff_limit()); - setDouble(updateStatement, 18, record.getAlarm_diff_limit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LocDataLimitsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locdatalimits " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocDataLimitsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocDataLimitsRecord oldRecord, LocDataLimitsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locdatalimits SET lid = ?, pe = ?, dur = ?, monthdaystart = ?, monthdayend = ?, gross_range_min = ?, gross_range_max = ?, reason_range_min = ?, reason_range_max = ?, roc_max = ?, alert_upper_limit = ?, alert_roc_limit = ?, alarm_upper_limit = ?, alarm_roc_limit = ?, alert_lower_limit = ?, alarm_lower_limit = ?, alert_diff_limit = ?, alarm_diff_limit = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getMonthdaystart()); - setString(updateStatement, 5, newRecord.getMonthdayend()); - setDouble(updateStatement, 6, newRecord.getGross_range_min()); - setDouble(updateStatement, 7, newRecord.getGross_range_max()); - setDouble(updateStatement, 8, newRecord.getReason_range_min()); - setDouble(updateStatement, 9, newRecord.getReason_range_max()); - setDouble(updateStatement, 10, newRecord.getRoc_max()); - setDouble(updateStatement, 11, newRecord.getAlert_upper_limit()); - setDouble(updateStatement, 12, newRecord.getAlert_roc_limit()); - setDouble(updateStatement, 13, newRecord.getAlarm_upper_limit()); - setDouble(updateStatement, 14, newRecord.getAlarm_roc_limit()); - setDouble(updateStatement, 15, newRecord.getAlert_lower_limit()); - setDouble(updateStatement, 16, newRecord.getAlarm_lower_limit()); - setDouble(updateStatement, 17, newRecord.getAlert_diff_limit()); - setDouble(updateStatement, 18, newRecord.getAlarm_diff_limit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LocDataLimitsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LocDataLimitsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LocDataLimitsRecord oldRecord = (LocDataLimitsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LocDataLimitsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocExtAgencyRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocExtAgencyRecord.java deleted file mode 100644 index 57f61baae6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocExtAgencyRecord.java +++ /dev/null @@ -1,99 +0,0 @@ -// filename: LocExtAgencyRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocExtAgency table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocExtAgencyRecord extends DbRecord -{ - private String lid; - - private String agency_code; - - private String office; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocExtAgencyRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocExtAgencyRecord(LocExtAgencyRecord origRecord) - { - setLid(origRecord.getLid()); - setAgency_code(origRecord.getAgency_code()); - setOffice(origRecord.getOffice()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocExtAgency record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getAgency_code() - { - return agency_code; - } - - public void setAgency_code(String agency_code) - { - this.agency_code = agency_code ; - } - - public String getOffice() - { - return office; - } - - public void setOffice(String office) - { - this.office = office ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND agency_code = '" + agency_code + "'" - + " AND office = '" + office + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getAgency_code() + " " + - getOffice() + " " + - "" ; - return outString; - } // end toString() -} // end of LocExtAgencyRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocExtAgencyTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocExtAgencyTable.java deleted file mode 100644 index bc1e6a6de9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocExtAgencyTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: LocExtAgencyTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locextagency table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocExtAgencyTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocExtAgencyTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocExtAgencyTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locextagency"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocExtAgencyRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocExtAgencyRecord record = null; - - // create a List to hold LocExtAgency Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locextagency " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocExtAgencyRecord - // and store its address in oneRecord - record = new LocExtAgencyRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocExtAgencyRecord object - - record.setLid(getString(rs, 1)); - record.setAgency_code(getString(rs, 2)); - record.setOffice(getString(rs, 3)); - - // add this LocExtAgencyRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocExtAgencyRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocExtAgencyRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocExtAgencyRecord record = null; - - // create a List to hold LocExtAgency Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locextagency " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocExtAgencyRecord - // and store its address in oneRecord - record = new LocExtAgencyRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocExtAgencyRecord object - - record.setLid(getString(rs, 1)); - record.setAgency_code(getString(rs, 2)); - record.setOffice(getString(rs, 3)); - - // add this LocExtAgencyRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocExtAgencyRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LocExtAgencyRecord object and.. -//----------------------------------------------------------------- - public int insert(LocExtAgencyRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO locextagency VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getAgency_code()); - setString(insertStatement, 3, record.getOffice()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locextagency " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocExtAgencyRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocExtAgencyRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locextagency SET lid = ?, agency_code = ?, office = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getAgency_code()); - setString(updateStatement, 3, record.getOffice()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LocExtAgencyRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locextagency " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocExtAgencyRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocExtAgencyRecord oldRecord, LocExtAgencyRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locextagency SET lid = ?, agency_code = ?, office = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getAgency_code()); - setString(updateStatement, 3, newRecord.getOffice()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LocExtAgencyRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LocExtAgencyRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LocExtAgencyRecord oldRecord = (LocExtAgencyRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LocExtAgencyTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocImageRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocImageRecord.java deleted file mode 100644 index c9345b8250..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocImageRecord.java +++ /dev/null @@ -1,154 +0,0 @@ -// filename: LocImageRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocImage table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocImageRecord extends DbRecord -{ - private String lid; - - private String imageid; - - private String title; - - private String descr; - - private String format; - - private String url_internal; - - private String url_external; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocImageRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocImageRecord(LocImageRecord origRecord) - { - setLid(origRecord.getLid()); - setImageid(origRecord.getImageid()); - setTitle(origRecord.getTitle()); - setDescr(origRecord.getDescr()); - setFormat(origRecord.getFormat()); - setUrl_internal(origRecord.getUrl_internal()); - setUrl_external(origRecord.getUrl_external()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocImage record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getImageid() - { - return imageid; - } - - public void setImageid(String imageid) - { - this.imageid = imageid ; - } - - public String getTitle() - { - return title; - } - - public void setTitle(String title) - { - this.title = title ; - } - - public String getDescr() - { - return descr; - } - - public void setDescr(String descr) - { - this.descr = descr ; - } - - public String getFormat() - { - return format; - } - - public void setFormat(String format) - { - this.format = format ; - } - - public String getUrl_internal() - { - return url_internal; - } - - public void setUrl_internal(String url_internal) - { - this.url_internal = url_internal ; - } - - public String getUrl_external() - { - return url_external; - } - - public void setUrl_external(String url_external) - { - this.url_external = url_external ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND imageid = '" + imageid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getImageid() + " " + - getTitle() + " " + - getDescr() + " " + - getFormat() + " " + - getUrl_internal() + " " + - getUrl_external() + " " + - "" ; - return outString; - } // end toString() -} // end of LocImageRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocImageTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocImageTable.java deleted file mode 100644 index 3463d31851..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocImageTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: LocImageTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locimage table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocImageTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocImageTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocImageTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locimage"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocImageRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocImageRecord record = null; - - // create a List to hold LocImage Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locimage " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocImageRecord - // and store its address in oneRecord - record = new LocImageRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocImageRecord object - - record.setLid(getString(rs, 1)); - record.setImageid(getString(rs, 2)); - record.setTitle(getString(rs, 3)); - record.setDescr(getString(rs, 4)); - record.setFormat(getString(rs, 5)); - record.setUrl_internal(getString(rs, 6)); - record.setUrl_external(getString(rs, 7)); - - // add this LocImageRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocImageRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocImageRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocImageRecord record = null; - - // create a List to hold LocImage Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locimage " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocImageRecord - // and store its address in oneRecord - record = new LocImageRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocImageRecord object - - record.setLid(getString(rs, 1)); - record.setImageid(getString(rs, 2)); - record.setTitle(getString(rs, 3)); - record.setDescr(getString(rs, 4)); - record.setFormat(getString(rs, 5)); - record.setUrl_internal(getString(rs, 6)); - record.setUrl_external(getString(rs, 7)); - - // add this LocImageRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocImageRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LocImageRecord object and.. -//----------------------------------------------------------------- - public int insert(LocImageRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO locimage VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getImageid()); - setString(insertStatement, 3, record.getTitle()); - setString(insertStatement, 4, record.getDescr()); - setString(insertStatement, 5, record.getFormat()); - setString(insertStatement, 6, record.getUrl_internal()); - setString(insertStatement, 7, record.getUrl_external()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locimage " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocImageRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocImageRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locimage SET lid = ?, imageid = ?, title = ?, descr = ?, format = ?, url_internal = ?, url_external = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getImageid()); - setString(updateStatement, 3, record.getTitle()); - setString(updateStatement, 4, record.getDescr()); - setString(updateStatement, 5, record.getFormat()); - setString(updateStatement, 6, record.getUrl_internal()); - setString(updateStatement, 7, record.getUrl_external()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LocImageRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM locimage " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocImageRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocImageRecord oldRecord, LocImageRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE locimage SET lid = ?, imageid = ?, title = ?, descr = ?, format = ?, url_internal = ?, url_external = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getImageid()); - setString(updateStatement, 3, newRecord.getTitle()); - setString(updateStatement, 4, newRecord.getDescr()); - setString(updateStatement, 5, newRecord.getFormat()); - setString(updateStatement, 6, newRecord.getUrl_internal()); - setString(updateStatement, 7, newRecord.getUrl_external()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LocImageRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LocImageRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LocImageRecord oldRecord = (LocImageRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LocImageTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocPDCRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocPDCRecord.java deleted file mode 100644 index 4cc02e2c84..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocPDCRecord.java +++ /dev/null @@ -1,240 +0,0 @@ -// This is a view record ! -// filename: LocPDCRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocPDC table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocPDCRecord extends DbRecord -{ - private String lid; - - private String name; - - private double lat; - - private double lon; - - private String hsa; - - private int post; - - private double elev; - - private String primary_pe; - - private double fs; - - private double fq; - - private String disp_class; - - private String is_dcp; - - private String is_observer; - - private String telem_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocPDCRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocPDCRecord(LocPDCRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setHsa(origRecord.getHsa()); - setPost(origRecord.getPost()); - setElev(origRecord.getElev()); - setPrimary_pe(origRecord.getPrimary_pe()); - setFs(origRecord.getFs()); - setFq(origRecord.getFq()); - setDisp_class(origRecord.getDisp_class()); - setIs_dcp(origRecord.getIs_dcp()); - setIs_observer(origRecord.getIs_observer()); - setTelem_type(origRecord.getTelem_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocPDC record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public int getPost() - { - return post; - } - - public void setPost(int post) - { - this.post = post ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - - public String getPrimary_pe() - { - return primary_pe; - } - - public void setPrimary_pe(String primary_pe) - { - this.primary_pe = primary_pe ; - } - - public double getFs() - { - return fs; - } - - public void setFs(double fs) - { - this.fs = fs ; - } - - public double getFq() - { - return fq; - } - - public void setFq(double fq) - { - this.fq = fq ; - } - - public String getDisp_class() - { - return disp_class; - } - - public void setDisp_class(String disp_class) - { - this.disp_class = disp_class ; - } - - public String getIs_dcp() - { - return is_dcp; - } - - public void setIs_dcp(String is_dcp) - { - this.is_dcp = is_dcp ; - } - - public String getIs_observer() - { - return is_observer; - } - - public void setIs_observer(String is_observer) - { - this.is_observer = is_observer ; - } - - public String getTelem_type() - { - return telem_type; - } - - public void setTelem_type(String telem_type) - { - this.telem_type = telem_type ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getLat() + " " + - getLon() + " " + - getHsa() + " " + - getPost() + " " + - getElev() + " " + - getPrimary_pe() + " " + - getFs() + " " + - getFq() + " " + - getDisp_class() + " " + - getIs_dcp() + " " + - getIs_observer() + " " + - getTelem_type() + " " + - "" ; - return outString; - } // end toString() -} // end of LocPDCRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocPDCView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocPDCView.java deleted file mode 100644 index 70a1d13ae6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocPDCView.java +++ /dev/null @@ -1,157 +0,0 @@ -// filename: LocPDCView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locpdc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocPDCView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocPDCTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocPDCView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locpdc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocPDCRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocPDCRecord record = null; - - // create a List to hold LocPDC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locpdc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocPDCRecord - // and store its address in oneRecord - record = new LocPDCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocPDCRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setHsa(getString(rs, 5)); - record.setPost(getInt(rs, 6)); - record.setElev(getDouble(rs, 7)); - record.setPrimary_pe(getString(rs, 8)); - record.setFs(getDouble(rs, 9)); - record.setFq(getDouble(rs, 10)); - record.setDisp_class(getString(rs, 11)); - record.setIs_dcp(getString(rs, 12)); - record.setIs_observer(getString(rs, 13)); - record.setTelem_type(getString(rs, 14)); - - // add this LocPDCRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocPDCRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocPDCRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocPDCRecord record = null; - - // create a List to hold LocPDC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locpdc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocPDCRecord - // and store its address in oneRecord - record = new LocPDCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocPDCRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setHsa(getString(rs, 5)); - record.setPost(getInt(rs, 6)); - record.setElev(getDouble(rs, 7)); - record.setPrimary_pe(getString(rs, 8)); - record.setFs(getDouble(rs, 9)); - record.setFq(getDouble(rs, 10)); - record.setDisp_class(getString(rs, 11)); - record.setIs_dcp(getString(rs, 12)); - record.setIs_observer(getString(rs, 13)); - record.setTelem_type(getString(rs, 14)); - - // add this LocPDCRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocPDCRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of LocPDCTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocRiverMonRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocRiverMonRecord.java deleted file mode 100644 index 3416efc81d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocRiverMonRecord.java +++ /dev/null @@ -1,296 +0,0 @@ -// This is a view record ! -// filename: LocRiverMonRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocRiverMon table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocRiverMonRecord extends DbRecord -{ - private String lid; - - private String name; - - private String county; - - private String state; - - private String hsa; - - private String stream; - - private double bankfull; - - private double action_stage; - - private double flood_stage; - - private double flood_flow; - - private double action_flow; - - private String primary_pe; - - private String proximity; - - private String reach; - - private double mile; - - private double minor; - - private double moderate; - - private double major; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocRiverMonRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocRiverMonRecord(LocRiverMonRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setHsa(origRecord.getHsa()); - setStream(origRecord.getStream()); - setBankfull(origRecord.getBankfull()); - setAction_stage(origRecord.getAction_stage()); - setFlood_stage(origRecord.getFlood_stage()); - setFlood_flow(origRecord.getFlood_flow()); - setAction_flow(origRecord.getAction_flow()); - setPrimary_pe(origRecord.getPrimary_pe()); - setProximity(origRecord.getProximity()); - setReach(origRecord.getReach()); - setMile(origRecord.getMile()); - setMinor(origRecord.getMinor()); - setModerate(origRecord.getModerate()); - setMajor(origRecord.getMajor()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocRiverMon record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public String getStream() - { - return stream; - } - - public void setStream(String stream) - { - this.stream = stream ; - } - - public double getBankfull() - { - return bankfull; - } - - public void setBankfull(double bankfull) - { - this.bankfull = bankfull ; - } - - public double getAction_stage() - { - return action_stage; - } - - public void setAction_stage(double action_stage) - { - this.action_stage = action_stage ; - } - - public double getFlood_stage() - { - return flood_stage; - } - - public void setFlood_stage(double flood_stage) - { - this.flood_stage = flood_stage ; - } - - public double getFlood_flow() - { - return flood_flow; - } - - public void setFlood_flow(double flood_flow) - { - this.flood_flow = flood_flow ; - } - - public double getAction_flow() - { - return action_flow; - } - - public void setAction_flow(double action_flow) - { - this.action_flow = action_flow ; - } - - public String getPrimary_pe() - { - return primary_pe; - } - - public void setPrimary_pe(String primary_pe) - { - this.primary_pe = primary_pe ; - } - - public String getProximity() - { - return proximity; - } - - public void setProximity(String proximity) - { - this.proximity = proximity ; - } - - public String getReach() - { - return reach; - } - - public void setReach(String reach) - { - this.reach = reach ; - } - - public double getMile() - { - return mile; - } - - public void setMile(double mile) - { - this.mile = mile ; - } - - public double getMinor() - { - return minor; - } - - public void setMinor(double minor) - { - this.minor = minor ; - } - - public double getModerate() - { - return moderate; - } - - public void setModerate(double moderate) - { - this.moderate = moderate ; - } - - public double getMajor() - { - return major; - } - - public void setMajor(double major) - { - this.major = major ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getCounty() + " " + - getState() + " " + - getHsa() + " " + - getStream() + " " + - getBankfull() + " " + - getAction_stage() + " " + - getFlood_stage() + " " + - getFlood_flow() + " " + - getAction_flow() + " " + - getPrimary_pe() + " " + - getProximity() + " " + - getReach() + " " + - getMile() + " " + - getMinor() + " " + - getModerate() + " " + - getMajor() + " " + - "" ; - return outString; - } // end toString() -} // end of LocRiverMonRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocRiverMonView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocRiverMonView.java deleted file mode 100644 index eed26dca4a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocRiverMonView.java +++ /dev/null @@ -1,165 +0,0 @@ -// filename: LocRiverMonView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locrivermon table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocRiverMonView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocRiverMonTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocRiverMonView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locrivermon"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocRiverMonRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocRiverMonRecord record = null; - - // create a List to hold LocRiverMon Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locrivermon " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocRiverMonRecord - // and store its address in oneRecord - record = new LocRiverMonRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocRiverMonRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - record.setState(getString(rs, 4)); - record.setHsa(getString(rs, 5)); - record.setStream(getString(rs, 6)); - record.setBankfull(getDouble(rs, 7)); - record.setAction_stage(getDouble(rs, 8)); - record.setFlood_stage(getDouble(rs, 9)); - record.setFlood_flow(getDouble(rs, 10)); - record.setAction_flow(getDouble(rs, 11)); - record.setPrimary_pe(getString(rs, 12)); - record.setProximity(getString(rs, 13)); - record.setReach(getString(rs, 14)); - record.setMile(getDouble(rs, 15)); - record.setMinor(getDouble(rs, 16)); - record.setModerate(getDouble(rs, 17)); - record.setMajor(getDouble(rs, 18)); - - // add this LocRiverMonRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocRiverMonRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocRiverMonRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocRiverMonRecord record = null; - - // create a List to hold LocRiverMon Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locrivermon " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocRiverMonRecord - // and store its address in oneRecord - record = new LocRiverMonRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocRiverMonRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setCounty(getString(rs, 3)); - record.setState(getString(rs, 4)); - record.setHsa(getString(rs, 5)); - record.setStream(getString(rs, 6)); - record.setBankfull(getDouble(rs, 7)); - record.setAction_stage(getDouble(rs, 8)); - record.setFlood_stage(getDouble(rs, 9)); - record.setFlood_flow(getDouble(rs, 10)); - record.setAction_flow(getDouble(rs, 11)); - record.setPrimary_pe(getString(rs, 12)); - record.setProximity(getString(rs, 13)); - record.setReach(getString(rs, 14)); - record.setMile(getDouble(rs, 15)); - record.setMinor(getDouble(rs, 16)); - record.setModerate(getDouble(rs, 17)); - record.setMajor(getDouble(rs, 18)); - - // add this LocRiverMonRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocRiverMonRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of LocRiverMonTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocTransmitRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocTransmitRecord.java deleted file mode 100644 index bfc036292b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocTransmitRecord.java +++ /dev/null @@ -1,72 +0,0 @@ -// This is a view record ! -// filename: LocTransmitRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocTransmit table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocTransmitRecord extends DbRecord -{ - private String lid; - - private String call_sign; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocTransmitRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocTransmitRecord(LocTransmitRecord origRecord) - { - setLid(origRecord.getLid()); - setCall_sign(origRecord.getCall_sign()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocTransmit record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getCall_sign() - { - return call_sign; - } - - public void setCall_sign(String call_sign) - { - this.call_sign = call_sign ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getCall_sign() + " " + - "" ; - return outString; - } // end toString() -} // end of LocTransmitRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocTransmitView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocTransmitView.java deleted file mode 100644 index f643c9b410..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocTransmitView.java +++ /dev/null @@ -1,133 +0,0 @@ -// filename: LocTransmitView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// loctransmit table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocTransmitView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocTransmitTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocTransmitView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("loctransmit"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocTransmitRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocTransmitRecord record = null; - - // create a List to hold LocTransmit Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM loctransmit " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocTransmitRecord - // and store its address in oneRecord - record = new LocTransmitRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocTransmitRecord object - - record.setLid(getString(rs, 1)); - record.setCall_sign(getString(rs, 2)); - - // add this LocTransmitRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocTransmitRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocTransmitRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocTransmitRecord record = null; - - // create a List to hold LocTransmit Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM loctransmit " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocTransmitRecord - // and store its address in oneRecord - record = new LocTransmitRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocTransmitRecord object - - record.setLid(getString(rs, 1)); - record.setCall_sign(getString(rs, 2)); - - // add this LocTransmitRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocTransmitRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of LocTransmitTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocViewRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocViewRecord.java deleted file mode 100644 index 2336902bf3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocViewRecord.java +++ /dev/null @@ -1,226 +0,0 @@ -// This is a view record ! -// filename: LocViewRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocView table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocViewRecord extends DbRecord -{ - private String lid; - - private String name; - - private double lat; - - private double lon; - - private String rb; - - private String state; - - private String county; - - private String type; - - private String wfo; - - private String hsa; - - private int post; - - private String stream; - - private String gsno; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocViewRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocViewRecord(LocViewRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setRb(origRecord.getRb()); - setState(origRecord.getState()); - setCounty(origRecord.getCounty()); - setType(origRecord.getType()); - setWfo(origRecord.getWfo()); - setHsa(origRecord.getHsa()); - setPost(origRecord.getPost()); - setStream(origRecord.getStream()); - setGsno(origRecord.getGsno()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocView record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public String getRb() - { - return rb; - } - - public void setRb(String rb) - { - this.rb = rb ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public int getPost() - { - return post; - } - - public void setPost(int post) - { - this.post = post ; - } - - public String getStream() - { - return stream; - } - - public void setStream(String stream) - { - this.stream = stream ; - } - - public String getGsno() - { - return gsno; - } - - public void setGsno(String gsno) - { - this.gsno = gsno ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getLat() + " " + - getLon() + " " + - getRb() + " " + - getState() + " " + - getCounty() + " " + - getType() + " " + - getWfo() + " " + - getHsa() + " " + - getPost() + " " + - getStream() + " " + - getGsno() + " " + - "" ; - return outString; - } // end toString() -} // end of LocViewRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocViewView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocViewView.java deleted file mode 100644 index d1ced9ba06..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocViewView.java +++ /dev/null @@ -1,155 +0,0 @@ -// filename: LocViewView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locview table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocViewView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocViewTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocViewView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locview"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocViewRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocViewRecord record = null; - - // create a List to hold LocView Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locview " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocViewRecord - // and store its address in oneRecord - record = new LocViewRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocViewRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setRb(getString(rs, 5)); - record.setState(getString(rs, 6)); - record.setCounty(getString(rs, 7)); - record.setType(getString(rs, 8)); - record.setWfo(getString(rs, 9)); - record.setHsa(getString(rs, 10)); - record.setPost(getInt(rs, 11)); - record.setStream(getString(rs, 12)); - record.setGsno(getString(rs, 13)); - - // add this LocViewRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocViewRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocViewRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocViewRecord record = null; - - // create a List to hold LocView Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locview " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocViewRecord - // and store its address in oneRecord - record = new LocViewRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocViewRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setRb(getString(rs, 5)); - record.setState(getString(rs, 6)); - record.setCounty(getString(rs, 7)); - record.setType(getString(rs, 8)); - record.setWfo(getString(rs, 9)); - record.setHsa(getString(rs, 10)); - record.setPost(getInt(rs, 11)); - record.setStream(getString(rs, 12)); - record.setGsno(getString(rs, 13)); - - // add this LocViewRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocViewRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of LocViewTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocWfoRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocWfoRecord.java deleted file mode 100644 index 3acc6ba2fe..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocWfoRecord.java +++ /dev/null @@ -1,128 +0,0 @@ -// This is a view record ! -// filename: LocWfoRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// LocWfo table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocWfoRecord extends DbRecord -{ - private String lid; - - private String county; - - private String state; - - private String wfo; - - private String primary_back; - - private String secondary_back; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocWfoRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocWfoRecord(LocWfoRecord origRecord) - { - setLid(origRecord.getLid()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setWfo(origRecord.getWfo()); - setPrimary_back(origRecord.getPrimary_back()); - setSecondary_back(origRecord.getSecondary_back()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a LocWfo record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getPrimary_back() - { - return primary_back; - } - - public void setPrimary_back(String primary_back) - { - this.primary_back = primary_back ; - } - - public String getSecondary_back() - { - return secondary_back; - } - - public void setSecondary_back(String secondary_back) - { - this.secondary_back = secondary_back ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getCounty() + " " + - getState() + " " + - getWfo() + " " + - getPrimary_back() + " " + - getSecondary_back() + " " + - "" ; - return outString; - } // end toString() -} // end of LocWfoRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocWfoView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocWfoView.java deleted file mode 100644 index 2bf2796513..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocWfoView.java +++ /dev/null @@ -1,141 +0,0 @@ -// filename: LocWfoView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// locwfo table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocWfoView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocWfoTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocWfoView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("locwfo"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocWfoRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocWfoRecord record = null; - - // create a List to hold LocWfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locwfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocWfoRecord - // and store its address in oneRecord - record = new LocWfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocWfoRecord object - - record.setLid(getString(rs, 1)); - record.setCounty(getString(rs, 2)); - record.setState(getString(rs, 3)); - record.setWfo(getString(rs, 4)); - record.setPrimary_back(getString(rs, 5)); - record.setSecondary_back(getString(rs, 6)); - - // add this LocWfoRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocWfoRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocWfoRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocWfoRecord record = null; - - // create a List to hold LocWfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM locwfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocWfoRecord - // and store its address in oneRecord - record = new LocWfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocWfoRecord object - - record.setLid(getString(rs, 1)); - record.setCounty(getString(rs, 2)); - record.setState(getString(rs, 3)); - record.setWfo(getString(rs, 4)); - record.setPrimary_back(getString(rs, 5)); - record.setSecondary_back(getString(rs, 6)); - - // add this LocWfoRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocWfoRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of LocWfoTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocationRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocationRecord.java deleted file mode 100644 index 1a0b69c591..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocationRecord.java +++ /dev/null @@ -1,461 +0,0 @@ -// filename: LocationRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Location table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LocationRecord extends DbRecord -{ - private String lid; - - private String county; - - private String coe; - - private String cpm; - - private String detail; - - private double elev; - - private String hdatum; - - private String hsa; - - private String hu; - - private double lat; - - private double lon; - - private String lremark; - - private long lrevise; - - private String name; - - private String network; - - private String rb; - - private String rfc; - - private long sbd; - - private String sn; - - private String state; - - private String waro; - - private String wfo; - - private String wsfo; - - private String type; - - private String des; - - private String det; - - private int post; - - private String stntype; - - private String tzone; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LocationRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LocationRecord(LocationRecord origRecord) - { - setLid(origRecord.getLid()); - setCounty(origRecord.getCounty()); - setCoe(origRecord.getCoe()); - setCpm(origRecord.getCpm()); - setDetail(origRecord.getDetail()); - setElev(origRecord.getElev()); - setHdatum(origRecord.getHdatum()); - setHsa(origRecord.getHsa()); - setHu(origRecord.getHu()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setLremark(origRecord.getLremark()); - setLrevise(origRecord.getLrevise()); - setName(origRecord.getName()); - setNetwork(origRecord.getNetwork()); - setRb(origRecord.getRb()); - setRfc(origRecord.getRfc()); - setSbd(origRecord.getSbd()); - setSn(origRecord.getSn()); - setState(origRecord.getState()); - setWaro(origRecord.getWaro()); - setWfo(origRecord.getWfo()); - setWsfo(origRecord.getWsfo()); - setType(origRecord.getType()); - setDes(origRecord.getDes()); - setDet(origRecord.getDet()); - setPost(origRecord.getPost()); - setStntype(origRecord.getStntype()); - setTzone(origRecord.getTzone()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Location record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getCoe() - { - return coe; - } - - public void setCoe(String coe) - { - this.coe = coe ; - } - - public String getCpm() - { - return cpm; - } - - public void setCpm(String cpm) - { - this.cpm = cpm ; - } - - public String getDetail() - { - return detail; - } - - public void setDetail(String detail) - { - this.detail = detail ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - - public String getHdatum() - { - return hdatum; - } - - public void setHdatum(String hdatum) - { - this.hdatum = hdatum ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - - public String getHu() - { - return hu; - } - - public void setHu(String hu) - { - this.hu = hu ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public String getLremark() - { - return lremark; - } - - public void setLremark(String lremark) - { - this.lremark = lremark ; - } - - public long getLrevise() - { - return lrevise; - } - - public void setLrevise(long lrevise) - { - this.lrevise = lrevise ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getNetwork() - { - return network; - } - - public void setNetwork(String network) - { - this.network = network ; - } - - public String getRb() - { - return rb; - } - - public void setRb(String rb) - { - this.rb = rb ; - } - - public String getRfc() - { - return rfc; - } - - public void setRfc(String rfc) - { - this.rfc = rfc ; - } - - public long getSbd() - { - return sbd; - } - - public void setSbd(long sbd) - { - this.sbd = sbd ; - } - - public String getSn() - { - return sn; - } - - public void setSn(String sn) - { - this.sn = sn ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getWaro() - { - return waro; - } - - public void setWaro(String waro) - { - this.waro = waro ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getWsfo() - { - return wsfo; - } - - public void setWsfo(String wsfo) - { - this.wsfo = wsfo ; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - - public String getDes() - { - return des; - } - - public void setDes(String des) - { - this.des = des ; - } - - public String getDet() - { - return det; - } - - public void setDet(String det) - { - this.det = det ; - } - - public int getPost() - { - return post; - } - - public void setPost(int post) - { - this.post = post ; - } - - public String getStntype() - { - return stntype; - } - - public void setStntype(String stntype) - { - this.stntype = stntype ; - } - - public String getTzone() - { - return tzone; - } - - public void setTzone(String tzone) - { - this.tzone = tzone ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getCounty() + " " + - getCoe() + " " + - getCpm() + " " + - getDetail() + " " + - getElev() + " " + - getHdatum() + " " + - getHsa() + " " + - getHu() + " " + - getLat() + " " + - getLon() + " " + - getLremark() + " " + - getDateStringFromLongTime(getLrevise()) + " " + - getName() + " " + - getNetwork() + " " + - getRb() + " " + - getRfc() + " " + - getDateStringFromLongTime(getSbd()) + " " + - getSn() + " " + - getState() + " " + - getWaro() + " " + - getWfo() + " " + - getWsfo() + " " + - getType() + " " + - getDes() + " " + - getDet() + " " + - getPost() + " " + - getStntype() + " " + - getTzone() + " " + - "" ; - return outString; - } // end toString() -} // end of LocationRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocationTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocationTable.java deleted file mode 100644 index 12d6f14ee6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LocationTable.java +++ /dev/null @@ -1,386 +0,0 @@ -// filename: LocationTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// location table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LocationTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LocationTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LocationTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("location"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LocationRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LocationRecord record = null; - - // create a List to hold Location Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM location " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocationRecord - // and store its address in oneRecord - record = new LocationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocationRecord object - - record.setLid(getString(rs, 1)); - record.setCounty(getString(rs, 2)); - record.setCoe(getString(rs, 3)); - record.setCpm(getString(rs, 4)); - record.setDetail(getString(rs, 5)); - record.setElev(getDouble(rs, 6)); - record.setHdatum(getString(rs, 7)); - record.setHsa(getString(rs, 8)); - record.setHu(getString(rs, 9)); - record.setLat(getDouble(rs, 10)); - record.setLon(getDouble(rs, 11)); - record.setLremark(getString(rs, 12)); - record.setLrevise(getDate(rs, 13)); - record.setName(getString(rs, 14)); - record.setNetwork(getString(rs, 15)); - record.setRb(getString(rs, 16)); - record.setRfc(getString(rs, 17)); - record.setSbd(getDate(rs, 18)); - record.setSn(getString(rs, 19)); - record.setState(getString(rs, 20)); - record.setWaro(getString(rs, 21)); - record.setWfo(getString(rs, 22)); - record.setWsfo(getString(rs, 23)); - record.setType(getString(rs, 24)); - record.setDes(getString(rs, 25)); - record.setDet(getString(rs, 26)); - record.setPost(getInt(rs, 27)); - record.setStntype(getString(rs, 28)); - record.setTzone(getString(rs, 29)); - - // add this LocationRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LocationRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LocationRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LocationRecord record = null; - - // create a List to hold Location Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM location " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LocationRecord - // and store its address in oneRecord - record = new LocationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LocationRecord object - - record.setLid(getString(rs, 1)); - record.setCounty(getString(rs, 2)); - record.setCoe(getString(rs, 3)); - record.setCpm(getString(rs, 4)); - record.setDetail(getString(rs, 5)); - record.setElev(getDouble(rs, 6)); - record.setHdatum(getString(rs, 7)); - record.setHsa(getString(rs, 8)); - record.setHu(getString(rs, 9)); - record.setLat(getDouble(rs, 10)); - record.setLon(getDouble(rs, 11)); - record.setLremark(getString(rs, 12)); - record.setLrevise(getDate(rs, 13)); - record.setName(getString(rs, 14)); - record.setNetwork(getString(rs, 15)); - record.setRb(getString(rs, 16)); - record.setRfc(getString(rs, 17)); - record.setSbd(getDate(rs, 18)); - record.setSn(getString(rs, 19)); - record.setState(getString(rs, 20)); - record.setWaro(getString(rs, 21)); - record.setWfo(getString(rs, 22)); - record.setWsfo(getString(rs, 23)); - record.setType(getString(rs, 24)); - record.setDes(getString(rs, 25)); - record.setDet(getString(rs, 26)); - record.setPost(getInt(rs, 27)); - record.setStntype(getString(rs, 28)); - record.setTzone(getString(rs, 29)); - - // add this LocationRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LocationRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LocationRecord object and.. -//----------------------------------------------------------------- - public int insert(LocationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO location VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getCounty()); - setString(insertStatement, 3, record.getCoe()); - setString(insertStatement, 4, record.getCpm()); - setString(insertStatement, 5, record.getDetail()); - setDouble(insertStatement, 6, record.getElev()); - setString(insertStatement, 7, record.getHdatum()); - setString(insertStatement, 8, record.getHsa()); - setString(insertStatement, 9, record.getHu()); - setDouble(insertStatement, 10, record.getLat()); - setDouble(insertStatement, 11, record.getLon()); - setString(insertStatement, 12, record.getLremark()); - setDate(insertStatement, 13, record.getLrevise()); - setString(insertStatement, 14, record.getName()); - setString(insertStatement, 15, record.getNetwork()); - setString(insertStatement, 16, record.getRb()); - setString(insertStatement, 17, record.getRfc()); - setDate(insertStatement, 18, record.getSbd()); - setString(insertStatement, 19, record.getSn()); - setString(insertStatement, 20, record.getState()); - setString(insertStatement, 21, record.getWaro()); - setString(insertStatement, 22, record.getWfo()); - setString(insertStatement, 23, record.getWsfo()); - setString(insertStatement, 24, record.getType()); - setString(insertStatement, 25, record.getDes()); - setString(insertStatement, 26, record.getDet()); - setInt(insertStatement, 27, record.getPost()); - setString(insertStatement, 28, record.getStntype()); - setString(insertStatement, 29, record.getTzone()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM location " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocationRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE location SET lid = ?, county = ?, coe = ?, cpm = ?, detail = ?, elev = ?, hdatum = ?, hsa = ?, hu = ?, lat = ?, lon = ?, lremark = ?, lrevise = ?, name = ?, network = ?, rb = ?, rfc = ?, sbd = ?, sn = ?, state = ?, waro = ?, wfo = ?, wsfo = ?, type = ?, des = ?, det = ?, post = ?, stntype = ?, tzone = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getCounty()); - setString(updateStatement, 3, record.getCoe()); - setString(updateStatement, 4, record.getCpm()); - setString(updateStatement, 5, record.getDetail()); - setDouble(updateStatement, 6, record.getElev()); - setString(updateStatement, 7, record.getHdatum()); - setString(updateStatement, 8, record.getHsa()); - setString(updateStatement, 9, record.getHu()); - setDouble(updateStatement, 10, record.getLat()); - setDouble(updateStatement, 11, record.getLon()); - setString(updateStatement, 12, record.getLremark()); - setDate(updateStatement, 13, record.getLrevise()); - setString(updateStatement, 14, record.getName()); - setString(updateStatement, 15, record.getNetwork()); - setString(updateStatement, 16, record.getRb()); - setString(updateStatement, 17, record.getRfc()); - setDate(updateStatement, 18, record.getSbd()); - setString(updateStatement, 19, record.getSn()); - setString(updateStatement, 20, record.getState()); - setString(updateStatement, 21, record.getWaro()); - setString(updateStatement, 22, record.getWfo()); - setString(updateStatement, 23, record.getWsfo()); - setString(updateStatement, 24, record.getType()); - setString(updateStatement, 25, record.getDes()); - setString(updateStatement, 26, record.getDet()); - setInt(updateStatement, 27, record.getPost()); - setString(updateStatement, 28, record.getStntype()); - setString(updateStatement, 29, record.getTzone()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LocationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM location " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LocationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LocationRecord oldRecord, LocationRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE location SET lid = ?, county = ?, coe = ?, cpm = ?, detail = ?, elev = ?, hdatum = ?, hsa = ?, hu = ?, lat = ?, lon = ?, lremark = ?, lrevise = ?, name = ?, network = ?, rb = ?, rfc = ?, sbd = ?, sn = ?, state = ?, waro = ?, wfo = ?, wsfo = ?, type = ?, des = ?, det = ?, post = ?, stntype = ?, tzone = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getCounty()); - setString(updateStatement, 3, newRecord.getCoe()); - setString(updateStatement, 4, newRecord.getCpm()); - setString(updateStatement, 5, newRecord.getDetail()); - setDouble(updateStatement, 6, newRecord.getElev()); - setString(updateStatement, 7, newRecord.getHdatum()); - setString(updateStatement, 8, newRecord.getHsa()); - setString(updateStatement, 9, newRecord.getHu()); - setDouble(updateStatement, 10, newRecord.getLat()); - setDouble(updateStatement, 11, newRecord.getLon()); - setString(updateStatement, 12, newRecord.getLremark()); - setDate(updateStatement, 13, newRecord.getLrevise()); - setString(updateStatement, 14, newRecord.getName()); - setString(updateStatement, 15, newRecord.getNetwork()); - setString(updateStatement, 16, newRecord.getRb()); - setString(updateStatement, 17, newRecord.getRfc()); - setDate(updateStatement, 18, newRecord.getSbd()); - setString(updateStatement, 19, newRecord.getSn()); - setString(updateStatement, 20, newRecord.getState()); - setString(updateStatement, 21, newRecord.getWaro()); - setString(updateStatement, 22, newRecord.getWfo()); - setString(updateStatement, 23, newRecord.getWsfo()); - setString(updateStatement, 24, newRecord.getType()); - setString(updateStatement, 25, newRecord.getDes()); - setString(updateStatement, 26, newRecord.getDet()); - setInt(updateStatement, 27, newRecord.getPost()); - setString(updateStatement, 28, newRecord.getStntype()); - setString(updateStatement, 29, newRecord.getTzone()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LocationRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LocationRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LocationRecord oldRecord = (LocationRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LocationTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LowwaterRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LowwaterRecord.java deleted file mode 100644 index 0a1db1dfd4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LowwaterRecord.java +++ /dev/null @@ -1,126 +0,0 @@ -// filename: LowwaterRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Lowwater table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class LowwaterRecord extends DbRecord -{ - private String lid; - - private long lwdat; - - private int q; - - private String lwrem; - - private double stage; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public LowwaterRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public LowwaterRecord(LowwaterRecord origRecord) - { - setLid(origRecord.getLid()); - setLwdat(origRecord.getLwdat()); - setQ(origRecord.getQ()); - setLwrem(origRecord.getLwrem()); - setStage(origRecord.getStage()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Lowwater record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getLwdat() - { - return lwdat; - } - - public void setLwdat(long lwdat) - { - this.lwdat = lwdat ; - } - - public int getQ() - { - return q; - } - - public void setQ(int q) - { - this.q = q ; - } - - public String getLwrem() - { - return lwrem; - } - - public void setLwrem(String lwrem) - { - this.lwrem = lwrem ; - } - - public double getStage() - { - return stage; - } - - public void setStage(double stage) - { - this.stage = stage ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND lwdat = '" + getDateStringFromLongTime(lwdat) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateStringFromLongTime(getLwdat()) + " " + - getQ() + " " + - getLwrem() + " " + - getStage() + " " + - "" ; - return outString; - } // end toString() -} // end of LowwaterRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LowwaterTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LowwaterTable.java deleted file mode 100644 index 5c5aad051e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/LowwaterTable.java +++ /dev/null @@ -1,266 +0,0 @@ -// filename: LowwaterTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// lowwater table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class LowwaterTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// LowwaterTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public LowwaterTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("lowwater"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of LowwaterRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - LowwaterRecord record = null; - - // create a List to hold Lowwater Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lowwater " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LowwaterRecord - // and store its address in oneRecord - record = new LowwaterRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LowwaterRecord object - - record.setLid(getString(rs, 1)); - record.setLwdat(getDate(rs, 2)); - record.setQ(getInt(rs, 3)); - record.setLwrem(getString(rs, 4)); - record.setStage(getDouble(rs, 5)); - - // add this LowwaterRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the LowwaterRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of LowwaterRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - LowwaterRecord record = null; - - // create a List to hold Lowwater Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM lowwater " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a LowwaterRecord - // and store its address in oneRecord - record = new LowwaterRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a LowwaterRecord object - - record.setLid(getString(rs, 1)); - record.setLwdat(getDate(rs, 2)); - record.setQ(getInt(rs, 3)); - record.setLwrem(getString(rs, 4)); - record.setStage(getDouble(rs, 5)); - - // add this LowwaterRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the LowwaterRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a LowwaterRecord object and.. -//----------------------------------------------------------------- - public int insert(LowwaterRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO lowwater VALUES (?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDate(insertStatement, 2, record.getLwdat()); - setInt(insertStatement, 3, record.getQ()); - setString(insertStatement, 4, record.getLwrem()); - setDouble(insertStatement, 5, record.getStage()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lowwater " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LowwaterRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LowwaterRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lowwater SET lid = ?, lwdat = ?, q = ?, lwrem = ?, stage = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDate(updateStatement, 2, record.getLwdat()); - setInt(updateStatement, 3, record.getQ()); - setString(updateStatement, 4, record.getLwrem()); - setDouble(updateStatement, 5, record.getStage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(LowwaterRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM lowwater " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a LowwaterRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(LowwaterRecord oldRecord, LowwaterRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE lowwater SET lid = ?, lwdat = ?, q = ?, lwrem = ?, stage = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDate(updateStatement, 2, newRecord.getLwdat()); - setInt(updateStatement, 3, newRecord.getQ()); - setString(updateStatement, 4, newRecord.getLwrem()); - setDouble(updateStatement, 5, newRecord.getStage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a LowwaterRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(LowwaterRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - LowwaterRecord oldRecord = (LowwaterRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of LowwaterTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MoistureRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MoistureRecord.java deleted file mode 100644 index 085876e894..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MoistureRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: MoistureRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Moisture table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class MoistureRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public MoistureRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public MoistureRecord(MoistureRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Moisture record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of MoistureRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MoistureTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MoistureTable.java deleted file mode 100644 index 123f5da207..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MoistureTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: MoistureTable.java -// author : DBGEN -// created : Tue May 31 17:52:24 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// moisture table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class MoistureTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// MoistureTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public MoistureTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("moisture"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of MoistureRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - MoistureRecord record = null; - - // create a List to hold Moisture Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM moisture " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a MoistureRecord - // and store its address in oneRecord - record = new MoistureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a MoistureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this MoistureRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the MoistureRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of MoistureRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - MoistureRecord record = null; - - // create a List to hold Moisture Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM moisture " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a MoistureRecord - // and store its address in oneRecord - record = new MoistureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a MoistureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this MoistureRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the MoistureRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a MoistureRecord object and.. -//----------------------------------------------------------------- - public int insert(MoistureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO moisture VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM moisture " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a MoistureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(MoistureRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE moisture SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(MoistureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM moisture " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a MoistureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(MoistureRecord oldRecord, MoistureRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE moisture SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a MoistureRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(MoistureRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - MoistureRecord oldRecord = (MoistureRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of MoistureTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MonthlyValuesRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MonthlyValuesRecord.java deleted file mode 100644 index fae0df8c03..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MonthlyValuesRecord.java +++ /dev/null @@ -1,326 +0,0 @@ -// filename: MonthlyValuesRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// MonthlyValues table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class MonthlyValuesRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private String adjustment; - - private long postingtime; - - private double jan_value; - - private double feb_value; - - private double mar_value; - - private double apr_value; - - private double may_value; - - private double jun_value; - - private double jul_value; - - private double aug_value; - - private double sep_value; - - private double oct_value; - - private double nov_value; - - private double dec_value; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public MonthlyValuesRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public MonthlyValuesRecord(MonthlyValuesRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setAdjustment(origRecord.getAdjustment()); - setPostingtime(origRecord.getPostingtime()); - setJan_value(origRecord.getJan_value()); - setFeb_value(origRecord.getFeb_value()); - setMar_value(origRecord.getMar_value()); - setApr_value(origRecord.getApr_value()); - setMay_value(origRecord.getMay_value()); - setJun_value(origRecord.getJun_value()); - setJul_value(origRecord.getJul_value()); - setAug_value(origRecord.getAug_value()); - setSep_value(origRecord.getSep_value()); - setOct_value(origRecord.getOct_value()); - setNov_value(origRecord.getNov_value()); - setDec_value(origRecord.getDec_value()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a MonthlyValues record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public String getAdjustment() - { - return adjustment; - } - - public void setAdjustment(String adjustment) - { - this.adjustment = adjustment ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public double getJan_value() - { - return jan_value; - } - - public void setJan_value(double jan_value) - { - this.jan_value = jan_value ; - } - - public double getFeb_value() - { - return feb_value; - } - - public void setFeb_value(double feb_value) - { - this.feb_value = feb_value ; - } - - public double getMar_value() - { - return mar_value; - } - - public void setMar_value(double mar_value) - { - this.mar_value = mar_value ; - } - - public double getApr_value() - { - return apr_value; - } - - public void setApr_value(double apr_value) - { - this.apr_value = apr_value ; - } - - public double getMay_value() - { - return may_value; - } - - public void setMay_value(double may_value) - { - this.may_value = may_value ; - } - - public double getJun_value() - { - return jun_value; - } - - public void setJun_value(double jun_value) - { - this.jun_value = jun_value ; - } - - public double getJul_value() - { - return jul_value; - } - - public void setJul_value(double jul_value) - { - this.jul_value = jul_value ; - } - - public double getAug_value() - { - return aug_value; - } - - public void setAug_value(double aug_value) - { - this.aug_value = aug_value ; - } - - public double getSep_value() - { - return sep_value; - } - - public void setSep_value(double sep_value) - { - this.sep_value = sep_value ; - } - - public double getOct_value() - { - return oct_value; - } - - public void setOct_value(double oct_value) - { - this.oct_value = oct_value ; - } - - public double getNov_value() - { - return nov_value; - } - - public void setNov_value(double nov_value) - { - this.nov_value = nov_value ; - } - - public double getDec_value() - { - return dec_value; - } - - public void setDec_value(double dec_value) - { - this.dec_value = dec_value ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND adjustment = '" + adjustment + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getAdjustment() + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getJan_value() + " " + - getFeb_value() + " " + - getMar_value() + " " + - getApr_value() + " " + - getMay_value() + " " + - getJun_value() + " " + - getJul_value() + " " + - getAug_value() + " " + - getSep_value() + " " + - getOct_value() + " " + - getNov_value() + " " + - getDec_value() + " " + - "" ; - return outString; - } // end toString() -} // end of MonthlyValuesRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MonthlyValuesTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MonthlyValuesTable.java deleted file mode 100644 index 96c7b0b039..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/MonthlyValuesTable.java +++ /dev/null @@ -1,336 +0,0 @@ -// filename: MonthlyValuesTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// monthlyvalues table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class MonthlyValuesTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// MonthlyValuesTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public MonthlyValuesTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("monthlyvalues"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of MonthlyValuesRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - MonthlyValuesRecord record = null; - - // create a List to hold MonthlyValues Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM monthlyvalues " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a MonthlyValuesRecord - // and store its address in oneRecord - record = new MonthlyValuesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a MonthlyValuesRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setAdjustment(getString(rs, 6)); - record.setPostingtime(getTimeStamp(rs, 7)); - record.setJan_value(getDouble(rs, 8)); - record.setFeb_value(getDouble(rs, 9)); - record.setMar_value(getDouble(rs, 10)); - record.setApr_value(getDouble(rs, 11)); - record.setMay_value(getDouble(rs, 12)); - record.setJun_value(getDouble(rs, 13)); - record.setJul_value(getDouble(rs, 14)); - record.setAug_value(getDouble(rs, 15)); - record.setSep_value(getDouble(rs, 16)); - record.setOct_value(getDouble(rs, 17)); - record.setNov_value(getDouble(rs, 18)); - record.setDec_value(getDouble(rs, 19)); - - // add this MonthlyValuesRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the MonthlyValuesRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of MonthlyValuesRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - MonthlyValuesRecord record = null; - - // create a List to hold MonthlyValues Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM monthlyvalues " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a MonthlyValuesRecord - // and store its address in oneRecord - record = new MonthlyValuesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a MonthlyValuesRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setAdjustment(getString(rs, 6)); - record.setPostingtime(getTimeStamp(rs, 7)); - record.setJan_value(getDouble(rs, 8)); - record.setFeb_value(getDouble(rs, 9)); - record.setMar_value(getDouble(rs, 10)); - record.setApr_value(getDouble(rs, 11)); - record.setMay_value(getDouble(rs, 12)); - record.setJun_value(getDouble(rs, 13)); - record.setJul_value(getDouble(rs, 14)); - record.setAug_value(getDouble(rs, 15)); - record.setSep_value(getDouble(rs, 16)); - record.setOct_value(getDouble(rs, 17)); - record.setNov_value(getDouble(rs, 18)); - record.setDec_value(getDouble(rs, 19)); - - // add this MonthlyValuesRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the MonthlyValuesRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a MonthlyValuesRecord object and.. -//----------------------------------------------------------------- - public int insert(MonthlyValuesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO monthlyvalues VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setString(insertStatement, 6, record.getAdjustment()); - setTimeStamp(insertStatement, 7, record.getPostingtime()); - setDouble(insertStatement, 8, record.getJan_value()); - setDouble(insertStatement, 9, record.getFeb_value()); - setDouble(insertStatement, 10, record.getMar_value()); - setDouble(insertStatement, 11, record.getApr_value()); - setDouble(insertStatement, 12, record.getMay_value()); - setDouble(insertStatement, 13, record.getJun_value()); - setDouble(insertStatement, 14, record.getJul_value()); - setDouble(insertStatement, 15, record.getAug_value()); - setDouble(insertStatement, 16, record.getSep_value()); - setDouble(insertStatement, 17, record.getOct_value()); - setDouble(insertStatement, 18, record.getNov_value()); - setDouble(insertStatement, 19, record.getDec_value()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM monthlyvalues " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a MonthlyValuesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(MonthlyValuesRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE monthlyvalues SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, adjustment = ?, postingtime = ?, jan_value = ?, feb_value = ?, mar_value = ?, apr_value = ?, may_value = ?, jun_value = ?, jul_value = ?, aug_value = ?, sep_value = ?, oct_value = ?, nov_value = ?, dec_value = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setString(updateStatement, 6, record.getAdjustment()); - setTimeStamp(updateStatement, 7, record.getPostingtime()); - setDouble(updateStatement, 8, record.getJan_value()); - setDouble(updateStatement, 9, record.getFeb_value()); - setDouble(updateStatement, 10, record.getMar_value()); - setDouble(updateStatement, 11, record.getApr_value()); - setDouble(updateStatement, 12, record.getMay_value()); - setDouble(updateStatement, 13, record.getJun_value()); - setDouble(updateStatement, 14, record.getJul_value()); - setDouble(updateStatement, 15, record.getAug_value()); - setDouble(updateStatement, 16, record.getSep_value()); - setDouble(updateStatement, 17, record.getOct_value()); - setDouble(updateStatement, 18, record.getNov_value()); - setDouble(updateStatement, 19, record.getDec_value()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(MonthlyValuesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM monthlyvalues " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a MonthlyValuesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(MonthlyValuesRecord oldRecord, MonthlyValuesRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE monthlyvalues SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, adjustment = ?, postingtime = ?, jan_value = ?, feb_value = ?, mar_value = ?, apr_value = ?, may_value = ?, jun_value = ?, jul_value = ?, aug_value = ?, sep_value = ?, oct_value = ?, nov_value = ?, dec_value = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setString(updateStatement, 6, newRecord.getAdjustment()); - setTimeStamp(updateStatement, 7, newRecord.getPostingtime()); - setDouble(updateStatement, 8, newRecord.getJan_value()); - setDouble(updateStatement, 9, newRecord.getFeb_value()); - setDouble(updateStatement, 10, newRecord.getMar_value()); - setDouble(updateStatement, 11, newRecord.getApr_value()); - setDouble(updateStatement, 12, newRecord.getMay_value()); - setDouble(updateStatement, 13, newRecord.getJun_value()); - setDouble(updateStatement, 14, newRecord.getJul_value()); - setDouble(updateStatement, 15, newRecord.getAug_value()); - setDouble(updateStatement, 16, newRecord.getSep_value()); - setDouble(updateStatement, 17, newRecord.getOct_value()); - setDouble(updateStatement, 18, newRecord.getNov_value()); - setDouble(updateStatement, 19, newRecord.getDec_value()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a MonthlyValuesRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(MonthlyValuesRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - MonthlyValuesRecord oldRecord = (MonthlyValuesRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of MonthlyValuesTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NWRTransmitterRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NWRTransmitterRecord.java deleted file mode 100644 index 1d3003671d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NWRTransmitterRecord.java +++ /dev/null @@ -1,237 +0,0 @@ -// filename: NWRTransmitterRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// NWRTransmitter table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class NWRTransmitterRecord extends DbRecord -{ - private String call_sign; - - private String wfo; - - private String city; - - private String county; - - private String state; - - private String coverage_area; - - private double lat; - - private double lon; - - private double transmit_freq; - - private int transmit_power; - - private String transmit_prod_code; - - private String transmit_countynum; - - private String use_transmitter; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public NWRTransmitterRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public NWRTransmitterRecord(NWRTransmitterRecord origRecord) - { - setCall_sign(origRecord.getCall_sign()); - setWfo(origRecord.getWfo()); - setCity(origRecord.getCity()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setCoverage_area(origRecord.getCoverage_area()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setTransmit_freq(origRecord.getTransmit_freq()); - setTransmit_power(origRecord.getTransmit_power()); - setTransmit_prod_code(origRecord.getTransmit_prod_code()); - setTransmit_countynum(origRecord.getTransmit_countynum()); - setUse_transmitter(origRecord.getUse_transmitter()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a NWRTransmitter record - - //----------------------------------------------------------------- - public String getCall_sign() - { - return call_sign; - } - - public void setCall_sign(String call_sign) - { - this.call_sign = call_sign ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getCity() - { - return city; - } - - public void setCity(String city) - { - this.city = city ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getCoverage_area() - { - return coverage_area; - } - - public void setCoverage_area(String coverage_area) - { - this.coverage_area = coverage_area ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public double getTransmit_freq() - { - return transmit_freq; - } - - public void setTransmit_freq(double transmit_freq) - { - this.transmit_freq = transmit_freq ; - } - - public int getTransmit_power() - { - return transmit_power; - } - - public void setTransmit_power(int transmit_power) - { - this.transmit_power = transmit_power ; - } - - public String getTransmit_prod_code() - { - return transmit_prod_code; - } - - public void setTransmit_prod_code(String transmit_prod_code) - { - this.transmit_prod_code = transmit_prod_code ; - } - - public String getTransmit_countynum() - { - return transmit_countynum; - } - - public void setTransmit_countynum(String transmit_countynum) - { - this.transmit_countynum = transmit_countynum ; - } - - public String getUse_transmitter() - { - return use_transmitter; - } - - public void setUse_transmitter(String use_transmitter) - { - this.use_transmitter = use_transmitter ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE call_sign = '" + call_sign + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getCall_sign() + " " + - getWfo() + " " + - getCity() + " " + - getCounty() + " " + - getState() + " " + - getCoverage_area() + " " + - getLat() + " " + - getLon() + " " + - getTransmit_freq() + " " + - getTransmit_power() + " " + - getTransmit_prod_code() + " " + - getTransmit_countynum() + " " + - getUse_transmitter() + " " + - "" ; - return outString; - } // end toString() -} // end of NWRTransmitterRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NWRTransmitterTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NWRTransmitterTable.java deleted file mode 100644 index a060fe0eaf..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NWRTransmitterTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: NWRTransmitterTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// nwrtransmitter table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class NWRTransmitterTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// NWRTransmitterTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public NWRTransmitterTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("nwrtransmitter"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of NWRTransmitterRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - NWRTransmitterRecord record = null; - - // create a List to hold NWRTransmitter Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM nwrtransmitter " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a NWRTransmitterRecord - // and store its address in oneRecord - record = new NWRTransmitterRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a NWRTransmitterRecord object - - record.setCall_sign(getString(rs, 1)); - record.setWfo(getString(rs, 2)); - record.setCity(getString(rs, 3)); - record.setCounty(getString(rs, 4)); - record.setState(getString(rs, 5)); - record.setCoverage_area(getString(rs, 6)); - record.setLat(getDouble(rs, 7)); - record.setLon(getDouble(rs, 8)); - record.setTransmit_freq(getDouble(rs, 9)); - record.setTransmit_power(getInt(rs, 10)); - record.setTransmit_prod_code(getString(rs, 11)); - record.setTransmit_countynum(getString(rs, 12)); - record.setUse_transmitter(getString(rs, 13)); - - // add this NWRTransmitterRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the NWRTransmitterRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of NWRTransmitterRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - NWRTransmitterRecord record = null; - - // create a List to hold NWRTransmitter Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM nwrtransmitter " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a NWRTransmitterRecord - // and store its address in oneRecord - record = new NWRTransmitterRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a NWRTransmitterRecord object - - record.setCall_sign(getString(rs, 1)); - record.setWfo(getString(rs, 2)); - record.setCity(getString(rs, 3)); - record.setCounty(getString(rs, 4)); - record.setState(getString(rs, 5)); - record.setCoverage_area(getString(rs, 6)); - record.setLat(getDouble(rs, 7)); - record.setLon(getDouble(rs, 8)); - record.setTransmit_freq(getDouble(rs, 9)); - record.setTransmit_power(getInt(rs, 10)); - record.setTransmit_prod_code(getString(rs, 11)); - record.setTransmit_countynum(getString(rs, 12)); - record.setUse_transmitter(getString(rs, 13)); - - // add this NWRTransmitterRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the NWRTransmitterRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a NWRTransmitterRecord object and.. -//----------------------------------------------------------------- - public int insert(NWRTransmitterRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO nwrtransmitter VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getCall_sign()); - setString(insertStatement, 2, record.getWfo()); - setString(insertStatement, 3, record.getCity()); - setString(insertStatement, 4, record.getCounty()); - setString(insertStatement, 5, record.getState()); - setString(insertStatement, 6, record.getCoverage_area()); - setDouble(insertStatement, 7, record.getLat()); - setDouble(insertStatement, 8, record.getLon()); - setDouble(insertStatement, 9, record.getTransmit_freq()); - setInt(insertStatement, 10, record.getTransmit_power()); - setString(insertStatement, 11, record.getTransmit_prod_code()); - setString(insertStatement, 12, record.getTransmit_countynum()); - setString(insertStatement, 13, record.getUse_transmitter()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM nwrtransmitter " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a NWRTransmitterRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(NWRTransmitterRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE nwrtransmitter SET call_sign = ?, wfo = ?, city = ?, county = ?, state = ?, coverage_area = ?, lat = ?, lon = ?, transmit_freq = ?, transmit_power = ?, transmit_prod_code = ?, transmit_countynum = ?, use_transmitter = ? " + where ); - - setString(updateStatement, 1, record.getCall_sign()); - setString(updateStatement, 2, record.getWfo()); - setString(updateStatement, 3, record.getCity()); - setString(updateStatement, 4, record.getCounty()); - setString(updateStatement, 5, record.getState()); - setString(updateStatement, 6, record.getCoverage_area()); - setDouble(updateStatement, 7, record.getLat()); - setDouble(updateStatement, 8, record.getLon()); - setDouble(updateStatement, 9, record.getTransmit_freq()); - setInt(updateStatement, 10, record.getTransmit_power()); - setString(updateStatement, 11, record.getTransmit_prod_code()); - setString(updateStatement, 12, record.getTransmit_countynum()); - setString(updateStatement, 13, record.getUse_transmitter()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(NWRTransmitterRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM nwrtransmitter " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a NWRTransmitterRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(NWRTransmitterRecord oldRecord, NWRTransmitterRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE nwrtransmitter SET call_sign = ?, wfo = ?, city = ?, county = ?, state = ?, coverage_area = ?, lat = ?, lon = ?, transmit_freq = ?, transmit_power = ?, transmit_prod_code = ?, transmit_countynum = ?, use_transmitter = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getCall_sign()); - setString(updateStatement, 2, newRecord.getWfo()); - setString(updateStatement, 3, newRecord.getCity()); - setString(updateStatement, 4, newRecord.getCounty()); - setString(updateStatement, 5, newRecord.getState()); - setString(updateStatement, 6, newRecord.getCoverage_area()); - setDouble(updateStatement, 7, newRecord.getLat()); - setDouble(updateStatement, 8, newRecord.getLon()); - setDouble(updateStatement, 9, newRecord.getTransmit_freq()); - setInt(updateStatement, 10, newRecord.getTransmit_power()); - setString(updateStatement, 11, newRecord.getTransmit_prod_code()); - setString(updateStatement, 12, newRecord.getTransmit_countynum()); - setString(updateStatement, 13, newRecord.getUse_transmitter()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a NWRTransmitterRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(NWRTransmitterRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - NWRTransmitterRecord oldRecord = (NWRTransmitterRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of NWRTransmitterTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NetworkRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NetworkRecord.java deleted file mode 100644 index 1dcf82dabc..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NetworkRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: NetworkRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Network table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class NetworkRecord extends DbRecord -{ - private String network; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public NetworkRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public NetworkRecord(NetworkRecord origRecord) - { - setNetwork(origRecord.getNetwork()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Network record - - //----------------------------------------------------------------- - public String getNetwork() - { - return network; - } - - public void setNetwork(String network) - { - this.network = network ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE network = '" + network + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getNetwork() + " " + - "" ; - return outString; - } // end toString() -} // end of NetworkRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NetworkTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NetworkTable.java deleted file mode 100644 index 0b17a66223..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/NetworkTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: NetworkTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// network table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class NetworkTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// NetworkTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public NetworkTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("network"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of NetworkRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - NetworkRecord record = null; - - // create a List to hold Network Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM network " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a NetworkRecord - // and store its address in oneRecord - record = new NetworkRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a NetworkRecord object - - record.setNetwork(getString(rs, 1)); - - // add this NetworkRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the NetworkRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of NetworkRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - NetworkRecord record = null; - - // create a List to hold Network Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM network " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a NetworkRecord - // and store its address in oneRecord - record = new NetworkRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a NetworkRecord object - - record.setNetwork(getString(rs, 1)); - - // add this NetworkRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the NetworkRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a NetworkRecord object and.. -//----------------------------------------------------------------- - public int insert(NetworkRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO network VALUES (? )"); - - setString(insertStatement, 1, record.getNetwork()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM network " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a NetworkRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(NetworkRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE network SET network = ? " + where ); - - setString(updateStatement, 1, record.getNetwork()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(NetworkRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM network " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a NetworkRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(NetworkRecord oldRecord, NetworkRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE network SET network = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getNetwork()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a NetworkRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(NetworkRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - NetworkRecord oldRecord = (NetworkRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of NetworkTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSDataTransRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSDataTransRecord.java deleted file mode 100644 index 6f1735fa11..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSDataTransRecord.java +++ /dev/null @@ -1,141 +0,0 @@ -// filename: OFSDataTransRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// OFSDataTrans table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class OFSDataTransRecord extends DbRecord -{ - private String pe; - - private short dur; - - private String extremum; - - private String ofs_data_type; - - private float fwd_time_window; - - private float bkw_time_window; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public OFSDataTransRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public OFSDataTransRecord(OFSDataTransRecord origRecord) - { - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setExtremum(origRecord.getExtremum()); - setOfs_data_type(origRecord.getOfs_data_type()); - setFwd_time_window(origRecord.getFwd_time_window()); - setBkw_time_window(origRecord.getBkw_time_window()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a OFSDataTrans record - - //----------------------------------------------------------------- - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public String getOfs_data_type() - { - return ofs_data_type; - } - - public void setOfs_data_type(String ofs_data_type) - { - this.ofs_data_type = ofs_data_type ; - } - - public float getFwd_time_window() - { - return fwd_time_window; - } - - public void setFwd_time_window(float fwd_time_window) - { - this.fwd_time_window = fwd_time_window ; - } - - public float getBkw_time_window() - { - return bkw_time_window; - } - - public void setBkw_time_window(float bkw_time_window) - { - this.bkw_time_window = bkw_time_window ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND extremum = '" + extremum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPe() + " " + - getDur() + " " + - getExtremum() + " " + - getOfs_data_type() + " " + - getFwd_time_window() + " " + - getBkw_time_window() + " " + - "" ; - return outString; - } // end toString() -} // end of OFSDataTransRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSDataTransTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSDataTransTable.java deleted file mode 100644 index 22621e050c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSDataTransTable.java +++ /dev/null @@ -1,271 +0,0 @@ -// filename: OFSDataTransTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// ofsdatatrans table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class OFSDataTransTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// OFSDataTransTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public OFSDataTransTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("ofsdatatrans"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of OFSDataTransRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - OFSDataTransRecord record = null; - - // create a List to hold OFSDataTrans Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ofsdatatrans " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a OFSDataTransRecord - // and store its address in oneRecord - record = new OFSDataTransRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a OFSDataTransRecord object - - record.setPe(getString(rs, 1)); - record.setDur(getShort(rs, 2)); - record.setExtremum(getString(rs, 3)); - record.setOfs_data_type(getString(rs, 4)); - record.setFwd_time_window(getReal(rs, 5)); - record.setBkw_time_window(getReal(rs, 6)); - - // add this OFSDataTransRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the OFSDataTransRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of OFSDataTransRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - OFSDataTransRecord record = null; - - // create a List to hold OFSDataTrans Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ofsdatatrans " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a OFSDataTransRecord - // and store its address in oneRecord - record = new OFSDataTransRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a OFSDataTransRecord object - - record.setPe(getString(rs, 1)); - record.setDur(getShort(rs, 2)); - record.setExtremum(getString(rs, 3)); - record.setOfs_data_type(getString(rs, 4)); - record.setFwd_time_window(getReal(rs, 5)); - record.setBkw_time_window(getReal(rs, 6)); - - // add this OFSDataTransRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the OFSDataTransRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a OFSDataTransRecord object and.. -//----------------------------------------------------------------- - public int insert(OFSDataTransRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO ofsdatatrans VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getPe()); - setShort(insertStatement, 2, record.getDur()); - setString(insertStatement, 3, record.getExtremum()); - setString(insertStatement, 4, record.getOfs_data_type()); - setReal(insertStatement, 5, record.getFwd_time_window()); - setReal(insertStatement, 6, record.getBkw_time_window()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ofsdatatrans " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a OFSDataTransRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(OFSDataTransRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ofsdatatrans SET pe = ?, dur = ?, extremum = ?, ofs_data_type = ?, fwd_time_window = ?, bkw_time_window = ? " + where ); - - setString(updateStatement, 1, record.getPe()); - setShort(updateStatement, 2, record.getDur()); - setString(updateStatement, 3, record.getExtremum()); - setString(updateStatement, 4, record.getOfs_data_type()); - setReal(updateStatement, 5, record.getFwd_time_window()); - setReal(updateStatement, 6, record.getBkw_time_window()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(OFSDataTransRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ofsdatatrans " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a OFSDataTransRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(OFSDataTransRecord oldRecord, OFSDataTransRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ofsdatatrans SET pe = ?, dur = ?, extremum = ?, ofs_data_type = ?, fwd_time_window = ?, bkw_time_window = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPe()); - setShort(updateStatement, 2, newRecord.getDur()); - setString(updateStatement, 3, newRecord.getExtremum()); - setString(updateStatement, 4, newRecord.getOfs_data_type()); - setReal(updateStatement, 5, newRecord.getFwd_time_window()); - setReal(updateStatement, 6, newRecord.getBkw_time_window()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a OFSDataTransRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(OFSDataTransRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - OFSDataTransRecord oldRecord = (OFSDataTransRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of OFSDataTransTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSStnTransRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSStnTransRecord.java deleted file mode 100644 index 83c0be7830..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSStnTransRecord.java +++ /dev/null @@ -1,113 +0,0 @@ -// filename: OFSStnTransRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// OFSStnTrans table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class OFSStnTransRecord extends DbRecord -{ - private String lid; - - private String ofs_data_type; - - private String shef_source_code; - - private String ofs_lid; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public OFSStnTransRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public OFSStnTransRecord(OFSStnTransRecord origRecord) - { - setLid(origRecord.getLid()); - setOfs_data_type(origRecord.getOfs_data_type()); - setShef_source_code(origRecord.getShef_source_code()); - setOfs_lid(origRecord.getOfs_lid()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a OFSStnTrans record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getOfs_data_type() - { - return ofs_data_type; - } - - public void setOfs_data_type(String ofs_data_type) - { - this.ofs_data_type = ofs_data_type ; - } - - public String getShef_source_code() - { - return shef_source_code; - } - - public void setShef_source_code(String shef_source_code) - { - this.shef_source_code = shef_source_code ; - } - - public String getOfs_lid() - { - return ofs_lid; - } - - public void setOfs_lid(String ofs_lid) - { - this.ofs_lid = ofs_lid ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ofs_data_type = '" + ofs_data_type + "'" - + " AND shef_source_code = '" + shef_source_code + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getOfs_data_type() + " " + - getShef_source_code() + " " + - getOfs_lid() + " " + - "" ; - return outString; - } // end toString() -} // end of OFSStnTransRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSStnTransTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSStnTransTable.java deleted file mode 100644 index 1c8b07af83..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OFSStnTransTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: OFSStnTransTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// ofsstntrans table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class OFSStnTransTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// OFSStnTransTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public OFSStnTransTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("ofsstntrans"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of OFSStnTransRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - OFSStnTransRecord record = null; - - // create a List to hold OFSStnTrans Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ofsstntrans " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a OFSStnTransRecord - // and store its address in oneRecord - record = new OFSStnTransRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a OFSStnTransRecord object - - record.setLid(getString(rs, 1)); - record.setOfs_data_type(getString(rs, 2)); - record.setShef_source_code(getString(rs, 3)); - record.setOfs_lid(getString(rs, 4)); - - // add this OFSStnTransRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the OFSStnTransRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of OFSStnTransRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - OFSStnTransRecord record = null; - - // create a List to hold OFSStnTrans Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ofsstntrans " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a OFSStnTransRecord - // and store its address in oneRecord - record = new OFSStnTransRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a OFSStnTransRecord object - - record.setLid(getString(rs, 1)); - record.setOfs_data_type(getString(rs, 2)); - record.setShef_source_code(getString(rs, 3)); - record.setOfs_lid(getString(rs, 4)); - - // add this OFSStnTransRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the OFSStnTransRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a OFSStnTransRecord object and.. -//----------------------------------------------------------------- - public int insert(OFSStnTransRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO ofsstntrans VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getOfs_data_type()); - setString(insertStatement, 3, record.getShef_source_code()); - setString(insertStatement, 4, record.getOfs_lid()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ofsstntrans " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a OFSStnTransRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(OFSStnTransRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ofsstntrans SET lid = ?, ofs_data_type = ?, shef_source_code = ?, ofs_lid = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getOfs_data_type()); - setString(updateStatement, 3, record.getShef_source_code()); - setString(updateStatement, 4, record.getOfs_lid()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(OFSStnTransRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ofsstntrans " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a OFSStnTransRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(OFSStnTransRecord oldRecord, OFSStnTransRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ofsstntrans SET lid = ?, ofs_data_type = ?, shef_source_code = ?, ofs_lid = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getOfs_data_type()); - setString(updateStatement, 3, newRecord.getShef_source_code()); - setString(updateStatement, 4, newRecord.getOfs_lid()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a OFSStnTransRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(OFSStnTransRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - OFSStnTransRecord oldRecord = (OFSStnTransRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of OFSStnTransTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ObserverRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ObserverRecord.java deleted file mode 100644 index e83e34ffe6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ObserverRecord.java +++ /dev/null @@ -1,363 +0,0 @@ -// filename: ObserverRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Observer table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ObserverRecord extends DbRecord -{ - private String lid; - - private String a1; - - private String a2; - - private String a3; - - private String city; - - private String state; - - private String zip; - - private String comm; - - private long dos; - - private String gn; - - private String hphone; - - private String firstname; - - private String lastname; - - private String phone; - - private String email; - - private String ornr; - - private double rate; - - private String recip; - - private String rprt; - - private String spons; - - private String ssn; - - private String tsk; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ObserverRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ObserverRecord(ObserverRecord origRecord) - { - setLid(origRecord.getLid()); - setA1(origRecord.getA1()); - setA2(origRecord.getA2()); - setA3(origRecord.getA3()); - setCity(origRecord.getCity()); - setState(origRecord.getState()); - setZip(origRecord.getZip()); - setComm(origRecord.getComm()); - setDos(origRecord.getDos()); - setGn(origRecord.getGn()); - setHphone(origRecord.getHphone()); - setFirstname(origRecord.getFirstname()); - setLastname(origRecord.getLastname()); - setPhone(origRecord.getPhone()); - setEmail(origRecord.getEmail()); - setOrnr(origRecord.getOrnr()); - setRate(origRecord.getRate()); - setRecip(origRecord.getRecip()); - setRprt(origRecord.getRprt()); - setSpons(origRecord.getSpons()); - setSsn(origRecord.getSsn()); - setTsk(origRecord.getTsk()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Observer record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getA1() - { - return a1; - } - - public void setA1(String a1) - { - this.a1 = a1 ; - } - - public String getA2() - { - return a2; - } - - public void setA2(String a2) - { - this.a2 = a2 ; - } - - public String getA3() - { - return a3; - } - - public void setA3(String a3) - { - this.a3 = a3 ; - } - - public String getCity() - { - return city; - } - - public void setCity(String city) - { - this.city = city ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getZip() - { - return zip; - } - - public void setZip(String zip) - { - this.zip = zip ; - } - - public String getComm() - { - return comm; - } - - public void setComm(String comm) - { - this.comm = comm ; - } - - public long getDos() - { - return dos; - } - - public void setDos(long dos) - { - this.dos = dos ; - } - - public String getGn() - { - return gn; - } - - public void setGn(String gn) - { - this.gn = gn ; - } - - public String getHphone() - { - return hphone; - } - - public void setHphone(String hphone) - { - this.hphone = hphone ; - } - - public String getFirstname() - { - return firstname; - } - - public void setFirstname(String firstname) - { - this.firstname = firstname ; - } - - public String getLastname() - { - return lastname; - } - - public void setLastname(String lastname) - { - this.lastname = lastname ; - } - - public String getPhone() - { - return phone; - } - - public void setPhone(String phone) - { - this.phone = phone ; - } - - public String getEmail() - { - return email; - } - - public void setEmail(String email) - { - this.email = email ; - } - - public String getOrnr() - { - return ornr; - } - - public void setOrnr(String ornr) - { - this.ornr = ornr ; - } - - public double getRate() - { - return rate; - } - - public void setRate(double rate) - { - this.rate = rate ; - } - - public String getRecip() - { - return recip; - } - - public void setRecip(String recip) - { - this.recip = recip ; - } - - public String getRprt() - { - return rprt; - } - - public void setRprt(String rprt) - { - this.rprt = rprt ; - } - - public String getSpons() - { - return spons; - } - - public void setSpons(String spons) - { - this.spons = spons ; - } - - public String getSsn() - { - return ssn; - } - - public void setSsn(String ssn) - { - this.ssn = ssn ; - } - - public String getTsk() - { - return tsk; - } - - public void setTsk(String tsk) - { - this.tsk = tsk ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getA1() + " " + - getA2() + " " + - getA3() + " " + - getCity() + " " + - getState() + " " + - getZip() + " " + - getComm() + " " + - getDateStringFromLongTime(getDos()) + " " + - getGn() + " " + - getHphone() + " " + - getFirstname() + " " + - getLastname() + " " + - getPhone() + " " + - getEmail() + " " + - getOrnr() + " " + - getRate() + " " + - getRecip() + " " + - getRprt() + " " + - getSpons() + " " + - getSsn() + " " + - getTsk() + " " + - "" ; - return outString; - } // end toString() -} // end of ObserverRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ObserverTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ObserverTable.java deleted file mode 100644 index 8bce3c548d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ObserverTable.java +++ /dev/null @@ -1,351 +0,0 @@ -// filename: ObserverTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// observer table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ObserverTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ObserverTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ObserverTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("observer"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ObserverRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ObserverRecord record = null; - - // create a List to hold Observer Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM observer " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ObserverRecord - // and store its address in oneRecord - record = new ObserverRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ObserverRecord object - - record.setLid(getString(rs, 1)); - record.setA1(getString(rs, 2)); - record.setA2(getString(rs, 3)); - record.setA3(getString(rs, 4)); - record.setCity(getString(rs, 5)); - record.setState(getString(rs, 6)); - record.setZip(getString(rs, 7)); - record.setComm(getString(rs, 8)); - record.setDos(getDate(rs, 9)); - record.setGn(getString(rs, 10)); - record.setHphone(getString(rs, 11)); - record.setFirstname(getString(rs, 12)); - record.setLastname(getString(rs, 13)); - record.setPhone(getString(rs, 14)); - record.setEmail(getString(rs, 15)); - record.setOrnr(getString(rs, 16)); - record.setRate(getDouble(rs, 17)); - record.setRecip(getString(rs, 18)); - record.setRprt(getString(rs, 19)); - record.setSpons(getString(rs, 20)); - record.setSsn(getString(rs, 21)); - record.setTsk(getString(rs, 22)); - - // add this ObserverRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ObserverRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ObserverRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ObserverRecord record = null; - - // create a List to hold Observer Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM observer " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ObserverRecord - // and store its address in oneRecord - record = new ObserverRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ObserverRecord object - - record.setLid(getString(rs, 1)); - record.setA1(getString(rs, 2)); - record.setA2(getString(rs, 3)); - record.setA3(getString(rs, 4)); - record.setCity(getString(rs, 5)); - record.setState(getString(rs, 6)); - record.setZip(getString(rs, 7)); - record.setComm(getString(rs, 8)); - record.setDos(getDate(rs, 9)); - record.setGn(getString(rs, 10)); - record.setHphone(getString(rs, 11)); - record.setFirstname(getString(rs, 12)); - record.setLastname(getString(rs, 13)); - record.setPhone(getString(rs, 14)); - record.setEmail(getString(rs, 15)); - record.setOrnr(getString(rs, 16)); - record.setRate(getDouble(rs, 17)); - record.setRecip(getString(rs, 18)); - record.setRprt(getString(rs, 19)); - record.setSpons(getString(rs, 20)); - record.setSsn(getString(rs, 21)); - record.setTsk(getString(rs, 22)); - - // add this ObserverRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ObserverRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ObserverRecord object and.. -//----------------------------------------------------------------- - public int insert(ObserverRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO observer VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getA1()); - setString(insertStatement, 3, record.getA2()); - setString(insertStatement, 4, record.getA3()); - setString(insertStatement, 5, record.getCity()); - setString(insertStatement, 6, record.getState()); - setString(insertStatement, 7, record.getZip()); - setString(insertStatement, 8, record.getComm()); - setDate(insertStatement, 9, record.getDos()); - setString(insertStatement, 10, record.getGn()); - setString(insertStatement, 11, record.getHphone()); - setString(insertStatement, 12, record.getFirstname()); - setString(insertStatement, 13, record.getLastname()); - setString(insertStatement, 14, record.getPhone()); - setString(insertStatement, 15, record.getEmail()); - setString(insertStatement, 16, record.getOrnr()); - setDouble(insertStatement, 17, record.getRate()); - setString(insertStatement, 18, record.getRecip()); - setString(insertStatement, 19, record.getRprt()); - setString(insertStatement, 20, record.getSpons()); - setString(insertStatement, 21, record.getSsn()); - setString(insertStatement, 22, record.getTsk()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM observer " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ObserverRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ObserverRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE observer SET lid = ?, a1 = ?, a2 = ?, a3 = ?, city = ?, state = ?, zip = ?, comm = ?, dos = ?, gn = ?, hphone = ?, firstname = ?, lastname = ?, phone = ?, email = ?, ornr = ?, rate = ?, recip = ?, rprt = ?, spons = ?, ssn = ?, tsk = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getA1()); - setString(updateStatement, 3, record.getA2()); - setString(updateStatement, 4, record.getA3()); - setString(updateStatement, 5, record.getCity()); - setString(updateStatement, 6, record.getState()); - setString(updateStatement, 7, record.getZip()); - setString(updateStatement, 8, record.getComm()); - setDate(updateStatement, 9, record.getDos()); - setString(updateStatement, 10, record.getGn()); - setString(updateStatement, 11, record.getHphone()); - setString(updateStatement, 12, record.getFirstname()); - setString(updateStatement, 13, record.getLastname()); - setString(updateStatement, 14, record.getPhone()); - setString(updateStatement, 15, record.getEmail()); - setString(updateStatement, 16, record.getOrnr()); - setDouble(updateStatement, 17, record.getRate()); - setString(updateStatement, 18, record.getRecip()); - setString(updateStatement, 19, record.getRprt()); - setString(updateStatement, 20, record.getSpons()); - setString(updateStatement, 21, record.getSsn()); - setString(updateStatement, 22, record.getTsk()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ObserverRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM observer " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ObserverRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ObserverRecord oldRecord, ObserverRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE observer SET lid = ?, a1 = ?, a2 = ?, a3 = ?, city = ?, state = ?, zip = ?, comm = ?, dos = ?, gn = ?, hphone = ?, firstname = ?, lastname = ?, phone = ?, email = ?, ornr = ?, rate = ?, recip = ?, rprt = ?, spons = ?, ssn = ?, tsk = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getA1()); - setString(updateStatement, 3, newRecord.getA2()); - setString(updateStatement, 4, newRecord.getA3()); - setString(updateStatement, 5, newRecord.getCity()); - setString(updateStatement, 6, newRecord.getState()); - setString(updateStatement, 7, newRecord.getZip()); - setString(updateStatement, 8, newRecord.getComm()); - setDate(updateStatement, 9, newRecord.getDos()); - setString(updateStatement, 10, newRecord.getGn()); - setString(updateStatement, 11, newRecord.getHphone()); - setString(updateStatement, 12, newRecord.getFirstname()); - setString(updateStatement, 13, newRecord.getLastname()); - setString(updateStatement, 14, newRecord.getPhone()); - setString(updateStatement, 15, newRecord.getEmail()); - setString(updateStatement, 16, newRecord.getOrnr()); - setDouble(updateStatement, 17, newRecord.getRate()); - setString(updateStatement, 18, newRecord.getRecip()); - setString(updateStatement, 19, newRecord.getRprt()); - setString(updateStatement, 20, newRecord.getSpons()); - setString(updateStatement, 21, newRecord.getSsn()); - setString(updateStatement, 22, newRecord.getTsk()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ObserverRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ObserverRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ObserverRecord oldRecord = (ObserverRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ObserverTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OfficeNotesRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OfficeNotesRecord.java deleted file mode 100644 index 9993336615..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OfficeNotesRecord.java +++ /dev/null @@ -1,155 +0,0 @@ -// filename: OfficeNotesRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// OfficeNotes table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class OfficeNotesRecord extends DbRecord -{ - private String topic; - - private String id; - - private long datatime; - - private long postingtime; - - private long updatetime; - - private long expiretime; - - private String note; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public OfficeNotesRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public OfficeNotesRecord(OfficeNotesRecord origRecord) - { - setTopic(origRecord.getTopic()); - setId(origRecord.getId()); - setDatatime(origRecord.getDatatime()); - setPostingtime(origRecord.getPostingtime()); - setUpdatetime(origRecord.getUpdatetime()); - setExpiretime(origRecord.getExpiretime()); - setNote(origRecord.getNote()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a OfficeNotes record - - //----------------------------------------------------------------- - public String getTopic() - { - return topic; - } - - public void setTopic(String topic) - { - this.topic = topic ; - } - - public String getId() - { - return id; - } - - public void setId(String id) - { - this.id = id ; - } - - public long getDatatime() - { - return datatime; - } - - public void setDatatime(long datatime) - { - this.datatime = datatime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public long getUpdatetime() - { - return updatetime; - } - - public void setUpdatetime(long updatetime) - { - this.updatetime = updatetime ; - } - - public long getExpiretime() - { - return expiretime; - } - - public void setExpiretime(long expiretime) - { - this.expiretime = expiretime ; - } - - public String getNote() - { - return note; - } - - public void setNote(String note) - { - this.note = note ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE topic = '" + topic + "'" - + " AND id = '" + id + "'" - + " AND postingtime = '" + getDateTimeStringFromLongTime(postingtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getTopic() + " " + - getId() + " " + - getDateTimeStringFromLongTime(getDatatime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getDateTimeStringFromLongTime(getUpdatetime()) + " " + - getDateTimeStringFromLongTime(getExpiretime()) + " " + - getNote() + " " + - "" ; - return outString; - } // end toString() -} // end of OfficeNotesRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OfficeNotesTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OfficeNotesTable.java deleted file mode 100644 index 70764a19b5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/OfficeNotesTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: OfficeNotesTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// officenotes table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class OfficeNotesTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// OfficeNotesTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public OfficeNotesTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("officenotes"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of OfficeNotesRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - OfficeNotesRecord record = null; - - // create a List to hold OfficeNotes Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM officenotes " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a OfficeNotesRecord - // and store its address in oneRecord - record = new OfficeNotesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a OfficeNotesRecord object - - record.setTopic(getString(rs, 1)); - record.setId(getString(rs, 2)); - record.setDatatime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - record.setUpdatetime(getTimeStamp(rs, 5)); - record.setExpiretime(getTimeStamp(rs, 6)); - record.setNote(getString(rs, 7)); - - // add this OfficeNotesRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the OfficeNotesRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of OfficeNotesRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - OfficeNotesRecord record = null; - - // create a List to hold OfficeNotes Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM officenotes " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a OfficeNotesRecord - // and store its address in oneRecord - record = new OfficeNotesRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a OfficeNotesRecord object - - record.setTopic(getString(rs, 1)); - record.setId(getString(rs, 2)); - record.setDatatime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - record.setUpdatetime(getTimeStamp(rs, 5)); - record.setExpiretime(getTimeStamp(rs, 6)); - record.setNote(getString(rs, 7)); - - // add this OfficeNotesRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the OfficeNotesRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a OfficeNotesRecord object and.. -//----------------------------------------------------------------- - public int insert(OfficeNotesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO officenotes VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getTopic()); - setString(insertStatement, 2, record.getId()); - setTimeStamp(insertStatement, 3, record.getDatatime()); - setTimeStamp(insertStatement, 4, record.getPostingtime()); - setTimeStamp(insertStatement, 5, record.getUpdatetime()); - setTimeStamp(insertStatement, 6, record.getExpiretime()); - setString(insertStatement, 7, record.getNote()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM officenotes " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a OfficeNotesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(OfficeNotesRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE officenotes SET topic = ?, id = ?, datatime = ?, postingtime = ?, updatetime = ?, expiretime = ?, note = ? " + where ); - - setString(updateStatement, 1, record.getTopic()); - setString(updateStatement, 2, record.getId()); - setTimeStamp(updateStatement, 3, record.getDatatime()); - setTimeStamp(updateStatement, 4, record.getPostingtime()); - setTimeStamp(updateStatement, 5, record.getUpdatetime()); - setTimeStamp(updateStatement, 6, record.getExpiretime()); - setString(updateStatement, 7, record.getNote()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(OfficeNotesRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM officenotes " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a OfficeNotesRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(OfficeNotesRecord oldRecord, OfficeNotesRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE officenotes SET topic = ?, id = ?, datatime = ?, postingtime = ?, updatetime = ?, expiretime = ?, note = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getTopic()); - setString(updateStatement, 2, newRecord.getId()); - setTimeStamp(updateStatement, 3, newRecord.getDatatime()); - setTimeStamp(updateStatement, 4, newRecord.getPostingtime()); - setTimeStamp(updateStatement, 5, newRecord.getUpdatetime()); - setTimeStamp(updateStatement, 6, newRecord.getExpiretime()); - setString(updateStatement, 7, newRecord.getNote()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a OfficeNotesRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(OfficeNotesRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - OfficeNotesRecord oldRecord = (OfficeNotesRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of OfficeNotesTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PairedValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PairedValueRecord.java deleted file mode 100644 index a05b15f4c8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PairedValueRecord.java +++ /dev/null @@ -1,287 +0,0 @@ -// filename: PairedValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PairedValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PairedValueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private int ref_value; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PairedValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PairedValueRecord(PairedValueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setRef_value(origRecord.getRef_value()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PairedValue record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public int getRef_value() - { - return ref_value; - } - - public void setRef_value(int ref_value) - { - this.ref_value = ref_value ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - + " AND ref_value = '" + ref_value + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getRef_value() + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of PairedValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PairedValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PairedValueTable.java deleted file mode 100644 index ba9a641d45..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PairedValueTable.java +++ /dev/null @@ -1,321 +0,0 @@ -// filename: PairedValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// pairedvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PairedValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PairedValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PairedValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("pairedvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PairedValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PairedValueRecord record = null; - - // create a List to hold PairedValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pairedvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PairedValueRecord - // and store its address in oneRecord - record = new PairedValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PairedValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setRef_value(getInt(rs, 9)); - record.setValue(getDouble(rs, 10)); - record.setShef_qual_code(getString(rs, 11)); - record.setQuality_code(getInt(rs, 12)); - record.setRevision(getShort(rs, 13)); - record.setProduct_id(getString(rs, 14)); - record.setProducttime(getTimeStamp(rs, 15)); - record.setPostingtime(getTimeStamp(rs, 16)); - - // add this PairedValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PairedValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PairedValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PairedValueRecord record = null; - - // create a List to hold PairedValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pairedvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PairedValueRecord - // and store its address in oneRecord - record = new PairedValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PairedValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setRef_value(getInt(rs, 9)); - record.setValue(getDouble(rs, 10)); - record.setShef_qual_code(getString(rs, 11)); - record.setQuality_code(getInt(rs, 12)); - record.setRevision(getShort(rs, 13)); - record.setProduct_id(getString(rs, 14)); - record.setProducttime(getTimeStamp(rs, 15)); - record.setPostingtime(getTimeStamp(rs, 16)); - - // add this PairedValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PairedValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PairedValueRecord object and.. -//----------------------------------------------------------------- - public int insert(PairedValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO pairedvalue VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setInt(insertStatement, 9, record.getRef_value()); - setDouble(insertStatement, 10, record.getValue()); - setString(insertStatement, 11, record.getShef_qual_code()); - setInt(insertStatement, 12, record.getQuality_code()); - setShort(insertStatement, 13, record.getRevision()); - setString(insertStatement, 14, record.getProduct_id()); - setTimeStamp(insertStatement, 15, record.getProducttime()); - setTimeStamp(insertStatement, 16, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pairedvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PairedValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PairedValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pairedvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, ref_value = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setInt(updateStatement, 9, record.getRef_value()); - setDouble(updateStatement, 10, record.getValue()); - setString(updateStatement, 11, record.getShef_qual_code()); - setInt(updateStatement, 12, record.getQuality_code()); - setShort(updateStatement, 13, record.getRevision()); - setString(updateStatement, 14, record.getProduct_id()); - setTimeStamp(updateStatement, 15, record.getProducttime()); - setTimeStamp(updateStatement, 16, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PairedValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pairedvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PairedValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PairedValueRecord oldRecord, PairedValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pairedvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, ref_value = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setInt(updateStatement, 9, newRecord.getRef_value()); - setDouble(updateStatement, 10, newRecord.getValue()); - setString(updateStatement, 11, newRecord.getShef_qual_code()); - setInt(updateStatement, 12, newRecord.getQuality_code()); - setShort(updateStatement, 13, newRecord.getRevision()); - setString(updateStatement, 14, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 15, newRecord.getProducttime()); - setTimeStamp(updateStatement, 16, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PairedValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PairedValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PairedValueRecord oldRecord = (PairedValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PairedValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PerfLogRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PerfLogRecord.java deleted file mode 100644 index 776ae8e5bc..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PerfLogRecord.java +++ /dev/null @@ -1,196 +0,0 @@ -// filename: PerfLogRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PerfLog table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PerfLogRecord extends DbRecord -{ - private String process; - - private long start_time; - - private int num_processed; - - private int num_reads; - - private int num_inserts; - - private int num_updates; - - private int num_deletes; - - private double elapsed_time; - - private double cpu_time; - - private double io_time; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PerfLogRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PerfLogRecord(PerfLogRecord origRecord) - { - setProcess(origRecord.getProcess()); - setStart_time(origRecord.getStart_time()); - setNum_processed(origRecord.getNum_processed()); - setNum_reads(origRecord.getNum_reads()); - setNum_inserts(origRecord.getNum_inserts()); - setNum_updates(origRecord.getNum_updates()); - setNum_deletes(origRecord.getNum_deletes()); - setElapsed_time(origRecord.getElapsed_time()); - setCpu_time(origRecord.getCpu_time()); - setIo_time(origRecord.getIo_time()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PerfLog record - - //----------------------------------------------------------------- - public String getProcess() - { - return process; - } - - public void setProcess(String process) - { - this.process = process ; - } - - public long getStart_time() - { - return start_time; - } - - public void setStart_time(long start_time) - { - this.start_time = start_time ; - } - - public int getNum_processed() - { - return num_processed; - } - - public void setNum_processed(int num_processed) - { - this.num_processed = num_processed ; - } - - public int getNum_reads() - { - return num_reads; - } - - public void setNum_reads(int num_reads) - { - this.num_reads = num_reads ; - } - - public int getNum_inserts() - { - return num_inserts; - } - - public void setNum_inserts(int num_inserts) - { - this.num_inserts = num_inserts ; - } - - public int getNum_updates() - { - return num_updates; - } - - public void setNum_updates(int num_updates) - { - this.num_updates = num_updates ; - } - - public int getNum_deletes() - { - return num_deletes; - } - - public void setNum_deletes(int num_deletes) - { - this.num_deletes = num_deletes ; - } - - public double getElapsed_time() - { - return elapsed_time; - } - - public void setElapsed_time(double elapsed_time) - { - this.elapsed_time = elapsed_time ; - } - - public double getCpu_time() - { - return cpu_time; - } - - public void setCpu_time(double cpu_time) - { - this.cpu_time = cpu_time ; - } - - public double getIo_time() - { - return io_time; - } - - public void setIo_time(double io_time) - { - this.io_time = io_time ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE process = '" + process + "'" - + " AND start_time = '" + getDateTimeStringFromLongTime(start_time) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getProcess() + " " + - getDateTimeStringFromLongTime(getStart_time()) + " " + - getNum_processed() + " " + - getNum_reads() + " " + - getNum_inserts() + " " + - getNum_updates() + " " + - getNum_deletes() + " " + - getElapsed_time() + " " + - getCpu_time() + " " + - getIo_time() + " " + - "" ; - return outString; - } // end toString() -} // end of PerfLogRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PerfLogTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PerfLogTable.java deleted file mode 100644 index 7a2afc9e31..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PerfLogTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: PerfLogTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// perflog table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PerfLogTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PerfLogTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PerfLogTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("perflog"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PerfLogRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PerfLogRecord record = null; - - // create a List to hold PerfLog Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM perflog " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PerfLogRecord - // and store its address in oneRecord - record = new PerfLogRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PerfLogRecord object - - record.setProcess(getString(rs, 1)); - record.setStart_time(getTimeStamp(rs, 2)); - record.setNum_processed(getInt(rs, 3)); - record.setNum_reads(getInt(rs, 4)); - record.setNum_inserts(getInt(rs, 5)); - record.setNum_updates(getInt(rs, 6)); - record.setNum_deletes(getInt(rs, 7)); - record.setElapsed_time(getDouble(rs, 8)); - record.setCpu_time(getDouble(rs, 9)); - record.setIo_time(getDouble(rs, 10)); - - // add this PerfLogRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PerfLogRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PerfLogRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PerfLogRecord record = null; - - // create a List to hold PerfLog Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM perflog " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PerfLogRecord - // and store its address in oneRecord - record = new PerfLogRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PerfLogRecord object - - record.setProcess(getString(rs, 1)); - record.setStart_time(getTimeStamp(rs, 2)); - record.setNum_processed(getInt(rs, 3)); - record.setNum_reads(getInt(rs, 4)); - record.setNum_inserts(getInt(rs, 5)); - record.setNum_updates(getInt(rs, 6)); - record.setNum_deletes(getInt(rs, 7)); - record.setElapsed_time(getDouble(rs, 8)); - record.setCpu_time(getDouble(rs, 9)); - record.setIo_time(getDouble(rs, 10)); - - // add this PerfLogRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PerfLogRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PerfLogRecord object and.. -//----------------------------------------------------------------- - public int insert(PerfLogRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO perflog VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getProcess()); - setTimeStamp(insertStatement, 2, record.getStart_time()); - setInt(insertStatement, 3, record.getNum_processed()); - setInt(insertStatement, 4, record.getNum_reads()); - setInt(insertStatement, 5, record.getNum_inserts()); - setInt(insertStatement, 6, record.getNum_updates()); - setInt(insertStatement, 7, record.getNum_deletes()); - setDouble(insertStatement, 8, record.getElapsed_time()); - setDouble(insertStatement, 9, record.getCpu_time()); - setDouble(insertStatement, 10, record.getIo_time()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM perflog " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PerfLogRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PerfLogRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE perflog SET process = ?, start_time = ?, num_processed = ?, num_reads = ?, num_inserts = ?, num_updates = ?, num_deletes = ?, elapsed_time = ?, cpu_time = ?, io_time = ? " + where ); - - setString(updateStatement, 1, record.getProcess()); - setTimeStamp(updateStatement, 2, record.getStart_time()); - setInt(updateStatement, 3, record.getNum_processed()); - setInt(updateStatement, 4, record.getNum_reads()); - setInt(updateStatement, 5, record.getNum_inserts()); - setInt(updateStatement, 6, record.getNum_updates()); - setInt(updateStatement, 7, record.getNum_deletes()); - setDouble(updateStatement, 8, record.getElapsed_time()); - setDouble(updateStatement, 9, record.getCpu_time()); - setDouble(updateStatement, 10, record.getIo_time()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PerfLogRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM perflog " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PerfLogRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PerfLogRecord oldRecord, PerfLogRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE perflog SET process = ?, start_time = ?, num_processed = ?, num_reads = ?, num_inserts = ?, num_updates = ?, num_deletes = ?, elapsed_time = ?, cpu_time = ?, io_time = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getProcess()); - setTimeStamp(updateStatement, 2, newRecord.getStart_time()); - setInt(updateStatement, 3, newRecord.getNum_processed()); - setInt(updateStatement, 4, newRecord.getNum_reads()); - setInt(updateStatement, 5, newRecord.getNum_inserts()); - setInt(updateStatement, 6, newRecord.getNum_updates()); - setInt(updateStatement, 7, newRecord.getNum_deletes()); - setDouble(updateStatement, 8, newRecord.getElapsed_time()); - setDouble(updateStatement, 9, newRecord.getCpu_time()); - setDouble(updateStatement, 10, newRecord.getIo_time()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PerfLogRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PerfLogRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PerfLogRecord oldRecord = (PerfLogRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PerfLogTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PointDataPresetsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PointDataPresetsRecord.java deleted file mode 100644 index 4333472b80..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PointDataPresetsRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: PointDataPresetsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PointDataPresets table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PointDataPresetsRecord extends DbRecord -{ - private String preset_id; - - private String descr; - - private short preset_rank; - - private String preset_string; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PointDataPresetsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PointDataPresetsRecord(PointDataPresetsRecord origRecord) - { - setPreset_id(origRecord.getPreset_id()); - setDescr(origRecord.getDescr()); - setPreset_rank(origRecord.getPreset_rank()); - setPreset_string(origRecord.getPreset_string()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PointDataPresets record - - //----------------------------------------------------------------- - public String getPreset_id() - { - return preset_id; - } - - public void setPreset_id(String preset_id) - { - this.preset_id = preset_id ; - } - - public String getDescr() - { - return descr; - } - - public void setDescr(String descr) - { - this.descr = descr ; - } - - public short getPreset_rank() - { - return preset_rank; - } - - public void setPreset_rank(short preset_rank) - { - this.preset_rank = preset_rank ; - } - - public String getPreset_string() - { - return preset_string; - } - - public void setPreset_string(String preset_string) - { - this.preset_string = preset_string ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE preset_id = '" + preset_id + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPreset_id() + " " + - getDescr() + " " + - getPreset_rank() + " " + - getPreset_string() + " " + - "" ; - return outString; - } // end toString() -} // end of PointDataPresetsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PointDataPresetsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PointDataPresetsTable.java deleted file mode 100644 index c97787148b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PointDataPresetsTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: PointDataPresetsTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// pointdatapresets table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PointDataPresetsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PointDataPresetsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PointDataPresetsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("pointdatapresets"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PointDataPresetsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PointDataPresetsRecord record = null; - - // create a List to hold PointDataPresets Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pointdatapresets " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PointDataPresetsRecord - // and store its address in oneRecord - record = new PointDataPresetsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PointDataPresetsRecord object - - record.setPreset_id(getString(rs, 1)); - record.setDescr(getString(rs, 2)); - record.setPreset_rank(getShort(rs, 3)); - record.setPreset_string(getString(rs, 4)); - - // add this PointDataPresetsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PointDataPresetsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PointDataPresetsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PointDataPresetsRecord record = null; - - // create a List to hold PointDataPresets Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pointdatapresets " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PointDataPresetsRecord - // and store its address in oneRecord - record = new PointDataPresetsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PointDataPresetsRecord object - - record.setPreset_id(getString(rs, 1)); - record.setDescr(getString(rs, 2)); - record.setPreset_rank(getShort(rs, 3)); - record.setPreset_string(getString(rs, 4)); - - // add this PointDataPresetsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PointDataPresetsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PointDataPresetsRecord object and.. -//----------------------------------------------------------------- - public int insert(PointDataPresetsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO pointdatapresets VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getPreset_id()); - setString(insertStatement, 2, record.getDescr()); - setShort(insertStatement, 3, record.getPreset_rank()); - setString(insertStatement, 4, record.getPreset_string()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pointdatapresets " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PointDataPresetsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PointDataPresetsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pointdatapresets SET preset_id = ?, descr = ?, preset_rank = ?, preset_string = ? " + where ); - - setString(updateStatement, 1, record.getPreset_id()); - setString(updateStatement, 2, record.getDescr()); - setShort(updateStatement, 3, record.getPreset_rank()); - setString(updateStatement, 4, record.getPreset_string()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PointDataPresetsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pointdatapresets " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PointDataPresetsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PointDataPresetsRecord oldRecord, PointDataPresetsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pointdatapresets SET preset_id = ?, descr = ?, preset_rank = ?, preset_string = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPreset_id()); - setString(updateStatement, 2, newRecord.getDescr()); - setShort(updateStatement, 3, newRecord.getPreset_rank()); - setString(updateStatement, 4, newRecord.getPreset_string()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PointDataPresetsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PointDataPresetsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PointDataPresetsRecord oldRecord = (PointDataPresetsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PointDataPresetsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PostProcessorRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PostProcessorRecord.java deleted file mode 100644 index 086ce28312..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PostProcessorRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: PostProcessorRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PostProcessor table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PostProcessorRecord extends DbRecord -{ - private String post_processor; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PostProcessorRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PostProcessorRecord(PostProcessorRecord origRecord) - { - setPost_processor(origRecord.getPost_processor()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PostProcessor record - - //----------------------------------------------------------------- - public String getPost_processor() - { - return post_processor; - } - - public void setPost_processor(String post_processor) - { - this.post_processor = post_processor ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE post_processor = '" + post_processor + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPost_processor() + " " + - "" ; - return outString; - } // end toString() -} // end of PostProcessorRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PostProcessorTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PostProcessorTable.java deleted file mode 100644 index ab99a0bd91..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PostProcessorTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: PostProcessorTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// postprocessor table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PostProcessorTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PostProcessorTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PostProcessorTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("postprocessor"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PostProcessorRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PostProcessorRecord record = null; - - // create a List to hold PostProcessor Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM postprocessor " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PostProcessorRecord - // and store its address in oneRecord - record = new PostProcessorRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PostProcessorRecord object - - record.setPost_processor(getString(rs, 1)); - - // add this PostProcessorRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PostProcessorRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PostProcessorRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PostProcessorRecord record = null; - - // create a List to hold PostProcessor Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM postprocessor " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PostProcessorRecord - // and store its address in oneRecord - record = new PostProcessorRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PostProcessorRecord object - - record.setPost_processor(getString(rs, 1)); - - // add this PostProcessorRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PostProcessorRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PostProcessorRecord object and.. -//----------------------------------------------------------------- - public int insert(PostProcessorRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO postprocessor VALUES (? )"); - - setString(insertStatement, 1, record.getPost_processor()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM postprocessor " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PostProcessorRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PostProcessorRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE postprocessor SET post_processor = ? " + where ); - - setString(updateStatement, 1, record.getPost_processor()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PostProcessorRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM postprocessor " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PostProcessorRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PostProcessorRecord oldRecord, PostProcessorRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE postprocessor SET post_processor = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPost_processor()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PostProcessorRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PostProcessorRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PostProcessorRecord oldRecord = (PostProcessorRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PostProcessorTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PowerRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PowerRecord.java deleted file mode 100644 index 728c17e4b4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PowerRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: PowerRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Power table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PowerRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PowerRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PowerRecord(PowerRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Power record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of PowerRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PowerTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PowerTable.java deleted file mode 100644 index f4708904d9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PowerTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: PowerTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// power table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PowerTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PowerTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PowerTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("power"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PowerRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PowerRecord record = null; - - // create a List to hold Power Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM power " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PowerRecord - // and store its address in oneRecord - record = new PowerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PowerRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this PowerRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PowerRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PowerRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PowerRecord record = null; - - // create a List to hold Power Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM power " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PowerRecord - // and store its address in oneRecord - record = new PowerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PowerRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this PowerRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PowerRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PowerRecord object and.. -//----------------------------------------------------------------- - public int insert(PowerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO power VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM power " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PowerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PowerRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE power SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PowerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM power " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PowerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PowerRecord oldRecord, PowerRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE power SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PowerRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PowerRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PowerRecord oldRecord = (PowerRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PowerTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PressureRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PressureRecord.java deleted file mode 100644 index 32cc0b5c03..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PressureRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: PressureRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Pressure table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PressureRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PressureRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PressureRecord(PressureRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Pressure record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of PressureRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PressureTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PressureTable.java deleted file mode 100644 index d22f39135f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PressureTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: PressureTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// pressure table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PressureTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PressureTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PressureTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("pressure"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PressureRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PressureRecord record = null; - - // create a List to hold Pressure Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pressure " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PressureRecord - // and store its address in oneRecord - record = new PressureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PressureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this PressureRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PressureRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PressureRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PressureRecord record = null; - - // create a List to hold Pressure Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pressure " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PressureRecord - // and store its address in oneRecord - record = new PressureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PressureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this PressureRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PressureRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PressureRecord object and.. -//----------------------------------------------------------------- - public int insert(PressureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO pressure VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pressure " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PressureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PressureRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pressure SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PressureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pressure " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PressureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PressureRecord oldRecord, PressureRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pressure SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PressureRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PressureRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PressureRecord oldRecord = (PressureRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PressureTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PrevProdRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PrevProdRecord.java deleted file mode 100644 index 98b79c42ed..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PrevProdRecord.java +++ /dev/null @@ -1,114 +0,0 @@ -// This is a view record ! -// filename: PrevProdRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PrevProd table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PrevProdRecord extends DbRecord -{ - private String product_id; - - private long producttime; - - private long postingtime; - - private String prodtype; - - private int issnum; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PrevProdRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PrevProdRecord(PrevProdRecord origRecord) - { - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - setProdtype(origRecord.getProdtype()); - setIssnum(origRecord.getIssnum()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PrevProd record - - //----------------------------------------------------------------- - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public String getProdtype() - { - return prodtype; - } - - public void setProdtype(String prodtype) - { - this.prodtype = prodtype ; - } - - public int getIssnum() - { - return issnum; - } - - public void setIssnum(int issnum) - { - this.issnum = issnum ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getProdtype() + " " + - getIssnum() + " " + - "" ; - return outString; - } // end toString() -} // end of PrevProdRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PrevProdView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PrevProdView.java deleted file mode 100644 index 939a8be60e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PrevProdView.java +++ /dev/null @@ -1,139 +0,0 @@ -// filename: PrevProdView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// prevprod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PrevProdView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PrevProdTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PrevProdView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("prevprod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PrevProdRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PrevProdRecord record = null; - - // create a List to hold PrevProd Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM prevprod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PrevProdRecord - // and store its address in oneRecord - record = new PrevProdRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PrevProdRecord object - - record.setProduct_id(getString(rs, 1)); - record.setProducttime(getTimeStamp(rs, 2)); - record.setPostingtime(getTimeStamp(rs, 3)); - record.setProdtype(getString(rs, 4)); - record.setIssnum(getInt(rs, 5)); - - // add this PrevProdRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PrevProdRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PrevProdRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PrevProdRecord record = null; - - // create a List to hold PrevProd Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM prevprod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PrevProdRecord - // and store its address in oneRecord - record = new PrevProdRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PrevProdRecord object - - record.setProduct_id(getString(rs, 1)); - record.setProducttime(getTimeStamp(rs, 2)); - record.setPostingtime(getTimeStamp(rs, 3)); - record.setProdtype(getString(rs, 4)); - record.setIssnum(getInt(rs, 5)); - - // add this PrevProdRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PrevProdRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of PrevProdTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProcValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProcValueRecord.java deleted file mode 100644 index 2d7f83131f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProcValueRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: ProcValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ProcValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ProcValueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ProcValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ProcValueRecord(ProcValueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ProcValue record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of ProcValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProcValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProcValueTable.java deleted file mode 100644 index f752ba3499..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProcValueTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: ProcValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// procvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ProcValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ProcValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ProcValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("procvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ProcValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ProcValueRecord record = null; - - // create a List to hold ProcValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM procvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ProcValueRecord - // and store its address in oneRecord - record = new ProcValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ProcValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this ProcValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ProcValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ProcValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ProcValueRecord record = null; - - // create a List to hold ProcValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM procvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ProcValueRecord - // and store its address in oneRecord - record = new ProcValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ProcValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this ProcValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ProcValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ProcValueRecord object and.. -//----------------------------------------------------------------- - public int insert(ProcValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO procvalue VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM procvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ProcValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ProcValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE procvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ProcValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM procvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ProcValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ProcValueRecord oldRecord, ProcValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE procvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ProcValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ProcValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ProcValueRecord oldRecord = (ProcValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ProcValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProductLinkRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProductLinkRecord.java deleted file mode 100644 index 9f435fdd7d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProductLinkRecord.java +++ /dev/null @@ -1,114 +0,0 @@ -// filename: ProductLinkRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ProductLink table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ProductLinkRecord extends DbRecord -{ - private String lid; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ProductLinkRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ProductLinkRecord(ProductLinkRecord origRecord) - { - setLid(origRecord.getLid()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ProductLink record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND product_id = '" + product_id + "'" - + " AND producttime = '" + getDateTimeStringFromLongTime(producttime) + "'" - + " AND postingtime = '" + getDateTimeStringFromLongTime(postingtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of ProductLinkRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProductLinkTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProductLinkTable.java deleted file mode 100644 index b8ec066262..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProductLinkTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: ProductLinkTable.java -// author : DBGEN -// created : Tue May 31 17:52:25 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// productlink table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ProductLinkTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ProductLinkTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ProductLinkTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("productlink"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ProductLinkRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ProductLinkRecord record = null; - - // create a List to hold ProductLink Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM productlink " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ProductLinkRecord - // and store its address in oneRecord - record = new ProductLinkRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ProductLinkRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - - // add this ProductLinkRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ProductLinkRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ProductLinkRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ProductLinkRecord record = null; - - // create a List to hold ProductLink Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM productlink " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ProductLinkRecord - // and store its address in oneRecord - record = new ProductLinkRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ProductLinkRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - - // add this ProductLinkRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ProductLinkRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ProductLinkRecord object and.. -//----------------------------------------------------------------- - public int insert(ProductLinkRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO productlink VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getProduct_id()); - setTimeStamp(insertStatement, 3, record.getProducttime()); - setTimeStamp(insertStatement, 4, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM productlink " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ProductLinkRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ProductLinkRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE productlink SET lid = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getProduct_id()); - setTimeStamp(updateStatement, 3, record.getProducttime()); - setTimeStamp(updateStatement, 4, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ProductLinkRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM productlink " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ProductLinkRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ProductLinkRecord oldRecord, ProductLinkRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE productlink SET lid = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 3, newRecord.getProducttime()); - setTimeStamp(updateStatement, 4, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ProductLinkRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ProductLinkRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ProductLinkRecord oldRecord = (ProductLinkRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ProductLinkTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProximityRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProximityRecord.java deleted file mode 100644 index f1b70517f4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProximityRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: ProximityRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Proximity table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ProximityRecord extends DbRecord -{ - private String proximity; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ProximityRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ProximityRecord(ProximityRecord origRecord) - { - setProximity(origRecord.getProximity()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Proximity record - - //----------------------------------------------------------------- - public String getProximity() - { - return proximity; - } - - public void setProximity(String proximity) - { - this.proximity = proximity ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE proximity = '" + proximity + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getProximity() + " " + - "" ; - return outString; - } // end toString() -} // end of ProximityRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProximityTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProximityTable.java deleted file mode 100644 index f095d3293b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ProximityTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: ProximityTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// proximity table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ProximityTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ProximityTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ProximityTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("proximity"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ProximityRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ProximityRecord record = null; - - // create a List to hold Proximity Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM proximity " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ProximityRecord - // and store its address in oneRecord - record = new ProximityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ProximityRecord object - - record.setProximity(getString(rs, 1)); - - // add this ProximityRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ProximityRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ProximityRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ProximityRecord record = null; - - // create a List to hold Proximity Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM proximity " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ProximityRecord - // and store its address in oneRecord - record = new ProximityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ProximityRecord object - - record.setProximity(getString(rs, 1)); - - // add this ProximityRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ProximityRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ProximityRecord object and.. -//----------------------------------------------------------------- - public int insert(ProximityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO proximity VALUES (? )"); - - setString(insertStatement, 1, record.getProximity()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM proximity " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ProximityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ProximityRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE proximity SET proximity = ? " + where ); - - setString(updateStatement, 1, record.getProximity()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ProximityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM proximity " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ProximityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ProximityRecord oldRecord, ProximityRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE proximity SET proximity = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getProximity()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ProximityRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ProximityRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ProximityRecord oldRecord = (ProximityRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ProximityTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PseudoGageValRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PseudoGageValRecord.java deleted file mode 100644 index f53f453b0c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PseudoGageValRecord.java +++ /dev/null @@ -1,154 +0,0 @@ -// filename: PseudoGageValRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PseudoGageVal table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PseudoGageValRecord extends DbRecord -{ - private String pseudo_gage_id; - - private long obstime; - - private double lat; - - private double lon; - - private float gage_value; - - private String man_edited; - - private float prev_gage_value; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PseudoGageValRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PseudoGageValRecord(PseudoGageValRecord origRecord) - { - setPseudo_gage_id(origRecord.getPseudo_gage_id()); - setObstime(origRecord.getObstime()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setGage_value(origRecord.getGage_value()); - setMan_edited(origRecord.getMan_edited()); - setPrev_gage_value(origRecord.getPrev_gage_value()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PseudoGageVal record - - //----------------------------------------------------------------- - public String getPseudo_gage_id() - { - return pseudo_gage_id; - } - - public void setPseudo_gage_id(String pseudo_gage_id) - { - this.pseudo_gage_id = pseudo_gage_id ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public float getGage_value() - { - return gage_value; - } - - public void setGage_value(float gage_value) - { - this.gage_value = gage_value ; - } - - public String getMan_edited() - { - return man_edited; - } - - public void setMan_edited(String man_edited) - { - this.man_edited = man_edited ; - } - - public float getPrev_gage_value() - { - return prev_gage_value; - } - - public void setPrev_gage_value(float prev_gage_value) - { - this.prev_gage_value = prev_gage_value ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE pseudo_gage_id = '" + pseudo_gage_id + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPseudo_gage_id() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getLat() + " " + - getLon() + " " + - getGage_value() + " " + - getMan_edited() + " " + - getPrev_gage_value() + " " + - "" ; - return outString; - } // end toString() -} // end of PseudoGageValRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PseudoGageValTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PseudoGageValTable.java deleted file mode 100644 index 8c9af31675..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PseudoGageValTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: PseudoGageValTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// pseudogageval table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PseudoGageValTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PseudoGageValTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PseudoGageValTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("pseudogageval"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PseudoGageValRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PseudoGageValRecord record = null; - - // create a List to hold PseudoGageVal Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pseudogageval " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PseudoGageValRecord - // and store its address in oneRecord - record = new PseudoGageValRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PseudoGageValRecord object - - record.setPseudo_gage_id(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setGage_value(getReal(rs, 5)); - record.setMan_edited(getString(rs, 6)); - record.setPrev_gage_value(getReal(rs, 7)); - - // add this PseudoGageValRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PseudoGageValRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PseudoGageValRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PseudoGageValRecord record = null; - - // create a List to hold PseudoGageVal Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pseudogageval " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PseudoGageValRecord - // and store its address in oneRecord - record = new PseudoGageValRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PseudoGageValRecord object - - record.setPseudo_gage_id(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setLat(getDouble(rs, 3)); - record.setLon(getDouble(rs, 4)); - record.setGage_value(getReal(rs, 5)); - record.setMan_edited(getString(rs, 6)); - record.setPrev_gage_value(getReal(rs, 7)); - - // add this PseudoGageValRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PseudoGageValRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PseudoGageValRecord object and.. -//----------------------------------------------------------------- - public int insert(PseudoGageValRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO pseudogageval VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getPseudo_gage_id()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setDouble(insertStatement, 3, record.getLat()); - setDouble(insertStatement, 4, record.getLon()); - setReal(insertStatement, 5, record.getGage_value()); - setString(insertStatement, 6, record.getMan_edited()); - setReal(insertStatement, 7, record.getPrev_gage_value()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pseudogageval " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PseudoGageValRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PseudoGageValRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pseudogageval SET pseudo_gage_id = ?, obstime = ?, lat = ?, lon = ?, gage_value = ?, man_edited = ?, prev_gage_value = ? " + where ); - - setString(updateStatement, 1, record.getPseudo_gage_id()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setDouble(updateStatement, 3, record.getLat()); - setDouble(updateStatement, 4, record.getLon()); - setReal(updateStatement, 5, record.getGage_value()); - setString(updateStatement, 6, record.getMan_edited()); - setReal(updateStatement, 7, record.getPrev_gage_value()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PseudoGageValRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pseudogageval " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PseudoGageValRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PseudoGageValRecord oldRecord, PseudoGageValRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pseudogageval SET pseudo_gage_id = ?, obstime = ?, lat = ?, lon = ?, gage_value = ?, man_edited = ?, prev_gage_value = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPseudo_gage_id()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setDouble(updateStatement, 3, newRecord.getLat()); - setDouble(updateStatement, 4, newRecord.getLon()); - setReal(updateStatement, 5, newRecord.getGage_value()); - setString(updateStatement, 6, newRecord.getMan_edited()); - setReal(updateStatement, 7, newRecord.getPrev_gage_value()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PseudoGageValRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PseudoGageValRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PseudoGageValRecord oldRecord = (PseudoGageValRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PseudoGageValTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PubRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PubRecord.java deleted file mode 100644 index 2014b2b531..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PubRecord.java +++ /dev/null @@ -1,113 +0,0 @@ -// filename: PubRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Pub table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PubRecord extends DbRecord -{ - private String lid; - - private long pbegin; - - private String ppub; - - private long pend; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PubRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PubRecord(PubRecord origRecord) - { - setLid(origRecord.getLid()); - setPbegin(origRecord.getPbegin()); - setPpub(origRecord.getPpub()); - setPend(origRecord.getPend()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Pub record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getPbegin() - { - return pbegin; - } - - public void setPbegin(long pbegin) - { - this.pbegin = pbegin ; - } - - public String getPpub() - { - return ppub; - } - - public void setPpub(String ppub) - { - this.ppub = ppub ; - } - - public long getPend() - { - return pend; - } - - public void setPend(long pend) - { - this.pend = pend ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pbegin = '" + getDateStringFromLongTime(pbegin) + "'" - + " AND ppub = '" + ppub + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateStringFromLongTime(getPbegin()) + " " + - getPpub() + " " + - getDateStringFromLongTime(getPend()) + " " + - "" ; - return outString; - } // end toString() -} // end of PubRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PubTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PubTable.java deleted file mode 100644 index a9a9e65c60..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PubTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: PubTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// pub table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PubTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PubTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PubTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("pub"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PubRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PubRecord record = null; - - // create a List to hold Pub Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pub " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PubRecord - // and store its address in oneRecord - record = new PubRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PubRecord object - - record.setLid(getString(rs, 1)); - record.setPbegin(getDate(rs, 2)); - record.setPpub(getString(rs, 3)); - record.setPend(getDate(rs, 4)); - - // add this PubRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PubRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PubRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PubRecord record = null; - - // create a List to hold Pub Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM pub " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PubRecord - // and store its address in oneRecord - record = new PubRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PubRecord object - - record.setLid(getString(rs, 1)); - record.setPbegin(getDate(rs, 2)); - record.setPpub(getString(rs, 3)); - record.setPend(getDate(rs, 4)); - - // add this PubRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PubRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PubRecord object and.. -//----------------------------------------------------------------- - public int insert(PubRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO pub VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDate(insertStatement, 2, record.getPbegin()); - setString(insertStatement, 3, record.getPpub()); - setDate(insertStatement, 4, record.getPend()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pub " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PubRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PubRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pub SET lid = ?, pbegin = ?, ppub = ?, pend = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDate(updateStatement, 2, record.getPbegin()); - setString(updateStatement, 3, record.getPpub()); - setDate(updateStatement, 4, record.getPend()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PubRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM pub " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PubRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PubRecord oldRecord, PubRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE pub SET lid = ?, pbegin = ?, ppub = ?, pend = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDate(updateStatement, 2, newRecord.getPbegin()); - setString(updateStatement, 3, newRecord.getPpub()); - setDate(updateStatement, 4, newRecord.getPend()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PubRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PubRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PubRecord oldRecord = (PubRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PubTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeDynDataRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeDynDataRecord.java deleted file mode 100644 index f3317c6af6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeDynDataRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: PurgeDynDataRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PurgeDynData table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PurgeDynDataRecord extends DbRecord -{ - private String table_name; - - private String time_column_name; - - private int num_hours_host; - - private int num_hours_backup; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PurgeDynDataRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PurgeDynDataRecord(PurgeDynDataRecord origRecord) - { - setTable_name(origRecord.getTable_name()); - setTime_column_name(origRecord.getTime_column_name()); - setNum_hours_host(origRecord.getNum_hours_host()); - setNum_hours_backup(origRecord.getNum_hours_backup()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PurgeDynData record - - //----------------------------------------------------------------- - public String getTable_name() - { - return table_name; - } - - public void setTable_name(String table_name) - { - this.table_name = table_name ; - } - - public String getTime_column_name() - { - return time_column_name; - } - - public void setTime_column_name(String time_column_name) - { - this.time_column_name = time_column_name ; - } - - public int getNum_hours_host() - { - return num_hours_host; - } - - public void setNum_hours_host(int num_hours_host) - { - this.num_hours_host = num_hours_host ; - } - - public int getNum_hours_backup() - { - return num_hours_backup; - } - - public void setNum_hours_backup(int num_hours_backup) - { - this.num_hours_backup = num_hours_backup ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE table_name = '" + table_name + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getTable_name() + " " + - getTime_column_name() + " " + - getNum_hours_host() + " " + - getNum_hours_backup() + " " + - "" ; - return outString; - } // end toString() -} // end of PurgeDynDataRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeDynDataTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeDynDataTable.java deleted file mode 100644 index fe17651335..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeDynDataTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: PurgeDynDataTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// purgedyndata table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PurgeDynDataTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PurgeDynDataTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PurgeDynDataTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("purgedyndata"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PurgeDynDataRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PurgeDynDataRecord record = null; - - // create a List to hold PurgeDynData Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM purgedyndata " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PurgeDynDataRecord - // and store its address in oneRecord - record = new PurgeDynDataRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PurgeDynDataRecord object - - record.setTable_name(getString(rs, 1)); - record.setTime_column_name(getString(rs, 2)); - record.setNum_hours_host(getInt(rs, 3)); - record.setNum_hours_backup(getInt(rs, 4)); - - // add this PurgeDynDataRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PurgeDynDataRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PurgeDynDataRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PurgeDynDataRecord record = null; - - // create a List to hold PurgeDynData Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM purgedyndata " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PurgeDynDataRecord - // and store its address in oneRecord - record = new PurgeDynDataRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PurgeDynDataRecord object - - record.setTable_name(getString(rs, 1)); - record.setTime_column_name(getString(rs, 2)); - record.setNum_hours_host(getInt(rs, 3)); - record.setNum_hours_backup(getInt(rs, 4)); - - // add this PurgeDynDataRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PurgeDynDataRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PurgeDynDataRecord object and.. -//----------------------------------------------------------------- - public int insert(PurgeDynDataRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO purgedyndata VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getTable_name()); - setString(insertStatement, 2, record.getTime_column_name()); - setInt(insertStatement, 3, record.getNum_hours_host()); - setInt(insertStatement, 4, record.getNum_hours_backup()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM purgedyndata " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PurgeDynDataRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PurgeDynDataRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE purgedyndata SET table_name = ?, time_column_name = ?, num_hours_host = ?, num_hours_backup = ? " + where ); - - setString(updateStatement, 1, record.getTable_name()); - setString(updateStatement, 2, record.getTime_column_name()); - setInt(updateStatement, 3, record.getNum_hours_host()); - setInt(updateStatement, 4, record.getNum_hours_backup()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PurgeDynDataRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM purgedyndata " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PurgeDynDataRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PurgeDynDataRecord oldRecord, PurgeDynDataRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE purgedyndata SET table_name = ?, time_column_name = ?, num_hours_host = ?, num_hours_backup = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getTable_name()); - setString(updateStatement, 2, newRecord.getTime_column_name()); - setInt(updateStatement, 3, newRecord.getNum_hours_host()); - setInt(updateStatement, 4, newRecord.getNum_hours_backup()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PurgeDynDataRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PurgeDynDataRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PurgeDynDataRecord oldRecord = (PurgeDynDataRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PurgeDynDataTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeProductRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeProductRecord.java deleted file mode 100644 index 42cca03111..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeProductRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: PurgeProductRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// PurgeProduct table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class PurgeProductRecord extends DbRecord -{ - private String product_id; - - private int num_versions; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public PurgeProductRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public PurgeProductRecord(PurgeProductRecord origRecord) - { - setProduct_id(origRecord.getProduct_id()); - setNum_versions(origRecord.getNum_versions()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a PurgeProduct record - - //----------------------------------------------------------------- - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public int getNum_versions() - { - return num_versions; - } - - public void setNum_versions(int num_versions) - { - this.num_versions = num_versions ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE product_id = '" + product_id + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getProduct_id() + " " + - getNum_versions() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of PurgeProductRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeProductTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeProductTable.java deleted file mode 100644 index 15921968ad..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/PurgeProductTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: PurgeProductTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// purgeproduct table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class PurgeProductTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// PurgeProductTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public PurgeProductTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("purgeproduct"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of PurgeProductRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - PurgeProductRecord record = null; - - // create a List to hold PurgeProduct Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM purgeproduct " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PurgeProductRecord - // and store its address in oneRecord - record = new PurgeProductRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PurgeProductRecord object - - record.setProduct_id(getString(rs, 1)); - record.setNum_versions(getInt(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - - // add this PurgeProductRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the PurgeProductRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of PurgeProductRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - PurgeProductRecord record = null; - - // create a List to hold PurgeProduct Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM purgeproduct " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a PurgeProductRecord - // and store its address in oneRecord - record = new PurgeProductRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a PurgeProductRecord object - - record.setProduct_id(getString(rs, 1)); - record.setNum_versions(getInt(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - - // add this PurgeProductRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the PurgeProductRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a PurgeProductRecord object and.. -//----------------------------------------------------------------- - public int insert(PurgeProductRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO purgeproduct VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getProduct_id()); - setInt(insertStatement, 2, record.getNum_versions()); - setTimeStamp(insertStatement, 3, record.getProducttime()); - setTimeStamp(insertStatement, 4, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM purgeproduct " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PurgeProductRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PurgeProductRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE purgeproduct SET product_id = ?, num_versions = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getProduct_id()); - setInt(updateStatement, 2, record.getNum_versions()); - setTimeStamp(updateStatement, 3, record.getProducttime()); - setTimeStamp(updateStatement, 4, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(PurgeProductRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM purgeproduct " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a PurgeProductRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(PurgeProductRecord oldRecord, PurgeProductRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE purgeproduct SET product_id = ?, num_versions = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getProduct_id()); - setInt(updateStatement, 2, newRecord.getNum_versions()); - setTimeStamp(updateStatement, 3, newRecord.getProducttime()); - setTimeStamp(updateStatement, 4, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a PurgeProductRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(PurgeProductRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - PurgeProductRecord oldRecord = (PurgeProductRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of PurgeProductTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasDynRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasDynRecord.java deleted file mode 100644 index 6a5cd49da1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasDynRecord.java +++ /dev/null @@ -1,170 +0,0 @@ -// filename: RWBiasDynRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RWBiasDyn table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RWBiasDynRecord extends DbRecord -{ - private String radid; - - private String office_id; - - private long obstime; - - private short memspan_ind; - - private double numpairs; - - private float sumgag; - - private float sumrad; - - private float bias; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RWBiasDynRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RWBiasDynRecord(RWBiasDynRecord origRecord) - { - setRadid(origRecord.getRadid()); - setOffice_id(origRecord.getOffice_id()); - setObstime(origRecord.getObstime()); - setMemspan_ind(origRecord.getMemspan_ind()); - setNumpairs(origRecord.getNumpairs()); - setSumgag(origRecord.getSumgag()); - setSumrad(origRecord.getSumrad()); - setBias(origRecord.getBias()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RWBiasDyn record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getMemspan_ind() - { - return memspan_ind; - } - - public void setMemspan_ind(short memspan_ind) - { - this.memspan_ind = memspan_ind ; - } - - public double getNumpairs() - { - return numpairs; - } - - public void setNumpairs(double numpairs) - { - this.numpairs = numpairs ; - } - - public float getSumgag() - { - return sumgag; - } - - public void setSumgag(float sumgag) - { - this.sumgag = sumgag ; - } - - public float getSumrad() - { - return sumrad; - } - - public void setSumrad(float sumrad) - { - this.sumrad = sumrad ; - } - - public float getBias() - { - return bias; - } - - public void setBias(float bias) - { - this.bias = bias ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND office_id = '" + office_id + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - + " AND memspan_ind = '" + memspan_ind + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getOffice_id() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMemspan_ind() + " " + - getNumpairs() + " " + - getSumgag() + " " + - getSumrad() + " " + - getBias() + " " + - "" ; - return outString; - } // end toString() -} // end of RWBiasDynRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasDynTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasDynTable.java deleted file mode 100644 index 7ceffb729d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasDynTable.java +++ /dev/null @@ -1,281 +0,0 @@ -// filename: RWBiasDynTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rwbiasdyn table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RWBiasDynTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RWBiasDynTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RWBiasDynTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rwbiasdyn"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RWBiasDynRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RWBiasDynRecord record = null; - - // create a List to hold RWBiasDyn Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwbiasdyn " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWBiasDynRecord - // and store its address in oneRecord - record = new RWBiasDynRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWBiasDynRecord object - - record.setRadid(getString(rs, 1)); - record.setOffice_id(getString(rs, 2)); - record.setObstime(getTimeStamp(rs, 3)); - record.setMemspan_ind(getShort(rs, 4)); - record.setNumpairs(getDouble(rs, 5)); - record.setSumgag(getReal(rs, 6)); - record.setSumrad(getReal(rs, 7)); - record.setBias(getReal(rs, 8)); - - // add this RWBiasDynRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RWBiasDynRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RWBiasDynRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RWBiasDynRecord record = null; - - // create a List to hold RWBiasDyn Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwbiasdyn " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWBiasDynRecord - // and store its address in oneRecord - record = new RWBiasDynRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWBiasDynRecord object - - record.setRadid(getString(rs, 1)); - record.setOffice_id(getString(rs, 2)); - record.setObstime(getTimeStamp(rs, 3)); - record.setMemspan_ind(getShort(rs, 4)); - record.setNumpairs(getDouble(rs, 5)); - record.setSumgag(getReal(rs, 6)); - record.setSumrad(getReal(rs, 7)); - record.setBias(getReal(rs, 8)); - - // add this RWBiasDynRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RWBiasDynRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RWBiasDynRecord object and.. -//----------------------------------------------------------------- - public int insert(RWBiasDynRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rwbiasdyn VALUES (?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setString(insertStatement, 2, record.getOffice_id()); - setTimeStamp(insertStatement, 3, record.getObstime()); - setShort(insertStatement, 4, record.getMemspan_ind()); - setDouble(insertStatement, 5, record.getNumpairs()); - setReal(insertStatement, 6, record.getSumgag()); - setReal(insertStatement, 7, record.getSumrad()); - setReal(insertStatement, 8, record.getBias()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwbiasdyn " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWBiasDynRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWBiasDynRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwbiasdyn SET radid = ?, office_id = ?, obstime = ?, memspan_ind = ?, numpairs = ?, sumgag = ?, sumrad = ?, bias = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setString(updateStatement, 2, record.getOffice_id()); - setTimeStamp(updateStatement, 3, record.getObstime()); - setShort(updateStatement, 4, record.getMemspan_ind()); - setDouble(updateStatement, 5, record.getNumpairs()); - setReal(updateStatement, 6, record.getSumgag()); - setReal(updateStatement, 7, record.getSumrad()); - setReal(updateStatement, 8, record.getBias()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RWBiasDynRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwbiasdyn " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWBiasDynRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWBiasDynRecord oldRecord, RWBiasDynRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwbiasdyn SET radid = ?, office_id = ?, obstime = ?, memspan_ind = ?, numpairs = ?, sumgag = ?, sumrad = ?, bias = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setString(updateStatement, 2, newRecord.getOffice_id()); - setTimeStamp(updateStatement, 3, newRecord.getObstime()); - setShort(updateStatement, 4, newRecord.getMemspan_ind()); - setDouble(updateStatement, 5, newRecord.getNumpairs()); - setReal(updateStatement, 6, newRecord.getSumgag()); - setReal(updateStatement, 7, newRecord.getSumrad()); - setReal(updateStatement, 8, newRecord.getBias()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RWBiasDynRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RWBiasDynRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RWBiasDynRecord oldRecord = (RWBiasDynRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RWBiasDynTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasStatRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasStatRecord.java deleted file mode 100644 index e45b359514..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasStatRecord.java +++ /dev/null @@ -1,321 +0,0 @@ -// filename: RWBiasStatRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RWBiasStat table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RWBiasStatRecord extends DbRecord -{ - private String office_id; - - private float min_gr_value_bias; - - private int npair_bias_select; - - private int npair_svar_update; - - private int std_cut; - - private int lag_cut; - - private int init_span; - - private int bias_qc_opt; - - private int num_span; - - private float mem_span1; - - private float mem_span2; - - private float mem_span3; - - private float mem_span4; - - private float mem_span5; - - private float mem_span6; - - private float mem_span7; - - private float mem_span8; - - private float mem_span9; - - private float mem_span10; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RWBiasStatRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RWBiasStatRecord(RWBiasStatRecord origRecord) - { - setOffice_id(origRecord.getOffice_id()); - setMin_gr_value_bias(origRecord.getMin_gr_value_bias()); - setNpair_bias_select(origRecord.getNpair_bias_select()); - setNpair_svar_update(origRecord.getNpair_svar_update()); - setStd_cut(origRecord.getStd_cut()); - setLag_cut(origRecord.getLag_cut()); - setInit_span(origRecord.getInit_span()); - setBias_qc_opt(origRecord.getBias_qc_opt()); - setNum_span(origRecord.getNum_span()); - setMem_span1(origRecord.getMem_span1()); - setMem_span2(origRecord.getMem_span2()); - setMem_span3(origRecord.getMem_span3()); - setMem_span4(origRecord.getMem_span4()); - setMem_span5(origRecord.getMem_span5()); - setMem_span6(origRecord.getMem_span6()); - setMem_span7(origRecord.getMem_span7()); - setMem_span8(origRecord.getMem_span8()); - setMem_span9(origRecord.getMem_span9()); - setMem_span10(origRecord.getMem_span10()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RWBiasStat record - - //----------------------------------------------------------------- - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - - public float getMin_gr_value_bias() - { - return min_gr_value_bias; - } - - public void setMin_gr_value_bias(float min_gr_value_bias) - { - this.min_gr_value_bias = min_gr_value_bias ; - } - - public int getNpair_bias_select() - { - return npair_bias_select; - } - - public void setNpair_bias_select(int npair_bias_select) - { - this.npair_bias_select = npair_bias_select ; - } - - public int getNpair_svar_update() - { - return npair_svar_update; - } - - public void setNpair_svar_update(int npair_svar_update) - { - this.npair_svar_update = npair_svar_update ; - } - - public int getStd_cut() - { - return std_cut; - } - - public void setStd_cut(int std_cut) - { - this.std_cut = std_cut ; - } - - public int getLag_cut() - { - return lag_cut; - } - - public void setLag_cut(int lag_cut) - { - this.lag_cut = lag_cut ; - } - - public int getInit_span() - { - return init_span; - } - - public void setInit_span(int init_span) - { - this.init_span = init_span ; - } - - public int getBias_qc_opt() - { - return bias_qc_opt; - } - - public void setBias_qc_opt(int bias_qc_opt) - { - this.bias_qc_opt = bias_qc_opt ; - } - - public int getNum_span() - { - return num_span; - } - - public void setNum_span(int num_span) - { - this.num_span = num_span ; - } - - public float getMem_span1() - { - return mem_span1; - } - - public void setMem_span1(float mem_span1) - { - this.mem_span1 = mem_span1 ; - } - - public float getMem_span2() - { - return mem_span2; - } - - public void setMem_span2(float mem_span2) - { - this.mem_span2 = mem_span2 ; - } - - public float getMem_span3() - { - return mem_span3; - } - - public void setMem_span3(float mem_span3) - { - this.mem_span3 = mem_span3 ; - } - - public float getMem_span4() - { - return mem_span4; - } - - public void setMem_span4(float mem_span4) - { - this.mem_span4 = mem_span4 ; - } - - public float getMem_span5() - { - return mem_span5; - } - - public void setMem_span5(float mem_span5) - { - this.mem_span5 = mem_span5 ; - } - - public float getMem_span6() - { - return mem_span6; - } - - public void setMem_span6(float mem_span6) - { - this.mem_span6 = mem_span6 ; - } - - public float getMem_span7() - { - return mem_span7; - } - - public void setMem_span7(float mem_span7) - { - this.mem_span7 = mem_span7 ; - } - - public float getMem_span8() - { - return mem_span8; - } - - public void setMem_span8(float mem_span8) - { - this.mem_span8 = mem_span8 ; - } - - public float getMem_span9() - { - return mem_span9; - } - - public void setMem_span9(float mem_span9) - { - this.mem_span9 = mem_span9 ; - } - - public float getMem_span10() - { - return mem_span10; - } - - public void setMem_span10(float mem_span10) - { - this.mem_span10 = mem_span10 ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE office_id = '" + office_id + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getOffice_id() + " " + - getMin_gr_value_bias() + " " + - getNpair_bias_select() + " " + - getNpair_svar_update() + " " + - getStd_cut() + " " + - getLag_cut() + " " + - getInit_span() + " " + - getBias_qc_opt() + " " + - getNum_span() + " " + - getMem_span1() + " " + - getMem_span2() + " " + - getMem_span3() + " " + - getMem_span4() + " " + - getMem_span5() + " " + - getMem_span6() + " " + - getMem_span7() + " " + - getMem_span8() + " " + - getMem_span9() + " " + - getMem_span10() + " " + - "" ; - return outString; - } // end toString() -} // end of RWBiasStatRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasStatTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasStatTable.java deleted file mode 100644 index f7da1cc20b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWBiasStatTable.java +++ /dev/null @@ -1,336 +0,0 @@ -// filename: RWBiasStatTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rwbiasstat table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RWBiasStatTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RWBiasStatTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RWBiasStatTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rwbiasstat"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RWBiasStatRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RWBiasStatRecord record = null; - - // create a List to hold RWBiasStat Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwbiasstat " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWBiasStatRecord - // and store its address in oneRecord - record = new RWBiasStatRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWBiasStatRecord object - - record.setOffice_id(getString(rs, 1)); - record.setMin_gr_value_bias(getReal(rs, 2)); - record.setNpair_bias_select(getInt(rs, 3)); - record.setNpair_svar_update(getInt(rs, 4)); - record.setStd_cut(getInt(rs, 5)); - record.setLag_cut(getInt(rs, 6)); - record.setInit_span(getInt(rs, 7)); - record.setBias_qc_opt(getInt(rs, 8)); - record.setNum_span(getInt(rs, 9)); - record.setMem_span1(getReal(rs, 10)); - record.setMem_span2(getReal(rs, 11)); - record.setMem_span3(getReal(rs, 12)); - record.setMem_span4(getReal(rs, 13)); - record.setMem_span5(getReal(rs, 14)); - record.setMem_span6(getReal(rs, 15)); - record.setMem_span7(getReal(rs, 16)); - record.setMem_span8(getReal(rs, 17)); - record.setMem_span9(getReal(rs, 18)); - record.setMem_span10(getReal(rs, 19)); - - // add this RWBiasStatRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RWBiasStatRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RWBiasStatRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RWBiasStatRecord record = null; - - // create a List to hold RWBiasStat Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwbiasstat " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWBiasStatRecord - // and store its address in oneRecord - record = new RWBiasStatRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWBiasStatRecord object - - record.setOffice_id(getString(rs, 1)); - record.setMin_gr_value_bias(getReal(rs, 2)); - record.setNpair_bias_select(getInt(rs, 3)); - record.setNpair_svar_update(getInt(rs, 4)); - record.setStd_cut(getInt(rs, 5)); - record.setLag_cut(getInt(rs, 6)); - record.setInit_span(getInt(rs, 7)); - record.setBias_qc_opt(getInt(rs, 8)); - record.setNum_span(getInt(rs, 9)); - record.setMem_span1(getReal(rs, 10)); - record.setMem_span2(getReal(rs, 11)); - record.setMem_span3(getReal(rs, 12)); - record.setMem_span4(getReal(rs, 13)); - record.setMem_span5(getReal(rs, 14)); - record.setMem_span6(getReal(rs, 15)); - record.setMem_span7(getReal(rs, 16)); - record.setMem_span8(getReal(rs, 17)); - record.setMem_span9(getReal(rs, 18)); - record.setMem_span10(getReal(rs, 19)); - - // add this RWBiasStatRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RWBiasStatRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RWBiasStatRecord object and.. -//----------------------------------------------------------------- - public int insert(RWBiasStatRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rwbiasstat VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getOffice_id()); - setReal(insertStatement, 2, record.getMin_gr_value_bias()); - setInt(insertStatement, 3, record.getNpair_bias_select()); - setInt(insertStatement, 4, record.getNpair_svar_update()); - setInt(insertStatement, 5, record.getStd_cut()); - setInt(insertStatement, 6, record.getLag_cut()); - setInt(insertStatement, 7, record.getInit_span()); - setInt(insertStatement, 8, record.getBias_qc_opt()); - setInt(insertStatement, 9, record.getNum_span()); - setReal(insertStatement, 10, record.getMem_span1()); - setReal(insertStatement, 11, record.getMem_span2()); - setReal(insertStatement, 12, record.getMem_span3()); - setReal(insertStatement, 13, record.getMem_span4()); - setReal(insertStatement, 14, record.getMem_span5()); - setReal(insertStatement, 15, record.getMem_span6()); - setReal(insertStatement, 16, record.getMem_span7()); - setReal(insertStatement, 17, record.getMem_span8()); - setReal(insertStatement, 18, record.getMem_span9()); - setReal(insertStatement, 19, record.getMem_span10()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwbiasstat " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWBiasStatRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWBiasStatRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwbiasstat SET office_id = ?, min_gr_value_bias = ?, npair_bias_select = ?, npair_svar_update = ?, std_cut = ?, lag_cut = ?, init_span = ?, bias_qc_opt = ?, num_span = ?, mem_span1 = ?, mem_span2 = ?, mem_span3 = ?, mem_span4 = ?, mem_span5 = ?, mem_span6 = ?, mem_span7 = ?, mem_span8 = ?, mem_span9 = ?, mem_span10 = ? " + where ); - - setString(updateStatement, 1, record.getOffice_id()); - setReal(updateStatement, 2, record.getMin_gr_value_bias()); - setInt(updateStatement, 3, record.getNpair_bias_select()); - setInt(updateStatement, 4, record.getNpair_svar_update()); - setInt(updateStatement, 5, record.getStd_cut()); - setInt(updateStatement, 6, record.getLag_cut()); - setInt(updateStatement, 7, record.getInit_span()); - setInt(updateStatement, 8, record.getBias_qc_opt()); - setInt(updateStatement, 9, record.getNum_span()); - setReal(updateStatement, 10, record.getMem_span1()); - setReal(updateStatement, 11, record.getMem_span2()); - setReal(updateStatement, 12, record.getMem_span3()); - setReal(updateStatement, 13, record.getMem_span4()); - setReal(updateStatement, 14, record.getMem_span5()); - setReal(updateStatement, 15, record.getMem_span6()); - setReal(updateStatement, 16, record.getMem_span7()); - setReal(updateStatement, 17, record.getMem_span8()); - setReal(updateStatement, 18, record.getMem_span9()); - setReal(updateStatement, 19, record.getMem_span10()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RWBiasStatRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwbiasstat " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWBiasStatRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWBiasStatRecord oldRecord, RWBiasStatRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwbiasstat SET office_id = ?, min_gr_value_bias = ?, npair_bias_select = ?, npair_svar_update = ?, std_cut = ?, lag_cut = ?, init_span = ?, bias_qc_opt = ?, num_span = ?, mem_span1 = ?, mem_span2 = ?, mem_span3 = ?, mem_span4 = ?, mem_span5 = ?, mem_span6 = ?, mem_span7 = ?, mem_span8 = ?, mem_span9 = ?, mem_span10 = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getOffice_id()); - setReal(updateStatement, 2, newRecord.getMin_gr_value_bias()); - setInt(updateStatement, 3, newRecord.getNpair_bias_select()); - setInt(updateStatement, 4, newRecord.getNpair_svar_update()); - setInt(updateStatement, 5, newRecord.getStd_cut()); - setInt(updateStatement, 6, newRecord.getLag_cut()); - setInt(updateStatement, 7, newRecord.getInit_span()); - setInt(updateStatement, 8, newRecord.getBias_qc_opt()); - setInt(updateStatement, 9, newRecord.getNum_span()); - setReal(updateStatement, 10, newRecord.getMem_span1()); - setReal(updateStatement, 11, newRecord.getMem_span2()); - setReal(updateStatement, 12, newRecord.getMem_span3()); - setReal(updateStatement, 13, newRecord.getMem_span4()); - setReal(updateStatement, 14, newRecord.getMem_span5()); - setReal(updateStatement, 15, newRecord.getMem_span6()); - setReal(updateStatement, 16, newRecord.getMem_span7()); - setReal(updateStatement, 17, newRecord.getMem_span8()); - setReal(updateStatement, 18, newRecord.getMem_span9()); - setReal(updateStatement, 19, newRecord.getMem_span10()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RWBiasStatRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RWBiasStatRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RWBiasStatRecord oldRecord = (RWBiasStatRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RWBiasStatTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWParamsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWParamsRecord.java deleted file mode 100644 index a8263e3838..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWParamsRecord.java +++ /dev/null @@ -1,239 +0,0 @@ -// filename: RWParamsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RWParams table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RWParamsRecord extends DbRecord -{ - private float rw_min_rain; - - private float rw_sep_dist; - - private float rw_lag0_ind_corr; - - private float rw_lag0_cond_corr; - - private short num_near_gages; - - private short num_near_rad_bins; - - private float def_cond_var_rad; - - private float def_ind_corr_scl; - - private float def_cond_corr_scl; - - private float min_ind_corr_scl; - - private float min_cond_corr_scl; - - private float max_ind_corr_scl; - - private float max_cond_corr_scl; - - private short nn_srch_method; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RWParamsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RWParamsRecord(RWParamsRecord origRecord) - { - setRw_min_rain(origRecord.getRw_min_rain()); - setRw_sep_dist(origRecord.getRw_sep_dist()); - setRw_lag0_ind_corr(origRecord.getRw_lag0_ind_corr()); - setRw_lag0_cond_corr(origRecord.getRw_lag0_cond_corr()); - setNum_near_gages(origRecord.getNum_near_gages()); - setNum_near_rad_bins(origRecord.getNum_near_rad_bins()); - setDef_cond_var_rad(origRecord.getDef_cond_var_rad()); - setDef_ind_corr_scl(origRecord.getDef_ind_corr_scl()); - setDef_cond_corr_scl(origRecord.getDef_cond_corr_scl()); - setMin_ind_corr_scl(origRecord.getMin_ind_corr_scl()); - setMin_cond_corr_scl(origRecord.getMin_cond_corr_scl()); - setMax_ind_corr_scl(origRecord.getMax_ind_corr_scl()); - setMax_cond_corr_scl(origRecord.getMax_cond_corr_scl()); - setNn_srch_method(origRecord.getNn_srch_method()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RWParams record - - //----------------------------------------------------------------- - public float getRw_min_rain() - { - return rw_min_rain; - } - - public void setRw_min_rain(float rw_min_rain) - { - this.rw_min_rain = rw_min_rain ; - } - - public float getRw_sep_dist() - { - return rw_sep_dist; - } - - public void setRw_sep_dist(float rw_sep_dist) - { - this.rw_sep_dist = rw_sep_dist ; - } - - public float getRw_lag0_ind_corr() - { - return rw_lag0_ind_corr; - } - - public void setRw_lag0_ind_corr(float rw_lag0_ind_corr) - { - this.rw_lag0_ind_corr = rw_lag0_ind_corr ; - } - - public float getRw_lag0_cond_corr() - { - return rw_lag0_cond_corr; - } - - public void setRw_lag0_cond_corr(float rw_lag0_cond_corr) - { - this.rw_lag0_cond_corr = rw_lag0_cond_corr ; - } - - public short getNum_near_gages() - { - return num_near_gages; - } - - public void setNum_near_gages(short num_near_gages) - { - this.num_near_gages = num_near_gages ; - } - - public short getNum_near_rad_bins() - { - return num_near_rad_bins; - } - - public void setNum_near_rad_bins(short num_near_rad_bins) - { - this.num_near_rad_bins = num_near_rad_bins ; - } - - public float getDef_cond_var_rad() - { - return def_cond_var_rad; - } - - public void setDef_cond_var_rad(float def_cond_var_rad) - { - this.def_cond_var_rad = def_cond_var_rad ; - } - - public float getDef_ind_corr_scl() - { - return def_ind_corr_scl; - } - - public void setDef_ind_corr_scl(float def_ind_corr_scl) - { - this.def_ind_corr_scl = def_ind_corr_scl ; - } - - public float getDef_cond_corr_scl() - { - return def_cond_corr_scl; - } - - public void setDef_cond_corr_scl(float def_cond_corr_scl) - { - this.def_cond_corr_scl = def_cond_corr_scl ; - } - - public float getMin_ind_corr_scl() - { - return min_ind_corr_scl; - } - - public void setMin_ind_corr_scl(float min_ind_corr_scl) - { - this.min_ind_corr_scl = min_ind_corr_scl ; - } - - public float getMin_cond_corr_scl() - { - return min_cond_corr_scl; - } - - public void setMin_cond_corr_scl(float min_cond_corr_scl) - { - this.min_cond_corr_scl = min_cond_corr_scl ; - } - - public float getMax_ind_corr_scl() - { - return max_ind_corr_scl; - } - - public void setMax_ind_corr_scl(float max_ind_corr_scl) - { - this.max_ind_corr_scl = max_ind_corr_scl ; - } - - public float getMax_cond_corr_scl() - { - return max_cond_corr_scl; - } - - public void setMax_cond_corr_scl(float max_cond_corr_scl) - { - this.max_cond_corr_scl = max_cond_corr_scl ; - } - - public short getNn_srch_method() - { - return nn_srch_method; - } - - public void setNn_srch_method(short nn_srch_method) - { - this.nn_srch_method = nn_srch_method ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRw_min_rain() + " " + - getRw_sep_dist() + " " + - getRw_lag0_ind_corr() + " " + - getRw_lag0_cond_corr() + " " + - getNum_near_gages() + " " + - getNum_near_rad_bins() + " " + - getDef_cond_var_rad() + " " + - getDef_ind_corr_scl() + " " + - getDef_cond_corr_scl() + " " + - getMin_ind_corr_scl() + " " + - getMin_cond_corr_scl() + " " + - getMax_ind_corr_scl() + " " + - getMax_cond_corr_scl() + " " + - getNn_srch_method() + " " + - "" ; - return outString; - } // end toString() -} // end of RWParamsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWParamsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWParamsTable.java deleted file mode 100644 index 634a47c5fa..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWParamsTable.java +++ /dev/null @@ -1,241 +0,0 @@ -// filename: RWParamsTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rwparams table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RWParamsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RWParamsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RWParamsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rwparams"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RWParamsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RWParamsRecord record = null; - - // create a List to hold RWParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWParamsRecord - // and store its address in oneRecord - record = new RWParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWParamsRecord object - - record.setRw_min_rain(getReal(rs, 1)); - record.setRw_sep_dist(getReal(rs, 2)); - record.setRw_lag0_ind_corr(getReal(rs, 3)); - record.setRw_lag0_cond_corr(getReal(rs, 4)); - record.setNum_near_gages(getShort(rs, 5)); - record.setNum_near_rad_bins(getShort(rs, 6)); - record.setDef_cond_var_rad(getReal(rs, 7)); - record.setDef_ind_corr_scl(getReal(rs, 8)); - record.setDef_cond_corr_scl(getReal(rs, 9)); - record.setMin_ind_corr_scl(getReal(rs, 10)); - record.setMin_cond_corr_scl(getReal(rs, 11)); - record.setMax_ind_corr_scl(getReal(rs, 12)); - record.setMax_cond_corr_scl(getReal(rs, 13)); - record.setNn_srch_method(getShort(rs, 14)); - - // add this RWParamsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RWParamsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RWParamsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RWParamsRecord record = null; - - // create a List to hold RWParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWParamsRecord - // and store its address in oneRecord - record = new RWParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWParamsRecord object - - record.setRw_min_rain(getReal(rs, 1)); - record.setRw_sep_dist(getReal(rs, 2)); - record.setRw_lag0_ind_corr(getReal(rs, 3)); - record.setRw_lag0_cond_corr(getReal(rs, 4)); - record.setNum_near_gages(getShort(rs, 5)); - record.setNum_near_rad_bins(getShort(rs, 6)); - record.setDef_cond_var_rad(getReal(rs, 7)); - record.setDef_ind_corr_scl(getReal(rs, 8)); - record.setDef_cond_corr_scl(getReal(rs, 9)); - record.setMin_ind_corr_scl(getReal(rs, 10)); - record.setMin_cond_corr_scl(getReal(rs, 11)); - record.setMax_ind_corr_scl(getReal(rs, 12)); - record.setMax_cond_corr_scl(getReal(rs, 13)); - record.setNn_srch_method(getShort(rs, 14)); - - // add this RWParamsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RWParamsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RWParamsRecord object and.. -//----------------------------------------------------------------- - public int insert(RWParamsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rwparams VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setReal(insertStatement, 1, record.getRw_min_rain()); - setReal(insertStatement, 2, record.getRw_sep_dist()); - setReal(insertStatement, 3, record.getRw_lag0_ind_corr()); - setReal(insertStatement, 4, record.getRw_lag0_cond_corr()); - setShort(insertStatement, 5, record.getNum_near_gages()); - setShort(insertStatement, 6, record.getNum_near_rad_bins()); - setReal(insertStatement, 7, record.getDef_cond_var_rad()); - setReal(insertStatement, 8, record.getDef_ind_corr_scl()); - setReal(insertStatement, 9, record.getDef_cond_corr_scl()); - setReal(insertStatement, 10, record.getMin_ind_corr_scl()); - setReal(insertStatement, 11, record.getMin_cond_corr_scl()); - setReal(insertStatement, 12, record.getMax_ind_corr_scl()); - setReal(insertStatement, 13, record.getMax_cond_corr_scl()); - setShort(insertStatement, 14, record.getNn_srch_method()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwparams " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWParamsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWParamsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwparams SET rw_min_rain = ?, rw_sep_dist = ?, rw_lag0_ind_corr = ?, rw_lag0_cond_corr = ?, num_near_gages = ?, num_near_rad_bins = ?, def_cond_var_rad = ?, def_ind_corr_scl = ?, def_cond_corr_scl = ?, min_ind_corr_scl = ?, min_cond_corr_scl = ?, max_ind_corr_scl = ?, max_cond_corr_scl = ?, nn_srch_method = ? " + where ); - - setReal(updateStatement, 1, record.getRw_min_rain()); - setReal(updateStatement, 2, record.getRw_sep_dist()); - setReal(updateStatement, 3, record.getRw_lag0_ind_corr()); - setReal(updateStatement, 4, record.getRw_lag0_cond_corr()); - setShort(updateStatement, 5, record.getNum_near_gages()); - setShort(updateStatement, 6, record.getNum_near_rad_bins()); - setReal(updateStatement, 7, record.getDef_cond_var_rad()); - setReal(updateStatement, 8, record.getDef_ind_corr_scl()); - setReal(updateStatement, 9, record.getDef_cond_corr_scl()); - setReal(updateStatement, 10, record.getMin_ind_corr_scl()); - setReal(updateStatement, 11, record.getMin_cond_corr_scl()); - setReal(updateStatement, 12, record.getMax_ind_corr_scl()); - setReal(updateStatement, 13, record.getMax_cond_corr_scl()); - setShort(updateStatement, 14, record.getNn_srch_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -} // end of RWParamsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWPrefsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWPrefsRecord.java deleted file mode 100644 index df74f6bad6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWPrefsRecord.java +++ /dev/null @@ -1,181 +0,0 @@ -// filename: RWPrefsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RWPrefs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RWPrefsRecord extends DbRecord -{ - private String userid; - - private String state_overlay; - - private String city_overlay; - - private String county_overlay; - - private String river_overlay; - - private String basin_overlay; - - private String radar_overlay; - - private short num_hours_wind; - - private String def_display_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RWPrefsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RWPrefsRecord(RWPrefsRecord origRecord) - { - setUserid(origRecord.getUserid()); - setState_overlay(origRecord.getState_overlay()); - setCity_overlay(origRecord.getCity_overlay()); - setCounty_overlay(origRecord.getCounty_overlay()); - setRiver_overlay(origRecord.getRiver_overlay()); - setBasin_overlay(origRecord.getBasin_overlay()); - setRadar_overlay(origRecord.getRadar_overlay()); - setNum_hours_wind(origRecord.getNum_hours_wind()); - setDef_display_type(origRecord.getDef_display_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RWPrefs record - - //----------------------------------------------------------------- - public String getUserid() - { - return userid; - } - - public void setUserid(String userid) - { - this.userid = userid ; - } - - public String getState_overlay() - { - return state_overlay; - } - - public void setState_overlay(String state_overlay) - { - this.state_overlay = state_overlay ; - } - - public String getCity_overlay() - { - return city_overlay; - } - - public void setCity_overlay(String city_overlay) - { - this.city_overlay = city_overlay ; - } - - public String getCounty_overlay() - { - return county_overlay; - } - - public void setCounty_overlay(String county_overlay) - { - this.county_overlay = county_overlay ; - } - - public String getRiver_overlay() - { - return river_overlay; - } - - public void setRiver_overlay(String river_overlay) - { - this.river_overlay = river_overlay ; - } - - public String getBasin_overlay() - { - return basin_overlay; - } - - public void setBasin_overlay(String basin_overlay) - { - this.basin_overlay = basin_overlay ; - } - - public String getRadar_overlay() - { - return radar_overlay; - } - - public void setRadar_overlay(String radar_overlay) - { - this.radar_overlay = radar_overlay ; - } - - public short getNum_hours_wind() - { - return num_hours_wind; - } - - public void setNum_hours_wind(short num_hours_wind) - { - this.num_hours_wind = num_hours_wind ; - } - - public String getDef_display_type() - { - return def_display_type; - } - - public void setDef_display_type(String def_display_type) - { - this.def_display_type = def_display_type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE userid = '" + userid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getUserid() + " " + - getState_overlay() + " " + - getCity_overlay() + " " + - getCounty_overlay() + " " + - getRiver_overlay() + " " + - getBasin_overlay() + " " + - getRadar_overlay() + " " + - getNum_hours_wind() + " " + - getDef_display_type() + " " + - "" ; - return outString; - } // end toString() -} // end of RWPrefsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWPrefsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWPrefsTable.java deleted file mode 100644 index 335dd83f4f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWPrefsTable.java +++ /dev/null @@ -1,286 +0,0 @@ -// filename: RWPrefsTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rwprefs table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RWPrefsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RWPrefsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RWPrefsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rwprefs"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RWPrefsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RWPrefsRecord record = null; - - // create a List to hold RWPrefs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwprefs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWPrefsRecord - // and store its address in oneRecord - record = new RWPrefsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWPrefsRecord object - - record.setUserid(getString(rs, 1)); - record.setState_overlay(getString(rs, 2)); - record.setCity_overlay(getString(rs, 3)); - record.setCounty_overlay(getString(rs, 4)); - record.setRiver_overlay(getString(rs, 5)); - record.setBasin_overlay(getString(rs, 6)); - record.setRadar_overlay(getString(rs, 7)); - record.setNum_hours_wind(getShort(rs, 8)); - record.setDef_display_type(getString(rs, 9)); - - // add this RWPrefsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RWPrefsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RWPrefsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RWPrefsRecord record = null; - - // create a List to hold RWPrefs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwprefs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWPrefsRecord - // and store its address in oneRecord - record = new RWPrefsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWPrefsRecord object - - record.setUserid(getString(rs, 1)); - record.setState_overlay(getString(rs, 2)); - record.setCity_overlay(getString(rs, 3)); - record.setCounty_overlay(getString(rs, 4)); - record.setRiver_overlay(getString(rs, 5)); - record.setBasin_overlay(getString(rs, 6)); - record.setRadar_overlay(getString(rs, 7)); - record.setNum_hours_wind(getShort(rs, 8)); - record.setDef_display_type(getString(rs, 9)); - - // add this RWPrefsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RWPrefsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RWPrefsRecord object and.. -//----------------------------------------------------------------- - public int insert(RWPrefsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rwprefs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getUserid()); - setString(insertStatement, 2, record.getState_overlay()); - setString(insertStatement, 3, record.getCity_overlay()); - setString(insertStatement, 4, record.getCounty_overlay()); - setString(insertStatement, 5, record.getRiver_overlay()); - setString(insertStatement, 6, record.getBasin_overlay()); - setString(insertStatement, 7, record.getRadar_overlay()); - setShort(insertStatement, 8, record.getNum_hours_wind()); - setString(insertStatement, 9, record.getDef_display_type()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwprefs " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWPrefsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWPrefsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwprefs SET userid = ?, state_overlay = ?, city_overlay = ?, county_overlay = ?, river_overlay = ?, basin_overlay = ?, radar_overlay = ?, num_hours_wind = ?, def_display_type = ? " + where ); - - setString(updateStatement, 1, record.getUserid()); - setString(updateStatement, 2, record.getState_overlay()); - setString(updateStatement, 3, record.getCity_overlay()); - setString(updateStatement, 4, record.getCounty_overlay()); - setString(updateStatement, 5, record.getRiver_overlay()); - setString(updateStatement, 6, record.getBasin_overlay()); - setString(updateStatement, 7, record.getRadar_overlay()); - setShort(updateStatement, 8, record.getNum_hours_wind()); - setString(updateStatement, 9, record.getDef_display_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RWPrefsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwprefs " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWPrefsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWPrefsRecord oldRecord, RWPrefsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwprefs SET userid = ?, state_overlay = ?, city_overlay = ?, county_overlay = ?, river_overlay = ?, basin_overlay = ?, radar_overlay = ?, num_hours_wind = ?, def_display_type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getUserid()); - setString(updateStatement, 2, newRecord.getState_overlay()); - setString(updateStatement, 3, newRecord.getCity_overlay()); - setString(updateStatement, 4, newRecord.getCounty_overlay()); - setString(updateStatement, 5, newRecord.getRiver_overlay()); - setString(updateStatement, 6, newRecord.getBasin_overlay()); - setString(updateStatement, 7, newRecord.getRadar_overlay()); - setShort(updateStatement, 8, newRecord.getNum_hours_wind()); - setString(updateStatement, 9, newRecord.getDef_display_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RWPrefsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RWPrefsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RWPrefsRecord oldRecord = (RWPrefsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RWPrefsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWRadarResultRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWRadarResultRecord.java deleted file mode 100644 index 2f973eb0af..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWRadarResultRecord.java +++ /dev/null @@ -1,168 +0,0 @@ -// filename: RWRadarResultRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RWRadarResult table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RWRadarResultRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private short num_gages; - - private String rad_avail; - - private double rw_bias_val_used; - - private double mem_span_used; - - private String edit_bias; - - private String ignore_radar; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RWRadarResultRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RWRadarResultRecord(RWRadarResultRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setNum_gages(origRecord.getNum_gages()); - setRad_avail(origRecord.getRad_avail()); - setRw_bias_val_used(origRecord.getRw_bias_val_used()); - setMem_span_used(origRecord.getMem_span_used()); - setEdit_bias(origRecord.getEdit_bias()); - setIgnore_radar(origRecord.getIgnore_radar()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RWRadarResult record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getNum_gages() - { - return num_gages; - } - - public void setNum_gages(short num_gages) - { - this.num_gages = num_gages ; - } - - public String getRad_avail() - { - return rad_avail; - } - - public void setRad_avail(String rad_avail) - { - this.rad_avail = rad_avail ; - } - - public double getRw_bias_val_used() - { - return rw_bias_val_used; - } - - public void setRw_bias_val_used(double rw_bias_val_used) - { - this.rw_bias_val_used = rw_bias_val_used ; - } - - public double getMem_span_used() - { - return mem_span_used; - } - - public void setMem_span_used(double mem_span_used) - { - this.mem_span_used = mem_span_used ; - } - - public String getEdit_bias() - { - return edit_bias; - } - - public void setEdit_bias(String edit_bias) - { - this.edit_bias = edit_bias ; - } - - public String getIgnore_radar() - { - return ignore_radar; - } - - public void setIgnore_radar(String ignore_radar) - { - this.ignore_radar = ignore_radar ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getNum_gages() + " " + - getRad_avail() + " " + - getRw_bias_val_used() + " " + - getMem_span_used() + " " + - getEdit_bias() + " " + - getIgnore_radar() + " " + - "" ; - return outString; - } // end toString() -} // end of RWRadarResultRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWRadarResultTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWRadarResultTable.java deleted file mode 100644 index 77277be6f3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWRadarResultTable.java +++ /dev/null @@ -1,281 +0,0 @@ -// filename: RWRadarResultTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rwradarresult table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RWRadarResultTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RWRadarResultTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RWRadarResultTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rwradarresult"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RWRadarResultRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RWRadarResultRecord record = null; - - // create a List to hold RWRadarResult Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwradarresult " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWRadarResultRecord - // and store its address in oneRecord - record = new RWRadarResultRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWRadarResultRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setNum_gages(getShort(rs, 3)); - record.setRad_avail(getString(rs, 4)); - record.setRw_bias_val_used(getDouble(rs, 5)); - record.setMem_span_used(getDouble(rs, 6)); - record.setEdit_bias(getString(rs, 7)); - record.setIgnore_radar(getString(rs, 8)); - - // add this RWRadarResultRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RWRadarResultRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RWRadarResultRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RWRadarResultRecord record = null; - - // create a List to hold RWRadarResult Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwradarresult " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWRadarResultRecord - // and store its address in oneRecord - record = new RWRadarResultRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWRadarResultRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setNum_gages(getShort(rs, 3)); - record.setRad_avail(getString(rs, 4)); - record.setRw_bias_val_used(getDouble(rs, 5)); - record.setMem_span_used(getDouble(rs, 6)); - record.setEdit_bias(getString(rs, 7)); - record.setIgnore_radar(getString(rs, 8)); - - // add this RWRadarResultRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RWRadarResultRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RWRadarResultRecord object and.. -//----------------------------------------------------------------- - public int insert(RWRadarResultRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rwradarresult VALUES (?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setShort(insertStatement, 3, record.getNum_gages()); - setString(insertStatement, 4, record.getRad_avail()); - setDouble(insertStatement, 5, record.getRw_bias_val_used()); - setDouble(insertStatement, 6, record.getMem_span_used()); - setString(insertStatement, 7, record.getEdit_bias()); - setString(insertStatement, 8, record.getIgnore_radar()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwradarresult " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWRadarResultRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWRadarResultRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwradarresult SET radid = ?, obstime = ?, num_gages = ?, rad_avail = ?, rw_bias_val_used = ?, mem_span_used = ?, edit_bias = ?, ignore_radar = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setShort(updateStatement, 3, record.getNum_gages()); - setString(updateStatement, 4, record.getRad_avail()); - setDouble(updateStatement, 5, record.getRw_bias_val_used()); - setDouble(updateStatement, 6, record.getMem_span_used()); - setString(updateStatement, 7, record.getEdit_bias()); - setString(updateStatement, 8, record.getIgnore_radar()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RWRadarResultRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwradarresult " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWRadarResultRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWRadarResultRecord oldRecord, RWRadarResultRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwradarresult SET radid = ?, obstime = ?, num_gages = ?, rad_avail = ?, rw_bias_val_used = ?, mem_span_used = ?, edit_bias = ?, ignore_radar = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setShort(updateStatement, 3, newRecord.getNum_gages()); - setString(updateStatement, 4, newRecord.getRad_avail()); - setDouble(updateStatement, 5, newRecord.getRw_bias_val_used()); - setDouble(updateStatement, 6, newRecord.getMem_span_used()); - setString(updateStatement, 7, newRecord.getEdit_bias()); - setString(updateStatement, 8, newRecord.getIgnore_radar()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RWRadarResultRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RWRadarResultRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RWRadarResultRecord oldRecord = (RWRadarResultRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RWRadarResultTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWResultRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWResultRecord.java deleted file mode 100644 index 4e6d5afb95..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWResultRecord.java +++ /dev/null @@ -1,210 +0,0 @@ -// filename: RWResultRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RWResult table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RWResultRecord extends DbRecord -{ - private String rfc; - - private long obstime; - - private short num_gag_avail; - - private int num_rad_avail; - - private int num_pseudo_gages; - - private String sat_avail; - - private String mapx_field_type; - - private String draw_precip; - - private String auto_save; - - private long last_exec_time; - - private long last_save_time; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RWResultRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RWResultRecord(RWResultRecord origRecord) - { - setRfc(origRecord.getRfc()); - setObstime(origRecord.getObstime()); - setNum_gag_avail(origRecord.getNum_gag_avail()); - setNum_rad_avail(origRecord.getNum_rad_avail()); - setNum_pseudo_gages(origRecord.getNum_pseudo_gages()); - setSat_avail(origRecord.getSat_avail()); - setMapx_field_type(origRecord.getMapx_field_type()); - setDraw_precip(origRecord.getDraw_precip()); - setAuto_save(origRecord.getAuto_save()); - setLast_exec_time(origRecord.getLast_exec_time()); - setLast_save_time(origRecord.getLast_save_time()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RWResult record - - //----------------------------------------------------------------- - public String getRfc() - { - return rfc; - } - - public void setRfc(String rfc) - { - this.rfc = rfc ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getNum_gag_avail() - { - return num_gag_avail; - } - - public void setNum_gag_avail(short num_gag_avail) - { - this.num_gag_avail = num_gag_avail ; - } - - public int getNum_rad_avail() - { - return num_rad_avail; - } - - public void setNum_rad_avail(int num_rad_avail) - { - this.num_rad_avail = num_rad_avail ; - } - - public int getNum_pseudo_gages() - { - return num_pseudo_gages; - } - - public void setNum_pseudo_gages(int num_pseudo_gages) - { - this.num_pseudo_gages = num_pseudo_gages ; - } - - public String getSat_avail() - { - return sat_avail; - } - - public void setSat_avail(String sat_avail) - { - this.sat_avail = sat_avail ; - } - - public String getMapx_field_type() - { - return mapx_field_type; - } - - public void setMapx_field_type(String mapx_field_type) - { - this.mapx_field_type = mapx_field_type ; - } - - public String getDraw_precip() - { - return draw_precip; - } - - public void setDraw_precip(String draw_precip) - { - this.draw_precip = draw_precip ; - } - - public String getAuto_save() - { - return auto_save; - } - - public void setAuto_save(String auto_save) - { - this.auto_save = auto_save ; - } - - public long getLast_exec_time() - { - return last_exec_time; - } - - public void setLast_exec_time(long last_exec_time) - { - this.last_exec_time = last_exec_time ; - } - - public long getLast_save_time() - { - return last_save_time; - } - - public void setLast_save_time(long last_save_time) - { - this.last_save_time = last_save_time ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE rfc = '" + rfc + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRfc() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getNum_gag_avail() + " " + - getNum_rad_avail() + " " + - getNum_pseudo_gages() + " " + - getSat_avail() + " " + - getMapx_field_type() + " " + - getDraw_precip() + " " + - getAuto_save() + " " + - getDateTimeStringFromLongTime(getLast_exec_time()) + " " + - getDateTimeStringFromLongTime(getLast_save_time()) + " " + - "" ; - return outString; - } // end toString() -} // end of RWResultRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWResultTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWResultTable.java deleted file mode 100644 index ab7792138a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RWResultTable.java +++ /dev/null @@ -1,296 +0,0 @@ -// filename: RWResultTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rwresult table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RWResultTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RWResultTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RWResultTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rwresult"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RWResultRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RWResultRecord record = null; - - // create a List to hold RWResult Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwresult " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWResultRecord - // and store its address in oneRecord - record = new RWResultRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWResultRecord object - - record.setRfc(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setNum_gag_avail(getShort(rs, 3)); - record.setNum_rad_avail(getInt(rs, 4)); - record.setNum_pseudo_gages(getInt(rs, 5)); - record.setSat_avail(getString(rs, 6)); - record.setMapx_field_type(getString(rs, 7)); - record.setDraw_precip(getString(rs, 8)); - record.setAuto_save(getString(rs, 9)); - record.setLast_exec_time(getTimeStamp(rs, 10)); - record.setLast_save_time(getTimeStamp(rs, 11)); - - // add this RWResultRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RWResultRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RWResultRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RWResultRecord record = null; - - // create a List to hold RWResult Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rwresult " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RWResultRecord - // and store its address in oneRecord - record = new RWResultRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RWResultRecord object - - record.setRfc(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setNum_gag_avail(getShort(rs, 3)); - record.setNum_rad_avail(getInt(rs, 4)); - record.setNum_pseudo_gages(getInt(rs, 5)); - record.setSat_avail(getString(rs, 6)); - record.setMapx_field_type(getString(rs, 7)); - record.setDraw_precip(getString(rs, 8)); - record.setAuto_save(getString(rs, 9)); - record.setLast_exec_time(getTimeStamp(rs, 10)); - record.setLast_save_time(getTimeStamp(rs, 11)); - - // add this RWResultRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RWResultRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RWResultRecord object and.. -//----------------------------------------------------------------- - public int insert(RWResultRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rwresult VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRfc()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setShort(insertStatement, 3, record.getNum_gag_avail()); - setInt(insertStatement, 4, record.getNum_rad_avail()); - setInt(insertStatement, 5, record.getNum_pseudo_gages()); - setString(insertStatement, 6, record.getSat_avail()); - setString(insertStatement, 7, record.getMapx_field_type()); - setString(insertStatement, 8, record.getDraw_precip()); - setString(insertStatement, 9, record.getAuto_save()); - setTimeStamp(insertStatement, 10, record.getLast_exec_time()); - setTimeStamp(insertStatement, 11, record.getLast_save_time()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwresult " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWResultRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWResultRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwresult SET rfc = ?, obstime = ?, num_gag_avail = ?, num_rad_avail = ?, num_pseudo_gages = ?, sat_avail = ?, mapx_field_type = ?, draw_precip = ?, auto_save = ?, last_exec_time = ?, last_save_time = ? " + where ); - - setString(updateStatement, 1, record.getRfc()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setShort(updateStatement, 3, record.getNum_gag_avail()); - setInt(updateStatement, 4, record.getNum_rad_avail()); - setInt(updateStatement, 5, record.getNum_pseudo_gages()); - setString(updateStatement, 6, record.getSat_avail()); - setString(updateStatement, 7, record.getMapx_field_type()); - setString(updateStatement, 8, record.getDraw_precip()); - setString(updateStatement, 9, record.getAuto_save()); - setTimeStamp(updateStatement, 10, record.getLast_exec_time()); - setTimeStamp(updateStatement, 11, record.getLast_save_time()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RWResultRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rwresult " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RWResultRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RWResultRecord oldRecord, RWResultRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rwresult SET rfc = ?, obstime = ?, num_gag_avail = ?, num_rad_avail = ?, num_pseudo_gages = ?, sat_avail = ?, mapx_field_type = ?, draw_precip = ?, auto_save = ?, last_exec_time = ?, last_save_time = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRfc()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setShort(updateStatement, 3, newRecord.getNum_gag_avail()); - setInt(updateStatement, 4, newRecord.getNum_rad_avail()); - setInt(updateStatement, 5, newRecord.getNum_pseudo_gages()); - setString(updateStatement, 6, newRecord.getSat_avail()); - setString(updateStatement, 7, newRecord.getMapx_field_type()); - setString(updateStatement, 8, newRecord.getDraw_precip()); - setString(updateStatement, 9, newRecord.getAuto_save()); - setTimeStamp(updateStatement, 10, newRecord.getLast_exec_time()); - setTimeStamp(updateStatement, 11, newRecord.getLast_save_time()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RWResultRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RWResultRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RWResultRecord oldRecord = (RWResultRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RWResultTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarLocRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarLocRecord.java deleted file mode 100644 index 25a40dfcbb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarLocRecord.java +++ /dev/null @@ -1,209 +0,0 @@ -// filename: RadarLocRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RadarLoc table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RadarLocRecord extends DbRecord -{ - private String radid; - - private String name; - - private String radid_prefix; - - private short radar_num; - - private String state; - - private double lat; - - private double lon; - - private double elev; - - private double tower_ht; - - private String use_radar; - - private String office_id; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RadarLocRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RadarLocRecord(RadarLocRecord origRecord) - { - setRadid(origRecord.getRadid()); - setName(origRecord.getName()); - setRadid_prefix(origRecord.getRadid_prefix()); - setRadar_num(origRecord.getRadar_num()); - setState(origRecord.getState()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setElev(origRecord.getElev()); - setTower_ht(origRecord.getTower_ht()); - setUse_radar(origRecord.getUse_radar()); - setOffice_id(origRecord.getOffice_id()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RadarLoc record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getRadid_prefix() - { - return radid_prefix; - } - - public void setRadid_prefix(String radid_prefix) - { - this.radid_prefix = radid_prefix ; - } - - public short getRadar_num() - { - return radar_num; - } - - public void setRadar_num(short radar_num) - { - this.radar_num = radar_num ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - - public double getTower_ht() - { - return tower_ht; - } - - public void setTower_ht(double tower_ht) - { - this.tower_ht = tower_ht ; - } - - public String getUse_radar() - { - return use_radar; - } - - public void setUse_radar(String use_radar) - { - this.use_radar = use_radar ; - } - - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getName() + " " + - getRadid_prefix() + " " + - getRadar_num() + " " + - getState() + " " + - getLat() + " " + - getLon() + " " + - getElev() + " " + - getTower_ht() + " " + - getUse_radar() + " " + - getOffice_id() + " " + - "" ; - return outString; - } // end toString() -} // end of RadarLocRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarLocTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarLocTable.java deleted file mode 100644 index bb8322f5aa..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarLocTable.java +++ /dev/null @@ -1,296 +0,0 @@ -// filename: RadarLocTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// radarloc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RadarLocTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RadarLocTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RadarLocTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("radarloc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RadarLocRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RadarLocRecord record = null; - - // create a List to hold RadarLoc Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM radarloc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RadarLocRecord - // and store its address in oneRecord - record = new RadarLocRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RadarLocRecord object - - record.setRadid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setRadid_prefix(getString(rs, 3)); - record.setRadar_num(getShort(rs, 4)); - record.setState(getString(rs, 5)); - record.setLat(getDouble(rs, 6)); - record.setLon(getDouble(rs, 7)); - record.setElev(getDouble(rs, 8)); - record.setTower_ht(getDouble(rs, 9)); - record.setUse_radar(getString(rs, 10)); - record.setOffice_id(getString(rs, 11)); - - // add this RadarLocRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RadarLocRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RadarLocRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RadarLocRecord record = null; - - // create a List to hold RadarLoc Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM radarloc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RadarLocRecord - // and store its address in oneRecord - record = new RadarLocRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RadarLocRecord object - - record.setRadid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setRadid_prefix(getString(rs, 3)); - record.setRadar_num(getShort(rs, 4)); - record.setState(getString(rs, 5)); - record.setLat(getDouble(rs, 6)); - record.setLon(getDouble(rs, 7)); - record.setElev(getDouble(rs, 8)); - record.setTower_ht(getDouble(rs, 9)); - record.setUse_radar(getString(rs, 10)); - record.setOffice_id(getString(rs, 11)); - - // add this RadarLocRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RadarLocRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RadarLocRecord object and.. -//----------------------------------------------------------------- - public int insert(RadarLocRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO radarloc VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setString(insertStatement, 2, record.getName()); - setString(insertStatement, 3, record.getRadid_prefix()); - setShort(insertStatement, 4, record.getRadar_num()); - setString(insertStatement, 5, record.getState()); - setDouble(insertStatement, 6, record.getLat()); - setDouble(insertStatement, 7, record.getLon()); - setDouble(insertStatement, 8, record.getElev()); - setDouble(insertStatement, 9, record.getTower_ht()); - setString(insertStatement, 10, record.getUse_radar()); - setString(insertStatement, 11, record.getOffice_id()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM radarloc " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RadarLocRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RadarLocRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE radarloc SET radid = ?, name = ?, radid_prefix = ?, radar_num = ?, state = ?, lat = ?, lon = ?, elev = ?, tower_ht = ?, use_radar = ?, office_id = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setString(updateStatement, 2, record.getName()); - setString(updateStatement, 3, record.getRadid_prefix()); - setShort(updateStatement, 4, record.getRadar_num()); - setString(updateStatement, 5, record.getState()); - setDouble(updateStatement, 6, record.getLat()); - setDouble(updateStatement, 7, record.getLon()); - setDouble(updateStatement, 8, record.getElev()); - setDouble(updateStatement, 9, record.getTower_ht()); - setString(updateStatement, 10, record.getUse_radar()); - setString(updateStatement, 11, record.getOffice_id()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RadarLocRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM radarloc " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RadarLocRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RadarLocRecord oldRecord, RadarLocRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE radarloc SET radid = ?, name = ?, radid_prefix = ?, radar_num = ?, state = ?, lat = ?, lon = ?, elev = ?, tower_ht = ?, use_radar = ?, office_id = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setString(updateStatement, 2, newRecord.getName()); - setString(updateStatement, 3, newRecord.getRadid_prefix()); - setShort(updateStatement, 4, newRecord.getRadar_num()); - setString(updateStatement, 5, newRecord.getState()); - setDouble(updateStatement, 6, newRecord.getLat()); - setDouble(updateStatement, 7, newRecord.getLon()); - setDouble(updateStatement, 8, newRecord.getElev()); - setDouble(updateStatement, 9, newRecord.getTower_ht()); - setString(updateStatement, 10, newRecord.getUse_radar()); - setString(updateStatement, 11, newRecord.getOffice_id()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RadarLocRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RadarLocRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RadarLocRecord oldRecord = (RadarLocRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RadarLocTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarRespRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarRespRecord.java deleted file mode 100644 index 830c569861..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarRespRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: RadarRespRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RadarResp table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RadarRespRecord extends DbRecord -{ - private String radid; - - private String site_id; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RadarRespRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RadarRespRecord(RadarRespRecord origRecord) - { - setRadid(origRecord.getRadid()); - setSite_id(origRecord.getSite_id()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RadarResp record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public String getSite_id() - { - return site_id; - } - - public void setSite_id(String site_id) - { - this.site_id = site_id ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getSite_id() + " " + - "" ; - return outString; - } // end toString() -} // end of RadarRespRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarRespTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarRespTable.java deleted file mode 100644 index 5f2dec10d3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadarRespTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: RadarRespTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// radarresp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RadarRespTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RadarRespTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RadarRespTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("radarresp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RadarRespRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RadarRespRecord record = null; - - // create a List to hold RadarResp Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM radarresp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RadarRespRecord - // and store its address in oneRecord - record = new RadarRespRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RadarRespRecord object - - record.setRadid(getString(rs, 1)); - record.setSite_id(getString(rs, 2)); - - // add this RadarRespRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RadarRespRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RadarRespRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RadarRespRecord record = null; - - // create a List to hold RadarResp Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM radarresp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RadarRespRecord - // and store its address in oneRecord - record = new RadarRespRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RadarRespRecord object - - record.setRadid(getString(rs, 1)); - record.setSite_id(getString(rs, 2)); - - // add this RadarRespRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RadarRespRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RadarRespRecord object and.. -//----------------------------------------------------------------- - public int insert(RadarRespRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO radarresp VALUES (?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setString(insertStatement, 2, record.getSite_id()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM radarresp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RadarRespRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RadarRespRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE radarresp SET radid = ?, site_id = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setString(updateStatement, 2, record.getSite_id()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RadarRespRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM radarresp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RadarRespRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RadarRespRecord oldRecord, RadarRespRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE radarresp SET radid = ?, site_id = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setString(updateStatement, 2, newRecord.getSite_id()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RadarRespRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RadarRespRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RadarRespRecord oldRecord = (RadarRespRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RadarRespTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadiationRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadiationRecord.java deleted file mode 100644 index 805327bcf4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadiationRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: RadiationRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Radiation table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RadiationRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RadiationRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RadiationRecord(RadiationRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Radiation record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of RadiationRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadiationTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadiationTable.java deleted file mode 100644 index 0d0644a3f8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RadiationTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: RadiationTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// radiation table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RadiationTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RadiationTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RadiationTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("radiation"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RadiationRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RadiationRecord record = null; - - // create a List to hold Radiation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM radiation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RadiationRecord - // and store its address in oneRecord - record = new RadiationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RadiationRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RadiationRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RadiationRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RadiationRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RadiationRecord record = null; - - // create a List to hold Radiation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM radiation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RadiationRecord - // and store its address in oneRecord - record = new RadiationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RadiationRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RadiationRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RadiationRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RadiationRecord object and.. -//----------------------------------------------------------------- - public int insert(RadiationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO radiation VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM radiation " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RadiationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RadiationRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE radiation SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RadiationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM radiation " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RadiationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RadiationRecord oldRecord, RadiationRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE radiation SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RadiationRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RadiationRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RadiationRecord oldRecord = (RadiationRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RadiationTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingRecord.java deleted file mode 100644 index 231cf96c5e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingRecord.java +++ /dev/null @@ -1,98 +0,0 @@ -// filename: RatingRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Rating table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RatingRecord extends DbRecord -{ - private String lid; - - private double stage; - - private double discharge; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RatingRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RatingRecord(RatingRecord origRecord) - { - setLid(origRecord.getLid()); - setStage(origRecord.getStage()); - setDischarge(origRecord.getDischarge()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Rating record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getStage() - { - return stage; - } - - public void setStage(double stage) - { - this.stage = stage ; - } - - public double getDischarge() - { - return discharge; - } - - public void setDischarge(double discharge) - { - this.discharge = discharge ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND stage = '" + stage + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getStage() + " " + - getDischarge() + " " + - "" ; - return outString; - } // end toString() -} // end of RatingRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingShiftRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingShiftRecord.java deleted file mode 100644 index eea98c0014..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingShiftRecord.java +++ /dev/null @@ -1,112 +0,0 @@ -// filename: RatingShiftRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RatingShift table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RatingShiftRecord extends DbRecord -{ - private String lid; - - private long date; - - private double shift_amount; - - private String active; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RatingShiftRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RatingShiftRecord(RatingShiftRecord origRecord) - { - setLid(origRecord.getLid()); - setDate(origRecord.getDate()); - setShift_amount(origRecord.getShift_amount()); - setActive(origRecord.getActive()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RatingShift record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public long getDate() - { - return date; - } - - public void setDate(long date) - { - this.date = date ; - } - - public double getShift_amount() - { - return shift_amount; - } - - public void setShift_amount(double shift_amount) - { - this.shift_amount = shift_amount ; - } - - public String getActive() - { - return active; - } - - public void setActive(String active) - { - this.active = active ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND date = '" + getDateStringFromLongTime(date) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDateStringFromLongTime(getDate()) + " " + - getShift_amount() + " " + - getActive() + " " + - "" ; - return outString; - } // end toString() -} // end of RatingShiftRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingShiftTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingShiftTable.java deleted file mode 100644 index 0f46aa29df..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingShiftTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: RatingShiftTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// ratingshift table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RatingShiftTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RatingShiftTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RatingShiftTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("ratingshift"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RatingShiftRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RatingShiftRecord record = null; - - // create a List to hold RatingShift Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ratingshift " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RatingShiftRecord - // and store its address in oneRecord - record = new RatingShiftRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RatingShiftRecord object - - record.setLid(getString(rs, 1)); - record.setDate(getDate(rs, 2)); - record.setShift_amount(getDouble(rs, 3)); - record.setActive(getString(rs, 4)); - - // add this RatingShiftRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RatingShiftRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RatingShiftRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RatingShiftRecord record = null; - - // create a List to hold RatingShift Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM ratingshift " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RatingShiftRecord - // and store its address in oneRecord - record = new RatingShiftRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RatingShiftRecord object - - record.setLid(getString(rs, 1)); - record.setDate(getDate(rs, 2)); - record.setShift_amount(getDouble(rs, 3)); - record.setActive(getString(rs, 4)); - - // add this RatingShiftRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RatingShiftRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RatingShiftRecord object and.. -//----------------------------------------------------------------- - public int insert(RatingShiftRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO ratingshift VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDate(insertStatement, 2, record.getDate()); - setDouble(insertStatement, 3, record.getShift_amount()); - setString(insertStatement, 4, record.getActive()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ratingshift " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RatingShiftRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RatingShiftRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ratingshift SET lid = ?, date = ?, shift_amount = ?, active = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDate(updateStatement, 2, record.getDate()); - setDouble(updateStatement, 3, record.getShift_amount()); - setString(updateStatement, 4, record.getActive()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RatingShiftRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM ratingshift " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RatingShiftRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RatingShiftRecord oldRecord, RatingShiftRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE ratingshift SET lid = ?, date = ?, shift_amount = ?, active = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDate(updateStatement, 2, newRecord.getDate()); - setDouble(updateStatement, 3, newRecord.getShift_amount()); - setString(updateStatement, 4, newRecord.getActive()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RatingShiftRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RatingShiftRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RatingShiftRecord oldRecord = (RatingShiftRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RatingShiftTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingTable.java deleted file mode 100644 index 81b93b90c3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RatingTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: RatingTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rating table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RatingTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RatingTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RatingTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rating"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RatingRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RatingRecord record = null; - - // create a List to hold Rating Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rating " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RatingRecord - // and store its address in oneRecord - record = new RatingRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RatingRecord object - - record.setLid(getString(rs, 1)); - record.setStage(getDouble(rs, 2)); - record.setDischarge(getDouble(rs, 3)); - - // add this RatingRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RatingRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RatingRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RatingRecord record = null; - - // create a List to hold Rating Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rating " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RatingRecord - // and store its address in oneRecord - record = new RatingRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RatingRecord object - - record.setLid(getString(rs, 1)); - record.setStage(getDouble(rs, 2)); - record.setDischarge(getDouble(rs, 3)); - - // add this RatingRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RatingRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RatingRecord object and.. -//----------------------------------------------------------------- - public int insert(RatingRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rating VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDouble(insertStatement, 2, record.getStage()); - setDouble(insertStatement, 3, record.getDischarge()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rating " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RatingRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RatingRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rating SET lid = ?, stage = ?, discharge = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDouble(updateStatement, 2, record.getStage()); - setDouble(updateStatement, 3, record.getDischarge()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RatingRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rating " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RatingRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RatingRecord oldRecord, RatingRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rating SET lid = ?, stage = ?, discharge = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDouble(updateStatement, 2, newRecord.getStage()); - setDouble(updateStatement, 3, newRecord.getDischarge()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RatingRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RatingRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RatingRecord oldRecord = (RatingRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RatingTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPCRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPCRecord.java deleted file mode 100644 index ce0d4143c6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPCRecord.java +++ /dev/null @@ -1,240 +0,0 @@ -// filename: RawPCRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RawPC table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RawPCRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RawPCRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RawPCRecord(RawPCRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RawPC record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of RawPCRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPCTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPCTable.java deleted file mode 100644 index 89807f4ff5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPCTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: RawPCTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rawpc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RawPCTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RawPCTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RawPCTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rawpc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RawPCRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RawPCRecord record = null; - - // create a List to hold RawPC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rawpc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RawPCRecord - // and store its address in oneRecord - record = new RawPCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RawPCRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RawPCRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RawPCRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RawPCRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RawPCRecord record = null; - - // create a List to hold RawPC Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rawpc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RawPCRecord - // and store its address in oneRecord - record = new RawPCRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RawPCRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RawPCRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RawPCRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RawPCRecord object and.. -//----------------------------------------------------------------- - public int insert(RawPCRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rawpc VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rawpc " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RawPCRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RawPCRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rawpc SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RawPCRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rawpc " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RawPCRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RawPCRecord oldRecord, RawPCRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rawpc SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RawPCRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RawPCRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RawPCRecord oldRecord = (RawPCRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RawPCTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPPRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPPRecord.java deleted file mode 100644 index 8dbaa4ef1a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPPRecord.java +++ /dev/null @@ -1,241 +0,0 @@ -// filename: RawPPRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RawPP table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RawPPRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RawPPRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RawPPRecord(RawPPRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RawPP record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of RawPPRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPPTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPPTable.java deleted file mode 100644 index 0afdff7bf9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPPTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: RawPPTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rawpp table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RawPPTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RawPPTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RawPPTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rawpp"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RawPPRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RawPPRecord record = null; - - // create a List to hold RawPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rawpp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RawPPRecord - // and store its address in oneRecord - record = new RawPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RawPPRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RawPPRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RawPPRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RawPPRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RawPPRecord record = null; - - // create a List to hold RawPP Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rawpp " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RawPPRecord - // and store its address in oneRecord - record = new RawPPRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RawPPRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RawPPRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RawPPRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RawPPRecord object and.. -//----------------------------------------------------------------- - public int insert(RawPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rawpp VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rawpp " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RawPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RawPPRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rawpp SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RawPPRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rawpp " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RawPPRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RawPPRecord oldRecord, RawPPRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rawpp SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RawPPRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RawPPRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RawPPRecord oldRecord = (RawPPRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RawPPTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPotherRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPotherRecord.java deleted file mode 100644 index f29dc548bf..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPotherRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: RawPotherRecord.java -// author : DBGEN -// created : Tue May 31 17:52:16 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RawPother table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RawPotherRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private float value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RawPotherRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RawPotherRecord(RawPotherRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RawPother record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public float getValue() - { - return value; - } - - public void setValue(float value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of RawPotherRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPotherTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPotherTable.java deleted file mode 100644 index 56ab5e0362..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RawPotherTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: RawPotherTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rawpother table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RawPotherTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RawPotherTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RawPotherTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rawpother"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RawPotherRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RawPotherRecord record = null; - - // create a List to hold RawPother Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rawpother " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RawPotherRecord - // and store its address in oneRecord - record = new RawPotherRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RawPotherRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getReal(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RawPotherRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RawPotherRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RawPotherRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RawPotherRecord record = null; - - // create a List to hold RawPother Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rawpother " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RawPotherRecord - // and store its address in oneRecord - record = new RawPotherRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RawPotherRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getReal(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this RawPotherRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RawPotherRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RawPotherRecord object and.. -//----------------------------------------------------------------- - public int insert(RawPotherRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rawpother VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setReal(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rawpother " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RawPotherRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RawPotherRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rawpother SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setReal(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RawPotherRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rawpother " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RawPotherRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RawPotherRecord oldRecord, RawPotherRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rawpother SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setReal(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RawPotherRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RawPotherRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RawPotherRecord oldRecord = (RawPotherRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RawPotherTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReferRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReferRecord.java deleted file mode 100644 index b0ca5db0ad..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReferRecord.java +++ /dev/null @@ -1,84 +0,0 @@ -// filename: ReferRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Refer table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ReferRecord extends DbRecord -{ - private String lid; - - private String reference; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ReferRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ReferRecord(ReferRecord origRecord) - { - setLid(origRecord.getLid()); - setReference(origRecord.getReference()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Refer record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getReference() - { - return reference; - } - - public void setReference(String reference) - { - this.reference = reference ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND reference = '" + reference + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getReference() + " " + - "" ; - return outString; - } // end toString() -} // end of ReferRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReferTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReferTable.java deleted file mode 100644 index 4c6bf0ddfe..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReferTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: ReferTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// refer table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ReferTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ReferTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ReferTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("refer"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ReferRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ReferRecord record = null; - - // create a List to hold Refer Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM refer " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ReferRecord - // and store its address in oneRecord - record = new ReferRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ReferRecord object - - record.setLid(getString(rs, 1)); - record.setReference(getString(rs, 2)); - - // add this ReferRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ReferRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ReferRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ReferRecord record = null; - - // create a List to hold Refer Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM refer " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ReferRecord - // and store its address in oneRecord - record = new ReferRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ReferRecord object - - record.setLid(getString(rs, 1)); - record.setReference(getString(rs, 2)); - - // add this ReferRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ReferRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ReferRecord object and.. -//----------------------------------------------------------------- - public int insert(ReferRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO refer VALUES (?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getReference()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM refer " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ReferRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ReferRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE refer SET lid = ?, reference = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getReference()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ReferRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM refer " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ReferRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ReferRecord oldRecord, ReferRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE refer SET lid = ?, reference = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getReference()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ReferRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ReferRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ReferRecord oldRecord = (ReferRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ReferTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RejectedDataRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RejectedDataRecord.java deleted file mode 100644 index 60113f2fdf..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RejectedDataRecord.java +++ /dev/null @@ -1,301 +0,0 @@ -// filename: RejectedDataRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RejectedData table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RejectedDataRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private long postingtime; - - private double value; - - private short revision; - - private String shef_qual_code; - - private String product_id; - - private long producttime; - - private int quality_code; - - private String reject_type; - - private String userid; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RejectedDataRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RejectedDataRecord(RejectedDataRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setPostingtime(origRecord.getPostingtime()); - setValue(origRecord.getValue()); - setRevision(origRecord.getRevision()); - setShef_qual_code(origRecord.getShef_qual_code()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setQuality_code(origRecord.getQuality_code()); - setReject_type(origRecord.getReject_type()); - setUserid(origRecord.getUserid()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RejectedData record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public String getReject_type() - { - return reject_type; - } - - public void setReject_type(String reject_type) - { - this.reject_type = reject_type ; - } - - public String getUserid() - { - return userid; - } - - public void setUserid(String userid) - { - this.userid = userid ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND probability = '" + probability + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - + " AND basistime = '" + getDateTimeStringFromLongTime(basistime) + "'" - + " AND postingtime = '" + getDateTimeStringFromLongTime(postingtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getValue() + " " + - getRevision() + " " + - getShef_qual_code() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getQuality_code() + " " + - getReject_type() + " " + - getUserid() + " " + - "" ; - return outString; - } // end toString() -} // end of RejectedDataRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RejectedDataTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RejectedDataTable.java deleted file mode 100644 index ff1c315752..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RejectedDataTable.java +++ /dev/null @@ -1,326 +0,0 @@ -// filename: RejectedDataTable.java -// author : DBGEN -// created : Tue May 31 17:52:26 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rejecteddata table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RejectedDataTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RejectedDataTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RejectedDataTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rejecteddata"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RejectedDataRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RejectedDataRecord record = null; - - // create a List to hold RejectedData Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rejecteddata " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RejectedDataRecord - // and store its address in oneRecord - record = new RejectedDataRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RejectedDataRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setPostingtime(getTimeStamp(rs, 9)); - record.setValue(getDouble(rs, 10)); - record.setRevision(getShort(rs, 11)); - record.setShef_qual_code(getString(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setQuality_code(getInt(rs, 15)); - record.setReject_type(getString(rs, 16)); - record.setUserid(getString(rs, 17)); - - // add this RejectedDataRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RejectedDataRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RejectedDataRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RejectedDataRecord record = null; - - // create a List to hold RejectedData Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rejecteddata " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RejectedDataRecord - // and store its address in oneRecord - record = new RejectedDataRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RejectedDataRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setPostingtime(getTimeStamp(rs, 9)); - record.setValue(getDouble(rs, 10)); - record.setRevision(getShort(rs, 11)); - record.setShef_qual_code(getString(rs, 12)); - record.setProduct_id(getString(rs, 13)); - record.setProducttime(getTimeStamp(rs, 14)); - record.setQuality_code(getInt(rs, 15)); - record.setReject_type(getString(rs, 16)); - record.setUserid(getString(rs, 17)); - - // add this RejectedDataRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RejectedDataRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RejectedDataRecord object and.. -//----------------------------------------------------------------- - public int insert(RejectedDataRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rejecteddata VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setTimeStamp(insertStatement, 9, record.getPostingtime()); - setDouble(insertStatement, 10, record.getValue()); - setShort(insertStatement, 11, record.getRevision()); - setString(insertStatement, 12, record.getShef_qual_code()); - setString(insertStatement, 13, record.getProduct_id()); - setTimeStamp(insertStatement, 14, record.getProducttime()); - setInt(insertStatement, 15, record.getQuality_code()); - setString(insertStatement, 16, record.getReject_type()); - setString(insertStatement, 17, record.getUserid()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rejecteddata " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RejectedDataRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RejectedDataRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rejecteddata SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, postingtime = ?, value = ?, revision = ?, shef_qual_code = ?, product_id = ?, producttime = ?, quality_code = ?, reject_type = ?, userid = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setTimeStamp(updateStatement, 9, record.getPostingtime()); - setDouble(updateStatement, 10, record.getValue()); - setShort(updateStatement, 11, record.getRevision()); - setString(updateStatement, 12, record.getShef_qual_code()); - setString(updateStatement, 13, record.getProduct_id()); - setTimeStamp(updateStatement, 14, record.getProducttime()); - setInt(updateStatement, 15, record.getQuality_code()); - setString(updateStatement, 16, record.getReject_type()); - setString(updateStatement, 17, record.getUserid()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RejectedDataRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rejecteddata " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RejectedDataRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RejectedDataRecord oldRecord, RejectedDataRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rejecteddata SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, postingtime = ?, value = ?, revision = ?, shef_qual_code = ?, product_id = ?, producttime = ?, quality_code = ?, reject_type = ?, userid = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setTimeStamp(updateStatement, 9, newRecord.getPostingtime()); - setDouble(updateStatement, 10, newRecord.getValue()); - setShort(updateStatement, 11, newRecord.getRevision()); - setString(updateStatement, 12, newRecord.getShef_qual_code()); - setString(updateStatement, 13, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 14, newRecord.getProducttime()); - setInt(updateStatement, 15, newRecord.getQuality_code()); - setString(updateStatement, 16, newRecord.getReject_type()); - setString(updateStatement, 17, newRecord.getUserid()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RejectedDataRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RejectedDataRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RejectedDataRecord oldRecord = (RejectedDataRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RejectedDataTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RequiredPeriodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RequiredPeriodRecord.java deleted file mode 100644 index 87a5a6f11c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RequiredPeriodRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: RequiredPeriodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RequiredPeriod table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RequiredPeriodRecord extends DbRecord -{ - private String period_req; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RequiredPeriodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RequiredPeriodRecord(RequiredPeriodRecord origRecord) - { - setPeriod_req(origRecord.getPeriod_req()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RequiredPeriod record - - //----------------------------------------------------------------- - public String getPeriod_req() - { - return period_req; - } - - public void setPeriod_req(String period_req) - { - this.period_req = period_req ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE period_req = '" + period_req + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPeriod_req() + " " + - "" ; - return outString; - } // end toString() -} // end of RequiredPeriodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RequiredPeriodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RequiredPeriodTable.java deleted file mode 100644 index 41e06e9970..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RequiredPeriodTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: RequiredPeriodTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// requiredperiod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RequiredPeriodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RequiredPeriodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RequiredPeriodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("requiredperiod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RequiredPeriodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RequiredPeriodRecord record = null; - - // create a List to hold RequiredPeriod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM requiredperiod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RequiredPeriodRecord - // and store its address in oneRecord - record = new RequiredPeriodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RequiredPeriodRecord object - - record.setPeriod_req(getString(rs, 1)); - - // add this RequiredPeriodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RequiredPeriodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RequiredPeriodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RequiredPeriodRecord record = null; - - // create a List to hold RequiredPeriod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM requiredperiod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RequiredPeriodRecord - // and store its address in oneRecord - record = new RequiredPeriodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RequiredPeriodRecord object - - record.setPeriod_req(getString(rs, 1)); - - // add this RequiredPeriodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RequiredPeriodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RequiredPeriodRecord object and.. -//----------------------------------------------------------------- - public int insert(RequiredPeriodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO requiredperiod VALUES (? )"); - - setString(insertStatement, 1, record.getPeriod_req()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM requiredperiod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RequiredPeriodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RequiredPeriodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE requiredperiod SET period_req = ? " + where ); - - setString(updateStatement, 1, record.getPeriod_req()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RequiredPeriodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM requiredperiod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RequiredPeriodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RequiredPeriodRecord oldRecord, RequiredPeriodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE requiredperiod SET period_req = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPeriod_req()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RequiredPeriodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RequiredPeriodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RequiredPeriodRecord oldRecord = (RequiredPeriodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RequiredPeriodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ResOwnerRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ResOwnerRecord.java deleted file mode 100644 index 4c3b83ed44..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ResOwnerRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: ResOwnerRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ResOwner table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ResOwnerRecord extends DbRecord -{ - private String owner; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ResOwnerRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ResOwnerRecord(ResOwnerRecord origRecord) - { - setOwner(origRecord.getOwner()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ResOwner record - - //----------------------------------------------------------------- - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE owner = '" + owner + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getOwner() + " " + - "" ; - return outString; - } // end toString() -} // end of ResOwnerRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ResOwnerTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ResOwnerTable.java deleted file mode 100644 index 5700df4257..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ResOwnerTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: ResOwnerTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// resowner table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ResOwnerTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ResOwnerTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ResOwnerTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("resowner"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ResOwnerRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ResOwnerRecord record = null; - - // create a List to hold ResOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM resowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ResOwnerRecord - // and store its address in oneRecord - record = new ResOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ResOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this ResOwnerRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ResOwnerRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ResOwnerRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ResOwnerRecord record = null; - - // create a List to hold ResOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM resowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ResOwnerRecord - // and store its address in oneRecord - record = new ResOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ResOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this ResOwnerRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ResOwnerRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ResOwnerRecord object and.. -//----------------------------------------------------------------- - public int insert(ResOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO resowner VALUES (? )"); - - setString(insertStatement, 1, record.getOwner()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM resowner " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ResOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ResOwnerRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE resowner SET owner = ? " + where ); - - setString(updateStatement, 1, record.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ResOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM resowner " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ResOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ResOwnerRecord oldRecord, ResOwnerRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE resowner SET owner = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ResOwnerRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ResOwnerRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ResOwnerRecord oldRecord = (ResOwnerRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ResOwnerTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RescapRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RescapRecord.java deleted file mode 100644 index fdf510e678..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RescapRecord.java +++ /dev/null @@ -1,98 +0,0 @@ -// filename: RescapRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Rescap table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RescapRecord extends DbRecord -{ - private String lid; - - private double elev; - - private double storage; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RescapRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RescapRecord(RescapRecord origRecord) - { - setLid(origRecord.getLid()); - setElev(origRecord.getElev()); - setStorage(origRecord.getStorage()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Rescap record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - - public double getStorage() - { - return storage; - } - - public void setStorage(double storage) - { - this.storage = storage ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND elev = '" + elev + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getElev() + " " + - getStorage() + " " + - "" ; - return outString; - } // end toString() -} // end of RescapRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RescapTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RescapTable.java deleted file mode 100644 index 429ee46f64..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RescapTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: RescapTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rescap table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RescapTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RescapTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RescapTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rescap"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RescapRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RescapRecord record = null; - - // create a List to hold Rescap Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rescap " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RescapRecord - // and store its address in oneRecord - record = new RescapRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RescapRecord object - - record.setLid(getString(rs, 1)); - record.setElev(getDouble(rs, 2)); - record.setStorage(getDouble(rs, 3)); - - // add this RescapRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RescapRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RescapRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RescapRecord record = null; - - // create a List to hold Rescap Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rescap " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RescapRecord - // and store its address in oneRecord - record = new RescapRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RescapRecord object - - record.setLid(getString(rs, 1)); - record.setElev(getDouble(rs, 2)); - record.setStorage(getDouble(rs, 3)); - - // add this RescapRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RescapRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RescapRecord object and.. -//----------------------------------------------------------------- - public int insert(RescapRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rescap VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setDouble(insertStatement, 2, record.getElev()); - setDouble(insertStatement, 3, record.getStorage()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rescap " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RescapRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RescapRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rescap SET lid = ?, elev = ?, storage = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setDouble(updateStatement, 2, record.getElev()); - setDouble(updateStatement, 3, record.getStorage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RescapRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rescap " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RescapRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RescapRecord oldRecord, RescapRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rescap SET lid = ?, elev = ?, storage = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setDouble(updateStatement, 2, newRecord.getElev()); - setDouble(updateStatement, 3, newRecord.getStorage()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RescapRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RescapRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RescapRecord oldRecord = (RescapRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RescapTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirModelRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirModelRecord.java deleted file mode 100644 index ea8b03f33f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirModelRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: ReservoirModelRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ReservoirModel table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ReservoirModelRecord extends DbRecord -{ - private String reservoir_model; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ReservoirModelRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ReservoirModelRecord(ReservoirModelRecord origRecord) - { - setReservoir_model(origRecord.getReservoir_model()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ReservoirModel record - - //----------------------------------------------------------------- - public String getReservoir_model() - { - return reservoir_model; - } - - public void setReservoir_model(String reservoir_model) - { - this.reservoir_model = reservoir_model ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE reservoir_model = '" + reservoir_model + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getReservoir_model() + " " + - "" ; - return outString; - } // end toString() -} // end of ReservoirModelRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirModelTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirModelTable.java deleted file mode 100644 index 1b12fad439..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirModelTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: ReservoirModelTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// reservoirmodel table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ReservoirModelTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ReservoirModelTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ReservoirModelTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("reservoirmodel"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ReservoirModelRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ReservoirModelRecord record = null; - - // create a List to hold ReservoirModel Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM reservoirmodel " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ReservoirModelRecord - // and store its address in oneRecord - record = new ReservoirModelRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ReservoirModelRecord object - - record.setReservoir_model(getString(rs, 1)); - - // add this ReservoirModelRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ReservoirModelRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ReservoirModelRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ReservoirModelRecord record = null; - - // create a List to hold ReservoirModel Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM reservoirmodel " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ReservoirModelRecord - // and store its address in oneRecord - record = new ReservoirModelRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ReservoirModelRecord object - - record.setReservoir_model(getString(rs, 1)); - - // add this ReservoirModelRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ReservoirModelRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ReservoirModelRecord object and.. -//----------------------------------------------------------------- - public int insert(ReservoirModelRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO reservoirmodel VALUES (? )"); - - setString(insertStatement, 1, record.getReservoir_model()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM reservoirmodel " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ReservoirModelRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ReservoirModelRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE reservoirmodel SET reservoir_model = ? " + where ); - - setString(updateStatement, 1, record.getReservoir_model()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ReservoirModelRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM reservoirmodel " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ReservoirModelRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ReservoirModelRecord oldRecord, ReservoirModelRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE reservoirmodel SET reservoir_model = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getReservoir_model()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ReservoirModelRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ReservoirModelRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ReservoirModelRecord oldRecord = (ReservoirModelRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ReservoirModelTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirRecord.java deleted file mode 100644 index 972b7c061c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirRecord.java +++ /dev/null @@ -1,293 +0,0 @@ -// filename: ReservoirRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Reservoir table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ReservoirRecord extends DbRecord -{ - private String lid; - - private String name; - - private String type; - - private String owner; - - private double deadpool; - - private double conserpool; - - private double floodpool; - - private double spillway; - - private double sill; - - private double top; - - private double surchg; - - private double elev; - - private int gates; - - private long impounded; - - private String uses; - - private String damids; - - private String damidn; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ReservoirRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ReservoirRecord(ReservoirRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setType(origRecord.getType()); - setOwner(origRecord.getOwner()); - setDeadpool(origRecord.getDeadpool()); - setConserpool(origRecord.getConserpool()); - setFloodpool(origRecord.getFloodpool()); - setSpillway(origRecord.getSpillway()); - setSill(origRecord.getSill()); - setTop(origRecord.getTop()); - setSurchg(origRecord.getSurchg()); - setElev(origRecord.getElev()); - setGates(origRecord.getGates()); - setImpounded(origRecord.getImpounded()); - setUses(origRecord.getUses()); - setDamids(origRecord.getDamids()); - setDamidn(origRecord.getDamidn()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Reservoir record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - - public double getDeadpool() - { - return deadpool; - } - - public void setDeadpool(double deadpool) - { - this.deadpool = deadpool ; - } - - public double getConserpool() - { - return conserpool; - } - - public void setConserpool(double conserpool) - { - this.conserpool = conserpool ; - } - - public double getFloodpool() - { - return floodpool; - } - - public void setFloodpool(double floodpool) - { - this.floodpool = floodpool ; - } - - public double getSpillway() - { - return spillway; - } - - public void setSpillway(double spillway) - { - this.spillway = spillway ; - } - - public double getSill() - { - return sill; - } - - public void setSill(double sill) - { - this.sill = sill ; - } - - public double getTop() - { - return top; - } - - public void setTop(double top) - { - this.top = top ; - } - - public double getSurchg() - { - return surchg; - } - - public void setSurchg(double surchg) - { - this.surchg = surchg ; - } - - public double getElev() - { - return elev; - } - - public void setElev(double elev) - { - this.elev = elev ; - } - - public int getGates() - { - return gates; - } - - public void setGates(int gates) - { - this.gates = gates ; - } - - public long getImpounded() - { - return impounded; - } - - public void setImpounded(long impounded) - { - this.impounded = impounded ; - } - - public String getUses() - { - return uses; - } - - public void setUses(String uses) - { - this.uses = uses ; - } - - public String getDamids() - { - return damids; - } - - public void setDamids(String damids) - { - this.damids = damids ; - } - - public String getDamidn() - { - return damidn; - } - - public void setDamidn(String damidn) - { - this.damidn = damidn ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getType() + " " + - getOwner() + " " + - getDeadpool() + " " + - getConserpool() + " " + - getFloodpool() + " " + - getSpillway() + " " + - getSill() + " " + - getTop() + " " + - getSurchg() + " " + - getElev() + " " + - getGates() + " " + - getDateStringFromLongTime(getImpounded()) + " " + - getUses() + " " + - getDamids() + " " + - getDamidn() + " " + - "" ; - return outString; - } // end toString() -} // end of ReservoirRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirTable.java deleted file mode 100644 index 50d2d7ff5e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ReservoirTable.java +++ /dev/null @@ -1,326 +0,0 @@ -// filename: ReservoirTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// reservoir table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ReservoirTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ReservoirTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ReservoirTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("reservoir"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ReservoirRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ReservoirRecord record = null; - - // create a List to hold Reservoir Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM reservoir " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ReservoirRecord - // and store its address in oneRecord - record = new ReservoirRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ReservoirRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setType(getString(rs, 3)); - record.setOwner(getString(rs, 4)); - record.setDeadpool(getDouble(rs, 5)); - record.setConserpool(getDouble(rs, 6)); - record.setFloodpool(getDouble(rs, 7)); - record.setSpillway(getDouble(rs, 8)); - record.setSill(getDouble(rs, 9)); - record.setTop(getDouble(rs, 10)); - record.setSurchg(getDouble(rs, 11)); - record.setElev(getDouble(rs, 12)); - record.setGates(getInt(rs, 13)); - record.setImpounded(getDate(rs, 14)); - record.setUses(getString(rs, 15)); - record.setDamids(getString(rs, 16)); - record.setDamidn(getString(rs, 17)); - - // add this ReservoirRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ReservoirRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ReservoirRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ReservoirRecord record = null; - - // create a List to hold Reservoir Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM reservoir " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ReservoirRecord - // and store its address in oneRecord - record = new ReservoirRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ReservoirRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setType(getString(rs, 3)); - record.setOwner(getString(rs, 4)); - record.setDeadpool(getDouble(rs, 5)); - record.setConserpool(getDouble(rs, 6)); - record.setFloodpool(getDouble(rs, 7)); - record.setSpillway(getDouble(rs, 8)); - record.setSill(getDouble(rs, 9)); - record.setTop(getDouble(rs, 10)); - record.setSurchg(getDouble(rs, 11)); - record.setElev(getDouble(rs, 12)); - record.setGates(getInt(rs, 13)); - record.setImpounded(getDate(rs, 14)); - record.setUses(getString(rs, 15)); - record.setDamids(getString(rs, 16)); - record.setDamidn(getString(rs, 17)); - - // add this ReservoirRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ReservoirRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ReservoirRecord object and.. -//----------------------------------------------------------------- - public int insert(ReservoirRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO reservoir VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getName()); - setString(insertStatement, 3, record.getType()); - setString(insertStatement, 4, record.getOwner()); - setDouble(insertStatement, 5, record.getDeadpool()); - setDouble(insertStatement, 6, record.getConserpool()); - setDouble(insertStatement, 7, record.getFloodpool()); - setDouble(insertStatement, 8, record.getSpillway()); - setDouble(insertStatement, 9, record.getSill()); - setDouble(insertStatement, 10, record.getTop()); - setDouble(insertStatement, 11, record.getSurchg()); - setDouble(insertStatement, 12, record.getElev()); - setInt(insertStatement, 13, record.getGates()); - setDate(insertStatement, 14, record.getImpounded()); - setString(insertStatement, 15, record.getUses()); - setString(insertStatement, 16, record.getDamids()); - setString(insertStatement, 17, record.getDamidn()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM reservoir " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ReservoirRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ReservoirRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE reservoir SET lid = ?, name = ?, type = ?, owner = ?, deadpool = ?, conserpool = ?, floodpool = ?, spillway = ?, sill = ?, top = ?, surchg = ?, elev = ?, gates = ?, impounded = ?, uses = ?, damids = ?, damidn = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getName()); - setString(updateStatement, 3, record.getType()); - setString(updateStatement, 4, record.getOwner()); - setDouble(updateStatement, 5, record.getDeadpool()); - setDouble(updateStatement, 6, record.getConserpool()); - setDouble(updateStatement, 7, record.getFloodpool()); - setDouble(updateStatement, 8, record.getSpillway()); - setDouble(updateStatement, 9, record.getSill()); - setDouble(updateStatement, 10, record.getTop()); - setDouble(updateStatement, 11, record.getSurchg()); - setDouble(updateStatement, 12, record.getElev()); - setInt(updateStatement, 13, record.getGates()); - setDate(updateStatement, 14, record.getImpounded()); - setString(updateStatement, 15, record.getUses()); - setString(updateStatement, 16, record.getDamids()); - setString(updateStatement, 17, record.getDamidn()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ReservoirRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM reservoir " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ReservoirRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ReservoirRecord oldRecord, ReservoirRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE reservoir SET lid = ?, name = ?, type = ?, owner = ?, deadpool = ?, conserpool = ?, floodpool = ?, spillway = ?, sill = ?, top = ?, surchg = ?, elev = ?, gates = ?, impounded = ?, uses = ?, damids = ?, damidn = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getName()); - setString(updateStatement, 3, newRecord.getType()); - setString(updateStatement, 4, newRecord.getOwner()); - setDouble(updateStatement, 5, newRecord.getDeadpool()); - setDouble(updateStatement, 6, newRecord.getConserpool()); - setDouble(updateStatement, 7, newRecord.getFloodpool()); - setDouble(updateStatement, 8, newRecord.getSpillway()); - setDouble(updateStatement, 9, newRecord.getSill()); - setDouble(updateStatement, 10, newRecord.getTop()); - setDouble(updateStatement, 11, newRecord.getSurchg()); - setDouble(updateStatement, 12, newRecord.getElev()); - setInt(updateStatement, 13, newRecord.getGates()); - setDate(updateStatement, 14, newRecord.getImpounded()); - setString(updateStatement, 15, newRecord.getUses()); - setString(updateStatement, 16, newRecord.getDamids()); - setString(updateStatement, 17, newRecord.getDamidn()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ReservoirRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ReservoirRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ReservoirRecord oldRecord = (ReservoirRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ReservoirTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RfcRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RfcRecord.java deleted file mode 100644 index 1c687a3f4c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RfcRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: RfcRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Rfc table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RfcRecord extends DbRecord -{ - private String rfc; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RfcRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RfcRecord(RfcRecord origRecord) - { - setRfc(origRecord.getRfc()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Rfc record - - //----------------------------------------------------------------- - public String getRfc() - { - return rfc; - } - - public void setRfc(String rfc) - { - this.rfc = rfc ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE rfc = '" + rfc + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRfc() + " " + - "" ; - return outString; - } // end toString() -} // end of RfcRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RfcTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RfcTable.java deleted file mode 100644 index 595e13a617..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RfcTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: RfcTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rfc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RfcTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RfcTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RfcTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rfc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RfcRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RfcRecord record = null; - - // create a List to hold Rfc Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rfc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RfcRecord - // and store its address in oneRecord - record = new RfcRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RfcRecord object - - record.setRfc(getString(rs, 1)); - - // add this RfcRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RfcRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RfcRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RfcRecord record = null; - - // create a List to hold Rfc Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rfc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RfcRecord - // and store its address in oneRecord - record = new RfcRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RfcRecord object - - record.setRfc(getString(rs, 1)); - - // add this RfcRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RfcRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RfcRecord object and.. -//----------------------------------------------------------------- - public int insert(RfcRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rfc VALUES (? )"); - - setString(insertStatement, 1, record.getRfc()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rfc " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RfcRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RfcRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rfc SET rfc = ? " + where ); - - setString(updateStatement, 1, record.getRfc()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RfcRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rfc " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RfcRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RfcRecord oldRecord, RfcRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rfc SET rfc = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRfc()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RfcRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RfcRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RfcRecord oldRecord = (RfcRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RfcTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonGroupRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonGroupRecord.java deleted file mode 100644 index 39265ca884..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonGroupRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: RiverMonGroupRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RiverMonGroup table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RiverMonGroupRecord extends DbRecord -{ - private String group_id; - - private String group_name; - - private int ordinal; - - private String hsa; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RiverMonGroupRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RiverMonGroupRecord(RiverMonGroupRecord origRecord) - { - setGroup_id(origRecord.getGroup_id()); - setGroup_name(origRecord.getGroup_name()); - setOrdinal(origRecord.getOrdinal()); - setHsa(origRecord.getHsa()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RiverMonGroup record - - //----------------------------------------------------------------- - public String getGroup_id() - { - return group_id; - } - - public void setGroup_id(String group_id) - { - this.group_id = group_id ; - } - - public String getGroup_name() - { - return group_name; - } - - public void setGroup_name(String group_name) - { - this.group_name = group_name ; - } - - public int getOrdinal() - { - return ordinal; - } - - public void setOrdinal(int ordinal) - { - this.ordinal = ordinal ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE group_id = '" + group_id + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getGroup_id() + " " + - getGroup_name() + " " + - getOrdinal() + " " + - getHsa() + " " + - "" ; - return outString; - } // end toString() -} // end of RiverMonGroupRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonGroupTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonGroupTable.java deleted file mode 100644 index 372d2b9de2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonGroupTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: RiverMonGroupTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rivermongroup table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RiverMonGroupTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RiverMonGroupTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RiverMonGroupTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rivermongroup"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RiverMonGroupRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RiverMonGroupRecord record = null; - - // create a List to hold RiverMonGroup Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rivermongroup " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverMonGroupRecord - // and store its address in oneRecord - record = new RiverMonGroupRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverMonGroupRecord object - - record.setGroup_id(getString(rs, 1)); - record.setGroup_name(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - record.setHsa(getString(rs, 4)); - - // add this RiverMonGroupRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RiverMonGroupRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RiverMonGroupRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RiverMonGroupRecord record = null; - - // create a List to hold RiverMonGroup Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rivermongroup " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverMonGroupRecord - // and store its address in oneRecord - record = new RiverMonGroupRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverMonGroupRecord object - - record.setGroup_id(getString(rs, 1)); - record.setGroup_name(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - record.setHsa(getString(rs, 4)); - - // add this RiverMonGroupRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RiverMonGroupRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RiverMonGroupRecord object and.. -//----------------------------------------------------------------- - public int insert(RiverMonGroupRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rivermongroup VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getGroup_id()); - setString(insertStatement, 2, record.getGroup_name()); - setInt(insertStatement, 3, record.getOrdinal()); - setString(insertStatement, 4, record.getHsa()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rivermongroup " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverMonGroupRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverMonGroupRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rivermongroup SET group_id = ?, group_name = ?, ordinal = ?, hsa = ? " + where ); - - setString(updateStatement, 1, record.getGroup_id()); - setString(updateStatement, 2, record.getGroup_name()); - setInt(updateStatement, 3, record.getOrdinal()); - setString(updateStatement, 4, record.getHsa()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RiverMonGroupRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rivermongroup " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverMonGroupRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverMonGroupRecord oldRecord, RiverMonGroupRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rivermongroup SET group_id = ?, group_name = ?, ordinal = ?, hsa = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getGroup_id()); - setString(updateStatement, 2, newRecord.getGroup_name()); - setInt(updateStatement, 3, newRecord.getOrdinal()); - setString(updateStatement, 4, newRecord.getHsa()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RiverMonGroupRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RiverMonGroupRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RiverMonGroupRecord oldRecord = (RiverMonGroupRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RiverMonGroupTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonLocationRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonLocationRecord.java deleted file mode 100644 index 4768ec77be..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonLocationRecord.java +++ /dev/null @@ -1,97 +0,0 @@ -// filename: RiverMonLocationRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RiverMonLocation table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RiverMonLocationRecord extends DbRecord -{ - private String lid; - - private String group_id; - - private int ordinal; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RiverMonLocationRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RiverMonLocationRecord(RiverMonLocationRecord origRecord) - { - setLid(origRecord.getLid()); - setGroup_id(origRecord.getGroup_id()); - setOrdinal(origRecord.getOrdinal()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RiverMonLocation record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getGroup_id() - { - return group_id; - } - - public void setGroup_id(String group_id) - { - this.group_id = group_id ; - } - - public int getOrdinal() - { - return ordinal; - } - - public void setOrdinal(int ordinal) - { - this.ordinal = ordinal ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getGroup_id() + " " + - getOrdinal() + " " + - "" ; - return outString; - } // end toString() -} // end of RiverMonLocationRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonLocationTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonLocationTable.java deleted file mode 100644 index 1dee607be6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverMonLocationTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: RiverMonLocationTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rivermonlocation table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RiverMonLocationTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RiverMonLocationTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RiverMonLocationTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rivermonlocation"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RiverMonLocationRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RiverMonLocationRecord record = null; - - // create a List to hold RiverMonLocation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rivermonlocation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverMonLocationRecord - // and store its address in oneRecord - record = new RiverMonLocationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverMonLocationRecord object - - record.setLid(getString(rs, 1)); - record.setGroup_id(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - - // add this RiverMonLocationRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RiverMonLocationRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RiverMonLocationRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RiverMonLocationRecord record = null; - - // create a List to hold RiverMonLocation Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rivermonlocation " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverMonLocationRecord - // and store its address in oneRecord - record = new RiverMonLocationRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverMonLocationRecord object - - record.setLid(getString(rs, 1)); - record.setGroup_id(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - - // add this RiverMonLocationRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RiverMonLocationRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RiverMonLocationRecord object and.. -//----------------------------------------------------------------- - public int insert(RiverMonLocationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rivermonlocation VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getGroup_id()); - setInt(insertStatement, 3, record.getOrdinal()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rivermonlocation " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverMonLocationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverMonLocationRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rivermonlocation SET lid = ?, group_id = ?, ordinal = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getGroup_id()); - setInt(updateStatement, 3, record.getOrdinal()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RiverMonLocationRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rivermonlocation " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverMonLocationRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverMonLocationRecord oldRecord, RiverMonLocationRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rivermonlocation SET lid = ?, group_id = ?, ordinal = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getGroup_id()); - setInt(updateStatement, 3, newRecord.getOrdinal()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RiverMonLocationRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RiverMonLocationRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RiverMonLocationRecord oldRecord = (RiverMonLocationRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RiverMonLocationTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverStatusRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverStatusRecord.java deleted file mode 100644 index 567f3816b6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverStatusRecord.java +++ /dev/null @@ -1,183 +0,0 @@ -// filename: RiverStatusRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RiverStatus table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RiverStatusRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private float probability; - - private long validtime; - - private long basistime; - - private double value; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RiverStatusRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RiverStatusRecord(RiverStatusRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setProbability(origRecord.getProbability()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setValue(origRecord.getValue()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RiverStatus record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND ts = '" + ts + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getProbability() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getValue() + " " + - "" ; - return outString; - } // end toString() -} // end of RiverStatusRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverStatusTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverStatusTable.java deleted file mode 100644 index f2a2aefaf7..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverStatusTable.java +++ /dev/null @@ -1,286 +0,0 @@ -// filename: RiverStatusTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// riverstatus table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RiverStatusTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RiverStatusTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RiverStatusTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("riverstatus"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RiverStatusRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RiverStatusRecord record = null; - - // create a List to hold RiverStatus Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM riverstatus " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverStatusRecord - // and store its address in oneRecord - record = new RiverStatusRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverStatusRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - - // add this RiverStatusRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RiverStatusRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RiverStatusRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RiverStatusRecord record = null; - - // create a List to hold RiverStatus Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM riverstatus " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverStatusRecord - // and store its address in oneRecord - record = new RiverStatusRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverStatusRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setProbability(getReal(rs, 6)); - record.setValidtime(getTimeStamp(rs, 7)); - record.setBasistime(getTimeStamp(rs, 8)); - record.setValue(getDouble(rs, 9)); - - // add this RiverStatusRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RiverStatusRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RiverStatusRecord object and.. -//----------------------------------------------------------------- - public int insert(RiverStatusRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO riverstatus VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setReal(insertStatement, 6, record.getProbability()); - setTimeStamp(insertStatement, 7, record.getValidtime()); - setTimeStamp(insertStatement, 8, record.getBasistime()); - setDouble(insertStatement, 9, record.getValue()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM riverstatus " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverStatusRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverStatusRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE riverstatus SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setReal(updateStatement, 6, record.getProbability()); - setTimeStamp(updateStatement, 7, record.getValidtime()); - setTimeStamp(updateStatement, 8, record.getBasistime()); - setDouble(updateStatement, 9, record.getValue()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RiverStatusRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM riverstatus " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverStatusRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverStatusRecord oldRecord, RiverStatusRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE riverstatus SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, probability = ?, validtime = ?, basistime = ?, value = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setReal(updateStatement, 6, newRecord.getProbability()); - setTimeStamp(updateStatement, 7, newRecord.getValidtime()); - setTimeStamp(updateStatement, 8, newRecord.getBasistime()); - setDouble(updateStatement, 9, newRecord.getValue()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RiverStatusRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RiverStatusRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RiverStatusRecord oldRecord = (RiverStatusRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RiverStatusTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverstatRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverstatRecord.java deleted file mode 100644 index db3b5c95d3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverstatRecord.java +++ /dev/null @@ -1,489 +0,0 @@ -// filename: RiverstatRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Riverstat table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RiverstatRecord extends DbRecord -{ - private String lid; - - private String primary_pe; - - private double bf; - - private double cb; - - private double da; - - private double response_time; - - private double threshold_runoff; - - private double fq; - - private double fs; - - private String gsno; - - private String level; - - private double mile; - - private double pool; - - private String por; - - private String rated; - - private double lat; - - private double lon; - - private String remark; - - private long rrevise; - - private String rsource; - - private String stream; - - private String tide; - - private String backwater; - - private String vdatum; - - private double action_flow; - - private double wstg; - - private double zd; - - private long ratedat; - - private String usgs_ratenum; - - private int uhgdur; - - private String use_latest_fcst; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RiverstatRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RiverstatRecord(RiverstatRecord origRecord) - { - setLid(origRecord.getLid()); - setPrimary_pe(origRecord.getPrimary_pe()); - setBf(origRecord.getBf()); - setCb(origRecord.getCb()); - setDa(origRecord.getDa()); - setResponse_time(origRecord.getResponse_time()); - setThreshold_runoff(origRecord.getThreshold_runoff()); - setFq(origRecord.getFq()); - setFs(origRecord.getFs()); - setGsno(origRecord.getGsno()); - setLevel(origRecord.getLevel()); - setMile(origRecord.getMile()); - setPool(origRecord.getPool()); - setPor(origRecord.getPor()); - setRated(origRecord.getRated()); - setLat(origRecord.getLat()); - setLon(origRecord.getLon()); - setRemark(origRecord.getRemark()); - setRrevise(origRecord.getRrevise()); - setRsource(origRecord.getRsource()); - setStream(origRecord.getStream()); - setTide(origRecord.getTide()); - setBackwater(origRecord.getBackwater()); - setVdatum(origRecord.getVdatum()); - setAction_flow(origRecord.getAction_flow()); - setWstg(origRecord.getWstg()); - setZd(origRecord.getZd()); - setRatedat(origRecord.getRatedat()); - setUsgs_ratenum(origRecord.getUsgs_ratenum()); - setUhgdur(origRecord.getUhgdur()); - setUse_latest_fcst(origRecord.getUse_latest_fcst()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Riverstat record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPrimary_pe() - { - return primary_pe; - } - - public void setPrimary_pe(String primary_pe) - { - this.primary_pe = primary_pe ; - } - - public double getBf() - { - return bf; - } - - public void setBf(double bf) - { - this.bf = bf ; - } - - public double getCb() - { - return cb; - } - - public void setCb(double cb) - { - this.cb = cb ; - } - - public double getDa() - { - return da; - } - - public void setDa(double da) - { - this.da = da ; - } - - public double getResponse_time() - { - return response_time; - } - - public void setResponse_time(double response_time) - { - this.response_time = response_time ; - } - - public double getThreshold_runoff() - { - return threshold_runoff; - } - - public void setThreshold_runoff(double threshold_runoff) - { - this.threshold_runoff = threshold_runoff ; - } - - public double getFq() - { - return fq; - } - - public void setFq(double fq) - { - this.fq = fq ; - } - - public double getFs() - { - return fs; - } - - public void setFs(double fs) - { - this.fs = fs ; - } - - public String getGsno() - { - return gsno; - } - - public void setGsno(String gsno) - { - this.gsno = gsno ; - } - - public String getLevel() - { - return level; - } - - public void setLevel(String level) - { - this.level = level ; - } - - public double getMile() - { - return mile; - } - - public void setMile(double mile) - { - this.mile = mile ; - } - - public double getPool() - { - return pool; - } - - public void setPool(double pool) - { - this.pool = pool ; - } - - public String getPor() - { - return por; - } - - public void setPor(String por) - { - this.por = por ; - } - - public String getRated() - { - return rated; - } - - public void setRated(String rated) - { - this.rated = rated ; - } - - public double getLat() - { - return lat; - } - - public void setLat(double lat) - { - this.lat = lat ; - } - - public double getLon() - { - return lon; - } - - public void setLon(double lon) - { - this.lon = lon ; - } - - public String getRemark() - { - return remark; - } - - public void setRemark(String remark) - { - this.remark = remark ; - } - - public long getRrevise() - { - return rrevise; - } - - public void setRrevise(long rrevise) - { - this.rrevise = rrevise ; - } - - public String getRsource() - { - return rsource; - } - - public void setRsource(String rsource) - { - this.rsource = rsource ; - } - - public String getStream() - { - return stream; - } - - public void setStream(String stream) - { - this.stream = stream ; - } - - public String getTide() - { - return tide; - } - - public void setTide(String tide) - { - this.tide = tide ; - } - - public String getBackwater() - { - return backwater; - } - - public void setBackwater(String backwater) - { - this.backwater = backwater ; - } - - public String getVdatum() - { - return vdatum; - } - - public void setVdatum(String vdatum) - { - this.vdatum = vdatum ; - } - - public double getAction_flow() - { - return action_flow; - } - - public void setAction_flow(double action_flow) - { - this.action_flow = action_flow ; - } - - public double getWstg() - { - return wstg; - } - - public void setWstg(double wstg) - { - this.wstg = wstg ; - } - - public double getZd() - { - return zd; - } - - public void setZd(double zd) - { - this.zd = zd ; - } - - public long getRatedat() - { - return ratedat; - } - - public void setRatedat(long ratedat) - { - this.ratedat = ratedat ; - } - - public String getUsgs_ratenum() - { - return usgs_ratenum; - } - - public void setUsgs_ratenum(String usgs_ratenum) - { - this.usgs_ratenum = usgs_ratenum ; - } - - public int getUhgdur() - { - return uhgdur; - } - - public void setUhgdur(int uhgdur) - { - this.uhgdur = uhgdur ; - } - - public String getUse_latest_fcst() - { - return use_latest_fcst; - } - - public void setUse_latest_fcst(String use_latest_fcst) - { - this.use_latest_fcst = use_latest_fcst ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPrimary_pe() + " " + - getBf() + " " + - getCb() + " " + - getDa() + " " + - getResponse_time() + " " + - getThreshold_runoff() + " " + - getFq() + " " + - getFs() + " " + - getGsno() + " " + - getLevel() + " " + - getMile() + " " + - getPool() + " " + - getPor() + " " + - getRated() + " " + - getLat() + " " + - getLon() + " " + - getRemark() + " " + - getDateStringFromLongTime(getRrevise()) + " " + - getRsource() + " " + - getStream() + " " + - getTide() + " " + - getBackwater() + " " + - getVdatum() + " " + - getAction_flow() + " " + - getWstg() + " " + - getZd() + " " + - getDateStringFromLongTime(getRatedat()) + " " + - getUsgs_ratenum() + " " + - getUhgdur() + " " + - getUse_latest_fcst() + " " + - "" ; - return outString; - } // end toString() -} // end of RiverstatRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverstatTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverstatTable.java deleted file mode 100644 index afbb54690c..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RiverstatTable.java +++ /dev/null @@ -1,396 +0,0 @@ -// filename: RiverstatTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// riverstat table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RiverstatTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RiverstatTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RiverstatTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("riverstat"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RiverstatRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RiverstatRecord record = null; - - // create a List to hold Riverstat Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM riverstat " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverstatRecord - // and store its address in oneRecord - record = new RiverstatRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverstatRecord object - - record.setLid(getString(rs, 1)); - record.setPrimary_pe(getString(rs, 2)); - record.setBf(getDouble(rs, 3)); - record.setCb(getDouble(rs, 4)); - record.setDa(getDouble(rs, 5)); - record.setResponse_time(getDouble(rs, 6)); - record.setThreshold_runoff(getDouble(rs, 7)); - record.setFq(getDouble(rs, 8)); - record.setFs(getDouble(rs, 9)); - record.setGsno(getString(rs, 10)); - record.setLevel(getString(rs, 11)); - record.setMile(getDouble(rs, 12)); - record.setPool(getDouble(rs, 13)); - record.setPor(getString(rs, 14)); - record.setRated(getString(rs, 15)); - record.setLat(getDouble(rs, 16)); - record.setLon(getDouble(rs, 17)); - record.setRemark(getString(rs, 18)); - record.setRrevise(getDate(rs, 19)); - record.setRsource(getString(rs, 20)); - record.setStream(getString(rs, 21)); - record.setTide(getString(rs, 22)); - record.setBackwater(getString(rs, 23)); - record.setVdatum(getString(rs, 24)); - record.setAction_flow(getDouble(rs, 25)); - record.setWstg(getDouble(rs, 26)); - record.setZd(getDouble(rs, 27)); - record.setRatedat(getDate(rs, 28)); - record.setUsgs_ratenum(getString(rs, 29)); - record.setUhgdur(getInt(rs, 30)); - record.setUse_latest_fcst(getString(rs, 31)); - - // add this RiverstatRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RiverstatRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RiverstatRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RiverstatRecord record = null; - - // create a List to hold Riverstat Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM riverstat " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RiverstatRecord - // and store its address in oneRecord - record = new RiverstatRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RiverstatRecord object - - record.setLid(getString(rs, 1)); - record.setPrimary_pe(getString(rs, 2)); - record.setBf(getDouble(rs, 3)); - record.setCb(getDouble(rs, 4)); - record.setDa(getDouble(rs, 5)); - record.setResponse_time(getDouble(rs, 6)); - record.setThreshold_runoff(getDouble(rs, 7)); - record.setFq(getDouble(rs, 8)); - record.setFs(getDouble(rs, 9)); - record.setGsno(getString(rs, 10)); - record.setLevel(getString(rs, 11)); - record.setMile(getDouble(rs, 12)); - record.setPool(getDouble(rs, 13)); - record.setPor(getString(rs, 14)); - record.setRated(getString(rs, 15)); - record.setLat(getDouble(rs, 16)); - record.setLon(getDouble(rs, 17)); - record.setRemark(getString(rs, 18)); - record.setRrevise(getDate(rs, 19)); - record.setRsource(getString(rs, 20)); - record.setStream(getString(rs, 21)); - record.setTide(getString(rs, 22)); - record.setBackwater(getString(rs, 23)); - record.setVdatum(getString(rs, 24)); - record.setAction_flow(getDouble(rs, 25)); - record.setWstg(getDouble(rs, 26)); - record.setZd(getDouble(rs, 27)); - record.setRatedat(getDate(rs, 28)); - record.setUsgs_ratenum(getString(rs, 29)); - record.setUhgdur(getInt(rs, 30)); - record.setUse_latest_fcst(getString(rs, 31)); - - // add this RiverstatRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RiverstatRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RiverstatRecord object and.. -//----------------------------------------------------------------- - public int insert(RiverstatRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO riverstat VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPrimary_pe()); - setDouble(insertStatement, 3, record.getBf()); - setDouble(insertStatement, 4, record.getCb()); - setDouble(insertStatement, 5, record.getDa()); - setDouble(insertStatement, 6, record.getResponse_time()); - setDouble(insertStatement, 7, record.getThreshold_runoff()); - setDouble(insertStatement, 8, record.getFq()); - setDouble(insertStatement, 9, record.getFs()); - setString(insertStatement, 10, record.getGsno()); - setString(insertStatement, 11, record.getLevel()); - setDouble(insertStatement, 12, record.getMile()); - setDouble(insertStatement, 13, record.getPool()); - setString(insertStatement, 14, record.getPor()); - setString(insertStatement, 15, record.getRated()); - setDouble(insertStatement, 16, record.getLat()); - setDouble(insertStatement, 17, record.getLon()); - setString(insertStatement, 18, record.getRemark()); - setDate(insertStatement, 19, record.getRrevise()); - setString(insertStatement, 20, record.getRsource()); - setString(insertStatement, 21, record.getStream()); - setString(insertStatement, 22, record.getTide()); - setString(insertStatement, 23, record.getBackwater()); - setString(insertStatement, 24, record.getVdatum()); - setDouble(insertStatement, 25, record.getAction_flow()); - setDouble(insertStatement, 26, record.getWstg()); - setDouble(insertStatement, 27, record.getZd()); - setDate(insertStatement, 28, record.getRatedat()); - setString(insertStatement, 29, record.getUsgs_ratenum()); - setInt(insertStatement, 30, record.getUhgdur()); - setString(insertStatement, 31, record.getUse_latest_fcst()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM riverstat " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverstatRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverstatRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE riverstat SET lid = ?, primary_pe = ?, bf = ?, cb = ?, da = ?, response_time = ?, threshold_runoff = ?, fq = ?, fs = ?, gsno = ?, level = ?, mile = ?, pool = ?, por = ?, rated = ?, lat = ?, lon = ?, remark = ?, rrevise = ?, rsource = ?, stream = ?, tide = ?, backwater = ?, vdatum = ?, action_flow = ?, wstg = ?, zd = ?, ratedat = ?, usgs_ratenum = ?, uhgdur = ?, use_latest_fcst = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPrimary_pe()); - setDouble(updateStatement, 3, record.getBf()); - setDouble(updateStatement, 4, record.getCb()); - setDouble(updateStatement, 5, record.getDa()); - setDouble(updateStatement, 6, record.getResponse_time()); - setDouble(updateStatement, 7, record.getThreshold_runoff()); - setDouble(updateStatement, 8, record.getFq()); - setDouble(updateStatement, 9, record.getFs()); - setString(updateStatement, 10, record.getGsno()); - setString(updateStatement, 11, record.getLevel()); - setDouble(updateStatement, 12, record.getMile()); - setDouble(updateStatement, 13, record.getPool()); - setString(updateStatement, 14, record.getPor()); - setString(updateStatement, 15, record.getRated()); - setDouble(updateStatement, 16, record.getLat()); - setDouble(updateStatement, 17, record.getLon()); - setString(updateStatement, 18, record.getRemark()); - setDate(updateStatement, 19, record.getRrevise()); - setString(updateStatement, 20, record.getRsource()); - setString(updateStatement, 21, record.getStream()); - setString(updateStatement, 22, record.getTide()); - setString(updateStatement, 23, record.getBackwater()); - setString(updateStatement, 24, record.getVdatum()); - setDouble(updateStatement, 25, record.getAction_flow()); - setDouble(updateStatement, 26, record.getWstg()); - setDouble(updateStatement, 27, record.getZd()); - setDate(updateStatement, 28, record.getRatedat()); - setString(updateStatement, 29, record.getUsgs_ratenum()); - setInt(updateStatement, 30, record.getUhgdur()); - setString(updateStatement, 31, record.getUse_latest_fcst()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RiverstatRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM riverstat " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RiverstatRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RiverstatRecord oldRecord, RiverstatRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE riverstat SET lid = ?, primary_pe = ?, bf = ?, cb = ?, da = ?, response_time = ?, threshold_runoff = ?, fq = ?, fs = ?, gsno = ?, level = ?, mile = ?, pool = ?, por = ?, rated = ?, lat = ?, lon = ?, remark = ?, rrevise = ?, rsource = ?, stream = ?, tide = ?, backwater = ?, vdatum = ?, action_flow = ?, wstg = ?, zd = ?, ratedat = ?, usgs_ratenum = ?, uhgdur = ?, use_latest_fcst = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPrimary_pe()); - setDouble(updateStatement, 3, newRecord.getBf()); - setDouble(updateStatement, 4, newRecord.getCb()); - setDouble(updateStatement, 5, newRecord.getDa()); - setDouble(updateStatement, 6, newRecord.getResponse_time()); - setDouble(updateStatement, 7, newRecord.getThreshold_runoff()); - setDouble(updateStatement, 8, newRecord.getFq()); - setDouble(updateStatement, 9, newRecord.getFs()); - setString(updateStatement, 10, newRecord.getGsno()); - setString(updateStatement, 11, newRecord.getLevel()); - setDouble(updateStatement, 12, newRecord.getMile()); - setDouble(updateStatement, 13, newRecord.getPool()); - setString(updateStatement, 14, newRecord.getPor()); - setString(updateStatement, 15, newRecord.getRated()); - setDouble(updateStatement, 16, newRecord.getLat()); - setDouble(updateStatement, 17, newRecord.getLon()); - setString(updateStatement, 18, newRecord.getRemark()); - setDate(updateStatement, 19, newRecord.getRrevise()); - setString(updateStatement, 20, newRecord.getRsource()); - setString(updateStatement, 21, newRecord.getStream()); - setString(updateStatement, 22, newRecord.getTide()); - setString(updateStatement, 23, newRecord.getBackwater()); - setString(updateStatement, 24, newRecord.getVdatum()); - setDouble(updateStatement, 25, newRecord.getAction_flow()); - setDouble(updateStatement, 26, newRecord.getWstg()); - setDouble(updateStatement, 27, newRecord.getZd()); - setDate(updateStatement, 28, newRecord.getRatedat()); - setString(updateStatement, 29, newRecord.getUsgs_ratenum()); - setInt(updateStatement, 30, newRecord.getUhgdur()); - setString(updateStatement, 31, newRecord.getUse_latest_fcst()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RiverstatRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RiverstatRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RiverstatRecord oldRecord = (RiverstatRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RiverstatTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RoutingMethodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RoutingMethodRecord.java deleted file mode 100644 index 091d95aa1d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RoutingMethodRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: RoutingMethodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RoutingMethod table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RoutingMethodRecord extends DbRecord -{ - private String hydraul_method; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RoutingMethodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RoutingMethodRecord(RoutingMethodRecord origRecord) - { - setHydraul_method(origRecord.getHydraul_method()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RoutingMethod record - - //----------------------------------------------------------------- - public String getHydraul_method() - { - return hydraul_method; - } - - public void setHydraul_method(String hydraul_method) - { - this.hydraul_method = hydraul_method ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE hydraul_method = '" + hydraul_method + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getHydraul_method() + " " + - "" ; - return outString; - } // end toString() -} // end of RoutingMethodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RoutingMethodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RoutingMethodTable.java deleted file mode 100644 index ed1c990566..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RoutingMethodTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: RoutingMethodTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// routingmethod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RoutingMethodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RoutingMethodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RoutingMethodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("routingmethod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RoutingMethodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RoutingMethodRecord record = null; - - // create a List to hold RoutingMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM routingmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RoutingMethodRecord - // and store its address in oneRecord - record = new RoutingMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RoutingMethodRecord object - - record.setHydraul_method(getString(rs, 1)); - - // add this RoutingMethodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RoutingMethodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RoutingMethodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RoutingMethodRecord record = null; - - // create a List to hold RoutingMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM routingmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RoutingMethodRecord - // and store its address in oneRecord - record = new RoutingMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RoutingMethodRecord object - - record.setHydraul_method(getString(rs, 1)); - - // add this RoutingMethodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RoutingMethodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RoutingMethodRecord object and.. -//----------------------------------------------------------------- - public int insert(RoutingMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO routingmethod VALUES (? )"); - - setString(insertStatement, 1, record.getHydraul_method()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM routingmethod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RoutingMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RoutingMethodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE routingmethod SET hydraul_method = ? " + where ); - - setString(updateStatement, 1, record.getHydraul_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RoutingMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM routingmethod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RoutingMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RoutingMethodRecord oldRecord, RoutingMethodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE routingmethod SET hydraul_method = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getHydraul_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RoutingMethodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RoutingMethodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RoutingMethodRecord oldRecord = (RoutingMethodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RoutingMethodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstGroupRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstGroupRecord.java deleted file mode 100644 index 67cd7d4ce8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstGroupRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: RpfFcstGroupRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RpfFcstGroup table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RpfFcstGroupRecord extends DbRecord -{ - private String group_id; - - private String group_name; - - private int ordinal; - - private String rec_all_included; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RpfFcstGroupRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RpfFcstGroupRecord(RpfFcstGroupRecord origRecord) - { - setGroup_id(origRecord.getGroup_id()); - setGroup_name(origRecord.getGroup_name()); - setOrdinal(origRecord.getOrdinal()); - setRec_all_included(origRecord.getRec_all_included()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RpfFcstGroup record - - //----------------------------------------------------------------- - public String getGroup_id() - { - return group_id; - } - - public void setGroup_id(String group_id) - { - this.group_id = group_id ; - } - - public String getGroup_name() - { - return group_name; - } - - public void setGroup_name(String group_name) - { - this.group_name = group_name ; - } - - public int getOrdinal() - { - return ordinal; - } - - public void setOrdinal(int ordinal) - { - this.ordinal = ordinal ; - } - - public String getRec_all_included() - { - return rec_all_included; - } - - public void setRec_all_included(String rec_all_included) - { - this.rec_all_included = rec_all_included ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE group_id = '" + group_id + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getGroup_id() + " " + - getGroup_name() + " " + - getOrdinal() + " " + - getRec_all_included() + " " + - "" ; - return outString; - } // end toString() -} // end of RpfFcstGroupRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstGroupTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstGroupTable.java deleted file mode 100644 index d57b5b1644..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstGroupTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: RpfFcstGroupTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rpffcstgroup table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RpfFcstGroupTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RpfFcstGroupTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RpfFcstGroupTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rpffcstgroup"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RpfFcstGroupRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RpfFcstGroupRecord record = null; - - // create a List to hold RpfFcstGroup Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rpffcstgroup " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RpfFcstGroupRecord - // and store its address in oneRecord - record = new RpfFcstGroupRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RpfFcstGroupRecord object - - record.setGroup_id(getString(rs, 1)); - record.setGroup_name(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - record.setRec_all_included(getString(rs, 4)); - - // add this RpfFcstGroupRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RpfFcstGroupRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RpfFcstGroupRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RpfFcstGroupRecord record = null; - - // create a List to hold RpfFcstGroup Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rpffcstgroup " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RpfFcstGroupRecord - // and store its address in oneRecord - record = new RpfFcstGroupRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RpfFcstGroupRecord object - - record.setGroup_id(getString(rs, 1)); - record.setGroup_name(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - record.setRec_all_included(getString(rs, 4)); - - // add this RpfFcstGroupRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RpfFcstGroupRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RpfFcstGroupRecord object and.. -//----------------------------------------------------------------- - public int insert(RpfFcstGroupRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rpffcstgroup VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getGroup_id()); - setString(insertStatement, 2, record.getGroup_name()); - setInt(insertStatement, 3, record.getOrdinal()); - setString(insertStatement, 4, record.getRec_all_included()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rpffcstgroup " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RpfFcstGroupRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RpfFcstGroupRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rpffcstgroup SET group_id = ?, group_name = ?, ordinal = ?, rec_all_included = ? " + where ); - - setString(updateStatement, 1, record.getGroup_id()); - setString(updateStatement, 2, record.getGroup_name()); - setInt(updateStatement, 3, record.getOrdinal()); - setString(updateStatement, 4, record.getRec_all_included()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RpfFcstGroupRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rpffcstgroup " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RpfFcstGroupRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RpfFcstGroupRecord oldRecord, RpfFcstGroupRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rpffcstgroup SET group_id = ?, group_name = ?, ordinal = ?, rec_all_included = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getGroup_id()); - setString(updateStatement, 2, newRecord.getGroup_name()); - setInt(updateStatement, 3, newRecord.getOrdinal()); - setString(updateStatement, 4, newRecord.getRec_all_included()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RpfFcstGroupRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RpfFcstGroupRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RpfFcstGroupRecord oldRecord = (RpfFcstGroupRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RpfFcstGroupTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstPointRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstPointRecord.java deleted file mode 100644 index 52403fe312..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstPointRecord.java +++ /dev/null @@ -1,195 +0,0 @@ -// filename: RpfFcstPointRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RpfFcstPoint table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RpfFcstPointRecord extends DbRecord -{ - private String lid; - - private String group_id; - - private int ordinal; - - private double chg_threshold; - - private String rec_type; - - private String primary_back; - - private String secondary_back; - - private int backhrs; - - private int forwardhrs; - - private double adjustendhrs; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RpfFcstPointRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RpfFcstPointRecord(RpfFcstPointRecord origRecord) - { - setLid(origRecord.getLid()); - setGroup_id(origRecord.getGroup_id()); - setOrdinal(origRecord.getOrdinal()); - setChg_threshold(origRecord.getChg_threshold()); - setRec_type(origRecord.getRec_type()); - setPrimary_back(origRecord.getPrimary_back()); - setSecondary_back(origRecord.getSecondary_back()); - setBackhrs(origRecord.getBackhrs()); - setForwardhrs(origRecord.getForwardhrs()); - setAdjustendhrs(origRecord.getAdjustendhrs()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RpfFcstPoint record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getGroup_id() - { - return group_id; - } - - public void setGroup_id(String group_id) - { - this.group_id = group_id ; - } - - public int getOrdinal() - { - return ordinal; - } - - public void setOrdinal(int ordinal) - { - this.ordinal = ordinal ; - } - - public double getChg_threshold() - { - return chg_threshold; - } - - public void setChg_threshold(double chg_threshold) - { - this.chg_threshold = chg_threshold ; - } - - public String getRec_type() - { - return rec_type; - } - - public void setRec_type(String rec_type) - { - this.rec_type = rec_type ; - } - - public String getPrimary_back() - { - return primary_back; - } - - public void setPrimary_back(String primary_back) - { - this.primary_back = primary_back ; - } - - public String getSecondary_back() - { - return secondary_back; - } - - public void setSecondary_back(String secondary_back) - { - this.secondary_back = secondary_back ; - } - - public int getBackhrs() - { - return backhrs; - } - - public void setBackhrs(int backhrs) - { - this.backhrs = backhrs ; - } - - public int getForwardhrs() - { - return forwardhrs; - } - - public void setForwardhrs(int forwardhrs) - { - this.forwardhrs = forwardhrs ; - } - - public double getAdjustendhrs() - { - return adjustendhrs; - } - - public void setAdjustendhrs(double adjustendhrs) - { - this.adjustendhrs = adjustendhrs ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getGroup_id() + " " + - getOrdinal() + " " + - getChg_threshold() + " " + - getRec_type() + " " + - getPrimary_back() + " " + - getSecondary_back() + " " + - getBackhrs() + " " + - getForwardhrs() + " " + - getAdjustendhrs() + " " + - "" ; - return outString; - } // end toString() -} // end of RpfFcstPointRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstPointTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstPointTable.java deleted file mode 100644 index c4ead24f2f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfFcstPointTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: RpfFcstPointTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rpffcstpoint table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RpfFcstPointTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RpfFcstPointTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RpfFcstPointTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rpffcstpoint"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RpfFcstPointRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RpfFcstPointRecord record = null; - - // create a List to hold RpfFcstPoint Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rpffcstpoint " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RpfFcstPointRecord - // and store its address in oneRecord - record = new RpfFcstPointRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RpfFcstPointRecord object - - record.setLid(getString(rs, 1)); - record.setGroup_id(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - record.setChg_threshold(getDouble(rs, 4)); - record.setRec_type(getString(rs, 5)); - record.setPrimary_back(getString(rs, 6)); - record.setSecondary_back(getString(rs, 7)); - record.setBackhrs(getInt(rs, 8)); - record.setForwardhrs(getInt(rs, 9)); - record.setAdjustendhrs(getDouble(rs, 10)); - - // add this RpfFcstPointRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RpfFcstPointRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RpfFcstPointRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RpfFcstPointRecord record = null; - - // create a List to hold RpfFcstPoint Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rpffcstpoint " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RpfFcstPointRecord - // and store its address in oneRecord - record = new RpfFcstPointRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RpfFcstPointRecord object - - record.setLid(getString(rs, 1)); - record.setGroup_id(getString(rs, 2)); - record.setOrdinal(getInt(rs, 3)); - record.setChg_threshold(getDouble(rs, 4)); - record.setRec_type(getString(rs, 5)); - record.setPrimary_back(getString(rs, 6)); - record.setSecondary_back(getString(rs, 7)); - record.setBackhrs(getInt(rs, 8)); - record.setForwardhrs(getInt(rs, 9)); - record.setAdjustendhrs(getDouble(rs, 10)); - - // add this RpfFcstPointRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RpfFcstPointRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RpfFcstPointRecord object and.. -//----------------------------------------------------------------- - public int insert(RpfFcstPointRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rpffcstpoint VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getGroup_id()); - setInt(insertStatement, 3, record.getOrdinal()); - setDouble(insertStatement, 4, record.getChg_threshold()); - setString(insertStatement, 5, record.getRec_type()); - setString(insertStatement, 6, record.getPrimary_back()); - setString(insertStatement, 7, record.getSecondary_back()); - setInt(insertStatement, 8, record.getBackhrs()); - setInt(insertStatement, 9, record.getForwardhrs()); - setDouble(insertStatement, 10, record.getAdjustendhrs()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rpffcstpoint " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RpfFcstPointRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RpfFcstPointRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rpffcstpoint SET lid = ?, group_id = ?, ordinal = ?, chg_threshold = ?, rec_type = ?, primary_back = ?, secondary_back = ?, backhrs = ?, forwardhrs = ?, adjustendhrs = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getGroup_id()); - setInt(updateStatement, 3, record.getOrdinal()); - setDouble(updateStatement, 4, record.getChg_threshold()); - setString(updateStatement, 5, record.getRec_type()); - setString(updateStatement, 6, record.getPrimary_back()); - setString(updateStatement, 7, record.getSecondary_back()); - setInt(updateStatement, 8, record.getBackhrs()); - setInt(updateStatement, 9, record.getForwardhrs()); - setDouble(updateStatement, 10, record.getAdjustendhrs()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(RpfFcstPointRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rpffcstpoint " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RpfFcstPointRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RpfFcstPointRecord oldRecord, RpfFcstPointRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rpffcstpoint SET lid = ?, group_id = ?, ordinal = ?, chg_threshold = ?, rec_type = ?, primary_back = ?, secondary_back = ?, backhrs = ?, forwardhrs = ?, adjustendhrs = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getGroup_id()); - setInt(updateStatement, 3, newRecord.getOrdinal()); - setDouble(updateStatement, 4, newRecord.getChg_threshold()); - setString(updateStatement, 5, newRecord.getRec_type()); - setString(updateStatement, 6, newRecord.getPrimary_back()); - setString(updateStatement, 7, newRecord.getSecondary_back()); - setInt(updateStatement, 8, newRecord.getBackhrs()); - setInt(updateStatement, 9, newRecord.getForwardhrs()); - setDouble(updateStatement, 10, newRecord.getAdjustendhrs()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RpfFcstPointRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(RpfFcstPointRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RpfFcstPointRecord oldRecord = (RpfFcstPointRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of RpfFcstPointTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfParamsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfParamsRecord.java deleted file mode 100644 index a7fdb2d78b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfParamsRecord.java +++ /dev/null @@ -1,155 +0,0 @@ -// filename: RpfParamsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// RpfParams table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class RpfParamsRecord extends DbRecord -{ - private int obshrs; - - private int fcsthrs; - - private String missval; - - private String misscat; - - private String misstim; - - private int rvsexphrs; - - private int flsexphrs; - - private int flwexphrs; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public RpfParamsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RpfParamsRecord(RpfParamsRecord origRecord) - { - setObshrs(origRecord.getObshrs()); - setFcsthrs(origRecord.getFcsthrs()); - setMissval(origRecord.getMissval()); - setMisscat(origRecord.getMisscat()); - setMisstim(origRecord.getMisstim()); - setRvsexphrs(origRecord.getRvsexphrs()); - setFlsexphrs(origRecord.getFlsexphrs()); - setFlwexphrs(origRecord.getFlwexphrs()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a RpfParams record - - //----------------------------------------------------------------- - public int getObshrs() - { - return obshrs; - } - - public void setObshrs(int obshrs) - { - this.obshrs = obshrs ; - } - - public int getFcsthrs() - { - return fcsthrs; - } - - public void setFcsthrs(int fcsthrs) - { - this.fcsthrs = fcsthrs ; - } - - public String getMissval() - { - return missval; - } - - public void setMissval(String missval) - { - this.missval = missval ; - } - - public String getMisscat() - { - return misscat; - } - - public void setMisscat(String misscat) - { - this.misscat = misscat ; - } - - public String getMisstim() - { - return misstim; - } - - public void setMisstim(String misstim) - { - this.misstim = misstim ; - } - - public int getRvsexphrs() - { - return rvsexphrs; - } - - public void setRvsexphrs(int rvsexphrs) - { - this.rvsexphrs = rvsexphrs ; - } - - public int getFlsexphrs() - { - return flsexphrs; - } - - public void setFlsexphrs(int flsexphrs) - { - this.flsexphrs = flsexphrs ; - } - - public int getFlwexphrs() - { - return flwexphrs; - } - - public void setFlwexphrs(int flwexphrs) - { - this.flwexphrs = flwexphrs ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getObshrs() + " " + - getFcsthrs() + " " + - getMissval() + " " + - getMisscat() + " " + - getMisstim() + " " + - getRvsexphrs() + " " + - getFlsexphrs() + " " + - getFlwexphrs() + " " + - "" ; - return outString; - } // end toString() -} // end of RpfParamsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfParamsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfParamsTable.java deleted file mode 100644 index 8898f04e0b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/RpfParamsTable.java +++ /dev/null @@ -1,217 +0,0 @@ -// filename: RpfParamsTable.java -// author : DBGEN -// created : Tue May 31 17:52:27 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// rpfparams table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class RpfParamsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// RpfParamsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public RpfParamsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rpfparams"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of RpfParamsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - RpfParamsRecord record = null; - - // create a List to hold RpfParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rpfparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RpfParamsRecord - // and store its address in oneRecord - record = new RpfParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RpfParamsRecord object - - record.setObshrs(getInt(rs, 1)); - record.setFcsthrs(getInt(rs, 2)); - record.setMissval(getString(rs, 3)); - record.setMisscat(getString(rs, 4)); - record.setMisstim(getString(rs, 5)); - record.setRvsexphrs(getInt(rs, 6)); - record.setFlsexphrs(getInt(rs, 7)); - record.setFlwexphrs(getInt(rs, 8)); - - // add this RpfParamsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the RpfParamsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of RpfParamsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - RpfParamsRecord record = null; - - // create a List to hold RpfParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM rpfparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a RpfParamsRecord - // and store its address in oneRecord - record = new RpfParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a RpfParamsRecord object - - record.setObshrs(getInt(rs, 1)); - record.setFcsthrs(getInt(rs, 2)); - record.setMissval(getString(rs, 3)); - record.setMisscat(getString(rs, 4)); - record.setMisstim(getString(rs, 5)); - record.setRvsexphrs(getInt(rs, 6)); - record.setFlsexphrs(getInt(rs, 7)); - record.setFlwexphrs(getInt(rs, 8)); - - // add this RpfParamsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the RpfParamsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a RpfParamsRecord object and.. -//----------------------------------------------------------------- - public int insert(RpfParamsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO rpfparams VALUES (?, ?, ?, ?, ?, ?, ?, ? )"); - - setInt(insertStatement, 1, record.getObshrs()); - setInt(insertStatement, 2, record.getFcsthrs()); - setString(insertStatement, 3, record.getMissval()); - setString(insertStatement, 4, record.getMisscat()); - setString(insertStatement, 5, record.getMisstim()); - setInt(insertStatement, 6, record.getRvsexphrs()); - setInt(insertStatement, 7, record.getFlsexphrs()); - setInt(insertStatement, 8, record.getFlwexphrs()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM rpfparams " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a RpfParamsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(RpfParamsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE rpfparams SET obshrs = ?, fcsthrs = ?, missval = ?, misscat = ?, misstim = ?, rvsexphrs = ?, flsexphrs = ?, flwexphrs = ? " + where ); - - setInt(updateStatement, 1, record.getObshrs()); - setInt(updateStatement, 2, record.getFcsthrs()); - setString(updateStatement, 3, record.getMissval()); - setString(updateStatement, 4, record.getMisscat()); - setString(updateStatement, 5, record.getMisstim()); - setInt(updateStatement, 6, record.getRvsexphrs()); - setInt(updateStatement, 7, record.getFlsexphrs()); - setInt(updateStatement, 8, record.getFlwexphrs()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -} // end of RpfParamsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalParamsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalParamsRecord.java deleted file mode 100644 index 6d8f9d5aa8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalParamsRecord.java +++ /dev/null @@ -1,113 +0,0 @@ -// filename: S3PostAnalParamsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// S3PostAnalParams table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class S3PostAnalParamsRecord extends DbRecord -{ - private short gg_weighting; - - private float gg_min_gage_val; - - private short gg_min_dist; - - private float kernel_est_scale; - - private float rhat; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public S3PostAnalParamsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public S3PostAnalParamsRecord(S3PostAnalParamsRecord origRecord) - { - setGg_weighting(origRecord.getGg_weighting()); - setGg_min_gage_val(origRecord.getGg_min_gage_val()); - setGg_min_dist(origRecord.getGg_min_dist()); - setKernel_est_scale(origRecord.getKernel_est_scale()); - setRhat(origRecord.getRhat()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a S3PostAnalParams record - - //----------------------------------------------------------------- - public short getGg_weighting() - { - return gg_weighting; - } - - public void setGg_weighting(short gg_weighting) - { - this.gg_weighting = gg_weighting ; - } - - public float getGg_min_gage_val() - { - return gg_min_gage_val; - } - - public void setGg_min_gage_val(float gg_min_gage_val) - { - this.gg_min_gage_val = gg_min_gage_val ; - } - - public short getGg_min_dist() - { - return gg_min_dist; - } - - public void setGg_min_dist(short gg_min_dist) - { - this.gg_min_dist = gg_min_dist ; - } - - public float getKernel_est_scale() - { - return kernel_est_scale; - } - - public void setKernel_est_scale(float kernel_est_scale) - { - this.kernel_est_scale = kernel_est_scale ; - } - - public float getRhat() - { - return rhat; - } - - public void setRhat(float rhat) - { - this.rhat = rhat ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getGg_weighting() + " " + - getGg_min_gage_val() + " " + - getGg_min_dist() + " " + - getKernel_est_scale() + " " + - getRhat() + " " + - "" ; - return outString; - } // end toString() -} // end of S3PostAnalParamsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalParamsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalParamsTable.java deleted file mode 100644 index 041f800c12..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalParamsTable.java +++ /dev/null @@ -1,205 +0,0 @@ -// filename: S3PostAnalParamsTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// s3postanalparams table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class S3PostAnalParamsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// S3PostAnalParamsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public S3PostAnalParamsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("s3postanalparams"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of S3PostAnalParamsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - S3PostAnalParamsRecord record = null; - - // create a List to hold S3PostAnalParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM s3postanalparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a S3PostAnalParamsRecord - // and store its address in oneRecord - record = new S3PostAnalParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a S3PostAnalParamsRecord object - - record.setGg_weighting(getShort(rs, 1)); - record.setGg_min_gage_val(getReal(rs, 2)); - record.setGg_min_dist(getShort(rs, 3)); - record.setKernel_est_scale(getReal(rs, 4)); - record.setRhat(getReal(rs, 5)); - - // add this S3PostAnalParamsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the S3PostAnalParamsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of S3PostAnalParamsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - S3PostAnalParamsRecord record = null; - - // create a List to hold S3PostAnalParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM s3postanalparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a S3PostAnalParamsRecord - // and store its address in oneRecord - record = new S3PostAnalParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a S3PostAnalParamsRecord object - - record.setGg_weighting(getShort(rs, 1)); - record.setGg_min_gage_val(getReal(rs, 2)); - record.setGg_min_dist(getShort(rs, 3)); - record.setKernel_est_scale(getReal(rs, 4)); - record.setRhat(getReal(rs, 5)); - - // add this S3PostAnalParamsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the S3PostAnalParamsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a S3PostAnalParamsRecord object and.. -//----------------------------------------------------------------- - public int insert(S3PostAnalParamsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO s3postanalparams VALUES (?, ?, ?, ?, ? )"); - - setShort(insertStatement, 1, record.getGg_weighting()); - setReal(insertStatement, 2, record.getGg_min_gage_val()); - setShort(insertStatement, 3, record.getGg_min_dist()); - setReal(insertStatement, 4, record.getKernel_est_scale()); - setReal(insertStatement, 5, record.getRhat()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM s3postanalparams " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a S3PostAnalParamsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(S3PostAnalParamsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE s3postanalparams SET gg_weighting = ?, gg_min_gage_val = ?, gg_min_dist = ?, kernel_est_scale = ?, rhat = ? " + where ); - - setShort(updateStatement, 1, record.getGg_weighting()); - setReal(updateStatement, 2, record.getGg_min_gage_val()); - setShort(updateStatement, 3, record.getGg_min_dist()); - setReal(updateStatement, 4, record.getKernel_est_scale()); - setReal(updateStatement, 5, record.getRhat()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -} // end of S3PostAnalParamsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalPrefsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalPrefsRecord.java deleted file mode 100644 index 6e76320d69..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalPrefsRecord.java +++ /dev/null @@ -1,153 +0,0 @@ -// filename: S3PostAnalPrefsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// S3PostAnalPrefs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class S3PostAnalPrefsRecord extends DbRecord -{ - private String userid; - - private String state_overlay; - - private String city_overlay; - - private String river_overlay; - - private String basin_overlay; - - private String radar_overlay; - - private short num_hours_wind; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public S3PostAnalPrefsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public S3PostAnalPrefsRecord(S3PostAnalPrefsRecord origRecord) - { - setUserid(origRecord.getUserid()); - setState_overlay(origRecord.getState_overlay()); - setCity_overlay(origRecord.getCity_overlay()); - setRiver_overlay(origRecord.getRiver_overlay()); - setBasin_overlay(origRecord.getBasin_overlay()); - setRadar_overlay(origRecord.getRadar_overlay()); - setNum_hours_wind(origRecord.getNum_hours_wind()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a S3PostAnalPrefs record - - //----------------------------------------------------------------- - public String getUserid() - { - return userid; - } - - public void setUserid(String userid) - { - this.userid = userid ; - } - - public String getState_overlay() - { - return state_overlay; - } - - public void setState_overlay(String state_overlay) - { - this.state_overlay = state_overlay ; - } - - public String getCity_overlay() - { - return city_overlay; - } - - public void setCity_overlay(String city_overlay) - { - this.city_overlay = city_overlay ; - } - - public String getRiver_overlay() - { - return river_overlay; - } - - public void setRiver_overlay(String river_overlay) - { - this.river_overlay = river_overlay ; - } - - public String getBasin_overlay() - { - return basin_overlay; - } - - public void setBasin_overlay(String basin_overlay) - { - this.basin_overlay = basin_overlay ; - } - - public String getRadar_overlay() - { - return radar_overlay; - } - - public void setRadar_overlay(String radar_overlay) - { - this.radar_overlay = radar_overlay ; - } - - public short getNum_hours_wind() - { - return num_hours_wind; - } - - public void setNum_hours_wind(short num_hours_wind) - { - this.num_hours_wind = num_hours_wind ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE userid = '" + userid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getUserid() + " " + - getState_overlay() + " " + - getCity_overlay() + " " + - getRiver_overlay() + " " + - getBasin_overlay() + " " + - getRadar_overlay() + " " + - getNum_hours_wind() + " " + - "" ; - return outString; - } // end toString() -} // end of S3PostAnalPrefsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalPrefsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalPrefsTable.java deleted file mode 100644 index 1a981cb7a4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/S3PostAnalPrefsTable.java +++ /dev/null @@ -1,276 +0,0 @@ -// filename: S3PostAnalPrefsTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// s3postanalprefs table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class S3PostAnalPrefsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// S3PostAnalPrefsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public S3PostAnalPrefsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("s3postanalprefs"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of S3PostAnalPrefsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - S3PostAnalPrefsRecord record = null; - - // create a List to hold S3PostAnalPrefs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM s3postanalprefs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a S3PostAnalPrefsRecord - // and store its address in oneRecord - record = new S3PostAnalPrefsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a S3PostAnalPrefsRecord object - - record.setUserid(getString(rs, 1)); - record.setState_overlay(getString(rs, 2)); - record.setCity_overlay(getString(rs, 3)); - record.setRiver_overlay(getString(rs, 4)); - record.setBasin_overlay(getString(rs, 5)); - record.setRadar_overlay(getString(rs, 6)); - record.setNum_hours_wind(getShort(rs, 7)); - - // add this S3PostAnalPrefsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the S3PostAnalPrefsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of S3PostAnalPrefsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - S3PostAnalPrefsRecord record = null; - - // create a List to hold S3PostAnalPrefs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM s3postanalprefs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a S3PostAnalPrefsRecord - // and store its address in oneRecord - record = new S3PostAnalPrefsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a S3PostAnalPrefsRecord object - - record.setUserid(getString(rs, 1)); - record.setState_overlay(getString(rs, 2)); - record.setCity_overlay(getString(rs, 3)); - record.setRiver_overlay(getString(rs, 4)); - record.setBasin_overlay(getString(rs, 5)); - record.setRadar_overlay(getString(rs, 6)); - record.setNum_hours_wind(getShort(rs, 7)); - - // add this S3PostAnalPrefsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the S3PostAnalPrefsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a S3PostAnalPrefsRecord object and.. -//----------------------------------------------------------------- - public int insert(S3PostAnalPrefsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO s3postanalprefs VALUES (?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getUserid()); - setString(insertStatement, 2, record.getState_overlay()); - setString(insertStatement, 3, record.getCity_overlay()); - setString(insertStatement, 4, record.getRiver_overlay()); - setString(insertStatement, 5, record.getBasin_overlay()); - setString(insertStatement, 6, record.getRadar_overlay()); - setShort(insertStatement, 7, record.getNum_hours_wind()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM s3postanalprefs " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a S3PostAnalPrefsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(S3PostAnalPrefsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE s3postanalprefs SET userid = ?, state_overlay = ?, city_overlay = ?, river_overlay = ?, basin_overlay = ?, radar_overlay = ?, num_hours_wind = ? " + where ); - - setString(updateStatement, 1, record.getUserid()); - setString(updateStatement, 2, record.getState_overlay()); - setString(updateStatement, 3, record.getCity_overlay()); - setString(updateStatement, 4, record.getRiver_overlay()); - setString(updateStatement, 5, record.getBasin_overlay()); - setString(updateStatement, 6, record.getRadar_overlay()); - setShort(updateStatement, 7, record.getNum_hours_wind()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(S3PostAnalPrefsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM s3postanalprefs " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a S3PostAnalPrefsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(S3PostAnalPrefsRecord oldRecord, S3PostAnalPrefsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE s3postanalprefs SET userid = ?, state_overlay = ?, city_overlay = ?, river_overlay = ?, basin_overlay = ?, radar_overlay = ?, num_hours_wind = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getUserid()); - setString(updateStatement, 2, newRecord.getState_overlay()); - setString(updateStatement, 3, newRecord.getCity_overlay()); - setString(updateStatement, 4, newRecord.getRiver_overlay()); - setString(updateStatement, 5, newRecord.getBasin_overlay()); - setString(updateStatement, 6, newRecord.getRadar_overlay()); - setShort(updateStatement, 7, newRecord.getNum_hours_wind()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a S3PostAnalPrefsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(S3PostAnalPrefsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - S3PostAnalPrefsRecord oldRecord = (S3PostAnalPrefsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of S3PostAnalPrefsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaParamsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaParamsRecord.java deleted file mode 100644 index 8f97c29e05..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaParamsRecord.java +++ /dev/null @@ -1,379 +0,0 @@ -// filename: SacSmaParamsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// SacSmaParams table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class SacSmaParamsRecord extends DbRecord -{ - private String basin_id; - - private String source; - - private long validtime; - - private long postingtime; - - private double uztwm; - - private double uzfwm; - - private double uzk; - - private double pctim; - - private double adimp; - - private double riva; - - private double zperc; - - private double rexp; - - private double lztwm; - - private double lzfsm; - - private double lzfpm; - - private double lzsk; - - private double lzpk; - - private double pfree; - - private double rserv; - - private double side; - - private double peadj; - - private double pxadj; - - private double efc; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public SacSmaParamsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public SacSmaParamsRecord(SacSmaParamsRecord origRecord) - { - setBasin_id(origRecord.getBasin_id()); - setSource(origRecord.getSource()); - setValidtime(origRecord.getValidtime()); - setPostingtime(origRecord.getPostingtime()); - setUztwm(origRecord.getUztwm()); - setUzfwm(origRecord.getUzfwm()); - setUzk(origRecord.getUzk()); - setPctim(origRecord.getPctim()); - setAdimp(origRecord.getAdimp()); - setRiva(origRecord.getRiva()); - setZperc(origRecord.getZperc()); - setRexp(origRecord.getRexp()); - setLztwm(origRecord.getLztwm()); - setLzfsm(origRecord.getLzfsm()); - setLzfpm(origRecord.getLzfpm()); - setLzsk(origRecord.getLzsk()); - setLzpk(origRecord.getLzpk()); - setPfree(origRecord.getPfree()); - setRserv(origRecord.getRserv()); - setSide(origRecord.getSide()); - setPeadj(origRecord.getPeadj()); - setPxadj(origRecord.getPxadj()); - setEfc(origRecord.getEfc()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a SacSmaParams record - - //----------------------------------------------------------------- - public String getBasin_id() - { - return basin_id; - } - - public void setBasin_id(String basin_id) - { - this.basin_id = basin_id ; - } - - public String getSource() - { - return source; - } - - public void setSource(String source) - { - this.source = source ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public double getUztwm() - { - return uztwm; - } - - public void setUztwm(double uztwm) - { - this.uztwm = uztwm ; - } - - public double getUzfwm() - { - return uzfwm; - } - - public void setUzfwm(double uzfwm) - { - this.uzfwm = uzfwm ; - } - - public double getUzk() - { - return uzk; - } - - public void setUzk(double uzk) - { - this.uzk = uzk ; - } - - public double getPctim() - { - return pctim; - } - - public void setPctim(double pctim) - { - this.pctim = pctim ; - } - - public double getAdimp() - { - return adimp; - } - - public void setAdimp(double adimp) - { - this.adimp = adimp ; - } - - public double getRiva() - { - return riva; - } - - public void setRiva(double riva) - { - this.riva = riva ; - } - - public double getZperc() - { - return zperc; - } - - public void setZperc(double zperc) - { - this.zperc = zperc ; - } - - public double getRexp() - { - return rexp; - } - - public void setRexp(double rexp) - { - this.rexp = rexp ; - } - - public double getLztwm() - { - return lztwm; - } - - public void setLztwm(double lztwm) - { - this.lztwm = lztwm ; - } - - public double getLzfsm() - { - return lzfsm; - } - - public void setLzfsm(double lzfsm) - { - this.lzfsm = lzfsm ; - } - - public double getLzfpm() - { - return lzfpm; - } - - public void setLzfpm(double lzfpm) - { - this.lzfpm = lzfpm ; - } - - public double getLzsk() - { - return lzsk; - } - - public void setLzsk(double lzsk) - { - this.lzsk = lzsk ; - } - - public double getLzpk() - { - return lzpk; - } - - public void setLzpk(double lzpk) - { - this.lzpk = lzpk ; - } - - public double getPfree() - { - return pfree; - } - - public void setPfree(double pfree) - { - this.pfree = pfree ; - } - - public double getRserv() - { - return rserv; - } - - public void setRserv(double rserv) - { - this.rserv = rserv ; - } - - public double getSide() - { - return side; - } - - public void setSide(double side) - { - this.side = side ; - } - - public double getPeadj() - { - return peadj; - } - - public void setPeadj(double peadj) - { - this.peadj = peadj ; - } - - public double getPxadj() - { - return pxadj; - } - - public void setPxadj(double pxadj) - { - this.pxadj = pxadj ; - } - - public double getEfc() - { - return efc; - } - - public void setEfc(double efc) - { - this.efc = efc ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE basin_id = '" + basin_id + "'" - + " AND source = '" + source + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getBasin_id() + " " + - getSource() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getUztwm() + " " + - getUzfwm() + " " + - getUzk() + " " + - getPctim() + " " + - getAdimp() + " " + - getRiva() + " " + - getZperc() + " " + - getRexp() + " " + - getLztwm() + " " + - getLzfsm() + " " + - getLzfpm() + " " + - getLzsk() + " " + - getLzpk() + " " + - getPfree() + " " + - getRserv() + " " + - getSide() + " " + - getPeadj() + " " + - getPxadj() + " " + - getEfc() + " " + - "" ; - return outString; - } // end toString() -} // end of SacSmaParamsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaParamsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaParamsTable.java deleted file mode 100644 index e084cc8aeb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaParamsTable.java +++ /dev/null @@ -1,356 +0,0 @@ -// filename: SacSmaParamsTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// sacsmaparams table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class SacSmaParamsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// SacSmaParamsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public SacSmaParamsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("sacsmaparams"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of SacSmaParamsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - SacSmaParamsRecord record = null; - - // create a List to hold SacSmaParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM sacsmaparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SacSmaParamsRecord - // and store its address in oneRecord - record = new SacSmaParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SacSmaParamsRecord object - - record.setBasin_id(getString(rs, 1)); - record.setSource(getString(rs, 2)); - record.setValidtime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - record.setUztwm(getDouble(rs, 5)); - record.setUzfwm(getDouble(rs, 6)); - record.setUzk(getDouble(rs, 7)); - record.setPctim(getDouble(rs, 8)); - record.setAdimp(getDouble(rs, 9)); - record.setRiva(getDouble(rs, 10)); - record.setZperc(getDouble(rs, 11)); - record.setRexp(getDouble(rs, 12)); - record.setLztwm(getDouble(rs, 13)); - record.setLzfsm(getDouble(rs, 14)); - record.setLzfpm(getDouble(rs, 15)); - record.setLzsk(getDouble(rs, 16)); - record.setLzpk(getDouble(rs, 17)); - record.setPfree(getDouble(rs, 18)); - record.setRserv(getDouble(rs, 19)); - record.setSide(getDouble(rs, 20)); - record.setPeadj(getDouble(rs, 21)); - record.setPxadj(getDouble(rs, 22)); - record.setEfc(getDouble(rs, 23)); - - // add this SacSmaParamsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the SacSmaParamsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of SacSmaParamsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - SacSmaParamsRecord record = null; - - // create a List to hold SacSmaParams Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM sacsmaparams " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SacSmaParamsRecord - // and store its address in oneRecord - record = new SacSmaParamsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SacSmaParamsRecord object - - record.setBasin_id(getString(rs, 1)); - record.setSource(getString(rs, 2)); - record.setValidtime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - record.setUztwm(getDouble(rs, 5)); - record.setUzfwm(getDouble(rs, 6)); - record.setUzk(getDouble(rs, 7)); - record.setPctim(getDouble(rs, 8)); - record.setAdimp(getDouble(rs, 9)); - record.setRiva(getDouble(rs, 10)); - record.setZperc(getDouble(rs, 11)); - record.setRexp(getDouble(rs, 12)); - record.setLztwm(getDouble(rs, 13)); - record.setLzfsm(getDouble(rs, 14)); - record.setLzfpm(getDouble(rs, 15)); - record.setLzsk(getDouble(rs, 16)); - record.setLzpk(getDouble(rs, 17)); - record.setPfree(getDouble(rs, 18)); - record.setRserv(getDouble(rs, 19)); - record.setSide(getDouble(rs, 20)); - record.setPeadj(getDouble(rs, 21)); - record.setPxadj(getDouble(rs, 22)); - record.setEfc(getDouble(rs, 23)); - - // add this SacSmaParamsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the SacSmaParamsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a SacSmaParamsRecord object and.. -//----------------------------------------------------------------- - public int insert(SacSmaParamsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO sacsmaparams VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getBasin_id()); - setString(insertStatement, 2, record.getSource()); - setTimeStamp(insertStatement, 3, record.getValidtime()); - setTimeStamp(insertStatement, 4, record.getPostingtime()); - setDouble(insertStatement, 5, record.getUztwm()); - setDouble(insertStatement, 6, record.getUzfwm()); - setDouble(insertStatement, 7, record.getUzk()); - setDouble(insertStatement, 8, record.getPctim()); - setDouble(insertStatement, 9, record.getAdimp()); - setDouble(insertStatement, 10, record.getRiva()); - setDouble(insertStatement, 11, record.getZperc()); - setDouble(insertStatement, 12, record.getRexp()); - setDouble(insertStatement, 13, record.getLztwm()); - setDouble(insertStatement, 14, record.getLzfsm()); - setDouble(insertStatement, 15, record.getLzfpm()); - setDouble(insertStatement, 16, record.getLzsk()); - setDouble(insertStatement, 17, record.getLzpk()); - setDouble(insertStatement, 18, record.getPfree()); - setDouble(insertStatement, 19, record.getRserv()); - setDouble(insertStatement, 20, record.getSide()); - setDouble(insertStatement, 21, record.getPeadj()); - setDouble(insertStatement, 22, record.getPxadj()); - setDouble(insertStatement, 23, record.getEfc()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM sacsmaparams " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SacSmaParamsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SacSmaParamsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE sacsmaparams SET basin_id = ?, source = ?, validtime = ?, postingtime = ?, uztwm = ?, uzfwm = ?, uzk = ?, pctim = ?, adimp = ?, riva = ?, zperc = ?, rexp = ?, lztwm = ?, lzfsm = ?, lzfpm = ?, lzsk = ?, lzpk = ?, pfree = ?, rserv = ?, side = ?, peadj = ?, pxadj = ?, efc = ? " + where ); - - setString(updateStatement, 1, record.getBasin_id()); - setString(updateStatement, 2, record.getSource()); - setTimeStamp(updateStatement, 3, record.getValidtime()); - setTimeStamp(updateStatement, 4, record.getPostingtime()); - setDouble(updateStatement, 5, record.getUztwm()); - setDouble(updateStatement, 6, record.getUzfwm()); - setDouble(updateStatement, 7, record.getUzk()); - setDouble(updateStatement, 8, record.getPctim()); - setDouble(updateStatement, 9, record.getAdimp()); - setDouble(updateStatement, 10, record.getRiva()); - setDouble(updateStatement, 11, record.getZperc()); - setDouble(updateStatement, 12, record.getRexp()); - setDouble(updateStatement, 13, record.getLztwm()); - setDouble(updateStatement, 14, record.getLzfsm()); - setDouble(updateStatement, 15, record.getLzfpm()); - setDouble(updateStatement, 16, record.getLzsk()); - setDouble(updateStatement, 17, record.getLzpk()); - setDouble(updateStatement, 18, record.getPfree()); - setDouble(updateStatement, 19, record.getRserv()); - setDouble(updateStatement, 20, record.getSide()); - setDouble(updateStatement, 21, record.getPeadj()); - setDouble(updateStatement, 22, record.getPxadj()); - setDouble(updateStatement, 23, record.getEfc()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(SacSmaParamsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM sacsmaparams " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SacSmaParamsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SacSmaParamsRecord oldRecord, SacSmaParamsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE sacsmaparams SET basin_id = ?, source = ?, validtime = ?, postingtime = ?, uztwm = ?, uzfwm = ?, uzk = ?, pctim = ?, adimp = ?, riva = ?, zperc = ?, rexp = ?, lztwm = ?, lzfsm = ?, lzfpm = ?, lzsk = ?, lzpk = ?, pfree = ?, rserv = ?, side = ?, peadj = ?, pxadj = ?, efc = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getBasin_id()); - setString(updateStatement, 2, newRecord.getSource()); - setTimeStamp(updateStatement, 3, newRecord.getValidtime()); - setTimeStamp(updateStatement, 4, newRecord.getPostingtime()); - setDouble(updateStatement, 5, newRecord.getUztwm()); - setDouble(updateStatement, 6, newRecord.getUzfwm()); - setDouble(updateStatement, 7, newRecord.getUzk()); - setDouble(updateStatement, 8, newRecord.getPctim()); - setDouble(updateStatement, 9, newRecord.getAdimp()); - setDouble(updateStatement, 10, newRecord.getRiva()); - setDouble(updateStatement, 11, newRecord.getZperc()); - setDouble(updateStatement, 12, newRecord.getRexp()); - setDouble(updateStatement, 13, newRecord.getLztwm()); - setDouble(updateStatement, 14, newRecord.getLzfsm()); - setDouble(updateStatement, 15, newRecord.getLzfpm()); - setDouble(updateStatement, 16, newRecord.getLzsk()); - setDouble(updateStatement, 17, newRecord.getLzpk()); - setDouble(updateStatement, 18, newRecord.getPfree()); - setDouble(updateStatement, 19, newRecord.getRserv()); - setDouble(updateStatement, 20, newRecord.getSide()); - setDouble(updateStatement, 21, newRecord.getPeadj()); - setDouble(updateStatement, 22, newRecord.getPxadj()); - setDouble(updateStatement, 23, newRecord.getEfc()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a SacSmaParamsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(SacSmaParamsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - SacSmaParamsRecord oldRecord = (SacSmaParamsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of SacSmaParamsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaStateRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaStateRecord.java deleted file mode 100644 index 1d9773abca..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaStateRecord.java +++ /dev/null @@ -1,211 +0,0 @@ -// filename: SacSmaStateRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// SacSmaState table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class SacSmaStateRecord extends DbRecord -{ - private String basin_id; - - private String source; - - private long validtime; - - private long basistime; - - private long postingtime; - - private double uztwc; - - private double uzfwc; - - private double lztwc; - - private double lzfsc; - - private double lzfpc; - - private double adimc; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public SacSmaStateRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public SacSmaStateRecord(SacSmaStateRecord origRecord) - { - setBasin_id(origRecord.getBasin_id()); - setSource(origRecord.getSource()); - setValidtime(origRecord.getValidtime()); - setBasistime(origRecord.getBasistime()); - setPostingtime(origRecord.getPostingtime()); - setUztwc(origRecord.getUztwc()); - setUzfwc(origRecord.getUzfwc()); - setLztwc(origRecord.getLztwc()); - setLzfsc(origRecord.getLzfsc()); - setLzfpc(origRecord.getLzfpc()); - setAdimc(origRecord.getAdimc()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a SacSmaState record - - //----------------------------------------------------------------- - public String getBasin_id() - { - return basin_id; - } - - public void setBasin_id(String basin_id) - { - this.basin_id = basin_id ; - } - - public String getSource() - { - return source; - } - - public void setSource(String source) - { - this.source = source ; - } - - public long getValidtime() - { - return validtime; - } - - public void setValidtime(long validtime) - { - this.validtime = validtime ; - } - - public long getBasistime() - { - return basistime; - } - - public void setBasistime(long basistime) - { - this.basistime = basistime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public double getUztwc() - { - return uztwc; - } - - public void setUztwc(double uztwc) - { - this.uztwc = uztwc ; - } - - public double getUzfwc() - { - return uzfwc; - } - - public void setUzfwc(double uzfwc) - { - this.uzfwc = uzfwc ; - } - - public double getLztwc() - { - return lztwc; - } - - public void setLztwc(double lztwc) - { - this.lztwc = lztwc ; - } - - public double getLzfsc() - { - return lzfsc; - } - - public void setLzfsc(double lzfsc) - { - this.lzfsc = lzfsc ; - } - - public double getLzfpc() - { - return lzfpc; - } - - public void setLzfpc(double lzfpc) - { - this.lzfpc = lzfpc ; - } - - public double getAdimc() - { - return adimc; - } - - public void setAdimc(double adimc) - { - this.adimc = adimc ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE basin_id = '" + basin_id + "'" - + " AND source = '" + source + "'" - + " AND validtime = '" + getDateTimeStringFromLongTime(validtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getBasin_id() + " " + - getSource() + " " + - getDateTimeStringFromLongTime(getValidtime()) + " " + - getDateTimeStringFromLongTime(getBasistime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getUztwc() + " " + - getUzfwc() + " " + - getLztwc() + " " + - getLzfsc() + " " + - getLzfpc() + " " + - getAdimc() + " " + - "" ; - return outString; - } // end toString() -} // end of SacSmaStateRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaStateTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaStateTable.java deleted file mode 100644 index 2c3e775b03..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SacSmaStateTable.java +++ /dev/null @@ -1,296 +0,0 @@ -// filename: SacSmaStateTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// sacsmastate table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class SacSmaStateTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// SacSmaStateTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public SacSmaStateTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("sacsmastate"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of SacSmaStateRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - SacSmaStateRecord record = null; - - // create a List to hold SacSmaState Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM sacsmastate " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SacSmaStateRecord - // and store its address in oneRecord - record = new SacSmaStateRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SacSmaStateRecord object - - record.setBasin_id(getString(rs, 1)); - record.setSource(getString(rs, 2)); - record.setValidtime(getTimeStamp(rs, 3)); - record.setBasistime(getTimeStamp(rs, 4)); - record.setPostingtime(getTimeStamp(rs, 5)); - record.setUztwc(getDouble(rs, 6)); - record.setUzfwc(getDouble(rs, 7)); - record.setLztwc(getDouble(rs, 8)); - record.setLzfsc(getDouble(rs, 9)); - record.setLzfpc(getDouble(rs, 10)); - record.setAdimc(getDouble(rs, 11)); - - // add this SacSmaStateRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the SacSmaStateRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of SacSmaStateRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - SacSmaStateRecord record = null; - - // create a List to hold SacSmaState Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM sacsmastate " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SacSmaStateRecord - // and store its address in oneRecord - record = new SacSmaStateRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SacSmaStateRecord object - - record.setBasin_id(getString(rs, 1)); - record.setSource(getString(rs, 2)); - record.setValidtime(getTimeStamp(rs, 3)); - record.setBasistime(getTimeStamp(rs, 4)); - record.setPostingtime(getTimeStamp(rs, 5)); - record.setUztwc(getDouble(rs, 6)); - record.setUzfwc(getDouble(rs, 7)); - record.setLztwc(getDouble(rs, 8)); - record.setLzfsc(getDouble(rs, 9)); - record.setLzfpc(getDouble(rs, 10)); - record.setAdimc(getDouble(rs, 11)); - - // add this SacSmaStateRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the SacSmaStateRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a SacSmaStateRecord object and.. -//----------------------------------------------------------------- - public int insert(SacSmaStateRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO sacsmastate VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getBasin_id()); - setString(insertStatement, 2, record.getSource()); - setTimeStamp(insertStatement, 3, record.getValidtime()); - setTimeStamp(insertStatement, 4, record.getBasistime()); - setTimeStamp(insertStatement, 5, record.getPostingtime()); - setDouble(insertStatement, 6, record.getUztwc()); - setDouble(insertStatement, 7, record.getUzfwc()); - setDouble(insertStatement, 8, record.getLztwc()); - setDouble(insertStatement, 9, record.getLzfsc()); - setDouble(insertStatement, 10, record.getLzfpc()); - setDouble(insertStatement, 11, record.getAdimc()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM sacsmastate " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SacSmaStateRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SacSmaStateRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE sacsmastate SET basin_id = ?, source = ?, validtime = ?, basistime = ?, postingtime = ?, uztwc = ?, uzfwc = ?, lztwc = ?, lzfsc = ?, lzfpc = ?, adimc = ? " + where ); - - setString(updateStatement, 1, record.getBasin_id()); - setString(updateStatement, 2, record.getSource()); - setTimeStamp(updateStatement, 3, record.getValidtime()); - setTimeStamp(updateStatement, 4, record.getBasistime()); - setTimeStamp(updateStatement, 5, record.getPostingtime()); - setDouble(updateStatement, 6, record.getUztwc()); - setDouble(updateStatement, 7, record.getUzfwc()); - setDouble(updateStatement, 8, record.getLztwc()); - setDouble(updateStatement, 9, record.getLzfsc()); - setDouble(updateStatement, 10, record.getLzfpc()); - setDouble(updateStatement, 11, record.getAdimc()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(SacSmaStateRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM sacsmastate " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SacSmaStateRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SacSmaStateRecord oldRecord, SacSmaStateRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE sacsmastate SET basin_id = ?, source = ?, validtime = ?, basistime = ?, postingtime = ?, uztwc = ?, uzfwc = ?, lztwc = ?, lzfsc = ?, lzfpc = ?, adimc = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getBasin_id()); - setString(updateStatement, 2, newRecord.getSource()); - setTimeStamp(updateStatement, 3, newRecord.getValidtime()); - setTimeStamp(updateStatement, 4, newRecord.getBasistime()); - setTimeStamp(updateStatement, 5, newRecord.getPostingtime()); - setDouble(updateStatement, 6, newRecord.getUztwc()); - setDouble(updateStatement, 7, newRecord.getUzfwc()); - setDouble(updateStatement, 8, newRecord.getLztwc()); - setDouble(updateStatement, 9, newRecord.getLzfsc()); - setDouble(updateStatement, 10, newRecord.getLzfpc()); - setDouble(updateStatement, 11, newRecord.getAdimc()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a SacSmaStateRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(SacSmaStateRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - SacSmaStateRecord oldRecord = (SacSmaStateRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of SacSmaStateTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTableViewRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTableViewRecord.java deleted file mode 100644 index 0f7f38906b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTableViewRecord.java +++ /dev/null @@ -1,128 +0,0 @@ -// This is a view record ! -// filename: ServiceTableViewRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ServiceTableView table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ServiceTableViewRecord extends DbRecord -{ - private String lid; - - private String name; - - private String stream; - - private String state; - - private String county; - - private String hsa; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ServiceTableViewRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ServiceTableViewRecord(ServiceTableViewRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setStream(origRecord.getStream()); - setState(origRecord.getState()); - setCounty(origRecord.getCounty()); - setHsa(origRecord.getHsa()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ServiceTableView record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getStream() - { - return stream; - } - - public void setStream(String stream) - { - this.stream = stream ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getHsa() - { - return hsa; - } - - public void setHsa(String hsa) - { - this.hsa = hsa ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getStream() + " " + - getState() + " " + - getCounty() + " " + - getHsa() + " " + - "" ; - return outString; - } // end toString() -} // end of ServiceTableViewRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTableViewView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTableViewView.java deleted file mode 100644 index 8edd5118d3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTableViewView.java +++ /dev/null @@ -1,141 +0,0 @@ -// filename: ServiceTableViewView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// servicetableview table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ServiceTableViewView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ServiceTableViewTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ServiceTableViewView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("servicetableview"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ServiceTableViewRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ServiceTableViewRecord record = null; - - // create a List to hold ServiceTableView Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM servicetableview " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ServiceTableViewRecord - // and store its address in oneRecord - record = new ServiceTableViewRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ServiceTableViewRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setStream(getString(rs, 3)); - record.setState(getString(rs, 4)); - record.setCounty(getString(rs, 5)); - record.setHsa(getString(rs, 6)); - - // add this ServiceTableViewRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ServiceTableViewRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ServiceTableViewRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ServiceTableViewRecord record = null; - - // create a List to hold ServiceTableView Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM servicetableview " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ServiceTableViewRecord - // and store its address in oneRecord - record = new ServiceTableViewRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ServiceTableViewRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setStream(getString(rs, 3)); - record.setState(getString(rs, 4)); - record.setCounty(getString(rs, 5)); - record.setHsa(getString(rs, 6)); - - // add this ServiceTableViewRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ServiceTableViewRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of ServiceTableViewTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTypeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTypeRecord.java deleted file mode 100644 index a9fd02fb09..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTypeRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: ServiceTypeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ServiceType table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ServiceTypeRecord extends DbRecord -{ - private String service_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ServiceTypeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ServiceTypeRecord(ServiceTypeRecord origRecord) - { - setService_type(origRecord.getService_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ServiceType record - - //----------------------------------------------------------------- - public String getService_type() - { - return service_type; - } - - public void setService_type(String service_type) - { - this.service_type = service_type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE service_type = '" + service_type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getService_type() + " " + - "" ; - return outString; - } // end toString() -} // end of ServiceTypeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTypeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTypeTable.java deleted file mode 100644 index 5866e20970..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ServiceTypeTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: ServiceTypeTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// servicetype table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ServiceTypeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ServiceTypeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ServiceTypeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("servicetype"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ServiceTypeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ServiceTypeRecord record = null; - - // create a List to hold ServiceType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM servicetype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ServiceTypeRecord - // and store its address in oneRecord - record = new ServiceTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ServiceTypeRecord object - - record.setService_type(getString(rs, 1)); - - // add this ServiceTypeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ServiceTypeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ServiceTypeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ServiceTypeRecord record = null; - - // create a List to hold ServiceType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM servicetype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ServiceTypeRecord - // and store its address in oneRecord - record = new ServiceTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ServiceTypeRecord object - - record.setService_type(getString(rs, 1)); - - // add this ServiceTypeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ServiceTypeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ServiceTypeRecord object and.. -//----------------------------------------------------------------- - public int insert(ServiceTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO servicetype VALUES (? )"); - - setString(insertStatement, 1, record.getService_type()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM servicetype " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ServiceTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ServiceTypeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE servicetype SET service_type = ? " + where ); - - setString(updateStatement, 1, record.getService_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ServiceTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM servicetype " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ServiceTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ServiceTypeRecord oldRecord, ServiceTypeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE servicetype SET service_type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getService_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ServiceTypeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ServiceTypeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ServiceTypeRecord oldRecord = (ServiceTypeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ServiceTypeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefDurRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefDurRecord.java deleted file mode 100644 index 5a56ec42c3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefDurRecord.java +++ /dev/null @@ -1,97 +0,0 @@ -// filename: ShefDurRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefDur table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefDurRecord extends DbRecord -{ - private short dur; - - private String durcode; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefDurRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefDurRecord(ShefDurRecord origRecord) - { - setDur(origRecord.getDur()); - setDurcode(origRecord.getDurcode()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefDur record - - //----------------------------------------------------------------- - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getDurcode() - { - return durcode; - } - - public void setDurcode(String durcode) - { - this.durcode = durcode ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE dur = '" + dur + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getDur() + " " + - getDurcode() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefDurRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefDurTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefDurTable.java deleted file mode 100644 index 0e3c10f8ee..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefDurTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: ShefDurTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefdur table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefDurTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefDurTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefDurTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefdur"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefDurRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefDurRecord record = null; - - // create a List to hold ShefDur Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefdur " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefDurRecord - // and store its address in oneRecord - record = new ShefDurRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefDurRecord object - - record.setDur(getShort(rs, 1)); - record.setDurcode(getString(rs, 2)); - record.setName(getString(rs, 3)); - - // add this ShefDurRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefDurRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefDurRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefDurRecord record = null; - - // create a List to hold ShefDur Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefdur " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefDurRecord - // and store its address in oneRecord - record = new ShefDurRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefDurRecord object - - record.setDur(getShort(rs, 1)); - record.setDurcode(getString(rs, 2)); - record.setName(getString(rs, 3)); - - // add this ShefDurRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefDurRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefDurRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefDurRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefdur VALUES (?, ?, ? )"); - - setShort(insertStatement, 1, record.getDur()); - setString(insertStatement, 2, record.getDurcode()); - setString(insertStatement, 3, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefdur " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefDurRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefDurRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefdur SET dur = ?, durcode = ?, name = ? " + where ); - - setShort(updateStatement, 1, record.getDur()); - setString(updateStatement, 2, record.getDurcode()); - setString(updateStatement, 3, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefDurRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefdur " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefDurRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefDurRecord oldRecord, ShefDurRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefdur SET dur = ?, durcode = ?, name = ? " + oldRecord.getWhereString() ); - - setShort(updateStatement, 1, newRecord.getDur()); - setString(updateStatement, 2, newRecord.getDurcode()); - setString(updateStatement, 3, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefDurRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefDurRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefDurRecord oldRecord = (ShefDurRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefDurTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefExRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefExRecord.java deleted file mode 100644 index cd9c6bf394..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefExRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: ShefExRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefEx table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefExRecord extends DbRecord -{ - private String extremum; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefExRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefExRecord(ShefExRecord origRecord) - { - setExtremum(origRecord.getExtremum()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefEx record - - //----------------------------------------------------------------- - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE extremum = '" + extremum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getExtremum() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefExRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefExTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefExTable.java deleted file mode 100644 index 48b461bf61..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefExTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: ShefExTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefex table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefExTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefExTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefExTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefex"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefExRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefExRecord record = null; - - // create a List to hold ShefEx Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefex " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefExRecord - // and store its address in oneRecord - record = new ShefExRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefExRecord object - - record.setExtremum(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this ShefExRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefExRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefExRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefExRecord record = null; - - // create a List to hold ShefEx Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefex " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefExRecord - // and store its address in oneRecord - record = new ShefExRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefExRecord object - - record.setExtremum(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this ShefExRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefExRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefExRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefExRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefex VALUES (?, ? )"); - - setString(insertStatement, 1, record.getExtremum()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefex " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefExRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefExRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefex SET extremum = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getExtremum()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefExRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefex " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefExRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefExRecord oldRecord, ShefExRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefex SET extremum = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getExtremum()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefExRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefExRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefExRecord oldRecord = (ShefExRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefExTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPETransRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPETransRecord.java deleted file mode 100644 index d84bb72e92..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPETransRecord.java +++ /dev/null @@ -1,98 +0,0 @@ -// filename: ShefPETransRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefPETrans table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefPETransRecord extends DbRecord -{ - private String pe; - - private int coded_value; - - private String value_trans; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefPETransRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefPETransRecord(ShefPETransRecord origRecord) - { - setPe(origRecord.getPe()); - setCoded_value(origRecord.getCoded_value()); - setValue_trans(origRecord.getValue_trans()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefPETrans record - - //----------------------------------------------------------------- - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public int getCoded_value() - { - return coded_value; - } - - public void setCoded_value(int coded_value) - { - this.coded_value = coded_value ; - } - - public String getValue_trans() - { - return value_trans; - } - - public void setValue_trans(String value_trans) - { - this.value_trans = value_trans ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE pe = '" + pe + "'" - + " AND coded_value = '" + coded_value + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPe() + " " + - getCoded_value() + " " + - getValue_trans() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefPETransRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPETransTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPETransTable.java deleted file mode 100644 index 0bb83e164a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPETransTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: ShefPETransTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefpetrans table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefPETransTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefPETransTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefPETransTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefpetrans"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefPETransRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefPETransRecord record = null; - - // create a List to hold ShefPETrans Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefpetrans " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefPETransRecord - // and store its address in oneRecord - record = new ShefPETransRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefPETransRecord object - - record.setPe(getString(rs, 1)); - record.setCoded_value(getInt(rs, 2)); - record.setValue_trans(getString(rs, 3)); - - // add this ShefPETransRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefPETransRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefPETransRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefPETransRecord record = null; - - // create a List to hold ShefPETrans Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefpetrans " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefPETransRecord - // and store its address in oneRecord - record = new ShefPETransRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefPETransRecord object - - record.setPe(getString(rs, 1)); - record.setCoded_value(getInt(rs, 2)); - record.setValue_trans(getString(rs, 3)); - - // add this ShefPETransRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefPETransRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefPETransRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefPETransRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefpetrans VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getPe()); - setInt(insertStatement, 2, record.getCoded_value()); - setString(insertStatement, 3, record.getValue_trans()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefpetrans " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefPETransRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefPETransRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefpetrans SET pe = ?, coded_value = ?, value_trans = ? " + where ); - - setString(updateStatement, 1, record.getPe()); - setInt(updateStatement, 2, record.getCoded_value()); - setString(updateStatement, 3, record.getValue_trans()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefPETransRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefpetrans " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefPETransRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefPETransRecord oldRecord, ShefPETransRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefpetrans SET pe = ?, coded_value = ?, value_trans = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPe()); - setInt(updateStatement, 2, newRecord.getCoded_value()); - setString(updateStatement, 3, newRecord.getValue_trans()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefPETransRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefPETransRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefPETransRecord oldRecord = (ShefPETransRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefPETransTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPeRecord.java deleted file mode 100644 index 34b2b12a06..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPeRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: ShefPeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefPe table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefPeRecord extends DbRecord -{ - private String pe; - - private String name; - - private String eng_unit; - - private String met_unit; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefPeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefPeRecord(ShefPeRecord origRecord) - { - setPe(origRecord.getPe()); - setName(origRecord.getName()); - setEng_unit(origRecord.getEng_unit()); - setMet_unit(origRecord.getMet_unit()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefPe record - - //----------------------------------------------------------------- - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getEng_unit() - { - return eng_unit; - } - - public void setEng_unit(String eng_unit) - { - this.eng_unit = eng_unit ; - } - - public String getMet_unit() - { - return met_unit; - } - - public void setMet_unit(String met_unit) - { - this.met_unit = met_unit ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE pe = '" + pe + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPe() + " " + - getName() + " " + - getEng_unit() + " " + - getMet_unit() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefPeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPeTable.java deleted file mode 100644 index d8cd1592a4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefPeTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: ShefPeTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefpe table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefPeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefPeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefPeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefpe"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefPeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefPeRecord record = null; - - // create a List to hold ShefPe Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefpe " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefPeRecord - // and store its address in oneRecord - record = new ShefPeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefPeRecord object - - record.setPe(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setEng_unit(getString(rs, 3)); - record.setMet_unit(getString(rs, 4)); - - // add this ShefPeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefPeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefPeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefPeRecord record = null; - - // create a List to hold ShefPe Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefpe " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefPeRecord - // and store its address in oneRecord - record = new ShefPeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefPeRecord object - - record.setPe(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setEng_unit(getString(rs, 3)); - record.setMet_unit(getString(rs, 4)); - - // add this ShefPeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefPeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefPeRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefPeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefpe VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getPe()); - setString(insertStatement, 2, record.getName()); - setString(insertStatement, 3, record.getEng_unit()); - setString(insertStatement, 4, record.getMet_unit()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefpe " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefPeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefPeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefpe SET pe = ?, name = ?, eng_unit = ?, met_unit = ? " + where ); - - setString(updateStatement, 1, record.getPe()); - setString(updateStatement, 2, record.getName()); - setString(updateStatement, 3, record.getEng_unit()); - setString(updateStatement, 4, record.getMet_unit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefPeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefpe " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefPeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefPeRecord oldRecord, ShefPeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefpe SET pe = ?, name = ?, eng_unit = ?, met_unit = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPe()); - setString(updateStatement, 2, newRecord.getName()); - setString(updateStatement, 3, newRecord.getEng_unit()); - setString(updateStatement, 4, newRecord.getMet_unit()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefPeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefPeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefPeRecord oldRecord = (ShefPeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefPeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefProbRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefProbRecord.java deleted file mode 100644 index e84008c50d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefProbRecord.java +++ /dev/null @@ -1,97 +0,0 @@ -// filename: ShefProbRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefProb table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefProbRecord extends DbRecord -{ - private String probcode; - - private float probability; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefProbRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefProbRecord(ShefProbRecord origRecord) - { - setProbcode(origRecord.getProbcode()); - setProbability(origRecord.getProbability()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefProb record - - //----------------------------------------------------------------- - public String getProbcode() - { - return probcode; - } - - public void setProbcode(String probcode) - { - this.probcode = probcode ; - } - - public float getProbability() - { - return probability; - } - - public void setProbability(float probability) - { - this.probability = probability ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE probcode = '" + probcode + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getProbcode() + " " + - getProbability() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefProbRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefProbTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefProbTable.java deleted file mode 100644 index 7af3a6266e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefProbTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: ShefProbTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefprob table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefProbTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefProbTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefProbTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefprob"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefProbRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefProbRecord record = null; - - // create a List to hold ShefProb Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefprob " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefProbRecord - // and store its address in oneRecord - record = new ShefProbRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefProbRecord object - - record.setProbcode(getString(rs, 1)); - record.setProbability(getReal(rs, 2)); - record.setName(getString(rs, 3)); - - // add this ShefProbRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefProbRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefProbRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefProbRecord record = null; - - // create a List to hold ShefProb Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefprob " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefProbRecord - // and store its address in oneRecord - record = new ShefProbRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefProbRecord object - - record.setProbcode(getString(rs, 1)); - record.setProbability(getReal(rs, 2)); - record.setName(getString(rs, 3)); - - // add this ShefProbRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefProbRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefProbRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefProbRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefprob VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getProbcode()); - setReal(insertStatement, 2, record.getProbability()); - setString(insertStatement, 3, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefprob " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefProbRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefProbRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefprob SET probcode = ?, probability = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getProbcode()); - setReal(updateStatement, 2, record.getProbability()); - setString(updateStatement, 3, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefProbRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefprob " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefProbRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefProbRecord oldRecord, ShefProbRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefprob SET probcode = ?, probability = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getProbcode()); - setReal(updateStatement, 2, newRecord.getProbability()); - setString(updateStatement, 3, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefProbRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefProbRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefProbRecord oldRecord = (ShefProbRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefProbTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefQcRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefQcRecord.java deleted file mode 100644 index 16b06d493b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefQcRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: ShefQcRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefQc table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefQcRecord extends DbRecord -{ - private String shef_qual_code; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefQcRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefQcRecord(ShefQcRecord origRecord) - { - setShef_qual_code(origRecord.getShef_qual_code()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefQc record - - //----------------------------------------------------------------- - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE shef_qual_code = '" + shef_qual_code + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getShef_qual_code() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefQcRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefQcTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefQcTable.java deleted file mode 100644 index aa5987cd39..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefQcTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: ShefQcTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefqc table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefQcTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefQcTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefQcTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefqc"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefQcRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefQcRecord record = null; - - // create a List to hold ShefQc Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefqc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefQcRecord - // and store its address in oneRecord - record = new ShefQcRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefQcRecord object - - record.setShef_qual_code(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this ShefQcRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefQcRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefQcRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefQcRecord record = null; - - // create a List to hold ShefQc Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefqc " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefQcRecord - // and store its address in oneRecord - record = new ShefQcRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefQcRecord object - - record.setShef_qual_code(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this ShefQcRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefQcRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefQcRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefQcRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefqc VALUES (?, ? )"); - - setString(insertStatement, 1, record.getShef_qual_code()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefqc " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefQcRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefQcRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefqc SET shef_qual_code = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getShef_qual_code()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefQcRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefqc " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefQcRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefQcRecord oldRecord, ShefQcRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefqc SET shef_qual_code = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getShef_qual_code()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefQcRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefQcRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefQcRecord oldRecord = (ShefQcRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefQcTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefTsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefTsRecord.java deleted file mode 100644 index 4a5e0004b1..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefTsRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: ShefTsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ShefTs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ShefTsRecord extends DbRecord -{ - private String ts; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ShefTsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ShefTsRecord(ShefTsRecord origRecord) - { - setTs(origRecord.getTs()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ShefTs record - - //----------------------------------------------------------------- - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE ts = '" + ts + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getTs() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of ShefTsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefTsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefTsTable.java deleted file mode 100644 index 25e7faba89..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ShefTsTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: ShefTsTable.java -// author : DBGEN -// created : Tue May 31 17:52:28 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// shefts table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ShefTsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ShefTsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ShefTsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("shefts"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ShefTsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ShefTsRecord record = null; - - // create a List to hold ShefTs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefts " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefTsRecord - // and store its address in oneRecord - record = new ShefTsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefTsRecord object - - record.setTs(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this ShefTsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ShefTsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ShefTsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ShefTsRecord record = null; - - // create a List to hold ShefTs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM shefts " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ShefTsRecord - // and store its address in oneRecord - record = new ShefTsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ShefTsRecord object - - record.setTs(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this ShefTsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ShefTsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ShefTsRecord object and.. -//----------------------------------------------------------------- - public int insert(ShefTsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO shefts VALUES (?, ? )"); - - setString(insertStatement, 1, record.getTs()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefts " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefTsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefTsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefts SET ts = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getTs()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ShefTsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM shefts " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ShefTsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ShefTsRecord oldRecord, ShefTsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE shefts SET ts = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getTs()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ShefTsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ShefTsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ShefTsRecord oldRecord = (ShefTsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ShefTsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowMethodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowMethodRecord.java deleted file mode 100644 index 27b3085841..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowMethodRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: SnowMethodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// SnowMethod table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class SnowMethodRecord extends DbRecord -{ - private String snow_method; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public SnowMethodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public SnowMethodRecord(SnowMethodRecord origRecord) - { - setSnow_method(origRecord.getSnow_method()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a SnowMethod record - - //----------------------------------------------------------------- - public String getSnow_method() - { - return snow_method; - } - - public void setSnow_method(String snow_method) - { - this.snow_method = snow_method ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE snow_method = '" + snow_method + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getSnow_method() + " " + - "" ; - return outString; - } // end toString() -} // end of SnowMethodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowMethodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowMethodTable.java deleted file mode 100644 index 7481faef33..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowMethodTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: SnowMethodTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// snowmethod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class SnowMethodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// SnowMethodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public SnowMethodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("snowmethod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of SnowMethodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - SnowMethodRecord record = null; - - // create a List to hold SnowMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM snowmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SnowMethodRecord - // and store its address in oneRecord - record = new SnowMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SnowMethodRecord object - - record.setSnow_method(getString(rs, 1)); - - // add this SnowMethodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the SnowMethodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of SnowMethodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - SnowMethodRecord record = null; - - // create a List to hold SnowMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM snowmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SnowMethodRecord - // and store its address in oneRecord - record = new SnowMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SnowMethodRecord object - - record.setSnow_method(getString(rs, 1)); - - // add this SnowMethodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the SnowMethodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a SnowMethodRecord object and.. -//----------------------------------------------------------------- - public int insert(SnowMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO snowmethod VALUES (? )"); - - setString(insertStatement, 1, record.getSnow_method()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM snowmethod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SnowMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SnowMethodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE snowmethod SET snow_method = ? " + where ); - - setString(updateStatement, 1, record.getSnow_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(SnowMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM snowmethod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SnowMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SnowMethodRecord oldRecord, SnowMethodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE snowmethod SET snow_method = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getSnow_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a SnowMethodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(SnowMethodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - SnowMethodRecord oldRecord = (SnowMethodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of SnowMethodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowRecord.java deleted file mode 100644 index 83f1812c96..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: SnowRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Snow table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class SnowRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public SnowRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public SnowRecord(SnowRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Snow record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of SnowRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowTable.java deleted file mode 100644 index 681d6bd61d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SnowTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: SnowTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// snow table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class SnowTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// SnowTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public SnowTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("snow"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of SnowRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - SnowRecord record = null; - - // create a List to hold Snow Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM snow " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SnowRecord - // and store its address in oneRecord - record = new SnowRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SnowRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this SnowRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the SnowRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of SnowRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - SnowRecord record = null; - - // create a List to hold Snow Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM snow " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SnowRecord - // and store its address in oneRecord - record = new SnowRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SnowRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this SnowRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the SnowRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a SnowRecord object and.. -//----------------------------------------------------------------- - public int insert(SnowRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO snow VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM snow " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SnowRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SnowRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE snow SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(SnowRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM snow " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SnowRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SnowRecord oldRecord, SnowRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE snow SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a SnowRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(SnowRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - SnowRecord oldRecord = (SnowRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of SnowTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SshpConfigRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SshpConfigRecord.java deleted file mode 100644 index 7c99cb28b6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SshpConfigRecord.java +++ /dev/null @@ -1,195 +0,0 @@ -// filename: SshpConfigRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// SshpConfig table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class SshpConfigRecord extends DbRecord -{ - private String lid; - - private String basin_id; - - private long postingtime; - - private String model_pref; - - private String auto_process; - - private String source_pref; - - private String use_static_evap; - - private String use_blend; - - private String blend_method; - - private int blend_hours; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public SshpConfigRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public SshpConfigRecord(SshpConfigRecord origRecord) - { - setLid(origRecord.getLid()); - setBasin_id(origRecord.getBasin_id()); - setPostingtime(origRecord.getPostingtime()); - setModel_pref(origRecord.getModel_pref()); - setAuto_process(origRecord.getAuto_process()); - setSource_pref(origRecord.getSource_pref()); - setUse_static_evap(origRecord.getUse_static_evap()); - setUse_blend(origRecord.getUse_blend()); - setBlend_method(origRecord.getBlend_method()); - setBlend_hours(origRecord.getBlend_hours()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a SshpConfig record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getBasin_id() - { - return basin_id; - } - - public void setBasin_id(String basin_id) - { - this.basin_id = basin_id ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public String getModel_pref() - { - return model_pref; - } - - public void setModel_pref(String model_pref) - { - this.model_pref = model_pref ; - } - - public String getAuto_process() - { - return auto_process; - } - - public void setAuto_process(String auto_process) - { - this.auto_process = auto_process ; - } - - public String getSource_pref() - { - return source_pref; - } - - public void setSource_pref(String source_pref) - { - this.source_pref = source_pref ; - } - - public String getUse_static_evap() - { - return use_static_evap; - } - - public void setUse_static_evap(String use_static_evap) - { - this.use_static_evap = use_static_evap ; - } - - public String getUse_blend() - { - return use_blend; - } - - public void setUse_blend(String use_blend) - { - this.use_blend = use_blend ; - } - - public String getBlend_method() - { - return blend_method; - } - - public void setBlend_method(String blend_method) - { - this.blend_method = blend_method ; - } - - public int getBlend_hours() - { - return blend_hours; - } - - public void setBlend_hours(int blend_hours) - { - this.blend_hours = blend_hours ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getBasin_id() + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getModel_pref() + " " + - getAuto_process() + " " + - getSource_pref() + " " + - getUse_static_evap() + " " + - getUse_blend() + " " + - getBlend_method() + " " + - getBlend_hours() + " " + - "" ; - return outString; - } // end toString() -} // end of SshpConfigRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SshpConfigTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SshpConfigTable.java deleted file mode 100644 index f74a49af17..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/SshpConfigTable.java +++ /dev/null @@ -1,291 +0,0 @@ -// filename: SshpConfigTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// sshpconfig table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class SshpConfigTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// SshpConfigTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public SshpConfigTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("sshpconfig"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of SshpConfigRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - SshpConfigRecord record = null; - - // create a List to hold SshpConfig Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM sshpconfig " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SshpConfigRecord - // and store its address in oneRecord - record = new SshpConfigRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SshpConfigRecord object - - record.setLid(getString(rs, 1)); - record.setBasin_id(getString(rs, 2)); - record.setPostingtime(getTimeStamp(rs, 3)); - record.setModel_pref(getString(rs, 4)); - record.setAuto_process(getString(rs, 5)); - record.setSource_pref(getString(rs, 6)); - record.setUse_static_evap(getString(rs, 7)); - record.setUse_blend(getString(rs, 8)); - record.setBlend_method(getString(rs, 9)); - record.setBlend_hours(getInt(rs, 10)); - - // add this SshpConfigRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the SshpConfigRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of SshpConfigRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - SshpConfigRecord record = null; - - // create a List to hold SshpConfig Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM sshpconfig " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a SshpConfigRecord - // and store its address in oneRecord - record = new SshpConfigRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a SshpConfigRecord object - - record.setLid(getString(rs, 1)); - record.setBasin_id(getString(rs, 2)); - record.setPostingtime(getTimeStamp(rs, 3)); - record.setModel_pref(getString(rs, 4)); - record.setAuto_process(getString(rs, 5)); - record.setSource_pref(getString(rs, 6)); - record.setUse_static_evap(getString(rs, 7)); - record.setUse_blend(getString(rs, 8)); - record.setBlend_method(getString(rs, 9)); - record.setBlend_hours(getInt(rs, 10)); - - // add this SshpConfigRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the SshpConfigRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a SshpConfigRecord object and.. -//----------------------------------------------------------------- - public int insert(SshpConfigRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO sshpconfig VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getBasin_id()); - setTimeStamp(insertStatement, 3, record.getPostingtime()); - setString(insertStatement, 4, record.getModel_pref()); - setString(insertStatement, 5, record.getAuto_process()); - setString(insertStatement, 6, record.getSource_pref()); - setString(insertStatement, 7, record.getUse_static_evap()); - setString(insertStatement, 8, record.getUse_blend()); - setString(insertStatement, 9, record.getBlend_method()); - setInt(insertStatement, 10, record.getBlend_hours()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM sshpconfig " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SshpConfigRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SshpConfigRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE sshpconfig SET lid = ?, basin_id = ?, postingtime = ?, model_pref = ?, auto_process = ?, source_pref = ?, use_static_evap = ?, use_blend = ?, blend_method = ?, blend_hours = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getBasin_id()); - setTimeStamp(updateStatement, 3, record.getPostingtime()); - setString(updateStatement, 4, record.getModel_pref()); - setString(updateStatement, 5, record.getAuto_process()); - setString(updateStatement, 6, record.getSource_pref()); - setString(updateStatement, 7, record.getUse_static_evap()); - setString(updateStatement, 8, record.getUse_blend()); - setString(updateStatement, 9, record.getBlend_method()); - setInt(updateStatement, 10, record.getBlend_hours()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(SshpConfigRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM sshpconfig " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a SshpConfigRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(SshpConfigRecord oldRecord, SshpConfigRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE sshpconfig SET lid = ?, basin_id = ?, postingtime = ?, model_pref = ?, auto_process = ?, source_pref = ?, use_static_evap = ?, use_blend = ?, blend_method = ?, blend_hours = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getBasin_id()); - setTimeStamp(updateStatement, 3, newRecord.getPostingtime()); - setString(updateStatement, 4, newRecord.getModel_pref()); - setString(updateStatement, 5, newRecord.getAuto_process()); - setString(updateStatement, 6, newRecord.getSource_pref()); - setString(updateStatement, 7, newRecord.getUse_static_evap()); - setString(updateStatement, 8, newRecord.getUse_blend()); - setString(updateStatement, 9, newRecord.getBlend_method()); - setInt(updateStatement, 10, newRecord.getBlend_hours()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a SshpConfigRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(SshpConfigRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - SshpConfigRecord oldRecord = (SshpConfigRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of SshpConfigTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StatProfRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StatProfRecord.java deleted file mode 100644 index adfaa3c6e8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StatProfRecord.java +++ /dev/null @@ -1,212 +0,0 @@ -// This is a view record ! -// filename: StatProfRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// StatProf table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class StatProfRecord extends DbRecord -{ - private String lid; - - private String name; - - private String primary_pe; - - private String stream; - - private double fs; - - private double wstg; - - private double fq; - - private double action_flow; - - private double zd; - - private double mile; - - private String reach; - - private String proximity; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public StatProfRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public StatProfRecord(StatProfRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setPrimary_pe(origRecord.getPrimary_pe()); - setStream(origRecord.getStream()); - setFs(origRecord.getFs()); - setWstg(origRecord.getWstg()); - setFq(origRecord.getFq()); - setAction_flow(origRecord.getAction_flow()); - setZd(origRecord.getZd()); - setMile(origRecord.getMile()); - setReach(origRecord.getReach()); - setProximity(origRecord.getProximity()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a StatProf record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getPrimary_pe() - { - return primary_pe; - } - - public void setPrimary_pe(String primary_pe) - { - this.primary_pe = primary_pe ; - } - - public String getStream() - { - return stream; - } - - public void setStream(String stream) - { - this.stream = stream ; - } - - public double getFs() - { - return fs; - } - - public void setFs(double fs) - { - this.fs = fs ; - } - - public double getWstg() - { - return wstg; - } - - public void setWstg(double wstg) - { - this.wstg = wstg ; - } - - public double getFq() - { - return fq; - } - - public void setFq(double fq) - { - this.fq = fq ; - } - - public double getAction_flow() - { - return action_flow; - } - - public void setAction_flow(double action_flow) - { - this.action_flow = action_flow ; - } - - public double getZd() - { - return zd; - } - - public void setZd(double zd) - { - this.zd = zd ; - } - - public double getMile() - { - return mile; - } - - public void setMile(double mile) - { - this.mile = mile ; - } - - public String getReach() - { - return reach; - } - - public void setReach(String reach) - { - this.reach = reach ; - } - - public String getProximity() - { - return proximity; - } - - public void setProximity(String proximity) - { - this.proximity = proximity ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getPrimary_pe() + " " + - getStream() + " " + - getFs() + " " + - getWstg() + " " + - getFq() + " " + - getAction_flow() + " " + - getZd() + " " + - getMile() + " " + - getReach() + " " + - getProximity() + " " + - "" ; - return outString; - } // end toString() -} // end of StatProfRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StatProfView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StatProfView.java deleted file mode 100644 index 6e3e3061b4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StatProfView.java +++ /dev/null @@ -1,153 +0,0 @@ -// filename: StatProfView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// statprof table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class StatProfView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// StatProfTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public StatProfView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("statprof"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of StatProfRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - StatProfRecord record = null; - - // create a List to hold StatProf Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM statprof " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StatProfRecord - // and store its address in oneRecord - record = new StatProfRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StatProfRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setPrimary_pe(getString(rs, 3)); - record.setStream(getString(rs, 4)); - record.setFs(getDouble(rs, 5)); - record.setWstg(getDouble(rs, 6)); - record.setFq(getDouble(rs, 7)); - record.setAction_flow(getDouble(rs, 8)); - record.setZd(getDouble(rs, 9)); - record.setMile(getDouble(rs, 10)); - record.setReach(getString(rs, 11)); - record.setProximity(getString(rs, 12)); - - // add this StatProfRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the StatProfRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of StatProfRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - StatProfRecord record = null; - - // create a List to hold StatProf Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM statprof " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StatProfRecord - // and store its address in oneRecord - record = new StatProfRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StatProfRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setPrimary_pe(getString(rs, 3)); - record.setStream(getString(rs, 4)); - record.setFs(getDouble(rs, 5)); - record.setWstg(getDouble(rs, 6)); - record.setFq(getDouble(rs, 7)); - record.setAction_flow(getDouble(rs, 8)); - record.setZd(getDouble(rs, 9)); - record.setMile(getDouble(rs, 10)); - record.setReach(getString(rs, 11)); - record.setProximity(getString(rs, 12)); - - // add this StatProfRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the StatProfRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of StatProfTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StateRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StateRecord.java deleted file mode 100644 index 306adbc3a4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StateRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: StateRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// State table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class StateRecord extends DbRecord -{ - private String state; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public StateRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public StateRecord(StateRecord origRecord) - { - setState(origRecord.getState()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a State record - - //----------------------------------------------------------------- - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE state = '" + state + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getState() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of StateRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StateTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StateTable.java deleted file mode 100644 index 2c40e86f26..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StateTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: StateTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// state table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class StateTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// StateTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public StateTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("state"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of StateRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - StateRecord record = null; - - // create a List to hold State Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM state " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StateRecord - // and store its address in oneRecord - record = new StateRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StateRecord object - - record.setState(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this StateRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the StateRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of StateRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - StateRecord record = null; - - // create a List to hold State Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM state " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StateRecord - // and store its address in oneRecord - record = new StateRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StateRecord object - - record.setState(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this StateRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the StateRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a StateRecord object and.. -//----------------------------------------------------------------- - public int insert(StateRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO state VALUES (?, ? )"); - - setString(insertStatement, 1, record.getState()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM state " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a StateRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(StateRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE state SET state = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getState()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(StateRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM state " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a StateRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(StateRecord oldRecord, StateRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE state SET state = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getState()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a StateRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(StateRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - StateRecord oldRecord = (StateRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of StateTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StationListRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StationListRecord.java deleted file mode 100644 index 4d90eef255..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StationListRecord.java +++ /dev/null @@ -1,170 +0,0 @@ -// This is a view record ! -// filename: StationListRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// StationList table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class StationListRecord extends DbRecord -{ - private String lid; - - private String name; - - private String firstname; - - private String lastname; - - private String rb; - - private String county; - - private String wfo; - - private String hphone; - - private String ophone; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public StationListRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public StationListRecord(StationListRecord origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setFirstname(origRecord.getFirstname()); - setLastname(origRecord.getLastname()); - setRb(origRecord.getRb()); - setCounty(origRecord.getCounty()); - setWfo(origRecord.getWfo()); - setHphone(origRecord.getHphone()); - setOphone(origRecord.getOphone()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a StationList record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - - public String getFirstname() - { - return firstname; - } - - public void setFirstname(String firstname) - { - this.firstname = firstname ; - } - - public String getLastname() - { - return lastname; - } - - public void setLastname(String lastname) - { - this.lastname = lastname ; - } - - public String getRb() - { - return rb; - } - - public void setRb(String rb) - { - this.rb = rb ; - } - - public String getCounty() - { - return county; - } - - public void setCounty(String county) - { - this.county = county ; - } - - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - - public String getHphone() - { - return hphone; - } - - public void setHphone(String hphone) - { - this.hphone = hphone ; - } - - public String getOphone() - { - return ophone; - } - - public void setOphone(String ophone) - { - this.ophone = ophone ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getName() + " " + - getFirstname() + " " + - getLastname() + " " + - getRb() + " " + - getCounty() + " " + - getWfo() + " " + - getHphone() + " " + - getOphone() + " " + - "" ; - return outString; - } // end toString() -} // end of StationListRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StationListView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StationListView.java deleted file mode 100644 index 76b8b02936..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StationListView.java +++ /dev/null @@ -1,147 +0,0 @@ -// filename: StationListView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// stationlist table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class StationListView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// StationListTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public StationListView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("stationlist"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of StationListRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - StationListRecord record = null; - - // create a List to hold StationList Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM stationlist " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StationListRecord - // and store its address in oneRecord - record = new StationListRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StationListRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setFirstname(getString(rs, 3)); - record.setLastname(getString(rs, 4)); - record.setRb(getString(rs, 5)); - record.setCounty(getString(rs, 6)); - record.setWfo(getString(rs, 7)); - record.setHphone(getString(rs, 8)); - record.setOphone(getString(rs, 9)); - - // add this StationListRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the StationListRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of StationListRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - StationListRecord record = null; - - // create a List to hold StationList Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM stationlist " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StationListRecord - // and store its address in oneRecord - record = new StationListRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StationListRecord object - - record.setLid(getString(rs, 1)); - record.setName(getString(rs, 2)); - record.setFirstname(getString(rs, 3)); - record.setLastname(getString(rs, 4)); - record.setRb(getString(rs, 5)); - record.setCounty(getString(rs, 6)); - record.setWfo(getString(rs, 7)); - record.setHphone(getString(rs, 8)); - record.setOphone(getString(rs, 9)); - - // add this StationListRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the StationListRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of StationListTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StnClassRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StnClassRecord.java deleted file mode 100644 index be755e66ca..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StnClassRecord.java +++ /dev/null @@ -1,125 +0,0 @@ -// filename: StnClassRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// StnClass table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class StnClassRecord extends DbRecord -{ - private String lid; - - private String disp_class; - - private String dcp; - - private String observer; - - private String telem_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public StnClassRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public StnClassRecord(StnClassRecord origRecord) - { - setLid(origRecord.getLid()); - setDisp_class(origRecord.getDisp_class()); - setDcp(origRecord.getDcp()); - setObserver(origRecord.getObserver()); - setTelem_type(origRecord.getTelem_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a StnClass record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getDisp_class() - { - return disp_class; - } - - public void setDisp_class(String disp_class) - { - this.disp_class = disp_class ; - } - - public String getDcp() - { - return dcp; - } - - public void setDcp(String dcp) - { - this.dcp = dcp ; - } - - public String getObserver() - { - return observer; - } - - public void setObserver(String observer) - { - this.observer = observer ; - } - - public String getTelem_type() - { - return telem_type; - } - - public void setTelem_type(String telem_type) - { - this.telem_type = telem_type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getDisp_class() + " " + - getDcp() + " " + - getObserver() + " " + - getTelem_type() + " " + - "" ; - return outString; - } // end toString() -} // end of StnClassRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StnClassTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StnClassTable.java deleted file mode 100644 index bf5e6d3aa8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/StnClassTable.java +++ /dev/null @@ -1,266 +0,0 @@ -// filename: StnClassTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// stnclass table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class StnClassTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// StnClassTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public StnClassTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("stnclass"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of StnClassRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - StnClassRecord record = null; - - // create a List to hold StnClass Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM stnclass " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StnClassRecord - // and store its address in oneRecord - record = new StnClassRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StnClassRecord object - - record.setLid(getString(rs, 1)); - record.setDisp_class(getString(rs, 2)); - record.setDcp(getString(rs, 3)); - record.setObserver(getString(rs, 4)); - record.setTelem_type(getString(rs, 5)); - - // add this StnClassRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the StnClassRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of StnClassRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - StnClassRecord record = null; - - // create a List to hold StnClass Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM stnclass " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a StnClassRecord - // and store its address in oneRecord - record = new StnClassRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a StnClassRecord object - - record.setLid(getString(rs, 1)); - record.setDisp_class(getString(rs, 2)); - record.setDcp(getString(rs, 3)); - record.setObserver(getString(rs, 4)); - record.setTelem_type(getString(rs, 5)); - - // add this StnClassRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the StnClassRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a StnClassRecord object and.. -//----------------------------------------------------------------- - public int insert(StnClassRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO stnclass VALUES (?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getDisp_class()); - setString(insertStatement, 3, record.getDcp()); - setString(insertStatement, 4, record.getObserver()); - setString(insertStatement, 5, record.getTelem_type()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM stnclass " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a StnClassRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(StnClassRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE stnclass SET lid = ?, disp_class = ?, dcp = ?, observer = ?, telem_type = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getDisp_class()); - setString(updateStatement, 3, record.getDcp()); - setString(updateStatement, 4, record.getObserver()); - setString(updateStatement, 5, record.getTelem_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(StnClassRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM stnclass " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a StnClassRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(StnClassRecord oldRecord, StnClassRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE stnclass SET lid = ?, disp_class = ?, dcp = ?, observer = ?, telem_type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getDisp_class()); - setString(updateStatement, 3, newRecord.getDcp()); - setString(updateStatement, 4, newRecord.getObserver()); - setString(updateStatement, 5, newRecord.getTelem_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a StnClassRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(StnClassRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - StnClassRecord oldRecord = (StnClassRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of StnClassTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelemRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelemRecord.java deleted file mode 100644 index 2317b9e8b9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelemRecord.java +++ /dev/null @@ -1,209 +0,0 @@ -// filename: TelemRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Telem table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TelemRecord extends DbRecord -{ - private String lid; - - private String type; - - private String payor; - - private double cost; - - private String criteria; - - private String owner; - - private String phone; - - private String sensorid; - - private String rptfreq; - - private String notify; - - private String obsvfreq; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TelemRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TelemRecord(TelemRecord origRecord) - { - setLid(origRecord.getLid()); - setType(origRecord.getType()); - setPayor(origRecord.getPayor()); - setCost(origRecord.getCost()); - setCriteria(origRecord.getCriteria()); - setOwner(origRecord.getOwner()); - setPhone(origRecord.getPhone()); - setSensorid(origRecord.getSensorid()); - setRptfreq(origRecord.getRptfreq()); - setNotify(origRecord.getNotify()); - setObsvfreq(origRecord.getObsvfreq()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Telem record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - - public String getPayor() - { - return payor; - } - - public void setPayor(String payor) - { - this.payor = payor ; - } - - public double getCost() - { - return cost; - } - - public void setCost(double cost) - { - this.cost = cost ; - } - - public String getCriteria() - { - return criteria; - } - - public void setCriteria(String criteria) - { - this.criteria = criteria ; - } - - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - - public String getPhone() - { - return phone; - } - - public void setPhone(String phone) - { - this.phone = phone ; - } - - public String getSensorid() - { - return sensorid; - } - - public void setSensorid(String sensorid) - { - this.sensorid = sensorid ; - } - - public String getRptfreq() - { - return rptfreq; - } - - public void setRptfreq(String rptfreq) - { - this.rptfreq = rptfreq ; - } - - public String getNotify() - { - return notify; - } - - public void setNotify(String notify) - { - this.notify = notify ; - } - - public String getObsvfreq() - { - return obsvfreq; - } - - public void setObsvfreq(String obsvfreq) - { - this.obsvfreq = obsvfreq ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getType() + " " + - getPayor() + " " + - getCost() + " " + - getCriteria() + " " + - getOwner() + " " + - getPhone() + " " + - getSensorid() + " " + - getRptfreq() + " " + - getNotify() + " " + - getObsvfreq() + " " + - "" ; - return outString; - } // end toString() -} // end of TelemRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelemTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelemTable.java deleted file mode 100644 index 35860d9205..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelemTable.java +++ /dev/null @@ -1,296 +0,0 @@ -// filename: TelemTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// telem table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TelemTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TelemTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TelemTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("telem"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TelemRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TelemRecord record = null; - - // create a List to hold Telem Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telem " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelemRecord - // and store its address in oneRecord - record = new TelemRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelemRecord object - - record.setLid(getString(rs, 1)); - record.setType(getString(rs, 2)); - record.setPayor(getString(rs, 3)); - record.setCost(getDouble(rs, 4)); - record.setCriteria(getString(rs, 5)); - record.setOwner(getString(rs, 6)); - record.setPhone(getString(rs, 7)); - record.setSensorid(getString(rs, 8)); - record.setRptfreq(getString(rs, 9)); - record.setNotify(getString(rs, 10)); - record.setObsvfreq(getString(rs, 11)); - - // add this TelemRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TelemRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TelemRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TelemRecord record = null; - - // create a List to hold Telem Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telem " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelemRecord - // and store its address in oneRecord - record = new TelemRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelemRecord object - - record.setLid(getString(rs, 1)); - record.setType(getString(rs, 2)); - record.setPayor(getString(rs, 3)); - record.setCost(getDouble(rs, 4)); - record.setCriteria(getString(rs, 5)); - record.setOwner(getString(rs, 6)); - record.setPhone(getString(rs, 7)); - record.setSensorid(getString(rs, 8)); - record.setRptfreq(getString(rs, 9)); - record.setNotify(getString(rs, 10)); - record.setObsvfreq(getString(rs, 11)); - - // add this TelemRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TelemRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TelemRecord object and.. -//----------------------------------------------------------------- - public int insert(TelemRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO telem VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getType()); - setString(insertStatement, 3, record.getPayor()); - setDouble(insertStatement, 4, record.getCost()); - setString(insertStatement, 5, record.getCriteria()); - setString(insertStatement, 6, record.getOwner()); - setString(insertStatement, 7, record.getPhone()); - setString(insertStatement, 8, record.getSensorid()); - setString(insertStatement, 9, record.getRptfreq()); - setString(insertStatement, 10, record.getNotify()); - setString(insertStatement, 11, record.getObsvfreq()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telem " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelemRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelemRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telem SET lid = ?, type = ?, payor = ?, cost = ?, criteria = ?, owner = ?, phone = ?, sensorid = ?, rptfreq = ?, notify = ?, obsvfreq = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getType()); - setString(updateStatement, 3, record.getPayor()); - setDouble(updateStatement, 4, record.getCost()); - setString(updateStatement, 5, record.getCriteria()); - setString(updateStatement, 6, record.getOwner()); - setString(updateStatement, 7, record.getPhone()); - setString(updateStatement, 8, record.getSensorid()); - setString(updateStatement, 9, record.getRptfreq()); - setString(updateStatement, 10, record.getNotify()); - setString(updateStatement, 11, record.getObsvfreq()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TelemRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telem " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelemRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelemRecord oldRecord, TelemRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telem SET lid = ?, type = ?, payor = ?, cost = ?, criteria = ?, owner = ?, phone = ?, sensorid = ?, rptfreq = ?, notify = ?, obsvfreq = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getType()); - setString(updateStatement, 3, newRecord.getPayor()); - setDouble(updateStatement, 4, newRecord.getCost()); - setString(updateStatement, 5, newRecord.getCriteria()); - setString(updateStatement, 6, newRecord.getOwner()); - setString(updateStatement, 7, newRecord.getPhone()); - setString(updateStatement, 8, newRecord.getSensorid()); - setString(updateStatement, 9, newRecord.getRptfreq()); - setString(updateStatement, 10, newRecord.getNotify()); - setString(updateStatement, 11, newRecord.getObsvfreq()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TelemRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TelemRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TelemRecord oldRecord = (TelemRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TelemTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmOwnerRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmOwnerRecord.java deleted file mode 100644 index f0721a1ceb..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmOwnerRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: TelmOwnerRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// TelmOwner table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TelmOwnerRecord extends DbRecord -{ - private String owner; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TelmOwnerRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TelmOwnerRecord(TelmOwnerRecord origRecord) - { - setOwner(origRecord.getOwner()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a TelmOwner record - - //----------------------------------------------------------------- - public String getOwner() - { - return owner; - } - - public void setOwner(String owner) - { - this.owner = owner ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE owner = '" + owner + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getOwner() + " " + - "" ; - return outString; - } // end toString() -} // end of TelmOwnerRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmOwnerTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmOwnerTable.java deleted file mode 100644 index e1156892b4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmOwnerTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: TelmOwnerTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// telmowner table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TelmOwnerTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TelmOwnerTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TelmOwnerTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("telmowner"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TelmOwnerRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TelmOwnerRecord record = null; - - // create a List to hold TelmOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telmowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelmOwnerRecord - // and store its address in oneRecord - record = new TelmOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelmOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this TelmOwnerRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TelmOwnerRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TelmOwnerRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TelmOwnerRecord record = null; - - // create a List to hold TelmOwner Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telmowner " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelmOwnerRecord - // and store its address in oneRecord - record = new TelmOwnerRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelmOwnerRecord object - - record.setOwner(getString(rs, 1)); - - // add this TelmOwnerRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TelmOwnerRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TelmOwnerRecord object and.. -//----------------------------------------------------------------- - public int insert(TelmOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO telmowner VALUES (? )"); - - setString(insertStatement, 1, record.getOwner()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telmowner " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelmOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelmOwnerRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telmowner SET owner = ? " + where ); - - setString(updateStatement, 1, record.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TelmOwnerRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telmowner " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelmOwnerRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelmOwnerRecord oldRecord, TelmOwnerRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telmowner SET owner = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getOwner()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TelmOwnerRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TelmOwnerRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TelmOwnerRecord oldRecord = (TelmOwnerRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TelmOwnerTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmPayorRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmPayorRecord.java deleted file mode 100644 index 9deb2c6aae..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmPayorRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: TelmPayorRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// TelmPayor table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TelmPayorRecord extends DbRecord -{ - private String payor; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TelmPayorRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TelmPayorRecord(TelmPayorRecord origRecord) - { - setPayor(origRecord.getPayor()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a TelmPayor record - - //----------------------------------------------------------------- - public String getPayor() - { - return payor; - } - - public void setPayor(String payor) - { - this.payor = payor ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE payor = '" + payor + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPayor() + " " + - "" ; - return outString; - } // end toString() -} // end of TelmPayorRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmPayorTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmPayorTable.java deleted file mode 100644 index b69c0662e5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmPayorTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: TelmPayorTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// telmpayor table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TelmPayorTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TelmPayorTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TelmPayorTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("telmpayor"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TelmPayorRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TelmPayorRecord record = null; - - // create a List to hold TelmPayor Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telmpayor " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelmPayorRecord - // and store its address in oneRecord - record = new TelmPayorRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelmPayorRecord object - - record.setPayor(getString(rs, 1)); - - // add this TelmPayorRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TelmPayorRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TelmPayorRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TelmPayorRecord record = null; - - // create a List to hold TelmPayor Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telmpayor " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelmPayorRecord - // and store its address in oneRecord - record = new TelmPayorRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelmPayorRecord object - - record.setPayor(getString(rs, 1)); - - // add this TelmPayorRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TelmPayorRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TelmPayorRecord object and.. -//----------------------------------------------------------------- - public int insert(TelmPayorRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO telmpayor VALUES (? )"); - - setString(insertStatement, 1, record.getPayor()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telmpayor " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelmPayorRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelmPayorRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telmpayor SET payor = ? " + where ); - - setString(updateStatement, 1, record.getPayor()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TelmPayorRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telmpayor " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelmPayorRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelmPayorRecord oldRecord, TelmPayorRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telmpayor SET payor = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPayor()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TelmPayorRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TelmPayorRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TelmPayorRecord oldRecord = (TelmPayorRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TelmPayorTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmTypeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmTypeRecord.java deleted file mode 100644 index 45ad1f694f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmTypeRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: TelmTypeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// TelmType table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TelmTypeRecord extends DbRecord -{ - private String type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TelmTypeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TelmTypeRecord(TelmTypeRecord origRecord) - { - setType(origRecord.getType()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a TelmType record - - //----------------------------------------------------------------- - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE type = '" + type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getType() + " " + - "" ; - return outString; - } // end toString() -} // end of TelmTypeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmTypeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmTypeTable.java deleted file mode 100644 index 7e0b3fadf0..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TelmTypeTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: TelmTypeTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// telmtype table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TelmTypeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TelmTypeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TelmTypeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("telmtype"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TelmTypeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TelmTypeRecord record = null; - - // create a List to hold TelmType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telmtype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelmTypeRecord - // and store its address in oneRecord - record = new TelmTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelmTypeRecord object - - record.setType(getString(rs, 1)); - - // add this TelmTypeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TelmTypeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TelmTypeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TelmTypeRecord record = null; - - // create a List to hold TelmType Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM telmtype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TelmTypeRecord - // and store its address in oneRecord - record = new TelmTypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TelmTypeRecord object - - record.setType(getString(rs, 1)); - - // add this TelmTypeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TelmTypeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TelmTypeRecord object and.. -//----------------------------------------------------------------- - public int insert(TelmTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO telmtype VALUES (? )"); - - setString(insertStatement, 1, record.getType()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telmtype " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelmTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelmTypeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telmtype SET type = ? " + where ); - - setString(updateStatement, 1, record.getType()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TelmTypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM telmtype " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TelmTypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TelmTypeRecord oldRecord, TelmTypeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE telmtype SET type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getType()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TelmTypeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TelmTypeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TelmTypeRecord oldRecord = (TelmTypeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TelmTypeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TemperatureRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TemperatureRecord.java deleted file mode 100644 index bfda2c5f28..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TemperatureRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: TemperatureRecord.java -// author : DBGEN -// created : Tue May 31 17:52:17 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Temperature table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TemperatureRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TemperatureRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TemperatureRecord(TemperatureRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Temperature record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of TemperatureRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TemperatureTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TemperatureTable.java deleted file mode 100644 index c5b944342d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TemperatureTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: TemperatureTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// temperature table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TemperatureTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TemperatureTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TemperatureTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("temperature"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TemperatureRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TemperatureRecord record = null; - - // create a List to hold Temperature Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM temperature " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TemperatureRecord - // and store its address in oneRecord - record = new TemperatureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TemperatureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this TemperatureRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TemperatureRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TemperatureRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TemperatureRecord record = null; - - // create a List to hold Temperature Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM temperature " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TemperatureRecord - // and store its address in oneRecord - record = new TemperatureRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TemperatureRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this TemperatureRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TemperatureRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TemperatureRecord object and.. -//----------------------------------------------------------------- - public int insert(TemperatureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO temperature VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM temperature " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TemperatureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TemperatureRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE temperature SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TemperatureRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM temperature " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TemperatureRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TemperatureRecord oldRecord, TemperatureRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE temperature SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TemperatureRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TemperatureRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TemperatureRecord oldRecord = (TemperatureRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TemperatureTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TextProductRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TextProductRecord.java deleted file mode 100644 index 8ffe572189..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TextProductRecord.java +++ /dev/null @@ -1,141 +0,0 @@ -// filename: TextProductRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// TextProduct table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TextProductRecord extends DbRecord -{ - private String product_id; - - private long producttime; - - private long postingtime; - - private String prodtype; - - private int issnum; - - private String product; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TextProductRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TextProductRecord(TextProductRecord origRecord) - { - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - setProdtype(origRecord.getProdtype()); - setIssnum(origRecord.getIssnum()); - setProduct(origRecord.getProduct()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a TextProduct record - - //----------------------------------------------------------------- - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - - public String getProdtype() - { - return prodtype; - } - - public void setProdtype(String prodtype) - { - this.prodtype = prodtype ; - } - - public int getIssnum() - { - return issnum; - } - - public void setIssnum(int issnum) - { - this.issnum = issnum ; - } - - public String getProduct() - { - return product; - } - - public void setProduct(String product) - { - this.product = product ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE product_id = '" + product_id + "'" - + " AND producttime = '" + getDateTimeStringFromLongTime(producttime) + "'" - + " AND postingtime = '" + getDateTimeStringFromLongTime(postingtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - getProdtype() + " " + - getIssnum() + " " + - getProduct() + " " + - "" ; - return outString; - } // end toString() -} // end of TextProductRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TextProductTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TextProductTable.java deleted file mode 100644 index 585e59d073..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TextProductTable.java +++ /dev/null @@ -1,271 +0,0 @@ -// filename: TextProductTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// textproduct table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TextProductTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TextProductTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TextProductTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("textproduct"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TextProductRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TextProductRecord record = null; - - // create a List to hold TextProduct Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM textproduct " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TextProductRecord - // and store its address in oneRecord - record = new TextProductRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TextProductRecord object - - record.setProduct_id(getString(rs, 1)); - record.setProducttime(getTimeStamp(rs, 2)); - record.setPostingtime(getTimeStamp(rs, 3)); - record.setProdtype(getString(rs, 4)); - record.setIssnum(getInt(rs, 5)); - record.setProduct(getString(rs, 6)); - - // add this TextProductRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TextProductRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TextProductRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TextProductRecord record = null; - - // create a List to hold TextProduct Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM textproduct " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TextProductRecord - // and store its address in oneRecord - record = new TextProductRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TextProductRecord object - - record.setProduct_id(getString(rs, 1)); - record.setProducttime(getTimeStamp(rs, 2)); - record.setPostingtime(getTimeStamp(rs, 3)); - record.setProdtype(getString(rs, 4)); - record.setIssnum(getInt(rs, 5)); - record.setProduct(getString(rs, 6)); - - // add this TextProductRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TextProductRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TextProductRecord object and.. -//----------------------------------------------------------------- - public int insert(TextProductRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO textproduct VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getProduct_id()); - setTimeStamp(insertStatement, 2, record.getProducttime()); - setTimeStamp(insertStatement, 3, record.getPostingtime()); - setString(insertStatement, 4, record.getProdtype()); - setInt(insertStatement, 5, record.getIssnum()); - setString(insertStatement, 6, record.getProduct()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM textproduct " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TextProductRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TextProductRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE textproduct SET product_id = ?, producttime = ?, postingtime = ?, prodtype = ?, issnum = ?, product = ? " + where ); - - setString(updateStatement, 1, record.getProduct_id()); - setTimeStamp(updateStatement, 2, record.getProducttime()); - setTimeStamp(updateStatement, 3, record.getPostingtime()); - setString(updateStatement, 4, record.getProdtype()); - setInt(updateStatement, 5, record.getIssnum()); - setString(updateStatement, 6, record.getProduct()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TextProductRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM textproduct " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TextProductRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TextProductRecord oldRecord, TextProductRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE textproduct SET product_id = ?, producttime = ?, postingtime = ?, prodtype = ?, issnum = ?, product = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 2, newRecord.getProducttime()); - setTimeStamp(updateStatement, 3, newRecord.getPostingtime()); - setString(updateStatement, 4, newRecord.getProdtype()); - setInt(updateStatement, 5, newRecord.getIssnum()); - setString(updateStatement, 6, newRecord.getProduct()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TextProductRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TextProductRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TextProductRecord oldRecord = (TextProductRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TextProductTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TimeZoneRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TimeZoneRecord.java deleted file mode 100644 index 0e58351d07..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TimeZoneRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: TimeZoneRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// TimeZone table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class TimeZoneRecord extends DbRecord -{ - private String tzone; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public TimeZoneRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public TimeZoneRecord(TimeZoneRecord origRecord) - { - setTzone(origRecord.getTzone()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a TimeZone record - - //----------------------------------------------------------------- - public String getTzone() - { - return tzone; - } - - public void setTzone(String tzone) - { - this.tzone = tzone ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE tzone = '" + tzone + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getTzone() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of TimeZoneRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TimeZoneTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TimeZoneTable.java deleted file mode 100644 index 215ff939a3..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/TimeZoneTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: TimeZoneTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// timezone table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class TimeZoneTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// TimeZoneTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public TimeZoneTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("timezone"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of TimeZoneRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - TimeZoneRecord record = null; - - // create a List to hold TimeZone Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM timezone " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TimeZoneRecord - // and store its address in oneRecord - record = new TimeZoneRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TimeZoneRecord object - - record.setTzone(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this TimeZoneRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the TimeZoneRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of TimeZoneRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - TimeZoneRecord record = null; - - // create a List to hold TimeZone Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM timezone " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a TimeZoneRecord - // and store its address in oneRecord - record = new TimeZoneRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a TimeZoneRecord object - - record.setTzone(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this TimeZoneRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the TimeZoneRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a TimeZoneRecord object and.. -//----------------------------------------------------------------- - public int insert(TimeZoneRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO timezone VALUES (?, ? )"); - - setString(insertStatement, 1, record.getTzone()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM timezone " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TimeZoneRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TimeZoneRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE timezone SET tzone = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getTzone()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(TimeZoneRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM timezone " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a TimeZoneRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(TimeZoneRecord oldRecord, TimeZoneRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE timezone SET tzone = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getTzone()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a TimeZoneRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(TimeZoneRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - TimeZoneRecord oldRecord = (TimeZoneRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of TimeZoneTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnitGraphRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnitGraphRecord.java deleted file mode 100644 index 485a59be6a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnitGraphRecord.java +++ /dev/null @@ -1,143 +0,0 @@ -// filename: UnitGraphRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// UnitGraph table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class UnitGraphRecord extends DbRecord -{ - private String lid; - - private String area_id; - - private String model; - - private int dur; - - private int ordinal; - - private double discharge; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public UnitGraphRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public UnitGraphRecord(UnitGraphRecord origRecord) - { - setLid(origRecord.getLid()); - setArea_id(origRecord.getArea_id()); - setModel(origRecord.getModel()); - setDur(origRecord.getDur()); - setOrdinal(origRecord.getOrdinal()); - setDischarge(origRecord.getDischarge()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a UnitGraph record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getArea_id() - { - return area_id; - } - - public void setArea_id(String area_id) - { - this.area_id = area_id ; - } - - public String getModel() - { - return model; - } - - public void setModel(String model) - { - this.model = model ; - } - - public int getDur() - { - return dur; - } - - public void setDur(int dur) - { - this.dur = dur ; - } - - public int getOrdinal() - { - return ordinal; - } - - public void setOrdinal(int ordinal) - { - this.ordinal = ordinal ; - } - - public double getDischarge() - { - return discharge; - } - - public void setDischarge(double discharge) - { - this.discharge = discharge ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND area_id = '" + area_id + "'" - + " AND model = '" + model + "'" - + " AND dur = '" + dur + "'" - + " AND ordinal = '" + ordinal + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getArea_id() + " " + - getModel() + " " + - getDur() + " " + - getOrdinal() + " " + - getDischarge() + " " + - "" ; - return outString; - } // end toString() -} // end of UnitGraphRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnitGraphTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnitGraphTable.java deleted file mode 100644 index 1342a17e2e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnitGraphTable.java +++ /dev/null @@ -1,271 +0,0 @@ -// filename: UnitGraphTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// unitgraph table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class UnitGraphTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// UnitGraphTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public UnitGraphTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("unitgraph"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of UnitGraphRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - UnitGraphRecord record = null; - - // create a List to hold UnitGraph Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM unitgraph " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UnitGraphRecord - // and store its address in oneRecord - record = new UnitGraphRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UnitGraphRecord object - - record.setLid(getString(rs, 1)); - record.setArea_id(getString(rs, 2)); - record.setModel(getString(rs, 3)); - record.setDur(getInt(rs, 4)); - record.setOrdinal(getInt(rs, 5)); - record.setDischarge(getDouble(rs, 6)); - - // add this UnitGraphRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the UnitGraphRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of UnitGraphRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - UnitGraphRecord record = null; - - // create a List to hold UnitGraph Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM unitgraph " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UnitGraphRecord - // and store its address in oneRecord - record = new UnitGraphRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UnitGraphRecord object - - record.setLid(getString(rs, 1)); - record.setArea_id(getString(rs, 2)); - record.setModel(getString(rs, 3)); - record.setDur(getInt(rs, 4)); - record.setOrdinal(getInt(rs, 5)); - record.setDischarge(getDouble(rs, 6)); - - // add this UnitGraphRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the UnitGraphRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a UnitGraphRecord object and.. -//----------------------------------------------------------------- - public int insert(UnitGraphRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO unitgraph VALUES (?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getArea_id()); - setString(insertStatement, 3, record.getModel()); - setInt(insertStatement, 4, record.getDur()); - setInt(insertStatement, 5, record.getOrdinal()); - setDouble(insertStatement, 6, record.getDischarge()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM unitgraph " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UnitGraphRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UnitGraphRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE unitgraph SET lid = ?, area_id = ?, model = ?, dur = ?, ordinal = ?, discharge = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getArea_id()); - setString(updateStatement, 3, record.getModel()); - setInt(updateStatement, 4, record.getDur()); - setInt(updateStatement, 5, record.getOrdinal()); - setDouble(updateStatement, 6, record.getDischarge()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(UnitGraphRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM unitgraph " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UnitGraphRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UnitGraphRecord oldRecord, UnitGraphRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE unitgraph SET lid = ?, area_id = ?, model = ?, dur = ?, ordinal = ?, discharge = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getArea_id()); - setString(updateStatement, 3, newRecord.getModel()); - setInt(updateStatement, 4, newRecord.getDur()); - setInt(updateStatement, 5, newRecord.getOrdinal()); - setDouble(updateStatement, 6, newRecord.getDischarge()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a UnitGraphRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(UnitGraphRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - UnitGraphRecord oldRecord = (UnitGraphRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of UnitGraphTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnRecord.java deleted file mode 100644 index 4a622ee201..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -// filename: UnkStnRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// UnkStn table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class UnkStnRecord extends DbRecord -{ - private String lid; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public UnkStnRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public UnkStnRecord(UnkStnRecord origRecord) - { - setLid(origRecord.getLid()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a UnkStn record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of UnkStnRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnTable.java deleted file mode 100644 index f9fe7bc6d6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnTable.java +++ /dev/null @@ -1,261 +0,0 @@ -// filename: UnkStnTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// unkstn table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class UnkStnTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// UnkStnTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public UnkStnTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("unkstn"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of UnkStnRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - UnkStnRecord record = null; - - // create a List to hold UnkStn Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM unkstn " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UnkStnRecord - // and store its address in oneRecord - record = new UnkStnRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UnkStnRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - - // add this UnkStnRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the UnkStnRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of UnkStnRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - UnkStnRecord record = null; - - // create a List to hold UnkStn Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM unkstn " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UnkStnRecord - // and store its address in oneRecord - record = new UnkStnRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UnkStnRecord object - - record.setLid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setPostingtime(getTimeStamp(rs, 4)); - - // add this UnkStnRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the UnkStnRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a UnkStnRecord object and.. -//----------------------------------------------------------------- - public int insert(UnkStnRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO unkstn VALUES (?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getProduct_id()); - setTimeStamp(insertStatement, 3, record.getProducttime()); - setTimeStamp(insertStatement, 4, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM unkstn " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UnkStnRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UnkStnRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE unkstn SET lid = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getProduct_id()); - setTimeStamp(updateStatement, 3, record.getProducttime()); - setTimeStamp(updateStatement, 4, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(UnkStnRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM unkstn " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UnkStnRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UnkStnRecord oldRecord, UnkStnRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE unkstn SET lid = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 3, newRecord.getProducttime()); - setTimeStamp(updateStatement, 4, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a UnkStnRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(UnkStnRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - UnkStnRecord oldRecord = (UnkStnRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of UnkStnTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnValueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnValueRecord.java deleted file mode 100644 index ab5cfbe086..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnValueRecord.java +++ /dev/null @@ -1,228 +0,0 @@ -// filename: UnkStnValueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// UnkStnValue table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class UnkStnValueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private short revision; - - private String shef_qual_code; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public UnkStnValueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public UnkStnValueRecord(UnkStnValueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setRevision(origRecord.getRevision()); - setShef_qual_code(origRecord.getShef_qual_code()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a UnkStnValue record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getRevision() + " " + - getShef_qual_code() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of UnkStnValueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnValueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnValueTable.java deleted file mode 100644 index f1758fa0e2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UnkStnValueTable.java +++ /dev/null @@ -1,301 +0,0 @@ -// filename: UnkStnValueTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// unkstnvalue table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class UnkStnValueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// UnkStnValueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public UnkStnValueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("unkstnvalue"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of UnkStnValueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - UnkStnValueRecord record = null; - - // create a List to hold UnkStnValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM unkstnvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UnkStnValueRecord - // and store its address in oneRecord - record = new UnkStnValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UnkStnValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setRevision(getShort(rs, 8)); - record.setShef_qual_code(getString(rs, 9)); - record.setProduct_id(getString(rs, 10)); - record.setProducttime(getTimeStamp(rs, 11)); - record.setPostingtime(getTimeStamp(rs, 12)); - - // add this UnkStnValueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the UnkStnValueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of UnkStnValueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - UnkStnValueRecord record = null; - - // create a List to hold UnkStnValue Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM unkstnvalue " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UnkStnValueRecord - // and store its address in oneRecord - record = new UnkStnValueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UnkStnValueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setRevision(getShort(rs, 8)); - record.setShef_qual_code(getString(rs, 9)); - record.setProduct_id(getString(rs, 10)); - record.setProducttime(getTimeStamp(rs, 11)); - record.setPostingtime(getTimeStamp(rs, 12)); - - // add this UnkStnValueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the UnkStnValueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a UnkStnValueRecord object and.. -//----------------------------------------------------------------- - public int insert(UnkStnValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO unkstnvalue VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setShort(insertStatement, 8, record.getRevision()); - setString(insertStatement, 9, record.getShef_qual_code()); - setString(insertStatement, 10, record.getProduct_id()); - setTimeStamp(insertStatement, 11, record.getProducttime()); - setTimeStamp(insertStatement, 12, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM unkstnvalue " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UnkStnValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UnkStnValueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE unkstnvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, revision = ?, shef_qual_code = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setShort(updateStatement, 8, record.getRevision()); - setString(updateStatement, 9, record.getShef_qual_code()); - setString(updateStatement, 10, record.getProduct_id()); - setTimeStamp(updateStatement, 11, record.getProducttime()); - setTimeStamp(updateStatement, 12, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(UnkStnValueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM unkstnvalue " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UnkStnValueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UnkStnValueRecord oldRecord, UnkStnValueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE unkstnvalue SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, revision = ?, shef_qual_code = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setShort(updateStatement, 8, newRecord.getRevision()); - setString(updateStatement, 9, newRecord.getShef_qual_code()); - setString(updateStatement, 10, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 11, newRecord.getProducttime()); - setTimeStamp(updateStatement, 12, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a UnkStnValueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(UnkStnValueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - UnkStnValueRecord oldRecord = (UnkStnValueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of UnkStnValueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UserPrefsRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UserPrefsRecord.java deleted file mode 100644 index 99a45badbd..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UserPrefsRecord.java +++ /dev/null @@ -1,125 +0,0 @@ -// filename: UserPrefsRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// UserPrefs table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class UserPrefsRecord extends DbRecord -{ - private String userid; - - private int title; - - private int statlist; - - private int sortlist; - - private int fieldlist; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public UserPrefsRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public UserPrefsRecord(UserPrefsRecord origRecord) - { - setUserid(origRecord.getUserid()); - setTitle(origRecord.getTitle()); - setStatlist(origRecord.getStatlist()); - setSortlist(origRecord.getSortlist()); - setFieldlist(origRecord.getFieldlist()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a UserPrefs record - - //----------------------------------------------------------------- - public String getUserid() - { - return userid; - } - - public void setUserid(String userid) - { - this.userid = userid ; - } - - public int getTitle() - { - return title; - } - - public void setTitle(int title) - { - this.title = title ; - } - - public int getStatlist() - { - return statlist; - } - - public void setStatlist(int statlist) - { - this.statlist = statlist ; - } - - public int getSortlist() - { - return sortlist; - } - - public void setSortlist(int sortlist) - { - this.sortlist = sortlist ; - } - - public int getFieldlist() - { - return fieldlist; - } - - public void setFieldlist(int fieldlist) - { - this.fieldlist = fieldlist ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE userid = '" + userid + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getUserid() + " " + - getTitle() + " " + - getStatlist() + " " + - getSortlist() + " " + - getFieldlist() + " " + - "" ; - return outString; - } // end toString() -} // end of UserPrefsRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UserPrefsTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UserPrefsTable.java deleted file mode 100644 index 2fabd0b531..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/UserPrefsTable.java +++ /dev/null @@ -1,266 +0,0 @@ -// filename: UserPrefsTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// userprefs table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class UserPrefsTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// UserPrefsTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public UserPrefsTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("userprefs"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of UserPrefsRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - UserPrefsRecord record = null; - - // create a List to hold UserPrefs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM userprefs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UserPrefsRecord - // and store its address in oneRecord - record = new UserPrefsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UserPrefsRecord object - - record.setUserid(getString(rs, 1)); - record.setTitle(getInt(rs, 2)); - record.setStatlist(getInt(rs, 3)); - record.setSortlist(getInt(rs, 4)); - record.setFieldlist(getInt(rs, 5)); - - // add this UserPrefsRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the UserPrefsRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of UserPrefsRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - UserPrefsRecord record = null; - - // create a List to hold UserPrefs Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM userprefs " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a UserPrefsRecord - // and store its address in oneRecord - record = new UserPrefsRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a UserPrefsRecord object - - record.setUserid(getString(rs, 1)); - record.setTitle(getInt(rs, 2)); - record.setStatlist(getInt(rs, 3)); - record.setSortlist(getInt(rs, 4)); - record.setFieldlist(getInt(rs, 5)); - - // add this UserPrefsRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the UserPrefsRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a UserPrefsRecord object and.. -//----------------------------------------------------------------- - public int insert(UserPrefsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO userprefs VALUES (?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getUserid()); - setInt(insertStatement, 2, record.getTitle()); - setInt(insertStatement, 3, record.getStatlist()); - setInt(insertStatement, 4, record.getSortlist()); - setInt(insertStatement, 5, record.getFieldlist()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM userprefs " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UserPrefsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UserPrefsRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE userprefs SET userid = ?, title = ?, statlist = ?, sortlist = ?, fieldlist = ? " + where ); - - setString(updateStatement, 1, record.getUserid()); - setInt(updateStatement, 2, record.getTitle()); - setInt(updateStatement, 3, record.getStatlist()); - setInt(updateStatement, 4, record.getSortlist()); - setInt(updateStatement, 5, record.getFieldlist()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(UserPrefsRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM userprefs " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a UserPrefsRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(UserPrefsRecord oldRecord, UserPrefsRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE userprefs SET userid = ?, title = ?, statlist = ?, sortlist = ?, fieldlist = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getUserid()); - setInt(updateStatement, 2, newRecord.getTitle()); - setInt(updateStatement, 3, newRecord.getStatlist()); - setInt(updateStatement, 4, newRecord.getSortlist()); - setInt(updateStatement, 5, newRecord.getFieldlist()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a UserPrefsRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(UserPrefsRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - UserPrefsRecord oldRecord = (UserPrefsRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of UserPrefsTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECactionRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECactionRecord.java deleted file mode 100644 index 4f1f25790e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECactionRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: VTECactionRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECaction table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECactionRecord extends DbRecord -{ - private String action; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECactionRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECactionRecord(VTECactionRecord origRecord) - { - setAction(origRecord.getAction()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECaction record - - //----------------------------------------------------------------- - public String getAction() - { - return action; - } - - public void setAction(String action) - { - this.action = action ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE action = '" + action + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getAction() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of VTECactionRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECactionTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECactionTable.java deleted file mode 100644 index cb75409b0e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECactionTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: VTECactionTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecaction table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECactionTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECactionTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECactionTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecaction"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECactionRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECactionRecord record = null; - - // create a List to hold VTECaction Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecaction " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECactionRecord - // and store its address in oneRecord - record = new VTECactionRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECactionRecord object - - record.setAction(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECactionRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECactionRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECactionRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECactionRecord record = null; - - // create a List to hold VTECaction Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecaction " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECactionRecord - // and store its address in oneRecord - record = new VTECactionRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECactionRecord object - - record.setAction(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECactionRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECactionRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECactionRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECactionRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecaction VALUES (?, ? )"); - - setString(insertStatement, 1, record.getAction()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecaction " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECactionRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECactionRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecaction SET action = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getAction()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECactionRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecaction " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECactionRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECactionRecord oldRecord, VTECactionRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecaction SET action = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getAction()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECactionRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECactionRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECactionRecord oldRecord = (VTECactionRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECactionTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECcauseRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECcauseRecord.java deleted file mode 100644 index a260c58072..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECcauseRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: VTECcauseRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECcause table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECcauseRecord extends DbRecord -{ - private String immed_cause; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECcauseRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECcauseRecord(VTECcauseRecord origRecord) - { - setImmed_cause(origRecord.getImmed_cause()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECcause record - - //----------------------------------------------------------------- - public String getImmed_cause() - { - return immed_cause; - } - - public void setImmed_cause(String immed_cause) - { - this.immed_cause = immed_cause ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE immed_cause = '" + immed_cause + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getImmed_cause() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of VTECcauseRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECcauseTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECcauseTable.java deleted file mode 100644 index 7079f43955..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECcauseTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: VTECcauseTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vteccause table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECcauseTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECcauseTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECcauseTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vteccause"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECcauseRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECcauseRecord record = null; - - // create a List to hold VTECcause Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vteccause " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECcauseRecord - // and store its address in oneRecord - record = new VTECcauseRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECcauseRecord object - - record.setImmed_cause(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECcauseRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECcauseRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECcauseRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECcauseRecord record = null; - - // create a List to hold VTECcause Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vteccause " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECcauseRecord - // and store its address in oneRecord - record = new VTECcauseRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECcauseRecord object - - record.setImmed_cause(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECcauseRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECcauseRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECcauseRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECcauseRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vteccause VALUES (?, ? )"); - - setString(insertStatement, 1, record.getImmed_cause()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vteccause " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECcauseRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECcauseRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vteccause SET immed_cause = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getImmed_cause()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECcauseRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vteccause " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECcauseRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECcauseRecord oldRecord, VTECcauseRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vteccause SET immed_cause = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getImmed_cause()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECcauseRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECcauseRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECcauseRecord oldRecord = (VTECcauseRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECcauseTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECeventRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECeventRecord.java deleted file mode 100644 index 387324132b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECeventRecord.java +++ /dev/null @@ -1,365 +0,0 @@ -// filename: VTECeventRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECevent table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECeventRecord extends DbRecord -{ - private String geoid; - - private String product_id; - - private long producttime; - - private String productmode; - - private String action; - - private String office_id; - - private String phenom; - - private String signif; - - private short etn; - - private long begintime; - - private long endtime; - - private String severity; - - private String immed_cause; - - private long risetime; - - private long cresttime; - - private long falltime; - - private String record; - - private String risets; - - private String crests; - - private String fallts; - - private double crest_value; - - private long expiretime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECeventRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECeventRecord(VTECeventRecord origRecord) - { - setGeoid(origRecord.getGeoid()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setProductmode(origRecord.getProductmode()); - setAction(origRecord.getAction()); - setOffice_id(origRecord.getOffice_id()); - setPhenom(origRecord.getPhenom()); - setSignif(origRecord.getSignif()); - setEtn(origRecord.getEtn()); - setBegintime(origRecord.getBegintime()); - setEndtime(origRecord.getEndtime()); - setSeverity(origRecord.getSeverity()); - setImmed_cause(origRecord.getImmed_cause()); - setRisetime(origRecord.getRisetime()); - setCresttime(origRecord.getCresttime()); - setFalltime(origRecord.getFalltime()); - setRecord(origRecord.getRecord()); - setRisets(origRecord.getRisets()); - setCrests(origRecord.getCrests()); - setFallts(origRecord.getFallts()); - setCrest_value(origRecord.getCrest_value()); - setExpiretime(origRecord.getExpiretime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECevent record - - //----------------------------------------------------------------- - public String getGeoid() - { - return geoid; - } - - public void setGeoid(String geoid) - { - this.geoid = geoid ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public String getProductmode() - { - return productmode; - } - - public void setProductmode(String productmode) - { - this.productmode = productmode ; - } - - public String getAction() - { - return action; - } - - public void setAction(String action) - { - this.action = action ; - } - - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - - public String getPhenom() - { - return phenom; - } - - public void setPhenom(String phenom) - { - this.phenom = phenom ; - } - - public String getSignif() - { - return signif; - } - - public void setSignif(String signif) - { - this.signif = signif ; - } - - public short getEtn() - { - return etn; - } - - public void setEtn(short etn) - { - this.etn = etn ; - } - - public long getBegintime() - { - return begintime; - } - - public void setBegintime(long begintime) - { - this.begintime = begintime ; - } - - public long getEndtime() - { - return endtime; - } - - public void setEndtime(long endtime) - { - this.endtime = endtime ; - } - - public String getSeverity() - { - return severity; - } - - public void setSeverity(String severity) - { - this.severity = severity ; - } - - public String getImmed_cause() - { - return immed_cause; - } - - public void setImmed_cause(String immed_cause) - { - this.immed_cause = immed_cause ; - } - - public long getRisetime() - { - return risetime; - } - - public void setRisetime(long risetime) - { - this.risetime = risetime ; - } - - public long getCresttime() - { - return cresttime; - } - - public void setCresttime(long cresttime) - { - this.cresttime = cresttime ; - } - - public long getFalltime() - { - return falltime; - } - - public void setFalltime(long falltime) - { - this.falltime = falltime ; - } - - public String getRecord() - { - return record; - } - - public void setRecord(String record) - { - this.record = record ; - } - - public String getRisets() - { - return risets; - } - - public void setRisets(String risets) - { - this.risets = risets ; - } - - public String getCrests() - { - return crests; - } - - public void setCrests(String crests) - { - this.crests = crests ; - } - - public String getFallts() - { - return fallts; - } - - public void setFallts(String fallts) - { - this.fallts = fallts ; - } - - public double getCrest_value() - { - return crest_value; - } - - public void setCrest_value(double crest_value) - { - this.crest_value = crest_value ; - } - - public long getExpiretime() - { - return expiretime; - } - - public void setExpiretime(long expiretime) - { - this.expiretime = expiretime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE geoid = '" + geoid + "'" - + " AND product_id = '" + product_id + "'" - + " AND producttime = '" + getDateTimeStringFromLongTime(producttime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getGeoid() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getProductmode() + " " + - getAction() + " " + - getOffice_id() + " " + - getPhenom() + " " + - getSignif() + " " + - getEtn() + " " + - getDateTimeStringFromLongTime(getBegintime()) + " " + - getDateTimeStringFromLongTime(getEndtime()) + " " + - getSeverity() + " " + - getImmed_cause() + " " + - getDateTimeStringFromLongTime(getRisetime()) + " " + - getDateTimeStringFromLongTime(getCresttime()) + " " + - getDateTimeStringFromLongTime(getFalltime()) + " " + - getRecord() + " " + - getRisets() + " " + - getCrests() + " " + - getFallts() + " " + - getCrest_value() + " " + - getDateTimeStringFromLongTime(getExpiretime()) + " " + - "" ; - return outString; - } // end toString() -} // end of VTECeventRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECeventTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECeventTable.java deleted file mode 100644 index 0f09705bce..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECeventTable.java +++ /dev/null @@ -1,351 +0,0 @@ -// filename: VTECeventTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecevent table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECeventTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECeventTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECeventTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecevent"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECeventRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECeventRecord record = null; - - // create a List to hold VTECevent Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecevent " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECeventRecord - // and store its address in oneRecord - record = new VTECeventRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECeventRecord object - - record.setGeoid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setProductmode(getString(rs, 4)); - record.setAction(getString(rs, 5)); - record.setOffice_id(getString(rs, 6)); - record.setPhenom(getString(rs, 7)); - record.setSignif(getString(rs, 8)); - record.setEtn(getShort(rs, 9)); - record.setBegintime(getTimeStamp(rs, 10)); - record.setEndtime(getTimeStamp(rs, 11)); - record.setSeverity(getString(rs, 12)); - record.setImmed_cause(getString(rs, 13)); - record.setRisetime(getTimeStamp(rs, 14)); - record.setCresttime(getTimeStamp(rs, 15)); - record.setFalltime(getTimeStamp(rs, 16)); - record.setRecord(getString(rs, 17)); - record.setRisets(getString(rs, 18)); - record.setCrests(getString(rs, 19)); - record.setFallts(getString(rs, 20)); - record.setCrest_value(getDouble(rs, 21)); - record.setExpiretime(getTimeStamp(rs, 22)); - - // add this VTECeventRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECeventRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECeventRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECeventRecord record = null; - - // create a List to hold VTECevent Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecevent " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECeventRecord - // and store its address in oneRecord - record = new VTECeventRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECeventRecord object - - record.setGeoid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setProductmode(getString(rs, 4)); - record.setAction(getString(rs, 5)); - record.setOffice_id(getString(rs, 6)); - record.setPhenom(getString(rs, 7)); - record.setSignif(getString(rs, 8)); - record.setEtn(getShort(rs, 9)); - record.setBegintime(getTimeStamp(rs, 10)); - record.setEndtime(getTimeStamp(rs, 11)); - record.setSeverity(getString(rs, 12)); - record.setImmed_cause(getString(rs, 13)); - record.setRisetime(getTimeStamp(rs, 14)); - record.setCresttime(getTimeStamp(rs, 15)); - record.setFalltime(getTimeStamp(rs, 16)); - record.setRecord(getString(rs, 17)); - record.setRisets(getString(rs, 18)); - record.setCrests(getString(rs, 19)); - record.setFallts(getString(rs, 20)); - record.setCrest_value(getDouble(rs, 21)); - record.setExpiretime(getTimeStamp(rs, 22)); - - // add this VTECeventRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECeventRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECeventRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECeventRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecevent VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getGeoid()); - setString(insertStatement, 2, record.getProduct_id()); - setTimeStamp(insertStatement, 3, record.getProducttime()); - setString(insertStatement, 4, record.getProductmode()); - setString(insertStatement, 5, record.getAction()); - setString(insertStatement, 6, record.getOffice_id()); - setString(insertStatement, 7, record.getPhenom()); - setString(insertStatement, 8, record.getSignif()); - setShort(insertStatement, 9, record.getEtn()); - setTimeStamp(insertStatement, 10, record.getBegintime()); - setTimeStamp(insertStatement, 11, record.getEndtime()); - setString(insertStatement, 12, record.getSeverity()); - setString(insertStatement, 13, record.getImmed_cause()); - setTimeStamp(insertStatement, 14, record.getRisetime()); - setTimeStamp(insertStatement, 15, record.getCresttime()); - setTimeStamp(insertStatement, 16, record.getFalltime()); - setString(insertStatement, 17, record.getRecord()); - setString(insertStatement, 18, record.getRisets()); - setString(insertStatement, 19, record.getCrests()); - setString(insertStatement, 20, record.getFallts()); - setDouble(insertStatement, 21, record.getCrest_value()); - setTimeStamp(insertStatement, 22, record.getExpiretime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecevent " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECeventRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECeventRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecevent SET geoid = ?, product_id = ?, producttime = ?, productmode = ?, action = ?, office_id = ?, phenom = ?, signif = ?, etn = ?, begintime = ?, endtime = ?, severity = ?, immed_cause = ?, risetime = ?, cresttime = ?, falltime = ?, record = ?, risets = ?, crests = ?, fallts = ?, crest_value = ?, expiretime = ? " + where ); - - setString(updateStatement, 1, record.getGeoid()); - setString(updateStatement, 2, record.getProduct_id()); - setTimeStamp(updateStatement, 3, record.getProducttime()); - setString(updateStatement, 4, record.getProductmode()); - setString(updateStatement, 5, record.getAction()); - setString(updateStatement, 6, record.getOffice_id()); - setString(updateStatement, 7, record.getPhenom()); - setString(updateStatement, 8, record.getSignif()); - setShort(updateStatement, 9, record.getEtn()); - setTimeStamp(updateStatement, 10, record.getBegintime()); - setTimeStamp(updateStatement, 11, record.getEndtime()); - setString(updateStatement, 12, record.getSeverity()); - setString(updateStatement, 13, record.getImmed_cause()); - setTimeStamp(updateStatement, 14, record.getRisetime()); - setTimeStamp(updateStatement, 15, record.getCresttime()); - setTimeStamp(updateStatement, 16, record.getFalltime()); - setString(updateStatement, 17, record.getRecord()); - setString(updateStatement, 18, record.getRisets()); - setString(updateStatement, 19, record.getCrests()); - setString(updateStatement, 20, record.getFallts()); - setDouble(updateStatement, 21, record.getCrest_value()); - setTimeStamp(updateStatement, 22, record.getExpiretime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECeventRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecevent " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECeventRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECeventRecord oldRecord, VTECeventRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecevent SET geoid = ?, product_id = ?, producttime = ?, productmode = ?, action = ?, office_id = ?, phenom = ?, signif = ?, etn = ?, begintime = ?, endtime = ?, severity = ?, immed_cause = ?, risetime = ?, cresttime = ?, falltime = ?, record = ?, risets = ?, crests = ?, fallts = ?, crest_value = ?, expiretime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getGeoid()); - setString(updateStatement, 2, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 3, newRecord.getProducttime()); - setString(updateStatement, 4, newRecord.getProductmode()); - setString(updateStatement, 5, newRecord.getAction()); - setString(updateStatement, 6, newRecord.getOffice_id()); - setString(updateStatement, 7, newRecord.getPhenom()); - setString(updateStatement, 8, newRecord.getSignif()); - setShort(updateStatement, 9, newRecord.getEtn()); - setTimeStamp(updateStatement, 10, newRecord.getBegintime()); - setTimeStamp(updateStatement, 11, newRecord.getEndtime()); - setString(updateStatement, 12, newRecord.getSeverity()); - setString(updateStatement, 13, newRecord.getImmed_cause()); - setTimeStamp(updateStatement, 14, newRecord.getRisetime()); - setTimeStamp(updateStatement, 15, newRecord.getCresttime()); - setTimeStamp(updateStatement, 16, newRecord.getFalltime()); - setString(updateStatement, 17, newRecord.getRecord()); - setString(updateStatement, 18, newRecord.getRisets()); - setString(updateStatement, 19, newRecord.getCrests()); - setString(updateStatement, 20, newRecord.getFallts()); - setDouble(updateStatement, 21, newRecord.getCrest_value()); - setTimeStamp(updateStatement, 22, newRecord.getExpiretime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECeventRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECeventRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECeventRecord oldRecord = (VTECeventRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECeventTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECphenomRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECphenomRecord.java deleted file mode 100644 index 944970d896..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECphenomRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: VTECphenomRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECphenom table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECphenomRecord extends DbRecord -{ - private String phenom; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECphenomRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECphenomRecord(VTECphenomRecord origRecord) - { - setPhenom(origRecord.getPhenom()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECphenom record - - //----------------------------------------------------------------- - public String getPhenom() - { - return phenom; - } - - public void setPhenom(String phenom) - { - this.phenom = phenom ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE phenom = '" + phenom + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getPhenom() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of VTECphenomRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECphenomTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECphenomTable.java deleted file mode 100644 index 846baf6a42..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECphenomTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: VTECphenomTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecphenom table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECphenomTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECphenomTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECphenomTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecphenom"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECphenomRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECphenomRecord record = null; - - // create a List to hold VTECphenom Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecphenom " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECphenomRecord - // and store its address in oneRecord - record = new VTECphenomRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECphenomRecord object - - record.setPhenom(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECphenomRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECphenomRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECphenomRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECphenomRecord record = null; - - // create a List to hold VTECphenom Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecphenom " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECphenomRecord - // and store its address in oneRecord - record = new VTECphenomRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECphenomRecord object - - record.setPhenom(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECphenomRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECphenomRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECphenomRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECphenomRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecphenom VALUES (?, ? )"); - - setString(insertStatement, 1, record.getPhenom()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecphenom " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECphenomRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECphenomRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecphenom SET phenom = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getPhenom()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECphenomRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecphenom " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECphenomRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECphenomRecord oldRecord, VTECphenomRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecphenom SET phenom = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getPhenom()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECphenomRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECphenomRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECphenomRecord oldRecord = (VTECphenomRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECphenomTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECpracticeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECpracticeRecord.java deleted file mode 100644 index ecee8646c9..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECpracticeRecord.java +++ /dev/null @@ -1,365 +0,0 @@ -// filename: VTECpracticeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECpractice table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECpracticeRecord extends DbRecord -{ - private String geoid; - - private String product_id; - - private long producttime; - - private String productmode; - - private String action; - - private String office_id; - - private String phenom; - - private String signif; - - private short etn; - - private long begintime; - - private long endtime; - - private String severity; - - private String immed_cause; - - private long risetime; - - private long cresttime; - - private long falltime; - - private String record; - - private String risets; - - private String crests; - - private String fallts; - - private double crest_value; - - private long expiretime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECpracticeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECpracticeRecord(VTECpracticeRecord origRecord) - { - setGeoid(origRecord.getGeoid()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setProductmode(origRecord.getProductmode()); - setAction(origRecord.getAction()); - setOffice_id(origRecord.getOffice_id()); - setPhenom(origRecord.getPhenom()); - setSignif(origRecord.getSignif()); - setEtn(origRecord.getEtn()); - setBegintime(origRecord.getBegintime()); - setEndtime(origRecord.getEndtime()); - setSeverity(origRecord.getSeverity()); - setImmed_cause(origRecord.getImmed_cause()); - setRisetime(origRecord.getRisetime()); - setCresttime(origRecord.getCresttime()); - setFalltime(origRecord.getFalltime()); - setRecord(origRecord.getRecord()); - setRisets(origRecord.getRisets()); - setCrests(origRecord.getCrests()); - setFallts(origRecord.getFallts()); - setCrest_value(origRecord.getCrest_value()); - setExpiretime(origRecord.getExpiretime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECpractice record - - //----------------------------------------------------------------- - public String getGeoid() - { - return geoid; - } - - public void setGeoid(String geoid) - { - this.geoid = geoid ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public String getProductmode() - { - return productmode; - } - - public void setProductmode(String productmode) - { - this.productmode = productmode ; - } - - public String getAction() - { - return action; - } - - public void setAction(String action) - { - this.action = action ; - } - - public String getOffice_id() - { - return office_id; - } - - public void setOffice_id(String office_id) - { - this.office_id = office_id ; - } - - public String getPhenom() - { - return phenom; - } - - public void setPhenom(String phenom) - { - this.phenom = phenom ; - } - - public String getSignif() - { - return signif; - } - - public void setSignif(String signif) - { - this.signif = signif ; - } - - public short getEtn() - { - return etn; - } - - public void setEtn(short etn) - { - this.etn = etn ; - } - - public long getBegintime() - { - return begintime; - } - - public void setBegintime(long begintime) - { - this.begintime = begintime ; - } - - public long getEndtime() - { - return endtime; - } - - public void setEndtime(long endtime) - { - this.endtime = endtime ; - } - - public String getSeverity() - { - return severity; - } - - public void setSeverity(String severity) - { - this.severity = severity ; - } - - public String getImmed_cause() - { - return immed_cause; - } - - public void setImmed_cause(String immed_cause) - { - this.immed_cause = immed_cause ; - } - - public long getRisetime() - { - return risetime; - } - - public void setRisetime(long risetime) - { - this.risetime = risetime ; - } - - public long getCresttime() - { - return cresttime; - } - - public void setCresttime(long cresttime) - { - this.cresttime = cresttime ; - } - - public long getFalltime() - { - return falltime; - } - - public void setFalltime(long falltime) - { - this.falltime = falltime ; - } - - public String getRecord() - { - return record; - } - - public void setRecord(String record) - { - this.record = record ; - } - - public String getRisets() - { - return risets; - } - - public void setRisets(String risets) - { - this.risets = risets ; - } - - public String getCrests() - { - return crests; - } - - public void setCrests(String crests) - { - this.crests = crests ; - } - - public String getFallts() - { - return fallts; - } - - public void setFallts(String fallts) - { - this.fallts = fallts ; - } - - public double getCrest_value() - { - return crest_value; - } - - public void setCrest_value(double crest_value) - { - this.crest_value = crest_value ; - } - - public long getExpiretime() - { - return expiretime; - } - - public void setExpiretime(long expiretime) - { - this.expiretime = expiretime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE geoid = '" + geoid + "'" - + " AND product_id = '" + product_id + "'" - + " AND producttime = '" + getDateTimeStringFromLongTime(producttime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getGeoid() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getProductmode() + " " + - getAction() + " " + - getOffice_id() + " " + - getPhenom() + " " + - getSignif() + " " + - getEtn() + " " + - getDateTimeStringFromLongTime(getBegintime()) + " " + - getDateTimeStringFromLongTime(getEndtime()) + " " + - getSeverity() + " " + - getImmed_cause() + " " + - getDateTimeStringFromLongTime(getRisetime()) + " " + - getDateTimeStringFromLongTime(getCresttime()) + " " + - getDateTimeStringFromLongTime(getFalltime()) + " " + - getRecord() + " " + - getRisets() + " " + - getCrests() + " " + - getFallts() + " " + - getCrest_value() + " " + - getDateTimeStringFromLongTime(getExpiretime()) + " " + - "" ; - return outString; - } // end toString() -} // end of VTECpracticeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECpracticeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECpracticeTable.java deleted file mode 100644 index 27c57cbfd6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECpracticeTable.java +++ /dev/null @@ -1,351 +0,0 @@ -// filename: VTECpracticeTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecpractice table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECpracticeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECpracticeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECpracticeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecpractice"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECpracticeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECpracticeRecord record = null; - - // create a List to hold VTECpractice Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecpractice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECpracticeRecord - // and store its address in oneRecord - record = new VTECpracticeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECpracticeRecord object - - record.setGeoid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setProductmode(getString(rs, 4)); - record.setAction(getString(rs, 5)); - record.setOffice_id(getString(rs, 6)); - record.setPhenom(getString(rs, 7)); - record.setSignif(getString(rs, 8)); - record.setEtn(getShort(rs, 9)); - record.setBegintime(getTimeStamp(rs, 10)); - record.setEndtime(getTimeStamp(rs, 11)); - record.setSeverity(getString(rs, 12)); - record.setImmed_cause(getString(rs, 13)); - record.setRisetime(getTimeStamp(rs, 14)); - record.setCresttime(getTimeStamp(rs, 15)); - record.setFalltime(getTimeStamp(rs, 16)); - record.setRecord(getString(rs, 17)); - record.setRisets(getString(rs, 18)); - record.setCrests(getString(rs, 19)); - record.setFallts(getString(rs, 20)); - record.setCrest_value(getDouble(rs, 21)); - record.setExpiretime(getTimeStamp(rs, 22)); - - // add this VTECpracticeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECpracticeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECpracticeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECpracticeRecord record = null; - - // create a List to hold VTECpractice Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecpractice " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECpracticeRecord - // and store its address in oneRecord - record = new VTECpracticeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECpracticeRecord object - - record.setGeoid(getString(rs, 1)); - record.setProduct_id(getString(rs, 2)); - record.setProducttime(getTimeStamp(rs, 3)); - record.setProductmode(getString(rs, 4)); - record.setAction(getString(rs, 5)); - record.setOffice_id(getString(rs, 6)); - record.setPhenom(getString(rs, 7)); - record.setSignif(getString(rs, 8)); - record.setEtn(getShort(rs, 9)); - record.setBegintime(getTimeStamp(rs, 10)); - record.setEndtime(getTimeStamp(rs, 11)); - record.setSeverity(getString(rs, 12)); - record.setImmed_cause(getString(rs, 13)); - record.setRisetime(getTimeStamp(rs, 14)); - record.setCresttime(getTimeStamp(rs, 15)); - record.setFalltime(getTimeStamp(rs, 16)); - record.setRecord(getString(rs, 17)); - record.setRisets(getString(rs, 18)); - record.setCrests(getString(rs, 19)); - record.setFallts(getString(rs, 20)); - record.setCrest_value(getDouble(rs, 21)); - record.setExpiretime(getTimeStamp(rs, 22)); - - // add this VTECpracticeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECpracticeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECpracticeRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECpracticeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecpractice VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getGeoid()); - setString(insertStatement, 2, record.getProduct_id()); - setTimeStamp(insertStatement, 3, record.getProducttime()); - setString(insertStatement, 4, record.getProductmode()); - setString(insertStatement, 5, record.getAction()); - setString(insertStatement, 6, record.getOffice_id()); - setString(insertStatement, 7, record.getPhenom()); - setString(insertStatement, 8, record.getSignif()); - setShort(insertStatement, 9, record.getEtn()); - setTimeStamp(insertStatement, 10, record.getBegintime()); - setTimeStamp(insertStatement, 11, record.getEndtime()); - setString(insertStatement, 12, record.getSeverity()); - setString(insertStatement, 13, record.getImmed_cause()); - setTimeStamp(insertStatement, 14, record.getRisetime()); - setTimeStamp(insertStatement, 15, record.getCresttime()); - setTimeStamp(insertStatement, 16, record.getFalltime()); - setString(insertStatement, 17, record.getRecord()); - setString(insertStatement, 18, record.getRisets()); - setString(insertStatement, 19, record.getCrests()); - setString(insertStatement, 20, record.getFallts()); - setDouble(insertStatement, 21, record.getCrest_value()); - setTimeStamp(insertStatement, 22, record.getExpiretime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecpractice " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECpracticeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECpracticeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecpractice SET geoid = ?, product_id = ?, producttime = ?, productmode = ?, action = ?, office_id = ?, phenom = ?, signif = ?, etn = ?, begintime = ?, endtime = ?, severity = ?, immed_cause = ?, risetime = ?, cresttime = ?, falltime = ?, record = ?, risets = ?, crests = ?, fallts = ?, crest_value = ?, expiretime = ? " + where ); - - setString(updateStatement, 1, record.getGeoid()); - setString(updateStatement, 2, record.getProduct_id()); - setTimeStamp(updateStatement, 3, record.getProducttime()); - setString(updateStatement, 4, record.getProductmode()); - setString(updateStatement, 5, record.getAction()); - setString(updateStatement, 6, record.getOffice_id()); - setString(updateStatement, 7, record.getPhenom()); - setString(updateStatement, 8, record.getSignif()); - setShort(updateStatement, 9, record.getEtn()); - setTimeStamp(updateStatement, 10, record.getBegintime()); - setTimeStamp(updateStatement, 11, record.getEndtime()); - setString(updateStatement, 12, record.getSeverity()); - setString(updateStatement, 13, record.getImmed_cause()); - setTimeStamp(updateStatement, 14, record.getRisetime()); - setTimeStamp(updateStatement, 15, record.getCresttime()); - setTimeStamp(updateStatement, 16, record.getFalltime()); - setString(updateStatement, 17, record.getRecord()); - setString(updateStatement, 18, record.getRisets()); - setString(updateStatement, 19, record.getCrests()); - setString(updateStatement, 20, record.getFallts()); - setDouble(updateStatement, 21, record.getCrest_value()); - setTimeStamp(updateStatement, 22, record.getExpiretime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECpracticeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecpractice " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECpracticeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECpracticeRecord oldRecord, VTECpracticeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecpractice SET geoid = ?, product_id = ?, producttime = ?, productmode = ?, action = ?, office_id = ?, phenom = ?, signif = ?, etn = ?, begintime = ?, endtime = ?, severity = ?, immed_cause = ?, risetime = ?, cresttime = ?, falltime = ?, record = ?, risets = ?, crests = ?, fallts = ?, crest_value = ?, expiretime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getGeoid()); - setString(updateStatement, 2, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 3, newRecord.getProducttime()); - setString(updateStatement, 4, newRecord.getProductmode()); - setString(updateStatement, 5, newRecord.getAction()); - setString(updateStatement, 6, newRecord.getOffice_id()); - setString(updateStatement, 7, newRecord.getPhenom()); - setString(updateStatement, 8, newRecord.getSignif()); - setShort(updateStatement, 9, newRecord.getEtn()); - setTimeStamp(updateStatement, 10, newRecord.getBegintime()); - setTimeStamp(updateStatement, 11, newRecord.getEndtime()); - setString(updateStatement, 12, newRecord.getSeverity()); - setString(updateStatement, 13, newRecord.getImmed_cause()); - setTimeStamp(updateStatement, 14, newRecord.getRisetime()); - setTimeStamp(updateStatement, 15, newRecord.getCresttime()); - setTimeStamp(updateStatement, 16, newRecord.getFalltime()); - setString(updateStatement, 17, newRecord.getRecord()); - setString(updateStatement, 18, newRecord.getRisets()); - setString(updateStatement, 19, newRecord.getCrests()); - setString(updateStatement, 20, newRecord.getFallts()); - setDouble(updateStatement, 21, newRecord.getCrest_value()); - setTimeStamp(updateStatement, 22, newRecord.getExpiretime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECpracticeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECpracticeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECpracticeRecord oldRecord = (VTECpracticeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECpracticeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECrecordRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECrecordRecord.java deleted file mode 100644 index 30e8194002..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECrecordRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: VTECrecordRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECrecord table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECrecordRecord extends DbRecord -{ - private String record; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECrecordRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECrecordRecord(VTECrecordRecord origRecord) - { - setRecord(origRecord.getRecord()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECrecord record - - //----------------------------------------------------------------- - public String getRecord() - { - return record; - } - - public void setRecord(String record) - { - this.record = record ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE record = '" + record + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRecord() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of VTECrecordRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECrecordTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECrecordTable.java deleted file mode 100644 index de735ed001..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECrecordTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: VTECrecordTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecrecord table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECrecordTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECrecordTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECrecordTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecrecord"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECrecordRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECrecordRecord record = null; - - // create a List to hold VTECrecord Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecrecord " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECrecordRecord - // and store its address in oneRecord - record = new VTECrecordRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECrecordRecord object - - record.setRecord(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECrecordRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECrecordRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECrecordRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECrecordRecord record = null; - - // create a List to hold VTECrecord Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecrecord " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECrecordRecord - // and store its address in oneRecord - record = new VTECrecordRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECrecordRecord object - - record.setRecord(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECrecordRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECrecordRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECrecordRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECrecordRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecrecord VALUES (?, ? )"); - - setString(insertStatement, 1, record.getRecord()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecrecord " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECrecordRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECrecordRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecrecord SET record = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getRecord()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECrecordRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecrecord " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECrecordRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECrecordRecord oldRecord, VTECrecordRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecrecord SET record = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRecord()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECrecordRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECrecordRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECrecordRecord oldRecord = (VTECrecordRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECrecordTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECseverRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECseverRecord.java deleted file mode 100644 index a204a76c5f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECseverRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: VTECseverRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECsever table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECseverRecord extends DbRecord -{ - private String severity; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECseverRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECseverRecord(VTECseverRecord origRecord) - { - setSeverity(origRecord.getSeverity()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECsever record - - //----------------------------------------------------------------- - public String getSeverity() - { - return severity; - } - - public void setSeverity(String severity) - { - this.severity = severity ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE severity = '" + severity + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getSeverity() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of VTECseverRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECseverTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECseverTable.java deleted file mode 100644 index 1dfd98c335..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECseverTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: VTECseverTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecsever table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECseverTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECseverTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECseverTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecsever"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECseverRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECseverRecord record = null; - - // create a List to hold VTECsever Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecsever " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECseverRecord - // and store its address in oneRecord - record = new VTECseverRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECseverRecord object - - record.setSeverity(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECseverRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECseverRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECseverRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECseverRecord record = null; - - // create a List to hold VTECsever Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecsever " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECseverRecord - // and store its address in oneRecord - record = new VTECseverRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECseverRecord object - - record.setSeverity(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECseverRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECseverRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECseverRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECseverRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecsever VALUES (?, ? )"); - - setString(insertStatement, 1, record.getSeverity()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecsever " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECseverRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECseverRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecsever SET severity = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getSeverity()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECseverRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecsever " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECseverRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECseverRecord oldRecord, VTECseverRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecsever SET severity = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getSeverity()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECseverRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECseverRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECseverRecord oldRecord = (VTECseverRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECseverTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECsignifRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECsignifRecord.java deleted file mode 100644 index bbbfeafb27..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECsignifRecord.java +++ /dev/null @@ -1,83 +0,0 @@ -// filename: VTECsignifRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// VTECsignif table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class VTECsignifRecord extends DbRecord -{ - private String signif; - - private String name; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public VTECsignifRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public VTECsignifRecord(VTECsignifRecord origRecord) - { - setSignif(origRecord.getSignif()); - setName(origRecord.getName()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a VTECsignif record - - //----------------------------------------------------------------- - public String getSignif() - { - return signif; - } - - public void setSignif(String signif) - { - this.signif = signif ; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE signif = '" + signif + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getSignif() + " " + - getName() + " " + - "" ; - return outString; - } // end toString() -} // end of VTECsignifRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECsignifTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECsignifTable.java deleted file mode 100644 index 4db659b55a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/VTECsignifTable.java +++ /dev/null @@ -1,251 +0,0 @@ -// filename: VTECsignifTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// vtecsignif table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class VTECsignifTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// VTECsignifTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public VTECsignifTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("vtecsignif"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of VTECsignifRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - VTECsignifRecord record = null; - - // create a List to hold VTECsignif Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecsignif " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECsignifRecord - // and store its address in oneRecord - record = new VTECsignifRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECsignifRecord object - - record.setSignif(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECsignifRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the VTECsignifRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of VTECsignifRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - VTECsignifRecord record = null; - - // create a List to hold VTECsignif Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM vtecsignif " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a VTECsignifRecord - // and store its address in oneRecord - record = new VTECsignifRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a VTECsignifRecord object - - record.setSignif(getString(rs, 1)); - record.setName(getString(rs, 2)); - - // add this VTECsignifRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the VTECsignifRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a VTECsignifRecord object and.. -//----------------------------------------------------------------- - public int insert(VTECsignifRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO vtecsignif VALUES (?, ? )"); - - setString(insertStatement, 1, record.getSignif()); - setString(insertStatement, 2, record.getName()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecsignif " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECsignifRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECsignifRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecsignif SET signif = ?, name = ? " + where ); - - setString(updateStatement, 1, record.getSignif()); - setString(updateStatement, 2, record.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(VTECsignifRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM vtecsignif " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a VTECsignifRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(VTECsignifRecord oldRecord, VTECsignifRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE vtecsignif SET signif = ?, name = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getSignif()); - setString(updateStatement, 2, newRecord.getName()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a VTECsignifRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(VTECsignifRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - VTECsignifRecord oldRecord = (VTECsignifRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of VTECsignifTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCoordAgencyRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCoordAgencyRecord.java deleted file mode 100644 index 521911a3f8..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCoordAgencyRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: WatSupCoordAgencyRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// WatSupCoordAgency table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WatSupCoordAgencyRecord extends DbRecord -{ - private String watsup_coord_agency; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WatSupCoordAgencyRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WatSupCoordAgencyRecord(WatSupCoordAgencyRecord origRecord) - { - setWatsup_coord_agency(origRecord.getWatsup_coord_agency()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a WatSupCoordAgency record - - //----------------------------------------------------------------- - public String getWatsup_coord_agency() - { - return watsup_coord_agency; - } - - public void setWatsup_coord_agency(String watsup_coord_agency) - { - this.watsup_coord_agency = watsup_coord_agency ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE watsup_coord_agency = '" + watsup_coord_agency + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getWatsup_coord_agency() + " " + - "" ; - return outString; - } // end toString() -} // end of WatSupCoordAgencyRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCoordAgencyTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCoordAgencyTable.java deleted file mode 100644 index 47dab31636..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCoordAgencyTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: WatSupCoordAgencyTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// watsupcoordagency table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WatSupCoordAgencyTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WatSupCoordAgencyTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WatSupCoordAgencyTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("watsupcoordagency"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WatSupCoordAgencyRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WatSupCoordAgencyRecord record = null; - - // create a List to hold WatSupCoordAgency Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsupcoordagency " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupCoordAgencyRecord - // and store its address in oneRecord - record = new WatSupCoordAgencyRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupCoordAgencyRecord object - - record.setWatsup_coord_agency(getString(rs, 1)); - - // add this WatSupCoordAgencyRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupCoordAgencyRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WatSupCoordAgencyRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WatSupCoordAgencyRecord record = null; - - // create a List to hold WatSupCoordAgency Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsupcoordagency " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupCoordAgencyRecord - // and store its address in oneRecord - record = new WatSupCoordAgencyRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupCoordAgencyRecord object - - record.setWatsup_coord_agency(getString(rs, 1)); - - // add this WatSupCoordAgencyRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupCoordAgencyRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WatSupCoordAgencyRecord object and.. -//----------------------------------------------------------------- - public int insert(WatSupCoordAgencyRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO watsupcoordagency VALUES (? )"); - - setString(insertStatement, 1, record.getWatsup_coord_agency()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsupcoordagency " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupCoordAgencyRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupCoordAgencyRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsupcoordagency SET watsup_coord_agency = ? " + where ); - - setString(updateStatement, 1, record.getWatsup_coord_agency()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WatSupCoordAgencyRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsupcoordagency " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupCoordAgencyRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupCoordAgencyRecord oldRecord, WatSupCoordAgencyRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsupcoordagency SET watsup_coord_agency = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getWatsup_coord_agency()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WatSupCoordAgencyRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WatSupCoordAgencyRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WatSupCoordAgencyRecord oldRecord = (WatSupCoordAgencyRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WatSupCoordAgencyTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCriterionRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCriterionRecord.java deleted file mode 100644 index a2644de8ce..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCriterionRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: WatSupCriterionRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// WatSupCriterion table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WatSupCriterionRecord extends DbRecord -{ - private String watsup_criterion; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WatSupCriterionRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WatSupCriterionRecord(WatSupCriterionRecord origRecord) - { - setWatsup_criterion(origRecord.getWatsup_criterion()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a WatSupCriterion record - - //----------------------------------------------------------------- - public String getWatsup_criterion() - { - return watsup_criterion; - } - - public void setWatsup_criterion(String watsup_criterion) - { - this.watsup_criterion = watsup_criterion ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE watsup_criterion = '" + watsup_criterion + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getWatsup_criterion() + " " + - "" ; - return outString; - } // end toString() -} // end of WatSupCriterionRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCriterionTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCriterionTable.java deleted file mode 100644 index f9c9cb4648..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupCriterionTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: WatSupCriterionTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// watsupcriterion table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WatSupCriterionTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WatSupCriterionTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WatSupCriterionTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("watsupcriterion"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WatSupCriterionRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WatSupCriterionRecord record = null; - - // create a List to hold WatSupCriterion Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsupcriterion " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupCriterionRecord - // and store its address in oneRecord - record = new WatSupCriterionRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupCriterionRecord object - - record.setWatsup_criterion(getString(rs, 1)); - - // add this WatSupCriterionRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupCriterionRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WatSupCriterionRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WatSupCriterionRecord record = null; - - // create a List to hold WatSupCriterion Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsupcriterion " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupCriterionRecord - // and store its address in oneRecord - record = new WatSupCriterionRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupCriterionRecord object - - record.setWatsup_criterion(getString(rs, 1)); - - // add this WatSupCriterionRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupCriterionRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WatSupCriterionRecord object and.. -//----------------------------------------------------------------- - public int insert(WatSupCriterionRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO watsupcriterion VALUES (? )"); - - setString(insertStatement, 1, record.getWatsup_criterion()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsupcriterion " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupCriterionRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupCriterionRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsupcriterion SET watsup_criterion = ? " + where ); - - setString(updateStatement, 1, record.getWatsup_criterion()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WatSupCriterionRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsupcriterion " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupCriterionRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupCriterionRecord oldRecord, WatSupCriterionRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsupcriterion SET watsup_criterion = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getWatsup_criterion()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WatSupCriterionRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WatSupCriterionRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WatSupCriterionRecord oldRecord = (WatSupCriterionRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WatSupCriterionTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupMethodRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupMethodRecord.java deleted file mode 100644 index 9b96d63189..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupMethodRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: WatSupMethodRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// WatSupMethod table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WatSupMethodRecord extends DbRecord -{ - private String watsup_method; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WatSupMethodRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WatSupMethodRecord(WatSupMethodRecord origRecord) - { - setWatsup_method(origRecord.getWatsup_method()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a WatSupMethod record - - //----------------------------------------------------------------- - public String getWatsup_method() - { - return watsup_method; - } - - public void setWatsup_method(String watsup_method) - { - this.watsup_method = watsup_method ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE watsup_method = '" + watsup_method + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getWatsup_method() + " " + - "" ; - return outString; - } // end toString() -} // end of WatSupMethodRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupMethodTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupMethodTable.java deleted file mode 100644 index 2d1b32cc0a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupMethodTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: WatSupMethodTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// watsupmethod table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WatSupMethodTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WatSupMethodTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WatSupMethodTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("watsupmethod"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WatSupMethodRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WatSupMethodRecord record = null; - - // create a List to hold WatSupMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsupmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupMethodRecord - // and store its address in oneRecord - record = new WatSupMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupMethodRecord object - - record.setWatsup_method(getString(rs, 1)); - - // add this WatSupMethodRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupMethodRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WatSupMethodRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WatSupMethodRecord record = null; - - // create a List to hold WatSupMethod Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsupmethod " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupMethodRecord - // and store its address in oneRecord - record = new WatSupMethodRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupMethodRecord object - - record.setWatsup_method(getString(rs, 1)); - - // add this WatSupMethodRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupMethodRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WatSupMethodRecord object and.. -//----------------------------------------------------------------- - public int insert(WatSupMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO watsupmethod VALUES (? )"); - - setString(insertStatement, 1, record.getWatsup_method()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsupmethod " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupMethodRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsupmethod SET watsup_method = ? " + where ); - - setString(updateStatement, 1, record.getWatsup_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WatSupMethodRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsupmethod " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupMethodRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupMethodRecord oldRecord, WatSupMethodRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsupmethod SET watsup_method = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getWatsup_method()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WatSupMethodRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WatSupMethodRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WatSupMethodRecord oldRecord = (WatSupMethodRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WatSupMethodTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupRespAgencyRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupRespAgencyRecord.java deleted file mode 100644 index fca39ef22a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupRespAgencyRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: WatSupRespAgencyRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// WatSupRespAgency table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WatSupRespAgencyRecord extends DbRecord -{ - private String watsup_resp_agency; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WatSupRespAgencyRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WatSupRespAgencyRecord(WatSupRespAgencyRecord origRecord) - { - setWatsup_resp_agency(origRecord.getWatsup_resp_agency()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a WatSupRespAgency record - - //----------------------------------------------------------------- - public String getWatsup_resp_agency() - { - return watsup_resp_agency; - } - - public void setWatsup_resp_agency(String watsup_resp_agency) - { - this.watsup_resp_agency = watsup_resp_agency ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE watsup_resp_agency = '" + watsup_resp_agency + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getWatsup_resp_agency() + " " + - "" ; - return outString; - } // end toString() -} // end of WatSupRespAgencyRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupRespAgencyTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupRespAgencyTable.java deleted file mode 100644 index bdfcae1da5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WatSupRespAgencyTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: WatSupRespAgencyTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// watsuprespagency table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WatSupRespAgencyTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WatSupRespAgencyTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WatSupRespAgencyTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("watsuprespagency"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WatSupRespAgencyRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WatSupRespAgencyRecord record = null; - - // create a List to hold WatSupRespAgency Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsuprespagency " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupRespAgencyRecord - // and store its address in oneRecord - record = new WatSupRespAgencyRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupRespAgencyRecord object - - record.setWatsup_resp_agency(getString(rs, 1)); - - // add this WatSupRespAgencyRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupRespAgencyRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WatSupRespAgencyRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WatSupRespAgencyRecord record = null; - - // create a List to hold WatSupRespAgency Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM watsuprespagency " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WatSupRespAgencyRecord - // and store its address in oneRecord - record = new WatSupRespAgencyRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WatSupRespAgencyRecord object - - record.setWatsup_resp_agency(getString(rs, 1)); - - // add this WatSupRespAgencyRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WatSupRespAgencyRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WatSupRespAgencyRecord object and.. -//----------------------------------------------------------------- - public int insert(WatSupRespAgencyRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO watsuprespagency VALUES (? )"); - - setString(insertStatement, 1, record.getWatsup_resp_agency()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsuprespagency " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupRespAgencyRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupRespAgencyRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsuprespagency SET watsup_resp_agency = ? " + where ); - - setString(updateStatement, 1, record.getWatsup_resp_agency()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WatSupRespAgencyRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM watsuprespagency " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WatSupRespAgencyRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WatSupRespAgencyRecord oldRecord, WatSupRespAgencyRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE watsuprespagency SET watsup_resp_agency = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getWatsup_resp_agency()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WatSupRespAgencyRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WatSupRespAgencyRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WatSupRespAgencyRecord oldRecord = (WatSupRespAgencyRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WatSupRespAgencyTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WaterQualityRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WaterQualityRecord.java deleted file mode 100644 index bd846d920e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WaterQualityRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: WaterQualityRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// WaterQuality table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WaterQualityRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WaterQualityRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WaterQualityRecord(WaterQualityRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a WaterQuality record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of WaterQualityRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WaterQualityTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WaterQualityTable.java deleted file mode 100644 index e4fc2a239a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WaterQualityTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: WaterQualityTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// waterquality table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WaterQualityTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WaterQualityTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WaterQualityTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("waterquality"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WaterQualityRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WaterQualityRecord record = null; - - // create a List to hold WaterQuality Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM waterquality " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WaterQualityRecord - // and store its address in oneRecord - record = new WaterQualityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WaterQualityRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this WaterQualityRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WaterQualityRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WaterQualityRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WaterQualityRecord record = null; - - // create a List to hold WaterQuality Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM waterquality " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WaterQualityRecord - // and store its address in oneRecord - record = new WaterQualityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WaterQualityRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this WaterQualityRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WaterQualityRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WaterQualityRecord object and.. -//----------------------------------------------------------------- - public int insert(WaterQualityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO waterquality VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM waterquality " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WaterQualityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WaterQualityRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE waterquality SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WaterQualityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM waterquality " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WaterQualityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WaterQualityRecord oldRecord, WaterQualityRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE waterquality SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WaterQualityRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WaterQualityRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WaterQualityRecord oldRecord = (WaterQualityRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WaterQualityTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WeatherRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WeatherRecord.java deleted file mode 100644 index 87227117bc..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WeatherRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: WeatherRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Weather table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WeatherRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WeatherRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WeatherRecord(WeatherRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Weather record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of WeatherRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WeatherTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WeatherTable.java deleted file mode 100644 index d720fe5a98..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WeatherTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: WeatherTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// weather table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WeatherTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WeatherTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WeatherTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("weather"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WeatherRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WeatherRecord record = null; - - // create a List to hold Weather Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM weather " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WeatherRecord - // and store its address in oneRecord - record = new WeatherRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WeatherRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this WeatherRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WeatherRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WeatherRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WeatherRecord record = null; - - // create a List to hold Weather Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM weather " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WeatherRecord - // and store its address in oneRecord - record = new WeatherRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WeatherRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this WeatherRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WeatherRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WeatherRecord object and.. -//----------------------------------------------------------------- - public int insert(WeatherRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO weather VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM weather " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WeatherRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WeatherRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE weather SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WeatherRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM weather " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WeatherRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WeatherRecord oldRecord, WeatherRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE weather SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WeatherRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WeatherRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WeatherRecord oldRecord = (WeatherRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WeatherTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WindRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WindRecord.java deleted file mode 100644 index 3a36c41a3d..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WindRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: WindRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Wind table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class WindRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public WindRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public WindRecord(WindRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Wind record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of WindRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WindTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WindTable.java deleted file mode 100644 index c29826ddc6..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/WindTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: WindTable.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// wind table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class WindTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// WindTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public WindTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("wind"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of WindRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - WindRecord record = null; - - // create a List to hold Wind Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM wind " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WindRecord - // and store its address in oneRecord - record = new WindRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WindRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this WindRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the WindRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of WindRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - WindRecord record = null; - - // create a List to hold Wind Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM wind " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a WindRecord - // and store its address in oneRecord - record = new WindRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a WindRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this WindRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the WindRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a WindRecord object and.. -//----------------------------------------------------------------- - public int insert(WindRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO wind VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM wind " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WindRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WindRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE wind SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(WindRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM wind " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a WindRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(WindRecord oldRecord, WindRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE wind SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a WindRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(WindRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - WindRecord oldRecord = (WindRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of WindTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/YUniqueRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/YUniqueRecord.java deleted file mode 100644 index 898c4542a5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/YUniqueRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -// filename: YUniqueRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// YUnique table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class YUniqueRecord extends DbRecord -{ - private String lid; - - private String pe; - - private short dur; - - private String ts; - - private String extremum; - - private long obstime; - - private double value; - - private String shef_qual_code; - - private int quality_code; - - private short revision; - - private String product_id; - - private long producttime; - - private long postingtime; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public YUniqueRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public YUniqueRecord(YUniqueRecord origRecord) - { - setLid(origRecord.getLid()); - setPe(origRecord.getPe()); - setDur(origRecord.getDur()); - setTs(origRecord.getTs()); - setExtremum(origRecord.getExtremum()); - setObstime(origRecord.getObstime()); - setValue(origRecord.getValue()); - setShef_qual_code(origRecord.getShef_qual_code()); - setQuality_code(origRecord.getQuality_code()); - setRevision(origRecord.getRevision()); - setProduct_id(origRecord.getProduct_id()); - setProducttime(origRecord.getProducttime()); - setPostingtime(origRecord.getPostingtime()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a YUnique record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getPe() - { - return pe; - } - - public void setPe(String pe) - { - this.pe = pe ; - } - - public short getDur() - { - return dur; - } - - public void setDur(short dur) - { - this.dur = dur ; - } - - public String getTs() - { - return ts; - } - - public void setTs(String ts) - { - this.ts = ts ; - } - - public String getExtremum() - { - return extremum; - } - - public void setExtremum(String extremum) - { - this.extremum = extremum ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public double getValue() - { - return value; - } - - public void setValue(double value) - { - this.value = value ; - } - - public String getShef_qual_code() - { - return shef_qual_code; - } - - public void setShef_qual_code(String shef_qual_code) - { - this.shef_qual_code = shef_qual_code ; - } - - public int getQuality_code() - { - return quality_code; - } - - public void setQuality_code(int quality_code) - { - this.quality_code = quality_code ; - } - - public short getRevision() - { - return revision; - } - - public void setRevision(short revision) - { - this.revision = revision ; - } - - public String getProduct_id() - { - return product_id; - } - - public void setProduct_id(String product_id) - { - this.product_id = product_id ; - } - - public long getProducttime() - { - return producttime; - } - - public void setProducttime(long producttime) - { - this.producttime = producttime ; - } - - public long getPostingtime() - { - return postingtime; - } - - public void setPostingtime(long postingtime) - { - this.postingtime = postingtime ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND pe = '" + pe + "'" - + " AND dur = '" + dur + "'" - + " AND ts = '" + ts + "'" - + " AND extremum = '" + extremum + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getPe() + " " + - getDur() + " " + - getTs() + " " + - getExtremum() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getValue() + " " + - getShef_qual_code() + " " + - getQuality_code() + " " + - getRevision() + " " + - getProduct_id() + " " + - getDateTimeStringFromLongTime(getProducttime()) + " " + - getDateTimeStringFromLongTime(getPostingtime()) + " " + - "" ; - return outString; - } // end toString() -} // end of YUniqueRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/YUniqueTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/YUniqueTable.java deleted file mode 100644 index 1a083ed1d5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/YUniqueTable.java +++ /dev/null @@ -1,306 +0,0 @@ -// filename: YUniqueTable.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// yunique table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class YUniqueTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// YUniqueTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public YUniqueTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("yunique"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of YUniqueRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - YUniqueRecord record = null; - - // create a List to hold YUnique Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM yunique " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a YUniqueRecord - // and store its address in oneRecord - record = new YUniqueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a YUniqueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this YUniqueRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the YUniqueRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of YUniqueRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - YUniqueRecord record = null; - - // create a List to hold YUnique Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM yunique " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a YUniqueRecord - // and store its address in oneRecord - record = new YUniqueRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a YUniqueRecord object - - record.setLid(getString(rs, 1)); - record.setPe(getString(rs, 2)); - record.setDur(getShort(rs, 3)); - record.setTs(getString(rs, 4)); - record.setExtremum(getString(rs, 5)); - record.setObstime(getTimeStamp(rs, 6)); - record.setValue(getDouble(rs, 7)); - record.setShef_qual_code(getString(rs, 8)); - record.setQuality_code(getInt(rs, 9)); - record.setRevision(getShort(rs, 10)); - record.setProduct_id(getString(rs, 11)); - record.setProducttime(getTimeStamp(rs, 12)); - record.setPostingtime(getTimeStamp(rs, 13)); - - // add this YUniqueRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the YUniqueRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a YUniqueRecord object and.. -//----------------------------------------------------------------- - public int insert(YUniqueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO yunique VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe()); - setShort(insertStatement, 3, record.getDur()); - setString(insertStatement, 4, record.getTs()); - setString(insertStatement, 5, record.getExtremum()); - setTimeStamp(insertStatement, 6, record.getObstime()); - setDouble(insertStatement, 7, record.getValue()); - setString(insertStatement, 8, record.getShef_qual_code()); - setInt(insertStatement, 9, record.getQuality_code()); - setShort(insertStatement, 10, record.getRevision()); - setString(insertStatement, 11, record.getProduct_id()); - setTimeStamp(insertStatement, 12, record.getProducttime()); - setTimeStamp(insertStatement, 13, record.getPostingtime()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM yunique " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a YUniqueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(YUniqueRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE yunique SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getPe()); - setShort(updateStatement, 3, record.getDur()); - setString(updateStatement, 4, record.getTs()); - setString(updateStatement, 5, record.getExtremum()); - setTimeStamp(updateStatement, 6, record.getObstime()); - setDouble(updateStatement, 7, record.getValue()); - setString(updateStatement, 8, record.getShef_qual_code()); - setInt(updateStatement, 9, record.getQuality_code()); - setShort(updateStatement, 10, record.getRevision()); - setString(updateStatement, 11, record.getProduct_id()); - setTimeStamp(updateStatement, 12, record.getProducttime()); - setTimeStamp(updateStatement, 13, record.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(YUniqueRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM yunique " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a YUniqueRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(YUniqueRecord oldRecord, YUniqueRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE yunique SET lid = ?, pe = ?, dur = ?, ts = ?, extremum = ?, obstime = ?, value = ?, shef_qual_code = ?, quality_code = ?, revision = ?, product_id = ?, producttime = ?, postingtime = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe()); - setShort(updateStatement, 3, newRecord.getDur()); - setString(updateStatement, 4, newRecord.getTs()); - setString(updateStatement, 5, newRecord.getExtremum()); - setTimeStamp(updateStatement, 6, newRecord.getObstime()); - setDouble(updateStatement, 7, newRecord.getValue()); - setString(updateStatement, 8, newRecord.getShef_qual_code()); - setInt(updateStatement, 9, newRecord.getQuality_code()); - setShort(updateStatement, 10, newRecord.getRevision()); - setString(updateStatement, 11, newRecord.getProduct_id()); - setTimeStamp(updateStatement, 12, newRecord.getProducttime()); - setTimeStamp(updateStatement, 13, newRecord.getPostingtime()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a YUniqueRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(YUniqueRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - YUniqueRecord oldRecord = (YUniqueRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of YUniqueTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZoneInfoRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZoneInfoRecord.java deleted file mode 100644 index ea09e71c96..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZoneInfoRecord.java +++ /dev/null @@ -1,100 +0,0 @@ -// This is a view record ! -// filename: ZoneInfoRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// ZoneInfo table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ZoneInfoRecord extends DbRecord -{ - private String lid; - - private String state; - - private String zonenum; - - private String descr; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ZoneInfoRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ZoneInfoRecord(ZoneInfoRecord origRecord) - { - setLid(origRecord.getLid()); - setState(origRecord.getState()); - setZonenum(origRecord.getZonenum()); - setDescr(origRecord.getDescr()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a ZoneInfo record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getZonenum() - { - return zonenum; - } - - public void setZonenum(String zonenum) - { - this.zonenum = zonenum ; - } - - public String getDescr() - { - return descr; - } - - public void setDescr(String descr) - { - this.descr = descr ; - } - -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getState() + " " + - getZonenum() + " " + - getDescr() + " " + - "" ; - return outString; - } // end toString() -} // end of ZoneInfoRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZoneInfoView.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZoneInfoView.java deleted file mode 100644 index baac9f422e..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZoneInfoView.java +++ /dev/null @@ -1,137 +0,0 @@ -// filename: ZoneInfoView.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// zoneinfo table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ZoneInfoView extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ZoneInfoTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ZoneInfoView(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("zoneinfo"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ZoneInfoRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ZoneInfoRecord record = null; - - // create a List to hold ZoneInfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM zoneinfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ZoneInfoRecord - // and store its address in oneRecord - record = new ZoneInfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ZoneInfoRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setZonenum(getString(rs, 3)); - record.setDescr(getString(rs, 4)); - - // add this ZoneInfoRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ZoneInfoRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ZoneInfoRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ZoneInfoRecord record = null; - - // create a List to hold ZoneInfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM zoneinfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ZoneInfoRecord - // and store its address in oneRecord - record = new ZoneInfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ZoneInfoRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setZonenum(getString(rs, 3)); - record.setDescr(getString(rs, 4)); - - // add this ZoneInfoRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ZoneInfoRecord objects - return recordList; - - } // end of selectNRecords method - -} // end of ZoneInfoTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZonenumRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZonenumRecord.java deleted file mode 100644 index 99a72bfba2..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZonenumRecord.java +++ /dev/null @@ -1,99 +0,0 @@ -// filename: ZonenumRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// Zonenum table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class ZonenumRecord extends DbRecord -{ - private String lid; - - private String state; - - private String zonenum; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public ZonenumRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public ZonenumRecord(ZonenumRecord origRecord) - { - setLid(origRecord.getLid()); - setState(origRecord.getState()); - setZonenum(origRecord.getZonenum()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Zonenum record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getState() - { - return state; - } - - public void setState(String state) - { - this.state = state ; - } - - public String getZonenum() - { - return zonenum; - } - - public void setZonenum(String zonenum) - { - this.zonenum = zonenum ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE lid = '" + lid + "'" - + " AND state = '" + state + "'" - + " AND zonenum = '" + zonenum + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getLid() + " " + - getState() + " " + - getZonenum() + " " + - "" ; - return outString; - } // end toString() -} // end of ZonenumRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZonenumTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZonenumTable.java deleted file mode 100644 index a59677ee23..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/ZonenumTable.java +++ /dev/null @@ -1,256 +0,0 @@ -// filename: ZonenumTable.java -// author : DBGEN -// created : Tue May 31 17:52:31 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// zonenum table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class ZonenumTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// ZonenumTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public ZonenumTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("zonenum"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of ZonenumRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - ZonenumRecord record = null; - - // create a List to hold Zonenum Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM zonenum " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ZonenumRecord - // and store its address in oneRecord - record = new ZonenumRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ZonenumRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setZonenum(getString(rs, 3)); - - // add this ZonenumRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the ZonenumRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of ZonenumRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - ZonenumRecord record = null; - - // create a List to hold Zonenum Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM zonenum " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a ZonenumRecord - // and store its address in oneRecord - record = new ZonenumRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a ZonenumRecord object - - record.setLid(getString(rs, 1)); - record.setState(getString(rs, 2)); - record.setZonenum(getString(rs, 3)); - - // add this ZonenumRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the ZonenumRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a ZonenumRecord object and.. -//----------------------------------------------------------------- - public int insert(ZonenumRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO zonenum VALUES (?, ?, ? )"); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getState()); - setString(insertStatement, 3, record.getZonenum()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM zonenum " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ZonenumRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ZonenumRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE zonenum SET lid = ?, state = ?, zonenum = ? " + where ); - - setString(updateStatement, 1, record.getLid()); - setString(updateStatement, 2, record.getState()); - setString(updateStatement, 3, record.getZonenum()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(ZonenumRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM zonenum " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a ZonenumRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(ZonenumRecord oldRecord, ZonenumRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE zonenum SET lid = ?, state = ?, zonenum = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getState()); - setString(updateStatement, 3, newRecord.getZonenum()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a ZonenumRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(ZonenumRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - ZonenumRecord oldRecord = (ZonenumRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of ZonenumTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhradaptRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhradaptRecord.java deleted file mode 100644 index 551d4f50e4..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhradaptRecord.java +++ /dev/null @@ -1,616 +0,0 @@ -// filename: dhradaptRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// dhradapt table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class dhradaptRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private float min_reflth; - - private float max_reflth; - - private float ref_tltest; - - private float rng_tltin; - - private float rng_tltout; - - private float max_birng; - - private float min_birng; - - private float min_echoar; - - private float min_awrefl; - - private float max_pctred; - - private float mlt_zrcoef; - - private float pwr_zrcoef; - - private float min_zrefl; - - private float max_zrefl; - - private float max_stmspd; - - private float max_timdif; - - private float min_artcon; - - private float tim_p1cont; - - private float tim_p2cont; - - private float max_ecarch; - - private float rng_cutoff; - - private float rng_e1coef; - - private float rng_e2coef; - - private float rng_e3coef; - - private float min_prate; - - private float max_prate; - - private float tim_restrt; - - private float max_timint; - - private float min_timprd; - - private float thr_hlyout; - - private float end_timgag; - - private float max_prdval; - - private float max_hlyval; - - private float tim_biest; - - private float thr_nosets; - - private float res_bias; - - private float longest_lag; - - private String bias_applied; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public dhradaptRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public dhradaptRecord(dhradaptRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setMin_reflth(origRecord.getMin_reflth()); - setMax_reflth(origRecord.getMax_reflth()); - setRef_tltest(origRecord.getRef_tltest()); - setRng_tltin(origRecord.getRng_tltin()); - setRng_tltout(origRecord.getRng_tltout()); - setMax_birng(origRecord.getMax_birng()); - setMin_birng(origRecord.getMin_birng()); - setMin_echoar(origRecord.getMin_echoar()); - setMin_awrefl(origRecord.getMin_awrefl()); - setMax_pctred(origRecord.getMax_pctred()); - setMlt_zrcoef(origRecord.getMlt_zrcoef()); - setPwr_zrcoef(origRecord.getPwr_zrcoef()); - setMin_zrefl(origRecord.getMin_zrefl()); - setMax_zrefl(origRecord.getMax_zrefl()); - setMax_stmspd(origRecord.getMax_stmspd()); - setMax_timdif(origRecord.getMax_timdif()); - setMin_artcon(origRecord.getMin_artcon()); - setTim_p1cont(origRecord.getTim_p1cont()); - setTim_p2cont(origRecord.getTim_p2cont()); - setMax_ecarch(origRecord.getMax_ecarch()); - setRng_cutoff(origRecord.getRng_cutoff()); - setRng_e1coef(origRecord.getRng_e1coef()); - setRng_e2coef(origRecord.getRng_e2coef()); - setRng_e3coef(origRecord.getRng_e3coef()); - setMin_prate(origRecord.getMin_prate()); - setMax_prate(origRecord.getMax_prate()); - setTim_restrt(origRecord.getTim_restrt()); - setMax_timint(origRecord.getMax_timint()); - setMin_timprd(origRecord.getMin_timprd()); - setThr_hlyout(origRecord.getThr_hlyout()); - setEnd_timgag(origRecord.getEnd_timgag()); - setMax_prdval(origRecord.getMax_prdval()); - setMax_hlyval(origRecord.getMax_hlyval()); - setTim_biest(origRecord.getTim_biest()); - setThr_nosets(origRecord.getThr_nosets()); - setRes_bias(origRecord.getRes_bias()); - setLongest_lag(origRecord.getLongest_lag()); - setBias_applied(origRecord.getBias_applied()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a dhradapt record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public float getMin_reflth() - { - return min_reflth; - } - - public void setMin_reflth(float min_reflth) - { - this.min_reflth = min_reflth ; - } - - public float getMax_reflth() - { - return max_reflth; - } - - public void setMax_reflth(float max_reflth) - { - this.max_reflth = max_reflth ; - } - - public float getRef_tltest() - { - return ref_tltest; - } - - public void setRef_tltest(float ref_tltest) - { - this.ref_tltest = ref_tltest ; - } - - public float getRng_tltin() - { - return rng_tltin; - } - - public void setRng_tltin(float rng_tltin) - { - this.rng_tltin = rng_tltin ; - } - - public float getRng_tltout() - { - return rng_tltout; - } - - public void setRng_tltout(float rng_tltout) - { - this.rng_tltout = rng_tltout ; - } - - public float getMax_birng() - { - return max_birng; - } - - public void setMax_birng(float max_birng) - { - this.max_birng = max_birng ; - } - - public float getMin_birng() - { - return min_birng; - } - - public void setMin_birng(float min_birng) - { - this.min_birng = min_birng ; - } - - public float getMin_echoar() - { - return min_echoar; - } - - public void setMin_echoar(float min_echoar) - { - this.min_echoar = min_echoar ; - } - - public float getMin_awrefl() - { - return min_awrefl; - } - - public void setMin_awrefl(float min_awrefl) - { - this.min_awrefl = min_awrefl ; - } - - public float getMax_pctred() - { - return max_pctred; - } - - public void setMax_pctred(float max_pctred) - { - this.max_pctred = max_pctred ; - } - - public float getMlt_zrcoef() - { - return mlt_zrcoef; - } - - public void setMlt_zrcoef(float mlt_zrcoef) - { - this.mlt_zrcoef = mlt_zrcoef ; - } - - public float getPwr_zrcoef() - { - return pwr_zrcoef; - } - - public void setPwr_zrcoef(float pwr_zrcoef) - { - this.pwr_zrcoef = pwr_zrcoef ; - } - - public float getMin_zrefl() - { - return min_zrefl; - } - - public void setMin_zrefl(float min_zrefl) - { - this.min_zrefl = min_zrefl ; - } - - public float getMax_zrefl() - { - return max_zrefl; - } - - public void setMax_zrefl(float max_zrefl) - { - this.max_zrefl = max_zrefl ; - } - - public float getMax_stmspd() - { - return max_stmspd; - } - - public void setMax_stmspd(float max_stmspd) - { - this.max_stmspd = max_stmspd ; - } - - public float getMax_timdif() - { - return max_timdif; - } - - public void setMax_timdif(float max_timdif) - { - this.max_timdif = max_timdif ; - } - - public float getMin_artcon() - { - return min_artcon; - } - - public void setMin_artcon(float min_artcon) - { - this.min_artcon = min_artcon ; - } - - public float getTim_p1cont() - { - return tim_p1cont; - } - - public void setTim_p1cont(float tim_p1cont) - { - this.tim_p1cont = tim_p1cont ; - } - - public float getTim_p2cont() - { - return tim_p2cont; - } - - public void setTim_p2cont(float tim_p2cont) - { - this.tim_p2cont = tim_p2cont ; - } - - public float getMax_ecarch() - { - return max_ecarch; - } - - public void setMax_ecarch(float max_ecarch) - { - this.max_ecarch = max_ecarch ; - } - - public float getRng_cutoff() - { - return rng_cutoff; - } - - public void setRng_cutoff(float rng_cutoff) - { - this.rng_cutoff = rng_cutoff ; - } - - public float getRng_e1coef() - { - return rng_e1coef; - } - - public void setRng_e1coef(float rng_e1coef) - { - this.rng_e1coef = rng_e1coef ; - } - - public float getRng_e2coef() - { - return rng_e2coef; - } - - public void setRng_e2coef(float rng_e2coef) - { - this.rng_e2coef = rng_e2coef ; - } - - public float getRng_e3coef() - { - return rng_e3coef; - } - - public void setRng_e3coef(float rng_e3coef) - { - this.rng_e3coef = rng_e3coef ; - } - - public float getMin_prate() - { - return min_prate; - } - - public void setMin_prate(float min_prate) - { - this.min_prate = min_prate ; - } - - public float getMax_prate() - { - return max_prate; - } - - public void setMax_prate(float max_prate) - { - this.max_prate = max_prate ; - } - - public float getTim_restrt() - { - return tim_restrt; - } - - public void setTim_restrt(float tim_restrt) - { - this.tim_restrt = tim_restrt ; - } - - public float getMax_timint() - { - return max_timint; - } - - public void setMax_timint(float max_timint) - { - this.max_timint = max_timint ; - } - - public float getMin_timprd() - { - return min_timprd; - } - - public void setMin_timprd(float min_timprd) - { - this.min_timprd = min_timprd ; - } - - public float getThr_hlyout() - { - return thr_hlyout; - } - - public void setThr_hlyout(float thr_hlyout) - { - this.thr_hlyout = thr_hlyout ; - } - - public float getEnd_timgag() - { - return end_timgag; - } - - public void setEnd_timgag(float end_timgag) - { - this.end_timgag = end_timgag ; - } - - public float getMax_prdval() - { - return max_prdval; - } - - public void setMax_prdval(float max_prdval) - { - this.max_prdval = max_prdval ; - } - - public float getMax_hlyval() - { - return max_hlyval; - } - - public void setMax_hlyval(float max_hlyval) - { - this.max_hlyval = max_hlyval ; - } - - public float getTim_biest() - { - return tim_biest; - } - - public void setTim_biest(float tim_biest) - { - this.tim_biest = tim_biest ; - } - - public float getThr_nosets() - { - return thr_nosets; - } - - public void setThr_nosets(float thr_nosets) - { - this.thr_nosets = thr_nosets ; - } - - public float getRes_bias() - { - return res_bias; - } - - public void setRes_bias(float res_bias) - { - this.res_bias = res_bias ; - } - - public float getLongest_lag() - { - return longest_lag; - } - - public void setLongest_lag(float longest_lag) - { - this.longest_lag = longest_lag ; - } - - public String getBias_applied() - { - return bias_applied; - } - - public void setBias_applied(String bias_applied) - { - this.bias_applied = bias_applied ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMin_reflth() + " " + - getMax_reflth() + " " + - getRef_tltest() + " " + - getRng_tltin() + " " + - getRng_tltout() + " " + - getMax_birng() + " " + - getMin_birng() + " " + - getMin_echoar() + " " + - getMin_awrefl() + " " + - getMax_pctred() + " " + - getMlt_zrcoef() + " " + - getPwr_zrcoef() + " " + - getMin_zrefl() + " " + - getMax_zrefl() + " " + - getMax_stmspd() + " " + - getMax_timdif() + " " + - getMin_artcon() + " " + - getTim_p1cont() + " " + - getTim_p2cont() + " " + - getMax_ecarch() + " " + - getRng_cutoff() + " " + - getRng_e1coef() + " " + - getRng_e2coef() + " " + - getRng_e3coef() + " " + - getMin_prate() + " " + - getMax_prate() + " " + - getTim_restrt() + " " + - getMax_timint() + " " + - getMin_timprd() + " " + - getThr_hlyout() + " " + - getEnd_timgag() + " " + - getMax_prdval() + " " + - getMax_hlyval() + " " + - getTim_biest() + " " + - getThr_nosets() + " " + - getRes_bias() + " " + - getLongest_lag() + " " + - getBias_applied() + " " + - "" ; - return outString; - } // end toString() -} // end of dhradaptRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhradaptTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhradaptTable.java deleted file mode 100644 index d9b28ad559..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhradaptTable.java +++ /dev/null @@ -1,441 +0,0 @@ -// filename: dhradaptTable.java -// author : DBGEN -// created : Tue May 31 17:52:20 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dhradapt table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class dhradaptTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// dhradaptTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public dhradaptTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dhradapt"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of dhradaptRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - dhradaptRecord record = null; - - // create a List to hold dhradapt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dhradapt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dhradaptRecord - // and store its address in oneRecord - record = new dhradaptRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dhradaptRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMin_reflth(getReal(rs, 3)); - record.setMax_reflth(getReal(rs, 4)); - record.setRef_tltest(getReal(rs, 5)); - record.setRng_tltin(getReal(rs, 6)); - record.setRng_tltout(getReal(rs, 7)); - record.setMax_birng(getReal(rs, 8)); - record.setMin_birng(getReal(rs, 9)); - record.setMin_echoar(getReal(rs, 10)); - record.setMin_awrefl(getReal(rs, 11)); - record.setMax_pctred(getReal(rs, 12)); - record.setMlt_zrcoef(getReal(rs, 13)); - record.setPwr_zrcoef(getReal(rs, 14)); - record.setMin_zrefl(getReal(rs, 15)); - record.setMax_zrefl(getReal(rs, 16)); - record.setMax_stmspd(getReal(rs, 17)); - record.setMax_timdif(getReal(rs, 18)); - record.setMin_artcon(getReal(rs, 19)); - record.setTim_p1cont(getReal(rs, 20)); - record.setTim_p2cont(getReal(rs, 21)); - record.setMax_ecarch(getReal(rs, 22)); - record.setRng_cutoff(getReal(rs, 23)); - record.setRng_e1coef(getReal(rs, 24)); - record.setRng_e2coef(getReal(rs, 25)); - record.setRng_e3coef(getReal(rs, 26)); - record.setMin_prate(getReal(rs, 27)); - record.setMax_prate(getReal(rs, 28)); - record.setTim_restrt(getReal(rs, 29)); - record.setMax_timint(getReal(rs, 30)); - record.setMin_timprd(getReal(rs, 31)); - record.setThr_hlyout(getReal(rs, 32)); - record.setEnd_timgag(getReal(rs, 33)); - record.setMax_prdval(getReal(rs, 34)); - record.setMax_hlyval(getReal(rs, 35)); - record.setTim_biest(getReal(rs, 36)); - record.setThr_nosets(getReal(rs, 37)); - record.setRes_bias(getReal(rs, 38)); - record.setLongest_lag(getReal(rs, 39)); - record.setBias_applied(getString(rs, 40)); - - // add this dhradaptRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the dhradaptRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of dhradaptRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - dhradaptRecord record = null; - - // create a List to hold dhradapt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dhradapt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dhradaptRecord - // and store its address in oneRecord - record = new dhradaptRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dhradaptRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMin_reflth(getReal(rs, 3)); - record.setMax_reflth(getReal(rs, 4)); - record.setRef_tltest(getReal(rs, 5)); - record.setRng_tltin(getReal(rs, 6)); - record.setRng_tltout(getReal(rs, 7)); - record.setMax_birng(getReal(rs, 8)); - record.setMin_birng(getReal(rs, 9)); - record.setMin_echoar(getReal(rs, 10)); - record.setMin_awrefl(getReal(rs, 11)); - record.setMax_pctred(getReal(rs, 12)); - record.setMlt_zrcoef(getReal(rs, 13)); - record.setPwr_zrcoef(getReal(rs, 14)); - record.setMin_zrefl(getReal(rs, 15)); - record.setMax_zrefl(getReal(rs, 16)); - record.setMax_stmspd(getReal(rs, 17)); - record.setMax_timdif(getReal(rs, 18)); - record.setMin_artcon(getReal(rs, 19)); - record.setTim_p1cont(getReal(rs, 20)); - record.setTim_p2cont(getReal(rs, 21)); - record.setMax_ecarch(getReal(rs, 22)); - record.setRng_cutoff(getReal(rs, 23)); - record.setRng_e1coef(getReal(rs, 24)); - record.setRng_e2coef(getReal(rs, 25)); - record.setRng_e3coef(getReal(rs, 26)); - record.setMin_prate(getReal(rs, 27)); - record.setMax_prate(getReal(rs, 28)); - record.setTim_restrt(getReal(rs, 29)); - record.setMax_timint(getReal(rs, 30)); - record.setMin_timprd(getReal(rs, 31)); - record.setThr_hlyout(getReal(rs, 32)); - record.setEnd_timgag(getReal(rs, 33)); - record.setMax_prdval(getReal(rs, 34)); - record.setMax_hlyval(getReal(rs, 35)); - record.setTim_biest(getReal(rs, 36)); - record.setThr_nosets(getReal(rs, 37)); - record.setRes_bias(getReal(rs, 38)); - record.setLongest_lag(getReal(rs, 39)); - record.setBias_applied(getString(rs, 40)); - - // add this dhradaptRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the dhradaptRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a dhradaptRecord object and.. -//----------------------------------------------------------------- - public int insert(dhradaptRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dhradapt VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setReal(insertStatement, 3, record.getMin_reflth()); - setReal(insertStatement, 4, record.getMax_reflth()); - setReal(insertStatement, 5, record.getRef_tltest()); - setReal(insertStatement, 6, record.getRng_tltin()); - setReal(insertStatement, 7, record.getRng_tltout()); - setReal(insertStatement, 8, record.getMax_birng()); - setReal(insertStatement, 9, record.getMin_birng()); - setReal(insertStatement, 10, record.getMin_echoar()); - setReal(insertStatement, 11, record.getMin_awrefl()); - setReal(insertStatement, 12, record.getMax_pctred()); - setReal(insertStatement, 13, record.getMlt_zrcoef()); - setReal(insertStatement, 14, record.getPwr_zrcoef()); - setReal(insertStatement, 15, record.getMin_zrefl()); - setReal(insertStatement, 16, record.getMax_zrefl()); - setReal(insertStatement, 17, record.getMax_stmspd()); - setReal(insertStatement, 18, record.getMax_timdif()); - setReal(insertStatement, 19, record.getMin_artcon()); - setReal(insertStatement, 20, record.getTim_p1cont()); - setReal(insertStatement, 21, record.getTim_p2cont()); - setReal(insertStatement, 22, record.getMax_ecarch()); - setReal(insertStatement, 23, record.getRng_cutoff()); - setReal(insertStatement, 24, record.getRng_e1coef()); - setReal(insertStatement, 25, record.getRng_e2coef()); - setReal(insertStatement, 26, record.getRng_e3coef()); - setReal(insertStatement, 27, record.getMin_prate()); - setReal(insertStatement, 28, record.getMax_prate()); - setReal(insertStatement, 29, record.getTim_restrt()); - setReal(insertStatement, 30, record.getMax_timint()); - setReal(insertStatement, 31, record.getMin_timprd()); - setReal(insertStatement, 32, record.getThr_hlyout()); - setReal(insertStatement, 33, record.getEnd_timgag()); - setReal(insertStatement, 34, record.getMax_prdval()); - setReal(insertStatement, 35, record.getMax_hlyval()); - setReal(insertStatement, 36, record.getTim_biest()); - setReal(insertStatement, 37, record.getThr_nosets()); - setReal(insertStatement, 38, record.getRes_bias()); - setReal(insertStatement, 39, record.getLongest_lag()); - setString(insertStatement, 40, record.getBias_applied()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dhradapt " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dhradaptRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dhradaptRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dhradapt SET radid = ?, obstime = ?, min_reflth = ?, max_reflth = ?, ref_tltest = ?, rng_tltin = ?, rng_tltout = ?, max_birng = ?, min_birng = ?, min_echoar = ?, min_awrefl = ?, max_pctred = ?, mlt_zrcoef = ?, pwr_zrcoef = ?, min_zrefl = ?, max_zrefl = ?, max_stmspd = ?, max_timdif = ?, min_artcon = ?, tim_p1cont = ?, tim_p2cont = ?, max_ecarch = ?, rng_cutoff = ?, rng_e1coef = ?, rng_e2coef = ?, rng_e3coef = ?, min_prate = ?, max_prate = ?, tim_restrt = ?, max_timint = ?, min_timprd = ?, thr_hlyout = ?, end_timgag = ?, max_prdval = ?, max_hlyval = ?, tim_biest = ?, thr_nosets = ?, res_bias = ?, longest_lag = ?, bias_applied = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setReal(updateStatement, 3, record.getMin_reflth()); - setReal(updateStatement, 4, record.getMax_reflth()); - setReal(updateStatement, 5, record.getRef_tltest()); - setReal(updateStatement, 6, record.getRng_tltin()); - setReal(updateStatement, 7, record.getRng_tltout()); - setReal(updateStatement, 8, record.getMax_birng()); - setReal(updateStatement, 9, record.getMin_birng()); - setReal(updateStatement, 10, record.getMin_echoar()); - setReal(updateStatement, 11, record.getMin_awrefl()); - setReal(updateStatement, 12, record.getMax_pctred()); - setReal(updateStatement, 13, record.getMlt_zrcoef()); - setReal(updateStatement, 14, record.getPwr_zrcoef()); - setReal(updateStatement, 15, record.getMin_zrefl()); - setReal(updateStatement, 16, record.getMax_zrefl()); - setReal(updateStatement, 17, record.getMax_stmspd()); - setReal(updateStatement, 18, record.getMax_timdif()); - setReal(updateStatement, 19, record.getMin_artcon()); - setReal(updateStatement, 20, record.getTim_p1cont()); - setReal(updateStatement, 21, record.getTim_p2cont()); - setReal(updateStatement, 22, record.getMax_ecarch()); - setReal(updateStatement, 23, record.getRng_cutoff()); - setReal(updateStatement, 24, record.getRng_e1coef()); - setReal(updateStatement, 25, record.getRng_e2coef()); - setReal(updateStatement, 26, record.getRng_e3coef()); - setReal(updateStatement, 27, record.getMin_prate()); - setReal(updateStatement, 28, record.getMax_prate()); - setReal(updateStatement, 29, record.getTim_restrt()); - setReal(updateStatement, 30, record.getMax_timint()); - setReal(updateStatement, 31, record.getMin_timprd()); - setReal(updateStatement, 32, record.getThr_hlyout()); - setReal(updateStatement, 33, record.getEnd_timgag()); - setReal(updateStatement, 34, record.getMax_prdval()); - setReal(updateStatement, 35, record.getMax_hlyval()); - setReal(updateStatement, 36, record.getTim_biest()); - setReal(updateStatement, 37, record.getThr_nosets()); - setReal(updateStatement, 38, record.getRes_bias()); - setReal(updateStatement, 39, record.getLongest_lag()); - setString(updateStatement, 40, record.getBias_applied()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(dhradaptRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dhradapt " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dhradaptRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dhradaptRecord oldRecord, dhradaptRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dhradapt SET radid = ?, obstime = ?, min_reflth = ?, max_reflth = ?, ref_tltest = ?, rng_tltin = ?, rng_tltout = ?, max_birng = ?, min_birng = ?, min_echoar = ?, min_awrefl = ?, max_pctred = ?, mlt_zrcoef = ?, pwr_zrcoef = ?, min_zrefl = ?, max_zrefl = ?, max_stmspd = ?, max_timdif = ?, min_artcon = ?, tim_p1cont = ?, tim_p2cont = ?, max_ecarch = ?, rng_cutoff = ?, rng_e1coef = ?, rng_e2coef = ?, rng_e3coef = ?, min_prate = ?, max_prate = ?, tim_restrt = ?, max_timint = ?, min_timprd = ?, thr_hlyout = ?, end_timgag = ?, max_prdval = ?, max_hlyval = ?, tim_biest = ?, thr_nosets = ?, res_bias = ?, longest_lag = ?, bias_applied = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setReal(updateStatement, 3, newRecord.getMin_reflth()); - setReal(updateStatement, 4, newRecord.getMax_reflth()); - setReal(updateStatement, 5, newRecord.getRef_tltest()); - setReal(updateStatement, 6, newRecord.getRng_tltin()); - setReal(updateStatement, 7, newRecord.getRng_tltout()); - setReal(updateStatement, 8, newRecord.getMax_birng()); - setReal(updateStatement, 9, newRecord.getMin_birng()); - setReal(updateStatement, 10, newRecord.getMin_echoar()); - setReal(updateStatement, 11, newRecord.getMin_awrefl()); - setReal(updateStatement, 12, newRecord.getMax_pctred()); - setReal(updateStatement, 13, newRecord.getMlt_zrcoef()); - setReal(updateStatement, 14, newRecord.getPwr_zrcoef()); - setReal(updateStatement, 15, newRecord.getMin_zrefl()); - setReal(updateStatement, 16, newRecord.getMax_zrefl()); - setReal(updateStatement, 17, newRecord.getMax_stmspd()); - setReal(updateStatement, 18, newRecord.getMax_timdif()); - setReal(updateStatement, 19, newRecord.getMin_artcon()); - setReal(updateStatement, 20, newRecord.getTim_p1cont()); - setReal(updateStatement, 21, newRecord.getTim_p2cont()); - setReal(updateStatement, 22, newRecord.getMax_ecarch()); - setReal(updateStatement, 23, newRecord.getRng_cutoff()); - setReal(updateStatement, 24, newRecord.getRng_e1coef()); - setReal(updateStatement, 25, newRecord.getRng_e2coef()); - setReal(updateStatement, 26, newRecord.getRng_e3coef()); - setReal(updateStatement, 27, newRecord.getMin_prate()); - setReal(updateStatement, 28, newRecord.getMax_prate()); - setReal(updateStatement, 29, newRecord.getTim_restrt()); - setReal(updateStatement, 30, newRecord.getMax_timint()); - setReal(updateStatement, 31, newRecord.getMin_timprd()); - setReal(updateStatement, 32, newRecord.getThr_hlyout()); - setReal(updateStatement, 33, newRecord.getEnd_timgag()); - setReal(updateStatement, 34, newRecord.getMax_prdval()); - setReal(updateStatement, 35, newRecord.getMax_hlyval()); - setReal(updateStatement, 36, newRecord.getTim_biest()); - setReal(updateStatement, 37, newRecord.getThr_nosets()); - setReal(updateStatement, 38, newRecord.getRes_bias()); - setReal(updateStatement, 39, newRecord.getLongest_lag()); - setString(updateStatement, 40, newRecord.getBias_applied()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a dhradaptRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(dhradaptRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - dhradaptRecord oldRecord = (dhradaptRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of dhradaptTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhrradarRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhrradarRecord.java deleted file mode 100644 index d6309c17c5..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhrradarRecord.java +++ /dev/null @@ -1,224 +0,0 @@ -// filename: dhrradarRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// dhrradar table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class dhrradarRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private short volcovpat; - - private short opermode; - - private float dbzmin; - - private float dbzinc; - - private float dbzcnt; - - private short j_date; - - private short j_time; - - private short mean_field_bias; - - private short sample_size; - - private String grid_filename; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public dhrradarRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public dhrradarRecord(dhrradarRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setVolcovpat(origRecord.getVolcovpat()); - setOpermode(origRecord.getOpermode()); - setDbzmin(origRecord.getDbzmin()); - setDbzinc(origRecord.getDbzinc()); - setDbzcnt(origRecord.getDbzcnt()); - setJ_date(origRecord.getJ_date()); - setJ_time(origRecord.getJ_time()); - setMean_field_bias(origRecord.getMean_field_bias()); - setSample_size(origRecord.getSample_size()); - setGrid_filename(origRecord.getGrid_filename()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a dhrradar record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getVolcovpat() - { - return volcovpat; - } - - public void setVolcovpat(short volcovpat) - { - this.volcovpat = volcovpat ; - } - - public short getOpermode() - { - return opermode; - } - - public void setOpermode(short opermode) - { - this.opermode = opermode ; - } - - public float getDbzmin() - { - return dbzmin; - } - - public void setDbzmin(float dbzmin) - { - this.dbzmin = dbzmin ; - } - - public float getDbzinc() - { - return dbzinc; - } - - public void setDbzinc(float dbzinc) - { - this.dbzinc = dbzinc ; - } - - public float getDbzcnt() - { - return dbzcnt; - } - - public void setDbzcnt(float dbzcnt) - { - this.dbzcnt = dbzcnt ; - } - - public short getJ_date() - { - return j_date; - } - - public void setJ_date(short j_date) - { - this.j_date = j_date ; - } - - public short getJ_time() - { - return j_time; - } - - public void setJ_time(short j_time) - { - this.j_time = j_time ; - } - - public short getMean_field_bias() - { - return mean_field_bias; - } - - public void setMean_field_bias(short mean_field_bias) - { - this.mean_field_bias = mean_field_bias ; - } - - public short getSample_size() - { - return sample_size; - } - - public void setSample_size(short sample_size) - { - this.sample_size = sample_size ; - } - - public String getGrid_filename() - { - return grid_filename; - } - - public void setGrid_filename(String grid_filename) - { - this.grid_filename = grid_filename ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getVolcovpat() + " " + - getOpermode() + " " + - getDbzmin() + " " + - getDbzinc() + " " + - getDbzcnt() + " " + - getJ_date() + " " + - getJ_time() + " " + - getMean_field_bias() + " " + - getSample_size() + " " + - getGrid_filename() + " " + - "" ; - return outString; - } // end toString() -} // end of dhrradarRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhrradarTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhrradarTable.java deleted file mode 100644 index 2e5ad44d86..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dhrradarTable.java +++ /dev/null @@ -1,301 +0,0 @@ -// filename: dhrradarTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dhrradar table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class dhrradarTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// dhrradarTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public dhrradarTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dhrradar"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of dhrradarRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - dhrradarRecord record = null; - - // create a List to hold dhrradar Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dhrradar " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dhrradarRecord - // and store its address in oneRecord - record = new dhrradarRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dhrradarRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setVolcovpat(getShort(rs, 3)); - record.setOpermode(getShort(rs, 4)); - record.setDbzmin(getReal(rs, 5)); - record.setDbzinc(getReal(rs, 6)); - record.setDbzcnt(getReal(rs, 7)); - record.setJ_date(getShort(rs, 8)); - record.setJ_time(getShort(rs, 9)); - record.setMean_field_bias(getShort(rs, 10)); - record.setSample_size(getShort(rs, 11)); - record.setGrid_filename(getString(rs, 12)); - - // add this dhrradarRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the dhrradarRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of dhrradarRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - dhrradarRecord record = null; - - // create a List to hold dhrradar Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dhrradar " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dhrradarRecord - // and store its address in oneRecord - record = new dhrradarRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dhrradarRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setVolcovpat(getShort(rs, 3)); - record.setOpermode(getShort(rs, 4)); - record.setDbzmin(getReal(rs, 5)); - record.setDbzinc(getReal(rs, 6)); - record.setDbzcnt(getReal(rs, 7)); - record.setJ_date(getShort(rs, 8)); - record.setJ_time(getShort(rs, 9)); - record.setMean_field_bias(getShort(rs, 10)); - record.setSample_size(getShort(rs, 11)); - record.setGrid_filename(getString(rs, 12)); - - // add this dhrradarRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the dhrradarRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a dhrradarRecord object and.. -//----------------------------------------------------------------- - public int insert(dhrradarRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dhrradar VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setShort(insertStatement, 3, record.getVolcovpat()); - setShort(insertStatement, 4, record.getOpermode()); - setReal(insertStatement, 5, record.getDbzmin()); - setReal(insertStatement, 6, record.getDbzinc()); - setReal(insertStatement, 7, record.getDbzcnt()); - setShort(insertStatement, 8, record.getJ_date()); - setShort(insertStatement, 9, record.getJ_time()); - setShort(insertStatement, 10, record.getMean_field_bias()); - setShort(insertStatement, 11, record.getSample_size()); - setString(insertStatement, 12, record.getGrid_filename()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dhrradar " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dhrradarRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dhrradarRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dhrradar SET radid = ?, obstime = ?, volcovpat = ?, opermode = ?, dbzmin = ?, dbzinc = ?, dbzcnt = ?, j_date = ?, j_time = ?, mean_field_bias = ?, sample_size = ?, grid_filename = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setShort(updateStatement, 3, record.getVolcovpat()); - setShort(updateStatement, 4, record.getOpermode()); - setReal(updateStatement, 5, record.getDbzmin()); - setReal(updateStatement, 6, record.getDbzinc()); - setReal(updateStatement, 7, record.getDbzcnt()); - setShort(updateStatement, 8, record.getJ_date()); - setShort(updateStatement, 9, record.getJ_time()); - setShort(updateStatement, 10, record.getMean_field_bias()); - setShort(updateStatement, 11, record.getSample_size()); - setString(updateStatement, 12, record.getGrid_filename()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(dhrradarRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dhrradar " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dhrradarRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dhrradarRecord oldRecord, dhrradarRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dhrradar SET radid = ?, obstime = ?, volcovpat = ?, opermode = ?, dbzmin = ?, dbzinc = ?, dbzcnt = ?, j_date = ?, j_time = ?, mean_field_bias = ?, sample_size = ?, grid_filename = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setShort(updateStatement, 3, newRecord.getVolcovpat()); - setShort(updateStatement, 4, newRecord.getOpermode()); - setReal(updateStatement, 5, newRecord.getDbzmin()); - setReal(updateStatement, 6, newRecord.getDbzinc()); - setReal(updateStatement, 7, newRecord.getDbzcnt()); - setShort(updateStatement, 8, newRecord.getJ_date()); - setShort(updateStatement, 9, newRecord.getJ_time()); - setShort(updateStatement, 10, newRecord.getMean_field_bias()); - setShort(updateStatement, 11, newRecord.getSample_size()); - setString(updateStatement, 12, newRecord.getGrid_filename()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a dhrradarRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(dhrradarRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - dhrradarRecord oldRecord = (dhrradarRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of dhrradarTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspadaptRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspadaptRecord.java deleted file mode 100644 index 8ca13de00a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspadaptRecord.java +++ /dev/null @@ -1,616 +0,0 @@ -// filename: dspadaptRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// dspadapt table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class dspadaptRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private float min_reflth; - - private float max_reflth; - - private float ref_tltest; - - private float rng_tltin; - - private float rng_tltout; - - private float max_birng; - - private float min_birng; - - private float min_echoar; - - private float min_awrefl; - - private float max_pctred; - - private float mlt_zrcoef; - - private float pwr_zrcoef; - - private float min_zrefl; - - private float max_zrefl; - - private float max_stmspd; - - private float max_timdif; - - private float min_artcon; - - private float tim_p1cont; - - private float tim_p2cont; - - private float max_ecarch; - - private float rng_cutoff; - - private float rng_e1coef; - - private float rng_e2coef; - - private float rng_e3coef; - - private float min_prate; - - private float max_prate; - - private float tim_restrt; - - private float max_timint; - - private float min_timprd; - - private float thr_hlyout; - - private float end_timgag; - - private float max_prdval; - - private float max_hlyval; - - private float tim_biest; - - private float thr_nosets; - - private float res_bias; - - private float longest_lag; - - private String bias_applied; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public dspadaptRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public dspadaptRecord(dspadaptRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setMin_reflth(origRecord.getMin_reflth()); - setMax_reflth(origRecord.getMax_reflth()); - setRef_tltest(origRecord.getRef_tltest()); - setRng_tltin(origRecord.getRng_tltin()); - setRng_tltout(origRecord.getRng_tltout()); - setMax_birng(origRecord.getMax_birng()); - setMin_birng(origRecord.getMin_birng()); - setMin_echoar(origRecord.getMin_echoar()); - setMin_awrefl(origRecord.getMin_awrefl()); - setMax_pctred(origRecord.getMax_pctred()); - setMlt_zrcoef(origRecord.getMlt_zrcoef()); - setPwr_zrcoef(origRecord.getPwr_zrcoef()); - setMin_zrefl(origRecord.getMin_zrefl()); - setMax_zrefl(origRecord.getMax_zrefl()); - setMax_stmspd(origRecord.getMax_stmspd()); - setMax_timdif(origRecord.getMax_timdif()); - setMin_artcon(origRecord.getMin_artcon()); - setTim_p1cont(origRecord.getTim_p1cont()); - setTim_p2cont(origRecord.getTim_p2cont()); - setMax_ecarch(origRecord.getMax_ecarch()); - setRng_cutoff(origRecord.getRng_cutoff()); - setRng_e1coef(origRecord.getRng_e1coef()); - setRng_e2coef(origRecord.getRng_e2coef()); - setRng_e3coef(origRecord.getRng_e3coef()); - setMin_prate(origRecord.getMin_prate()); - setMax_prate(origRecord.getMax_prate()); - setTim_restrt(origRecord.getTim_restrt()); - setMax_timint(origRecord.getMax_timint()); - setMin_timprd(origRecord.getMin_timprd()); - setThr_hlyout(origRecord.getThr_hlyout()); - setEnd_timgag(origRecord.getEnd_timgag()); - setMax_prdval(origRecord.getMax_prdval()); - setMax_hlyval(origRecord.getMax_hlyval()); - setTim_biest(origRecord.getTim_biest()); - setThr_nosets(origRecord.getThr_nosets()); - setRes_bias(origRecord.getRes_bias()); - setLongest_lag(origRecord.getLongest_lag()); - setBias_applied(origRecord.getBias_applied()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a dspadapt record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public float getMin_reflth() - { - return min_reflth; - } - - public void setMin_reflth(float min_reflth) - { - this.min_reflth = min_reflth ; - } - - public float getMax_reflth() - { - return max_reflth; - } - - public void setMax_reflth(float max_reflth) - { - this.max_reflth = max_reflth ; - } - - public float getRef_tltest() - { - return ref_tltest; - } - - public void setRef_tltest(float ref_tltest) - { - this.ref_tltest = ref_tltest ; - } - - public float getRng_tltin() - { - return rng_tltin; - } - - public void setRng_tltin(float rng_tltin) - { - this.rng_tltin = rng_tltin ; - } - - public float getRng_tltout() - { - return rng_tltout; - } - - public void setRng_tltout(float rng_tltout) - { - this.rng_tltout = rng_tltout ; - } - - public float getMax_birng() - { - return max_birng; - } - - public void setMax_birng(float max_birng) - { - this.max_birng = max_birng ; - } - - public float getMin_birng() - { - return min_birng; - } - - public void setMin_birng(float min_birng) - { - this.min_birng = min_birng ; - } - - public float getMin_echoar() - { - return min_echoar; - } - - public void setMin_echoar(float min_echoar) - { - this.min_echoar = min_echoar ; - } - - public float getMin_awrefl() - { - return min_awrefl; - } - - public void setMin_awrefl(float min_awrefl) - { - this.min_awrefl = min_awrefl ; - } - - public float getMax_pctred() - { - return max_pctred; - } - - public void setMax_pctred(float max_pctred) - { - this.max_pctred = max_pctred ; - } - - public float getMlt_zrcoef() - { - return mlt_zrcoef; - } - - public void setMlt_zrcoef(float mlt_zrcoef) - { - this.mlt_zrcoef = mlt_zrcoef ; - } - - public float getPwr_zrcoef() - { - return pwr_zrcoef; - } - - public void setPwr_zrcoef(float pwr_zrcoef) - { - this.pwr_zrcoef = pwr_zrcoef ; - } - - public float getMin_zrefl() - { - return min_zrefl; - } - - public void setMin_zrefl(float min_zrefl) - { - this.min_zrefl = min_zrefl ; - } - - public float getMax_zrefl() - { - return max_zrefl; - } - - public void setMax_zrefl(float max_zrefl) - { - this.max_zrefl = max_zrefl ; - } - - public float getMax_stmspd() - { - return max_stmspd; - } - - public void setMax_stmspd(float max_stmspd) - { - this.max_stmspd = max_stmspd ; - } - - public float getMax_timdif() - { - return max_timdif; - } - - public void setMax_timdif(float max_timdif) - { - this.max_timdif = max_timdif ; - } - - public float getMin_artcon() - { - return min_artcon; - } - - public void setMin_artcon(float min_artcon) - { - this.min_artcon = min_artcon ; - } - - public float getTim_p1cont() - { - return tim_p1cont; - } - - public void setTim_p1cont(float tim_p1cont) - { - this.tim_p1cont = tim_p1cont ; - } - - public float getTim_p2cont() - { - return tim_p2cont; - } - - public void setTim_p2cont(float tim_p2cont) - { - this.tim_p2cont = tim_p2cont ; - } - - public float getMax_ecarch() - { - return max_ecarch; - } - - public void setMax_ecarch(float max_ecarch) - { - this.max_ecarch = max_ecarch ; - } - - public float getRng_cutoff() - { - return rng_cutoff; - } - - public void setRng_cutoff(float rng_cutoff) - { - this.rng_cutoff = rng_cutoff ; - } - - public float getRng_e1coef() - { - return rng_e1coef; - } - - public void setRng_e1coef(float rng_e1coef) - { - this.rng_e1coef = rng_e1coef ; - } - - public float getRng_e2coef() - { - return rng_e2coef; - } - - public void setRng_e2coef(float rng_e2coef) - { - this.rng_e2coef = rng_e2coef ; - } - - public float getRng_e3coef() - { - return rng_e3coef; - } - - public void setRng_e3coef(float rng_e3coef) - { - this.rng_e3coef = rng_e3coef ; - } - - public float getMin_prate() - { - return min_prate; - } - - public void setMin_prate(float min_prate) - { - this.min_prate = min_prate ; - } - - public float getMax_prate() - { - return max_prate; - } - - public void setMax_prate(float max_prate) - { - this.max_prate = max_prate ; - } - - public float getTim_restrt() - { - return tim_restrt; - } - - public void setTim_restrt(float tim_restrt) - { - this.tim_restrt = tim_restrt ; - } - - public float getMax_timint() - { - return max_timint; - } - - public void setMax_timint(float max_timint) - { - this.max_timint = max_timint ; - } - - public float getMin_timprd() - { - return min_timprd; - } - - public void setMin_timprd(float min_timprd) - { - this.min_timprd = min_timprd ; - } - - public float getThr_hlyout() - { - return thr_hlyout; - } - - public void setThr_hlyout(float thr_hlyout) - { - this.thr_hlyout = thr_hlyout ; - } - - public float getEnd_timgag() - { - return end_timgag; - } - - public void setEnd_timgag(float end_timgag) - { - this.end_timgag = end_timgag ; - } - - public float getMax_prdval() - { - return max_prdval; - } - - public void setMax_prdval(float max_prdval) - { - this.max_prdval = max_prdval ; - } - - public float getMax_hlyval() - { - return max_hlyval; - } - - public void setMax_hlyval(float max_hlyval) - { - this.max_hlyval = max_hlyval ; - } - - public float getTim_biest() - { - return tim_biest; - } - - public void setTim_biest(float tim_biest) - { - this.tim_biest = tim_biest ; - } - - public float getThr_nosets() - { - return thr_nosets; - } - - public void setThr_nosets(float thr_nosets) - { - this.thr_nosets = thr_nosets ; - } - - public float getRes_bias() - { - return res_bias; - } - - public void setRes_bias(float res_bias) - { - this.res_bias = res_bias ; - } - - public float getLongest_lag() - { - return longest_lag; - } - - public void setLongest_lag(float longest_lag) - { - this.longest_lag = longest_lag ; - } - - public String getBias_applied() - { - return bias_applied; - } - - public void setBias_applied(String bias_applied) - { - this.bias_applied = bias_applied ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getMin_reflth() + " " + - getMax_reflth() + " " + - getRef_tltest() + " " + - getRng_tltin() + " " + - getRng_tltout() + " " + - getMax_birng() + " " + - getMin_birng() + " " + - getMin_echoar() + " " + - getMin_awrefl() + " " + - getMax_pctred() + " " + - getMlt_zrcoef() + " " + - getPwr_zrcoef() + " " + - getMin_zrefl() + " " + - getMax_zrefl() + " " + - getMax_stmspd() + " " + - getMax_timdif() + " " + - getMin_artcon() + " " + - getTim_p1cont() + " " + - getTim_p2cont() + " " + - getMax_ecarch() + " " + - getRng_cutoff() + " " + - getRng_e1coef() + " " + - getRng_e2coef() + " " + - getRng_e3coef() + " " + - getMin_prate() + " " + - getMax_prate() + " " + - getTim_restrt() + " " + - getMax_timint() + " " + - getMin_timprd() + " " + - getThr_hlyout() + " " + - getEnd_timgag() + " " + - getMax_prdval() + " " + - getMax_hlyval() + " " + - getTim_biest() + " " + - getThr_nosets() + " " + - getRes_bias() + " " + - getLongest_lag() + " " + - getBias_applied() + " " + - "" ; - return outString; - } // end toString() -} // end of dspadaptRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspadaptTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspadaptTable.java deleted file mode 100644 index 243deaf001..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspadaptTable.java +++ /dev/null @@ -1,441 +0,0 @@ -// filename: dspadaptTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dspadapt table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class dspadaptTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// dspadaptTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public dspadaptTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dspadapt"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of dspadaptRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - dspadaptRecord record = null; - - // create a List to hold dspadapt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dspadapt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dspadaptRecord - // and store its address in oneRecord - record = new dspadaptRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dspadaptRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMin_reflth(getReal(rs, 3)); - record.setMax_reflth(getReal(rs, 4)); - record.setRef_tltest(getReal(rs, 5)); - record.setRng_tltin(getReal(rs, 6)); - record.setRng_tltout(getReal(rs, 7)); - record.setMax_birng(getReal(rs, 8)); - record.setMin_birng(getReal(rs, 9)); - record.setMin_echoar(getReal(rs, 10)); - record.setMin_awrefl(getReal(rs, 11)); - record.setMax_pctred(getReal(rs, 12)); - record.setMlt_zrcoef(getReal(rs, 13)); - record.setPwr_zrcoef(getReal(rs, 14)); - record.setMin_zrefl(getReal(rs, 15)); - record.setMax_zrefl(getReal(rs, 16)); - record.setMax_stmspd(getReal(rs, 17)); - record.setMax_timdif(getReal(rs, 18)); - record.setMin_artcon(getReal(rs, 19)); - record.setTim_p1cont(getReal(rs, 20)); - record.setTim_p2cont(getReal(rs, 21)); - record.setMax_ecarch(getReal(rs, 22)); - record.setRng_cutoff(getReal(rs, 23)); - record.setRng_e1coef(getReal(rs, 24)); - record.setRng_e2coef(getReal(rs, 25)); - record.setRng_e3coef(getReal(rs, 26)); - record.setMin_prate(getReal(rs, 27)); - record.setMax_prate(getReal(rs, 28)); - record.setTim_restrt(getReal(rs, 29)); - record.setMax_timint(getReal(rs, 30)); - record.setMin_timprd(getReal(rs, 31)); - record.setThr_hlyout(getReal(rs, 32)); - record.setEnd_timgag(getReal(rs, 33)); - record.setMax_prdval(getReal(rs, 34)); - record.setMax_hlyval(getReal(rs, 35)); - record.setTim_biest(getReal(rs, 36)); - record.setThr_nosets(getReal(rs, 37)); - record.setRes_bias(getReal(rs, 38)); - record.setLongest_lag(getReal(rs, 39)); - record.setBias_applied(getString(rs, 40)); - - // add this dspadaptRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the dspadaptRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of dspadaptRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - dspadaptRecord record = null; - - // create a List to hold dspadapt Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dspadapt " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dspadaptRecord - // and store its address in oneRecord - record = new dspadaptRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dspadaptRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setMin_reflth(getReal(rs, 3)); - record.setMax_reflth(getReal(rs, 4)); - record.setRef_tltest(getReal(rs, 5)); - record.setRng_tltin(getReal(rs, 6)); - record.setRng_tltout(getReal(rs, 7)); - record.setMax_birng(getReal(rs, 8)); - record.setMin_birng(getReal(rs, 9)); - record.setMin_echoar(getReal(rs, 10)); - record.setMin_awrefl(getReal(rs, 11)); - record.setMax_pctred(getReal(rs, 12)); - record.setMlt_zrcoef(getReal(rs, 13)); - record.setPwr_zrcoef(getReal(rs, 14)); - record.setMin_zrefl(getReal(rs, 15)); - record.setMax_zrefl(getReal(rs, 16)); - record.setMax_stmspd(getReal(rs, 17)); - record.setMax_timdif(getReal(rs, 18)); - record.setMin_artcon(getReal(rs, 19)); - record.setTim_p1cont(getReal(rs, 20)); - record.setTim_p2cont(getReal(rs, 21)); - record.setMax_ecarch(getReal(rs, 22)); - record.setRng_cutoff(getReal(rs, 23)); - record.setRng_e1coef(getReal(rs, 24)); - record.setRng_e2coef(getReal(rs, 25)); - record.setRng_e3coef(getReal(rs, 26)); - record.setMin_prate(getReal(rs, 27)); - record.setMax_prate(getReal(rs, 28)); - record.setTim_restrt(getReal(rs, 29)); - record.setMax_timint(getReal(rs, 30)); - record.setMin_timprd(getReal(rs, 31)); - record.setThr_hlyout(getReal(rs, 32)); - record.setEnd_timgag(getReal(rs, 33)); - record.setMax_prdval(getReal(rs, 34)); - record.setMax_hlyval(getReal(rs, 35)); - record.setTim_biest(getReal(rs, 36)); - record.setThr_nosets(getReal(rs, 37)); - record.setRes_bias(getReal(rs, 38)); - record.setLongest_lag(getReal(rs, 39)); - record.setBias_applied(getString(rs, 40)); - - // add this dspadaptRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the dspadaptRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a dspadaptRecord object and.. -//----------------------------------------------------------------- - public int insert(dspadaptRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dspadapt VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setReal(insertStatement, 3, record.getMin_reflth()); - setReal(insertStatement, 4, record.getMax_reflth()); - setReal(insertStatement, 5, record.getRef_tltest()); - setReal(insertStatement, 6, record.getRng_tltin()); - setReal(insertStatement, 7, record.getRng_tltout()); - setReal(insertStatement, 8, record.getMax_birng()); - setReal(insertStatement, 9, record.getMin_birng()); - setReal(insertStatement, 10, record.getMin_echoar()); - setReal(insertStatement, 11, record.getMin_awrefl()); - setReal(insertStatement, 12, record.getMax_pctred()); - setReal(insertStatement, 13, record.getMlt_zrcoef()); - setReal(insertStatement, 14, record.getPwr_zrcoef()); - setReal(insertStatement, 15, record.getMin_zrefl()); - setReal(insertStatement, 16, record.getMax_zrefl()); - setReal(insertStatement, 17, record.getMax_stmspd()); - setReal(insertStatement, 18, record.getMax_timdif()); - setReal(insertStatement, 19, record.getMin_artcon()); - setReal(insertStatement, 20, record.getTim_p1cont()); - setReal(insertStatement, 21, record.getTim_p2cont()); - setReal(insertStatement, 22, record.getMax_ecarch()); - setReal(insertStatement, 23, record.getRng_cutoff()); - setReal(insertStatement, 24, record.getRng_e1coef()); - setReal(insertStatement, 25, record.getRng_e2coef()); - setReal(insertStatement, 26, record.getRng_e3coef()); - setReal(insertStatement, 27, record.getMin_prate()); - setReal(insertStatement, 28, record.getMax_prate()); - setReal(insertStatement, 29, record.getTim_restrt()); - setReal(insertStatement, 30, record.getMax_timint()); - setReal(insertStatement, 31, record.getMin_timprd()); - setReal(insertStatement, 32, record.getThr_hlyout()); - setReal(insertStatement, 33, record.getEnd_timgag()); - setReal(insertStatement, 34, record.getMax_prdval()); - setReal(insertStatement, 35, record.getMax_hlyval()); - setReal(insertStatement, 36, record.getTim_biest()); - setReal(insertStatement, 37, record.getThr_nosets()); - setReal(insertStatement, 38, record.getRes_bias()); - setReal(insertStatement, 39, record.getLongest_lag()); - setString(insertStatement, 40, record.getBias_applied()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dspadapt " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dspadaptRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dspadaptRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dspadapt SET radid = ?, obstime = ?, min_reflth = ?, max_reflth = ?, ref_tltest = ?, rng_tltin = ?, rng_tltout = ?, max_birng = ?, min_birng = ?, min_echoar = ?, min_awrefl = ?, max_pctred = ?, mlt_zrcoef = ?, pwr_zrcoef = ?, min_zrefl = ?, max_zrefl = ?, max_stmspd = ?, max_timdif = ?, min_artcon = ?, tim_p1cont = ?, tim_p2cont = ?, max_ecarch = ?, rng_cutoff = ?, rng_e1coef = ?, rng_e2coef = ?, rng_e3coef = ?, min_prate = ?, max_prate = ?, tim_restrt = ?, max_timint = ?, min_timprd = ?, thr_hlyout = ?, end_timgag = ?, max_prdval = ?, max_hlyval = ?, tim_biest = ?, thr_nosets = ?, res_bias = ?, longest_lag = ?, bias_applied = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setReal(updateStatement, 3, record.getMin_reflth()); - setReal(updateStatement, 4, record.getMax_reflth()); - setReal(updateStatement, 5, record.getRef_tltest()); - setReal(updateStatement, 6, record.getRng_tltin()); - setReal(updateStatement, 7, record.getRng_tltout()); - setReal(updateStatement, 8, record.getMax_birng()); - setReal(updateStatement, 9, record.getMin_birng()); - setReal(updateStatement, 10, record.getMin_echoar()); - setReal(updateStatement, 11, record.getMin_awrefl()); - setReal(updateStatement, 12, record.getMax_pctred()); - setReal(updateStatement, 13, record.getMlt_zrcoef()); - setReal(updateStatement, 14, record.getPwr_zrcoef()); - setReal(updateStatement, 15, record.getMin_zrefl()); - setReal(updateStatement, 16, record.getMax_zrefl()); - setReal(updateStatement, 17, record.getMax_stmspd()); - setReal(updateStatement, 18, record.getMax_timdif()); - setReal(updateStatement, 19, record.getMin_artcon()); - setReal(updateStatement, 20, record.getTim_p1cont()); - setReal(updateStatement, 21, record.getTim_p2cont()); - setReal(updateStatement, 22, record.getMax_ecarch()); - setReal(updateStatement, 23, record.getRng_cutoff()); - setReal(updateStatement, 24, record.getRng_e1coef()); - setReal(updateStatement, 25, record.getRng_e2coef()); - setReal(updateStatement, 26, record.getRng_e3coef()); - setReal(updateStatement, 27, record.getMin_prate()); - setReal(updateStatement, 28, record.getMax_prate()); - setReal(updateStatement, 29, record.getTim_restrt()); - setReal(updateStatement, 30, record.getMax_timint()); - setReal(updateStatement, 31, record.getMin_timprd()); - setReal(updateStatement, 32, record.getThr_hlyout()); - setReal(updateStatement, 33, record.getEnd_timgag()); - setReal(updateStatement, 34, record.getMax_prdval()); - setReal(updateStatement, 35, record.getMax_hlyval()); - setReal(updateStatement, 36, record.getTim_biest()); - setReal(updateStatement, 37, record.getThr_nosets()); - setReal(updateStatement, 38, record.getRes_bias()); - setReal(updateStatement, 39, record.getLongest_lag()); - setString(updateStatement, 40, record.getBias_applied()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(dspadaptRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dspadapt " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dspadaptRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dspadaptRecord oldRecord, dspadaptRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dspadapt SET radid = ?, obstime = ?, min_reflth = ?, max_reflth = ?, ref_tltest = ?, rng_tltin = ?, rng_tltout = ?, max_birng = ?, min_birng = ?, min_echoar = ?, min_awrefl = ?, max_pctred = ?, mlt_zrcoef = ?, pwr_zrcoef = ?, min_zrefl = ?, max_zrefl = ?, max_stmspd = ?, max_timdif = ?, min_artcon = ?, tim_p1cont = ?, tim_p2cont = ?, max_ecarch = ?, rng_cutoff = ?, rng_e1coef = ?, rng_e2coef = ?, rng_e3coef = ?, min_prate = ?, max_prate = ?, tim_restrt = ?, max_timint = ?, min_timprd = ?, thr_hlyout = ?, end_timgag = ?, max_prdval = ?, max_hlyval = ?, tim_biest = ?, thr_nosets = ?, res_bias = ?, longest_lag = ?, bias_applied = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setReal(updateStatement, 3, newRecord.getMin_reflth()); - setReal(updateStatement, 4, newRecord.getMax_reflth()); - setReal(updateStatement, 5, newRecord.getRef_tltest()); - setReal(updateStatement, 6, newRecord.getRng_tltin()); - setReal(updateStatement, 7, newRecord.getRng_tltout()); - setReal(updateStatement, 8, newRecord.getMax_birng()); - setReal(updateStatement, 9, newRecord.getMin_birng()); - setReal(updateStatement, 10, newRecord.getMin_echoar()); - setReal(updateStatement, 11, newRecord.getMin_awrefl()); - setReal(updateStatement, 12, newRecord.getMax_pctred()); - setReal(updateStatement, 13, newRecord.getMlt_zrcoef()); - setReal(updateStatement, 14, newRecord.getPwr_zrcoef()); - setReal(updateStatement, 15, newRecord.getMin_zrefl()); - setReal(updateStatement, 16, newRecord.getMax_zrefl()); - setReal(updateStatement, 17, newRecord.getMax_stmspd()); - setReal(updateStatement, 18, newRecord.getMax_timdif()); - setReal(updateStatement, 19, newRecord.getMin_artcon()); - setReal(updateStatement, 20, newRecord.getTim_p1cont()); - setReal(updateStatement, 21, newRecord.getTim_p2cont()); - setReal(updateStatement, 22, newRecord.getMax_ecarch()); - setReal(updateStatement, 23, newRecord.getRng_cutoff()); - setReal(updateStatement, 24, newRecord.getRng_e1coef()); - setReal(updateStatement, 25, newRecord.getRng_e2coef()); - setReal(updateStatement, 26, newRecord.getRng_e3coef()); - setReal(updateStatement, 27, newRecord.getMin_prate()); - setReal(updateStatement, 28, newRecord.getMax_prate()); - setReal(updateStatement, 29, newRecord.getTim_restrt()); - setReal(updateStatement, 30, newRecord.getMax_timint()); - setReal(updateStatement, 31, newRecord.getMin_timprd()); - setReal(updateStatement, 32, newRecord.getThr_hlyout()); - setReal(updateStatement, 33, newRecord.getEnd_timgag()); - setReal(updateStatement, 34, newRecord.getMax_prdval()); - setReal(updateStatement, 35, newRecord.getMax_hlyval()); - setReal(updateStatement, 36, newRecord.getTim_biest()); - setReal(updateStatement, 37, newRecord.getThr_nosets()); - setReal(updateStatement, 38, newRecord.getRes_bias()); - setReal(updateStatement, 39, newRecord.getLongest_lag()); - setString(updateStatement, 40, newRecord.getBias_applied()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a dspadaptRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(dspadaptRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - dspadaptRecord oldRecord = (dspadaptRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of dspadaptTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspradarRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspradarRecord.java deleted file mode 100644 index 542191e9d0..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspradarRecord.java +++ /dev/null @@ -1,294 +0,0 @@ -// filename: dspradarRecord.java -// author : DBGEN -// created : Tue May 31 17:52:14 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// dspradar table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class dspradarRecord extends DbRecord -{ - private String radid; - - private long obstime; - - private short volcovpat; - - private short opermode; - - private float minval; - - private float maxval; - - private float num_data_lev; - - private float scale_factor; - - private long begin_time; - - private long end_time; - - private short j_beg_date; - - private short j_beg_time; - - private short j_end_date; - - private short j_end_time; - - private short mean_field_bias; - - private short sample_size; - - private String grid_filename; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public dspradarRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public dspradarRecord(dspradarRecord origRecord) - { - setRadid(origRecord.getRadid()); - setObstime(origRecord.getObstime()); - setVolcovpat(origRecord.getVolcovpat()); - setOpermode(origRecord.getOpermode()); - setMinval(origRecord.getMinval()); - setMaxval(origRecord.getMaxval()); - setNum_data_lev(origRecord.getNum_data_lev()); - setScale_factor(origRecord.getScale_factor()); - setBegin_time(origRecord.getBegin_time()); - setEnd_time(origRecord.getEnd_time()); - setJ_beg_date(origRecord.getJ_beg_date()); - setJ_beg_time(origRecord.getJ_beg_time()); - setJ_end_date(origRecord.getJ_end_date()); - setJ_end_time(origRecord.getJ_end_time()); - setMean_field_bias(origRecord.getMean_field_bias()); - setSample_size(origRecord.getSample_size()); - setGrid_filename(origRecord.getGrid_filename()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a dspradar record - - //----------------------------------------------------------------- - public String getRadid() - { - return radid; - } - - public void setRadid(String radid) - { - this.radid = radid ; - } - - public long getObstime() - { - return obstime; - } - - public void setObstime(long obstime) - { - this.obstime = obstime ; - } - - public short getVolcovpat() - { - return volcovpat; - } - - public void setVolcovpat(short volcovpat) - { - this.volcovpat = volcovpat ; - } - - public short getOpermode() - { - return opermode; - } - - public void setOpermode(short opermode) - { - this.opermode = opermode ; - } - - public float getMinval() - { - return minval; - } - - public void setMinval(float minval) - { - this.minval = minval ; - } - - public float getMaxval() - { - return maxval; - } - - public void setMaxval(float maxval) - { - this.maxval = maxval ; - } - - public float getNum_data_lev() - { - return num_data_lev; - } - - public void setNum_data_lev(float num_data_lev) - { - this.num_data_lev = num_data_lev ; - } - - public float getScale_factor() - { - return scale_factor; - } - - public void setScale_factor(float scale_factor) - { - this.scale_factor = scale_factor ; - } - - public long getBegin_time() - { - return begin_time; - } - - public void setBegin_time(long begin_time) - { - this.begin_time = begin_time ; - } - - public long getEnd_time() - { - return end_time; - } - - public void setEnd_time(long end_time) - { - this.end_time = end_time ; - } - - public short getJ_beg_date() - { - return j_beg_date; - } - - public void setJ_beg_date(short j_beg_date) - { - this.j_beg_date = j_beg_date ; - } - - public short getJ_beg_time() - { - return j_beg_time; - } - - public void setJ_beg_time(short j_beg_time) - { - this.j_beg_time = j_beg_time ; - } - - public short getJ_end_date() - { - return j_end_date; - } - - public void setJ_end_date(short j_end_date) - { - this.j_end_date = j_end_date ; - } - - public short getJ_end_time() - { - return j_end_time; - } - - public void setJ_end_time(short j_end_time) - { - this.j_end_time = j_end_time ; - } - - public short getMean_field_bias() - { - return mean_field_bias; - } - - public void setMean_field_bias(short mean_field_bias) - { - this.mean_field_bias = mean_field_bias ; - } - - public short getSample_size() - { - return sample_size; - } - - public void setSample_size(short sample_size) - { - this.sample_size = sample_size ; - } - - public String getGrid_filename() - { - return grid_filename; - } - - public void setGrid_filename(String grid_filename) - { - this.grid_filename = grid_filename ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE radid = '" + radid + "'" - + " AND obstime = '" + getDateTimeStringFromLongTime(obstime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getRadid() + " " + - getDateTimeStringFromLongTime(getObstime()) + " " + - getVolcovpat() + " " + - getOpermode() + " " + - getMinval() + " " + - getMaxval() + " " + - getNum_data_lev() + " " + - getScale_factor() + " " + - getDateTimeStringFromLongTime(getBegin_time()) + " " + - getDateTimeStringFromLongTime(getEnd_time()) + " " + - getJ_beg_date() + " " + - getJ_beg_time() + " " + - getJ_end_date() + " " + - getJ_end_time() + " " + - getMean_field_bias() + " " + - getSample_size() + " " + - getGrid_filename() + " " + - "" ; - return outString; - } // end toString() -} // end of dspradarRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspradarTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspradarTable.java deleted file mode 100644 index cbadefc991..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/dspradarTable.java +++ /dev/null @@ -1,326 +0,0 @@ -// filename: dspradarTable.java -// author : DBGEN -// created : Tue May 31 17:52:21 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// dspradar table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class dspradarTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// dspradarTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public dspradarTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("dspradar"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of dspradarRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - dspradarRecord record = null; - - // create a List to hold dspradar Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dspradar " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dspradarRecord - // and store its address in oneRecord - record = new dspradarRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dspradarRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setVolcovpat(getShort(rs, 3)); - record.setOpermode(getShort(rs, 4)); - record.setMinval(getReal(rs, 5)); - record.setMaxval(getReal(rs, 6)); - record.setNum_data_lev(getReal(rs, 7)); - record.setScale_factor(getReal(rs, 8)); - record.setBegin_time(getTimeStamp(rs, 9)); - record.setEnd_time(getTimeStamp(rs, 10)); - record.setJ_beg_date(getShort(rs, 11)); - record.setJ_beg_time(getShort(rs, 12)); - record.setJ_end_date(getShort(rs, 13)); - record.setJ_end_time(getShort(rs, 14)); - record.setMean_field_bias(getShort(rs, 15)); - record.setSample_size(getShort(rs, 16)); - record.setGrid_filename(getString(rs, 17)); - - // add this dspradarRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the dspradarRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of dspradarRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - dspradarRecord record = null; - - // create a List to hold dspradar Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM dspradar " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a dspradarRecord - // and store its address in oneRecord - record = new dspradarRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a dspradarRecord object - - record.setRadid(getString(rs, 1)); - record.setObstime(getTimeStamp(rs, 2)); - record.setVolcovpat(getShort(rs, 3)); - record.setOpermode(getShort(rs, 4)); - record.setMinval(getReal(rs, 5)); - record.setMaxval(getReal(rs, 6)); - record.setNum_data_lev(getReal(rs, 7)); - record.setScale_factor(getReal(rs, 8)); - record.setBegin_time(getTimeStamp(rs, 9)); - record.setEnd_time(getTimeStamp(rs, 10)); - record.setJ_beg_date(getShort(rs, 11)); - record.setJ_beg_time(getShort(rs, 12)); - record.setJ_end_date(getShort(rs, 13)); - record.setJ_end_time(getShort(rs, 14)); - record.setMean_field_bias(getShort(rs, 15)); - record.setSample_size(getShort(rs, 16)); - record.setGrid_filename(getString(rs, 17)); - - // add this dspradarRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the dspradarRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a dspradarRecord object and.. -//----------------------------------------------------------------- - public int insert(dspradarRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO dspradar VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getRadid()); - setTimeStamp(insertStatement, 2, record.getObstime()); - setShort(insertStatement, 3, record.getVolcovpat()); - setShort(insertStatement, 4, record.getOpermode()); - setReal(insertStatement, 5, record.getMinval()); - setReal(insertStatement, 6, record.getMaxval()); - setReal(insertStatement, 7, record.getNum_data_lev()); - setReal(insertStatement, 8, record.getScale_factor()); - setTimeStamp(insertStatement, 9, record.getBegin_time()); - setTimeStamp(insertStatement, 10, record.getEnd_time()); - setShort(insertStatement, 11, record.getJ_beg_date()); - setShort(insertStatement, 12, record.getJ_beg_time()); - setShort(insertStatement, 13, record.getJ_end_date()); - setShort(insertStatement, 14, record.getJ_end_time()); - setShort(insertStatement, 15, record.getMean_field_bias()); - setShort(insertStatement, 16, record.getSample_size()); - setString(insertStatement, 17, record.getGrid_filename()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dspradar " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dspradarRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dspradarRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dspradar SET radid = ?, obstime = ?, volcovpat = ?, opermode = ?, minval = ?, maxval = ?, num_data_lev = ?, scale_factor = ?, begin_time = ?, end_time = ?, j_beg_date = ?, j_beg_time = ?, j_end_date = ?, j_end_time = ?, mean_field_bias = ?, sample_size = ?, grid_filename = ? " + where ); - - setString(updateStatement, 1, record.getRadid()); - setTimeStamp(updateStatement, 2, record.getObstime()); - setShort(updateStatement, 3, record.getVolcovpat()); - setShort(updateStatement, 4, record.getOpermode()); - setReal(updateStatement, 5, record.getMinval()); - setReal(updateStatement, 6, record.getMaxval()); - setReal(updateStatement, 7, record.getNum_data_lev()); - setReal(updateStatement, 8, record.getScale_factor()); - setTimeStamp(updateStatement, 9, record.getBegin_time()); - setTimeStamp(updateStatement, 10, record.getEnd_time()); - setShort(updateStatement, 11, record.getJ_beg_date()); - setShort(updateStatement, 12, record.getJ_beg_time()); - setShort(updateStatement, 13, record.getJ_end_date()); - setShort(updateStatement, 14, record.getJ_end_time()); - setShort(updateStatement, 15, record.getMean_field_bias()); - setShort(updateStatement, 16, record.getSample_size()); - setString(updateStatement, 17, record.getGrid_filename()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(dspradarRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM dspradar " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a dspradarRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(dspradarRecord oldRecord, dspradarRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE dspradar SET radid = ?, obstime = ?, volcovpat = ?, opermode = ?, minval = ?, maxval = ?, num_data_lev = ?, scale_factor = ?, begin_time = ?, end_time = ?, j_beg_date = ?, j_beg_time = ?, j_end_date = ?, j_end_time = ?, mean_field_bias = ?, sample_size = ?, grid_filename = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getRadid()); - setTimeStamp(updateStatement, 2, newRecord.getObstime()); - setShort(updateStatement, 3, newRecord.getVolcovpat()); - setShort(updateStatement, 4, newRecord.getOpermode()); - setReal(updateStatement, 5, newRecord.getMinval()); - setReal(updateStatement, 6, newRecord.getMaxval()); - setReal(updateStatement, 7, newRecord.getNum_data_lev()); - setReal(updateStatement, 8, newRecord.getScale_factor()); - setTimeStamp(updateStatement, 9, newRecord.getBegin_time()); - setTimeStamp(updateStatement, 10, newRecord.getEnd_time()); - setShort(updateStatement, 11, newRecord.getJ_beg_date()); - setShort(updateStatement, 12, newRecord.getJ_beg_time()); - setShort(updateStatement, 13, newRecord.getJ_end_date()); - setShort(updateStatement, 14, newRecord.getJ_end_time()); - setShort(updateStatement, 15, newRecord.getMean_field_bias()); - setShort(updateStatement, 16, newRecord.getSample_size()); - setString(updateStatement, 17, newRecord.getGrid_filename()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a dspradarRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(dspradarRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - dspradarRecord oldRecord = (dspradarRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of dspradarTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/velocityRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/velocityRecord.java deleted file mode 100644 index c0f864316f..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/velocityRecord.java +++ /dev/null @@ -1,126 +0,0 @@ -// filename: velocityRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// velocity table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class velocityRecord extends DbRecord -{ - private String mosaicid; - - private long createtime; - - private double umean; - - private double vmean; - - private short count; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public velocityRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public velocityRecord(velocityRecord origRecord) - { - setMosaicid(origRecord.getMosaicid()); - setCreatetime(origRecord.getCreatetime()); - setUmean(origRecord.getUmean()); - setVmean(origRecord.getVmean()); - setCount(origRecord.getCount()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a velocity record - - //----------------------------------------------------------------- - public String getMosaicid() - { - return mosaicid; - } - - public void setMosaicid(String mosaicid) - { - this.mosaicid = mosaicid ; - } - - public long getCreatetime() - { - return createtime; - } - - public void setCreatetime(long createtime) - { - this.createtime = createtime ; - } - - public double getUmean() - { - return umean; - } - - public void setUmean(double umean) - { - this.umean = umean ; - } - - public double getVmean() - { - return vmean; - } - - public void setVmean(double vmean) - { - this.vmean = vmean ; - } - - public short getCount() - { - return count; - } - - public void setCount(short count) - { - this.count = count ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE mosaicid = '" + mosaicid + "'" - + " AND createtime = '" + getDateTimeStringFromLongTime(createtime) + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getMosaicid() + " " + - getDateTimeStringFromLongTime(getCreatetime()) + " " + - getUmean() + " " + - getVmean() + " " + - getCount() + " " + - "" ; - return outString; - } // end toString() -} // end of velocityRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/velocityTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/velocityTable.java deleted file mode 100644 index 2aa6f16c66..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/velocityTable.java +++ /dev/null @@ -1,266 +0,0 @@ -// filename: velocityTable.java -// author : DBGEN -// created : Tue May 31 17:52:29 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// velocity table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class velocityTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// velocityTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public velocityTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("velocity"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of velocityRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - velocityRecord record = null; - - // create a List to hold velocity Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM velocity " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a velocityRecord - // and store its address in oneRecord - record = new velocityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a velocityRecord object - - record.setMosaicid(getString(rs, 1)); - record.setCreatetime(getTimeStamp(rs, 2)); - record.setUmean(getDouble(rs, 3)); - record.setVmean(getDouble(rs, 4)); - record.setCount(getShort(rs, 5)); - - // add this velocityRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the velocityRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of velocityRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - velocityRecord record = null; - - // create a List to hold velocity Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM velocity " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a velocityRecord - // and store its address in oneRecord - record = new velocityRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a velocityRecord object - - record.setMosaicid(getString(rs, 1)); - record.setCreatetime(getTimeStamp(rs, 2)); - record.setUmean(getDouble(rs, 3)); - record.setVmean(getDouble(rs, 4)); - record.setCount(getShort(rs, 5)); - - // add this velocityRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the velocityRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a velocityRecord object and.. -//----------------------------------------------------------------- - public int insert(velocityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO velocity VALUES (?, ?, ?, ?, ? )"); - - setString(insertStatement, 1, record.getMosaicid()); - setTimeStamp(insertStatement, 2, record.getCreatetime()); - setDouble(insertStatement, 3, record.getUmean()); - setDouble(insertStatement, 4, record.getVmean()); - setShort(insertStatement, 5, record.getCount()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM velocity " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a velocityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(velocityRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE velocity SET mosaicid = ?, createtime = ?, umean = ?, vmean = ?, count = ? " + where ); - - setString(updateStatement, 1, record.getMosaicid()); - setTimeStamp(updateStatement, 2, record.getCreatetime()); - setDouble(updateStatement, 3, record.getUmean()); - setDouble(updateStatement, 4, record.getVmean()); - setShort(updateStatement, 5, record.getCount()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(velocityRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM velocity " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a velocityRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(velocityRecord oldRecord, velocityRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE velocity SET mosaicid = ?, createtime = ?, umean = ?, vmean = ?, count = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getMosaicid()); - setTimeStamp(updateStatement, 2, newRecord.getCreatetime()); - setDouble(updateStatement, 3, newRecord.getUmean()); - setDouble(updateStatement, 4, newRecord.getVmean()); - setShort(updateStatement, 5, newRecord.getCount()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a velocityRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(velocityRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - velocityRecord oldRecord = (velocityRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of velocityTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/verifresptypeRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/verifresptypeRecord.java deleted file mode 100644 index 39b4e53f5a..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/verifresptypeRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: verifresptypeRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// verifresptype table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class verifresptypeRecord extends DbRecord -{ - private String verif_resp_type; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public verifresptypeRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public verifresptypeRecord(verifresptypeRecord origRecord) - { - setVerif_resp_type(origRecord.getVerif_resp_type()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a verifresptype record - - //----------------------------------------------------------------- - public String getVerif_resp_type() - { - return verif_resp_type; - } - - public void setVerif_resp_type(String verif_resp_type) - { - this.verif_resp_type = verif_resp_type ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE verif_resp_type = '" + verif_resp_type + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getVerif_resp_type() + " " + - "" ; - return outString; - } // end toString() -} // end of verifresptypeRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/verifresptypeTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/verifresptypeTable.java deleted file mode 100644 index 8810ebba73..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/verifresptypeTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: verifresptypeTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// verifresptype table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class verifresptypeTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// verifresptypeTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public verifresptypeTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("verifresptype"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of verifresptypeRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - verifresptypeRecord record = null; - - // create a List to hold verifresptype Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM verifresptype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a verifresptypeRecord - // and store its address in oneRecord - record = new verifresptypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a verifresptypeRecord object - - record.setVerif_resp_type(getString(rs, 1)); - - // add this verifresptypeRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the verifresptypeRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of verifresptypeRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - verifresptypeRecord record = null; - - // create a List to hold verifresptype Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM verifresptype " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a verifresptypeRecord - // and store its address in oneRecord - record = new verifresptypeRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a verifresptypeRecord object - - record.setVerif_resp_type(getString(rs, 1)); - - // add this verifresptypeRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the verifresptypeRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a verifresptypeRecord object and.. -//----------------------------------------------------------------- - public int insert(verifresptypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO verifresptype VALUES (? )"); - - setString(insertStatement, 1, record.getVerif_resp_type()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM verifresptype " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a verifresptypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(verifresptypeRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE verifresptype SET verif_resp_type = ? " + where ); - - setString(updateStatement, 1, record.getVerif_resp_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(verifresptypeRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM verifresptype " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a verifresptypeRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(verifresptypeRecord oldRecord, verifresptypeRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE verifresptype SET verif_resp_type = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getVerif_resp_type()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a verifresptypeRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(verifresptypeRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - verifresptypeRecord oldRecord = (verifresptypeRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of verifresptypeTable class diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/wfoRecord.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/wfoRecord.java deleted file mode 100644 index ff72189704..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/wfoRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -// filename: wfoRecord.java -// author : DBGEN -// created : Tue May 31 17:52:18 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into a -// wfo table record format -// - -package ohd.hseb.ihfsdb.generated; - -import ohd.hseb.db.*; - -public class wfoRecord extends DbRecord -{ - private String wfo; - - //--------------------------------------------------------------- - // Empty constructor - //--------------------------------------------------------------- - public wfoRecord() - { - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public wfoRecord(wfoRecord origRecord) - { - setWfo(origRecord.getWfo()); - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a wfo record - - //----------------------------------------------------------------- - public String getWfo() - { - return wfo; - } - - public void setWfo(String wfo) - { - this.wfo = wfo ; - } - -//----------------------------------------------------------------- -// getWhereString() - this method is called with no arguments -// and returns a String that contains a valid where clause containing all the -// primary key fields. -//----------------------------------------------------------------- - public String getWhereString() - { - String outString = - "WHERE wfo = '" + wfo + "'" - ; - return outString; - } // end toString() -//----------------------------------------------------------------- -// toString() - this method is called with no arguments -// and returns a String of the internal values -//----------------------------------------------------------------- - public String toString() - { - String outString = - getWfo() + " " + - "" ; - return outString; - } // end toString() -} // end of wfoRecord class - diff --git a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/wfoTable.java b/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/wfoTable.java deleted file mode 100644 index 138af55c3b..0000000000 --- a/javaUtilities/hydro/ohd.ihfsdb/src/ohd/hseb/ihfsdb/generated/wfoTable.java +++ /dev/null @@ -1,246 +0,0 @@ -// filename: wfoTable.java -// author : DBGEN -// created : Tue May 31 17:52:30 CDT 2011 using database hd_ob83oax -// description: This class is used to get data from and put data into the -// wfo table of an IHFS database -// -package ohd.hseb.ihfsdb.generated; - -import java.sql.*; - -import java.util.*; - -import ohd.hseb.db.*; - -public class wfoTable extends DbTable -{ -//----------------------------------------------------------------- -// Private data -//----------------------------------------------------------------- - private int _recordsFound = -1; -//----------------------------------------------------------------- -// wfoTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public wfoTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("wfo"); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a List of wfoRecord objects - //----------------------------------------------------------------- - public List select(String where) throws SQLException - { - wfoRecord record = null; - - // create a List to hold wfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM wfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a wfoRecord - // and store its address in oneRecord - record = new wfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a wfoRecord object - - record.setWfo(getString(rs, 1)); - - // add this wfoRecord object to the list - recordList.add(record); - } - // Close the result set - rs.close(); - - // return a List which holds the wfoRecord objects - return recordList; - - } // end of select method - - //----------------------------------------------------------------- - // selectNRecords() - this method is called with a where clause and returns - // a List filled with a maximum of maxRecordCount of wfoRecord objects - //----------------------------------------------------------------- - public List selectNRecords(String where, int maxRecordCount) throws SQLException - { - wfoRecord record = null; - - // create a List to hold wfo Records - List recordList = new ArrayList(); - - // set number of records found to zero - _recordsFound = 0; - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = "SELECT * FROM wfo " + where; - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery(selectStatement); - - // loop through the result set - while (rs.next()) - { - // create an instance of a wfoRecord - // and store its address in oneRecord - record = new wfoRecord(); - - // increment the number of records found - _recordsFound++; - - // assign the data returned to the result set for one - // record in the database to a wfoRecord object - - record.setWfo(getString(rs, 1)); - - // add this wfoRecord object to the list - recordList.add(record); - if (_recordsFound >= maxRecordCount) - { - break; - } - } - // Close the result set - rs.close(); - - // return a List which holds the wfoRecord objects - return recordList; - - } // end of selectNRecords method - -//----------------------------------------------------------------- -// insert() - this method is called with a wfoRecord object and.. -//----------------------------------------------------------------- - public int insert(wfoRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( -" INSERT INTO wfo VALUES (? )"); - - setString(insertStatement, 1, record.getWfo()); - - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(String where) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM wfo " + where; - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a wfoRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(wfoRecord record, String where) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE wfo SET wfo = ? " + where ); - - setString(updateStatement, 1, record.getWfo()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// delete() - this method is called with a where clause and returns -// the number of records deleted -//----------------------------------------------------------------- - public int delete(wfoRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL delete statement and issue it - // construct the delete statement - String deleteStatement = "DELETE FROM wfo " + record.getWhereString(); - - // get the number of records processed by the delete - returnCode = getStatement().executeUpdate(deleteStatement); - - return returnCode; - } // end of delete method - -//----------------------------------------------------------------- -// update() - this method is called with a wfoRecord object and a where clause.. -//----------------------------------------------------------------- - public int update(wfoRecord oldRecord, wfoRecord newRecord) throws SQLException - { - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - PreparedStatement updateStatement = getConnection().prepareStatement( -" UPDATE wfo SET wfo = ? " + oldRecord.getWhereString() ); - - setString(updateStatement, 1, newRecord.getWfo()); - // get the number of records processed by the update - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a wfoRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - public int insertOrUpdate(wfoRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - wfoRecord oldRecord = (wfoRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} // end of wfoTable class diff --git a/javaUtilities/hydro/ohd.lib/.classpath b/javaUtilities/hydro/ohd.lib/.classpath deleted file mode 100644 index 2f9baf09a2..0000000000 --- a/javaUtilities/hydro/ohd.lib/.classpath +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/javaUtilities/hydro/ohd.lib/.project b/javaUtilities/hydro/ohd.lib/.project deleted file mode 100644 index 9ac72bdcf9..0000000000 --- a/javaUtilities/hydro/ohd.lib/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.lib - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.lib/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.lib/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 11fa5059d6..0000000000 --- a/javaUtilities/hydro/ohd.lib/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 15:02:10 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.lib/ChartDirector.jar b/javaUtilities/hydro/ohd.lib/ChartDirector.jar deleted file mode 100644 index c056a55520..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/ChartDirector.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.lib/META-INF/MANIFEST.MF deleted file mode 100644 index fd3486f982..0000000000 --- a/javaUtilities/hydro/ohd.lib/META-INF/MANIFEST.MF +++ /dev/null @@ -1,332 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Lib -Bundle-SymbolicName: ohd.lib -Bundle-Version: 1.0.0 -Bundle-ClassPath: activation.jar, - bsf.jar, - bsh-2.0b4.jar, - ChartDirector.jar, - damcrest.jar, - fldat.jar, - ihfsdb.jar, - jcchart.jar, - jdom.jar, - junit.jar, - mail-1.4.1.jar, - netcdfUI-2.2.22.jar, - nlog4j-1.2.21.jar, - org.eclipse.swt.gtk.linux.x86_3.4.1.v3452b.jar, - org.eclipse.swt_3.4.2.v3452b.jar, - postgresql-8.2-506.jdbc3.jar, - rax_apps.jar, - rfc_util.jar -Export-Package: ChartDirector, - RTi.Util.GUI, - RTi.Util.IO, - RTi.Util.Message, - RTi.Util.String, - bsh, - bsh.classpath, - bsh.collection, - bsh.commands, - bsh.org.objectweb.asm, - bsh.reflect, - bsh.servlet, - bsh.util, - com.klg.jclass.beans, - com.klg.jclass.beans.resources, - com.klg.jclass.cell, - com.klg.jclass.cell.renderers, - com.klg.jclass.cell.swing, - com.klg.jclass.chart, - com.klg.jclass.chart.applet, - com.klg.jclass.chart.beans, - com.klg.jclass.chart.beans.resources, - com.klg.jclass.chart.customizer, - com.klg.jclass.chart.customizer.resources, - com.klg.jclass.chart.data, - com.klg.jclass.chart.property, - com.klg.jclass.chart.property.html, - com.klg.jclass.chart.resources, - com.klg.jclass.util, - com.klg.jclass.util.graphics, - com.klg.jclass.util.internal, - com.klg.jclass.util.io, - com.klg.jclass.util.io.resources, - com.klg.jclass.util.legend, - com.klg.jclass.util.legend.resources, - com.klg.jclass.util.progress, - com.klg.jclass.util.resources, - com.klg.jclass.util.swing, - com.klg.jclass.util.swing.beans, - com.klg.jclass.util.swing.beans.resources, - com.klg.jclass.util.swing.encode, - com.klg.jclass.util.swing.encode.resources, - com.klg.jclass.util.swing.resources, - com.klg.jclass.util.value, - com.klg.jclass.util.xml, - com.sitraka.licensing, - com.sitraka.licensing.util, - com.sun.activation.registries, - com.sun.activation.viewers, - com.sun.mail.handlers, - com.sun.mail.iap, - com.sun.mail.imap, - com.sun.mail.imap.protocol, - com.sun.mail.mbox, - com.sun.mail.pop3, - com.sun.mail.smtp, - com.sun.mail.util, - gov.noaa.FWGUI, - gov.noaa.FloodWav.Component, - gov.noaa.flddb, - gov.noaa.fldwav, - gov.noaa.fldwav.component, - gov.noaa.fldwav.controller, - gov.noaa.fldwav.gui, - gov.noaa.fldwav.parser, - gov.noaa.hec.parser, - gov.nws.ohd.probvs, - gov.nws.ohd.probvs.Discrimination_stat, - gov.nws.ohd.probvs.ROC_stat, - gov.nws.ohd.probvs.RPSS_stat, - gov.nws.ohd.probvs.RPS_stat, - gov.nws.ohd.probvs.Reliability_stat, - gov.nws.ohd.probvs.applicationControl, - gov.nws.ohd.probvs.batchUserInterface, - gov.nws.ohd.probvs.espadpIteration_DMI, - gov.nws.ohd.probvs.exception, - gov.nws.ohd.util, - javax.activation, - javax.mail, - javax.mail.event, - javax.mail.internet, - javax.mail.search, - javax.mail.util, - junit.awtui, - junit.extensions, - junit.framework, - junit.runner, - junit.swingui, - junit.textui, - ohd.hseb.color_chooser, - ohd.hseb.db, - ohd.hseb.dbgen, - ohd.hseb.fp_vtec_info, - ohd.hseb.geomap.contour, - ohd.hseb.geomap.model, - ohd.hseb.geomap.projection, - ohd.hseb.grid, - ohd.hseb.measurement, - ohd.hseb.model, - ohd.hseb.model.mkcapi, - ohd.hseb.model.sacsma, - ohd.hseb.raxbase, - ohd.hseb.raxbase.db, - ohd.hseb.raxbase.gui, - ohd.hseb.raxbase.model, - ohd.hseb.raxbase.table, - ohd.hseb.raxbase.util, - ohd.hseb.raxdb.generated, - ohd.hseb.raxdb_sync, - ohd.hseb.rfc.bbuilder, - ohd.hseb.rfc.bbuilder.commandpanels, - ohd.hseb.rfc.chart, - ohd.hseb.rfc.chart.propmgr, - ohd.hseb.rfc.chart.props, - ohd.hseb.rfc.espadp.bbuilder, - ohd.hseb.rfc.espvs.bbuilder, - ohd.hseb.rfc.ivp.batch, - ohd.hseb.rfc.ivp.bbuilder, - ohd.hseb.rfc.ivp.chart, - ohd.hseb.rfc.ivp.core, - ohd.hseb.rfc.ivp.core.stats, - ohd.hseb.rfc.ivp.data, - ohd.hseb.rfc.ivp.gui, - ohd.hseb.rfc.ivp.jobs, - ohd.hseb.rfc.ivp.project, - ohd.hseb.rfc.ivp.vfyruninfo, - ohd.hseb.rfc.ivp.wizard, - ohd.hseb.rfc.sacsnow, - ohd.hseb.rfc.util.batch, - ohd.hseb.rfc.util.data, - ohd.hseb.rfc.util.dist, - ohd.hseb.rfc.util.graphics, - ohd.hseb.rfc.util.listpanels, - ohd.hseb.rfc.util.misc, - ohd.hseb.rfc.util.pagewindow, - ohd.hseb.rfc.xefs.hmos, - ohd.hseb.util, - ohd.hseb.util.gui, - ohd.hseb.util.gui.drawing, - ohd.hseb.util.gui.jchecktree, - ohd.hseb.util.gui.jtable, - ohd.hseb.util.io, - ohd.hseb.util.test, - org.apache.bsf, - org.apache.bsf.dbline, - org.apache.bsf.debug, - org.apache.bsf.debug.clientImpl, - org.apache.bsf.debug.jsdi, - org.apache.bsf.debug.meta, - org.apache.bsf.debug.serverImpl, - org.apache.bsf.debug.util, - org.apache.bsf.engines.jacl, - org.apache.bsf.engines.javascript, - org.apache.bsf.engines.jython, - org.apache.bsf.engines.netrexx, - org.apache.bsf.engines.xslt, - org.apache.bsf.util, - org.apache.bsf.util.cf, - org.apache.bsf.util.event, - org.apache.bsf.util.event.adapters, - org.apache.bsf.util.event.generator, - org.apache.bsf.util.type, - org.apache.log4j, - org.apache.log4j.config, - org.apache.log4j.helpers, - org.apache.log4j.jdbc, - org.apache.log4j.jmx, - org.apache.log4j.net, - org.apache.log4j.or, - org.apache.log4j.or.jms, - org.apache.log4j.or.sax, - org.apache.log4j.spi, - org.apache.log4j.varia, - org.apache.log4j.xml, - org.apache.taglibs.bsf, - org.eclipse.swt, - org.eclipse.swt.accessibility, - org.eclipse.swt.awt, - org.eclipse.swt.browser, - org.eclipse.swt.custom, - org.eclipse.swt.dnd, - org.eclipse.swt.events, - org.eclipse.swt.graphics, - org.eclipse.swt.internal, - org.eclipse.swt.internal.accessibility.gtk, - org.eclipse.swt.internal.cairo, - org.eclipse.swt.internal.cde, - org.eclipse.swt.internal.gnome, - org.eclipse.swt.internal.gtk, - org.eclipse.swt.internal.image, - org.eclipse.swt.internal.mozilla, - org.eclipse.swt.internal.opengl.glx, - org.eclipse.swt.internal.theme, - org.eclipse.swt.layout, - org.eclipse.swt.opengl, - org.eclipse.swt.printing, - org.eclipse.swt.program, - org.eclipse.swt.widgets, - org.jdom, - org.jdom.adapters, - org.jdom.filter, - org.jdom.input, - org.jdom.output, - org.jdom.transform, - org.jdom.xpath, - org.pietschy.wizard, - org.pietschy.wizard.models, - org.pietschy.wizard.pane, - org.postgresql, - org.postgresql.core, - org.postgresql.core.types, - org.postgresql.core.v2, - org.postgresql.core.v3, - org.postgresql.ds, - org.postgresql.ds.common, - org.postgresql.ds.jdbc23, - org.postgresql.fastpath, - org.postgresql.geometric, - org.postgresql.jdbc2, - org.postgresql.jdbc2.optional, - org.postgresql.jdbc3, - org.postgresql.largeobject, - org.postgresql.ssl, - org.postgresql.translation, - org.postgresql.util, - org.postgresql.xa, - org.slf4j, - org.slf4j.impl, - org.slf4j.spi, - thredds.catalog, - thredds.catalog.crawl, - thredds.catalog.dl, - thredds.catalog.parser.jdom, - thredds.catalog.query, - thredds.catalog.search, - thredds.catalog.search.ui, - thredds.catalog.ui, - thredds.catalog.ui.query, - thredds.catalog.ui.tools, - thredds.cataloggen, - thredds.cataloggen.catalogrefexpander, - thredds.cataloggen.config, - thredds.cataloggen.datasetenhancer, - thredds.cataloggen.inserter, - thredds.crawlabledataset, - thredds.crawlabledataset.filter, - thredds.crawlabledataset.sorter, - thredds.datamodel.gis, - thredds.datatype, - thredds.datatype.prefs, - thredds.dqc, - thredds.ui, - thredds.util, - thredds.util.net, - thredds.viewer.gis, - thredds.viewer.gis.shapefile, - thredds.viewer.gis.worldmap, - thredds.viewer.ui, - thredds.viewer.ui.event, - thredds.viewer.ui.geoloc, - thredds.viewer.ui.table, - thredds.wcs, - ucar.atd.dorade, - ucar.ma2, - ucar.nc2, - ucar.nc2.adde, - ucar.nc2.dataset, - ucar.nc2.dataset.conv, - ucar.nc2.dataset.grid, - ucar.nc2.dataset.transform, - ucar.nc2.dods, - ucar.nc2.dt, - ucar.nc2.dt.fmr, - ucar.nc2.dt.fmrc, - ucar.nc2.dt.grid, - ucar.nc2.dt.image, - ucar.nc2.dt.point, - ucar.nc2.dt.point.decode, - ucar.nc2.dt.radial, - ucar.nc2.dt.trajectory, - ucar.nc2.geotiff, - ucar.nc2.iosp.bufr, - ucar.nc2.iosp.cinrad, - ucar.nc2.iosp.dmsp, - ucar.nc2.iosp.dorade, - ucar.nc2.iosp.gini, - ucar.nc2.iosp.grib, - ucar.nc2.iosp.nexrad2, - ucar.nc2.iosp.nids, - ucar.nc2.ncml, - ucar.nc2.thredds, - ucar.nc2.thredds.server, - ucar.nc2.ui, - ucar.nc2.ui.grid, - ucar.nc2.ui.image, - ucar.nc2.ui.point, - ucar.nc2.units, - ucar.nc2.util, - ucar.unidata.geoloc, - ucar.unidata.geoloc.projection, - ucar.unidata.geoloc.vertical, - ucar.unidata.io, - ucar.unidata.io.bzip2, - ucar.unidata.io.http, - ucar.unidata.util, - ucar.units, - ucar.util.prefs, - ucar.util.prefs.ui -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/javaUtilities/hydro/ohd.lib/activation.jar b/javaUtilities/hydro/ohd.lib/activation.jar deleted file mode 100644 index 29a59a9ee1..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/activation.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/bsf.jar b/javaUtilities/hydro/ohd.lib/bsf.jar deleted file mode 100644 index caa4dea709..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/bsf.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/bsh-2.0b4.jar b/javaUtilities/hydro/ohd.lib/bsh-2.0b4.jar deleted file mode 100644 index 36fe03d71c..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/bsh-2.0b4.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/build.properties b/javaUtilities/hydro/ohd.lib/build.properties deleted file mode 100644 index 05871edf00..0000000000 --- a/javaUtilities/hydro/ohd.lib/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -bin.includes = META-INF/,\ - activation.jar,\ - bsf.jar,\ - bsh-2.0b4.jar,\ - ChartDirector.jar,\ - damcrest.jar,\ - fldat.jar,\ - ihfsdb.jar,\ - jcchart.jar,\ - jdom.jar,\ - junit.jar,\ - mail-1.4.1.jar,\ - netcdfUI-2.2.22.jar,\ - nlog4j-1.2.21.jar,\ - org.eclipse.swt.gtk.linux.x86_3.4.1.v3452b.jar,\ - org.eclipse.swt_3.4.2.v3452b.jar,\ - postgresql-8.2-506.jdbc3.jar,\ - rax_apps.jar,\ - rfc_util.jar diff --git a/javaUtilities/hydro/ohd.lib/fldat.jar b/javaUtilities/hydro/ohd.lib/fldat.jar deleted file mode 100644 index c3cb6a36fc..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/fldat.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/jcchart.jar b/javaUtilities/hydro/ohd.lib/jcchart.jar deleted file mode 100644 index 6b7a797954..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/jcchart.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/jdom.jar b/javaUtilities/hydro/ohd.lib/jdom.jar deleted file mode 100644 index 6d04bac92f..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/jdom.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/junit.jar b/javaUtilities/hydro/ohd.lib/junit.jar deleted file mode 100644 index e0c7ded869..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/junit.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/mail-1.4.1.jar b/javaUtilities/hydro/ohd.lib/mail-1.4.1.jar deleted file mode 100644 index 1d15e793ec..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/mail-1.4.1.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/netcdfUI-2.2.22.jar b/javaUtilities/hydro/ohd.lib/netcdfUI-2.2.22.jar deleted file mode 100644 index aa8c22cfd1..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/netcdfUI-2.2.22.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/nlog4j-1.2.21.jar b/javaUtilities/hydro/ohd.lib/nlog4j-1.2.21.jar deleted file mode 100644 index c0fc307783..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/nlog4j-1.2.21.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/ohd.lib.ecl b/javaUtilities/hydro/ohd.lib/ohd.lib.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3452b.jar b/javaUtilities/hydro/ohd.lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3452b.jar deleted file mode 100644 index 3c7215513f..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3452b.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/org.eclipse.swt_3.4.2.v3452b.jar b/javaUtilities/hydro/ohd.lib/org.eclipse.swt_3.4.2.v3452b.jar deleted file mode 100644 index bb3bc675dd..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/org.eclipse.swt_3.4.2.v3452b.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/postgresql-8.2-506.jdbc3.jar b/javaUtilities/hydro/ohd.lib/postgresql-8.2-506.jdbc3.jar deleted file mode 100644 index 05a1cde163..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/postgresql-8.2-506.jdbc3.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/rax_apps.jar b/javaUtilities/hydro/ohd.lib/rax_apps.jar deleted file mode 100644 index a4bc218d47..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/rax_apps.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.lib/rfc_util.jar b/javaUtilities/hydro/ohd.lib/rfc_util.jar deleted file mode 100644 index 1e8666f22d..0000000000 Binary files a/javaUtilities/hydro/ohd.lib/rfc_util.jar and /dev/null differ diff --git a/javaUtilities/hydro/ohd.map/.classpath b/javaUtilities/hydro/ohd.map/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.map/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.map/.project b/javaUtilities/hydro/ohd.map/.project deleted file mode 100644 index 3d7d9ebfb1..0000000000 --- a/javaUtilities/hydro/ohd.map/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.map - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.map/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.map/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 586a2523e3..0000000000 --- a/javaUtilities/hydro/ohd.map/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 08:47:45 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.map/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.map/META-INF/MANIFEST.MF deleted file mode 100644 index 1d323f2ca4..0000000000 --- a/javaUtilities/hydro/ohd.map/META-INF/MANIFEST.MF +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Map -Bundle-SymbolicName: ohd.map -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.sshp;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.map/build.properties b/javaUtilities/hydro/ohd.map/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.map/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.map/build.xml b/javaUtilities/hydro/ohd.map/build.xml deleted file mode 100644 index cd291e1e2a..0000000000 --- a/javaUtilities/hydro/ohd.map/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.map/ohd.map.ecl b/javaUtilities/hydro/ohd.map/ohd.map.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/DrawingTools.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/DrawingTools.java deleted file mode 100644 index 35587be015..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/DrawingTools.java +++ /dev/null @@ -1,166 +0,0 @@ -package ohd.hseb.geomap; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.model.Polygon; -import ohd.hseb.geomap.projection.MapProjection; - -public class DrawingTools -{ - - public static void drawPoint(Graphics g, MapProjection projection, LatLonPoint latlonPoint) - { - Point screenPoint = projection.getScreenPoint(latlonPoint); - - drawScreenPoint(g, screenPoint); - } - //------------------------------------------------------------------------------------------------- - - public static void drawLineSegment(Graphics g, MapProjection projection, LatLonPoint point1, LatLonPoint point2) - { - String header = "DrawingTools.drawLineSegment(): "; - - Point screenPoint1 = projection.getScreenPoint(point1); - Point screenPoint2 = projection.getScreenPoint(point2); - - - if (bothPointsAreInRange(screenPoint1, screenPoint2, projection)) - { - // System.out.println(header + "screenPoint1 = " + screenPoint1 + " screenPoint2 = " + screenPoint2); - - drawScreenLine(g, screenPoint1, screenPoint2); - } - - - } - - //------------------------------------------------------------------------------------------------- - - private static void drawScreenPoint(Graphics g, Point screenPoint) - { - int width = 5; - int height = 5; - g.fillOval(screenPoint.x, screenPoint.y, width, height); - } - - //------------------------------------------------------------------------------------------------- - - private static void drawScreenLine(Graphics g, Point screenPoint1, Point screenPoint2) - { - String header = "DrawingTools.drawScreenLine(): "; - if ((screenPoint1 != null) && (screenPoint2 != null) ) - { - - g.drawLine(screenPoint1.x, screenPoint1.y, screenPoint2.x, screenPoint2.y); - - } - else - { - System.out.println(header + " both screen Points were null"); - } - - } - - //------------------------------------------------------------------------------------------------- - private static boolean bothPointsAreInRange(Point screenPoint1, Point screenPoint2, MapProjection projection ) - { - boolean result = false; - - if (pointIsInRange(screenPoint1, projection) && (pointIsInRange(screenPoint2, projection))) - { - result = true; - } - - return result; - } - //------------------------------------------------------------------------------------------------- - private static boolean pointIsInRange(Point screenPoint, MapProjection projection) - { - boolean result = false; - - if ( (screenPoint.x > -1) && (screenPoint.x < projection.getMapWidth()) ) - { - if ( (screenPoint.y > -1) && (screenPoint.y < projection.getMapHeight()) ) - { - result = true; - } - } - - return result; - } - //------------------------------------------------------------------------------------------------- - - public static void drawPolygon(Graphics g, MapProjection projection, Polygon polygon) - { - - String header = "DrawingTools.drawPolygon(): "; - // System.out.println(header); - - List pointList = polygon.getPointList(); - LatLonPoint previousPoint = null; - - boolean firstTime = true; - - for (LatLonPoint point : pointList) - { - if (firstTime) - { - firstTime = false; - //drawPoint(point); - } - - else - { - drawLineSegment(g, projection, previousPoint, point); - } - - previousPoint = point; - } - } - - //------------------------------------------------------------------------------------------------- - public static void drawPolyline(Graphics g, MapProjection projection, LatLonPolyline polyline) - { - - String header = "DrawingTools.drawPolygon(): "; - // System.out.println(header); - - List pointList = polyline.getPointList(); - LatLonPoint previousPoint = null; - - boolean firstTime = true; - - for (LatLonPoint point : pointList) - { - if (firstTime) - { - firstTime = false; - //drawPoint(point); - } - - else - { - drawLineSegment(g, projection, previousPoint, point); - } - - previousPoint = point; - } - } - - //------------------------------------------------------------------------------------------------- - - public static void setDrawingColor(Graphics g, Color color) - { - String header = "DrawingTools.setDrawingColor(): "; - - g.setColor(color); - - return; - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/MapCanvas.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/MapCanvas.java deleted file mode 100644 index 38e8094cc7..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/MapCanvas.java +++ /dev/null @@ -1,218 +0,0 @@ -package ohd.hseb.geomap; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.gui.drawing.BufferedCanvas; -import ohd.hseb.geomap.layer.MapLayer; -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.projection.MapProjection; - -public class MapCanvas extends BufferedCanvas -{ - CodeTimer _timer = new CodeTimer(); - - protected List _mapLayerList = new ArrayList(); - private MapProjection _projection = null; - - //------------------------------------------------------------------------------------------------- - - public MapCanvas(MapProjection projection, int width, int height) - { - super(0,0, width, height); - setProjection(projection); - - projection.setMapHeight(height); - projection.setMapWidth(width); - - setBackground(Color.green); - - addListeners(); - } - - //------------------------------------------------------------------------------------------------- - private void addListeners() - { - addComponentListener(new ResizeListener()); - } - - //------------------------------------------------------------------------------------------------- - - public void setMapScaleFactor(double mapScaleFactor) - { - _projection.setMapScaleFactor(mapScaleFactor); - repaint(); - } - - //------------------------------------------------------------------------------------------------- - - public double getMapScaleFactor() - { - return _projection.getMapScaleFactor(); - } - - //------------------------------------------------------------------------------------------------- - public void zoom(double zoomFactor) - { - double mapScaleFactor = _projection.getMapScaleFactor() * zoomFactor; - setMapScaleFactor(mapScaleFactor); - } - //------------------------------------------------------------------------------------------------- - - public void pan(double northSouthPanProportion, double eastWestProportion) - { - - // String header = "MapCanvas.pan(): "; - // System.out.println(header + northSouthPanProportion + " " + eastWestProportion); - - _projection.panProportionally(northSouthPanProportion, eastWestProportion); - - repaint(); - } -// ------------------------------------------------------------------------------------------------- - - public void setLatLonBounds(LatLonBounds latLonbounds) - { - String header = "MapCanvas.setLatLonBounds(): "; - System.out.println(header); - _projection.setLatLonBounds(latLonbounds); - repaint(); - } - - //------------------------------------------------------------------------------------------------- - public void recenterMap(LatLonPoint newCenter) - { - String header = "MapCanvas.recenterMap(): "; - System.out.println(header); - _projection.setCenterLatLon(newCenter); - - repaint(); - } - //------------------------------------------------------------------------------------------------- - - - public void removeMapLayer(MapLayer mapLayer) - { - _mapLayerList.remove(mapLayer); - setNeedsToRedraw(true); - } - - //------------------------------------------------------------------------------------------------- - - - public void addMapLayer(MapLayer mapLayer, int layerLevel) - { - _mapLayerList.add(layerLevel, mapLayer); - setNeedsToRedraw(true); - } - - //------------------------------------------------------------------------------------------------- - - public void addMapLayer(MapLayer mapLayer) - { - int index = _mapLayerList.size(); - addMapLayer(mapLayer, index); - } - - //------------------------------------------------------------------------------------------------- - - public void draw(Graphics g) - { - String header = "MapCanvas.draw(): "; - - _timer.start(); - System.out.println(header); - clearBufferedImage(g); - drawAllMapLayers(); - - _timer.stop(header + "drawing time took "); - } - - //------------------------------------------------------------------------------------------------- - private void clearBufferedImage(Graphics g) - { - g.setColor(Color.black); - g.fillRect(0, 0, getWidth(), getHeight()); - } - // ------------------------------------------------------------------------------------------------- - - - private void drawAllMapLayers() - { - for (MapLayer mapLayer : _mapLayerList) - { - if (mapLayer.shouldDraw() ) - { - drawMapLayer(mapLayer); - } - } - } - - //------------------------------------------------------------------------------------------------- - private void drawMapLayer(MapLayer mapLayer) - { - String header = "MapCanvas.drawMapLayer(): "; - // System.out.println(header); - - MapCanvas canvas = this; - mapLayer.draw(getBufferedImageGraphics(), getProjection()); - - return; - } - - //------------------------------------------------------------------------------------------------- - - public void setProjection(MapProjection projection) - { - _projection = projection; - } - - //------------------------------------------------------------------------------------------------- - - public MapProjection getProjection() - { - return _projection; - } - - //------------------------------------------------------------------------------------------------- - public void recenterAtXY(int x, int y) - { - Point clickedPoint = new Point(x,y); - LatLonPoint newCenter = _projection.getLatLonPoint(clickedPoint); - - System.out.println("clickedPoint = " + clickedPoint); - System.out.println("newCenter = " + newCenter); - - Point screen2 = _projection.getScreenPoint(newCenter); - System.out.println("newCenter back to screen point = " + screen2 ); - - - recenterMap(newCenter); - - return; - } - - //------------------------------------------------------------------------------------------------- - - private class ResizeListener extends ComponentAdapter - { - public void componentResized(ComponentEvent event) - { - _projection.setMapWidth(getWidth()); - _projection.setMapHeight(getHeight()); - repaint(); - } - } - - - - //------------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/MapDataManager.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/MapDataManager.java deleted file mode 100644 index ca43d1a6e4..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/MapDataManager.java +++ /dev/null @@ -1,268 +0,0 @@ -package ohd.hseb.geomap; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.RpfFcstPointRecord; -import ohd.hseb.ihfsdb.generated.RpfFcstPointTable; -import ohd.hseb.ihfsdb.generated.StnClassRecord; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.util.Logger; -import ohd.hseb.geomap.examples.StationPoint; -import ohd.hseb.geomap.model.LatLonPoint; - - -public class MapDataManager -{ - private Database _db = null; - private Logger _logger = null; - private Map _locationMap = new HashMap(); - - // -------------------------------------------------------------------------------------------- - - public MapDataManager(String connectionString, Logger logger) - { - super(); - - _db = new Database(); - _logger = logger; - - _db.connectWithDriverSearch(connectionString); - - initializeLocationMap(); - - return; - } - - // -------------------------------------------------------------------------------------------- - - private void initializeLocationMap() - { - - LocationTable table = new LocationTable(_db); - - try - { - List recordList = (List) table.select(" order by lid"); - - for (LocationRecord record : recordList) - { - _locationMap.put(record.getLid(), record); - } - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - // -------------------------------------------------------------------------------------------- - - public List getPrecipMonitorPointList() - { - List pointList = new ArrayList(); - - StnClassTable table = new StnClassTable(_db); - - List recordList = null; - - String whereString = "WHERE disp_class like '%P%' "; - - try - { - - recordList = (List) table.select(whereString); - - for (StnClassRecord record : recordList) - { - StationPoint point = getStationPoint(record.getLid()); - pointList.add(point); - } - - } - catch (SQLException e) - { - e.printStackTrace(); - } - - return pointList; - } - - // -------------------------------------------------------------------------------------------- - - private StationPoint getStationPoint(String lid) - { - StationPoint stationPoint = null; - LocationRecord record = _locationMap.get(lid); - - if (record != null) - { - LatLonPoint latLonPoint = new LatLonPoint(record.getLat(), -record.getLon()); - stationPoint = new StationPoint(record.getLid(), record.getName(), latLonPoint ); - } - - return stationPoint; - } - // -------------------------------------------------------------------------------------------- - - public List getRiverProFcstPointList() - { - List stationList = new ArrayList(); - - RpfFcstPointTable table = new RpfFcstPointTable(_db); - - try - { - List recordList = (List) table.select(""); - - for (RpfFcstPointRecord record: recordList) - { - StationPoint point = getStationPoint(record.getLid()); - stationList.add(point); - } - } - catch (SQLException e) - { - e.printStackTrace(); - } - - return stationList; - } - // -------------------------------------------------------------------------------------------- - - public List getSshpFcstPointList() - { - //stolen from SSHP's DataMgr - List locationIdList = new ArrayList(); - List sshpList = new ArrayList(); - - List recordList = null; - - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - String whereClause = null; - - try - { - whereClause = " WHERE lid IN (SELECT lid FROM SshpConfig)" + - " AND lid IN (SELECT distinct(lid) FROM Rating) " + - " AND lid IN (SELECT distinct(lid) FROM UnitGraph) " + - " AND ((fs IS NOT NULL) OR (fq is NOT NULL)) ORDER BY lid "; - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (RiverstatRecord) recordList.get(i); - - locationIdList.add(record.getLid()); - } - - sshpList = loadSshpLocations(locationIdList); - - } - catch (SQLException e) - { - logSQLException(e); - } - - return sshpList; - - - } - // ----------------------------------------------------------------------------------------- - - private List loadSshpLocations(List locationIdList) - { - String header = "MapDataManager.loadSshpLocation(): "; - - List sshpList = new ArrayList(); - - LocationTable table = new LocationTable(_db); - - - //create the where clause - - StringBuffer whereBuffer = new StringBuffer("WHERE lid in ( "); - - boolean firstTime = true; - - for (String id : locationIdList) - { - if (! firstTime) - { - whereBuffer.append(", "); - } - else - { - firstTime = false; - } - - whereBuffer.append("'" + id +"'"); - } - whereBuffer.append(") "); - - System.out.println(header + whereBuffer); - - // run the Location table query to load up the objects - - try - { - - List recordList = (List) table.select(whereBuffer.toString()); - - for (LocationRecord record : recordList) - { - LatLonPoint latLonPoint = new LatLonPoint(record.getLat(), -record.getLon()); - - StationPoint fcstPoint = new StationPoint(record.getLid(), record.getName(), latLonPoint ); - - // System.out.println(header + " fcstPoint = " + fcstPoint); - sshpList.add(fcstPoint); - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - return sshpList; - - } - // ----------------------------------------------------------------------------------------- - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - // -------------------------------------------------------------------------------------------- - - public void disconnect() - { - _db.disconnect(); - } - - // ------------------------------------------------------------------------------------------- - public void finalize() - { - disconnect(); - } - - // ------------------------------------------------------------------------ - -} //MapDataManager diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/MapFrame.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/MapFrame.java deleted file mode 100644 index 668fce7934..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/MapFrame.java +++ /dev/null @@ -1,936 +0,0 @@ -package ohd.hseb.geomap.examples; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JSeparator; -import javax.swing.KeyStroke; - - -import ohd.hseb.geomap.MapCanvas; -import ohd.hseb.geomap.MapDataManager; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.sshp.precip.XmrgReader; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; -import ohd.hseb.geomap.io.BCDFileReader; -import ohd.hseb.geomap.io.BinaryGeoDataFileReader; -import ohd.hseb.geomap.io.ElevationFileReader; -import ohd.hseb.geomap.layer.BaseColorDeterminer; -import ohd.hseb.geomap.layer.CenterPointMapLayer; -import ohd.hseb.geomap.layer.ColorDeterminer; -import ohd.hseb.geomap.layer.ElevationMapLayer; -import ohd.hseb.geomap.layer.GriddedMapLayer; -import ohd.hseb.geomap.layer.MapLayer; -import ohd.hseb.geomap.layer.PolyLineMapLayer; -import ohd.hseb.geomap.layer.PolygonMapLayer; -import ohd.hseb.geomap.layer.XmrgGridToGridAdapter; -import ohd.hseb.geomap.model.ElevationMap; -import ohd.hseb.geomap.model.HrapRowColToLatLonConverter; -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.model.Polygon; -import ohd.hseb.geomap.projection.FlatMapProjection; -import ohd.hseb.geomap.projection.MapProjection; - -public class MapFrame extends JFrame -{ - // ------------------------------------------------------------------------------------------------ - - private JMenuBar _menuBar = null; - - private JPopupMenu _popupMenu = null; - private Point _pointPopUpInvoked = null; - - - private MapCanvas _mapCanvas = null; - private MapProjection _mapProjection = null; - private MapDataManager _dataManager = null; - - // shared Data - private ElevationMap _elevationMap = null; - - // station data - List _sshpFcstPointList = null; - - // station data - List _riverProFcstPointList = null; - - // station data - List _precipMonitorPointList = null; - - // layers - - private MapLayer _stateMapLayer = null; - private MapLayer _countyMapLayer = null; - private MapLayer _basinMapLayer = null; - - - private MapLayer _riverMapLayer = null; - private MapLayer _streamMapLayer = null; - - private MapLayer _elevationImageMapLayer = null; - private MapLayer _elevationContourMapLayer = null; - - private MapLayer _qpeImageMapLayer = null; - private MapLayer _qpeContourMapLayer = null; - - - private MapLayer _centerPointMapLayer = null; - private MapLayer _riverProPointMapLayer = null; - private MapLayer _sshpPointMapLayer = null; - private MapLayer _precipMonitorPointMapLayer = null; - - String _geoDir = "/awips/hydroapps/ob83_fwr/whfs/local/data/geo/"; - - // ------------------------------------------------------------------------------------------------ - - public MapFrame(MapDataManager dataManager) - { - _dataManager = dataManager; - - setTitle("MapFrame Experimental Window"); - - this.addWindowListener(new FrameCloseWindowListener() ); - - LatLonPoint centerLatLonPoint = new LatLonPoint(31.14, -98.12); - - - _mapProjection = new FlatMapProjection(centerLatLonPoint); - - // _mapProjection = new PolarProjection(centerLatLonPoint, 800); - - initGui(); - - } - - // ------------------------------------------------------------------------------------------------ - - private void initGui() - { - - Dimension mapSize = new Dimension(500, 500); - - //init the map canvas - _mapCanvas = new MapCanvas(_mapProjection, mapSize.width, mapSize.height); - _mapCanvas.setBackground(Color.cyan); - - - //create the mapLayers - - _elevationImageMapLayer = createElevationMapLayer(); - _elevationContourMapLayer = createElevationContourMapLayer(_elevationMap); - - _qpeImageMapLayer = createQpeMapLayer(true); - _qpeContourMapLayer = createQpeMapLayer(false); - - - _countyMapLayer = createCountyMapLayer(); - _countyMapLayer.setShouldDraw(false); - - _stateMapLayer = createStateMapLayer(); - _stateMapLayer.setShouldDraw(false); - - _centerPointMapLayer = new CenterPointMapLayer(10, Color.RED); - - - _sshpFcstPointList = _dataManager.getSshpFcstPointList(); - _sshpPointMapLayer = new RiverFcstPointMapLayer(_sshpFcstPointList, Color.ORANGE); - - - _precipMonitorPointList = _dataManager.getPrecipMonitorPointList(); - _precipMonitorPointMapLayer = new PrecipMonitorPointMapLayer(_precipMonitorPointList); - - _riverProFcstPointList = _dataManager.getRiverProFcstPointList(); - _riverProPointMapLayer = new RiverFcstPointMapLayer(_riverProFcstPointList, Color.green); - - - // String riverFilePath = "streams_latlon.LX"; - String riverFilePath = _geoDir + "/" + "rivers_latlon.LX"; - _riverMapLayer = createBinaryLineMapLayer(riverFilePath, Color.BLUE); - - String streamFilePath = _geoDir + "/" + "streams_latlon.LX"; - _streamMapLayer = createBinaryLineMapLayer(streamFilePath, Color.cyan); - - - String basinFilePath = "basins_latlon.LX"; - _basinMapLayer = createBinaryLineMapLayer(_geoDir + "/" + basinFilePath, new Color(244, 164, 96)); - - - //add map layers - _mapCanvas.addMapLayer(_elevationImageMapLayer); - _mapCanvas.addMapLayer(_elevationContourMapLayer); - _mapCanvas.addMapLayer(_stateMapLayer); - _mapCanvas.addMapLayer(_countyMapLayer); - _mapCanvas.addMapLayer(_basinMapLayer); - _mapCanvas.addMapLayer(_riverMapLayer); - _mapCanvas.addMapLayer(_streamMapLayer); - - _mapCanvas.addMapLayer(_qpeImageMapLayer); - _mapCanvas.addMapLayer(_qpeContourMapLayer); - - _mapCanvas.addMapLayer(_sshpPointMapLayer); - _mapCanvas.addMapLayer(_riverProPointMapLayer); - _mapCanvas.addMapLayer(_precipMonitorPointMapLayer); - _mapCanvas.addMapLayer(_centerPointMapLayer); - - _mapCanvas.setPreferredSize(mapSize); - //_mapCanvas.setBackground(Color.magenta); - - JPanel buttonPanel = createButtonPanel(); - - Container contentPane = this.getContentPane(); - contentPane.setBackground(Color.green); - - // setup the main panel - - JPanel panel = new JPanel(); - panel.setBackground(Color.yellow); - - GridBagLayout layoutMgr = new GridBagLayout(); - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - panel.setLayout(layoutMgr); - // col, row numCols numRows Wcol wrow - addComponent(panel, buttonPanel, mainGbc, 0, 0, 1, 1, 0, 0, 0); - addComponent(panel, _mapCanvas, mainGbc, 0, 1, 1, 20, 1, 1, 1); - - _mapCanvas.setVisible(true); - - // contentPane.setLayout(new BorderLayout()); - contentPane.add(panel); - - - - //init the menubar - initMenuBar(); - setJMenuBar(_menuBar); - - // init the mapCanvas popupMenu - initPopupMenu(); - - //add popupListener - _mapCanvas.addMouseListener(new PopupListener()); - - //add other mouse button press listeners - _mapCanvas.addMouseListener(new RecenterAndZoomListener()); - _mapCanvas.addMouseListener(new SelectStationListener()); - - - this.setSize(new Dimension(500, 500)); - this.pack(); - this.setVisible(true); - } - // -------------------------------------------------------------------------------------------- - - - // -------------------------------------------------------------------------------------------- - - private JPanel createButtonPanel() - { - JPanel buttonPanel = new JPanel(); - - //create the buttons - JButton zoomInButton = new JButton("Zoom In"); - JButton zoomOutButton = new JButton("Zoom Out"); - - JButton westButton = new JButton("Pan West"); - JButton eastButton = new JButton("Pan East"); - JButton northButton = new JButton("Pan North"); - JButton southButton = new JButton("Pan South"); - - //arrange them in the gui - buttonPanel.add(zoomInButton); - buttonPanel.add(zoomOutButton); - - //pan buttons - buttonPanel.add(westButton); - buttonPanel.add(eastButton); - buttonPanel.add(northButton); - buttonPanel.add(southButton); - - //add listeners - zoomInButton.addActionListener(new ZoomListener("IN")); - zoomOutButton.addActionListener(new ZoomListener("OUT")); - - northButton.addActionListener(new PanListener(PanListener.NORTH)); - southButton.addActionListener(new PanListener(PanListener.SOUTH)); - eastButton.addActionListener(new PanListener(PanListener.EAST)); - westButton.addActionListener(new PanListener(PanListener.WEST)); - - return buttonPanel; - } - // --------------------------------------------------------------------------------------------------------------- - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - JMenu menu = null; - JMenuItem menuItem = null; - JCheckBoxMenuItem checkBox = null; - - //File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new FrameCloseWindowListener()); - menu.add(menuItem); - - - // Edit/View Menu - menu = new JMenu("View/Edit"); - menu.setMnemonic(KeyEvent.VK_V); - menu.getAccessibleContext().setAccessibleDescription( - "View/Edit time series data."); - _menuBar.add(menu); - - - // edit menu items - - addMapLayerCheckBoxMenuItem(menu, "Show CenterPoint", _centerPointMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show States", _stateMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show Counties", _countyMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show Basins", _basinMapLayer); - - addMapLayerCheckBoxMenuItem(menu, "Show Rivers", _riverMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show Streams", _streamMapLayer); - - addMapLayerCheckBoxMenuItem(menu, "Show QPE Image", _qpeImageMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show QPE Contour", _qpeContourMapLayer); - - addMapLayerCheckBoxMenuItem(menu, "Show Elevation Image", _elevationImageMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show Elevation Contour", _elevationContourMapLayer); - - addMapLayerCheckBoxMenuItem(menu, "Show SSHP Points", _sshpPointMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show RiverPro Points", _riverProPointMapLayer); - addMapLayerCheckBoxMenuItem(menu, "Show PrecipMonitor Points", _precipMonitorPointMapLayer); - - } - // -------------------------------------------------------------------------------------------- - private void addMapLayerCheckBoxMenuItem(JMenu menu, String text, MapLayer mapLayer) - { - JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem(text); - menu.add( checkBoxMenuItem); - - checkBoxMenuItem.addActionListener(new MapLayerToggleButtonListener(mapLayer)); - mapLayer.setShouldDraw(false); - } - - // -------------------------------------------------------------------------------------------- - private void initPopupMenu() - { - _popupMenu = new JPopupMenu(); - JPopupMenu menu = _popupMenu; - JMenuItem menuItem = null; - - - // zooming - - menuItem = new JMenuItem("In"); - menuItem.addActionListener(new ZoomListener("IN")); - menu.add(menuItem); - - menuItem = new JMenuItem("Out"); - menuItem.addActionListener(new ZoomListener("OUT")); - menu.add(menuItem); - - //recentering - - menuItem = new JMenuItem("Recenter"); - menuItem.addActionListener(new RecenterActionListener()); - menu.add(menuItem); - - JSeparator separator = new JSeparator(); - menu.add(separator); - - //panning - menuItem = new JMenuItem("Up"); - menuItem.addActionListener(new PanListener(PanListener.NORTH)); - menu.add(menuItem); - - menuItem = new JMenuItem("Down"); - menuItem.addActionListener(new PanListener(PanListener.SOUTH)); - menu.add(menuItem); - - menuItem = new JMenuItem("Left"); - menuItem.addActionListener(new PanListener(PanListener.WEST)); - menu.add(menuItem); - - menuItem = new JMenuItem("Right"); - menuItem.addActionListener(new PanListener(PanListener.EAST)); - menu.add(menuItem); - - - } - // --------------------------------------------------------------------------------------------------------------- - - - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - -// how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - -// what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - -// the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY, - int fill) - { - - gbc.fill = fill; - - addComponent(container, component, gbc ,column, row, columnCells, rowCells, weightX, weightY); - - return; - } - - - public MapLayer createStaticMapLayer() - { - List latLongPointList = getLatLongPointList(34, 42, -76); - Polygon polygon = new Polygon(latLongPointList); - - List polygonList = new ArrayList(); - - polygonList.add(polygon); - - MapLayer mapLayer = new PolygonMapLayer(polygonList); - mapLayer.setColor(Color.RED); - - return mapLayer; - - } - - public MapLayer createBinaryLineMapLayer(String filePath, Color color) - { - - BinaryGeoDataFileReader reader = new BinaryGeoDataFileReader(filePath); - List lineList = reader.readLineList(); - MapLayer mapLayer = new PolyLineMapLayer(lineList); - mapLayer.setColor(color); - - return mapLayer; - } - - - public MapLayer createElevationMapLayer() - { - String header = "MapFrame.createElevationMapLayer(): "; - String fileName = "topography"; - //String polygonFileDirPath = "/awips/fxa/data/localizationDataSets/RHA"; - - String dirPath = _geoDir; - - String filePath = dirPath + '/' + fileName; - - CodeTimer readTimer = new CodeTimer(); - readTimer.start(); - // ElevationFileReaderSlow reader = new ElevationFileReaderSlow(filePath); - ElevationFileReader reader = new ElevationFileReader(filePath); - _elevationMap = reader.read(); - readTimer.stop(header + "elevation file reading took "); - // System.out.println("elevationMap = " + map); - - ElevationMapLayer mapLayer = new ElevationMapLayer(_elevationMap, false); - - mapLayer.setColor(Color.red); - - return mapLayer; - - } - - - public MapLayer createElevationContourMapLayer(ElevationMap map) - { - ElevationMapLayer mapLayer = new ElevationMapLayer(map, true); - - mapLayer.setColor(Color.red); - - return mapLayer; - } - - - - public MapLayer createCountyMapLayer() - { - String fileName = "reg_county.bcd"; - // String dirPath = "/awips/fxa/data/localizationDataSets/RHA"; //the normal location for this stuff - String dirPath = _geoDir + "/chip"; - String filePath = dirPath + '/' + fileName; - - MapLayer mapLayer = createBCDPolygonMapLayer(filePath, Color.white, true); - - return mapLayer; - - } - - public MapLayer createBCDPolygonMapLayer(String filePath, Color color) - { - return createBCDPolygonMapLayer(filePath, color, false); - } - - public MapLayer createBCDPolygonMapLayer(String filePath, Color color, boolean setLatLonBounds) - { - BCDFileReader reader = new BCDFileReader(filePath); - List polygonList = reader.readPolygonList(); - - MapLayer mapLayer = new PolygonMapLayer(polygonList); - mapLayer.setColor(color); - - if (setLatLonBounds) - { - LatLonBounds bounds = reader.getLatLonBounds(); - _mapCanvas.setLatLonBounds(bounds); - // _mapCanvas.repaint(); - - } - - return mapLayer; - - } - public MapLayer createStateMapLayer() - { - String fileName = "conandsta.bcd"; - String dirPath = "/awips/fxa/data/"; - - String filePath = dirPath + '/' + fileName; - - MapLayer mapLayer = createBCDPolygonMapLayer(filePath, Color.white); - - return mapLayer; - - } - - // ------------------------------------------------------------------------------------------------ - - public MapLayer createQpeMapLayer(boolean shouldDrawImage) - { - - //set up the log file and the XmrgReader - String logDirPath = "/awips/hydroapps/ob83_fwr/whfs/local/data/log/misc"; - String logFileName = "MapFrame.xmrgReader.log"; - Logger logger = new FileLogger(logDirPath + "/" + logFileName); - XmrgReader reader = new XmrgReader(logger); - - - //get the time of the latest hour in millis - long millisPerHour = 1000 * 60 * 60; - long time = System.currentTimeMillis()/ millisPerHour ; - time *= millisPerHour; - - //assemble the filePath - String fileName = "chip.xmrg"; - String dirPath = "/awips/hydroapps/ob83_fwr/precip_proc/local/data/mpe/qpe"; - String filePath = dirPath + '/' + fileName; - - - //load the grid - XmrgGrid xmrgGrid = reader.loadGrid(time, filePath); - XmrgGridToGridAdapter grid = new XmrgGridToGridAdapter(xmrgGrid); - - //create the mapLayer - RowColToLatLonTranslator translator = new HrapRowColToLatLonConverter(xmrgGrid.getBaseRow(), - xmrgGrid.getBaseCol()); - - String[] colorNameArray = { "GRAY30", - "GRAY30", - "GRAY30", - "DODGERBLUE1", - "CYAN", - "DARKGREEN", - "GREEN", - "GREENYELLOW", - "YELLOW", - "GOLD2", - "DARKORANGE1", - "RED", - "RED3", - "RED4", - "MAGENTA1", - "DARKORCHID", - "DARKTURQUOISE" - }; - - double[] levelArray = {0.0, - 0.1, - 0.2, - 0.3, - 0.4, - 0,5, - 0.7, - 1.2, - 1.5, - 1.7, - 2.0, - 2.5, - 3.0 - }; - - - - ColorDeterminer colorDeterminer = new BaseColorDeterminer(colorNameArray, levelArray); - - MapLayer mapLayer = new GriddedMapLayer(grid, translator, colorDeterminer, shouldDrawImage); - - return mapLayer; - - } - - // ------------------------------------------------------------------------------------------------ - - // --------------------------------------------------------------------------------------------- - - public void redrawIt() - { - repaint(); - } - - - // ------------------------------------------------------------------------------------------------ - public static List getLatLongPointList(double lowLat, double highLat, double lon) - { - List pointList = new ArrayList(); - - for (double lat = lowLat; lat <= highLat; lat++) - { - LatLonPoint point = new LatLonPoint(lat, lon); - pointList.add(point); - - } - - return pointList; - } - - // ------------------------------------------------------------------------------------------------ - private class StateToggleButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent event) - { - JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) event.getSource(); - _stateMapLayer.setShouldDraw(checkBox.isSelected()); - _mapCanvas.repaint(); - } - } - - // ------------------------------------------------------------------------------------------------ - private class MapLayerToggleButtonListener implements ActionListener - { - private MapLayer _mapLayer = null; - - public MapLayerToggleButtonListener(MapLayer mapLayer) - { - _mapLayer = mapLayer; - } - - public void actionPerformed(ActionEvent event) - { - JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) event.getSource(); - _mapLayer.setShouldDraw(checkBox.isSelected()); - _mapCanvas.repaint(); - } - } - // ------------------------------------------------------------------------------------------------ - private class CountyToggleButtonListener implements ActionListener - { - - - public void actionPerformed(ActionEvent event) - { - JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) event.getSource(); - _countyMapLayer.setShouldDraw(checkBox.isSelected()); - _mapCanvas.repaint(); - } - } - // ------------------------------------------------------------------------------------------------ - - - private class FrameCloseWindowListener extends WindowAdapter implements ActionListener - { - public void windowClosing(WindowEvent evt) - { - dispose(); - System.exit(0); - } - - public void actionPerformed(ActionEvent event) - { - dispose(); - System.exit(0); - } - - } - // ------------------------------------------------------------------------------------------------ - private class PanListener implements ActionListener - { - private static final int NORTH = 0; - private static final int SOUTH = 1; - private static final int EAST = 2; - private static final int WEST = 3; - - - private int _direction = -1; - - private double _panProportion = 0.25; - - public PanListener(int direction) - { - _direction = direction; - } - - public void actionPerformed(ActionEvent evt) - { - switch (_direction) - { - case NORTH: - { - _mapCanvas.pan(_panProportion, 0); - break; - } - - case SOUTH : - { - _mapCanvas.pan( - _panProportion, 0); - break; - } - - case EAST : - { - _mapCanvas.pan(0, _panProportion); - break; - } - - case WEST : - { - _mapCanvas.pan(0, - _panProportion); - break; - } - - } - } - } //end PanListener - - // ------------------------------------------------------------------------------------------------ - - private class ZoomListener implements ActionListener - { - - private boolean shouldZoomIn = false; - - public ZoomListener(String type) - { - if (type.equalsIgnoreCase("IN")) - { - shouldZoomIn = true; - } - else - { - shouldZoomIn = false; - } - } - - public void actionPerformed(ActionEvent evt) - { - final double zoomInFactor = 1.5; - final double zoomOutFactor = 1.0/zoomInFactor; - double zoomFactor = 1; - - double mapScaleFactor = _mapCanvas.getMapScaleFactor(); - - if (shouldZoomIn) - { - zoomFactor = zoomInFactor; - } - else - { - zoomFactor = zoomOutFactor; - } - - _mapCanvas.zoom(zoomFactor); - - } - - } //end inner class ZoomListener - - //------------------------------------------------------------------------------------------------- - - private class RecenterActionListener implements ActionListener - { - public void actionPerformed(ActionEvent event) - { - - _mapCanvas.recenterAtXY(_pointPopUpInvoked.x, _pointPopUpInvoked.y ); - - } - } - // ------------------------------------------------------------------------------------------------ - private class RecenterAndZoomListener extends MouseAdapter - { - public void mousePressed(MouseEvent event) - { - int buttonId = event.getButton(); - - if (buttonId == MouseEvent.BUTTON1) - { - System.out.println("MapFrame.RecenterListener: would be selecting now."); - } - else if (buttonId == MouseEvent.BUTTON2) - { - _mapCanvas.recenterAtXY(event.getX(), event.getY() ); - _mapCanvas.zoom(1.5); - } - - } - } - - //------------------------------------------------------------------------------------------------- - - private class PopupListener extends MouseAdapter - { - - public void mousePressed(MouseEvent event) - { - if (event.getButton() == MouseEvent.BUTTON3 ) - { - _pointPopUpInvoked = event.getPoint(); - _popupMenu.show(_mapCanvas, _pointPopUpInvoked.x, _pointPopUpInvoked.y); - } - return; - } - } - - // ------------------------------------------------------------------------------------------------ - - private class SelectStationListener extends MouseAdapter - { - public void mousePressed(MouseEvent event) - { - if (event.getButton() == MouseEvent.BUTTON1) - { - StationPoint fcstPoint = findClosestStation(event.getPoint()); - if (fcstPoint != null) - { - - System.out.println("MapFrame.SelectStationListener: you just selected " + - fcstPoint.getId() + "." ); - } - else - { - System.out.println("MapFrame.SelectStationListener: No close point could be found ." ); - } - } - } - - } //end SelectStationListener - //------------------------------------------------------------------------------------------------- - - private StationPoint findClosestStation(Point clickedPoint) - { - StationPoint closestFcstPoint = null; - double closestDistance = 0.0; - - for (StationPoint fcstPoint : _sshpFcstPointList) - { - Point screenPoint = _mapProjection.getScreenPoint(fcstPoint.getLatLonPoint()); - - double distance = clickedPoint.distance(screenPoint); - - if ( (closestFcstPoint == null) || (distance < closestDistance) ) - { - closestDistance = distance; - closestFcstPoint = fcstPoint; - } - } - - return closestFcstPoint; - } - - //------------------------------------------------------------------------------------------------- - - public static void main(String[] args) - { - if (args.length < 2) - { - System.out.println("Usage: java ohd.hseb.geomap.MapFrame "); - } - - String connectionString = args[0]; - String logFilePath = args[1]; - Logger logger = new FileLogger(logFilePath); - - MapDataManager dataManager = new MapDataManager(connectionString, logger); - - MapFrame frame = new MapFrame(dataManager); - - frame.setVisible(true); - - frame.redrawIt(); - } - // ------------------------------------------------------------------------------------------------ - - - -} //end class MapFrame diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/PrecipMonitorPointMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/PrecipMonitorPointMapLayer.java deleted file mode 100644 index f1be8a50d8..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/PrecipMonitorPointMapLayer.java +++ /dev/null @@ -1,139 +0,0 @@ -package ohd.hseb.geomap.examples; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; -import java.util.List; - -import ohd.hseb.geomap.layer.BaseMapLayer; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.projection.MapProjection; - -public class PrecipMonitorPointMapLayer extends BaseMapLayer -{ - - private List _stationPointList = null; - - // ----------------------------------------------------------------------------------------------- - - public PrecipMonitorPointMapLayer(List pointList ) - { - _stationPointList = pointList; - } - - // ----------------------------------------------------------------------------------------------- - - public void draw(Graphics g, MapProjection projection) - { - String header = "SshpPointMapLayer.draw(): "; - // System.out.println(header); - - - for(StationPoint point : getStationPointList()) - { - // System.out.println(header + point); - drawStationPoint(g, projection, point); - } - } - - // ----------------------------------------------------------------------------------------------- - - private void drawStationPoint(Graphics g, MapProjection projection, StationPoint stationPoint) - { - String header = "PrecipMonitorPointMapLayer.drawStationPoint(): "; - // System.out.println(header); - - LatLonPoint latLonPoint = stationPoint.getLatLonPoint(); - - int size = 2; - - Point screenPoint = projection.getScreenPoint(latLonPoint); - - // drawTriangle(g, size, Color.GREEN, screenPoint); - drawCircle(g, size, Color.MAGENTA, screenPoint); - - // drawLabel(g, stationPoint.getId(), Color.WHITE, screenPoint, 5, 0); - } - - // ----------------------------------------------------------------------------------------------- - - public void drawLabel(Graphics g, String text, - Color color, Point screenPoint, - int xOffset, int yOffset) - { - - g.setColor(color); - g.drawString(text, screenPoint.x + xOffset, screenPoint.y + yOffset); - } - - // ----------------------------------------------------------------------------------------------- - public void drawTriangle(Graphics g, - int size, - Color color, - Point screenPoint) - { - - java.awt.Polygon p = new java.awt.Polygon(); - - int x1 = screenPoint.x; - int y1 = screenPoint.y - size/2; - - int x2 = screenPoint.x - size/2; - int y2 = screenPoint.y + size/2; - - int x3 = screenPoint.x + size/2; - int y3 = screenPoint.y + size/2; - - p.addPoint(x1, y1); - p.addPoint(x2, y2); - p.addPoint(x3, y3); - - g.setColor(color); - - g.fillPolygon(p); - - } - - // ----------------------------------------------------------------------------------------------- - - public void drawCircle(Graphics g, - int size, - Color color, - Point screenPoint) - { - - Graphics2D g2 = (Graphics2D) g; - - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - g2.setColor(color); - - int halfSize = size/2; - - g2.fillOval(screenPoint.x - halfSize, - screenPoint.y - halfSize, - size, size); - - return; - } - - // ----------------------------------------------------------------------------------------------- - // ----------------------------------------------------------------------------------------------- - - public void setStationPointList(List pointList) - { - _stationPointList = pointList; - } - - public List getStationPointList() - { - return _stationPointList; - } - - // ----------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/RiverFcstPointMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/RiverFcstPointMapLayer.java deleted file mode 100644 index ac5956db30..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/RiverFcstPointMapLayer.java +++ /dev/null @@ -1,113 +0,0 @@ -package ohd.hseb.geomap.examples; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - - -import java.util.List; - -import ohd.hseb.geomap.layer.BaseMapLayer; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.projection.MapProjection; - - -public class RiverFcstPointMapLayer extends BaseMapLayer -{ - private List _fcstPointList = null; - private Color _color = null; - - // ----------------------------------------------------------------------------------------------- - - public RiverFcstPointMapLayer(List pointList, Color color) - { - _fcstPointList = pointList; - _color = color; - } - - // ----------------------------------------------------------------------------------------------- - - public void draw(Graphics g, MapProjection projection) - { - String header = "RiverFcstPointMapLayer.draw(): "; - // System.out.println(header); - - - for(StationPoint point : getFcstPointList()) - { - // System.out.println(header + point); - drawFcstPoint(g, projection, point); - } - } - - // ----------------------------------------------------------------------------------------------- - - private void drawFcstPoint(Graphics g, MapProjection projection, StationPoint fcstPoint) - { - String header = "RiverFcstPointMapLayer.drawFcstPoint(): "; - // System.out.println(header); - - LatLonPoint latLonPoint = fcstPoint.getLatLonPoint(); - - int size = 8; - - Point screenPoint = projection.getScreenPoint(latLonPoint); - - drawTriangle(g, size, _color, screenPoint); - - drawLabel(g, fcstPoint.getId(), Color.WHITE, screenPoint, 5, 0); - } - - // ----------------------------------------------------------------------------------------------- - - public void drawLabel(Graphics g, String text, - Color color, Point screenPoint, - int xOffset, int yOffset) - { - - g.setColor(color); - g.drawString(text, screenPoint.x + xOffset, screenPoint.y + yOffset); - } - - // ----------------------------------------------------------------------------------------------- - public void drawTriangle(Graphics g, - int size, - Color color, - Point screenPoint) - { - - java.awt.Polygon p = new java.awt.Polygon(); - - int x1 = screenPoint.x; - int y1 = screenPoint.y - size/2; - - int x2 = screenPoint.x - size/2; - int y2 = screenPoint.y + size/2; - - int x3 = screenPoint.x + size/2; - int y3 = screenPoint.y + size/2; - - p.addPoint(x1, y1); - p.addPoint(x2, y2); - p.addPoint(x3, y3); - - g.setColor(color); - - g.fillPolygon(p); - - } - // ----------------------------------------------------------------------------------------------- - - public void setFcstPointList(List pointList) - { - _fcstPointList = pointList; - } - - public List getFcstPointList() - { - return _fcstPointList; - } - - // ----------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/StationPoint.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/StationPoint.java deleted file mode 100644 index 612611c1a3..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/examples/StationPoint.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.geomap.examples; - -import ohd.hseb.geomap.model.LatLonPoint; - -public class StationPoint -{ - private String _id; - private String _name; - private LatLonPoint _latLonPoint; - - // ---------------------------------------------------------------------------- - - public StationPoint(String id, String name, LatLonPoint latLonPoint) - { - setId(id); - setName(name); - setLatLonPoint(latLonPoint); - - return; - } - - // ---------------------------------------------------------------------------- - - public void setId(String id) - { - _id = id; - } - - // ---------------------------------------------------------------------------- - - public String getId() - { - return _id; - } - - // ---------------------------------------------------------------------------- - - - public void setName(String name) - { - _name = name; - } - - // ---------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - - // ---------------------------------------------------------------------------- - - - public void setLatLonPoint(LatLonPoint latLonPoint) - { - _latLonPoint = latLonPoint; - } - - // ---------------------------------------------------------------------------- - - public LatLonPoint getLatLonPoint() - { - return _latLonPoint; - } - // ---------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/BCDFileReader.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/BCDFileReader.java deleted file mode 100644 index c194a92b11..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/BCDFileReader.java +++ /dev/null @@ -1,161 +0,0 @@ -package ohd.hseb.geomap.io; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.model.Polygon; - -public class BCDFileReader -{ - private DataInputStream _reader = null; - private LatLonBounds _latLonBounds = null; - - // ------------------------------------------------------------------------------- - - public BCDFileReader(String filePath) - { - try - { - _reader = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath))); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - // ------------------------------------------------------------------------------- - - public List readPolygonList() - { - String header = "BCDFileReader.readPolygonList(): "; - - List polygonList = new ArrayList (); - - boolean done = false; - while (! done) - { - Polygon polygon = readPolygon(); - if (polygon != null) - { - polygonList.add(polygon); - } - else // polygon == null - { - done = true; - } - } - - System.out.println(header + "Lat lon bounds are " + _latLonBounds); - - try - { - _reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - return polygonList; - } - - // ------------------------------------------------------------------------------- - - public Polygon readPolygon() - { - String header = "BCDFileReader.readPolygon(): "; - Polygon polygon = null; - List pointList = new ArrayList(); - - try - { - //read header - - int numPoints = _reader.readInt(); - float boundsLat1 = _reader.readFloat(); - float boundsLat2 = _reader.readFloat(); - float boundsLon1 = _reader.readFloat(); - float boundsLon2 = _reader.readFloat(); - - if (_latLonBounds == null) - { - _latLonBounds = new LatLonBounds(boundsLat1, boundsLat2, boundsLon1, boundsLon2); - } - else - { - _latLonBounds.updateLatLonBounds(boundsLat1, boundsLat2, boundsLon1, boundsLon2); - //System.out.println("Lat lon bounds are " + _latLonBounds); - } - - //reader points - for (int i = 0 ; i < numPoints; i++) - { - float lat = _reader.readFloat(); - float lon = _reader.readFloat(); - LatLonPoint point = new LatLonPoint(lat, lon); - pointList.add(point); - } - } - - catch (EOFException e) - { - //not an error - } - catch (IOException e) - { - e.printStackTrace(); - } - - if (pointList.size() > 0) - { - polygon = new Polygon(pointList); - } - - return polygon; - - } - - // ------------------------------------------------------------------------------- - - public List readLineList() - { - List lineList = new ArrayList (); - - return lineList; - } - - // ------------------------------------------------------------------------------- - - public List readPointList() - { - List pointList = new ArrayList (); - - return pointList; - } - - // ------------------------------------------------------------------------------- - - public void setLatLonBounds(LatLonBounds latLonBounds) - { - _latLonBounds = latLonBounds; - } - - // ------------------------------------------------------------------------------- - - public LatLonBounds getLatLonBounds() - { - return _latLonBounds; - } - - // ------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/BinaryGeoDataFileReader.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/BinaryGeoDataFileReader.java deleted file mode 100644 index 5c587fa66f..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/BinaryGeoDataFileReader.java +++ /dev/null @@ -1,158 +0,0 @@ -package ohd.hseb.geomap.io; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.EndianConverter; -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; - -public class BinaryGeoDataFileReader -{ - private DataInputStream _reader = null; - private LatLonBounds _latLonBounds = null; - - // ------------------------------------------------------------------------------- - - public BinaryGeoDataFileReader(String filePath) - { - try - { - _reader = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath))); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - // ------------------------------------------------------------------------------- - - public List readLineList() - { - String header = "BinaryGeoDataFileReader.readLineList(): "; - - List lineList = new ArrayList (); - - int lineCount = 0; - System.out.println(header); - - try - { - - boolean done = false; - while (! done) - { - LatLonPolyline latLonPolyline = readLine(); - if (latLonPolyline != null) - { - lineList.add(latLonPolyline); - lineCount++; - } - else // line == null - { - done = true; - } - } - - System.out.println(header + "lineCount = " + lineCount); - - - _reader.close(); - } - catch(EOFException e) - { - //do nothing - } - catch (IOException e) - { - e.printStackTrace(); - } - - return lineList; - } - - // ------------------------------------------------------------------------------- - - private LatLonPolyline readLine() throws IOException - { - String header = "BinaryGeoDataFileReader.readLine(): "; - - String lid = readNCharsIntoString(9); - String name = readNCharsIntoString(21); - - int order = readInt(); - - int pointCount = readInt(); - // System.out.println(header + "lid = " + lid); - // System.out.println(header + "name = " + name); - - //System.out.println(header + "pointCount = " + pointCount); - - - List pointList = new ArrayList(); - - for (int i = 0; i < pointCount; i++) - { - - float lat = readFloat(); - float lon = readFloat(); - lon *= -1; - - LatLonPoint latLonPoint = new LatLonPoint(lat, lon); - - // System.out.println(header + "latLonPoint = " + latLonPoint); - - pointList.add(latLonPoint); - } - - LatLonPolyline latLonPolyline = new LatLonPolyline(pointList); - - - return latLonPolyline; - } - // ------------------------------------------------------------------------------- - private int readInt() throws IOException - { - - - int number = _reader.readInt(); - - return EndianConverter.convert(number); - - } - // ------------------------------------------------------------------------------- - - private float readFloat() throws IOException - { - float number = _reader.readFloat(); - - return EndianConverter.convert(number); - - } - - // ------------------------------------------------------------------------------- - private String readNCharsIntoString(int charCount) throws IOException - { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < charCount; i++) - { - char c = (char) _reader.readByte(); - if (i < charCount - 1) - { - buffer.append(c); - } - } - - return buffer.toString(); - - } - // ------------------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/ElevationFileReader.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/ElevationFileReader.java deleted file mode 100644 index 2d610ab75e..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/ElevationFileReader.java +++ /dev/null @@ -1,115 +0,0 @@ -package ohd.hseb.geomap.io; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.StringTokenizer; - -import ohd.hseb.geomap.model.ElevationMap; -import ohd.hseb.geomap.model.LatLonBounds; - -public class ElevationFileReader -{ - private BufferedReader _reader = null; - - // ------------------------------------------------------------------------------- - - public ElevationFileReader(String filePath) - { - try - { - _reader = new BufferedReader(new FileReader(filePath)); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - // ------------------------------------------------------------------------------- - - public ElevationMap read() - { - ElevationMap map = null; - - try - { - String line = _reader.readLine(); - - - map = readHeader(line); - - line = _reader.readLine(); - readBody(line, map); - _reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - - return map; - } - // ------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------- - public ElevationMap readHeader(String line) throws IOException - { - - String header = "ElevationFileReaderSlow.readHeader(): "; - StringTokenizer tokenizer = new StringTokenizer(line); - - double lat1 = Double.parseDouble(tokenizer.nextToken()); - double lon1 = Double.parseDouble(tokenizer.nextToken()); - - // negate the longitude - lon1 *= -1; - - double latRange = Double.parseDouble(tokenizer.nextToken()); - double lonRange = Double.parseDouble(tokenizer.nextToken()); - - System.out.println(header + "lat1 = " + lat1 + " lon1 = " + lon1 + - "latRange = " + latRange + "longRange = " + lonRange); - - double lat2 = lat1 - latRange; - double lon2 = lon1 + lonRange; - - double latResInArcMinutes = Double.parseDouble(tokenizer.nextToken()); - double lonResInArcMinutes = Double.parseDouble(tokenizer.nextToken()); - - LatLonBounds latLonBounds = new LatLonBounds(lat1, lat2, lon1, lon2); - - System.out.println(header + "lat lon bounds = " + latLonBounds); - - - double latResInDegrees = latResInArcMinutes/60.0; - double lonResInDegrees = lonResInArcMinutes/60.0; - - - ElevationMap map = new ElevationMap(latLonBounds, latResInDegrees, lonResInDegrees); - - return map; - - } - // ------------------------------------------------------------------------------- - public void readBody(String line, ElevationMap map) throws IOException - { - StringTokenizer tokenizer = new StringTokenizer(line); - short elevation = 0; - - int rowCount = map.getRowCount(); - int colCount = map.getColCount(); - - for (int row = 0; row < rowCount; row++) - { - for (int col = 0; col < colCount; col++) - { - elevation = Short.parseShort(tokenizer.nextToken()); - - map.setValue(row, col, elevation); - } - } - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/ElevationFileReaderSlow.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/ElevationFileReaderSlow.java deleted file mode 100644 index bd255b2393..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/io/ElevationFileReaderSlow.java +++ /dev/null @@ -1,123 +0,0 @@ -package ohd.hseb.geomap.io; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.Scanner; - -import ohd.hseb.geomap.model.ElevationMap; -import ohd.hseb.geomap.model.LatLonBounds; - -public class ElevationFileReaderSlow -{ - private BufferedReader _reader = null; - - // ------------------------------------------------------------------------------- - - public ElevationFileReaderSlow(String filePath) - { - try - { - int size = 10000000; - _reader = new BufferedReader(new FileReader(filePath), size); - // _reader = new BufferedReader(new FileReader(filePath)); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - // ------------------------------------------------------------------------------- - - public ElevationMap read() - { - ElevationMap map = null; - - Scanner scanner = new Scanner(_reader); - - try - { - map = readHeader(scanner); - readBody(scanner, map); - _reader.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - - return map; - } - // ------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------- - public ElevationMap readHeader(Scanner scanner) throws IOException - { - - String header = "ElevationFileReaderSlow.readHeader(): "; - - - double lat1 = scanner.nextDouble(); - double lon1 = scanner.nextDouble(); - - // negate the longitude - lon1 *= -1; - - double latRange = scanner.nextDouble(); - double lonRange = scanner.nextDouble(); - - System.out.println(header + "lat1 = " + lat1 + " lon1 = " + lon1 + - "latRange = " + latRange + "longRange = " + lonRange); - - double lat2 = lat1 - latRange; - double lon2 = lon1 + lonRange; - - double latResInArcMinutes = scanner.nextDouble(); - double lonResInArcMinutes = scanner.nextDouble(); - - LatLonBounds latLonBounds = new LatLonBounds(lat1, lat2, lon1, lon2); - - System.out.println(header + "lat lon bounds = " + latLonBounds); - - - double latResInDegrees = latResInArcMinutes/60.0; - double lonResInDegrees = lonResInArcMinutes/60.0; - - - ElevationMap map = new ElevationMap(latLonBounds, latResInDegrees, lonResInDegrees); - - return map; - - } - // ------------------------------------------------------------------------------- - public void readBody(Scanner scanner, ElevationMap map) throws IOException - { - boolean done = false; - - double northLat = map.getLatLonBounds().getNorthLat(); - double southLat = map.getLatLonBounds().getSouthLat(); - double westLon = map.getLatLonBounds().getWestLon(); - double eastLon = map.getLatLonBounds().getEastLon(); - - double currentLat = northLat; - double currentLon = westLon; - - short elevation = 0; - - int rowCount = map.getRowCount(); - int colCount = map.getColCount(); - - for (int row = 0; row < rowCount; row++) - { - for (int col = 0; col < colCount; col++) - { - elevation = scanner.nextShort(); - - map.setValue(row, col, elevation); - } - } - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/BaseColorDeterminer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/BaseColorDeterminer.java deleted file mode 100644 index 62d60fde81..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/BaseColorDeterminer.java +++ /dev/null @@ -1,96 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.util.Map; - -import ohd.hseb.util.io.RGBTextFileReader; - -public class BaseColorDeterminer implements ColorDeterminer -{ - // ------------------------------------------------------------------------ - - private static Color[] _colorArray = null; - private static String[] _colorNameArray = null; - private static double[] _levelArray = null; - // ------------------------------------------------------------------------ - - public BaseColorDeterminer(String[] colorNameArray, double[] levelArray) - { - _colorArray = initColorArray(colorNameArray); - setLevelArray(levelArray); - } - - // ------------------------------------------------------------------------ - public Color getColorByValue(double value) - { - - String header = "BaseColorDeterminer.getColorByValue(): "; - - int index = getColorIndexFromValue(value); - - - Color color = _colorArray[index]; - - return color; - } - - // ------------------------------------------------------------------------------------------------------- - private int getColorIndexFromValue(double value) - { - int index = 0; - - int maxValue = 10; - int intervalCount = 20; - - double increment = (double) maxValue / (double) intervalCount; - - - for (index = 0; index < _levelArray.length; index++) - { - if (value <= _levelArray[index]) - { - break; - } - } - - - return index; - } - // ------------------------------------------------------------------------------------------------------- - public double[] getLevelArray() - { - return _levelArray; - } - // ------------------------------------------------------------------------ - private void setLevelArray(double[] levelArray) - { - _levelArray = levelArray; - } - // ------------------------------------------------------------------------ - - - private Color[] initColorArray(String[] colorNameArray) - { - - RGBTextFileReader reader = new RGBTextFileReader(); - String filePath = "/usr/lib/X11/rgb.txt"; - - Map map = reader.read(filePath); - - int size = colorNameArray.length; - - Color[] colorArray = new Color[size]; - - for (int i = 0; i < colorNameArray.length; i++) - { - String colorName = colorNameArray[i].toUpperCase(); - - Color color = map.get(colorName); - colorArray[i] = color; - // System.out.println("color = " + colorName + " " + color); - } - - return colorArray; - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/BaseMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/BaseMapLayer.java deleted file mode 100644 index 834cc74ee8..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/BaseMapLayer.java +++ /dev/null @@ -1,45 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; - -import ohd.hseb.geomap.projection.MapProjection; - -public abstract class BaseMapLayer implements MapLayer -{ - private Color _color = null; - private boolean _shouldDraw = true; - - // ------------------------------------------------------------------------------------ - - public void setShouldDraw(boolean shouldDraw) - { - _shouldDraw = shouldDraw; - } - - // ------------------------------------------------------------------------------------ - - public boolean shouldDraw() - { - return _shouldDraw; - } - - // ------------------------------------------------------------------------------------ - - public abstract void draw(Graphics g, MapProjection projection); - - // ------------------------------------------------------------------------------------ - - public void setColor(Color color) - { - _color = color; - } - - // ------------------------------------------------------------------------------------ - - public Color getColor() - { - return _color; - } - // ------------------------------------------------------------------------------------ -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/CenterPointMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/CenterPointMapLayer.java deleted file mode 100644 index 2e7a153c16..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/CenterPointMapLayer.java +++ /dev/null @@ -1,44 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; - -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.projection.MapProjection; - -public class CenterPointMapLayer extends BaseMapLayer -{ - - private int _size = 6; - private int _halfSize = 3; - private Color _color = null; - - public CenterPointMapLayer(int size, Color color) - { - _size = size; - _halfSize = _size/2; - _color = color; - } - - public void draw(Graphics graphics, MapProjection projection) - { - Graphics2D g2 = (Graphics2D) graphics; - LatLonPoint centerLatLonPoint = projection.getCenterLatLon(); - - Point centerXYPoint = projection.getScreenPoint(centerLatLonPoint); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - g2.setColor(_color); - - g2.fillOval(centerXYPoint.x - _halfSize, - centerXYPoint.y - _halfSize, - _size, _size); - - } - - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/ColorDeterminer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/ColorDeterminer.java deleted file mode 100644 index 44bb5194b2..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/ColorDeterminer.java +++ /dev/null @@ -1,10 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; - -public interface ColorDeterminer -{ - Color getColorByValue(double value); - double[] getLevelArray(); - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/ElevationMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/ElevationMapLayer.java deleted file mode 100644 index 28e64d8fad..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/ElevationMapLayer.java +++ /dev/null @@ -1,737 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import ohd.hseb.geomap.DrawingTools; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.io.RGBTextFileReader; -import ohd.hseb.geomap.model.ElevationMap; -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.projection.MapProjection; -import ohd.hseb.geomap.contour.RowToLatLonContourer; - - -public class ElevationMapLayer extends BaseMapLayer -{ - private ElevationMap _elevationMap = null; - - private List < List > _listOfLatLonPolylineLists = null; //the outer list is a list of a list of polylines for each contour level - - private boolean _useContouring = false; - private boolean _haveComputedContour = false; - - private short[][] _colorIndexArray = null; //correlates to the map coordinates - private int _rowCount = 0; - private int _colCount = 0; - - private static Color[] _colorArray = null; - private static String[] _colorNameArray = { "grey28", - "grey36", - "grey43", - "grey51", - "grey59", - "DarkGrey", - "grey74", - "grey25", - "grey31", - "grey38", - "burlywood4", - "wheat4", - "LightYellow4", - "burlywood3", - "grey19", - "grey25", - "salmon4", - "LightSalmon4", - "burlywood4", - "burlywood4", - "LightSalmon3", - "grey28", - "DarkOliveGreen", - "DarkOliveGreen4", - "LightGoldenrod4", - "khaki4", - "DarkOliveGreen3", - "DarkKhaki", - "DarkGreen", - "DarkGreen", - "DarkGreen", - "green4", - "green4", - "green4", - "green3" }; - - - - static - { - - initColorArray(); - - } - - // -------------------------------------------------------------------------------------------------- - - public ElevationMapLayer(ElevationMap elevationMap, boolean useContouring) - { - setElevationMap(elevationMap); - - determineColorsFromMap(elevationMap); - - setUseContouring(useContouring); - - } - // -------------------------------------------------------------------------------------------------- - private void determineColorsFromMap(ElevationMap elevationMap) - { - int rowCount = elevationMap.getRowCount(); - int colCount = elevationMap.getColCount(); - - _rowCount = rowCount; - _colCount = colCount; - - _colorIndexArray = new short[rowCount][colCount]; - - for (int row = 0; row < rowCount; row++ ) - { - for (int col = 0; col < colCount; col++) - { - - int value = _elevationMap.getValue(row, col); - - _colorIndexArray[row][col] = getColorIndexFromValue(value, row, col); - - } - } - } - // -------------------------------------------------------------------------------------------------- - - private static void initColorArray() - { - - RGBTextFileReader reader = new RGBTextFileReader(); - String filePath = "/usr/lib/X11/rgb.txt"; - - Map map = reader.read(filePath); - - int size = _colorNameArray.length; - - _colorArray = new Color[size]; - - for (int i = 0; i < _colorNameArray.length; i++) - { - String colorName = _colorNameArray[i].toUpperCase(); - - Color color = map.get(colorName); - _colorArray[i] = color; - // System.out.println("color = " + colorName + " " + color); - } - - } - // -------------------------------------------------------------------------------------------------- - private static void initColorArrayOld() - { - final int colorCount = 12; - final int intensityIncrement = 20; - _colorArray = new Color[colorCount]; - int intensity = 20; - - - for (int i = 0; i < colorCount; i++) - { - - Color color = new Color (intensity, intensity, intensity); - - _colorArray[i] = color; - - intensity += intensityIncrement; - - } - - } - - // -------------------------------------------------------------------------------------------------- - public void draw(Graphics g, MapProjection projection) - { - //drawImage(g, projection); - - if (useContouring()) - { - drawContour(g, projection); - } - else - { - drawImageByLatLon(g, projection); - } - } - - // -------------------------------------------------------------------------------------------------- - private void drawContour(Graphics g, MapProjection projection) - { - String header = "ElevationMapLayer.drawContour() "; - - System.out.println(header); - - if (! haveComputedContour()) - { - computeContour(); - setHaveComputedContour(true); - } - - - Color colorArray[] = {Color.red, Color.yellow, Color.blue, Color.green, Color.white }; - drawContourLines(g, projection, colorArray, _listOfLatLonPolylineLists); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void computeContour() - { - RowToLatLonContourer contourer = new RowToLatLonContourer(_elevationMap.getValueArray(), _elevationMap); - double[] levelArray = {80.0, 160.0, 240.0, 320.0 }; - _listOfLatLonPolylineLists = contourer.contour(levelArray); - } - // -------------------------------------------------------------------------------------------------- - private void drawContourLines(Graphics g, MapProjection projection, Color[] colorArray, List < List > listOfPolylineLists) - { - int colorIndex = 0; - - for (List polyLineList: listOfPolylineLists ) //for each contour level - { - g.setColor(colorArray[colorIndex]); - for (LatLonPolyline polyline: polyLineList) //for each polyline - { - DrawingTools.drawPolyline(g, projection, polyline); - } - colorIndex++; - } - } - // -------------------------------------------------------------------------------------------------- - - - private void drawImageByLatLon(Graphics g, MapProjection projection) - { - - String header = "ElevationMapLayer.draw(): "; - System.out.println(header); - - LatLonBounds latLonBounds = _elevationMap.getLatLonBounds(); - double origLatRes = _elevationMap.getLatResInDegrees(); - double origLonRes = _elevationMap.getLonResInDegrees(); - - - Point point1 = null; - Point point2 = null; - - int width = 0; - int height = 0; - int halfWidth = 0; - int halfHeight = 0; - - int rectangleCount = 0; - int virtualRectangleCount = 0; - - CodeTimer drawLoopTimer = new CodeTimer(); - CodeTimer drawOnlyTimer = new CodeTimer(); - CodeTimer coordinateTimer = new CodeTimer(); - CodeTimer colorSettingTimer = new CodeTimer(); - CodeTimer adjacentTimer = new CodeTimer(); - CodeTimer timerTimer = new CodeTimer(); - - - drawLoopTimer.start(); - - double northLat = projection.getLatLonBounds().getNorthLat(); - double southLat = projection.getLatLonBounds().getSouthLat(); - double eastLon = projection.getLatLonBounds().getEastLon(); - double westLon = projection.getLatLonBounds().getWestLon(); - - List listResolutionFactors = determineResolutionFactor(northLat,westLon, origLatRes, origLonRes, projection); - - double latResFactor = (Integer) listResolutionFactors.get(0); - double lonResFactor = (Integer) listResolutionFactors.get(1); - - double latRes = origLatRes * latResFactor; - - double lonRes = origLonRes * lonResFactor; - - - for (double lat = northLat; lat >= southLat; lat -= latRes) - { - for (double lon = westLon; lon <= eastLon; lon += lonRes) - { - // timerTimer.restart(); - coordinateTimer.restart(); - // timerTimer.stop(); - - point1 = projection.getScreenPoint(lat, lon); - point2 = projection.getScreenPoint(lat - latRes, lon + lonRes); - - height = (point2.y - point1.y) + 1; - halfHeight = height/2; - - width = (point2.x - point1.x) + 1; - halfWidth = width/2; - - - int x = point1.x - halfWidth; - int y = point1.y - halfHeight; - - int row = _elevationMap.getRow(lat); - int col = _elevationMap.getCol(lon); - - - // timerTimer.restart(); - coordinateTimer.stop(); - // timerTimer.stop(); - - // System.out.println(header + "lat = " + lat + " lon = " + lon + " row = " + row + " col = " + col); - - colorSettingTimer.restart(); - - // int value = _elevationMap.getValue(row, col); - - // int colorIndex = getColorIndexFromValue(value, row, col); - - int colorIndex = getColorIndexFromStoredValues(row, col); - Color color = getColorFromColorIndex(colorIndex); - g.setColor(color); - - colorSettingTimer.stop(); - - - - // adjacentTimer.restart(); - // - // int adjacentRectangleCount = getSameColorAdjacentRectanglesInSameRow(point1, width, row, colorIndex, projection); - // adjacentTimer.stop(); - int adjacentRectangleCount = 0; - - drawOnlyTimer.restart(); - - g.fillRect(x, y, (adjacentRectangleCount + 1) * width, height); - - //g.fillRect(x, y, width, height); - drawOnlyTimer.stop(); - - col += adjacentRectangleCount; //need to increment the column - - rectangleCount++; - virtualRectangleCount += 1 + adjacentRectangleCount; - - - } //end for col - } //end for row - - - drawLoopTimer.stop(header + " nested for loop took "); - System.out.println(header + " the elapsed time of the drawing itself was " + drawOnlyTimer.getElapsedTime() + " in millis. "); - System.out.println(header + " The elapsed time for screen coordinate determination was " + coordinateTimer.getElapsedTime() + " in millis. "); - // System.out.println(header + " The elapsed time for the adjacent pixels determination was " + adjacentTimer.getElapsedTime() + " in millis. "); - System.out.println(header + " The elapsed time for color determination and setting was " + colorSettingTimer.getElapsedTime() + " in millis. "); - // System.out.println(header + " The elapsed time for a single timer was " + timerTimer.getElapsedTime() + " in millis. "); - - - - System.out.println(header + "drew " + rectangleCount + " actual rectangles."); - System.out.println(header + "drew " + virtualRectangleCount + " virtual rectangles."); - - - } - - // -------------------------------------------------------------------------------------------------- - private List determineResolutionFactor(double lat, double lon, double latRes, double lonRes, MapProjection projection) - { - String header = "ElevationMapLayer.determineLatResolutionFactor()"; - - - double newLatRes = latRes; - double newLonRes = lonRes; - - int latFactor = 1; - int lonFactor = 1; - - // double latRes = _elevationMap.getLatResInDegrees(); - // double lonRes = _elevationMap.getLonResInDegrees(); - - - Point point1 = null; - Point point2 = null; - - int width = 0; - int height = 0; - int halfWidth = 0; - int halfHeight = 0; - - boolean done = false; - - while (! done) - { - point1 = projection.getScreenPoint(lat, lon); - point2 = projection.getScreenPoint(lat - newLatRes, lon + newLonRes); - - height = (point2.y - point1.y) + 1; - - width = (point2.x - point1.x) + 1; - - System.out.println(header + " height = " + height + " width = " + width); - - if (height <= 1) - { - newLatRes *= 2; - latFactor *= 2; - - } - - if (width == 1) - { - newLonRes *= 2; - lonFactor *= 2; - } - - if ((height > 1) && (width > 1 )) - { - done = true; - } - } - - System.out.println(header + " latFactor = " + latFactor + " lonFactor = " + lonFactor); - - - List resultList = new ArrayList(); - resultList.add(latFactor); - resultList.add(lonFactor); - - return resultList; - } - // -------------------------------------------------------------------------------------------------- - - public void drawImage(Graphics g, MapProjection projection) - { - - String header = "ElevationMapLayer.drawImage2(): "; - // System.out.println(header); - - LatLonBounds latLonBounds = _elevationMap.getLatLonBounds(); - double latRes = _elevationMap.getLatResInDegrees(); - double lonRes = _elevationMap.getLonResInDegrees(); - - Point point1 = null; - Point point2 = null; - - int width = 0; - int height = 0; - int halfWidth = 0; - int halfHeight = 0; - - int rectangleCount = 0; - int virtualRectangleCount = 0; - - CodeTimer drawLoopTimer = new CodeTimer(); - CodeTimer drawOnlyTimer = new CodeTimer(); - - CodeTimer coordinateTimer = new CodeTimer(); - - drawLoopTimer.start(); - - - for (int row = 0; row < _elevationMap.getRowCount(); row++) - { - double lat = _elevationMap.getLat(row); - - for (int col = 0; col < _elevationMap.getColCount(); col++) - { - - coordinateTimer.restart(); - double lon = _elevationMap.getLon(col); - - // System.out.println(header + "lat = " + lat + " lon = " + lon); - - // System.out.println(header + "In range ! lat = " + lat + " lon = " + lon); - point1 = projection.getScreenPoint(lat, lon); - point2 = projection.getScreenPoint(lat - latRes, lon + lonRes); - - height = (point2.y - point1.y) + 1; - halfHeight = height/2; - - width = (point2.x - point1.x) + 1; - halfWidth = width/2; - - int x = point1.x - halfWidth; - int y = point1.y - halfHeight; - - coordinateTimer.stop(); - - boolean isInRange = isInRange(x,y, projection); - - - if (isInRange) - { - - int value = _elevationMap.getValue(row, col); - int colorIndex = getColorIndexFromValue(value, row, col); - - - Color color = getColorFromColorIndex(colorIndex); - - g.setColor(color); - - int adjacentRectangleCount = getSameColorAdjacentRectanglesInSameRow(point1, width, row, colorIndex, projection); - //int adjacentRectangleCount = 0; - - drawOnlyTimer.restart(); - - // (colorIndex < 3) - { - g.fillRect(x, y, (adjacentRectangleCount + 1) * width, height); - rectangleCount++; - } - - //g.fillRect(x, y, width, height); - drawOnlyTimer.stop(); - - col += adjacentRectangleCount; //need to increment the column - - // rectangleCount++; - virtualRectangleCount += 1 + adjacentRectangleCount; - } - - } //end for col - } //end for row - - - - drawLoopTimer.stop(header + " nested for loop took "); - System.out.println(header + " The elapsed time of the drawing itself was " + drawOnlyTimer.getElapsedTime() + " in millis. "); - System.out.println(header + " The elapsed time for screen coordinate determination was " + coordinateTimer.getElapsedTime() + " in millis. "); - - - - System.out.println(header + "drew " + rectangleCount + " actual rectangles."); - System.out.println(header + "drew " + virtualRectangleCount + " virtual rectangles."); - - - } - // -------------------------------------------------------------------------------------------------- - private int getSameColorAdjacentRectanglesInSameRow(Point point, int width, int origRow, int origColorIndex, MapProjection projection) - { - String header = "ElevationMapLayer.getSameColorAdjacentRectanglesInSameColumn() "; - int count = 0; - int y = point.y; - int colorIndex = 0; - - //given an x-y point, column, and a projection, determine if there are adjacent points of the same color that can now be drawn - for (int x = point.x + width ; x < projection.getMapWidth(); x += width) - { - LatLonPoint latLonPoint = projection.getLatLonPoint(x, y); - - int row = _elevationMap.getRow(latLonPoint.getLat()); - int col = _elevationMap.getCol(latLonPoint.getLon()); - - double lat2 = _elevationMap.getLat(row); - int row2 = _elevationMap.getRow(lat2); - - if (row == origRow) - { - - int value = _elevationMap.getValue(row, col); - - colorIndex = getColorIndexFromValue(value, row, col); - - if (colorIndex == origColorIndex) - { - count++; - } - else - { - break; - } - } - else - { - break; - } - - } - /* - if (count > 0) - { - System.out.println(header + "count = " + count); - } - */ - - return count; - } - // -------------------------------------------------------------------------------------------------- - - private boolean sameColor(Color color1, Color color2) - { - boolean result = false; - - if ( (color1.getRed() == color2.getRed()) && - (color1.getBlue() == color2.getBlue()) && - (color1.getGreen() == color2.getGreen()) - ) - { - result = true; - } - - return result; - } - // -------------------------------------------------------------------------------------------------- - - private boolean isInRange(double lat, double lon, MapProjection projection) - { - boolean result = false; - - if (projection.isInRange(lat, lon)) - { - result = true; - } - - /* - if ((x > 0) && (x < projection.getMapWidth()) && - (y > 0) && (y < projection.getMapHeight()) ) - { - result = true; - } - */ - - return result; - } - private boolean isInRange(int x, int y, MapProjection projection) - { - boolean result = false; - - if ((x > 0) && (x < projection.getMapWidth()) && - (y > 0) && (y < projection.getMapHeight()) ) - { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private short getColorIndexFromStoredValues(int row, int col) - { - short result = 0; - - if ((row > -1 ) && (row < _rowCount) && - (col > -1) && (col < _colCount)) - { - result = _colorIndexArray[row][col]; - } - - return result; - } - - private short getColorIndexFromValue(int value, int row, int col) - { - short colorIndex = 0; - - if (value < 80 ) - colorIndex = 3; - - else if (value < 160 ) - colorIndex = 10; - - else if (value < 240 ) - colorIndex = 17; - - else if (value < 320 ) - colorIndex = 24; - - else - colorIndex = 31; - - - //shading - - int colorIndexDelta = _elevationMap.getValue(row + 1, col) / 3 - //value to south - ( _elevationMap.getValue(row, col + 1) / 3); //value to east - - - if (colorIndexDelta > 3) - colorIndexDelta = 3; - - if (colorIndexDelta < -3) - colorIndexDelta = -3; - - // Adjust the color to give the illusion of illumination from - // the southwest. - colorIndex += colorIndexDelta; - - if (colorIndex > (short) _colorArray.length -1) - { - colorIndex = (short) (_colorArray.length -1); - } - else if (colorIndex < 0) - { - colorIndex = 0; - } - - return colorIndex; - } - - private Color getColorFromColorIndex(int colorIndex) - { - return _colorArray[colorIndex]; - } - - private Color getColorFromValue(int value, int row, int col) - { - int colorIndex = getColorIndexFromValue(value, row, col); - return getColorFromColorIndex(colorIndex); - - } - // -------------------------------------------------------------------------------------------------- - public void setElevationMap(ElevationMap elevationMap) - { - _elevationMap = elevationMap; - } - // -------------------------------------------------------------------------------------------------- - - public ElevationMap getElevationMap() - { - return _elevationMap; - } - // -------------------------------------------------------------------------------------------------- - public void setUseContouring(boolean useContouring) - { - _useContouring = useContouring; - } - // -------------------------------------------------------------------------------------------------- - - public boolean useContouring() - { - return _useContouring; - } - // -------------------------------------------------------------------------------------------------- - public void setHaveComputedContour(boolean haveComputedContour) - { - _haveComputedContour = haveComputedContour; - } - public boolean haveComputedContour() - { - return _haveComputedContour; - } - private void setListOfLatLonPolylineLists(List < List > listOfLatLonPolylineLists) - { - _listOfLatLonPolylineLists = listOfLatLonPolylineLists; - } - private List < List > getListOfLatLonPolylineLists() - { - return _listOfLatLonPolylineLists; - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/GriddedMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/GriddedMapLayer.java deleted file mode 100644 index 37e7afd981..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/GriddedMapLayer.java +++ /dev/null @@ -1,338 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; -import java.util.List; - -import ohd.hseb.geomap.DrawingTools; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.geomap.contour.ContourGrid; -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; -import ohd.hseb.geomap.contour.RowToLatLonContourer; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.projection.MapProjection; - - - -public class GriddedMapLayer extends BaseMapLayer -{ - private ContourGrid _grid = null; - private RowColToLatLonTranslator _rowColToLatLonTranslator = null; - private ColorDeterminer _colorDeterminer = null; - - - private List < List > _listOfLatLonPolylineLists = null; //the outer list is a list of a list of polylines for each contour level - - - private boolean _drawImage = true; - - - - private boolean _haveComputedContour = false; - - - // -------------------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------------------------- - public GriddedMapLayer(ContourGrid grid, - RowColToLatLonTranslator rowColToLatLonTranslator, - ColorDeterminer colorDeterminer, - boolean drawImage) - { - setGrid(grid); - setRowColToLatLonTranslator(rowColToLatLonTranslator); - setColorDeterminer(colorDeterminer); - setShouldDrawImage(drawImage); - } - - // ------------------------------------------------------------------------------------------------------- - - public void draw(Graphics g, MapProjection projection) - { - if (shouldDrawImage()) - { - drawImage(g, projection); - } - else - { - drawContour(g, projection); - } - - } - // ------------------------------------------------------------------------------------------------------- - public void drawImage(Graphics g, MapProjection projection) - { - String header = "GriddedMapLayer.drawImage(): "; - - int rowCount = _grid.getRowCount(); - int colCount = _grid.getColCount(); - - LatLonPoint latLonPoint1 = null; - LatLonPoint latLonPoint2 = null; - LatLonPoint latLonPoint3 = null; - LatLonPoint latLonPoint4 = null; - - CodeTimer latlonTimer = new CodeTimer(); - - for (int row = 0; row < rowCount; row++) - { - for (int col = 0; col < colCount; col++) - { - double value = _grid.getValue(row, col); - - if (value > 0) - { - latlonTimer.restart(); - latLonPoint1 = _rowColToLatLonTranslator.getLatLonPoint(row, col); - latLonPoint2 = _rowColToLatLonTranslator.getLatLonPoint(row, col + 1 ); - latLonPoint3 = _rowColToLatLonTranslator.getLatLonPoint(row + 1, col + 1 ); - latLonPoint4 = _rowColToLatLonTranslator.getLatLonPoint(row + 1, col); - latlonTimer.stop(); - - // System.out.println(header + "latLonPoint1 = " + latLonPoint1); - - - Point screenPoint1 = projection.getScreenPoint(latLonPoint1); - Point screenPoint2 = projection.getScreenPoint(latLonPoint2); - Point screenPoint3 = projection.getScreenPoint(latLonPoint3); - Point screenPoint4 = projection.getScreenPoint(latLonPoint4); - - int width = (screenPoint2.x - screenPoint1.x) + 1; - int height = (screenPoint1.y - screenPoint4.y) + 1; - - - int halfWidth = width/2; - int halfHeight = height/2; - - - - - // System.out.println(header + "row = " + row+ " col = " + col + "value = " + value); - - - - - //System.out.println(header + "value = " + value); - Color color = getColorFromValue(value); - - g.setColor(color); - - // draw the square so that its center is at (screenPoint1.x, screenPoint1.y) - int x = screenPoint1.x - halfWidth; - int y = screenPoint1.y - halfHeight; - - // System.out.println(header + "x = " + x + " y = " + y); - - // System.out.println(header + "width = " + width + " height = " + height); - - // if the x and y values are make it a rectangle, then draw one instead of a polygon - if ((screenPoint2.x == screenPoint3.x) && (screenPoint1.y == screenPoint2.y)) - { - g.fillRect(x, y, width, height); - } - else //it is not a rectangle, so use a polygon - { - int xPoints[] = {screenPoint1.x, screenPoint2.x, screenPoint3.x, screenPoint4.x}; - - int yPoints[] = {screenPoint1.y, screenPoint2.y, screenPoint3.y, screenPoint4.y}; - - g.fillPolygon(xPoints, yPoints, 4); - } - - - } - } - } - - System.out.println(header + "latLon calculations took " + latlonTimer.getElapsedTime() + " millis."); - - - } //end drawImage - - - // -------------------------------------------------------------------------------------------------- - public void drawImageOld(Graphics g, MapProjection projection) - { - String header = "GriddedMapLayer.drawImageOld(): "; - - int rowCount = _grid.getRowCount(); - int colCount = _grid.getColCount(); - - LatLonPoint latLonPoint1 = null; - LatLonPoint latLonPoint2 = null; - - for (int row = 0; row < rowCount; row++) - { - for (int col = 0; col < colCount; col++) - { - - latLonPoint1 = _rowColToLatLonTranslator.getLatLonPoint(row, col); - latLonPoint2 = _rowColToLatLonTranslator.getLatLonPoint(row + 1, col+1); - - // System.out.println(header + "latLonPoint1 = " + latLonPoint1); - - - Point screenPoint1 = projection.getScreenPoint(latLonPoint1); - Point screenPoint2 = projection.getScreenPoint(latLonPoint2); - - int width = (screenPoint2.x - screenPoint1.x) + 1; - int height = (screenPoint1.y - screenPoint2.y) + 1; - - - int halfWidth = width/2; - int halfHeight = height/2; - - - - double value = _grid.getValue(row, col); - - // System.out.println(header + "row = " + row+ " col = " + col + "value = " + value); - - - - if (value > 0) - { - //System.out.println(header + "value = " + value); - Color color = getColorFromValue(value); - - g.setColor(color); - - // draw the square so that its center is at (screenPoint1.x, screenPoint1.y) - int x = screenPoint1.x - halfWidth; - int y = screenPoint1.y - halfHeight; - - // System.out.println(header + "x = " + x + " y = " + y); - - // System.out.println(header + "width = " + width + " height = " + height); - - - g.fillRect(x, y, width, height); - } - } - } - - } //end drawImageOld - - - // -------------------------------------------------------------------------------------------------- - private void drawContour(Graphics g, MapProjection projection) - { - String header = "ElevationMapLayer.drawContour() "; - - System.out.println(header); - - double[] levelArray = _colorDeterminer.getLevelArray(); - - if (! haveComputedContour()) - { - computeContour(levelArray); - setHaveComputedContour(true); - } - // -------------------------------------------------------------------------------------------------- - - - drawContourLines(g, projection, getColorDeterminer(), levelArray, _listOfLatLonPolylineLists); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void computeContour(double[] levelArray) - { - - RowToLatLonContourer contourer = new RowToLatLonContourer(_grid, - getRowColToLatLonTranslator() ); - - _listOfLatLonPolylineLists = contourer.contour(levelArray); - } - // -------------------------------------------------------------------------------------------------- - private void drawContourLines(Graphics g, MapProjection projection, - ColorDeterminer colorDeterminer, - double[] levelArray, - List < List > listOfPolylineLists) - { - int levelIndex = 0; - - for (List polyLineList: listOfPolylineLists ) //for each contour level - { - Color color = colorDeterminer.getColorByValue(levelArray[levelIndex]); - - g.setColor(color); - for (LatLonPolyline polyline: polyLineList) //for each polyline - { - DrawingTools.drawPolyline(g, projection, polyline); - } - levelIndex++; - } - } - - // -------------------------------------------------------------------------------------------------- - public void setHaveComputedContour(boolean haveComputedContour) - { - _haveComputedContour = haveComputedContour; - } - // -------------------------------------------------------------------------------------------------- - - - public boolean haveComputedContour() - { - return _haveComputedContour; - } - // -------------------------------------------------------------------------------------------------- - - - // -------------------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------------------------- - private Color getColorFromValue(double value) - { - return getColorDeterminer().getColorByValue(value); - } - - // ------------------------------------------------------------------------------------------------------- - - public void setGrid(ContourGrid grid) - { - _grid = grid; - } - // ------------------------------------------------------------------------------------------------------- - - public ContourGrid getGrid() - { - return _grid; - } - // ------------------------------------------------------------------------------------------------------- - - public void setShouldDrawImage(boolean drawImage) - { - _drawImage = drawImage; - } - - public boolean shouldDrawImage() - { - return _drawImage; - } - - private void setRowColToLatLonTranslator(RowColToLatLonTranslator rowColToLatLonTranslator) - { - _rowColToLatLonTranslator = rowColToLatLonTranslator; - } - - private RowColToLatLonTranslator getRowColToLatLonTranslator() - { - return _rowColToLatLonTranslator; - } - - public void setColorDeterminer(ColorDeterminer colorDeterminer) - { - _colorDeterminer = colorDeterminer; - } - - public ColorDeterminer getColorDeterminer() - { - return _colorDeterminer; - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/MapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/MapLayer.java deleted file mode 100644 index f8bbc4d341..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/MapLayer.java +++ /dev/null @@ -1,18 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; - -import ohd.hseb.geomap.projection.MapProjection; - -public interface MapLayer -{ - Color getColor(); - void setColor(Color color); - - void setShouldDraw(boolean shouldDraw); - - boolean shouldDraw(); - - void draw(Graphics graphics, MapProjection projection); -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/PolyLineMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/PolyLineMapLayer.java deleted file mode 100644 index 273b099129..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/PolyLineMapLayer.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; - - -import java.util.List; - -import ohd.hseb.geomap.DrawingTools; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import ohd.hseb.geomap.projection.MapProjection; - - - -public class PolyLineMapLayer extends BaseMapLayer -{ - List _latLongLineList = null; - - // ----------------------------------------------------------------------------------------------- - - public PolyLineMapLayer(List latLongLineList ) - { - _latLongLineList = latLongLineList; - } - - // ----------------------------------------------------------------------------------------------- - - public void draw(Graphics g, MapProjection projection) - { - String header = "LineMapLayer.draw(): "; - // System.out.println(header); - - - for(LatLonPolyline latLonPolyline : _latLongLineList) - { - drawLine(g, projection, latLonPolyline); - } - } - - // ----------------------------------------------------------------------------------------------- - - private void drawLine(Graphics g, MapProjection projection, LatLonPolyline latLonPolyline) - { - String header = "LineMapLayer.drawLine(): "; - //System.out.println(header); - - Color color = getColor(); - - g.setColor(color); - - List pointList = latLonPolyline.getPointList(); - - for (int i= 0; i < pointList.size() - 1; i++) - { - LatLonPoint point1 = pointList.get(i); - LatLonPoint point2 = pointList.get(i+1); - - - DrawingTools.drawLineSegment(g, projection, point1, point2); - } - - - } - - // ----------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/PolygonMapLayer.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/PolygonMapLayer.java deleted file mode 100644 index 517826f9c5..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/PolygonMapLayer.java +++ /dev/null @@ -1,53 +0,0 @@ -package ohd.hseb.geomap.layer; - -import java.awt.Color; -import java.awt.Graphics; - -import java.util.List; - -import ohd.hseb.geomap.DrawingTools; -import ohd.hseb.geomap.model.Polygon; -import ohd.hseb.geomap.projection.MapProjection; - -public class PolygonMapLayer extends BaseMapLayer -{ - List _latLongPolygonList = null; - - // ----------------------------------------------------------------------------------------------- - - public PolygonMapLayer(List latLongPolygonList ) - { - _latLongPolygonList = latLongPolygonList; - } - - // ----------------------------------------------------------------------------------------------- - - public void draw(Graphics g, MapProjection projection) - { - String header = "PolygonMapLayer.draw(): "; - // System.out.println(header); - - - for(Polygon polygon : _latLongPolygonList) - { - drawPolygon(g, projection, polygon); - } - } - - // ----------------------------------------------------------------------------------------------- - - private void drawPolygon(Graphics g, MapProjection projection, Polygon polygon) - { - String header = "PolygonMapLayer.drawPolygon(): "; - //System.out.println(header); - - Color color = getColor(); - - g.setColor(color); - - DrawingTools.drawPolygon(g, projection, polygon); - } - - // ----------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/XmrgGridToGridAdapter.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/XmrgGridToGridAdapter.java deleted file mode 100644 index 9db29223c1..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/layer/XmrgGridToGridAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -package ohd.hseb.geomap.layer; - -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.geomap.contour.ContourGrid; - -public class XmrgGridToGridAdapter implements ContourGrid -{ - private XmrgGrid _xmrgGrid = null; - - // --------------------------------------------------------------------------------------------- - public XmrgGridToGridAdapter(XmrgGrid xmrgGrid) - { - _xmrgGrid = xmrgGrid; - } - // --------------------------------------------------------------------------------------------- - - public double getValue(int row, int col) - { - int hrapRow = row + _xmrgGrid.getBaseRow(); - int hrapCol = col + _xmrgGrid.getBaseCol(); - - return _xmrgGrid.getValue(hrapRow, hrapCol); - } - // --------------------------------------------------------------------------------------------- - public void setValue(int row, int col, double value) - { - int hrapRow = row + _xmrgGrid.getBaseRow(); - int hrapCol = col + _xmrgGrid.getBaseCol(); - - _xmrgGrid.setValue(hrapRow, hrapCol, value); - - return; - } - // --------------------------------------------------------------------------------------------- - - - public int getColCount() - { - - return _xmrgGrid.getColCount(); - } - - // --------------------------------------------------------------------------------------------- - - public int getRowCount() - { - return _xmrgGrid.getRowCount(); - } - - // --------------------------------------------------------------------------------------------- - - - public double[][] getValuesArray() - { - return _xmrgGrid.getValuesArray(); - } - - // --------------------------------------------------------------------------------------------- - -} //end XmrgGridToGridAdapter diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/test/ContouringTest.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/test/ContouringTest.java deleted file mode 100644 index 2a6643f8c0..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/test/ContouringTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package ohd.hseb.geomap.test; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; -import ohd.hseb.geomap.contour.RowToLatLonContourer; -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.LatLonPolyline; -import junit.framework.TestCase; - -public class ContouringTest extends TestCase -{ - - - protected void setUp() - { - - } - - public void testContouring() - { - - double [][] valueArray = { - {15, 20, 30 }, - {5, 15, 25 }, - {5, 0, 15 } - - }; - - double northLat = 2; - double southLat = 0; - double eastLat = 2; - double westLat = 0; - LatLonBounds bounds = new LatLonBounds(northLat, southLat, westLat, eastLat); - - RowColToLatLonTranslator translator = new MockRowColToLatLonTranslator(bounds, 1.0, 1.0); - RowToLatLonContourer contourer = new RowToLatLonContourer(valueArray, translator ); - - List polylineList = contourer.contourOneLevel(10); - for (LatLonPolyline polyline: polylineList) - { - System.out.println(polyline + "\n"); - } - - - List desiredPolylineList = new ArrayList(); - - //polyLine1 - LatLonPolyline polyLine = new LatLonPolyline(); - polyLine.addPoint(new LatLonPoint(1, 0.5)); - polyLine.addPoint(new LatLonPoint(0.5, 0)); - - desiredPolylineList.add(polyLine); - - //polyLine2 - polyLine = new LatLonPolyline(); - polyLine.addPoint(new LatLonPoint(1, 0.5)); - polyLine.addPoint(new LatLonPoint(1 + 1.0/3.0, 1.0)); - - desiredPolylineList.add(polyLine); - - //polyLine3 - polyLine = new LatLonPolyline(); - polyLine.addPoint(new LatLonPoint(2, 1 + (2.0/3.0))); - polyLine.addPoint(new LatLonPoint(1 + (1.0/3.0), 1.0)); - - desiredPolylineList.add(polyLine); - - - boolean equalLists = equalPolyLineLists(desiredPolylineList, polylineList); - boolean desiredEquals = true; - assertEquals(desiredEquals, equalLists); - - - } - - - public boolean equalPolyLineLists(List polylineList1, List polylineList2) - { - boolean result = false; - - if (polylineList1.size() == polylineList2.size()) - { - result = true; - for (int i = 0; i < polylineList1.size(); i++) - { - LatLonPolyline polyline1 = polylineList1.get(i); - LatLonPolyline polyline2 = polylineList2.get(i); - if (! polyline1.equals(polyline2)) - { - result = false; - System.out.println("polyline1 " + polyline1 + " != polyline 2 " + polyline2); - break; - } - } - - } - - return result; - } - -} diff --git a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/test/MockRowColToLatLonTranslator.java b/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/test/MockRowColToLatLonTranslator.java deleted file mode 100644 index ebb488bb06..0000000000 --- a/javaUtilities/hydro/ohd.map/src/ohd/hseb/geomap/test/MockRowColToLatLonTranslator.java +++ /dev/null @@ -1,103 +0,0 @@ -package ohd.hseb.geomap.test; - -import ohd.hseb.geomap.contour.RowColToLatLonTranslator; -import ohd.hseb.geomap.model.LatLonBounds; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.RowColumnPoint; - -public class MockRowColToLatLonTranslator implements RowColToLatLonTranslator -{ - private LatLonBounds _latLonBounds = null; - private double _latResInDegrees = 0; - private double _lonResInDegrees = 0; - // ------------------------------------------------------------------------------ - - public MockRowColToLatLonTranslator(LatLonBounds bounds, double latResInDegrees, double lonResInDegrees) - { - _latLonBounds = new LatLonBounds(bounds); - _latResInDegrees = latResInDegrees; - - } - // ------------------------------------------------------------------------------ - - public RowColumnPoint getRowColumnPoint(LatLonPoint latLonPoint) - { - double row = getRow(latLonPoint.getLat()); - double col = getCol(latLonPoint.getLon()); - - return new RowColumnPoint(row, col); - } - // ------------------------------------------------------------------------------ - public LatLonPoint getLatLonPoint(double row, double col) - { - - double lat = getLat((int)row); - double lon = getLon((int)col); - - return new LatLonPoint(lat, lon); - } - // ------------------------------------------------------------------------------ - public LatLonPoint getLatLonPoint(RowColumnPoint rowColumnPoint) - { - return getLatLonPoint(rowColumnPoint.getRow(), rowColumnPoint.getCol()); - } - // ------------------------------------------------------------------------------ - - public double getLat(int row) - { - double lat = row; - - return lat; - } - // ------------------------------------------------------------------------------ - public double getLon(int col) - { - double lon = col; - - return lon; - } - // ------------------------------------------------------------------------------ - - public int getRow(double lat) - { - int row = -1; - row = (int) Math.ceil(lat); - - return row; - } - // ------------------------------------------------------------------------------ - public int getCol(double lon) - { - int col = -1; - - col = (int) Math.ceil(lon); - - return col; - } - // ------------------------------------------------------------------------------ - - public void setLatResInDegrees(double latResInDegrees) - { - _latResInDegrees = latResInDegrees; - } - // ------------------------------------------------------------------------------ - - public double getLatResInDegrees() - { - return _latResInDegrees; - } - // ------------------------------------------------------------------------------ - - public void setLonResInDegrees(double lonResInDegrees) - { - _lonResInDegrees = lonResInDegrees; - } - // ------------------------------------------------------------------------------ - - public double getLonResInDegrees() - { - return _lonResInDegrees; - } - - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/.classpath b/javaUtilities/hydro/ohd.misc_dialogs/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.misc_dialogs/.project b/javaUtilities/hydro/ohd.misc_dialogs/.project deleted file mode 100644 index 83efc585a7..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.misc_dialogs - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.misc_dialogs/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.misc_dialogs/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 43029d90ab..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 09:09:32 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.misc_dialogs/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.misc_dialogs/META-INF/MANIFEST.MF deleted file mode 100644 index 07d9184628..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/META-INF/MANIFEST.MF +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Misc_dialogs -Bundle-SymbolicName: ohd.misc_dialogs -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0", - ohd.tsl;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.misc_dialogs/build.properties b/javaUtilities/hydro/ohd.misc_dialogs/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.misc_dialogs/build.xml b/javaUtilities/hydro/ohd.misc_dialogs/build.xml deleted file mode 100644 index 41e3242071..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.misc_dialogs/ohd.misc_dialogs.ecl b/javaUtilities/hydro/ohd.misc_dialogs/ohd.misc_dialogs.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.misc_dialogs/scripts/run_ColorChooserDialog b/javaUtilities/hydro/ohd.misc_dialogs/scripts/run_ColorChooserDialog deleted file mode 100644 index ced698e6e1..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/scripts/run_ColorChooserDialog +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/ksh -# file name: run_ColorChooserDialog -# Created: 07/12/2007 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# need to add a path to the jar file for this application -export CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/MiscDialogs.jar:$DB_DRIVER_PATH - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -Dte=`date +%m%d%Y` - -LOG_FILE=$WHFS_LOCAL_DATA_DIR/log/color_scale/ColorChooserDialog_$Dte.log -TMPLOGFILE=$WHFS_LOCAL_DATA_DIR/log/color_scale/ColorChooserDialog.tmp - -tail -1200 $LOG_FILE > $TMPLOGFILE -mv $TMPLOGFILE $LOG_FILE - -if [ $# -ne 3 ] -then - echo "run_ColorChooserDialog " - exit 1 -else - APPLICATION_NAME=$1 - LOGIN_ID=`whoami` - DEFAULT_COLOR_SCALE_FILE=$2 - RGB_COLOR_FILE=$3 -fi - -######################################################################## - -# set up an X Terminal window to write stdout and run the ColorChooser Dialog -# application using java -xterm -T ColorChooserDialog -iconic -n ColorChooserDialog -e $JBINDIR/java ohd.hseb.color_chooser.ColorChooserDialog $JDBCURL $LOG_FILE $APPLICATION_NAME $LOGIN_ID $DEFAULT_COLOR_SCALE_FILE $RGB_COLOR_FILE diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorChooserDialog.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorChooserDialog.java deleted file mode 100644 index aa09c03329..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorChooserDialog.java +++ /dev/null @@ -1,2258 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; - -public class ColorChooserDialog extends JDialog implements Runnable -{ - - private static boolean _isRunning = false; - private static Thread _thread = null; - private static long _lastUpdateTime = 0; - - private Container _frameContentPane = getContentPane(); - - private JTabbedPane _tabbedPane = new JTabbedPane(); - private JPanel _tabbedPanePanel = new JPanel( new GridBagLayout() ); - private JComponent _viewPanelTab = new JPanel( new GridBagLayout() ); - private JComponent _editPanelTab = new JPanel( new GridBagLayout() ); - - private JPanel _viewTabComboBoxPanel = new JPanel( new GridBagLayout() ); - private JPanel _editTabComboBoxPanel = new JPanel( new GridBagLayout() ); - private JPanel _viewTabColorsDisplayPanel = new JPanel( new GridBagLayout() ); - - private String[] _setComboBoxString = { "default", "user", "office" }; - private JPanel _viewTabSetComboBoxPanel = new JPanel( new GridBagLayout() ); - private JLabel _viewTabSetComboBoxLabel = new JLabel( "Source" ); - private JLabel _viewTabUsedColorsSetLabel = new JLabel( "" ); - private JLabel _editTabUsedColorsSetLabel = new JLabel( "" ); - private JPanel _viewTabUserIDComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _viewTabUserIDComboBox = new JComboBox(); - private JLabel _viewTabUserIDLabel = new JLabel( "User ID" ); - private JPanel _viewTabColorUseComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _viewTabColorUseComboBox = null; - private JLabel _viewTabColorUseLabel = new JLabel( "Data Type" ); - private String[] _viewTabDurationComboBoxInteger = { "0" }; - private JComboBox _viewTabDurationComboBox = new JComboBox ( _viewTabDurationComboBoxInteger ); - private JPanel _viewTabDurationPanel = new JPanel( new GridBagLayout() ); - private JLabel _viewTabDurationLabel = new JLabel( "Duration" ); - private JLabel _viewTabDurationUnitsLabel = new JLabel( "Hrs" ); - - private JPanel _editTabSetComboBoxPanel = new JPanel( new GridBagLayout() ); - private JLabel _editTabSetComboBoxLabel = new JLabel( "Source" ); - private JComboBox _editTabSetComboBox = new JComboBox( _setComboBoxString ); - private JPanel _editTabUserIDComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _editTabUserIDComboBox = new JComboBox(); - private JLabel _editTabUserIDLabel = new JLabel( "User ID" ); - private JPanel _editTabColorUseComboBoxPanel = new JPanel( new GridBagLayout() ); - private JComboBox _editTabColorUseComboBox = null; - private JLabel _editTabColorUseLabel = new JLabel( "Data Type" ); - private String[] _editTabDurationComboBoxDouble = { "0" }; - private JComboBox _editTabDurationComboBox = new JComboBox ( _editTabDurationComboBoxDouble ); - private JPanel _editTabDurationPanel = new JPanel( new GridBagLayout() ); - private JLabel _editTabDurationLabel = new JLabel( "Duration" ); - private JLabel _editTabDurationUnitsLabel = new JLabel( "Hrs" ); - - private JComboBox _editTabSaveAsColorUseComboBox = null; - private JLabel _editTabSaveAsLabel = new JLabel( "Save for datatype:" ); - - private JPanel _editTabModifyColorScaleValueSetPanel = new JPanel( new GridBagLayout() ); - private JPanel _editTabColor = new JPanel(); - private JTextField _editTabScaleValue = new JTextField(); - private JButton _editTabAddColorSet = new JButton( "
    Add/Update
    Color-Value
    Pair
    " ); - private JButton _editTabDeleteColorSet = new JButton( "
    Delete Color-Value
    Pair
    " ); - - private JPanel _editTabButtonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAsUserButton = null; - private JButton _saveAsOfficeButton = new JButton( "
    Save
    as office
    " ); - private JButton _deleteUserButton = null; - private JButton _deleteOfficeButton = new JButton( "
    Delete
    as office
    "); - - private JPanel _editTabColorsDisplayPanel = new JPanel( new GridBagLayout() ); - private JPanel _editTabUsedColorsDisplayPanel = new JPanel( new GridBagLayout() ); - - private JPanel _viewTabCloseButtonPanel = new JPanel( new GridBagLayout() ); - private JButton _closeButton = new JButton( "Close" ); - - private JPanel _viewTabVCRButtonColorPanel = new JPanel( new GridBagLayout() ); - private JButton _viewTabVCRLeftColorButton = new JButton( "\u25C4"); - private JButton _viewTabVCRRightColorButton = new JButton( "\u25BA"); - - private JButton _editTabResetColorButton = new JButton( "Undo Unsaved Changes"); - - private JPanel _editTabVCRButtonScaleValuePanel = new JPanel( new GridBagLayout() ); - private JButton _editTabVCRLeftScaleValueButton = new JButton( "\u25C4"); - private JButton _editTabVCRRightScaleValueButton = new JButton( "\u25BA"); - - private ColorChooserDialogDataMgr _dataMgr = null; - - private List _usedColorScaleValueSetList = new ArrayList(); - private String _userID = null; - - private static final int VIEW_PANEL_TAB_ID = 1; - private static final int EDIT_PANEL_TAB_ID = 2; - private int _activeTabID = EDIT_PANEL_TAB_ID; - - private static final int DEFAULT_WIDTH = 600; - private static final int DEFAULT_HEIGHT = 550; - - private static final float MISSING = -9999; - private static final float MINIMUM_VALUE = -8888; - - private ColorScaleValueSet _displayedColorScaleValueSet = null; - private ColorScaleValueSet _usedColorScaleValueSet = null; - private TreeSet _allColorUsesSet = new TreeSet(); - private Set _currentDisplayedDurationSet = null; - private NamedColorMatcher _namedColorMatcher = null; - - private boolean _updatingComboBoxes = false; - - public ColorChooserDialog() - { - } - - public ColorChooserDialog( JFrame owner, ColorChooserDialogDataMgr dataMgr, String userID ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, "Color Scale Manager - User:" + userID, true ); - _dataMgr = dataMgr; - _userID = userID; - _dataMgr.setUserID( userID ); - initGui(); - addListeners(); - } - // ------------------------------------------------------------------------------------- - - private void initGui() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - setLayoutManager(); - addFrameComponenets(); - - updateUsedColorScaleValueSetList(); - updateAllColorUsesSet(); - - addViewPanelTabComponents(); - addEditPanelTabComponents(); - addComboBoxComponents(); - addCloseButtonPanelComponents(); - - initComboBoxes(); - - addToolTips(); - - displayColorScaleValues(); - return; - } - - private void addToolTips() - { - // private JButton _deleteUserButton = null; - // private JButton _deleteOfficeButton = new JButton( "
    Delete
    as office
    "); - - - _editTabResetColorButton.setToolTipText(" Undoes the changes in working
    memory for the currently selected
    color set, returning it to
    what is stored in the database. "); - - _editTabVCRLeftScaleValueButton.setToolTipText(" Selects the previous DataType/Duration
    combination for the currently selected source. "); - _editTabVCRRightScaleValueButton.setToolTipText(" Selects the next DataType/Duration
    combination for the currently selected source. "); - - _editTabAddColorSet.setToolTipText(" Puts the edited color-value pair
    into the set in working memory. "); - _editTabDeleteColorSet.setToolTipText(" Removes the edited color-value
    from the set in working memory. "); - - _saveAsUserButton.setToolTipText(" For the current user,
    saves the currently selected color set to the database. "); - _saveAsOfficeButton.setToolTipText(" For the office default settings,
    saves the currently selected color set to the database. "); - - _deleteUserButton.setToolTipText(" Remove the color set with the currently selected
    DataType/Duration combination
    from the database for this user. "); - _deleteOfficeButton.setToolTipText(" Remove the color set with the currently selected
    DataType/Duration combination
    from the database for the office."); - - - } - - private void addCloseButtonPanelComponents() - { - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabCloseButtonPanel, _closeButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void addEditPanelTabComponents() - { - JPanel editTabHorizontalSeparatorPanel = new JPanel(); - JPanel editTabVirticalSeparatorPanel = new JPanel(); - JPanel editTabVirticalSeparatorPanel2 = new JPanel(); - - _editTabButtonPanel.setBorder( BorderFactory.createTitledBorder( "Color-Value Set Database Controls" ) ); - editTabHorizontalSeparatorPanel.setPreferredSize( new Dimension( 50, 250 ) ); - editTabVirticalSeparatorPanel.setPreferredSize( new Dimension( 350, 60 ) ); - editTabVirticalSeparatorPanel2.setPreferredSize( new Dimension( 350, 60 ) ); - _editTabColorUseComboBox = new JComboBox( getColorUseComboBoxString() ); - _editTabUsedColorsDisplayPanel.setBorder( BorderFactory.createTitledBorder( "Used Color Set" ) ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _editPanelTab, _editTabComboBoxPanel, 0, 0, 25, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabColorsDisplayPanel, 0, 1, 25, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, editTabVirticalSeparatorPanel, 0, 6, 7, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabModifyColorScaleValueSetPanel, 8, 6, 10, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, editTabVirticalSeparatorPanel2, 18, 6, 7, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _editPanelTab, editTabHorizontalSeparatorPanel, 0, 11, 25, 10, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabUsedColorsDisplayPanel, 0, 22, 25, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _editPanelTab, _editTabButtonPanel, 0, 27, 25, 5, 1, 1, GridBagConstraints.BOTH ); - - _editTabColor.setBackground( Color.BLACK ); - _editTabSaveAsColorUseComboBox = new JComboBox( _allColorUsesSet.toArray() ); - - JPanel saveAsColorUseLabelComboBoxPanel = new JPanel(); - JPanel saveDeleteDbButtonPanel = new JPanel(); - JPanel modifyColorSetsPanel = new JPanel( new GridBagLayout() ); - JPanel colorSetPanel = new JPanel( new GridBagLayout() ); - - saveAsColorUseLabelComboBoxPanel.add( _editTabSaveAsLabel ); - saveAsColorUseLabelComboBoxPanel.add( _editTabSaveAsColorUseComboBox ); - saveDeleteDbButtonPanel.add( _saveAsUserButton ); - saveDeleteDbButtonPanel.add( _saveAsOfficeButton ); - saveDeleteDbButtonPanel.add( _deleteUserButton ); - saveDeleteDbButtonPanel.add( _deleteOfficeButton ); - - GridBagConstraints buttonGbc = new GridBagConstraints(); - buttonGbc.insets = new Insets(2,2,2,2); - buttonGbc.weightx = 1; - buttonGbc.weighty = 1; - //JPanel panel, Component component, GridBagConstraints gbc, int column, int row, int width, int height, int fill ) - ComponentHelper.addPanelComponent( modifyColorSetsPanel, _editTabAddColorSet, buttonGbc, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( modifyColorSetsPanel, _editTabDeleteColorSet, buttonGbc, 1, 2, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( colorSetPanel, _editTabColor, buttonGbc, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( colorSetPanel, _editTabScaleValue, buttonGbc, 1, 2, 1, 1, GridBagConstraints.BOTH ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, colorSetPanel, 1, 1, 1, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabModifyColorScaleValueSetPanel, modifyColorSetsPanel, 2, 1, 1, 2, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _editTabButtonPanel, saveAsColorUseLabelComboBoxPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabButtonPanel, saveDeleteDbButtonPanel, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void addViewPanelTabComponents() - { - JPanel horizontalSeparatorPanel = new JPanel(); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 50, 350 ) ); - - _viewTabColorUseComboBox = new JComboBox( getColorUseComboBoxString() ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _viewPanelTab, _viewTabComboBoxPanel, 0, 0, 25, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _viewPanelTab, _viewTabColorsDisplayPanel, 0, 2, 25, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _viewPanelTab, horizontalSeparatorPanel, 0, 7, 25, 10, 1, 1, GridBagConstraints.BOTH ); - } - - private void addComboBoxComponents() - { - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabSetComboBoxPanel, _viewTabSetComboBoxLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabSetComboBoxPanel, _viewTabUsedColorsSetLabel, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - - ComponentHelper.addPanelComponent( _viewTabUserIDComboBoxPanel, _viewTabUserIDLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabUserIDComboBoxPanel, _viewTabUserIDComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _viewTabColorUseComboBoxPanel, _viewTabColorUseLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabColorUseComboBoxPanel, _viewTabColorUseComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _viewTabDurationPanel, _viewTabDurationLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabDurationPanel, _viewTabDurationComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabDurationPanel, _viewTabDurationUnitsLabel, 2, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - _viewTabUserIDComboBoxPanel.setVisible( false ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabSetComboBoxPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabUserIDComboBoxPanel, 2, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabColorUseComboBoxPanel, 3, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _viewTabComboBoxPanel, _viewTabDurationPanel, 4, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - - - - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _editTabSetComboBoxPanel, _editTabSetComboBoxLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabSetComboBoxPanel, _editTabSetComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabUserIDComboBoxPanel, _editTabUserIDLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabUserIDComboBoxPanel, _editTabUserIDComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabColorUseComboBoxPanel, _editTabColorUseLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabColorUseComboBoxPanel, _editTabColorUseComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabDurationPanel, _editTabDurationLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabDurationPanel, _editTabDurationComboBox, 1, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabDurationPanel, _editTabDurationUnitsLabel, 2, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - _editTabUserIDComboBoxPanel.setVisible( false ); - _editTabDurationComboBox.setEditable( true ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabSetComboBoxPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabUserIDComboBoxPanel, 2, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabColorUseComboBoxPanel, 3, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabComboBoxPanel, _editTabDurationPanel, 4, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - - _editTabDurationComboBox.setName( "EditTabDuration" ); - _viewTabDurationComboBox.setName( "ViewTabDuration" ); - } - - private void setLayoutManager() - { - _frameContentPane.setLayout( new GridBagLayout() ); - } - - private void addFrameComponenets() - { - _tabbedPane.setPreferredSize( new Dimension( 200, 600 ) ); - - ComponentHelper.addPanelComponent( _tabbedPanePanel, _tabbedPane, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _viewTabComboBoxPanel, 0, 0, 25, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _tabbedPanePanel, 0, 2, 25, 30, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _viewTabCloseButtonPanel, 0, 32, 25, 1, 1, 1, GridBagConstraints.BOTH ); - _viewPanelTab.setName( "ViewPanelTab" ); - _editPanelTab.setName( "EditPanelTab" ); - _tabbedPane.addTab( "Edit Color Sets", _editPanelTab ); - _tabbedPane.addTab( "Browse Color Sets", _viewPanelTab ); - _saveAsUserButton = new JButton( "
    Save as
    " + _userID + "
    " ); - _deleteUserButton = new JButton( "
    Delete as
    " + _userID + "
    "); - _deleteOfficeButton.setEnabled( false ); - _deleteUserButton.setEnabled( false ); - } - - private void displayColorScaleValues() - { - _viewTabColorsDisplayPanel.removeAll(); - _editTabColorsDisplayPanel.removeAll(); - _editTabUsedColorsDisplayPanel.removeAll(); - ColorSet colorSet = null; - ScaleValueSet scaleValueSet = null; - String colorUse = null; - String userIDString = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - colorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - } - else - { - colorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - } - - ColorScaleValueSet colorScaleValueSet = getColorScaleValueSetByColorUse( colorUse ); - - if ( colorScaleValueSet != null ) - { - userIDString = colorScaleValueSet.getUserID(); - - if ( userIDString.equalsIgnoreCase( "HARDCODED" ) ) - { - _viewTabUsedColorsSetLabel.setText( "default" ); - } - else if ( userIDString.equalsIgnoreCase( "default" ) ) - { - _viewTabUsedColorsSetLabel.setText( "office" ); - } - else - { - _viewTabUsedColorsSetLabel.setText( "user (" + userIDString + ")" ); - } - } - - if ( colorScaleValueSet != null ) - { - colorSet = colorScaleValueSet.getColorSet(); - scaleValueSet = colorScaleValueSet.getScaleValueSet(); - } - - if ( ( colorSet != null ) && ( scaleValueSet != null ) ) - { - List namedColorList = colorSet.getNamedColorList(); - int colorSetListSize = namedColorList.size(); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _viewTabVCRButtonColorPanel, _viewTabVCRLeftColorButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _viewTabVCRButtonColorPanel, _viewTabVCRRightColorButton, 2, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _viewTabColorsDisplayPanel, _viewTabVCRButtonColorPanel, 1, 1, colorSetListSize, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _editTabVCRButtonScaleValuePanel, _editTabVCRLeftScaleValueButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabVCRButtonScaleValuePanel, _editTabVCRRightScaleValueButton, 2, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _editTabColorsDisplayPanel, _editTabVCRButtonScaleValuePanel, 1, 1, colorSetListSize, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _editTabColorsDisplayPanel, _editTabResetColorButton, 1, 8, colorSetListSize, 1, 1, 1, GridBagConstraints.NONE ); - - for ( int i = 0; i < namedColorList.size(); i++ ) - { - Double scaleValueDouble = (Double) scaleValueSet.getScaleValueSet().get( i ); - NamedColor namedColor = getClosestNamedColor( (Color) namedColorList.get( i ) ); - - addColorValueDisplayPanelToTabContainerPanel( scaleValueDouble, - namedColor, - _viewTabColorsDisplayPanel, - i, - false); - - addColorValueDisplayPanelToTabContainerPanel( scaleValueDouble, - namedColor, - _editTabColorsDisplayPanel, - i, - true); - } //end for - } - _displayedColorScaleValueSet = colorScaleValueSet; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - _usedColorScaleValueSet = getUsedColorScaleValueSetByColorUse( colorUse ); - - if ( _usedColorScaleValueSet != null ) - { - List usedColorSetList = _usedColorScaleValueSet.getColorSet().getNamedColorList(); - List usedScaleValueSetList = _usedColorScaleValueSet.getScaleValueSet().getScaleValueSet(); - - for ( int i = 0; i < usedColorSetList.size(); i++ ) - { - Double scaleValueDouble = (Double) usedScaleValueSetList.get( i ); - NamedColor namedColor = getClosestNamedColor( (Color) usedColorSetList.get( i ) ); - addColorValueDisplayPanelToTabContainerPanel( scaleValueDouble, - namedColor, - _editTabUsedColorsDisplayPanel, - i, - false); - } - - userIDString = _usedColorScaleValueSet.getUserID(); - - if ( userIDString.equalsIgnoreCase( "HARDCODED" ) ) - { - _editTabUsedColorsSetLabel.setText( "default" ); - } - else if ( userIDString.equalsIgnoreCase( "default" ) ) - { - _editTabUsedColorsSetLabel.setText( "office" ); - } - else - { - _editTabUsedColorsSetLabel.setText( "user (" + userIDString + ")" ); - } - } - } - - if ( _usedColorScaleValueSet != null ) - { - _editTabUsedColorsDisplayPanel.setBorder( BorderFactory.createTitledBorder( "Used Color Set - Source: " + _editTabUsedColorsSetLabel.getText() + - " Data-Type: " + _usedColorScaleValueSet.getColorUseString() + - " Duration: " + _usedColorScaleValueSet.getDuration() ) ); - } - - _viewTabColorsDisplayPanel.setVisible( false ); - _viewTabColorsDisplayPanel.setVisible( true ); - _editTabColorsDisplayPanel.setVisible( false ); - _editTabColorsDisplayPanel.setVisible( true ); - _editTabUsedColorsDisplayPanel.setVisible( false ); - _editTabUsedColorsDisplayPanel.setVisible( true ); - } - - // ---------------------------------------------------------------------------------------------------- - private void addColorValueDisplayPanelToTabContainerPanel(Double scaleValueDouble, - NamedColor namedColor, - JPanel colorsDisplayPanel, - int indexOfSlotPanel, - boolean addClickColorSelectionListener) - { - int i = indexOfSlotPanel; - JPanel colorPanel = new JPanel(); - JTextField scaleValueTextField = new JTextField(); - JPanel colorAndScalePairPanel = new JPanel(); - - colorPanel.setBackground( namedColor ); - colorPanel.setBorder( BorderFactory.createRaisedBevelBorder() ); - - colorAndScalePairPanel.setLayout( new GridBagLayout() ); - colorAndScalePairPanel.setPreferredSize( new Dimension( 10, 50 ) ); - - scaleValueTextField.setText( getFormattedDoubleString(scaleValueDouble)); - - scaleValueTextField.setEditable( false ); - - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( colorAndScalePairPanel, colorPanel, 0, 0, 1, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( colorAndScalePairPanel, scaleValueTextField, 0, 5, 1, 5, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( colorsDisplayPanel, colorAndScalePairPanel, i, 2, 1, 5, 1, 1, GridBagConstraints.BOTH ); - - if (addClickColorSelectionListener) - { - colorPanel.addMouseListener( new ClickColorSelectionListener( scaleValueDouble ) ); - scaleValueTextField.addMouseListener( new EditScaleValueTextFieldListener( colorPanel, scaleValueDouble ) ); - } - } - - private void initComboBoxes() - { - String selectedColorUseString = (String) _editTabColorUseComboBox.getSelectedItem(); - _editTabSaveAsColorUseComboBox.setSelectedItem( selectedColorUseString ); - } - - - private List getFilteredColorScaleValueSetList( String userID, String colorUse ) - { - List filteredColorScaleValueSetList = new ArrayList(); - List databaseColorScaleValueSetList = _usedColorScaleValueSetList; - - ColorScaleValueSet extractedColorScaleValueSet = null; - - for ( int i = 0; i < databaseColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) databaseColorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( userID ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) ) - { - filteredColorScaleValueSetList.add( extractedColorScaleValueSet ); - } - } - - return filteredColorScaleValueSetList; - } - - private ColorScaleValueSet getUsedColorScaleValueSetByColorUse( String colorUse ) - { - ColorScaleValueSet foundColorScaleValueSet = null; - ColorScaleValueSet returnColorScaleValueSet = null; - - List userColorScaleValueSetList = new ArrayList(); - List officeColorScaleValueSetList = new ArrayList(); -// List flatFileColorScaleValueSetList = _dataMgr.getDefaultColorScaleValueSetList(); - List flatFileColorScaleValueSetList = _usedColorScaleValueSetList; - - userColorScaleValueSetList = getFilteredColorScaleValueSetList( _userID, colorUse ); - officeColorScaleValueSetList = getFilteredColorScaleValueSetList( "default", colorUse ); - - foundColorScaleValueSet = findClosestColorScaleValueSet( userColorScaleValueSetList, colorUse ); - - if ( foundColorScaleValueSet == null ) - { - foundColorScaleValueSet = findClosestColorScaleValueSet( officeColorScaleValueSetList, colorUse ); - } - - if ( foundColorScaleValueSet == null ) - { - foundColorScaleValueSet = findClosestColorScaleValueSet( flatFileColorScaleValueSetList, colorUse ); - } - - returnColorScaleValueSet = new ColorScaleValueSet( foundColorScaleValueSet ); - - return returnColorScaleValueSet; - } - - private ColorScaleValueSet findClosestColorScaleValueSet( List userColorScaleValueSetList, String colorUse ) - { - ColorScaleValueSet foundColorScaleValueSet = null; - double duration = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - - ColorScaleValueSet extractedColorScaleValueSet = null; - List foundColorUseColorScaleValueSetList = new ArrayList(); - - for ( int i = 0; i < userColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) userColorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) ) - { - foundColorUseColorScaleValueSetList.add( extractedColorScaleValueSet ); - } - } - - if ( foundColorUseColorScaleValueSetList.size() > 0 ) - { - foundColorScaleValueSet = getClosestMatchingDurationColorScaleValueSet( foundColorUseColorScaleValueSetList, - duration ); - } - - return foundColorScaleValueSet; - } - - private ColorScaleValueSet getClosestMatchingDurationColorScaleValueSet( List foundColorUseColorScaleValueSetList, - double duration ) - { - ColorScaleValueSet closestMatchingColorScaleValueSet = null; - ColorScaleValueSet extractedColorScaleValueSet = null; - double durationDiff = 1000; - - for ( int i = 0; i < foundColorUseColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) foundColorUseColorScaleValueSetList.get( i ); - - if ( ( Math.abs( extractedColorScaleValueSet.getDuration() - duration ) ) < durationDiff ) - { - durationDiff = Math.abs( extractedColorScaleValueSet.getDuration() - duration ); - closestMatchingColorScaleValueSet = extractedColorScaleValueSet; - } - } - return closestMatchingColorScaleValueSet; - } - - private void updateAllColorUsesSet() - { - List defaultColorList = _dataMgr.getDefaultColorScaleValueSetList(); - List databaseColorList = _dataMgr.getColorValueTableColorScaleValueSetList(); - ColorScaleValueSet extractedColorScaleValueSet = null; - - for ( int i = 0; i < defaultColorList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) defaultColorList.get( i ); - _allColorUsesSet.add( extractedColorScaleValueSet.getColorUseString() ); - } - for ( int i = 0; i < databaseColorList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) databaseColorList.get( i ); - _allColorUsesSet.add( extractedColorScaleValueSet.getColorUseString() ); - } - } - - private String getFormattedDoubleString(double value) - { - return getFormattedDoubleString(value, "%7.2f"); - } - - private String getFormattedDoubleString(double value, String format) - { - String text = null; - - if ( value == MINIMUM_VALUE ) - { - text = "< Min"; - } - else if ( value == MISSING ) - { - text = "MSG"; - } - else - { - text = String.format(format, value); - } - - return text; - } - - private NamedColor getClosestNamedColor( Color color ) - { - NamedColor namedColor = null; - - if ( _namedColorMatcher == null ) - { - _namedColorMatcher = new NamedColorMatcher( _dataMgr.getRGBColorMap() ); - } - - namedColor = _namedColorMatcher.getClosestNamedColor( color ); - - return namedColor; - } - - private class EditScaleValueTextFieldListener extends MouseAdapter - { - private JPanel _associatedColorPanel = null; - private double _scaleValueDouble = 0; - - public EditScaleValueTextFieldListener( JPanel associatedColorPanel, double scaleValueDouble ) - { - _associatedColorPanel = associatedColorPanel; - _scaleValueDouble = scaleValueDouble; - } - - public void mousePressed( MouseEvent e ) - { - _editTabColor.setBackground( _associatedColorPanel.getBackground() ); - - _editTabScaleValue.setText( getFormattedDoubleString( _scaleValueDouble ) ); - } - } - - private class ClickColorSelectionListener extends MouseAdapter - { - private double _scaleValueDouble = 0; - - public ClickColorSelectionListener( Double scaleValueDouble ) - { - _scaleValueDouble = scaleValueDouble; - } - - public void mousePressed( MouseEvent e ) - { - JPanel panel = (JPanel) e.getSource(); - - _editTabColor.setBackground( panel.getBackground() ); - - _editTabScaleValue.setText( getFormattedDoubleString(_scaleValueDouble ) ); - - displayColorPickerDialog(); - - addColorSet(); - } - } - - - - private String[] getColorUseComboBoxString() - { - String[] colorUseComboBoxString = null; - List hvDefaultColorList = _dataMgr.getDefaultColorScaleValueSetList(); - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - Set colorUseSet = new HashSet(); - String selectedItem = null; - String colorUseString = null; - - List colorUseNamesList = new ArrayList(); - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedItem = _viewTabUsedColorsSetLabel.getText(); - } - else - { - selectedItem = (String) _editTabSetComboBox.getSelectedItem(); - } - - if ( selectedItem.equalsIgnoreCase( "default" ) ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBoxPanel.setVisible( false ); - } - else - { - _editTabUserIDComboBoxPanel.setVisible( false ); - } - for ( int i = 0; i < hvDefaultColorList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) hvDefaultColorList.get( i ); - colorUseString = colorScaleValueSet.getColorUseString(); - if ( ! colorUseSet.contains( colorUseString ) ) - { - colorUseSet.add( colorUseString ); - colorUseNamesList.add( colorUseString ); - } - } - - colorUseComboBoxString = (String[]) colorUseNamesList.toArray( new String[ colorUseNamesList.size() ] ); - } - - if ( selectedItem.equalsIgnoreCase( "user" ) ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBoxPanel.setVisible( true ); - } - else - { - _editTabUserIDComboBoxPanel.setVisible( true ); - } - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ! colorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) - { - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - } - - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxString = (String[]) colorUseSet.toArray( new String[ colorUseSet.size() ] ); - } - - if ( selectedItem.equalsIgnoreCase( "office" ) ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBoxPanel.setVisible( false ); - } - else - { - _editTabUserIDComboBoxPanel.setVisible( false ); - } - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( colorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) - { - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - } - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxString = (String[]) colorUseSet.toArray( new String[ colorUseSet.size() ] ); - } - - if ( selectedItem.equalsIgnoreCase( "" ) ) - { - for ( int i = 0; i < _usedColorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxString = (String[]) colorUseSet.toArray( new String[ colorUseSet.size() ] ); - - } - return colorUseComboBoxString; - } - - private void updateUserIDComboBox() - { - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - List userIDsList = new ArrayList(); - Set userIDsSet = new HashSet(); - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - ColorScaleValueSet colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ! colorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) - { - userIDsList.add( colorScaleValueSet.getUserID() ); - } - } - - userIDsSet.addAll( userIDsList ); - - Iterator iterator = userIDsSet.iterator(); - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabUserIDComboBox.removeAllItems(); - while ( iterator.hasNext() ) - { - String userID = (String) iterator.next(); - - _viewTabUserIDComboBox.addItem( userID ); - } - } - else - { -// _updatingComboBoxes = true; - _editTabUserIDComboBox.removeAllItems(); - while ( iterator.hasNext() ) - { - String userID = (String) iterator.next(); - - _editTabUserIDComboBox.addItem( userID ); - } -// _updatingComboBoxes = false; - } - - if ( userIDsSet.isEmpty() ) - { - _editTabUserIDComboBox.addItem( "-----" ); - } - } - - - private List getDurationSet() - { - String selectedItem = null; - ColorScaleValueSet extractedColorScaleValueSet = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedItem = _viewTabUsedColorsSetLabel.getText(); - } - else - { - selectedItem = (String) _editTabSetComboBox.getSelectedItem(); - } - - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - SortedSet durationSet = new TreeSet (); - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - if ( selectedItem.equalsIgnoreCase( "user" ) ) - { - String selectedUser = null; - String selectedColorUse = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedUser = (String) _viewTabUserIDComboBox.getSelectedItem(); - selectedColorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - - } - else - { - selectedUser = (String) _editTabUserIDComboBox.getSelectedItem(); - selectedColorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - - } - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( selectedUser ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( selectedColorUse ) ) ) - { - durationSet.add( extractedColorScaleValueSet.getDuration() ); - } - } - } - else if ( selectedItem.equalsIgnoreCase( "office" ) ) - { - String selectedColorUse = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedColorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - } - else - { - selectedColorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - } - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( selectedColorUse ) ) ) - { - durationSet.add( extractedColorScaleValueSet.getDuration() ); - } - } - } - } - - if ( ( _activeTabID == VIEW_PANEL_TAB_ID ) || ( selectedItem.equalsIgnoreCase( "default" ) ) ) - { - String selectedColorUse = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedColorUse = (String) _viewTabColorUseComboBox.getSelectedItem(); - } - else - { - selectedColorUse = (String) _editTabColorUseComboBox.getSelectedItem(); - } - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - if ( selectedColorUse != null ) - { - for ( int i = 0; i < _usedColorScaleValueSetList.size(); i++ ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - if ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( selectedColorUse ) ) - { - durationSet.add( extractedColorScaleValueSet.getDuration() ); - } - } - } - } - else - { - durationSet.add( 0.0 ); - } - } - - _currentDisplayedDurationSet = durationSet; - - List sortedDurationStringList = getSortedDurationStringList( durationSet ); - - return sortedDurationStringList; - } - - private List getSortedDurationStringList( SortedSet durationSet ) - { - List sortedDurationDoubleList = new ArrayList ( durationSet ); - List sortedDurationStringList = new ArrayList (); - - - for( Double duration : sortedDurationDoubleList ) - { - sortedDurationStringList.add( getComboBoxDurationString( duration ) ); - } - - return sortedDurationStringList; - } - - - public String getComboBoxDurationString( double doubleValue ) - { - String returnString = ""; - - if ( Math.floor( doubleValue ) == doubleValue ) - { - returnString = "" + ( (int) doubleValue ); - } - else - { - returnString = "" + doubleValue; - } - - return returnString; - } - - private ColorScaleValueSet getColorScaleValueSetByColorUse( String colorUse ) - { - List colorScaleValueSetList = null; - ColorScaleValueSet colorScaleValueSet = null; - String selectedUser = null; - Double selectedDurationDouble = -1.0; - double selectedDuration = -1; - ColorScaleValueSet extractedColorScaleValueSet = null; - - String setComboBoxString = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedDurationDouble = getDurationComboBoxDoubleValue( _viewTabDurationComboBox ); - } - else - { - setComboBoxString = (String) _editTabSetComboBox.getSelectedItem(); - selectedDurationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - } - int i = 0; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) // in Edit Tab - { - if ( ( setComboBoxString.equalsIgnoreCase( "default" ) ) && ( selectedDurationDouble != null ) ) - { - colorScaleValueSetList = _dataMgr.getDefaultColorScaleValueSetList(); - while ( ( i < colorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getDuration() == selectedDurationDouble ) ) - { - colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - } - i++; - } - - } - else if ( ( setComboBoxString.equalsIgnoreCase( "user" ) ) && ( selectedDurationDouble != null ) ) - { - colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedUser = (String) _viewTabUserIDComboBox.getSelectedItem(); - selectedDurationDouble = (Double) _viewTabDurationComboBox.getSelectedItem(); - } - else - { - selectedUser = (String) _editTabUserIDComboBox.getSelectedItem(); - selectedDurationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - } - if ( selectedDurationDouble != null ) - { - selectedDuration = selectedDurationDouble; - - extractedColorScaleValueSet = null; - - while ( ( i < colorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( selectedUser ) ) && - ( extractedColorScaleValueSet.getDuration() == selectedDuration ) ) - { - colorScaleValueSet = extractedColorScaleValueSet; - } - i++; - } - } - - } - else if ( ( setComboBoxString.equalsIgnoreCase( "office" ) ) && ( selectedDurationDouble != null ) ) - { - colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedDurationDouble = (Double) _viewTabDurationComboBox.getSelectedItem(); - } - else - { - selectedDurationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - } - - if ( selectedDurationDouble != null ) - { - selectedDuration = selectedDurationDouble; - - while ( ( i < colorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( ( extractedColorScaleValueSet.getUserID().equalsIgnoreCase( "default" ) ) && - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) && - ( extractedColorScaleValueSet.getDuration() == selectedDuration ) ) - { - colorScaleValueSet = extractedColorScaleValueSet; - } - i++; - } - } - - } - } - else - { - double duration = -1.0; - if ( _viewTabDurationComboBox.getSelectedItem() != null ) - { - Double durationDouble = getDurationComboBoxDoubleValue( _viewTabDurationComboBox ); - duration = durationDouble; - } - - extractedColorScaleValueSet = null; - while ( ( i < _usedColorScaleValueSetList.size() ) && ( colorScaleValueSet == null ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) _usedColorScaleValueSetList.get( i ); - - if ( ( ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) || - ( extractedColorScaleValueSet.getColorUseString().equalsIgnoreCase( colorUse ) ) ) && - ( ( extractedColorScaleValueSet.getDuration() ) == duration ) ) - { - colorScaleValueSet = extractedColorScaleValueSet; - } - i++; - } - } - return colorScaleValueSet; - } - - private Double getDurationComboBoxDoubleValue( JComboBox comboBox ) - { - Double returnValue = null; - - Object selectedItem = comboBox.getSelectedItem(); - - if ( selectedItem instanceof String ) - { - String selectedItemString = (String) selectedItem; - if ( selectedItemString != null ) - { - returnValue = Double.parseDouble( selectedItemString ); - } - } - else if ( selectedItem instanceof Integer ) - { - Integer selectedItemInteger = (Integer) selectedItem; - if ( selectedItemInteger != null ) - { - returnValue = selectedItemInteger.doubleValue(); - } - } - return returnValue; - } - - private void updateColorUseComboBox( String userID ) - { - List colorUseComboBoxList = new ArrayList(); - List colorScaleValueSetList = _dataMgr.getColorValueTableColorScaleValueSetList(); - Set colorUseSet = new HashSet(); - ColorScaleValueSet colorScaleValueSet = null; - - List colorUseNamesList = new ArrayList(); - - for ( int i = 0; i < colorScaleValueSetList.size(); i++ ) - { - colorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetList.get( i ); - if ( colorScaleValueSet.getUserID().equalsIgnoreCase( userID ) ) - { - colorUseNamesList.add( colorScaleValueSet.getColorUseString() ); - } - } - - colorUseSet.addAll( colorUseNamesList ); - - colorUseComboBoxList.addAll( colorUseSet ); - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - _viewTabColorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseComboBoxList.size(); i++ ) - { - _viewTabColorUseComboBox.addItem( (String) colorUseComboBoxList.get( i ) ); - } - } - else - { - _editTabColorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseComboBoxList.size(); i++ ) - { - _editTabColorUseComboBox.addItem( (String) colorUseComboBoxList.get( i ) ); - } - } - } - - private void clickLeftVCRButton( JComboBox setComboBox, JComboBox colorUseComboBox, JComboBox durationComboBox ) - { - int index = 0; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - String selectedSetString = (String) setComboBox.getSelectedItem(); - String selectedColorUseString = (String) colorUseComboBox.getSelectedItem(); - - if ( ( selectedSetString.equalsIgnoreCase( "user" ) ) && ( selectedColorUseString.equalsIgnoreCase( "precipitation" ) ) ) - { - index = durationComboBox.getSelectedIndex(); - int durationItemCount = durationComboBox.getItemCount(); - - if ( index == 0 ) - { - index = durationItemCount - 1; - } - else - { - index--; - } - durationComboBox.setSelectedIndex( index ); - - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == 0 ) - { - index = colorUseItemCount - 1; - } - else - { - index--; - } - colorUseComboBox.setSelectedIndex( index ); - } - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == 0 ) - { - index = colorUseItemCount - 1; - } - else - { - index--; - } - colorUseComboBox.setSelectedIndex( index ); - } - - displayColorScaleValues(); - } - - private void clickRightVCRButton( JComboBox setComboBox, JComboBox colorUseComboBox, JComboBox durationComboBox ) - { - int index = 0; - - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - String selectedSetString = (String) setComboBox.getSelectedItem(); - String selectedColorUseString = (String) colorUseComboBox.getSelectedItem(); - if ( ( selectedSetString.equalsIgnoreCase( "user" ) ) && ( selectedColorUseString.equalsIgnoreCase( "precipitation" ) ) ) - { - index = durationComboBox.getSelectedIndex(); - int durationItemCount = durationComboBox.getItemCount(); - - if ( index == ( durationItemCount - 1 ) ) - { - index = 0; - } - else - { - index++; - } - durationComboBox.setSelectedIndex( index ); - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == ( colorUseItemCount - 1 ) ) - { - index = 0; - } - else - { - index++; - } - colorUseComboBox.setSelectedIndex( index ); - } - } - else - { - index = colorUseComboBox.getSelectedIndex(); - int colorUseItemCount = colorUseComboBox.getItemCount(); - - if ( index == ( colorUseItemCount - 1 ) ) - { - index = 0; - } - else - { - index++; - } - colorUseComboBox.setSelectedIndex( index ); - } - - displayColorScaleValues(); - } - - private ColorScaleValueSet getNewColorScaleValueSet() - { - ColorScaleValueSet colorScaleValueSet = new ColorScaleValueSet(); - ScaleValueSet scaleValueSet = new ScaleValueSet(); - ColorSet colorSet = new ColorSet(); - - scaleValueSet.addScaleValue( -9999 ); - scaleValueSet.addScaleValue( -8888 ); - - colorSet.addNamedColor( new Color( 0, 0, 0 ) ); - colorSet.addNamedColor( new Color( 102, 102, 102 ) ); - - colorScaleValueSet.setScaleValueSet( scaleValueSet ); - colorScaleValueSet.setColorSet( colorSet ); - return colorScaleValueSet; - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _viewTabColorUseComboBox.addActionListener( new ColorUseComboBoxSelectionListener() ); - _editTabColorUseComboBox.addActionListener( new ColorUseComboBoxSelectionListener() ); - _editTabSetComboBox.addActionListener( new SetComboBoxSelectionListener() ); - _viewTabDurationComboBox.addActionListener( new DurationComboBoxListener() ); - _editTabDurationComboBox.addActionListener( new DurationComboBoxListener() ); - _tabbedPane.addChangeListener( new TabChangeListener() ); - _viewTabVCRLeftColorButton.addActionListener( new ViewTabLeftVCRButtonColorListener() ); - _viewTabVCRRightColorButton.addActionListener( new ViewTabRightVCRButtonColorListener() ); - _editTabVCRLeftScaleValueButton.addActionListener( new EditTabLeftVCRButtonScaleValueListener() ); - _editTabVCRRightScaleValueButton.addActionListener( new EditTabRightVCRButtonScaleValueListener() ); - _frameContentPane.addMouseWheelListener( new ColorUseComboBoxMouseWheelListener() ); - _viewTabUserIDComboBox.addActionListener( new UserIDComboBoxListener() ); - _editTabUserIDComboBox.addActionListener( new UserIDComboBoxListener() ); - _editTabAddColorSet.addActionListener( new AddColorSet() ); - _editTabDeleteColorSet.addActionListener( new DeleteColorSet() ); - _editTabResetColorButton.addActionListener( new ResetColorSetListener() ); - _editTabColor.addMouseListener( new ClickEditTabColor() ); - _saveAsUserButton.addActionListener( new SaveAsUserButtonListener() ); - _saveAsOfficeButton.addActionListener( new SaveAsOfficeButtonListener() ); - _deleteUserButton.addActionListener( new DeleteAsUserButtonListener() ); - _deleteOfficeButton.addActionListener( new DeleteAsOfficeButtonListener() ); - } - - - private class DeleteAsUserButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to delete the user set " + - ( (String) _editTabColorUseComboBox.getSelectedItem() ), "Delete Confirmation" ) ) - { - ColorScaleValueSet colorScaleValueSetToDelete = getCurrentlyDisplayedColorScaleValueSet(); - _dataMgr.deleteAsUser( colorScaleValueSetToDelete ); - _editTabSetComboBox.setSelectedItem( "user" ); - _editTabUserIDComboBox.setSelectedItem( _userID ); - - String colorUseString = colorScaleValueSetToDelete.getColorUseString(); - - if ( userHasColorUse( colorUseString, _userID ) ) - { - _editTabColorUseComboBox.setSelectedItem( colorUseString ); - } - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - setLastUpdateTimeToCurrentTime(); - } - } - } - - private boolean userHasColorUse( String colorUseString, String userID ) - { - boolean foundColorUse = false; - List userColorScaleValueSetList = getFilteredColorScaleValueSetList( userID, colorUseString ); - if ( userColorScaleValueSetList.size() > 0 ) - { - foundColorUse = true; - } - - return foundColorUse; - } - - - private class DeleteAsOfficeButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to delete the office set " + - ( (String) _editTabColorUseComboBox.getSelectedItem() ), "Delete Confirmation" ) ) - { - ColorScaleValueSet colorScaleValueSetToDelete = getCurrentlyDisplayedColorScaleValueSet(); - _dataMgr.deleteAsOffice( colorScaleValueSetToDelete ); - _editTabSetComboBox.setSelectedItem( "office" ); - String colorUseString = colorScaleValueSetToDelete.getColorUseString(); - - if ( userHasColorUse( colorUseString, "default" ) ) - { - _editTabColorUseComboBox.setSelectedItem( colorUseString ); - } - - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - setLastUpdateTimeToCurrentTime(); - } - } - } - - private class SaveAsOfficeButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to save the displayed color set as the office set?", "Save Confirmation" ) ) - { - Double durationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - ColorScaleValueSet colorScaleValueSetToSave = getCurrentlyDisplayedColorScaleValueSet(); - if ( ( colorScaleValueSetToSave == null ) || ( durationDouble == null ) ) - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "No color set is displayed", "Unable to save" ); - } - else - { - double duration = durationDouble; - String colorUseToSaveString = (String) _editTabSaveAsColorUseComboBox.getSelectedItem(); - - colorScaleValueSetToSave.setDuration( duration ); - colorScaleValueSetToSave.setColorUseString( colorUseToSaveString ); - - _dataMgr.saveAsOffice( colorScaleValueSetToSave ); - setLastUpdateTimeToCurrentTime(); - } - String setString = (String) _editTabSetComboBox.getSelectedItem(); - - if ( setString.equalsIgnoreCase( "default" ) ) - { - _editTabDurationComboBox.setSelectedItem( 0 ); - } - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - } - } - } - - private class SaveAsUserButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( DialogHelper.displayConfirmDialog( ColorChooserDialog.this, "Are you sure you want to save the displayed color set as your user set?", "Save Confirmation" ) ) - { - Double durationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - ColorScaleValueSet colorScaleValueSetToSave = getCurrentlyDisplayedColorScaleValueSet(); - if ( ( colorScaleValueSetToSave == null ) || ( durationDouble == null ) ) - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "No color set is displayed", "Unable to save" ); - } - else - { - double duration = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - String colorUseToSaveString = (String) _editTabSaveAsColorUseComboBox.getSelectedItem(); - colorScaleValueSetToSave.setDuration( duration ); - colorScaleValueSetToSave.setColorUseString( colorUseToSaveString ); - - _dataMgr.saveAsUser( colorScaleValueSetToSave, duration ); - setLastUpdateTimeToCurrentTime(); - } - String setString = (String) _editTabSetComboBox.getSelectedItem(); - - if ( setString.equalsIgnoreCase( "default" ) ) - { - _editTabDurationComboBox.setSelectedIndex( 0 ); - } - - updateUsedColorScaleValueSetList(); - displayColorScaleValues(); - } - } - } - - private ColorScaleValueSet getCurrentlyDisplayedColorScaleValueSet() - { - return _displayedColorScaleValueSet; - } - - private void updateUsedColorScaleValueSetList() - { - _dataMgr.resetColorValueTableColorScaleValueSetList(); - List hvDefaultColorList = _dataMgr.getDefaultColorScaleValueSetList(); - List colorValueTableList = _dataMgr.getColorValueTableColorScaleValueSetList(); - String colorUseString = null; - String userIDString = null; - double duration = 0.0; - Set colorUseNamesSet = new HashSet(); - Set usedColorScaleValueSetsSet = new HashSet(); - ColorScaleValueSet matchingColorScaleValueSet = null; - - ColorScaleValueSet colorScaleValueSet = null; - - _usedColorScaleValueSetList = new ArrayList(); - - // Find used ColorScaleValueSet (user/office/hardcoded) for each default ColorUse - for ( int i = 0; i < hvDefaultColorList.size(); i++ ) - { - colorScaleValueSet = (ColorScaleValueSet) hvDefaultColorList.get( i ); - matchingColorScaleValueSet = findMatchingUsedSet( colorScaleValueSet ); - usedColorScaleValueSetsSet.add( matchingColorScaleValueSet ); - colorUseNamesSet.add( matchingColorScaleValueSet.getColorUseString() ); - } - - // To include "non standard durations" for precip - for ( int i = 0; i < colorValueTableList.size(); i++ ) - { - colorScaleValueSet = (ColorScaleValueSet) colorValueTableList.get( i ); - - userIDString = colorScaleValueSet.getUserID(); - - if ( ( userIDString.equalsIgnoreCase( _userID ) ) || ( userIDString.equalsIgnoreCase( "default" ) ) ) - { - colorUseString = colorScaleValueSet.getColorUseString(); - - matchingColorScaleValueSet = findMatchingUsedSet( colorScaleValueSet ); - usedColorScaleValueSetsSet.add( matchingColorScaleValueSet ); - } - } - _usedColorScaleValueSetList.addAll( usedColorScaleValueSetsSet ); - } - - private ColorScaleValueSet findMatchingUsedSet( ColorScaleValueSet defaultColorScaleValueSet ) - { - ColorScaleValueSet usedColorScaleValueSet = ColorScaleValueSet.getCopyOfColorScaleValueSet( defaultColorScaleValueSet ); - - List colorScaleValueSetFromDatabaseList = _dataMgr.getColorValueTableColorScaleValueSetList(); - ColorScaleValueSet extractedColorScaleValueSet = null; - String colorUseName = usedColorScaleValueSet.getColorUseString(); - double duration = usedColorScaleValueSet.getDuration(); - String extractedColorUseString = null; - boolean foundUserSet = false; - int i = 0; - - while ( ( i < colorScaleValueSetFromDatabaseList.size() ) && ( ! foundUserSet ) ) - { - extractedColorScaleValueSet = (ColorScaleValueSet) colorScaleValueSetFromDatabaseList.get( i ); - extractedColorUseString = extractedColorScaleValueSet.getColorUseString(); - - if ( ( colorUseName.equalsIgnoreCase( extractedColorUseString ) ) && - ( duration == ( extractedColorScaleValueSet.getDuration() ) ) ) - { - String extractedUserIDString = extractedColorScaleValueSet.getUserID(); - - if ( extractedUserIDString.equalsIgnoreCase( "default" ) ) - { - usedColorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); - } - else if ( extractedUserIDString.equalsIgnoreCase( _userID ) ) - { - usedColorScaleValueSet = new ColorScaleValueSet( extractedColorScaleValueSet ); - - foundUserSet = true; - } - } - i++; - } - - return usedColorScaleValueSet; - } - - private class ResetColorSetListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _dataMgr.resetColorValueTableColorScaleValueSetList(); - _dataMgr.resetHvDefaultColorList(); - - displayColorScaleValues(); - } - } - - private void displayColorPickerDialog() - { - ColorHolder colorHolder = new ColorHolder( _editTabColor.getBackground() ); - - ColorPickerDialog colorPicker = new ColorPickerDialog( ColorChooserDialog.this, colorHolder ); - colorPicker.setPreferredSize( new Dimension( 300, 300 ) ); - colorPicker.setVisible( true ); - - NamedColor namedColor = getClosestNamedColor( colorHolder.getColor() ); - - _editTabColor.setBackground( namedColor ); - } - - private class ClickEditTabColor extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - displayColorPickerDialog(); - } - } - - private class DeleteColorSet implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - try - { - double scaleValueToDelete = Double.valueOf( _editTabScaleValue.getText() ); - int i = 0; - int index = -1; - String colorUseComboBoxString = (String) _editTabColorUseComboBox.getSelectedItem(); - ColorScaleValueSet colorScaleValueSet = getColorScaleValueSetByColorUse( colorUseComboBoxString ); - ScaleValueSet scaleValueSet = colorScaleValueSet.getScaleValueSet(); - ColorSet colorSet = colorScaleValueSet.getColorSet(); - - while ( ( i < scaleValueSet.getScaleValueSet().size() ) && ( index == -1 ) ) - { - double scaleValue = (Double) scaleValueSet.getScaleValueSet().get( i ); - - if ( closeEnoughToBeEqual( scaleValueToDelete, scaleValue ) ) - { - index = i; - } - i++; - } - - if ( index != -1 ) - { - scaleValueSet.deleteScaleValueAtIndex( index ); - colorSet.deleteNamedColorAtIndex( index ); - } - - displayColorScaleValues(); - - } - catch ( NumberFormatException error ) - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "Can not delete Missing/Below Threshold value", "Unable to Delete" ); - } - - } - } - - private void addColorSet() - { - String editTabScaleValueString = _editTabScaleValue.getText().trim(); - double newScaleValue = -1; - boolean validScaleValue = true; - - if ( ! editTabScaleValueString.equalsIgnoreCase( "" ) ) - { - if ( editTabScaleValueString.equalsIgnoreCase( "MSG" ) ) - { - newScaleValue = -9999; - } - else if ( editTabScaleValueString.equalsIgnoreCase( "< Min" ) ) - { - newScaleValue = -8888; - } - else - { - try - { - newScaleValue = Double.valueOf( editTabScaleValueString ); - } - catch (NumberFormatException ex ) - { - validScaleValue = false; - } - } - - if ( validScaleValue ) - { - int index = -1; - int i = 0; - boolean replaceValue = false; - - String colorUseComboBoxString = (String) _editTabColorUseComboBox.getSelectedItem(); - ColorScaleValueSet colorScaleValueSet = getColorScaleValueSetByColorUse( colorUseComboBoxString ); - if ( colorScaleValueSet == null ) - { - colorScaleValueSet = _displayedColorScaleValueSet; - Double durationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - colorScaleValueSet.setColorUseString( colorUseComboBoxString ); - colorScaleValueSet.setDuration( durationDouble ); - _dataMgr.addColorScaleValueSetToColorValueTableList( colorScaleValueSet ); - } - - ScaleValueSet scaleValueSet = colorScaleValueSet.getScaleValueSet(); - ColorSet colorSet = colorScaleValueSet.getColorSet(); - if ( ( scaleValueSet != null ) && ( colorSet != null ) ) - { - while ( ( i < scaleValueSet.getScaleValueSet().size() ) && ( index == -1 ) ) - { - double scaleValue = (Double) scaleValueSet.getScaleValueSet().get( i ); - - if ( closeEnoughToBeEqual(newScaleValue, scaleValue) ) - { - index = i; - replaceValue = true; - } - - if ( newScaleValue < scaleValue ) - { - index = i; - } - i++; - } - } - - if ( index == -1 ) - { - index = i; - } - - if ( replaceValue ) - { - scaleValueSet.replaceScaleValueAtIndex( newScaleValue, index ); - colorSet.replaceNamedColorAtIndex( _editTabColor.getBackground(), index ); - } - else - { - scaleValueSet.addScaleValueAtIndex( newScaleValue, index ); - colorSet.addNamedColorAtIndex( _editTabColor.getBackground(), index ); - } - - _displayedColorScaleValueSet = colorScaleValueSet; - displayColorScaleValues(); - } - else - { - DialogHelper.displayErrorDialog( ColorChooserDialog.this, "Invalid ScaleValue entered", "Invalid ScaleValue" ); - } - } - } - - private class AddColorSet implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - addColorSet(); - } - } - - private boolean closeEnoughToBeEqual(double value1, double value2) - { - boolean result = false; - - if (Math.abs((value1 - value2)) < 0.0001) - { - result = true; - } - - return result; - - } - - private class ViewTabLeftVCRButtonColorListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickLeftVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - - private class ViewTabRightVCRButtonColorListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickRightVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - - private class EditTabLeftVCRButtonScaleValueListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickLeftVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - - private class EditTabRightVCRButtonScaleValueListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clickRightVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - - private class ColorUseComboBoxMouseWheelListener implements MouseWheelListener - { - - public void mouseWheelMoved( MouseWheelEvent e ) - { - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - if ( e.getWheelRotation() > 0 ) - { - clickLeftVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - else - { - clickRightVCRButton( null, _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - else - { - if ( e.getWheelRotation() > 0 ) - { - clickLeftVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - else - { - clickRightVCRButton( _editTabSetComboBox, _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - } - } - - - private class TabChangeListener implements ChangeListener - { - - public void stateChanged( ChangeEvent e ) - { - JTabbedPane jTabbedPane = (JTabbedPane) e.getSource(); - String activeTabString = jTabbedPane.getSelectedComponent().getName(); - - jTabbedPane.setBackground( Color.LIGHT_GRAY ) ; - - if ( activeTabString.equalsIgnoreCase( "ViewPanelTab" ) ) - { - _activeTabID = VIEW_PANEL_TAB_ID; - _dataMgr.resetColorValueTableColorScaleValueSetList(); - _dataMgr.resetHvDefaultColorList(); -// displayUsedColorSets(); - } - else if ( activeTabString.equalsIgnoreCase( "EditPanelTab" ) ) - { - _activeTabID = EDIT_PANEL_TAB_ID; - _editTabSetComboBox.setSelectedItem( "default" ); - } - displayColorScaleValues(); - } - } - - private class ColorUseComboBoxSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( ! _updatingComboBoxes ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - String colorUseString = (String) _viewTabColorUseComboBox.getSelectedItem(); - - if ( ( colorUseString != null ) && ( ! colorUseString.equalsIgnoreCase( "-----" ) ) ) - { - UpdateDurationComboBoxByColorUseComboBox( _viewTabColorUseComboBox, _viewTabDurationComboBox ); - } - } - else - { - String colorUseString = (String) _editTabColorUseComboBox.getSelectedItem(); - - if ( ( colorUseString != null ) && ( ! colorUseString.equalsIgnoreCase( "-----" ) ) ) - { - UpdateDurationComboBoxByColorUseComboBox( _editTabColorUseComboBox, _editTabDurationComboBox ); - } - } - } - } - } - - private void UpdateDurationComboBoxByColorUseComboBox( JComboBox colorUseComboBox, JComboBox durationComboBox ) - { - List durationSet = getDurationSet(); - String selectedColorUseString = (String) colorUseComboBox.getSelectedItem(); - String setString = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - setString = _viewTabUsedColorsSetLabel.getText(); - } - else - { - setString = (String) _editTabSetComboBox.getSelectedItem(); - } - if ( selectedColorUseString != null ) - { - List durationList = new ArrayList( durationSet ); - - durationComboBox.removeAllItems(); - - for( String duration : durationList ) - { - durationComboBox.addItem( duration ); - } - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - _editTabSaveAsColorUseComboBox.setSelectedItem( selectedColorUseString ); - } - } - - if ( colorUseComboBox.getItemCount() > 0 ) - { - displayColorScaleValues(); - } - String colorUseString = (String) _editTabColorUseComboBox.getSelectedItem(); - } - - private class UserIDComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( ! _updatingComboBoxes ) - { - - String selectedUserID = null; - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - selectedUserID = (String) _viewTabUserIDComboBox.getSelectedItem(); - } - else - { - selectedUserID = (String) _editTabUserIDComboBox.getSelectedItem(); - if ( isUsersSet() ) - { - _deleteUserButton.setEnabled( true ); - } - else - { - _deleteUserButton.setEnabled( false ); - } - } - - updateColorUseComboBox( selectedUserID ); - } - } - } - - private class DurationComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( ! _updatingComboBoxes ) - { - - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - UpdateColorScaleValuesByDurationUpdate( _viewTabUsedColorsSetLabel.getText(), _viewTabUserIDComboBox ); - } - else // In the edit tab - { - Double durationDouble = getDurationComboBoxDoubleValue( _editTabDurationComboBox ); - if ( durationDouble != null ) - { - if ( ( _currentDisplayedDurationSet != null ) && ( _currentDisplayedDurationSet.contains( durationDouble ) ) ) - { - String editTabSetComboBoxString = (String) _editTabSetComboBox.getSelectedItem(); - UpdateColorScaleValuesByDurationUpdate( editTabSetComboBoxString, _editTabUserIDComboBox ); - } - } - } - } - } - } - - private void UpdateColorScaleValuesByDurationUpdate( String setComboBoxString, JComboBox userIDComboBox ) - { - String selectedUserID = null; - - if ( setComboBoxString.indexOf( "user" ) != -1 ) - { - if ( _activeTabID == EDIT_PANEL_TAB_ID ) - { - selectedUserID = (String) userIDComboBox.getSelectedItem(); - } - else - { - selectedUserID = _userID; - } - } - - displayColorScaleValues(); - } - - - private class SetComboBoxSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _activeTabID == VIEW_PANEL_TAB_ID ) - { - populateSetComboBox( _viewTabUsedColorsSetLabel.getText(), _viewTabColorUseComboBox ); - } - else - { - String editTabSetComboBoxString = (String) _editTabSetComboBox.getSelectedItem(); - - populateSetComboBox( editTabSetComboBoxString, _editTabColorUseComboBox ); - if ( isUsersSet() ) - { - _deleteUserButton.setEnabled( true ); - } - else - { - _deleteUserButton.setEnabled( false ); - } - if ( isOfficeSet() ) - { - _deleteOfficeButton.setEnabled( true ); - } - else - { - _deleteOfficeButton.setEnabled( false ); - } - - } - } - } - - private boolean isUsersSet() - { - boolean isUserSet = false; - - String setString = (String) _editTabSetComboBox.getSelectedItem(); - String userID = (String) _editTabUserIDComboBox.getSelectedItem(); - - if ( - ( setString != null ) && - ( userID != null ) && - ( setString.equalsIgnoreCase( "user" ) ) && - ( userID.equalsIgnoreCase( _userID ) ) ) - { - isUserSet = true; - } - - return isUserSet; - } - - private boolean isOfficeSet() - { - boolean isOfficeSet = false; - - String setString = (String) _editTabSetComboBox.getSelectedItem(); - - if ( - ( setString != null ) && - ( setString.equalsIgnoreCase( "office" ) ) ) - { - isOfficeSet = true; - } - - return isOfficeSet; - } - - private void populateSetComboBox( String setComboBoxString, JComboBox colorUseComboBox ) - { - String[] colorUseStringArray = getColorUseComboBoxString(); - - if ( setComboBoxString.equalsIgnoreCase( "default" ) ) - { - colorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseStringArray.length; i++ ) - { - colorUseComboBox.addItem( colorUseStringArray[ i ] ); - } - } - else if ( setComboBoxString.equalsIgnoreCase( "user" ) ) - { - updateUserIDComboBox(); - } - else if ( colorUseStringArray.length == 0 ) // empty database and office is selected - { - colorUseComboBox.removeAllItems(); - colorUseComboBox.addItem( "-----" ); - } - else if ( setComboBoxString.equalsIgnoreCase( "office" ) ) - { - colorUseComboBox.removeAllItems(); - - for ( int i = 0; i < colorUseStringArray.length; i++ ) - { - colorUseComboBox.addItem( colorUseStringArray[ i ] ); - } - displayColorScaleValues(); - } - } - - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - - - public static boolean validateInputParameters( String[] args ) - { - boolean valid = false; - - if ( args.length < 6 ) - { - System.out.println( "ColorChooserDialog " ); - } - else - { - valid = true; - } - - return valid; - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - //shutdown the thread in the ColorChooseDialog and set the _isRunning variable to false; - _thread.stop(); - _lastUpdateTime = -1; //indicate that we are closed - ColorChooserDialog._isRunning = false; - - this.dispose(); - } - - - public static long getLastUpdateTime() - { - return _lastUpdateTime; - } - - private static void setLastUpdateTimeToCurrentTime() - { - //return the time in seconds, so divide by 1000 - _lastUpdateTime = System.currentTimeMillis()/1000; - } - - public static void show(String jdbcConnectionString, String logFilePath, - String applicationName, String userID, String defaultColorFilePath, - String rgbColorFilePath ) - { - if (! _isRunning) //make sure that we don't invoke 2 of these dialogs at a time - { - _lastUpdateTime = 0; //when called a second time, this variable needs to be reset - - ColorChooserDialogDataMgr dataMgr = null; - ColorChooserDialog dialog = null; - boolean validInputParameters = false; - FileLogger logger = null; - - logger = new FileLogger( logFilePath ); - - dataMgr = new ColorChooserDialogDataMgr( jdbcConnectionString, logger, applicationName, defaultColorFilePath, rgbColorFilePath); - - dialog = new ColorChooserDialog( new JFrame(), dataMgr, userID ); - - _thread = new Thread(dialog); - _thread.start(); - _isRunning = true; - } - } - - public void run() - { - //This is here to allow the caller to continue functioning while this window is open - this.setVisible(true); - } - - - public static void main(String[] args) - { - boolean validInputParameters = false; - - validInputParameters = ColorChooserDialog.validateInputParameters( args ); - - if ( validInputParameters == true ) - { - - String jdbcConnectionString = args[0]; - String logFilePath = args[ 1 ]; - String applicationName = args[ 2 ]; - String userID = args[3]; - String defaultColorFilePath = args[ 4 ]; - String rgbColorFilePath = args[ 5 ]; - - show(jdbcConnectionString, logFilePath, applicationName, userID, defaultColorFilePath, rgbColorFilePath); - } - } - - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorChooserDialogDataMgr.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorChooserDialogDataMgr.java deleted file mode 100644 index dd973ee728..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorChooserDialogDataMgr.java +++ /dev/null @@ -1,610 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.TreeSet; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.ColorNameRecord; -import ohd.hseb.ihfsdb.generated.ColorNameTable; -import ohd.hseb.ihfsdb.generated.ColorValueRecord; -import ohd.hseb.ihfsdb.generated.ColorValueTable; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.Logger; -import ohd.hseb.util.StringParser; - -public class ColorChooserDialogDataMgr -{ - private Database _db = null; - private Logger _logger = null; - private String _applicationName = null; - private List _defaultColorScaleValueSetList = new ArrayList(); - private List _colorValueTableColorScaleValueSetList = new ArrayList(); - private HashMap _rgbColorMap = new HashMap(); - private HashMap _hardCodedColorUseToDatabaseColorUseMap = new HashMap(); - private String _userID = null; - private String _defaultColorFilePath = null; - private String _rgbColorFilePath = null; - - - public ColorChooserDialogDataMgr( String baseConnectionString, Logger logger, String applicationName, - String defaultColorFilePath, String rgbColorFilePath ) - { - super(); - - _db = new Database(); - _logger = logger; - _applicationName = applicationName; - _defaultColorFilePath = defaultColorFilePath; - _rgbColorFilePath = rgbColorFilePath; - - _db.connectWithDriverSearch( baseConnectionString ); - - readRGBTextFile(); - readHydroViewDefaultColorFile(); - readColorValuesFromDatabase(); -// testRgbTextVersusColorNameTable(); - } - public String getHardCodedColorUse( String colorUse ) - { - return (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorUse ); - } - - public void disconnect() - { - _db.disconnect(); - } - - // ------------------------------------------------------------------------ - public void finalize() - { - disconnect(); - } - - public void readColorValuesFromDatabase() - { - ColorValueTable table = new ColorValueTable( _db ); - ColorValue colorValue = new ColorValue(); - int i = 0; -/* - String whereClause = "WHERE application_name='" + _applicationName + "' AND userid != 'default' " + - "AND userid != 'factory_default' ORDER BY color_use_name, userid, duration, " + - "threshold_value"; -*/ - String whereClause = "WHERE application_name='" + _applicationName + "' AND userid != 'factory_default' " + - "ORDER BY color_use_name, userid, duration, threshold_value"; - - List colorValueRecordsList = null; - ColorScaleValueSet colorScaleValueSet = new ColorScaleValueSet(); - ColorSet colorSet = null; -// Color colorObject = null; - ScaleValueSet scaleValueSet = null; -// double scaleValue = 0; - String currentIndexString = null, prevIndexString = null; - CodeTimer timer = new CodeTimer(); - timer.start(); - CodeTimer timer2 = new CodeTimer(); - String colorUseString = null; - - try - { - colorValueRecordsList = table.select( whereClause ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - - timer.stop( "Finished reading the ColorValue table in " ); - timer2.start(); - - for ( i = 0; i < colorValueRecordsList.size(); i++ ) - { - colorValue = getColorValueFromColorValueRecord( (ColorValueRecord) colorValueRecordsList.get( i ) ); - if ( i == 0 ) - { - prevIndexString = getColorValueKeyString( colorValue ); - scaleValueSet = new ScaleValueSet(); - colorSet = new ColorSet(); - scaleValueSet.addScaleValue( colorValue.getThresholdValue() ); - colorSet.addNamedColor( getNamedColorByName( colorValue.getColorName() ) ); - - colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorValue.getColorUseName() ); - if ( colorUseString != null ) - { - colorScaleValueSet.setColorUseString( colorUseString ); - } - else - { - colorScaleValueSet.setColorUseString( colorValue.getColorUseName() ); - } - - colorScaleValueSet.setDuration( colorValue.getDuration() ); - colorScaleValueSet.setUserID( colorValue.getUserID() ); - } - else if ( i == ( colorValueRecordsList.size() - 1 ) ) // Last entry in the records list - { - scaleValueSet.addScaleValue( colorValue.getThresholdValue() ); - colorSet.addNamedColor( getNamedColorByName( colorValue.getColorName() ) ); - colorScaleValueSet.setColorSet( colorSet ); - colorScaleValueSet.setScaleValueSet( scaleValueSet ); - _colorValueTableColorScaleValueSetList.add( colorScaleValueSet ); - } - else - { - currentIndexString = getColorValueKeyString( colorValue ); - if ( currentIndexString.equalsIgnoreCase( prevIndexString ) ) // same index - { - scaleValueSet.addScaleValue( colorValue.getThresholdValue() ); - colorSet.addNamedColor( getNamedColorByName( colorValue.getColorName() ) ); - } - else // new index - { - colorScaleValueSet.setColorSet( colorSet ); - colorScaleValueSet.setScaleValueSet( scaleValueSet ); - _colorValueTableColorScaleValueSetList.add( colorScaleValueSet ); - prevIndexString = currentIndexString; - scaleValueSet = new ScaleValueSet(); - colorSet = new ColorSet(); - colorScaleValueSet = new ColorScaleValueSet(); - scaleValueSet.addScaleValue( colorValue.getThresholdValue() ); - colorSet.addNamedColor( getNamedColorByName( colorValue.getColorName() ) ); - colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorValue.getColorUseName() ); - if ( colorUseString != null ) - { - colorScaleValueSet.setColorUseString( colorUseString ); - } - else - { - colorScaleValueSet.setColorUseString( colorValue.getColorUseName() ); - } - colorScaleValueSet.setDuration( colorValue.getDuration() ); - colorScaleValueSet.setUserID( colorValue.getUserID() ); - } - } - } - timer2.stop( "Finished processing the ColorValue table in " ); - } - - - private NamedColor getNamedColorByName( String colorName ) - { - NamedColor namedColor = (NamedColor) getRGBColorMap().get( colorName ); - - return namedColor; - } - - private String getColorValueKeyString( ColorValue colorValue ) - { - return colorValue.getUserID() + "|" + colorValue.getColorUseName() + "|" + colorValue.getDuration(); - } - - private ColorValue getColorValueFromColorValueRecord( ColorValueRecord record ) - { - ColorValue colorValue = new ColorValue(); - - colorValue.setApplicationName( record.getApplication_name() ); - colorValue.setColorName( record.getColor_name() ); - colorValue.setColorUseName( record.getColor_use_name() ); - colorValue.setDuration( (double) record.getDuration() / (double) 3600 ); - colorValue.setThresholdUnit( record.getThreshold_unit() ); - colorValue.setThresholdValue( record.getThreshold_value() ); - colorValue.setUserID( record.getUserid() ); - - return colorValue; - } - - private void saveColorScaleValueSet( List colorValueRecordList, String userID, String colorUseString, double duration ) - { - ColorValueTable table = new ColorValueTable( _db ); - - int durationSecondsInt = (int) ( duration*3600 ); - - String whereClause = "WHERE userID='" + userID + "' AND application_name='" + _applicationName + "' AND " + - "color_use_name='" + colorUseString + "' AND duration=" + durationSecondsInt; - - System.out.println( whereClause ); - - try - { - table.delete( whereClause ); - for ( int i = 0; i < colorValueRecordList.size(); i++ ) - { - ColorValueRecord record = (ColorValueRecord) colorValueRecordList.get( i ); - table.insert( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - - resetHvDefaultColorList(); - resetColorValueTableColorScaleValueSetList(); - } - - public void saveAsOffice( ColorScaleValueSet colorScaleValueSet ) - { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( colorScaleValueSet, "default" ); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorScaleValueSet.getColorUseString() ); - if ( colorUseString == null ) //Checking to see if the color Use is in the hash map. If not, use the original name. - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - saveColorScaleValueSet( colorValueRecordList, "default", colorUseString, colorScaleValueSet.getDuration() ); - } - - public void saveAsUser( ColorScaleValueSet colorScaleValueSet, double duration ) - { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( - colorScaleValueSet, _userID); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorScaleValueSet.getColorUseString() ); - if ( colorUseString == null ) //Checking to see if the color Use is in the hash map. If not, use the original name. - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - saveColorScaleValueSet( colorValueRecordList, _userID, colorUseString, duration ); - } - - public void deleteAsUser( ColorScaleValueSet colorScaleValueSet ) - { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( colorScaleValueSet, _userID ); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorScaleValueSet.getColorUseString() ); - - if ( colorUseString == null ) - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - deleteColorScaleValueSet( colorValueRecordList, _userID, colorUseString, colorScaleValueSet.getDuration() ); - } - - public void deleteAsOffice( ColorScaleValueSet colorScaleValueSet ) - { - List colorValueRecordList = getColorValueRecordListFromColorScaleValueSet( colorScaleValueSet, "default" ); - - String colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorScaleValueSet.getColorUseString() ); - - if ( colorUseString == null ) - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - deleteColorScaleValueSet( colorValueRecordList, "default", colorUseString, colorScaleValueSet.getDuration() ); - } - - private void deleteColorScaleValueSet( List colorValueRecordList, String userID, String colorUseString, double duration ) - { - ColorValueTable table = new ColorValueTable( _db ); - - String whereClause = "WHERE userID='" + userID + "' AND application_name='" + _applicationName + "' AND " + - "color_use_name='" + colorUseString + "' AND duration=" + duration*3600; - - try - { - table.delete( whereClause ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - - resetHvDefaultColorList(); - resetColorValueTableColorScaleValueSetList(); - } - - private List getColorValueRecordListFromColorScaleValueSet( ColorScaleValueSet colorScaleValueSet, String userID ) - { - List colorValueRecordList = new ArrayList(); - - ColorValueRecord record = new ColorValueRecord(); - ColorSet colorSet = colorScaleValueSet.getColorSet(); - List colorSetList = colorSet.getNamedColorList(); - List scaleValueSetList = colorScaleValueSet.getScaleValueSet().getScaleValueSet(); - String colorUseString = null; - - record.setApplication_name( _applicationName ); - colorUseString = (String) _hardCodedColorUseToDatabaseColorUseMap.get( colorScaleValueSet.getColorUseString() ); - if ( colorUseString == null ) //Checking to see if the color Use is in the hash map. If not, use the original name. - { - colorUseString = colorScaleValueSet.getColorUseString(); - } - - record.setColor_use_name( colorUseString ); - record.setDuration( (int) ( colorScaleValueSet.getDuration() * 3600 ) ); - record.setUserid( userID ); - record.setThreshold_unit( "E" ); - - for ( int i = 0; i < scaleValueSetList.size(); i++ ) - { - double scaleValue = (Double) scaleValueSetList.get( i ); - NamedColor namedColor = (NamedColor) colorSetList.get( i ); - - record.setThreshold_value( scaleValue ); - record.setColor_name( namedColor.getName() ); - - colorValueRecordList.add( record ); - record = new ColorValueRecord( record ); - } - return colorValueRecordList; - } - - - public void setUserID( String userID ) - { - _userID = userID; - } - - private Set getColorNameTableSet() - { - Set colorNameSet = new HashSet(); - ColorNameTable table = new ColorNameTable( _db ); - - try - { - List recordList = table.select( "" ); - for ( ColorNameRecord record : recordList ) - { - colorNameSet.add( record.getColor_name() ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - - - return colorNameSet; - } - - public void readRGBTextFile() - { - File rgbColorFile = null; - BufferedReader reader = null; - String line = null; - String[] tokenizedString = null; - String colorName = null; - Set nameFromColorNameTableSet = getColorNameTableSet(); - rgbColorFile = new File( _rgbColorFilePath ); - - try - { - reader = new BufferedReader( new FileReader( rgbColorFile ) ); - line = reader.readLine(); //discard the first line - line = reader.readLine(); - while ( line != null ) - { - tokenizedString = StringParser.tokenize( line ); - colorName = getRGBColorName( tokenizedString ); - -// if the read in RGB color name exists in the ColorName table, then add to the _rgbColorMap - if ( nameFromColorNameTableSet.contains( colorName.toUpperCase() ) ) - { - NamedColor namedColor = new NamedColor( colorName, Integer.parseInt( tokenizedString[ 0 ] ), - Integer.parseInt( tokenizedString[ 1 ] ), - Integer.parseInt( tokenizedString[ 2 ] ) ); - - - _rgbColorMap.put( colorName.toUpperCase(), namedColor ); - } - line = reader.readLine(); - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - - - private String getRGBColorName( String[] tokenizedName ) - { - StringBuffer rgbColorName = new StringBuffer(); - - for ( int i = 3; i < tokenizedName.length;i++ ) - { - rgbColorName.append( tokenizedName[ i ] ); - - if ( i != ( tokenizedName.length - 1 ) ) - { - rgbColorName.append( " " ); - } - } - - return rgbColorName.toString(); - } - - public void readHydroViewDefaultColorFile() - { -// String hydroviewDefaultColorFileName = null; - AppsDefaults appsDefaults = new AppsDefaults(); - File hydroviewDefaultColorFile = null; - BufferedReader reader = null; - String line = null; - String colorSetString = null; - String colorUseString = null; - String colorString = null; - String databaseColorUseString = null; - float scaleValue = 0; - NamedColor namedColor = null; - String[] tokenizedString = null; - - ColorScaleValueSet colorScaleValueSet = null; - ColorSet colorSet = new ColorSet(); - ScaleValueSet scaleValueSet = new ScaleValueSet(); - - hydroviewDefaultColorFile = new File( _defaultColorFilePath ); - - try - { - reader = new BufferedReader( new FileReader( hydroviewDefaultColorFile ) ); - line = reader.readLine(); - while ( line != null ) - { - if ( line.trim().length() > 0 ) // not an empty line - { - tokenizedString = StringParser.tokenize( line ); - if ( line.indexOf( "|" ) == -1 ) - { - colorString = tokenizedString [ 0 ]; - namedColor = getNamedColorByName( colorString ); - scaleValue = Float.valueOf( tokenizedString [ 1 ] ); - colorSet.addNamedColor( namedColor ); - scaleValueSet.addScaleValue( scaleValue ); - - } - else //line read in is the color set name (first line of each set) - { - colorScaleValueSet = new ColorScaleValueSet(); - - StringTokenizer tokenizer = new StringTokenizer( line, "|" ); - - colorUseString = tokenizer.nextToken(); - databaseColorUseString = tokenizer.nextToken(); - - insertColorUseStringIntoHashMap( colorUseString, databaseColorUseString ); - - colorScaleValueSet.setColorUseString( colorUseString ); - } - } - else //empty line - { - colorScaleValueSet.setColorSet( colorSet ); - colorScaleValueSet.setScaleValueSet( scaleValueSet ); - colorScaleValueSet.setUserID( "HARDCODED" ); - colorScaleValueSet.setDuration( 0 ); - _defaultColorScaleValueSetList.add( colorScaleValueSet ); - colorSet = new ColorSet(); - scaleValueSet = new ScaleValueSet(); - } - line = reader.readLine(); - } - } - catch( IOException e ) - { - e.printStackTrace(); - } - } - - private void testRgbTextVersusColorNameTable() - { - ColorNameTable table = new ColorNameTable( _db ); - List extraCrapList = new ArrayList(); - Set rgbHashSet = new TreeSet( _rgbColorMap.keySet() ); - List rgbList = new ArrayList( _rgbColorMap.keySet() ); - String colorName = null; - - try - { - List recordList = table.select( "" ); - Set recordSet = new TreeSet(); - - for ( int i = 0; i < recordList.size(); i++ ) - { - ColorNameRecord record = (ColorNameRecord) recordList.get( i ); - colorName = record.getColor_name(); - recordSet.add( getStringWithoutSpaces( colorName ) ); - if ( ! rgbHashSet.contains( colorName ) ) - { - extraCrapList.add( colorName ); - System.out.println( colorName + " is not in the RGB text file but is in the database" ); - } - } - - - for ( int i = 0; i < rgbList.size(); i++ ) - { - String rgbColorName = getStringWithoutSpaces( (String) rgbList.get( i ) ); - if ( ! recordSet.contains( rgbColorName ) ) - { - extraCrapList.add( rgbColorName ); - System.out.println( rgbColorName + " is not in the database but is in the RGB text file" ); - } - } - - - System.out.println( "DONE" ); - - } - catch (SQLException e) - { - e.printStackTrace(); - } - } - - private String getStringWithoutSpaces( String colorName ) - { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < colorName.length() ; i++) - { - char c = colorName.charAt(i); - if (c != ' ') - { - buffer.append(c); - } - } - - return buffer.toString(); - } - private void insertColorUseStringIntoHashMap( String colorUseString, String databaseColorUseString ) - { - _hardCodedColorUseToDatabaseColorUseMap.put( colorUseString, databaseColorUseString ); - _hardCodedColorUseToDatabaseColorUseMap.put( databaseColorUseString, colorUseString ); - } - - public List getDefaultColorScaleValueSetList() - { - return _defaultColorScaleValueSetList; - } - - public void setApplicationName(String _applicationName) { - this._applicationName = _applicationName; - } - - public String getApplicationName() { - return _applicationName; - } - - public List getColorValueTableColorScaleValueSetList() - { - return _colorValueTableColorScaleValueSetList; - } - - public void addColorScaleValueSetToColorValueTableList( ColorScaleValueSet colorScaleValueSet ) - { - _colorValueTableColorScaleValueSetList.add( colorScaleValueSet ); - } - - public void resetColorValueTableColorScaleValueSetList() - { - _colorValueTableColorScaleValueSetList = new ArrayList(); - readColorValuesFromDatabase(); - } - - public void resetHvDefaultColorList() - { - _defaultColorScaleValueSetList = new ArrayList(); - readHydroViewDefaultColorFile(); - } - - public HashMap getRGBColorMap() - { - return _rgbColorMap; - } -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorHolder.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorHolder.java deleted file mode 100644 index 2cb7f967f1..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorHolder.java +++ /dev/null @@ -1,25 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; - -public class ColorHolder -{ - private Color _color = null; - - public ColorHolder( Color color ) - { - setColor(color); - } - - public void setColor(Color color) - { - _color = color; - } - - public Color getColor() - { - return _color; - } - - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorPickerDialog.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorPickerDialog.java deleted file mode 100644 index cea5ddb44a..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorPickerDialog.java +++ /dev/null @@ -1,188 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JDialog; -import javax.swing.JPanel; - -import ohd.hseb.util.gui.ComponentHelper; - -public class ColorPickerDialog extends JDialog -{ - private ColorHolder _colorHolder = null; -// private ColorSet _colorSet = null; -// private int _indexValueOfDefaultColor = 0; - private Container _frameContentPane = getContentPane(); - private JPanel _colorDialogPanel = new JPanel(); - private JColorChooser _jColorChooserDialog = new JColorChooser(); - - private JPanel _buttonPanel = new JPanel(); - private JButton _okButton = new JButton( "OK" ); - private JButton _cancelButton = new JButton( "Cancel" ); - - -/* - public ColorPickerDialog( Frame owner, Color color, ColorSet colorSet ) - { - super( owner, "Color Picker", true ); - - _frameContentPane.setLayout( new GridBagLayout() ); - _colorDialogPanel.setLayout( new GridBagLayout() ); - - _jColorChooserDialog.setColor( color ); - - ComponentHelper.addFrameComponent( _frameContentPane, _colorDialogPanel, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _colorDialogPanel, _jColorChooserDialog, 1, 1, 1, 1, GridBagConstraints.BOTH ); - setSize( 400, 600 ); - - } -*/ -/* - public ColorPickerDialog( JDialog owner, Color color, ColorSet colorSet ) - { - super( owner, "Color Picker", true ); - _colorSet = colorSet; - _defaultColor = color; - initGUI(); - _indexValueOfDefaultColor = getIndexOfDefaultColorFromColorSet(); - - addListeners(); - } -*/ - public ColorPickerDialog( JDialog owner, ColorHolder colorHolder ) - { - super( owner, "Color Picker", true ); - _colorHolder = colorHolder; - initGUI(); -// _indexValueOfDefaultColor = getIndexOfDefaultColorFromColorSet(); - - addListeners(); - } - - - private void initGUI() - { - _frameContentPane.setLayout( new GridBagLayout() ); - _colorDialogPanel.setLayout( new GridBagLayout() ); - _buttonPanel.setLayout( new GridBagLayout() ); - - _jColorChooserDialog.setColor( _colorHolder.getColor() ); - - setSize( 430, 400 ); - _buttonPanel.setPreferredSize( new Dimension( 30, 40 ) ); -// X, Y, #Col, #Row - - ComponentHelper.addFrameComponent( _frameContentPane, _colorDialogPanel, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 1, 2, 1, 3, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _colorDialogPanel, _jColorChooserDialog, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _okButton, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _cancelButton, 2, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _okButton.addActionListener( new OkButtonListener() ); - _cancelButton.addActionListener( windowCloser ); - - - } - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - -/* - private int getIndexOfDefaultColorFromColorSet() - { - List colorList = _colorSet.getNamedColorList(); - Color extractedColor = null; - int index = -1; - - for ( int i = 0; i < colorList.size(); i++ ) - { - extractedColor = (Color) colorList.get( i ); - if ( extractedColor.equals( _defaultColor ) ) - { - index = i; - } - } - - return index; - } -*/ - - private class OkButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _colorHolder.setColor( _jColorChooserDialog.getColor() ); -// ColorPickerDialog.this.setVisible( false ); - closeWindow(); - } - } - - /* - private class OkButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - List colorSetList = _colorSet.getNamedColorList(); - Color colorObject = null; - - colorSetList.set( _indexValueOfDefaultColor, _jColorChooserDialog.getColor() ); - - closeWindow(); - } - } - - - private class OkButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - List colorSetList = _colorSet.getNamedColorList(); - Color colorObject = null; - - colorSetList.set( _indexValueOfDefaultColor, _jColorChooserDialog.getColor() ); - - closeWindow(); - } - } -*/ - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - - public static void main ( String[] args ) - { -// ColorPickerDialog colorPicker = new ColorPickerDialog( new Frame(), Color.blue, true ); -// colorPicker.setVisible( true ); - } - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorScaleValueSet.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorScaleValueSet.java deleted file mode 100644 index 350a190d97..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorScaleValueSet.java +++ /dev/null @@ -1,100 +0,0 @@ -package ohd.hseb.color_chooser; - -public class ColorScaleValueSet -{ - private ColorSet _colorSet = null; - private ScaleValueSet _scaleValueSet = null; - private String _colorUseString = null; - private double _duration = -99999; - private String _userID = null; - - - public ColorScaleValueSet() - { - } - - public ColorScaleValueSet( ColorScaleValueSet colorScaleValueSet ) - { - setColorSet( new ColorSet( colorScaleValueSet.getColorSet() ) ); - setScaleValueSet( new ScaleValueSet( colorScaleValueSet.getScaleValueSet() ) ); - setColorUseString( new String( colorScaleValueSet.getColorUseString() ) ); - setUserID( new String( colorScaleValueSet.getUserID() ) ); - setDuration( colorScaleValueSet.getDuration() ); -/* - setColorSet( colorScaleValueSet.getColorSet() ); - setScaleValueSet( colorScaleValueSet.getScaleValueSet() ); - setColorUseString( colorScaleValueSet.getColorUseString() ); - setUserID( colorScaleValueSet.getUserID() ); - setDuration( colorScaleValueSet.getDuration() ); - */ - } - - public static ColorScaleValueSet getCopyOfColorScaleValueSet( ColorScaleValueSet colorScaleValueSet ) - { - ColorScaleValueSet returnColorScaleValueSet = new ColorScaleValueSet(); - - returnColorScaleValueSet.setColorSet( new ColorSet( colorScaleValueSet.getColorSet() ) ); - returnColorScaleValueSet.setScaleValueSet( new ScaleValueSet( colorScaleValueSet.getScaleValueSet() ) ); - returnColorScaleValueSet.setColorUseString( new String( colorScaleValueSet.getColorUseString() ) ); - returnColorScaleValueSet.setUserID( new String( colorScaleValueSet.getUserID() ) ); - returnColorScaleValueSet.setDuration( colorScaleValueSet.getDuration() ); - - return returnColorScaleValueSet; - } - - public String toString() - { - return _userID + " " + _colorUseString + " " + _duration + "\n" + _colorSet; - } - - public void setColorSet( ColorSet colorSet ) - { - _colorSet = colorSet; - } - - public ColorSet getColorSet() - { - return _colorSet; - } - - public void setScaleValueSet(ScaleValueSet scaleValueSet) - { - _scaleValueSet = scaleValueSet; - } - - public ScaleValueSet getScaleValueSet() - { - return _scaleValueSet; - } - - public void setColorUseString(String colorUseString) - { - _colorUseString = colorUseString; - } - - public String getColorUseString() - { - return _colorUseString; - } - - public void setDuration( double duration ) - { - _duration = duration; - } - - public double getDuration() - { - return _duration; - } - - public void setUserID( String userID ) - { - _userID = userID; - } - - public String getUserID() - { - return _userID; - } - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorSet.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorSet.java deleted file mode 100644 index 724c0b74df..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorSet.java +++ /dev/null @@ -1,72 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - -public class ColorSet -{ - - private List _namedColorList = new ArrayList(); // List of NamedColor objects - - public ColorSet() - { - } - - public ColorSet( ColorSet colorSet ) - { - List namedColorList = colorSet.getNamedColorList(); - - for ( int i = 0; i < namedColorList.size(); i++ ) - { - NamedColor extractedNamedColor = (NamedColor) namedColorList.get( i ); - if ( extractedNamedColor != null ) - { - _namedColorList.add( new NamedColor( extractedNamedColor ) ); - } - } - } - - public ColorSet( List namedColorList ) - { - _namedColorList = namedColorList; - } - - public void addNamedColor( Color colorObject ) - { - _namedColorList.add( colorObject ); - } - - public void addNamedColorAtIndex( Color colorObject, int index ) - { - _namedColorList.add( index, colorObject ); - } - - public void deleteNamedColorAtIndex( int index ) - { - _namedColorList.remove( index ); - } - - public void replaceNamedColorAtIndex( Color colorObject, int index ) - { - _namedColorList.remove( index ); - _namedColorList.add( index, colorObject ); - } - - public String toString() - { - StringBuffer returnString = new StringBuffer(); - for ( int i = 0; i < _namedColorList.size(); i++ ) - { - NamedColor namedColor = (NamedColor) _namedColorList.get( i ); - returnString.append( namedColor + "\n" ); - } - - return returnString.toString(); - } - - public List getNamedColorList() - { - return _namedColorList; - } -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorValue.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorValue.java deleted file mode 100644 index 5f6a45fe5e..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ColorValue.java +++ /dev/null @@ -1,87 +0,0 @@ -package ohd.hseb.color_chooser; - -public class ColorValue -{ - private String _userID; - private String _applicationName; - private String _colorUseName; - private double _duration; - private double _thresholdValue; - private String _thresholdUnit; - private String _colorName; - - public void setUserID( String userID ) - { - _userID = userID; - } - - public String getUserID() - { - return _userID; - } - - public void setApplicationName( String applicationName ) - { - _applicationName = applicationName; - } - - public String getApplicationName() - { - return _applicationName; - } - - public void setColorUseName( String colorUseName ) - { - _colorUseName = colorUseName; - } - - public String getColorUseName() - { - return _colorUseName; - } - - public void setDuration( double duration ) - { - _duration = duration; - } - - public double getDuration() - { - return _duration; - } - - public void setThresholdValue( double thresholdValue ) - { - _thresholdValue = thresholdValue; - } - - public double getThresholdValue() - { - return _thresholdValue; - } - - public void setThresholdUnit( String thresholdUnit ) - { - _thresholdUnit = thresholdUnit; - } - - public String getThresholdUnit() - { - return _thresholdUnit; - } - - public void setColorName( String colorName ) - { - _colorName = colorName; - } - - public String getColorName() - { - return _colorName; - } - - public String toString() - { - return _userID + " " + _colorUseName + " " + _duration + " " + _thresholdValue + " " + _colorName; - } -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/NamedColor.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/NamedColor.java deleted file mode 100644 index 6bc74c96ee..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/NamedColor.java +++ /dev/null @@ -1,48 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; - -import ohd.hseb.util.StringParser; - -public class NamedColor extends Color -{ - private String _name = null; - - public NamedColor( String name, int redValue, int greenValue, int blueValue ) - { - super( redValue, greenValue, blueValue ); - String[] tokenizedString = StringParser.tokenize( name ); - StringBuffer nameBuffer = new StringBuffer(); - for ( int i = 0; i < tokenizedString.length; i++ ) - { - nameBuffer.append( tokenizedString[ i ] ); - } - setName( nameBuffer.toString().toUpperCase() ); - } - - public NamedColor( String name, Color color ) - { - this( name, color.getRed(), color.getGreen(), color.getBlue() ); - } - - public NamedColor( NamedColor namedColor ) - { - this( namedColor.getName(), namedColor ); - } - - public String toString() - { - return _name + " " + super.toString(); - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/NamedColorMatcher.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/NamedColorMatcher.java deleted file mode 100644 index b534d90e9c..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/NamedColorMatcher.java +++ /dev/null @@ -1,94 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class NamedColorMatcher -{ - List _namedColorList = null; - - public NamedColorMatcher(Map nameToNamedColorMap) - { - _namedColorList = new ArrayList( nameToNamedColorMap.values()); - } - - public NamedColor getClosestNamedColor(Color color) - { - NamedColor bestNamedColor = null; - Set specialWhiteNameSet = new HashSet(); - Set specialBlackNameSet = new HashSet(); - specialWhiteNameSet.add("GRAY100"); - specialBlackNameSet.add("GRAY0"); - - List colorList = _namedColorList; - - for (NamedColor namedColor : colorList) - // for (int i = 0; i < _namedColorList.size(); i++) - { - // NamedColor namedColor = (NamedColor) _namedColorList.get(i); - - if (isCloserColor(color, namedColor, bestNamedColor)) - { - bestNamedColor = namedColor; - } - } - -// System.out.println("Desired Color was " + color); -// System.out.println("Found Named Color was " + bestNamedColor); - if ( bestNamedColor != null ) - { - String bestNamedColorString = bestNamedColor.getName().toUpperCase(); - if ( specialWhiteNameSet.contains( bestNamedColorString ) ) - { - bestNamedColor = new NamedColor( "WHITE", bestNamedColor ); - } - else if ( specialBlackNameSet.contains( bestNamedColorString ) ) - { - bestNamedColor = new NamedColor( "BLACK", bestNamedColor ); - } - } - return bestNamedColor; - } - - // -------------------------------------------------------------------------------------------------------- - private boolean isCloserColor(Color color, NamedColor testNamedColor, NamedColor bestNamedColor) - { - boolean isCloser = false; - - if ( (testNamedColor != null) && (bestNamedColor != null) ) - { - double distanceFromTestNamedColor = getDistance(color, testNamedColor); - double distanceFromBestNamedColor = getDistance(color, bestNamedColor); - - if (distanceFromTestNamedColor < distanceFromBestNamedColor) - { - isCloser = true; - } - } - else if ((bestNamedColor == null) && (testNamedColor != null) ) - { - isCloser = true; - } - return isCloser; - } - // -------------------------------------------------------------------------------------------------------- - private double getDistance(Color color, NamedColor namedColor) - { - double distance = 0.0; - - int redDiff = color.getRed() - namedColor.getRed(); - int greenDiff = color.getGreen() - namedColor.getGreen(); - int blueDiff = color.getBlue() - namedColor.getBlue(); - - //intentionally not taking the square root - Chip - distance = (redDiff * redDiff) + (greenDiff * greenDiff) + (blueDiff * blueDiff); - - return distance; - } - - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ScaleValueSet.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ScaleValueSet.java deleted file mode 100644 index 8f7d4d9167..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/color_chooser/ScaleValueSet.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.color_chooser; - -import java.util.ArrayList; -import java.util.List; - -public class ScaleValueSet -{ - private List _scaleValueSet = new ArrayList(); - - public ScaleValueSet() - { - } - - public ScaleValueSet( List scaleValueSet ) - { - setScaleValueSet( scaleValueSet ); - } - - public ScaleValueSet( ScaleValueSet scaleValueSet ) - { - List scaleValueSetList = scaleValueSet.getScaleValueSet(); - - for ( int i = 0; i < scaleValueSetList.size(); i++ ) - { - _scaleValueSet.add( scaleValueSetList.get( i ) ); - } - } - - public void addScaleValue( double value ) - { - _scaleValueSet.add( value ); - } - - public void addScaleValueAtIndex( double value, int index ) - { - _scaleValueSet.add( index, value ); - } - - public void replaceScaleValueAtIndex( double value, int index ) - { - _scaleValueSet.remove( index ); - _scaleValueSet.add( index, value ); - } - - public void deleteScaleValueAtIndex( int index ) - { - _scaleValueSet.remove( index ); - } - - public void setScaleValueSet( List scaleValueSet ) - { - _scaleValueSet = scaleValueSet; - } - - public List getScaleValueSet() - { - return _scaleValueSet; - } -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpCurPrevVtec.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpCurPrevVtec.java deleted file mode 100644 index 9f4dbf4019..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpCurPrevVtec.java +++ /dev/null @@ -1,467 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.util.ArrayList; - -public class FpCurPrevVtec -{ - private String _locId; - private String _locName; - private String _locStream; - private String _locPe; - private double _floodStg; - private double _floodFlow; - private long _obsBeginTime; - private long _fcstEndTime; - private double _adjustendhrs; - private String _curAction; - private String _curPhenom; - private String _curSignif; - private String _curSeverity; - private String _curCause; - private String _curRecord; - private int _curEtn; - private double _curCrestValue; - private long _curBeginTime; - private long _curEndTime; - private long _curRiseTime; - private long _curCrestTime; - private long _curFallTime; - private String _prevAction; - private String _prevPhenom; - private String _prevSignif; - private String _prevSeverity; - private String _prevCause; - private String _prevRecord; - private int _prevEtn; - private double _prevCrestValue; - private String _prevRiseType; - private String _prevCrestType; - private String _prevFallType; - private long _prevBeginTime; - private long _prevEndTime; - private long _prevRiseTime; - private long _prevCrestTime; - private long _prevFallTime; - private long _prevProductTime; - private ArrayList _obsValuetTimeList; - private ArrayList _fcstValueTimeList; - - public FpCurPrevVtec() - { - - } - - public String getLocId() - { - return _locId; - } - - public void setLocId(String locId) - { - _locId = locId; - } - public String getLocName() - { - return _locName; - } - - public void setLocName(String locName) - { - _locName = locName; - } - - public String getLocStream() - { - return _locStream; - } - - public void setLocStream(String locStream) - { - _locStream = locStream; - } - - public String getLocPe() - { - return _locPe; - } - - public void setLocPe(String locPe) - { - _locPe = locPe; - } - - public double getFloodStg() - { - return _floodStg; - } - - public void setFloodStg(double floodStg) - { - _floodStg = floodStg; - } - - public double getFloodFlow() - { - return _floodFlow; - } - - public void setFloodFlow(double floodFlow) - { - _floodFlow = floodFlow; - } - - public long getObsBeginTime() - { - return _obsBeginTime; - } - - public void setObsBeginTime(long obsBeginTime) - { - _obsBeginTime = obsBeginTime; - } - - public long getFcstEndTime() - { - return _fcstEndTime; - } - - public void setFcstEndTime(long fcstEndTime) - { - _fcstEndTime = fcstEndTime; - } - - public double getAdjustEndhrs() - { - return _adjustendhrs; - } - - public void setAdjustEndhrs(double adjustendhrs) - { - _adjustendhrs = adjustendhrs; - } - - public String getcurAction() - { - return _curAction; - } - - public void setcurAction(String curAction) - { - _curAction = curAction; - } - - public String getcurPhenom() - { - return _curPhenom; - } - - public void setcurPhenom(String curPhenom) - { - _curPhenom = curPhenom; - } - - public String getcurSignif() - { - return _curSignif; - } - - public void setcurSignif(String curSignif) - { - _curSignif = curSignif; - } - - public String getcurSeverity() - { - return _curSeverity; - } - - public void setcurSeverity(String curSeverity) - { - _curSeverity = curSeverity; - } - - public String getcurCause() - { - return _curCause; - } - - public void setcurCause(String curCause) - { - _curCause = curCause; - } - - public String getcurRecord() - { - return _curRecord; - } - - public void setcurRecord(String curRecord) - { - _curRecord = curRecord; - } - - public int getcurEtn() - { - return _curEtn; - } - - public void setcurEtn(int curEtn) - { - _curEtn = curEtn; - } - - public double getcurCrestValue() - { - return _curCrestValue; - } - - public void setcurCrestValue(double curCrestValue) - { - _curCrestValue = curCrestValue; - } - - public long getcurBeginTime() - { - return _curBeginTime; - } - - public void setcurBeginTime(long curBeginTime) - { - _curBeginTime = curBeginTime; - } - - public long getcurEndTime() - { - return _curEndTime; - } - - public void setcurEndTime(long curEndTime) - { - _curEndTime = curEndTime; - } - - public long getcurRiseTime() - { - return _curRiseTime; - } - - public void setcurRiseTime(long curRiseTime) - { - _curRiseTime = curRiseTime; - } - - public long getcurCrestTime() - { - return _curCrestTime; - } - - public void setcurCrestTime(long curCrestTime) - { - _curCrestTime = curCrestTime; - } - - public long getcurFallTime() - { - return _curFallTime; - } - - public void setcurFallTime(long curFallTime) - { - _curFallTime = curFallTime; - } - - - public String getprevAction() - { - return _prevAction; - } - - public void setprevAction(String prevAction) - { - _prevAction = prevAction; - } - - public String getprevPhenom() - { - return _prevPhenom; - } - - public void setprevPhenom(String prevPhenom) - { - _prevPhenom = prevPhenom; - } - - public String getprevSignif() - { - return _prevSignif; - } - - public void setprevSignif(String prevSignif) - { - _prevSignif = prevSignif; - } - - public String getprevSeverity() - { - return _prevSeverity; - } - - public void setprevSeverity(String prevSeverity) - { - _prevSeverity = prevSeverity; - } - - public String getprevCause() - { - return _prevCause; - } - - public void setprevCause(String prevCause) - { - _prevCause = prevCause; - } - - public String getprevRecord() - { - return _prevRecord; - } - - public void setprevRecord(String prevRecord) - { - _prevRecord = prevRecord; - } - - public int getprevEtn() - { - return _prevEtn; - } - - public void setprevEtn(int prevEtn) - { - _prevEtn = prevEtn; - } - - public double getprevCrestValue() - { - return _prevCrestValue; - } - - public void setprevCrestValue(double prevCrestValue) - { - _prevCrestValue = prevCrestValue; - } - - public String getprevRiseType() - { - return _prevRiseType; - } - - public void setprevRiseType(String prevRiseType) - { - _prevRiseType = prevRiseType; - } - - public String getprevCrestType() - { - return _prevCrestType; - } - - public void setprevCrestType(String prevCrestType) - { - _prevCrestType = prevCrestType; - } - - public String getprevFallType() - { - return _prevFallType; - } - - public void setprevFallType(String prevFallType) - { - _prevFallType = prevFallType; - } - - public long getprevBeginTime() - { - return _prevBeginTime; - } - - public void setprevBeginTime(long prevBeginTime) - { - _prevBeginTime = prevBeginTime; - } - - public long getprevEndTime() - { - return _prevEndTime; - } - - public void setprevEndTime(long prevEndTime) - { - _prevEndTime = prevEndTime; - } - - public long getprevRiseTime() - { - return _prevRiseTime; - } - - public void setprevRiseTime(long prevRiseTime) - { - _prevRiseTime = prevRiseTime; - } - - public long getprevCrestTime() - { - return _prevCrestTime; - } - - public void setprevCrestTime(long prevCrestTime) - { - _prevCrestTime = prevCrestTime; - } - - public long getprevFallTime() - { - return _prevFallTime; - } - - public void setprevFallTime(long prevFallTime) - { - _prevFallTime = prevFallTime; - } - - public long getprevProductTime() - { - return _prevProductTime; - } - - public void setprevProductTime(long prevProductTime) - { - _prevProductTime = prevProductTime; - } - - public String toString() - { - String str = null; - return str; - } - - public ArrayList getObsValuetTimeList() { - return _obsValuetTimeList; - } - - public void setObsValuetTimeList(ArrayList obsValuetTimeList) { - _obsValuetTimeList = obsValuetTimeList; - } - - public ArrayList getFcstValueTimeList() { - return _fcstValueTimeList; - } - - public void setFcstValueTimeList(ArrayList fcstValueTimeList) { - _fcstValueTimeList = fcstValueTimeList; - } - - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfo.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfo.java deleted file mode 100644 index 211fdb8cc0..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfo.java +++ /dev/null @@ -1,1177 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -//import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.FlowToStageValueMapper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; - -import ohd.hseb.timeserieslite.gui.drawing.SignificantLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TsCanvasToolTipListener; -import ohd.hseb.timeserieslite.gui.drawing.TsDataPointPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslCanvasPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslTimeLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TslBackgroundPainter; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.fp_vtec_info.FpCurPrevVtec; -import ohd.hseb.fp_vtec_info.FpVtecInfoFrame; - -public class FpVtecInfo { - private static final long MISSING_INT = -9999; - - private static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - - private static final long MILLIS_PER_SECOND = 1000; - - private static final int TOP_MARGIN = 100; - - private int _defaultHoursBackInTime = 120; - - private int _defaultHoursForwardInTime = 336; - - private FpVtecInfoDataManager _dataMgr = null; - - private String _locationId = null; - - private List _paramCodeList = new ArrayList(); - - private String _jdbcConnectionString = null; - - private FpCurPrevVtec _fpCurPrevVtecRecord = null; - - private PDCDataType _dataType = null; - - private List _dataTypeList = new ArrayList(); - - private long _startTime = 0; - - private long _endTime = 0; - - private int HOURS_TO_ROUND = 6; - - private FpVtecInfoFrame _frame = null; - - private TsPaintableCanvas _canvas = null; - - private TimeHolder _curVtecBeginTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecEndTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecRiseTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecCrestTimeHolder = new TimeHolder(); - - private TimeHolder _curVtecFallTimeHolder = new TimeHolder(); - - private static Map _physicalElementMap = new HashMap(); - static { - _physicalElementMap.put("HG", PDCDataType.HEIGHT); - _physicalElementMap.put("HP", PDCDataType.HEIGHT); - _physicalElementMap.put("HT", PDCDataType.HEIGHT); - _physicalElementMap.put("HM", PDCDataType.HEIGHT); - _physicalElementMap.put("HL", PDCDataType.HEIGHT); - _physicalElementMap.put("HZ", PDCDataType.HEIGHT); - _physicalElementMap.put("HK", PDCDataType.HEIGHT); - _physicalElementMap.put("QR", PDCDataType.DISCHARGE); - _physicalElementMap.put("QT", PDCDataType.DISCHARGE); - _physicalElementMap.put("QS", PDCDataType.DISCHARGE); - _physicalElementMap.put("QA", PDCDataType.DISCHARGE); - _physicalElementMap.put("QM", PDCDataType.DISCHARGE); - - } - - // ------------------------------------------------------------------------------------- - - public static void show(String dbConnString, String locationId, - String paramCodeString1, String paramCodeString2) { - - String[] argStringArray = { dbConnString, locationId, paramCodeString1, - paramCodeString2 }; - - FpVtecInfoFrame.setLastUpdateTime(FpVtecInfoFrame.STILL_OPENED); - - for (int i = 0; i < argStringArray.length; i++) { - System.out.println("argStringArray[" + i + "] = " - + argStringArray[i]); - } - - FpVtecInfo app = new FpVtecInfo(); - app.display(argStringArray, true); - - // need to refresh frame in "Update Graph" and "Save Changes" - app.getFrame().setApplication(app); - - } - - // -------------------------------------------------------------------------------------------------- - - public static void main(String[] argStringArray) { - FpVtecInfo app = new FpVtecInfo(); - app.display(argStringArray, true); - - // need to refresh frame in "Update Graph" and "Save Changes" - app.getFrame().setApplication(app); - - } - - // -------------------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) { - - CodeTimer timer = new CodeTimer(); - System.out - .println("Start to display event's timeseries and VTEC information"); - - // retrive the input arguments - handleCommandLineArgs(argStringArray); - - String header = "FpVtecInfo.display()"; - - // read FP, VTEC information from input file - timer.start(); - _dataMgr.readInputFileFormFpCurPrevVtecInfoMap(); - timer.stop(header + " read input file took"); - - // set the timeseries beginTime and endTime based on backhrs and - // forecasthrs - // store FP/VTEC information to _fpCurPrevVtecRecord for location - // _locationId - - _fpCurPrevVtecRecord = setTSBeginEndTimeWindow(_locationId); - - // prepare the JFrame for display window - if (_frame == null) - _frame = new FpVtecInfoFrame(_fpCurPrevVtecRecord, _dataMgr); - - _frame.setExitOnClose(exitOnClose); - - // get canvas from frame - _canvas = _frame.getCanvas(); - - // determine the stage or flow data type - - if (_dataTypeList.size() > 0) { - _dataType = (PDCDataType) _dataTypeList.get(0); - } - - // draw the canvas - timer.start(); - initializeCanvas(_dataType, _paramCodeList, _canvas); - timer.stop(header + " initializeCanvas() took "); - - timer.start(); - _frame.setVisible(true); - timer.stop(header + "setVisible() took "); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void handleCommandLineArgs(String[] argStringArray) { - String header = "FpVtecInfo.handleCommandLineArgs(): "; - - // includes the optional jdbcConnectionString - if (argStringArray.length > 0) { - _jdbcConnectionString = argStringArray[0]; - _dataMgr = new FpVtecInfoDataManager(_jdbcConnectionString); - System.out.println("_jdbcConnection = " + _jdbcConnectionString); - } - - // location id - if (argStringArray.length > 1) { - _locationId = argStringArray[1]; - System.out.println("_locationId = " + _locationId); - } - - // create param code list and dataType list - for (int i = 2; i < argStringArray.length; i++) { - String paramCodeString = argStringArray[i]; - System.out.println(header + "paramCodeString = " + paramCodeString); - - if ((paramCodeString != null) && (paramCodeString.length() == 6)) // valid - // example - // = - // HRIRGZ - { - ParamCode paramCode = new ParamCode(paramCodeString); - - paramCode = expandParamCode(_locationId, paramCode); - - if (paramCode != null) { - _paramCodeList.add(paramCode); - - // String physicalElement = paramCode.substring(0,2); - PDCDataType dataType = getDataTypeFromPhysicalElement(paramCode - .getPe()); - _dataTypeList.add(dataType); - } - } - } - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void initializeCanvas(PDCDataType dataType, List paramCodeList, - TsPaintableCanvas canvas) { - initializeTimeWindow(canvas); - - // make room for the large area required by the text header in the graph - canvas.setTopMargin(TOP_MARGIN); - - if (dataType == PDCDataType.HEIGHT) { - - initForHeight(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DISCHARGE) { - initForDischarge(_locationId, paramCodeList, canvas); - } - - // call this again to make it redraw everything correctly - // it wasn't working without this - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // ----------------------------------------------------------------------- - public void redrawCanvas() { - _canvas.refresh(); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void initializeTimeWindow(TsPaintableCanvas canvas) { - setStartTime(_startTime); - setEndTime(_endTime); - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // ---------------------------------------------------------------------------------------------------- - private FpCurPrevVtec setTSBeginEndTimeWindow(String locationId) { - String header = "FpVtecInfo.setTSBeginEndTime() "; - Map tempMap = new HashMap(); - - // get current time - long currentTime = System.currentTimeMillis(); - long roundedCurrentTime = TimeHelper.truncateTimeInMillisToNearestHour( - currentTime, HOURS_TO_ROUND); - - // set up time window - // get the backhrs and forwardhrs from record for locationId - - tempMap = _dataMgr.getvtecinfoMap(); - - FpCurPrevVtec temp = (FpCurPrevVtec) tempMap.get(locationId); - - if (temp != null) { - long obs_begintime_inmillis = temp.getObsBeginTime() - * MILLIS_PER_SECOND; - long fcst_endtime_inmillis = temp.getFcstEndTime() - * MILLIS_PER_SECOND; - - long rounded_obs_begintime = TimeHelper - .truncateTimeInMillisToNearestHour(obs_begintime_inmillis, - HOURS_TO_ROUND); - long rounded_fcst_endtime = TimeHelper - .truncateTimeInMillisToNearestHour(fcst_endtime_inmillis, - HOURS_TO_ROUND); - - if ((temp.getObsBeginTime() == MISSING_INT) - || (temp.getObsBeginTime() == 0)) - setStartTime(roundedCurrentTime - - (_defaultHoursBackInTime * MILLIS_PER_HOUR)); - else - setStartTime(rounded_obs_begintime); - - if ((temp.getFcstEndTime() == MISSING_INT) - || (temp.getFcstEndTime() == 0)) - setEndTime(roundedCurrentTime - + (_defaultHoursForwardInTime * MILLIS_PER_HOUR)); - else - setEndTime(rounded_fcst_endtime); - - } - - else { - System.out.println(header + "VTEC record not found for " - + locationId); - } - - return temp; - - } - - // -------------------------------------------------------------------------------------------------- - - private boolean isValueAvailable(Measurement measurement, MeasuringUnit unit) { - boolean result = false; - - if (measurement != null) { - if (measurement.getValue(unit) > 0.0) { - result = true; - } - } - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private void addCanvasListeners(TsPaintableCanvas canvas, - ValueMapper valueMapper) { - // Add listener for the tooltip - TsCanvasToolTipListener toolTipMgr = new TsCanvasToolTipListener( - canvas, valueMapper); - canvas.addMouseMotionListener(toolTipMgr); - - // Add listener for the timelines drag - TimeLineAdjustmentListener adjustmentListener = new TimeLineAdjustmentListener( - this, canvas, getCurVtecBeginTimeHolder(), - getCurVtecEndTimeHolder(), getCurVtecRiseTimeHolder(), - getCurVtecCrestTimeHolder(), getCurVtecFallTimeHolder()); - canvas.addMouseListener(adjustmentListener); - - return; - } - - // ------------------------------------------------------------------------------------- - private ParamCode expandParamCode(String locationId, ParamCode paramCode) { - - String header = "FpVtecInfo.expandParamCode(): "; - ParamCode expandedParamCode = new ParamCode(paramCode); - String expandedParamCodeString = null; - - String typeSource = paramCode.getTypeSource(); - String peString = paramCode.getPe(); - - if (typeSource.indexOf('-') == 1) { - if (typeSource.charAt(0) == 'F') { - typeSource = _dataMgr.getPreferredFcstTypeSource(locationId, - peString); - - if (typeSource != null) { - expandedParamCode.setTypeSource(typeSource); - expandedParamCodeString = expandedParamCode.toString(); - } else { - expandedParamCode = null; - expandedParamCodeString = null; - } - } - - } else { - expandedParamCodeString = expandedParamCode.toString(); - } - - System.out.println(header + "original paramCode = " - + paramCode.toString()); - System.out.println(header + "expandedParamCode = " - + expandedParamCodeString); - - return expandedParamCode; - - } - - // ------------------------------------------------------------------------------------- - - PDCDataType getDataTypeFromPhysicalElement(String physicalElement) { - - PDCDataType dataType = (PDCDataType) _physicalElementMap - .get(physicalElement); - if (dataType == null) { - if (stringStartsWith(physicalElement, 'H')) { - dataType = PDCDataType.HEIGHT; - } - if (stringStartsWith(physicalElement, 'Q')) { - dataType = PDCDataType.DISCHARGE; - } - } - - return dataType; - - } - - // ------------------------------------------------------------------------------------- - - private boolean stringStartsWith(String physicalElement, char firstCharacter) { - boolean result = false; - - if ((physicalElement != null) && (physicalElement.length() > 0) - && (physicalElement.charAt(0) == firstCharacter)) { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------- - - public void initForHeight(String locationId, List paramCodeList, - TsPaintableCanvas canvas) { - long curvtec_beginTime = 0; - long curvtec_endTime = 0; - long curvtec_riseTime = 0; - long curvtec_crestTime = 0; - long curvtec_fallTime = 0; - - String header = "FpVtecInfo.initForHeight(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - Color outlineColor = Color.WHITE; - Color cur_timeLineColor = Color.WHITE; - Color curvtec_begintimeLineColor = Color.BLUE; - Color curvtec_endtimeLineColor = Color.GREEN; - Color curvtec_risetimeLineColor = Color.ORANGE; - Color curvtec_cresttimeLineColor = Color.RED; - Color curvtec_falltimeLineColor = Color.MAGENTA; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = null; // actually depends on rating curve - // existence - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - // handel the begintime saved as CURRENT time - if (_fpCurPrevVtecRecord.getcurBeginTime() == -1) { - getCurVtecBeginTimeHolder().setTime(currentTime); - } else if (_fpCurPrevVtecRecord.getcurBeginTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecBeginTimeHolder().setTime(MISSING_INT); - } else { - curvtec_beginTime = _fpCurPrevVtecRecord.getcurBeginTime() - * MILLIS_PER_SECOND; - getCurVtecBeginTimeHolder().setTime(curvtec_beginTime); - - } - - // handel the endtime as CURRENT time - if (_fpCurPrevVtecRecord.getcurEndTime() == -1) { - getCurVtecEndTimeHolder().setTime(currentTime); - } else if (_fpCurPrevVtecRecord.getcurEndTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecEndTimeHolder().setTime(MISSING_INT); - } else { - curvtec_endTime = _fpCurPrevVtecRecord.getcurEndTime() - * MILLIS_PER_SECOND; - getCurVtecEndTimeHolder().setTime(curvtec_endTime); - } - - // handle the risetime - if (_fpCurPrevVtecRecord.getcurRiseTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecRiseTimeHolder().setTime(MISSING_INT); - } else { - curvtec_riseTime = _fpCurPrevVtecRecord.getcurRiseTime() - * MILLIS_PER_SECOND; - getCurVtecRiseTimeHolder().setTime(curvtec_riseTime); - } - - // handle the crest time - if (_fpCurPrevVtecRecord.getcurCrestTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecCrestTimeHolder().setTime(MISSING_INT); - } else { - curvtec_crestTime = _fpCurPrevVtecRecord.getcurCrestTime() - * MILLIS_PER_SECOND; - getCurVtecCrestTimeHolder().setTime(curvtec_crestTime); - } - - // handle the falltime - if (_fpCurPrevVtecRecord.getcurFallTime() == MISSING_INT) { - // do not draw the MSG time - getCurVtecFallTimeHolder().setTime(MISSING_INT); - } else { - curvtec_fallTime = _fpCurPrevVtecRecord.getcurFallTime() - * MILLIS_PER_SECOND; - getCurVtecFallTimeHolder().setTime(curvtec_fallTime); - } - - // set title and measuring units - - String titleString = "River Stages for " + locationId; - - // read in the observed time series - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - - // read in the forecast time series - - fcstTs = _dataMgr.loadFcstStageTimeSeries(locationId, - paramCode, getEndTime(), _fpCurPrevVtecRecord); - - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } else // observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = _dataMgr.loadObservedStageTimeSeries(locationId, - paramCode, getStartTime(), _fpCurPrevVtecRecord); - - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - } - - // create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - ValueMapper valueMapper = null; - - if (ratingCurve.exists()) { - valueMapper = new StageToFlowValueMapper(ratingCurve); - rightAxisLabelString = "cfs"; - } else { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "feet"; - } - - // the textheader in the TimeSeries/VTEC info window - String[] textHeaderStringArray = null; - - if (_fpCurPrevVtecRecord != null) { - textHeaderStringArray = getTextHeaderStringArray(locationId, - _fpCurPrevVtecRecord, obsParamCodeString.substring(0, 5), - fcstParamCodeString.substring(0, 5), unit.toString()); - - } - - TslBackgroundPainter backgroundPainter = new TslBackgroundPainter( - outlineColor, leftAxisLabelString, rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - // time lines painter - // Current time line - if (currentTimeHolder != null) { - // TslTimeLinePainter timeLinePainter = new - // TslTimeLinePainter(cur_timeLineColor, - // "N", 95, currentTimeHolder); - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter( - cur_timeLineColor, "N", 95, currentTimeHolder); - - assignPainterToCanvas(timeLinePainter, canvas); - } - - // Event begin time line - - TslTimeLinePainter curvtec_begintimeLinePainter = new TslTimeLinePainter( - curvtec_begintimeLineColor, "B", 95, - getCurVtecBeginTimeHolder()); - assignPainterToCanvas(curvtec_begintimeLinePainter, canvas); - - // Event end time line - - TslTimeLinePainter curvtec_endtimeLinePainter = new TslTimeLinePainter( - curvtec_endtimeLineColor, "E", 95, getCurVtecEndTimeHolder()); - - assignPainterToCanvas(curvtec_endtimeLinePainter, canvas); - - // Event Rise time line - - TslTimeLinePainter curvtec_risetimeLinePainter = new TslTimeLinePainter( - curvtec_risetimeLineColor, "R", 95, - getCurVtecRiseTimeHolder()); - - assignPainterToCanvas(curvtec_risetimeLinePainter, canvas); - - // Event Crest time line - - TslTimeLinePainter curvtec_cresttimeLinePainter = new TslTimeLinePainter( - curvtec_cresttimeLineColor, "C", 95, - getCurVtecCrestTimeHolder()); - - assignPainterToCanvas(curvtec_cresttimeLinePainter, canvas); - - - // Event Fall time line - - TslTimeLinePainter curvtec_falltimeLinePainter = new TslTimeLinePainter( - curvtec_falltimeLineColor, "F", 95, - getCurVtecFallTimeHolder()); - - assignPainterToCanvas(curvtec_falltimeLinePainter, canvas); - - - // significant value line painters for floodstage and actionstage - - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - Color actionStageColor = Color.YELLOW; - Color floodStageColor = Color.ORANGE; - Color moderateStageColor = Color.RED; - Color majorStageColor = Color.MAGENTA; - - if (sigRiverLevels != null) { - boolean shouldPaint = false; - - // flood stage - Measurement floodStageMeasurement = new Measurement(sigRiverLevels - .getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = new SignificantLinePainter( - floodStageColor, floodStageMeasurement, unit); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - floodStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(floodStagePainter, canvas); - - // action stage - Measurement actionStageMeasurement = new Measurement(sigRiverLevels - .getActionStage(), unit); - - SignificantLinePainter actionStagePainter = new SignificantLinePainter( - actionStageColor, actionStageMeasurement, unit); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - actionStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(actionStagePainter, canvas); - - // moderate stage - double moderatefs = sigRiverLevels.getModerateFloodStage(); - Measurement moderateStageMeasurement = new Measurement( - sigRiverLevels.getModerateFloodStage(), unit); - - SignificantLinePainter moderateStagePainter = new SignificantLinePainter( - moderateStageColor, moderateStageMeasurement, unit); - - shouldPaint = isValueAvailable(moderateStageMeasurement, unit); - moderateStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(moderateStagePainter, canvas); - - // major stage - Measurement majorStageMeasurement = new Measurement(sigRiverLevels - .getMajorFloodStage(), unit); - - SignificantLinePainter majorStagePainter = new SignificantLinePainter( - majorStageColor, majorStageMeasurement, unit); - - shouldPaint = isValueAvailable(majorStageMeasurement, unit); - majorStagePainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(majorStagePainter, canvas); - - } - - // observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, - obsTsHolder); - obsTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, - fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ------------------------------------------------------------------------------------ - public void initForDischarge(String locationId, List paramCodeList, - TsPaintableCanvas canvas) { - long curvtec_beginTime = 0; - long curvtec_endTime = 0; - long curvtec_riseTime = 0; - long curvtec_crestTime = 0; - long curvtec_fallTime = 0; - - String header = "FpVtecInfo.initForDischarge(): "; - - MeasuringUnit unit = MeasuringUnit.cfs; - - canvas.setDisplayedMeasuringUnit(unit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.WHITE; - Color curvtec_begintimeLineColor = Color.BLUE; - Color curvtec_endtimeLineColor = Color.GREEN; - Color curvtec_risetimeLineColor = Color.ORANGE; - Color curvtec_cresttimeLineColor = Color.RED; - Color curvtec_falltimeLineColor = Color.MAGENTA; - - String leftAxisLabelString = "cfs"; - String rightAxisLabelString = null; // actually depends on rating curve - // existence - - // Set time - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - // handel the begintime saved as CURRENT time - if (_fpCurPrevVtecRecord.getcurBeginTime() == -1) { - // curvtec_beginTimeHolder = new TimeHolder(); - getCurVtecBeginTimeHolder().setTime(currentTime); - } else if (_fpCurPrevVtecRecord.getcurBeginTime() != -9999) { - curvtec_beginTime = _fpCurPrevVtecRecord.getcurBeginTime() - * MILLIS_PER_SECOND; - // curvtec_beginTimeHolder = new TimeHolder(); - getCurVtecBeginTimeHolder().setTime(curvtec_beginTime); - } - if (_fpCurPrevVtecRecord.getcurEndTime() != -9999) { - curvtec_endTime = _fpCurPrevVtecRecord.getcurEndTime() - * MILLIS_PER_SECOND; - // curvtec_endTimeHolder = new TimeHolder(); - getCurVtecEndTimeHolder().setTime(curvtec_endTime); - } - if (_fpCurPrevVtecRecord.getcurRiseTime() != -9999) { - curvtec_riseTime = _fpCurPrevVtecRecord.getcurRiseTime() - * MILLIS_PER_SECOND; - // curvtec_riseTimeHolder = new TimeHolder(); - getCurVtecRiseTimeHolder().setTime(curvtec_riseTime); - } - if (_fpCurPrevVtecRecord.getcurCrestTime() != -9999) { - curvtec_crestTime = _fpCurPrevVtecRecord.getcurCrestTime() - * MILLIS_PER_SECOND; - // curvtec_crestTimeHolder = new TimeHolder(); - getCurVtecCrestTimeHolder().setTime(curvtec_crestTime); - } - if (_fpCurPrevVtecRecord.getcurFallTime() != -9999) { - curvtec_fallTime = _fpCurPrevVtecRecord.getcurFallTime() - * MILLIS_PER_SECOND; - // curvtec_fallTimeHolder = new TimeHolder(); - getCurVtecFallTimeHolder().setTime(curvtec_fallTime); - } - - // set title and measuring units - - String titleString = "River Discharge for " + locationId; - // read in the observed time series - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - // read in the forecast time series - fcstTs = _dataMgr.loadFcstDischargeTimeSeries(locationId, - paramCode, getEndTime(), _fpCurPrevVtecRecord); - - fcstStageTimer - .stop(header + "loadFcstDischargeTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } else // observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = _dataMgr.loadObservedDischargeTimeSeries(locationId, - paramCode, getStartTime(), _fpCurPrevVtecRecord); - stageTimer.stop(header - + "loadObservedDischargeTimeSeries took "); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - } - - // create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - ValueMapper valueMapper = null; - - if (ratingCurve.exists()) { - valueMapper = new FlowToStageValueMapper(ratingCurve); - rightAxisLabelString = "feet"; - } else { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "cfs"; - } - - String[] textHeaderStringArray = null; - - if (_fpCurPrevVtecRecord != null) { - textHeaderStringArray = getTextHeaderStringArray(locationId, - _fpCurPrevVtecRecord, obsParamCodeString.substring(0, 5), - fcstParamCodeString.substring(0, 5), unit.toString()); - } - - TslBackgroundPainter backgroundPainter = new TslBackgroundPainter( - outlineColor, leftAxisLabelString, rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - // time line painter - if (currentTimeHolder != null) { - TslTimeLinePainter nowtimeLinePainter = new TslTimeLinePainter( - timeLineColor, "N", 95, currentTimeHolder); - // nowtimeLineLabelPainter.setTimeType("N"); - assignPainterToCanvas(nowtimeLinePainter, canvas); - } - - if (getCurVtecBeginTimeHolder() != null) { - TslTimeLinePainter curvtec_begintimeLinePainter = new TslTimeLinePainter( - curvtec_begintimeLineColor, "B", 95, - getCurVtecBeginTimeHolder()); - assignPainterToCanvas(curvtec_begintimeLinePainter, canvas); - } - - if (getCurVtecEndTimeHolder() != null) { - TslTimeLinePainter curvtec_endtimeLinePainter = new TslTimeLinePainter( - curvtec_endtimeLineColor, "E", 95, - getCurVtecEndTimeHolder()); - - assignPainterToCanvas(curvtec_endtimeLinePainter, canvas); - } - - if (getCurVtecRiseTimeHolder() != null) { - TslTimeLinePainter curvtec_risetimeLinePainter = new TslTimeLinePainter( - curvtec_risetimeLineColor, "R", 95, - getCurVtecRiseTimeHolder()); - - assignPainterToCanvas(curvtec_risetimeLinePainter, canvas); - } - - if (getCurVtecCrestTimeHolder() != null) { - TslTimeLinePainter curvtec_cresttimeLinePainter = new TslTimeLinePainter( - curvtec_cresttimeLineColor, "C", 95, - getCurVtecCrestTimeHolder()); - - assignPainterToCanvas(curvtec_cresttimeLinePainter, canvas); - } - - if (getCurVtecFallTimeHolder() != null) { - TslTimeLinePainter curvtec_falltimeLinePainter = new TslTimeLinePainter( - curvtec_falltimeLineColor, "F", 95, - getCurVtecFallTimeHolder()); - - assignPainterToCanvas(curvtec_falltimeLinePainter, canvas); - } - - // significant value line painters for floodflow and actionflow - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - Color floodFlowColor = Color.RED; - Color moderateFlowColor = Color.MAGENTA; - Color majorFlowColor = Color.CYAN; - Color actionFlowColor = Color.YELLOW; - - if (sigRiverLevels != null) { - boolean shouldPaint = false; - - // Flood Flow - Measurement floodFlowMeasurement = new Measurement(sigRiverLevels - .getFloodFlow(), unit); - - SignificantLinePainter floodFlowPainter = new SignificantLinePainter( - floodFlowColor, floodFlowMeasurement, unit); - - shouldPaint = isValueAvailable(floodFlowMeasurement, unit); - floodFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(floodFlowPainter, canvas); - - // action flow - Measurement actionFlowMeasurement = new Measurement(sigRiverLevels - .getActionFlow(), unit); - - SignificantLinePainter actionFlowPainter = new SignificantLinePainter( - actionFlowColor, actionFlowMeasurement, unit); - - shouldPaint = isValueAvailable(actionFlowMeasurement, unit); - actionFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(actionFlowPainter, canvas); - - // moderate flow - Measurement moderateFlowMeasurement = new Measurement( - sigRiverLevels.getModerateFloodFlow(), unit); - - SignificantLinePainter moderateFlowPainter = new SignificantLinePainter( - moderateFlowColor, moderateFlowMeasurement, unit); - - shouldPaint = isValueAvailable(moderateFlowMeasurement, unit); - moderateFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(moderateFlowPainter, canvas); - - // major flow - Measurement majorFlowMeasurement = new Measurement(sigRiverLevels - .getMajorFloodFlow(), unit); - - SignificantLinePainter majorFlowPainter = new SignificantLinePainter( - majorFlowColor, majorFlowMeasurement, unit); - - shouldPaint = isValueAvailable(majorFlowMeasurement, unit); - majorFlowPainter.setShouldPaint(shouldPaint); - assignPainterToCanvas(majorFlowPainter, canvas); - - } - - // observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, - obsTsHolder); - obsTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, - fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ------------------------------------------------------------------------------------ - - private void assignPainterToCanvas(TslCanvasPainter painter, - TsPaintableCanvas canvas) { - painter.setCanvas(canvas); - canvas.addTsCanvasPainter(painter); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslTimeLinePainter painter, - TsPaintableCanvas canvas) { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void assignPainterToCanvas(TslBackgroundPainter painter, - TsPaintableCanvas canvas) { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private String[] getTextHeaderStringArray(String locationId, - FpCurPrevVtec fpcurprevvtecRecord, String paramCodeString, - String fcstParamCodeString, String unitString) { - String[] textHeaderStringArray = null; - StringBuffer paramCodeStringBuffer = new StringBuffer(paramCodeString); - if (fcstParamCodeString != null) { - paramCodeStringBuffer.append(" " + fcstParamCodeString); - } - - textHeaderStringArray = new String[3]; - - // Lid-Name-FldStg - // if (unitString.equals("feet")) - if (_dataType == PDCDataType.HEIGHT) - textHeaderStringArray[0] = locationId + " - " - + fpcurprevvtecRecord.getLocName() + " - " - + fpcurprevvtecRecord.getLocStream() + " - " - + "Flood Stage: " + fpcurprevvtecRecord.getFloodStg() + " " - + unitString; - else - textHeaderStringArray[0] = locationId + " - " - + fpcurprevvtecRecord.getLocName() + " - " - + fpcurprevvtecRecord.getLocStream() + " - " - + "Flood Flow: " + fpcurprevvtecRecord.getFloodFlow() - + unitString; - - // PE-TS - textHeaderStringArray[1] = "PE/DUR/TS: " - + paramCodeStringBuffer.toString(); - - // Current VTEC phenom, signif and ETN - - textHeaderStringArray[2] = "Proposed VTEC Phenom: " - + fpcurprevvtecRecord.getcurPhenom() + " " + "Signif: " - + fpcurprevvtecRecord.getcurSignif() + " " + "ETN: " - + fpcurprevvtecRecord.getcurEtn(); - - return textHeaderStringArray; - - } - - // -------------------------------------------------------------------------------------------------- - /* - * private String wrapInHTML(String origString) { StringBuffer buffer = new - * StringBuffer("
    " + origString + "
    "); - * - * return buffer.toString(); } - */ - // ------------------------------------------------------------ - /* - * private String getVerticalText(String origText) { char[] charArray = - * origText.toCharArray(); StringBuffer buffer = new StringBuffer(); - * - * buffer.append(""); for (int i = 0; i < charArray.length; i++) { - * buffer.append(charArray[i]); - * - * //don't do a break for the last one if (i < charArray.length-1) { - * buffer.append("
    "); } } buffer.append(""); - * - * String verticalText = buffer.toString(); - * - * return verticalText; } - * // - * -------------------------------------------------------------------------------------------------- - * - * - * /** @param startTime The startTime to set. - */ - public void setStartTime(long startTime) { - _startTime = startTime; - } - - // -------------------------------------------------------------------------------------------------- - - /** - * @return Returns the startTime. - */ - public long getStartTime() { - return _startTime; - } - - // -------------------------------------------------------------------------------------------------- - - /** - * @param endTime - * The endTime to set. - */ - public void setEndTime(long endTime) { - _endTime = endTime; - } - - /** - * @return Returns the endTime. - */ - public long getEndTime() { - return _endTime; - } - - // -------------------------------------------------------------------------------------------------- - /** - * @return _fpCurPrevVtecRecord - */ - public FpCurPrevVtec getFpCurPrevVtecRecord() { - return _fpCurPrevVtecRecord; - } - - public FpVtecInfoFrame getFrame() { - return _frame; - } - - public void setFrame(FpVtecInfoFrame _frame) { - this._frame = _frame; - } - - public FpVtecInfoDataManager get_dataMgr() { - return _dataMgr; - } - - public void set_dataMgr(FpVtecInfoDataManager mgr) { - _dataMgr = mgr; - } - - public TimeHolder getCurVtecBeginTimeHolder() { - return _curVtecBeginTimeHolder; - } - - public TimeHolder getCurVtecEndTimeHolder() { - return _curVtecEndTimeHolder; - } - - public TimeHolder getCurVtecRiseTimeHolder() { - return _curVtecRiseTimeHolder; - } - - public TimeHolder getCurVtecCrestTimeHolder() { - return _curVtecCrestTimeHolder; - } - - public TimeHolder getCurVtecFallTimeHolder() { - return _curVtecFallTimeHolder; - } - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoDataManager.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoDataManager.java deleted file mode 100644 index b2e9ae4326..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoDataManager.java +++ /dev/null @@ -1,606 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.sql.SQLException; - - -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.FloodcatRecord; -import ohd.hseb.ihfsdb.generated.FloodcatTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; - -public class FpVtecInfoDataManager -{ - - private static final long MILLIS_PER_SECOND = 1000; - - private Database _db = null; - private Logger _logger = null; - - private String _jdbcConnectionString = null; - - private String _rpfdataFilePath = null; - private Map _vtecinfoMap = new HashMap(); - - // --------------------------------------------------------------------------------- - - public FpVtecInfoDataManager(String jdbcConnectionString) - { - _logger = new FileLogger(true); - - _jdbcConnectionString = jdbcConnectionString; - - _db = new Database(); - - _db.connect(_jdbcConnectionString); - - getAppsDefaults(); - } - // --------------------------------------------------------------------------------- - - private void getAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - - _rpfdataFilePath = ad.getToken( "rpf_template_dir" ) + "/"; - - return; - } - //---------------------------------------------------------------------------------- - - public void readInputFileFormFpCurPrevVtecInfoMap() - { - //String header = "FpVtecInfoDataManager.readInputFileFormCurPrevVtecInfoMap(): "; - String fpvtecinfoFileName = getFpVtecInfoFileName(); - FpVtecInfoFileReader reader = new FpVtecInfoFileReader(fpvtecinfoFileName); - - _vtecinfoMap = reader.read(); - - return; - } - -// ------------------------------------------------------------------------ - private String getFpVtecInfoFileName() - { - String fpvtecinfoFileName = _rpfdataFilePath + - "fpvtecinfo.dat"; - System.out.println("FpVtecInfoDataManager: getFpVtecInfoFileName()" + - fpvtecinfoFileName); - - return fpvtecinfoFileName; - } - - -// ------------------------------------------------------------------------------------- - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId, - ParamCode paramCode, - long startTime, - FpCurPrevVtec fpCurPrevVtecRecord) - { - final double missingValue = -9999.0; - String header = "FpVtecInfoDataManager.loadObservedStageTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - AbsTimeMeasurement measurement = null; - ArrayList obsValueTimeList = new ArrayList(); - String obsValueTimeRecord = null; - String [] temp = null; - double obsValue = missingValue; - long obsTime = 0; - - - try - { - obsValueTimeList = fpCurPrevVtecRecord.getObsValuetTimeList(); - - if (obsValueTimeList != null) - { - for (int i = 0; i < obsValueTimeList.size(); i++) - { - obsValueTimeRecord = obsValueTimeList.get(i).toString(); - - //don't let the missing values be included - - temp = obsValueTimeRecord.split(","); - obsValue = Double.parseDouble(temp[0]); - obsTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(obsValue, - obsTime, - unit); - - stageTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch(Exception e) - { - System.err.println(header + "error loading observed data from obsValueTimeList"); - e.printStackTrace(); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedDischargeTimeSeries(String locationId, - ParamCode paramCode, - long startTime, - FpCurPrevVtec fpCurPrevVtecRecord) - { - final double missingValue = -9999.0; - - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "FpVtecInfoDataManager.loadObservedDischargeTimeSeries(): "; - - AbsTimeMeasurement measurement = null; - ArrayList obsValueTimeList = new ArrayList(); - String obsValueTimeRecord = null; - String [] temp = null; - double obsValue = missingValue; - long obsTime = 0; - - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - try - { - obsValueTimeList = fpCurPrevVtecRecord.getObsValuetTimeList(); - - if (obsValueTimeList != null) - { - for (int i = 0; i < obsValueTimeList.size(); i++) - { - obsValueTimeRecord = obsValueTimeList.get(i).toString(); - - temp = obsValueTimeRecord.split(","); - obsValue = Double.parseDouble(temp[0]); - obsTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(obsValue, - obsTime, - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch(Exception e) - { - System.err.println(header + "error loading observed data from obsValueTimeList"); - e.printStackTrace(); - } - - - return dischargeTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - ParamCode paramCode, - long endTime, - FpCurPrevVtec fpCurPrevVtecRecord) - { - long originalBasisTime = 0; - final double missingValue = -9999.0; - - MeasuringUnit unit = MeasuringUnit.feet; - AbsTimeMeasurement measurement = null; - String header = "FpVtecInfoDataManager.loadFcstStageTimeSeries(): "; - ArrayList fcstValueTimeList = new ArrayList(); - String fcstValueTimeRecord = null; - String [] temp = null; - double fcstValue = missingValue; - long fcstTime = 0; - - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - - try - { - fcstValueTimeList = fpCurPrevVtecRecord.getFcstValueTimeList(); - - if (fcstValueTimeList != null) - { - for (int i = 0; i < fcstValueTimeList.size(); i++) - { - fcstValueTimeRecord = fcstValueTimeList.get(i).toString(); - - temp = fcstValueTimeRecord.split(","); - fcstValue = Double.parseDouble(temp[0]); - fcstTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(fcstValue, - fcstTime, - unit); - - stageTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch(Exception e) - { - System.err.println(header + "error loading forecast data from fcstValueTimeList"); - e.printStackTrace(); - } - - - return stageTimeSeries; - } - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - ParamCode paramCode, - long endTime, - FpCurPrevVtec fpCurPrevVtecRecord) - { - long originalBasisTime = 0; - final double missingValue = -9999.0; - - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "FpVtecInfoDataManager.loadFcstDischargeTimeSeries(): "; - - ArrayList fcstValueTimeList = new ArrayList(); - String fcstValueTimeRecord = null; - String [] temp = null; - double fcstValue = missingValue; - long fcstTime = 0; - AbsTimeMeasurement measurement = null; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - - try - { - fcstValueTimeList = fpCurPrevVtecRecord.getFcstValueTimeList(); - - if (fcstValueTimeList != null) - { - for (int i = 0; i < fcstValueTimeList.size(); i++) - { - fcstValueTimeRecord = fcstValueTimeList.get(i).toString(); - - temp = fcstValueTimeRecord.split(","); - fcstValue = Double.parseDouble(temp[0]); - fcstTime = (Long.parseLong(temp[1])) * MILLIS_PER_SECOND; - - measurement = new AbsTimeMeasurement(fcstValue, - fcstTime, - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - } - } - } - - catch(Exception e) - { - System.err.println(header + "error loading forecast data from fcstValueTimeList"); - e.printStackTrace(); - } - - return dischargeTimeSeries; - } - - - // ------------------------------------------------------------------------------------ - public RatingCurve loadRatingCurve(String locationId) - { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - - try - { - ratingRecordList = ratingTable.select("WHERE LID = '" + - locationId + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" + - locationId + "' AND active = 'T' ORDER BY date desc", 1 ); - - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId + "'"); - - //determine total amount of active - //rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) - { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList.get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - } - - //initialize the RatingCurve object with data from the database, including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) - { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - //done by addRatingPoint - //ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } //end for - - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) - { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList.get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord.getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } - catch (SQLException e) - { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - // ------------------------------------------------------------------------------ - - - public SigRiverLevels loadSigRiverLevels(String locationId) - { - String header = "FpVtecInfoDataManager.loadSigRiverLevels(): "; - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (RiverstatRecord) recordList.get(0); - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - // need to change the common lib SigRiverLevels.java - - - if (DbTable.isNull(actionStage)) - { - System.out.println(header + " actionStage is null for " + locationId); - } - if (DbTable.isNull(record.getPrimary_pe())) - { - System.out.println(header + " primary_pe is null for " + locationId); - record.setPrimary_pe("HG"); - } - - levels = new SigRiverLevels(locationId, - record.getPrimary_pe(), - floodStage, - actionStage, - floodFlow, - actionFlow); - // load moderate and major floods - - loadFloodCategories(levels); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return levels; - } - - // -------------------------------------------------------------------------------------------------- - private void loadFloodCategories(SigRiverLevels levels) - { - FloodcatTable table = new FloodcatTable(_db); - FloodcatRecord record = null; - - String whereClause = "WHERE lid = '" + levels.getLocationId() + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (FloodcatRecord) recordList.get(0); - - levels.setMinorFloodFlow(record.getMinor_flow()); - levels.setModerateFloodFlow(record.getModerate_flow()); - levels.setMajorFloodFlow(record.getMajor_flow()); - - levels.setMinorFloodStage(record.getMinor_stage()); - levels.setModerateFloodStage(record.getModerate_stage()); - levels.setMajorFloodStage(record.getMajor_stage()); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return; - } - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSource(String lid, - String pe) - { - String header = "FpVtecInfoDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + "'" + - " AND pe = '" + pe + "'" + - " AND dur = 0 " + - " AND ts like 'F%' " + - " order by ts_rank ASC" ; - - try - { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - if (pe.charAt(0)=='H') - { - for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - if (fcstHeightRecordExists(record)) - { - newTypeSource = record.getTs(); - break; - } - } - - } - else //pe is not 'H*', so don't look at fcstHeight to see if it exists - { - newTypeSource = record.getTs(); - } - - } - } - catch(SQLException e) - { - logSQLException(e); - } - - // System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // -------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------- - public boolean fcstHeightRecordExists(IngestFilterRecord ingestRecord) - { - boolean result = false; - - String header = "FpVtecInfoDataManager.fcstHeightRecordExists(): "; - - FcstHeightTable table = new FcstHeightTable(_db); - - String whereClause = "WHERE lid = '" + ingestRecord.getLid() + "'" + - " AND pe = '" + ingestRecord.getPe() + "'" + - " AND dur = " + ingestRecord.getDur() + - " AND ts = '" + ingestRecord.getTs() + "'"; - - - try - { - int recordCount = table.selectCount(whereClause); - - if (recordCount > 0) - { - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - - public Map getvtecinfoMap() - { - return _vtecinfoMap; - } - - public String get_rpfdataFilePath() { - return _rpfdataFilePath; - } - - public void set_rpfdataFilePath(String filePath) { - _rpfdataFilePath = filePath; - } - - public Database get_db() { - return _db; - } - - public void set_db(Database _db) { - this._db = _db; - } - -} //end FpVtecInfoDataManager diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoFileReader.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoFileReader.java deleted file mode 100644 index 883898ffb6..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoFileReader.java +++ /dev/null @@ -1,445 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -//import java.util.List; -import java.util.Map; -//import java.util.Scanner; -import java.util.StringTokenizer; -import ohd.hseb.fp_vtec_info.FpCurPrevVtec; - -public class FpVtecInfoFileReader -{ - //private List _fpvtecinfoList; - private String _fullFilePath = null; - private boolean _debug = false; - private BufferedReader _reader = null; - private Map _fpcurprevvtecMap = null; - - // ------------------------------------------------------------------------------ - public FpVtecInfoFileReader() - { - - } - // ---------------------------------------------------------------------------------- - public FpVtecInfoFileReader(String fullFilePath) - { - _fullFilePath = fullFilePath; - _fpcurprevvtecMap = new HashMap(); - } - - // ---------------------------------------------------------------------------------- - public Map read() - { - String header = "FpVtecInfoFileReader.read() "; - - try - { - FileReader fileReader = new FileReader(_fullFilePath); - _reader = new BufferedReader(fileReader); - - readFileHeader(); - - boolean done = false; - - while ( ! done ) - { - try - { - FpCurPrevVtec fpvtecinfo = readFpVtecData(); - if (fpvtecinfo != null) - { - _fpcurprevvtecMap.put(fpvtecinfo.getLocId(), fpvtecinfo); - - } - else - { - System.out.println("fpvtecinfo is null"); - debug_logline(header + "fpvtecinfo is null"); - } - - } - catch (EOFException e) - { - done = true; - } - catch (Exception e) - { - System.err.println(header + - "Exception reading file " + _fullFilePath + - " " + e.getMessage()); - e.printStackTrace(); - - done = true; - } - } //end while - - - if (_reader != null) - { - _reader.close(); - _reader = null; - } - - } //end try - catch (FileNotFoundException e) - { - System.err.println("Unable to open" + _fullFilePath); - - } - catch (IOException e) - { - System.err.println("Unable to open" + _fullFilePath); - } - - return _fpcurprevvtecMap; - } - - // ---------------------------------------------------------------------------------- - private void readFileHeader() throws IOException - { - String header = "FpVtecInfoFileReader.readFileHeader(): "; - String line = null; - - //ignore the first 4 lines in the fpvtecinfo.dat - line = _reader.readLine(); - debug_logline(header + " line 1 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 2 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 3 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 4 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 5 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 6 = " + line); - - } - - // ---------------------------------------------------------------------------------- - - private FpCurPrevVtec readFpVtecData() throws IOException - { - String header = "FpVtecInfoFileReader.readFpVtecData(): "; - StringTokenizer fpLineTokenizer = null; - StringTokenizer curVtecLineTokenizer = null; - StringTokenizer prevVtecLineTokenizer = null; - StringTokenizer observedTSLineTokenizer = null; - StringTokenizer fcstTSLineTokenizer = null; - ArrayList obsValueTimeList = new ArrayList(); - ArrayList fcstValueTimeList = new ArrayList(); - - // The first line includes fp information for specific location - - String stationFpDataLine = _reader.readLine(); - - if (stationFpDataLine == null) - { - throw new EOFException(); - } - else - fpLineTokenizer = new StringTokenizer(stationFpDataLine, ","); - - // The second line includes current VTEC information for specific location - - String stationCurVtecDataLine = _reader.readLine(); - if (stationCurVtecDataLine == null) - { - throw new EOFException(); - } - else - curVtecLineTokenizer = new StringTokenizer(stationCurVtecDataLine, ","); - - - // The third line includes previous VTEC information for specific location - - String stationPrevVtecDataLine = _reader.readLine(); - - if (stationPrevVtecDataLine == null) - { - throw new EOFException(); - } - else if (stationPrevVtecDataLine.equals("MSG")) - { - //no previous event exist - System.out.println("No previous event exist."); - } - else - { - prevVtecLineTokenizer = new StringTokenizer(stationPrevVtecDataLine, ","); - } - - // The fourth line includes observed timesreis data - String stationObservedTSLine = _reader.readLine(); - - if (stationObservedTSLine == null) - { - throw new EOFException(); - } - else if (stationObservedTSLine.equals("MSG")) - { - //no observed TS exists - System.out.println("No Observed TimeSeries data exists."); - } - else - { - observedTSLineTokenizer = new StringTokenizer(stationObservedTSLine, ";"); - } - - // The fifth line includes forecast timesreis data - String stationForecastTSLine = _reader.readLine(); - - if (stationForecastTSLine == null) - { - throw new EOFException(); - } - else if (stationForecastTSLine.equals("MSG")) - { - //no forecast TS exists - System.out.println("No Forecast TimeSeries data exists."); - } - else - { - fcstTSLineTokenizer = new StringTokenizer(stationForecastTSLine, ";"); - } - - FpCurPrevVtec descriptor = new FpCurPrevVtec(); - - // parse out the first line FP information - - String lid = fpLineTokenizer.nextToken(); - descriptor.setLocId(lid.trim()); - - - String name = fpLineTokenizer.nextToken(); - descriptor.setLocName(name.trim()); - - - String stream = fpLineTokenizer.nextToken(); - descriptor.setLocStream(stream.trim()); - - - String pe = fpLineTokenizer.nextToken(); - descriptor.setLocPe(pe.trim()); - - - double fs = Double.parseDouble(fpLineTokenizer.nextToken()); - descriptor.setFloodStg(fs); - - - double fq = Double.parseDouble(fpLineTokenizer.nextToken()); - descriptor.setFloodFlow(fq); - - - long obs_begintime = Long.parseLong(fpLineTokenizer.nextToken()); - descriptor.setObsBeginTime(obs_begintime); - - long fcst_endtime = Long.parseLong(fpLineTokenizer.nextToken()); - descriptor.setFcstEndTime(fcst_endtime); - - double adjustendhrs = Double.parseDouble(fpLineTokenizer.nextToken()); - descriptor.setAdjustEndhrs(adjustendhrs); - - - debug_logline(header + "lid = " + lid + " " + - "name = " + name + " " + - "stream = " + stream); - - - // parse out second line current VTEC information - - String cur_action = curVtecLineTokenizer.nextToken(); - descriptor.setcurAction(cur_action.trim()); - - String cur_phenom = curVtecLineTokenizer.nextToken(); - descriptor.setcurPhenom(cur_phenom.trim()); - - String cur_signif = curVtecLineTokenizer.nextToken(); - descriptor.setcurSignif(cur_signif.trim()); - - String cur_severity = curVtecLineTokenizer.nextToken(); - descriptor.setcurSeverity(cur_severity.trim()); - - String cur_cause = curVtecLineTokenizer.nextToken(); - descriptor.setcurCause(cur_cause.trim()); - - String cur_record = curVtecLineTokenizer.nextToken(); - descriptor.setcurRecord(cur_record.trim()); - - int cur_etn = Integer.parseInt(curVtecLineTokenizer.nextToken()); - descriptor.setcurEtn(cur_etn); - - double cur_crest_value = Double.parseDouble(curVtecLineTokenizer.nextToken()); - descriptor.setcurCrestValue(cur_crest_value); - - long cur_begintime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurBeginTime(cur_begintime); - - long cur_endtime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurEndTime(cur_endtime); - - long cur_risetime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurRiseTime(cur_risetime); - - long cur_cresttime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurCrestTime(cur_cresttime); - - long cur_falltime = Long.parseLong(curVtecLineTokenizer.nextToken()); - descriptor.setcurFallTime(cur_falltime); - - debug_logline(header + "cur_action = " + cur_action + " " + - "cur_phenom = " + cur_phenom + " " + - "cur_signif = " + cur_signif + " " + - "cur_severity = " + cur_severity + " " + - "cur_cause = " + cur_cause + " " + - "cur_record = " + cur_record + " " + - "cur_etn = " + cur_etn + " " + - "cur_crest_value = " + cur_crest_value); - - // parse out third line previous VTEC information - - if (prevVtecLineTokenizer != null) - { - String prev_action = prevVtecLineTokenizer.nextToken(); - descriptor.setprevAction(prev_action); - - String prev_phenom = prevVtecLineTokenizer.nextToken(); - descriptor.setprevPhenom(prev_phenom); - - String prev_signif = prevVtecLineTokenizer.nextToken(); - descriptor.setprevSignif(prev_signif); - - String prev_severity = prevVtecLineTokenizer.nextToken(); - descriptor.setprevSeverity(prev_severity); - - String prev_cause = prevVtecLineTokenizer.nextToken(); - descriptor.setprevCause(prev_cause); - - String prev_record = prevVtecLineTokenizer.nextToken(); - descriptor.setprevRecord(prev_record); - - - int prev_etn = Integer.parseInt(prevVtecLineTokenizer.nextToken()); - descriptor.setprevEtn(prev_etn); - - double prev_crest_value = Double.parseDouble(prevVtecLineTokenizer.nextToken()); - descriptor.setprevCrestValue(prev_crest_value); - - String prev_rise_ts = prevVtecLineTokenizer.nextToken(); - descriptor.setprevRiseType(prev_rise_ts); - - String prev_crest_ts = prevVtecLineTokenizer.nextToken(); - descriptor.setprevCrestType(prev_crest_ts); - - String prev_fall_ts = prevVtecLineTokenizer.nextToken(); - descriptor.setprevFallType(prev_fall_ts); - - long prev_begintime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevBeginTime(prev_begintime); - - long prev_endtime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevEndTime(prev_endtime); - - long prev_risetime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevRiseTime(prev_risetime); - - long prev_cresttime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevCrestTime(prev_cresttime); - - long prev_falltime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevFallTime(prev_falltime); - - long prev_producttime = Long.parseLong(prevVtecLineTokenizer.nextToken()); - descriptor.setprevProductTime(prev_producttime); - - debug_logline(header + "prev_action = " + prev_action + " " + - "prev_phenom = " + prev_phenom + " " + - "prev_signif = " + prev_signif + " " + - "prev_severity = " + prev_severity + " " + - "prev_cause = " + prev_cause + " " + - "prev_record = " + prev_record + " " + - "prev_etn = " + prev_etn + " " + - "prev_crest_value = " + prev_crest_value + " " + - "prev_rise_ts = " + prev_rise_ts + " " + - "prev_crest_ts = " + prev_crest_ts + " " + - "prev_fall_ts = " + prev_fall_ts); - } - - // parse out the observed time series data - - if (observedTSLineTokenizer != null) - { - while (observedTSLineTokenizer.hasMoreTokens()) { - obsValueTimeList.add(observedTSLineTokenizer.nextToken()); - } - - descriptor.setObsValuetTimeList(obsValueTimeList); - } - - // pase out the forecast time series data - - if (fcstTSLineTokenizer != null) - { - while (fcstTSLineTokenizer.hasMoreTokens()) { - fcstValueTimeList.add(fcstTSLineTokenizer.nextToken()); - } - - descriptor.setFcstValueTimeList(fcstValueTimeList); - } - - return descriptor; - } - - //--------------------------------------------------------- - public void setDebug(boolean debug) - { - this._debug = debug; - } - - //--------------------------------------------------------------------------------- - - public boolean getDebug() - { - return _debug; - } - - // ---------------------------------------------------------------------------------- - private void debug_logline(String message) - { - debug_log(message + '\n'); - - return; - } - // ---------------------------------------------------------------------------------- - - private void debug_log(String message) - { - if (getDebug()) - { - System.out.print(message); - } - - return; - } - // ---------------------------------------------------------------------------------- - - public Map getFpCurPrevVtecMap() - { - return _fpcurprevvtecMap; - } - - // --------------------------------------------------------------------------------- -} - - diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoFrame.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoFrame.java deleted file mode 100644 index c57233183b..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/FpVtecInfoFrame.java +++ /dev/null @@ -1,2303 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.awt.*; -import java.awt.event.*; - -import javax.swing.border.Border; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.*; - -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.OutputStream; - -import java.io.PrintWriter; -import ohd.hseb.gui.util.ScreenCaptureActionListener; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.gui.DialogHelper; -//import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.db.DbTimeHelper; - - -//------------------------------------------------------------------------------ - -public class FpVtecInfoFrame extends JFrame -{ - //------------------------------------------------------------------------------ - //private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - private static final int MILLIS_PER_SECOND = 1000; - private static long _dragged_line; - //private static final int HOURS_TO_ROUND = 6; - private static final long MISSING_INT = -9999; - private static final String MISSING_STR = "MSG"; - private Dimension _minSize = new Dimension(250, 250); - private Dimension _maxSize = new Dimension(1000,1000); - - protected static final int STILL_OPENED = 0; - protected static final int CLOSED_BUT_NOT_SAVED = -1; - - private OutputStream _outputStream = null; - //private boolean _fileIsOpen = false; - private PrintWriter _writer = null; - private static long _lastUpdateTime = STILL_OPENED; - private long _currentTime = 0; - - //window sizing variables - - private Dimension _initialSize = new Dimension(1250, 550); - - private JMenuBar _menuBar = null; - private JPanel _mainPanel = null; - private JPanel _tslPanel = null; - private JPanel _curvtecPanel = null; - private JPanel _prevvtecPanel = null; - private JPanel _windowButtonPanel = null; - private JPanel _buttonPanel = null; - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - - // in _curvtecPanel - private JLabel _curvtecPanelLabel = null; - private JLabel _curvtecActionComboBoxLabel = null; - - private String[] _curvtecActionComboBoxString = {"CAN", "CON", "COR", "EXP", "EXT", - "NEW", "ROU"}; - - private JComboBox _curvtecActionComboBox = new JComboBox(_curvtecActionComboBoxString); - private JLabel _curvtecPhenomComboBoxLabel = null; - private String[] _curvtecPhenomComboBoxString = {"FL", "HY"}; - private JComboBox _curvtecPhenomComboBox = new JComboBox(_curvtecPhenomComboBoxString); - private JLabel _curvtecSignifComboBoxLabel = null; - private String[] _curvtecSignifComboBoxString = {"A (wAtch)", "S (Statement)", - "W (Warning)", "Y (advisorY)" }; - private JComboBox _curvtecSignifComboBox = new JComboBox(_curvtecSignifComboBoxString); - private JLabel _curvtecSeverityComboBoxLabel = null; - private String[] _curvtecSeverityComboBoxString = {"0 (N/A)", "1 (Minor)", "2 (Moderate)", - "3 (Major)", "N (None)", "U (Unknown)" }; - private JComboBox _curvtecSeverityComboBox = new JComboBox(_curvtecSeverityComboBoxString); - - private JLabel _curvtecICComboBoxLabel = null; - - private String[] _curvtecICComboBoxString = {"DM (Dam Fail)","DR (Dam Rel)", - "ER (Exc Rain)", "ET (Flow Tidal)", - "FS (Surge)", "FT (Fld/Tide)", - "GO (Glacial)", "IC (Ice Mix)","IJ (Ice Jam)", - "MC (Multiple)", "OT (Other)", - "RS (Rain/Snow)", "SM (Snow Melt)", - "UU (Unknown)","WT (Wind/Tidal)"}; - - private JComboBox _curvtecICComboBox = new JComboBox(_curvtecICComboBoxString); - private JLabel _curvtecRecordComboBoxLabel = null; - private String[] _curvtecRecordComboBoxString = {"NO (NotExp)", "NR (Near)", - "OO (N/A)", "UU (None)"}; - private JComboBox _curvtecRecordComboBox = new JComboBox(_curvtecRecordComboBoxString); - - private JLabel _curvtecBeginTimeLabel = null; - private DateTimeTextField _curvtecBeginTimeTextField = null; - private JRadioButton _curvtecBeginTimeSetMissingRadioButton = null; - private JRadioButton _curvtecBeginTimeSetCurrentRadioButton = null; - private JRadioButton _curvtecBeginTimeRadioButton = null; - - private JLabel _curvtecEndTimeLabel = null; - private DateTimeTextField _curvtecEndTimeTextField = null; - private JRadioButton _curvtecEndTimeSetMissingRadioButton = null; - private JRadioButton _curvtecEndTimeSetCurrentRadioButton = null; - private JRadioButton _curvtecEndTimeRadioButton = null; - - private JLabel _curvtecRiseTimeLabel = null; - private DateTimeTextField _curvtecRiseTimeTextField = null; - private JCheckBox _curvtecRiseTimeSetMissingCheckBox = null; - private JLabel _curvtecCrestTimeLabel = null; - private DateTimeTextField _curvtecCrestTimeTextField = null; - private JCheckBox _curvtecCrestTimeSetMissingCheckBox = null; - private JLabel _curvtecCrestValueLabel = null; - private JTextField _curvtecCrestValueTextField = null; - private String _curCrestValueStr = null; - private JLabel _curvtecFallTimeLabel = null; - private DateTimeTextField _curvtecFallTimeTextField = null; - private JCheckBox _curvtecFallTimeSetMissingCheckBox = null; - // private JButton _curvtecUpdateGraphButton = null; - private JButton _curvtecSaveChangesButton = null; - private JButton _curvtecResetButton = null; - - // in _prevvtecPanel - private JLabel _prevvtecpanelLabel = null; - private JLabel _prevvtecActionLabel = null; - private JTextField _prevvtecActionTextField = null; - private JLabel _prevvtecPhenomLabel = null; - private JTextField _prevvtecPhenomTextField = null; - private JLabel _prevvtecSignifLabel = null; - private JTextField _prevvtecSignifTextField = null; - private JLabel _prevvtecSeverityLabel = null; - private JTextField _prevvtecSeverityTextField = null; - private JLabel _prevvtecICLabel = null; - private JTextField _prevvtecICTextField = null; - private JLabel _prevvtecRecordLabel = null; - private JTextField _prevvtecRecordTextField = null; - private JLabel _prevvtecBeginTimeLabel = null; - private JTextField _prevvtecBeginTimeTextField = null; - private JLabel _prevvtecEndTimeLabel = null; - private JTextField _prevvtecEndTimeTextField = null; - private JLabel _prevvtecRiseTimeLabel = null; - private JTextField _prevvtecRiseTimeTextField = null; - private JLabel _prevvtecRiseTypeLabel = null; - private JTextField _prevvtecRiseTypeTextField = null; - private JLabel _prevvtecCrestTimeLabel = null; - private JTextField _prevvtecCrestTimeTextField = null; - private JLabel _prevvtecCrestValueLabel = null; - private JTextField _prevvtecCrestValueTextField = null; - private JLabel _prevvtecCrestTypeLabel = null; - private JTextField _prevvtecCrestTypeTextField = null; - private JLabel _prevvtecFallTimeLabel = null; - private JTextField _prevvtecFallTimeTextField = null; - private JLabel _prevvtecFallTypeLabel = null; - private JTextField _prevvtecFallTypeTextField = null; - private JLabel _prevvtecProductTimeLabel = null; - private JTextField _prevvtecProductTimeTextField = null; - - // Booleans related to check boxes and radio button - private boolean _forceSetRiseTimeMissing = false; - private boolean _forceSetCrestTimeMissing = false; - private boolean _forceSetFallTimeMissing = false; - private boolean _forceSetBeginTimeMissing = false; - private boolean _forceSetBeginTimeCurrent = false; - private boolean _forceSetBeginTime = false; - private boolean _forceSetEndTimeMissing = false; - private boolean _forceSetEndTimeCurrent = false; - private boolean _forceSetEndTime = false; - - // in _initWindowButtonPanel - private JButton _closeButton = null; - - private FpCurPrevVtec _fpCurPrevVtecData = null; - - // for canvas - private TsPaintableCanvas _canvas = null; - //private ValueMapper _rightAxisValueMapper = null; - - private boolean _exitOnClose = false; - private FpVtecInfoDataManager _dataMgr = null; - - //define object for FpVtecInfo - private FpVtecInfo _application; - - // keep the original proposed VTEC information - private String _selected_curAction = null; - private String _selected_curPhenom = null; - private String _selected_curSignif_str = null; - private String _selected_curSeverity_str = null; - private String _selected_curCause_str = null; - private String _selected_curRecord_str = null; - private String _selected_curCrestValue_str = null; - private long _selected_curBeginTime = 0; - private long _selected_curEndTime = 0; - private long _selected_curRiseTime = 0; - private long _selected_curCrestTime = 0; - private long _selected_curFallTime = 0; - - private boolean _graphicalChange = false; - - //------------------------------------------------------------------------------ - - public FpVtecInfoFrame(FpCurPrevVtec fpCurPrevVtecRecord, - FpVtecInfoDataManager dataMgr) - { - // get the Fp/vtec information from fpcurprevvtecrecord - - _fpCurPrevVtecData = fpCurPrevVtecRecord; - _dataMgr = dataMgr; - - initGui(); - - return; - } - - // --------------------------------------------------------------------------------- - - public void setTimeWindow(long startTime, long endTime) - { - _canvas.setTimeWindow(startTime, endTime); - - return; - } - - //------------------------------------------------------------------------------ - public TsPaintableCanvas getCanvas() - { - - return _canvas; - - } - - //------------------------------------------------------------------------------ - - public void setExitOnClose(boolean exitOnClose) - { - _exitOnClose = exitOnClose; - - return; - } - //------------------------------------------------------------------------------ - - private void initGui() - { - //setAlwaysOnTop(true); - - - // canvas needs to be initialized before the menu bar, - // because of the screen capturer - initCanvas(0, 0, - _initialSize.width, - _initialSize.height); - - String dbName = _dataMgr.get_db().getDatabaseName(); - String windowTitle = "TimeSeries/Valid Time Event Code Information Window on " + dbName; - - this.setTitle(windowTitle); - - initMenuBar(); - - //limit the range of the resizing - // this object can be local because it remains in memory as a listener - //WindowResizingManager manager = new WindowResizingManager(this, _minSize, _maxSize); - - _tslPanel = new JPanel(); - _tslPanel.setBackground(Color.white); - - settslPanelLayout(); - - addtslPanelListeners(); - - // init curvtec info Panel - initCurVtecPanel(); - - // init prevvtec info Panel - initPrevVtecPanel(); - - // create window control button - initWindowButtonPanel(); - - // create the _buttonPanel including _curvtecPanel, _prevvtecPanel and - // _windowButtonPanel - _buttonPanel = new JPanel(); - - GridBagConstraints buttonGbc = new GridBagConstraints(); - buttonGbc.fill = GridBagConstraints.BOTH; - - buttonGbc.insets = new Insets(2,2,2,2); - buttonGbc.anchor = GridBagConstraints.NORTHWEST; - buttonGbc.weightx = 1; - buttonGbc.weighty = 1; - _buttonPanel.setPreferredSize(new Dimension(1200,280)); - - _buttonPanel.setLayout(new GridBagLayout()); - - addComponent(_buttonPanel, _curvtecPanel, buttonGbc, 0, 0, 1, 3, 1, 0); - addComponent(_buttonPanel, _prevvtecPanel, buttonGbc, 1, 0, 1, 3, 3, 0); - addComponent(_buttonPanel, _windowButtonPanel, buttonGbc, 0, 10, 5, 1, 1, 1); - - //create main panel including _tslPanel(canvas) and _buttonPanel - _mainPanel = new JPanel(); - - GridBagLayout layoutMgr = new GridBagLayout(); - - GridBagConstraints mainGbc = new GridBagConstraints(); - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - //set size for the _mainPanel including the _tslPanel and _buttonPanel - _mainPanel.setPreferredSize(new Dimension(1200,920)); - - _mainPanel.setLayout(layoutMgr); - - // add components to the main panel - - //setJMenuBar(_menuBar); - addComponent(_mainPanel, _tslPanel, mainGbc, 0, 0, 3, 9, 1, 1); - addComponent(_mainPanel, _buttonPanel, mainGbc, 0, 10, 3, 3, 1, 0); - - //add the _mainPanel to the Frame and initialize the frame - this.getContentPane().add(_mainPanel); - - // pack the two panels to a prefererred size and layouts - this.pack(); - - return; - } - - //--------------------------------------------------------------------- - private void initCurVtecPanel() - { - String toolTipText = null; - String selected_curSignif = null; - String selected_curSeverity = null; - String selected_curCause = null; - String selected_curRecord = null; - - Dimension panelDimension = new Dimension(500, 250); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - // get _currentTime; - - _currentTime = System.currentTimeMillis(); - - _curvtecPanel = new JPanel(); - _curvtecPanel.setPreferredSize(panelDimension); - - JPanel panel = _curvtecPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - _curvtecPanelLabel = new JLabel("Proposed VTEC Information:"); - - // init Action ComboBoxapplication - _curvtecActionComboBoxLabel = new JLabel("Action:"); - _selected_curAction = _fpCurPrevVtecData.getcurAction(); - _curvtecActionComboBox.setSelectedItem(_selected_curAction); - - // init Phenom ComboBoxapplication - _curvtecPhenomComboBoxLabel = new JLabel("Phenom:"); - _selected_curPhenom = _fpCurPrevVtecData.getcurPhenom(); - _curvtecPhenomComboBox.setSelectedItem(_selected_curPhenom); - - // init Signif ComboBoxapplication - _curvtecSignifComboBoxLabel = new JLabel(" Signif:"); - selected_curSignif = _fpCurPrevVtecData.getcurSignif(); - if (selected_curSignif.equals("A")) - _selected_curSignif_str = "A (wAtch)"; - else if (selected_curSignif.equals("S")) - _selected_curSignif_str = "S (Statement)"; - else if (selected_curSignif.equals("W")) - _selected_curSignif_str = "W (Warning)"; - else if (selected_curSignif.equals("Y")) - _selected_curSignif_str = "Y (advisorY)"; - - _curvtecSignifComboBox.setSelectedItem(_selected_curSignif_str); - - // init Severity ComboBoxapplication - _curvtecSeverityComboBoxLabel = new JLabel("Severity:"); - selected_curSeverity = _fpCurPrevVtecData.getcurSeverity(); - if (selected_curSeverity.equals("0")) - _selected_curSeverity_str = "0 (N/A)"; - else if (selected_curSeverity.equals("1")) - _selected_curSeverity_str = "1 (Minor)"; - else if (selected_curSeverity.equals("2")) - _selected_curSeverity_str = "2 (Moderate)"; - else if (selected_curSeverity.equals("3")) - _selected_curSeverity_str = "3 (Major)"; - else if (selected_curSeverity.equals("N")) - _selected_curSeverity_str = "N (None)"; - else if (selected_curSeverity.equals("U")) - _selected_curSeverity_str = "U (Unknown)"; - - _curvtecSeverityComboBox.setSelectedItem(_selected_curSeverity_str); - - // init Immediate Cause ComboBox - _curvtecICComboBoxLabel = new JLabel("Cause:"); - selected_curCause = _fpCurPrevVtecData.getcurCause(); - - if (selected_curCause.equals("DM")) - _selected_curCause_str = "DM (Dam Fail)"; - if (selected_curCause.equals("DR")) - _selected_curCause_str = "DR (Dam Rel)"; - if (selected_curCause.equals("ER")) - _selected_curCause_str = "ER (Exc Rain)"; - if (selected_curCause.equals("ET")) - _selected_curCause_str = "ET (Flow Tidal)"; - if (selected_curCause.equals("FS")) - _selected_curCause_str = "FS (Surge)"; - if (selected_curCause.equals("FT")) - _selected_curCause_str = "FT (Fld/Tide)"; - if (selected_curCause.equals("GO")) - _selected_curCause_str = "GO (Glacial)"; - if (selected_curCause.equals("IC")) - _selected_curCause_str = "IC (Ice Mix)"; - if (selected_curCause.equals("IJ")) - _selected_curCause_str = "IJ (Ice Jam)"; - if (selected_curCause.equals("MC")) - _selected_curCause_str = "MC (Multiple)"; - if (selected_curCause.equals("OT")) - _selected_curCause_str = "OT (Other)"; - if (selected_curCause.equals("RS")) - _selected_curCause_str = "RS (Rain/Snow)"; - if (selected_curCause.equals("SM")) - _selected_curCause_str = "SM (Snow Melt)"; - if (selected_curCause.equals("UU")) - _selected_curCause_str = "UU (Unknown)"; - if (selected_curCause.equals("WT")) - _selected_curCause_str = "WT (Wind/Tidal)"; - - _curvtecICComboBox.setSelectedItem(_selected_curCause_str); - - // init Record ComboBoxapplication - _curvtecRecordComboBoxLabel = new JLabel(" Record:"); - selected_curRecord = _fpCurPrevVtecData.getcurRecord(); - if (selected_curRecord.equals("NO")) - _selected_curRecord_str = "NO (NotExp)"; - else if (selected_curRecord.equals("NR")) - _selected_curRecord_str = "NR (Near)"; - else if (selected_curRecord.equals("OO")) - _selected_curRecord_str = "OO (N/A)"; - else if (selected_curRecord.equals("UU")) - _selected_curRecord_str = "UU (None)"; - - _curvtecRecordComboBox.setSelectedItem(_selected_curRecord_str); - - // init Current VTEC BeginTime textfield - toolTipText = "Proposed VTEC Event Begin Time. Click on Text Box to edit."; - _curvtecBeginTimeLabel = new JLabel("Begin Time:"); - _curvtecBeginTimeLabel.setToolTipText(toolTipText); - // this constructor to get the date/time in minute. - _curvtecBeginTimeTextField = new DateTimeTextField(getCurVtecBeginTime(), this, - "Begin", 30, true); - _selected_curBeginTime = getCurVtecBeginTime(); - if (_forceSetBeginTimeMissing == true) - { - _curvtecBeginTimeTextField.setText("MSG"); - - } - else if (_forceSetBeginTimeCurrent == true) - { - _curvtecBeginTimeTextField.setText("CURRENT"); - - } - - _curvtecBeginTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - - - // init radio button for set begintime as missing - _curvtecBeginTimeSetMissingRadioButton = new JRadioButton("Set MSG", - _forceSetBeginTimeMissing); - _curvtecBeginTimeSetMissingRadioButton.addActionListener(new SelectBeginTimeMissingRadioButtonListener()); - - // init radio button for set begintime as current - _curvtecBeginTimeSetCurrentRadioButton = new JRadioButton("Set CURRENT", - _forceSetBeginTimeCurrent); - - _curvtecBeginTimeSetCurrentRadioButton.addActionListener(new SelectBeginTimeCurrentRadioButtonListener()); - - // init radio button for set begintime as regular - _curvtecBeginTimeRadioButton = new JRadioButton("Set Date/Time", - _forceSetBeginTime); - _curvtecBeginTimeRadioButton.addActionListener(new SelectBeginTimeRadioButtonListener()); - - // create ButtonGroup - ButtonGroup curvtecBeginTimeButtonGroup = new ButtonGroup(); - curvtecBeginTimeButtonGroup.add(_curvtecBeginTimeSetMissingRadioButton); - curvtecBeginTimeButtonGroup.add(_curvtecBeginTimeSetCurrentRadioButton); - curvtecBeginTimeButtonGroup.add(_curvtecBeginTimeRadioButton); - - // init Current VTEC EndTime textfield - toolTipText = "Proposed VTEC Event End Time. Click on Text Box to edit."; - _curvtecEndTimeLabel = new JLabel("End Time:"); - _curvtecEndTimeLabel.setToolTipText(toolTipText); - _curvtecEndTimeTextField = new DateTimeTextField(getCurVtecEndTime(), this, - "End", 30, true); - _selected_curEndTime = getCurVtecEndTime(); - - if (_forceSetEndTimeMissing == true) - { - _curvtecEndTimeTextField.setText("MSG"); - } - else if (_forceSetEndTimeCurrent == true) - { - _curvtecEndTimeTextField.setText("CURRENT"); - - } - - _curvtecEndTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - - - // init radio button for set end time as missing - _curvtecEndTimeSetMissingRadioButton = new JRadioButton("Set MSG", - _forceSetEndTimeMissing); - _curvtecEndTimeSetMissingRadioButton.addActionListener(new SelectEndTimeMissingRadioButtonListener()); - - // init radio button for set end time as current - _curvtecEndTimeSetCurrentRadioButton = new JRadioButton("Set CURRENT", - _forceSetEndTimeCurrent); - _curvtecEndTimeSetCurrentRadioButton.addActionListener(new SelectEndTimeCurrentRadioButtonListener()); - - // init radio button for set end time as regular - _curvtecEndTimeRadioButton = new JRadioButton("Set Date/Time", - _forceSetEndTime); - - _curvtecEndTimeRadioButton.addActionListener(new SelectEndTimeRadioButtonListener()); - - - // create ButtonGroup - ButtonGroup curvtecEndTimeButtonGroup = new ButtonGroup(); - curvtecEndTimeButtonGroup.add(_curvtecEndTimeSetMissingRadioButton); - curvtecEndTimeButtonGroup.add(_curvtecEndTimeSetCurrentRadioButton); - curvtecEndTimeButtonGroup.add(_curvtecEndTimeRadioButton); - - // init Current VTEC event rise above fs time - toolTipText = "Proposed VTEC Event Rise Above Flood Stage Time. Click on Text Box to edit."; - _curvtecRiseTimeLabel = new JLabel("AbvFld Time:"); - _curvtecRiseTimeLabel.setToolTipText(toolTipText); - _curvtecRiseTimeTextField = new DateTimeTextField(getCurVtecRiseTime(), this, - "AbvFld", - 30, true); - _selected_curRiseTime = getCurVtecRiseTime(); - if (_forceSetRiseTimeMissing == true) - { - _curvtecRiseTimeTextField.setText("MSG"); - } - - _curvtecRiseTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - // init checkbox for set risetime as missing - _curvtecRiseTimeSetMissingCheckBox = new JCheckBox("Set MSG", - _forceSetRiseTimeMissing); - - _curvtecRiseTimeSetMissingCheckBox.addActionListener(new ChangeRiseTimeMissingCheckBoxListener()); - - // init Current VTEC event crest time - toolTipText = "Proposed VTEC Event Crest Time. Click on Text Box to edit."; - _curvtecCrestTimeLabel = new JLabel("Crest Time:"); - _curvtecCrestTimeLabel.setToolTipText(toolTipText); - _curvtecCrestTimeTextField = new DateTimeTextField(getCurVtecCrestTime(), this, - "Crest", - 30, true); - _selected_curCrestTime = getCurVtecCrestTime(); - if (_forceSetCrestTimeMissing == true) - { - _curvtecCrestTimeTextField.setText("MSG"); - } - _curvtecCrestTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - // init checkbox for set cresttime as missing - _curvtecCrestTimeSetMissingCheckBox = new JCheckBox("Set MSG", - _forceSetCrestTimeMissing); - - _curvtecCrestTimeSetMissingCheckBox.addActionListener(new ChangeCrestTimeMissingCheckBoxListener()); - - // init Crest Value textfield - toolTipText = "Proposed VTEC Crest Value. Click on Text Box to edit. Record and Severity" + - " fields may automatically change if crest value is changed"; - _curvtecCrestValueLabel = new JLabel("Crest Value:"); - _curvtecCrestValueLabel.setToolTipText(toolTipText); - _curvtecCrestValueTextField = new JTextField(getCurVtecCrestValue()); - _curCrestValueStr = getCurVtecCrestValue().trim(); - _selected_curCrestValue_str = _curCrestValueStr; - - // init Current VTEC event fall time - toolTipText = "Proposed VTEC Event Fall Below Flood Stage Time. Click on Text Box to edit."; - _curvtecFallTimeLabel = new JLabel("BlwFld Time:"); - _curvtecFallTimeLabel.setToolTipText(toolTipText); - _curvtecFallTimeTextField = new DateTimeTextField(getCurVtecFallTime(), this, - "BlwFld", - 40, true); - _selected_curFallTime = getCurVtecFallTime(); - if (_forceSetFallTimeMissing == true) - { - _curvtecFallTimeTextField.setText("MSG"); - } - _curvtecFallTimeTextField.getDocument().addDocumentListener(new UpdateVtecTimeDocumentListener()); - - // init checkbox for set falltime as missing - _curvtecFallTimeSetMissingCheckBox = new JCheckBox("Set MSG", - _forceSetFallTimeMissing); - - _curvtecFallTimeSetMissingCheckBox.addActionListener(new ChangeFallTimeMissingCheckBoxListener()); - - //JButton _curvtecSaveChangesButton - _curvtecSaveChangesButton = new JButton("Save Changes"); - _curvtecSaveChangesButton.setEnabled(true); - _curvtecSaveChangesButton.addActionListener( new SaveChangeListener()); - - //JButton _curvtecResetButton - _curvtecResetButton = new JButton("Reset"); - _curvtecResetButton.setEnabled(true); - _curvtecResetButton.addActionListener( new ResetListener()); - - // Separate - JSeparator separator = new JSeparator(JSeparator.HORIZONTAL); - - // add all component to panel - // col, row numCols numRows Wcol wrow - - addComponent(panel, _curvtecPanelLabel, gbc, 0, 0, 2, 1, 1, 0); - addComponent(panel, _curvtecActionComboBoxLabel, gbc, 0, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecActionComboBox, gbc, 1, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecPhenomComboBoxLabel, gbc, 2, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecPhenomComboBox, gbc, 3, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecSignifComboBoxLabel, gbc, 4, 1, 1, 1, 1, 0); - addComponent(panel, _curvtecSignifComboBox, gbc, 5, 1, 1, 1, 1, 0); - - - addComponent(panel, _curvtecSeverityComboBoxLabel,gbc, 0, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecSeverityComboBox, gbc, 1, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecICComboBoxLabel, gbc, 2, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecICComboBox, gbc, 3, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecRecordComboBoxLabel, gbc, 4, 2, 1, 1, 1, 0); - addComponent(panel, _curvtecRecordComboBox, gbc, 5, 2, 1, 1, 1, 0); - - addComponent(panel, _curvtecBeginTimeLabel, gbc, 0, 3, 1, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeTextField, gbc, 1, 3, 2, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeSetMissingRadioButton,gbc,3,3,1, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeSetCurrentRadioButton,gbc,4,3,1, 1, 1, 0); - addComponent(panel, _curvtecBeginTimeRadioButton, gbc, 5, 3, 1, 1, 1, 0); - - addComponent(panel, _curvtecEndTimeLabel, gbc, 0, 4, 1, 1, 1, 0); - addComponent(panel, _curvtecEndTimeTextField, gbc, 1, 4, 2, 1, 1, 0); - addComponent(panel, _curvtecEndTimeSetMissingRadioButton,gbc,3,4, 1, 1, 1, 0); - addComponent(panel, _curvtecEndTimeSetCurrentRadioButton,gbc,4,4, 1, 1, 1, 0); - addComponent(panel, _curvtecEndTimeRadioButton, gbc, 5, 4, 1, 1, 1, 0); - - addComponent(panel, _curvtecRiseTimeLabel, gbc, 0, 5, 1, 1, 1, 0); - addComponent(panel, _curvtecRiseTimeTextField, gbc, 1, 5, 2, 1, 1, 0); - addComponent(panel, _curvtecRiseTimeSetMissingCheckBox, gbc, 3, 5, 1, 1, 1, 0); - - addComponent(panel, _curvtecCrestTimeLabel, gbc, 0, 6, 1, 1, 1, 0); - addComponent(panel, _curvtecCrestTimeTextField, gbc, 1, 6, 2, 1, 1, 0); - addComponent(panel, _curvtecCrestTimeSetMissingCheckBox, gbc, 3, 6,1, 1, 1, 0); - - addComponent(panel, _curvtecCrestValueLabel, gbc, 4, 6, 1, 1, 1, 0); - addComponent(panel, _curvtecCrestValueTextField, gbc, 5, 6, 1, 1, 1, 0); - - addComponent(panel, _curvtecFallTimeLabel, gbc, 0, 7, 1, 1, 1, 0); - addComponent(panel, _curvtecFallTimeTextField, gbc, 1, 7, 2, 1, 1, 0); - addComponent(panel, _curvtecFallTimeSetMissingCheckBox, gbc, 3, 7, 1, 1, 1, 0); - addComponent(panel, separator, gbc, 0, 8, 6, 1, 1, 0); - //addComponent(panel, _curvtecUpdateGraphButton, gbc, 0, 9, 2, 1, 1, 0); - addComponent(panel, _curvtecResetButton, gbc, 1, 9, 2, 1, 1, 0); - addComponent(panel, _curvtecSaveChangesButton, gbc, 3, 9, 2, 1, 1, 0); - - return; - - } - - //--------------------------------------------------------------------- - private void initPrevVtecPanel() - { - Dimension panelDimension = new Dimension(550, 250); - - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(4, 4, 4, 4); - gbc.weightx = 1; - gbc.weighty = 1; - - _prevvtecPanel = new JPanel(); - _prevvtecPanel.setPreferredSize(panelDimension); - - JPanel panel = _prevvtecPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - // Just display previous event's VTEC info, not allow customize - _prevvtecpanelLabel = new JLabel("Previous VTEC Information:"); - - _prevvtecActionLabel = new JLabel("Action:"); - _prevvtecActionTextField = new JTextField(getPrevVtecAction()); - _prevvtecActionTextField.setEditable(false); - - _prevvtecICLabel = new JLabel("Cause:"); - _prevvtecICTextField = new JTextField(getPrevVtecIC()); - _prevvtecICTextField.setEditable(false); - - _prevvtecRecordLabel = new JLabel("Record:"); - _prevvtecRecordTextField = new JTextField(getPrevVtecRecord()); - _prevvtecRecordTextField.setEditable(false); - - _prevvtecPhenomLabel = new JLabel("Phenom:"); - _prevvtecPhenomTextField = new JTextField(getPrevVtecPhenom()); - _prevvtecPhenomTextField.setEditable(false); - - _prevvtecSignifLabel = new JLabel("Signif:"); - _prevvtecSignifTextField = new JTextField(getPrevVtecSignif()); - _prevvtecSignifTextField.setEditable(false); - - _prevvtecSeverityLabel = new JLabel("Severity:"); - _prevvtecSeverityTextField = new JTextField(getPrevVtecSeverity()); - _prevvtecSeverityTextField.setEditable(false); - - // init previous VTEC BeginTime textfield - _prevvtecBeginTimeLabel = new JLabel("Begin Time:"); - _prevvtecBeginTimeTextField = new JTextField(getPrevVtecBeginTime()); - _prevvtecBeginTimeTextField.setEditable(false); - - // init previous VTEC EndTime textfield - _prevvtecEndTimeLabel = new JLabel("End Time:"); - _prevvtecEndTimeTextField = new JTextField(getPrevVtecEndTime()); - _prevvtecEndTimeTextField.setEditable(false); - - // init pervious VTEC event rise above fs time - _prevvtecRiseTimeLabel = new JLabel("AbvFld Time:"); - _prevvtecRiseTimeTextField = new JTextField(getPrevVtecRiseTime()); - _prevvtecRiseTimeTextField.setEditable(false); - - // init previous VTEC event rise type - _prevvtecRiseTypeLabel = new JLabel("AbvFld Type:"); - _prevvtecRiseTypeTextField = new JTextField(getPrevVtecRiseType()); - _prevvtecRiseTypeTextField.setEditable(false); - - // init previous VTEC event crest time - _prevvtecCrestTimeLabel = new JLabel("Crest Time:"); - _prevvtecCrestTimeTextField = new JTextField(getPrevVtecCrestTime()); - _prevvtecCrestTimeTextField.setEditable(false); - - // init previous VTEC event crest value - _prevvtecCrestValueLabel = new JLabel("Crest Value:"); - _prevvtecCrestValueTextField = new JTextField(getPrevVtecCrestValue()); - _prevvtecCrestValueTextField.setEditable(false); - - // init previous VTEC event crest type - _prevvtecCrestTypeLabel = new JLabel("Crest Type:"); - _prevvtecCrestTypeTextField = new JTextField(getPrevVtecCrestType()); - _prevvtecCrestTypeTextField.setEditable(false); - - // init previous VTEC event fall time - _prevvtecFallTimeLabel = new JLabel("BlwFld Time:"); - _prevvtecFallTimeTextField = new JTextField(getPrevVtecFallTime()); - _prevvtecFallTimeTextField.setEditable(false); - - // init previous VTEC event fall type - _prevvtecFallTypeLabel = new JLabel("BlwFld Type:"); - _prevvtecFallTypeTextField = new JTextField(getPrevVtecFallType()); - _prevvtecFallTypeTextField.setEditable(false); - - //init previous VTEC event product time - _prevvtecProductTimeLabel = new JLabel("Product Time:"); - _prevvtecProductTimeTextField = new JTextField(getPrevVtecProductTime()); - _prevvtecProductTimeTextField.setEditable(false); - - - // add components into panel - // col, row numCols numRows Wcol wrow - addComponent(panel, _prevvtecpanelLabel, gbc, 0, 0, 2, 1, 1, 0); - addComponent(panel, _prevvtecActionLabel, gbc, 0, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecActionTextField, gbc, 1, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecPhenomLabel, gbc, 2, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecPhenomTextField, gbc, 3, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecSignifLabel, gbc, 4, 1, 1, 1, 1, 0); - addComponent(panel, _prevvtecSignifTextField, gbc, 5, 1, 1, 1, 1, 0); - - addComponent(panel, _prevvtecSeverityLabel, gbc, 0, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecSeverityTextField, gbc, 1, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecICLabel, gbc, 2, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecICTextField, gbc, 3, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecRecordLabel, gbc, 4, 2, 1, 1, 1, 0); - addComponent(panel, _prevvtecRecordTextField, gbc, 5, 2, 1, 1, 1, 0); - - - addComponent(panel, _prevvtecBeginTimeLabel, gbc, 0, 3, 1, 1, 1, 0); - addComponent(panel, _prevvtecBeginTimeTextField, gbc, 1, 3, 3, 1, 1, 0); - addComponent(panel, _prevvtecEndTimeLabel, gbc, 0, 4, 1, 1, 1, 0); - addComponent(panel, _prevvtecEndTimeTextField, gbc, 1, 4, 3, 1, 1, 0); - addComponent(panel, _prevvtecRiseTimeLabel, gbc, 0, 5, 1, 1, 1, 0); - addComponent(panel, _prevvtecRiseTimeTextField, gbc, 1, 5, 3, 1, 1, 0); - addComponent(panel, _prevvtecRiseTypeLabel, gbc, 4, 5, 1, 1, 1, 0); - addComponent(panel, _prevvtecRiseTypeTextField, gbc, 5, 5, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestTimeLabel, gbc, 0, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestTimeTextField, gbc, 1, 6, 3, 1, 1, 0); - addComponent(panel, _prevvtecCrestTypeLabel, gbc, 4, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestTypeTextField,gbc, 5, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestValueLabel, gbc, 6, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecCrestValueTextField, gbc, 7, 6, 1, 1, 1, 0); - addComponent(panel, _prevvtecFallTimeLabel, gbc, 0, 7, 1, 1, 1, 0); - addComponent(panel, _prevvtecFallTimeTextField, gbc, 1, 7, 3, 1, 1, 0); - addComponent(panel, _prevvtecFallTypeLabel, gbc, 4, 7, 1, 1, 1, 0); - addComponent(panel, _prevvtecFallTypeTextField, gbc, 5, 7, 1, 1, 1, 0); - addComponent(panel, _prevvtecProductTimeLabel, gbc, 0, 8, 1, 1, 1, 0); - addComponent(panel, _prevvtecProductTimeTextField,gbc, 1, 8, 3, 1, 1, 0); - - return; - - } - - //--------------------------------------------------------------------- - private void initWindowButtonPanel() - { - Dimension panelDimension = new Dimension(980, 100); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - _windowButtonPanel = new JPanel(); - _windowButtonPanel.setPreferredSize(panelDimension); - - JPanel panel = _windowButtonPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - _closeButton = new JButton("Close"); - _closeButton.addActionListener(new CloseListener()); - - // add components into panel - // col, row numCols numRows Wcol wrow - addComponent(panel, _closeButton, gbc, 0, 0, 0, 0, 0, 0); - - return; - - } - //----------------------------------------------------------------- - private void settslPanelLayout() - { - _tslPanel.setLayout(new GridBagLayout()); - GridBagConstraints mainPanelGbc = new GridBagConstraints(); - mainPanelGbc.fill = GridBagConstraints.BOTH; - - if (_canvas == null) - { - System.out.println("Canvas is null"); - } - - // add components into panel - // col, row numCols numRows Wcol wrow - addComponent(_tslPanel, _canvas, mainPanelGbc, 0, 0, 1, 1, 1, 1); - - return; - } - - //----------------------------------------------------------------- - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - //----------------------------------------------------------------- - - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - // for screencapture button - ScreenCaptureActionListener screenCaptureActionListener = - new ScreenCaptureActionListener(this, FpVtecInfoFrame.this); - - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new CloseListener()); - menu.add(menuItem); - - - // create a button directly on the menuBar - - Color menuBarColor = _menuBar.getBackground(); - Border invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - JButton saveButton = new JButton(" Save Screen "); - saveButton.addActionListener(screenCaptureActionListener); - saveButton.setBorder(invisibleBorder); - saveButton.setSize(60, 30); - String saveButtonTooltipText = "Capture the screen to a file."; - saveButton.setToolTipText(saveButtonTooltipText); - _menuBar.add(saveButton); - - - HelpActionListener helpActionListener = new HelpActionListener(); - JButton helpButton = new JButton("Help"); - helpButton.addActionListener(helpActionListener); - helpButton.setBorder(invisibleBorder); - helpButton.setSize(60, 30); - _menuBar.add(helpButton); - - - //add to the Frame - setJMenuBar(_menuBar); - - return; - } - - //----------------------------------------------------------------- - - private void addtslPanelListeners() - { - - //allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - } - //-----------------------------------------------------------------\ - - private void close() - { - if (_exitOnClose) - { - FpVtecInfoFrame.this.setVisible(false); - - dispose(); - - //System.exit(0); comment out, just close the SeriesTime/VTEC window, not - // main application - } - } - - private void closeWithoutSaving() - { - - _lastUpdateTime = CLOSED_BUT_NOT_SAVED; - - if (_exitOnClose) - { - FpVtecInfoFrame.this.setVisible(false); - dispose(); - - //System.exit(0); comment out, just close the SeriesTime/VTEC window, not - // main application - } - } - - //----------------------------------------------------------------- - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - closeWithoutSaving(); - } - } - - //----------------------------------------------------------------- - - - private class FrameCloseWindowListener extends WindowAdapter - { - public void windowClosing(WindowEvent evt) - { - closeWithoutSaving(); - } - - } - - public void showMessage() - { - long obsCutOffTime = _application.getStartTime(); - long fcstCutOffTime = _application.getEndTime(); - String obsCutOffTimeString = ""; - String fcstCutOffTimeString = ""; - - if (obsCutOffTime > 0 && fcstCutOffTime > 0) - { - obsCutOffTimeString = DbTimeHelper.getDateTimeStringFromLongTime(obsCutOffTime); - fcstCutOffTimeString = DbTimeHelper.getDateTimeStringFromLongTime(fcstCutOffTime); - } - - String message = "The YELLOW time series is observed data.\n" + - "The GREEN time series is forecast data. \n" + - "The vertical WHITE line with 'N' is current time.\n" + - "The vertical BLUE line with 'B' is proposed vtec event's begin time.\n" + - "The vertical GREEN line with 'E' is proposed vtec event's end time. \n" + - "The vertical ORANGE line with 'R' is proposed vtec event's rise above flood level time.\n" + - "The vertical RED line with 'C' is proposed vtec event's crest time.\n" + - "The vertical MEGENTA line with 'F' is proposed vtec event's fall below flood level time.\n" + - "The horizontal YELLOW line is action level.\n" + - "The horizontal ORANGE line is flood level.\n" + - "The horizontal RED line is moderate flood level. \n" + - "The horizontal MEGENTA line is major flood level. \n" + - "The timeseries window starts from " + obsCutOffTimeString + "Z to " + - fcstCutOffTimeString + "Z"; - - DialogHelper.displayMessageDialog(this, message, "TimeSeries/VTEC Help"); - } - // ------------------------------------------------------------------------------------ - - private class HelpActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - showMessage(); - } - - } - - // ------------------------------------------------------------------------------------- - // action for the button "Update " - /*private class UpdateGraphListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - updateGraph(); - return; - } - } */ - // ------------------------------------------------------------------------------------ - public void updateGraph() - { - // get the time from time text fields, set them to - //_fpCurPrevVtecData, and TimeHolder - - long currentTime = System.currentTimeMillis(); - - // for the begintime - if (_curvtecBeginTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurBeginTime(MISSING_INT); - _application.getCurVtecBeginTimeHolder().setTime(MISSING_INT); - } - else if (_curvtecBeginTimeTextField.getText().equals("CURRENT")) - { - _fpCurPrevVtecData.setcurBeginTime(-1); - _application.getCurVtecBeginTimeHolder().setTime(currentTime); - } - else - { - _fpCurPrevVtecData.setcurBeginTime(_curvtecBeginTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecBeginTimeHolder().setTime(_curvtecBeginTimeTextField.getTime()); - } - - - // for the end time - if (_curvtecEndTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurEndTime(MISSING_INT); - _application.getCurVtecEndTimeHolder().setTime(MISSING_INT); - } - else if (_curvtecEndTimeTextField.getText().equals("CURRENT")) - { - _fpCurPrevVtecData.setcurEndTime(-1); - _application.getCurVtecEndTimeHolder().setTime(currentTime); - } - else - { - _fpCurPrevVtecData.setcurEndTime(_curvtecEndTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecEndTimeHolder().setTime(_curvtecEndTimeTextField.getTime()); - } - - // for the rise time - if (_curvtecRiseTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurRiseTime(MISSING_INT); - _application.getCurVtecRiseTimeHolder().setTime(MISSING_INT); - } - else - { - _fpCurPrevVtecData.setcurRiseTime(_curvtecRiseTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecRiseTimeHolder().setTime(_curvtecRiseTimeTextField.getTime()); - } - - // for the crest time - if (_curvtecCrestTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurCrestTime(MISSING_INT); - _application.getCurVtecCrestTimeHolder().setTime(MISSING_INT); - } - else - { - _fpCurPrevVtecData.setcurCrestTime(_curvtecCrestTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecCrestTimeHolder().setTime(_curvtecCrestTimeTextField.getTime()); - } - - // for the fall time - if (_curvtecFallTimeTextField.getText().equals("MSG")) - { - _fpCurPrevVtecData.setcurFallTime(MISSING_INT); - _application.getCurVtecFallTimeHolder().setTime(MISSING_INT); - } - else - { - _fpCurPrevVtecData.setcurFallTime(_curvtecFallTimeTextField.getTime()/MILLIS_PER_SECOND); - _application.getCurVtecFallTimeHolder().setTime(_curvtecFallTimeTextField.getTime()); - } - - // repaint the canvas - _application.redrawCanvas(); - - } - - - // ----------------------------------------------------------------------- - public void updateCurDateTimeTextField() - { - long new_curVTECBeginTime = 0; - long new_curVTECEndTime = 0; - long new_curVTECRiseTime = 0; - long new_curVTECCrestTime = 0; - long new_curVTECFallTime = 0; - - _graphicalChange = true; - - new_curVTECBeginTime = (_application.getCurVtecBeginTimeHolder()).getTime(); - if (new_curVTECBeginTime == MISSING_INT) - { - _curvtecBeginTimeSetMissingRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setText("MSG"); - } - else if (_curvtecBeginTimeTextField.getText().equals("CURRENT") && - (_dragged_line != TimeLineAdjustmentListener.BEGIN_DRAGGED)) - { - _curvtecBeginTimeSetCurrentRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setText("CURRENT"); - } - else - { - _curvtecBeginTimeRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setTime(new_curVTECBeginTime); - } - - new_curVTECEndTime = (_application.getCurVtecEndTimeHolder()).getTime(); - if (new_curVTECEndTime == MISSING_INT) - { - _curvtecEndTimeSetMissingRadioButton.setSelected(true); - _curvtecEndTimeTextField.setText("MSG"); - } - else if (_curvtecEndTimeTextField.getText().equals("CURRENT") && - (_dragged_line != TimeLineAdjustmentListener.END_DRAGGED )) - { - _curvtecEndTimeSetCurrentRadioButton.setSelected(true); - _curvtecEndTimeTextField.setText("CURRENT"); - } - else - { - _curvtecEndTimeRadioButton.setSelected(true); - _curvtecEndTimeTextField.setTime(new_curVTECEndTime); - } - - new_curVTECRiseTime = (_application.getCurVtecRiseTimeHolder()).getTime(); - if (new_curVTECRiseTime == MISSING_INT) - { - _curvtecRiseTimeSetMissingCheckBox.setSelected(true); - _curvtecRiseTimeTextField.setText("MSG"); - } - else - { - _curvtecRiseTimeSetMissingCheckBox.setSelected(false); - _curvtecRiseTimeTextField.setTime(new_curVTECRiseTime); - } - - new_curVTECCrestTime = (_application.getCurVtecCrestTimeHolder()).getTime(); - if (new_curVTECCrestTime == MISSING_INT) - { - _curvtecCrestTimeSetMissingCheckBox.setSelected(true); - _curvtecCrestTimeTextField.setText("MSG"); - } - else - { - _curvtecCrestTimeSetMissingCheckBox.setSelected(false); - _curvtecCrestTimeTextField.setTime(new_curVTECCrestTime); - } - - new_curVTECFallTime = (_application.getCurVtecFallTimeHolder()).getTime(); - if (new_curVTECFallTime == MISSING_INT) - { - _curvtecFallTimeSetMissingCheckBox.setSelected(true); - _curvtecFallTimeTextField.setText("MSG"); - } - else - { - _curvtecFallTimeSetMissingCheckBox.setSelected(false); - _curvtecFallTimeTextField.setTime(new_curVTECFallTime); - } - - _graphicalChange = false; - } - - public void setDraggedLine(long dragged_line) - { - _dragged_line = dragged_line; - - } - public void resetCurVtecPanel() - { - _curvtecActionComboBox.setSelectedItem(_selected_curAction); - _curvtecPhenomComboBox.setSelectedItem(_selected_curPhenom); - _curvtecSignifComboBox.setSelectedItem(_selected_curSignif_str); - _curvtecSeverityComboBox.setSelectedItem(_selected_curSeverity_str); - _curvtecICComboBox.setSelectedItem(_selected_curCause_str); - _curvtecRecordComboBox.setSelectedItem(_selected_curRecord_str); - - // reset to original event begin time - - if (_selected_curBeginTime == MISSING_INT) - { - _curvtecBeginTimeSetMissingRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setText("MSG"); - } - else if (_selected_curBeginTime == -1) - { - _curvtecBeginTimeSetCurrentRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setText("CURRENT"); - } - else - { - _curvtecBeginTimeRadioButton.setSelected(true); - _curvtecBeginTimeTextField.setTime(_selected_curBeginTime); - } - - // reset to original event end time - - if (_selected_curEndTime == MISSING_INT) - { - _curvtecEndTimeSetMissingRadioButton.setSelected(true); - _curvtecEndTimeTextField.setText("MSG"); - } - else if (_selected_curEndTime == -1) - { - _curvtecEndTimeSetCurrentRadioButton.setSelected(true); - _curvtecEndTimeTextField.setText("CURRENT"); - } - else - { - _curvtecEndTimeRadioButton.setSelected(true); - _curvtecEndTimeTextField.setTime(_selected_curEndTime); - } - - // reset to original event rise above flood level time - - if (_selected_curRiseTime == MISSING_INT) - { - _curvtecRiseTimeSetMissingCheckBox.setSelected(true); - _curvtecRiseTimeTextField.setText("MSG"); - } - else - { - _curvtecRiseTimeSetMissingCheckBox.setSelected(false); - _curvtecRiseTimeTextField.setTime(_selected_curRiseTime); - } - - // reset to original event crest above flood level time - - if (_selected_curCrestTime == MISSING_INT) - { - _curvtecCrestTimeSetMissingCheckBox.setSelected(true); - _curvtecCrestTimeTextField.setText("MSG"); - } - else - { - _curvtecCrestTimeSetMissingCheckBox.setSelected(false); - _curvtecCrestTimeTextField.setTime(_selected_curCrestTime); - } - - // reset to original event fall below flood level time - - if (_selected_curFallTime == MISSING_INT) - { - _curvtecFallTimeSetMissingCheckBox.setSelected(true); - _curvtecFallTimeTextField.setText("MSG"); - } - else - { - _curvtecFallTimeSetMissingCheckBox.setSelected(false); - _curvtecFallTimeTextField.setTime(_selected_curFallTime); - } - - - - // reset to original crest value - _curvtecCrestValueTextField.setText(_selected_curCrestValue_str); - - - updateGraph(); - - } - - /*public void resetCurVtecTime() - { - - } - */ - // ---------------------------------------------------------------------------------------- - private class ResetListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - FpVtecInfoFrame.this.resetCurVtecPanel(); - } - } - // ----------------------------------------------------------------------------------------- - private class SaveChangeListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String header = "SaveChangeListener.actionPerformed():"; - Double curCrestValue = -9999.0; - Boolean curCrestValueEdit = false; - StringBuffer outputStringBuffer = new StringBuffer(); - - if ( DialogHelper.displayConfirmDialog( FpVtecInfoFrame.this, "Are you sure you want to save the edits (will update the VTEC Settings window), " + - "and close the TimeSeries/VTEC window?", "Save Changes and Close" ) ) - { - // update file curvteceditfile.dat - String outputfilePath = FpVtecInfoFrame.this.get_dataMgr().get_rpfdataFilePath(); - - String fpvtecinfoOutputFileName = outputfilePath + "curvteceditsaved.dat" ; - - openOutputFile( fpvtecinfoOutputFileName); - - long curTime = System.currentTimeMillis(); - outputStringBuffer.append( "The output file with edits for proposed VTEC information is created on:" - + DbTimeHelper.getDateTimeStringFromLongTime(curTime) + "\n" ); - outputStringBuffer.append("###lid,locname,action,phenom,signif,severity,cause,record,etn,crest_value," + - "begintime,endtime,risetime,cresttime,falltime###" + "\n"); - - String lid = _fpCurPrevVtecData.getLocId(); - String locName = _fpCurPrevVtecData.getLocName(); - String curAction = (String) _curvtecActionComboBox.getSelectedItem(); - - String curPhenom = (String) _curvtecPhenomComboBox.getSelectedItem(); - - String curSignif = (String) _curvtecSignifComboBox.getSelectedItem(); - String sub_curSignif = curSignif.substring(0, 1); - - String curSeverity = (String) _curvtecSeverityComboBox.getSelectedItem(); - String sub_curSeverity = curSeverity.substring(0, 1); - - - String curCause = (String)_curvtecICComboBox.getSelectedItem(); - String sub_curCause = curCause.substring(0, 2); - - String curRecord = (String)_curvtecRecordComboBox.getSelectedItem(); - String sub_curRecord = curRecord.substring(0, 2); - - int curEtn = _fpCurPrevVtecData.getcurEtn(); - String curCrestString = _curvtecCrestValueTextField.getText().trim(); - - if (curCrestString.equals(_curCrestValueStr)) - curCrestValueEdit = false; - else - curCrestValueEdit = true; - - _curCrestValueStr = curCrestString; - - if (curCrestString == null || curCrestString.equals("")) - { - DialogHelper.displayErrorDialog( FpVtecInfoFrame.this, "No crest value entered", "Unable to save" ); - } - else - curCrestValue = Double.valueOf(curCrestString); - - String curBeginTime = _curvtecBeginTimeTextField.getText().trim(); - String curEndTime = _curvtecEndTimeTextField.getText().trim(); - String curRiseTime = _curvtecRiseTimeTextField.getText().trim(); - String curCrestTime = _curvtecCrestTimeTextField.getText().trim(); - String curFallTime = _curvtecFallTimeTextField.getText().trim(); - - /*String curBeginTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecBeginTimeHolder().getTime()).trim(); - String curEndTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecEndTimeHolder().getTime()).trim(); - String curRiseTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecRiseTimeHolder().getTime()).trim(); - String curCrestTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecCrestTimeHolder().getTime()).trim(); - String curFallTime = DbTimeHelper.getDateTimeStringFromLongTime(_application.getCurVtecFallTimeHolder().getTime()).trim(); - */ - - - if (curBeginTime == null || curEndTime == null || curRiseTime == null - || curCrestTime == null || curFallTime == null) - { - DialogHelper.displayErrorDialog( FpVtecInfoFrame.this, "No time entered", "Unable to save" ); - } - - - outputStringBuffer.append(lid + "," + locName + "," + curAction + "," + - curPhenom + "," + sub_curSignif + "," + sub_curSeverity + - "," + sub_curCause + "," + sub_curRecord + "," + curEtn + - "," + curCrestValue + "," + curCrestValueEdit + "," + curBeginTime + "," + - curEndTime +"," + curRiseTime +"," + curCrestTime + - "," + curFallTime); - - _writer.println( outputStringBuffer); - _writer.flush(); - - // update the outputfile timestamp - setLastUpdateTimeToCurrentTime(); - System.out.println(header + "_lastUpdateTime = " + FpVtecInfoFrame.getLastUpdateTime()); - - // close the current TimeSeries/VTEC window - - close(); - - } - - } - } -// ---------------------------------------------------------------- - private static void setLastUpdateTimeToCurrentTime() - { - //return the time in seconds, so divide by 1000 - _lastUpdateTime = System.currentTimeMillis()/1000; - - return; - } - - protected static void setLastUpdateTime(long lastUpdateTimeInSeconds) - { - //return the time in seconds, so divide by 1000 - _lastUpdateTime = lastUpdateTimeInSeconds; - - return; - } - // --------------------------------------------------------------- - public static long getLastUpdateTime() - { - return _lastUpdateTime; - } - -// ------------------------------------------------------------------------ - - private void openOutputFile(String fileName) - { - try - { - if (fileName != null) - { - _outputStream = new BufferedOutputStream( new FileOutputStream(fileName, false) ); - - // _fileIsOpen = true; - } - else //fileName == null - { - _outputStream = System.out; - } - - _writer = new PrintWriter( _outputStream ); - } - catch (java.io.IOException e) - { - System.out.println( e ); - - } - } - - // ------------------------------------------------------------------------------------ - private void initCanvas(int x, int y, - int width, int height) - - { - MeasuringUnit measuringUnit = MeasuringUnit.feet; - - _canvas = new TsPaintableCanvas( - measuringUnit, - x, y, - width, height); - - _canvas.setPreferredSize(_initialSize); - // _canvas.setMinimumSize(_minSize); - - return; - - } //end initCanvas - - - // --------------------------------------------------------------------------------- - /* - * get the current event's begin time for the specified locationId - */ - private long getCurVtecBeginTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurBeginTime() == MISSING_INT) - { - _forceSetBeginTimeMissing = true; - time = MISSING_INT; - } - else if (_fpCurPrevVtecData.getcurBeginTime() == -1) - { - _forceSetBeginTimeCurrent = true; - time = -1; - } - else - { - _forceSetBeginTime = true; - - time = _fpCurPrevVtecData.getcurBeginTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecBeginTime():" + "begintime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's end time for the specified locationId - */ - private long getCurVtecEndTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurEndTime() == MISSING_INT) - { - _forceSetEndTimeMissing = true; - time = MISSING_INT; - } - else if (_fpCurPrevVtecData.getcurEndTime() == -1) - { - _forceSetEndTimeCurrent = true; - time = -1; - } - else - { - _forceSetEndTime = true; - time = _fpCurPrevVtecData.getcurEndTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecEndTime():" + "endtime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's rise above flood stage time for the specified locationId - */ - private long getCurVtecRiseTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurRiseTime() == MISSING_INT) - { - _forceSetRiseTimeMissing = true; - time = MISSING_INT; - } - else - { - _forceSetRiseTimeMissing = false; - time = _fpCurPrevVtecData.getcurRiseTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecRiseTime():" + "risetime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's crest time for the specified locationId - */ - private long getCurVtecCrestTime() - { - long time = -2; - - try - { - if (_fpCurPrevVtecData.getcurCrestTime() == MISSING_INT) - { - _forceSetCrestTimeMissing = true; - time = MISSING_INT; - } - else - { - _forceSetCrestTimeMissing = false; - time = _fpCurPrevVtecData.getcurCrestTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecCrestTime():" + "cresttime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the current event's crest value for the specified locationId - */ - private String getCurVtecCrestValue() - { - double value = -9999.0; - String valuestring = null; - - try - { - value = _fpCurPrevVtecData.getcurCrestValue(); - valuestring = Double.toString(value); - - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecCrestValue():" + "crest value =" + value); - } - return valuestring; - } - // --------------------------------------------------------------------------------- - /* - * get the current event's fall below of flood stage time for the specified locationId - */ - private long getCurVtecFallTime() - { - long time = -2; - - try - { - if ( _fpCurPrevVtecData.getcurFallTime() == MISSING_INT) - { - _forceSetFallTimeMissing = true; - time = MISSING_INT; - } - else - { - _forceSetFallTimeMissing = false; - time = _fpCurPrevVtecData.getcurFallTime() * MILLIS_PER_SECOND; - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getCurVtecFallTime():" + "falltime =" + time); - } - return time; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's action code for the specified locationId - */ - private String getPrevVtecAction() - { - String prevVtecAction = ""; - - try - { - prevVtecAction = _fpCurPrevVtecData.getprevAction(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecAction():" + "Action =" + prevVtecAction); - } - return prevVtecAction; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's Record for the specified locationId - */ - private String getPrevVtecRecord() - { - String prevVtecRecord = ""; - - try - { - prevVtecRecord = _fpCurPrevVtecData.getprevRecord(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecRecord():" + "Record =" + prevVtecRecord); - } - return prevVtecRecord; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's rise type for the specified locationId - */ - private String getPrevVtecRiseType() - { - String prevVtecRiseType = ""; - - try - { - prevVtecRiseType = _fpCurPrevVtecData.getprevRiseType(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecRiseType():" + "Rise Type =" + prevVtecRiseType); - } - return prevVtecRiseType; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's crest type for the specified locationId - */ - private String getPrevVtecCrestType() - { - String prevVtecCrestType = ""; - - try - { - prevVtecCrestType = _fpCurPrevVtecData.getprevCrestType(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecCrestType():" + "Crest Type =" + prevVtecCrestType); - } - return prevVtecCrestType; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's fall type for the specified locationId - */ - private String getPrevVtecFallType() - { - String prevVtecFallType = ""; - - try - { - prevVtecFallType = _fpCurPrevVtecData.getprevFallType(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecFallType():" + "Fall Type =" + prevVtecFallType); - } - return prevVtecFallType; - } - // --------------------------------------------------------------------------------- - /* - * get the previous event's action code for the specified locationId - */ - private String getPrevVtecIC() - { - String prevVtecIC = ""; - - - try - { - prevVtecIC = _fpCurPrevVtecData.getprevCause(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecIC():" + "Immediate Cause =" + prevVtecIC); - } - return prevVtecIC; - } - -// --------------------------------------------------------------------------------- - /* - * get the previous event's phenom code for the specified locationId - */ - private String getPrevVtecPhenom() - { - String prevVtecPhenom = ""; - - try - { - prevVtecPhenom = _fpCurPrevVtecData.getprevPhenom(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecPhenom():" + "Phenom =" + prevVtecPhenom); - } - return prevVtecPhenom; - } - -// --------------------------------------------------------------------------------- - /* - * get the previous event's Signif code for the specified locationId - */ - private String getPrevVtecSignif() - { - String prevVtecSignif = ""; - - try - { - prevVtecSignif = _fpCurPrevVtecData.getprevSignif(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecSignif():" + "Signif =" + prevVtecSignif); - } - return prevVtecSignif; - } - -// --------------------------------------------------------------------------------- - /* - * get the previous event's severity code for the specified locationId - */ - private String getPrevVtecSeverity() - { - String prevVtecSeverity = ""; - - try - { - prevVtecSeverity = _fpCurPrevVtecData.getprevSeverity(); - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecSeverity():" + "Severity =" + prevVtecSeverity); - } - return prevVtecSeverity; - } - // --------------------------------------------------------------------------------- - /* - * get the previous event's Begin Time for the specified locationId - */ - private String getPrevVtecBeginTime() - { - long time = -1; - String timestring = ""; - - try - { - - - time = _fpCurPrevVtecData.getprevBeginTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecBeginTime():" + "begintime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's end time for the specified locationId - */ - private String getPrevVtecEndTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevEndTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecEndTime():" + "endtime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's rise abpve flood stage time for the specified locationId - */ - private String getPrevVtecRiseTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevRiseTime(); - if (time == MISSING_INT ) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecRiseTime():" + "risetime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's crest time for the specified locationId - */ - private String getPrevVtecCrestTime() - { - long time = -1; - String timestring = ""; - try - { - time = _fpCurPrevVtecData.getprevCrestTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if (time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecCrestTime():" + "cresttime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's crest value for the specified locationId - */ - private String getPrevVtecCrestValue() - { - double value = -9999.0; - String valuestring = null; - - try - { - value = _fpCurPrevVtecData.getprevCrestValue(); - if (value != 0.0) - valuestring = Double.toString(value); - - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecCrestValue():" + "crest value =" + value); - } - - return valuestring; - } - - - - // --------------------------------------------------------------------------------- - /* - * get the previous event's fall time for the specified locationId - */ - private String getPrevVtecFallTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevFallTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if ( time != 0) - { - time = time * MILLIS_PER_SECOND; - //timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - timestring = DbTimeHelper.getDateTimeToMinutesStringFromLongTime(time ); - - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecFallTime():" + "falltime =" + time); - } - return timestring; - } - - // --------------------------------------------------------------------------------- - /* - * get the previous event's product time for the specified locationId - */ - private String getPrevVtecProductTime() - { - long time = -1; - String timestring = ""; - - try - { - time = _fpCurPrevVtecData.getprevProductTime(); - if (time == MISSING_INT) - { - timestring = "MSG"; - } - else if ( time != 0) - { - time = time * MILLIS_PER_SECOND; - timestring = DbTimeHelper.getDateTimeStringFromLongTime(time); - } - } - catch (Throwable t) - { - System.out.println("FpVtecInfoFrame().getPrevVtecProductTime():" + "producttime =" + time); - } - return timestring; - } - - // ------------------------------------------------------------------------------ - public FpVtecInfo getApplication() { - return _application; - } - - // -------------------------------------------------------------------------------- - - public void setApplication(FpVtecInfo application) { - this._application = application; - } - - //---------------------------------------------------------------------------------- - private class UpdateVtecTimeDocumentListener implements DocumentListener - { - - public void insertUpdate(DocumentEvent arg0) - { - - if (! _graphicalChange) - { - System.out.println("UpdateVtecTimeDocumentListener.insertUpdate() event used."); - updateGraph(); - } - else - { - System.out.println("UpdateVtecTimeDocumentListener.insertUpdate() event ignored."); - - } - - } - - public void removeUpdate(DocumentEvent arg0) - { - - } - - public void changedUpdate(DocumentEvent arg0) - { - - } - - } - - public FpVtecInfoDataManager get_dataMgr() { - return _dataMgr; - } - - public void set_dataMgr(FpVtecInfoDataManager mgr) { - _dataMgr = mgr; - } - - // action for check box _curvtecRiseTimeSetMissingCheckBox - private class ChangeRiseTimeMissingCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecRiseTimeTextField.setText("MSG"); - } - else - { - _curvtecRiseTimeTextField.setTime(_currentTime); - - } - - updateGraph(); - - } - } - - // action for check box _curvtecCrestTimeSetMissingCheckBox - private class ChangeCrestTimeMissingCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecCrestTimeTextField.setText("MSG"); - - } - else - { - _curvtecCrestTimeTextField.setTime(_currentTime); - - } - - updateGraph(); - - } - } - - // action for check box _curvtecFallTimeSetMissingCheckBox - private class ChangeFallTimeMissingCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecFallTimeTextField.setText("MSG"); - - } - else - { - _curvtecFallTimeTextField.setTime(_currentTime); - - } - - updateGraph(); - - } - - } - - // action for radio button _curvtecBeginTimeSetMissingRadioButton - private class SelectBeginTimeMissingRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecBeginTimeTextField.setText("MSG"); - updateGraph(); - - } - - } - } - - - // action for radio button _curvtecBeginTimeSetCurrentRadioButton - private class SelectBeginTimeCurrentRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecBeginTimeTextField.setText("CURRENT"); - updateGraph(); - } - - } - } - - // action for radio button _curvtecBeginTimeRadioButton - private class SelectBeginTimeRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecBeginTimeTextField.setTime(_currentTime); - updateGraph(); - - } - - } - } - -// action for radio button _curvtecEndTimeSetMissingRadioButton - private class SelectEndTimeMissingRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecEndTimeTextField.setText("MSG"); - updateGraph(); - - } - - } - } - - - // action for radio button _curvtecEndTimeSetCurrentRadioButton - private class SelectEndTimeCurrentRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecEndTimeTextField.setText("CURRENT"); - updateGraph(); - - } - - } - } - - // action for radio button _curvtecEndTimeRadioButton - private class SelectEndTimeRadioButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - AbstractButton abstractButton = (AbstractButton) evt.getSource(); - boolean selected = abstractButton.getModel().isSelected(); - if (selected == true) - { - _curvtecEndTimeTextField.setTime(_currentTime); - updateGraph(); - - } - - } - } - -} diff --git a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/TimeLineAdjustmentListener.java b/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/TimeLineAdjustmentListener.java deleted file mode 100644 index d626f29b30..0000000000 --- a/javaUtilities/hydro/ohd.misc_dialogs/src/ohd/hseb/fp_vtec_info/TimeLineAdjustmentListener.java +++ /dev/null @@ -1,237 +0,0 @@ -package ohd.hseb.fp_vtec_info; - -import java.awt.Point; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; -import java.util.HashMap; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class TimeLineAdjustmentListener extends MouseAdapter implements MouseMotionListener { - - private boolean _button1Down = false; - private boolean _tipShownOnce = false; - - // variables related to keyboard commands - private boolean _hasFocus = false; - private Point _mousePosition = null; - private TimeHolder _beginTimeHolder = null; - private TimeHolder _endTimeHolder = null; - private TimeHolder _riseTimeHolder = null; - private TimeHolder _crestTimeHolder = null; - private TimeHolder _fallTimeHolder = null; - - /*private TimeHolder[] _timeHolderArray = null;*/ - - private Map _timeHolderMap = null; - private TimeHolder _selectedTimeHolder = null; - - // List _pointList = new ArrayList(); - private TsPaintableCanvas _canvas = null; - private FpVtecInfo _worker = null; - - /* define constants */ - protected static final int BEGIN_DRAGGED = -2; - protected static final int END_DRAGGED = -1; - private static long dragged_line = 0; - - // constructor - public TimeLineAdjustmentListener(FpVtecInfo worker, - TsPaintableCanvas canvas, TimeHolder beginTimeHolder, - TimeHolder endTimeHolder, TimeHolder riseTimeHolder, - TimeHolder crestTimeHolder, TimeHolder fallTimeHolder) - { - _beginTimeHolder = beginTimeHolder; - _endTimeHolder = endTimeHolder; - _riseTimeHolder = riseTimeHolder; - _crestTimeHolder = crestTimeHolder; - _fallTimeHolder = fallTimeHolder; - - - /*_timeHolderArray = new TimeHolder[] { beginTimeHolder, endTimeHolder, - riseTimeHolder, crestTimeHolder, fallTimeHolder }; -*/ - /* create a new HashMap _timeHolderMap */ - _timeHolderMap = new HashMap(); - - /* initialize the new HashMap object */ - _timeHolderMap.put("begin", beginTimeHolder); - _timeHolderMap.put("end", endTimeHolder); - _timeHolderMap.put("rise", riseTimeHolder); - _timeHolderMap.put("crest", crestTimeHolder); - _timeHolderMap.put("fall", fallTimeHolder); - - - _canvas = canvas; - _worker = worker; - } - - public void mouseDragged(MouseEvent event) { - String header = "TimeLineAdjustmentListener.mouseDragged(): "; - System.out.println(header + "activated "); - - if (_button1Down) { - Point point = event.getPoint(); - // System.out.println("activated mouseDragged, button = " + button - // ); - // adjustTimeLine(point); - } - - } - - public void mouseMoved(MouseEvent event) { - _mousePosition = event.getPoint(); - // do nothing - } - - public void mousePressed(MouseEvent event) { - String header = "TimeLineAdjustmentListener.mousePressed(): "; - System.out.println(header); - - int button = event.getButton(); - if (button == MouseEvent.BUTTON1) { - _button1Down = true; - _selectedTimeHolder = findClosestTimeHolder(event.getPoint()); - } else { - - } - - return; - - } - - public void mouseReleased(MouseEvent event) { - System.out.println("Precip adjust listener: mouseReleased()"); - int button = event.getButton(); - - if (button == MouseEvent.BUTTON1) { - _button1Down = false; - - adjustTimeLine(event.getPoint()); - _selectedTimeHolder = null; - } - - } - - public void mouseEntered(MouseEvent event) { - // get the focus on this canvas, so that the keyboard commands will work - // on it - // AnalysisWindow.this._precipCanvas.requestFocusInWindow(); - // System.out.println("mouseEntered():" + " requested focus "); - _hasFocus = true; - } - - public void mouseExited(MouseEvent event) { - _hasFocus = false; - } - - public void keyPressed(KeyEvent e) { - - } - - public void keyReleased(KeyEvent e) { - - } - - public void keyTyped(KeyEvent e) { - - } - - // ---------------------------------------------------------------------------------- - private TimeHolder findClosestTimeHolder(Point point) { - long timeInMillis = getTimeFromPoint(point); - - long timeWindowInHours = 3; - final long timeWindowInMillis = timeWindowInHours * TimeHelper.MILLIS_PER_HOUR; - - long timeDiffInMillis = 0; - long bigTimeInMillis = timeWindowInMillis + 1; - long minDiffInMillis = bigTimeInMillis; - - TimeHolder closestTimeHolder = null; - - for (String key : _timeHolderMap.keySet()) - { - TimeHolder timeHolder = _timeHolderMap.get(key); - long timefromtimeholder = timeHolder.getTime(); - - timeDiffInMillis = Math.abs(timeHolder.getTime() - timeInMillis); - - if (timeDiffInMillis < minDiffInMillis) { - minDiffInMillis = timeDiffInMillis; - closestTimeHolder = timeHolder; - - /* determine which line is dragged */ - if (key.equals("begin")) - dragged_line = BEGIN_DRAGGED; - else if (key.equals("end")) - dragged_line = END_DRAGGED; - else - dragged_line = 0; - } - } - - // make sure that the closest one is within the time window - if (minDiffInMillis > timeWindowInMillis) { - closestTimeHolder = null; - dragged_line = 0; - - } - - return closestTimeHolder; - } - - // ---------------------------------------------------------------------------------- - - private long getTimeFromPoint(Point point) { - DataPoint dataPoint = _canvas.getViewport().getDataPoint(point); - - long newTime = (long) Math.floor(dataPoint.getX()); - - newTime /= TimeHelper.MILLIS_PER_HALF_HOUR; - newTime *= TimeHelper.MILLIS_PER_HALF_HOUR; - - return newTime; - } - - private void adjustTimeLine(Point point) { - String header = "TimeLineAdjustment.adjustTimeLine(): "; - - TimeHolder timeHolder = _selectedTimeHolder; - System.out.println(header + "_selectedTimeHolder = " - + _selectedTimeHolder); - if (timeHolder == null) { - return; - } - - long newTime = getTimeFromPoint(point); - - long oldTime = timeHolder.getTime(); - - System.out.println(header - + DbTimeHelper.getDateTimeStringFromLongTime(oldTime) - + " new time = " - + DbTimeHelper.getDateTimeStringFromLongTime(newTime)); - - timeHolder.setTime(newTime); - - System.out.println(header + "time line moved to " - + DbTimeHelper.getDateTimeStringFromLongTime(newTime)); - - _worker.getFrame().setDraggedLine(dragged_line); - _worker.getFrame().updateCurDateTimeTextField(); - _worker.getFrame().updateGraph(); - - } // end adjustTimeLine - -} // end TimeLineAdjustmentListener - -// -------------------------------------------------------------------- - diff --git a/javaUtilities/hydro/ohd.mpe/.classpath b/javaUtilities/hydro/ohd.mpe/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.mpe/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.mpe/.project b/javaUtilities/hydro/ohd.mpe/.project deleted file mode 100644 index b31bb9395b..0000000000 --- a/javaUtilities/hydro/ohd.mpe/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.mpe - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.mpe/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.mpe/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 1f90512afb..0000000000 --- a/javaUtilities/hydro/ohd.mpe/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 09:14:53 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.mpe/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.mpe/META-INF/MANIFEST.MF deleted file mode 100644 index 33e6525e86..0000000000 --- a/javaUtilities/hydro/ohd.mpe/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Mpe -Bundle-SymbolicName: ohd.mpe -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.sshp;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.mpe/build.properties b/javaUtilities/hydro/ohd.mpe/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.mpe/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.mpe/build.xml b/javaUtilities/hydro/ohd.mpe/build.xml deleted file mode 100644 index 3b1a90e57d..0000000000 --- a/javaUtilities/hydro/ohd.mpe/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.mpe/ohd.mpe.ecl b/javaUtilities/hydro/ohd.mpe/ohd.mpe.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/util/MPEProductDescriptor.java b/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/util/MPEProductDescriptor.java deleted file mode 100644 index 514106ba95..0000000000 --- a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/util/MPEProductDescriptor.java +++ /dev/null @@ -1,533 +0,0 @@ -package ohd.hseb.mpe.util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.util.AppsDefaults; - -/** - * - * - * /** - * Class to handle MPE Product information, including product generation dependencies, for MPE. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * May 2013 DCS 167    C. Gobs    Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - - * - */ -public class MPEProductDescriptor implements Comparable -{ - public static final String MPE_RMOSAIC = "RMOSAIC"; - public static final String MPE_AVGRMOSAIC = "AVGRMOSAIC"; - public static final String MPE_MAXRMOSAIC = "MAXRMOSAIC"; - public static final String MPE_BMOSAIC = "BMOSAIC"; - public static final String MPE_LMOSAIC = "LMOSAIC"; - public static final String MPE_GAGEONLY = "GAGEONLY"; - public static final String MPE_MMOSAIC = "MMOSAIC"; - public static final String MPE_MLMOSAIC = "MLMOSAIC"; - public static final String MPE_SATPRE = "SATPRE"; - public static final String MPE_LSATPRE = "LSATPRE"; - public static final String MPE_SRMOSAIC = "SRMOSAIC"; - public static final String MPE_SGMOSAIC = "SGMOSAIC"; - public static final String MPE_SRGMOSAIC = "SRGMOSAIC"; - public static final String MPE_P3LMOSAIC = "P3LMOSAIC"; - public static final String MPE_BESTQPE = "xmrg"; - public static final String MPE_RFCBMOSAIC = "RFCBMOSAIC"; - public static final String MPE_RFCMMOSAIC = "RFCMMOSAIC"; - public static final String MPE_RFCMOSAIC = "RFCMOSAIC"; - - //Q2 products - public static final String MPE_QMOSAIC = "QMOSAIC"; - public static final String MPE_LQMOSAIC = "LQMOSAIC"; - public static final String MPE_MLQMOSAIC = "MLQMOSAIC"; - - - - public static final MPEProductDescriptor MPE_RMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Radar Mosaic", MPE_RMOSAIC, "Radar Mosaic", "mpe_rmosaic_dir", - null, null); - - public static final MPEProductDescriptor MPE_AVGRMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Average Radar Mosaic", MPE_AVGRMOSAIC, "Average Radar Mosaic", - "mpe_avgrmosaic_dir", null, null); - - public static final MPEProductDescriptor MPE_MAXRMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Maximum Radar Mosaic", MPE_MAXRMOSAIC, "Maximum Radar Mosaic", - "mpe_maxrmosaic_dir", null, null); - - public static final MPEProductDescriptor MPE_BMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Field Bias Mosaic", MPE_BMOSAIC, "Field Bias Mosaic", - "mpe_bmosaic_dir", new String[] { MPE_RMOSAIC }, null); - - public static final MPEProductDescriptor MPE_LMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Local Bias Mosaic", MPE_LMOSAIC, "Local Bias Mosaic", - "mpe_lmosaic_dir", new String[] { MPE_RMOSAIC }, null); - - public static final MPEProductDescriptor MPE_GAGEONLY_DESCRIPTOR = new MPEProductDescriptor( - "Gage Only Analysis", MPE_GAGEONLY, "Gage Only Analysis", - "mpe_gageonly_dir", new String[] { MPE_RMOSAIC }, null); - - public static final MPEProductDescriptor MPE_MMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Multi-sensor Mosaic", MPE_MMOSAIC, "Multi-sensor Mosaic", - "mpe_mmosaic_dir", new String[] { MPE_RMOSAIC, - "MMOSAIC" }, null); - - public static final MPEProductDescriptor MPE_MLMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Local Bias Multi-sensor Mosaic", MPE_MLMOSAIC, "Local Bias Multi-sensor Mosaic", - "mpe_mlmosaic_dir", new String[] { MPE_RMOSAIC, MPE_LMOSAIC }, null); - - public static final MPEProductDescriptor MPE_SATPRE_DESCRIPTOR = new MPEProductDescriptor( - "Satellite Precipitation Field", MPE_SATPRE, "Satellite Precipitation Field", - "mpe_satpre_dir", null, null); - - public static final MPEProductDescriptor MPE_LSATPRE_DESCRIPTOR = new MPEProductDescriptor( - "Local Bias Satellite Precipitation Field", - MPE_LSATPRE, - "Local Bias Satellite Precipitation Field", "mpe_lsatpre_dir", - new String[] { MPE_RMOSAIC, - MPE_LMOSAIC }, null); - - public static final MPEProductDescriptor MPE_SRMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Satellite Radar Mosaic", MPE_SRMOSAIC, "Satellite Radar Mosaic", - "mpe_srmosaic_dir", new String[] { MPE_LSATPRE, - MPE_LMOSAIC }, null); - - public static final MPEProductDescriptor MPE_SGMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Satellite Gage Mosaic", MPE_SGMOSAIC, "Satellite Gage Mosaic", - "mpe_sgmosaic_dir", new String[] {MPE_LSATPRE }, null); - - public static final MPEProductDescriptor MPE_SRGMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Satellite Radar Gage Mosaic", MPE_SRGMOSAIC, "Satellite Radar Gage Mosaic", - "mpe_srgmosaic_dir", new String[] { MPE_LSATPRE, MPE_LMOSAIC }, null); - - public static final MPEProductDescriptor MPE_P3LMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Triangulated Radar Mosaic", MPE_P3LMOSAIC, "Triangulated Radar Mosaic", - "mpe_p3lmosaic_dir", new String[] { MPE_RMOSAIC }, null); - - public static final MPEProductDescriptor MPE_BESTQPE_DESCRIPTOR = new MPEProductDescriptor( - "Best Estimate QPE", MPE_BESTQPE, "Best Estimate QPE", "mpe_qpe_dir", null, null); - - public static final MPEProductDescriptor MPE_RFCBMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "RFC Mean Field Bias Mosaic", MPE_RFCBMOSAIC, "RFC Mean Field Bias Mosaic", - "mpe_rfcbmosaic_dir", new String[] { MPE_RMOSAIC }, null); - - public static final MPEProductDescriptor MPE_RFCMMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "RFC Multi-sensor Mosaic", MPE_RFCMMOSAIC, "RFC Multi-sensor Mosaic", - "mpe_rfcmmosaic_dir", new String[] { MPE_RMOSAIC, MPE_RFCBMOSAIC }, null); - - public static final MPEProductDescriptor MPE_RFCMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "RFC Best QPE Mosaic", MPE_RFCMOSAIC, "RFC Best QPE Mosaic", - "mpe_rfcmosaic_dir", null, null); - -//new Q2 products - - public static final MPEProductDescriptor MPE_QMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Q2 Mosaic", MPE_QMOSAIC, "Q2 Mosaic", - "mpe_qmosaic_dir", null, null); - - public static final MPEProductDescriptor MPE_LQMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Q2 Local Bias Mosaic", MPE_LQMOSAIC, "Q2 Local Bias Mosaic", - "mpe_lqmosaic_dir", new String[] { MPE_QMOSAIC }, null); - - public static final MPEProductDescriptor MPE_MLQMOSAIC_DESCRIPTOR = new MPEProductDescriptor( - "Q2 Multi-sensor Mosaic", MPE_MLQMOSAIC, "Q2 Multi-sensor Mosaic", - "mpe_mlqmosaic_dir", new String[] { MPE_QMOSAIC, MPE_LQMOSAIC }, null); - - - - private static List _listOfAllPossibleMPEProductDescriptors = new ArrayList();; - private static Map _mapOfAllPossibleMPEProductDescriptors = new HashMap (); - private static List _listOfAvailableMPEProductDescriptors = new ArrayList(); - - static - { - - // _listOfAllPossibleMPEProductDescriptors = new ArrayList(); - - // This was commented out by Chip Gobs on 10/1/08 - // The code was reduced in size by using the private constructor to do this work. - - addDescriptorToListAndHashMap(MPE_RMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_AVGRMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_MAXRMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_BMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_LMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_GAGEONLY_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_MMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_MLMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_SATPRE_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_LSATPRE_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_SRMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_SGMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_SRGMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_P3LMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_BESTQPE_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_RFCBMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_RFCMMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_RFCMOSAIC_DESCRIPTOR); - - - // Q2 products - addDescriptorToListAndHashMap(MPE_QMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_LQMOSAIC_DESCRIPTOR); - addDescriptorToListAndHashMap(MPE_MLQMOSAIC_DESCRIPTOR); - - - - /* Populate lists of available MPE Products, those are being - * created by MPEFieldGen. - */ - - determineAvailableMPEProducts(); - - // The list of available MPE products is initially ordered by the how they are - // specified in the mpe_generate_list token. Reorder the products to match - // how they appear on the PrecipFields menu. - orderAvailableMPEProductsToMatchPrecipFieldsMenu(); - } - - private String _productName; - private String _productFilenamePrefix; - private String _productDescription; - private String _productPathToken; - private String[] _dependencies; - private XmrgGrid _mpeProductDataGrid; - - private MPEProductDescriptor(String productName, String productFilenamePrefix, String productDescription, - String productPathToken, String[] dependencies, XmrgGrid mpeProductDataGrid) - { - setProductName(productName); - setProductFilenamePrefix(productFilenamePrefix); - setProductDescription(productDescription); - setProductPathToken(productPathToken); - setDependencies(dependencies); - setMpeProductDataGrid(mpeProductDataGrid); - - // addDescriptorToListAndHashMap(this); - } - - private static void addDescriptorToListAndHashMap(MPEProductDescriptor descriptor) - { - _listOfAllPossibleMPEProductDescriptors.add(descriptor); - _mapOfAllPossibleMPEProductDescriptors.put(descriptor.getProductFilenamePrefix(), descriptor); - } - - public static List getListOfAllPossibleMPEProductDescriptors() - { - return _listOfAllPossibleMPEProductDescriptors; - } - - public static List getListOfAllAvailableMPEProductDescriptors() - { - return _listOfAvailableMPEProductDescriptors; - } - - private static Map getMapOfAllPossibleMPEProductDescriptors() - { - return _mapOfAllPossibleMPEProductDescriptors; - } - - private static void determineAvailableMPEProducts () - { - getAvailableMpeProductsFromMPEGenerateList(); - addMPEQPEFieldTypeIfNeeded(); - addRFCMosaicIfNeeded(); - addBaseRadarMosaicIfNeeded(); - } - - private static void orderAvailableMPEProductsToMatchPrecipFieldsMenu () - { - // Iterate over the list of all possible MPE Products. It is - // assumed that this list is in the same order as the items - // on the MPE Editor PrecipFields menu. - - MPEProductDescriptor product; - List _tempListOfAvailableMPEProductDescriptors; - _tempListOfAvailableMPEProductDescriptors = new ArrayList (); - Iterator MPEproduct = _listOfAllPossibleMPEProductDescriptors.iterator(); - - while ( MPEproduct.hasNext() ) - { - product = MPEproduct.next(); - - if ( _listOfAvailableMPEProductDescriptors.contains(product)) - { - _tempListOfAvailableMPEProductDescriptors.add(product); - } - } - - _listOfAvailableMPEProductDescriptors = _tempListOfAvailableMPEProductDescriptors; - - } - - private static void getAvailableMpeProductsFromMPEGenerateList() - { - String header = "MPEProductDescriptor.getAvailableMpeProductsFromMPEGenerateList(): "; - - final String MPE_GENERATE_LIST_TOKEN = "mpe_generate_list"; - final String DEFAULT_GENERATE_LIST = MPE_BMOSAIC + "," + MPE_GAGEONLY + "," + - MPE_LMOSAIC + "," + MPE_LSATPRE + "," + - MPE_MLMOSAIC + "," + MPE_MMOSAIC + "," + - MPE_RMOSAIC + "," + MPE_SATPRE; - - AppsDefaults appsDefaults = new AppsDefaults(); - MPEProductDescriptor mpeProductDescriptor; - String generateList; - String token; - StringTokenizer generateListTokens; - - generateList = appsDefaults.getToken(MPE_GENERATE_LIST_TOKEN, - DEFAULT_GENERATE_LIST); - - generateListTokens = new StringTokenizer(generateList, ","); - - - while (generateListTokens.hasMoreElements()) - { - token = generateListTokens.nextToken(); - - mpeProductDescriptor = getMapOfAllPossibleMPEProductDescriptors().get(token); - - if (mpeProductDescriptor != null ) - { - addMPEProductToGenerateListIfNeeded(mpeProductDescriptor); - System.out.println(header + "mpeProduct = " + mpeProductDescriptor.getProductFilenamePrefix()); - } - else - { - System.out.println(header + "Unrecognized mpe_generate_list value " - + token + "."); - } - - } - - // Force the addition of the XMRG field. The XMRG field is always - // generated. - mpeProductDescriptor = getMapOfAllPossibleMPEProductDescriptors().get(MPE_BESTQPE); - addMPEProductToGenerateListIfNeeded(mpeProductDescriptor); - - - } - - private static void addMPEQPEFieldTypeIfNeeded() - { - final String MPE_QPE_FIELDTYPE_TOKEN = "mpe_qpe_fieldtype"; - final String DEFAULT_QPE_FIELD_TYPE = MPE_MMOSAIC; - - AppsDefaults appsDefaults = new AppsDefaults(); - String bestQPE = appsDefaults.getToken(MPE_QPE_FIELDTYPE_TOKEN, - DEFAULT_QPE_FIELD_TYPE); - - System.out.println ("The value of token " + MPE_QPE_FIELDTYPE_TOKEN + " is " + bestQPE ); - - MPEProductDescriptor mpeProduct = getMapOfAllPossibleMPEProductDescriptors().get(bestQPE); - - if (mpeProduct == null) - { - System.out.println("Invalid mpe_qpe_fieldtype variable: " + bestQPE); - System.out.println("Using default mpe_qpe_fieldtype value: " - + DEFAULT_QPE_FIELD_TYPE); - mpeProduct = getMapOfAllPossibleMPEProductDescriptors().get(DEFAULT_QPE_FIELD_TYPE); - } - - addMPEProductToGenerateListIfNeeded(mpeProduct); - } - - private static void addRFCMosaicIfNeeded() - { - final String GENERATE_AREAL_QPE_TOKEN = "mpe_generate_areal_qpe"; - final String DEFAULT_GENERATE_AREAL_QPE = "OFF"; - - // The RFC Mosaic is handled in a special way. - AppsDefaults appsDefaults = new AppsDefaults(); - MPEProductDescriptor mpeProduct; - - String generateArealQPE = appsDefaults.getToken( - GENERATE_AREAL_QPE_TOKEN, DEFAULT_GENERATE_AREAL_QPE); - - System.out.println ( "The value of token " + GENERATE_AREAL_QPE_TOKEN + " is " + generateArealQPE); - - if (generateArealQPE.compareToIgnoreCase("ON") == 0) - { - mpeProduct = getMapOfAllPossibleMPEProductDescriptors().get(MPE_RFCMOSAIC); - - if ( mpeProduct!= null) - { - if ( !getListOfAllAvailableMPEProductDescriptors().contains(mpeProduct)) - { - getListOfAvailableMPEProductDescriptors().add(mpeProduct); - checkProductDependencies(mpeProduct); - } - } - } - } - - private static void addBaseRadarMosaicIfNeeded() - { - final String MPE_BASE_RADAR_MOSAIC_TOKEN = "mpe_base_radar_mosaic"; - final String DEFAULT_BASE_RADAR_MOSAIC = "RMOSAIC"; - - // The RFC Mosaic is handled in a special way. - AppsDefaults appsDefaults = new AppsDefaults(); - MPEProductDescriptor mpeProduct; - - String mpeBaseRadarMosaic = appsDefaults.getToken(MPE_BASE_RADAR_MOSAIC_TOKEN, DEFAULT_BASE_RADAR_MOSAIC); - System.out.println ( "The value of token " + MPE_BASE_RADAR_MOSAIC_TOKEN + " is " + mpeBaseRadarMosaic); - - mpeProduct = getMapOfAllPossibleMPEProductDescriptors().get(mpeBaseRadarMosaic); - - if ( mpeProduct!= null) - { - if ( !getListOfAllAvailableMPEProductDescriptors().contains(mpeProduct)) - { - getListOfAvailableMPEProductDescriptors().add(mpeProduct); - checkProductDependencies(mpeProduct); - } - } - - } - - private static void checkProductDependencies(MPEProductDescriptor product) - { - String dependency; - MPEProductDescriptor dependentMPEProductDescriptor; - - if (product.getDependencies() != null) - { - for (int i = 0; i < product.getDependencies().length; ++i) - { - dependency = product.getDependencies()[i]; - dependentMPEProductDescriptor = getMapOfAllPossibleMPEProductDescriptors().get( - dependency); - - if (dependentMPEProductDescriptor != null) - { - if (!getListOfAvailableMPEProductDescriptors().contains( - dependentMPEProductDescriptor)) - { - getListOfAvailableMPEProductDescriptors().add(dependentMPEProductDescriptor); - checkProductDependencies(dependentMPEProductDescriptor); - } - } - else - { - System.out.println("For product " - + product.getProductName() - + " unrecognized dependency " + dependency); - } - - } - } - } - - static private void addMPEProductToGenerateListIfNeeded( MPEProductDescriptor productDescriptor) - { - if (productDescriptor != null) - { - if (!getListOfAvailableMPEProductDescriptors().contains( - productDescriptor)) - { - getListOfAvailableMPEProductDescriptors().add(productDescriptor); - checkProductDependencies(productDescriptor); - } - } - - } - - public void setProductName(String productName) - { - _productName = productName; - } - - public String getProductName() - { - return _productName; - } - - public void setProductDescription(String productDescription) - { - _productDescription = productDescription; - } - - public String getProductDescription() - { - return _productDescription; - } - - public void setProductPathToken(String productPathToken) - { - _productPathToken = productPathToken; - } - - public String getProductPathToken() - { - return _productPathToken; - } - - public void setDependencies(String[] dependencies) - { - _dependencies = dependencies; - } - - public String[] getDependencies() - { - return _dependencies; - } - - public int compareTo(MPEProductDescriptor o) - { - String thisProductName = getProductName(); - String thatProductName = o.getProductName(); - - // TODO Auto-generated method stub - return thisProductName.compareTo(thatProductName); - } - - public void setMpeProductDataGrid(XmrgGrid mpeProductDataGrid) - { - this._mpeProductDataGrid = mpeProductDataGrid; - } - - public XmrgGrid getMpeProductDataGrid() - { - return _mpeProductDataGrid; - } - - public static void setListOfAvailableMPEProductDescriptors( - List listOfAvailableMPEProductDescriptors) - { - MPEProductDescriptor._listOfAvailableMPEProductDescriptors = listOfAvailableMPEProductDescriptors; - } - - public static List getListOfAvailableMPEProductDescriptors() - { - return _listOfAvailableMPEProductDescriptors; - } - - public void setProductFilenamePrefix(String productFilenamePrefix) - { - _productFilenamePrefix = productFilenamePrefix; - } - - public String getProductFilenamePrefix() - { - return _productFilenamePrefix; - } - -} diff --git a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableCellEditor.java b/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableCellEditor.java deleted file mode 100644 index d4403e310b..0000000000 --- a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableCellEditor.java +++ /dev/null @@ -1,64 +0,0 @@ -package ohd.hseb.mpe.window; - -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; - -import javax.swing.DefaultCellEditor; -import javax.swing.JOptionPane; -import javax.swing.JTextField; - -public class GageTableCellEditor extends DefaultCellEditor -{ - public GageTableCellEditor() - { - super (new JTextField()); - - getComponent().addFocusListener(new gageTableFocusListener()); - - - // Set the number of mouse clicks necessary to start editing. - setClickCountToStart(1); - - - - } - - public boolean stopCellEditing () - { - String newCellValue = (String) getCellEditorValue(); - - // The cell must contain a real number or 'm' or 'M' or "" - if ( newCellValue.compareToIgnoreCase("m") != 0 && - newCellValue.compareTo("") != 0) - { - try - { - new Float(newCellValue).floatValue(); - } - catch ( NumberFormatException e) - { - JOptionPane.showMessageDialog(null, "Invalid Value"); - return false; - } - } - - return super.stopCellEditing(); - } - - - private class gageTableFocusListener extends FocusAdapter - { - public void focusGained ( FocusEvent e) - { - JTextField textField = (JTextField) e.getComponent(); - - int stringLength = textField.getText().length(); - - if ( stringLength > 0 ) - { - textField.setSelectionStart(0); - textField.setSelectionEnd(stringLength); - } - } - } -} diff --git a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableDataManager.java b/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableDataManager.java deleted file mode 100644 index 7fdfa3fa68..0000000000 --- a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableDataManager.java +++ /dev/null @@ -1,606 +0,0 @@ -package ohd.hseb.mpe.window; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Scanner; -import java.util.TimeZone; - -import ohd.hseb.mpe.util.MPEProductDescriptor; - -import ohd.hseb.sshp.precip.XmrgReader; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.FileLogger; -import ohd.hseb.db.DbTable; -import ohd.hseb.grid.XmrgGrid; - - -public class GageTableDataManager -{ - private Date _productDate; - - private String _inputGageFilePath; - - private String _editedGageFilePath; - - private String _bestEstimateDateForm; - - private List _availableMPEProductList; - - private FileLogger _fileLogger; - - private boolean _first = true; - private static boolean _mpe_selected_grid_status = false; - private String _mpe_selected_grid_gagediff = null; - - - - public GageTableDataManager(FileLogger fileLogger, - String inputGageFilePath, String editedGageFilePath) - { - List availableMPEProductList; - - setFileLogger(fileLogger); - setGageFilePath(inputGageFilePath); - setEditedGageFilePath(editedGageFilePath); - - // retrieve availableMPEProductList from setting file first if it exists - // availableMPEProductList = getAvailableMPEProductFromSettingFile(); - - //if (availableMPEProductList.size() <= 0) - //{ - //availableMPEProductList = MPEProductDescriptor - // .getListOfAllAvailableMPEProductDescriptors(); - //} - - - availableMPEProductList = MPEProductDescriptor - .getListOfAllAvailableMPEProductDescriptors(); - setAvailableMPEProductList(availableMPEProductList); - - _productDate = null; - - // Set the best estimate XMRG date form. - AppsDefaults appsDefaults = new AppsDefaults(); - _bestEstimateDateForm = appsDefaults.getToken("st3_date_form", "mdY"); - - }; - - /* private List getAvailableMPEProductFromSettingFile () - { - String header = "GageTableDataManager.getAvailableMPEProductFromSettingFile(): "; - List availableMPEProductListFromSettingFile = new ArrayList (); - - BufferedReader in = null; - boolean fileExist = false; - String line; - - File fileHandlerDir = new File(getEditedGageFilePath()); - String settingsFile = fileHandlerDir.getParent() +"/MPEGageTableDisplaySettings.txt"; - - System.out.println(header+"The settingsFile is "+ settingsFile); - File fileHandler = new File(settingsFile); - fileExist = fileHandler.exists(); - - if (!fileExist) - { - _fileLogger.log(header + "Setting File can not be found, use default."); - System.out.println(header + "Setting File not be found, use default"); - } - else - { - try - { - in = new BufferedReader(new FileReader(fileHandler)); - if ( in.readLine() != null) - { - // return the info from settings file as a whole string buffer - while ((line = in.readLine()) != null ) - { - int strStart = in.toString().indexOf("COLUMN:"); - int strEnd = in.toString().indexOf("|"); - if (strStart >= 0 && strEnd > strStart) - { - String productName = in.toString().substring(strStart, strEnd); - } - } - - - } - - _fileLogger.log(header + "Retrieve availableMPEProductList from setting file " + settingsFile); - System.out.println(header + "Retrieve availableMPEProductList from setting file " + settingsFile); - - in.close(); - - } catch (IOException e) - { - _fileLogger.log(header+ "Unable to retrieve availableMPEProductList from file " + settingsFile); - e.printStackTrace(_fileLogger.getPrintWriter()); - e.printStackTrace(); - } - } - - return availableMPEProductListFromSettingFile; - }*/ - - public List readData() throws IOException, ParseException - { - String header = "GageTableDataManager.readData(): "; - - Float default_editValue = DbTable.getNullFloat(); - double default_diffValue; - double gridValue = DbTable.getNullDouble(); - List gageRecordList = null; - Map productValueMap = new HashMap(); - XmrgGrid xmrgGrid = null; - - - - System.out.println(header + "1"); - - gageRecordList = readGageValueFile(); - - System.out.println(header + "2"); - - - List rowDataList = new ArrayList( - gageRecordList.size()); - - System.out.println(header + "2.1"); - - readProductFile(); - - System.out.println(header + "3"); - - System.out.println(header + "gageRecordList.size() = " + gageRecordList.size()); - System.out.println(header + "getAvailableMPEProductList().size() = " + getAvailableMPEProductList().size()); - - int maxIterations = gageRecordList.size() * getAvailableMPEProductList().size(); - System.out.println(header + "nested loop iterations will equal = " + maxIterations); - - System.out.println(header + "4"); - - int iterationCount = 0; - - // Build records based on the number of gages. - // For each gage read from the gage value list. - for (GageFileRecord record : gageRecordList) - { - for (MPEProductDescriptor mpeProductDescriptor : getAvailableMPEProductList()) - { - iterationCount++; - xmrgGrid = mpeProductDescriptor.getMpeProductDataGrid(); - - gridValue = DbTable.getNullDouble(); - - if (xmrgGrid.isValid()) - { - gridValue = xmrgGrid.getValue((int) record.getHrapY(), - (int) record.getHrapX()); - - if (gridValue < 0) - { - gridValue = DbTable.getNullDouble(); - } - } - - productValueMap.put(mpeProductDescriptor.getProductName(), - new Double(gridValue)); - - - if ((iterationCount % 2000) == 0) - { - System.out.println(header + " iterationCount = " + iterationCount + " of " + maxIterations); - } - } - - //initialize the default_diffValue between GageValue and Best Estimate Grid Value - default_diffValue = setDiffGageGridValue(record.getValue(), productValueMap); - - GageTableRowData gageRow = new GageTableRowData(record.getLid(), - record.getValue(), default_editValue, default_diffValue, record.getRadarID(), productValueMap); - gageRow.addAllCellsToMap(); - rowDataList.add(gageRow); - } - - return rowDataList; - } - - - private Double setDiffGageGridValue(float gageValue,Map productValueMap) - - { - String header = "GageTableDataManager.setDiffGageGridValue: "; - final String MPE_SELECTED_GRID_GAGEDIFF_TOKEN = "mpe_selected_grid_gagediff"; - final String DEFAULT_SELECTED_GRID_GAGEDIFF = "Best Estimate QPE"; - - String tokenPrefix = null; - String tokenName = null; - - AppsDefaults appsDefaults = new AppsDefaults(); - Double default_diffValue = DbTable.getNullDouble(); - - - if (_first == true) - { - tokenPrefix = appsDefaults.getToken(MPE_SELECTED_GRID_GAGEDIFF_TOKEN); - - for (Iterator i = MPEProductDescriptor.getListOfAvailableMPEProductDescriptors().iterator(); - i.hasNext();) - { - MPEProductDescriptor item = i.next(); - if (tokenPrefix != null && tokenPrefix .equals(item.getProductFilenamePrefix())) - tokenName = item.getProductName(); - } - - if (tokenName == null) - _mpe_selected_grid_gagediff = DEFAULT_SELECTED_GRID_GAGEDIFF; - - else if (productValueMap.containsKey(tokenName) == false) - _mpe_selected_grid_gagediff = DEFAULT_SELECTED_GRID_GAGEDIFF; - - else - _mpe_selected_grid_gagediff = tokenName; - - System.out.println(header + "The value of token mpe_selected_grid_gagediff is " + - _mpe_selected_grid_gagediff); - - _first = false; - } - - - Double gridData = (Double) productValueMap.get(_mpe_selected_grid_gagediff); - - if (gageValue < 0.0 || gridData == null || gridData == DbTable.getNullDouble() ) - default_diffValue = DbTable.getNullDouble(); - else - default_diffValue = gageValue - gridData; - - - return default_diffValue; - } - - - private List readGageValueFile() throws IOException, ParseException - { - Date productDate = null; - float hrapX; - float hrapY; - float value; - - List gageRecordList = new ArrayList(); - Scanner recordScanner = null; - SimpleDateFormat utcSimpleDateFormat = new SimpleDateFormat( - "yyyy MM dd HH"); - String gageRecord = null; - String lid = null; - String radarID = null; - - utcSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - BufferedReader inputGageFile = new BufferedReader( - new InputStreamReader(new FileInputStream(getGageFilePath()))); - - gageRecord = inputGageFile.readLine(); - - if (gageRecord != null) - { - /* - * The first record of the gage file contains the date and time of - * the gage data int year, month, day, hour format. - */ - productDate = new Date(utcSimpleDateFormat.parse(gageRecord) - .getTime()); - setProductDate(productDate); - } - else - { - throw new IOException("Missing date string in first record of gage file."); - } - - gageRecord = inputGageFile.readLine(); - - while (gageRecord != null && gageRecord.equals("") == false) - { - recordScanner = new Scanner(gageRecord); - lid = recordScanner.next(); - hrapX = recordScanner.nextFloat(); - hrapY = recordScanner.nextFloat(); - radarID = recordScanner.next(); - value = recordScanner.nextFloat(); - - if (value < 0) - { - value = DbTable.getNullFloat(); - } - - gageRecordList.add(new GageFileRecord(lid, hrapX, hrapY, radarID, value)); - gageRecord = inputGageFile.readLine(); - } - - inputGageFile.close(); - - return gageRecordList; - } - - private void readProductFile() - { - String header = "GageTableDataManager.readProductFile(): "; - AppsDefaults appsDefaults = new AppsDefaults(); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH"); - SimpleDateFormat alternativeXmrgDateFormat = new SimpleDateFormat("MMddyyyyHH"); - - System.out.println(header + "1" ); - - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - alternativeXmrgDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - System.out.println(header + "2" ); - - - String productDateString = dateFormat.format(getProductDate()); - - System.out.println(header + "3" ); - String alternativeXmrgProductDateString = alternativeXmrgDateFormat.format(getProductDate()); - - System.out.println(header + "4" ); - String productPath = null; - - XmrgGrid xmrgGrid = null; - - System.out.println(header + "5" ); - XmrgReader xmrgReader = new XmrgReader(getFileLogger()); - - System.out.println(header + "6" ); - - System.out.println(header + "getAvailableMPEProductList().size() = " + getAvailableMPEProductList().size() ); - - System.out.println(header + "7" ); - - for (MPEProductDescriptor product : getAvailableMPEProductList()) - { - // Build the path to the product. If reading the XMRG product file - // then need to take into consideration that the date on the filename - // may be format yyyyMMddHH or MMddYYYYHH. - productPath = appsDefaults.getToken(product.getProductPathToken(), - ""); - - if ((product.getProductFilenamePrefix().compareTo("xmrg") == 0) && - (_bestEstimateDateForm.compareTo("mdY") == 0 ) ) - { - productPath += "/" + product.getProductFilenamePrefix() + alternativeXmrgProductDateString - + "z"; - } - else - { - productPath += "/" + product.getProductFilenamePrefix() + productDateString - + "z"; - } - - // Retrieve the XMRG grid for the product. - System.out.println("Retrieving data for " + productPath); - - xmrgGrid = xmrgReader.loadGrid(getProductDate().getTime(), - productPath); - - if (xmrgGrid != null) - { - product.setMpeProductDataGrid(xmrgGrid); - } - } - } - - public void saveUpdatedGageData(List gageRowDataList) throws IOException - { - File editedGageFile = new File(getEditedGageFilePath()); - File tempGageFile = null; - float gageValue; - List gageFileRecordList = new ArrayList(); - String gageId = null; - - // Write the data to a temp file and then move it to the - // official edited gage data file. This prevents the C - // program from reading the file while the Java program is - // writing it. - String outputPath = editedGageFile.getParent() + "/temp"; - tempGageFile = new File(outputPath); - System.out.println("The temp output path is " + outputPath); - - try - { - PrintWriter outputGageFile = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(outputPath)))); - - for (GageTableRowData gageTableRowData : gageRowDataList) - { - // Check if this gage value has been edited. - - if (gageTableRowData.getOrginalValue() != gageTableRowData - .getValue()) - { - gageId = gageTableRowData.getGageId(); - gageValue = gageTableRowData.getValue(); - - if (gageValue == DbTable.getNullFloat()) - { - gageValue = -1; - } - - gageFileRecordList.add(new GageFileRecord(gageId, 0.0f, - 0.0f, "M", gageValue)); - - } - - } - - for (GageFileRecord gageFileRecord : gageFileRecordList) - { - outputGageFile.println(gageFileRecord); - } - - outputGageFile.close(); - tempGageFile.renameTo(editedGageFile); - } - catch (IOException e) - { - getFileLogger().log( - "Error processing gage file " + getGageFilePath() - + "/gages.txt"); - throw e; - } - } - - public void setAvailableMPEProductList( - List availableMPEProductList) - { - _availableMPEProductList = availableMPEProductList; - } - - public List getAvailableMPEProductList() - { - return _availableMPEProductList; - - } - - public void setFileLogger(FileLogger fileLogger) - { - _fileLogger = fileLogger; - } - - public FileLogger getFileLogger() - { - return _fileLogger; - } - - public void setGageFilePath(String _gageFilePath) - { - this._inputGageFilePath = _gageFilePath; - } - - public String getGageFilePath() - { - return _inputGageFilePath; - } - - public void setProductDate(Date productDate) - { - _productDate = productDate; - } - - public Date getProductDate() - { - return _productDate; - } - - public void setEditedGageFilePath(String editedGageFilePath) - { - this._editedGageFilePath = editedGageFilePath; - } - - public String getEditedGageFilePath() - { - return _editedGageFilePath; - } - - private class GageFileRecord - { - private String _lid; - private float _hrapX; - private float _hrapY; - private String _radarID; - private float _value; - - public GageFileRecord(String lid, float hrapX, float hrapY, String radarID, float value) - { - setLid(lid); - setHrapX(hrapX); - setHrapY(hrapY); - setRadarID(radarID); - setValue(value); - } - - public void setLid(String lid) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setHrapX(float hrapX) - { - _hrapX = hrapX; - } - - public float getHrapX() - { - return _hrapX; - } - - public void setHrapY(float hrapY) - { - _hrapY = hrapY; - } - - public float getHrapY() - { - return _hrapY; - } - - public void setValue(float value) - { - _value = value; - } - - public float getValue() - { - return _value; - } - - public String toString() - { - String outputString = getLid() + " " + getHrapX() + " " - + getHrapY() + " " + getValue(); - return outputString; - } - - public void setRadarID(String radarID) - { - _radarID = radarID; - } - - public String getRadarID() - { - return _radarID; - } - - } - - public String get_mpe_selected_grid_gagediff() { - return _mpe_selected_grid_gagediff; - } - - public void set_mpe_selected_grid_gagediff(String _mpe_selected_grid_gagediff) { - this._mpe_selected_grid_gagediff = _mpe_selected_grid_gagediff; - } - -} diff --git a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableFrame.java b/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableFrame.java deleted file mode 100644 index 11cc93b3e1..0000000000 --- a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableFrame.java +++ /dev/null @@ -1,1145 +0,0 @@ -package ohd.hseb.mpe.window; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -//import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -//import java.awt.event.ComponentAdapter; -//import java.awt.event.ComponentEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.TimeZone; - -import javax.swing.AbstractListModel; -import javax.swing.ComboBoxModel; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -//import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataListener; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; - -import ohd.hseb.db.DbTable; -import ohd.hseb.mpe.util.MPEProductDescriptor; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptorManager; -import ohd.hseb.util.gui.jtable.JTableManager; -import ohd.hseb.util.gui.jtable.JTableModel; - -public class GageTableFrame extends JFrame implements Runnable -{ - /** - * - */ - private static final long serialVersionUID = 1L; - private static final String gageTableSettingFileHeader="#GageTableSettings File\n"; - - private static boolean _isRunning = false; - private static Thread _thread = null; - - private GageTableDataManager _dataManager; - private JTableManager _tableManager; - private FileLogger _fileLogger; - - private final int _valueColumnWidth = 55; - // private final int _maxWindowWidth = 1250; - - private String _settingsFile = null; - JComboBox _selectGridList = null; - String [] _gridDataName = null; - int _selected_index = DbTable.getNullInt(); - - public GageTableFrame(FileLogger fileLogger, - GageTableDataManager dataManager) - { - setDataManager(dataManager); - setFileLogger(fileLogger); - } - - static private void gageTableClosingAction(GageTableFrame gageFrame, - String inputFilePath, String editedFilePath, FileLogger logger) - { - File inputFile = new File(inputFilePath); - File editedFile = new File(editedFilePath); - - // Delete the input file. - inputFile.delete(); - - // If it doesn't exist, touch the edited gage output file. - // This file contains the edited gage data. It also acts - // as a sentinel to indicate that the Gage Table has been - // closed. - try - { - editedFile.createNewFile(); - } - catch (IOException e) - { - logger.log(e.getMessage()); - } - - if (_isRunning == true) - { - _isRunning = false; - _thread.stop(); - - } - - if (gageFrame != null) - { - gageFrame.dispose(); - } - } - - public void showGageTable() throws IOException, ParseException - { - String header = "GageTableFrame.showGageTable(): "; - - JButton saveButton = null; - JButton cancelButton = null; - JLabel searchLabel = null; - JTextField searchTextField = null; - JPanel gageTablePanel = null; - JPanel searchPanel = null; - // JPanel buttonPanel = null; - JScrollPane tableScrollPane = null; - JLabel selectGridLabel = null; - - - System.out.println(header + " 1 "); - - Container container = getContentPane(); - - GridBagConstraints constraints = new GridBagConstraints(); - - saveButton = new JButton("Save"); - cancelButton = new JButton("Cancel"); - searchLabel = new JLabel("Search for LID:"); - searchTextField = new JTextField(5); - gageTablePanel = new JPanel(); - searchPanel = new JPanel(); - // buttonPanel = new JPanel(); - selectGridLabel = new JLabel(" Select Grid Field Compared With Gage:"); - - - SimpleDateFormat utcSimpleDateFormat = new SimpleDateFormat( - "HH'Z' MMMMM dd, yyyy"); - String productDate; - - utcSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - System.out.println(header + " 2 "); - - container.setLayout(new GridBagLayout()); - gageTablePanel.setLayout(new GridLayout(1, 1)); - searchPanel.setLayout(new FlowLayout(FlowLayout.LEFT) ); - // buttonPanel.setLayout(new BorderLayout()); - - - System.out.println(header + " 2.1 "); - - // load rowDataList - List rowDataList = getDataManager().readData(); - - System.out.println(header + " 2.2 "); - - // define the directory and name of the office-wide settings file including the - // the table column header names and sorting, and table column length etc info - - //String settingsFileDir = getDataManager().getEditedGageFilePath(); - - AppsDefaults appsDefaults = new AppsDefaults(); - String settingsFileDir = appsDefaults.getToken("rfcwide_input_dir", - "/awips/hydroapps/precip_proc/local/data/app/mpe"); - - File fileHandlerDir = new File(settingsFileDir); - String settingsFile = fileHandlerDir.getPath() +"/MPEGageTableDisplaySettings.txt"; - - set_settingsFile(settingsFile); - - System.out.println(header + " 2.3 "); - - // retrieve the columns - - List columnDescriptorList = createColumnDescriptorList(); - - System.out.println(header + " 2.4 "); - - productDate = utcSimpleDateFormat.format(getDataManager() - .getProductDate()); - setTitle("MPE Gage Table " + productDate); - - System.out.println(header + " 3 "); - - - tableScrollPane = createJTable(columnDescriptorList, rowDataList); - - System.out.println(header + " 4 "); - - createMenus(); - - System.out.println(header + " 5 "); - - /* create a list for "select grid field" to allow user customize the grid field which - they want to compare with gage value field, then the difference of gagevallue-gridvalue will - be displayed in the "Diff (Gage - Grid)" colunm. The default field "Best Estimate QPE" will - be used as the grid field if 1) token mpe_selected_grid_gagediff is NOT set AND 2)the "Best - Estimate QPE" field IS included in mpe_generate_list token. Otherwise, "No field selected" - will be highlighted in the combobox list */ - - createSelectGridList(); - - String [] gridDataName = get_gridDataName(); - int selected_index = get_selected_index(); - - _selectGridList = new JComboBox(gridDataName); - _selectGridList.setSelectedIndex(selected_index); - _selectGridList.addActionListener(new selectGridActionListener()); - - - searchTextField.addKeyListener(new keyActionListener()); - - constraints.anchor = GridBagConstraints.NORTHWEST; - constraints.fill = GridBagConstraints.NONE; - constraints.insets = new Insets(5, 5, 5, 5); - - addComponent(container, searchPanel, constraints, 0, 0, 1, 1, 0, 0); - addComponent(searchPanel, searchLabel, constraints, 0, 0, 1, 1, 1, 0); - addComponent(searchPanel, searchTextField, constraints, 1, 0, 1, 1, 1, 0); - - addComponent(searchPanel, selectGridLabel, constraints, 2, 0, 2, 1, 5, 1.0); - addComponent(searchPanel, _selectGridList, constraints, 3, 0, 2, 1, 1, 0); - - /* searchPanel.add(searchLabel); - searchPanel.add(searchTextField); - searchPanel.add(selectGridLabel); - searchPanel.add(_selectGridList); - */ - - constraints.anchor = GridBagConstraints.LINE_START; - constraints.fill = GridBagConstraints.BOTH; - constraints.insets = new Insets(10, 16, 2, 20); - - gageTablePanel.add(tableScrollPane); - - addComponent(container, gageTablePanel, constraints, 0, 1, 3, 2, 1.0, - 1.0); - - constraints.anchor = GridBagConstraints.LAST_LINE_START; - constraints.fill = GridBagConstraints.NONE; - constraints.insets = new Insets(15, 16, 15, 20); - - addComponent(container, saveButton, constraints, 0, 3, 1, 1, 0.0, 0.0); - - constraints.anchor = GridBagConstraints.EAST; - constraints.fill = GridBagConstraints.NONE; - constraints.insets = new Insets(15, 20, 15, 20); - - addComponent(container, cancelButton, constraints, 2, 3, 1, 1, 0.0, 0.0); - - /* buttonPanel.add(saveButton, BorderLayout.WEST); - buttonPanel.add(cancelButton, BorderLayout.EAST); - */ - - System.out.println(header + " 6 "); - - /*container.setLayout(new BorderLayout()); - container.add(searchPanel,BorderLayout.NORTH); - container.add(gageTablePanel, BorderLayout.CENTER); - container.add(buttonPanel, BorderLayout.SOUTH); - */ - - pack(); - - System.out.println(header + " 7 "); - - //set the initial width and height of the window - - /*int columnWidthTotal = _valueColumnWidth * columnDescriptorList.size(); - - int windowWidth = 100 + columnWidthTotal; - if (windowWidth > _maxWindowWidth) - { - windowWidth = _maxWindowWidth; - } - int windowHeight = 700; - - - setSize(new Dimension(windowWidth, windowHeight)); - */ - System.out.println(header + " 8 "); - - saveButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - try - { - saveGageTableEdits(); - } - catch (IOException ex) - { - getFileLogger().log(ex.getMessage()); - } - - gageTableClosingAction(GageTableFrame.this, getDataManager() - .getGageFilePath(), getDataManager() - .getEditedGageFilePath(), getFileLogger()); - } - }); - - cancelButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - gageTableClosingAction(GageTableFrame.this, getDataManager() - .getGageFilePath(), getDataManager() - .getEditedGageFilePath(), getFileLogger()); - } - }); - addWindowListener(new WindowAdapter() - { - public void windowClosing(WindowEvent e) - { - gageTableClosingAction(GageTableFrame.this, getDataManager() - .getGageFilePath(), getDataManager() - .getEditedGageFilePath(), getFileLogger()); - } - }); - - - System.out.println(header + " 9 "); - setVisible(true); - - // Resize the window to trick the column headings into expanding to be large - // enough to show full labels. - /*Rectangle bounds = this.getBounds(); - Dimension originalFrameDimension = new Dimension (bounds.width, bounds.height); - Dimension newFrameDimension = new Dimension (bounds.width+100, bounds.height); - this.setSize(newFrameDimension); - this.repaint(); - this.setSize(originalFrameDimension);*/ - - System.out.println(header + " 10 "); - _tableManager.refreshDisplay(); - pack(); - - System.out.println(header + " 11 "); - } - - public JScrollPane createJTable(List columnDescriptorList, List rowDataList) - { - - ComplexJTableManager jTableManager = new ComplexJTableManager( - columnDescriptorList, rowDataList); - - jTableManager.setTableCellEditor(Object.class, new GageTableCellEditor ()); - - setTableManager(jTableManager); - - // check if settings file exists, if does, create the table with the columns - // defined in settings file. If not, then create the table with default setting. - - String settingString = loadSettingStringFromSettingsFile(); - - if (settingString.length() > 0) - { - getTableManager().getTableSettings().setSettingsFromString(settingString); - getTableManager().refreshDisplay(); - - } - - // Add listener for Table Cell Update events. - jTableManager.addTableListener(new GageTableModelListener()); - - // getTableManager().setPreferredSizeForJScrollPane( - // new Dimension(680, 340)); - getTableManager().setPreferredSizeForJScrollPane( - new Dimension(1190, 545)); - - JScrollPane tableScrollPane= getTableManager().getJScrollPane(); - - return tableScrollPane; - } - - public void createMenus() - { - JMenuBar menuBar = new JMenuBar(); - setJMenuBar(menuBar); - - JMenu fileMenu = new JMenu("File"); - fileMenu.setMnemonic('F'); - JMenuItem columnSelectionMenuItem = new JMenuItem("Column Selection"); - columnSelectionMenuItem.setMnemonic('C'); - fileMenu.add(columnSelectionMenuItem); - - JMenuItem refreshMenuItem = new JMenuItem("Refresh"); - refreshMenuItem.setMnemonic('R'); - fileMenu.add(refreshMenuItem); - - JMenuItem saveSettingMenuItem = new JMenuItem("Save Settings"); - saveSettingMenuItem.setMnemonic('S'); - fileMenu.add(saveSettingMenuItem); - - - ChangeColumnsDisplayedMenuListener changeMenuListener = new ChangeColumnsDisplayedMenuListener(); - columnSelectionMenuItem.addActionListener(changeMenuListener); - - RefreshMenuListener RefreshMenuListener = new RefreshMenuListener(); - refreshMenuItem.addActionListener(RefreshMenuListener); - - SaveSettingMenuListener saveSettingMenuListener = new SaveSettingMenuListener(); - saveSettingMenuItem.addActionListener(saveSettingMenuListener); - - menuBar.add(fileMenu); - } - - public class RefreshMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - try - { - List rowDataList = getDataManager().readData(); - getTableManager().setChangedAllRowDataList(rowDataList); - getTableManager().refreshDisplay(); - } - catch (Exception ex) - { - getFileLogger().log(ex.getMessage()); - gageTableClosingAction(GageTableFrame.this, getDataManager() - .getGageFilePath(), getDataManager() - .getEditedGageFilePath(), getFileLogger()); - } - } - } - - public class SaveSettingMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - saveSettingsToFile(); - } - - } - - private class GageTableModelListener implements TableModelListener - { - public void tableChanged(TableModelEvent e) - { - - if ((e != null) && (e.getType() == TableModelEvent.UPDATE)) - { - int cellRow = e.getFirstRow(); - int cellColumn = e.getColumn(); - JTableModel tableModel = (JTableModel) e.getSource(); - - if ((cellRow != TableModelEvent.HEADER_ROW) - && (cellColumn != TableModelEvent.ALL_COLUMNS) - && (cellRow == e.getLastRow())) - { - String newValue = (String) tableModel.getValueAt(cellRow, - cellColumn); - - // Get the data list structure from the Table Manager. - List rowDataList = getTableManager() - .getAllRowDataList(); - GageTableRowData rowData = rowDataList.get(cellRow); - - // Update the edited row. - // The custom cell editor makes sure that the value is - // either a real number - // or 'm' or 'M' or "". - if (newValue.compareTo("") == 0) - { - rowData.setValue(rowData.getOrginalValue()); - } - else - { - if (newValue.compareToIgnoreCase("m") == 0) - { - rowData.setValue(DbTable.getNullFloat()); - } - - else - { - rowData.setValue(new Float(newValue).floatValue()); - } - } - - rowData.addAllCellsToMap(); - } - } - } - } - - public void saveGageTableEdits() throws IOException - { - List gageTableRowList = getTableManager() - .getAllRowDataList(); - getDataManager().saveUpdatedGageData(gageTableRowList); - } - - private class ChangeColumnsDisplayedMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header="GageTableFrame.ChangeColumnsDisplayedMenuListener(): "; - getTableManager().invokeColumnSelector(GageTableFrame.this); - - // update the combobox for grid data to compare with gage data - - createSelectGridList(); - - String [] updatedGridList = get_gridDataName(); - int updated_selected_index = get_selected_index(); - - List strList = new ArrayList (); - for(String str : updatedGridList) - { - strList.add(str); - } - - for (int l = 0; l < strList.size(); l++) - System.out.println(header + "strList is " + strList.get(l)); - - System.out.println(header +"the updated selected_index is " + updated_selected_index); - - ChangeSelectGridListModel changeSelectGridListModel = new ChangeSelectGridListModel(strList); - - get_selectGridList().setModel(changeSelectGridListModel); - - get_selectGridList().setSelectedIndex(updated_selected_index); - get_selectGridList().addActionListener(new selectGridActionListener()); - - } - } - - private class ChangeSelectGridListModel extends AbstractListModel implements ComboBoxModel - { - private Object selectedItem; - - private List strList; - - public ChangeSelectGridListModel(List arrayList) { - strList = arrayList; - } - - public Object getSelectedItem() { - return selectedItem; - } - - public void setSelectedItem(Object newValue) { - selectedItem = newValue; - } - - public int getSize() { - return strList.size(); - } - - public Object getElementAt(int i) { - return strList.get(i); - } - - - - } - - public void createSelectGridList() - { - String header="GageTableFrame.create_selectGridList(): "; - boolean qpe_found = false; - String[] currentlyDisplayedName = null; - int selected_index = DbTable.getNullInt(); - int gridDataName_num = 0; - String [] gridDataName; - - // get current Displayed column names - currentlyDisplayedName = getTableManager().getColumnNamesThatAreCurrentlyDisplayed(); - - // get rid of "LID", "Radar ID", "Gage Value", "Edit Gage Value" and "Diff (Gage-Grid)" - // column names - gridDataName = new String[currentlyDisplayedName.length - 4 ]; - - for (int i = 0; i < currentlyDisplayedName.length; i++) - { - - if ((currentlyDisplayedName[i].equals("LID") == false) && - (currentlyDisplayedName[i].equals("Radar ID") == false) && - (currentlyDisplayedName[i].equals("Gage Value") == false) && - (currentlyDisplayedName[i].equals("Edit Gage Value") == false) && - (currentlyDisplayedName[i].equals("Diff (Gage-Grid)") == false)) - { - gridDataName[gridDataName_num] = currentlyDisplayedName[i]; - gridDataName_num++; - } - - } - - for (int k =0; k createColumnDescriptorList() - { - String header = "GageTableFrame.createColumnDescriptorList(): "; - - // create the default columnDescriptorList - System.out.println(header + "1"); - List columnDescriptorList = new ArrayList(); - List availableMPEProductList; - - System.out.println(header + "2"); - - // The LID and Value and Radar ID columns always exist. - columnDescriptorList.add(new JTableColumnDescriptor("LID", true, _valueColumnWidth, - "center", "Location ID")); - - System.out.println(header + "3"); - - // for GAGE Value column. - JTableColumnDescriptor originalValueColumnDescriptor = new JTableColumnDescriptor("Gage Value", true, - _valueColumnWidth, "center", "Gage Value"); - originalValueColumnDescriptor.setSortAsc(true); - - columnDescriptorList.add(originalValueColumnDescriptor); - - System.out.println(header + "4"); - - // Edit GAGE Value column - JTableColumnDescriptor valueColumnDescriptor = new JTableColumnDescriptor( - "Edit Gage Value", true, _valueColumnWidth, "center", "Edit Gage Value"); - - System.out.println(header + "4.1"); - - GageTableCellEditor cellEditor = new GageTableCellEditor(); - - System.out.println(header + "4.2"); - - valueColumnDescriptor.turnOnCellEditing(cellEditor); - - System.out.println(header + "4.3"); - - valueColumnDescriptor.setSortAsc(true); - - - System.out.println(header + "4.4"); - - columnDescriptorList.add(valueColumnDescriptor); - - System.out.println(header + "5"); - - JTableColumnDescriptor diffColumnDescriptor = new JTableColumnDescriptor("Diff (Gage-Grid)", true, - 74, "center", "Difference between Gage Value and Grid Data"); - - diffColumnDescriptor.setSortAsc(true); - columnDescriptorList.add(diffColumnDescriptor); - - System.out.println(header + "6"); - - - columnDescriptorList.add(new JTableColumnDescriptor("Radar ID", true, - _valueColumnWidth, "center", "Radar ID")); - - System.out.println(header + "7"); - - // Get a list of the fields being generated by the MPE Field Generator. - availableMPEProductList = getDataManager().getAvailableMPEProductList(); - - System.out.println(header + "8"); - - int counter = 0; - - for (MPEProductDescriptor mpeProduct : availableMPEProductList) - { - counter++; - - System.out.println(header + "9, iteration # " + counter); - - JTableColumnDescriptor descriptor = new JTableColumnDescriptor(mpeProduct - .getProductName(), true, _valueColumnWidth, "center", mpeProduct - .getProductDescription()); - descriptor.setSortAsc(true); - - System.out.println(header + "10, iteration # " + counter); - - - if (mpeProduct.getProductFilenamePrefix().equals(MPEProductDescriptor.MPE_BESTQPE)) - { - - System.out.println(header + "11, iteration # " + counter); - columnDescriptorList.add(5, descriptor); - System.out.println(header + "12, iteration # " + counter); - } - else //all other columns - { - columnDescriptorList.add(descriptor); - } - } - - return columnDescriptorList; - } - - private String loadSettingStringFromSettingsFile() - { - String header = "GageTableFrame.loadSettingStringFromSettingsFile(): "; - StringBuffer settingString = new StringBuffer(); - BufferedReader in = null; - boolean fileExist = false; - String line; - - File fileHandler = new File(get_settingsFile()); - fileExist = fileHandler.exists(); - - if (!fileExist) - { - _fileLogger.log(header + "Setting File can not be found, use default."); - System.out.println(header + "Setting File not be found, use default"); - } - else - { - - try - { - in = new BufferedReader(new FileReader(fileHandler)); - if ( in.readLine() != null) - { - while ((line = in.readLine()) != null ) - { - settingString.append(line).append("\n"); - - } - - } - - _fileLogger.log(header + "Setting File " + get_settingsFile() + " is loaded"); - System.out.println(header + "Setting File " + get_settingsFile() + " is loaded"); - - in.close(); - - } catch (IOException e) - { - _fileLogger.log(header+ "Unable to read from file " + get_settingsFile()); - e.printStackTrace(_fileLogger.getPrintWriter()); - e.printStackTrace(); - } - } - - return settingString.toString(); - } - - public static void show(String logFilePath, String inputGageFilePath, - String editedGageFilePath, String gageLogPath) - { - File editedFile = new File(editedGageFilePath); - File inputFile = new File(inputGageFilePath); - - if (!_isRunning) // make sure that we don't invoke 2 of these gage - // tables - // at a time - { - FileLogger logger = new FileLogger(logFilePath); - GageTableFrame gageTable = null; - - try - { - editedFile.delete(); - GageTableDataManager gageTableDataManager = new GageTableDataManager( - logger, inputGageFilePath, editedGageFilePath); - gageTable = new GageTableFrame(logger, gageTableDataManager); - gageTable.showGageTable(); - } - catch (Exception e) - { - System.out.println(e.getMessage()); - logger.log(e.getMessage()); - gageTableClosingAction(gageTable, inputGageFilePath, - editedGageFilePath, logger); - } - - _thread = new Thread(gageTable); - _thread.start(); - - _isRunning = true; - } - } - - // -------------------------------------------------------------------------------------------------- - public static void main(String[] args) - { - AppsDefaults appsDefaults = new AppsDefaults(); - File editedFile = null; - File inputFile = null; - String logDir = appsDefaults - .getToken("mpe_editor_logs_dir", - "/awips/hydroapps/precip_proc/local/data/log/mpe_editor"); - FileLogger fileLogger = new FileLogger(logDir + "/GageTable.log"); - String gageFileDir = appsDefaults.getToken("mpe_scratch_dir", - "/awips/hydroapps/precip_proc/local/data/mpe/dailyQC/scratch"); - String inputGageFilePath = gageFileDir + "/gages.dat"; - String editedGageFilePath = gageFileDir + "/edited_gages.dat"; - GageTableFrame gageTable = null; - editedFile = new File(editedGageFilePath); - inputFile = new File(inputGageFilePath); - - - try - { - editedFile.delete(); - GageTableDataManager gageTableDataManager = new GageTableDataManager( - fileLogger, inputGageFilePath, editedGageFilePath); - gageTable = new GageTableFrame(fileLogger, gageTableDataManager); - gageTable.showGageTable(); - } - catch (Exception e) - { - e.printStackTrace(); - fileLogger.log(e.getMessage()); - inputFile.delete(); - - gageTableClosingAction(gageTable, inputGageFilePath, - editedGageFilePath, fileLogger); - } - } - - // --------------------------------------------------------------------------------------------------- - public void setFileLogger(FileLogger _fileLogger) - { - this._fileLogger = _fileLogger; - } - - public FileLogger getFileLogger() - { - return _fileLogger; - } - - public void setDataManager(GageTableDataManager _dataManager) - { - this._dataManager = _dataManager; - } - - public GageTableDataManager getDataManager() - { - return _dataManager; - } - - public void run() - { - // This is here to allow the caller to continue functioning while this - // window is open - - this.setVisible(true); - - } - - public void setTableManager(JTableManager tableManager) - { - _tableManager = tableManager; - } - - public JTableManager getTableManager() - { - return _tableManager; - } - - private class keyActionListener extends KeyAdapter - { - public void keyReleased(KeyEvent e) - { - ArrayList rowsToHighlight = null; - Component eventComponent = e.getComponent(); - boolean foundFirstMatch = false; - int firstRowToHighlight; - int lastRowToHighlight; - String lidInTable = null; - String lidInTableSubstring = null; - String searchText = ((JTextField) eventComponent).getText().toUpperCase(); - - - List gageTableRowList = getTableManager() - .getAllRowDataList(); - - getTableManager().deselectRows(0, gageTableRowList.size() - 1); - - if (searchText.length() > 0) - { - rowsToHighlight = new ArrayList(); - - for (int i = 0; i < gageTableRowList.size(); ++i) - { - lidInTable = gageTableRowList.get(i).getGageId(); - - if (searchText.length() <= lidInTable.length()) - { - lidInTableSubstring = lidInTable.substring(0, - searchText.length()); - - if (searchText.equals(lidInTableSubstring)) - { - foundFirstMatch = true; - rowsToHighlight.add(new Integer(i)); - - } - // else if (searchText.compareTo(lidInTableSubstring) < 0) - // { - // break; - // } - } - } - - if (foundFirstMatch) - { - firstRowToHighlight = rowsToHighlight.get(0).intValue(); - lastRowToHighlight = rowsToHighlight.get( - rowsToHighlight.size() - 1).intValue(); - getTableManager().selectRows(firstRowToHighlight, - lastRowToHighlight); - } - } - else - { - getTableManager().selectRows(0, 0); - } - - } - - } - - private class selectGridActionListener implements ActionListener - { - - public void actionPerformed(ActionEvent e) - { - /* get the selected Grid Field from the combobox, then recalculate the "Diff (Gage-Grid)" - field, and update the gage table window */ - - JComboBox cb = (JComboBox)e.getSource(); - String gridName = (String)cb.getSelectedItem(); - - getDataManager().set_mpe_selected_grid_gagediff(gridName); - System.out.println("updated _mpe_selected_grid_gagediff is :" + getDataManager().get_mpe_selected_grid_gagediff()); - - RefreshMenuListener refresh = new RefreshMenuListener(); - - refresh.actionPerformed(e); - - } - - } - -public String get_settingsFile() { - - return _settingsFile; -} - -public void set_settingsFile(String file) { - _settingsFile = file; -} - - - -public JComboBox get_selectGridList() { - return _selectGridList; -} - -public void set_selectGridList(JComboBox gridList) { - _selectGridList = gridList; -} - -public String [] get_gridDataName() { - return _gridDataName; -} - -public void set_gridDataName(String [] dataName) { - _gridDataName = dataName; -} - -public int get_selected_index() { - return _selected_index; -} - -public void set_selected_index(int _selected_index) { - this._selected_index = _selected_index; -} - - - -} diff --git a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableRowData.java b/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableRowData.java deleted file mode 100644 index 4109d88bf3..0000000000 --- a/javaUtilities/hydro/ohd.mpe/src/ohd/hseb/mpe/window/GageTableRowData.java +++ /dev/null @@ -1,121 +0,0 @@ -package ohd.hseb.mpe.window; - -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.DbTable; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class GageTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = "M"; - - // These are the parts of the Gage Table record - // which always present. - private String _gageId; - private String _radarId; - private float _value; - private Float _editValue; - private Double _diffValue; - private float _orginalValue; - private Map _productValueMap; - - public GageTableRowData( String gageId, float value, Float editValue, Double diffValue, String radarId, Map productValueMap) - { - - setGageId(gageId); - setValue(value); - setEditValue(editValue); - setDiffValue(diffValue); - setRadarId(radarId); - setOrginalValue(value); - setProductValueMap(productValueMap); - } - - public void setGageId(String gageId) - { - _gageId = gageId; - } - - public String getGageId() - { - return _gageId; - } - - public void setValue(float value) - { - _value = value; - } - - public float getValue() - { - return _value; - } - - public void addAllCellsToMap() - { - Set > mapEntrySet = null; - - addCell ( new BaseTableCell("LID", CellType.STRING, getGageId(), _missingRepresentation)); - addCell ( new BaseTableCell("Gage Value", CellType.FLOAT, getValue(), _missingRepresentation)); - addCell ( new BaseTableCell("Edit Gage Value", CellType.FLOAT, getEditValue(), "")); - addCell (new BaseTableCell("Diff (Gage-Grid)", CellType.DOUBLE, getDiffValue(), _missingRepresentation)); - addCell ( new BaseTableCell("Radar ID", CellType.STRING, getRadarId(), _missingRepresentation)); - - mapEntrySet = getProductValueMap().entrySet(); - - for ( Map.Entry mapEntry : mapEntrySet ) - { - addCell ( new BaseTableCell(mapEntry.getKey(), CellType.DOUBLE, mapEntry.getValue().doubleValue(), _missingRepresentation )); - } - } - - public void setProductValueMap(Map productValueMap) - { - _productValueMap = productValueMap; - } - - public Map getProductValueMap() - { - return _productValueMap; - } - - public void setOrginalValue(float orginalValue) - { - this._orginalValue = orginalValue; - } - - public float getOrginalValue() - { - return _orginalValue; - } - - public void setRadarId(String radarId) - { - _radarId = radarId; - } - - public String getRadarId() - { - return _radarId; - } - - public Float getEditValue() { - return _editValue; - } - - public void setEditValue(Float _editValue) { - this._editValue = _editValue; - } - - public Double getDiffValue() { - return _diffValue; - } - - public void setDiffValue(Double _diffValue) { - this._diffValue = _diffValue; - } - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/.classpath b/javaUtilities/hydro/ohd.pdc_pp/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.pdc_pp/.project b/javaUtilities/hydro/ohd.pdc_pp/.project deleted file mode 100644 index d3268ee648..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.pdc_pp - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.pdc_pp/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.pdc_pp/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index ea19aa0e3c..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 09:57:21 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.pdc_pp/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.pdc_pp/META-INF/MANIFEST.MF deleted file mode 100644 index 4738a544b1..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,12 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Pdc_pp -Bundle-SymbolicName: ohd.pdc_pp -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0", - ohd.ihfsdb;bundle-version="1.0.0" -Export-Package: ohd.hseb.pdc_pp, - ohd.hseb.pdc_pp.sample_data_set diff --git a/javaUtilities/hydro/ohd.pdc_pp/build.properties b/javaUtilities/hydro/ohd.pdc_pp/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.pdc_pp/build.xml b/javaUtilities/hydro/ohd.pdc_pp/build.xml deleted file mode 100644 index e4bf50ae3c..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/ohd.pdc_pp.ecl b/javaUtilities/hydro/ohd.pdc_pp/ohd.pdc_pp.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.pdc_pp/scripts/pdc_pp_test b/javaUtilities/hydro/ohd.pdc_pp/scripts/pdc_pp_test deleted file mode 100644 index efb0d70b8d..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/scripts/pdc_pp_test +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/ksh - -# File name: run_pdc_pp -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - - -export CONNECTION_STRING=$JDBCURL - -#get java dir -export SYS_JAVA_DIR=$($GAD_DIR/get_apps_defaults$OS_SUFFIX sys_java_dir) -export SYS_JAVA_BIN_DIR=$SYS_JAVA_DIR/bin - -# set java classpath - -export CLASSPATH=.:$SYS_JAVA_DIR\ -:$SYS_JAVA_BIN_DIR\ -:$DB_DRIVER_PATH\ -:$WHFS_BIN_DIR/pdc_pp.jar - -# set up an X Terminal window to write stdout and run the DamCrest -# application using java -$SYS_JAVA_BIN_DIR/java ohd.hseb.pdc_pp.sample_data_set.PDCPreProcessorTest $CONNECTION_STRING $PDC_PP_LOG_DIR \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/scripts/run_pdc_pp b/javaUtilities/hydro/ohd.pdc_pp/scripts/run_pdc_pp deleted file mode 100644 index 24f33800d2..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/scripts/run_pdc_pp +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/ksh - -# File name: run_pdc_pp -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -export CONNECTION_STRING=$JDBCURL -#export CONNECTION_STRING=jdbc:postgresql://lx1-nhdr:5432/hd_ob6rhax?user=oper - -#get java dir -export SYS_JAVA_DIR=$($GAD_DIR/get_apps_defaults$OS_SUFFIX sys_java_dir) -export SYS_JAVA_BIN_DIR=$SYS_JAVA_DIR/bin - -#truncate the preprocessor log -export LOGFILE=$PDC_PP_LOG_DIR/PDCPreprocessor.log -export LOGFILE_TMP=$PDC_PP_LOG_DIR/PDCPreprocessor.tmp -tail -12000 $LOGFILE > $LOGFILE_TMP -mv $LOGFILE_TMP $LOGFILE - - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH:$WHFS_BIN_DIR/pdc_pp.jar - -AMIRUNNING_DIR=$PDC_PP_LOG_DIR -. /awips/hydroapps/public/bin/amirunning - -if [[ $AmIRunning = "yes" ]] -then - echo Startup cancelled because of prior running instance >> $LOGFILE - exit 1 -fi - -#Execute the PDC Preprocessor -$SYS_JAVA_BIN_DIR/java ohd.hseb.pdc_pp.PDCPreprocessor $CONNECTION_STRING $1 >>$LOGFILE 2>&1 -exit \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/DailyTimeSlotPolicy.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/DailyTimeSlotPolicy.java deleted file mode 100644 index e6d6aecb47..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/DailyTimeSlotPolicy.java +++ /dev/null @@ -1,54 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Map; - -public class DailyTimeSlotPolicy implements TimeSlotPolicy -{ - public Long getSlotDateTimeInMillis( long originalDateTimeInMillis ) - { - - originalDateTimeInMillis = truncateTimeInMillisToDay( originalDateTimeInMillis ); - originalDateTimeInMillis += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; - - return new Long( originalDateTimeInMillis ); - } - - public void insertTimeValuePairIfBetterMatch( Map timeValuePairHashMap, TimeValuePair newTimeValuePair ) - { - long newTopOfTheHourDateTime = truncateTimeInMillisToDay( newTimeValuePair.getDateTime() ); - newTopOfTheHourDateTime += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; - - long newObsDateTimeDiff = 0; - long oldObsDateTimeDiff = 0; - Long topOfHourKey = new Long( newTopOfTheHourDateTime ); - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairHashMap.get( topOfHourKey ); - - newObsDateTimeDiff = Math.abs( newTimeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( timeValuePair == null ) - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - } - else - { - oldObsDateTimeDiff = Math.abs( timeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( oldObsDateTimeDiff > newObsDateTimeDiff ) // if new valuepair is closer to top of the hour - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - } - } - } - - private long truncateTimeInMillisToDay( long dateTime ) - { - long dateTimeReturnValue = dateTime; - - dateTimeReturnValue /= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - dateTimeReturnValue *= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - - return dateTimeReturnValue; - } - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/HourlyTimeSlotPolicy.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/HourlyTimeSlotPolicy.java deleted file mode 100644 index a08a0f9ac4..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/HourlyTimeSlotPolicy.java +++ /dev/null @@ -1,75 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Map; - -import ohd.hseb.util.TimeHelper; - -public class HourlyTimeSlotPolicy implements TimeSlotPolicy -{ - private long _minutesBeforeTopOfHour = PDCPreprocessorDataMgr._minutesBeforeTopOfHour; - private long _minutesAfterTopOfHour = PDCPreprocessorDataMgr._minutesAfterTopOfHour; - - public Long getSlotDateTimeInMillis( long originalDateTimeInMillis ) - { - return new Long( TimeHelper.roundTimeInMillisToNearestHour( originalDateTimeInMillis ) ); - } - - private boolean obsDateTimeInRange( long dateTime, long newTopOfTheHourDateTime ) - { - long lowerWindowMinutes = newTopOfTheHourDateTime - ( _minutesBeforeTopOfHour * 60 * 1000 ); - long upperWindowMinutes = newTopOfTheHourDateTime + ( _minutesAfterTopOfHour * 60 * 1000 ); - boolean inRange = false; - - if ( ( dateTime >= lowerWindowMinutes ) && ( dateTime <= upperWindowMinutes ) ) - { - inRange = true; - } - - return inRange; - } - - public void insertTimeValuePairIfBetterMatch( Map timeValuePairHashMap, TimeValuePair newTimeValuePair ) - { - - String header = "HourlyTimeSlotPolicy.insertTimeValuePairIfBetterMatch() "; - - long newTopOfTheHourDateTime = TimeHelper.roundTimeInMillisToNearestHour( newTimeValuePair.getDateTime() ); - long newObsDateTimeDiff = 0; - long oldObsDateTimeDiff = 0; - Long topOfHourKey = new Long( newTopOfTheHourDateTime ); - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairHashMap.get( topOfHourKey ); - - newObsDateTimeDiff = Math.abs( newTimeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( timeValuePair == null ) - { - if ( obsDateTimeInRange( newTimeValuePair.getDateTime(), newTopOfTheHourDateTime ) ) - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - // System.out.println(header + "null previous value, so put " + newTimeValuePair + " into the map"); - } - else - { - // System.out.println(header + " " + timeValuePair + " is out of the time range, so won't insert into the map"); - } - - } - else - { - oldObsDateTimeDiff = Math.abs( timeValuePair.getDateTime() - newTopOfTheHourDateTime ); - - if ( oldObsDateTimeDiff > newObsDateTimeDiff ) // if new valuepair is closer to top of the hour - { - timeValuePairHashMap.put( topOfHourKey, newTimeValuePair ); - // System.out.println(header + "closer than previous value, so put " + newTimeValuePair + " into the map"); - } - else - { - - // System.out.println(header + " " + newTimeValuePair + " is not closer in time than " + - // timeValuePair + " so won't insert into the map"); - } - } - } -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/IrregularObsTimeSeries.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/IrregularObsTimeSeries.java deleted file mode 100644 index fc8e2b6833..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/IrregularObsTimeSeries.java +++ /dev/null @@ -1,174 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Gautam Sood - * - */ -public class IrregularObsTimeSeries -{ - private RegularObsTimeSeriesDescriptor _obsTimeSeriesDescriptor; - private Map _timeValuePairMap = new HashMap(); - private boolean _valuePairListNeedsRefreshing = true; - private List _timeValuePairList = new ArrayList(); - private List _dateTimeList = new ArrayList(); - private long _timeStepIntervalInMillis = 0; - -/** - * @param descriptor - RegularObsTimeSeriesDescriptor - * @param timeStepIntervalInHours - Time step duration in hours. e.g. hourly timeseries, 6 hourly timeseries, etc - * @param timeSlotPolicy - Hourly or Daily time slot policy - */ - public IrregularObsTimeSeries( RegularObsTimeSeriesDescriptor descriptor, long timeStepIntervalInHours ) - { - _obsTimeSeriesDescriptor = descriptor; - _timeStepIntervalInMillis = timeStepIntervalInHours * PDCPreprocessorDataMgr.MILLIS_PER_HOUR; - } - - public IrregularObsTimeSeries( IrregularObsTimeSeries obsTimeSeries, long timeStepDurationInHours ) - { - setObsTimeSeriesDescriptor( obsTimeSeries.getDescriptor() ); - setTopOfTheHourTimeValuePairMap( obsTimeSeries.getTopOfTheHourTimeValuePairMap() ); - setDateTimeList( obsTimeSeries.getDateTimeList() ); - _timeStepIntervalInMillis = timeStepDurationInHours * PDCPreprocessorDataMgr.MILLIS_PER_HOUR; - } - - public String toString() - { - updateTimeValuePairList(); - - StringBuffer stringBuffer = new StringBuffer(); - - for ( int i = 0; i < _timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) _timeValuePairList.get( i ); - stringBuffer.append(timeValuePair); - } - return stringBuffer.toString(); - } - - public List getTimeValuePairList( boolean forceRefresh ) - { - if ( ( _valuePairListNeedsRefreshing ) || ( forceRefresh ) ) - { - updateTimeValuePairList(); - } - - return _timeValuePairList; - } - - private void setDateTimeList( List dateTimeList ) - { - _dateTimeList = dateTimeList; - } - - private List getDateTimeList() - { - return _dateTimeList; - } - - - private void updateTimeValuePairList() - { - _timeValuePairList.clear(); - - for ( int i = 0; i < _dateTimeList.size(); i++ ) - { - Long dateTimeLong = (Long) _dateTimeList.get( i ); - TimeValuePair timeValuePair = (TimeValuePair) _timeValuePairMap.get( dateTimeLong ); - _timeValuePairList.add( timeValuePair ); - } - - _valuePairListNeedsRefreshing = false; - return; - } - - public void addTimeValuePairIfBetterMatch( TimeValuePair newTimeValuePair ) - { - _valuePairListNeedsRefreshing = true; - - Long dateTimeLong = new Long( newTimeValuePair.getDateTime() ); - - _timeValuePairMap.put( dateTimeLong, newTimeValuePair ); - addDateTimeToDateTimeList( dateTimeLong ); - } - - private void addDateTimeToDateTimeList( Long dateTimeLong ) - { - int index = -1; - boolean found = false; - - for ( int i = 0; i < _dateTimeList.size(); i++ ) - { - Long dateTime = (Long) _dateTimeList.get( i ); - - - if ( dateTimeLong.longValue() < dateTime.longValue() ) - { - index = i; - found = true; - break; - } - } - - if ( found ) //descriptor inserted at index - { - _dateTimeList.add( index, dateTimeLong ); - } - else // descriptorlist is either empty or descriptor belongs at the end of the list - { - index = 0; - _dateTimeList.add( dateTimeLong ); - } - } - - - public void setObsTimeSeriesDescriptor( RegularObsTimeSeriesDescriptor obsTimeSeriesDescriptor ) - { - _obsTimeSeriesDescriptor = obsTimeSeriesDescriptor; - } - - public RegularObsTimeSeriesDescriptor getDescriptor() - { - return _obsTimeSeriesDescriptor; - } - - public void setTimeValuePairList( List timeValueList ) - { - _timeValuePairList.addAll( timeValueList ); - } - - public void addTimeValuePairList( List timeValueList ) - { - _valuePairListNeedsRefreshing = true; - for ( int i = 0; i < timeValueList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValueList.get( i ); - addTimeValuePairIfBetterMatch( timeValuePair ); - } - } - - public void setTopOfTheHourTimeValuePairMap( Map topOfTheHourTimeValuePairMap ) - { - _timeValuePairMap = topOfTheHourTimeValuePairMap; - } - - public Map getTopOfTheHourTimeValuePairMap() - { - return _timeValuePairMap; - } - - - /** - * @return Returns the timeStepDurationInMillis. - */ - public long getTimeStepIntervalInMillis() - { - return _timeStepIntervalInMillis; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/Location.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/Location.java deleted file mode 100644 index 826732d551..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/Location.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.pdc_pp; - -import ohd.hseb.model.RatingCurve; - -public class Location -{ - private String _lid = null; - private double _lat = 0; - private double _lon = 0; - private double _elevation = 0; - private String _locationName = null; - private boolean _isRiverStation = false; - private boolean _isFcstPoint = false; - private String _hsa = null; - private double _floodStage = 0; - private double _floodFlow = 0; - private RatingCurve _ratingCurve = null; - private boolean _isDCP = false; - private boolean _isObserver = false; - private String _telemType = null; - - public Location() - { - } - - public Location( Location location ) - { - _lid = location.getLid(); - _hsa = location.getHsa(); - _lat = location.getLat(); - _lon = location.getLon(); - _elevation = location.getElevation(); - _locationName = location.getLocationName(); - _isRiverStation = location.isRiverStation(); - _floodStage = location.getFloodStage(); - _floodFlow = location.getFloodFlow(); - _ratingCurve = location.getRatingCurve(); - _isDCP = location.isDCP(); - _isObserver = location.isObserver(); - _telemType = location.getTelemType(); - } - - public String toString() - { - String string = null; - - string = "LID = " + _lid + - " HSA = " + _hsa + - " Lat = " + _lat + - " Lon = " + _lon + - " Elev = " + _elevation + - " Location Name = " + _locationName + - " RiverStation = " + _isRiverStation + - " Flood Stage = " + _floodStage + - " Flood Flow = " + _floodFlow + - " DCP = " + _isDCP + - " Observer = " + _isObserver + - " Telem Type = " + _telemType; - - return string; - } - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setLat( double lat ) - { - _lat = lat; - } - public double getLat() - { - return _lat; - } - public void setLon( double lon ) - { - _lon = lon; - } - public double getLon() - { - return _lon; - } - public void setElevation( double elevation ) - { - _elevation = elevation; - } - public double getElevation() - { - return _elevation; - } - public void setLocationName( String locationName ) - { - _locationName = locationName; - } - public String getLocationName() - { - return _locationName; - } - - public void setRiverStation( boolean isRiverStation ) - { - _isRiverStation = isRiverStation; - } - - public boolean isRiverStation() - { - return _isRiverStation; - } - - public void setFloodStage( double floodStage ) - { - _floodStage = floodStage; - } - - public double getFloodStage() - { - return _floodStage; - } - - public void setHsa( String hsa ) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } - - public void setFcstPoint( boolean isFcstPoint ) - { - _isFcstPoint = isFcstPoint; - } - - public String isFcstPoint() - { - String result = "F"; - - if ( _isFcstPoint ) - { - result = "T"; - } - - return result; - } - - public void setFloodFlow( double floodFlow ) - { - _floodFlow = floodFlow; - } - - public double getFloodFlow() - { - return _floodFlow; - } - - public void setRatingCurve( RatingCurve ratingCurve ) - { - _ratingCurve = ratingCurve; - } - - public RatingCurve getRatingCurve() - { - return _ratingCurve; - } - - public void setDCP( boolean isDCP ) - { - _isDCP = isDCP; - } - - public boolean isDCP() - { - return _isDCP; - } - - public void setObserver( boolean isObserver ) - { - _isObserver = isObserver; - } - - public boolean isObserver() - { - return _isObserver; - } - - public void setTelemType( String telemType ) - { - _telemType = telemType; - } - - public String getTelemType() - { - return _telemType; - } -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/NonPrecipObsTableManager.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/NonPrecipObsTableManager.java deleted file mode 100644 index b990f18abf..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/NonPrecipObsTableManager.java +++ /dev/null @@ -1,258 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; - -import ohd.hseb.util.CodeTimer; - - - -public class NonPrecipObsTableManager extends DbTable -{ - public static final int DECIMAL_PLACES = 2; - - public NonPrecipObsTableManager(Database database, String tableName ) - { - //Constructor calls DbTable's constructor - super(database); - setTableName( tableName ); - } - - - //----------------------------------------------------------------- - // select() - this method is called with a where clause and returns - // a Vector of ObservedData objects - //----------------------------------------------------------------- - public List select( String tableName, int numHoursToProcess, long endTime ) throws SQLException - { - String header = "NonPrecipObsTableManager.select: "; - - CodeTimer nonPrecipObsTableTimer = new CodeTimer(); - if ( PDCPreprocessorDataMgr._DEBUG ) - { - nonPrecipObsTableTimer.start(); - } - RegularObsTimeSeriesDescriptor obsTimeSeriesDescriptor = - new RegularObsTimeSeriesDescriptor(); - RegularObsTimeSeries obsTimeSeries = null; - double value = 0.0; - long obsTime = 0; - TimeValuePair timeValuePair = null; - - long hourlyEndTime = TimeHelper.roundTimeInMillisToNearestHour( endTime ); - long hourlyStartTime = hourlyEndTime - - ( ( numHoursToProcess - 1) * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - - long dailyEndTime = truncateTimeInMillisToDay( endTime ); - dailyEndTime += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; //12z to 12z - long dailyStartTime = dailyEndTime - - ( ( numHoursToProcess ) * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - - String pe = null; - String extremum = null; - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - DailyTimeSlotPolicy dailyTimeSlotPolicy = new DailyTimeSlotPolicy(); - CodeTimer queryTimer = new CodeTimer(); - - List obsTimeSeriesList = new ArrayList(); - int recordsFound = 0; - - String tabbedheader = " " + header; - - Map obsTimeSeriesMap = new HashMap(); - - // create a List to hold Height Records - - // Create the SQL statement and issue it - // construct the select statment - String selectStatement = - "Select lid, pe, dur, extremum, ts, value, obstime from " + - tableName + " WHERE obstime >= '" + - DbTimeHelper.getDateTimeStringFromLongTime( hourlyStartTime ) + "'"; - - - // get the result set back from the query to the database - ResultSet rs = getStatement().executeQuery( selectStatement ); - - // loop through the result set - boolean rsNext = rs.next(); - - // Setting the start and end time for the timeseries - - while ( rsNext ) - { - obsTimeSeriesDescriptor.setLid( getTrimmedString( rs.getString( 1 ) ) ); - pe = getTrimmedString( rs.getString( 2 ) ); - obsTimeSeriesDescriptor.setPe( pe ); - obsTimeSeriesDescriptor.setDur( rs.getShort( 3 ) ); - extremum = getTrimmedString( rs.getString( 4 ) ); - obsTimeSeriesDescriptor.setExtremum( extremum ); - obsTimeSeriesDescriptor.setTs( getTrimmedString( rs.getString( 5 ) ) ); - value = MathHelper.roundToNDecimalPlaces(rs.getDouble( 6 ), DECIMAL_PLACES) ; - obsTime = getLongTime( rs.getString( 7 ) ); - - timeValuePair = new TimeValuePair( obsTime, value ); - - obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesMap.get( obsTimeSeriesDescriptor ); - - if ( obsTimeSeries == null ) - { - // Check for Air Temperature Daily MAX and MIN - if ( (pe.equalsIgnoreCase("TA")) && - ((extremum.equalsIgnoreCase("X")) || (extremum.equalsIgnoreCase("N"))) ) - { - obsTimeSeriesDescriptor.setEndTime( dailyEndTime ); - obsTimeSeriesDescriptor.setStartTime( dailyStartTime ); - - //System.out.println(header + "dailyEndTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(dailyEndTime)); - - RegularObsTimeSeriesDescriptor newDescriptor = - new RegularObsTimeSeriesDescriptor( obsTimeSeriesDescriptor ); - - obsTimeSeries = - new RegularObsTimeSeries( newDescriptor, 24, - dailyTimeSlotPolicy ); // 24 hour data - } - else - { - obsTimeSeriesDescriptor.setEndTime( hourlyEndTime ); - obsTimeSeriesDescriptor.setStartTime( hourlyStartTime ); - RegularObsTimeSeriesDescriptor newDescriptor = - new RegularObsTimeSeriesDescriptor( obsTimeSeriesDescriptor ); - - obsTimeSeries = new RegularObsTimeSeries( newDescriptor, 1, - hourlyTimeSlotPolicy ); // hourly data - } - - addTimeSeriesToOrderedList( obsTimeSeriesList, obsTimeSeries ); - - obsTimeSeriesMap.put( obsTimeSeries.getDescriptor(), obsTimeSeries ); - } - - - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - - // increment the number of records found - recordsFound++; - rsNext = rs.next(); - } - - System.out.println(header + "table = " + tableName + - " raw recordsFound = " + recordsFound); - - // Close the result set - rs.close(); - - - return obsTimeSeriesList; - } // end of select method - - -// ------------------------------------------------------------------------- - -/** - * - * @param dateTime - date/time in milliseconds - * @return - the date/time truncated to the day. e.g. 10-30-2005 5:00pm becomes 10-30-2005 12:00am - */ - private long truncateTimeInMillisToDay( long dateTime ) - { - long dateTimeReturnValue = dateTime; - - dateTimeReturnValue /= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - dateTimeReturnValue *= PDCPreprocessorDataMgr.MILLIS_PER_DAY; - - return dateTimeReturnValue; - } - - - // -------------------------------------------------------------------------------------------- - public void addTimeSeriesToOrderedList(List obsTimeSeriesList, RegularObsTimeSeries newTimeSeries ) - { - String header = "NonPrecipobsTableManager.addTimeSeriesToOrderedList(): "; - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - Comparator comparator = new RegularObsTimeSeriesComparator(); - - index = Collections.binarySearch(obsTimeSeriesList, newTimeSeries, comparator); // -4 - - // Add the non-existent item to the list - if (index < 0) - { - obsTimeSeriesList.add(-index-1, newTimeSeries); - } - else if (index == 0) - { - obsTimeSeriesList.add(index, newTimeSeries); - System.out.println(header + "Item added at 0 index in the list"); - } - - else - { - System.out.println(header + "Item aleady in the list"); - } - } - - // -------------------------------------------------------------------------------------------- - - - public void addTimeSeriesToOrderedList_old( List obsTimeSeriesList, - RegularObsTimeSeries newTimeSeries ) - { - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( i ); - - if ( newLid.compareToIgnoreCase( obsTimeSeries.getDescriptor().getLid() ) < 0 ) - { - index = i; - found = true; - break; - } - } - - if ( found ) //descriptor inserted at index - { - obsTimeSeriesList.add( index, newTimeSeries ); - } - else // descriptorlist is either empty or descriptor belongs at the end of the list - { - index = 0; - obsTimeSeriesList.add( newTimeSeries ); - } - } - - public long getLongTime( String timeString ) - { - long longTime = 0; - - longTime = getLongTimeFromDateTimeString( timeString ); - return longTime; - } - - public List select( String arg0 ) throws SQLException - { - throw new Error( "NonPrecipObsTable.select(String) should not be used" ); - } -} // end of HeightTable class diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileReader.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileReader.java deleted file mode 100644 index 88e8c6013c..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileReader.java +++ /dev/null @@ -1,496 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.InputMismatchException; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - - -public class PDCFileReader -{ - private List _obsTimeSeriesList; - private String _fullFilePath = null; - - private int _numberOfValues = 0; - private long _startTimeInSeconds = 0; - private int _timeIntervalInSeconds = 0; - private Map _durCodetoDurMap = null; - private boolean _debug = false; - - private BufferedReader _reader = null; - - private static final int SECONDS_PER_HOUR = 3600; - - - // ---------------------------------------------------------------------------------- - public PDCFileReader(String fullFilePath) - { - this(fullFilePath, PDCFileReader.getDurCodeToDurMap()); - } - - // ---------------------------------------------------------------------------------- - public PDCFileReader(String fullFilePath, Map durCodeToDurMap) - { - _fullFilePath = fullFilePath; - _durCodetoDurMap = durCodeToDurMap; - _obsTimeSeriesList = new ArrayList(); - } - - public void resetObsTimeSeriesList() - { - if(_obsTimeSeriesList == null) - _obsTimeSeriesList = new ArrayList(); - else - _obsTimeSeriesList.clear(); - - Runtime.getRuntime().gc(); - } - // ---------------------------------------------------------------------------------- - public List read() - { - String header = "PDCFileReader.read() "; - // boolean done = false; - - - try - { - FileReader fileReader = new FileReader(_fullFilePath); - _reader = new BufferedReader(fileReader); - - readFileHeader(); - - - String line = "DUMMY"; - - boolean done = false; - - while ( ! done ) - { - try - { - RegularObsTimeSeries timeSeries = readRegularStationData(); - if (timeSeries != null) - { - // debug_logline(header + - // " adding timeSeries to _obsTimeSeriesList " + - // timeSeries.getDescriptor() + - // " value pair list size() = " + - // timeSeries.getTimeValuePairList(true).size()); - - _obsTimeSeriesList.add(timeSeries); - - } - else - { - debug_logline(header + "timeSeries is null"); - } - - } - catch (EOFException e) - { - done = true; - } - catch (Exception e) - { - System.err.println(header + - "Exception reading file " + _fullFilePath + - " " + e.getMessage()); - e.printStackTrace(); - - done = true; - } - } //end while - - // System.out.println(header + "_obsTimeSeriesList contains " + - // _obsTimeSeriesList.size() + " time series. "); - - - if (_reader != null) - { - _reader.close(); - _reader = null; - } - - } //end try - catch (FileNotFoundException e) - { - System.err.println("Unable to open" + _fullFilePath); - _obsTimeSeriesList = null; - } - catch (IOException e) - { - System.err.println("Unable to open" + _fullFilePath); - _obsTimeSeriesList = null; - } - - return _obsTimeSeriesList; - } - - // ---------------------------------------------------------------------------------- - private void readFileHeader() throws IOException - { - String header = "PDCFileReader.readFileHeader(): "; - String line = null; - - //ignore the first 6 lines - line = _reader.readLine(); - debug_logline(header + " line 1 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 2 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 3 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 4 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 5 = " + line); - - line = _reader.readLine(); - debug_logline(header + " line 6 = " + line); - - String fileHeaderString = _reader.readLine(); - - StringTokenizer tokenizer = new StringTokenizer(fileHeaderString); - - _numberOfValues = Integer.parseInt(tokenizer.nextToken()); - - _startTimeInSeconds = Long.parseLong(tokenizer.nextToken()); - - _timeIntervalInSeconds = Integer.parseInt(tokenizer.nextToken()); - - - debug_logline("_numberOfHours = " + _numberOfValues + - " _startTimeInSeconds = " + _startTimeInSeconds + - " _timeIntervalInSeconds = " + _timeIntervalInSeconds ); - - } - // ---------------------------------------------------------------------------------- - private RegularObsTimeSeries readRegularStationData() throws Exception - { - - String header = "PDCFileReader.readRegularStationData() "; - RegularObsTimeSeriesDescriptor descriptor = readStationHeader(); - - debug_log(header + "descriptor = " + descriptor + "\n"); - - TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - - long timeIntervalInHours = _timeIntervalInSeconds/SECONDS_PER_HOUR ; - - RegularObsTimeSeries timeSeries = new RegularObsTimeSeries(descriptor, - timeIntervalInHours, - timeSlotPolicy); - - try - { - readValues(timeSeries); - } - catch (Exception e) - { - System.err.println(header + - "Error when reading values for descriptor = " + - descriptor); - e.printStackTrace(); - } - - // System.out.println(header + "returning timeSeries = " + timeSeries); - return timeSeries; - } - - - // ---------------------------------------------------------------------------------- - - private RegularObsTimeSeriesDescriptor readStationHeader() throws IOException - { - String header = "PDCFileReader.readStationHeader(): "; - - - String stationHeaderLine = _reader.readLine(); - - - - StringTokenizer headerTokenizer = new StringTokenizer(stationHeaderLine); - // Scanner headerScanner = new Scanner(stationHeaderLine); - - String deviceLine = _reader.readLine(); - - if ( (stationHeaderLine == null) || (deviceLine == null) ) - { - throw new EOFException(); - } - - StringTokenizer deviceLineTokenizer = new StringTokenizer(deviceLine); - - // Scanner deviceScanner = new Scanner(deviceLine); - - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - - long startTimeInMillis = _startTimeInSeconds * 1000; - long timeIntervalInMillis = _timeIntervalInSeconds * 1000; - long endTimeInMillis = startTimeInMillis + ((_numberOfValues-1) * timeIntervalInMillis); - - descriptor.setStartTime(startTimeInMillis); - descriptor.setEndTime(endTimeInMillis) ; - - String lid = headerTokenizer.nextToken(); - descriptor.setLid(lid); - - String hsa = headerTokenizer.nextToken(); - String paramCode = headerTokenizer.nextToken(); - - debug_logline("lid = " + lid + - " hsa = " + hsa + - " paramCode = " + paramCode); - - - //Work on the ParamCode. It is in multiple parts - setPedtse(descriptor, paramCode); - - double elevation = Double.parseDouble(headerTokenizer.nextToken()); - double lat = Double.parseDouble(headerTokenizer.nextToken()); - double lon = Double.parseDouble(headerTokenizer.nextToken()); - String fcst_pointString = headerTokenizer.nextToken(); - String name = restOfLine(headerTokenizer); - name = name.trim(); - - debug_logline(header + "name = :" + name + ":"); - - - // parse out the device line - String dcpString = deviceLineTokenizer.nextToken(); - String observerString = deviceLineTokenizer.nextToken(); - String telemTypes = restOfLine(deviceLineTokenizer); - - debug_logline(""); - debug_logline("dcpString = " + dcpString + - " observerString = " + observerString + - " telemTypes String = " + telemTypes); - - // descriptor.setHsa // can't do it easily, but don't need it anyway - - // System.out.println(header + " descriptor = " + descriptor); - - return descriptor; - } - - // ---------------------------------------------------------------------------------- - String restOfLine(StringTokenizer tokenizer) - { - String header = "PDCFileReader.restOfLine(): "; - - StringBuffer buffer = new StringBuffer(); - - int count = 0; - - while (tokenizer.hasMoreTokens()) - { - buffer.append(tokenizer.nextToken() + " "); - count++; - } - - //get rid of extra " " at the end - if (count > 0) - { - int spaceIndex = buffer.lastIndexOf(" "); - buffer.delete(spaceIndex, spaceIndex+1); - } - - String restOfLineString = buffer.toString(); - - // debug_log(header + " restofLine = " + restOfLineString + "\n"); - - return restOfLineString; - } - - // ---------------------------------------------------------------------------------- - private void setPedtse(RegularObsTimeSeriesDescriptor descriptor, String paramCode) - { - - int length = paramCode.length(); - - try - { - descriptor.setPe(paramCode.substring(0, 2)); - - String durCodeString = paramCode.substring(2, 3); - String durString = (String) _durCodetoDurMap.get(durCodeString); - short dur = 0; - - if (durString != null) - { - dur = Short.parseShort(durString); - } - - descriptor.setDur(dur); - - String typeSource = paramCode.substring(3, 5); - descriptor.setTs(typeSource); - - String extremum = paramCode.substring(5, 6); - - descriptor.setExtremum(extremum); - } - catch (Error e) - { - - } - - return; - } - // ---------------------------------------------------------------------------------- - - private void readValues(RegularObsTimeSeries timeSeries) throws IOException - { - String header = "PDCFileReader.readValues(): "; - long time = _startTimeInSeconds * 1000; - long incrementTime = timeSeries.getTimeStepIntervalInMillis(); - - RegularObsTimeSeriesDescriptor desc = timeSeries.getDescriptor(); - - double value = 0.0; - - List pairList = new ArrayList(); - - debug_logline(header + "attempting to read " + _numberOfValues + " values."); - - String valueLine = _reader.readLine(); - StringTokenizer tokenizer = new StringTokenizer(valueLine); - boolean isMissing = false; - - - if (valueLine.indexOf("MISSING") > -1) - { - System.out.println(header + " time series " + desc.toString() + " is SET to MISSING!"); - desc.setMissing(true); - isMissing = true; - } - - - for (int i = 0; i < _numberOfValues; i++) - { - try - { - if (isMissing) - { - value = PDCFileWriter.MISSING; - } - else - { - value = Double.parseDouble(tokenizer.nextToken()); - } - - debug_log("value[" + i +"] = " + value); - } - catch (InputMismatchException e1) - { - debug_log("when i = " + i); - debug_logline("read in a bad value from line = " + valueLine); - - throw (new InputMismatchException("bad read at entry # " + - i + " (starts at 0)" + - " value line = " + valueLine + - " TS Descriptor = " + desc )); - } - - TimeValuePair pair = new TimeValuePair(time, value); - pairList.add(pair); - - time += incrementTime; - } - - debug_logline(""); - - timeSeries.addTimeValuePairList(pairList); - - // int size = timeSeries.getTimeValuePairList(true).size(); - - // System.out.println(header + "timeSeries.getTimeValuePairList(true).size() = " + size ); - - - return; - } - - // ---------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - String fileName = "/fs/hseb/ob72/wfo_rfc/whfs/local/data/pdc_pp/keep/cachedWind.dat"; - - Map durCodeToDurMap = getDurCodeToDurMap(); - - PDCFileReader reader = new PDCFileReader (fileName, durCodeToDurMap); - reader.setDebug(true); - - reader.read(); - - - } - // ---------------------------------------------------------------------------------- - private static Map getDurCodeToDurMap() - { - // used just for testing. Real code uses database to access - //shefdur table. - Map durCodeToDurMap = new HashMap(); - - addCodeToMap(durCodeToDurMap, "I", 0); - addCodeToMap(durCodeToDurMap, "H", 1001); - addCodeToMap(durCodeToDurMap, "B", 1002); - addCodeToMap(durCodeToDurMap, "T", 1003); - addCodeToMap(durCodeToDurMap, "F", 1004); - addCodeToMap(durCodeToDurMap, "Q", 1006); - addCodeToMap(durCodeToDurMap, "D", 2001); - addCodeToMap(durCodeToDurMap, "Z", 5000); - - - return durCodeToDurMap; - } - - private static void addCodeToMap(Map durCodeToDurMap, String durCode, int duration) - { - durCodeToDurMap.put(durCode, duration + ""); - } - /** - * @param debug The debug to set. - */ - public void setDebug(boolean debug) - { - this._debug = debug; - } - /** - * @return Returns the debug. - */ - public boolean getDebug() - { - return _debug; - } - - // ---------------------------------------------------------------------------------- - private void debug_logline(String message) - { - debug_log(message + '\n'); - - return; - } - // ---------------------------------------------------------------------------------- - private void debug_log(String message) - { - if (getDebug()) - { - System.out.print(message); - } - - return; - } - // ---------------------------------------------------------------------------------- -} - - diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileReaderSlow.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileReaderSlow.java deleted file mode 100644 index ad3d5de40e..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileReaderSlow.java +++ /dev/null @@ -1,422 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.InputMismatchException; -import java.util.List; -import java.util.Map; -import java.util.Scanner; - - -public class PDCFileReaderSlow -{ - private List _obsTimeSeriesList; - private String _fullFilePath = null; - private Scanner _scanner = null; - - private int _numberOfValues = 0; - private long _startTimeInSeconds = 0; - private int _timeIntervalInSeconds = 0; - private Map _durCodetoDurMap = null; - private boolean _debug = false; - - - - private static final int SECONDS_PER_HOUR = 3600; - - - // ---------------------------------------------------------------------------------- - public PDCFileReaderSlow(String fullFilePath) - { - this(fullFilePath, PDCFileReaderSlow.getDurCodeToDurMap()); - } - - // ---------------------------------------------------------------------------------- - public PDCFileReaderSlow(String fullFilePath, Map durCodeToDurMap) - { - _fullFilePath = fullFilePath; - _durCodetoDurMap = durCodeToDurMap; - - _obsTimeSeriesList = new ArrayList(); - } - // ---------------------------------------------------------------------------------- - public List read() - { - String header = "PDCFileReaderSlow.read() "; - // boolean done = false; - - try - { - FileReader fileReader = new FileReader(_fullFilePath); - BufferedReader reader = new BufferedReader(fileReader); - _scanner = new Scanner ( reader ); - - readFileHeader(); - - while ( _scanner.hasNext() ) - { - try - { - RegularObsTimeSeries timeSeries = readRegularStationData(); - if (timeSeries != null) - { - // debug_logline(header + - // " adding timeSeries to _obsTimeSeriesList " + - // timeSeries.getDescriptor() + - // " value pair list size() = " + - // timeSeries.getTimeValuePairList(true).size()); - - _obsTimeSeriesList.add(timeSeries); - - } - else - { - debug_logline(header + "timeSeries is null"); - } - - } - catch (Exception e) - { - System.err.println(header + - "Exception reading file " + _fullFilePath + - " " + e.getMessage()); - e.printStackTrace(); - // done = true; - } - } - - // System.out.println(header + "_obsTimeSeriesList contains " + - // _obsTimeSeriesList.size() + " time series. "); - - - } - catch (FileNotFoundException e) - { - System.err.println("Unable to open" + _fullFilePath); - _obsTimeSeriesList = null; - } - - if (_scanner != null) - { - _scanner.close(); - } - - return _obsTimeSeriesList; - } - - // ---------------------------------------------------------------------------------- - private void readFileHeader() - { - String header = "PDCFileReaderSlow.readFileHeader(): "; - String line = null; - - //ignore the first 6 lines - line = _scanner.nextLine(); - debug_logline(header + " line 1 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 2 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 3 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 4 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 5 = " + line); - - line = _scanner.nextLine(); - debug_logline(header + " line 6 = " + line); - - String fileHeaderString = _scanner.nextLine(); - Scanner fileHeaderScanner = new Scanner(fileHeaderString); - - - _numberOfValues = fileHeaderScanner.nextInt(); - - _startTimeInSeconds = fileHeaderScanner.nextLong(); - - _timeIntervalInSeconds = fileHeaderScanner.nextInt(); - - - debug_logline("_numberOfHours = " + _numberOfValues + - " _startTimeInSeconds = " + _startTimeInSeconds + - " _timeIntervalInSeconds = " + _timeIntervalInSeconds ); - - } - // ---------------------------------------------------------------------------------- - private RegularObsTimeSeries readRegularStationData() throws Exception - { - - String header = "PDCFileReaderSlow.readRegularStationData() "; - RegularObsTimeSeriesDescriptor descriptor = readStationHeader(); - - debug_log(header + "descriptor = " + descriptor); - - TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - - long timeIntervalInHours = _timeIntervalInSeconds/SECONDS_PER_HOUR ; - - RegularObsTimeSeries timeSeries = new RegularObsTimeSeries(descriptor, - timeIntervalInHours, - timeSlotPolicy); - - try - { - readValues(timeSeries); - } - catch (Exception e) - { - System.err.println(header + - "Error when reading values for descriptor = " + - descriptor); - e.printStackTrace(); - } - - // System.out.println(header + "returning timeSeries = " + timeSeries); - return timeSeries; - } - - - // ---------------------------------------------------------------------------------- - - private RegularObsTimeSeriesDescriptor readStationHeader() - { - - String stationHeaderLine = _scanner.nextLine(); - Scanner headerScanner = new Scanner(stationHeaderLine); - - String deviceLine = _scanner.nextLine(); - Scanner deviceScanner = new Scanner(deviceLine); - - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - String header = "PDCFileReaderSlow.readStationHeader(): "; - long startTimeInMillis = _startTimeInSeconds * 1000; - long timeIntervalInMillis = _timeIntervalInSeconds * 1000; - long endTimeInMillis = startTimeInMillis + ((_numberOfValues-1) * timeIntervalInMillis); - - descriptor.setStartTime(startTimeInMillis); - descriptor.setEndTime(endTimeInMillis) ; - - String lid = headerScanner.next(); - descriptor.setLid(lid); - - String hsa = headerScanner.next(); - String paramCode = headerScanner.next(); - - //Work on the ParamCode. It is in multiple parts - setPedtse(descriptor, paramCode); - - double elevation = headerScanner.nextDouble(); - double lat = headerScanner.nextDouble(); - double lon = headerScanner.nextDouble(); - String fcst_pointString = headerScanner.next(); - String name = headerScanner.nextLine(); - name = name.trim(); - - debug_logline(header + "name = :" + name + ":"); - - - // parse out the device line - String dcpString = deviceScanner.next(); - String observerString = deviceScanner.next(); - String telemTypes = deviceScanner.nextLine(); - - debug_logline(""); - debug_logline("dcpString = " + dcpString + - " observerString = " + observerString + - " telemTypes String = " + telemTypes); - - // descriptor.setHsa // can't do it easily, but don't need it anyway - - // System.out.println(header + " descriptor = " + descriptor); - - return descriptor; - } - - // ---------------------------------------------------------------------------------- - private void setPedtse(RegularObsTimeSeriesDescriptor descriptor, String paramCode) - { - - int length = paramCode.length(); - - try - { - descriptor.setPe(paramCode.substring(0, 2)); - - String durCodeString = paramCode.substring(2, 3); - String durString = (String) _durCodetoDurMap.get(durCodeString); - short dur = 0; - - if (durString != null) - { - dur = Short.parseShort(durString); - } - - descriptor.setDur(dur); - - String typeSource = paramCode.substring(3, 5); - descriptor.setTs(typeSource); - - String extremum = paramCode.substring(5, 6); - - descriptor.setExtremum(extremum); - } - catch (Error e) - { - - } - - return; - } - // ---------------------------------------------------------------------------------- - - private void readValues(RegularObsTimeSeries timeSeries) - { - String header = "PDCFileReaderSlow.readValues(): "; - long time = _startTimeInSeconds * 1000; - long incrementTime = timeSeries.getTimeStepIntervalInMillis(); - - RegularObsTimeSeriesDescriptor desc = timeSeries.getDescriptor(); - - double value = 0.0; - - List pairList = new ArrayList(); - - debug_logline(header + "attempting to read " + _numberOfValues + " values."); - - String valueLine = _scanner.nextLine(); - Scanner valueScanner = new Scanner(valueLine); - boolean isMissing = false; - - - if (valueLine.indexOf("MISSING") > -1) - { - System.out.println(header + " time series " + desc.toString() + " is SET to MISSING!"); - desc.setMissing(true); - isMissing = true; - } - - - for (int i = 0; i < _numberOfValues; i++) - { - try - { - if (isMissing) - { - value = PDCFileWriter.MISSING; - } - else - { - value = valueScanner.nextDouble(); - } - - // debug_log("value[" + i +"] = " + value); - } - catch (InputMismatchException e1) - { - debug_log("when i = " + i); - debug_logline("read in a bad value from line = " + valueLine); - - throw (new InputMismatchException("bad read at entry # " + - i + " (starts at 0)" + - " value line = " + valueLine + - " TS Descriptor = " + desc )); - } - - TimeValuePair pair = new TimeValuePair(time, value); - pairList.add(pair); - - time += incrementTime; - } - - debug_logline(""); - - timeSeries.addTimeValuePairList(pairList); - - // int size = timeSeries.getTimeValuePairList(true).size(); - - // System.out.println(header + "timeSeries.getTimeValuePairList(true).size() = " + size ); - - - return; - } - - // ---------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - String fileName = "/fs/hseb/ob72/wfo_rfc/whfs/local/data/pdc_pp/keep/cachedWind.dat"; - - Map durCodeToDurMap = getDurCodeToDurMap(); - - PDCFileReaderSlow reader = new PDCFileReaderSlow (fileName, durCodeToDurMap); - reader.setDebug(true); - - reader.read(); - - - } - // ---------------------------------------------------------------------------------- - private static Map getDurCodeToDurMap() - { - // used just for testing. Real code uses database to access - //shefdur table. - Map durCodeToDurMap = new HashMap(); - - addCodeToMap(durCodeToDurMap, "I", 0); - addCodeToMap(durCodeToDurMap, "H", 1001); - addCodeToMap(durCodeToDurMap, "B", 1002); - addCodeToMap(durCodeToDurMap, "T", 1003); - addCodeToMap(durCodeToDurMap, "F", 1004); - addCodeToMap(durCodeToDurMap, "Q", 1006); - addCodeToMap(durCodeToDurMap, "D", 2001); - addCodeToMap(durCodeToDurMap, "Z", 5000); - - - return durCodeToDurMap; - } - - private static void addCodeToMap(Map durCodeToDurMap, String durCode, int duration) - { - durCodeToDurMap.put(durCode, duration + ""); - } - /** - * @param debug The debug to set. - */ - public void setDebug(boolean debug) - { - this._debug = debug; - } - /** - * @return Returns the debug. - */ - public boolean getDebug() - { - return _debug; - } - - // ---------------------------------------------------------------------------------- - private void debug_logline(String message) - { - debug_log(message + '\n'); - - return; - } - // ---------------------------------------------------------------------------------- - private void debug_log(String message) - { - if (getDebug()) - { - System.out.print(message); - } - - return; - } - // ---------------------------------------------------------------------------------- -} - - diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileWriter.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileWriter.java deleted file mode 100644 index 5781c39b0c..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCFileWriter.java +++ /dev/null @@ -1,822 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.text.DecimalFormat; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; - -public class PDCFileWriter -{ - public static final int MISSING = -9999; - private static final double MISSING_DOUBLE = MISSING; - - - private String _preprocessedFilePath = null; - private boolean _fileIsOpen = false; - private boolean _keepPreprocessedFileOpen = false; - private OutputStream _outputStream = null; - private PrintWriter _writer = null; - - private Map _locationHashMap = null; - private Map _shefDurMap = null; - // private Map _shefDurToDurcodeMap = null; - - - private boolean _DEBUG = false; - - CodeTimer _timeSeriesOutputStringTimer = null; - - private long _startTime = 0; - private long _endTime = 0; - - - //this will change during the processing - //it exists solely for monitor different parts of the processing - private int _timeSeriesValueCount = 0; - - - // ------------------------------------------------------------------------------ - - public PDCFileWriter(Map locationHashMap, - Map shefDurMap, - Map shefDurToDurcodeMap, - String preprocessedFilePath) - { - _locationHashMap = locationHashMap; - _shefDurMap = shefDurMap; - // _shefDurToDurcodeMap = shefDurToDurcodeMap; - _preprocessedFilePath = preprocessedFilePath; - - return; - } - // ---------------------------------------------------------------------------------- - - public void writeIrregularObsDataToFile( List obsTimeSeriesList, String fileName ) - { - - _timeSeriesOutputStringTimer = new CodeTimer(); - //_decimalFormatTimer = new CodeTimer(); - - if ( ( obsTimeSeriesList != null ) && (! obsTimeSeriesList.isEmpty() ) ) - { - String header = "PDCFileWriter.writeIrregularObsDataToFile(): "; - StringBuffer outputStringBuffer = new StringBuffer(); - String finalPreProcessedFileName = _preprocessedFilePath + fileName + ".dat"; - String preProcessedWorkFileName = finalPreProcessedFileName + ".work"; - - - //open if needed - if (!isPreprocessedFileOpen()) - { - // System.out.println("writeIrregularObsDataToFile() : Opening " + fileName); - openPreProcessedFile( preProcessedWorkFileName ); - // _writer = new PrintWriter( _outputStream ); - } - - // write out the message, pre-pending date time stamp if required - if ( _DEBUG ) - { - System.out.println( "Writing out to file: " + _preprocessedFilePath + fileName + ".dat" ); - System.out.flush(); - } - - long curTime = System.currentTimeMillis(); - outputStringBuffer.append( "Created on: " + - DbTimeHelper.getDateTimeStringFromLongTime( curTime ) + "\n" ); - - outputStringBuffer.append( "####(file header)NUM_OF_VALUES START_TIME TIME_INTERVAL_BETWEEN_VALUES_IN_SECONDS\n" ); - outputStringBuffer.append( "####LID HSA PEDSTE ELEV LAT LON FCST_PNT(T/F) STATION_NAME\n" ); - outputStringBuffer.append( "####DCP_FLAG OBSERVER_FLAG TELEM_TYPE_STRINGS \n" ); - outputStringBuffer.append( "####VALUES\n" ); - if ( obsTimeSeriesList != null ) - { - IrregularObsTimeSeries firstObsTimeSeries = (IrregularObsTimeSeries) obsTimeSeriesList.get( 0 ); - int num_of_values = firstObsTimeSeries.getTimeValuePairList( true ).size(); - long start_time = firstObsTimeSeries.getDescriptor().getStartTime(); - long timeStepIntervalInMillis = firstObsTimeSeries.getTimeStepIntervalInMillis(); - long timeStepIntervalInSeconds = timeStepIntervalInMillis / 1000; - - long end_time = firstObsTimeSeries.getDescriptor().getEndTime(); - - // long end_time = start_time + ( (num_of_values - 1) * timeStepIntervalInMillis ); - - - /* - * long start_time = firstObsTimeSeries.getDescriptor().getStartTime(); - long end_time = firstObsTimeSeries.getDescriptor().getEndTime(); - * - */ - - outputStringBuffer.append("#### start time = " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " end time = " + - DbTimeHelper.getDateTimeStringFromLongTime(end_time) + '\n'); - - - - if ( _DEBUG ) - { - outputStringBuffer.append( num_of_values + " " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " " + timeStepIntervalInSeconds + "\n" ); - } - else - { - outputStringBuffer.append( num_of_values + " " + start_time/1000 + - " " + timeStepIntervalInSeconds + "\n" ); - } - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - IrregularObsTimeSeries obsTimeSeries = (IrregularObsTimeSeries) obsTimeSeriesList.get( i ); - if ( obsTimeSeries != null ) - { - outputStringBuffer.append( getOutputStringFromLocationAndIrregularObsTimeSeries( obsTimeSeries ) ); - } - } - } - else - { - outputStringBuffer.append("#### start time = UNKNOWN " + - " end time = UNKNOWN \n"); - - } - - _writer.println( outputStringBuffer ); - _writer.flush(); - - //close if supposed to do so - if (! _keepPreprocessedFileOpen ) - { - // System.out.println("writeIrregularObsDataToFile() closing the file"); - closePreprocessedFile(); - File workFile = new File( preProcessedWorkFileName ); - File finalFile = new File ( finalPreProcessedFileName ); - finalFile.delete(); - workFile.renameTo( new File( finalPreProcessedFileName ) ); - } - } - } - -// ------------------------------------------------------------------------ - - private String getOutputStringFromLocationAndIrregularObsTimeSeries( IrregularObsTimeSeries obsTimeSeries ) - { - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - String lid = descriptor.getLid(); - String shef_param_code = null; - Location location = (Location) _locationHashMap.get( lid ); - StringBuffer outputString = new StringBuffer(); - - shef_param_code = descriptor.getPe() + _shefDurMap.get( "" + descriptor.getDur() ) + - descriptor.getTs() + descriptor.getExtremum(); - descriptor.setShef_param_code( shef_param_code ); - outputString.append( location.getLid() + " " + location.getHsa() + " " + - descriptor.getShef_param_code() + " " + location.getElevation() + " " + - location.getLat() + " " + location.getLon() + " " + location.isFcstPoint() + " " + - location.getLocationName() + "\n" ); - - if ( location.isDCP() ) - { - outputString.append( "T " ); - } - else - { - outputString.append( "F " ); - } - - if ( location.isObserver() ) - { - outputString.append( "T " ); - } - else - { - outputString.append( "F " ); - } - - if ( ( location.getTelemType() == null ) || (location.getTelemType().length() == 0) ) - { - outputString.append( "NO_TELEM_TYPE" ); - } - else - { - outputString.append( location.getTelemType() ); - } - outputString.append( "\n" + getIrregularObsTimeSeriesOutputString( obsTimeSeries ) + "\n" ); - - - return outputString.toString(); - } - -// ------------------------------------------------------------------------ - private String getIrregularObsTimeSeriesOutputString( IrregularObsTimeSeries obsTimeSeries ) - { - String header = "PDCFileWriter.getIrregularObsTimeSeriesOutputString(): "; - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String missingDoubleString = getFormattedNumber(MISSING_DOUBLE, decimalFormat) + ""; - - StringBuffer outputStringBuffer = new StringBuffer(); - - double formattedNumber = 0.0; - String dateTimeString = null; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - - dateTimeString = DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime()); - // formattedNumber = getFormattedNumber(timeValuePair.getValue(), decimalFormat ); - outputStringBuffer.append( dateTimeString + "|" + - timeValuePair.getValue() + "\n"); - - - } - else - { - outputStringBuffer.append(timeValuePair.getValue() + " "); - } - } - else - { - if ( _DEBUG ) - { - outputStringBuffer.append(missingDoubleString + "\n"); - } - else - { - outputStringBuffer.append(missingDoubleString + " "); - } - - } - } - return outputStringBuffer.toString(); - } - - - private String old_getIrregularObsTimeSeriesOutputString( IrregularObsTimeSeries obsTimeSeries ) - { - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String outputString = ""; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - outputString += DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime() ) + - "|" + decimalFormat.format( timeValuePair.getValue() ) + "\n"; - } - else - { - outputString += decimalFormat.format( timeValuePair.getValue() ) + " "; - } - } - else - { - if ( _DEBUG ) - { - outputString += MISSING_DOUBLE + "\n"; - } - else - { - outputString += MISSING_DOUBLE + " "; - } - } - } - return outputString; - } - -// ------------------------------------------------------------------------ - public void writeRegularObsDataToFile( List obsTimeSeriesList, String fileName ) - { - String header = "PDCFileWriter.writeRegularObsDataToFile(): "; - CodeTimer fileTimer = new CodeTimer(); - // CodeTimer outputStringTimer = new CodeTimer(); - - _timeSeriesOutputStringTimer = new CodeTimer(); - // _decimalFormatTimer = new CodeTimer(); - - - if ( ( obsTimeSeriesList != null ) && (! obsTimeSeriesList.isEmpty() ) ) - { - - StringBuffer outputStringBuffer = new StringBuffer(); - String finalPreProcessedFileName = _preprocessedFilePath + fileName + ".dat"; - String preProcessedWorkFileName = finalPreProcessedFileName + ".work"; - - //open if needed - if (!isPreprocessedFileOpen()) - { - openPreProcessedFile( preProcessedWorkFileName ); - // _writer = new PrintWriter(_outputStream); - } - - if ( _DEBUG ) - { - System.out.println( "Writing out to file: " + _preprocessedFilePath + fileName + ".dat" ); - System.out.flush(); - } - - long curTime = System.currentTimeMillis(); - // write out the message, pre-pending date time stamp if required - if ( _DEBUG ) - { - - outputStringBuffer.append( "DEBUGGABLE OUTPUT FILE Created on: " + - DbTimeHelper.getDateTimeStringFromLongTime( curTime ) + "\n" ); - } - else - { - outputStringBuffer.append( "Created on: " + - DbTimeHelper.getDateTimeStringFromLongTime( curTime ) + "\n" ); - } - - outputStringBuffer.append( "####(file header)NUM_OF_VALUES START_TIME TIME_INTERVAL_BETWEEN_VALUES_IN_SECONDS\n" ); - outputStringBuffer.append( "####LID HSA PEDSTE ELEV LAT LON FCST_PNT(T/F) STATION_NAME\n" ); - outputStringBuffer.append( "####DCP_FLAG OBSERVER_FLAG TELEM_TYPE_STRINGS \n" ); - outputStringBuffer.append( "####VALUES\n" ); - if ( ( obsTimeSeriesList != null ) && (obsTimeSeriesList.size() > 0) ) - { - RegularObsTimeSeries firstObsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( 0 ); - int num_of_values = firstObsTimeSeries.getTimeValuePairList( true ).size(); - - _timeSeriesValueCount = num_of_values; - - long start_time = firstObsTimeSeries.getDescriptor().getStartTime(); - long timeStepIntervalInMillis = firstObsTimeSeries.getTimeStepIntervalInMillis(); - long timeStepIntervalInSeconds = timeStepIntervalInMillis / 1000; - long end_time = start_time + ( (num_of_values - 1) * timeStepIntervalInMillis ); - - _startTime = start_time; - _endTime = end_time; - - outputStringBuffer.append("#### start time = " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " end time = " + - DbTimeHelper.getDateTimeStringFromLongTime(end_time) + '\n'); - - if ( _DEBUG ) - { - outputStringBuffer.append( num_of_values + " " + - DbTimeHelper.getDateTimeStringFromLongTime( start_time ) + - " " + timeStepIntervalInSeconds + "\n" ); - } - else - { - outputStringBuffer.append( num_of_values + " " + start_time/1000 + - " " + timeStepIntervalInSeconds + "\n" ); - } - - - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( i ); - if ( obsTimeSeries != null ) - { - outputStringBuffer.append( - getRegularObsTimeSeriesOutputStringWhenMergedWithLocation( obsTimeSeries ) ); - - } - } - } - else - { - outputStringBuffer.append("#### start time = UNKNOWN" + - " end time = UNKNOWN \n"); - - return; - } - - - - //System.out.println(header + - // "creating the output string from each obsTimeSeries and its location entry took a total of " + - // outputStringTimer.getElapsedTime() + " millis."); - - // System.out.println(header + - // "creating the output string from each obsTimeSeries alone took a total of " + - // _timeSeriesOutputStringTimer.getElapsedTime() + " millis."); - - - - // fileTimer.start(); - _writer.println( outputStringBuffer ); - // fileTimer.stop(header + "writing the outputStringBuffer to the file took"); - _writer.flush(); - - // close if supposed to do so - if (!_keepPreprocessedFileOpen) - { - closePreprocessedFile(); - File workFile = new File(preProcessedWorkFileName); - File finalFile = new File(finalPreProcessedFileName); - finalFile.delete(); - workFile.renameTo(new File(finalPreProcessedFileName)); - } - } - } - -// ------------------------------------------------------------------------ - - private StringBuffer getRegularObsTimeSeriesOutputStringWhenMergedWithLocation( RegularObsTimeSeries obsTimeSeries ) - { - String header = "PDCFileWriter.getRegularObsTimeSeriesOutputStringWhenMergedWithLocation(): "; - - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - - if (descriptor == null) - { - System.out.println(header + " ***************** the time series descriptor is null"); - } - - String lid = descriptor.getLid(); - String shef_param_code = null; - Location location = (Location) _locationHashMap.get( lid ); - - - StringBuffer outputStringBuffer = new StringBuffer(); - - - if (location == null) - { - System.out.println(header + " ***************** the location object is null for lid = " + lid); - } - - - //Make sure that a pe of PC ends up with a duration of 0, - //even though within the preprocessor, before writing, it has a different duration - //, matching the calculated accumulations it applies to. The "I" duration in this case - //indicates the source of the data, not the period for which accumulations were computed - if (descriptor.getPe().equals("PC")) - { - descriptor.setDur((short)0); - } - String durationString = (String) _shefDurMap.get( "" + descriptor.getDur() ); - - shef_param_code = descriptor.getPe() + durationString + - descriptor.getTs() + descriptor.getExtremum(); - descriptor.setShef_param_code( shef_param_code ); - - outputStringBuffer.append(location.getLid() + " " + location.getHsa() + " " + - descriptor.getShef_param_code() + " " + location.getElevation() + " " + - location.getLat() + " " + location.getLon() + " " + location.isFcstPoint() + " " + - location.getLocationName() + "\n" ); - - if ( location.isDCP() ) - { - outputStringBuffer.append( "T " ); - } - else - { - outputStringBuffer.append( "F " ); - } - - if ( location.isObserver() ) - { - outputStringBuffer.append( "T " ); - } - else - { - outputStringBuffer.append( "F " ); - } - - if ( ( location.getTelemType() == null ) || (location.getTelemType().length() == 0) ) - { - outputStringBuffer.append( "NO_TELEM_TYPE" ); - } - else - { - outputStringBuffer.append( location.getTelemType() ); - } - - - // _timeSeriesOutputStringTimer.restart(); - - outputStringBuffer.append( "\n" + getRegularObsTimeSeriesTimeValuePairListOutputString( obsTimeSeries ) + "\n" ); - // _timeSeriesOutputStringTimer.stop(); - - return outputStringBuffer; - } - -// ------------------------------------------------------------------------ - private String getObsTimeSeriesOutputString_orig_way( RegularObsTimeSeries obsTimeSeries ) - { - String header = "PDCFileWriter.getObsTimeSeriesOutputString_orig_way(): "; - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String outputString = ""; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - outputString += DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime() ) + - "|" + decimalFormat.format( timeValuePair.getValue() ) + "\n"; - } - else - { - outputString += decimalFormat.format( timeValuePair.getValue() ) + " "; - } - } - else - { - if ( _DEBUG ) - { - outputString += decimalFormat.format( MISSING_DOUBLE ) + "\n"; - } - else - { - outputString += decimalFormat.format( MISSING_DOUBLE ) + " "; - } - } - } - return outputString; - } //orig way - - - private String getObsTimeSeriesOutputString_old( RegularObsTimeSeries obsTimeSeries ) - { - String header = "PDCFileWriter.getObsTimeSeriesOutputString_old(): "; - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String outputString = ""; - String formattedNumberString = null; - String dateTimeString = null; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - dateTimeString= DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime() ); - formattedNumberString = getFormattedNumber_old(timeValuePair.getValue(), decimalFormat ); - outputString += dateTimeString + - "|" + formattedNumberString + "\n"; - } - else - { - formattedNumberString = getFormattedNumber_old(timeValuePair.getValue(), decimalFormat ); - outputString += formattedNumberString + " "; - } - } - else - { - if ( _DEBUG ) - { - formattedNumberString = getFormattedNumber_old(MISSING_DOUBLE, decimalFormat ); - outputString += formattedNumberString + "\n"; - } - else - { - formattedNumberString = getFormattedNumber_old(MISSING_DOUBLE, decimalFormat ); - outputString += formattedNumberString + " "; - } - } - } - return outputString; - } //old way - - // -------------------------------------------------------------------------------------------- - - private String getRegularObsTimeSeriesTimeValuePairListOutputString( RegularObsTimeSeries obsTimeSeries ) - { - String header = "PDCFileWriter.getRegularObsTimeSeriesTimeValuePairListOutputString(): "; - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - //Map timeValuePairMap = ob - - - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - String missingDoubleString = getFormattedNumber(MISSING_DOUBLE, decimalFormat) + ""; - - StringBuffer outputStringBuffer = new StringBuffer(); - - //double formattedNumber = 0.0; - String dateTimeString = null; - - if (timeValuePairList.size() > _timeSeriesValueCount) - { - // System.out.println(header + "\nFor " + obsTimeSeries.getDescriptor().toString() + - // " timeValuePairList.size() = " + timeValuePairList.size() + - // "> intended _timeSeriesValueCount = " + _timeSeriesValueCount); - } - else if (timeValuePairList.size() < _timeSeriesValueCount) - { - System.out.println(header + "\n *******For " + obsTimeSeries.getDescriptor().toString() + - " timeValuePairList.size() = " + timeValuePairList.size() + - " < intended _timeSeriesValueCount = " + _timeSeriesValueCount); - - } - else - { - //System.out.println(header + "\nFor " + obsTimeSeries.getDescriptor().toString() + - // " timeValuePairList.size() = intended _timeSeriesValueCount"); - } - - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - - if ( - (descriptor.getStartTime() > _startTime) || - (descriptor.getEndTime() < _endTime) - ) - { - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(descriptor.getStartTime()); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(descriptor.getEndTime()); - System.out.println(header + descriptor.toString() + " goes from " + - startTimeString + " to " + endTimeString ); - - - String origStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_startTime); - String origEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_endTime); - - System.out.println(header + " and should have gone from " + - origStartTimeString + " to " + origEndTimeString ); - - System.out.println(header + " merger string = " + obsTimeSeries.getMergerString() + '\n'); - - - } - - if (! descriptor.isMissing() ) //NOT MISSING - { - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - if ( _DEBUG ) - { - dateTimeString = DbTimeHelper.getDateTimeStringFromLongTime( timeValuePair.getDateTime()); - // formattedNumber = getFormattedNumber(timeValuePair.getValue(), decimalFormat ); - outputStringBuffer.append( dateTimeString + "|" + - timeValuePair.getValue() + "\n"); - } - else - { - // formattedNumber = getFormattedNumber(timeValuePair.getValue(), decimalFormat ); - outputStringBuffer.append(timeValuePair.getValue() + " "); - } - } - else - { - if ( _DEBUG ) - { - outputStringBuffer.append(missingDoubleString + "\n"); - } - else - { - outputStringBuffer.append(missingDoubleString + " "); - } - - } - } - - } - else //the time series is missing - { - outputStringBuffer.append("MISSING"); - /* - for ( long indexTime = descriptor.getStartTime(); - indexTime < descriptor.getEndTime(); - indexTime += PDCPreprocessorDataMgr.MILLIS_PER_HOUR ) - { - outputStringBuffer.append(missingDoubleString + " "); - } - */ - - } - - - return outputStringBuffer.toString(); - } -// ------------------------------------------------------------------------- - public double getFormattedNumber(double value, DecimalFormat decimalFormat) - { - // _decimalFormatTimer.restart(); - - // value = roundToPlaces(value, 2); - - // String numberString = decimalFormat.format(value); - - // _decimalFormatTimer.stop(); - - return value; - } - - - // ------------------------------------------------------------------------- - - public String getFormattedNumber_old(double value, DecimalFormat decimalFormat) - { - //_decimalFormatTimer.restart(); - - String numberString = decimalFormat.format(value); - - // _decimalFormatTimer.stop(); - - return value + ""; - } -// ------------------------------------------------------------------------- - - public double getFormattedNumberWithRounding(double value, DecimalFormat decimalFormat) - { - // _decimalFormatTimer.restart(); - - value = MathHelper.roundToNDecimalPlaces(value, 2); - - // String numberString = decimalFormat.format(value); - - // _decimalFormatTimer.stop(); - - return value; - } - - -// ------------------------------------------------------------------------- - - private boolean isPreprocessedFileOpen() - { - return _fileIsOpen; - } - -// ------------------------------------------------------------------------ - - public void closePreprocessedFile() - { - if (isPreprocessedFileOpen() ) - { - _fileIsOpen = false; - _writer.close(); - } - } - -// ------------------------------------------------------------------------ - - public void closePreprocessedFile( PrintWriter writer ) - { - if (isPreprocessedFileOpen() ) - { - _fileIsOpen = false; - writer.close(); - } - } - -// ------------------------------------------------------------------------ - - private void openPreProcessedFile(String fileName) - { - try - { - if (fileName != null) - { - _outputStream = new BufferedOutputStream( new FileOutputStream(fileName, false) ); - - _fileIsOpen = true; - } - else //fileName == null - { - _outputStream = System.out; - } - - _writer = new PrintWriter( _outputStream ); - } - catch (java.io.IOException e) - { - System.out.println( e ); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - } - - // ------------------------------------------------------------------------ - - - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCPreprocessor.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCPreprocessor.java deleted file mode 100644 index b5a7e16677..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCPreprocessor.java +++ /dev/null @@ -1,1201 +0,0 @@ -/* - * Created on Jun 13, 2005 - * - * - * - */ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -/** - * @author Gautam Sood - * Chip Gobs - */ -public class PDCPreprocessor -{ - private static final String _versionString = "OB8.1"; - private static final String _dateString = "March 27, 2007"; - - private static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - private static final Runtime _runtime = Runtime.getRuntime(); - - private PDCPreprocessorDataMgr _dataMgr = null; - private boolean _debug = false; - - private String _preprocessedFilePath = null; //directory where the processed files are placed in - private String _logDirName = null; //directory where the log will be placed in - private Logger _logger = null; - private Set _completeLidSet = null; - private Set _completeRiverStationLidSet = null; - - private long _endTime = 0; - private long _endTimeLastHour = 0; - // private long _endTimeNextHour = 0; - - private List _heightTimeSeriesList = null; - - private List _stagePoolTimeSeriesList = new ArrayList(); - private List _percentFloodFlowTimeSeriesList = new ArrayList(); - - - private List _lakeTimeSeriesList = null; - private List _dischargeTimeSeriesList = null; - private List _heightDerivedDischargeTimeSeriesList = new ArrayList(); - private List _flowStorageTimeSeriesList = new ArrayList(); - - - private List _temperatureTimeSeriesList = null; - private List _tempTimeSeriesList = new ArrayList(); - private List _maxTempTimeSeriesList = new ArrayList(); - private List _minTempTimeSeriesList = new ArrayList(); - private List _dewPointTimeSeriesList = new ArrayList(); - private List _deltaDewPointTimeSeriesList = new ArrayList(); - private List _deltaTempTimeSeriesList = new ArrayList(); - - private List _windTimeSeriesList = null; - private List _windSpeedTimeSeriesList = new ArrayList(); - private List _windDirectionTimeSeriesList = new ArrayList(); - - private List _snowTimeSeriesList = null; - private List _snowWaterTimeSeriesList = new ArrayList(); - private List _depthAboveFloodStageTimeSeriesList = new ArrayList(); - private List _deltaSnowWaterTimeSeriesList = new ArrayList(); - - private List _weatherTimeSeriesList = null; - private List _relativeHumidityTimeSeriesList = new ArrayList(); - - - private List _instantPrecipTimeSeriesList = new ArrayList(); - private List _hourlyPrecipTimeSeriesList = new ArrayList(); - private List _threeHourPrecipTimeSeriesList = new ArrayList(); - private List _sixHourPrecipTimeSeriesList = new ArrayList(); - private List _twentyFourHourPrecipTimeSeriesList = new ArrayList(); - - private int _heightHours = 0; - private int _temperatureHours = 0; - private int _snowHours = 0; - private int _windHours = 0; - private int _weatherHours = 0; - private int _precipHours = 0; - private int _lowerWindow = 0; - private int _upperWindow = 0; - - public PDCPreprocessor() - { - } - -/** - * initialize( String[] args ) - Used to process the command line arguments and set appropriate variables. - * @param args - Command line arguments - */ - private void initialize( String[] args ) - { - String header = "PDCPreprocessor.initialize(): "; - StringBuffer baseConnectionStringBuffer = new StringBuffer(); //gotten from the command line - String logFileName = null; - - - getAppsDefaults(); - - - for (int i = 0; i < args.length; i++) - { - System.out.println("args[" + i + "] = " + args[i]); - } - - processCommandLineArguments( baseConnectionStringBuffer, args ); - - logFileName = _logDirName + "/PDCPreprocessor.log"; - - _logger = new FileLogger(logFileName, true, true); - - - _logger.log("----------------------------------------------------------------------------------------- "); - _logger.log("version = " + _versionString + " date = " + _dateString); - - _logger.log( "Starting PDC Preprocessor - " + - DbTimeHelper.getDateTimeStringFromLongTime( System.currentTimeMillis() ) ); - - - _logger.log(header + "JDBC connection string = " + - baseConnectionStringBuffer.toString() ); - - _dataMgr = new PDCPreprocessorDataMgr( - baseConnectionStringBuffer.toString(), - _logger, - _preprocessedFilePath, - _lowerWindow, - _upperWindow, - _debug); - - _endTime = System.currentTimeMillis(); - _endTimeLastHour = _endTime; - _endTimeLastHour /= MILLIS_PER_HOUR; - _endTimeLastHour *= MILLIS_PER_HOUR; - - // _endTimeNextHour = _endTimeLastHour + MILLIS_PER_HOUR; - - - } - - // ----------------------------------------------------------------------------------------- - - private void disconnect() - { - _dataMgr.disconnect(); - return; - } - - // ----------------------------------------------------------------------------------------- - - private long getNonPrecipEndTime() - { - - return _endTimeLastHour; - } - - private long getNonPrecipDailyEndTime() - { - String header = "PDCPreprocessor.getNonPrecipDailyEndTime(): "; - - long dailyEndTime = _endTimeLastHour; - dailyEndTime /= PDCPreprocessorDataMgr.MILLIS_PER_DAY ; - dailyEndTime *= PDCPreprocessorDataMgr.MILLIS_PER_DAY ; - - dailyEndTime += PDCPreprocessorDataMgr.MILLIS_PER_12_HOURS; - - System.out.println(header + "dailyEndTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(dailyEndTime)); - - return dailyEndTime; - - } - - // ----------------------------------------------------------------------------------------- - - private long getPrecipEndTime() - { - - return _endTime; - } - - // ----------------------------------------------------------------------------------------- - -/** - * processObsData() - Processes the Observed data and calls appropriate methods from the Data Manager to write the data - * out to the .dat files. - */ - public void processObsData() - { - String header = "PDCPreprocessor.processObsData(): "; - - CodeTimer precipTimer = new CodeTimer(); - - _dataMgr.createLidMap(); - _dataMgr.createShefDurMap(); - _completeLidSet = _dataMgr.getCompleteLidSet(); - - _completeRiverStationLidSet = _dataMgr.getRiverStationLidSet(); - - _dataMgr.handleCacheAging(); - - printFreeMemory("Before handleHeightData"); - handleHeightData(); - printFreeMemory("After handleHeightData"); - - handleFlowAndStorageData(); - printFreeMemory("After handleFlowAndStorageData"); - - handleTemperatureData(); - printFreeMemory("After handleTemperatureData"); - - - handleWindData(); - printFreeMemory("After handleWindData"); - - - handleSnowData(); - printFreeMemory("After handleSnowData"); - - - handleWeatherData(); - printFreeMemory("After handleWeatherData"); - - - - // handle precip data - precipTimer.start(); - // processPrecipData(); - processPrecipDataWithCaching(_precipHours); - precipTimer.stop("Reading and processing the Precip Data took "); - - CodeTimer writePrecipDataFileTimer = new CodeTimer(); - writePrecipDataFileTimer.start(); - _dataMgr.writeIrregularObsDataToFile(_instantPrecipTimeSeriesList, "PrecipInstant"); - - _dataMgr.writeRegularObsDataToFile(_hourlyPrecipTimeSeriesList, "Precip1Hour"); - _dataMgr.writeRegularObsDataToFile(_threeHourPrecipTimeSeriesList, "Precip3Hour"); - _dataMgr.writeRegularObsDataToFile(_sixHourPrecipTimeSeriesList, "Precip6Hour"); - _dataMgr.writeRegularObsDataToFile(_twentyFourHourPrecipTimeSeriesList, "Precip24Hour"); - - writePrecipDataFileTimer.stop("Writing all of the precip data files took"); - } - - static public void printFreeMemory() - { - printFreeMemory(null); - } - - static public void printFreeMemory(String message) - { - long freeMemory = _runtime.freeMemory(); - long maxMemory = _runtime.maxMemory(); - if (message == null) - { - message = ""; - } - - System.out.println(message + " Free memory = " + freeMemory + " Max memory = " + maxMemory); - - } - - private void handleHeightData() - { - String header = "PDCPreprocessor.handleHeightData(): "; - - CodeTimer heightDbTimer = new CodeTimer(); - CodeTimer heightCacheTimer = new CodeTimer(); - - heightCacheTimer.start(); - _heightTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( "Height", - getNonPrecipEndTime(), _heightHours ); - heightCacheTimer.stop(header + "height cache usage took"); - - addMissingRiverTimeSeries( _heightTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "HG", "RZ", "Z", - (short) 0, getNonPrecipEndTime(), _heightHours, true), true ); - - processHeightTimeSeriesList(); - - _heightTimeSeriesList = null; - System.gc(); - - _dataMgr.writeRegularObsDataToFile( _stagePoolTimeSeriesList, "Height" ); - _dataMgr.writeRegularObsDataToFile( _depthAboveFloodStageTimeSeriesList, "HeightAboveFloodStage" ); - - - - _stagePoolTimeSeriesList = null; - _depthAboveFloodStageTimeSeriesList = null; - - System.gc(); - - } - // -------------------------------------------------------------------------------------------- - private void handleFlowAndStorageData() - { - _lakeTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( "Lake", getNonPrecipEndTime(), _heightHours ); - _dischargeTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( "Discharge", getNonPrecipEndTime(), _heightHours ); - // addMissingTimeSeries( _lakeTimeSeriesList, getRegularObsTimeSeriesDescriptor( "LS", "RZ", "Z", (short) 0, getNonPrecipEndTime(), _heightHours ), true ); - - //adds discharge data that was derived from height data, as needed (if there was no data for it) - incorporateConvertedHeightData(_heightDerivedDischargeTimeSeriesList, - _dischargeTimeSeriesList); - - addMissingTimeSeries( _dischargeTimeSeriesList, getRegularObsTimeSeriesDescriptor( "QR", "RZ", "Z", (short) 0, getNonPrecipEndTime(), _heightHours, true ), true ); - // addMissingTimeSeries( _dischargeTimeSeriesList, getRegularObsTimeSeriesDescriptor( "QT", "RZ", "Z", (short) 0, getNonPrecipEndTime(), _heightHours, true ), true ); - - - printFreeMemory("handleFlowAndStorageData() before processFlowStorageTimeSeriesList()"); - - processFlowStorageTimeSeriesList(); - - printFreeMemory("handleFlowAndStorageData() after processFlowStorageTimeSeriesList()"); - - - _lakeTimeSeriesList = null; - _dischargeTimeSeriesList = null; - _heightDerivedDischargeTimeSeriesList = null; - System.gc(); - - printFreeMemory("handleFlowAndStorageData() before processFloodFlowPercentageTimeSeriesList()"); - - processFloodFlowPercentageTimeSeriesList(); - printFreeMemory("handleFlowAndStorageData() after processFloodFlowPercentageTimeSeriesList()"); - - - printFreeMemory("handleFlowAndStorageData() before writeRegularObsDataToFile() #1"); - _dataMgr.writeRegularObsDataToFile( _flowStorageTimeSeriesList, "FlowStorage" ); - printFreeMemory("handleFlowAndStorageData() after writeRegularObsDataToFile() #1"); - - printFreeMemory("handleFlowAndStorageData() before writeRegularObsDataToFile() #2"); - _dataMgr.writeRegularObsDataToFile( _percentFloodFlowTimeSeriesList, "PercentFloodFlow" ); - printFreeMemory("handleFlowAndStorageData() after writeRegularObsDataToFile() #2"); - - - } - // -------------------------------------------------------------------------------------------- - - private void incorporateConvertedHeightData(List derivedDischargeTimeSeriesList, - List dischargeTimeSeriesList) - { - - // if there are any derived time series that - // are not present in the regular discharge time series, then add them - - List timeSeriesToAddList = new ArrayList(); - - int lastFoundIndex = 0; - - for (int i = 0; i < derivedDischargeTimeSeriesList.size(); i++) - { - RegularObsTimeSeries derivedDischargeTimeSeries = - (RegularObsTimeSeries) derivedDischargeTimeSeriesList.get(i); - - RegularObsTimeSeriesDescriptor derivedDescriptor = - derivedDischargeTimeSeries.getDescriptor(); - - String derivedLid = derivedDescriptor.getLid(); - - boolean foundMatch = false; - for (int j = lastFoundIndex; !foundMatch && j < dischargeTimeSeriesList.size(); j++) - { - RegularObsTimeSeries dischargeTimeSeries = - (RegularObsTimeSeries) dischargeTimeSeriesList.get(j); - - RegularObsTimeSeriesDescriptor descriptor = dischargeTimeSeries.getDescriptor(); - - if (derivedLid.equalsIgnoreCase(descriptor.getLid()) ) - { - foundMatch = true; - lastFoundIndex = j; - } - - - } - - if (! foundMatch) //it wasn't in the list, so add it to the list to add later - // we don't want to screw up the iteration through the dischargeTimeSeriesList - { - timeSeriesToAddList.add(derivedDischargeTimeSeries); - } - - } - - // add all of the needed converted time series - for (int i = 0; i < timeSeriesToAddList.size(); i++) - { - RegularObsTimeSeries timeSeries = - (RegularObsTimeSeries) timeSeriesToAddList.get(i); - - addTimeSeriesToOrderedList(dischargeTimeSeriesList, timeSeries); - } - - } - // -------------------------------------------------------------------------------------------- - - private void handleTemperatureData() - { - - // Note: Temperature data does NOT use caching. - // It was found to be too complicated. - // Your mileage may vary. - String header = "PDCPreprocessor.handleTemperatureData(): "; - CodeTimer timer = new CodeTimer(); - - CodeTimer dbTimer = new CodeTimer(); - CodeTimer addMissingTimer = new CodeTimer(); - CodeTimer processTimer = new CodeTimer(); - CodeTimer fileWriterTimer = new CodeTimer(); - timer.start(); - - dbTimer.start(); - _temperatureTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListFromDb( "Temperature", getNonPrecipEndTime(), _temperatureHours ); - dbTimer.stop(header + " reading from the db took "); - - - addMissingTimer.start(); - - addMissingTimeSeries( _temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "TA", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _temperatureHours, true ), true ); - - addMissingTimeSeries( _temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "TA", "RZ", "X", (short) 0, - getNonPrecipDailyEndTime(), _temperatureHours, false ), false ); - - addMissingTimeSeries( _temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "TA", "RZ", "N", (short) 0, - getNonPrecipDailyEndTime(), _temperatureHours, false ), false ); - - addMissingTimeSeries( _temperatureTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "TD", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _temperatureHours, true ), true ); - - addMissingTimer.stop(header + "4 addMissingTimeSeries() calls took "); - - - processTimer.start(); - - printFreeMemory(header + "before processTemperatureTimeSeriesList"); - - processTemperatureTimeSeriesList(); - processTimer.stop(header + " processing Temperature data took "); - printFreeMemory(header + "after processTemperatureTimeSeriesList"); - - _temperatureTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _temperatureTimeSeriesList = null"); - - - fileWriterTimer.start(); - _dataMgr.writeRegularObsDataToFile( _tempTimeSeriesList, "Temperature" ); - _tempTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _tempTimeSeriesList = null"); - - _dataMgr.writeRegularObsDataToFile( _minTempTimeSeriesList, "TemperatureMin" ); - _minTempTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _minTempTimeSeriesList = null"); - - - _dataMgr.writeRegularObsDataToFile( _maxTempTimeSeriesList, "TemperatureMax" ); - _maxTempTimeSeriesList = null; - System.gc(); - printFreeMemory(header + "after _maxTempTimeSeriesList = null"); - - _dataMgr.writeRegularObsDataToFile( _dewPointTimeSeriesList, "DewPoint" ); - _dataMgr.writeRegularObsDataToFile( _deltaTempTimeSeriesList, "TemperatureDelta" ); - _dataMgr.writeRegularObsDataToFile( _deltaDewPointTimeSeriesList, "DewPointDelta" ); - fileWriterTimer.stop(header + " all the 6 file writes took "); - - - _tempTimeSeriesList = null; - _minTempTimeSeriesList = null; - _maxTempTimeSeriesList = null; - _dewPointTimeSeriesList = null; - _deltaTempTimeSeriesList = null; - _deltaDewPointTimeSeriesList = null; - - System.gc(); - - timer.stop(header + " took "); - } - // -------------------------------------------------------------------------------------------- - private void handleWindData() - { - - String header = "PDCPreprocessor.handleWindData(): "; - - CodeTimer windTimer = new CodeTimer(); - windTimer.start(); - _windTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( "Wind", - getNonPrecipEndTime(), _windHours ); - - windTimer.stop(header + "wind cache usage took "); - addMissingTimeSeries( _windTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "UD", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _windHours, true ), true ); - addMissingTimeSeries( _windTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "US", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _windHours, true ), true ); - - processWindTimeSeriesList(); - _windTimeSeriesList = null; - System.gc(); - - _dataMgr.writeRegularObsDataToFile( _windSpeedTimeSeriesList, "WindSpeed" ); - _dataMgr.writeRegularObsDataToFile( _windDirectionTimeSeriesList, "WindDirection" ); - - _windSpeedTimeSeriesList = null; - _windDirectionTimeSeriesList = null; - - System.gc(); - } - - // ---------------------------------------------------------------------------------------------- - - private void handleSnowData() - { - String header = "PDCPreprocessor.handleSnowData(): "; - - CodeTimer snowTimer = new CodeTimer(); - snowTimer.start(); - _snowTimeSeriesList = _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( "Snow", getNonPrecipEndTime(), _snowHours ); - snowTimer.stop(header + "snow cache usage took "); - - addMissingTimeSeries( _snowTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "SW", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _snowHours, true ), true ); - processSnowTimeSeriesList(); - _snowTimeSeriesList = null; - System.gc(); - - - _dataMgr.writeRegularObsDataToFile( _snowWaterTimeSeriesList, "SnowWaterEquivalent" ); - _dataMgr.writeRegularObsDataToFile( _deltaSnowWaterTimeSeriesList, "SnowWaterEquivalentDelta" ); - - - } - - private void handleWeatherData() - { - _weatherTimeSeriesList = - _dataMgr.getNonPrecipObsTimeSeriesListUsingCache( "Weather", - getNonPrecipEndTime(), _weatherHours ); - - addMissingTimeSeries( _weatherTimeSeriesList, - getRegularObsTimeSeriesDescriptor( "XR", "RZ", "Z", (short) 0, - getNonPrecipEndTime(), _weatherHours, true ), true ); - processWeatherTimeSeriesList(); - _weatherTimeSeriesList = null; - System.gc(); - - - _dataMgr.writeRegularObsDataToFile( _relativeHumidityTimeSeriesList, "RelativeHumidity" ); - _relativeHumidityTimeSeriesList = null; - System.gc(); - - } - - // -------------------------------------------------------------------------------------------- - private void addAllMissingTimeSeries() - { - addMissingTimeSeries( _heightTimeSeriesList, getRegularObsTimeSeriesDescriptor( "HG", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _heightHours, true ), true ); - addMissingTimeSeries( _temperatureTimeSeriesList, getRegularObsTimeSeriesDescriptor( "TA", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _temperatureHours, true ), true ); - addMissingTimeSeries( _temperatureTimeSeriesList, getRegularObsTimeSeriesDescriptor( "TA", "RZ", "X", Short.parseShort( "0" ), getNonPrecipEndTime(), _temperatureHours, false ), false ); - addMissingTimeSeries( _temperatureTimeSeriesList, getRegularObsTimeSeriesDescriptor( "TA", "RZ", "N", Short.parseShort( "0" ), getNonPrecipEndTime(), _temperatureHours, false ), false ); - addMissingTimeSeries( _temperatureTimeSeriesList, getRegularObsTimeSeriesDescriptor( "TD", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _temperatureHours, true ), true ); - addMissingTimeSeries( _windTimeSeriesList, getRegularObsTimeSeriesDescriptor( "UD", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _windHours, true ), true ); - addMissingTimeSeries( _windTimeSeriesList, getRegularObsTimeSeriesDescriptor( "US", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _windHours, true ), true ); - addMissingTimeSeries( _snowTimeSeriesList, getRegularObsTimeSeriesDescriptor( "SW", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _snowHours, true ), true ); - addMissingTimeSeries( _weatherTimeSeriesList, getRegularObsTimeSeriesDescriptor( "XR", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _weatherHours, true ), true ); - addMissingTimeSeries( _lakeTimeSeriesList, getRegularObsTimeSeriesDescriptor( "LS", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _heightHours, true ), true ); - addMissingTimeSeries( _dischargeTimeSeriesList, getRegularObsTimeSeriesDescriptor( "QR", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _heightHours, true ), true ); - addMissingTimeSeries( _dischargeTimeSeriesList, getRegularObsTimeSeriesDescriptor( "QT", "RZ", "Z", Short.parseShort( "0" ), getNonPrecipEndTime(), _heightHours, true ), true ); - } - // -------------------------------------------------------------------------------------------- - - private void addMissingTimeSeries( List obsTimeSeriesList, - RegularObsTimeSeriesDescriptor descriptor, - boolean isHourly, Set lidSet ) - { - String header = "PDCPreprocessor.addMissingTimeSeries(): "; - CodeTimer methodTimer = new CodeTimer(); - methodTimer.start(); - - CodeTimer getLidSetTimer = new CodeTimer(); - CodeTimer createMissingTimer = new CodeTimer(); - CodeTimer addToOrderListTimer = new CodeTimer(); - - Set partialLidSet = null; - Set missingLidSet = new HashSet( lidSet ); - List missingLidList = null; - String lid = null; - - descriptor.setMissing(true); - - if ( - (descriptor.isMissing() == true) && - (descriptor.getExtremum().equals("X") ) - ) - { - System.out.println(header + "descriptor = " + descriptor ); - } - - getLidSetTimer.start(); - partialLidSet = getLidSetFromObsTimeSeriesList( - obsTimeSeriesList, - descriptor.getPe(), - descriptor.getExtremum() ); - - getLidSetTimer.stop(header + " getLidSetFromObsTimeSeriesList() took"); - - missingLidSet.removeAll( partialLidSet ); - - missingLidList = new ArrayList( missingLidSet ); - - - - for ( int i = 0; i < missingLidList.size(); i++ ) - { - lid = (String) missingLidList.get( i ); - createMissingTimer.restart(); - RegularObsTimeSeries obsTimeSeries = - createMissingTimeSeries( lid, - new RegularObsTimeSeriesDescriptor( descriptor ), - isHourly ); - createMissingTimer.stop(); - - addToOrderListTimer.restart(); - addTimeSeriesToOrderedList( obsTimeSeriesList, obsTimeSeries ); - addToOrderListTimer.stop(); - } - - System.out.println(header + - "total elapsed time for createMissingTimeSeries calls = " + - createMissingTimer.getElapsedTime() + " millis."); - - System.out.println(header + - "total elapsed time for addToOrderListTimer calls = " + - addToOrderListTimer.getElapsedTime() + " millis."); - - methodTimer.stop(header + "took"); - } - - - private void addMissingTimeSeries( List obsTimeSeriesList, - RegularObsTimeSeriesDescriptor descriptor, - boolean isHourly ) - { - addMissingTimeSeries(obsTimeSeriesList, descriptor, isHourly, _completeLidSet); - - return; - } - - private void addMissingRiverTimeSeries( List obsTimeSeriesList, - RegularObsTimeSeriesDescriptor descriptor, - boolean isHourly ) - { - addMissingTimeSeries(obsTimeSeriesList, descriptor, isHourly, _completeRiverStationLidSet); - - return; - } - - // -------------------------------------------------------------------------------------------- - private RegularObsTimeSeries createMissingTimeSeries( String lid, - RegularObsTimeSeriesDescriptor descriptor, - boolean isHourly ) - { - RegularObsTimeSeries obsTimeSeries = null; - - descriptor.setLid( lid ); - - descriptor.setMissing(true); - - if ( isHourly ) - { - obsTimeSeries = new RegularObsTimeSeries( descriptor, 1, new HourlyTimeSlotPolicy() ); - } - else - { - obsTimeSeries = new RegularObsTimeSeries( descriptor, 24, new DailyTimeSlotPolicy() ); - } - - - - /* - - for ( long indexTime = descriptor.getStartTime(); - indexTime < descriptor.getEndTime(); - indexTime += PDCPreprocessorDataMgr.MILLIS_PER_HOUR ) - { - TimeValuePair timeValuePair = new TimeValuePair( indexTime, PDCPreprocessorDataMgr.MISSING ); - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - } - */ - - return obsTimeSeries; - } - - - // -------------------------------------------------------------------------------------------- - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor ( String pe, - String ts, - String extremum, - short duration, - long endTime, - int hoursToProcess, - boolean adjustByOneHour) - { - - int hoursBack = hoursToProcess; - - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - - descriptor.setPe( pe ); - descriptor.setTs( ts ); - descriptor.setExtremum( extremum ); - descriptor.setDur( duration ); - descriptor.setEndTime( TimeHelper.roundTimeInMillisToNearestHour( endTime ) ); - - if (adjustByOneHour) //for normal descriptors, not for TA X or TA N - { - hoursBack -= 1; - } - - descriptor.setStartTime( descriptor.getEndTime() - ( ( hoursBack ) * - PDCPreprocessorDataMgr.MILLIS_PER_HOUR ) ); - - return descriptor; - } - - // -------------------------------------------------------------------------------------------- - public void addTimeSeriesToOrderedList(List obsTimeSeriesList, RegularObsTimeSeries newTimeSeries ) - { - String header = "PDCPreprocessor.addTimeSeriesToOrderedList(): "; - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - Comparator comparator = new RegularObsTimeSeriesComparator(); - - index = Collections.binarySearch(obsTimeSeriesList, newTimeSeries, comparator); // -4 - - // Add the non-existent item to the list - if (index < 0) - { - obsTimeSeriesList.add(-index-1, newTimeSeries); - } - - else if (index == 0) - { - obsTimeSeriesList.add(index, newTimeSeries); - System.out.println(header + "Item added at 0 index in the list"); - } - - else - { - System.out.println(header + "Item aleady in the list"); - } - } - - // -------------------------------------------------------------------------------------------- - public void addTimeSeriesToOrderedList_orig( List obsTimeSeriesList, RegularObsTimeSeries newTimeSeries ) - { - RegularObsTimeSeries obsTimeSeries = null; - String newLid = newTimeSeries.getDescriptor().getLid(); - int index = -1; - boolean found = false; - - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( i ); - - if ( newLid.compareToIgnoreCase( obsTimeSeries.getDescriptor().getLid() ) < 0 ) - { - index = i; - found = true; - break; - } - } - - if ( found ) //descriptor inserted at index - { - obsTimeSeriesList.add( index, newTimeSeries ); - } - else // descriptorlist is either empty or descriptor belongs at the end of the list - { - index = 0; - obsTimeSeriesList.add( newTimeSeries ); - } - } - -/** - * - * @param obsTimeSeriesList - list of ObsTimeSeries objects - * @return Set of lids in the obsTimeSeriesList - */ - private Set getLidSetFromObsTimeSeriesList( List obsTimeSeriesList, String pe, String extremum ) - { - Set lidSet = new HashSet(); - - for ( int i = 0; i < obsTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) obsTimeSeriesList.get( i ); - if ( ( obsTimeSeries.getDescriptor().getPe().equalsIgnoreCase( pe ) ) && - ( obsTimeSeries.getDescriptor().getExtremum().equalsIgnoreCase( extremum ) ) ) - { - lidSet.add( obsTimeSeries.getDescriptor().getLid() ); - } - } - return lidSet; - } -/** - * Takes the temperature Timeseries List and extracts 24 hour min/max, Air temperature, and Dewpoint timeseries - * - */ - private void processTemperatureTimeSeriesList() - { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if ( _temperatureTimeSeriesList != null ) - { - for ( int i = 0; i < _temperatureTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _temperatureTimeSeriesList.get( i ); - - descriptor = obsTimeSeries.getDescriptor(); - long startTime = descriptor.getStartTime(); - - pe = descriptor.getPe(); - if ( ( pe.equalsIgnoreCase( "TA" ) ) && - ( descriptor.getExtremum().equalsIgnoreCase( "X" ) ) ) - { - // descriptor.setStartTime( startTime + 24 * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - obsTimeSeries.setObsTimeSeriesDescriptor( descriptor ); - _maxTempTimeSeriesList.add( obsTimeSeries ); - } - else if ( ( pe.equalsIgnoreCase( "TA" ) ) && - ( descriptor.getExtremum().equalsIgnoreCase( "N" ) ) ) - { - // descriptor.setStartTime( startTime + 24 * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - obsTimeSeries.setObsTimeSeriesDescriptor( descriptor ); - - _minTempTimeSeriesList.add( obsTimeSeries ); - } - else if ( ( pe.equalsIgnoreCase( "TA" ) ) && - ( descriptor.getExtremum().equalsIgnoreCase( "Z" ) ) ) - { - _tempTimeSeriesList.add( obsTimeSeries ); - _deltaTempTimeSeriesList.add( _dataMgr.getDeltaTimeSeries( obsTimeSeries ) ); - - } - else if ( pe.equalsIgnoreCase( "TD" ) ) - { - _deltaDewPointTimeSeriesList.add( _dataMgr.getDeltaTimeSeries( obsTimeSeries ) ); - - // descriptor.setStartTime( startTime + 24 * PDCPreprocessorDataMgr.MILLIS_PER_HOUR ); - _dewPointTimeSeriesList.add( obsTimeSeries ); - - } - } - } - } - - -/** - * takes the Snow Timeseries list and extracts all Timeseries with a PE of "SW" - * - */ - private void processSnowTimeSeriesList() - { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if ( _snowTimeSeriesList != null ) - { - for ( int i = 0; i < _snowTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _snowTimeSeriesList.get( i ); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if ( pe.equalsIgnoreCase( "SW" ) ) // Snow Water equivalent - { - _snowWaterTimeSeriesList.add( obsTimeSeries ); - _deltaSnowWaterTimeSeriesList.add( _dataMgr.getDeltaTimeSeries( obsTimeSeries ) ); - } - } - } - } - -/** - * processFlowStorageTimeSeriesList() - Processes the dischargeTimeSeriesList and retrieves the valid flowStorage - * timeseries - * - */ - private void processFlowStorageTimeSeriesList() - { - String pe = null; - - RegularObsTimeSeriesDescriptor descriptor = null; - - if ( _dischargeTimeSeriesList != null ) - { - for ( int i = 0; i < _dischargeTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _dischargeTimeSeriesList.get( i ); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if ( ( pe.equalsIgnoreCase( "QR" ) ) || ( pe.equalsIgnoreCase( "QT" ) ) ) - { - addTimeSeriesToOrderedList( _flowStorageTimeSeriesList, obsTimeSeries ); -// _flowStorageTimeSeriesList.add ( obsTimeSeries ); - } - } - } - - if ( _lakeTimeSeriesList != null ) - { - for ( int i = 0; i < _lakeTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _lakeTimeSeriesList.get( i ); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if ( pe.equalsIgnoreCase( "LS" ) ) - { - addTimeSeriesToOrderedList( _flowStorageTimeSeriesList, obsTimeSeries ); -// _flowStorageTimeSeriesList.add ( obsTimeSeries ); - } - } - } - } - - -/** -* takes the Weather Timeseries list and extracts all Timeseries with a PE of "XR" (Relative Humidity) -* -*/ - private void processWeatherTimeSeriesList() - { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if ( _weatherTimeSeriesList != null ) - { - for ( int i = 0; i < _weatherTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _weatherTimeSeriesList.get( i ); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if ( pe.equalsIgnoreCase( "XR" ) ) // Relative Humidity - { - _relativeHumidityTimeSeriesList.add( obsTimeSeries ); - } - } - } - } - -/** - * Takes the Wind Timeseries and extracts the Wind Speed and Wind Direction Time Series - * - */ - private void processWindTimeSeriesList() - { - String pe = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if ( _windTimeSeriesList != null ) - { - for ( int i = 0; i < _windTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _windTimeSeriesList.get( i ); - - descriptor = obsTimeSeries.getDescriptor(); - - pe = descriptor.getPe(); - - if ( pe.equalsIgnoreCase( "US" ) ) // Wind speed - { - _windSpeedTimeSeriesList.add( obsTimeSeries ); - } - else if ( pe.equalsIgnoreCase( "UD" ) ) // Wind direction - { - _windDirectionTimeSeriesList.add( obsTimeSeries ); - } - } - } - - } - -/** - * Takes all of the Height Timeseries and divides it into the stage/pool and depth_above_flood_stage timeserieslist. - * Also creates a flowstorage timeseries list - * - */ - private void processHeightTimeSeriesList() - { - String header = "PDCPreprocessor.processHeightTimeSeriesList(): "; - - String pe = null; - RegularObsTimeSeries derivedDischargeTimeSeries = null; - - if ( _heightTimeSeriesList != null ) - { - for ( int i = 0; i < _heightTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _heightTimeSeriesList.get( i ); - pe = obsTimeSeries.getDescriptor().getPe(); - - if ( - pe.equalsIgnoreCase( "HG" ) || - pe.equalsIgnoreCase( "HP" ) || - pe.equalsIgnoreCase( "HT" ) - ) - { - _stagePoolTimeSeriesList.add( obsTimeSeries ); - _depthAboveFloodStageTimeSeriesList.add( _dataMgr.getDepthAboveFSTimeSeries( obsTimeSeries ) ); - derivedDischargeTimeSeries = _dataMgr.getDischargeTimeSeriesFromHeightTimeSeries( obsTimeSeries ); - if ( derivedDischargeTimeSeries != null ) - { - _heightDerivedDischargeTimeSeriesList.add( derivedDischargeTimeSeries ); - } - } - } - } - } - -/** - * Takes the floodStorageTimeSeriesList and creates the percentFloodFlowTimeSeriesList - * - */ - private void processFloodFlowPercentageTimeSeriesList() - { - String pe = null; - - if ( _flowStorageTimeSeriesList != null ) - { - for ( int i = 0; i < _flowStorageTimeSeriesList.size(); i++ ) - { - RegularObsTimeSeries obsTimeSeries = (RegularObsTimeSeries) _flowStorageTimeSeriesList.get( i ); - if ( obsTimeSeries != null ) - { - //pe = obsTimeSeries.getDescriptor().getPe(); - - RegularObsTimeSeries percentFloodFlowTimeSeries = - _dataMgr.getPercentFloodFlowTimeSeriesListFromFlowStorageTimeSeries( obsTimeSeries ); - if ( percentFloodFlowTimeSeries != null ) - { - _percentFloodFlowTimeSeriesList.add( percentFloodFlowTimeSeries ); - } - - } - } - } - } - -/** - * Runs the PDC Precip Preprocessor (C code) and then takes the generated C code and creates the instant/six hour/24 hour - * precip timeseries lists. - * - */ - private void processPrecipData() - { - if ( _precipHours > 0 ) - { - _dataMgr.executePDCPrecipPP(getPrecipEndTime(), _precipHours); - _instantPrecipTimeSeriesList = _dataMgr.getInstantaneousPrecipTimeSeriesList(getPrecipEndTime()); - - _hourlyPrecipTimeSeriesList = _dataMgr.get1HourPrecipTimeSeriesListFromCFile(); - _threeHourPrecipTimeSeriesList = _dataMgr.get3HourPrecipTimeSeriesListFromCFile(); - _sixHourPrecipTimeSeriesList = _dataMgr.get6HourPrecipTimeSeriesListFromCFile(); - _twentyFourHourPrecipTimeSeriesList = _dataMgr.get24HourPrecipTimeSeriesListFromCFile(); - } - } - - private void processPrecipDataWithCaching(int numHoursToPreprocess) - { - PrecipListHolder holder = - _dataMgr.processPrecipDataWithCaching(getPrecipEndTime(), numHoursToPreprocess); - - _instantPrecipTimeSeriesList = holder.getInstantPrecipTimeSeriesList(); - _hourlyPrecipTimeSeriesList = holder.getOneHourPrecipTimeSeriesList(); - _threeHourPrecipTimeSeriesList = holder.getThreeHourPrecipTimeSeriesList(); - _sixHourPrecipTimeSeriesList = holder.getSixHourPrecipTimeSeriesList(); - _twentyFourHourPrecipTimeSeriesList = holder.getTwentyFourHourPrecipTimeSeriesList(); - } - - - -/** - * - * @param baseConnectionStringBuffer - Postgres database connection string - * @param logDirName - Directory where the log file will be created - * @param args - Command line arguments - */ - private void processCommandLineArguments( StringBuffer baseConnectionStringBuffer, - String[] args ) - { - if ( args.length < 1 ) - { - System.err.println("Usage: ohd.hseb.PDCPreprocessor.PDCPreprocessor connection_string logFileDir "); - System.exit(0); - } - - baseConnectionStringBuffer.append( args[0] ); - - if ( args.length >= 2 ) - { - if ( args[1].equalsIgnoreCase( "true" ) ) - { - _debug = true; - } - } - } - -/** - * Get's token values from .Apps_defaults - * - */ - private void getAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - // String OS = System.getProperty("os.name").toLowerCase(); - - _temperatureHours = ad.getInt( "pdc_temperature_hours", 168 ) + 24; - _heightHours = ad.getInt( "pdc_height_hours", 168 ); - _snowHours = ad.getInt( "pdc_snow_hours", 168 ) + 24; - _windHours = ad.getInt( "pdc_wind_hours", 168 ); - _weatherHours = ad.getInt( "pdc_weather_hours", 168 ); - _precipHours = ad.getInt( "pdc_precip_hours", 168 ); - _lowerWindow = ad.getInt( "pdc_lower_window", 2 ); - _upperWindow = ad.getInt( "pdc_upper_window", 2 ); - - // if ( (OS.indexOf("nt") > -1) - // || (OS.indexOf("windows 2000") > -1) - // || (OS.indexOf("windows xp") > -1) ) - // { - // _preprocessedFilePath = "D:\\data\\PDCPreprocessor\\data\\"; - // _logDirName = "D:\\data\\PDCPreprocessor\\log\\"; - // } - // else // assume it's unix - // { - _preprocessedFilePath = ad.getToken( "pdc_pp_dir" ) + "/"; - _logDirName = ad.getToken( "pdc_pp_log_dir" ) + "/"; - - // } - } - - public void testPDCFiles() - { - _dataMgr.testPDCFiles(); - - } - - public static void main( String[] args ) - { - - CodeTimer programTimer = new CodeTimer(); - programTimer.start(); - - PDCPreprocessor pdcPreprocessor = new PDCPreprocessor(); - boolean debug = false; - - pdcPreprocessor.initialize( args ); - - pdcPreprocessor.processObsData(); - - pdcPreprocessor.disconnect(); - - programTimer.stop("Finished PDCProcessor in"); - } - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCPreprocessorDataMgr.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCPreprocessorDataMgr.java deleted file mode 100644 index 898d091db2..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PDCPreprocessorDataMgr.java +++ /dev/null @@ -1,1769 +0,0 @@ -/* - * Created on September 10, 2005 - * - * - */ -package ohd.hseb.pdc_pp; - - - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.LocPDCRecord; -import ohd.hseb.ihfsdb.generated.LocPDCView; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.ShefDurRecord; -import ohd.hseb.ihfsdb.generated.ShefDurTable; -import ohd.hseb.ihfsdb.generated.StnClassRecord; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.pdc_pp.Location; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.EnvHelper; -import ohd.hseb.util.IntegerHolder; -import ohd.hseb.util.Logger; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.StringParser; -import ohd.hseb.util.TimeHelper; - -public class PDCPreprocessorDataMgr -{ - public static final int MISSING = -9999; - // private static final double MISSING_DOUBLE = MISSING; - private static String OS = System.getProperty("os.name").toLowerCase(); - - - public static final long MILLIS_PER_HALF_HOUR = 30 * 60 * 1000; - public static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; - public static final long MILLIS_PER_12_HOURS = MILLIS_PER_HOUR * 12; - public static final long MILLIS_PER_MINUTE = 60 * 1000; - public static long _minutesBeforeTopOfHour; - public static long _minutesAfterTopOfHour; - public static boolean _DEBUG = false; - - -// Variables used for the preprocessed file - private String _preprocessedFilePath = null; - // private long _endTime = System.currentTimeMillis(); - - private Database _db = null; - private Logger _logger = null; - private Map _locationHashMap = null; - private Map _shefDurMap = null; - private Map _shefDurToDurcodeMap = null; - - - private int _nonPrecipHoursToReadWhenCaching = 24; - private int _precipHoursToReadWhenCaching = 48; //currently, must be a multiple of 24 hours - private long _cacheRefreshAgeMaxInMillis = 60 * 60 * 1000; - - // private String _dataDir = null; - private String _refreshIndicatorBaseFileName = "CacheRefreshIndicator.dat"; - - - - - -// ------------------------------------------------------------------------ - - public PDCPreprocessorDataMgr( String baseConnectionString, - Logger logger, - String preprocessedFilePath, - long minutesBeforeTopOfHour, - long minutesAfterTopOfHour, - boolean debug ) - { - super(); - - _db = new Database(); - _logger = logger; - _DEBUG = debug; - _preprocessedFilePath = preprocessedFilePath; - _minutesBeforeTopOfHour = minutesBeforeTopOfHour; - _minutesAfterTopOfHour = minutesAfterTopOfHour; - - getAppsDefaults(); - - if ( baseConnectionString == null ) - { - baseConnectionString = getBaseConnectionString(); - } - _db.connectWithDriverSearch( baseConnectionString ); - } - - // ------------------------------------------------------------------------------------ - - private void getAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - - _preprocessedFilePath = ad.getToken( "pdc_pp_dir" ) + "/"; - - int cacheRefreshAgeInMinutes = ad.getInt("pdc_clean_cache_minutes", 59); - _cacheRefreshAgeMaxInMillis = cacheRefreshAgeInMinutes * MILLIS_PER_MINUTE; - - System.out.println("_cacheRefreshAgeMax = " + _cacheRefreshAgeMaxInMillis); - - return; - } -// ------------------------------------------------------------------------ - - public String getDatabaseName() - { - String dbName = _db.getDatabaseName(); - return dbName; - } - -// ------------------------------------------------------------------------ - - private String getBaseConnectionString() - { - //this is used in testing mode, not the production mode - String connectionURLPart = "jdbc:postgresql://dx1-nhdr:5432/hd_ob6ounx?user=oper"; - return connectionURLPart; - } - -// ------------------------------------------------------------------------ - -/** -* createLidMap() - Creates a Hashmap of Location objects. Used for the RegularObsTimeSeriesDescriptor objects -*/ - public void createLidMap() - { - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - CodeTimer lidHashMapTimer = new CodeTimer(); - CodeTimer locPDCViewTimer = new CodeTimer(); - CodeTimer riverStatTableTimer = new CodeTimer(); - CodeTimer putHashMapTimer = new CodeTimer(); - CodeTimer parseTimer = new CodeTimer(); - CodeTimer ratingCurveTimer = new CodeTimer(); - - Location location = null; - String whereClause = ""; - - LocPDCView locPDCView = new LocPDCView( _db ); - RiverstatTable riverStatTable = new RiverstatTable( _db ); - StnClassTable stationClassTable = new StnClassTable(_db); - - - List locPDCViewList = null; - List riverStatRecordList = null; - List stationClassList = null; - - if ( _DEBUG ) - { - lidHashMapTimer.start(); - } - - try - { - if ( _DEBUG ) - { - locPDCViewTimer.start(); - } - locPDCViewList = locPDCView.select( whereClause ); - if ( _DEBUG ) - { - locPDCViewTimer.stop( "Finished LocPDCView query in " ); - } - - if ( _DEBUG ) - { - riverStatTableTimer.start(); - } - riverStatRecordList = riverStatTable.select( whereClause ); - if ( _DEBUG ) - { - riverStatTableTimer.stop( "Finished RiverStatTable query in " ); - } - - - stationClassList = stationClassTable.select( whereClause ); - - } - catch( SQLException e ) - { - logSQLException(e); - e.printStackTrace(); - } - - if ( _locationHashMap == null ) - { - _locationHashMap = new HashMap(); - } - if ( _DEBUG ) - { - System.out.println( "Size of recordslist = " + locPDCViewList.size() ); - System.out.flush(); - } - - for ( int i = 0; i < locPDCViewList.size(); i++ ) - { - LocPDCRecord locPDCRecord = (LocPDCRecord) locPDCViewList.get( i ); - location = new Location(); - location.setLid( locPDCRecord.getLid().trim() ); - location.setHsa( locPDCRecord.getHsa().trim() ); - - if ( _DEBUG ) - { - parseTimer.restart(); - } - - double formattedLat = getFormattedDouble(locPDCRecord.getLat(), 2, DbTable.getNullDouble(), 0.0); - location.setLat(formattedLat); - - double formattedLon = getFormattedDouble(locPDCRecord.getLon(), 2, DbTable.getNullDouble(), 0.0); - location.setLon(formattedLon); - - if ( _DEBUG ) - { - parseTimer.stop(); - } - - location.setElevation( locPDCRecord.getElev() ); - location.setLocationName( locPDCRecord.getName() ); - location.setRiverStation( false ); - - double fq = locPDCRecord.getFq(); - double fs = locPDCRecord.getFs(); - - if (locPDCRecord.getLid().equals("ESFO2")) - { - System.out.println("fs = " + fs); - } - - if ( ( fq == 0 ) || (DbTable.isNull(fq)) )// missing value - { - location.setFloodFlow( MISSING ); - } - else - { - location.setFloodFlow( fq ); - } - - if (( fs == 0 ) || (DbTable.isNull(fs)))// missing value - { - location.setFloodStage( MISSING ); - } - else - { - location.setFloodStage( fs ); - } - - if ( ( fq == MISSING ) && ( fs != MISSING ) && (location.getRatingCurve() != null ) ) - { - location.setFloodFlow( location.getRatingCurve().getDischargeFromStage( fs ) ); - } - - String dispClass = locPDCRecord.getDisp_class(); - - if ( ( dispClass.indexOf( "F" ) ) != -1 ) - { - location.setFcstPoint( true ); - } - else - { - location.setFcstPoint( false ); - } - - String dcp = locPDCRecord.getIs_dcp(); - - if ( ( dcp.indexOf( "T" ) ) != -1 ) - { - location.setDCP( true ); - } - else - { - location.setDCP( false ); - } - - String observer = locPDCRecord.getIs_observer(); - - if ( ( observer.indexOf( "T" ) ) != -1 ) - { - location.setObserver( true ); - } - else - { - location.setObserver( false ); - } - - location.setTelemType( locPDCRecord.getTelem_type() ); - if ( _DEBUG ) - { - putHashMapTimer.restart(); - } - _locationHashMap.put( location.getLid(), location ); - if ( _DEBUG ) - { - putHashMapTimer.stop(); - } - } - - /* - for ( int i = 0; i < riverStatRecordList.size(); i++ ) - { - RiverstatRecord riverStatRecord = (RiverstatRecord) riverStatRecordList.get( i ); - - Location selectedLoc = (Location) _locationHashMap.get( riverStatRecord.getLid() ); - - if ( ( selectedLoc != null ) && ( riverStatRecord != null ) ) - { - selectedLoc.setRiverStation( true ); - } - } - */ - - - //For each stationClassRecord, match it up to a location record. - // if there is a match, set the river station indicator to true if - // stnClassRecord's display class contains F, D, or R. - - for ( int i = 0; i < stationClassList.size(); i++ ) - { - StnClassRecord stnClassRecord = (StnClassRecord) stationClassList.get( i ); - - Location selectedLoc = (Location) _locationHashMap.get( stnClassRecord.getLid() ); - - - if ( ( selectedLoc != null ) && ( stnClassRecord != null ) ) - { - String displayClassString = stnClassRecord.getDisp_class(); - if ( (displayClassString.contains("R")) || - (displayClassString.contains("D")) || - (displayClassString.contains("F")) - ) - { - selectedLoc.setRiverStation( true ); - } - - } - } - - if ( _DEBUG ) - { - ratingCurveTimer.restart(); - } - - loadRatingCurves(); - if ( _DEBUG ) - { - ratingCurveTimer.stop(); - } - - if ( _DEBUG ) - { - System.out.println( "push HashMap finished in " + putHashMapTimer.getElapsedTime() + " millis" ); - System.out.println( "parseTimer finished in " + parseTimer.getElapsedTime() + " millis" ); - System.out.println( "ratingCurveTimer finished in " + ratingCurveTimer.getElapsedTime() + " millis" ); - lidHashMapTimer.stop( "Finished creating Lid HashMap in " ); - } - } - - //-------------------------------------------------------------------------------- - - private double getFormattedDouble(double originalValue, int decimalPlacesToMaintain, - double missingValue, double missingValueReplacement) - { - double value = missingValueReplacement; - - if (originalValue == missingValue) - { - originalValue = missingValueReplacement; - } - else - { - value = MathHelper.roundToNDecimalPlaces(originalValue, decimalPlacesToMaintain); - } - - return value; - } - - // ------------------------------------------------------------------------ - - public Set getCompleteLidSet() - { - Set completeLidSet = _locationHashMap.keySet(); - - return completeLidSet; - } - - public Set getRiverStationLidSet() - { - List locationKeyList = new ArrayList(_locationHashMap.keySet()); - - Set completeRiverStationLidSet = new HashSet(); - - //find all river stations and add their lids to the lid set. - for (int i = 0; i < locationKeyList.size(); i++) - { - String lid = (String) locationKeyList.get(i); - Location location = (Location) _locationHashMap.get(lid); - if (location.isRiverStation()) - { - completeRiverStationLidSet.add(lid); - } - } - - return completeRiverStationLidSet; - } - -// ------------------------------------------------------------------------ - - public RegularObsTimeSeries getDischargeTimeSeriesFromHeightTimeSeries( RegularObsTimeSeries obsTimeSeries ) - { - RegularObsTimeSeries newTimeSeries = null; - RegularObsTimeSeriesDescriptor descriptor = - new RegularObsTimeSeriesDescriptor(obsTimeSeries.getDescriptor()); - - Location location = (Location) _locationHashMap.get( descriptor.getLid() ); - // DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - String dischargeString = null; - RatingCurve ratingCurve = location.getRatingCurve(); - boolean wrongPe = false; - - //change the descriptor and check for a nonconvertable PE - if (descriptor.getPe().equalsIgnoreCase("HG")) - { - descriptor.setPe("QR"); - } - else if (descriptor.getPe().equalsIgnoreCase("HT")) - { - descriptor.setPe("QT"); - } - else - { - wrongPe = true; - } - - - if ( !wrongPe && ratingCurve != null && ratingCurve.exists()) - { - - - - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - newTimeSeries = new RegularObsTimeSeries( descriptor, 1, hourlyTimeSlotPolicy ); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - - double dischargeValue = 0.0; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - TimeValuePair newTimeValuePair = new TimeValuePair( timeValuePair.getDateTime() ); - - dischargeValue = ratingCurve.getDischargeFromStage( timeValuePair.getValue() ); - dischargeValue = MathHelper.roundToNDecimalPlaces(dischargeValue, 2); - newTimeValuePair.setValue(dischargeValue); - - // dischargeString = decimalFormat.format( ratingCurve.getDischargeFromStage( timeValuePair.getValue() ) ); - // newTimeValuePair.setValue( Double.parseDouble( dischargeString ) ); - - newTimeSeries.addTimeValuePairIfBetterMatch( newTimeValuePair ); - } - } - } - - return newTimeSeries; - } - -// ------------------------------------------------------------------------ - - public RegularObsTimeSeries getPercentFloodFlowTimeSeriesListFromFlowStorageTimeSeries( RegularObsTimeSeries obsTimeSeries ) - { - RegularObsTimeSeries newTimeSeries = null; - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - Location location = (Location) _locationHashMap.get( descriptor.getLid() ); - // DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - if ( location.getFloodFlow() > 0.0 ) - { - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - newTimeSeries = new RegularObsTimeSeries( descriptor, 1, hourlyTimeSlotPolicy ); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - - double percentFloodFlow = 0.0; - - for ( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - TimeValuePair newTimeValuePair = new TimeValuePair( timeValuePair.getDateTime() ); - - - if (! timeValuePair.isMissingValue()) - { - percentFloodFlow = timeValuePair.getValue() / location.getFloodFlow(); - percentFloodFlow = 100.0 * MathHelper.roundToNDecimalPlaces(percentFloodFlow, 2); - - //String valueString = decimalFormat.format( timeValuePair.getValue() / location.getFloodFlow() ); - //newTimeValuePair.setValue( Double.parseDouble( valueString ) ); - - if ((percentFloodFlow >= 0.0) && (percentFloodFlow <= 100.0) ) - { - newTimeValuePair.setValue(percentFloodFlow ); - newTimeSeries.addTimeValuePairIfBetterMatch( newTimeValuePair ); - } - } - } - } - } - return newTimeSeries; - } - -// ------------------------------------------------------------------------ - - public void loadRatingCurves() - { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List allRatingRecordList = null; - List singleStationRatingRecordList = new ArrayList(); - - List allRatingShiftRecordList = null; - List singleStationShiftList = null; - - List allRiverstatRecordList = null; - RiverstatRecord riverStatRecord = null; - - String prevLid = null; - - int riverStatIndex = 0; - int ratingShiftIndex = 0; - IntegerHolder ratingShiftIndexHolder = new IntegerHolder( ratingShiftIndex ); - IntegerHolder riverStatIndexHolder = new IntegerHolder( riverStatIndex ); - - try - { - allRatingRecordList = ratingTable.select( "ORDER BY lid, stage" ); - allRatingShiftRecordList = ratingShiftTable.select( "WHERE active = 'T' ORDER BY lid, date desc" ); - allRiverstatRecordList = riverstatTable.select( "ORDER BY lid" ); - - for ( int i = 0; i < allRatingRecordList.size(); i++ ) - { - RatingRecord ratingRecord = (RatingRecord) allRatingRecordList.get( i ); - // you have at least one rating curve that you have dealt with - // and you are still going - if ((prevLid != null) && (! ratingRecord.getLid().equalsIgnoreCase(prevLid))) - { - singleStationShiftList = - getStationRatingShiftRecordListFromRatingShiftRecordList( prevLid, - allRatingShiftRecordList, - ratingShiftIndexHolder ); - riverStatRecord = - getRiverStatRecordFromRiverStatRecordList( prevLid, - allRiverstatRecordList, - riverStatIndexHolder ); - //process old - loadRatingCurveByRecordList( singleStationRatingRecordList, singleStationShiftList, riverStatRecord, prevLid ); - - singleStationRatingRecordList.clear(); - } - - singleStationRatingRecordList.add(ratingRecord); - prevLid = ratingRecord.getLid(); - } - - } - catch (SQLException e) - { - logSQLException(e); - ratingCurve = null; - } - } - -// ------------------------------------------------------------------------ - - - private void loadRatingCurveByRecordList( List ratingRecordList, - List ratingShiftList, - RiverstatRecord riverStatRecord, - String locationId ) - { - String header = "loadRatingCurveByRecordList(): "; - - RatingCurve ratingCurve = null; - - //determine total amount of active - //rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) - { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList.get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - //System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - //initialize the RatingCurve object with data from the database, including - // the totalShiftAmount - ratingCurve = new RatingCurve( locationId ); - - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) - { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - //done by addRatingPoint - //ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } //end for - - // set the USGS fields in the rating curve - if ( riverStatRecord != null ) - { - ratingCurve.setUsgsRatingNumber(riverStatRecord.getUsgs_ratenum()); - ratingCurve.setRatingDate(riverStatRecord.getRatedat()); - } - - Location location = (Location) _locationHashMap.get( locationId ); - - - if (location != null) - { - location.setRatingCurve( ratingCurve ); - } - else - { - System.out.println(header + - " Station classification missing ERROR for locationId = " + - locationId + " + Run set_stnclass.LX to update station classifications."); - } - - } - -// ------------------------------------------------------------------------ - -/** - * @param lid - location id - * @param allRatingShiftRecordList - Complete list of ratingShiftRecords sorted by lid - * @param ratingShiftIndexHolder - Index holder for the current ratingShift Index - * @return Single station ratingShiftRecordList - */ - private List getStationRatingShiftRecordListFromRatingShiftRecordList( String lid, - List allRatingShiftRecordList, - IntegerHolder ratingShiftIndexHolder ) - { - List ratingShiftRecordList = new ArrayList(); - RatingShiftRecord record = null; - - boolean found = false; - boolean done = false; - - for ( int i = ratingShiftIndexHolder.getValue(); i < allRatingShiftRecordList.size() && !done; i++ ) - { - record = (RatingShiftRecord) allRatingShiftRecordList.get( i ); - if ( record.getLid().equalsIgnoreCase( lid ) ) - { - ratingShiftRecordList.add( record ); - found = true; - ratingShiftIndexHolder.setValue( i ); - } - else if ( found ) // prevlid does not match current lid and lid has already been found so we've found all the ratingshifts for the lid - { - done = true; - } - } - return ratingShiftRecordList; - } - -// ------------------------------------------------------------------------ - -/** - * Get's the matching riverstatrecord for the passed in lid - * @param lid - location id - * @param allRiverStatRecordList - Complete list of RiverstatRecords - * @param riverStatIndexHolder - Index holder for the current riverstat Index - */ - private RiverstatRecord getRiverStatRecordFromRiverStatRecordList( String lid, - List allRiverStatRecordList, - IntegerHolder riverStatIndexHolder ) - { - RiverstatRecord record = null; - - boolean found = false; - - for ( int i = riverStatIndexHolder.getValue(); i < allRiverStatRecordList.size() && !found; i++ ) - { - record = (RiverstatRecord) allRiverStatRecordList.get( i ); - if ( record.getLid().equalsIgnoreCase( lid ) ) - { - found = true; - riverStatIndexHolder.setValue( i ); - } - } - return record; - } - - -// ------------------------------------------------------------------------ - -/** - * createShefDurMap() - Creates a Hashmap of Shef durations. Used for creating PEDTSEPs when writing out the data to - * .DAT files - */ - public Map getShefDurCodeToDurMap() - { - return _shefDurToDurcodeMap; - } - - public void createShefDurMap() - { - CodeTimer timer1 = new CodeTimer(); - - if ( _DEBUG ) - { - timer1.start(); - } - - ShefDurTable table = new ShefDurTable( _db ); - List shefDurRecordList = null; - - try - { - shefDurRecordList = table.select( "" ); - } - catch(SQLException e) - { - logSQLException(e); - } - - if ( _shefDurMap == null ) - { - _shefDurMap = new HashMap(); - _shefDurToDurcodeMap = new HashMap(); - } - - for ( int i = 0; i < shefDurRecordList.size(); i++ ) - { - ShefDurRecord record = (ShefDurRecord) shefDurRecordList.get( i ); - _shefDurMap.put( "" + record.getDur(), record.getDurcode() ); - _shefDurToDurcodeMap.put(record.getDurcode(), "" + record.getDur() ); - } - - if ( _DEBUG ) - { - timer1.stop( "Finished creating ShefDurMap in " ); - } - } - -// ------------------------------------------------------------------------ - - - /** - * getCachedNonPrecipObsTimeSeriesList - Queries the database and returns a List of Observed Time Series. - * @param tableName - Name of the table to query. - * @param numHoursToPreProcess - The number of hours of data to preprocess. - * - * @return obsTimeSeriesList - List of RegularObsTimeSeries objects - */ - private List readNonPrecipObsTimeSeriesListFromCachedFile(String fullFilePath) - { - - PDCFileReader reader = new PDCFileReader(fullFilePath, _shefDurToDurcodeMap); - - List obsTimeSeriesList = reader.read(); - - return obsTimeSeriesList; - } -// ------------------------------------------------------------------------ - - private List readPrecipObsTimeSeriesListFromCachedFile(String fullFilePath) - { - - PDCFileReader reader = new PDCFileReader(fullFilePath, _shefDurToDurcodeMap); - - List obsTimeSeriesList = reader.read(); - - return obsTimeSeriesList; - } - -// ------------------------------------------------------------------------ - public List getNonPrecipObsTimeSeriesListUsingCache(String tableName, - long endTime, - int numHoursToPreprocess) - { - String header = "PDCPreprocessorDataMgr.getNonPrecipObsTimeSeriesListUsingCache(): "; - List resultantTimeSeriesList = null; - List fileTimeSeriesList = null; - List dbTimeSeriesList = null; - CodeTimer dbTimer = new CodeTimer(); - CodeTimer writeTimer = new CodeTimer(); - - int numHoursToRetrieveFromDb = 0; - - String fullFilePath = _preprocessedFilePath + "/cached" + tableName + ".dat"; - - fileTimeSeriesList = readNonPrecipObsTimeSeriesListFromCachedFile(fullFilePath); - - if (isCachedDataCurrentEnough(fileTimeSeriesList, - _nonPrecipHoursToReadWhenCaching)) - - { - numHoursToRetrieveFromDb = _nonPrecipHoursToReadWhenCaching; - } - else //re-retrieve everything from the db - { - numHoursToRetrieveFromDb = numHoursToPreprocess; - } - - - System.out.println(header + "for table = " + tableName + - ", numHoursToRetrieveFromDb = " + - numHoursToRetrieveFromDb); - - dbTimer.start(); - dbTimeSeriesList = getNonPrecipObsTimeSeriesListFromDb( tableName, endTime, numHoursToRetrieveFromDb ); - dbTimer.stop(header + "db read within cache read took "); - - long newStartTime = getNewStartTime(endTime, 1, numHoursToPreprocess); - - resultantTimeSeriesList = TimeSeriesListMgr.mergeTimeSeriesLists(dbTimeSeriesList, - fileTimeSeriesList, - newStartTime, - endTime); - - - - // for the next time this program is run, write out the newly cached - // data - // I don't want the missing data to be saved - - writeTimer.start(); - writeRegularObsDataToFile( resultantTimeSeriesList, "cached" + tableName); - writeTimer.stop(header + "writing to data file within cache read took "); - - return resultantTimeSeriesList; - } - // -------------------------------------------------------------------------------------------- - public List getPrecipObsTimeSeriesListFromCache(int timeStepIntervalInHours) - { - List cachedDataTimeSeriesList = null; - - String fullFilePath = _preprocessedFilePath + "/cached" + timeStepIntervalInHours + "HourPrecip.dat"; - - cachedDataTimeSeriesList = readPrecipObsTimeSeriesListFromCachedFile(fullFilePath); - - return cachedDataTimeSeriesList; - } - // -------------------------------------------------------------------------------------------- - - public void handleCacheAging() - { - if (! isCacheNewEnough()) - { - deleteOldCacheFiles(); - updateCacheRefreshIndicator(); - } - } - - // -------------------------------------------------------------------------------------------- - - private boolean isCacheNewEnough() - { - boolean result = false; - - File file = new File( getCacheRefreshIndicatorFileName() ); - if (file.exists()) - { - long fileCreationTime = file.lastModified(); - long currentTime = System.currentTimeMillis(); - - long ageInMillis = currentTime - fileCreationTime; - if (ageInMillis < _cacheRefreshAgeMaxInMillis ) - { - result = true; - } - else - { - result = false; - } - } - - return result; - } - // -------------------------------------------------------------------------------------------- - - private void deleteOldCacheFiles() - { - File directory = new File(_preprocessedFilePath); - - File fileArray[] = directory.listFiles(); - - if (fileArray != null) - { - - for (int i = 0; i < fileArray.length; i++) - { - File file = fileArray[i]; - String fileName = file.getName(); - if (fileName.startsWith("cached") && - fileName.endsWith(".dat")) - { - file.delete(); - } - - } - } - - } - - // -------------------------------------------------------------------------------------------- - - - - private void updateCacheRefreshIndicator() - { - File file = new File( getCacheRefreshIndicatorFileName() ); - try - { - if (file.exists()) - { - file.delete(); - } - - file.createNewFile(); - } - catch (IOException e) - { - System.out.println(e.getMessage()); - } - } - // -------------------------------------------------------------------------------------------- - - private String getCacheRefreshIndicatorFileName() - { - return _preprocessedFilePath + "/" + _refreshIndicatorBaseFileName; - } - // -------------------------------------------------------------------------------------------- - - private boolean isCachedDataCurrentEnough(List fileTimeSeriesList, int cacheHours) - { - /* - * This examines the times of the data in the cache. - * shouldCacheBeAccepted() examines the last time that the cache itself was - * completely recreated from scratch. - * - */ - String header = "PDCPreprocessorDataMgr.isCachedDataCurrentEnough() :"; - boolean result = false; - - if (fileTimeSeriesList != null) //if there is no file, then it is not current enough - { - RegularObsTimeSeries firstFileTs = (RegularObsTimeSeries) fileTimeSeriesList.get(0); - - // System.out.println(header + " firstFileTs = " + firstFileTs); - - long lastFileObsTime = firstFileTs.getLatestTimeValue(0); - - - long currentTime = System.currentTimeMillis(); - - // System.out.println(header + " lastFileObsTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(lastFileObsTime) + - // " currentTime = " + DbTimeHelper.getDateTimeStringFromLongTime(currentTime) ); - - - long stalenessTime = currentTime - lastFileObsTime; - - if (stalenessTime < cacheHours * MILLIS_PER_HOUR) - { - result = true; - } - } - else - { - System.out.println(header + - "fileTimeSeriesList is null, so need to read more data from db"); - } - - return result; - } - // -------------------------------------------------------------------------------------------- - -// ------------------------------------------------------------------------- - -// ------------------------------------------------------------------------- -/** - * getNonPrecipObsTimeSeriesListFromDb - Queries the database and returns a List of - * Observed data. - * - * @param tableName - - * Name of the table to query. - * @param numHoursToPreProcess - - * The number of hours of data to preprocess. - * - * @return obsTimeSeriesList - List of RegularObsTimeSeries data - */ - public List getNonPrecipObsTimeSeriesListFromDb( String tableName, - long endTime, int numHoursToPreProcess ) - { - String header = "PDCPreprocessorDataMgr.getNonPrecipObsTimeSeriesListFromDb(): "; - NonPrecipObsTableManager table = new NonPrecipObsTableManager( _db, tableName ); - List obsTimeSeriesList = null; - - if ( numHoursToPreProcess > 0 ) - { - try - { - obsTimeSeriesList = table.select( tableName, numHoursToPreProcess, endTime ); - } - catch(SQLException e) - { - logSQLException(e); - } - } - - System.out.println(header + - "for table = " + tableName + - ", records retrieved = " + obsTimeSeriesList.size()); - - return obsTimeSeriesList; - } - -// ------------------------------------------------------------------------ - - public RegularObsTimeSeries getDepthAboveFSTimeSeries( RegularObsTimeSeries obsTimeSeries ) - { - RegularObsTimeSeries newTimeSeries = null; - Location location = (Location) _locationHashMap.get( obsTimeSeries.getDescriptor().getLid() ); - double floodStage = MISSING; - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - if ( location == null ) - { - System.out.println( "Pause" ); - } - if ( location.isRiverStation() ) - { - newTimeSeries = new RegularObsTimeSeries( obsTimeSeries.getDescriptor(), 1, hourlyTimeSlotPolicy ); - floodStage = location.getFloodStage(); - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - - for( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - if ( timeValuePair != null ) - { - TimeValuePair newTimeValuePair = new TimeValuePair( timeValuePair.getDateTime() ); - if ( ( floodStage == MISSING ) || ( timeValuePair.getValue() == MISSING ) ) - { - newTimeValuePair.setValue( MISSING ); - } - else - { - newTimeValuePair.setValue( timeValuePair.getValue() - floodStage ); - } - newTimeSeries.addTimeValuePairIfBetterMatch( newTimeValuePair ); - } - } - } - else - { - newTimeSeries = new RegularObsTimeSeries( obsTimeSeries.getDescriptor(), 1, hourlyTimeSlotPolicy ); - List timeValuePairList = obsTimeSeries.getTimeValuePairList( true ); - for( int i = 0; i < timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairList.get( i ); - TimeValuePair newTimeValuePair = null; - if ( timeValuePair != null ) - { - newTimeValuePair = new TimeValuePair( timeValuePair.getDateTime(), MISSING ); - newTimeSeries.addTimeValuePairIfBetterMatch( newTimeValuePair ); - } - } - } - return newTimeSeries; - } - -// ------------------------------------------------------------------------ - - public RegularObsTimeSeries getDeltaTimeSeries( RegularObsTimeSeries obsTimeSeries ) - { - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - RegularObsTimeSeriesDescriptor descriptor = obsTimeSeries.getDescriptor(); - long previousDayTime = descriptor.getStartTime(); - - HourlyTimeSlotPolicy hourlyTimeSlotPolicy = new HourlyTimeSlotPolicy(); - - RegularObsTimeSeries newTimeSeries = new RegularObsTimeSeries( obsTimeSeries.getDescriptor(), 1, - hourlyTimeSlotPolicy ); - - descriptor.setStartTime( previousDayTime + ( MILLIS_PER_DAY ) ); - - Map timeValuePairMap = obsTimeSeries.getTopOfTheHourTimeValuePairMap(); - - for ( long indexTime = descriptor.getStartTime(); indexTime <= descriptor.getEndTime(); indexTime+=MILLIS_PER_HOUR ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairMap.get( new Long( indexTime ) ); - if ( timeValuePair != null ) - { - TimeValuePair newTimeValuePair = new TimeValuePair( timeValuePair.getDateTime() ); - TimeValuePair previousTimeValuePair = (TimeValuePair) timeValuePairMap.get( new Long( previousDayTime) ); - - if ( ( timeValuePair == null ) - || ( previousTimeValuePair == null ) - || ( previousTimeValuePair.getValue() == MISSING ) - || ( timeValuePair.getValue() == MISSING ) ) - { - - } - else - { - double newValue = timeValuePair.getValue() - previousTimeValuePair.getValue(); - - newTimeValuePair.setValue( Double.parseDouble( decimalFormat.format( newValue ) ) ); - newTimeSeries.addTimeValuePairIfBetterMatch( newTimeValuePair ); - } - - previousDayTime += MILLIS_PER_HOUR; - } - - } - - return newTimeSeries; - } - -// ------------------------------------------------------------------------ - - public void executePDCPrecipPP(long endTime, int precipHoursToReadFromDB) - { - CodeTimer executePDCPrecipPPTimer = new CodeTimer(); - - if ( _DEBUG ) - { - executePDCPrecipPPTimer.start(); - } - - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - String commandString = dirString + "/run_pdc_precip_pp" + - " " + ( endTime / 1000 ) + - " " + precipHoursToReadFromDB; - - if ( (OS.indexOf("nt") > -1) - || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1) ) // Checking to see if running on Linux or Windows - { - } - else - { - try - { - System.out.println("Command string = :" + commandString + ":"); - Process process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } - catch(IOException e) - { - logException( e ); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - - catch( InterruptedException e ) - { - logException( e ); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - } - if ( _DEBUG ) - { - executePDCPrecipPPTimer.stop( "Completed call of PDCPrecipPP in " ); - } - } - - - public List getInstantaneousPrecipTimeSeriesList(long endTime) - { - List instantPrecipTimeSeriesList = new ArrayList(); - String instantPrecipInputFileName = null; - - if ( (OS.indexOf("nt") > -1) - || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1) ) - { - instantPrecipInputFileName = "D:/data/pdcpreprocessor/geninstantprecip.out"; - } - else // assume it's unix - { - instantPrecipInputFileName = _preprocessedFilePath + "/geninstantprecip.out"; - } - - try - { - File instantPrecipFile = new File( instantPrecipInputFileName ); - - BufferedReader _reader = new BufferedReader( new FileReader( instantPrecipFile ) ); - String line = _reader.readLine(); //discard the first line - line = _reader.readLine(); //discard the second line - line = _reader.readLine(); //discard the third line - line = _reader.readLine(); - - while ( ( line = _reader.readLine() ) != null ) //reads the next line and checks if it's null - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - String[] tokenizedLine = StringParser.tokenize( line ); - - descriptor.setLid( tokenizedLine[ 0 ] ); - descriptor.setPe( tokenizedLine[ 1 ] ); - descriptor.setDur( (short) 1001 ); - descriptor.setExtremum( "Z" ); - descriptor.setTs( tokenizedLine[ 2 ] ); - descriptor.setStartTime( endTime - MILLIS_PER_DAY ); - descriptor.setEndTime( endTime ); - - line = _reader.readLine(); - tokenizedLine = StringParser.tokenize( line ); - - - IrregularObsTimeSeries obsTimeSeries = new IrregularObsTimeSeries( descriptor, 1 ); - - long startTime = endTime - MILLIS_PER_DAY; - int counter = 0; - - // add all of the regular hours for the last 24 hours, 1..24 - for ( long indexTime = startTime; indexTime < endTime; indexTime+=MILLIS_PER_HOUR ) - { - TimeValuePair timeValuePair = new TimeValuePair( indexTime ); - timeValuePair.setValue( Double.parseDouble( tokenizedLine[ counter++ ] ) ); - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - } - - // add the special entry that is for the last half hour - TimeValuePair timeValuePair = new TimeValuePair( endTime - (MILLIS_PER_HALF_HOUR) ); - timeValuePair.setValue( Double.parseDouble( tokenizedLine[ counter++ ] ) ); - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - - instantPrecipTimeSeriesList.add( obsTimeSeries ); - } - } - catch( FileNotFoundException e ) - { - logException(e); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - catch( IOException e ) - { - logException(e); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - return instantPrecipTimeSeriesList; - } - -// ------------------------------------------------------------------------ - - - -// ------------------------------------------------------------------------ - public List get1HourPrecipTimeSeriesListFromCFile() - { - return readPrecipTimeSeriesListFromCGeneratedFile(1, 1001); - } -// ------------------------------------------------------------------------ - public List get3HourPrecipTimeSeriesListFromCFile() - { - return readPrecipTimeSeriesListFromCGeneratedFile(3, 1003); - } -// ------------------------------------------------------------------------ - public List get6HourPrecipTimeSeriesListFromCFile() - { - return readPrecipTimeSeriesListFromCGeneratedFile(6, 1006); - } -// ------------------------------------------------------------------------ - public List get24HourPrecipTimeSeriesListFromCFile() - { - return readPrecipTimeSeriesListFromCGeneratedFile(24, 2001); - } -// ------------------------------------------------------------------------ - - - public List readPrecipTimeSeriesListFromCGeneratedFile(int timeStepIntervalInHours, - int durationCode) - { - List precipTimeSeriesList = new ArrayList(); - - String fileName = "gen"+ timeStepIntervalInHours+ "hourprecip.out"; - - String precipInputFileName = null; - String[] tokenizedLine = null; - - if ( (OS.indexOf("nt") > -1) - || (OS.indexOf("windows 2000") > -1) - || (OS.indexOf("windows xp") > -1) ) - { - precipInputFileName = "D:/data/pdcpreprocessor/" + fileName; - } - else // assume it's unix - { - precipInputFileName = _preprocessedFilePath + "/" + fileName; - } - - try - { - File precipInputFile = new File( precipInputFileName ); - - BufferedReader _reader = new BufferedReader( new FileReader( precipInputFile ) ); - String line = _reader.readLine(); //discard the first line - line = _reader.readLine(); //discard the second line - line = _reader.readLine(); //discard the third line - line = _reader.readLine(); //discard the fourth line - line = _reader.readLine(); - tokenizedLine = StringParser.tokenize( line ); - - long startTime = Long.parseLong( tokenizedLine[ 0 ] ) * 1000; - long endTime = Long.parseLong( tokenizedLine[ 1 ] ) * 1000; - - while ( ( line = _reader.readLine() ) != null ) //reads the next line and checks if it's null - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - tokenizedLine = StringParser.tokenize( line ); - - descriptor.setLid( tokenizedLine[ 0 ] ); - //descriptor.setPe( "PP" ); //added 5/16/06 - - descriptor.setPe( tokenizedLine[ 1 ] ); //commented out because I want acumm. precip to display as PP - descriptor.setDur( (short) durationCode ); - descriptor.setExtremum( "Z" ); - descriptor.setTs( tokenizedLine[ 2 ] ); - descriptor.setStartTime( startTime ); - descriptor.setEndTime( endTime ); - - line = _reader.readLine(); - tokenizedLine = StringParser.tokenize( line ); - - TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - - RegularObsTimeSeries obsTimeSeries = - new RegularObsTimeSeries(descriptor, - timeStepIntervalInHours, - timeSlotPolicy); - - int counter = 0; - -// System.out.println( ( _endTime - startTime ) / ( 1000 * 60 ) ); - - long indexTime = startTime; - - // add in all the TimeValuePairs for the complete periods - for ( int i = 0; i < tokenizedLine.length-1; i++ ) - { - TimeValuePair timeValuePair = new TimeValuePair( indexTime ); - timeValuePair.setValue( Double.parseDouble( tokenizedLine[ counter++ ] ) ); - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - indexTime += timeStepIntervalInHours * MILLIS_PER_HOUR; - } - - // add in the tvp for the last (possibly) incomplete period - TimeValuePair timeValuePair = new TimeValuePair( endTime ); - timeValuePair.setValue( Double.parseDouble( tokenizedLine[ counter++ ] ) ); - obsTimeSeries.addTimeValuePairIfBetterMatch( timeValuePair ); - - precipTimeSeriesList.add( obsTimeSeries ); - } - } - catch( FileNotFoundException e ) - { - logException( e ); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - catch( IOException e ) - { - logException( e ); - if ( _DEBUG ) - { - e.printStackTrace(); - } - } - - - return precipTimeSeriesList; - } - -// ------------------------------------------------------------------------ - - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } -// ------------------------------------------------------------------------ - - private void logException( Exception exception ) - { - _logger.log( "ERROR = " + - exception.getMessage() ); - exception.printStackTrace( _logger.getPrintWriter() ); - - _logger.log( "End of stack trace" ); - } - -// ------------------------------------------------------------------------ - public PrecipListHolder processPrecipDataWithCaching(long endTime, int numHoursToPreprocess) - { - CodeTimer cCodeTimer = new CodeTimer(); - CodeTimer cacheReadTimer = new CodeTimer(); - CodeTimer processingTimer = new CodeTimer(); - CodeTimer instTimer = new CodeTimer(); - CodeTimer mergingTimer = new CodeTimer(); - - PrecipListHolder precipListHolder = new PrecipListHolder(); - - String header = "PDCPreprocessor.processPrecipDataWithCaching(): "; - int hoursToReadWhenCaching = _precipHoursToReadWhenCaching; //Note, MUST be a multiple of 24 hours - int numHoursToRetrieveUsingCRoutines = 0; - //read in cached Precip Data into all 4 Lists of RegularObsTimeSeries objects - //adjust the number of hours to read for the C program, - // based on how much I read in from the cache and how current it is - - // call the c program - // read some the list of observed time series data from the c file - - - // merge the c file data and the cached file data - // save the merged data into the cache - - // write out the merged data - - cacheReadTimer.start(); - - List cached1HourPrecipTimeSeriesList = - getPrecipObsTimeSeriesListFromCache(1); - - List cached3HourPrecipTimeSeriesList = - getPrecipObsTimeSeriesListFromCache(3); - - List cached6HourPrecipTimeSeriesList = - getPrecipObsTimeSeriesListFromCache(6); - - List cached24HourPrecipTimeSeriesList = - getPrecipObsTimeSeriesListFromCache(24); - - cacheReadTimer.stop(header + "reading the cache took "); - - - List instantPrecipTimeSeriesList = null; - List oneHourPrecipTimeSeriesList = null; - List threeHourPrecipTimeSeriesList = null; - List sixHourPrecipTimeSeriesList = null; - List twentyFourHourPrecipTimeSeriesList = null; - - - //determine how many hours to retrieve fresh from the database - if ( - (isCachedDataCurrentEnough(cached1HourPrecipTimeSeriesList, hoursToReadWhenCaching)) && - (isCachedDataCurrentEnough(cached3HourPrecipTimeSeriesList, hoursToReadWhenCaching)) && - (isCachedDataCurrentEnough(cached6HourPrecipTimeSeriesList, hoursToReadWhenCaching)) && - (isCachedDataCurrentEnough(cached24HourPrecipTimeSeriesList, hoursToReadWhenCaching)) - ) - { - numHoursToRetrieveUsingCRoutines = hoursToReadWhenCaching; - } - else //re-retrieve everything from the db - { - numHoursToRetrieveUsingCRoutines = numHoursToPreprocess; - } - - - - // retrieve fresh data and merge it with the data previously retrieved from the cache. - if ( numHoursToPreprocess > 0 ) - { - System.out.println(header + " asking for " + - numHoursToRetrieveUsingCRoutines + " from C code"); - - cCodeTimer.start(); - - executePDCPrecipPP(endTime, numHoursToRetrieveUsingCRoutines); - - cCodeTimer.stop(header + "Running the C Precip preprocessor alone took"); - - - instTimer.start(); - instantPrecipTimeSeriesList = getInstantaneousPrecipTimeSeriesList(endTime); - precipListHolder.setInstantPrecipTimeSeriesList(instantPrecipTimeSeriesList); - instTimer.stop(header + " calculating Instantaneous Precip took "); - - mergingTimer.start(); - - // Merge all the time series (plural) - long newStartTime = 0; - oneHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList(endTime, 1, - numHoursToPreprocess, - 1001, - cached1HourPrecipTimeSeriesList); - precipListHolder.setOneHourPrecipTimeSeriesList(oneHourPrecipTimeSeriesList); - - - threeHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList(endTime, 3, - numHoursToPreprocess, - 1003, - cached3HourPrecipTimeSeriesList); - precipListHolder.setThreeHourPrecipTimeSeriesList(threeHourPrecipTimeSeriesList); - - - sixHourPrecipTimeSeriesList = getMergedPrecipTimeSeriesList(endTime, 6, - numHoursToPreprocess, - 1006, - cached6HourPrecipTimeSeriesList); - precipListHolder.setSixHourPrecipTimeSeriesList(sixHourPrecipTimeSeriesList); - - - twentyFourHourPrecipTimeSeriesList= getMergedPrecipTimeSeriesList(endTime, 24, - numHoursToPreprocess, - 2001, - cached24HourPrecipTimeSeriesList); - precipListHolder.setTwentyForHourPrecipTimeSeriesList(twentyFourHourPrecipTimeSeriesList); - - mergingTimer.stop(header + "merging the 1,3,6, and 24 hour time series took"); - - } - - return precipListHolder; - } - -// ------------------------------------------------------------------------ - private List getMergedPrecipTimeSeriesList(long endTime, int timeStepInHours, - int numHoursToPreprocess, - int durationCode, - List cachedPrecipTimeSeriesList) - { - String header = "PDCPreprocessorDataMgr.getMergedPrecipTimeSeriesList() "; - List mergedDataList = null; - List freshDataList = null; - long newStartTime = 0; - - String cachedDataFileName = "cached" + timeStepInHours + "HourPrecip"; - - - freshDataList = readPrecipTimeSeriesListFromCGeneratedFile(timeStepInHours, durationCode); - - newStartTime = getNewStartTime(endTime, timeStepInHours, numHoursToPreprocess); - long newEndTime = getNewEndTime(endTime, timeStepInHours); - - TimeSeriesListMgr.setNewStartTime(freshDataList, newStartTime); - - String newStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(newStartTime); - String newEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(newEndTime); - - System.out.println(header + " " + - timeStepInHours + "-hour timestep, newStartTime = " + - newStartTimeString + " newEndTime = " + newEndTimeString); - - mergedDataList = TimeSeriesListMgr.mergeTimeSeriesLists(freshDataList, - cachedPrecipTimeSeriesList, - newStartTime, - newEndTime); - - // copy to the cache for the next run - writeRegularObsDataToFile(mergedDataList, cachedDataFileName); - - return mergedDataList; - - } -// ------------------------------------------------------------------------ - long getNewStartTime(long endTime, int timeStepIntervalInHours, int numHoursToPreprocess) - { - long newStartTime = 0; - long hoursBack = 0; - - //----examine this section for simplification and correction- - // long numPeriods = numHoursToPreprocess / timeStepIntervalInHours; - // long millisBackInTime = numPeriods * timeStepIntervalInHours * MILLIS_PER_HOUR; - - if (timeStepIntervalInHours == 1) - { - hoursBack = numHoursToPreprocess - 1; - } - else - { - hoursBack = numHoursToPreprocess - 1; - } - - long timeStepIntervalInMillis = timeStepIntervalInHours * MILLIS_PER_HOUR; - long millisBackInTime = hoursBack * MILLIS_PER_HOUR; - - newStartTime = endTime - millisBackInTime; - newStartTime /= timeStepIntervalInMillis; - newStartTime *= timeStepIntervalInMillis; - //---------------- - - if (timeStepIntervalInHours == 24) - { - newStartTime += MILLIS_PER_12_HOURS; //12z is used instead of 0z - } - - return newStartTime; - - } - -// ------------------------------------------------------------------------ - - long getNewEndTime(long origEndTime, int timeStepIntervalInHours) - { - String header = "PDCPreprocessor.getNewEndTime(): "; - long endTime = 0; - - if (timeStepIntervalInHours != 24) - { - // System.out.println(header + "orig end time was " + DbTimeHelper.getDateTimeStringFromLongTime(origEndTime)); - endTime = TimeHelper.truncateTimeInMillisToNearestHour(origEndTime, timeStepIntervalInHours); - endTime += timeStepIntervalInHours * MILLIS_PER_HOUR; - } - - // System.out.println(header + "new time is " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - else //if (timeStepIntervalInHours == 24) - { - long twelveHourEndTime = TimeHelper.truncateTimeInMillisToNearestHour(origEndTime, 12); - long twentyFourHourEndTime = TimeHelper.truncateTimeInMillisToNearestHour(origEndTime, 24); - - if (twelveHourEndTime == twentyFourHourEndTime) //before 12 Z - { - endTime = twelveHourEndTime + MILLIS_PER_12_HOURS; - - } - else //after 12Z - { - endTime = twelveHourEndTime + MILLIS_PER_DAY; - } - - - } - - return endTime; - } -// ------------------------------------------------------------------------ - -/** - * disconnect() - Closes the active connection to the database - */ - public void disconnect() - { - _db.disconnect(); - } - -// ------------------------------------------------------------------------ - - public void finalize() - { - disconnect(); - } - -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------- - public void writeIrregularObsDataToFile( List obsTimeSeriesList, String fileName ) - { - PDCFileWriter writer = new PDCFileWriter(_locationHashMap, - _shefDurMap, - _shefDurToDurcodeMap, - _preprocessedFilePath); - writer.writeIrregularObsDataToFile(obsTimeSeriesList, fileName); - } - - - public void writeRegularObsDataToFile( List obsTimeSeriesList, String fileName ) - { - PDCFileWriter writer = new PDCFileWriter(_locationHashMap, - _shefDurMap, - _shefDurToDurcodeMap, - _preprocessedFilePath); - writer.writeRegularObsDataToFile(obsTimeSeriesList, fileName); - } - - - public void setPreprocessedFilePath( String preprocessedFilePath ) - { - _preprocessedFilePath = preprocessedFilePath; - } - -// ------------------------------------------------------------------------ - public void testPDCFiles() - { - String fullFilePath = _preprocessedFilePath + "/cachedHeight.dat"; - - PDCFileReaderSlow reader = new PDCFileReaderSlow(fullFilePath, _shefDurToDurcodeMap); - - List obsTimeSeriesList = reader.read(); - - - PDCFileWriter writer = new PDCFileWriter(_locationHashMap, - _shefDurMap, - _shefDurToDurcodeMap, - _preprocessedFilePath); - - writer.writeRegularObsDataToFile(obsTimeSeriesList, "cachedHeight2"); - } - -// ------------------------------------------------------------------------ - - /** - * @return Returns whether in debug mode or not. - */ -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PdcMergeTest.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PdcMergeTest.java deleted file mode 100644 index 0b71c25c39..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PdcMergeTest.java +++ /dev/null @@ -1,548 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -import junit.framework.TestCase; - -public class PdcMergeTest extends TestCase -{ - public static final long MILLIS_PER_HALF_HOUR = 30 * 60 * 1000; - public static final long MILLIS_PER_HOUR = 60 * 60 * 1000; - public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; - public static final long MILLIS_PER_12_HOURS = MILLIS_PER_HOUR * 12; - public static final long MILLIS_PER_MINUTE = 60 * 1000; - - - private String pdc_pp_dirValue = "./pdctest/"; - - private RegularObsTimeSeries _cached3HourTimeSeries = null; - private RegularObsTimeSeries _fresh3HourTimeSeries = null; - private RegularObsTimeSeries _expectedMerged3HourTimeSeries = null; - - private RegularObsTimeSeries _cached24HourTimeSeries = null; - private RegularObsTimeSeries _fresh24HourTimeSeries = null; - private RegularObsTimeSeries _expectedMerged24HourTimeSeries = null; - - private PDCPreprocessorDataMgr _dataMgr = null; - - // 3 hour variables - private long _3HourStartTime = _3HourCachedTimeValuePairArray[0].getDateTime(); - private String _3HourStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_3HourStartTime); - private String _3HourEndTimeString = "2007-01-02 05:15:00"; - private long _3HourEndTime = DbTimeHelper.getLongTimeFromDateTimeString(_3HourEndTimeString); - private int _3HourLookBackWindow = 24; - - - // 24 hour variables - private long _24HourStartTime = _24HourCachedTimeValuePairArray[0].getDateTime(); - private String _24HourStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_24HourStartTime); - private String _24HourEndTimeString = "2007-01-11 03:07:00"; - private long _24HourEndTime = DbTimeHelper.getLongTimeFromDateTimeString(_24HourEndTimeString); - private int _24HourLookBackWindow = 240; - - - private static TimeValuePair[] _3HourCachedTimeValuePairArray = - { - tvp("2007-01-01 00:00:00", 1.0), - tvp("2007-01-01 03:00:00", 2.0), - tvp("2007-01-01 06:00:00", 3.0), - tvp("2007-01-01 09:00:00", 4.0), - tvp("2007-01-01 12:00:00", 5.0), - tvp("2007-01-01 15:00:00", 6.0), - tvp("2007-01-01 18:00:00", 7.0), - tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), - tvp("2007-01-02 03:00:00", 10.0) - }; - - private static TimeValuePair[] _3HourFreshTimeValuePairArray = - { - // tvp("2007-01-01 00:00:00", 1.0), - // tvp("2007-01-01 03:00:00", 2.0), - // tvp("2007-01-01 06:00:00", 3.0), - // tvp("2007-01-01 09:00:00", 4.0), - // tvp("2007-01-01 12:00:00", 5.0), - // tvp("2007-01-01 15:00:00", 6.0), - // tvp("2007-01-01 18:00:00", 7.0), - tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), - tvp("2007-01-02 03:00:00", 11.0), - tvp("2007-01-02 06:00:00", 5.5) - }; - - private static TimeValuePair[] _3HourExpectedMergedTimeValuePairArray = - { - // tvp("2007-01-01 00:00:00", 1.0), - // tvp("2007-01-01 03:00:00", 2.0), - tvp("2007-01-01 06:00:00", 3.0), - tvp("2007-01-01 09:00:00", 4.0), - tvp("2007-01-01 12:00:00", 5.0), - tvp("2007-01-01 15:00:00", 6.0), - tvp("2007-01-01 18:00:00", 7.0), - tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), - tvp("2007-01-02 03:00:00", 11.0), - tvp("2007-01-02 06:00:00", 5.5) - }; - - - private static TimeValuePair[] _24HourCachedTimeValuePairArray = - { - tvp("2007-01-01 12:00:00", 1.0), - tvp("2007-01-02 12:00:00", 2.0), - tvp("2007-01-03 12:00:00", 3.0), - tvp("2007-01-04 12:00:00", 4.0), - tvp("2007-01-05 12:00:00", 5.0), - tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), - tvp("2007-01-08 12:00:00", 8.0), - // tvp("2007-01-09 12:00:00", 9.0), - // tvp("2007-01-10 12:00:00", 10.0) - }; - - private static TimeValuePair[] _24HourFreshTimeValuePairArray = - { - // tvp("2007-01-01 12:00:00", 1.0), - // tvp("2007-01-02 12:00:00", 2.0), - // tvp("2007-01-03 12:00:00", 3.0), - // tvp("2007-01-04 12:00:00", 4.0), - // tvp("2007-01-05 12:00:00", 5.0), - tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), - tvp("2007-01-08 12:00:00", 8.0), - tvp("2007-01-09 12:00:00", 9.0), - tvp("2007-01-10 12:00:00", 11.0), - tvp("2007-01-11 12:00:00", 5.5) - }; - - private static TimeValuePair[] _24HourExpectedMergedTimeValuePairArray = - { - tvp("2007-01-01 12:00:00", 1.0), - tvp("2007-01-02 12:00:00", 2.0), - tvp("2007-01-03 12:00:00", 3.0), - tvp("2007-01-04 12:00:00", 4.0), - tvp("2007-01-05 12:00:00", 5.0), - tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), - tvp("2007-01-08 12:00:00", 8.0), - tvp("2007-01-09 12:00:00", 9.0), - tvp("2007-01-10 12:00:00", 11.0), - tvp("2007-01-11 12:00:00", 5.5) - }; - - // -------------------------------------------------------------------------------------------------------- - - - public PdcMergeTest() - { - AppsDefaults ad = new AppsDefaults(); - - String preprocessedFilePath = ad.getToken( "pdc_pp_dir" ) + "/"; - String logDirName = ad.getToken( "pdc_pp_log_dir" ) + "/"; - - Logger logger = new FileLogger(logDirName + "PdcMergeTest.log"); - - String connectionString = "jdbc:postgresql://dx1-nhdr:5432/hd_ob81fwr?user=pguser"; - - _dataMgr = new PDCPreprocessorDataMgr(connectionString, logger, preprocessedFilePath, 5, 5, true); - - return; - } - - // -------------------------------------------------------------------------------------------------------- - protected void setUp() throws Exception - { - super.setUp(); - - createCachedTimeSeries(); - createFreshTimeSeries(); - createExpectedMergedTimeSeries(); - - } - // -------------------------------------------------------------------------------------------------------- - - - protected void tearDown() throws Exception - { - super.tearDown(); - } - - // -------------------------------------------------------------------------------------------------------- - - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor(String lid, - String startTimeString, - String endTimeString) - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - descriptor.setLid(lid); - descriptor.setPe("PP"); - descriptor.setDur((short) 1001); - descriptor.setTs("RG"); - descriptor.setExtremum("Z"); - - long startTime = DbTimeHelper.getLongTimeFromDateTimeString(startTimeString); - descriptor.setStartTime(startTime); - - long endTime = DbTimeHelper.getLongTimeFromDateTimeString(endTimeString); - descriptor.setEndTime(endTime); - - - return descriptor; - } - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor(String lid, - long startTime, - long endTime) - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - descriptor.setLid(lid); - descriptor.setPe("PP"); - descriptor.setDur((short) 1001); - descriptor.setTs("RG"); - descriptor.setExtremum("Z"); - - descriptor.setStartTime(startTime); - descriptor.setEndTime(endTime); - - - return descriptor; - } -// -------------------------------------------------------------------------------------------------------- - - private void addPairs(TimeValuePair[] timeValuePairArray, RegularObsTimeSeries regularObsTimeSeries) - { - String header = "PdcMergeTest.addPairs(): "; - for (int i = 0; i < timeValuePairArray.length; i++) - { - TimeValuePair tvp = timeValuePairArray[i]; - if (tvp != null) - { - regularObsTimeSeries.addTimeValuePairIfBetterMatch(tvp); - } - else - { - System.out.println(header + "tvp is null"); - } - } - - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeries createTimeSeries(String lid, int durationInHours, - TimeValuePair[] timeValuePairArray ) - { - //TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - TimeSlotPolicy timeSlotPolicy = null; - - TimeValuePair firstPair = timeValuePairArray[0]; - TimeValuePair lastPair = timeValuePairArray[timeValuePairArray.length-1]; - - long startTime = firstPair.getDateTime(); - long endTime = lastPair.getDateTime(); - - if (durationInHours == 3) - { - timeSlotPolicy = new HourlyTimeSlotPolicy(); - } - else if (durationInHours == 24) - { - timeSlotPolicy = new DailyTimeSlotPolicy(); - } - - - RegularObsTimeSeriesDescriptor descriptor = getRegularObsTimeSeriesDescriptor(lid, startTime, endTime); - - RegularObsTimeSeries timeSeries = - new RegularObsTimeSeries(descriptor, durationInHours, timeSlotPolicy); - - addPairs(timeValuePairArray, timeSeries); - - return timeSeries; - - } - // -------------------------------------------------------------------------------------------------------- - - private void createCachedTimeSeries() - { - _cached3HourTimeSeries = createTimeSeries("TEST1", 3, _3HourCachedTimeValuePairArray); - _cached24HourTimeSeries = createTimeSeries("TEST1", 24, _24HourCachedTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - private void createFreshTimeSeries() - { - _fresh3HourTimeSeries = createTimeSeries("TEST1", 3, _3HourFreshTimeValuePairArray); - _fresh24HourTimeSeries = createTimeSeries("TEST1", 24, _24HourFreshTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - private void createExpectedMergedTimeSeries() - { - _expectedMerged3HourTimeSeries = createTimeSeries("TEST1", 3, _3HourExpectedMergedTimeValuePairArray); - _expectedMerged24HourTimeSeries = createTimeSeries("TEST1", 24, _24HourExpectedMergedTimeValuePairArray); - } - - // -------------------------------------------------------------------------------------------------------- - - public void innerTestMerge(final long endTime, - int timeStepInHours, int numHoursToPreprocess, - RegularObsTimeSeries cachedTimeSeries, - RegularObsTimeSeries freshTimeSeries, - RegularObsTimeSeries expectedMergedTimeSeries) - { - - String header = "PdcMergeTest.innerTestMerge(): "; - - //The current PDC merge way - long newStartTime = _dataMgr.getNewStartTime(endTime, timeStepInHours, numHoursToPreprocess); - long newEndTime = _dataMgr.getNewEndTime(endTime, timeStepInHours); - - // long newStartTime = getNewStartTime(endTime, timeStepInHours, numHoursToPreprocess); - // long newEndTime = getNewEndTime(endTime, timeStepInHours); - - String originalEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - String newStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(newStartTime); - String newEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(newEndTime); - - System.out.println(header + "original end time = " + originalEndTimeString); - System.out.println(header + " " + - timeStepInHours + "-hour timestep, newStartTime = " + - newStartTimeString + " newEndTime = " + newEndTimeString); - - //These lists of time series (plural) will have only 1 time series each - List freshList = new ArrayList(); - freshList.add(freshTimeSeries); - - List cachedList = new ArrayList(); - cachedList.add(cachedTimeSeries); - - - List mergedList = TimeSeriesListMgr.mergeTimeSeriesLists(freshList, cachedList, newStartTime, newEndTime); - RegularObsTimeSeries mergedTs = null; - - //get out the 1 merged time series that we are expecting - for (int i = 0; i < mergedList.size(); i++) - { - mergedTs = (RegularObsTimeSeries) mergedList.get(i); - } - - //check that the merged list still has only 1 time series - assertEquals(1, mergedList.size()); - - //verify that the name of the time series is correct - String lid = mergedTs.getDescriptor().getLid(); - assertEquals("TEST1", lid); - - - //verify that there are contents each time series - - boolean biggerThanZero = false; - - //fresh - biggerThanZero = freshTimeSeries.getTimeValuePairList(true).size() > 0; - assertEquals(true, biggerThanZero); - - //cached - biggerThanZero = cachedTimeSeries.getTimeValuePairList(true).size() > 0; - assertEquals(true, biggerThanZero); - - //merged - biggerThanZero = mergedTs.getTimeValuePairList(true).size() > 0; - assertEquals(true, biggerThanZero); - - - // verify that the fresh and cached are not equal - boolean freshTsAndCachedEqual = regularTimeSeriesEqual(freshTimeSeries, cachedTimeSeries); - assertEquals(false, freshTsAndCachedEqual); - - // verify that the fresh and mergedTs are equal, since mergeTs really IS freshTs - boolean mergeTsAndFreshEqual = regularTimeSeriesEqual(mergedTs, freshTimeSeries); - assertEquals(true, mergeTsAndFreshEqual); - - - - - // verify that the cached and mergeTs are not equal - boolean mergeTsAndCachedEqual = regularTimeSeriesEqual(mergedTs, cachedTimeSeries); - assertEquals(false, mergeTsAndCachedEqual); - - // verify that the mergedTs is equal to the expectedMergedTimeSeries - - boolean mergedTsAndExpectedMergedTsEqual = regularTimeSeriesEqual(mergedTs, expectedMergedTimeSeries); - if (! mergedTsAndExpectedMergedTsEqual) - { - System.out.println(" mergedTs = "); - System.out.println(mergedTs); - - System.out.println("expected mergedTs = "); - System.out.println(expectedMergedTimeSeries + "\n"); - } - assertEquals(true, mergedTsAndExpectedMergedTsEqual); - - } - // -------------------------------------------------------------------------------------------------------- - - public void test3HourMerge() - { - innerTestMerge(_3HourEndTime, 3, _3HourLookBackWindow, - _cached3HourTimeSeries, - _fresh3HourTimeSeries, - _expectedMerged3HourTimeSeries); - - long lastValue = _fresh3HourTimeSeries.getLatestTimeValue(-9999); - long expectedLastValue = DbTimeHelper.getLongTimeFromDateTimeString("2007-01-02 06:00:00"); - assertEquals(expectedLastValue, lastValue); - } - // -------------------------------------------------------------------------------------------------------- - - public void testGetNewEndTime() - { - innerTestGetNewEndTime("2007-01-01 12:00:00", "2007-01-01 00:00:00", 24); - innerTestGetNewEndTime("2007-01-01 12:00:00", "2007-01-01 03:00:00", 24); - innerTestGetNewEndTime("2007-01-01 12:00:00", "2007-01-01 11:00:00", 24); - innerTestGetNewEndTime("2007-01-02 12:00:00", "2007-01-01 12:00:00", 24); - innerTestGetNewEndTime("2007-01-02 12:00:00", "2007-01-01 13:00:00", 24); - innerTestGetNewEndTime("2007-01-02 12:00:00", "2007-01-01 16:00:00", 24); - } - - // -------------------------------------------------------------------------------------------------------- - - - public void innerTestGetNewEndTime(String expectedDateTimeString, - String originalDateTimeString, - int timeStepInHours) - { - - String header = "PdcMergeTest.innerTestGenNewEndTime(): "; - - long origEndTime = DbTimeHelper.getLongTimeFromDateTimeString(originalDateTimeString); - long expectedEndTime = DbTimeHelper.getLongTimeFromDateTimeString(expectedDateTimeString); - - long newEndTime = _dataMgr.getNewEndTime(origEndTime, timeStepInHours); - String newEndDateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(newEndTime); - - if (expectedEndTime != newEndTime) - { - System.out.println(header + "originalDateTimeString = " + originalDateTimeString + - "\n expectedEndTime = " + expectedDateTimeString + " while the " + - "\n actual new end time is " + newEndDateTimeString); - } - - assertEquals(expectedEndTime, newEndTime); - - } - - public void test24HourMerge() - { - innerTestMerge(_24HourEndTime, 24, _24HourLookBackWindow, - _cached24HourTimeSeries, - _fresh24HourTimeSeries, - _expectedMerged24HourTimeSeries); - - long lastValue = _fresh24HourTimeSeries.getLatestTimeValue(-9999); - System.out.println("24 hour last value = " + DbTimeHelper.getDateTimeStringFromLongTime(lastValue)); - long expectedLastValue = DbTimeHelper.getLongTimeFromDateTimeString("2007-01-11 12:00:00"); - assertEquals(expectedLastValue, lastValue); - } - // -------------------------------------------------------------------------------------------------------- - - private boolean regularTimeSeriesEqual(RegularObsTimeSeries rts1, RegularObsTimeSeries rts2) - { - boolean result = true; - - List tvpList1 = rts1.getTimeValuePairList(true); - List tvpList2 = rts2.getTimeValuePairList(true); - - - // System.out.println("tvpList1.size() = " + tvpList1.size()); - // System.out.println("tvpList2.size() = " + tvpList2.size()); - - //check the sizes - if (tvpList1.size() != tvpList2.size() ) - { - result = false; - } - - - - - //if that passed, check the individual parts - for (int i = 0; result && i < tvpList1.size(); i++) - { - TimeValuePair tvp1 = (TimeValuePair) tvpList1.get(i); - TimeValuePair tvp2 = (TimeValuePair) tvpList2.get(i); - - if (mismatchedNullness(tvp1, tvp2)) - { - result = false; - } - - else if ((tvp1 == null) && (tvp2 == null)) - { - // System.out.println("tvp 1 and tvp2 are both null "); - ; //do nothing - } - - else if (tvp1 == null) - { - // System.out.println("tvp1 is null "); - ; //do nothing - } - - - else if (tvp2 == null) - { - // System.out.println("tvp2 is null "); - ; //do nothing - } - - else if ((tvp1.getValue() != tvp2.getValue()) ) - { - //System.out.println("tvp 1 = " + tvp1 + " tvp2 = " + tvp2); - result = false; - } - - } - - return result; - } - - - // -------------------------------------------------------------------------------------------------------- - private boolean mismatchedNullness(TimeValuePair tvp1, TimeValuePair tvp2) - { - boolean result = false; - - if ((tvp1 == null) && (tvp2 != null)) - { - result = true; - } - else if ( (tvp2 != null) && (tvp2 == null)) - { - result = true; - } - - return result; - } - // -------------------------------------------------------------------------------------------------------- - - private static TimeValuePair tvp(String dateTimeString, double value) - { - long time = DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - return new TimeValuePair(time, value); - - } - - // -------------------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PdcReadTest.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PdcReadTest.java deleted file mode 100644 index 21985decfb..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PdcReadTest.java +++ /dev/null @@ -1,401 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -import junit.framework.TestCase; - -public class PdcReadTest extends TestCase -{ - Database _db = null; - private RegularObsTimeSeries _correct3HourTimeSeries = null; - - private RegularObsTimeSeries _correct24HourTimeSeries = null; - private PDCPreprocessorDataMgr _dataMgr = null; - - private static TimeValuePair[] _3HourCorrectTimeValuePairArray = - { - tvp("2007-01-01 00:00:00", 1.0), - tvp("2007-01-01 03:00:00", 2.0), - tvp("2007-01-01 06:00:00", 3.0), - tvp("2007-01-01 09:00:00", 4.0), - tvp("2007-01-01 12:00:00", 5.0), - tvp("2007-01-01 15:00:00", 6.0), - tvp("2007-01-01 18:00:00", 7.0), - tvp("2007-01-01 21:00:00", 8.0), - tvp("2007-01-02 00:00:00", 9.0), - tvp("2007-01-02 03:00:00", 11.0) - }; - - private static TimeValuePair[] _24HourCorrectTimeValuePairArray = - { - tvp("2007-01-01 12:00:00", 1.0), - tvp("2007-01-02 12:00:00", 2.0), - tvp("2007-01-03 12:00:00", 3.0), - tvp("2007-01-04 12:00:00", 4.0), - tvp("2007-01-05 12:00:00", 5.0), - tvp("2007-01-06 12:00:00", 6.0), - tvp("2007-01-07 12:00:00", 7.0), - tvp("2007-01-08 12:00:00", 8.0), - tvp("2007-01-09 12:00:00", 9.0), - tvp("2007-01-10 12:00:00", 10.0) - }; - - - // 3 hour variables - private long _3HourStartTime = _3HourCorrectTimeValuePairArray[0].getDateTime(); - private String _3HourStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_3HourStartTime); - - private long _3HourEndTime = _3HourCorrectTimeValuePairArray[9].getDateTime(); - private String _3HourEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_3HourEndTime); - - - // 24 hour variables - private long _24HourStartTime = _24HourCorrectTimeValuePairArray[0].getDateTime(); - private String _24HourStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_24HourStartTime); - - private long _24HourEndTime = _24HourCorrectTimeValuePairArray[9].getDateTime(); - private String _24HourEndTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_24HourEndTime); - - - public PdcReadTest() - { - - AppsDefaults ad = new AppsDefaults(); - - String preprocessedFilePath = ad.getToken( "pdc_pp_dir" ) + "/"; - String logDirName = ad.getToken( "pdc_pp_log_dir" ) + "/"; - - Logger logger = new FileLogger(logDirName + "PdcReadTest.log"); - - String connectionString = "jdbc:postgresql://dx1-nhdr:5432/hd_ob81fwr?user=pguser"; - - _dataMgr = new PDCPreprocessorDataMgr(connectionString, logger, preprocessedFilePath, 5, 5, true); - - long time = DbTimeHelper.getLongTimeFromDateTimeString("2007-01-01 12:00:00"); - System.out.println("time = " + time); - - time = DbTimeHelper.getLongTimeFromDateTimeString(" 2007-01-10 12:00:00"); - System.out.println("time = " + time); - - - } - // -------------------------------------------------------------------------------------------------------- - protected void setUp() throws Exception - { - super.setUp(); - - - createCorrectTimeSeries(); - - } - // -------------------------------------------------------------------------------------------------------- - - - protected void tearDown() throws Exception - { - super.tearDown(); - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeriesDescriptor getRegularObsTimeSeriesDescriptor(String lid, - String startTimeString, - String endTimeString) - { - RegularObsTimeSeriesDescriptor descriptor = new RegularObsTimeSeriesDescriptor(); - descriptor.setLid(lid); - descriptor.setPe("PP"); - descriptor.setDur((short) 1001); - descriptor.setTs("RG"); - descriptor.setExtremum("Z"); - - long startTime = DbTimeHelper.getLongTimeFromDateTimeString(startTimeString); - descriptor.setStartTime(startTime); - - long endTime = DbTimeHelper.getLongTimeFromDateTimeString(endTimeString); - descriptor.setEndTime(endTime); - - - return descriptor; - } - - // -------------------------------------------------------------------------------------------------------- - private RegularObsTimeSeries createTimeSeries(String lid, int durationInHours, TimeValuePair[] timeValuePairArray ) - { - //TimeSlotPolicy timeSlotPolicy = new HourlyTimeSlotPolicy(); - TimeSlotPolicy timeSlotPolicy = null; - - String startTimeString = null; - String endTimeString = null; - - if (durationInHours == 3) - { - startTimeString = _3HourStartTimeString; - endTimeString = _3HourEndTimeString; - } - else if (durationInHours == 24) - { - startTimeString = _24HourStartTimeString; - endTimeString = _24HourEndTimeString; - } - - - RegularObsTimeSeriesDescriptor descriptor = getRegularObsTimeSeriesDescriptor(lid, startTimeString, endTimeString); - - RegularObsTimeSeries timeSeries = - new RegularObsTimeSeries(descriptor, durationInHours, timeSlotPolicy); - - addPairs(timeValuePairArray, timeSeries); - - return timeSeries; - - } - // -------------------------------------------------------------------------------------------------------- - - private void addPairs(TimeValuePair[] timeValuePairArray, RegularObsTimeSeries regularObsTimeSeries) - { - for (int i = 0; i < timeValuePairArray.length; i++) - { - TimeValuePair tvp = timeValuePairArray[i]; - if (tvp != null) - { - regularObsTimeSeries.addTimeValuePairIfBetterMatch(tvp); - } - } - - } - - // -------------------------------------------------------------------------------------------------------- - - - private void createCorrectTimeSeries() - { - _correct3HourTimeSeries = createTimeSeries("TEST1", 3, _3HourCorrectTimeValuePairArray); - _correct24HourTimeSeries = createTimeSeries("TEST1", 24, _24HourCorrectTimeValuePairArray); - } - // -------------------------------------------------------------------------------------------------------- - - public void innerCFileRead(int timeStepIntervalInHours, int durationCode, RegularObsTimeSeries correctTimeSeries) - { - - long newStartTime = correctTimeSeries.getDescriptor().getStartTime(); - long endTime = correctTimeSeries.getDescriptor().getEndTime(); - - //These lists of time series (plural) will have only 1 time series each - - List readTsList = _dataMgr.readPrecipTimeSeriesListFromCGeneratedFile(timeStepIntervalInHours, durationCode); - - RegularObsTimeSeries readTs = null; - - for (int i = 0; i < readTsList.size(); i++) - { - readTs = (RegularObsTimeSeries) readTsList.get(i); - } - - String lid = readTs.getDescriptor().getLid(); - assertEquals("TEST1", lid); - - boolean readAndCorrectTimeSeriesEqual = regularTimeSeriesEqual(readTs, correctTimeSeries); - assertEquals(true, readAndCorrectTimeSeriesEqual); - - } - // -------------------------------------------------------------------------------------------------------- - - public void test3HourRead() - { - innerCFileRead(3, 1003, _correct3HourTimeSeries); - } - // -------------------------------------------------------------------------------------------------------- - - public void test24HourRead() - { - innerCFileRead(24, 2001, _correct24HourTimeSeries); - } - // -------------------------------------------------------------------------------------------------------- - public void testPDCFileRead() - { - CodeTimer timer1 = new CodeTimer(); - CodeTimer timer2 = new CodeTimer(); - - String fileName = "/awips/hydroapps/ob82/whfs/local/data/pdc_pp/cached1HourPrecip.dat"; - - - timer1.start(); - PDCFileReaderSlow reader1 = new PDCFileReaderSlow(fileName); - List list1 = reader1.read(); - timer1.stop("old PDCFileReaderSlow took"); - - timer2.start(); - PDCFileReader reader2 = new PDCFileReader(fileName); - // reader2.setDebug(true); - List list2 = reader2.read(); - timer2.stop("new PDCFileReaderSlow took"); - - - boolean actualResult = listOfRegularTimeSeriesEqual(list1, list2); - - assertEquals(true, actualResult); - - } - // -------------------------------------------------------------------------------------------------------- - private boolean atLeastOneIsNull(Object object1, Object object2) - { - boolean result = false; - - if ( (object1 == null) || (object2 == null)) - { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - - private boolean bothAreNull(Object object1, Object object2) - { - boolean result = false; - - if ( (object1 == null) && (object2 == null)) - { - result = true; - } - - return result; - } - - // -------------------------------------------------------------------------------------------------------- - - - private boolean listOfRegularTimeSeriesEqual(List list1, List list2) - { - boolean result = true; - - - - if (atLeastOneIsNull(list1, list2)) - { - if (bothAreNull(list1, list2)) - { - result = true; - } - else //they are different - { - result = false; - } - } - - else if (list1.size() != list2.size()) //neither is null - { - result = false; //size is different, the lists are not the same - } - - else //size is same, need to check some more - { - result = true; //assume they are the same. change if proved false - - for (int i = 0; i < list1.size(); i++) - { - RegularObsTimeSeries ts1 = (RegularObsTimeSeries) list1.get(i); - RegularObsTimeSeries ts2 = (RegularObsTimeSeries) list2.get(i); - - if (! regularTimeSeriesEqual(ts1, ts2)) - { - result = false; // something is different, so the lists are not the same - break; - - } - } - - } - - return result; - - } - - // -------------------------------------------------------------------------------------------------------- - - - private boolean regularTimeSeriesEqual(RegularObsTimeSeries rts1, RegularObsTimeSeries rts2) - { - boolean result = true; - - List tvpList1 = rts1.getTimeValuePairList(true); - List tvpList2 = rts2.getTimeValuePairList(true); - - - //System.out.println("tvpList1.size() = " + tvpList1.size()); - - //check the sizes - if (tvpList1.size() != tvpList2.size() ) - { - result = false; - } - - - - - //if that passed, check the individual parts - for (int i = 0; result && i < tvpList1.size(); i++) - { - TimeValuePair tvp1 = (TimeValuePair) tvpList1.get(i); - TimeValuePair tvp2 = (TimeValuePair) tvpList2.get(i); - - if (mismatchedNullness(tvp1, tvp2)) - { - result = false; - } - - else if (tvp1 == null) - { - //System.out.print("tvp 1 and tvp2 are both null "); - ; //do nothing - } - - else if ((tvp1.getValue() != tvp2.getValue()) ) - { - //System.out.println("tvp 1 = " + tvp1 + " tvp2 = " + tvp2); - result = false; - } - - } - - return result; - } - - - // -------------------------------------------------------------------------------------------------------- - private boolean mismatchedNullness(TimeValuePair tvp1, TimeValuePair tvp2) - { - boolean result = false; - - if ((tvp1 == null) && (tvp2 != null)) - { - result = true; - } - else if ( (tvp2 != null) && (tvp2 == null)) - { - result = true; - } - - return result; - } - // -------------------------------------------------------------------------------------------------------- - - private static TimeValuePair tvp(String dateTimeString, double value) - { - long time = DbTimeHelper.getLongTimeFromDateTimeString(dateTimeString); - return new TimeValuePair(time, value); - - } - - // -------------------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PrecipListHolder.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PrecipListHolder.java deleted file mode 100644 index f674749b72..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/PrecipListHolder.java +++ /dev/null @@ -1,85 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.List; - -public class PrecipListHolder -{ - private List _instantPrecipTimeSeriesList; - private List _oneHourPrecipTimeSeriesList; - private List _threeHourPrecipTimeSeriesList; - private List _sixHourPrecipTimeSeriesList; - private List _twentyForHourPrecipTimeSeriesList; - - // -------------------------------------------------------------------------------------- - /** - * @param instantPrecipTimeSeriesList The instantPrecipTimeSeriesList to set. - */ - public void setInstantPrecipTimeSeriesList(List instantPrecipTimeSeriesList) - { - this._instantPrecipTimeSeriesList = instantPrecipTimeSeriesList; - } - /** - * @return Returns the instantPrecipTimeSeriesList. - */ - public List getInstantPrecipTimeSeriesList() - { - return _instantPrecipTimeSeriesList; - } - /** - * @param oneHourPrecipTimeSeriesList The oneHourPrecipTimeSeriesList to set. - */ - public void setOneHourPrecipTimeSeriesList(List oneHourPrecipTimeSeriesList) - { - this._oneHourPrecipTimeSeriesList = oneHourPrecipTimeSeriesList; - } - /** - * @return Returns the oneHourPrecipTimeSeriesList. - */ - public List getOneHourPrecipTimeSeriesList() - { - return _oneHourPrecipTimeSeriesList; - } - /** - * @param threeHourPrecipTimeSeriesList The threeHourPrecipTimeSeriesList to set. - */ - public void setThreeHourPrecipTimeSeriesList(List threeHourPrecipTimeSeriesList) - { - this._threeHourPrecipTimeSeriesList = threeHourPrecipTimeSeriesList; - } - /** - * @return Returns the _3hourPrecipTimeSeriesList. - */ - public List getThreeHourPrecipTimeSeriesList() - { - return _threeHourPrecipTimeSeriesList; - } - /** - * @param sixHourPrecipTimeSeriesList The sixHourPrecipTimeSeriesList to set. - */ - public void setSixHourPrecipTimeSeriesList(List sixHourPrecipTimeSeriesList) - { - this._sixHourPrecipTimeSeriesList = sixHourPrecipTimeSeriesList; - } - /** - * @return Returns the sixHourPrecipTimeSeriesList. - */ - public List getSixHourPrecipTimeSeriesList() - { - return _sixHourPrecipTimeSeriesList; - } - /** - * @param twentyForHourPrecipTimeSeriesList The twentyForHourPrecipTimeSeriesList to set. - */ - public void setTwentyForHourPrecipTimeSeriesList(List twentyForHourPrecipTimeSeriesList) - { - this._twentyForHourPrecipTimeSeriesList = twentyForHourPrecipTimeSeriesList; - } - /** - * @return Returns the twentyForHourPrecipTimeSeriesList. - */ - public List getTwentyFourHourPrecipTimeSeriesList() - { - return _twentyForHourPrecipTimeSeriesList; - } - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeries.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeries.java deleted file mode 100644 index 5cc620b10e..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeries.java +++ /dev/null @@ -1,442 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * - * @author Gautam Sood - * - */ -public class RegularObsTimeSeries -{ - - private String _mergerString = null; - - private TimeSlotPolicy _timeSlotPolicy = null; - private RegularObsTimeSeriesDescriptor _obsTimeSeriesDescriptor; - private Map _topOfTheHourTimeValuePairMap = new HashMap(); - private boolean _valuePairListNeedsRefreshing = true; - private List _timeValuePairList = new ArrayList(); -// private List _dateTimeList = new ArrayList(); - private long _timeStepDurationInMillis = 0; //Time in millis between each value - - private static final int MILLIS_PER_HOUR = 60 * 60 * 1000; - -/** - * @param descriptor - RegularObsTimeSeriesDescriptor - * @param timeStepDurationInHours - Time step duration in hours. e.g. hourly timeseries, 6 hourly timeseries, etc - * @param timeSlotPolicy - Hourly or Daily time slot policy - */ - public RegularObsTimeSeries( RegularObsTimeSeriesDescriptor descriptor, long timeStepDurationInHours, TimeSlotPolicy timeSlotPolicy ) - { - _obsTimeSeriesDescriptor = descriptor; - _timeStepDurationInMillis = timeStepDurationInHours * PDCPreprocessorDataMgr.MILLIS_PER_HOUR; - _timeSlotPolicy = timeSlotPolicy; - - setMergerString("UNTOUCHED"); - } - - public RegularObsTimeSeries( RegularObsTimeSeries origTimeSeries) - { - //Note: This is a deep copy, not a shallow one - setObsTimeSeriesDescriptor(new RegularObsTimeSeriesDescriptor(origTimeSeries.getDescriptor()) ); - - _timeSlotPolicy = origTimeSeries._timeSlotPolicy; //immutable object - - Map copiedMap = copyTimeOfTheHourTimeValuePairMap(origTimeSeries.getTopOfTheHourTimeValuePairMap()); - setTopOfTheHourTimeValuePairMap( copiedMap ); - - // setDateTimeList( origTimeSeries.getDateTimeList() ); - _timeStepDurationInMillis = origTimeSeries.getTimeStepIntervalInMillis(); - - setMergerString(origTimeSeries.getMergerString()); - } - - private Map copyTimeOfTheHourTimeValuePairMap(Map origMap) - { - Map map = new HashMap(); - - TimeValuePair origPair = null; - TimeValuePair newPair = null; - - Collection valuesCollection = origMap.values(); - - List valueList = new ArrayList(valuesCollection); - - for (int i = 0; i < valueList.size(); i++) - { - origPair = (TimeValuePair) valueList.get(i); - - newPair = new TimeValuePair(origPair); - map.put( new Long(newPair.getDateTime()), newPair); - - } - return map; - } - - - public String toString() - { - updateTimeValuePairList(); - - StringBuffer stringBuffer = new StringBuffer(); - - stringBuffer.append("Time step = " + _timeStepDurationInMillis/MILLIS_PER_HOUR + " hours: "); - - for ( int i = 0; i < _timeValuePairList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) _timeValuePairList.get( i ); - if (timeValuePair != null) - { - stringBuffer.append(timeValuePair.toString() + '|'); - } - } - return stringBuffer.toString(); - } - - public List getTimeValuePairList( boolean forceRefresh ) - { - if ( ( _valuePairListNeedsRefreshing ) || ( forceRefresh ) ) - { - updateTimeValuePairList(); - } - - return _timeValuePairList; - } - - private void updateTimeValuePairList() - { - String header = "RegularObsTimeSeries.updateTimeValuePairList(): "; - _timeValuePairList.clear(); - long endTime = _obsTimeSeriesDescriptor.getEndTime(); - long startTime = _obsTimeSeriesDescriptor.getStartTime(); - - // System.out.println(header + "startTime = " + startTime + " endTime = " + endTime ); - - for ( long time = startTime; time <= endTime; time+=_timeStepDurationInMillis ) - { - Long dateTimeLong = new Long( time ); - TimeValuePair timeValuePair = (TimeValuePair) _topOfTheHourTimeValuePairMap.get( dateTimeLong ); - - /* - if (timeValuePair == null) - { - System.out.println(header + " value being added is null for desc = " + _obsTimeSeriesDescriptor); - } - */ - - _timeValuePairList.add( timeValuePair ); - - } - - _valuePairListNeedsRefreshing = false; - return; - } - - public void addTimeValuePairIfBetterMatch( TimeValuePair newTimeValuePair ) - { - _valuePairListNeedsRefreshing = true; - - if (_timeSlotPolicy == null) //null is, in effect, a permissive policy, letting everything in - { - Long key = new Long(newTimeValuePair.getDateTime()); - _topOfTheHourTimeValuePairMap.put(key, newTimeValuePair); - } - - else //when you have a real policy - { - Long topOfTheHourKey = _timeSlotPolicy.getSlotDateTimeInMillis(newTimeValuePair.getDateTime()); - - if (topOfTheHourKey != null) - { - _timeSlotPolicy.insertTimeValuePairIfBetterMatch(_topOfTheHourTimeValuePairMap, newTimeValuePair); - } - } - } - - /** - * @param otherTimeSeries - * This method takes the argument's time value pairs and uses them to - * update the current object's _topOfTheHourTimeValuePairMap. - * - */ - public void replaceMatchingTimeValuePairs(RegularObsTimeSeries otherTimeSeries) - { - String header = "RegularObsTimeSeries.replaceMatchingTimeValuePairs(): "; - boolean done = false; - - this._valuePairListNeedsRefreshing = true; - - List otherTimeValuePairList = otherTimeSeries.getTimeValuePairList(true); - if (otherTimeValuePairList == null) - { - System.err.println(header + " ERROR - otherTimeValuePairList is null. "); - done = true; - } - - for (int i = 0; ( !done && (i < otherTimeValuePairList.size()) ); i++) - { - TimeValuePair newTimeValuePair = (TimeValuePair) otherTimeValuePairList.get(i); - Long key = null; - - if (newTimeValuePair != null) - { - key = new Long(newTimeValuePair.getDateTime()); - if (key != null) - { - //if there is a value already here, then replace it - if (this._topOfTheHourTimeValuePairMap.get(key) != null) - { - this._topOfTheHourTimeValuePairMap.put(key, newTimeValuePair); - } - else //value not already present, so leave it alone - { - - } - } - else - { - throw new Error(header + "key is not allowed to be null"); - } - } - - } - - return; - } - - // --------------------------------------------------------------------------------------- - public void replaceNonMatchingTimeValuePairs(RegularObsTimeSeries anotherTimeSeries) - { - String header = "RegularObsTimeSeries.replaceNonMatchingTimeValuePairs(): "; - boolean done = false; - - this._valuePairListNeedsRefreshing = true; - - List otherTimeValuePairList = anotherTimeSeries.getTimeValuePairList(true); - if (otherTimeValuePairList == null) - { - System.err.println(header + " ERROR - otherTimeValuePairList is null. "); - done = true; - } - - for (int i = 0; ( !done && (i < otherTimeValuePairList.size()) ); i++) - { - TimeValuePair newTimeValuePair = (TimeValuePair) otherTimeValuePairList.get(i); - Long key = null; - - if (newTimeValuePair != null) - { - key = new Long(newTimeValuePair.getDateTime()); - if (key != null) - { - //if there is no value already here, then put one in - if (this._topOfTheHourTimeValuePairMap.get(key) == null) - { - this._topOfTheHourTimeValuePairMap.put(key, newTimeValuePair); - } - else //value already present, so leave it alone - { - - } - } - else - { - throw new Error(header + "key is not allowed to be null"); - } - } - - } - - return; - } - - // --------------------------------------------------------------------------------------- - - public void removeTimeValuePairsBefore(long startTime) - { - List keyList = new ArrayList(_topOfTheHourTimeValuePairMap.keySet()); - - //remove any excess Hours from the front of the list. - for (int i = 0; i < keyList.size() ; i++) - { - Object objectKey = keyList.get(i); - - if (objectKey != null) - { - Long key = (Long) objectKey; - - if (key.longValue() < startTime) - { - _topOfTheHourTimeValuePairMap.remove(key); - } - } - - } - _valuePairListNeedsRefreshing = true; - } - - // --------------------------------------------------------------------------------------- - - public void removeTimeValuePairsAfter(long endTime) - { - List keyList = new ArrayList(_topOfTheHourTimeValuePairMap.keySet()); - - //remove any excess Hours from the front of the list. - for (int i = 0; i < keyList.size() ; i++) - { - Object objectKey = keyList.get(i); - - if (objectKey != null) - { - Long key = (Long) objectKey; - - if (key.longValue() > endTime) - { - _topOfTheHourTimeValuePairMap.remove(key); - } - } - - } - _valuePairListNeedsRefreshing = true; - } - - // --------------------------------------------------------------------------------------- - - public long getLatestTimeValue(long badValue) - { - String header = "RegularObsTimeSeries.getLatestTimeValue(): "; - long latestTimeValue = badValue; - List timeValuePairList = getTimeValuePairList(false); - - if (timeValuePairList != null) - { - - if (timeValuePairList.size() > 0) - { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(timeValuePairList.size() - 1); - if (pair != null) - { - latestTimeValue = pair.getDateTime(); - // System.out.println(header + "latestTimeValue = " - // + latestTimeValue); - } - else - { - // System.out.println(header + "latest TimeValuePair is null "); - } - } - else - { - // System.out.println(header + "timeValuePairList.size() == 0 "); - } - } - else - { - // System.out.println(header + "timeValuePairList is null"); - } - - return latestTimeValue; - } - - // --------------------------------------------------------------------------------------- - - public void setObsTimeSeriesDescriptor( RegularObsTimeSeriesDescriptor obsTimeSeriesDescriptor ) - { - _obsTimeSeriesDescriptor = obsTimeSeriesDescriptor; - _valuePairListNeedsRefreshing = true; - } - // --------------------------------------------------------------------------------------- - - public RegularObsTimeSeriesDescriptor getDescriptor() - { - return _obsTimeSeriesDescriptor; - } - // --------------------------------------------------------------------------------------- - public void setStartTime(long startTime) - { - getDescriptor().setStartTime(startTime); - - _valuePairListNeedsRefreshing = true; - - } - // --------------------------------------------------------------------------------------- - - public void setEndTime(long endTime) - { - getDescriptor().setEndTime(endTime); - - _valuePairListNeedsRefreshing = true; - - } - // --------------------------------------------------------------------------------------- - public void setTimeValuePairList( List timeValueList ) - { - _timeValuePairList.addAll( timeValueList ); - } - // --------------------------------------------------------------------------------------- - - public void addTimeValuePairList( List timeValueList ) - { - String header = "RegularObsTimeSeries.addTimeValuePairList(): "; - _valuePairListNeedsRefreshing = true; - for ( int i = 0; i < timeValueList.size(); i++ ) - { - TimeValuePair timeValuePair = (TimeValuePair) timeValueList.get( i ); - // System.out.println(header + " attempting to add timeValuePair = " + timeValuePair ); - addTimeValuePairIfBetterMatch( timeValuePair ); - } - } - // --------------------------------------------------------------------------------------- - - public void setTopOfTheHourTimeValuePairMap( Map topOfTheHourTimeValuePairMap ) - { - _topOfTheHourTimeValuePairMap = topOfTheHourTimeValuePairMap; - } - // --------------------------------------------------------------------------------------- - - public Map getTopOfTheHourTimeValuePairMap() - { - return _topOfTheHourTimeValuePairMap; - } - // --------------------------------------------------------------------------------------- - - // public void setDateTimeList( List dateTimeList ) - // { - // _dateTimeList = dateTimeList; - // } - - // public List getDateTimeList() - // { - // return _dateTimeList; - // } - - /** - * @return Returns the timeStepDurationInMillis. - */ - public long getTimeStepIntervalInMillis() - { - return _timeStepDurationInMillis; - } - - /** - * @param mergerString The mergerString to set. - */ - public void setMergerString(String mergerString) - { - _mergerString = mergerString; - } - - /** - * @return Returns the mergerString. - */ - public String getMergerString() - { - return _mergerString; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java deleted file mode 100644 index 872262e228..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java +++ /dev/null @@ -1,23 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Comparator; - -public class RegularObsTimeSeriesComparator implements Comparator -{ - - public int compare(Object object1, Object object2) - { - RegularObsTimeSeries ts1 = (RegularObsTimeSeries) object1; - RegularObsTimeSeries ts2 = (RegularObsTimeSeries) object2; - - RegularObsTimeSeriesDescriptor desc1 = ts1.getDescriptor(); - RegularObsTimeSeriesDescriptor desc2 = ts2.getDescriptor(); - - int returnValue = desc1.toString().compareTo(desc2.toString()); - - return returnValue; - } - - - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java.new b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java.new deleted file mode 100644 index 701cd81854..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesComparator.java.new +++ /dev/null @@ -1,63 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Comparator; - -public class RegularObsTimeSeriesComparator implements Comparator -{ - - public int compare(Object object1, Object object2) - { - RegularObsTimeSeries ts1 = (RegularObsTimeSeries) object1; - RegularObsTimeSeries ts2 = (RegularObsTimeSeries) object2; - - RegularObsTimeSeriesDescriptor desc1 = ts1.getDescriptor(); - RegularObsTimeSeriesDescriptor desc2 = ts2.getDescriptor(); - RegularObsTimeSeriesDescriptor first = null; - RegularObsTimeSeriesDescriptor second = null; - - String header = "RegularObsTimeSeriesComparator.compare(): "; - - - int returnValue = desc1.toString().compareTo(desc2.toString()); - - - - if ( - (desc1.getLid().equals("WETO2") || desc1.getLid().equals("ALXO2")) && - (desc2.getLid().equals(desc1.getLid()) ) - ) - { - //System.out.println(header + "desc1 = :" + desc1.toString() + ":"); - //System.out.println(header + "desc2 = :" + desc2.toString() + ":\n"); - - - if (returnValue < 0) - { - first = desc1; - second = desc2; - // System.out.println(header + first.toString() + " comes before " + second.toString()); - } - else if (returnValue > 0) - { - first = desc2; - second = desc1; - // System.out.println(header + first.toString() + " comes before " + second.toString()); - } - else - { - System.out.println(header + " equals " ); - } - - System.out.println(header + "first = :" + first.toString() + ":"); - System.out.println(header + "second = :" + second.toString() + ":\n"); - - - - } - - return returnValue; - } - - - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesDescriptor.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesDescriptor.java deleted file mode 100644 index db2b253ae2..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/RegularObsTimeSeriesDescriptor.java +++ /dev/null @@ -1,252 +0,0 @@ -package ohd.hseb.pdc_pp; - -import ohd.hseb.model.ParamCode; -import ohd.hseb.util.TimeHelper; - -public class RegularObsTimeSeriesDescriptor -{ - private String _lid; - private String _shefParamCodeString; - private ParamCode _paramCode; - private String _pe; - private short _dur; - private String _extremum; - private String _ts; - private long _endTime = 0; - private long _startTime = 0; - private String _outputString = null; - private String _identityString = null; - private int _hashCode = 0; - private boolean _missing = false; - - private boolean _identityChanged = true; // is used to determine whether to recalculate the tostring - - public RegularObsTimeSeriesDescriptor() {} - - public RegularObsTimeSeriesDescriptor( RegularObsTimeSeriesDescriptor descriptor ) - { - _lid = descriptor.getLid(); - _pe = descriptor.getPe(); - _dur = descriptor.getDur(); - _extremum = descriptor.getExtremum(); - _ts = descriptor.getTs(); - _endTime = descriptor.getEndTime(); - _startTime = descriptor.getStartTime(); - - _missing = descriptor._missing; - - - getIdentity(); - - // _identityChanged = descriptor.hasIdentityChanged(); - - // _outputString = descriptor.getOutputString(); - // _hashCode = descriptor._hashCode; - - - } - - - private void getIdentity() - { - if ( _identityChanged ) - { -// computeToString(); -// computeHashCode(); - - _outputString = "lid = " + _lid + - " pe = " + _pe + - " dur = " + _dur + - " extremum = " + _extremum + - " ts = " + _ts; - - _hashCode = _outputString.hashCode(); - - _shefParamCodeString = getPe() + ParamCode.getShefDurationCode(getDur()) + - getTs() + getExtremum(); - - _identityChanged = false; - } - } - - private void getIdentityString() - { - _identityString = _lid + "|" + _pe + "|" + _shefParamCodeString + "|" + _dur + "|" + _extremum + "|" + _ts; - } - - public String toString() - { - getIdentity(); - - return _outputString; - } - - public int hashCode() - { - getIdentity(); - - return _hashCode; - } - -/* - private void computeToString() - { - _outputString = "lid = " + _lid + - " pe = " + _pe + - " shef_param_code = " + _shef_param_code + - " dur = " + _dur + - " extremum = " + _extremum + - " ts = " + _ts; - } - - private void computeHashCode() - { - _hashCode = _outputString.hashCode(); - } - -*/ - public boolean equals( Object object ) - { - RegularObsTimeSeriesDescriptor descriptor = (RegularObsTimeSeriesDescriptor) object; - boolean returnValue = false; - - // if ( this.toString().equals( descriptor.toString() ) ) - if ( _hashCode == descriptor.hashCode()) - { - returnValue = true; - } - else - { - returnValue = false; - } - - return returnValue; - } - - - public String getLid() - { - return _lid; - } - - public String getPe() - { - return _pe; - } - - public short getDur() - { - return _dur; - } - - public String getTs() - { - return _ts; - } - - public String getExtremum() - { - return _extremum; - } - - public String getShef_param_code() - { - getIdentity(); - - return _shefParamCodeString; - } - - public void setLid( String lid ) - { - _lid = lid; - setIdentityChanged( true ); - } - - public void setPe( String pe ) - { - _pe = pe; - setIdentityChanged( true ); - } - - public void setShef_param_code( String shef_param_code ) - { - _shefParamCodeString = shef_param_code; - setIdentityChanged( true ); - } - - public void setDur( short dur ) - { - _dur = dur; - setIdentityChanged( true ); - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - setIdentityChanged( true ); - } - - public void setTs( String ts ) - { - _ts = ts; - setIdentityChanged( true ); - } - - public void setIdentityChanged( boolean valueChanged ) - { - _identityChanged = valueChanged; - } - - public boolean hasIdentityChanged() - { - return _identityChanged; - } - - public void setOutputString( String outputString ) - { - _outputString = outputString; - setIdentityChanged( true ); - } - - public String getOutputString() - { - return _outputString; - } - - public void setEndTime( long endTime ) - { - _endTime = TimeHelper.roundTimeInMillisToNearestHour( endTime ); - } - - public long getEndTime() - { - return _endTime; - } - - public void setStartTime( long startTime ) - { - _startTime = TimeHelper.roundTimeInMillisToNearestHour( startTime ); - } - - public long getStartTime() - { - return _startTime; - } - - /** - * @param missing The missing to set. - */ - public void setMissing(boolean missing) - { - _missing = missing; - } - - /** - * @return Returns the missing. - */ - public boolean isMissing() - { - return _missing; - } -} - diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeSeriesListMgr.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeSeriesListMgr.java deleted file mode 100644 index 032509b0ef..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeSeriesListMgr.java +++ /dev/null @@ -1,377 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -//import ohd.hseb.util.CodeTimer; - -public class TimeSeriesListMgr -{ - - final static String INITIAL_MATCH= "NO MATCH"; - final static String REGULAR_MATCH= "Fresh and Cached"; - final static String REGULAR_MATCH_PE_SWITCH= "Fresh and Cached WITH PE swap"; - final static String CACHE_ONLY = "Cache Only"; - final static String FRESH_ONLY = "Fresh Only"; - - - /**The purpose of this class is to group all the methods for handling the List of RegularObsTimeSeries - * It is intended to be called by the PDCPreprocessorDataManager */ -// ------------------------------------------------------------------------- - - public static void setNewStartTime(List timeSeriesList, long newStartTime) - { - - RegularObsTimeSeries timeSeries = null; - RegularObsTimeSeriesDescriptor descriptor = null; - - if (timeSeriesList == null) - { - return; - } - - for (int i = 0; i < timeSeriesList.size(); i++) - { - timeSeries = (RegularObsTimeSeries) timeSeriesList.get(i); - - descriptor = timeSeries.getDescriptor(); - descriptor.setStartTime(newStartTime); - - //consider combining this with the setting of the descriptor's starttime, since if they are - // not atomic, bugs could be introduced - timeSeries.removeTimeValuePairsBefore(newStartTime); - } - } - -// ------------------------------------------------------------------------- - - public static List mergeTimeSeriesLists(List freshTimeSeriesList, - List cachedTimeSeriesList, - long newStartTime, - long endTime) - - { - // CodeTimer addTimer = new CodeTimer(); - - String header = "TimeSeriesListMgr.mergeTimeSeriesLists() :"; - List mergedTimeSeriesList = new ArrayList(); - - RegularObsTimeSeries freshTs = null; - RegularObsTimeSeries cachedTs = null; - RegularObsTimeSeries mergedTs = null; - - RegularObsTimeSeriesDescriptor freshTsDesc = null; - - // System.out.println(header + "newStartTime = " + newStartTime); - - if ((freshTimeSeriesList != null) && (cachedTimeSeriesList != null)) - { - //build a map to be used for searching for the matching time series - Map cachedTimeSeriesMap = createTimeSeriesMap(cachedTimeSeriesList); - List unmatchedCachedTimeSeriesDescriptorList = createUnmatchedTimeSeriesDescriptorList(cachedTimeSeriesList); - - // for each time series in list 1, find the matching time series - for (int i = 0; i < freshTimeSeriesList.size(); i++) - { - - freshTs = (RegularObsTimeSeries) freshTimeSeriesList.get(i); - freshTsDesc = freshTs.getDescriptor(); - - // add in the cachedTs data - // mergedTs = copyTimeSeriesWithAdjustedStartTime(freshTs, newStartTime); - mergedTs = freshTs; - mergedTs.setStartTime(newStartTime); - mergedTs.setEndTime(endTime); - - mergedTs.setMergerString(INITIAL_MATCH); - - cachedTs = findMatchingTimeSeries(freshTs, cachedTimeSeriesMap); - - //removed this section, since I won't merge different PE's or TS's - /* - //make a second attempt at retrieving the cached data since the - // pe might have changed from PC to PP or vice versa. - if (cachedTs == null) - { - - String origPe = freshTs.getDescriptor().getPe(); - String newPe = null; - if (origPe.equals("PC")) - { - newPe = "PP"; - } - else if (origPe.equals("PP")) - { - newPe = "PC"; - } - - if (newPe != null) //if performed a swap - { - // System.out.println(header - // + "Swapping PEs for cache search for \nfreshTs Descriptor = " - // + " from " + origPe + " to " + newPe); - freshTs.getDescriptor().setPe(newPe); - cachedTs = findMatchingTimeSeries(freshTs, cachedTimeSeriesMap); - } - } - */ - - // if found matching cached data - if (cachedTs != null) //foundMatching TS - { - mergedTs.setMergerString(REGULAR_MATCH); - - //This cachedTs has been matched with a freshTs, so remove it from the unmatched list - unmatchedCachedTimeSeriesDescriptorList.remove(cachedTs.getDescriptor()); - - mergedTs.replaceNonMatchingTimeValuePairs(cachedTs); - } - else //cachedTs == null //did not find a match - { - - mergedTs.setMergerString(FRESH_ONLY); - - - System.out.println(header - + "ERROR - Could not find a match for the \nfreshTs Descriptor = " - + freshTsDesc); - - } - - // add the merged time series to the list - mergedTimeSeriesList.add(mergedTs); - - - } //end for each freshTimeSeriesList - - - // For each time series that was in the cachedTimeSeriesList, but not in the fresh data time series List, - // trim the times neatly and then let that be the merged list, since there - // really is no merger possible - - RegularObsTimeSeries unmatchedCachedTs = null; - RegularObsTimeSeriesDescriptor unmatchedCachedTsDesc = null; - - // System.out.println(header + "before unmatched ts loop"); - - int matchedIndex = -1; - int size = unmatchedCachedTimeSeriesDescriptorList.size(); - // System.out.println(header + " preparing to loop " + size + " times. "); - - for (int i = 0; i < size ; i++) - { - unmatchedCachedTsDesc = (RegularObsTimeSeriesDescriptor) - unmatchedCachedTimeSeriesDescriptorList.get(i); - unmatchedCachedTs = (RegularObsTimeSeries) cachedTimeSeriesMap.get(unmatchedCachedTsDesc); - - - if (unmatchedCachedTs != null) - { - unmatchedCachedTs.setStartTime(newStartTime); - unmatchedCachedTs.setEndTime(endTime); - unmatchedCachedTs.setMergerString(CACHE_ONLY); - - matchedIndex = addToOrderedMergedTimeSeriesList(unmatchedCachedTs, - mergedTimeSeriesList, - matchedIndex+1); - } - else - { - System.err.println(header + "ERROR unexpectedly null time series"); - } - - } // end for each unmatchedTimeSeries - - } //end if - - else //missing either time series - { - // there is no cached list to merge, so the freshTimeSeries List is expected to contain - // maxHours worth of data . Normally, it will contain less data. - //System.out.println(header + ""); - mergedTimeSeriesList = freshTimeSeriesList; - - } - - return mergedTimeSeriesList; - } - -// ------------------------------------------------------------------------- - private static int addToOrderedMergedTimeSeriesList(RegularObsTimeSeries timeSeries, - List mergedTimeSeriesList, - int startingIndex) - { - String header = "TimeSeriesListMgr.addToOrderedMergedTimeSeriesList(): "; - int matchingIndex = -1; - RegularObsTimeSeries curTs = null; - RegularObsTimeSeriesDescriptor curTsDesc = null; - - RegularObsTimeSeriesDescriptor tsDesc = timeSeries.getDescriptor(); - - boolean inserted = false; - - for (int i = startingIndex; i < mergedTimeSeriesList.size(); i++) - { - curTs = (RegularObsTimeSeries) mergedTimeSeriesList.get(i); - curTsDesc = curTs.getDescriptor(); - - int compareValue = tsDesc.toString().compareTo(curTsDesc.toString()); - - if (compareValue < 0) - { - mergedTimeSeriesList.add(i, timeSeries); - matchingIndex = i; - inserted = true; - break; - } - else if (compareValue == 0) - { - System.out.println(header + "ERROR, the compare value equals 0. Not expected. "); - break; - } - } - - if (! inserted) //either only item in list, or multiple items and it is last - { - mergedTimeSeriesList.add(timeSeries); - matchingIndex = mergedTimeSeriesList.size() - 1; - } - - return matchingIndex; - - } - -// ------------------------------------------------------------------------- - - - private static List createUnmatchedTimeSeriesDescriptorList(List regularObsTimeSeriesList) - { - List newList = new ArrayList(); - - for (int i = 0; (regularObsTimeSeriesList != null ) && i < regularObsTimeSeriesList.size(); i++) - { - RegularObsTimeSeries ts = (RegularObsTimeSeries) regularObsTimeSeriesList.get(i); - RegularObsTimeSeriesDescriptor desc = ts.getDescriptor(); - newList.add(desc); - } - - return newList; - } -// ------------------------------------------------------------------------- - - private static Map createTimeSeriesMap(List regularObsTimeSeriesList) - { - Map newMap = new HashMap(); - - for (int i = 0; (regularObsTimeSeriesList != null ) && i < regularObsTimeSeriesList.size(); i++) - { - RegularObsTimeSeries ts = (RegularObsTimeSeries) regularObsTimeSeriesList.get(i); - newMap.put(ts.getDescriptor(), ts); - } - - return newMap; - } -// ------------------------------------------------------------------------- - private static RegularObsTimeSeries findMatchingTimeSeries(RegularObsTimeSeries tsToFindMatchFor, Map timeSeriesMap) - { - RegularObsTimeSeries foundTs = null; - RegularObsTimeSeriesDescriptor descriptor = null; - RegularObsTimeSeriesDescriptor alteredDescriptorCopy = null; - boolean changedDuration = false; - short previousDuration = -1; - - if (timeSeriesMap != null) - { - descriptor = tsToFindMatchFor.getDescriptor(); - - Object key = null; - - if ( descriptor.getPe().equals("PC")) //need to change the duration to 0 - { - previousDuration = descriptor.getDur(); - changedDuration = true; - descriptor.setDur( (short) 0); - key = descriptor; - - // alteredDescriptorCopy = new RegularObsTimeSeriesDescriptor(descriptor); - // alteredDescriptorCopy.setDur((short)0); - // key = alteredDescriptorCopy; - } - else //everything is normal, no changes needed - { - key = descriptor; - } - - foundTs = (RegularObsTimeSeries) timeSeriesMap.get(key); - - if (changedDuration) - { - descriptor.setDur(previousDuration); - } - } - - return foundTs; - } - -// ------------------------------------------------------------------------- - - private static RegularObsTimeSeries copyTimeSeriesWithAdjustedStartTime(RegularObsTimeSeries origTs, - long newStartTime) - { - String header = "PDCPreprocessorDataMgr.copyTimeSeriesWithAdjustedStartTime(): "; - RegularObsTimeSeries newTs = null; - RegularObsTimeSeriesDescriptor newTsDesc = null; - RegularObsTimeSeriesDescriptor origTsDesc = null; - - origTsDesc = origTs.getDescriptor(); - - - newTs = new RegularObsTimeSeries(origTs); - - /* - if (origTsDesc.getLid().equals("KERO2") - && origTsDesc.getPe().equals("PC")) - { - System.out.println("***************************************"); - System.out.println(header + "after copying \n" - + "\n origTimeSeries = " + origTs + "\n newTimeSeries = " - + newTs); - } - */ - // adjust the start time of the mergedTs so that it goes back as far as - // we want it to - long endTime = origTsDesc.getEndTime(); - - - newTsDesc = newTs.getDescriptor(); - newTsDesc.setStartTime(newStartTime); - newTsDesc.setEndTime(endTime); - - /* - if (origTsDesc.getLid().equals("KERO2") - && origTsDesc.getPe().equals("PC")) - { - System.out.println(header + "after changing start and end times \n" - + "\n origTimeSeries = " + origTs + "\n newTimeSeries = " - + newTs); - - System.out.println(header + "\nold startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(origTsDesc.getStartTime()) + - "\nold EndTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(origTsDesc.getEndTime()) + - "\nnew startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(newStartTime) + - "\nnew endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - System.out.println("***************************************"); - - } -*/ - - return newTs; - } - -// ------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeSlotPolicy.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeSlotPolicy.java deleted file mode 100644 index 3b2a1b11cd..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeSlotPolicy.java +++ /dev/null @@ -1,12 +0,0 @@ -package ohd.hseb.pdc_pp; - -import java.util.Map; - -public interface TimeSlotPolicy -{ - - public Long getSlotDateTimeInMillis( long originalDateTimeInMillis ); - - public void insertTimeValuePairIfBetterMatch( Map timeValuePairHashMap, TimeValuePair timeValuePair ); - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeValuePair.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeValuePair.java deleted file mode 100644 index a7962da642..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/TimeValuePair.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.pdc_pp; - -import ohd.hseb.db.DbTimeHelper; - -public class TimeValuePair -{ - private long _dateTime = 0; - private double _value = 0.0; - private boolean _isMissing = true; - - public TimeValuePair( long dateTime, double value ) - { - _dateTime = dateTime; - _value = value; - _isMissing = false; - } - - public TimeValuePair( long dateTime ) - { - _dateTime = dateTime; - _isMissing = true; - } - - public TimeValuePair( TimeValuePair timeValuePair ) - { - this(timeValuePair.getDateTime(), timeValuePair.getValue() ); - // _dateTime = timeValuePair.getDateTime(); - // _value = timeValuePair.getValue(); - } - - public String toString() - { - String string = DbTimeHelper.getDateTimeStringFromLongTime( _dateTime ) + "," + _value; -// String string = _value + " "; - - return string; - } - - public boolean isMissingValue() - { - boolean returnValue = false; - - if ( _value == PDCPreprocessorDataMgr.MISSING ) - { - returnValue = true; - } - - return returnValue; - } - - public void setDateTime( long dateTime ) - { - _dateTime = dateTime; - } - - public long getDateTime() - { - return _dateTime; - } - - public void setValue( double value ) - { - _value = value; - } - - public double getValue() - { - return _value; - } -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/sample_data_set/CreateSampleDataSet.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/sample_data_set/CreateSampleDataSet.java deleted file mode 100644 index b3bd77edad..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/sample_data_set/CreateSampleDataSet.java +++ /dev/null @@ -1,84 +0,0 @@ -package ohd.hseb.pdc_pp.sample_data_set; - -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -public class CreateSampleDataSet -{ - private SampleDataSetCreatorDataMgr _dataMgr = null; - private boolean _createData = true; - - public CreateSampleDataSet() - { - - } - - /** - * initialize( String[] args ) - Used to process the command line arguments and set appropriate variables. - * @param args - Command line arguments - */ - private void initialize( String[] args ) - { - StringBuffer baseConnectionStringBuffer = new StringBuffer(); //gotten from the command line - StringBuffer logDirName = new StringBuffer(); - String logFileName = null; - Logger logger = null; - - processCommandLineArguments( baseConnectionStringBuffer, logDirName, args ); - - logFileName = logDirName + "/SampleDataSetCreator.log"; - - logger = new FileLogger(logFileName, true, true); - - _dataMgr = new SampleDataSetCreatorDataMgr(baseConnectionStringBuffer.toString(), logger ); - if ( _createData ) - { - _dataMgr.create_test_location(); - _dataMgr.create_test_data(); - } - else - { - _dataMgr.removeAllData(); - } - } - - /** - * - * @param baseConnectionStringBuffer - Postgres database connection string - * @param logDirName - Directory where the log file will be created - * @param args - Command line arguments - */ - private void processCommandLineArguments( StringBuffer baseConnectionStringBuffer, - StringBuffer logDirName, String[] args ) - { - if ( args.length < 2 ) - { - System.err.println("Usage: ohd.hseb.PDCPreprocessor.sample_data_set.CreateSampleDataSet connection_string logFileDir "); - System.exit(0); - } - - if ( args.length == 3 ) - { - if ( args[2].equalsIgnoreCase( "true" ) ) - { - _createData = true; - } - else - { - _createData = false; - } - } - - baseConnectionStringBuffer.append( args[0] ); - logDirName.append( args[1] ); - } - - public static void main( String[] args ) - { - CreateSampleDataSet dataCreator = new CreateSampleDataSet(); - - dataCreator.initialize( args ); - - - } -} diff --git a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/sample_data_set/SampleDataSetCreatorDataMgr.java b/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/sample_data_set/SampleDataSetCreatorDataMgr.java deleted file mode 100644 index 0aebdc8b10..0000000000 --- a/javaUtilities/hydro/ohd.pdc_pp/src/ohd/hseb/pdc_pp/sample_data_set/SampleDataSetCreatorDataMgr.java +++ /dev/null @@ -1,871 +0,0 @@ -package ohd.hseb.pdc_pp.sample_data_set; - -import java.sql.SQLException; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.CurPCRecord; -import ohd.hseb.ihfsdb.generated.CurPCTable; -import ohd.hseb.ihfsdb.generated.CurPPRecord; -import ohd.hseb.ihfsdb.generated.CurPPTable; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.LakeRecord; -import ohd.hseb.ihfsdb.generated.LakeTable; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.SnowRecord; -import ohd.hseb.ihfsdb.generated.SnowTable; -import ohd.hseb.ihfsdb.generated.StnClassRecord; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.ihfsdb.generated.TemperatureRecord; -import ohd.hseb.ihfsdb.generated.TemperatureTable; -import ohd.hseb.ihfsdb.generated.WeatherRecord; -import ohd.hseb.ihfsdb.generated.WeatherTable; -import ohd.hseb.ihfsdb.generated.WindRecord; -import ohd.hseb.ihfsdb.generated.WindTable; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -public class SampleDataSetCreatorDataMgr -{ - private Database _db = null; - private Logger _logger = null; - private static String OS = System.getProperty("os.name").toLowerCase(); - private String _connectionString = null; - private long _endTime = System.currentTimeMillis(); - private long _TOTHEndTime = TimeHelper.roundTimeInMillisToNearestHour( _endTime ); - private long _startTime = _TOTHEndTime - ( 24 * TimeHelper.MILLIS_PER_HOUR ); - private String _lid1 = "1PDC1"; - private String _lid2 = "1PDC2"; - - public SampleDataSetCreatorDataMgr( String baseConnectionString, Logger logger ) - { - super(); - - _db = new Database(); - _logger = logger; - - if ( baseConnectionString == null ) - { - baseConnectionString = getBaseConnectionString(); - } - _connectionString = baseConnectionString; - _db.connectWithDriverSearch( _connectionString ); - } - - public void create_test_location() - { - LocationRecord locationRecord1 = new LocationRecord(); - LocationRecord locationRecord2 = new LocationRecord(); - StnClassRecord stnClassRecord1 = new StnClassRecord(); - StnClassRecord stnClassRecord2 = new StnClassRecord(); - RiverstatRecord riverStatRecord1 = new RiverstatRecord(); - RiverstatRecord riverStatRecord2 = new RiverstatRecord(); - RatingRecord ratingRecord1 = new RatingRecord(); - RatingRecord ratingRecord2 = new RatingRecord(); - RatingTable ratingTable = new RatingTable( _db ); - LocationTable locationTable = new LocationTable( _db ); - StnClassTable stnClassTable = new StnClassTable( _db ); - RiverstatTable riverstatTable = new RiverstatTable( _db ); - List recordList = null; - - locationRecord1.setLid( _lid1 ); - locationRecord1.setCounty( "BRYAN" ); - locationRecord1.setDetail( "1 W" ); - locationRecord1.setElev( 503 ); - locationRecord1.setHsa( "OUN" ); - locationRecord1.setLat( 32.34343456 ); - locationRecord1.setLon( 97.232341123 ); - locationRecord1.setLremark( "US HWY 70 NR LT BANK ON DS SIDE OF BRIDGE OVER BLUE RIVER, 1 MI. W OF BLUE, OK AND 8 MI. E OF DURANT, OKDURANT/BRYAN COUNTY CEMA IS BACKUP OBSERVER TO DCP" ); - locationRecord1.setLrevise( System.currentTimeMillis() ); - locationRecord1.setName( "PDC Test Site 1" ); - locationRecord1.setNetwork( "B" ); - locationRecord1.setRb( "RED 3" ); - locationRecord1.setRfc( "ABRFC" ); - locationRecord1.setState( "OK" ); - locationRecord1.setWfo( "OUN" ); - locationRecord1.setTzone( "MST7" ); - stnClassRecord1.setLid( _lid1 ); - stnClassRecord1.setDisp_class( "RPTO" ); - stnClassRecord1.setDcp( "T" ); - stnClassRecord1.setObserver( "T" ); - stnClassRecord1.setTelem_type( "NONE" ); - riverStatRecord1.setLid( _lid1 ); - riverStatRecord1.setFq( 42000 ); - riverStatRecord1.setFs( 22 ); - ratingRecord1.setLid( _lid1 ); - - - locationRecord2.setLid( _lid2 ); - locationRecord2.setCounty( "BRYAN" ); - locationRecord2.setDetail( "1 W" ); - locationRecord2.setElev( 503 ); - locationRecord2.setHsa( "OUN" ); - locationRecord2.setLat( 30.34343456 ); - locationRecord2.setLon( 99.232341123 ); - locationRecord2.setLremark( "US HWY 70 NR LT BANK ON DS SIDE OF BRIDGE OVER BLUE RIVER, 1 MI. W OF BLUE, OK AND 8 MI. E OF DURANT, OKDURANT/BRYAN COUNTY CEMA IS BACKUP OBSERVER TO DCP" ); - locationRecord2.setLrevise( System.currentTimeMillis() ); - locationRecord2.setName( "PDC Test Site 2" ); - locationRecord2.setNetwork( "B" ); - locationRecord2.setRb( "RED 3" ); - locationRecord2.setRfc( "ABRFC" ); - locationRecord2.setState( "OK" ); - locationRecord2.setWfo( "OUN" ); - locationRecord2.setTzone( "MST7" ); - stnClassRecord2.setLid( _lid2 ); - stnClassRecord2.setDisp_class( "RPTO" ); - stnClassRecord2.setDcp( "T" ); - stnClassRecord2.setObserver( "T" ); - stnClassRecord2.setTelem_type( "NONE" ); - riverStatRecord2.setLid( _lid2 ); - riverStatRecord2.setFq( 5750 ); - riverStatRecord2.setFs( 25 ); - ratingRecord2.setLid( _lid2 ); - - - try - { - recordList = locationTable.select( "WHERE LID = '" + _lid1 + "' or LID = '" + _lid2 + "' " ); - - if ( recordList.size() == 0 ) - { - System.out.println( "Inserting Location/StnClass/Riverstat/Rating records for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - locationTable.insert( locationRecord1 ); - locationTable.insert( locationRecord2 ); - stnClassTable.insert( stnClassRecord1 ); - stnClassTable.insert( stnClassRecord2 ); - riverstatTable.insert( riverStatRecord1 ); - riverstatTable.insert( riverStatRecord2 ); - for ( double i = 0; i < 5.0; i+=0.1 ) - { - ratingRecord1.setStage( i ); - ratingRecord1.setDischarge( i*1.5 ); - ratingTable.insert( ratingRecord1 ); - } - - for ( double i = 0; i < 5.0; i+=0.2 ) - { - ratingRecord2.setStage( i ); - ratingRecord2.setDischarge( i*2.5 ); - ratingTable.insert( ratingRecord2 ); - } - } - else - { - System.out.println( "Test locations already exist in the Location/StnClass/Riverstat/Rating tables...\n" + - "Removing and reinserting Location/StnClass/Riverstat/Rating records for locations " + - "\"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - ratingTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - riverstatTable.delete( riverStatRecord1 ); - riverstatTable.delete( riverStatRecord2 ); - stnClassTable.delete( stnClassRecord1 ); - stnClassTable.delete( stnClassRecord2 ); - locationTable.delete( locationRecord1 ); - locationTable.delete( locationRecord2 ); - locationTable.insert( locationRecord1 ); - locationTable.insert( locationRecord2 ); - stnClassTable.insert( stnClassRecord1 ); - stnClassTable.insert( stnClassRecord2 ); - riverstatTable.insert( riverStatRecord1 ); - riverstatTable.insert( riverStatRecord2 ); - for ( double i = 0; i < 5.0; i+=0.1 ) - { - ratingRecord1.setStage( i ); - ratingRecord1.setDischarge( i*1.5 ); - ratingTable.insert( ratingRecord1 ); - } - - for ( double i = 0; i < 5.0; i+=0.2 ) - { - ratingRecord2.setStage( i ); - ratingRecord2.setDischarge( i*2.5 ); - ratingTable.insert( ratingRecord2 ); - } - } - } - catch (SQLException e ) - { - e.printStackTrace(); - } - } - - public void create_test_data() - { - deleteTestData(); - createHeightData(); - createTemperatureData(); - createWindData(); - createSnowData(); - createWeatherData(); - createLakeData(); - createDischargeData(); - createPCData(); - createPPData(); - } - - public void removeAllData() - { - RatingTable ratingTable = new RatingTable( _db ); - LocationTable locationTable = new LocationTable( _db ); - StnClassTable stnClassTable = new StnClassTable( _db ); - RiverstatTable riverstatTable = new RiverstatTable( _db ); - - System.out.println( "Deleting data from the Location/Riverstat/StnClass/Rating tables" ); - deleteTestData(); - try - { - ratingTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - stnClassTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - riverstatTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - locationTable.delete( "WHERE lid = '" + _lid1 + "' OR lid = '" + _lid2 + "'" ); - } - catch (SQLException e ) - { - e.printStackTrace(); - } - } - private void deleteTestData() - { - HeightTable heightTable = new HeightTable( _db ); - TemperatureTable tempTable = new TemperatureTable( _db ); - WindTable windTable = new WindTable( _db ); - SnowTable snowTable = new SnowTable( _db ); - WeatherTable weatherTable = new WeatherTable( _db ); - LakeTable lakeTable = new LakeTable( _db ); - DischargeTable dischargeTable = new DischargeTable( _db ); - CurPCTable curPCTable = new CurPCTable( _db ); - CurPPTable curPPTable = new CurPPTable( _db ); - System.out.println( "Clearing out old test data" ); - try - { - heightTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - tempTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - windTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - snowTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - weatherTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - lakeTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - dischargeTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - curPCTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - curPPTable.delete( "WHERE LID='" + _lid1 + "' OR LID='" + _lid2 + "'" ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - } - - private void createHeightData() - { - System.out.println( "Inserting test Height data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - HeightRecord record = new HeightRecord(); - HeightTable heightTable = new HeightTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "HG" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "HG" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - heightTable.insert( record ); - record.setPe( "HP" ); - record.setValue( value*1000 ); - heightTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "HG" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - heightTable.insert( record ); - record.setPe( "HP" ); - record.setValue( value*1000 ); - heightTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createTemperatureData() - { - System.out.println( "Inserting test Temperature data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - TemperatureRecord record = new TemperatureRecord(); - TemperatureTable temperatureTable = new TemperatureTable( _db ); - short dur = 1001; - short revision = 0; - double value = 50.0; - - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "TA" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = ( _startTime - 24 * TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setExtremum( "Z" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - temperatureTable.insert( record ); - if ( indexTime == _startTime ) - { - record.setExtremum( "N" ); - temperatureTable.insert( record ); - } - if ( indexTime == _TOTHEndTime ) - { - record.setExtremum( "X" ); - temperatureTable.insert( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 1; - } - - value = 2; - - record.setPe( "TD" ); - - for ( long indexTime = _startTime-(24*TimeHelper.MILLIS_PER_HOUR); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setValue( value ); - try - { - record.setObstime( indexTime ); - temperatureTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value++; - } - - record.setPe( "TA" ); - record.setLid( _lid2 ); - value = 60; - - for ( long indexTime = ( _startTime - 24 * TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setExtremum( "Z" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - temperatureTable.insert( record ); - if ( indexTime == _startTime ) - { - record.setExtremum( "N" ); - temperatureTable.insert( record ); - } - if ( indexTime == _TOTHEndTime ) - { - record.setExtremum( "X" ); - temperatureTable.insert( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 2; - } - - value = 2; - - record.setPe( "TD" ); - for ( long indexTime = _startTime-(24*TimeHelper.MILLIS_PER_HOUR); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setValue( value ); - record.setObstime( indexTime ); - try - { - temperatureTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 2; - } - - } - - private void createWindData() - { - System.out.println( "Inserting test Wind data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - WindRecord record = new WindRecord(); - WindTable windTable = new WindTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "US" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "US" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - record.setPe( "UD" ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "US" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - record.setPe( "UD" ); - try - { - windTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createSnowData() - { - System.out.println( "Inserting test Snow data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - SnowRecord record = new SnowRecord(); - SnowTable snowTable = new SnowTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "SW" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = ( _startTime - 24*TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - snowTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = ( _startTime - 24*TimeHelper.MILLIS_PER_HOUR ); indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - snowTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createWeatherData() - { - System.out.println( "Inserting test Weather data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - WeatherRecord record = new WeatherRecord(); - WeatherTable weatherTable = new WeatherTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "XR" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - weatherTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - weatherTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createLakeData() - { - System.out.println( "Inserting test Lake data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - LakeRecord record = new LakeRecord(); - LakeTable lakeTable = new LakeTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "LS" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - lakeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - lakeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createDischargeData() - { - System.out.println( "Inserting test Discharge data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - DischargeRecord record = new DischargeRecord(); - DischargeTable dischargeTable = new DischargeTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "QR" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "QR" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - dischargeTable.insert( record ); - record.setPe( "QT" ); - dischargeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setPe( "QR" ); - record.setObstime( indexTime ); - record.setValue( value ); - try - { - dischargeTable.insert( record ); - record.setPe( "QT" ); - dischargeTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createPCData() - { - System.out.println( "Inserting test PC data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - CurPCRecord record = new CurPCRecord(); - CurPCTable curPCTable = new CurPCTable( _db ); - short dur = 0; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "PC" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPCTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.1; - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPCTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - value += 0.2; - } - } - - private void createPPData() - { - System.out.println( "Inserting test PP data for locations \"" + _lid1 + "\" and \"" + _lid2 + "\" " ); - CurPPRecord record = new CurPPRecord(); - CurPPTable curPPTable = new CurPPTable( _db ); - short dur = 1001; - short revision = 0; - double value = 0.0; - record.setLid( _lid1 ); - record.setDur( dur ); - record.setPe( "PP" ); - record.setTs( "RG" ); - record.setExtremum( "Z" ); - record.setShef_qual_code( "Z" ); - record.setQuality_code( 1879048191 ); - record.setRevision( revision ); - record.setProduct_id( "KWOHRRSOUN" ); - record.setProducttime( _endTime ); - record.setPostingtime( _endTime ); - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPPTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - } - - record.setLid( _lid2 ); - value = 0.2; - - for ( long indexTime = _startTime; indexTime <= _TOTHEndTime; indexTime += TimeHelper.MILLIS_PER_HOUR ) - { - record.setObstime( indexTime ); - record.setValue( value ); - try - { - curPPTable.insert( record ); - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - } - } - - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - private void logException( Exception exception ) - { - _logger.log( "ERROR = " + - exception.getMessage() ); - exception.printStackTrace( _logger.getPrintWriter() ); - - _logger.log( "End of stack trace" ); - } - - private String getBaseConnectionString() - { - //this is used in testing mode, not the production mode - String connectionURLPart = "jdbc:postgresql://dx1-nhdr:5432/hd_ob7ounx?user=pguser"; - return connectionURLPart; - } -} diff --git a/javaUtilities/hydro/ohd.prism/.classpath b/javaUtilities/hydro/ohd.prism/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.prism/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.prism/.project b/javaUtilities/hydro/ohd.prism/.project deleted file mode 100644 index 1626a0aefe..0000000000 --- a/javaUtilities/hydro/ohd.prism/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.prism - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.prism/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.prism/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index a48b7c7e5b..0000000000 --- a/javaUtilities/hydro/ohd.prism/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:00:03 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.prism/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.prism/META-INF/MANIFEST.MF deleted file mode 100644 index 938d1c5271..0000000000 --- a/javaUtilities/hydro/ohd.prism/META-INF/MANIFEST.MF +++ /dev/null @@ -1,7 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Prism -Bundle-SymbolicName: ohd.prism -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.prism/build.properties b/javaUtilities/hydro/ohd.prism/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.prism/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.prism/build.xml b/javaUtilities/hydro/ohd.prism/build.xml deleted file mode 100644 index 9638b032fa..0000000000 --- a/javaUtilities/hydro/ohd.prism/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.prism/ohd.prism.ecl b/javaUtilities/hydro/ohd.prism/ohd.prism.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.prism/scripts/run_create_prism b/javaUtilities/hydro/ohd.prism/scripts/run_create_prism deleted file mode 100644 index 7c9650b1a0..0000000000 --- a/javaUtilities/hydro/ohd.prism/scripts/run_create_prism +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/ksh - -# run_create_prism -# -# Bryon Lawrence October 5, 2006 OHD -# -# Purpose: -# -# This is the run script for the MPEClimo PRISM generating program. It takes -# the national precipitation and temperature PRISM files available from Orgeon State -# University and crops them to a office's MPE forecast area. These cropped PRISM -# files are stored in XMRG format. They can be displayed in MPE Editor. -# -# This script requires three arguments: -# -# 1) Input Prism File Prefix -# 2) Output Prism File Suffix -# 3) Temperature/Precipitation PRISM flag. This may be either "t" or "p" -# -# The prism_input_dir token provides the path to the raw PRISM files. -# The prism_output_dir token provides the path to the cropped XMRG PRISM files. -# -# This routine expects there to be 13 raw PRISM files, one for each month and one -# for the entire year. This routine will create XMRG files corresponding to the -# raw PRISM files. -# -# This routine assumes that the input prism files have the suffix "_MM" where MM -# is the 2 digit month number. When generating the output PRISM files, this -# routine will append a "_MMM" to each month's XMRG PRISM filename. MMM is the -# lower case 3 character month abbreviation. -# -# For example, run_create_prism us_tmax prism_max_temp t -# -# Will look for the files -# -# us_tmax_01 us_tmax_04 us_tmax_07 us_tmax_10 us_tmax_14 -# us_tmax_02 us_tmax_05 us_tmax_08 us_tmax_11 -# us_tmax_03 us_tmax_06 us_tmax_09 us_tmax_12 -# -# in the input directort specified by the prism_input_dir token. -# -# It will generate the following files in the prism_output_dir token: -# -# prism_max_temp_jan prism_max_temp_apr prism_max_temp_jul prism_max_temp_oct -# prism_max_temp_feb prism_max_temp_may prism_max_temp_aug prism_max_temp_nov -# prism_max_temp_mar prism_max_temp_jun prism_max_temp_sep prism_max_temp_dec -# prism_max_temp_ann -# -# -# - -if [[ $# -ne 3 ]] -then - print "Usage: run_create_prism " - print " " - print " " - exit 1; -fi - -export SYS_JAVA_BIN_DIR=$SYS_JAVA_DIR/bin - -# Temporarily set here. -export CLASSPATH=${PPROC_BIN}/prism.jar - -# Temporarily set here. -export prism_input_dir=/fs/hseb/whfs/site_data/mpe_data/PRISM -#export prism_output_dir=/fs/hseb/whfs/cbrfc_historical/cbrfc/mpe_editor/local/data/app/MPE/PRISM - -# Start the MPEClimo program -$SYS_JAVA_BIN_DIR/java ohd.hseb.prism.MPEClimo $1 $2 $3 diff --git a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/Converter.java b/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/Converter.java deleted file mode 100644 index 5d58dc236a..0000000000 --- a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/Converter.java +++ /dev/null @@ -1,47 +0,0 @@ -package ohd.hseb.prism; - -// import ohd.hseb.prism.*; - -public class Converter implements MPEConstants -{ - static public class HrapPoint - { - private double hrap_row; - private double hrap_col; - - public double getHrapRow ( ) - { - return hrap_row; - } - - public double getHrapCol ( ) - { - return hrap_col; - } - } - - static public HrapPoint convertLatLonToHrap ( double longitude, - double latitude ) - { - double r; - HrapPoint hrap_point = new HrapPoint ( ); - - latitude *= D2RAD; - longitude = ( longitude + 180.0 - REF_LON ) * D2RAD; - r = RE * Math.cos (latitude)/(1.0 + Math.sin(latitude)); - hrap_point.hrap_col = r * Math.sin(longitude); - hrap_point.hrap_row = r * Math.cos(longitude); - hrap_point.hrap_col += HRAP_BASE_COL; - hrap_point.hrap_row += HRAP_BASE_ROW; - - return hrap_point; - } - - static public void main ( String args [ ] ) - { - HrapPoint hrap = convertLatLonToHrap ( 100.63, 33.48 ); - - System.out.println ( "Row: " + hrap.hrap_row ); - System.out.println ( "Col: " + hrap.hrap_col ); - } -} diff --git a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/GeoData.java b/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/GeoData.java deleted file mode 100644 index 8c4ccd9621..0000000000 --- a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/GeoData.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Created on August 25, 2005 - * - */ - -/** - * @author Bryon Lawrence - * - * This retrieves the contents of the coord_xxxx.dat file. - * For a RFC, xxxx is the name of the office. For a WFO, - * xxxx is 'host'. - */ -package ohd.hseb.prism; - -import java.io.*; -import ohd.hseb.util.*; - -public class GeoData { - - static private String _filepath; - private int _southwest_column = -1; - private int _southwest_row = -1; - private int _number_of_columns = -1; - private int _number_of_rows = -1; - - // Static initializer - static - { - build_filepath ( ); - } - - static private void build_filepath ( ) - { - String office_name = ""; - String geo_data_dir = ""; - AppsDefaults apps_defaults = new AppsDefaults ( ); - - office_name = apps_defaults.getToken ( "st3_rfc" ); - geo_data_dir = apps_defaults.getToken ( "geo_data" ); - - _filepath = geo_data_dir + "/" + office_name +"/ascii/coord_" + - office_name + ".dat"; - } - - private void read_geo_data ( ) throws IOException - { - BufferedReader _reader = new BufferedReader ( - new FileReader ( _filepath ) ); - _southwest_column = Integer.parseInt( _reader.readLine ( ) ); - _southwest_row = Integer.parseInt ( _reader.readLine ( ) ); - _number_of_columns = Integer.parseInt ( _reader.readLine ( ) ); - _number_of_rows = Integer.parseInt ( _reader.readLine ( ) ); - - } - - public int getSouthwestColumn ( ) - { - return _southwest_column; - } - - public int getSouthwestRow ( ) - { - return _southwest_row; - } - - public int getNumColumns ( ) - { - return _number_of_columns; - } - - public int getNumRows ( ) - { - return _number_of_rows; - } - - static public String getFilePath ( ) - { - return _filepath; - } - - GeoData ( ) throws IOException - { - read_geo_data ( ); - } -} diff --git a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/MPEClimo.java b/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/MPEClimo.java deleted file mode 100644 index 312cdf4b64..0000000000 --- a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/MPEClimo.java +++ /dev/null @@ -1,578 +0,0 @@ -package ohd.hseb.prism; - -import java.io.*; -import ohd.hseb.util.*; - -/** - * @author Bryon Lawrence - * March 8, 2006 - * - * This program crops a national PRISM file to the size of an office's MPE area. - * It stores this cropped PRISM product as an XMRG file which can be read and - * displayed by MPE Editor. This program replaces the create_prism program. - * - * The arguments to this program are: - * - * "prefix_of_input_prism_file" "prefix_of_output_prism_file" - * - * The input prism files are assumed to have a suffix of _MM where MM is the - * two digit month number. - * - * 01 January - * 02 February - * 03 March - * 04 April - * 05 May - * 06 June - * 07 July - * 08 August - * 09 September - * 10 October - * 11 November - * 12 December - * - * A suffix of _MMM is placed on each output XMRG PRISM file. The MMM is the 3 - * character month abbreviation: - * - * jan January - * feb February - * mar March - * apr April - * may May - * jun June - * jul July - * aug August - * sep September - * oct October - * nov November - * dec December - * - * An optional third argument indicates whether a precipitation or temperature - * prism file is being. "p" indicates a precipitation file. "t" indicates a - * temperature file. If this argument is omitted, then a precipitation file is - * assumed. - * - * The tokens input_prism_dir and output_prism_dir define the directories - * of the input PRISM files and the output cropped XMRG files. If these are not - * set, then this program will look for the prism files in the current working - * directory. - * - * This program expects there to be 13 raw prism files in the directory specified by - * input_prism_dir. These include 12 monthly files and 1 annual prism file. - * This program will produce 13 XMRG files corresponding to the 13 input files. - * - * Example of usage: - * - * export prism_input_dir=/fs/hseb/whfs/site_data/mpe_data/PRISM - * export prism_output_dir=/awips/hydroapps/precip_proc/local/data/app/mpe/prism - * - * java MPEClimo us_tmin prism_min_temp_ounx t - * - * This will look for raw prism files in the /fs/hseb/whfs/site_data/mpe_data/PRISM - * directory for the following files: - * - * us_tmin_01 us_tmin_04 us_tmin_07 us_tmin_10 us_tmin_14 - * us_tmin_02 us_tmin_05 us_tmin_08 us_tmin_11 - * us_tmin_03 us_tmin_06 us_tmin_09 us_tmin_12 - * - * It will create the following output files in the - * /awips/hydroapps/precip_proc/local/data/app/mpe/PRISM directory: - * - * prism_min_temp_ounx_jan prism_min_temp_ounx_aug - * prism_min_temp_ounx_feb prism_min_temp_ounx_sep - * prism_min_temp_ounx_mar prism_min_temp_ounx_oct - * prism_min_temp_ounx_apr prism_min_temp_ounx_nov - * prism_min_temp_ounx_may prism_min_temp_ounx_dec - * prism_min_temp_ounx_jun prism_min_temp_ounx_ann - * prism_min_temp_ounx_jul - * - * The "t" argument specifies this is by default - */ - -public class MPEClimo implements MPEConstants -{ - - static private boolean temperature_prism_flag = false; - static private double scale_factor = 1.0; - - static public double[][] cropPrismToHrapGrid ( Prism prism, - int southwest_column, - int southwest_row, - int number_columns, - int number_rows ) - { - double latitude_upper_left; - double col_longitude; - double row_latitude ; - double cellsize = prism.getCellSize ( ); - double latitude_lower_left = prism.getSouthWestLat ( ); - double longitude_lower_left = prism.getSouthWestLong ( ); - double precip[][] = new double [ number_columns ] [ number_rows ]; - Converter.HrapPoint hrap_point; - int count [][] = new int [ number_columns ] [ number_rows ]; - int hrap_row; - int hrap_col; - int num_prism_cols = prism.getNumColumns ( ); - int num_prism_rows = prism.getNumRows ( ); - int prism_data [ ][ ] = prism.getPrism ( ); - int prism_nodata = prism.getNoDataVal ( ); - - // Initialize the count and precipitation arrays to 0. - for ( int col = 0; col < number_columns; ++ col ) - { - for ( int row =0; row < number_rows; ++ row ) - { - count [ col ] [ row ] = 0; - precip [ col ] [ row ] = 0.0; - } - } - - // Get the latitude of the upperleft corner. - latitude_upper_left = latitude_lower_left + cellsize * num_prism_rows; - - // Process data row by row. - for ( int row = 0; row < num_prism_rows; ++row ) - { - row_latitude = latitude_upper_left - ( ( row - 0.5 ) * cellsize ); - - for ( int col = 0; col < num_prism_cols; ++col ) - { - if ( prism_data [ row ][ col ] != prism_nodata ) - { - col_longitude = longitude_lower_left + - ( ( col - 0.5 ) * cellsize ); - col_longitude = - col_longitude; - - hrap_point = Converter.convertLatLonToHrap ( col_longitude, - row_latitude ); - hrap_row = (int)hrap_point.getHrapRow ( ); - hrap_col = (int)hrap_point.getHrapCol ( ); - - hrap_row -= southwest_row; - hrap_col -= southwest_column; - - if ( ( hrap_row >= 0 ) && - ( hrap_row < number_rows ) && - ( hrap_col >= 0 ) && - ( hrap_col < number_columns ) ) - { - count [ hrap_col ] [ hrap_row ] ++; - precip [ hrap_col ][ hrap_row ] += prism_data [ row ] [ col ]; - } - } - } - } - - /* Compute the average. */ - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - if ( count [ col ][ row ] == 0 ) - { - precip [ col ] [ row ] = MISSING; - } - else - { - precip [ col ] [ row ] = precip [ col ] [ row ]/ - count [ col ] [ row ]; - } - } - } - - // Fill in any holes in the data. - double sum; - int col_begin = 0; - int col_end = 0; - int num = 0; - int row_begin = 0; - int row_end = 0; - - for ( int row = 0; row < number_rows; ++ row ) - { - row_begin = row - 1 ; - - if ( row_begin < 0 ) row_begin = 0; - - row_end = row + 1; - - if ( row_end == number_rows ) row_end = row; - - for ( int col = 0; col < number_columns; ++ col ) - { - if ( count [ col ] [ row ] == 0 ) - { - col_begin = col - 1; - if ( col_begin < 0 ) col_begin = 0; - - col_end = col + 1; - - if ( col_end == number_columns ) col_end = col; - - num = 0; - sum = 0.0; - - for ( int row_fill = row_begin; row_fill <= row_end; - ++row_fill ) - { - for ( int col_fill = col_begin; col_fill <= col_end; - ++ col_fill ) - { - if ( count [ col_fill ] [ row_fill ] > 0 ) - { - ++num; - sum += precip [ col_fill ] [ row_fill ]; - } - } - } - - if ( num == 0 ) - { - precip [ col ] [ row ] = MISSING; - } - else - { - precip [ col ] [ row ] = sum / num; - } - } - } - - } - - return precip; - } - - static void appendPrismToHrapGrid ( Prism prism, - int southwest_column, - int southwest_row, - int number_columns, - int number_rows, - double precip[][]) - { - double latitude_upper_left; - double col_longitude; - double row_latitude ; - double cellsize = prism.getCellSize ( ); - double latitude_lower_left = prism.getSouthWestLat ( ); - double longitude_lower_left = prism.getSouthWestLong ( ); - Converter.HrapPoint hrap_point; - int count [][] = new int [ number_columns ] [ number_rows ]; - int hrap_row; - int hrap_col; - int num_prism_cols = prism.getNumColumns ( ); - int num_prism_rows = prism.getNumRows ( ); - int prism_data [ ][ ] = prism.getPrism ( ); - int prism_nodata = prism.getNoDataVal ( ); - -// Initialize the count array to 0. - for ( int col = 0; col < number_columns; ++ col ) - { - for ( int row =0; row < number_rows; ++ row ) - { - count [ col ] [ row ] = 0; - } - } - -// Get the latitude of the upperleft corner. - latitude_upper_left = latitude_lower_left + cellsize * num_prism_rows; - -// Process data row by row. - for ( int row = 0; row < num_prism_rows; ++row ) - { - row_latitude = latitude_upper_left - ( ( row - 0.5 ) * cellsize ); - - for ( int col = 0; col < num_prism_cols; ++col ) - { - if ( prism_data [ row ][ col ] != prism_nodata ) - { - col_longitude = longitude_lower_left + - ( ( col - 0.5 ) * cellsize ); - col_longitude = - col_longitude; - - hrap_point = Converter.convertLatLonToHrap ( col_longitude, - row_latitude ); - hrap_row = (int)hrap_point.getHrapRow ( ); - hrap_col = (int)hrap_point.getHrapCol ( ); - - hrap_row -= southwest_row; - hrap_col -= southwest_column; - - if ( ( precip [hrap_col][hrap_row] == MISSING) && - ( hrap_row >= 0 ) && - ( hrap_row < number_rows ) && - ( hrap_col >= 0 ) && - ( hrap_col < number_columns ) ) - { - count [ hrap_col ] [ hrap_row ] ++; - precip [ hrap_col ][ hrap_row ] += prism_data [ row ] [ col ]; - } - } - } - } - - /* Compute the average. */ - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - if ( count [ col ][ row ] > 0 ) - { - precip [ col ] [ row ] = precip [ col ] [ row ]/ - count [ col ] [ row ]; - } - } - } - -// Fill in any holes in the data. - double sum; - int col_begin = 0; - int col_end = 0; - int num = 0; - int row_begin = 0; - int row_end = 0; - - for ( int row = 0; row < number_rows; ++ row ) - { - row_begin = row - 1 ; - - if ( row_begin < 0 ) row_begin = 0; - - row_end = row + 1; - - if ( row_end == number_rows ) row_end = row; - - for ( int col = 0; col < number_columns; ++ col ) - { - if ( count [ col ] [ row ] == 0 ) - { - col_begin = col - 1; - if ( col_begin < 0 ) col_begin = 0; - - col_end = col + 1; - - if ( col_end == number_columns ) col_end = col; - - num = 0; - sum = 0.0; - - for ( int row_fill = row_begin; row_fill <= row_end; - ++row_fill ) - { - for ( int col_fill = col_begin; col_fill <= col_end; - ++ col_fill ) - { - if ( count [ col_fill ] [ row_fill ] > 0 ) - { - ++num; - sum += precip [ col_fill ] [ row_fill ]; - } - } - } - - if ( num > 0 ) - { - precip [ col ] [ row ] = sum / num; - } - } - } - - } - - } - - static void convertPrismData ( int number_columns, - int number_rows, - double precip[][] ) - { - // If processing temperature data, convert them from Celcius to - // Fahrenheit. - if ( temperature_prism_flag ) - { - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - if ( precip [ col ] [ row ] != MISSING ) - { - precip [ col ] [ row ] /= 100.0 ; - -// Convert from Celcius to Fahrenheit - precip [col][row] = ( precip [col][row] * 1.8 ) + 32; - } - else - { - precip [ col ] [ row ] = MISSING_SAVE; - } - } - } - } - else - { - for ( int row = 0; row < number_rows; ++ row ) - { - for ( int col = 0; col < number_columns; ++ col ) - { - if ( precip [ col ] [ row ] != MISSING ) - { - precip [ col ] [ row ] /= 100.0 ; - } - else - { - precip [ col ] [ row ] = MISSING_SAVE; - } - - } - } - } - } - - /* - * The Main Routine for MPE Climo. - */ - static public void main ( String args [ ] ) - { - double precip [ ][ ]; - GeoData geo_data; - final String month_array [ ] = new String [ ] { "01", "02", "03", "04", - "05", "06", "07", "08", "09", "10", - "11", "12", "14" }; - final String month_name_array [ ] = new String [ ] {"jan", "feb", "mar", - "apr", "may", "jun", - "jul", "aug", "sep", - "oct", "nov", "dec", - "ann" }; - int southwest_column; - int southwest_row; - int number_columns; - int number_rows; - - Prism prism; - String prism_output_path = Prism.getOutputFilePath ( ); - String file; - - // The user must supply the prefix of the national prism file(s). The - // national prism file(s) is assumed to end with the month number. For example - // 01 like us_tmin_01 - // The user must also supply the file name prefix of the cropped, output - // Prism file. The user must also supply a single character flag indicating - // whether the file contains temperature ('T') or precipitation ('P') data. - - // The number of args must be at least 3. Any higher number indicates that the user - // has supplied multiple PRISM input files which will be mosaicked to provide - // information for the office's MPE area. - if (args.length < MINIMUM_COMMAND_LINE_ARGS ) - { - System.out.println( "Must provide the prefix of the input prism file(s)"); - System.out.println( "and the cropped, output prism file."); - System.out.print ( "Usage: MPEclimo input_prism_file_prefix [input_prism_file_prefix2 ...] "); - System.out.println ("output_prism_file_prefix "); - System.exit(1); - } - - int numInputFiles = (args.length - MINIMUM_COMMAND_LINE_ARGS) + 1; - - // The user must supply a flag indicating whether temperature or - // precipitation PRISM xmrg files are to be created. - - if ( args [ args.length - 1 ].charAt(0) == 't' || args [ args.length - 1 ].charAt(0) == 'T') - { - temperature_prism_flag = true; - - // The scale factor for precipitation data is 1.0. - // The scale factor for temperature data is 10.0. - scale_factor = 10.0; - } - - // Read the coordinates of the MPE forecast area the - // PRISM data will be cropped to. - try - { - geo_data = new GeoData ( ); - southwest_column = geo_data.getSouthwestColumn ( ); - southwest_row = geo_data.getSouthwestRow ( ); - number_columns = geo_data.getNumColumns ( ); - number_rows = geo_data.getNumRows ( ); - - System.out.println ( "South West Column: " + southwest_column ); - System.out.println ( "South West Row: " + southwest_row ); - System.out.println ( "Number of Columns: " + number_columns ); - System.out.println ( "Number of Rows: " + number_rows ); - - prism = new Prism ( ); - - /* Start a timer. This will show how much time is spent - * reading the prism data. - */ - CodeTimer totalTime = new CodeTimer (); - totalTime.start(); - - for ( int month = 0; month < month_array.length; ++ month ) - { - - // Construct the input PRISM file name - file = args[0]+ "_" + month_array [ month ]; - prism.readPrism (file); - System.out.println ( "Processing file: " + Prism.getInputFilePath () - + "/" + file ); - System.out.println ( prism ); - - // Crop the PRISM data to the forecast area. - precip = cropPrismToHrapGrid ( prism, southwest_column, - southwest_row, - number_columns, - number_rows ); - - // Merge the PRISM data for any other source files - // into the precip array. - - for ( int i = 1; i < numInputFiles; ++i ) - { - //Construct the input PRISM file name - file = args[i]+ "_" + month_array [ month ]; - prism.readPrism (file); - System.out.println ( "Processing file: " + Prism.getInputFilePath () - + "/" + file ); - System.out.println ( prism ); - appendPrismToHrapGrid ( prism, - southwest_column, - southwest_row, - number_columns, - number_rows, - precip ); - } - - convertPrismData ( number_columns, - number_rows, - precip ); - - // Write the prism data to an XMRG file. - file = prism_output_path + "/" + args[args.length-2] + "_"+ month_name_array [ month ]; - System.out.println( "Writing PRISM data to " + file ); - - XMRG.writeXMRG ( file, - "lawrence", - "HP", - "PRISM", - "xxxxxx", - "xxxxxx", - precip, - scale_factor, - southwest_column, - southwest_row, - number_columns, - number_rows, - 9998, - 1, - false ); - } - - totalTime.stop("Total read time for Scanner "); - System.exit ( 0 ); - } - catch ( IOException e ) - { - System.out.println ( e.toString ( ) ); - System.exit ( 1 ); - } - } -} diff --git a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/MPEConstants.java b/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/MPEConstants.java deleted file mode 100644 index f9e6a083c0..0000000000 --- a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/MPEConstants.java +++ /dev/null @@ -1,18 +0,0 @@ -package ohd.hseb.prism; - -public interface MPEConstants -{ - double PI=3.141592654; - double D2RAD=PI/180.0; - double EARTHR=6371.2; - double REF_LAT=60.0; - double REF_LON=105.0; - double RMESH=4.7625; - double TLAT=REF_LAT*D2RAD; - double RE=(EARTHR * ( 1.0 + Math.sin(TLAT)))/RMESH; - double HRAP_BASE_COL=401.0; - double HRAP_BASE_ROW=1601.0; - double MISSING=-9999.0; - double MISSING_SAVE=-999.0; - int MINIMUM_COMMAND_LINE_ARGS=3; -} diff --git a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/Prism.java b/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/Prism.java deleted file mode 100644 index c3d77855b4..0000000000 --- a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/Prism.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Created on August 25, 2005 - */ - -/** - * @ author Bryon Lawrence - * - * This is the Java version of the create_prism - * program. - */ -package ohd.hseb.prism; - -import java.io.*; -import java.util.*; -import ohd.hseb.util.*; - -public class Prism -{ - static private String _prism_input_path; - static private String _prism_output_path; - - private double _cellsize; - private double _latitude_southwest_corner; - private double _longitude_southwest_corner; - private int _nodata_value; - private int _num_rows; - private int _num_cols; - private int[][] _prism_data; - - // Static initializer for prism input path and - // prism output path. - static - { - AppsDefaults apps_defaults = new AppsDefaults ( ); - _prism_input_path = apps_defaults.getToken ( "prism_input_dir" ); - _prism_output_path = apps_defaults.getToken ( "prism_output_dir" ); - } - - public void readPrism ( String prism_filename ) throws IOException - { - - String prism_filepath; - String token; - - // Build the input filepath. - prism_filepath = _prism_input_path + "/" + prism_filename; - FileInputStream fileInputStream = new FileInputStream(prism_filepath); - BufferedInputStream bufferedInputStream = new BufferedInputStream ( fileInputStream); - - Scanner scanner = new Scanner ( bufferedInputStream ); - - //Do we need to read the string? - token = scanner.next(); - _num_cols = scanner.nextInt ( ); - - token = scanner.next(); - _num_rows = scanner.nextInt ( ); - - token = scanner.next(); - _longitude_southwest_corner = scanner.nextDouble(); - - token = scanner.next(); - _latitude_southwest_corner = scanner.nextDouble(); - - token = scanner.next(); - _cellsize = scanner.nextDouble(); - - token = scanner.next(); - _nodata_value = scanner.nextInt(); - - _prism_data = new int [ _num_rows ] [ _num_cols ]; - - CodeTimer outerTimer = new CodeTimer ( ); - CodeTimer innerTimer = new CodeTimer ( ); - outerTimer.start(); - - for ( int row = 0; row < _num_rows; ++row ) - { - for ( int col = 0; col < _num_cols; ++col ) - { - innerTimer.restart(); - _prism_data [ row ] [ col ] = scanner.nextInt (); - innerTimer.stop(); - } - - } - - outerTimer.stop( "The nested for loops took "); - - System.out.println( "Parse Token Elapsed Time = " + innerTimer.getElapsedTime()); - scanner.close(); - - } - - /* This method is not used. It represents a faster way of reading - * and Processing PRISM data. But the code is trickier. Code readability - * has been chosen over performance. - */ - public void readPrismOld ( String prism_filename ) throws IOException - { - String line; - String prism_filepath; - String token; - StringTokenizer token_string; - - // Build the input filepath. - prism_filepath = _prism_input_path + "/" + prism_filename; - - FileInputStream fileInputStream = new FileInputStream(prism_filepath); - InputStreamReader inputStreamReader = new InputStreamReader (fileInputStream); - BufferedReader reader = new BufferedReader(inputStreamReader); - - //DataInputStream reader = new DataInputStream (new BufferedReader ( - // new FileReader ( _prism_filepath ) )); - - - // Read the number of columns - line = reader.readLine ( ); - - token_string = new StringTokenizer ( line ); - token = token_string.nextToken( ); - token = token_string.nextToken( ); - - //Do we need to read the string? - _num_cols = Integer.parseInt ( token ); - - // Read the number of rows - line = reader.readLine ( ); - token_string = new StringTokenizer ( line ); - token = token_string.nextToken ( ); - token = token_string.nextToken( ); - _num_rows = Integer.parseInt ( token ); - - // Read the longitude of the lowerleft corner - line = reader.readLine ( ); - token_string = new StringTokenizer ( line ); - token = token_string.nextToken ( ); - token = token_string.nextToken ( ); - _longitude_southwest_corner = Double.parseDouble ( token ); - - // Read the latitude of the lowerleft corner - line = reader.readLine ( ); - token_string = new StringTokenizer ( line ); - token = token_string.nextToken ( ); - token = token_string.nextToken ( ); - _latitude_southwest_corner = Double.parseDouble (token); - - // Read the cell size - line = reader.readLine ( ); - token_string = new StringTokenizer ( line ); - token = token_string.nextToken ( ); - token = token_string.nextToken ( ); - _cellsize = Double.parseDouble (token); - - // Read the nodata value. - line = reader.readLine ( ); - token_string = new StringTokenizer ( line ); - token = token_string.nextToken ( ); - token = token_string.nextToken ( ); - _nodata_value = Integer.parseInt (token); - - _prism_data = new int [ _num_rows ] [ _num_cols ]; - - CodeTimer outerTimer = new CodeTimer ( ); - CodeTimer innerTimer = new CodeTimer ( ); - outerTimer.start(); - - for ( int row = 0; row < _num_rows; ++row ) - { - line = reader.readLine ( ); - token_string = new StringTokenizer ( line ); - - for ( int col = 0; col < _num_cols; ++col ) - { - innerTimer.restart(); - token = token_string.nextToken ( ); - _prism_data [ row ][ col ] = Integer.parseInt(token); - innerTimer.stop(); - } - } - - outerTimer.stop( "The nested for loops took "); - - System.out.println( "Parse Token Elapsed Time = " + innerTimer.getElapsedTime()); - reader.close(); - - } - - public int getNumColumns ( ) - { - return _num_cols; - } - - public int getNumRows ( ) - { - return _num_rows; - } - - public double getSouthWestLong ( ) - { - return _longitude_southwest_corner; - } - - public double getSouthWestLat ( ) - { - return _latitude_southwest_corner; - } - - public double getCellSize ( ) - { - return _cellsize; - } - - public int getNoDataVal ( ) - { - return _nodata_value; - } - - public int[][] getPrism ( ) - { - return _prism_data; - } - - public String toString ( ) - { - return new String ( "num_rows: " + _num_rows + " num_cols: " + - _num_cols + " southwest longitude: " + - _longitude_southwest_corner + - " southwest latitude: " + - _latitude_southwest_corner ); - } - - static public String getInputFilePath ( ) - { - return _prism_input_path; - } - - static public String getOutputFilePath ( ) - { - return _prism_output_path; - } -} diff --git a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/XMRG.java b/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/XMRG.java deleted file mode 100644 index b6d5b42fdb..0000000000 --- a/javaUtilities/hydro/ohd.prism/src/ohd/hseb/prism/XMRG.java +++ /dev/null @@ -1,114 +0,0 @@ -package ohd.hseb.prism; - -import java.io.*; - - -public class XMRG -{ - static public void writeXMRG ( String filePath, - String user, - String OS, - String process, - String datetimes, - String datetimev, - double [ ] [ ] data_matrix, - double conversion_factor, - int southwest_column, - int southwest_row, - int number_columns, - int number_rows, - int maxval, - int version_number, - boolean replace_missing ) throws IOException - { - byte [ ] byte_array; - byte [ ] boperuser = new byte [ 10 ]; - byte [ ] bdatev = new byte [ 20 ]; - byte [ ] bdates = new byte [ 20 ]; - byte [ ] bproc_flag = new byte [ 8 ]; - - DataOutputStream file; - int record_length; - short mosaic [][] = new short [ number_columns ] [ number_rows ]; - - // This method writes XMRG files. - String operuser = OS + user; - byte_array = operuser.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - boperuser [ i ] = byte_array [ i ]; - } - - byte_array = process.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - bproc_flag [ i ] = byte_array [ i ]; - } - - byte_array = datetimes.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - bdates [ i ] = byte_array [ i ]; - } - - byte_array = datetimev.getBytes ( ); - - for ( int i = 0; i < byte_array.length; ++i ) - { - bdatev [ i ] = byte_array [ i ]; - } - - - for ( int col = 0; col < number_columns; ++ col ) - { - for ( int row = 0; row < number_rows; ++ row ) - { - mosaic [ col ][ row ] = ( short ) ( data_matrix [ col ] [ row ] * - conversion_factor ); - } - } - - - // Open the output file. - // Write the xmrg header information. - file = new DataOutputStream ( new FileOutputStream ( - new File ( filePath ) ) ); - - // Write the first record of the header. - file.writeInt ( 16 ); - file.writeInt ( southwest_column ); - file.writeInt ( southwest_row ); - file.writeInt ( number_columns ); - file.writeInt ( number_rows ); - file.writeInt ( 16 ); - - // Write the second record of the header. - file.writeInt ( 66 ); - file.write ( boperuser, 0, boperuser.length ); - file.write ( bdates, 0, bdates.length ); - file.write ( bproc_flag, 0, bproc_flag.length ); - file.write ( bdatev, 0, bdatev.length ); - file.writeInt ( maxval ); - file.writeInt ( version_number ); - file.writeInt ( 66 ); - - // Compute the data record length in bytes. - record_length = number_columns * 2; - - // Write the data records. - for ( int row = 0; row < number_rows; ++ row ) - { - file.writeInt ( record_length ); - - for ( int col = 0; col < number_columns; ++ col ) - { - file.writeShort ( mosaic [ col ] [ row ] ); - } - - file.writeInt ( record_length ); - } - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/.classpath b/javaUtilities/hydro/ohd.rax_apps/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.rax_apps/.project b/javaUtilities/hydro/ohd.rax_apps/.project deleted file mode 100644 index e0ab7cb3ed..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.rax_apps - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.rax_apps/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.rax_apps/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 599f6f7895..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:22:16 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.rax_apps/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.rax_apps/META-INF/MANIFEST.MF deleted file mode 100644 index 6fc033a5ac..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Rax_apps -Bundle-SymbolicName: ohd.rax_apps -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.rax_apps/build.properties b/javaUtilities/hydro/ohd.rax_apps/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.rax_apps/build.xml b/javaUtilities/hydro/ohd.rax_apps/build.xml deleted file mode 100644 index 06b9c3e100..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/ohd.rax_apps.ecl b/javaUtilities/hydro/ohd.rax_apps/ohd.rax_apps.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.rax_apps/scripts/run_raxdb_sync b/javaUtilities/hydro/ohd.rax_apps/scripts/run_raxdb_sync deleted file mode 100644 index 504694ebd1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/scripts/run_raxdb_sync +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/ksh -# file name: run_IHFS_RAX_Sync_batch -# Created: 05/24/2007 -# Edited : 08/03/2007 - Added unix remove command to delete log files -# Edited : 09/06/2007 - Removed delete log file logic -# Edited : 10/24/2007 - Renamed jar from raxdb_sync.jar to rax_apps.jar - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for RAX applications -. /rfc_arc/lib/rax.profile - -# need to add a path to the jar file for this application -export CLASSPATH=$DB_DRIVER_PATH:$RUN_FROM_DIR/rax_apps.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -# run application using java -$JBINDIR/java ohd.hseb.raxdb_sync.RaxDbSyncBatch $IHFS_JDBCURL $RAX_JDBCURL diff --git a/javaUtilities/hydro/ohd.rax_apps/scripts/start_raxbase b/javaUtilities/hydro/ohd.rax_apps/scripts/start_raxbase deleted file mode 100644 index 08e0e418fc..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/scripts/start_raxbase +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/ksh -# file name: start_raxbase -# Last Updated: 01/02/2008 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for RAX applications -. /rfc_arc/lib/rax.profile - -# need to add a path to the jar file for this application -export CLASSPATH=$DB_DRIVER_PATH:$RUN_FROM_DIR/rax_apps.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -# run application using java -xterm -T RaxBase -iconic -n RaxBase -e $JBINDIR/java -Xmx512m -Xms32m ohd.hseb.raxbase.RaxBase $RAX_JDBCURL $IHFS_JDBCURL $ADB_NAME . diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/RaxBase.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/RaxBase.java deleted file mode 100644 index af31c3e0ba..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/RaxBase.java +++ /dev/null @@ -1,1636 +0,0 @@ -package ohd.hseb.raxbase; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.border.BevelBorder; - -import ohd.hseb.raxbase.gui.AdjustFactorEditor; -import ohd.hseb.raxbase.gui.AgencyEditor; -import ohd.hseb.raxbase.gui.AverageEditor; -import ohd.hseb.raxbase.gui.CountiesEditor; -import ohd.hseb.raxbase.gui.CountryEditor; -import ohd.hseb.raxbase.gui.CrestEditor; -import ohd.hseb.raxbase.gui.DataLimitsEditor; -import ohd.hseb.raxbase.gui.Huc2Editor; -import ohd.hseb.raxbase.gui.Huc4Editor; -import ohd.hseb.raxbase.gui.Huc6Editor; -import ohd.hseb.raxbase.gui.Huc8Editor; -import ohd.hseb.raxbase.gui.IngestFilterEditor; -import ohd.hseb.raxbase.gui.LocationEditor; -import ohd.hseb.raxbase.gui.ModCtrlEditor; -import ohd.hseb.raxbase.gui.ProcessAdjustFactorDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessCrestDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessDataLimitsDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessIngestFilterDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessLocDataLimitsDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessLocationDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessRatingDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessReservoirDifferencesDialog; -import ohd.hseb.raxbase.gui.ProcessRiverCritDifferencesDialog; -import ohd.hseb.raxbase.gui.ProdEditor; -import ohd.hseb.raxbase.gui.RatingCurveEditor; -import ohd.hseb.raxbase.gui.ReservoirEditor; -import ohd.hseb.raxbase.gui.RfcEditor; -import ohd.hseb.raxbase.gui.RiverCritEditor; -import ohd.hseb.raxbase.gui.SensOKEditor; -import ohd.hseb.raxbase.gui.ShefDurationEditor; -import ohd.hseb.raxbase.gui.ShefExtremumEditor; -import ohd.hseb.raxbase.gui.ShefPE1Editor; -import ohd.hseb.raxbase.gui.ShefPEEditor; -import ohd.hseb.raxbase.gui.ShefPETransEditor; -import ohd.hseb.raxbase.gui.ShefProbEditor; -import ohd.hseb.raxbase.gui.ShefQCEditor; -import ohd.hseb.raxbase.gui.ShefTSEditor; -import ohd.hseb.raxbase.gui.SlopeProfileEditor; -import ohd.hseb.raxbase.gui.StateEditor; -import ohd.hseb.raxbase.gui.StatusBar; -import ohd.hseb.raxbase.gui.WfoHsaEditor; -import ohd.hseb.raxbase.model.RaxLocation; -import ohd.hseb.raxbase.table.ArcBaseLocationJTableRowData; -import ohd.hseb.raxbase.util.CursorController; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RaxBase extends JFrame -{ - private Container _frameContentPane = getContentPane(); - - private JMenuBar _menuBar = null; - private JPopupMenu _popupMenu = new JPopupMenu(); - private JPanel _filterPanel = new JPanel( new FlowLayout() ); - private JLabel _filterLabel = new JLabel( "LID: " ); - private JTextField _filterTextField = new JTextField(); - private JButton _filterButton = new JButton( "Filter" ); - private StatusBar _statusBar = new StatusBar(); - - private String _dateString = "May 16, 2008"; - private String _buildString = "OB8.3"; - private String _versionString = "Application: RaxBase" + - "\nVersion: " + _buildString + - "\nDate: " + _dateString + - "\nDeveloped By: National Weather Service" + - "\n Office of Hydrologic Development" + - "\n Hydrology Laboratory"; - private RaxBaseDataMgr _dataMgr = null; - - private String _titleString = null; - - private boolean _filtered = false; - -// JTable variables - private JTableManager _arcBaseTableManager = null; - private List _arcBaseColumnDescriptorList = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - - public RaxBase( RaxBaseDataMgr dataMgr ) - { - _dataMgr = dataMgr; - _dataMgr.initRaxLocationRowDataList(); - initGui(); - setJMenuBar( _menuBar ); - setTitle( "RaxBase" ); - } - - /** - * Initializes the GUI for the main window - * - */ - private void initGui() - { - setSize( 1024, 768 ); - - setLayout( new GridBagLayout() ); - initMenuBar(); - initFilterPanel(); - initJTable(); - initMainWindow(); - refreshPopupMenu(); - addListeners(); - } - - /** - * Initialize the ArcBase JTable - * - * @return None - * - */ - private void initJTable() - { - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _allRowDataList = new ArrayList(); - setArcBaseColumnDescriptorList(); - _arcBaseTableManager = new ComplexJTableManager( _arcBaseColumnDescriptorList, _allRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _arcBaseTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _arcBaseTableManager.setDisplayableColumns( columnsSelected, true, true ); - _arcBaseTableManager.setPreferredSizeForJScrollPane( new Dimension( 1020, 600 ) ); - _tableScrollPane = _arcBaseTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add( _tableScrollPane ); - tableScrollPanePanel.setMinimumSize( new Dimension( 1030,710 ) ); - JPanel tablePanel = new JPanel(); - tablePanel.add( tableScrollPanePanel ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, tablePanel, 0, 3, 3, 30, 1, 1, GridBagConstraints.BOTH ); - } - - /** - * Sets up the Columns for the arcbase jtable - * - */ - private void setArcBaseColumnDescriptorList() - { - _arcBaseColumnDescriptorList = new ArrayList(); - - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Station", true, 100, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Begin Date", true, 100, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "End Date", true, 100, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Latitude", true, 100, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Longitude", true, 100, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 225, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Detailed Info", true, 225, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "HSA", true, 50, "center" ) ); - - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "Elevation", false, 50, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "State", false, 50, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "HUC", false, 50, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "WFO", false, 50, "center" ) ); - _arcBaseColumnDescriptorList.add(new JTableColumnDescriptor( "RFC", false, 50, "center" ) ); - - } - - /** - * Initializes the Main window - * - */ - private void initMainWindow() - { - JPanel horizontalPanel = new JPanel(); - horizontalPanel.setPreferredSize(new Dimension( 50, 50 ) ); - - // X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, horizontalPanel, 0, 1, 3, 1, 1, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _frameContentPane, _statusBar, 0, 33, 3, 1, 1, 0, GridBagConstraints.BOTH); - } - - private void refreshPopupMenu() - { - _popupMenu.removeAll(); - - String lidString = ""; - RaxLocation raxLocation = null; - String dashString = ""; - - int rows[] = _arcBaseTableManager.getSelectedRowIndices(); - if ( rows.length != 0 ) - { - int rowIndex = rows[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lidString = raxLocation.getLid() + " options"; - } - -// JMenuItem menuItem = new JMenuItem( lidString ); -// _popupMenu.add( menuItem ); -// _popupMenu.setBorder( new LineBorder( Color.BLACK, 2 ) ); -// _popupMenu.setBorder( BorderFactory.createBevelBorder( BevelBorder.RAISED, Color.GRAY, Color.BLACK ) ); - -// _popupMenu.setBorder( BorderFactory.createTitledBorder( new LineBorder( Color.BLACK, 2 ), lidString ) ); - _popupMenu.setBorder( BorderFactory.createTitledBorder( BorderFactory.createBevelBorder( BevelBorder.RAISED, Color.GRAY, Color.BLACK ), lidString ) ); - -// for ( int i = 0; i < lidString.length(); i++ ) -// { -// dashString += "-"; -// } - -// menuItem = new JMenuItem( dashString ); -// _popupMenu.add( menuItem ); - - JMenuItem menuItem = null; - - menuItem = new JMenuItem( "Modify Location" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchModifyLocationEditorGUI() ); - menuItem = new JMenuItem( "River Gage" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchRiverCritEditorGUI() ); - menuItem = new JMenuItem( "Rating Information" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchRatingCurveEditorGUI() ); - menuItem = new JMenuItem( "Crest History" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchCrestHistoryEditorGUI() ); - menuItem = new JMenuItem( "Slope Profile" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchSlopeProfileEditorGUI() ); - menuItem = new JMenuItem( "Average" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchAverageEditorGUI() ); - menuItem = new JMenuItem( "Reservoir" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchReservoirEditorGUI() ); - menuItem = new JMenuItem( "SensOK" ); - _popupMenu.add( menuItem ); - menuItem.addActionListener( new LaunchSensOKEditor() ); - } - - /** - * Initializes the Filter Panel - * - */ - private void initFilterPanel() - { - - _filterTextField.setColumns( 10 ); - _filterPanel.add( _filterLabel); - _filterPanel.add( _filterTextField ); - _filterPanel.add( _filterButton ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _filterPanel, 0, 0, 3, 1, GridBagConstraints.BOTH ); - } - - /** - * Adds listeneres to various components in the GUI - * - * @return NONE - * - */ - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - addWindowListener( windowCloser ); - - _filterButton.addActionListener( new FilterButtonListener() ); - MouseListener doubleClickListener = new DoubleClickListener(); - MouseListener popupListener = new PopupListener(); - _arcBaseTableManager.addTableListener( doubleClickListener ); - _arcBaseTableManager.addTableListener( popupListener ); - } - - private class PopupListener extends MouseAdapter implements MouseListener - { - public void mousePressed(MouseEvent e) - { - maybeShowPopup(e); - } - - public void mouseReleased(MouseEvent e) - { - maybeShowPopup(e); - } - - private void maybeShowPopup(MouseEvent e) - { - - if (e.isPopupTrigger()) - { - refreshPopupMenu(); - _popupMenu.show(e.getComponent(), - e.getX(), e.getY()); - } - } - } - - /** - * Listener for the JTable to allow the user to double click on a location entry - * @author gsood - * - */ - private class DoubleClickListener implements MouseListener - { - public void mouseClicked( MouseEvent e ) - { - if ( ( e.getClickCount() == 2 ) && ( e.getButton() == MouseEvent.BUTTON1 ) ) - { - boolean newLocation = false; - LaunchLocationEditor( newLocation ); - } - } - - public void mouseEntered( MouseEvent e ){} - public void mouseExited( MouseEvent e ){} - public void mousePressed( MouseEvent e ){} - public void mouseReleased( MouseEvent e ){} - } - - /** - * Listener for closing the main application window - * @author gsood - * - */ - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - /** - * Location Editor (Add) Launcher Listener - * @author gsood - * - */ - private class LaunchAddLocationEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean newLocation = true; - LaunchLocationEditor( newLocation ); - } - } - - /** - * Location Editor (Modify) Launcher Listener - * @author gsood - * - */ - private class LaunchModifyLocationEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Modify Location" ); - } - else - { - boolean newLocation = false; - LaunchLocationEditor( newLocation ); - } - } - } - - /** - * River Crit Editor Launcher Listener - * @author gsood - * - */ - private class LaunchRiverCritEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "RiverCrit Editor" ); - } - else - { - LaunchRiverCritEditor(); - } - } - } - - /** - * Rating Curve Editor Launcher Listener - * @author gsood - * - */ - private class LaunchRatingCurveEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Rating Curve Editor" ); - } - else - { - LaunchRatingCurveEditor(); - } - } - } - - /** - * Crest History Editor Launcher Listener - * @author gsood - * - */ - private class LaunchCrestHistoryEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Crest History Editor" ); - } - else - { - LaunchCrestEditor(); - } - } - } - - /** - * Slope Profile Editor Launcher Listener - * @author gsood - * - */ - private class LaunchSlopeProfileEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Slope Profile Editor" ); - } - else - { - LaunchSlopeProfileEditor(); - } - } - } - - /** - * Average Editor Launcher Listener - * @author gsood - * - */ - private class LaunchAverageEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Average Editor" ); - } - else - { - LaunchAverageEditor(); - } - } - } - - /** - * Reservoir Editor Launcher Editor - * @author gsood - * - */ - private class LaunchReservoirEditorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Reservoir Editor" ); - } - else - { - LaunchReservoirEditor(); - } - } - } - - /** - * IngestFilter Editor Launcher Listener - * @author gsood - * - */ - private class LaunchIngestFilterEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchIngestFilterEditor(); - } - } - - /** - * AdjustFactor Editor Launcher Listener - * @author gsood - * - */ - private class LaunchAdjustFactorEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchAdjustFactorEditor(); - } - } - - /** - * ProcessAdjustFactor Launcher - * @author gsood - * - */ - private class LaunchProcessAdjustFactorGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessAdjustFactorGUI(); - } - } - - /** - * ProcessRiverCrit Launcher - * @author gsood - * - */ - private class LaunchProcessRiverCritGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessRiverCritGUI(); - } - } - - /** - * ProcessLocation Launcher - * @author gsood - * - */ - private class LaunchProcessLocationGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessLocationGUI(); - } - } - - private class LaunchModCtrlEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchModCtrlEditor(); - } - } - - private class LaunchCountryEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchCountryEditor(); - } - } - - private class LaunchHuc2Editor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchHuc2Editor(); - } - } - - private class LaunchHuc4Editor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchHuc4Editor(); - } - } - - private class LaunchHuc6Editor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchHuc6Editor(); - } - } - - private class LaunchWfoHsaEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchWfoHsaEditor(); - } - } - - private class LaunchShefPETransEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefPETransEditor(); - } - } - - private class LaunchProdEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProdEditor(); - } - } - - private class LaunchAgencyEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchAgencyEditor(); - } - } - - private class LaunchShefTSEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefTSEditor(); - } - } - - private class LaunchShefQCEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefQCEditor(); - } - } - - private class LaunchShefProbEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefProbEditor(); - } - } - - private class LaunchShefPE1Editor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefPE1Editor(); - } - } - - private class LaunchShefPEEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefPEEditor(); - } - } - - private class LaunchShefExEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefExEditor(); - } - } - - private class LaunchShefDurEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchShefDurEditor(); - } - } - - private class LaunchRfcEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchRfcEditor(); - } - } - - private class LaunchHuc8Editor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchHuc8Editor(); - } - } - - private class LaunchCountiesEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchCountiesEditor(); - } - } - - private class LaunchStateEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchStateEditor(); - } - } - /** - * ProcessIngestFilter Launcher - * @author gsood - * - */ - private class LaunchProcessIngestFilterGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessIngestFilterGUI(); - } - } - - /** - * ProcessCrest Launcher - * @author gsood - * - */ - private class LaunchProcessCrestGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessCrestGUI(); - } - } - - private class LaunchProcessRatingGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessRatingGUI(); - } - } - - /** - * ProcessDataLimits Launcher - * @author gsood - * - */ - private class LaunchProcessDataLimitsGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessDataLimitsGUI(); - } - } - - /** - * ProcessLocDataLimits Launcher - * @author gsood - * - */ - private class LaunchProcessLocDataLimitsGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessLocDataLimitsGUI(); - } - } - - /** - * ProcessReservoir Launcher - * @author gsood - * - */ - private class LaunchProcessReservoirGUI implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchProcessReservoirGUI(); - } - } - - - private class LaunchDataLimitsEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - LaunchDataLimitsEditor(); - } - } - - private class LaunchSensOKEditor implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _arcBaseTableManager.getSelectedRowIndices().length == 0 ) - { - DialogHelper.displayErrorDialog( RaxBase.this, "You must select a Location first", "Sensok Editor" ); - } - else - { - LaunchSensOKEditor(); - } - } - - } - - private class DisplayAboutDialog implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - DialogHelper.displayMessageDialog( RaxBase.this, _versionString ); - } - } - - private class DisplayPreferencesListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - LaunchDisplayPreferences(); - } - } - - - private void LaunchDisplayPreferences() - { - _arcBaseTableManager.invokeColumnSelector( this ); - } - - private void LaunchLocationEditor( boolean newLocation ) - { - RaxLocation raxLocation = null; - - if ( ! newLocation ) // modify a location - { - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - } - LocationEditor locEditorGUI = new LocationEditor( this, _dataMgr, raxLocation ); - locEditorGUI.displayGUI(); - _dataMgr.updateRaxLocationRowDataList(); - if ( _filtered ) - { - filterLids(); - } - } - - private void updateTitleString( RaxLocation raxLocation ) - { - String lid = raxLocation.getLid(); - - _titleString = lid; - - if ( raxLocation.getName() != null ) - { - _titleString += " - " + raxLocation.getName(); - } - } - - private void LaunchRiverCritEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - - updateTitleString( raxLocation ); - - lid = raxLocation.getLid(); - - RiverCritEditor riverCritEditorGUI = new RiverCritEditor( this, _dataMgr, lid, _titleString ); - riverCritEditorGUI.displayGUI(); - } - - private void LaunchRatingCurveEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lid = raxLocation.getLid(); - updateTitleString( raxLocation ); - - RatingCurveEditor ratingCurveEditor = new RatingCurveEditor( this, _dataMgr, lid, _titleString ); - ratingCurveEditor.displayGUI(); - } - - private void LaunchCrestEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lid = raxLocation.getLid(); - updateTitleString( raxLocation ); - - CrestEditor crestEditorGUI = new CrestEditor( this, _dataMgr, lid, _titleString ); - crestEditorGUI.displayGUI(); - } - - private void LaunchSlopeProfileEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lid = raxLocation.getLid(); - updateTitleString( raxLocation ); - - SlopeProfileEditor slopeProfileEditor = new SlopeProfileEditor( this, _dataMgr, lid, _titleString ); - slopeProfileEditor.displayGUI(); - } - - private void LaunchAverageEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lid = raxLocation.getLid(); - updateTitleString( raxLocation ); - - AverageEditor averageEditor = new AverageEditor( this, _dataMgr, lid, _titleString ); - averageEditor.displayGUI(); - } - - private void LaunchReservoirEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lid = raxLocation.getLid(); - updateTitleString( raxLocation ); - - ReservoirEditor reservoirEditorGUI = new ReservoirEditor( this, _dataMgr, lid, _titleString ); - reservoirEditorGUI.displayGUI(); - } - - private void LaunchSensOKEditor() - { - RaxLocation raxLocation = null; - String lid = null; - - int rowIndex = ( _arcBaseTableManager.getSelectedRowIndices() )[ 0 ]; - ArcBaseLocationJTableRowData arcBaseLocationJTableRowData = (ArcBaseLocationJTableRowData) _arcBaseTableManager.getSelectedRowData( rowIndex ); - raxLocation = _dataMgr.getRaxLocationFromJTableRowData( arcBaseLocationJTableRowData ); - lid = raxLocation.getLid(); - updateTitleString( raxLocation ); - - SensOKEditor sensOKEditorGUI = new SensOKEditor( this, _dataMgr, lid, _titleString ); - sensOKEditorGUI.displayGUI(); - - } - - private void LaunchIngestFilterEditor() - { - IngestFilterEditor ingestFilterEditorGUI = new IngestFilterEditor( this, _dataMgr ); - ingestFilterEditorGUI.displayGUI(); - } - - private void LaunchAdjustFactorEditor() - { - AdjustFactorEditor adjustFactorEditorGUI = new AdjustFactorEditor( this, _dataMgr ); - adjustFactorEditorGUI.displayGUI(); - } - - private void LaunchProcessAdjustFactorGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessAdjustFactorDifferencesDialog procAdjFactorDiffGUI = new ProcessAdjustFactorDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procAdjFactorDiffGUI.displayGUI(); - } - } - - private void LaunchProcessRiverCritGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessRiverCritDifferencesDialog procRiverCritDiffGUI = new ProcessRiverCritDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procRiverCritDiffGUI.displayGUI(); - } - } - - private void LaunchProcessLocationGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessLocationDifferencesDialog procLocationDiffGUI = new ProcessLocationDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procLocationDiffGUI.displayGUI(); - } - } - - private void LaunchModCtrlEditor() - { - ModCtrlEditor modCtrlEditor = new ModCtrlEditor( this, _dataMgr ); - modCtrlEditor.displayGUI(); - } - - private void LaunchCountryEditor() - { - CountryEditor countryEditor = new CountryEditor( this, _dataMgr ); - countryEditor.displayGUI(); - } - - private void LaunchCountiesEditor() - { - CountiesEditor countiesEditor = new CountiesEditor( this, _dataMgr ); - countiesEditor.displayGUI(); - } - - private void LaunchHuc2Editor() - { - Huc2Editor huc2Editor = new Huc2Editor( this, _dataMgr ); - huc2Editor.displayGUI(); - } - - private void LaunchHuc4Editor() - { - Huc4Editor huc4Editor = new Huc4Editor( this, _dataMgr ); - huc4Editor.displayGUI(); - } - - private void LaunchShefPETransEditor() - { - ShefPETransEditor shefPeTransEditor = new ShefPETransEditor( this, _dataMgr ); - shefPeTransEditor.displayGUI(); - } - - private void LaunchProdEditor() - { - ProdEditor prodEditor = new ProdEditor( this, _dataMgr ); - prodEditor.displayGUI(); - } - - private void LaunchAgencyEditor() - { - AgencyEditor agencyEditor = new AgencyEditor( this, _dataMgr ); - agencyEditor.displayGUI(); - } - - private void LaunchShefTSEditor() - { - ShefTSEditor shefTSEditor = new ShefTSEditor( this, _dataMgr ); - shefTSEditor.displayGUI(); - } - - private void LaunchShefQCEditor() - { - ShefQCEditor shefQCEditor = new ShefQCEditor( this, _dataMgr ); - shefQCEditor.displayGUI(); - } - - private void LaunchShefProbEditor() - { - ShefProbEditor shefProbEditor = new ShefProbEditor( this, _dataMgr ); - shefProbEditor.displayGUI(); - } - - private void LaunchShefPE1Editor() - { - ShefPE1Editor shefPe1Editor = new ShefPE1Editor( this, _dataMgr ); - shefPe1Editor.displayGUI(); - } - - private void LaunchShefPEEditor() - { - ShefPEEditor shefPeEditor = new ShefPEEditor( this, _dataMgr ); - shefPeEditor.displayGUI(); - } - - private void LaunchShefExEditor() - { - ShefExtremumEditor shefExEditor = new ShefExtremumEditor( this, _dataMgr ); - shefExEditor.displayGUI(); - } - - private void LaunchShefDurEditor() - { - ShefDurationEditor shefDurEditor = new ShefDurationEditor( this, _dataMgr ); - shefDurEditor.displayGUI(); - } - - private void LaunchRfcEditor() - { - RfcEditor rfcEditor = new RfcEditor( this, _dataMgr ); - rfcEditor.displayGUI(); - } - - private void LaunchWfoHsaEditor() - { - WfoHsaEditor wfoHsaEditor = new WfoHsaEditor( this, _dataMgr ); - wfoHsaEditor.displayGUI(); - } - - private void LaunchHuc8Editor() - { - Huc8Editor huc8Editor = new Huc8Editor( this, _dataMgr ); - huc8Editor.displayGUI(); - } - - private void LaunchHuc6Editor() - { - Huc6Editor huc6Editor = new Huc6Editor( this, _dataMgr ); - huc6Editor.displayGUI(); - } - - private void LaunchStateEditor() - { - StateEditor stateEditor = new StateEditor( this, _dataMgr ); - stateEditor.displayGUI(); - } - - private void LaunchProcessIngestFilterGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessIngestFilterDifferencesDialog procIngestFilterDiffGUI = new ProcessIngestFilterDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procIngestFilterDiffGUI.displayGUI(); - } - } - - private void LaunchProcessRatingGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessRatingDifferencesDialog procRatingDiffGUI = new ProcessRatingDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procRatingDiffGUI.displayGUI(); - } - } - - private void LaunchProcessCrestGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessCrestDifferencesDialog procCrestDiffGUI = new ProcessCrestDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procCrestDiffGUI.displayGUI(); - } - } - - private void LaunchProcessReservoirGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessReservoirDifferencesDialog procResvDiffGUI = new ProcessReservoirDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procResvDiffGUI.displayGUI(); - } - } - - private void LaunchProcessDataLimitsGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessDataLimitsDifferencesDialog procDataLimitsDiffGUI = new ProcessDataLimitsDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procDataLimitsDiffGUI.displayGUI(); - } - } - - private void LaunchProcessLocDataLimitsGUI() - { - if ( _dataMgr.initProcessDataMgr() ) - { - ProcessLocDataLimitsDifferencesDialog procLocDataLimitsDiffGUI = new ProcessLocDataLimitsDifferencesDialog( this, _dataMgr.getRaxSyncDataMgr() ); - procLocDataLimitsDiffGUI.displayGUI(); - } - } - - private void LaunchDataLimitsEditor() - { - DataLimitsEditor dataLimitsEditorGUI = new DataLimitsEditor( this, _dataMgr ); - dataLimitsEditorGUI.displayGUI(); - } - - private void filterLids() - { - _filtered = true; - String filterString = _filterTextField.getText().toUpperCase().trim(); - _allRowDataList = _dataMgr.getFilteredRaxLocationRowDataList( filterString ); - _arcBaseTableManager.setChangedAllRowDataList( _allRowDataList ); - _arcBaseTableManager.refreshDisplay(); - _statusBar.setMessage( "Record count: " + _allRowDataList.size() ); - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - System.exit( 1 ); - } - - - /** - * Filter Button listener. This will take the text out of the _filterTextField and use it to filter the list - * of locations coming from the Location table in the Rax Database. - * - * - */ - private class FilterButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - filterLids(); - } - } - - /** - * Initializes the Menu Bar for the main GUI - * - * @return NONE - * - */ - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - ActionListener cursorListener = null; - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - - menu = new JMenu( "File" ); - menu.setMnemonic( KeyEvent.VK_F ); - menu.getAccessibleContext().setAccessibleDescription( "Access File Menus" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Preferences" ); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_P, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Open preferences window" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new DisplayPreferencesListener() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem("Exit Application"); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Exit the Application" ); - menu.add(menuItem); - menuItem.addActionListener( new WindowCloserListener() ); - - //====================== - - menu = new JMenu( "Location" ); - menu.setMnemonic( KeyEvent.VK_L ); - menu.getAccessibleContext().setAccessibleDescription( "Access Location Menus" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Add Location" ); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_A, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Add a Location" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchAddLocationEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Modify Location" ); - menuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_M, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Modify a Location" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchModifyLocationEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - //====================== - - menu = new JMenu( "GageInfo" ); - menu.setMnemonic( KeyEvent.VK_G ); - menu.getAccessibleContext().setAccessibleDescription( "Access RiverGage Menu" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "River Gage" ); - menuItem.getAccessibleContext().setAccessibleDescription( "River Crit" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchRiverCritEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Rating Information" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Rating Information" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchRatingCurveEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Crest History" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Crest History" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchCrestHistoryEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Slope Profile" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Slope Profile" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchSlopeProfileEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Average" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Average" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchAverageEditorGUI() ); - menuItem.addActionListener( cursorListener ); - - //====================== - - menu = new JMenu( "Reservoir" ); - menu.setMnemonic( KeyEvent.VK_R ); - menu.getAccessibleContext().setAccessibleDescription( "Reservoir Menu" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Reservoir" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Reservoir" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchReservoirEditorGUI() ); - menuItem.addActionListener( cursorListener ); - //====================== - - menu = new JMenu( "Data Ingest" ); - menu.setMnemonic( KeyEvent.VK_D ); - menu.getAccessibleContext().setAccessibleDescription( "Data Ingest Menu" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Ingest Filter" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Ingest Filter" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchIngestFilterEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Adjust Factor" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Adjust Factor" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchAdjustFactorEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "QC Data Limits" ); - menuItem.getAccessibleContext().setAccessibleDescription( "QC Data Limits" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchDataLimitsEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Sensok" ); - menuItem.getAccessibleContext().setAccessibleDescription( "Sensok" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchSensOKEditor() ); - menuItem.addActionListener( cursorListener ); - - //====================== - - menu = new JMenu( "Reference" ); - menu.setMnemonic( KeyEvent.VK_E ); - menu.getAccessibleContext().setAccessibleDescription( "Reference Menu" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Country" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchCountryEditor() ); - menuItem.addActionListener( cursorListener ); - - - menuItem = new JMenuItem( "State" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchStateEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Counties" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchCountiesEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "HUC2" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchHuc2Editor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "HUC4" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchHuc4Editor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "HUC6" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchHuc6Editor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "HUC8" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchHuc8Editor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "WFO_HSA" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchWfoHsaEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "RFC" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchRfcEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "ShefDur" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefDurEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Shefex" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefExEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Shefpetrans" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefPETransEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "ShefPE" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefPEEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "ShefPE1" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefPE1Editor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Shefprob" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefProbEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "ShefQC" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefQCEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "ShefTS" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchShefTSEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Agency" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchAgencyEditor() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Prod" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProdEditor() ); - menuItem.addActionListener( cursorListener ); - - //====================== - - menu = new JMenu( "NWSRFS" ); - menu.setMnemonic( KeyEvent.VK_N ); - menu.getAccessibleContext().setAccessibleDescription( "NWSRFS Menu" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Modctrl" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchModCtrlEditor() ); - menuItem.addActionListener( cursorListener ); - - //====================== - - menu = new JMenu( "SyncDBs" ); - menu.setMnemonic( KeyEvent.VK_S ); - menu.getAccessibleContext().setAccessibleDescription( "Process IHFS Menu" ); - menu.setToolTipText( "" ); - _menuBar.add( menu ); - - menuItem = new JMenuItem( "Location" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessLocationGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Ingest Filter" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessIngestFilterGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Adjust Factor" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessAdjustFactorGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "River Crit" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessRiverCritGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Crest" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessCrestGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Rating/Shift" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessRatingGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Data Limits" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessDataLimitsGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "LocData Limits" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessLocDataLimitsGUI() ); - menuItem.addActionListener( cursorListener ); - - menuItem = new JMenuItem( "Reservoir" ); - menu.add( menuItem ); - cursorListener = CursorController.createListener( this, new LaunchProcessReservoirGUI() ); - menuItem.addActionListener( cursorListener ); - - //acts as a separator to move the Help menu all the way to the right - menuItem = new JMenuItem(""); - menuItem.setEnabled(false); - _menuBar.add(menuItem); - - - // Help Menu - - menu = new JMenu("Help"); - menu.setMnemonic(KeyEvent.VK_H); - menu.getAccessibleContext().setAccessibleDescription( "Access help menu items." ); - _menuBar.add(menu); - - menuItem = new JMenuItem("About..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_B, ActionEvent.ALT_MASK ) ); - menuItem.getAccessibleContext().setAccessibleDescription( "Display the About Dialog." ); - menu.add(menuItem); - menuItem.addActionListener( new DisplayAboutDialog() ); - } - - /** - * Displays the RaxBase GUI - * - * @param jdbcConnectionString - JDBC Connection String - * @param logFilePath - Full filepath for the logfile - * - * @return NONE - * - */ - public static void show(String jdbcConnectionString, String ihfsConnectionString, String raxDBNameString, String logFilePath ) - { - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( jdbcConnectionString, ihfsConnectionString, logFilePath ); - RaxBase raxBase = new RaxBase( dataMgr ); - raxBase.setTitle( "RaxBase (" + raxDBNameString + ") - OB8.3" ); - raxBase.setVisible( true ); - } - - public static boolean validateInputParameters( String[] args ) - { - boolean valid = false; - - if ( args.length > 3 ) - { - valid = true; - } - - return valid; - } - - public static void main( String[] args ) - { - boolean validInputParameters = false; - - validInputParameters = RaxBase.validateInputParameters( args ); - - if ( validInputParameters == true ) - { - String raxJDBCConnectionString = args[0]; - String ihfsJDBCConnectionString = args[ 1 ]; - String raxDBNameString = args[ 2 ]; - String logFilePath = args[ 3 ]; - show(raxJDBCConnectionString, ihfsJDBCConnectionString, raxDBNameString, logFilePath ); - } - else - { - System.err.println( "Usage: RaxBase " ); - } - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/RaxBaseDataMgr.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/RaxBaseDataMgr.java deleted file mode 100644 index 53d72d812f..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/RaxBaseDataMgr.java +++ /dev/null @@ -1,4273 +0,0 @@ -package ohd.hseb.raxbase; - -import java.beans.PropertyChangeListener; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.JFrame; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.ShefProbRecord; -import ohd.hseb.ihfsdb.generated.ShefProbTable; -import ohd.hseb.raxbase.db.CustomRaxRatingTable; -import ohd.hseb.raxbase.model.Agency; -import ohd.hseb.raxbase.model.Average; -import ohd.hseb.raxbase.model.Counties; -import ohd.hseb.raxbase.model.Country; -import ohd.hseb.raxbase.model.Huc2; -import ohd.hseb.raxbase.model.Huc4; -import ohd.hseb.raxbase.model.Huc6; -import ohd.hseb.raxbase.model.Huc8; -import ohd.hseb.raxbase.model.ModCtrl; -import ohd.hseb.raxbase.model.Prod; -import ohd.hseb.raxbase.model.RaxAdjustFactor; -import ohd.hseb.raxbase.model.RaxCrest; -import ohd.hseb.raxbase.model.RaxDataLimits; -import ohd.hseb.raxbase.model.RaxIngestFilter; -import ohd.hseb.raxbase.model.RaxLocDataLimits; -import ohd.hseb.raxbase.model.RaxLocation; -import ohd.hseb.raxbase.model.RaxRating; -import ohd.hseb.raxbase.model.RaxRatingOffset; -import ohd.hseb.raxbase.model.RaxRatingPoint; -import ohd.hseb.raxbase.model.RaxRatingShift; -import ohd.hseb.raxbase.model.RaxReservoir; -import ohd.hseb.raxbase.model.RaxRiverCrit; -import ohd.hseb.raxbase.model.Rfc; -import ohd.hseb.raxbase.model.Sensok; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.model.ShefPE1; -import ohd.hseb.raxbase.model.ShefPETrans; -import ohd.hseb.raxbase.model.ShefProb; -import ohd.hseb.raxbase.model.ShefQC; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.raxbase.model.SlopeProfile; -import ohd.hseb.raxbase.model.State; -import ohd.hseb.raxbase.model.WfoHsa; -import ohd.hseb.raxbase.table.ArcBaseAdjustFactorJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseAgencyJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseCountiesJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseCountryJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseCrestJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseDataLimitsJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseHuc2JTableRowData; -import ohd.hseb.raxbase.table.ArcBaseHuc4JTableRowData; -import ohd.hseb.raxbase.table.ArcBaseHuc6JTableRowData; -import ohd.hseb.raxbase.table.ArcBaseHuc8JTableRowData; -import ohd.hseb.raxbase.table.ArcBaseIngestFilterJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseLocationJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseModCtrlJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseProdJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseRatingJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseRatingOffsetsJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseRfcJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefDurationJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefExtremumJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefPE1JTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefPEJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefPETransJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefProbJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefQCJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseShefTSJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseStateJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseWfoHsaJTableRowData; -import ohd.hseb.raxbase.util.ModalDialogRunner; -import ohd.hseb.raxbase.util.StatusDialog; -import ohd.hseb.raxdb.generated.AgencyRecord; -import ohd.hseb.raxdb.generated.AgencyTable; -import ohd.hseb.raxdb.generated.AvgRecord; -import ohd.hseb.raxdb.generated.AvgTable; -import ohd.hseb.raxdb.generated.CountiesRecord; -import ohd.hseb.raxdb.generated.CountiesTable; -import ohd.hseb.raxdb.generated.CountryRecord; -import ohd.hseb.raxdb.generated.CountryTable; -import ohd.hseb.raxdb.generated.Huc2Record; -import ohd.hseb.raxdb.generated.Huc2Table; -import ohd.hseb.raxdb.generated.Huc4Record; -import ohd.hseb.raxdb.generated.Huc4Table; -import ohd.hseb.raxdb.generated.Huc6Record; -import ohd.hseb.raxdb.generated.Huc6Table; -import ohd.hseb.raxdb.generated.Huc8Record; -import ohd.hseb.raxdb.generated.Huc8Table; -import ohd.hseb.raxdb.generated.ModctrlRecord; -import ohd.hseb.raxdb.generated.ModctrlTable; -import ohd.hseb.raxdb.generated.ProdRecord; -import ohd.hseb.raxdb.generated.ProdTable; -import ohd.hseb.raxdb.generated.RaxAdjustFactorRecord; -import ohd.hseb.raxdb.generated.RaxAdjustFactorTable; -import ohd.hseb.raxdb.generated.RaxCrestRecord; -import ohd.hseb.raxdb.generated.RaxCrestTable; -import ohd.hseb.raxdb.generated.RaxDataLimitsRecord; -import ohd.hseb.raxdb.generated.RaxDataLimitsTable; -import ohd.hseb.raxdb.generated.RaxIngestFilterRecord; -import ohd.hseb.raxdb.generated.RaxIngestFilterTable; -import ohd.hseb.raxdb.generated.RaxLocDataLimitsRecord; -import ohd.hseb.raxdb.generated.RaxLocDataLimitsTable; -import ohd.hseb.raxdb.generated.RaxLocationRecord; -import ohd.hseb.raxdb.generated.RaxLocationTable; -import ohd.hseb.raxdb.generated.RaxRatingRecord; -import ohd.hseb.raxdb.generated.RaxRatingShiftRecord; -import ohd.hseb.raxdb.generated.RaxRatingShiftTable; -import ohd.hseb.raxdb.generated.RaxRatingTable; -import ohd.hseb.raxdb.generated.RaxReservoirRecord; -import ohd.hseb.raxdb.generated.RaxReservoirTable; -import ohd.hseb.raxdb.generated.RaxRiverCritRecord; -import ohd.hseb.raxdb.generated.RaxRiverCritTable; -import ohd.hseb.raxdb.generated.RfcRecord; -import ohd.hseb.raxdb.generated.RfcTable; -import ohd.hseb.raxdb.generated.SensokRecord; -import ohd.hseb.raxdb.generated.SensokTable; -import ohd.hseb.raxdb.generated.ShefdurRecord; -import ohd.hseb.raxdb.generated.ShefdurTable; -import ohd.hseb.raxdb.generated.ShefexRecord; -import ohd.hseb.raxdb.generated.ShefexTable; -import ohd.hseb.raxdb.generated.Shefpe1Record; -import ohd.hseb.raxdb.generated.Shefpe1Table; -import ohd.hseb.raxdb.generated.ShefpeRecord; -import ohd.hseb.raxdb.generated.ShefpeTable; -import ohd.hseb.raxdb.generated.ShefpetransRecord; -import ohd.hseb.raxdb.generated.ShefpetransTable; -import ohd.hseb.raxdb.generated.ShefprobRecord; -import ohd.hseb.raxdb.generated.ShefprobTable; -import ohd.hseb.raxdb.generated.ShefqcRecord; -import ohd.hseb.raxdb.generated.ShefqcTable; -import ohd.hseb.raxdb.generated.SheftsRecord; -import ohd.hseb.raxdb.generated.SheftsTable; -import ohd.hseb.raxdb.generated.SlopeprofileRecord; -import ohd.hseb.raxdb.generated.SlopeprofileTable; -import ohd.hseb.raxdb.generated.StateRecord; -import ohd.hseb.raxdb.generated.StateTable; -import ohd.hseb.raxdb.generated.Wfo_hsaRecord; -import ohd.hseb.raxdb.generated.Wfo_hsaTable; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.DialogHelper; - -public class RaxBaseDataMgr -{ - private Database _raxDb = null; - private List _raxLocationRowDataList = null; - private List _raxLocationList = null; - private List _raxDataLimitsList = null; - private List _raxAdjustFactorList = null; - private List _raxCrestList = null; - private List _modCtrlList = null; - private List _countryList = null; - private List _huc2List = null; - private List _huc4List = null; - private List _huc6List = null; - private List _huc8List = null; - private List _shefPE1List = null; - private List _wfoHsaList = null; - private List _rfcList = null; - private List _stateList = null; - private List _countiesList = null; - private List _shefPETransList = null; - private List _shefQCList = null; - private List _agencyList = null; - private List _prodList = null; - private List _raxRatingList = null; - private List _raxRatingShiftList = null; - private List _raxOffsetsList = null; - private List _raxLocDataLimitsList = null; - private List _raxIngestFilterRowDataList = null; - private List _raxIngestFilterList = null; // might not keep - private List _raxRiverCritList = null; - private Map _raxIngestFilterRowDataToRaxIngestFilterMap = new HashMap(); - private Map _raxDataLimitsRowDataToRaxDataLimitsMap = new HashMap(); - private Map _raxAdjustFactorRowDataToRaxAdjustFactorMap = new HashMap(); - private Map _raxCrestRowDataToRaxCrestMap = new HashMap(); - private Map _modCtrlRowDataToModCtrlMap = new HashMap(); - private Map _raxLocDataLimitsRowDataToRaxLocDataLimitsMap = new HashMap(); - private Map _countryRowDataToCountryMap = new HashMap(); - private Map _stateRowDataToStateMap = new HashMap(); - private Map _countiesRowDataToCountiesMap = new HashMap(); - private Map _huc2RowDataToHuc2Map = new HashMap(); - private Map _huc4RowDataToHuc4Map = new HashMap(); - private Map _huc6RowDataToHuc6Map = new HashMap(); - private Map _huc8RowDataToHuc8Map = new HashMap(); - private Map _wfoHsaRowDataToWfoHsaMap = new HashMap(); - private Map _rfcRowDataToRfcMap = new HashMap(); - private Map _shefDurRowDataToShefDurMap = new HashMap(); - private Map _shefExRowDataToShefExMap = new HashMap(); - private Map _shefPeTransRowDataToShefPeTransMap = new HashMap(); - private Map _shefPeRowDataToShefPeMap = new HashMap(); - private Map _shefPe1RowDataToShefPe1Map = new HashMap(); - private Map _shefProbRowDataToShefProbMap = new HashMap(); - private Map _shefQCRowDataToShefQCMap = new HashMap(); - private Map _shefTsRowDataToShefTsMap = new HashMap(); - private Map _agencyRowDataToAgencyMap = new HashMap(); - private Map _prodRowDataToProdMap = new HashMap(); - private Map _stateCountryFipsStringToStateRecordMap = new HashMap(); - - private RaxSyncDataMgr _raxSyncDataMgr = null; - - private String _ihfsConnectionString = null; - - private List _shefPeList = null; - private List _shefDurationList = null; - private List _shefTSList = null; - private List _shefExtremumList = null; - private List _shefProbList = null; - private Map _shefPEMap = new HashMap(); - private Map _shefDurationMap = new HashMap(); - private Map _shefTSMap = new HashMap(); - private Map _shefExtremumMap = new HashMap(); - private Map _shefProbMap = new HashMap(); - - private Logger _logger = null; - - private static final String _numberFormatString = "0.0000"; - private static final DecimalFormat _numberFormatter = new DecimalFormat(_numberFormatString); - - private StatusDialog _statDialog = null; - - // private static final short MISSING = -9999; - - public RaxBaseDataMgr( String jdbcConnectionString ) - { - _raxDb = new Database(); - setLogger( "/awips/hydroapps/ob83_fwr/whfs/local/log" ); - _raxDb.connectWithDriverSearch( jdbcConnectionString ); - initShefPeList(); - initShefDurationList(); - initShefProbList(); - initShefTSList(); - initShefExtremumList(); - } - - public void initRaxLocationRowDataList() - { - _raxLocationRowDataList = getLocationRowDataList(); - } - - public RaxBaseDataMgr( String jdbcConnectionString, String ihfsConnectionString, String logFilePath ) - { - this( jdbcConnectionString ); - setLogger( logFilePath ); - _ihfsConnectionString = ihfsConnectionString; - } - - private void setLogger( String logFilePath ) - { - String logFileName = logFilePath + "/RaxBase.log"; - - _logger = new FileLogger( logFileName, true, true ); - } - - - - public void updateRaxLocationRowDataList() - { - _raxLocationRowDataList = getLocationRowDataList(); - } -// ------------------------------------ PUBLIC METHODS -------------------------------- - - public boolean initProcessDataMgr() - { - boolean created = false; - - if ( getRaxSyncDataMgr() == null ) - { - try - { - Connection connection = DriverManager.getConnection( _ihfsConnectionString ); - connection.close(); - _raxSyncDataMgr = new RaxSyncDataMgr( _ihfsConnectionString, _raxDb ); - created = true; - } - catch( SQLException e ) - { - DialogHelper.displayErrorDialog( new JFrame(), "Error in IHFS JDBC URL: " + _ihfsConnectionString, "Bad IHFS JDBC URL" ); - } - } - else // not null - { - created = true; - } - - return created; - } - - /** - * This method reads from the Location table in the Rax Database, creates a list of RaxLocation objects, - * creates a list of ArcBaseLocationJTableRowData objects (used for the jtable), and returns the - * rowdata List - * - * @return Returns a list of Location Row Data objects - */ - public List getLocationRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - List raxLocationRecordsList = null; - List raxLocationRowDataList = null; - - raxLocationRecordsList = getRaxLocationRecordsList(); - _raxLocationList = getRaxLocationListFromRaxLocationRecordsList( raxLocationRecordsList ); - - raxLocationRowDataList = getRowDataListFromRaxLocationList(); - - _logger.log( "Finished reading in RaxLocation data in " + timer1.stop() ); - return raxLocationRowDataList; - } - - public String getFormattedDouble( double value ) - { - return _numberFormatter.format(value); - } - - public List getFilteredRaxLocationRowDataList( String filterString ) - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - List filteredRaxLocationRowDataList = new ArrayList(); - boolean foundMatch = false; - ArcBaseLocationJTableRowData rowData = null; - int startIndex = -9999; - - if ( ! filterString.equalsIgnoreCase( "" ) ) // not a blank string - { - for ( int i = 0; i < _raxLocationRowDataList.size(); i++ ) - { - rowData = (ArcBaseLocationJTableRowData) _raxLocationRowDataList.get( i ); - - if ( rowData.getRaxLocation().getLid().startsWith( filterString ) ) - { - startIndex = i; - foundMatch = true; - break; - } - } - - while ( ( foundMatch == true ) && ( startIndex < _raxLocationRowDataList.size() ) ) - { - rowData = (ArcBaseLocationJTableRowData) _raxLocationRowDataList.get( startIndex ); - if ( rowData.getRaxLocation().getLid().startsWith( filterString ) ) - { - rowData.addAllCellsToMap(); - filteredRaxLocationRowDataList.add( rowData ); - } - else - { - foundMatch = false; - } - startIndex++; - } - } - else - { - filteredRaxLocationRowDataList = _raxLocationRowDataList; - } - - _logger.log( "Finished filtering RaxLocationRowData in " + timer1.stop() ); - return filteredRaxLocationRowDataList; - } - - /** - * This method does the following: - * 1) Reads from the IngestFilter, ShefPE, ShefDur, ShefTS, and ShefEX table in the Rax Database - * 2) Creates a list of RaxIngestFilter objects - * 3) Creates a list of ArcBaseIngestFilterJTableRowData objects (used for the jtable) - * 4) returns the rowdata List - * - * @return Returns a list of IngestFilter Row Data objects - */ - public void initIngestFilterRowData( PropertyChangeListener listener ) - { - _statDialog = new StatusDialog( "Loading IngestFilter data..." ); - _statDialog.addPropertyChangeListener( listener ); - - Thread t = new Thread( new Runnable() - { - public void run() - { - _statDialog.setVisible( true ); - } - } - ); - - t.start(); - - ModalDialogRunner dialogRunner = new ModalDialogRunner( this ); - dialogRunner.start(); - -// _raxIngestFilterRowDataList = createIngestFilterRowDataList(); - } - - public void finishProcess() - { - _statDialog.setVisible( false ); - _statDialog.firePropListener(); - } - - public void updateIngestFilterRowData() - { - _raxIngestFilterRowDataList = createIngestFilterRowDataList(); - } - - public List getDataLimitsRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - List raxDataLimitsRecordsList = null; - List raxDataLimitsRowDataList = null; - - raxDataLimitsRecordsList = getRaxDataLimitsRecordsList(); - _raxDataLimitsList = getRaxDataLimitsListFromRaxDataLimitsRecordsList( raxDataLimitsRecordsList ); - - raxDataLimitsRowDataList = getRowDataListFromRaxDataLimitsList(); - - _logger.log( "Finished reading in RaxDataLimits data in " + timer1.stop() ); - - return raxDataLimitsRowDataList; - } - - public List getAdjustFactorRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List raxAdjustFactorRecordsList = null; - List raxAdjustFactorRowDataList = null; - - raxAdjustFactorRecordsList = getRaxAdjustFactorRecordsList(); - _raxAdjustFactorList = getRaxAdjustFactorListFromRaxAdjustFactorRecordsList( raxAdjustFactorRecordsList ); - - raxAdjustFactorRowDataList = getRowDataListFromRaxAdjustFactorList(); - - _logger.log( "Finished reading in RaxAdjustFactor data in " + timer1.stop() ); - - return raxAdjustFactorRowDataList; - } - - public List getCrestRowDataList( String lid ) - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List raxCrestRecordsList = null; - List raxCrestRowDataList = null; - - raxCrestRecordsList = getRaxCrestRecordsList( lid ); - _raxCrestList = getRaxCrestListFromRaxCrestRecordsList( raxCrestRecordsList ); - - raxCrestRowDataList = getRowDataListFromRaxCrestList(); - - _logger.log( "Finished reading in Crest data in " + timer1.stop() ); - - return raxCrestRowDataList; - } - - public List getCountiesRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List countiesRecordsList = null; - List countiesRowDataList = null; - - countiesRecordsList = getCountiesRecordsList(); - _countiesList = getCountiesListFromCountiesRecordsList( countiesRecordsList ); - - countiesRowDataList = getRowDataFromCountiesList(); - - _logger.log( "Finished reading in Counties data in " + timer1.stop() ); - - return countiesRowDataList; - } - - public List getStateRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List stateRecordsList = null; - List stateRowDataList = null; - - stateRecordsList = getStateRecordsList(); - _stateList = getStateListFromStateRecordsList( stateRecordsList ); - - stateRowDataList = getRowDataFromStateList(); - - _logger.log( "Finished reading in State data in " + timer1.stop() ); - - return stateRowDataList; - } - - public List getProdRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List prodRecordsList = null; - List prodRowDataList = null; - - prodRecordsList = getProdRecordsList(); - _prodList = getProdListFromProdRecordsList( prodRecordsList ); - - prodRowDataList = getRowDataFromProdList(); - - _logger.log( "Finished reading in Prod data in " + timer1.stop() ); - - return prodRowDataList; - } - - public List getHuc8RowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List huc8RecordsList = null; - List huc8RowDataList = null; - - huc8RecordsList = getHuc8RecordsList(); - _huc8List = getHuc8ListFromHuc8RecordsList( huc8RecordsList ); - - huc8RowDataList = getRowDataFromHuc8List(); - - _logger.log( "Finished reading in Huc8 data in " + timer1.stop() ); - - return huc8RowDataList; - } - - public List getHuc6RowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List huc6RecordsList = null; - List huc6RowDataList = null; - - huc6RecordsList = getHuc6RecordsList(); - _huc6List = getHuc6ListFromHuc6RecordsList( huc6RecordsList ); - - huc6RowDataList = getRowDataFromHuc6List(); - - _logger.log( "Finished reading in Huc6 data in " + timer1.stop() ); - - return huc6RowDataList; - } - - public List getShefQCRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefQCRecordsList = null; - List shefQCRowDataList = null; - - shefQCRecordsList = getShefQCRecordsList(); - _shefQCList = getShefQCListFromShefQCRecordsList( shefQCRecordsList ); - - shefQCRowDataList = getRowDataFromShefQCList(); - - _logger.log( "Finished reading in ShefQC data in " + timer1.stop() ); - - return shefQCRowDataList; - } - - public List getAgencyRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List agencyRecordsList = null; - List agencyRowDataList = null; - - agencyRecordsList = getAgencyRecordsList(); - _agencyList = getAgencyListFromAgencyRecordsList( agencyRecordsList ); - - agencyRowDataList = getRowDataFromAgencyList(); - - _logger.log( "Finished reading in Agency data in " + timer1.stop() ); - - return agencyRowDataList; - } - - public List getShefPe1RowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefPe1RecordsList = null; - List shefPe1RowDataList = null; - - shefPe1RecordsList = getPE1RecordsList(); - _shefPE1List = getShefPE1ListFromShefPE1RecordsList( shefPe1RecordsList ); - - shefPe1RowDataList = getRowDataFromShefPE1List(); - - _logger.log( "Finished reading in ShefPE1 data in " + timer1.stop() ); - - return shefPe1RowDataList; - } - - public List getHuc4RowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List huc4RecordsList = null; - List huc4RowDataList = null; - - huc4RecordsList = getHuc4RecordsList(); - _huc4List = getHuc4ListFromHuc4RecordsList( huc4RecordsList ); - - huc4RowDataList = getRowDataFromHuc4List(); - - _logger.log( "Finished reading in Huc4 data in " + timer1.stop() ); - - return huc4RowDataList; - } - - public List getRfcRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List rfcRecordsList = null; - List rfcRowDataList = null; - - rfcRecordsList = getRfcRecordsList(); - _rfcList = getRfcListFromRfcRecordsList( rfcRecordsList ); - - rfcRowDataList = getRowDataFromRfcList(); - - _logger.log( "Finished reading in Rfc data in " + timer1.stop() ); - - return rfcRowDataList; - } - - public List getWfoHsaRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List wfoHsaRecordsList = null; - List wfoHsaRowDataList = null; - - wfoHsaRecordsList = getWfoHsaRecordsList(); - _wfoHsaList = getWfoHsaListFromWfoHsaRecordsList( wfoHsaRecordsList ); - - wfoHsaRowDataList = getRowDataFromWfoHsaList(); - - _logger.log( "Finished reading in WfoHsa data in " + timer1.stop() ); - - return wfoHsaRowDataList; - } - - public List getShefTsRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefTsRowDataList = null; - - shefTsRowDataList = getRowDataFromShefTsList(); - - _logger.log( "Finished reading in ShefTS data in " + timer1.stop() ); - - return shefTsRowDataList; - } - - public List getShefExRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefExRowDataList = null; - - shefExRowDataList = getRowDataFromShefExList(); - - _logger.log( "Finished reading in ShefExtremum data in " + timer1.stop() ); - - return shefExRowDataList; - } - - public List getShefProbRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefProbRowDataList = null; - - shefProbRowDataList = getRowDataFromShefProbList(); - - _logger.log( "Finished reading in ShefProb data in " + timer1.stop() ); - - return shefProbRowDataList; - } - - public List getShefPeRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefPeRowDataList = null; - - shefPeRowDataList = getRowDataFromShefPEList(); - - _logger.log( "Finished reading in ShefPE data in " + timer1.stop() ); - - return shefPeRowDataList; - } - - public List getShefDurRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefDurRowDataList = null; - initShefDurationList(); - shefDurRowDataList = getRowDataFromShefDurationList(); - - _logger.log( "Finished reading in ShefDur data in " + timer1.stop() ); - - return shefDurRowDataList; - } - - public List getShefPeTransRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List shefPETransRecordsList = null; - List shefPETransRowDataList = null; - - shefPETransRecordsList = getShefPETransRecordsList(); - _shefPETransList = getShefPETransListFromShefPETransRecordsList( shefPETransRecordsList ); - - shefPETransRowDataList = getRowDataFromShefPETransList(); - - _logger.log( "Finished reading in ShefPETrans data in " + timer1.stop() ); - - return shefPETransRowDataList; - } - - public List getHuc2RowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List huc2RecordsList = null; - List huc2RowDataList = null; - - huc2RecordsList = getHuc2RecordsList(); - _huc2List = getHuc2ListFromHuc2RecordsList( huc2RecordsList ); - - huc2RowDataList = getRowDataFromHuc2List(); - - _logger.log( "Finished reading in Huc2 data in " + timer1.stop() ); - - return huc2RowDataList; - } - - public List getCountryRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List countryRecordsList = null; - List countryRowDataList = null; - - countryRecordsList = getCountryRecordsList(); - _countryList = getCountryListFromCountryRecordsList( countryRecordsList ); - - countryRowDataList = getRowDataFromCountryList(); - - _logger.log( "Finished reading in Country data in " + timer1.stop() ); - - return countryRowDataList; - } - - public List getModCtrlRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List modCtrlRecordsList = null; - List modCtrlRowDataList = null; - - modCtrlRecordsList = getModCtrlRecordsList(); - _modCtrlList = getModCtrlListFromModCtrlRecordsList( modCtrlRecordsList ); - - modCtrlRowDataList = getRowDataListFromModCtrlList(); - - _logger.log( "Finished reading in ModCtrl data in " + timer1.stop() ); - - return modCtrlRowDataList; - } - - public List getRatingCurveList( String lid ) - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List raxRatingRecordsList = null; - - raxRatingRecordsList = getRaxRatingRecordsList( lid ); - _raxRatingList = getRaxRatingListFromRaxRatingRecordsList( raxRatingRecordsList ); - - _logger.log( "Finished reading in Rating Data in " + timer1.stop() ); - - return _raxRatingList; - } - - public List getRatingShiftList( String lid ) - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List raxRatingShiftRecordsList = null; - - raxRatingShiftRecordsList = getRaxRatingShiftRecordsList( lid ); - _raxRatingShiftList = getRaxRatingShiftListFromRaxRatingShiftRecordsList( raxRatingShiftRecordsList ); - - _logger.log( "Finished reading in Rating Shift data in " + timer1.stop() ); - - return _raxRatingShiftList; - } - - - public List getRatingCurveRowDataList( RaxRating raxRating ) - { - List ratingCurveRowDataList = new ArrayList(); - - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - if ( raxRating != null ) - { - ratingCurveRowDataList = getRatingCurveRowDataListFromRaxRating( raxRating.getRaxRatingPointList() ); - } - - _logger.log( "Finished reading in Rating Point data in " + timer1.stop() ); - - return ratingCurveRowDataList; - } - - public List getOffsetsRowDataList( RaxRating raxRating ) - { - List ratingOffsetsRowDataList = new ArrayList(); - - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - if ( raxRating != null ) - { - ratingOffsetsRowDataList = getRatingOffsetsRowDataListFromRaxRating( raxRating.getOffsets() ); - } - _logger.log( "Finished reading in Offsets data in " + timer1.stop() ); - - return ratingOffsetsRowDataList; - } - - public List getLocDataLimitsRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - List raxLocDataLimitsRecordsList = null; - List raxLocDataLimitsRowDataList = null; - - raxLocDataLimitsRecordsList = getRaxLocDataLimitsRecordsList(); - _raxLocDataLimitsList = getRaxLocDataLimitsListFromRaxLocDataLimitsRecordsList( raxLocDataLimitsRecordsList ); - - raxLocDataLimitsRowDataList = getRowDataListFromRaxLocDataLimitsList(); - - _logger.log( "Finished reading in RaxLocDataLimits data in " + timer1.stop() ); - - return raxLocDataLimitsRowDataList; - } - - public List setupAndGetRaxRiverCritList( String lid ) - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - - List raxRiverCritRecordsList = null; - - raxRiverCritRecordsList = getRaxRiverCritRecordsList( lid ); - _raxRiverCritList = getRaxRiverCritListFromRaxRiverCritRecordsList( raxRiverCritRecordsList ); - - _logger.log( "Finished reading in RaxRiverCrit data in " + timer1.stop() ); - - return _raxRiverCritList; - } - - public List getRaxReservoirListFromRaxLocation( String lid ) - { - List raxReservoirList = new ArrayList(); - List raxReservoirRecordsList = null; - RaxReservoirRecord record = null; - RaxReservoirTable table = new RaxReservoirTable( _raxDb ); - String where = " WHERE lid='" + lid + "' "; - - try - { - raxReservoirRecordsList = table.select( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < raxReservoirRecordsList.size(); i++ ) - { - record = (RaxReservoirRecord) raxReservoirRecordsList.get( i ); - raxReservoirList.add( new RaxReservoir( record ) ); - } - - return raxReservoirList; - } - - public List getAverageList( String lid ) - { - List averageList = new ArrayList(); - List averageRecordsList = null; - AvgRecord record = null; - AvgTable table = new AvgTable( _raxDb ); - String where = " WHERE lid ='" + lid + "' "; - - try - { - averageRecordsList = table.select( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < averageRecordsList.size(); i++ ) - { - record = (AvgRecord) averageRecordsList.get( i ); - averageList.add( new Average( record ) ); - } - - return averageList; - } - - public List getSensokList( String lid ) - { - List sensokList = new ArrayList(); - List sensOkRecordList = null; - SensokRecord record = null; - SensokTable table = new SensokTable( _raxDb ); - String where = " WHERE lid = '" + lid + "' "; - - try - { - sensOkRecordList = table.select( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < sensOkRecordList.size(); i++ ) - { - record = (SensokRecord) sensOkRecordList.get( i ); - sensokList.add( new Sensok( record ) ); - } - - return sensokList; - } - - public List getSlopeProfileList( String lid ) - { - List slopeProfileList = new ArrayList(); - List slopeProfileRecordList = null; - SlopeprofileRecord record = null; - SlopeprofileTable table = new SlopeprofileTable( _raxDb ); - String where = " WHERE lid = '" + lid + "' "; - try - { - slopeProfileRecordList = table.select( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < slopeProfileRecordList.size(); i++ ) - { - record = (SlopeprofileRecord) slopeProfileRecordList.get( i ); - slopeProfileList.add( new SlopeProfile( record ) ); - } - - return slopeProfileList; - } - -// ------------------------------------ INGEST FILTER --------------------------------- - - private List getRowDataListFromRaxIngestFilterList() - { - List raxIngestFilterRowDataList = new ArrayList(); - ArcBaseIngestFilterJTableRowData rowData = new ArcBaseIngestFilterJTableRowData(); - RaxIngestFilter raxIngestFilter = null; - - for ( int i = 0; i < _raxIngestFilterList.size(); i++ ) - { - raxIngestFilter = (RaxIngestFilter) _raxIngestFilterList.get( i ); - rowData = new ArcBaseIngestFilterJTableRowData(); - - rowData.setRaxIngestFilter( raxIngestFilter ); - - rowData.addAllCellsToMap(); - - raxIngestFilterRowDataList.add( rowData ); - _raxIngestFilterRowDataToRaxIngestFilterMap.put( rowData, raxIngestFilter ); - } - - return raxIngestFilterRowDataList; - } - - private List getRaxIngestFilterRecordsList() - { - List raxIngestFilterRecordsList = null; - RaxIngestFilterTable table = new RaxIngestFilterTable( _raxDb ); - - _logger.log( "Starting to read IngestFilterRecords" ); - try - { -// raxIngestFilterRecordsList = table.select( " WHERE lid > 'A' AND lid <= 'C' ORDER BY lid " ); - raxIngestFilterRecordsList = table.select( " ORDER BY lid " ); - } - catch ( SQLException e ) - { - } - - System.gc(); - - _logger.log( "Finished reading " + raxIngestFilterRecordsList.size() + " records" ); - - return raxIngestFilterRecordsList; - } - - private List getRaxIngestFilterListFromRaxIngestFilterRecordsList( List raxIngestFilterRecordsList ) - { - List raxIngestFilterList = new ArrayList(); - RaxIngestFilterRecord raxIngestFilterRecord = null; - - for ( int i = 0; i < raxIngestFilterRecordsList.size(); i++ ) - { - raxIngestFilterRecord = (RaxIngestFilterRecord) raxIngestFilterRecordsList.get( i ); - - raxIngestFilterList.add( new RaxIngestFilter( raxIngestFilterRecord ) ); - } - - return raxIngestFilterList; - } - - -// -------------------------------- LOCATION ----------------------------- - - - /** - * Takes a List of RaxLocation objects and creates a list of ArcBaseLocationJTableRowData objects used by the - * JTable in the main GUI - * - * @param locationList - List of RaxLocation objects - * @return - List of ArcBaseLocationJTableRowData objects - */ - private List getRowDataListFromRaxLocationList() - { - List raxLocationRowDataList = new ArrayList(); - ArcBaseLocationJTableRowData rowData = new ArcBaseLocationJTableRowData(); - RaxLocation raxLocation = null; - - for ( int i = 0; i < _raxLocationList.size(); i++ ) - { - raxLocation = (RaxLocation) _raxLocationList.get( i ); - rowData = new ArcBaseLocationJTableRowData(); - - rowData.setRaxLocation( raxLocation ); - - rowData.addAllCellsToMap(); - raxLocationRowDataList.add( rowData ); - } - return raxLocationRowDataList; - } - - /** - * Takes a List of RaxLocationRecord objects retrieved from the archive database and converts it to a List - * of RaxLocation objects. - * - * @param raxLocationRecordsList - List of RaxLocationRecords - * @return - List of RaxLocation objects - */ - private List getRaxLocationListFromRaxLocationRecordsList( List raxLocationRecordsList ) - { - List raxLocationList = new ArrayList(); - RaxLocationRecord raxLocationRecord = null; - - for ( int i = 0; i < raxLocationRecordsList.size(); i++ ) - { - raxLocationRecord = (RaxLocationRecord) raxLocationRecordsList.get( i ); - - raxLocationList.add( new RaxLocation( raxLocationRecord ) ); - } - return raxLocationList; - } - - - public RaxLocation getRaxLocationFromJTableRowData( ArcBaseLocationJTableRowData rowData ) - { - RaxLocation raxLocation = new RaxLocation(); - RaxLocation extractedRaxLocation = null; - - for ( int i = 0; i < _raxLocationList.size(); i++ ) - { - extractedRaxLocation = (RaxLocation) _raxLocationList.get( i ); - - if ( ( extractedRaxLocation.getLid().equalsIgnoreCase( rowData.getRaxLocation().getLid() ) ) && - ( extractedRaxLocation.getBeginDate() == rowData.getRaxLocation().getBeginDate() ) ) - { - raxLocation = extractedRaxLocation; - break; - } - } - return raxLocation; - } - -// ------------------------------------ DATA LIMITS -------------------------------- - - private List getRowDataListFromRaxDataLimitsList() - { - List raxDataLimitsRowDataList = new ArrayList(); - ArcBaseDataLimitsJTableRowData rowData = new ArcBaseDataLimitsJTableRowData(); - RaxDataLimits dataLimits = null; - - for ( int i = 0; i < _raxDataLimitsList.size(); i++ ) - { - dataLimits = (RaxDataLimits) _raxDataLimitsList.get( i ); - rowData = new ArcBaseDataLimitsJTableRowData(); - - rowData.setLid( "" ); - rowData.setPe( dataLimits.getPe() ); - rowData.setDuration( dataLimits.getDur() + "/" + dataLimits.getIdur() ); - rowData.setMonthDayStart( dataLimits.getMonthDayStart() ); - rowData.setMonthDayEnd( dataLimits.getMonthDayEnd() ); - rowData.setGrossRangeMin( dataLimits.getGrossRangeMin() ); - rowData.setGrossRangeMax( dataLimits.getGrossRangeMax() ); - rowData.setReasonRangeMin( dataLimits.getReasonRangeMin() ); - rowData.setReasonRangeMax( dataLimits.getReasonRangeMax() ); - rowData.setRocMax( dataLimits.getRoc() ); - rowData.setAlertLimit( dataLimits.getAlertLimit() ); - rowData.setAlertRocLimit( dataLimits.getAlertRocLimit() ); - rowData.setAlarmLimit( dataLimits.getAlarmLimit() ); - rowData.setAlarmRocLimit( dataLimits.getAlarmRocLimit() ); - - rowData.addAllCellsToMap(); - raxDataLimitsRowDataList.add( rowData ); - _raxDataLimitsRowDataToRaxDataLimitsMap.put( rowData, dataLimits ); - } - - return raxDataLimitsRowDataList; - } - - private List getRowDataListFromRaxAdjustFactorList() - { - List raxAdjustFactorRowDataList = new ArrayList(); - ArcBaseAdjustFactorJTableRowData rowData = new ArcBaseAdjustFactorJTableRowData(); - RaxAdjustFactor raxAdjustFactor = null; - - for ( int i = 0; i < _raxAdjustFactorList.size(); i++ ) - { - raxAdjustFactor = (RaxAdjustFactor) _raxAdjustFactorList.get( i ); - rowData = new ArcBaseAdjustFactorJTableRowData(); - - rowData.setRaxAdjustFactor( raxAdjustFactor ); - - rowData.addAllCellsToMap(); - raxAdjustFactorRowDataList.add( rowData ); - _raxAdjustFactorRowDataToRaxAdjustFactorMap.put( rowData, raxAdjustFactor ); - } - - return raxAdjustFactorRowDataList; - } - - private List getRowDataFromCountiesList() - { - List countiesRowDataList = new ArrayList(); - ArcBaseCountiesJTableRowData rowData = new ArcBaseCountiesJTableRowData(); - Counties counties = null; - - for ( int i = 0; i < _countiesList.size(); i++ ) - { - counties = (Counties) _countiesList.get( i ); - rowData = new ArcBaseCountiesJTableRowData(); - - rowData.setCounty( counties.getCounty() ); - rowData.setCountryFips( counties.getCountryFips() ); - rowData.setCountyFips( counties.getCountyFips() ); - rowData.setState( counties.getState() ); - rowData.setWfo( counties.getWfo() ); - rowData.setZon( counties.getZon() ); - - rowData.addAllCellsToMap(); - countiesRowDataList.add( rowData ); - _countiesRowDataToCountiesMap.put( rowData, counties ); - } - - return countiesRowDataList; - } - - private List getRowDataFromStateList() - { - List stateRowDataList = new ArrayList(); - ArcBaseStateJTableRowData rowData = new ArcBaseStateJTableRowData(); - State state = null; - - for ( int i = 0; i < _stateList.size(); i++ ) - { - state = (State) _stateList.get( i ); - rowData = new ArcBaseStateJTableRowData(); - - rowData.setState( state.getState() ); - rowData.setCountryFips( state.getCountryFips() ); - rowData.setName( state.getName() ); - rowData.setNcdc( state.getNcdc() ); - rowData.setStateFips( state.getStateFips() ); - - rowData.addAllCellsToMap(); - stateRowDataList.add( rowData ); - _stateRowDataToStateMap.put( rowData, state ); - } - - return stateRowDataList; - } - - private List getRowDataFromProdList() - { - List prodRowDataList = new ArrayList(); - ArcBaseProdJTableRowData rowData = new ArcBaseProdJTableRowData(); - Prod prod = null; - - for ( int i = 0; i < _prodList.size(); i++ ) - { - prod = (Prod) _prodList.get( i ); - rowData = new ArcBaseProdJTableRowData(); - - rowData.setId( prod.getId() ); - rowData.setPmax( prod.getPmax() ); - rowData.setPap( prod.getPap() ); - rowData.setErr( prod.getErr() ); - rowData.setGra( prod.getGra() ); - rowData.setPr1( prod.getPr1() ); - rowData.setNet( prod.getNet() ); - - rowData.addAllCellsToMap(); - prodRowDataList.add( rowData ); - _prodRowDataToProdMap.put( rowData, prod ); - } - return prodRowDataList; - } - - private List getRowDataFromHuc8List() - { - List huc8RowDataList = new ArrayList(); - ArcBaseHuc8JTableRowData rowData = new ArcBaseHuc8JTableRowData(); - Huc8 huc8 = null; - - for ( int i = 0; i < _huc8List.size(); i++ ) - { - huc8 = (Huc8) _huc8List.get( i ); - rowData = new ArcBaseHuc8JTableRowData(); - - rowData.setCode12( huc8.getCode12() ); - rowData.setCode34( huc8.getCode34() ); - rowData.setCode56( huc8.getCode56() ); - rowData.setCode78( huc8.getCode78() ); - rowData.setCode8( huc8.getCode8() ); - rowData.setDescat( huc8.getDescat() ); - - rowData.addAllCellsToMap(); - huc8RowDataList.add( rowData ); - _huc8RowDataToHuc8Map.put( rowData, huc8 ); - } - - return huc8RowDataList; - } - - private List getRowDataFromHuc6List() - { - List huc6RowDataList = new ArrayList(); - ArcBaseHuc6JTableRowData rowData = new ArcBaseHuc6JTableRowData(); - Huc6 huc6 = null; - - for ( int i = 0; i < _huc6List.size(); i++ ) - { - huc6 = (Huc6) _huc6List.get( i ); - rowData = new ArcBaseHuc6JTableRowData(); - - rowData.setCode12( huc6.getCode12() ); - rowData.setCode34( huc6.getCode34() ); - rowData.setCode56( huc6.getCode56() ); - rowData.setCode6( huc6.getCode6() ); - rowData.setDesacct( huc6.getDesacct() ); - - rowData.addAllCellsToMap(); - huc6RowDataList.add( rowData ); - _huc6RowDataToHuc6Map.put( rowData, huc6 ); - } - - return huc6RowDataList; - } - - private List getRowDataFromShefQCList() - { - List shefQCRowDataList = new ArrayList(); - ArcBaseShefQCJTableRowData rowData = new ArcBaseShefQCJTableRowData(); - ShefQC shefQC = null; - - for ( int i = 0; i < _shefQCList.size(); i++ ) - { - shefQC = (ShefQC) _shefQCList.get( i ); - rowData = new ArcBaseShefQCJTableRowData(); - - rowData.setShefQualifierCode( shefQC.getShefQualifierCode() ); - rowData.setPower( shefQC.getPower() ); - rowData.setName( shefQC.getName() ); - - rowData.addAllCellsToMap(); - shefQCRowDataList.add( rowData ); - _shefQCRowDataToShefQCMap.put( rowData, shefQC ); - } - - return shefQCRowDataList; - } - - private List getRowDataFromAgencyList() - { - List agencyRowDataList = new ArrayList(); - ArcBaseAgencyJTableRowData rowData = new ArcBaseAgencyJTableRowData(); - Agency agency = null; - - for ( int i = 0; i < _agencyList.size(); i++ ) - { - agency = (Agency) _agencyList.get( i ); - rowData = new ArcBaseAgencyJTableRowData(); - - rowData.setAgCode( agency.getAgCode() ); - rowData.setAgLoc( agency.getAgLoc() ); - rowData.setDes( agency.getDes() ); - - rowData.addAllCellsToMap(); - agencyRowDataList.add( rowData ); - _agencyRowDataToAgencyMap.put( rowData, agency ); - } - - return agencyRowDataList; - } - - private List getRowDataFromShefPE1List() - { - List shefPe1RowDataList = new ArrayList(); - ArcBaseShefPE1JTableRowData rowData = new ArcBaseShefPE1JTableRowData(); - ShefPE1 shefPe1 = null; - - for ( int i = 0; i < _shefPE1List.size(); i++ ) - { - shefPe1 = (ShefPE1) _shefPE1List.get( i ); - rowData = new ArcBaseShefPE1JTableRowData(); - - rowData.setPe1( shefPe1.getPe1() ); - rowData.setName( shefPe1.getName() ); - - rowData.addAllCellsToMap(); - shefPe1RowDataList.add( rowData ); - _shefPe1RowDataToShefPe1Map.put( rowData, shefPe1 ); - } - - return shefPe1RowDataList; - } - - private List getRowDataFromHuc4List() - { - List huc4RowDataList = new ArrayList(); - ArcBaseHuc4JTableRowData rowData = new ArcBaseHuc4JTableRowData(); - Huc4 huc4 = null; - - for ( int i = 0; i < _huc4List.size(); i++ ) - { - huc4 = (Huc4) _huc4List.get( i ); - rowData = new ArcBaseHuc4JTableRowData(); - - rowData.setCode12( huc4.getCode12() ); - rowData.setCode34( huc4.getCode34() ); - rowData.setCode4( huc4.getCode4() ); - rowData.setDesreg( huc4.getDessubreg() ); - - rowData.addAllCellsToMap(); - huc4RowDataList.add( rowData ); - _huc4RowDataToHuc4Map.put( rowData, huc4 ); - } - - return huc4RowDataList; - } - - private List getRowDataFromRfcList() - { - List rfcRowDataList = new ArrayList(); - ArcBaseRfcJTableRowData rowData = new ArcBaseRfcJTableRowData(); - Rfc rfc = null; - - for ( int i = 0; i < _rfcList.size(); i++ ) - { - rfc = (Rfc) _rfcList.get( i ); - rowData = new ArcBaseRfcJTableRowData(); - - rowData.setRfc( rfc.getRfc() ); - - rowData.addAllCellsToMap(); - rfcRowDataList.add( rowData ); - _rfcRowDataToRfcMap.put( rowData, rfc ); - } - - return rfcRowDataList; - } - - private List getRowDataFromWfoHsaList() - { - List wfoHsaRowDataList = new ArrayList(); - ArcBaseWfoHsaJTableRowData rowData = new ArcBaseWfoHsaJTableRowData(); - WfoHsa wfoHsa = null; - - for ( int i = 0; i < _wfoHsaList.size(); i++ ) - { - wfoHsa = (WfoHsa) _wfoHsaList.get( i ); - rowData = new ArcBaseWfoHsaJTableRowData(); - - rowData.setWfoHsa( wfoHsa.getWfoHsa() ); - - rowData.addAllCellsToMap(); - wfoHsaRowDataList.add( rowData ); - _wfoHsaRowDataToWfoHsaMap.put( rowData, wfoHsa ); - } - - return wfoHsaRowDataList; - } - - private List getRowDataFromShefTsList() - { - List shefTsRowDataList = new ArrayList(); - ArcBaseShefTSJTableRowData rowData = new ArcBaseShefTSJTableRowData(); - ShefTS shefTS = null; - - for ( int i = 0; i < _shefTSList.size(); i++ ) - { - shefTS = (ShefTS) _shefTSList.get( i ); - rowData = new ArcBaseShefTSJTableRowData(); - - rowData.setTS( shefTS.getTs() ); - rowData.setName( shefTS.getName() ); - - rowData.addAllCellsToMap(); - shefTsRowDataList.add( rowData ); - _shefTsRowDataToShefTsMap.put( rowData, shefTS ); - } - - return shefTsRowDataList; - } - - private List getRowDataFromShefExList() - { - List shefExRowDataList = new ArrayList(); - ArcBaseShefExtremumJTableRowData rowData = new ArcBaseShefExtremumJTableRowData(); - ShefExtremum shefEx = null; - - for ( int i = 0; i < _shefExtremumList.size(); i++ ) - { - shefEx = (ShefExtremum) _shefExtremumList.get( i ); - rowData = new ArcBaseShefExtremumJTableRowData(); - - rowData.setExtremum( shefEx.getExtremum() ); - rowData.setName( shefEx.getName() ); - - rowData.addAllCellsToMap(); - shefExRowDataList.add( rowData ); - _shefExRowDataToShefExMap.put( rowData, shefEx ); - } - - return shefExRowDataList; - } - - private List getRowDataFromShefProbList() - { - List shefProbRowDataList = new ArrayList(); - ArcBaseShefProbJTableRowData rowData = new ArcBaseShefProbJTableRowData(); - ShefProb shefProb = null; - - for ( int i = 0; i < _shefProbList.size(); i++ ) - { - shefProb = (ShefProb) _shefProbList.get( i ); - rowData = new ArcBaseShefProbJTableRowData(); - - rowData.setP( shefProb.getP() ); - rowData.setProbability( shefProb.getProbability() ); - rowData.setName( shefProb.getName() ); - - rowData.addAllCellsToMap(); - shefProbRowDataList.add( rowData ); - _shefProbRowDataToShefProbMap.put( rowData, shefProb ); - } - - return shefProbRowDataList; - } - - private List getRowDataFromShefPEList() - { - List shefPeRowDataList = new ArrayList(); - ArcBaseShefPEJTableRowData rowData = new ArcBaseShefPEJTableRowData(); - ShefPE shefPe = null; - - for( int i = 0; i < _shefPeList.size(); i++ ) - { - shefPe = (ShefPE) _shefPeList.get( i ); - rowData = new ArcBaseShefPEJTableRowData(); - - rowData.setPe( shefPe.getPe() ); - rowData.setName( shefPe.getName() ); - rowData.setEngUnit( shefPe.getEngUnit() ); - rowData.setMetUnit( shefPe.getMetUnit() ); - - rowData.addAllCellsToMap(); - shefPeRowDataList.add( rowData ); - _shefPeRowDataToShefPeMap.put( rowData, shefPe ); - } - - return shefPeRowDataList; - } - - private List getRowDataFromShefDurationList() - { - List shefDurRowDataList = new ArrayList(); - ArcBaseShefDurationJTableRowData rowData = new ArcBaseShefDurationJTableRowData(); - ShefDuration shefDur = null; - - for ( int i = 0; i < _shefDurationList.size(); i++ ) - { - shefDur = (ShefDuration) _shefDurationList.get( i ); - rowData = new ArcBaseShefDurationJTableRowData(); - - rowData.setDuration( shefDur.getDuration() ); - rowData.setIDuration( shefDur.getIduration() ); - rowData.setName( shefDur.getName() ); - - rowData.addAllCellsToMap(); - shefDurRowDataList.add( rowData ); - _shefDurRowDataToShefDurMap.put( rowData, shefDur ); - } - - return shefDurRowDataList; - } - - private List getRowDataFromShefPETransList() - { - List shefPETransRowDataList = new ArrayList(); - ArcBaseShefPETransJTableRowData rowData = new ArcBaseShefPETransJTableRowData(); - ShefPETrans shefPETrans = null; - - for ( int i = 0; i < _shefPETransList.size(); i++ ) - { - shefPETrans = (ShefPETrans) _shefPETransList.get( i ); - rowData = new ArcBaseShefPETransJTableRowData(); - - rowData.setPe( shefPETrans.getPe() ); - rowData.setCodePosition( shefPETrans.getCodePosition() ); - rowData.setCodedValue( shefPETrans.getCodedValue() ); - - rowData.addAllCellsToMap(); - shefPETransRowDataList.add( rowData ); - _shefPeTransRowDataToShefPeTransMap.put( rowData, shefPETrans ); - } - - return shefPETransRowDataList; - } - - private List getRowDataFromHuc2List() - { - List huc2RowDataList = new ArrayList(); - ArcBaseHuc2JTableRowData rowData = new ArcBaseHuc2JTableRowData(); - Huc2 huc2 = null; - - for ( int i = 0; i < _huc2List.size(); i++ ) - { - huc2 = (Huc2) _huc2List.get( i ); - rowData = new ArcBaseHuc2JTableRowData(); - - rowData.setCode12( huc2.getCode12() ); - rowData.setCode2( huc2.getCode2() ); - rowData.setDesreg( huc2.getDesreg() ); - - rowData.addAllCellsToMap(); - huc2RowDataList.add( rowData ); - _huc2RowDataToHuc2Map.put( rowData, huc2 ); - } - - return huc2RowDataList; - } - - private List getRowDataFromCountryList() - { - List countryRowDataList = new ArrayList(); - ArcBaseCountryJTableRowData rowData = new ArcBaseCountryJTableRowData(); - Country country = null; - - for ( int i = 0; i < _countryList.size(); i++ ) - { - country = (Country) _countryList.get( i ); - rowData = new ArcBaseCountryJTableRowData(); - - rowData.setCountry( country.getCountry() ); - rowData.setCountryFips( country.getCountryFips() ); - - rowData.addAllCellsToMap(); - countryRowDataList.add( rowData ); - _countryRowDataToCountryMap.put( rowData, country ); - } - - return countryRowDataList; - } - - private List getRowDataListFromModCtrlList() - { - List modCtrlRowDataList = new ArrayList(); - ArcBaseModCtrlJTableRowData rowData = new ArcBaseModCtrlJTableRowData(); - ModCtrl modCtrl = null; - - for ( int i = 0; i < _modCtrlList.size(); i++ ) - { - modCtrl = (ModCtrl) _modCtrlList.get( i ); - rowData = new ArcBaseModCtrlJTableRowData(); - - rowData.setModName( modCtrl.getModName() ); - rowData.setLoad( modCtrl.isLoad() ); - rowData.setFetchOper( modCtrl.isFetchOper() ); - rowData.setFetchSpin( modCtrl.isFetchSpin() ); - - rowData.addAllCellsToMap(); - modCtrlRowDataList.add( rowData ); - getModCtrlRowDataToModCtrlMap().put( rowData, modCtrl ); - } - - return modCtrlRowDataList; - } - - private List getRowDataListFromRaxCrestList() - { - List raxCrestRowDataList = new ArrayList(); - ArcBaseCrestJTableRowData rowData = new ArcBaseCrestJTableRowData(); - RaxCrest raxCrest = null; - - for ( int i = 0; i < _raxCrestList.size(); i++ ) - { - raxCrest = (RaxCrest) _raxCrestList.get( i ); - rowData = new ArcBaseCrestJTableRowData(); - - rowData.setDate( raxCrest.getDateCrest() ); - rowData.setFlow( raxCrest.getFlow() ); - rowData.setStage( raxCrest.getStage() ); - rowData.setTime( raxCrest.getCrestDateTime() ); - - rowData.addAllCellsToMap(); - raxCrestRowDataList.add( rowData ); - getRaxCrestRowDataToRaxCrestMap().put( rowData, raxCrest ); - } - - return raxCrestRowDataList; - } - - private List getRatingCurveRowDataListFromRaxRating( List raxRatingPointList ) - { - List raxRatingRowDataList = new ArrayList(); - ArcBaseRatingJTableRowData rowData = new ArcBaseRatingJTableRowData(); - RaxRatingPoint raxRatingPoint = null; - - for ( int i = 0; i < raxRatingPointList.size(); i++ ) - { - raxRatingPoint = (RaxRatingPoint) raxRatingPointList.get( i ); - rowData = new ArcBaseRatingJTableRowData(); - - rowData.setStage( raxRatingPoint.getStage() ); - rowData.setDischarge( raxRatingPoint.getDischarge() ); - rowData.setShiftedStage( 0 ); - rowData.addAllCellsToMap(); - raxRatingRowDataList.add( rowData ); - } - - return raxRatingRowDataList; - } - - private List getRatingOffsetsRowDataListFromRaxRating( List raxRatingOffsetsList ) - { - List ratingOffsetsRowDataList = new ArrayList(); - ArcBaseRatingOffsetsJTableRowData rowData = new ArcBaseRatingOffsetsJTableRowData(); - RaxRatingOffset raxRatingOffset = null; - - for ( int i = 0; i < raxRatingOffsetsList.size(); i++ ) - { - raxRatingOffset = (RaxRatingOffset) raxRatingOffsetsList.get( i ); - rowData = new ArcBaseRatingOffsetsJTableRowData(); - - rowData.setStage( raxRatingOffset.getStage() ); - rowData.setOffset( raxRatingOffset.getOffset() ); - rowData.addAllCellsToMap(); - ratingOffsetsRowDataList.add( rowData ); - } - - return ratingOffsetsRowDataList; - } - - private List getRowDataListFromRaxLocDataLimitsList() - { - List raxLocDataLimitsRowDataList = new ArrayList(); - ArcBaseDataLimitsJTableRowData rowData = new ArcBaseDataLimitsJTableRowData(); - RaxLocDataLimits locDataLimits = null; - - for ( int i = 0; i < _raxLocDataLimitsList.size(); i++ ) - { - locDataLimits = (RaxLocDataLimits) _raxLocDataLimitsList.get( i ); - rowData = new ArcBaseDataLimitsJTableRowData(); - - rowData.setLid( locDataLimits.getLid() ); - rowData.setPe( locDataLimits.getPe() ); - rowData.setDuration( locDataLimits.getDur() + "/" + locDataLimits.getIdur() ); - rowData.setMonthDayStart( locDataLimits.getMonthDayStart() ); - rowData.setMonthDayEnd( locDataLimits.getMonthDayEnd() ); - rowData.setGrossRangeMin( locDataLimits.getGrossRangeMin() ); - rowData.setGrossRangeMax( locDataLimits.getGrossRangeMax() ); - rowData.setReasonRangeMin( locDataLimits.getReasonRangeMin() ); - rowData.setReasonRangeMax( locDataLimits.getReasonRangeMax() ); - rowData.setRocMax( locDataLimits.getRoc() ); - rowData.setAlertLimit( locDataLimits.getAlertLimit() ); - rowData.setAlertRocLimit( locDataLimits.getAlertRocLimit() ); - rowData.setAlarmLimit( locDataLimits.getAlarmLimit() ); - rowData.setAlarmRocLimit( locDataLimits.getAlarmRocLimit() ); - - rowData.addAllCellsToMap(); - raxLocDataLimitsRowDataList.add( rowData ); - _raxLocDataLimitsRowDataToRaxLocDataLimitsMap.put( rowData, locDataLimits ); - } - - return raxLocDataLimitsRowDataList; - - } - - - private List getRaxDataLimitsListFromRaxDataLimitsRecordsList( List raxDataLimitsRecordsList ) - { - List raxDataLimitsList = new ArrayList(); - RaxDataLimitsRecord record = null; - - for ( int i = 0; i < raxDataLimitsRecordsList.size(); i++ ) - { - record = (RaxDataLimitsRecord) raxDataLimitsRecordsList.get( i ); - - raxDataLimitsList.add( getRaxDataLimitsFromRaxDataLimitsRecord( record ) ); - } - - return raxDataLimitsList; - } - - private List getCountiesListFromCountiesRecordsList( List countiesRecordsList ) - { - List countiesList = new ArrayList(); - CountiesRecord record = null; - - for ( int i = 0; i < countiesRecordsList.size(); i++ ) - { - record = (CountiesRecord) countiesRecordsList.get( i ); - - countiesList.add( new Counties( record ) ); - } - - return countiesList; - } - - private List getStateListFromStateRecordsList( List stateRecordsList ) - { - List stateList = new ArrayList(); - StateRecord record = null; - - for ( int i = 0; i < stateRecordsList.size(); i++ ) - { - record = (StateRecord) stateRecordsList.get( i ); - - stateList.add( new State( record ) ); - } - - return stateList; - } - - private List getProdListFromProdRecordsList( List prodRecordsList ) - { - List prodList = new ArrayList(); - ProdRecord record = null; - - for ( int i = 0; i < prodRecordsList.size(); i++ ) - { - record = (ProdRecord) prodRecordsList.get( i ); - - prodList.add( new Prod( record ) ); - } - - return prodList; - } - - private List getHuc8ListFromHuc8RecordsList( List huc8RecordsList ) - { - List huc8List = new ArrayList(); - Huc8Record record = null; - - for ( int i = 0; i < huc8RecordsList.size(); i++ ) - { - record = (Huc8Record) huc8RecordsList.get( i ); - - huc8List.add( new Huc8( record ) ); - } - - return huc8List; - } - - private List getHuc6ListFromHuc6RecordsList( List huc6RecordsList ) - { - List huc6List = new ArrayList(); - Huc6Record record = null; - - for ( int i = 0; i < huc6RecordsList.size(); i++ ) - { - record = (Huc6Record) huc6RecordsList.get( i ); - - huc6List.add( new Huc6( record ) ); - } - - return huc6List; - } - - private List getShefQCListFromShefQCRecordsList( List shefQCRecordsList ) - { - List shefQCList = new ArrayList(); - ShefqcRecord record = null; - - for ( int i = 0; i < shefQCRecordsList.size(); i++ ) - { - record = (ShefqcRecord) shefQCRecordsList.get( i ); - - shefQCList.add( new ShefQC( record ) ); - } - - return shefQCList; - } - - private List getAgencyListFromAgencyRecordsList( List agencyRecordsList ) - { - List agencyList = new ArrayList(); - AgencyRecord record = null; - - for ( int i = 0; i < agencyRecordsList.size(); i++ ) - { - record = (AgencyRecord) agencyRecordsList.get( i ); - - agencyList.add( new Agency( record ) ); - } - - return agencyList; - } - - private List getShefPE1ListFromShefPE1RecordsList( List shefPe1RecordsList ) - { - List shefPe1List = new ArrayList(); - Shefpe1Record record = null; - - for ( int i = 0; i < shefPe1RecordsList.size(); i++ ) - { - record = (Shefpe1Record) shefPe1RecordsList.get( i ); - - shefPe1List.add( new ShefPE1( record ) ); - } - - return shefPe1List; - } - - private List getHuc4ListFromHuc4RecordsList( List huc4RecordsList ) - { - List huc4List = new ArrayList(); - Huc4Record record = null; - - for ( int i = 0; i < huc4RecordsList.size(); i++ ) - { - record = (Huc4Record) huc4RecordsList.get( i ); - - huc4List.add( new Huc4( record ) ); - } - - return huc4List; - } - - private List getRfcListFromRfcRecordsList( List rfcRecordsList ) - { - List rfcList = new ArrayList(); - RfcRecord record = null; - - for ( int i = 0; i < rfcRecordsList.size(); i++ ) - { - record = (RfcRecord) rfcRecordsList.get( i ); - - rfcList.add( new Rfc( record ) ); - } - - return rfcList; - } - - private List getWfoHsaListFromWfoHsaRecordsList( List wfoHsaRecordsList ) - { - List wfoHsaList = new ArrayList(); - Wfo_hsaRecord record = null; - - for ( int i = 0; i < wfoHsaRecordsList.size(); i++ ) - { - record = (Wfo_hsaRecord) wfoHsaRecordsList.get( i ); - - wfoHsaList.add( new WfoHsa( record ) ); - } - - return wfoHsaList; - } - - private List getShefPETransListFromShefPETransRecordsList( List shefPETransRecordsList ) - { - List shefPETransList = new ArrayList(); - ShefpetransRecord record = null; - - for ( int i = 0; i < shefPETransRecordsList.size(); i++ ) - { - record = (ShefpetransRecord) shefPETransRecordsList.get( i ); - - shefPETransList.add( new ShefPETrans( record ) ); - } - - return shefPETransList; - } - - private List getHuc2ListFromHuc2RecordsList( List huc2RecordsList ) - { - List huc2List = new ArrayList(); - Huc2Record record = null; - - for ( int i = 0; i < huc2RecordsList.size(); i++ ) - { - record = (Huc2Record) huc2RecordsList.get( i ); - - huc2List.add( new Huc2( record ) ); - } - - return huc2List; - } - - private List getCountryListFromCountryRecordsList( List countryRecordsList ) - { - List countryList = new ArrayList(); - CountryRecord record = null; - - for ( int i = 0; i < countryRecordsList.size(); i++ ) - { - record = (CountryRecord) countryRecordsList.get( i ); - - countryList.add( new Country( record ) ); - } - - return countryList; - } - - private List getModCtrlListFromModCtrlRecordsList( List modCtrlRecordsList ) - { - List modCtrlList = new ArrayList(); - ModctrlRecord record = null; - - for ( int i = 0; i < modCtrlRecordsList.size(); i++ ) - { - record = (ModctrlRecord) modCtrlRecordsList.get( i ); - - modCtrlList.add( new ModCtrl( record ) ); - } - - return modCtrlList; - } - - private List getRaxCrestListFromRaxCrestRecordsList( List raxCrestRecordsList ) - { - List raxCrestList = new ArrayList(); - RaxCrestRecord record = null; - - for ( int i = 0; i < raxCrestRecordsList.size(); i++ ) - { - record = (RaxCrestRecord) raxCrestRecordsList.get( i ); - - raxCrestList.add( new RaxCrest( record ) ); - } - return raxCrestList; - } - - private List getRaxRatingListFromRaxRatingRecordsList( List raxRatingRecordsList ) - { - List raxRatingList = new ArrayList(); - RaxRatingRecord record = null; - - for ( int i = 0; i < raxRatingRecordsList.size(); i++ ) - { - record = (RaxRatingRecord) raxRatingRecordsList.get( i ); - - raxRatingList.add( new RaxRating( record ) ); - } - - return raxRatingList; - } - - private List getRaxRatingShiftListFromRaxRatingShiftRecordsList( List raxRatingShiftRecordsList ) - { - List raxRatingShiftList = new ArrayList(); - RaxRatingShiftRecord record = null; - - for ( int i = 0; i < raxRatingShiftRecordsList.size(); i++ ) - { - record = (RaxRatingShiftRecord) raxRatingShiftRecordsList.get( i ); - - raxRatingShiftList.add( new RaxRatingShift( record ) ); - } - - return raxRatingShiftList; - } - - private List getRaxAdjustFactorListFromRaxAdjustFactorRecordsList( List raxAdjustFactorRecordsList ) - { - List raxAdjustFactorsList = new ArrayList(); - RaxAdjustFactorRecord record = null; - - for ( int i = 0; i < raxAdjustFactorRecordsList.size(); i++ ) - { - record = (RaxAdjustFactorRecord) raxAdjustFactorRecordsList.get( i ); - - raxAdjustFactorsList.add( new RaxAdjustFactor( record ) ); - } - - return raxAdjustFactorsList; - } - - private RaxDataLimits getRaxDataLimitsFromRaxDataLimitsRecord( RaxDataLimitsRecord record ) - { - RaxDataLimits raxDataLimits = new RaxDataLimits( record ); - return raxDataLimits; - } - - private List getRaxLocDataLimitsListFromRaxLocDataLimitsRecordsList( List raxLocDataLimitsRecordsList ) - { - List raxLocDataLimitsList = new ArrayList(); - RaxLocDataLimitsRecord record = null; - - for ( int i = 0; i < raxLocDataLimitsRecordsList.size(); i++ ) - { - record = (RaxLocDataLimitsRecord) raxLocDataLimitsRecordsList.get( i ); - - raxLocDataLimitsList.add( new RaxLocDataLimits( record ) ); - } - - return raxLocDataLimitsList; - } - - private List getRaxRiverCritListFromRaxRiverCritRecordsList( List raxRiverCritRecordsList ) - { - List raxRiverCritList = new ArrayList(); - RaxRiverCritRecord record = null; - - for ( int i = 0; i < raxRiverCritRecordsList.size(); i++ ) - { - record = (RaxRiverCritRecord) raxRiverCritRecordsList.get( i ); - raxRiverCritList.add( RaxRiverCrit.getRaxRiverCrit( record ) ); - } - return raxRiverCritList; - } - - public List createIngestFilterRowDataList() - { - CodeTimer timer1 = new CodeTimer(); - timer1.start(); - List raxIngestFilterRecordsList = null; - List raxIngestFilterRowDataList = null; - - raxIngestFilterRecordsList = getRaxIngestFilterRecordsList(); - _raxIngestFilterList = getRaxIngestFilterListFromRaxIngestFilterRecordsList( raxIngestFilterRecordsList ); - - raxIngestFilterRowDataList = getRowDataListFromRaxIngestFilterList(); - - _logger.log( "Finished reading IngestFilter data in " + timer1.stop() ); - return raxIngestFilterRowDataList; - } - - - public List getIngestFilterRowDataList() - { - return _raxIngestFilterRowDataList; - } - - public void initShefExtremumList() - { - _shefExtremumList = new ArrayList(); - List shefExRecordList = new ArrayList(); - ShefexTable table = new ShefexTable( _raxDb ); - ShefexRecord record = null; - ShefExtremum shefExtremum = null; - - try - { - shefExRecordList = table.select( " ORDER BY e " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - for ( int i = 0; i < shefExRecordList.size(); i++ ) - { - record = (ShefexRecord) shefExRecordList.get( i ); - - shefExtremum = new ShefExtremum(); - - shefExtremum.setExtremum( record.getE() ); - shefExtremum.setName( record.getName() ); - - _shefExtremumList.add( shefExtremum ); - _shefExtremumMap.put( shefExtremum.getExtremum(), shefExtremum ); - _shefExtremumMap.put( shefExtremum, shefExtremum.getExtremum() ); - } - } - - public void initShefTSList() - { - _shefTSList = new ArrayList(); - List shefTSRecordList = new ArrayList(); - SheftsTable table = new SheftsTable( _raxDb ); - SheftsRecord record = null; - ShefTS shefTS = null; - - try - { - shefTSRecordList = table.select( " ORDER BY t,s " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < shefTSRecordList.size(); i++ ) - { - record = (SheftsRecord) shefTSRecordList.get( i ); - - shefTS = new ShefTS(); - - shefTS.setTs( record.getT() + record.getS() ); - shefTS.setName( record.getName() ); - - _shefTSList.add( shefTS ); - _shefTSMap.put( shefTS.getTs(), shefTS ); - _shefTSMap.put( shefTS, shefTS.getTs() ); - } - } - - public void initShefProbList() - { - _shefProbList = new ArrayList(); - List shefProbRecordList = new ArrayList(); - ShefProbTable table = new ShefProbTable( _raxDb ); - ShefProbRecord record = null; - ShefProb shefProb = null; - - try - { - shefProbRecordList = table.select( " ORDER BY p " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - for ( int i = 0; i < shefProbRecordList.size(); i++ ) - { - record = (ShefProbRecord) shefProbRecordList.get( i ); - shefProb = new ShefProb(); - - shefProb.setName( record.getName() ); - shefProb.setP( record.getProbcode() ); - shefProb.setProbability( Float.parseFloat( getFormattedDouble( record.getProbability() ) ) ); - - _shefProbList.add( shefProb ); - _shefProbMap.put( shefProb.getP(), shefProb ); - _shefProbMap.put( shefProb, shefProb.getP() ); - } - } - - public void initShefDurationList() - { - _shefDurationList = new ArrayList(); - List shefDurationRecordList = new ArrayList(); - ShefdurTable table = new ShefdurTable( _raxDb ); - ShefdurRecord record = null; - ShefDuration shefDur = null; - - try - { - shefDurationRecordList = table.select( " ORDER BY idur " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < shefDurationRecordList.size(); i++ ) - { - record = (ShefdurRecord) shefDurationRecordList.get( i ); - - shefDur = new ShefDuration( record ); - - _shefDurationList.add( shefDur ); - _shefDurationMap.put( shefDur.getDuration(), shefDur ); - _shefDurationMap.put( shefDur, shefDur.getDuration() ); - } - } - - - public void initShefPeList() - { - _shefPeList = new ArrayList(); - List shefPeRecordList = new ArrayList(); - ShefpeTable table = new ShefpeTable( _raxDb ); - ShefpeRecord record = null; - ShefPE shefPE = null; - - try - { - shefPeRecordList = table.select( " ORDER BY pe1, pe2 " ); - - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < shefPeRecordList.size(); i++ ) - { - record = (ShefpeRecord) shefPeRecordList.get( i ); - - shefPE = new ShefPE(); - - shefPE.setPe( record.getPe1() + record.getPe2() ); - shefPE.setName( record.getName() ); - shefPE.setEngUnit( record.getEng_unit() ); - shefPE.setMetUnit( record.getMet_unit() ); - - _shefPeList.add( shefPE ); - _shefPEMap.put( shefPE.getPe(), shefPE ); - _shefPEMap.put( shefPE, shefPE.getPe() ); - } - } - - /** - * Retrieves a list of RaxLocation objects from the Archive database - * - * @return NONE - */ - private List getRaxLocationRecordsList() - { - List raxLocationRecordsList = null; - RaxLocationTable table = new RaxLocationTable( _raxDb ); - - try - { - raxLocationRecordsList = table.select( " ORDER BY lid " ); - } - catch ( SQLException e ) - { - - } - - return raxLocationRecordsList; - } - - private List getRaxDataLimitsRecordsList() - { - List raxDataLimitsRecordsList = null; - RaxDataLimitsTable table = new RaxDataLimitsTable( _raxDb ); - - try - { - raxDataLimitsRecordsList = table.select( " ORDER BY pe1,pe2 " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxDataLimitsRecordsList; - } - - private List getRaxAdjustFactorRecordsList() - { - List raxAdjustFactorRecordsList = null; - RaxAdjustFactorTable table = new RaxAdjustFactorTable( _raxDb ); - - try - { - raxAdjustFactorRecordsList = table.select( "" ); - } - catch (SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxAdjustFactorRecordsList; - } - - private List getCountiesRecordsList() - { - List countiesRecordsList = null; - CountiesTable table = new CountiesTable( _raxDb ); - - try - { - countiesRecordsList = table.select( " ORDER BY county" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return countiesRecordsList; - } - - private List getStateRecordsListOrderedByCountryState() - { - List stateRecordsList = null; - StateTable table = new StateTable( _raxDb ); - - try - { - stateRecordsList = table.select( "ORDER BY countryfips, state" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return stateRecordsList; - } - - private List getWfoHsaRecordsListOrderedByWfo() - { - List wfoHsaRecordsList = null; - Wfo_hsaTable table = new Wfo_hsaTable( _raxDb ); - - try - { - wfoHsaRecordsList = table.select( "ORDER BY wfo_hsa" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return wfoHsaRecordsList; - } - - private List getStateRecordsList() - { - List stateRecordsList = null; - StateTable table = new StateTable( _raxDb ); - - try - { - stateRecordsList = table.select( "ORDER BY state" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return stateRecordsList; - } - - private List getRfcRecordsList() - { - List rfcRecordsList = null; - RfcTable table = new RfcTable( _raxDb ); - - try - { - rfcRecordsList = table.select( " ORDER BY rfc " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return rfcRecordsList; - } - - private List getWfoHsaRecordsList() - { - List wfoHsaRecordsList = null; - Wfo_hsaTable table = new Wfo_hsaTable( _raxDb ); - - try - { - wfoHsaRecordsList = table.select( " ORDER BY wfo_hsa " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return wfoHsaRecordsList; - } - - private List getShefPETransRecordsList() - { - List shefPETransRecordsList = null; - ShefpetransTable table = new ShefpetransTable( _raxDb ); - - try - { - shefPETransRecordsList = table.select( " ORDER BY pe1, pe2 " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return shefPETransRecordsList; - } - - private List getHuc2RecordsList() - { - List huc2RecordsList = null; - Huc2Table table = new Huc2Table( _raxDb ); - - try - { - huc2RecordsList = table.select( " ORDER BY code12" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return huc2RecordsList; - } - - private List getProdRecordsList() - { - List prodRecordsList = null; - ProdTable table = new ProdTable( _raxDb ); - - try - { - prodRecordsList = table.select( " ORDER BY id " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return prodRecordsList; - } - - private List getHuc8RecordsList() - { - List huc8RecordsList = null; - Huc8Table table = new Huc8Table( _raxDb ); - - try - { - huc8RecordsList = table.select( " ORDER BY code12" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return huc8RecordsList; - } - - private List getHuc6RecordsList() - { - List huc6RecordsList = null; - Huc6Table table = new Huc6Table( _raxDb ); - - try - { - huc6RecordsList = table.select( " ORDER BY code12" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return huc6RecordsList; - } - - private List getShefQCRecordsList() - { - List shefQCRecordsList = null; - ShefqcTable table = new ShefqcTable( _raxDb ); - - try - { - shefQCRecordsList = table.select( " ORDER BY power " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return shefQCRecordsList; - } - - private List getAgencyRecordsList() - { - List agencyRecordsList = null; - AgencyTable table = new AgencyTable( _raxDb ); - - try - { - agencyRecordsList = table.select( " ORDER BY agcode " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return agencyRecordsList; - } - - private List getPE1RecordsList() - { - List shefPe1RecordsList = null; - Shefpe1Table table = new Shefpe1Table( _raxDb ); - - try - { - shefPe1RecordsList = table.select( " ORDER BY PE1 " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return shefPe1RecordsList; - } - - private List getHuc4RecordsList() - { - List huc4RecordsList = null; - Huc4Table table = new Huc4Table( _raxDb ); - - try - { - huc4RecordsList = table.select( " ORDER BY code12" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return huc4RecordsList; - } - - private List getCountryRecordsList() - { - List countryRecordsList = null; - CountryTable table = new CountryTable( _raxDb ); - - try - { - countryRecordsList = table.select( " ORDER BY country" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return countryRecordsList; - } - - private List getModCtrlRecordsList() - { - List modCtrlRecordsList = null; - ModctrlTable table = new ModctrlTable( _raxDb ); - - try - { - modCtrlRecordsList = table.select( " ORDER BY mod_name" ); - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return modCtrlRecordsList; - } - - private List getRaxCrestRecordsList( String lid ) - { - List raxCrestRecordsList = null; - RaxCrestTable table = new RaxCrestTable( _raxDb ); - - try - { - raxCrestRecordsList = table.select( " WHERE LID = '" + lid + "' " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxCrestRecordsList; - } - - private List getRaxRatingRecordsList( String lid ) - { - List raxRatingRecordsList = null; - RaxRatingTable table = new RaxRatingTable( _raxDb ); - - try - { - raxRatingRecordsList = table.select( " WHERE LID = '" + lid + "' " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxRatingRecordsList; - } - - private List getRaxRatingShiftRecordsList( String lid ) - { - List raxRatingShiftRecordsList = null; - RaxRatingShiftTable table = new RaxRatingShiftTable( _raxDb ); - - try - { - raxRatingShiftRecordsList = table.select( " WHERE LID = '" + lid + "' " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxRatingShiftRecordsList; - } - - private List getRaxLocDataLimitsRecordsList() - { - List raxLocDataLimitsRecordsList = null; - RaxLocDataLimitsTable table = new RaxLocDataLimitsTable( _raxDb ); - - try - { - raxLocDataLimitsRecordsList = table.select( " ORDER BY pe1, pe2, lid " ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxLocDataLimitsRecordsList; - } - - private List getRaxRiverCritRecordsList( String lid ) - { - List raxRiverCritRecordsList = null; - RaxRiverCritTable table = new RaxRiverCritTable( _raxDb ); - - try - { - raxRiverCritRecordsList = table.select( " WHERE LID='" + lid + "'" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return raxRiverCritRecordsList; - } - - public List getShefPeList() - { - return _shefPeList; - } - - public List getShefProbList() - { - return _shefProbList; - } - - public List getShefDurationList() - { - return _shefDurationList; - } - - public List getShefTSList() - { - return _shefTSList; - } - - public List getShefExtremumList() - { - return _shefExtremumList; - } - public Map getRaxIngestFilterRowDataToRaxIngestFilterMap() - { - return _raxIngestFilterRowDataToRaxIngestFilterMap; - } - - public Map getShefPEMap() - { - return _shefPEMap; - } - - public Map getShefDurationMap() - { - return _shefDurationMap; - } - - public Map getShefTSMap() - { - return _shefTSMap; - } - - public Map getShefExtremumMap() - { - return _shefExtremumMap; - } - - public Map getShefProbMap() - { - return _shefProbMap; - } - - public Map getRaxDataLimitsRowDataToRaxDataLimitsMap() - { - return _raxDataLimitsRowDataToRaxDataLimitsMap; - } - - public Map getRaxLocDataLimitsRowDataToRaxLocDataLimitsMap() - { - return _raxLocDataLimitsRowDataToRaxLocDataLimitsMap; - } - - public Map getRaxAdjustFactorRowDataToRaxAdjustFactorMap() - { - return _raxAdjustFactorRowDataToRaxAdjustFactorMap; - } - - public Map getRaxCrestRowDataToRaxCrestMap() - { - return _raxCrestRowDataToRaxCrestMap; - } - - public void setEndDateForLidInReservoir( RaxReservoir reservoir ) - { - RaxReservoirTable table = new RaxReservoirTable( _raxDb ); - RaxReservoirRecord record = null; - RaxReservoirRecord newRecord = null; - List raxReservoirRecordList = new ArrayList(); - StringDataConverter converter = new StringDataConverter(); - String where = " WHERE LID = '" + reservoir.getLid() + "' "; - String endDateString = DbTimeHelper.getDateStringFromLongTime( System.currentTimeMillis() ); - long endDate = converter.getLongDateValue( endDateString ); - - try - { - raxReservoirRecordList = table.select( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < raxReservoirRecordList.size(); i++ ) - { - record = (RaxReservoirRecord) raxReservoirRecordList.get( i ); - - if ( ! - ( ( record.getLid().equalsIgnoreCase( reservoir.getLid() ) ) && - ( record.getSbd() == reservoir.getBeginDate() ) ) ) - { - if ( record.getSed() == DbTable.getNullLong() ) // End date is null - { - newRecord = new RaxReservoirRecord( record ); - newRecord.setSed( endDate ); - try - { - table.update( record, newRecord ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - } - } - } - - public void setEndDateForLidInLocation( RaxLocation raxLocation ) - { - RaxLocationTable table = new RaxLocationTable( _raxDb ); - RaxLocationRecord record = null; - RaxLocationRecord newRecord = null; - List raxLocationRecordList = new ArrayList(); - StringDataConverter converter = new StringDataConverter(); - String where = " WHERE LID='" + raxLocation.getLid() + "' "; - String endDateString = DbTimeHelper.getDateStringFromLongTime( System.currentTimeMillis() ); - long endDate = converter.getLongDateValue( endDateString ); - - try - { - raxLocationRecordList = table.select( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - for ( int i = 0; i < raxLocationRecordList.size(); i++ ) - { - record = (RaxLocationRecord) raxLocationRecordList.get( i ); - - if ( ! - ( ( record.getLid().equalsIgnoreCase( raxLocation.getLid() ) ) && - ( record.getSbd() == raxLocation.getBeginDate() ) ) ) - { - if ( record.getSed() == DbTable.getNullLong() ) // End date is null - { - newRecord = new RaxLocationRecord( record ); - newRecord.setSed( endDate ); - try - { - table.update( record, newRecord ); - } - catch ( SQLException e ){} - } - } - } - } - - public boolean doesRaxLocationExist( RaxLocation raxLocation ) - { - boolean exists = false; - - RaxLocationTable table = new RaxLocationTable( _raxDb ); - List raxLocationList = null; - StringDataConverter converter = new StringDataConverter(); - - String where = " WHERE LID = '" + raxLocation.getLid() + "' AND SBD = '" + converter.getDateStringFromDateLong( raxLocation.getBeginDate() ) + "' "; - - try - { - raxLocationList = table.select( where ); - if ( ! raxLocationList.isEmpty() ) - { - exists = true; - } - } - catch ( SQLException e ){} - - return exists; - } - - public boolean doesRaxReservoirExist( RaxReservoir raxReservoir ) - { - boolean exists = false; - - RaxReservoirTable table = new RaxReservoirTable( _raxDb ); - List raxReservoirList = null; - StringDataConverter converter = new StringDataConverter(); - - String where = " WHERE LID = '" + raxReservoir.getLid() + "' AND SBD = '" + converter.getDateStringFromDateLong( raxReservoir.getBeginDate() ) + "' "; - - try - { - raxReservoirList = table.select( where ); - if ( ! raxReservoirList.isEmpty() ) - { - exists = true; - } - } - catch ( SQLException e ){} - - return exists; - } - - public boolean doesNewerRaxLocationExist( RaxLocation raxLocation ) - { - boolean exists = false; - - RaxLocationTable table = new RaxLocationTable( _raxDb ); - List raxLocationList = null; - StringDataConverter converter = new StringDataConverter(); - RaxLocationRecord raxLocationRecord = null; - - String where = " WHERE LID = '" + raxLocation.getLid() + "' AND SED IS NULL "; - - try - { - raxLocationList = table.select( where ); - - for ( int i = 0; i < raxLocationList.size(); i++ ) - { - raxLocationRecord = (RaxLocationRecord) raxLocationList.get( i ); - if ( raxLocationRecord.getSbd() > raxLocation.getBeginDate() ) - { - exists = true; - break; - } - } - } - catch ( SQLException e ){} - - return exists; - } - - public boolean doesNewerRaxReservoirExist( RaxReservoir reservoir ) - { - boolean exists = false; - - RaxReservoirTable table = new RaxReservoirTable( _raxDb ); - List raxReservoirList = null; - StringDataConverter converter = new StringDataConverter(); - RaxReservoirRecord raxReservoirRecord = null; - - String where = " WHERE LID = '" + reservoir.getLid() + "' AND SED IS NULL "; - - try - { - raxReservoirList = table.select( where ); - - for ( int i = 0; i < raxReservoirList.size(); i++ ) - { - raxReservoirRecord = (RaxReservoirRecord) raxReservoirList.get( i ); - if ( raxReservoirRecord.getSbd() > reservoir.getBeginDate() ) - { - exists = true; - break; - } - } - } - catch ( SQLException e ){} - - return exists; - } - - public String getStateCountryFipsString( StateRecord record ) - { - String stateCountryFips = record.getState() + " / " + record.getCountryfips(); - - return stateCountryFips; - } - - public String getStateCountryFipsString( Counties counties ) - { - String stateCountryFips = counties.getState() + " / " + counties.getCountryFips(); - - return stateCountryFips; - } - - - public List getStateCountryFipsListFromStateRecordsList( List stateRecordsList ) - { - List stateCountryFipsList = new ArrayList(); - - for ( int i = 0 ; i < stateRecordsList.size(); i++ ) - { - StateRecord record = (StateRecord) stateRecordsList.get( i ); - stateCountryFipsList.add( getStateCountryFipsString( record ) ); - _stateCountryFipsStringToStateRecordMap.put( getStateCountryFipsString( record ), record ); - } - - return stateCountryFipsList; - } - - public List getWfoListFromWfoHsaRecordsList( List wfoHsaRecordsList ) - { - List wfoList = new ArrayList(); - - for ( int i = 0; i < wfoHsaRecordsList.size(); i++ ) - { - Wfo_hsaRecord record = (Wfo_hsaRecord) wfoHsaRecordsList.get( i ); - wfoList.add( record.getWfo_hsa() ); - } - - return wfoList; - } - - public List getStateCountryFipsList() - { - List stateRecordsList = getStateRecordsListOrderedByCountryState(); - List stateCountryFipsList = getStateCountryFipsListFromStateRecordsList( stateRecordsList ); - - return stateCountryFipsList; - } - - public List getWfoList() - { - List wfoHsaRecordsList = getWfoHsaRecordsListOrderedByWfo(); - List wfoList = getWfoListFromWfoHsaRecordsList( wfoHsaRecordsList ); - - return wfoList; - } - -// ------------------------------ Save to Database Methods ------------------------ - - public void saveRaxCrestToDatabase( RaxCrest raxCrest ) - { - RaxCrestTable table = new RaxCrestTable( _raxDb ); - RaxCrestRecord record = RaxCrest.getRaxCrestRecord( raxCrest ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void saveRaxIngestFilter( RaxIngestFilter raxIngestFilter ) - { - RaxIngestFilterTable table = new RaxIngestFilterTable( _raxDb ); - RaxIngestFilterRecord record = RaxIngestFilter.getRaxIngestFilterRecord( raxIngestFilter ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public boolean saveCounties( Counties counties ) - { - CountiesTable table = new CountiesTable( _raxDb ); - CountiesRecord record = Counties.getCountiesRecord( counties ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveState( State state ) - { - StateTable table = new StateTable( _raxDb ); - StateRecord record = State.getStateRecord( state ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveProd( Prod prod ) - { - ProdTable table = new ProdTable( _raxDb ); - ProdRecord record = Prod.getProdRecord( prod ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - public boolean saveHuc8( Huc8 huc8 ) - { - Huc8Table table = new Huc8Table( _raxDb ); - Huc8Record record = Huc8.getHuc8Record( huc8 ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveHuc6( Huc6 huc6 ) - { - Huc6Table table = new Huc6Table( _raxDb ); - Huc6Record record = Huc6.getHuc6Record( huc6 ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveHuc4( Huc4 huc4 ) - { - Huc4Table table = new Huc4Table( _raxDb ); - Huc4Record record = Huc4.getHuc4Record( huc4 ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveRfc( Rfc rfc ) - { - RfcTable table = new RfcTable( _raxDb ); - RfcRecord record = Rfc.getRfcRecord( rfc ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveWfoHsa( WfoHsa wfoHsa ) - { - Wfo_hsaTable table = new Wfo_hsaTable( _raxDb ); - Wfo_hsaRecord record = WfoHsa.getWfoHsaRecord( wfoHsa ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefProb( ShefProb shefProb ) - { - ShefprobTable table = new ShefprobTable( _raxDb ); - ShefprobRecord record = ShefProb.getShefProbRecord( shefProb ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefQC( ShefQC shefQC ) - { - ShefqcTable table = new ShefqcTable( _raxDb ); - ShefqcRecord record = ShefQC.getShefQCRecord( shefQC ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefPe( ShefPE shefPe ) - { - ShefpeTable table = new ShefpeTable( _raxDb ); - ShefpeRecord record = ShefPE.getShefPeRecord( shefPe ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveAgency( Agency agency ) - { - AgencyTable table = new AgencyTable( _raxDb ); - AgencyRecord record = Agency.getAgencyRecord( agency ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefPe1( ShefPE1 shefPe1 ) - { - Shefpe1Table table = new Shefpe1Table( _raxDb ); - Shefpe1Record record = ShefPE1.getShefPe1Record( shefPe1 ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefPeTrans( ShefPETrans shefPETrans ) - { - ShefpetransTable table = new ShefpetransTable( _raxDb ); - ShefpetransRecord record = ShefPETrans.getShefPeTransRecord( shefPETrans ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefTs( ShefTS shefTS ) - { - SheftsTable table = new SheftsTable( _raxDb ); - SheftsRecord record = ShefTS.getShefTSRecord( shefTS ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefEx( ShefExtremum shefEx ) - { - ShefexTable table = new ShefexTable( _raxDb ); - ShefexRecord record = ShefExtremum.getShefExRecord( shefEx ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveShefDur( ShefDuration shefDur ) - { - ShefdurTable table = new ShefdurTable( _raxDb ); - ShefdurRecord record = ShefDuration.getShefDurRecord( shefDur ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveHuc2( Huc2 huc2 ) - { - Huc2Table table = new Huc2Table( _raxDb ); - Huc2Record record = Huc2.getHuc2Record( huc2 ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveCountry( Country country ) - { - CountryTable table = new CountryTable( _raxDb ); - CountryRecord record = Country.getCountryRecord( country ); - boolean saved = false; - - try - { - table.insert( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - - - public boolean saveModCtrl( ModCtrl modCtrl ) - { - ModctrlTable table = new ModctrlTable( _raxDb ); - ModctrlRecord record = ModCtrl.getModCtrlRecord( modCtrl ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveRaxDataLimits( RaxDataLimits raxDataLimits ) - { - RaxDataLimitsTable table = new RaxDataLimitsTable( _raxDb ); - RaxDataLimitsRecord record = RaxDataLimits.getRaxDataLimitsRecord( raxDataLimits ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - - public boolean saveRaxLocDataLimits( RaxLocDataLimits raxLocDataLimits ) - { - RaxLocDataLimitsTable table = new RaxLocDataLimitsTable( _raxDb ); - RaxLocDataLimitsRecord record = RaxLocDataLimits.getRaxLocDataLimitsRecord( raxLocDataLimits ); - boolean saved = false; - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public boolean saveRaxRiverCrit( RaxRiverCrit raxRiverCrit ) - { - RaxRiverCritTable table = new RaxRiverCritTable( _raxDb ); - RaxRiverCritRecord record = RaxRiverCrit.getRaxRiverCritRecord( raxRiverCrit ); - boolean saved = false; - - try - { - table.insertOrUpdate( record ); - saved = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return saved; - } - - public void saveRaxAdjustFactor( RaxAdjustFactor raxAdjustFactor ) - { - RaxAdjustFactorTable table = new RaxAdjustFactorTable( _raxDb ); - RaxAdjustFactorRecord record = RaxAdjustFactor.getRaxAdjustFactorRecord( raxAdjustFactor ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public boolean insertNewLocation( RaxLocation raxLocation ) - { - RaxLocationTable table = new RaxLocationTable( _raxDb ); - RaxLocationRecord record = RaxLocation.getRaxLocationRecord( raxLocation ); - int numberOfRecordsInserted = -9999; - boolean inserted = false; - - try - { - numberOfRecordsInserted = table.insert( record ); - if ( numberOfRecordsInserted == 1 ) - { - inserted = true; - } - } - catch ( SQLException e ) - { - } - - return inserted; - } - - public void saveLocation( RaxLocation raxLocation ) - { - RaxLocationTable table = new RaxLocationTable( _raxDb ); - RaxLocationRecord record = RaxLocation.getRaxLocationRecord( raxLocation ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void saveReservoir( RaxReservoir raxReservoir ) - { - RaxReservoirTable table = new RaxReservoirTable( _raxDb ); - RaxReservoirRecord record = RaxReservoir.getRaxReservoirRecord( raxReservoir ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void saveRaxRatingShift( RaxRatingShift raxRatingShift ) - { - RaxRatingShiftTable table = new RaxRatingShiftTable( _raxDb ); - RaxRatingShiftRecord record = RaxRatingShift.getRaxRatingShiftRecord( raxRatingShift ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void saveRaxRating( RaxRating raxRating ) - { - CustomRaxRatingTable table = new CustomRaxRatingTable( _raxDb ); - RaxRatingRecord record = RaxRating.getRaxRatingRecord( raxRating ); - _logger.log( "RECORD = " + record ); - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public boolean saveAverage( Average avg ) - { - boolean success = false; - - AvgTable table = new AvgTable( _raxDb ); - AvgRecord record = Average.getAverageRecord( avg ); - - try - { - table.insertOrUpdate( record ); - success = true; - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return success; - } - - public boolean saveSlopeProfile( SlopeProfile slopeProfile ) - { - boolean success = false; - - SlopeprofileTable table = new SlopeprofileTable( _raxDb ); - SlopeprofileRecord record = SlopeProfile.getSlopeProfileRecord( slopeProfile ); - - try - { - table.insertOrUpdate( record ); - success = true; - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return success; - } - - public boolean saveSensok( Sensok sensok ) - { - boolean success = false; - - SensokTable table = new SensokTable( _raxDb ); - SensokRecord record = Sensok.getSensokRecord( sensok ); - - try - { - table.insertOrUpdate( record ); - success = true; - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return success; - } - -// ------------------------------ Delete from Database Methods ------------------------ - - public void deleteRaxCrestFromDatabase( RaxCrest raxCrest ) - { - RaxCrestTable table = new RaxCrestTable( _raxDb ); - RaxCrestRecord record = RaxCrest.getRaxCrestRecord( raxCrest ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteCountiesFromDataBase( Counties counties ) - { - CountiesTable table = new CountiesTable( _raxDb ); - CountiesRecord record = Counties.getCountiesRecord( counties ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteStateFromDataBase( State state ) - { - StateTable table = new StateTable( _raxDb ); - StateRecord record = State.getStateRecord( state ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteProdFromDataBase( Prod prod ) - { - ProdTable table = new ProdTable( _raxDb ); - ProdRecord record = Prod.getProdRecord( prod ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteHuc8FromDataBase( Huc8 huc8 ) - { - Huc8Table table = new Huc8Table( _raxDb ); - Huc8Record record = Huc8.getHuc8Record( huc8 ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteHuc6FromDataBase( Huc6 huc6 ) - { - Huc6Table table = new Huc6Table( _raxDb ); - Huc6Record record = Huc6.getHuc6Record( huc6 ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteHuc4FromDataBase( Huc4 huc4 ) - { - Huc4Table table = new Huc4Table( _raxDb ); - Huc4Record record = Huc4.getHuc4Record( huc4 ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRfcFromDataBase( Rfc rfc ) - { - RfcTable table = new RfcTable( _raxDb ); - RfcRecord record = Rfc.getRfcRecord( rfc ); - - try - { - table.delete( record ); - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteWfoHsaFromDataBase( WfoHsa wfoHsa ) - { - Wfo_hsaTable table = new Wfo_hsaTable( _raxDb ); - Wfo_hsaRecord record = WfoHsa.getWfoHsaRecord( wfoHsa ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteAgencyFromDataBase( Agency agency ) - { - AgencyTable table = new AgencyTable( _raxDb ); - AgencyRecord record = Agency.getAgencyRecord( agency ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefPe1FromDataBase( ShefPE1 shefPe ) - { - Shefpe1Table table = new Shefpe1Table( _raxDb ); - Shefpe1Record record = ShefPE1.getShefPe1Record( shefPe ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefProbFromDataBase( ShefProb shefProb ) - { - ShefprobTable table = new ShefprobTable( _raxDb ); - ShefprobRecord record = ShefProb.getShefProbRecord( shefProb ); - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefQCFromDataBase( ShefQC shefQC ) - { - ShefqcTable table = new ShefqcTable( _raxDb ); - ShefqcRecord record = ShefQC.getShefQCRecord( shefQC ); - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefPeFromDataBase( ShefPE shefPe ) - { - ShefpeTable table = new ShefpeTable( _raxDb ); - ShefpeRecord record = ShefPE.getShefPeRecord( shefPe ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefPeTransFromDataBase( ShefPETrans shefPETrans ) - { - ShefpetransTable table = new ShefpetransTable( _raxDb ); - ShefpetransRecord record = ShefPETrans.getShefPeTransRecord( shefPETrans ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefTsFromDataBase( ShefTS shefTS ) - { - SheftsTable table = new SheftsTable( _raxDb ); - SheftsRecord record = ShefTS.getShefTSRecord( shefTS ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefExtremumFromDataBase( ShefExtremum shefEx ) - { - ShefexTable table = new ShefexTable( _raxDb ); - ShefexRecord record = ShefExtremum.getShefExRecord( shefEx ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteShefDurationFromDataBase( ShefDuration shefDur ) - { - ShefdurTable table = new ShefdurTable( _raxDb ); - ShefdurRecord record = ShefDuration.getShefDurRecord( shefDur ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteHuc2FromDataBase( Huc2 huc2 ) - { - Huc2Table table = new Huc2Table( _raxDb ); - Huc2Record record = Huc2.getHuc2Record( huc2 ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteCountryFromDataBase( Country country ) - { - CountryTable table = new CountryTable( _raxDb ); - CountryRecord record = Country.getCountryRecord( country ); - String where = " WHERE Country='" + record.getCountry() + "' AND CountryFips='" + record.getCountryfips() + "'"; - - try - { - table.delete( where ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteModCtrlFromDataBase( ModCtrl modCtrl ) - { - ModctrlTable table = new ModctrlTable( _raxDb ); - ModctrlRecord record = ModCtrl.getModCtrlRecord( modCtrl ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRaxReservoirFromDatabase( RaxReservoir raxReservoir ) - { - RaxReservoirTable table = new RaxReservoirTable( _raxDb ); - RaxReservoirRecord record = RaxReservoir.getRaxReservoirRecord( raxReservoir ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRaxIngestFilterFromDatabase( RaxIngestFilter raxIngestFilter ) - { - RaxIngestFilterTable table = new RaxIngestFilterTable( _raxDb ); - RaxIngestFilterRecord record = RaxIngestFilter.getRaxIngestFilterRecord( raxIngestFilter ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRaxLocDataLimitsFromDatabase( RaxLocDataLimits raxLocDataLimits ) - { - RaxLocDataLimitsTable table = new RaxLocDataLimitsTable( _raxDb ); - RaxLocDataLimitsRecord record = RaxLocDataLimits.getRaxLocDataLimitsRecord( raxLocDataLimits ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRaxDataLimitsFromDatabase( RaxDataLimits raxDataLimits ) - { - RaxDataLimitsTable table = new RaxDataLimitsTable( _raxDb ); - RaxDataLimitsRecord record = RaxDataLimits.getRaxDataLimitsRecord( raxDataLimits ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRaxRiverCrit( RaxRiverCrit raxRiverCrit ) - { - RaxRiverCritTable table = new RaxRiverCritTable( _raxDb ); - RaxRiverCritRecord record = RaxRiverCrit.getRaxRiverCritRecord( raxRiverCrit ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public void deleteRaxAdjustFactorFromDatabase( RaxAdjustFactor raxAdjustFactor ) - { - RaxAdjustFactorTable table = new RaxAdjustFactorTable( _raxDb ); - RaxAdjustFactorRecord record = RaxAdjustFactor.getRaxAdjustFactorRecord( raxAdjustFactor ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - } - - public boolean deleteAverageFromDatabase( Average average ) - { - boolean deleted = false; - - AvgTable table = new AvgTable( _raxDb ); - AvgRecord record = Average.getAverageRecord( average ); - - try - { - table.delete( record ); - deleted = true; - } - catch( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return deleted; - } - - public boolean deleteSlopeProfileFromDatabase( SlopeProfile slopeProfile ) - { - boolean deleted = false; - - SlopeprofileTable table = new SlopeprofileTable( _raxDb ); - SlopeprofileRecord record = SlopeProfile.getSlopeProfileRecord( slopeProfile ); - - try - { - table.delete( record ); - deleted = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return deleted; - } - - public boolean deleteSensokFromDatabase( Sensok sensok ) - { - boolean deleted = false; - - SensokTable table = new SensokTable( _raxDb ); - SensokRecord record = Sensok.getSensokRecord( sensok ); - - try - { - table.delete( record ); - deleted = true; - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - return deleted; - } - - public RaxSyncDataMgr getRaxSyncDataMgr() - { - return _raxSyncDataMgr; - } - - - public RaxLocation getRaxLocation( String lid ) - { - RaxLocation raxLocation = null; - RaxLocationRecord record = null; - RaxLocationTable table = new RaxLocationTable( _raxDb ); - List recordList = null; - - try - { - recordList = table.select( " WHERE LID ='" + lid + "'" ); - } - catch ( SQLException e ) - { - e.printStackTrace( _logger.getPrintWriter() ); - } - - if ( ( recordList != null ) && ( ! recordList.isEmpty() ) ) - { - record = (RaxLocationRecord) recordList.get( 0 ); - raxLocation = new RaxLocation( record ); - } - - return raxLocation; - } - - public void setRaxIngestFilterRowDataList( List rowDataList ) - { - _raxIngestFilterRowDataList = rowDataList; - } - - public Map getModCtrlRowDataToModCtrlMap() - { - return _modCtrlRowDataToModCtrlMap; - } - - public Map getCountryRowDataToCountryMap() - { - return _countryRowDataToCountryMap; - } - - public Map getStateRowDataToStateMap() - { - return _stateRowDataToStateMap; - } - - public Map getCountiesRowDataToCountiesMap() - { - return _countiesRowDataToCountiesMap; - } - - public Map getHuc2RowDataToHuc2Map() - { - return _huc2RowDataToHuc2Map; - } - - public Map getHuc4RowDataToHuc4Map() - { - return _huc4RowDataToHuc4Map; - } - - public Map getHuc6RowDataToHuc6Map() - { - return _huc6RowDataToHuc6Map; - } - - public Map getHuc8RowDataToHuc8Map() - { - return _huc8RowDataToHuc8Map; - } - - public Map getWfoHsaRowDataToWfoHsaMap() - { - return _wfoHsaRowDataToWfoHsaMap; - } - - public Map getRfcRowDataToRfcMap() - { - return _rfcRowDataToRfcMap; - } - - public Map getShefDurRowDataToShefDurMap() - { - return _shefDurRowDataToShefDurMap; - } - - public Map getShefExRowDataToShefExMap() - { - return _shefExRowDataToShefExMap; - } - - public Map getShefPeTransRowDataToShefPeTransMap() - { - return _shefPeTransRowDataToShefPeTransMap; - } - - public Map getShefPeRowDataToShefPeMap() - { - return _shefPeRowDataToShefPeMap; - } - - public Map getShefPe1RowDataToShefPe1Map() - { - return _shefPe1RowDataToShefPe1Map; - } - - public Map getShefProbRowDataToShefProbMap() - { - return _shefProbRowDataToShefProbMap; - } - - public Map getShefQCRowDataToShefQCMap() - { - return _shefQCRowDataToShefQCMap; - } - - public Map getShefTsRowDataToShefTsMap() - { - return _shefTsRowDataToShefTsMap; - } - - public Map getAgencyRowDataToAgencyMap() - { - return _agencyRowDataToAgencyMap; - } - - public Map getProdRowDataToProdMap() - { - return _prodRowDataToProdMap; - } - - public Map getStateCountryFipsStringToStateMap() - { - return _stateCountryFipsStringToStateRecordMap; - } -} - diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/db/CustomRaxRatingTable.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/db/CustomRaxRatingTable.java deleted file mode 100644 index a6b82347ca..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/db/CustomRaxRatingTable.java +++ /dev/null @@ -1,153 +0,0 @@ -package ohd.hseb.raxbase.db; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.raxdb.generated.RaxRatingRecord; -import ohd.hseb.raxdb.generated.RaxRatingTable; - -public class CustomRaxRatingTable extends RaxRatingTable -{ -// ----------------------------------------------------------------- -// RaxRatingTable() - constructor to set statement variable and initialize -// number of records found to zero -//----------------------------------------------------------------- - public CustomRaxRatingTable(Database database) - { - //Constructor calls DbTable's constructor - super(database); - setTableName("rating"); - } - - private String createArrayString(String origArrayString) - { - String arrayString = "null"; - - if (origArrayString != null) - { - arrayString = "'" + origArrayString + "'"; - } - - return arrayString; - } - -// ----------------------------------------------------------------- -// insert() - this method is called with a RaxRatingRecord object and.. -//----------------------------------------------------------------- - public int insert(RaxRatingRecord record) throws SQLException - { - int returnCode=-999; - - // Create a SQL insert statement and issue it - // construct the insert statement - PreparedStatement insertStatement = getConnection().prepareStatement( - " INSERT INTO rating VALUES (?, ?, ?, ?, ?, ?, ?, ?, " + - createArrayString(record.getStgflow()) + ", ?, ?, " + - createArrayString(record.getOffsets()) + ", ? )"); - - // " UPDATE rating SET lid = ?, pe1 = ?, pe2 = ?, tbl = ?, valid_date = ?, src = ?, othagid = ?, rfs_input = ?, stgflow = " + newRecord.getStgflow() + " , units = ?, interpolate = ?, offsets = + " + newRecord.getOffsets() + " allowstg = ? " + oldRecord.getWhereString() ); - - setString(insertStatement, 1, record.getLid()); - setString(insertStatement, 2, record.getPe1()); - setString(insertStatement, 3, record.getPe2()); - setDouble(insertStatement, 4, record.getTbl()); - setTimeStamp(insertStatement, 5, record.getValid_date()); - setString(insertStatement, 6, record.getSrc()); - setString(insertStatement, 7, record.getOthagid()); - setString(insertStatement, 8, record.getRfs_input()); - - // setString(insertStatement, 9, record.getStgflow()); - setString(insertStatement, 9, record.getUnits()); - setString(insertStatement, 10, record.getInterpolate()); - // setString(insertStatement, 12, record.getOffsets()); - setDouble(insertStatement, 11, record.getAllowstg()); - /* - setString(insertStatement, 9, record.getStgflow()); - setString(insertStatement, 10, record.getUnits()); - setString(insertStatement, 11, record.getInterpolate()); - setString(insertStatement, 12, record.getOffsets()); - setDouble(insertStatement, 13, record.getAllowstg()); - */ - // get the number of records processed by the insert - returnCode = insertStatement.executeUpdate(); - - return returnCode; - - } // end of insert method - - - public int update(RaxRatingRecord oldRecord, RaxRatingRecord newRecord) throws SQLException - { - String header = "CustomRaxRatingTable.update(oldRecord, newRecord): "; - - int returnCode=-999; - // Create a SQL update statement and issue it - // construct the update statement - - - System.out.println(header + "newRecord.getStgflow() = " + newRecord.getStgflow()); - - String updateStatementString = " UPDATE rating SET lid = ?, pe1 = ?, pe2 = ?, tbl = ?, valid_date = ?, src = ?, othagid = ?, rfs_input = ?, stgflow = " + - createArrayString(newRecord.getStgflow()) + - ", units = ?, interpolate = ?, offsets = " + - createArrayString(newRecord.getOffsets()) + - ", allowstg = ? " + oldRecord.getWhereString(); - - PreparedStatement updateStatement = getConnection().prepareStatement( updateStatementString ); - - - String newOffsetsString = null; - - setString(updateStatement, 1, newRecord.getLid()); - setString(updateStatement, 2, newRecord.getPe1()); - setString(updateStatement, 3, newRecord.getPe2()); - setDouble(updateStatement, 4, newRecord.getTbl()); - setTimeStamp(updateStatement, 5, newRecord.getValid_date()); - setString(updateStatement, 6, newRecord.getSrc()); - setString(updateStatement, 7, newRecord.getOthagid()); - setString(updateStatement, 8, newRecord.getRfs_input()); - setString(updateStatement, 9, newRecord.getUnits()); - setString(updateStatement, 10, newRecord.getInterpolate()); - setDouble(updateStatement, 11, newRecord.getAllowstg()); - - // setArray(updateStatement, 9, newRecord.getStgflow()); - // setString(updateStatement, 10, newRecord.getUnits()); - // setString(updateStatement, 11, newRecord.getInterpolate()); - // setArray(updateStatement, 12, newRecord.getOffsets()); - // setDouble(updateStatement, 13, newRecord.getAllowstg()); - // get the number of records processed by the update - - - System.out.println(header + " newRecord.getStgflow() = " + newRecord.getStgflow()); - System.out.println(header + " updateStatement = " + updateStatement); - returnCode = updateStatement.executeUpdate(); - - return returnCode; - - } // end of updateRecord method - -//----------------------------------------------------------------- -// insertOrUpdate() - this method is call with a RaxRatingRecord object. -// the number of records inserted or updated -//----------------------------------------------------------------- - - - public int insertOrUpdate(RaxRatingRecord record) throws SQLException - { - int returnCode=-999; - List recordList = select(record.getWhereString()); - - if (recordList.size() < 1) - { - returnCode = insert(record); - } - else - { - RaxRatingRecord oldRecord = (RaxRatingRecord) recordList.get(0); - returnCode = update(oldRecord, record); - } - return returnCode; - } // end of insertOrUpdate() -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AdjustFactorEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AdjustFactorEditor.java deleted file mode 100644 index 54fe7d4ab9..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AdjustFactorEditor.java +++ /dev/null @@ -1,582 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxAdjustFactor; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.raxbase.table.ArcBaseAdjustFactorJTableRowData; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class AdjustFactorEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - - private StringDataConverter _converter = new StringDataConverter(); - - private Map _peJLStringToPeMap = new HashMap(); - private Map _durCBStringToDurMap = new HashMap(); - private Map _extremumCBStringToExtremumMap = new HashMap(); - private Map _tsCBStringToTSMap = new HashMap(); - -// JTable variables - private JTableManager _AFETableManager = null; - private List _AFEColumnDescriptorList = null; - private List _adjustFactorRowDataList = null; - private List _filteredRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _tableScrollPanePanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private JComboBox _durationComboBox = null; - private JComboBox _tsComboBox = null; - private JComboBox _extremumComboBox = null; - private JLabel _peLabel = new JLabel( "PE (Physical Element):" ); - private JList _peJList = new JList(); - private JScrollPane _peScrollPane = new JScrollPane(); - private DefaultListModel _peListModel = new DefaultListModel(); - private List _peJLStringList= null; - - private JLabel _descriptorLabel = new JLabel( " Adjusted Value = ( ( ( Raw Value / Divisor ) + Base ) * Multiplier ) + Adder" ); - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _updateInsertButton = new JButton( "Update/Insert" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private LabeledTextField _lidLTF = new LabeledTextField( "Location:", "", "Location", 8 ); - private LabeledTextField _beginDateLTF = new LabeledTextField( "Begin Date:", "", "Begin Date", 12 ); - private LabeledTextField _divisorLTF = new LabeledTextField( "Divisor:", "", "Divisor factor in formula to change from raw value to adjusted value", 10 ); - private LabeledTextField _baseLTF = new LabeledTextField( "Base:", "", "Base factor in formula to change from raw value to adjusted value", 10 ); - private LabeledTextField _multiplierLTF = new LabeledTextField( "Multiplier:", "", "Multiplier in formula to change from raw value to adjusted value", 10 ); - private LabeledTextField _adderLTF = new LabeledTextField( "Adder:", "", "Additive factor in formula to change raw value to adjusted value for posting", 10 ); - - private Map _raxAdjustFactorRowDataToRaxAdjustFactorMap = new HashMap(); - - public AdjustFactorEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Adjust Factor Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 760, 825 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initItemSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - _raxAdjustFactorRowDataToRaxAdjustFactorMap = _dataMgr.getRaxAdjustFactorRowDataToRaxAdjustFactorMap(); - pack(); - setVisible( true ); - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _updateInsertButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - } - - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Selected Item" ) ); - - setupPEJList(); - setupDurationComboBox(); - setupTypeSourceComboBox(); - setupExtremumComboBox(); - - _peJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _peScrollPane = new JScrollPane( _peJList ); - _peScrollPane.setPreferredSize( new Dimension( 250, 100 ) ); - JLabel durationLabel = new JLabel( "Duration:" ); - JLabel tsLabel = new JLabel( "TypeSource:" ); - JLabel extremumLabel = new JLabel( "Extremum:" ); - GridBagConstraints gbLabelConstraints = new GridBagConstraints(); - GridBagConstraints gbTFConstraints = new GridBagConstraints(); - - gbLabelConstraints.anchor = GridBagConstraints.EAST; - gbLabelConstraints.weightx = 1; - gbLabelConstraints.weighty = 1; - - gbTFConstraints.anchor = GridBagConstraints.WEST; - gbTFConstraints.weightx = 1; - gbTFConstraints.weighty = 1; - _beginDateLTF.setEditTextField( false ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _selectedItemPanel, _lidLTF, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _selectedItemPanel, _beginDateLTF, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, durationLabel, gbLabelConstraints, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _durationComboBox, gbTFConstraints, 1, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, tsLabel, gbLabelConstraints, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _tsComboBox, gbTFConstraints, 1, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, extremumLabel, gbLabelConstraints, 0, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _extremumComboBox, gbTFConstraints, 1, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _peLabel, gbTFConstraints, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _selectedItemPanel, _peScrollPane, 2, 1, 2, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _selectedItemPanel, _divisorLTF, 0, 6, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _selectedItemPanel, _baseLTF, 2, 6, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _selectedItemPanel, _multiplierLTF, 0, 7, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _selectedItemPanel, _adderLTF, 2, 7, 2, 1, 1, 1, GridBagConstraints.NONE ); - _hDateChooser.addOwner( this ); - } - - private void initItemSelectionPanel() - { - initJTable(); - - _tableScrollPanePanel.setBorder( BorderFactory.createTitledBorder( "Summary By Location of Data Adjustment Factors" ) ); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _tableScrollPanePanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _descriptorLabel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 23, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - - private void updateJTable() - { - _adjustFactorRowDataList = _dataMgr.getAdjustFactorRowDataList(); - _AFETableManager.setChangedAllRowDataList( _adjustFactorRowDataList ); - _AFETableManager.refreshDisplay(); - } - - private void initJTable() - { - _adjustFactorRowDataList = _dataMgr.getAdjustFactorRowDataList(); - setAFEColumnDescriptorList(); - _AFETableManager = new ComplexJTableManager( _AFEColumnDescriptorList, _adjustFactorRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _AFETableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _AFETableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _AFETableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 600, 300 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _tableScrollPanePanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void setAFEColumnDescriptorList() - { - _AFEColumnDescriptorList = new ArrayList(); - - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Location", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "PE", true, 30, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Dur", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "TS", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Extremum", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Begin Date", true, 100, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Divisor", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Base", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Multiplier", true, 75, "center" ) ); - _AFEColumnDescriptorList.add(new JTableColumnDescriptor( "Adder", true, 75, "center" ) ); - } - - private void setupPEJList() - { - List shefPeList = _dataMgr.getShefPeList(); - String peString = null; - - _peJLStringList = new ArrayList(); - for ( int i = 0; i < shefPeList.size(); i++ ) - { - ShefPE shefPE = (ShefPE) shefPeList.get( i ); - _peJLStringList.add( getShefPEJListString( shefPE ) ); - _peJLStringToPeMap.put( getShefPEJListString( shefPE ), shefPE ); - } - - for ( int i = 0; i < _peJLStringList.size(); i++ ) - { - peString = (String) _peJLStringList.get( i ); - _peListModel.addElement( peString ); - } - - _peJList.setModel( _peListModel ); - } - - private String getShefPEJListString( ShefPE shefPE ) - { - String shefPEString = shefPE.getPe() + " " + shefPE.getName(); - - return shefPEString; - } - - private void setupDurationComboBox() - { - List shefDurList = _dataMgr.getShefDurationList(); - List shefDurationStringList = new ArrayList(); - - for ( int i = 0; i < shefDurList.size(); i++ ) - { - ShefDuration shefDur = (ShefDuration) shefDurList.get( i ); - shefDurationStringList.add( getShefDurationComboBoxString( shefDur ) ); - _durCBStringToDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur ); - } - - _durationComboBox = new JComboBox( shefDurationStringList.toArray() ); - } - - private String getShefDurationComboBoxString( ShefDuration shefDuration ) - { - String shefDurationString = shefDuration.getName() + " ( " + shefDuration.getIduration() + "/" + shefDuration.getDuration() + " )"; - - return shefDurationString; - } - - private void setupTypeSourceComboBox() - { - List shefTSList = _dataMgr.getShefTSList(); - List shefTSStringList = new ArrayList(); - - for ( int i = 0; i < shefTSList.size(); i++ ) - { - ShefTS shefTS = (ShefTS) shefTSList.get( i ); - shefTSStringList.add( getShefTSComboBoxString( shefTS ) ); - _tsCBStringToTSMap.put( getShefTSComboBoxString( shefTS ), shefTS ); - } - - _tsComboBox = new JComboBox( shefTSStringList.toArray() ); - } - - private String getShefTSComboBoxString( ShefTS shefTS ) - { - String shefTSString = shefTS.getName() + " (" + shefTS.getTs() + ") "; - - return shefTSString; - } - - private void setupExtremumComboBox() - { - List shefExList = _dataMgr.getShefExtremumList(); - List shefExStringList = new ArrayList(); - - for ( int i = 0; i < shefExList.size(); i++ ) - { - ShefExtremum shefEX = (ShefExtremum) shefExList.get( i ); - shefExStringList.add( getShefExtremumComboBoxString( shefEX ) ); - _extremumCBStringToExtremumMap.put( getShefExtremumComboBoxString( shefEX ), shefEX ); - } - - _extremumComboBox = new JComboBox( shefExStringList.toArray() ); - } - - private String getShefExtremumComboBoxString( ShefExtremum shefEX ) - { - String shefExString = shefEX.getName() + " (" + shefEX.getExtremum() + ") "; - - return shefExString; - } - - private void updateInsertRaxAdjustFactor() - { - RaxAdjustFactor raxAdjustFactor = new RaxAdjustFactor(); - ShefPE pe = (ShefPE) _peJLStringToPeMap.get( (String) _peJList.getSelectedValue() ); - ShefTS ts = (ShefTS) _tsCBStringToTSMap.get( (String) _tsComboBox.getSelectedItem() ); - ShefExtremum extremum = (ShefExtremum) _extremumCBStringToExtremumMap.get( (String) _extremumComboBox.getSelectedItem() ); - ShefDuration dur = (ShefDuration) _durCBStringToDurMap.get( (String) _durationComboBox.getSelectedItem() ); - - raxAdjustFactor.setLid( _lidLTF.getTextFieldText() ); - raxAdjustFactor.setPe( pe.getPe() ); - raxAdjustFactor.setTs( ts.getTs() ); - raxAdjustFactor.setExtremum( extremum.getExtremum() ); - raxAdjustFactor.setDur( dur.getDuration() ); - raxAdjustFactor.setIdur( dur.getIduration() ); - raxAdjustFactor.setDivisor( _converter.getDoubleValue( _divisorLTF.getTextFieldText() ) ); - raxAdjustFactor.setBase( _converter.getDoubleValue( _baseLTF.getTextFieldText() ) ); - raxAdjustFactor.setMultiplier( _converter.getDoubleValue( _multiplierLTF.getTextFieldText() ) ); - raxAdjustFactor.setAdder( _converter.getDoubleValue( _adderLTF.getTextFieldText() ) ); - raxAdjustFactor.setBeginDate( _converter.getLongDateValue( _beginDateLTF.getTextFieldText() ) ); - - _dataMgr.saveRaxAdjustFactor( raxAdjustFactor ); - - updateJTable(); - } - - private void clearSelectedItemPanel() - { - _lidLTF.setTextField( "" ); - _divisorLTF.setTextField( "" ); - _baseLTF.setTextField( "" ); - _multiplierLTF.setTextField( "" ); - _adderLTF.setTextField( "" ); - _beginDateLTF.setTextField( "" ); - _peJList.setSelectedIndex( 0 ); - _durationComboBox.setSelectedIndex( 0 ); - _tsComboBox.setSelectedIndex( 0 ); - _extremumComboBox.setSelectedIndex( 0 ); - } - - private void populateDataInputPanel( RaxAdjustFactor adjustFactor ) - { - _lidLTF.setTextField( adjustFactor.getLid() ); - - _divisorLTF.setTextField( adjustFactor.getDivisor() ); - _baseLTF.setTextField( adjustFactor.getBase() ); - _multiplierLTF.setTextField( adjustFactor.getMultiplier() ); - _adderLTF.setTextField( adjustFactor.getAdder() ); - _beginDateLTF.setTextFieldDate( adjustFactor.getBeginDate() ); - ShefPE shefPE = (ShefPE) _dataMgr.getShefPEMap().get( adjustFactor.getPe() ); - if ( shefPE != null ) - { - _peJList.setSelectedValue( getShefPEJListString( shefPE ), true ); - } - else - { - _peJList.clearSelection(); - } - - - ShefDuration shefDur = (ShefDuration) _dataMgr.getShefDurationMap().get( adjustFactor.getDur() ); - if ( shefDur != null ) - { - _durationComboBox.setSelectedItem( getShefDurationComboBoxString( shefDur ) ); - } - else - { - _durationComboBox.setSelectedItem( "" ); - } - - ShefTS shefTS = (ShefTS) _dataMgr.getShefTSMap().get( adjustFactor.getTs() ); - if ( shefTS != null ) - { - _tsComboBox.setSelectedItem( getShefTSComboBoxString( shefTS ) ); - } - else - { - _tsComboBox.setSelectedItem( "" ); - } - - ShefExtremum shefEx = (ShefExtremum) _dataMgr.getShefExtremumMap().get( adjustFactor.getExtremum() ); - if ( shefEx != null ) - { - _extremumComboBox.setSelectedItem( getShefExtremumComboBoxString( shefEx ) ); - } - else - { - _extremumComboBox.setSelectedItem( "" ); - } - - } - - private void launchDateWindow() - { - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = 0; - - if ( _beginDateLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - dateLong = System.currentTimeMillis(); - } - else - { - dateLong = DbTimeHelper.getLongTimeFromDateString( _beginDateLTF.getTextFieldText() ) + dayInMillis; - } - - calendar.setTimeInMillis( dateLong ); - - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - } - - private void deleteRaxAdjustFactor() - { - RaxAdjustFactor raxAdjustFactor = null; - List selectedRowsData = _AFETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseAdjustFactorJTableRowData rowData = (ArcBaseAdjustFactorJTableRowData) selectedRowsData.get( 0 ); - raxAdjustFactor = (RaxAdjustFactor) _raxAdjustFactorRowDataToRaxAdjustFactorMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxAdjustFactor.keyString(), "Delete Adjust Factor" ) ) - { - _dataMgr.deleteRaxAdjustFactorFromDatabase( raxAdjustFactor ); - clearSelectedItemPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select an Adjust Factor entry", "Delete Adjust Factor" ); - } - } - - public void dateChosen( JDialog jDialog ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - _beginDateLTF.setTextField( dateString ); - } - - private void addListeners() - { - _AFETableManager.addTableListener( new AFETableListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _beginDateLTF.addTextFieldMouseListener( new DateFieldMouseListener() ); - - _updateInsertButton.addActionListener( new UpdateInsertButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _closeButton.addActionListener( windowCloser ); - - addWindowListener( windowCloser ); - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteRaxAdjustFactor(); - } - } - - private class UpdateInsertButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateInsertRaxAdjustFactor(); - } - } - - private class DateFieldMouseListener implements MouseListener - { - public void mouseClicked( MouseEvent e ) - { - } - - public void mouseEntered( MouseEvent e ) - { - } - - public void mouseExited( MouseEvent e ) - { - } - - public void mousePressed( MouseEvent e ) - { - launchDateWindow(); - } - - public void mouseReleased( MouseEvent e ) - { - } - } - - private class AFETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - List rowDataList = null; - - RaxAdjustFactor raxAdjustFactor = null; - - ArcBaseAdjustFactorJTableRowData rowData = (ArcBaseAdjustFactorJTableRowData) _AFETableManager.getSelectedRowsData().get( 0 ); - - raxAdjustFactor = (RaxAdjustFactor) _raxAdjustFactorRowDataToRaxAdjustFactorMap.get( rowData ); - - populateDataInputPanel( raxAdjustFactor ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser", "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser adb_ob83raxtest", "/fs/home/gsood/" ); - AdjustFactorEditor adjustFactorEditorGUI = new AdjustFactorEditor( frame, dataMgr ); - adjustFactorEditorGUI.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AgencyEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AgencyEditor.java deleted file mode 100644 index 2ad816b6ec..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AgencyEditor.java +++ /dev/null @@ -1,311 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Agency; -import ohd.hseb.raxbase.table.ArcBaseAgencyJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class AgencyEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _agencyTableManager = null; - private List _agencyColumnDescriptorList = null; - private List _agencyRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _agencySelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _agCodeLTF = new LabeledTextField( "AgencyCode:", "", "Abbreviation for agency", 7 ); - private LabeledTextField _agLocLTF = new LabeledTextField( "AgencyLoc:", "", "Location of agency", 4 ); - private LabeledTextField _descLTF = new LabeledTextField( "Desc:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _agencyRowDataToAgencyMap = null; - - public AgencyEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Agency Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 340, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initAgencySelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initAgencySelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _agencySelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefTS" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _agCodeLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _agLocLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _descLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _agencyRowDataToAgencyMap = _dataMgr.getAgencyRowDataToAgencyMap(); - } - - private void initJTable() - { - _agencyRowDataList = _dataMgr.getAgencyRowDataList(); - setCEColumnDescriptorList(); - _agencyTableManager = new ComplexJTableManager( _agencyColumnDescriptorList, _agencyRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _agencyTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _agencyTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _agencyTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 100, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _agencySelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _agencyRowDataList = _dataMgr.getAgencyRowDataList(); - _agencyTableManager.setChangedAllRowDataList( _agencyRowDataList ); - _agencyTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _agencyColumnDescriptorList = new ArrayList(); - - _agencyColumnDescriptorList.add(new JTableColumnDescriptor( "AgCode", true, 50, "center" ) ); - _agencyColumnDescriptorList.add(new JTableColumnDescriptor( "AgLoc", true, 50, "center" ) ); - _agencyColumnDescriptorList.add(new JTableColumnDescriptor( "Desc", true, 200, "center" ) ); - } - - private void populateDataInputPanel( Agency agency ) - { - if ( agency != null ) - { - _agCodeLTF.setTextField( agency.getAgCode() ); - _agLocLTF.setTextField( agency.getAgLoc() ); - _descLTF.setTextField( agency.getDes() ); - } - } - - private void clearDataInputPanel() - { - _agCodeLTF.setTextField( "" ); - _agLocLTF.setTextField( "" ); - _descLTF.setTextField( "" ); - } - - private boolean saveAgency() - { - boolean saved = false; - - if ( ! ( ( _agCodeLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || - ( _agLocLTF.getTextFieldText().equalsIgnoreCase( "" ) ) ) ) - { - if ( _descLTF.getTextFieldText().length() <= 20 ) - { - Agency agency = new Agency(); - - agency.setAgCode( _agCodeLTF.getTextFieldText() ); - agency.setAgLoc( _agLocLTF.getTextFieldText() ); - agency.setDes( _descLTF.getTextFieldText() ); - - saved = _dataMgr.saveAgency( agency ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please limit the description to 20 characters", "Error saving Agency" ); - } - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for AgLoc/AgCode", "Save Agency" ); - } - - return saved; - } - - private void deleteAgency() - { - Agency agency = null; - List selectedRowsData = _agencyTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseAgencyJTableRowData rowData = (ArcBaseAgencyJTableRowData) selectedRowsData.get( 0 ); - agency = (Agency) _agencyRowDataToAgencyMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + agency.keyString(), "Delete Agency" ) ) - { - _dataMgr.deleteAgencyFromDataBase( agency ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select an Agency", "Delete Agency" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _agencyTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveAgency(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveAgency() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteAgency(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Agency agency = null; - - ArcBaseAgencyJTableRowData rowData = (ArcBaseAgencyJTableRowData) _agencyTableManager.getSelectedRowsData().get( 0 ); - agency = (Agency) _agencyRowDataToAgencyMap.get( rowData ); - populateDataInputPanel( agency ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - AgencyEditor agencyEditor = new AgencyEditor( frame, dataMgr ); - agencyEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AverageEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AverageEditor.java deleted file mode 100644 index d68e76f627..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/AverageEditor.java +++ /dev/null @@ -1,563 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Average; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.model.ShefProb; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; - -public class AverageEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private List _averageList = null; - - private Average _selectedAverage = null; - - private LabeledComboBox _selectionLCB = new LabeledComboBox(); - private Map _selectionStringToAverageMap = new HashMap(); - private String _lid = null; - private RaxBaseDataMgr _dataMgr = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - - private StringDataConverter _converter = new StringDataConverter(); - - private JPanel _dataPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _lidLTF = new LabeledTextField( "Lid:", "", "Location ID", 8 ); - private LabeledComboBox _peLCB = null; - private LabeledComboBox _durLCB = null; - private LabeledComboBox _tsLCB = null; - private LabeledComboBox _extremumLCB = null; - private LabeledComboBox _probLCB = null; - private LabeledTextField _janLTF = new LabeledTextField( "Jan:" , "", "Monthly Value for January", 10 ); - private LabeledTextField _febLTF = new LabeledTextField( "Feb:" , "", "Monthly Value for February", 10 ); - private LabeledTextField _marLTF = new LabeledTextField( "Mar:" , "", "Monthly Value for March", 10 ); - private LabeledTextField _aprLTF = new LabeledTextField( "Apr:" , "", "Monthly Value for April", 10 ); - private LabeledTextField _mayLTF = new LabeledTextField( "May:" , "", "Monthly Value for May", 10 ); - private LabeledTextField _junLTF = new LabeledTextField( "Jun:" , "", "Monthly Value for June", 10 ); - private LabeledTextField _julLTF = new LabeledTextField( "Jul:" , "", "Monthly Value for July", 10 ); - private LabeledTextField _augLTF = new LabeledTextField( "Aug:" , "", "Monthly Value for August", 10 ); - private LabeledTextField _sepLTF = new LabeledTextField( "Sep:" , "", "Monthly Value for September", 10 ); - private LabeledTextField _octLTF = new LabeledTextField( "Oct:" , "", "Monthly Value for October", 10 ); - private LabeledTextField _novLTF = new LabeledTextField( "Nov:" , "", "Monthly Value for November", 10 ); - private LabeledTextField _decLTF = new LabeledTextField( "Dec:" , "", "Monthly Value for December", 10 ); - private LabeledTextField _calcDateLTF = new LabeledTextField( "CalcDate:", "", "Date monthly values were calculated", 10 ); - - private List _peCBStringList = new ArrayList(); - private List _tsCBStringList = new ArrayList(); - private Map _peCBStringToPeMap = new HashMap(); - private Map _durCBStringToDurMap = new HashMap(); - private Map _durCBStringToIDurMap = new HashMap(); - private Map _probCBStringToProbMap = new HashMap(); - private Map _tsCBStringToTSMap = new HashMap(); - private Map _extremumCBStringToExtremumMap = new HashMap(); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete from Database" ); - - private JPopupMenu _popupMenu = new JPopupMenu(); - - public AverageEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "Average Editor - " + title, true ); - _dataMgr = dataMgr; - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 620, 550 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - updateAverageList(); - - updateSelectionComboBox(); - initComboBoxes(); - initDataPanel(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - populateDataPanel( _selectedAverage ); - pack(); - setVisible( true ); - } - - private void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initDataPanel() - { - _dataPanel.setBorder( BorderFactory.createTitledBorder( "Selected Entry" ) ); - _calcDateLTF.setEditTextField( false ); - _hDateChooser.addOwner( this ); - - _lidLTF.setEditTextField( false ); - _lidLTF.setTextField( _lid ); - - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataPanel, _lidLTF, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _peLCB, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _durLCB, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _tsLCB, 0, 3, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _extremumLCB, 0, 4, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _probLCB, 0, 5, 2, 1, 1, 1, GridBagConstraints.NONE ); - -// ComponentHelper.addPanelComponent( _dataPanel, _pLTF, 0, 5, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _janLTF, 0, 6, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _febLTF, 0, 7, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _marLTF, 0, 8, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _aprLTF, 0, 9, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _mayLTF, 0, 10, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _junLTF, 0, 11, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _julLTF, 0, 12, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _augLTF, 0, 13, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _sepLTF, 0, 14, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _octLTF, 0, 15, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _novLTF, 0, 16, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _decLTF, 0, 17, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _calcDateLTF, 0, 18, 2, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _selectionLCB, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _dataPanel, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void populateDataPanel( Average average ) - { - if ( average != null ) - { - _lidLTF.setTextField( average.getLid() ); - - ShefPE shefPE = (ShefPE) _dataMgr.getShefPEMap().get( average.getPe() ); - _peLCB.setSelectedItem( getShefPEComboBoxString( shefPE ) ); - - ShefDuration shefDur = (ShefDuration) _dataMgr.getShefDurationMap().get( average.getDur() ); - _durLCB.setSelectedItem( getShefDurationComboBoxString( shefDur ) ); - - ShefTS shefTS = (ShefTS) _dataMgr.getShefTSMap().get( average.getTs() ); - _tsLCB.setSelectedItem( getShefTSString( shefTS ) ); - - ShefExtremum shefEx = (ShefExtremum) _dataMgr.getShefExtremumMap().get( average.getExtremum() ); - _extremumLCB.setSelectedItem( getShefExtremumComboBoxString( shefEx ) ); - - ShefProb shefProb = (ShefProb) _dataMgr.getShefProbMap().get( average.getP() ); - _probLCB.setSelectedItem( getShefProbComboBoxString( shefProb ) ); - - _janLTF.setTextField( average.getJan() ); - _febLTF.setTextField( average.getFeb() ); - _marLTF.setTextField( average.getMar() ); - _aprLTF.setTextField( average.getApr() ); - _mayLTF.setTextField( average.getMay() ); - _junLTF.setTextField( average.getJun() ); - _julLTF.setTextField( average.getJul() ); - _augLTF.setTextField( average.getAug() ); - _sepLTF.setTextField( average.getSep() ); - _octLTF.setTextField( average.getOct() ); - _novLTF.setTextField( average.getNov() ); - _decLTF.setTextField( average.getDec() ); - _calcDateLTF.setTextField( _converter.getDateStringFromDateLong( average.getCalcdate() ) ); - } - } - - - private void initComboBoxes() - { - List shefPeList = _dataMgr.getShefPeList(); - List shefDurationList = _dataMgr.getShefDurationList(); - List shefTypeSourceList = _dataMgr.getShefTSList(); - List shefExtremumList = _dataMgr.getShefExtremumList(); - List shefProbList = _dataMgr.getShefProbList(); - - List shefPeStringList = new ArrayList(); - List shefDurationStringList = new ArrayList(); - List shefTypeSourceStringList = new ArrayList(); - List shefExtremumStringList = new ArrayList(); - List shefProbStringList = new ArrayList(); - - for ( int i = 0; i < shefPeList.size(); i++ ) - { - ShefPE shefPE = (ShefPE) shefPeList.get( i ); - shefPeStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringToPeMap.put( getShefPEComboBoxString( shefPE ), shefPE.getPe() ); - } - - for ( int i = 0; i < shefDurationList.size(); i++ ) - { - ShefDuration shefDur = (ShefDuration) shefDurationList.get( i ); - shefDurationStringList.add( getShefDurationComboBoxString( shefDur ) ); - _durCBStringToDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur.getDuration() ); - _durCBStringToIDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur.getIduration() ); - } - - for ( int i = 0; i < shefProbList.size(); i++ ) - { - ShefProb shefProb = (ShefProb) shefProbList.get( i ); - shefProbStringList.add( getShefProbComboBoxString( shefProb ) ); - _probCBStringToProbMap.put( getShefProbComboBoxString( shefProb ), shefProb.getP() ); - } - - for ( int i = 0; i < shefTypeSourceList.size(); i++ ) - { - ShefTS shefTS = (ShefTS) shefTypeSourceList.get( i ); - shefTypeSourceStringList.add( getShefTSString( shefTS ) ); - _tsCBStringList.add( getShefTSString( shefTS ) ); - _tsCBStringToTSMap.put( getShefTSString( shefTS ), shefTS.getTs() ); - } - - for ( int i = 0; i < shefExtremumList.size(); i++ ) - { - ShefExtremum shefEx = (ShefExtremum) shefExtremumList.get( i ); - shefExtremumStringList.add( getShefExtremumComboBoxString(shefEx ) ); - _extremumCBStringToExtremumMap.put( getShefExtremumComboBoxString( shefEx ), shefEx.getExtremum() ); - } - - _peLCB = new LabeledComboBox( "PE:", shefPeStringList ); - _durLCB = new LabeledComboBox( "Duration:", shefDurationStringList ); - _tsLCB = new LabeledComboBox( "Type Source:", shefTypeSourceStringList ); - _extremumLCB = new LabeledComboBox( "Extremum:", shefExtremumStringList ); - _probLCB = new LabeledComboBox( "Probability:", shefProbStringList ); - } - - private String getShefExtremumComboBoxString( ShefExtremum shefEx ) - { - String shefExtremumString = shefEx.getName() + " (" + shefEx.getExtremum() + ")"; - - return shefExtremumString; - } - - private String getShefTSString( ShefTS shefTS ) - { - String shefTSString = shefTS.getName() + " (" + shefTS.getTs() + ")"; - - return shefTSString; - } - - private String getShefPEComboBoxString( ShefPE shefPE ) - { - String shefPEString = shefPE.getPe() + " " + shefPE.getName(); - - return shefPEString; - } - - private String getShefDurationComboBoxString( ShefDuration shefDuration ) - { - String shefDurationString = shefDuration.getName() + " ( " + shefDuration.getIduration() + "/" + shefDuration.getDuration() + " )"; - - return shefDurationString; - } - - private String getShefProbComboBoxString( ShefProb shefProb ) - { - String shefProbString = ""; - - if ( shefProb != null ) - { - shefProbString = shefProb.getP() + "/" + shefProb.getProbability(); - } - - return shefProbString; - } - - private void updateSelectionComboBox() - { - Average average = null; - List selectionComboBoxStringList = new ArrayList(); - String dateString = null; - - _selectionStringToAverageMap.clear(); - _selectionLCB.getComboBox().removeAllItems(); - - for ( int i = 0; i < _averageList.size(); i++ ) - { - average = (Average) _averageList.get( i ); - selectionComboBoxStringList.add( getSelectedAverageString( average ) ); - _selectionStringToAverageMap.put( getSelectedAverageString( average ), average ); - } - - if ( selectionComboBoxStringList.isEmpty() ) - { - selectionComboBoxStringList.add( "No entries found" ); - } - _selectionLCB.setComboBoxFromStringArray( selectionComboBoxStringList.toArray() ); - _selectionLCB.setLabel( "Select Average Entry:" ); - _selectionLCB.setLabelPreferredSize( new Dimension( 150, 15 ) ); - _selectionLCB.setComboBoxPreferredSize( new Dimension( 375, 15 ) ); - - String selectedItem = _selectionLCB.getSelectedCBItem(); - - _selectedAverage = (Average) _selectionStringToAverageMap.get( selectedItem ); - } - - private String getSelectedAverageString( Average average ) - { - return "PE = " + average.getPe() + " | Dur = " + average.getDur() + " | TS = " + - average.getTs() + " | Extremum = " + average.getExtremum() + " | P = " + average.getP(); - } - - private void updateAverageList() - { - _averageList = _dataMgr.getAverageList( _lid ); - } - - private void deleteAverage() - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - Average average = (Average) _selectionStringToAverageMap.get( selectedItem ); - - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + average.keyString(), "Delete Average" ) ) - { - boolean success = _dataMgr.deleteAverageFromDatabase( average ); - if ( ! success ) - { - DialogHelper.displayErrorDialog( this, "Unable to delete Average entry", "Delete Average Error" ); - } - updateAverageList(); - updateSelectionComboBox(); - } - } - - private boolean saveAverage() - { - boolean saved = false; - - Average average = new Average(); - - String pe = (String) _peLCB.getSelectedItem(); - String ts = (String) _tsLCB.getSelectedItem(); - String extremum = (String) _extremumLCB.getSelectedItem(); - String duration = (String) _durLCB.getSelectedItem(); - String prob = (String) _probLCB.getSelectedItem(); - short iDuration = (Short) _durCBStringToIDurMap.get( duration ); - - - average.setLid( _lidLTF.getTextFieldText() ); - average.setPe( (String) _peCBStringToPeMap.get( pe ) ); - average.setDur( (String) _durCBStringToDurMap.get( duration ) ); - average.setIdur( iDuration ); - average.setTs( (String) _tsCBStringToTSMap.get( ts ) ); - average.setExtremum( (String) _extremumCBStringToExtremumMap.get( extremum ) ); - average.setP( (String) _probCBStringToProbMap.get( prob ) ); - average.setJan( _converter.getDoubleValue( _janLTF.getTextFieldText() ) ); - average.setFeb( _converter.getDoubleValue( _febLTF.getTextFieldText() ) ); - average.setMar( _converter.getDoubleValue( _marLTF.getTextFieldText() ) ); - average.setApr( _converter.getDoubleValue( _aprLTF.getTextFieldText() ) ); - average.setMay( _converter.getDoubleValue( _mayLTF.getTextFieldText() ) ); - average.setJun( _converter.getDoubleValue( _junLTF.getTextFieldText() ) ); - average.setJul( _converter.getDoubleValue( _julLTF.getTextFieldText() ) ); - average.setAug( _converter.getDoubleValue( _augLTF.getTextFieldText() ) ); - average.setSep( _converter.getDoubleValue( _sepLTF.getTextFieldText() ) ); - average.setOct( _converter.getDoubleValue( _octLTF.getTextFieldText() ) ); - average.setNov( _converter.getDoubleValue( _novLTF.getTextFieldText() ) ); - average.setDec( _converter.getDoubleValue( _decLTF.getTextFieldText() ) ); - average.setCalcdate( _converter.getLongDateValue( _calcDateLTF.getTextFieldText() ) ); - - saved = _dataMgr.saveAverage( average ); - updateAverageList(); - updateSelectionComboBox(); - - return saved; - } - - private void launchDateWindow() - { - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = System.currentTimeMillis(); - - if ( ! _calcDateLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - dateLong = _converter.getLongDateValue( _calcDateLTF.getTextFieldText() ) + dayInMillis; - } - - calendar.setTimeInMillis( dateLong ); - - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - } - - public void dateChosen( JDialog jdialog ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - _calcDateLTF.setTextField( dateString ); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _selectionLCB.addComboBoxActionListener( new ItemSelectionListener() ); - - _closeButton.addActionListener( windowCloser ); - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - - _calcDateLTF.addTextFieldMouseListener( new DateFieldMouseListener() ); - } - - private class DateFieldMouseListener implements MouseListener - { - public void mouseReleased( MouseEvent e ){} - public void mouseClicked( MouseEvent e ){} - public void mouseEntered( MouseEvent e ){} - public void mouseExited( MouseEvent e ){} - public void mousePressed( MouseEvent e ) - { - launchDateWindow(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteAverage(); - } - } - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveAverage(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveAverage() ) - { - closeWindow(); - } - else - { - DialogHelper.displayErrorDialog( AverageEditor.this, "Unable to save the Average entry", "Error Saving Average" ); - } - } - } - - private class ItemSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e) - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - Average average = (Average) _selectionStringToAverageMap.get( selectedItem ); - - if ( average != null ) - { - populateDataPanel( average ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - String title = "ALEC2"; - String name = dataMgr.getRaxLocation( "ALEC2" ).getName(); - - if ( name != null ) - { - title += " - " + name; - } - - - AverageEditor averageEditor = new AverageEditor( frame, dataMgr, "ALEC2", title ); - averageEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CountiesEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CountiesEditor.java deleted file mode 100644 index ed69cabfe5..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CountiesEditor.java +++ /dev/null @@ -1,326 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Counties; -import ohd.hseb.raxbase.table.ArcBaseCountiesJTableRowData; -import ohd.hseb.raxdb.generated.StateRecord; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class CountiesEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _countiesTableManager = null; - private List _countiesColumnDescriptorList = null; - private List _countiesRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _countiesSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _countyLTF = new LabeledTextField( "County: ", "", "County", 23 ); - private LabeledComboBox _stateCountryFipsLCB = new LabeledComboBox( "State/CountryFips:" ); - private LabeledTextField _countyFipsLTF = new LabeledTextField( "CountyFips: ", "", "3 char county FIPS code", 4 ); - private LabeledComboBox _wfoLCB = new LabeledComboBox( "Wfo:" ); - private LabeledTextField _zonLTF = new LabeledTextField( "Zon: ", "", "NWS zone code", 5 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _countiesRowDataToCountiesMap = null; - - public CountiesEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Counties Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 520, 500 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initComboBoxes(); - initCountiesSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initCountiesSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _countiesSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected County" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _countyLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _stateCountryFipsLCB, 0, 2, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _selectedItemPanel, _countyFipsLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _wfoLCB, 0, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _zonLTF, 0, 5, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _countiesRowDataToCountiesMap = _dataMgr.getCountiesRowDataToCountiesMap(); - } - - private void initComboBoxes() - { - _stateCountryFipsLCB.setComboBox( _dataMgr.getStateCountryFipsList() ); - _wfoLCB.setComboBox( _dataMgr.getWfoList() ); - } - - private void initJTable() - { - _countiesRowDataList = _dataMgr.getCountiesRowDataList(); - setCountiesEColumnDescriptorList(); - _countiesTableManager = new ComplexJTableManager( _countiesColumnDescriptorList, _countiesRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _countiesTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _countiesTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _countiesTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _countiesSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _countiesRowDataList = _dataMgr.getCountiesRowDataList(); - _countiesTableManager.setChangedAllRowDataList( _countiesRowDataList ); - _countiesTableManager.refreshDisplay(); - } - - private void setCountiesEColumnDescriptorList() - { - _countiesColumnDescriptorList = new ArrayList(); - - _countiesColumnDescriptorList.add(new JTableColumnDescriptor( "County", true, 150, "center" ) ); - _countiesColumnDescriptorList.add(new JTableColumnDescriptor( "State", true, 60, "center" ) ); - _countiesColumnDescriptorList.add(new JTableColumnDescriptor( "CountryFips", true, 80, "center" ) ); - _countiesColumnDescriptorList.add(new JTableColumnDescriptor( "CountyFips", true, 80, "center" ) ); - _countiesColumnDescriptorList.add(new JTableColumnDescriptor( "WFO", true, 60, "center" ) ); - _countiesColumnDescriptorList.add(new JTableColumnDescriptor( "ZON", true, 60, "center" ) ); - } - - private void populateDataInputPanel( Counties counties ) - { - if ( counties != null ) - { - _countyLTF.setTextField( counties.getCounty() ); - _stateCountryFipsLCB.setSelectedItem( _dataMgr.getStateCountryFipsString( counties ) ); - _countyFipsLTF.setTextField( counties.getCountyFips() ); - _wfoLCB.setSelectedItem( counties.getWfo() ); - _zonLTF.setTextField( counties.getZon() ); - } - } - - private void clearDataInputPanel() - { - _countyLTF.setTextField( "" ); - _stateCountryFipsLCB.setSelectedIndex( 0 ); - _countyFipsLTF.setTextField( "" ); - _wfoLCB.setSelectedIndex( 0 ); - _zonLTF.setTextField( "" ); - } - - private boolean saveCounties() - { - boolean saved = false; - Map stateCountryFipsStringToStateRecordMap = _dataMgr.getStateCountryFipsStringToStateMap(); - String stateCountryFipsSelectedItem = _stateCountryFipsLCB.getSelectedCBItem(); - - StateRecord record = (StateRecord) stateCountryFipsStringToStateRecordMap.get( stateCountryFipsSelectedItem ); - Counties counties = new Counties(); - - counties.setCounty( _countyLTF.getTextFieldText() ); - - counties.setState( record.getState() ); - counties.setCountryFips( record.getCountryfips() ); - - - counties.setCountyFips( _countyFipsLTF.getTextFieldText() ); - counties.setWfo( _wfoLCB.getSelectedCBItem() ); - counties.setZon( _zonLTF.getTextFieldText() ); - - saved = _dataMgr.saveCounties( counties ); - - updateJTable(); - - return saved; - } - - private void deleteCounties() - { - Counties counties = null; - List selectedRowsData = _countiesTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseCountiesJTableRowData rowData = (ArcBaseCountiesJTableRowData) selectedRowsData.get( 0 ); - counties = (Counties) _countiesRowDataToCountiesMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + counties.keyString(), "Delete County" ) ) - { - _dataMgr.deleteCountiesFromDataBase( counties ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a County", "Delete County" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _countiesTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveCounties(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveCounties() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteCounties(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Counties counties = null; - - ArcBaseCountiesJTableRowData rowData = (ArcBaseCountiesJTableRowData) _countiesTableManager.getSelectedRowsData().get( 0 ); - counties = (Counties) _countiesRowDataToCountiesMap.get( rowData ); - populateDataInputPanel( counties ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser", "", "/fs/home/gsood/" ); - - CountiesEditor countiesEditor = new CountiesEditor( frame, dataMgr ); - countiesEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CountryEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CountryEditor.java deleted file mode 100644 index 1c2cf99b1d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CountryEditor.java +++ /dev/null @@ -1,290 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Country; -import ohd.hseb.raxbase.table.ArcBaseCountryJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class CountryEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _CETableManager = null; - private List _CEColumnDescriptorList = null; - private List _countryRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _countrySelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _countryLTF = new LabeledTextField( "Country: ", "", "Country", 10 ); - private LabeledTextField _countryFipsLTF = new LabeledTextField( "CountryFips: ", "", "Country", 10 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _countryRowDataToCountryMap = null; - - public CountryEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Country Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 310, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initCountrySelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initCountrySelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _countrySelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Country" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _countryLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _countryFipsLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _countryRowDataToCountryMap = _dataMgr.getCountryRowDataToCountryMap(); - } - - private void initJTable() - { - _countryRowDataList = _dataMgr.getCountryRowDataList(); - setCEColumnDescriptorList(); - _CETableManager = new ComplexJTableManager( _CEColumnDescriptorList, _countryRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _CETableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _CETableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _CETableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _countrySelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _countryRowDataList = _dataMgr.getCountryRowDataList(); - _CETableManager.setChangedAllRowDataList( _countryRowDataList ); - _CETableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _CEColumnDescriptorList = new ArrayList(); - - _CEColumnDescriptorList.add(new JTableColumnDescriptor( "Country", true, 120, "center" ) ); - _CEColumnDescriptorList.add(new JTableColumnDescriptor( "CountryFips", true, 120, "center" ) ); - } - - private void populateDataInputPanel( Country country ) - { - if ( country != null ) - { - _countryLTF.setTextField( country.getCountry() ); - _countryFipsLTF.setTextField( country.getCountryFips() ); - } - } - - private void clearDataInputPanel() - { - _countryLTF.setTextField( "" ); - _countryFipsLTF.setTextField( "" ); - } - - private boolean saveCountry() - { - boolean saved = false; - - Country country = new Country(); - - country.setCountry( _countryLTF.getTextFieldText() ); - country.setCountryFips( _countryFipsLTF.getTextFieldText() ); - - saved = _dataMgr.saveCountry( country ); - - updateJTable(); - - return saved; - } - - private void deleteCountry() - { - Country country = null; - List selectedRowsData = _CETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseCountryJTableRowData rowData = (ArcBaseCountryJTableRowData) selectedRowsData.get( 0 ); - country = (Country) _countryRowDataToCountryMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + country.keyString(), "Delete Country" ) ) - { - _dataMgr.deleteCountryFromDataBase( country ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Country", "Delete Country" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _CETableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveCountry(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveCountry() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteCountry(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Country country = null; - - ArcBaseCountryJTableRowData rowData = (ArcBaseCountryJTableRowData) _CETableManager.getSelectedRowsData().get( 0 ); - country = (Country) _countryRowDataToCountryMap.get( rowData ); - populateDataInputPanel( country ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - CountryEditor countryEditor = new CountryEditor( frame, dataMgr ); - countryEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CrestEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CrestEditor.java deleted file mode 100644 index 6e69072867..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/CrestEditor.java +++ /dev/null @@ -1,574 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxCrest; -import ohd.hseb.raxbase.table.ArcBaseCrestJTableRowData; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class CrestEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private String _lid = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - - private StringDataConverter _converter = new StringDataConverter(); - -// JTable variables - private JTableManager _CETableManager = null; - private List _CEColumnDescriptorList = null; - private List _crestRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _crestSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _stageLTF = new LabeledTextField( " Stage: ", "", "Stage", 10 ); - private LabeledTextField _stgQualLTF = new LabeledTextField( "Stage Quality Code:", "", "Quality Code", 10 ); - private LabeledTextField _flowLTF = new LabeledTextField( " Flow: ", "", "Flow", 10 ); - private LabeledTextField _flowQualLTF = new LabeledTextField( " Flow Quality Code: ", "", "Quality Code", 10 ); - private LabeledTextField _dateLTF = new LabeledTextField( "Date:", "", "Date", 10 ); - private LabeledTextField _timeLTF = new LabeledTextField( "Time:", "", "Time", 10 ); - - private JCheckBox _oldDatumCB = new JCheckBox( "Based on Old Datum" ); - private JCheckBox _hwMarkCB = new JCheckBox( "Observed by High Water Mark" ); - private JCheckBox _jamCB = new JCheckBox( "Affected by Ice Jam" ); - private String[] _prelimStringArray = { "", "Official Crest", "Record Crest", "Preliminary Status" }; - private LabeledComboBox _prelimLCB = new LabeledComboBox( "Prelim:", _prelimStringArray ); - private Map _prelimCBStringToPrelimMap = new HashMap(); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _newButton = new JButton( "New" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _raxCrestRowDataToRaxCrestMap = null; - - public CrestEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "Crest Editor - " + title, true ); - _dataMgr = dataMgr; - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 500, 625 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initCrestSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initCrestSelectionPanel() - { - initJTable(); - - ComponentHelper.addPanelComponent( _crestSelectionPanel, _deleteButton, 0, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - } - - private void initSelectedItemPanel() - { - JPanel cbPanel = new JPanel( new GridBagLayout() ); - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Crest" ) ); - JPanel vPanel = new JPanel(); -// vPanel.setBackground( Color.RED ); - _dateLTF.setEditTextField( false ); - _stgQualLTF.setLabelPreferredSize( new Dimension( 130, 15 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( cbPanel, _oldDatumCB, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( cbPanel, _hwMarkCB, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( cbPanel, _jamCB, 0, 2, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _selectedItemPanel, _stageLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _stgQualLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _flowLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _flowQualLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _dateLTF, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _timeLTF, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, cbPanel, 0, 4, 3, 1, GridBagConstraints.NONE ); - -// ComponentHelper.addPanelComponent( _selectedItemPanel, _prelimComboBox, 1, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _prelimLCB, 1, 3, 2, 1, GridBagConstraints.BOTH ); - - - for ( int i = 1; i < _prelimStringArray.length; i++ ) - { - String prelimCharString = _prelimStringArray[ i ].substring( 0, 1 ); - _prelimCBStringToPrelimMap.put( _prelimStringArray[ i ], prelimCharString ); - _prelimCBStringToPrelimMap.put( prelimCharString, _prelimStringArray[ i ] ); - } - _hDateChooser.addOwner( this ); - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _newButton, 3, 0, 1, 1, GridBagConstraints.NONE ); -// ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 4, 0, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _crestSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - - private void initHashMaps() - { - _raxCrestRowDataToRaxCrestMap = _dataMgr.getRaxCrestRowDataToRaxCrestMap(); - } - - private void initJTable() - { - _crestRowDataList = _dataMgr.getCrestRowDataList( _lid ); - setCEColumnDescriptorList(); - _CETableManager = new ComplexJTableManager( _CEColumnDescriptorList, _crestRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _CETableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _CETableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _CETableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 300 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _crestSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _crestRowDataList = _dataMgr.getCrestRowDataList( _lid ); - _CETableManager.setChangedAllRowDataList( _crestRowDataList ); - _CETableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _CEColumnDescriptorList = new ArrayList(); - - _CEColumnDescriptorList.add(new JTableColumnDescriptor( "Stage", true, 120, "center" ) ); - _CEColumnDescriptorList.add(new JTableColumnDescriptor( "Flow", true, 120, "center" ) ); - _CEColumnDescriptorList.add(new JTableColumnDescriptor( "Date", true, 120, "center" ) ); - _CEColumnDescriptorList.add(new JTableColumnDescriptor( "Time", true, 120, "center" ) ); - } - - private void clearDataInputPanel() - { - _stageLTF.setTextField( "" ); - _stgQualLTF.setTextField( "" ); - _flowLTF.setTextField( "" ); - _flowQualLTF.setTextField( "" ); - _dateLTF.setTextField( "" ); - _timeLTF.setTextField( "" ); - _oldDatumCB.setSelected( false ); - _hwMarkCB.setSelected( false ); - _jamCB.setSelected( false ); - _prelimLCB.setSelectedIndex( 0 ); - } - - private void populateDataInputPanel( RaxCrest raxCrest ) - { - _stageLTF.setTextField( raxCrest.getStage() ); - _stgQualLTF.setTextField( raxCrest.getStgQual() ); - _flowLTF.setTextField( raxCrest.getFlow() ); - _flowQualLTF.setTextField( raxCrest.getFlowQual() ); - _dateLTF.setTextFieldDate( raxCrest.getDateCrest() ); - _timeLTF.setTextField( raxCrest.getCrestDateTime() ); - - if ( raxCrest.getOldDatum().equalsIgnoreCase( "Y" ) ) - { - _oldDatumCB.setSelected( true ); - } - else - { - _oldDatumCB.setSelected( false ); - } - - if ( raxCrest.getHw().equalsIgnoreCase( "Y" ) ) - { - _hwMarkCB.setSelected( true ); - } - else - { - _hwMarkCB.setSelected( false ); - } - - if ( raxCrest.getJam().equalsIgnoreCase( "Y" ) ) - { - _jamCB.setSelected( true ); - } - else - { - _jamCB.setSelected( false ); - } - - String prelim = raxCrest.getPrelim(); - _prelimLCB.setSelectedItem( (String) _prelimCBStringToPrelimMap.get( prelim ) ); - } - - private boolean saveCrest() - { - boolean saved = false; - - RaxCrest raxCrest = new RaxCrest(); - String dateString = _dateLTF.getTextFieldText().trim(); - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - raxCrest.setLid( _lid ); - - raxCrest.setDateCrest( _converter.getLongDateValue( dateString ) ); - - raxCrest.setCrestDateTime( _timeLTF.getTextFieldText() ); - raxCrest.setStage( _converter.getDoubleValue( _stageLTF.getTextFieldText() ) ); - raxCrest.setStgQual( _stgQualLTF.getTextFieldText() ); - raxCrest.setFlow( _converter.getDoubleValue( _flowLTF.getTextFieldText() ) ); - raxCrest.setFlowQual( _flowQualLTF.getTextFieldText() ); - raxCrest.setHw( getYNStringFromCB( _hwMarkCB ) ); - raxCrest.setJam( getYNStringFromCB( _jamCB ) ); - raxCrest.setOldDatum( getYNStringFromCB( _oldDatumCB ) ); - String prelimString = (String) _prelimCBStringToPrelimMap.get( (String ) _prelimLCB.getSelectedItem() ); - raxCrest.setPrelim( prelimString ); - - _dataMgr.saveRaxCrestToDatabase( raxCrest ); - - saved = true; - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Must select a valid date", "Save Crest" ); - } - - return saved; - } - - private void deleteCrest() - { - RaxCrest raxCrest = null; - List selectedRowsData = _CETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseCrestJTableRowData rowData = (ArcBaseCrestJTableRowData) selectedRowsData.get( 0 ); - raxCrest = (RaxCrest) _raxCrestRowDataToRaxCrestMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxCrest.keyString(), "Delete Crest" ) ) - { - _dataMgr.deleteRaxCrestFromDatabase( raxCrest ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a crest", "Delete Crest" ); - } - } - - private String getYNStringFromCB( JCheckBox checkBox ) - { - String ynString; - - if ( checkBox.isSelected() ) - { - ynString = "Y"; - } - else - { - ynString = "N"; - } - - return ynString; - } - - private void launchDateWindow() - { - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = System.currentTimeMillis(); - - if ( ! _dateLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - dateLong = _converter.getLongDateValue( _dateLTF.getTextFieldText() ) + dayInMillis; - } - - calendar.setTimeInMillis( dateLong ); - - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - } - - public void dateChosen( JDialog jDialog ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - _dateLTF.setTextField( dateString ); - } - - private boolean isQualityTextFieldLengthToLong( String qcString, KeyEvent e ) - { - boolean tooLong = false; - - if ( qcString.length() > 1 ) - { - tooLong = true; - } - - return tooLong; - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _CETableManager.addTableListener( new CETableListener() ); - _newButton.addActionListener( new NewButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _dateLTF.addTextFieldMouseListener( new DateFieldMouseListener() ); - _stgQualLTF.addTextFieldKeyListener( new StgQualKeyListener() ); - _flowQualLTF.addTextFieldKeyListener( new FlowQualKeyListener() ); - } - - private class StgQualKeyListener implements KeyListener - { - String __oldString = null; - - public void keyPressed( KeyEvent arg0 ) - { - if ( _stgQualLTF.getTextFieldText().length() > 1 ) - { - __oldString = _stgQualLTF.getTextFieldText().substring( 0, 1 ); - } - else - { - __oldString = _stgQualLTF.getTextFieldText(); - } - } - - public void keyReleased( KeyEvent e ) - { - if ( isQualityTextFieldLengthToLong( _flowQualLTF.getTextFieldText(), e ) ) - { - _stgQualLTF.setTextField( __oldString ); - } - } - - public void keyTyped( KeyEvent arg0 ){} - } - - private class FlowQualKeyListener implements KeyListener - { - String __oldString = null; - - public void keyPressed( KeyEvent arg0 ) - { - if ( _flowQualLTF.getTextFieldText().length() > 1 ) - { - __oldString = _flowQualLTF.getTextFieldText().substring( 0, 1 ); - } - else - { - __oldString = _flowQualLTF.getTextFieldText(); - } - } - - public void keyReleased( KeyEvent e ) - { - if ( isQualityTextFieldLengthToLong( _flowQualLTF.getTextFieldText(), e ) ) - { - _flowQualLTF.setTextField( __oldString ); - } - } - - public void keyTyped( KeyEvent arg0 ){} - } - private class DateFieldMouseListener implements MouseListener - { - public void mouseClicked( MouseEvent e ) - { - } - - public void mouseEntered( MouseEvent e ) - { - } - - public void mouseExited( MouseEvent e ) - { - } - - public void mousePressed( MouseEvent e ) - { - launchDateWindow(); - } - - public void mouseReleased( MouseEvent e ) - { - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveCrest(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteCrest(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveCrest() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - private class CETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - RaxCrest raxCrest = null; - - ArcBaseCrestJTableRowData rowData = (ArcBaseCrestJTableRowData) _CETableManager.getSelectedRowsData().get( 0 ); - raxCrest = (RaxCrest) _raxCrestRowDataToRaxCrestMap.get( rowData ); - populateDataInputPanel( raxCrest ); - } - } - } - - private class NewButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clearDataInputPanel(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - String title = "ZZV"; - String name = dataMgr.getRaxLocation( "ZZV" ).getName(); - - if ( name != null ) - { - title += " - " + name; - } - - - CrestEditor crestEditorGUI = new CrestEditor( frame, dataMgr, "ZZV", title ); - crestEditorGUI.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/DataLimitsEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/DataLimitsEditor.java deleted file mode 100644 index 25eedee7d4..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/DataLimitsEditor.java +++ /dev/null @@ -1,1087 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTable; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxDataLimits; -import ohd.hseb.raxbase.model.RaxLocDataLimits; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.table.ArcBaseDataLimitsJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class DataLimitsEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private Map _raxDLRowDataToRaxDLMap = null; - private Map _raxLocDLRowDataToRaxLocDLMap = null; - -// JTable variables - private JTableManager _DLETableManager = null; - private List _DLEColumnDescriptorList = null; - private List _dataLimitsRowDataList = null; - private List _locDataLimitsRowDataList = null; - private List _filteredRowDataList = null; - private JScrollPane _tableScrollPane = null; - - private JPanel _dataLimitsSelectionPanel = new JPanel( new GridBagLayout() ); - private JPanel _tableScrollPanePanel = new JPanel( new GridBagLayout() ); - private JLabel _listLabel = new JLabel( "List:" ); - private String[] _limitsLocLimitsStringArray = { "Default Limits", "Location Limits" }; - private JComboBox _limitsLocLimitsCB = new JComboBox( _limitsLocLimitsStringArray ); - private JCheckBox _lidFilterCB = new JCheckBox( "Location" ); - private JTextField _lidFilterTextBox = new JTextField(); - private JCheckBox _peFilterCB = new JCheckBox( "Physical Element" ); - private JList _peFilterJList = new JList(); - private JScrollPane _peFilterScrollPane = new JScrollPane(); - private DefaultListModel _peFilterListModel = new DefaultListModel(); - - private List _peJLStringList= null; - private Map _peJLStringToPeMap = new HashMap(); - private Map _durCBStringToDurMap = new HashMap(); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private JLabel _lidLabel = new JLabel( "Location: " ); - private JTextField _lidTextField = new JTextField(); - private JLabel _durationLabel = new JLabel( "Duration: " ); - private JComboBox _durationComboBox = new JComboBox(); - private JLabel _startDateLabel = new JLabel( "Start MM-DD: " ); - private JTextField _startDateTextField = new JTextField(); - private JLabel _endDateLabel = new JLabel( "End MM-DD: " ); - private JTextField _endDateTextField = new JTextField(); - private JLabel _peLabel = new JLabel( "PE (Physical Element):" ); - private JList _peJList = new JList(); - private JScrollPane _peScrollPane = new JScrollPane(); - private DefaultListModel _peListModel = new DefaultListModel(); - private JLabel _minLabel = new JLabel( " Minimum " ); - private JLabel _maxLabel = new JLabel( " Maximum " ); - private JLabel _grossRangeLabel = new JLabel( "Gross Range: " ); - private JLabel _reasonRangeLabel = new JLabel( "Reasonable Range: " ); - private JLabel _rocLabel = new JLabel( "Rate of Change (ROC): " ); - private JLabel _unitsLabel = new JLabel( "Units/Hour" ); - private JLabel _alertAlarmLimitsLabel = new JLabel( "Alert/Alarm Limits" ); - private JLabel _limitsLabel = new JLabel( "Limit" ); - private JLabel _rocLimitLabel = new JLabel( "ROC" ); - private JLabel _alertLabel = new JLabel( "Alert" ); - private JLabel _alarmLabel = new JLabel( "Alarm" ); - private JTextField _grossRangeMinTF = new JTextField(); - private JTextField _grossRangeMaxTF = new JTextField(); - private JTextField _reasonRangeMinTF = new JTextField(); - private JTextField _reasonRangeMaxTF = new JTextField(); - private JTextField _rocTextField = new JTextField(); - private JTextField _alertTextField = new JTextField(); - private JTextField _alertRocTextField = new JTextField(); - private JTextField _alarmTextField = new JTextField(); - private JTextField _alarmRocTextField = new JTextField(); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - private JButton _deleteButton = new JButton( "Delete" ); - - public DataLimitsEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "DataLimits Editor", true ); - _dataMgr = dataMgr; - updateRowDataLists(); - } - - private void updateRowDataLists() - { - _dataLimitsRowDataList = _dataMgr.getDataLimitsRowDataList(); - _locDataLimitsRowDataList = _dataMgr.getLocDataLimitsRowDataList(); - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1100, 825 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initListSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initFilters(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initFilters() - { - activateLidFilter( false ); - activatePEFilter( false ); - enableLidFilter( false ); - } - - private void initHashMaps() - { - _raxDLRowDataToRaxDLMap = _dataMgr.getRaxDataLimitsRowDataToRaxDataLimitsMap(); - _raxLocDLRowDataToRaxLocDLMap = _dataMgr.getRaxLocDataLimitsRowDataToRaxLocDataLimitsMap(); - } - - private void updateJTable( boolean refresh ) - { - if ( refresh ) - { - updateRowDataLists(); - } - String dataLimitsString = (String) _limitsLocLimitsCB.getSelectedItem(); - - if ( dataLimitsString.equalsIgnoreCase( "Location Limits" ) ) - { - _DLETableManager.setChangedAllRowDataList( _locDataLimitsRowDataList ); - enableLidFilter( true ); - } - else - { - _DLETableManager.setChangedAllRowDataList( _dataLimitsRowDataList ); - enableLidFilter( false ); - } - _DLETableManager.refreshDisplay(); - - } - private void initJTable() - { - _dataLimitsRowDataList = _dataMgr.getDataLimitsRowDataList(); - setLocDLEColumnDescriptorList(); - _DLETableManager = new ComplexJTableManager( _DLEColumnDescriptorList, _dataLimitsRowDataList, ListSelectionModel.SINGLE_SELECTION ); - enableLocationInColumnDescriptorList( false ); - String columnsSelected[] = _DLETableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _DLETableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _DLETableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 1000, 300 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _tableScrollPanePanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - - } - - private void initListSelectionPanel() - { - GridBagConstraints gbLabelConstraints = new GridBagConstraints(); - GridBagConstraints gbTFConstraints = new GridBagConstraints(); - GridBagConstraints gbFilterConstraints = new GridBagConstraints(); - JPanel filterPanel = new JPanel( new GridBagLayout() ); - JPanel hPanel = new JPanel(); - JPanel vPanel = new JPanel(); - JPanel vPanel2 = new JPanel(); - - gbLabelConstraints.anchor = GridBagConstraints.EAST; - gbLabelConstraints.weightx = 1; - gbLabelConstraints.weighty = 0; - - gbTFConstraints.anchor = GridBagConstraints.WEST; - gbTFConstraints.weightx = 1; - gbTFConstraints.weighty = 0; - - initJTable(); // Initializes the JTable - - _lidFilterTextBox.setColumns( 8 ); - - setupPEJList( _peFilterListModel, _peFilterJList ); // Set up the PE Filter JList - - _peFilterJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _peFilterScrollPane = new JScrollPane( _peFilterJList ); - - _peFilterScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); -// _peFilterJList.setPreferredSize( new Dimension( 215, 100 ) ); -// _peFilterScrollPane.setPreferredSize( new Dimension( 225, 100 ) ); - - _dataLimitsSelectionPanel.setBorder( BorderFactory.createTitledBorder( "Limits" ) ); -// _dataLimitsSelectionPanel.setPreferredSize( new Dimension( 1000, 600 ) ); - filterPanel.setBorder( BorderFactory.createTitledBorder( "Filters" ) ); -// filterPanel.setPreferredSize( new Dimension( 500, 500 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataLimitsSelectionPanel, _listLabel, gbLabelConstraints, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataLimitsSelectionPanel, _limitsLocLimitsCB, gbTFConstraints, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataLimitsSelectionPanel, vPanel2, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( filterPanel, _lidFilterCB, gbLabelConstraints, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( filterPanel, _lidFilterTextBox, gbTFConstraints, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( filterPanel, _peFilterCB, gbLabelConstraints, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( filterPanel, _peFilterScrollPane, gbTFConstraints, 2, 1, 1, 1, GridBagConstraints.NONE ); - - - gbFilterConstraints.gridx = 3; - gbFilterConstraints.gridy = 0; - gbFilterConstraints.gridwidth = 1; - gbFilterConstraints.gridheight = 1; - gbFilterConstraints.weightx = 1; - gbFilterConstraints.weighty = 1; - gbFilterConstraints.fill = GridBagConstraints.BOTH; - - GridBagLayout layoutMgr = (GridBagLayout) _dataLimitsSelectionPanel.getLayout(); - layoutMgr.setConstraints( filterPanel, gbFilterConstraints ); - - _dataLimitsSelectionPanel.add( filterPanel ); - - ComponentHelper.addPanelComponent( _dataLimitsSelectionPanel, hPanel, 0, 1, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _dataLimitsSelectionPanel, _tableScrollPanePanel, 0, 2, 10, 1, 1, 1, GridBagConstraints.BOTH ); - } - - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _dataLimitsSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void initSelectedItemPanel() - { - List shefDurList = _dataMgr.getShefDurationList(); - - GridBagConstraints gbLabelConstraints = new GridBagConstraints(); - GridBagConstraints gbTFConstraints = new GridBagConstraints(); - List shefDurationStringList = new ArrayList(); - JPanel lidDurDatesPanel = new JPanel( new GridBagLayout() ); - JPanel minMaxRangePanel = new JPanel( new GridBagLayout() ); - JPanel vPanel1 = new JPanel(); -// JPanel vPanel2 = new JPanel(); - JPanel vPanel3 = new JPanel(); - JPanel vPanel4 = new JPanel(); - JPanel hPanel1 = new JPanel(); - JPanel hPanel2 = new JPanel(); - JPanel hPanel3 = new JPanel(); - JPanel hPanel4 = new JPanel(); - - gbLabelConstraints.anchor = GridBagConstraints.EAST; - gbLabelConstraints.weightx = 1; - gbLabelConstraints.weighty = 0; - - gbTFConstraints.anchor = GridBagConstraints.WEST; - gbTFConstraints.weightx = 1; - gbTFConstraints.weighty = 0; - - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Limits for Selected Item" ) ); - minMaxRangePanel.setBorder( BorderFactory.createTitledBorder( "Quality Control Limits" ) ); - - setupPEJList( _peListModel, _peJList ); - - for ( int i = 0; i < shefDurList.size(); i++ ) - { - ShefDuration shefDur = (ShefDuration) shefDurList.get( i ); - shefDurationStringList.add( getShefDurationComboBoxString( shefDur ) ); - _durCBStringToDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur ); - } - - _durationComboBox = new JComboBox( shefDurationStringList.toArray() ); - - _peJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _peScrollPane = new JScrollPane( _peJList ); - - _lidTextField.setColumns( 7 ); - _startDateTextField.setColumns( 7 ); - _endDateTextField.setColumns( 7 ); - - _peScrollPane.setPreferredSize( new Dimension( 125, 100 ) ); - - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( lidDurDatesPanel, _lidLabel, gbLabelConstraints, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _lidTextField, gbTFConstraints, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, hPanel1, 1, 1, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _durationLabel, gbLabelConstraints, 1, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _durationComboBox, gbTFConstraints, 2, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, hPanel2, 1, 3, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _startDateLabel, gbLabelConstraints, 1, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _startDateTextField, gbTFConstraints, 2, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, hPanel3, 1, 5, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _endDateLabel, gbLabelConstraints, 1, 6, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( lidDurDatesPanel, _endDateTextField, gbTFConstraints, 2, 6, 1, 1, GridBagConstraints.NONE ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( minMaxRangePanel, vPanel3, 1, 0, 1, 4, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _minLabel, 2, 0, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, vPanel4, 3, 0, 1, 4, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _maxLabel, 4, 0, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _grossRangeLabel, gbLabelConstraints, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _grossRangeMinTF, gbTFConstraints, 2, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _grossRangeMaxTF, 4, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _reasonRangeLabel, gbLabelConstraints, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _reasonRangeMinTF, gbTFConstraints, 2, 2, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _reasonRangeMaxTF, 4, 2, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _rocLabel, gbLabelConstraints, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _rocTextField, gbTFConstraints, 2, 3, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _unitsLabel, 4, 3, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, hPanel4, 0, 4, 5, 2, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addPanelComponent( minMaxRangePanel, _alertAlarmLimitsLabel, 0, 6, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _limitsLabel, 2, 6, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _rocLimitLabel, 4, 6, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _alertLabel, gbLabelConstraints, 0, 7, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _alertTextField, gbTFConstraints, 2, 7, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _alertRocTextField, 4, 7, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _alarmLabel, gbLabelConstraints, 0, 8, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _alarmTextField,gbTFConstraints, 2, 8, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( minMaxRangePanel, _alarmRocTextField, 4, 8, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addPanelComponent( _selectedItemPanel, lidDurDatesPanel, 0, 0, 1, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _selectedItemPanel, vPanel1, 2, 0, 1, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _peLabel, 3, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _peScrollPane, 3, 1, 1, 1, 1, 4, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _selectedItemPanel, minMaxRangePanel, 4, 0, 1, 2, 1, 1, GridBagConstraints.BOTH ); - - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 3, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 4, 0, 1, 1, GridBagConstraints.NONE ); - } - - private void enableLocationInColumnDescriptorList( boolean enableLocation ) - { - if ( _DLEColumnDescriptorList != null ) - { - JTableColumnDescriptor colDesc = null; - - for ( int i = 0; i < _DLEColumnDescriptorList.size(); i++ ) - { - colDesc = (JTableColumnDescriptor) _DLEColumnDescriptorList.get( i ); - if ( colDesc.getColumnName().equalsIgnoreCase( "Location" ) ) - { - colDesc.setDisplay( enableLocation ); - break; - } - } - } - } - -/* - private void setDLEColumnDescriptorList() - { - _DLEColumnDescriptorList = new ArrayList(); - - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "PE", true, 30, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Dur", true, 75, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Start", true, 50, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "End", true, 50, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Gross Min", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Gross Max", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Reasonable
    Min", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Reasonable
    Max", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Rate of
    Change", true, 75, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alert Limit", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alert Limit
    ROC", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alarm Limit", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alarm Limit
    ROC", true, 100, "center" ) ); - } -*/ - - private void setLocDLEColumnDescriptorList() - { - _DLEColumnDescriptorList = new ArrayList(); - - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Location", true, 75, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "PE", true, 30, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Dur", true, 75, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Start", true, 50, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "End", true, 50, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Gross Min", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Gross Max", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Reasonable
    Min", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Reasonable
    Max", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Rate of
    Change", true, 75, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alert Limit", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alert Limit
    ROC", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alarm Limit", true, 100, "center" ) ); - _DLEColumnDescriptorList.add(new JTableColumnDescriptor( "Alarm Limit
    ROC", true, 100, "center" ) ); - } - - private String getShefPEJListString( ShefPE shefPE ) - { - String shefPEString = shefPE.getPe() + " " + shefPE.getName(); - - return shefPEString; - } - - private String getShefDurationComboBoxString( ShefDuration shefDuration ) - { - String shefDurationString = shefDuration.getName() + " ( " + shefDuration.getIduration() + "/" + shefDuration.getDuration() + " )"; - - return shefDurationString; - } - - private void setupPEJList( DefaultListModel listModel, JList peJList ) - { - List shefPeList = _dataMgr.getShefPeList(); - String peString = null; - - if ( _peJLStringList == null ) - { - _peJLStringList = new ArrayList(); - for ( int i = 0; i < shefPeList.size(); i++ ) - { - ShefPE shefPE = (ShefPE) shefPeList.get( i ); - _peJLStringList.add( getShefPEJListString( shefPE ) ); - _peJLStringToPeMap.put( getShefPEJListString( shefPE ), shefPE ); - } - } - - for ( int i = 0; i < _peJLStringList.size(); i++ ) - { - peString = (String) _peJLStringList.get( i ); - listModel.addElement( peString ); - } - - peJList.setModel( listModel ); - } - - private void activateLidFilter( boolean enable ) - { - if ( enable ) - { - _lidFilterTextBox.setEnabled( true ); - } - else - { - _lidFilterTextBox.setEnabled( false ); - } - } - - private void activatePEFilter( boolean enable ) - { - if ( enable ) - { - _peFilterJList.setEnabled( true ); - _peFilterScrollPane.setEnabled( true ); - } - else - { - _peFilterJList.setEnabled( false ); - _peFilterScrollPane.setEnabled( false ); - } - } - - private void enableLidFilter( boolean enable ) - { - if ( enable ) - { - _lidFilterCB.setVisible( true ); - _lidFilterTextBox.setVisible( true ); - _lidTextField.setVisible( true ); - _lidLabel.setVisible( true ); - } - else - { - _lidFilterCB.setVisible( false ); - _lidFilterTextBox.setVisible( false ); - _lidTextField.setVisible( false ); - _lidLabel.setVisible( false ); - } - } - - private void displayFilteredDataLimitsEntries() - { - _filteredRowDataList = filterRowData(); - - clearSelectedItemTextFields(); - -// _statusBar.setMessage( _filteredRowDataList.size() + " entries" ); -// System.out.println( "FilteredRowDataList has " + _filteredRowDataList.size() + " records" ); - - _DLETableManager.setChangedAllRowDataList( _filteredRowDataList ); - - _DLETableManager.refreshDisplay(); - } - - private List getLimitsLocLimitsCBRowDataList() - { - String dataLimitsString = (String) _limitsLocLimitsCB.getSelectedItem(); - List rowDataList = null; - - if ( dataLimitsString.equalsIgnoreCase( "Location Limits" ) ) - { - rowDataList = _locDataLimitsRowDataList; - } - else - { - rowDataList = _dataLimitsRowDataList; - } - - return rowDataList; - } - - private List filterRowData() - { - List filteredRowDataList = new ArrayList(); - List rowDataList = getLimitsLocLimitsCBRowDataList(); - - if ( ( _lidFilterCB.isSelected() ) || - ( _peFilterCB.isSelected() ) ) - { - ArcBaseDataLimitsJTableRowData rowData = null; - ArcBaseDataLimitsJTableRowData addRowData = null; - - for ( int i = 0; i < rowDataList.size(); i++ ) - { - rowData = (ArcBaseDataLimitsJTableRowData) rowDataList.get( i ); - - if ( ( passFilterByLid( rowData ) ) && - ( passFilterByPE( rowData ) ) ) - { - filteredRowDataList.add( rowData ); - } - } - } - else - { - return rowDataList; - } - return filteredRowDataList; - } - - private boolean passFilterByLid( ArcBaseDataLimitsJTableRowData rowData ) - { - boolean addRowData = false; // Only false if the checkbox is enabled AND does not match the filter string - - if ( _lidFilterCB.isSelected() ) - { - String rowDataLid = rowData.getLid().toLowerCase(); - - String filterString = _lidFilterTextBox.getText().trim().toLowerCase(); - - if ( rowDataLid.startsWith( filterString ) ) - { - addRowData = true; - } - } - else - { - addRowData = true; - } - return addRowData; - } - - private boolean passFilterByPE( ArcBaseDataLimitsJTableRowData rowData ) - { - boolean addRowData = false; //Only false if the checkbox is enabled and is not in the PE filter list - Object[] peJListObjectArray = null; - - if ( _peFilterCB.isSelected() ) - { - peJListObjectArray = _peFilterJList.getSelectedValues(); - Set selectedPESet = new HashSet(); - String peString = rowData.getPe(); - - for ( int i = 0; i < peJListObjectArray.length; i++ ) - { - selectedPESet.add( (String) peJListObjectArray[ i ] ); - } - - for ( int i = 0; i < _peJLStringList.size(); i++ ) - { - String peCBString = (String) _peJLStringList.get( i ); - if ( peCBString.startsWith( peString ) ) - { - if ( selectedPESet.contains( peCBString ) ) - { - addRowData = true; - } - } - } - } - else - { - addRowData = true; - } - return addRowData; - } - - private void clearSelectedItemTextFields() - { - _lidTextField.setText( "" ); - _startDateTextField.setText( "" ); - _endDateTextField.setText( "" ); - _grossRangeMinTF.setText( "" ); - _grossRangeMaxTF.setText( "" ); - _reasonRangeMinTF.setText( "" ); - _reasonRangeMaxTF.setText( "" ); - _rocTextField.setText( "" ); - _alertTextField.setText( "" ); - _alertRocTextField.setText( "" ); - _alarmTextField.setText( "" ); - _alarmRocTextField.setText( "" ); - _peJList.setSelectedIndex( 0 ); - _durationComboBox.setSelectedIndex( 0 ); - } - - private boolean saveToDatabase() - { - String dataLimitsString = (String) _limitsLocLimitsCB.getSelectedItem(); - boolean saved = false; - - if ( dataLimitsString.equalsIgnoreCase( "Location Limits" ) ) - { - RaxLocDataLimits raxLocDataLimits = new RaxLocDataLimits(); - ShefPE shefPe = (ShefPE) _peJLStringToPeMap.get( (String) _peJList.getSelectedValue() ); - ShefDuration shefDur = (ShefDuration) _durCBStringToDurMap.get( (String) _durationComboBox.getSelectedItem() ); - - raxLocDataLimits.setLid( _lidTextField.getText().toUpperCase() ); - raxLocDataLimits.setPe( shefPe.getPe() ); - raxLocDataLimits.setDur( shefDur.getDuration() ); - raxLocDataLimits.setIdur( shefDur.getIduration() ); - raxLocDataLimits.setMonthDayStart( _startDateTextField.getText() ); - raxLocDataLimits.setMonthDayEnd( _endDateTextField.getText() ); - raxLocDataLimits.setGrossRangeMin( getDoubleValue( _grossRangeMinTF.getText() ) ); - raxLocDataLimits.setGrossRangeMax( getDoubleValue( _grossRangeMaxTF.getText() ) ); - raxLocDataLimits.setReasonRangeMin( getDoubleValue( _reasonRangeMinTF.getText() ) ); - raxLocDataLimits.setReasonRangeMax( getDoubleValue( _reasonRangeMaxTF.getText() ) ); - raxLocDataLimits.setRoc( getDoubleValue( _rocTextField.getText() ) ); - raxLocDataLimits.setAlertLimit( getDoubleValue( _alertTextField.getText() ) ); - raxLocDataLimits.setAlertRocLimit( getDoubleValue( _alertRocTextField.getText() ) ); - raxLocDataLimits.setAlarmLimit( getDoubleValue( _alarmTextField.getText() ) ); - raxLocDataLimits.setAlarmRocLimit( getDoubleValue( _alarmRocTextField.getText() ) ); - - saved = _dataMgr.saveRaxLocDataLimits( raxLocDataLimits ); - - updateJTable( true ); - } - else - { - RaxDataLimits raxDataLimits = new RaxDataLimits(); - ShefPE shefPe = (ShefPE) _peJLStringToPeMap.get( (String) _peJList.getSelectedValue() ); - ShefDuration shefDur = (ShefDuration) _durCBStringToDurMap.get( (String) _durationComboBox.getSelectedItem() ); - - raxDataLimits.setPe( shefPe.getPe() ); - raxDataLimits.setDur( shefDur.getDuration() ); - raxDataLimits.setIdur( shefDur.getIduration() ); - raxDataLimits.setMonthDayStart( _startDateTextField.getText() ); - raxDataLimits.setMonthDayEnd( _endDateTextField.getText() ); - raxDataLimits.setGrossRangeMin( getDoubleValue( _grossRangeMinTF.getText() ) ); - raxDataLimits.setGrossRangeMax( getDoubleValue( _grossRangeMaxTF.getText() ) ); - raxDataLimits.setReasonRangeMin( getDoubleValue( _reasonRangeMinTF.getText() ) ); - raxDataLimits.setReasonRangeMax( getDoubleValue( _reasonRangeMaxTF.getText() ) ); - raxDataLimits.setRoc( getDoubleValue( _rocTextField.getText() ) ); - raxDataLimits.setAlertLimit( getDoubleValue( _alertTextField.getText() ) ); - raxDataLimits.setAlertRocLimit( getDoubleValue( _alertRocTextField.getText() ) ); - raxDataLimits.setAlarmLimit( getDoubleValue( _alarmTextField.getText() ) ); - raxDataLimits.setAlarmRocLimit( getDoubleValue( _alarmRocTextField.getText() ) ); - - saved = _dataMgr.saveRaxDataLimits( raxDataLimits ); - - updateJTable( true ); - } - - return saved; - } - - private double getDoubleValue( String value ) - { - double returnValue = DbTable.getNullDouble(); - - if ( ! value.equalsIgnoreCase( "" ) ) - { - returnValue = Double.parseDouble( value ); - } - - return returnValue; - } - - private void populateDataInputPanel( RaxLocDataLimits raxLocDataLimits, boolean local ) - { - if ( local ) - { - _lidTextField.setText( raxLocDataLimits.getLid() ); - } - _startDateTextField.setText( raxLocDataLimits.getMonthDayStart() ); - _endDateTextField.setText( raxLocDataLimits.getMonthDayEnd() ); - setNumberFields( _grossRangeMinTF, raxLocDataLimits.getGrossRangeMin() ); - setNumberFields( _grossRangeMaxTF, raxLocDataLimits.getGrossRangeMax() ); - setNumberFields( _reasonRangeMinTF, raxLocDataLimits.getReasonRangeMin() ); - setNumberFields( _reasonRangeMaxTF, raxLocDataLimits.getReasonRangeMax() ); - setNumberFields( _rocTextField, raxLocDataLimits.getRoc() ); - setNumberFields( _alertTextField, raxLocDataLimits.getAlertLimit() ); - setNumberFields( _alertRocTextField, raxLocDataLimits.getAlertRocLimit() ); - setNumberFields( _alarmTextField, raxLocDataLimits.getAlarmLimit() ); - setNumberFields( _alarmRocTextField, raxLocDataLimits.getAlarmRocLimit() ); - - ShefPE shefPE = (ShefPE) _dataMgr.getShefPEMap().get( raxLocDataLimits.getPe() ); - if ( shefPE != null ) - { - _peJList.setSelectedValue( getShefPEJListString( shefPE ), true ); - } - else - { - _peJList.clearSelection(); - } - - ShefDuration shefDur = (ShefDuration) _dataMgr.getShefDurationMap().get( raxLocDataLimits.getDur() ); - if ( shefDur != null ) - { - _durationComboBox.setSelectedItem( getShefDurationComboBoxString( shefDur ) ); - } - else - { - _durationComboBox.setSelectedItem( "" ); - } - - } - - private void setNumberFields( JTextField txtField, double doubleValue ) - { - if ( DbTable.isNull( doubleValue ) ) - { - txtField.setText( "" ); - } - else - { - txtField.setText( Double.toString( doubleValue ) ); - } - } - - private void deleteDataLimits() - { - String dataLimitsString = (String) _limitsLocLimitsCB.getSelectedItem(); - boolean delete = false; - - if ( dataLimitsString.equalsIgnoreCase( "Location Limits" ) ) - { - RaxLocDataLimits raxLocDataLimits = null; - List selectedRowsData = _DLETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseDataLimitsJTableRowData rowData = (ArcBaseDataLimitsJTableRowData) selectedRowsData.get( 0 ); - raxLocDataLimits = (RaxLocDataLimits) _raxLocDLRowDataToRaxLocDLMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxLocDataLimits.keyString(), "Delete LocDataLimit" ) ) - { - _dataMgr.deleteRaxLocDataLimitsFromDatabase( raxLocDataLimits ); - clearSelectedItemTextFields(); - updateJTable( true ); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Local Data Limit", "Delete LocDataLimit" ); - } - } - else - { - RaxDataLimits raxDataLimits = null; - List selectedRowsData = _DLETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseDataLimitsJTableRowData rowData = (ArcBaseDataLimitsJTableRowData) selectedRowsData.get( 0 ); - raxDataLimits = (RaxDataLimits) _raxDLRowDataToRaxDLMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxDataLimits.keyString(), "Delete DataLimit" ) ) - { - _dataMgr.deleteRaxDataLimitsFromDatabase( raxDataLimits ); - clearSelectedItemTextFields(); - updateJTable( true ); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Data Limit", "Delete DataLimit" ); - } - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _limitsLocLimitsCB.addActionListener( new LimitsLocLimitsComboBoxListener() ); - _lidFilterCB.addActionListener( new LidFilterCheckBoxListener() ); - _peFilterCB.addActionListener( new PEFilterCheckBoxListener() ); - _lidFilterTextBox.addKeyListener( new LidFilterTextFieldListener() ); - _peFilterJList.addListSelectionListener( new PEFilterJListListener() ); - - _DLETableManager.addTableListener( new DLETableListener() ); - - _closeButton.addActionListener( windowCloser ); - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - - addWindowListener( windowCloser ); - - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteDataLimits(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveToDatabase(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveToDatabase() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clearSelectedItemTextFields(); - } - } - - private class PEFilterJListListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - displayFilteredDataLimitsEntries(); - } - } - } - - private class DLETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - String dataLimitsString = (String) _limitsLocLimitsCB.getSelectedItem(); - List rowDataList = null; - - if ( dataLimitsString.equalsIgnoreCase( "Location Limits" ) ) - { - RaxLocDataLimits raxLocDataLimits = null; - - ArcBaseDataLimitsJTableRowData rowData = (ArcBaseDataLimitsJTableRowData) _DLETableManager.getSelectedRowsData().get( 0 ); - - raxLocDataLimits = (RaxLocDataLimits) _raxLocDLRowDataToRaxLocDLMap.get( rowData ); - - populateDataInputPanel( raxLocDataLimits, true ); - } - else - { - RaxLocDataLimits raxLocDataLimits = null; - RaxDataLimits raxDataLimits = null; - - ArcBaseDataLimitsJTableRowData rowData = (ArcBaseDataLimitsJTableRowData) _DLETableManager.getSelectedRowsData().get( 0 ); - - raxDataLimits = (RaxDataLimits) _raxDLRowDataToRaxDLMap.get( rowData ); - raxLocDataLimits = new RaxLocDataLimits( raxDataLimits ); - - populateDataInputPanel( raxLocDataLimits, false ); - } - - } - } - } - - private class PEFilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean enabled = _peFilterCB.isSelected(); - if ( enabled ) - { - activatePEFilter( true ); - } - else - { - activatePEFilter( false ); - _peFilterJList.clearSelection(); - displayFilteredDataLimitsEntries(); - } - } - } - - private class LidFilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean enabled = _lidFilterCB.isSelected(); - if ( enabled ) - { - activateLidFilter( true ); - } - else - { - activateLidFilter( false ); - _lidFilterTextBox.setText( "" ); - displayFilteredDataLimitsEntries(); - } - } - } - private class LimitsLocLimitsComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - activateLidFilter( false ); - activatePEFilter( false ); - _lidFilterCB.setSelected( false ); - _peFilterCB.setSelected( false ); - _lidFilterTextBox.setText( "" ); - boolean refresh = false; - -// updateJTable( refresh ); - - String dataLimitsString = (String) _limitsLocLimitsCB.getSelectedItem(); - - if ( dataLimitsString.equalsIgnoreCase( "Location Limits" ) ) - { - enableLocationInColumnDescriptorList( true ); - _DLETableManager.setChangedAllRowDataList( _locDataLimitsRowDataList ); - enableLidFilter( true ); - String columnsSelected[] = getFixedColumnOrderStringArray( _DLETableManager.getColumnNamesThatAreCurrentlyDisplayed() ); - _DLETableManager.setColumnsForDisplay( columnsSelected ); - } - else - { - enableLocationInColumnDescriptorList( false ); - _DLETableManager.setChangedAllRowDataList( _dataLimitsRowDataList ); - enableLidFilter( false ); - } - _DLETableManager.refreshDisplay(); - } - } - - private String[] getFixedColumnOrderStringArray( String[] columnStringArray ) - { - String[] columnsSelected = new String[ columnStringArray.length ]; - - columnsSelected[ 0 ] = "Location"; - - for ( int i = 1; i < columnStringArray.length; i++ ) - { - columnsSelected[ i ] = columnStringArray[ i - 1 ]; - } - - return columnsSelected; - } - - - private String[] getColumnDescriptorStringArray() - { - String[] columnDescriptorArray = null; - - if ( _DLEColumnDescriptorList != null ) - { - columnDescriptorArray = new String[ _DLEColumnDescriptorList.size() ]; - JTableColumnDescriptor colDesc = null; - - for ( int i = 0; i < _DLEColumnDescriptorList.size(); i++ ) - { - colDesc = (JTableColumnDescriptor) _DLEColumnDescriptorList.get( i ); - columnDescriptorArray[ i ] = colDesc.getColumnName(); - } - } - return columnDescriptorArray; - } - - - private class LidFilterTextFieldListener implements KeyListener - { - public void keyPressed( KeyEvent e ) - { - } - - public void keyReleased( KeyEvent e ) - { - if ( e.getKeyCode() != 16 ) // Shift key - { - displayFilteredDataLimitsEntries(); - } - } - - public void keyTyped( KeyEvent e ) - { - } - } - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser", "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser adb_ob83raxtest", "/fs/home/gsood/" ); - DataLimitsEditor dataLimitsEditorGUI = new DataLimitsEditor( frame, dataMgr ); - dataLimitsEditorGUI.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc2Editor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc2Editor.java deleted file mode 100644 index da95adbbaf..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc2Editor.java +++ /dev/null @@ -1,296 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Huc2; -import ohd.hseb.raxbase.table.ArcBaseHuc2JTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class Huc2Editor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _huc2TableManager = null; - private List _huc2ColumnDescriptorList = null; - private List _huc2RowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _huc2SelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _code12LTF = new LabeledTextField( "Code12:", "", "USGS region code", 3 ); - private LabeledTextField _code2LTF = new LabeledTextField( "Code2:", "", "USGS region code", 3 ); - private LabeledTextField _desregLTF = new LabeledTextField( "Description:", "", "Description", 60 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _huc2RowDataToHuc2Map = null; - - public Huc2Editor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Huc2 Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 940, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initHuc2SelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initHuc2SelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _huc2SelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Huc2" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _code12LTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code2LTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _desregLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _huc2RowDataToHuc2Map = _dataMgr.getHuc2RowDataToHuc2Map(); - } - - private void initJTable() - { - _huc2RowDataList = _dataMgr.getHuc2RowDataList(); - setCEColumnDescriptorList(); - _huc2TableManager = new ComplexJTableManager( _huc2ColumnDescriptorList, _huc2RowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _huc2TableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _huc2TableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _huc2TableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _huc2SelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _huc2RowDataList = _dataMgr.getHuc2RowDataList(); - _huc2TableManager.setChangedAllRowDataList( _huc2RowDataList ); - _huc2TableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _huc2ColumnDescriptorList = new ArrayList(); - - _huc2ColumnDescriptorList.add(new JTableColumnDescriptor( "Code12", true, 50, "center" ) ); - _huc2ColumnDescriptorList.add(new JTableColumnDescriptor( "Code2", true, 50, "center" ) ); - _huc2ColumnDescriptorList.add(new JTableColumnDescriptor( "Desc", true, 800, "center" ) ); - } - - private void populateDataInputPanel( Huc2 huc2 ) - { - if ( huc2 != null ) - { - _code12LTF.setTextField( huc2.getCode12() ); - _code2LTF.setTextField( huc2.getCode2() ); - _desregLTF.setTextField( huc2.getDesreg() ); - } - } - - private void clearDataInputPanel() - { - _code12LTF.setTextField( "" ); - _code2LTF.setTextField( "" ); - _desregLTF.setTextField( "" ); - } - - private boolean saveHuc2() - { - boolean saved = false; - - Huc2 huc2 = new Huc2(); - - huc2.setCode12( _code12LTF.getTextFieldText() ); - huc2.setCode2( _code2LTF.getTextFieldText() ); - huc2.setDesreg( _desregLTF.getTextFieldText() ); - - saved = _dataMgr.saveHuc2( huc2 ); - - updateJTable(); - - return saved; - } - - private void deleteHuc2() - { - Huc2 huc2 = null; - List selectedRowsData = _huc2TableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseHuc2JTableRowData rowData = (ArcBaseHuc2JTableRowData) selectedRowsData.get( 0 ); - huc2 = (Huc2) _huc2RowDataToHuc2Map.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + huc2.keyString(), "Delete Huc2" ) ) - { - _dataMgr.deleteHuc2FromDataBase( huc2 ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Huc2", "Delete Huc2" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _huc2TableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveHuc2(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveHuc2() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteHuc2(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Huc2 huc2 = null; - - ArcBaseHuc2JTableRowData rowData = (ArcBaseHuc2JTableRowData) _huc2TableManager.getSelectedRowsData().get( 0 ); - huc2 = (Huc2) _huc2RowDataToHuc2Map.get( rowData ); - populateDataInputPanel( huc2 ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - Huc2Editor huc2Editor = new Huc2Editor( frame, dataMgr ); - huc2Editor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc4Editor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc4Editor.java deleted file mode 100644 index 200633a47a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc4Editor.java +++ /dev/null @@ -1,302 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Huc4; -import ohd.hseb.raxbase.table.ArcBaseHuc4JTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class Huc4Editor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _huc4TableManager = null; - private List _huc4ColumnDescriptorList = null; - private List _huc4RowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _huc4SelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _code12LTF = new LabeledTextField( "Code12:", "", "USGS region code", 3 ); - private LabeledTextField _code34LTF = new LabeledTextField( "Code34:", "", "USGS region code", 3 ); - private LabeledTextField _code4LTF = new LabeledTextField( "Code4:", "", "USGS region code", 5 ); - private LabeledTextField _dessubregLTF = new LabeledTextField( "Description:", "", "Description", 60 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _huc4RowDataToHuc4Map = null; - - public Huc4Editor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Huc4 Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 980, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initHuc4SelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initHuc4SelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _huc4SelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Huc4" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _code12LTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code34LTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code4LTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _dessubregLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _huc4RowDataToHuc4Map = _dataMgr.getHuc4RowDataToHuc4Map(); - } - - private void initJTable() - { - _huc4RowDataList = _dataMgr.getHuc4RowDataList(); - setCEColumnDescriptorList(); - _huc4TableManager = new ComplexJTableManager( _huc4ColumnDescriptorList, _huc4RowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _huc4TableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _huc4TableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _huc4TableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _huc4SelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _huc4RowDataList = _dataMgr.getHuc4RowDataList(); - _huc4TableManager.setChangedAllRowDataList( _huc4RowDataList ); - _huc4TableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _huc4ColumnDescriptorList = new ArrayList(); - - _huc4ColumnDescriptorList.add(new JTableColumnDescriptor( "Code12", true, 50, "center" ) ); - _huc4ColumnDescriptorList.add(new JTableColumnDescriptor( "Code34", true, 50, "center" ) ); - _huc4ColumnDescriptorList.add(new JTableColumnDescriptor( "Code4", true, 50, "center" ) ); - _huc4ColumnDescriptorList.add(new JTableColumnDescriptor( "Desc", true, 800, "center" ) ); - } - - private void populateDataInputPanel( Huc4 huc4 ) - { - if ( huc4 != null ) - { - _code12LTF.setTextField( huc4.getCode12() ); - _code34LTF.setTextField( huc4.getCode34() ); - _code4LTF.setTextField( huc4.getCode4() ); - _dessubregLTF.setTextField( huc4.getDessubreg() ); - } - } - - private void clearDataInputPanel() - { - _code12LTF.setTextField( "" ); - _code34LTF.setTextField( "" ); - _code4LTF.setTextField( "" ); - _dessubregLTF.setTextField( "" ); - } - - private boolean saveHuc4() - { - boolean saved = false; - - Huc4 huc4 = new Huc4(); - - huc4.setCode12( _code12LTF.getTextFieldText() ); - huc4.setCode34( _code34LTF.getTextFieldText() ); - huc4.setCode4( _code4LTF.getTextFieldText() ); - huc4.setDessubreg( _dessubregLTF.getTextFieldText() ); - - saved = _dataMgr.saveHuc4( huc4 ); - - updateJTable(); - - return saved; - } - - private void deleteHuc4() - { - Huc4 huc4 = null; - List selectedRowsData = _huc4TableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseHuc4JTableRowData rowData = (ArcBaseHuc4JTableRowData) selectedRowsData.get( 0 ); - huc4 = (Huc4) _huc4RowDataToHuc4Map.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + huc4.keyString(), "Delete Huc4" ) ) - { - _dataMgr.deleteHuc4FromDataBase( huc4 ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Huc4", "Delete Huc4" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _huc4TableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveHuc4(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveHuc4() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteHuc4(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Huc4 huc4 = null; - - ArcBaseHuc4JTableRowData rowData = (ArcBaseHuc4JTableRowData) _huc4TableManager.getSelectedRowsData().get( 0 ); - huc4 = (Huc4) _huc4RowDataToHuc4Map.get( rowData ); - populateDataInputPanel( huc4 ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - Huc4Editor huc4Editor = new Huc4Editor( frame, dataMgr ); - huc4Editor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc6Editor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc6Editor.java deleted file mode 100644 index b343ed7da2..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc6Editor.java +++ /dev/null @@ -1,308 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Huc6; -import ohd.hseb.raxbase.table.ArcBaseHuc6JTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class Huc6Editor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _huc6TableManager = null; - private List _huc6ColumnDescriptorList = null; - private List _huc6RowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _huc6SelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _code12LTF = new LabeledTextField( "Code12:", "", "USGS region code", 3 ); - private LabeledTextField _code34LTF = new LabeledTextField( "Code34:", "", "USGS region code", 3 ); - private LabeledTextField _code56LTF = new LabeledTextField( "Code56:", "", "USGS region code", 3 ); - private LabeledTextField _code6LTF = new LabeledTextField( "Code6:", "", "USGS region code", 7 ); - private LabeledTextField _desacctLTF = new LabeledTextField( "Description:", "", "Description", 60 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _huc6RowDataToHuc6Map = null; - - public Huc6Editor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Huc6 Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1050, 500 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initHuc6SelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initHuc6SelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _huc6SelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Huc6" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _code12LTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code34LTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code56LTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code6LTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _desacctLTF, 0, 4, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _huc6RowDataToHuc6Map = _dataMgr.getHuc6RowDataToHuc6Map(); - } - - private void initJTable() - { - _huc6RowDataList = _dataMgr.getHuc6RowDataList(); - setCEColumnDescriptorList(); - _huc6TableManager = new ComplexJTableManager( _huc6ColumnDescriptorList, _huc6RowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _huc6TableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _huc6TableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _huc6TableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _huc6SelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _huc6RowDataList = _dataMgr.getHuc6RowDataList(); - _huc6TableManager.setChangedAllRowDataList( _huc6RowDataList ); - _huc6TableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _huc6ColumnDescriptorList = new ArrayList(); - - _huc6ColumnDescriptorList.add(new JTableColumnDescriptor( "Code12", true, 50, "center" ) ); - _huc6ColumnDescriptorList.add(new JTableColumnDescriptor( "Code34", true, 50, "center" ) ); - _huc6ColumnDescriptorList.add(new JTableColumnDescriptor( "Code56", true, 50, "center" ) ); - _huc6ColumnDescriptorList.add(new JTableColumnDescriptor( "Code6", true, 70, "center" ) ); - _huc6ColumnDescriptorList.add(new JTableColumnDescriptor( "Desc", true, 800, "center" ) ); - } - - private void populateDataInputPanel( Huc6 huc6 ) - { - if ( huc6 != null ) - { - _code12LTF.setTextField( huc6.getCode12() ); - _code34LTF.setTextField( huc6.getCode34() ); - _code56LTF.setTextField( huc6.getCode56() ); - _code6LTF.setTextField( huc6.getCode6() ); - _desacctLTF.setTextField( huc6.getDesacct() ); - } - } - - private void clearDataInputPanel() - { - _code12LTF.setTextField( "" ); - _code34LTF.setTextField( "" ); - _code56LTF.setTextField( "" ); - _code6LTF.setTextField( "" ); - _desacctLTF.setTextField( "" ); - } - - private boolean saveHuc6() - { - boolean saved = false; - - Huc6 huc6 = new Huc6(); - - huc6.setCode12( _code12LTF.getTextFieldText() ); - huc6.setCode34( _code34LTF.getTextFieldText() ); - huc6.setCode56( _code56LTF.getTextFieldText() ); - huc6.setCode6( _code6LTF.getTextFieldText() ); - huc6.setDesacct( _desacctLTF.getTextFieldText() ); - - saved = _dataMgr.saveHuc6( huc6 ); - - updateJTable(); - - return saved; - } - - private void deleteHuc6() - { - Huc6 huc6 = null; - List selectedRowsData = _huc6TableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseHuc6JTableRowData rowData = (ArcBaseHuc6JTableRowData) selectedRowsData.get( 0 ); - huc6 = (Huc6) _huc6RowDataToHuc6Map.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + huc6.keyString(), "Delete Huc6" ) ) - { - _dataMgr.deleteHuc6FromDataBase( huc6 ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Huc6", "Delete Huc6" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _huc6TableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveHuc6(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveHuc6() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteHuc6(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Huc6 huc6 = null; - - ArcBaseHuc6JTableRowData rowData = (ArcBaseHuc6JTableRowData) _huc6TableManager.getSelectedRowsData().get( 0 ); - huc6 = (Huc6) _huc6RowDataToHuc6Map.get( rowData ); - populateDataInputPanel( huc6 ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - Huc6Editor huc6Editor = new Huc6Editor( frame, dataMgr ); - huc6Editor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc8Editor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc8Editor.java deleted file mode 100644 index 99002f5136..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/Huc8Editor.java +++ /dev/null @@ -1,314 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Huc8; -import ohd.hseb.raxbase.table.ArcBaseHuc8JTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class Huc8Editor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _huc8TableManager = null; - private List _huc8ColumnDescriptorList = null; - private List _huc8RowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _huc8SelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _code12LTF = new LabeledTextField( "Code12:", "", "USGS region code", 3 ); - private LabeledTextField _code34LTF = new LabeledTextField( "Code34:", "", "USGS region code", 3 ); - private LabeledTextField _code56LTF = new LabeledTextField( "Code56:", "", "USGS region code", 3 ); - private LabeledTextField _code78LTF = new LabeledTextField( "Code78:", "", "USGS region code", 3 ); - private LabeledTextField _code8LTF = new LabeledTextField( "Code8:", "", "USGS region code", 9 ); - private LabeledTextField _desactLTF = new LabeledTextField( "Description:", "", "Description", 60 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _huc8RowDataToHuc8Map = null; - - public Huc8Editor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Huc8 Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1150, 500 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initHuc8SelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initHuc8SelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _huc8SelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Huc8" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _code12LTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code34LTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code56LTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code78LTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _code8LTF, 0, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _desactLTF, 0, 5, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _huc8RowDataToHuc8Map = _dataMgr.getHuc8RowDataToHuc8Map(); - } - - private void initJTable() - { - _huc8RowDataList = _dataMgr.getHuc8RowDataList(); - setCEColumnDescriptorList(); - _huc8TableManager = new ComplexJTableManager( _huc8ColumnDescriptorList, _huc8RowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _huc8TableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _huc8TableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _huc8TableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _huc8SelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _huc8RowDataList = _dataMgr.getHuc8RowDataList(); - _huc8TableManager.setChangedAllRowDataList( _huc8RowDataList ); - _huc8TableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _huc8ColumnDescriptorList = new ArrayList(); - - _huc8ColumnDescriptorList.add(new JTableColumnDescriptor( "Code12", true, 60, "center" ) ); - _huc8ColumnDescriptorList.add(new JTableColumnDescriptor( "Code34", true, 60, "center" ) ); - _huc8ColumnDescriptorList.add(new JTableColumnDescriptor( "Code56", true, 60, "center" ) ); - _huc8ColumnDescriptorList.add(new JTableColumnDescriptor( "Code78", true, 60, "center" ) ); - _huc8ColumnDescriptorList.add(new JTableColumnDescriptor( "Code8", true, 80, "center" ) ); - _huc8ColumnDescriptorList.add(new JTableColumnDescriptor( "Desc", true, 800, "center" ) ); - } - - private void populateDataInputPanel( Huc8 huc8 ) - { - if ( huc8 != null ) - { - _code12LTF.setTextField( huc8.getCode12() ); - _code34LTF.setTextField( huc8.getCode34() ); - _code56LTF.setTextField( huc8.getCode56() ); - _code78LTF.setTextField( huc8.getCode78() ); - _code8LTF.setTextField( huc8.getCode8() ); - _desactLTF.setTextField( huc8.getDescat() ); - } - } - - private void clearDataInputPanel() - { - _code12LTF.setTextField( "" ); - _code34LTF.setTextField( "" ); - _code56LTF.setTextField( "" ); - _code78LTF.setTextField( "" ); - _code8LTF.setTextField( "" ); - _desactLTF.setTextField( "" ); - } - - private boolean saveHuc8() - { - boolean saved = false; - - Huc8 huc8 = new Huc8(); - - huc8.setCode12( _code12LTF.getTextFieldText() ); - huc8.setCode34( _code34LTF.getTextFieldText() ); - huc8.setCode56( _code56LTF.getTextFieldText() ); - huc8.setCode78( _code78LTF.getTextFieldText() ); - huc8.setCode8( _code8LTF.getTextFieldText() ); - huc8.setDescat( _desactLTF.getTextFieldText() ); - - saved = _dataMgr.saveHuc8( huc8 ); - - updateJTable(); - - return saved; - } - - private void deleteHuc8() - { - Huc8 huc8 = null; - List selectedRowsData = _huc8TableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseHuc8JTableRowData rowData = (ArcBaseHuc8JTableRowData) selectedRowsData.get( 0 ); - huc8 = (Huc8) _huc8RowDataToHuc8Map.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + huc8.keyString(), "Delete Huc8" ) ) - { - _dataMgr.deleteHuc8FromDataBase( huc8 ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Huc8", "Delete Huc8" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _huc8TableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveHuc8(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveHuc8() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteHuc8(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Huc8 huc8 = null; - - ArcBaseHuc8JTableRowData rowData = (ArcBaseHuc8JTableRowData) _huc8TableManager.getSelectedRowsData().get( 0 ); - huc8 = (Huc8) _huc8RowDataToHuc8Map.get( rowData ); - populateDataInputPanel( huc8 ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - Huc8Editor huc8Editor = new Huc8Editor( frame, dataMgr ); - huc8Editor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/IngestFilterEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/IngestFilterEditor.java deleted file mode 100644 index 2663f6a5fc..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/IngestFilterEditor.java +++ /dev/null @@ -1,1149 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxIngestFilter; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.raxbase.table.ArcBaseIngestFilterJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class IngestFilterEditor extends JDialog implements PropertyChangeListener -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private Map _raxIFRowDataToRaxIFMap = new HashMap(); - - private Map _peCBStringToPeMap = new HashMap(); - private Map _durCBStringToDurMap = new HashMap(); - private Map _durCBStringToIDurMap = new HashMap(); - private Map _tsCBStringToTSMap = new HashMap(); - private Map _extremumCBStringToExtremumMap = new HashMap(); - - private JPanel _ingestFilterListPanel = new JPanel( new GridBagLayout() ); - - private StatusBar _statusBar = new StatusBar(); - -// JTable variables - private JTableManager _IFETableManager = null; - private List _IFEColumnDescriptorList = null; - private List _allRowDataList = null; - private List _filteredRowDataList = null; //Filtered row data entries - private JScrollPane _tableScrollPane = null; - - private JPanel _dataInputPanel = new JPanel( new GridBagLayout() ); - private JLabel _lidLabel = new JLabel( "Location:" ); - private JTextField _lidTextField = new JTextField(); - private JLabel _peLabel = new JLabel( "Physical Element:" ); - private JComboBox _peComboBox = new JComboBox(); - private JLabel _durationLabel = new JLabel( "Duration:" ); - private JComboBox _durationComboBox = new JComboBox(); - private JLabel _typeSourceLabel = new JLabel( "Type Source:" ); - private JComboBox _typeSourceComboBox = new JComboBox(); - private JLabel _extremumLabel = new JLabel( "Extremum:" ); - private JComboBox _extremumComboBox = new JComboBox(); - private JLabel _rankLabel = new JLabel( "Type Source Rank:" ); - private JComboBox _rankComboBox = new JComboBox(); - private JLabel _masterLabel = new JLabel( "Master Switch:" ); - private JCheckBox _masterCheckBox = new JCheckBox(); - private JLabel _ofsLabel = new JLabel( "OFS Input Switch" ); - private JCheckBox _ofsCheckBox = new JCheckBox(); - private JLabel _mpeInputLabel = new JLabel( "MPE Input Switch:" ); - private JCheckBox _mpeInputCheckBox = new JCheckBox(); - private JLabel _detailLabel = new JLabel( "Detail:" ); - private JTextField _detailTextField = new JTextField(); - private JLabel _newReportLabel = new JLabel( "New Report:" ); - private JCheckBox _newReportCheckBox = new JCheckBox(); - private JLabel _activeLabel = new JLabel( "Active:" ); - private JCheckBox _activeCheckBox = new JCheckBox(); - private JLabel _obsTimeLabel = new JLabel( "ObsTime:" ); - private JTextField _obsTimeTextField = new JTextField(); - private JLabel _ownAgencyLabel = new JLabel( "Owner Agency:" ); - private JTextField _ownAgencyTextField = new JTextField(); - private JLabel _ownLocationLabel = new JLabel( "Owner Location:" ); - private JTextField _ownLocationTextField = new JTextField(); - - private List _peCBStringList = new ArrayList(); - private List _tsCBStringList = new ArrayList(); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveButton = new JButton( "Save to Database" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - private JButton _deleteButton = new JButton( "Delete Highlighted Entry" ); - - private JPanel _filterPanel = new JPanel( new GridBagLayout() ); - private JLabel _filterByLabel = new JLabel( "Filter By:" ); - private JCheckBox _lidFilterCheckBox = new JCheckBox(); - private JCheckBox _tsFilterCheckBox = new JCheckBox(); - private JCheckBox _peFilterCheckBox = new JCheckBox(); - private JCheckBox _switchesFilterCheckBox = new JCheckBox(); - private JLabel _lidFilterPanelLabel = new JLabel( "Location:" ); - private JLabel _peFilterPanelLabel = new JLabel( "Physical Element:" ); - private JLabel _tsFilterPanelLabel = new JLabel( "Type Source:" ); - private JLabel _switchesFilterPanelLabel = new JLabel( "Switches:" ); - private JTextField _lidFilterTextField = new JTextField(); - private JList _peJList = null; - private JScrollPane _peScrollPane = new JScrollPane(); - private DefaultListModel _peListModel = new DefaultListModel(); - private JComboBox _tsFilterComboBox = new JComboBox(); - private JCheckBox _masterFilterCB = new JCheckBox(); - private JCheckBox _ofsFilterCB = new JCheckBox(); - private JCheckBox _mpeFilterCB = new JCheckBox(); - - public IngestFilterEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Ingest Filter Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1100, 825 ) ); - initData(); - } - - private void initData() - { - _dataMgr.initIngestFilterRowData( this ); - } - - public void propertyChange( PropertyChangeEvent evt ) - { - initGUI(); - } - - public void initGUI() - { - setLayout( new GridBagLayout() ); - _raxIFRowDataToRaxIFMap = _dataMgr.getRaxIngestFilterRowDataToRaxIngestFilterMap(); - initJTable(); - initFrameComponenets(); - initComboBoxes(); - initDataInputPanel(); - initButtonPanel(); - initFilterPanel(); - _statusBar.setMessage( _allRowDataList.size() + " entries" ); - addListeners(); - pack(); - setVisible( true ); - } - - - private void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "IngestFilter Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 3, 0, 1, 1, GridBagConstraints.NONE ); - } - - private void initFilterPanel() - { - JLabel horizontalLabel = new JLabel( "---------------------------" ); - - _filterPanel.setBorder( BorderFactory.createTitledBorder( "Filter Parameters" ) ); - - _lidFilterCheckBox.setText( "Location" ); - _tsFilterCheckBox.setText( "Type Source" ); - _peFilterCheckBox.setText( "Physical Element" ); - _switchesFilterCheckBox.setText( "Switches" ); - _masterFilterCB.setText( "Master" ); - _ofsFilterCB.setText( "OFS" ); - _mpeFilterCB.setText( "MPE" ); - - _lidFilterTextField.setColumns( 9 ); - - setupPEJlist(); -// _peJList.setPreferredSize( new Dimension( 100, 100 ) ); - _peJList.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); - _peScrollPane = new JScrollPane( _peJList ); - - _tsFilterComboBox = new JComboBox( _tsCBStringList.toArray() ); - - activateLIDFilter( false ); - activatePEFilter( false ); - activateTSFilter( false ); - activateSwitchesFilter( false ); - - JPanel switchFilterPanel = new JPanel( new GridBagLayout() ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _filterPanel, _filterByLabel, 0, 0, 2, 2, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _lidFilterCheckBox, 2, 0, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _tsFilterCheckBox, 4, 0, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _peFilterCheckBox, 2, 1, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _switchesFilterCheckBox, 4, 1, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, horizontalLabel, 0, 2, 6, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _lidFilterPanelLabel, 0, 3, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _lidFilterTextField, 2, 3, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _peFilterPanelLabel, 0, 4, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _peScrollPane, 2, 4, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _tsFilterPanelLabel, 0, 5, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, _tsFilterComboBox, 2, 5, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _filterPanel, switchFilterPanel, 0, 6, 4, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( switchFilterPanel, _switchesFilterPanelLabel, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( switchFilterPanel, _masterFilterCB, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( switchFilterPanel, _ofsFilterCB, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( switchFilterPanel, _mpeFilterCB, 3, 0, 1, 1, GridBagConstraints.NONE ); - - } - - private void activateLIDFilter( boolean active ) - { - if ( active ) - { - _lidFilterPanelLabel.setEnabled( true ); - _lidFilterTextField.setEnabled( true ); - } - else - { - _lidFilterPanelLabel.setEnabled( false ); - _lidFilterTextField.setEnabled( false ); - _lidFilterTextField.setText( "" ); - } - } - - private void activatePEFilter( boolean active ) - { - if ( active ) - { - _peFilterPanelLabel.setEnabled( true ); - _peScrollPane.setEnabled( true ); - _peJList.setEnabled( true ); - } - else - { - _peFilterPanelLabel.setEnabled( false ); - _peScrollPane.setEnabled( false ); - _peJList.setEnabled( false ); - } - } - - private void activateTSFilter( boolean active ) - { - if ( active ) - { - _tsFilterPanelLabel.setEnabled( true ); - _tsFilterComboBox.setEnabled( true ); - } - else - { - _tsFilterPanelLabel.setEnabled( false ); - _tsFilterComboBox.setEnabled( false ); - _tsFilterComboBox.setSelectedIndex( 0 ); - } - } - - private void activateSwitchesFilter( boolean active ) - { - if ( active ) - { - _switchesFilterPanelLabel.setEnabled( true ); - _masterFilterCB.setEnabled( true ); - _ofsFilterCB.setEnabled( true ); - _mpeFilterCB.setEnabled( true ); - } - else - { - _switchesFilterPanelLabel.setEnabled( false ); - _masterFilterCB.setEnabled( false ); - _masterFilterCB.setSelected( false ); - _ofsFilterCB.setEnabled( false ); - _ofsFilterCB.setSelected( false ); - _mpeFilterCB.setEnabled( false ); - _mpeFilterCB.setSelected( false ); - } - } - - private void setupPEJlist() - { - String peString = null; - for ( int i = 0; i < _peCBStringList.size(); i++ ) - { - peString = (String) _peCBStringList.get( i ); - _peListModel.addElement( peString ); - } - - _peJList = new JList( _peListModel ); - } - - private void initComboBoxes() - { - List shefPeList = _dataMgr.getShefPeList(); - List shefDurationList = _dataMgr.getShefDurationList(); - List shefTypeSourceList = _dataMgr.getShefTSList(); - List shefExtremumList = _dataMgr.getShefExtremumList(); - - List shefPeStringList = new ArrayList(); - List shefDurationStringList = new ArrayList(); - List shefTypeSourceStringList = new ArrayList(); - List shefExtremumStringList = new ArrayList(); - String[] tsRankStringArray = { "", "1st", "2nd", "3rd", "4th", "5th" }; - - shefPeStringList.add( "" ); - for ( int i = 0; i < shefPeList.size(); i++ ) - { - ShefPE shefPE = (ShefPE) shefPeList.get( i ); - shefPeStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringToPeMap.put( getShefPEComboBoxString( shefPE ), shefPE.getPe() ); - } - - shefDurationStringList.add( "" ); - for ( int i = 0; i < shefDurationList.size(); i++ ) - { - ShefDuration shefDur = (ShefDuration) shefDurationList.get( i ); - shefDurationStringList.add( getShefDurationComboBoxString( shefDur ) ); - _durCBStringToDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur.getDuration() ); - _durCBStringToIDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur.getIduration() ); - } - - shefTypeSourceStringList.add( "" ); - for ( int i = 0; i < shefTypeSourceList.size(); i++ ) - { - ShefTS shefTS = (ShefTS) shefTypeSourceList.get( i ); - shefTypeSourceStringList.add( getShefTSString( shefTS ) ); - _tsCBStringList.add( getShefTSString( shefTS ) ); - _tsCBStringToTSMap.put( getShefTSString( shefTS ), shefTS.getTs() ); - } - - shefExtremumStringList.add( "" ); - for ( int i = 0; i < shefExtremumList.size(); i++ ) - { - ShefExtremum shefEx = (ShefExtremum) shefExtremumList.get( i ); - shefExtremumStringList.add( getShefExtremumComboBoxString(shefEx ) ); - _extremumCBStringToExtremumMap.put( getShefExtremumComboBoxString( shefEx ), shefEx.getExtremum() ); - } - - _peComboBox = new JComboBox( shefPeStringList.toArray() ); - _durationComboBox = new JComboBox( shefDurationStringList.toArray() ); - _typeSourceComboBox = new JComboBox( shefTypeSourceStringList.toArray() ); - _extremumComboBox = new JComboBox( shefExtremumStringList.toArray() ); - - _rankComboBox = new JComboBox( tsRankStringArray ); - } - - private String getShefExtremumComboBoxString( ShefExtremum shefEx ) - { - String shefExtremumString = shefEx.getName() + " (" + shefEx.getExtremum() + ")"; - - return shefExtremumString; - } - - private String getShefTSString( ShefTS shefTS ) - { - String shefTSString = shefTS.getName() + " (" + shefTS.getTs() + ")"; - - return shefTSString; - } - - private String getShefPEComboBoxString( ShefPE shefPE ) - { - String shefPEString = shefPE.getPe() + " " + shefPE.getName(); - - return shefPEString; - } - - private String getShefDurationComboBoxString( ShefDuration shefDuration ) - { - String shefDurationString = shefDuration.getName() + " ( " + shefDuration.getIduration() + "/" + shefDuration.getDuration() + " )"; - - return shefDurationString; - } - - private void initDataInputPanel() - { - GridBagConstraints gbLabelConstraints = new GridBagConstraints(); - GridBagConstraints gbTFConstraints = new GridBagConstraints(); - _dataInputPanel.setBorder( BorderFactory.createTitledBorder( "Selected Item" ) ); - - gbLabelConstraints.anchor = GridBagConstraints.EAST; - gbLabelConstraints.weightx = 1; - gbLabelConstraints.weighty = 0; - - gbTFConstraints.anchor = GridBagConstraints.WEST; - gbTFConstraints.weightx = 1; - gbTFConstraints.weighty = 0; - - _lidTextField.setColumns( 8 ); - _detailTextField.setColumns( 45 ); - _obsTimeTextField.setColumns( 20 ); - _ownAgencyTextField.setColumns( 7 ); - _ownLocationTextField.setColumns( 4 ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataInputPanel, _lidLabel, gbLabelConstraints, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _lidTextField, gbTFConstraints, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _peLabel, gbLabelConstraints, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _peComboBox, gbTFConstraints, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _durationLabel, gbLabelConstraints, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _durationComboBox, gbTFConstraints, 1, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _typeSourceLabel, gbLabelConstraints, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _typeSourceComboBox, gbTFConstraints, 1, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _extremumLabel, gbLabelConstraints, 0, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _extremumComboBox, gbTFConstraints, 1, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _rankLabel, gbLabelConstraints, 0, 5, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _rankComboBox, gbTFConstraints, 1, 5, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _masterLabel, gbLabelConstraints, 0, 6, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _masterCheckBox, gbTFConstraints, 1, 6, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _ofsLabel, gbLabelConstraints, 0, 7, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _ofsCheckBox, gbTFConstraints, 1, 7, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _mpeInputLabel, gbLabelConstraints, 0, 8, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _mpeInputCheckBox, gbTFConstraints, 1, 8, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _detailLabel, gbLabelConstraints, 0, 9, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _detailTextField, gbTFConstraints, 1, 9, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _newReportLabel, gbLabelConstraints, 0, 10, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _newReportCheckBox, gbTFConstraints, 1, 10, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _activeLabel, gbLabelConstraints, 0, 11, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _activeCheckBox, gbTFConstraints, 1, 11, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _obsTimeLabel, gbLabelConstraints, 0, 12, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _obsTimeTextField, gbTFConstraints, 1, 12, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _ownAgencyLabel, gbLabelConstraints, 0, 13, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _ownAgencyTextField, gbTFConstraints, 1, 13, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _ownLocationLabel, gbLabelConstraints, 0, 14, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _ownLocationTextField, gbTFConstraints, 1, 14, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponenets() - { - _dialogContentPane.setLayout( new GridBagLayout() ); - JPanel horizontalPanel = new JPanel(); - horizontalPanel.setPreferredSize(new Dimension( 50, 50 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _filterPanel, 2, 0, 2, 10, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _dataInputPanel, 0, 11, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 12, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, horizontalPanel, 0, 13, 4, 1, 1, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _statusBar, 0, 14, 4, 1, GridBagConstraints.BOTH ); - } - - /** - * Initialize the ArcBase JTable - * - * @return None - * - */ - private void initJTable() - { - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _allRowDataList = _dataMgr.getIngestFilterRowDataList(); - setIFEColumnDescriptorList(); - _IFETableManager = new ComplexJTableManager( _IFEColumnDescriptorList, _allRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _IFETableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _IFETableManager.setDisplayableColumns( columnsSelected, true, true ); - _IFETableManager.setPreferredSizeForJScrollPane( new Dimension( 550, 300 ) ); - _tableScrollPane = _IFETableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel( new GridLayout( 1, 1 ) ); - tableScrollPanePanel.add( _tableScrollPane ); - tableScrollPanePanel.setPreferredSize( new Dimension( 555,310 ) ); - tableScrollPanePanel.setBorder( BorderFactory.createTitledBorder( "Ingest Filter Contents for Locations" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, tableScrollPanePanel, 0, 0, 2, 10, 1, 1, GridBagConstraints.BOTH ); - - } - - private void displayFilteredIngestFilterEntries() - { - _filteredRowDataList = filterRowData(); - - _statusBar.setMessage( _filteredRowDataList.size() + " entries" ); -// System.out.println( "FilteredRowDataList has " + _filteredRowDataList.size() + " records" ); - - _IFETableManager.setChangedAllRowDataList( _filteredRowDataList ); - - _IFETableManager.refreshDisplay(); - - } - - - private List filterRowData() - { - List filteredRowDataList = new ArrayList(); - - if ( ( _lidFilterCheckBox.isSelected() ) || - ( _tsFilterCheckBox.isSelected() ) || - ( _peFilterCheckBox.isSelected() ) || - ( _switchesFilterCheckBox.isSelected() ) ) - { - ArcBaseIngestFilterJTableRowData rowData = null; - ArcBaseIngestFilterJTableRowData addRowData = null; - - for ( int i = 0; i < _allRowDataList.size(); i++ ) - { - rowData = (ArcBaseIngestFilterJTableRowData) _allRowDataList.get( i ); - - if ( ( passFilterByLid( rowData ) ) && - ( passFilterByPE( rowData ) ) && - ( passFilterByTS( rowData ) ) && - ( passFilterBySwitches( rowData ) ) ) - { - filteredRowDataList.add( rowData ); - } - } - } - else - { - return _allRowDataList; - } - - return filteredRowDataList; - } - - private boolean passFilterBySwitches( ArcBaseIngestFilterJTableRowData rowData ) - { - boolean addRowData = false; - - if ( _switchesFilterCheckBox.isSelected() ) - { - if ( ( passSwitchFilter( _masterFilterCB.isSelected(), rowData.getRaxIngestFilter().isIngest() ) ) && - ( passSwitchFilter( _ofsFilterCB.isSelected(), rowData.getRaxIngestFilter().isOfsInput() ) ) && - ( passSwitchFilter( _mpeFilterCB.isSelected(), rowData.getRaxIngestFilter().isMpeInput() ) ) ) - { - addRowData = true; - } - } - else - { - addRowData = true; - } - return addRowData; - } - - private boolean passSwitchFilter( boolean isFilterOn, boolean enabled ) - { - boolean passFilter = (isFilterOn == enabled); //evil - return passFilter; - } - - private boolean passFilterByTS( ArcBaseIngestFilterJTableRowData rowData ) - { - boolean addRowData = false; - - if ( _tsFilterCheckBox.isSelected() ) - { - String tsCBString = (String) _tsFilterComboBox.getSelectedItem(); - - if ( tsCBString.indexOf( "(" + rowData.getRaxIngestFilter().getTs() + ")" ) > 0 ) - { - addRowData = true; - } - } - else - { - addRowData = true; - } - - return addRowData; - } - - private boolean passFilterByPE( ArcBaseIngestFilterJTableRowData rowData ) - { - boolean addRowData = false; //Only false if the checkbox is enabled and is not in the PE filter list - Object[] peJListObjectArray = null; - - if ( ( _peFilterCheckBox.isSelected() ) && ( ! _peJList.isSelectionEmpty() ) ) - { - peJListObjectArray = _peJList.getSelectedValues(); - Set selectedPESet = new HashSet(); - String peString = rowData.getRaxIngestFilter().getPe(); - - for ( int i = 0; i < peJListObjectArray.length; i++ ) - { - selectedPESet.add( (String) peJListObjectArray[ i ] ); - } - - for ( int i = 0; i < _peCBStringList.size(); i++ ) - { - String peCBString = (String) _peCBStringList.get( i ); - if ( peCBString.startsWith( peString ) ) - { - if ( selectedPESet.contains( peCBString ) ) - { - addRowData = true; - } - } - } - - } - else - { - addRowData = true; - } - - return addRowData; - } - - private boolean passFilterByLid_Shorter( ArcBaseIngestFilterJTableRowData rowData ) - { - boolean addRowData = true; // Only false if the checkbox is enabled AND does not match the filter string - - boolean attemptFilter = _lidFilterCheckBox.isSelected(); - - if ( attemptFilter ) - { - String filterString = _lidFilterTextField.getText().trim(); - - if ( ! rowData.getRaxIngestFilter().getLid().startsWith( filterString ) ) - { - addRowData = false; - } - } - - return addRowData; - } - - - private boolean passFilterByLid( ArcBaseIngestFilterJTableRowData rowData ) - { - boolean addRowData = false; // Only false if the checkbox is enabled AND does not match the filter string - - if ( _lidFilterCheckBox.isSelected() ) - { - String filterString = _lidFilterTextField.getText().toUpperCase().trim(); - - if ( rowData.getRaxIngestFilter().getLid().startsWith( filterString ) ) - { - addRowData = true; - } - } - else - { - addRowData = true; - } - return addRowData; - } - - private void clearDataInputPanel() - { - _lidTextField.setText( "" ); - _masterCheckBox.setSelected( false ); - _ofsCheckBox.setSelected( false); - _mpeInputCheckBox.setSelected( false ); - _peComboBox.setSelectedIndex( 0 ); - _durationComboBox.setSelectedIndex( 0 ); - _typeSourceComboBox.setSelectedIndex( 0 ); - _extremumComboBox.setSelectedIndex( 0 ); - _newReportCheckBox.setSelected( false ); - _activeCheckBox.setSelected( false ); - _obsTimeTextField.setText( "" ); - _ownAgencyTextField.setText( "" ); - _ownLocationTextField.setText( "" ); - _rankComboBox.setSelectedIndex( 1 ); - } - - private void addRowDataToJTable( RaxIngestFilter raxIngestFilter ) - { - String keyString = raxIngestFilter.getPrimaryKey(); - ArcBaseIngestFilterJTableRowData addRowData = new ArcBaseIngestFilterJTableRowData(); - String extractedKeyString = null; - ArcBaseIngestFilterJTableRowData rowData = null; - boolean found = false; - - addRowData.setRaxIngestFilter( raxIngestFilter ); - - for ( int i = 0; i < _allRowDataList.size(); i++ ) - { - rowData = (ArcBaseIngestFilterJTableRowData) _allRowDataList.get( i ); - - extractedKeyString = rowData.getRaxIngestFilter().getPrimaryKey(); - - if ( keyString.equalsIgnoreCase( extractedKeyString ) ) - { - _allRowDataList.remove( rowData ); - _allRowDataList.add( addRowData ); - found = true; - break; - } - } - - if ( ! found ) - { - _allRowDataList.add( addRowData ); - } - - _raxIFRowDataToRaxIFMap.put( addRowData, raxIngestFilter ); - - addRowData.addAllCellsToMap(); - _IFETableManager.setChangedAllRowDataList( _allRowDataList ); - _IFETableManager.sort( "Location", false, true ); - _IFETableManager.refreshDisplay(); - } - - private void removeRowDataFromJTable( RaxIngestFilter raxIngestFilter ) - { - ArcBaseIngestFilterJTableRowData removeRowData = new ArcBaseIngestFilterJTableRowData(); - ArcBaseIngestFilterJTableRowData rowData = null; - - for ( int i = 0; i < _allRowDataList.size(); i++ ) - { - rowData = (ArcBaseIngestFilterJTableRowData) _allRowDataList.get( i ); - if ( raxIngestFilter.getPrimaryKey().equalsIgnoreCase( rowData.getRaxIngestFilter().getPrimaryKey() ) ) - { - _allRowDataList.remove( rowData ); - break; - } - } - _IFETableManager.setChangedAllRowDataList( _allRowDataList ); - _IFETableManager.refreshDisplay(); - } - - private void deleteRaxIngestFilter() - { - RaxIngestFilter raxIngestFilter = null; - List selectedRowsData = _IFETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseIngestFilterJTableRowData rowData = (ArcBaseIngestFilterJTableRowData) selectedRowsData.get( 0 ); - raxIngestFilter = (RaxIngestFilter) _raxIFRowDataToRaxIFMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxIngestFilter.keyString(), "Delete Ingest Filter Entry" ) ) - { - _dataMgr.deleteRaxIngestFilterFromDatabase( raxIngestFilter ); - clearDataInputPanel(); - removeRowDataFromJTable( raxIngestFilter ); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a crest", "Delete Crest" ); - } - } - - - private void saveRaxIngestFilter() - { - RaxIngestFilter raxIngestFilter = new RaxIngestFilter(); - - String pe = (String) _peComboBox.getSelectedItem(); - String ts = (String) _typeSourceComboBox.getSelectedItem(); - String extremum = (String) _extremumComboBox.getSelectedItem(); - String duration = (String) _durationComboBox.getSelectedItem(); - short iDuration = (Short) _durCBStringToIDurMap.get( duration ); - short tsRank = (short) _rankComboBox.getSelectedIndex(); - - raxIngestFilter.setLid( _lidTextField.getText() ); - raxIngestFilter.setPe( (String) _peCBStringToPeMap.get( pe ) ); - raxIngestFilter.setDur( (String) _durCBStringToDurMap.get( duration ) ); - raxIngestFilter.setIdur( iDuration ); - raxIngestFilter.setTs( (String ) _tsCBStringToTSMap.get( ts ) ); - raxIngestFilter.setExtremum( (String) _extremumCBStringToExtremumMap.get( extremum ) ); - raxIngestFilter.setTsRank( tsRank ); - raxIngestFilter.setDetailInfo( _detailTextField.getText() ); - raxIngestFilter.setIngest( _masterCheckBox.isSelected() ); - raxIngestFilter.setNewReport( _newReportCheckBox.isSelected() ); - raxIngestFilter.setActive( _activeCheckBox.isSelected() ); - raxIngestFilter.setOfsInput( _ofsCheckBox.isSelected() ); - - long obsTime = 0; - - if ( _obsTimeTextField.getText().equalsIgnoreCase( "" ) ) - { - obsTime = DbTimeHelper.getLongTimeFromTimeToSecondsString( null ); - } - else - { - obsTime = DbTimeHelper.getLongTimeFromTimeToSecondsString( _obsTimeTextField.getText() ); - } - - raxIngestFilter.setObsTime( obsTime ); -// raxIngestFilter.setObsTime( DbTimeHelper.getLongTimeFromTimeToSecondsString(_obsTimeTextField.getText()) ); - raxIngestFilter.setOwnerAgency( _ownAgencyTextField.getText() ); - raxIngestFilter.setOwnerLocation( _ownLocationTextField.getText() ); - raxIngestFilter.setMpeInput( _mpeInputCheckBox.isSelected() ); - - _dataMgr.saveRaxIngestFilter( raxIngestFilter ); - - addRowDataToJTable( raxIngestFilter ); - System.out.println( raxIngestFilter ); - } - - private void populateDataInputPanel( RaxIngestFilter raxIF ) - { - String obsTimeString = null; - - _lidTextField.setText( raxIF.getLid() ); - - if ( raxIF.isIngest() ) - { - _masterCheckBox.setSelected( true ); - } - else - { - _masterCheckBox.setSelected( false ); - } - - if ( raxIF.isOfsInput() ) - { - _ofsCheckBox.setSelected( true ); - } - else - { - _ofsCheckBox.setSelected( false ); - } - - if ( raxIF.isMpeInput() ) - { - _mpeInputCheckBox.setSelected( true ); - } - else - { - _mpeInputCheckBox.setSelected( false ); - } - - ShefPE shefPE = (ShefPE) _dataMgr.getShefPEMap().get( raxIF.getPe() ); - if ( shefPE != null ) - { - _peComboBox.setSelectedItem( getShefPEComboBoxString( shefPE ) ); - } - else - { - _peComboBox.setSelectedItem( "" ); - } - - ShefDuration shefDur = (ShefDuration) _dataMgr.getShefDurationMap().get( raxIF.getDur() ); - if ( shefDur != null ) - { - _durationComboBox.setSelectedItem( getShefDurationComboBoxString( shefDur ) ); - } - else - { - _durationComboBox.setSelectedItem( "" ); - } - - ShefTS shefTS = (ShefTS) _dataMgr.getShefTSMap().get( raxIF.getTs() ); - if ( shefTS != null ) - { - _typeSourceComboBox.setSelectedItem( getShefTSString( shefTS ) ); - } - else - { - _typeSourceComboBox.setSelectedItem( "" ); - } - - ShefExtremum shefEx = (ShefExtremum) _dataMgr.getShefExtremumMap().get( raxIF.getExtremum() ); - if ( shefEx != null ) - { - _extremumComboBox.setSelectedItem( getShefExtremumComboBoxString( shefEx ) ); - } - else - { - _extremumComboBox.setSelectedItem( "" ); - } - - - _detailTextField.setText( raxIF.getDetailInfo() ); - - _newReportCheckBox.setSelected( raxIF.isNewReport() ); - - _activeCheckBox.setSelected( raxIF.isActive() ); - - if ( DbTable.isNull( raxIF.getObsTime() ) ) - { - obsTimeString = ""; - } - else - { - obsTimeString = DbTimeHelper.getTimeToSecondsStringFromLongTime( raxIF.getObsTime() ); - } - - _obsTimeTextField.setText( obsTimeString ); - _ownAgencyTextField.setText( raxIF.getOwnerAgency() ); - _ownLocationTextField.setText( raxIF.getOwnerLocation() ); - - short tsRank = raxIF.getTsRank(); - - switch ( tsRank ) - { - case 1: _rankComboBox.setSelectedIndex( 1 ); break; - case 2: _rankComboBox.setSelectedIndex( 2 ); break; - case 3: _rankComboBox.setSelectedIndex( 3 ); break; - case 4: _rankComboBox.setSelectedIndex( 4 ); break; - case 5: _rankComboBox.setSelectedIndex( 5 ); break; - default: _rankComboBox.setSelectedIndex( 0 ); break; - } - } - - - /** - * Sets up the Columns for the arcbase jtable - * - */ - private void setIFEColumnDescriptorList() - { - _IFEColumnDescriptorList = new ArrayList(); - - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "Location", true, 75, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "PE", true, 50, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "Dur", true, 75, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "TypeSrc", true, 75, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "Ext", true, 50, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "Rank", true, 50, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "Master", true, 50, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "OFS", true, 50, "center" ) ); - _IFEColumnDescriptorList.add(new JTableColumnDescriptor( "MPE", true, 50, "center" ) ); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - addWindowListener( windowCloser ); - - _IFETableManager.addTableListener( new IFETableListener() ); - - _closeButton.addActionListener( windowCloser ); - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - - _lidFilterCheckBox.addActionListener( new LidFilterCheckBoxListener() ); - _tsFilterCheckBox.addActionListener( new TSFilterCheckBoxListener() ); - _peFilterCheckBox.addActionListener( new PEFilterCheckBoxListener() ); - _switchesFilterCheckBox.addActionListener( new SwitchesFilterCheckBoxListener() ); - - _lidFilterTextField.addKeyListener( new LidFilterTextFieldListener() ); - _peJList.addListSelectionListener( new PEFilterJListListener() ); - _tsFilterComboBox.addActionListener( new TSFilterComboBoxListener() ); - _masterFilterCB.addActionListener( new Master_OFS_MPE_FilterCheckBoxListener() ); - _ofsFilterCB.addActionListener( new Master_OFS_MPE_FilterCheckBoxListener() ); - _mpeFilterCB.addActionListener( new Master_OFS_MPE_FilterCheckBoxListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveRaxIngestFilter(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteRaxIngestFilter(); - } - } - - private class Master_OFS_MPE_FilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - displayFilteredIngestFilterEntries(); - } - } - - private class PEFilterJListListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - displayFilteredIngestFilterEntries(); - } - } - } - - private class TSFilterComboBoxListener implements ActionListener - { - - public void actionPerformed( ActionEvent e ) - { - displayFilteredIngestFilterEntries(); - } - } - - private class LidFilterTextFieldListener implements KeyListener - { - public void keyPressed( KeyEvent e ) - { - } - - public void keyReleased( KeyEvent e ) - { - displayFilteredIngestFilterEntries(); - } - - public void keyTyped( KeyEvent e ) - { - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clearDataInputPanel(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - private class TSFilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _tsFilterCheckBox.isSelected() ) - { - activateTSFilter( true ); - } - else - { - activateTSFilter( false ); - displayFilteredIngestFilterEntries(); - } - } - - } - - private class PEFilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _peFilterCheckBox.isSelected() ) - { - activatePEFilter( true ); - } - else - { - activatePEFilter( false ); - _peJList.clearSelection(); - displayFilteredIngestFilterEntries(); - } - } - } - - private class SwitchesFilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _switchesFilterCheckBox.isSelected() ) - { - activateSwitchesFilter( true ); - } - else - { - activateSwitchesFilter( false ); - } - displayFilteredIngestFilterEntries(); - } - } - - private class LidFilterCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( _lidFilterCheckBox.isSelected() ) - { - activateLIDFilter( true ); - } - else - { - activateLIDFilter( false ); - displayFilteredIngestFilterEntries(); - } - } - } - - private class IFETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - RaxIngestFilter raxIngestFilter = null; - ArcBaseIngestFilterJTableRowData rowData = (ArcBaseIngestFilterJTableRowData) _IFETableManager.getSelectedRowsData().get( 0 ); - - raxIngestFilter = (RaxIngestFilter) _raxIFRowDataToRaxIFMap.get( rowData ); - - populateDataInputPanel( raxIngestFilter ); - } - } - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - IngestFilterEditor ingestFilterEditorGUI = new IngestFilterEditor( frame, dataMgr ); - ingestFilterEditorGUI.displayGUI(); - } - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/LocationEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/LocationEditor.java deleted file mode 100644 index 632d74de33..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/LocationEditor.java +++ /dev/null @@ -1,583 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Calendar; -import java.util.GregorianCalendar; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxLocation; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; - -public class LocationEditor extends JDialog implements HDateChooserOwner -{ - private static final short MISSING = -9999; - - private Container _dialogContentPane = getContentPane(); - private RaxLocation _raxLocation = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - - private int _clickedDateField = MISSING; - - private long _beginDate = MISSING; - - private StringDataConverter _converter = new StringDataConverter(); - - private RaxBaseDataMgr _dataMgr = null; - - private JPanel _geographicPhysicalPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _lidLTF = new LabeledTextField( " Location:", "", 5 ); - private LabeledTextField _startDateLTF = new LabeledTextField( " Start Date:", "", 11 ); - private LabeledTextField _endDateLTF = new LabeledTextField( " End Date:", "", 11 ); - private LabeledTextField _goesLTF = new LabeledTextField( " GOES:", "", 9 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", 35 ); - private LabeledTextField _detailLTF = new LabeledTextField( "Detail:", "", 45 ); - private LabeledTextField _latitudeLTF = new LabeledTextField( " Latitude:", "", 8 ); - private LabeledTextField _longitudeLTF = new LabeledTextField( " Longitude:", "", 8 ); - private LabeledTextField _elevationLTF = new LabeledTextField( " Elevation:", "", 8 ); - private LabeledTextField _stateLTF = new LabeledTextField( " State:", "", 2 ); - private LabeledTextField _hucLTF = new LabeledTextField( " HUC:", "", 8 ); - private LabeledTextField _countyFipsLTF = new LabeledTextField( " County FIPS:", "", 3 ); - private LabeledTextField _zonLTF = new LabeledTextField( " Zone Code:", "", 4 ); - private LabeledTextField _hsaLTF = new LabeledTextField( " HSA:", "", 3 ); - private LabeledTextField _wfoLTF = new LabeledTextField( " WFO:", "", 3 ); - private LabeledTextField _postLTF = new LabeledTextField( " Post Code:", "", 2 ); - private LabeledTextField _dbSourceLTF = new LabeledTextField( " DB Source:", "", 3 ); - private LabeledTextField _rfcLTF = new LabeledTextField( " RFC:", "", 2 ); - private LabeledTextField _countryFipsLTF = new LabeledTextField( "Country FIPS:", "", 2 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _okButton = new JButton( "Save and Close" ); - private JButton _saveToDatabaseButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - - private boolean _modifyLocation = false; - - - public LocationEditor( JFrame frame, RaxBaseDataMgr dataMgr, RaxLocation location ) - { - super( frame, "Location Editor", true ); - _raxLocation = location; - _dataMgr = dataMgr; - - if ( _raxLocation != null ) - { - setTitle( "Modify Location - " + _raxLocation.getLid() ); - _lidLTF.setEditTextField( false ); - _modifyLocation = true; - } - else - { - setTitle( "Add Location" ); - _lidLTF.setEditTextField( true ); - _modifyLocation = false; - } - } - - public LocationEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - this( frame, dataMgr, null ); - } - - - public void displayGUI() - { - setPreferredSize( new Dimension ( 700, 500 ) ); - populateFields(); - if ( _raxLocation != null ) - { - _beginDate = _raxLocation.getBeginDate(); - } - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initFrameComponenets(); - initGeographicPhysicalPanel(); - initButtonPanel(); - addListeners(); - pack(); - setVisible( true ); - } - - private void populateFields() - { - - if ( _raxLocation != null ) - { - double lon = _raxLocation.getLongitude(); - double lat = _raxLocation.getLatitude(); - String lonString = ""; - String latString = ""; - - if ( lon != DbTable.getNullDouble() ) - { - lonString = _dataMgr.getFormattedDouble( lon ); - } - - if ( lat != DbTable.getNullDouble() ) - { - latString = _dataMgr.getFormattedDouble( lat ); - } - - _lidLTF.setTextField( _raxLocation.getLid() ); - _goesLTF.setTextField( _raxLocation.getGoes() ); - _nameLTF.setTextField( _raxLocation.getName() ); - _detailLTF.setTextField( _raxLocation.getDetailInfo() ); - - _latitudeLTF.setTextField( latString ); - _longitudeLTF.setTextField( lonString ); - _elevationLTF.setTextField( _converter.getStringFromInt( _raxLocation.getElevation() ) ); - _postLTF.setTextField( _converter.getStringFromShort( _raxLocation.getPostCode() ) ); - _startDateLTF.setTextField( _converter.getDateStringFromDateLong( _raxLocation.getBeginDate() ) ); - _endDateLTF.setTextField( _converter.getDateStringFromDateLong( _raxLocation.getEndDate() ) ); - _stateLTF.setTextField( _raxLocation.getState() ); - _hucLTF.setTextField( _raxLocation.getHuc() ); - _countyFipsLTF.setTextField( _raxLocation.getCountyFips() ); - _zonLTF.setTextField( _raxLocation.getZone() ); - _hsaLTF.setTextField( _raxLocation.getHsa() ); - _wfoLTF.setTextField( _raxLocation.getWfo() ); - _dbSourceLTF.setTextField( _raxLocation.getDbsource() ); - _rfcLTF.setTextField( _raxLocation.getRfc() ); - _countryFipsLTF.setTextField( _raxLocation.getCountryfips() ); - } - } - - private void initGeographicPhysicalPanel() - { - GridBagConstraints gbLabelConstraints = new GridBagConstraints(); - GridBagConstraints gbTFConstraints = new GridBagConstraints(); - _geographicPhysicalPanel.setBorder( BorderFactory.createTitledBorder( "Geographic/Physical" ) ); - - gbLabelConstraints.anchor = GridBagConstraints.EAST; - gbLabelConstraints.weightx = 1; - gbLabelConstraints.weighty = 0; - - gbTFConstraints.anchor = GridBagConstraints.WEST; - gbTFConstraints.weightx = 1; - gbTFConstraints.weighty = 0; - JPanel vPanel = new JPanel(); - vPanel.setPreferredSize( new Dimension( 100, 100 ) ); -// vPanel.setBackground( Color.RED ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _lidLTF, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _startDateLTF, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _endDateLTF, 1, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _goesLTF, 1, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _nameLTF, 1, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _detailLTF, 1, 5, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _latitudeLTF, 1, 6, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _longitudeLTF, 1, 7, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _elevationLTF, 1, 8, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _stateLTF, 1, 9, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _hucLTF, 1, 10, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _countyFipsLTF, 1, 11, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _zonLTF, 1, 12, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _hsaLTF, 1, 13, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _wfoLTF, 1, 14, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _postLTF, 1, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _dbSourceLTF, 1, 16, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _rfcLTF, 1, 17, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, _countryFipsLTF, 1, 18, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _geographicPhysicalPanel, vPanel, 2, 0, 1, 19, GridBagConstraints.BOTH ); - - _hDateChooser.addOwner( this ); - - _startDateLTF.setEditTextField( false ); - _endDateLTF.setEditTextField( false ); - } - - private void initFrameComponenets() - { - _dialogContentPane.setLayout( new GridBagLayout() ); - ComponentHelper.addFrameComponent( _dialogContentPane, _geographicPhysicalPanel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "Database Controls" ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _okButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveToDatabaseButton, 1, 0, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, GridBagConstraints.VERTICAL ); - } - - private RaxLocation getRaxLocationToSave() - { - RaxLocation raxLocation = new RaxLocation(); - - raxLocation.setLid( _lidLTF.getTextFieldText().toUpperCase() ); - raxLocation.setGoes( _goesLTF.getTextFieldText() ); - raxLocation.setName( _nameLTF.getTextFieldText() ); - raxLocation.setDetailInfo( _detailLTF.getTextFieldText() ); - raxLocation.setLatitude( _converter.getDoubleValue( _latitudeLTF.getTextFieldText() ) ); - raxLocation.setLongitude( _converter.getDoubleValue( _longitudeLTF.getTextFieldText() ) ); - raxLocation.setElevation( _converter.getIntValue( _elevationLTF.getTextFieldText() ) ); - raxLocation.setPostCode( _converter.getShortValue( _postLTF.getTextFieldText() ) ); - raxLocation.setBeginDate( _converter.getLongDateValue( _startDateLTF.getTextFieldText() ) ); - raxLocation.setEndDate( _converter.getLongDateValue( _endDateLTF.getTextFieldText() ) ); - raxLocation.setState( _stateLTF.getTextFieldText() ); - raxLocation.setHuc( _hucLTF.getTextFieldText() ); - raxLocation.setCountyFips( _countyFipsLTF.getTextFieldText() ); - raxLocation.setZone( _zonLTF.getTextFieldText() ); - raxLocation.setHsa( _hsaLTF.getTextFieldText() ); - raxLocation.setWfo( _wfoLTF.getTextFieldText() ); - raxLocation.setDbsource( _dbSourceLTF.getTextFieldText() ); - raxLocation.setRfc( _rfcLTF.getTextFieldText() ); - raxLocation.setCountryfips( _countryFipsLTF.getTextFieldText() ); - - return raxLocation; - } - - private void saveLocation() - { -/* Location Save Logic - - Add Location Save Button -User click's Add Location. -User enters all of the information. -When user click's save: -If the record with the same Lid/Sbd combination exists: - Pop up an error message saying the record exists already. -If the record does not exist: - If a Sed is not specified: - If a previous record with the same (Lid/null Sed) combo and a more recent Sbd exists - Pop up an error message letting the user know that a more recent (Lid/Sbd/Null Sed) combo exists. - If a previous record with the same (Lid/null Sed) combo and an older Sbd exists - Insert the new record into the database and set the older entries with the same (Lid/null Sed)s Sed to todays date - If a Sed is specified: - add the new record to the database. - -Modify Location Save Button -User click's Modify Location -User enters/modifies information. -When user click's save: -If a record with the same (Lid/Sbd) combination exists: - If a Sed is specified: - If the user has changed the Sbd since bringing up the Modify Location window: - Pop up a warning message that queries the user on whether they are sure they want to overwrite the existing record. - If the user has not modified the Sbd since bringing up the Modify Location window: - Update the record in the database with the new information without prompting/warning the user. - If a Sed is not specified: - If the user has changed the Sbd since bringing up the Modify Location window: - If a previous record with the same (Lid/null Sed) combo and a more recent Sbd does not exist: - Pop up a warning message that queries the user on whether they are sure they want to overwrite the existing record. - If a previous record with the same (Lid/null Sed) combo and a more recent Sbd does exist: - Pop up an error message letting the user know that a more recent (Lid/Sbd/Null Sed) combo exists. - If the user has not modified the Sbd since bringing up the Modify Location window: - If a previous record with the same (Lid/null Sed) combo and a more recent Sbd does not exist: - Update the record in the database with the new information without prompting/warning the user. - If a previous record with the same (Lid/null Sed) combo and a more recent Sbd does exist: - Pop up a warning message that queries the user on whether they are sure they want to overwrite the existing record. -If the record does not exist: - If a Sed is not specified: - If a previous record with the same (Lid/null Sed) combo and a more recent Sbd exists - Pop up an error message letting the user know that a more recent (Lid/Sbd/Null Sed) combo exists. - If a previous record with the same (Lid/null Sed) combo and an older Sbd exists - Insert the new record into the database and set the older entries with the same (Lid/null Sed)s Sed to todays date - If a Sed is specified: - add the new record to the database. - - DialogHelper.displayMessageDialog( this, "Soon to be implemented", "Save Location" ); -*/ - if ( _converter.getLongDateValue( _startDateLTF.getTextFieldText() ) != DbTable.getNullDouble() ) - { - RaxLocation raxLocation = getRaxLocationToSave(); - - boolean startDateChanged = true; - - long endDate = _converter.getLongDateValue( _endDateLTF.getTextFieldText() ); - - if ( raxLocation.getBeginDate() == _beginDate ) - { - startDateChanged = false; - } - - if ( _modifyLocation ) // User selected Modify Location - { - boolean recordExists = _dataMgr.doesRaxLocationExist( raxLocation ); - - if ( recordExists ) // Lid/Start Date exists - { - if ( endDate != DbTable.getNullLong() ) // End date is specified - { - if ( startDateChanged ) // Record found in the database AND start date was changed - // Have user confirm whether to save or not - { - if ( DialogHelper.displayConfirmDialog( this, "A record already exists for " + raxLocation + "\n Are you sure you want to save", "Save RaxLocation" ) ); - { - _dataMgr.saveLocation( raxLocation ); //User confirms that they want to overwrite the changes - } - } - else // Start date was not changed. - { - _dataMgr.saveLocation( raxLocation ); - } - } - else // End date is not specified - { - boolean newerRecordExists = _dataMgr.doesNewerRaxLocationExist( raxLocation ); - - if ( startDateChanged ) // Start date changed - { - if ( newerRecordExists ) // newer record exists - { - DialogHelper.displayErrorDialog( this, "A record with a newer Sbd and null Sed exists", "Save Location" ); - } - else // newer record does not exist - { - if ( DialogHelper.displayConfirmDialog( this, "A record already exists for " + raxLocation + "\n Are you sure you want to save", "Save RaxLocation" ) ) - { - _dataMgr.saveLocation( raxLocation ); //User confirms that they want to overwrite the changes - } - } - } - else // Start date has not been changed - { - if ( newerRecordExists ) // newer record exists - { - if ( DialogHelper.displayConfirmDialog( this, "A record already exists for " + raxLocation + "\n Are you sure you want to save", "Save RaxLocation" ) ) - { - _dataMgr.saveLocation( raxLocation ); //User confirms that they want to overwrite the changes - } - } - else // newer record does not exist - { - _dataMgr.saveLocation( raxLocation ); - } - } - } - } - else // Lid/Start Date does not exist - { - if ( endDate == DbTable.getNullLong() ) // End date is not specified - { - boolean newerRecordExists = _dataMgr.doesNewerRaxLocationExist( raxLocation ); - if ( newerRecordExists ) // Newer record exists - { - DialogHelper.displayErrorDialog( this, "A record with a newer Sbd and null Sed exists", "Save Location" ); - } - else // No newer records exist. Insert new record and close out all old records with null end dates - { - _dataMgr.insertNewLocation( raxLocation ); - _dataMgr.setEndDateForLidInLocation( raxLocation ); - } - } - else // End date is specified - { - _dataMgr.saveLocation( raxLocation ); - } - } - } - else // User selected Add Location - { - boolean recordExists = _dataMgr.doesRaxLocationExist( raxLocation ); - - if ( recordExists ) // A record with the same Lid/Sbd exists already - { - DialogHelper.displayErrorDialog( this, raxLocation + "\n\nalready exists", "Save Location" ); - } - else - { - if ( endDate == DbTable.getNullLong() ) // End date is not specified - { - boolean newerRecordExists = _dataMgr.doesNewerRaxLocationExist( raxLocation ); - if ( newerRecordExists ) // Newer record exists - { - DialogHelper.displayErrorDialog( this, "A record with a newer Sbd and null Sed exists", "Save Location" ); - } - else // No newer records exist. Insert new record and close out all old records with null end dates - { - _dataMgr.insertNewLocation( raxLocation ); - _dataMgr.setEndDateForLidInLocation( raxLocation ); - } - } - else // End date is specified - { - _dataMgr.insertNewLocation( raxLocation ); - } - } - } - } - } - - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - DateFieldMouseListener startDateFieldMouseListener = new DateFieldMouseListener( 0 ); - DateFieldMouseListener endDateFieldMouseListener = new DateFieldMouseListener( 1 ); - - _saveToDatabaseButton.addActionListener( new SaveToDatabaseActionListener() ); - _okButton.addActionListener( new SaveToDatabaseAndCloseActionListener() ); - _closeButton.addActionListener( windowCloser ); - - _startDateLTF.addTextFieldMouseListener( startDateFieldMouseListener ); - _endDateLTF.addTextFieldMouseListener( endDateFieldMouseListener ); - - addWindowListener( windowCloser ); - } - - private class DateFieldMouseListener implements MouseListener - { - private int __clickedDateField = -9999; - - public DateFieldMouseListener( int clickedDateField ) - { - __clickedDateField = clickedDateField; - } - - public void mouseClicked( MouseEvent e ) - { - } - - public void mouseEntered( MouseEvent e ) - { - } - - public void mouseExited( MouseEvent e ) - { - } - - public void mousePressed( MouseEvent e ) - { - launchDateWindow( __clickedDateField ); - } - - public void mouseReleased( MouseEvent e ) - { - } - } - - private void launchDateWindow( int clickedDateField ) - { - _clickedDateField = clickedDateField; - - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = 0; - String dateString = null; - - switch ( _clickedDateField ) - { - case 0: dateString = _startDateLTF.getTextFieldText(); break; - case 1: dateString = _endDateLTF.getTextFieldText(); break; - } - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - dateLong = DbTimeHelper.getLongTimeFromDateString( dateString ) + dayInMillis; - } - else - { - dateLong = System.currentTimeMillis(); - } - - calendar.setTimeInMillis( dateLong ); - - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - - } - - public void dateChosen( JDialog jDialog ) - { - String dateString = null; - - if ( _clickedDateField != -9999 ) - { - Calendar calendar = _hDateChooser.getDate(); - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - switch ( _clickedDateField ) - { - case 0: _startDateLTF.setTextField( dateString ); break; - case 1: _endDateLTF.setTextField( dateString ); break; - } - _clickedDateField = -9999; - } - } - - private class SaveToDatabaseAndCloseActionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveLocation(); - closeWindow(); - } - } - - private class SaveToDatabaseActionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveLocation(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - - LocationEditor locEditorGUI = new LocationEditor( frame, dataMgr ); - locEditorGUI.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ModCtrlEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ModCtrlEditor.java deleted file mode 100644 index 3fed224ab0..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ModCtrlEditor.java +++ /dev/null @@ -1,306 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ModCtrl; -import ohd.hseb.raxbase.table.ArcBaseModCtrlJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ModCtrlEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _MCETableManager = null; - private List _MCEColumnDescriptorList = null; - private List _modCtrlRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _modCtrlSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _modNameLTF = new LabeledTextField( "ModName: ", "", "Mod Name", 10 ); - private JCheckBox _loadCB = new JCheckBox( "Load" ); - private JCheckBox _fetchOperCB = new JCheckBox( "Fetch Oper" ); - private JCheckBox _fetchSpinCB = new JCheckBox( "Fetch Spin" ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _modCtrlRowDataToModCtrlMap = null; - - public ModCtrlEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ModCtrl Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 510, 625 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initModCtrlSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initModCtrlSelectionPanel() - { - initJTable(); - - ComponentHelper.addPanelComponent( _modCtrlSelectionPanel, _deleteButton, 0, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _modCtrlSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 3, 0, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ModCtrl" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _modNameLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _loadCB, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _fetchOperCB, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _fetchSpinCB, 0, 3, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _modCtrlRowDataToModCtrlMap = _dataMgr.getModCtrlRowDataToModCtrlMap(); - } - - private void initJTable() - { - _modCtrlRowDataList = _dataMgr.getModCtrlRowDataList(); - setMCEColumnDescriptorList(); - _MCETableManager = new ComplexJTableManager( _MCEColumnDescriptorList, _modCtrlRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _MCETableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _MCETableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _MCETableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 300 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _modCtrlSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _modCtrlRowDataList = _dataMgr.getModCtrlRowDataList(); - _MCETableManager.setChangedAllRowDataList( _modCtrlRowDataList ); - _MCETableManager.refreshDisplay(); - } - - private void setMCEColumnDescriptorList() - { - _MCEColumnDescriptorList = new ArrayList(); - - _MCEColumnDescriptorList.add(new JTableColumnDescriptor( "ModName", true, 120, "center" ) ); - _MCEColumnDescriptorList.add(new JTableColumnDescriptor( "Load", true, 120, "center" ) ); - _MCEColumnDescriptorList.add(new JTableColumnDescriptor( "FetchOper", true, 120, "center" ) ); - _MCEColumnDescriptorList.add(new JTableColumnDescriptor( "FetchSpin", true, 120, "center" ) ); - } - - private void populateDataInputPanel( ModCtrl modCtrl ) - { - if ( modCtrl != null ) - { - _modNameLTF.setTextField( modCtrl.getModName() ); - _loadCB.setSelected( modCtrl.isLoad() ); - _fetchOperCB.setSelected( modCtrl.isFetchOper() ); - _fetchSpinCB.setSelected( modCtrl.isFetchSpin() ); - } - } - - private void clearDataInputPanel() - { - _modNameLTF.setTextField( "" ); - _loadCB.setSelected( false ); - _fetchOperCB.setSelected( false ); - _fetchSpinCB.setSelected( false ); - } - - private boolean saveModCtrl() - { - boolean saved = false; - - ModCtrl modCtrl = new ModCtrl(); - - modCtrl.setModName( _modNameLTF.getTextFieldText() ); - modCtrl.setLoad( _loadCB.isSelected() ); - modCtrl.setFetchOper( _fetchOperCB.isSelected() ); - modCtrl.setFetchSpin( _fetchSpinCB.isSelected() ); - - saved = _dataMgr.saveModCtrl( modCtrl ); - - updateJTable(); - - return saved; - } - - private void deleteModCtrl() - { - ModCtrl modCtrl = null; - List selectedRowsData = _MCETableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseModCtrlJTableRowData rowData = (ArcBaseModCtrlJTableRowData) selectedRowsData.get( 0 ); - modCtrl = (ModCtrl) _modCtrlRowDataToModCtrlMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + modCtrl.keyString(), "Delete ModCtrl" ) ) - { - _dataMgr.deleteModCtrlFromDataBase( modCtrl ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a modctrl", "Delete ModCtrl" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _MCETableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveModCtrl(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveModCtrl() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteModCtrl(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ModCtrl modCtrl = null; - - ArcBaseModCtrlJTableRowData rowData = (ArcBaseModCtrlJTableRowData) _MCETableManager.getSelectedRowsData().get( 0 ); - modCtrl = (ModCtrl) _modCtrlRowDataToModCtrlMap.get( rowData ); - populateDataInputPanel( modCtrl ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ModCtrlEditor modCtrlEditor = new ModCtrlEditor( frame, dataMgr ); - modCtrlEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessAdjustFactorDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessAdjustFactorDifferencesDialog.java deleted file mode 100644 index 2ccb2857b1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessAdjustFactorDifferencesDialog.java +++ /dev/null @@ -1,152 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.AdjustFactorRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.RaxAdjustFactorRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessAdjustFactorDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessAdjustFactorDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process AdjustFactor", "AdjustFactor", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(Lid | PE | Dur | TS | Extremum)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxAdjustFactorRecord record = (RaxAdjustFactorRecord) recordDiff.getRaxRecord(); - StringPadder padder = new StringPadder( 8, 8 ); - - cbString = padder.getFrontPaddedString( record.getLid() ) + " | " + - PEManager.getPEFromPe1Pe2( record.getPe1(), record.getPe2() ) + " | " + - record.getDur() + " | " + - TSManager.getTSFromTandS( record.getT(), record.getS() ) + " | " + - record.getE(); - - return cbString; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - AdjustFactorRecord ihfsRecord = (AdjustFactorRecord) _selectedRecordDiff.getIhfsRecord(); - RaxAdjustFactorRecord raxRecord = (RaxAdjustFactorRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = _padder.getFrontPaddedString( ihfsRecord.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRecord.getLid() ); - String pe = _padder.getFrontPaddedString( ihfsRecord.getPe() ) + "PE" + _padder.getEndPaddedString( "PE", raxRecord.getPe1() + raxRecord.getPe2() ); - String dur = _padder.getFrontPaddedString( ihfsRecord.getDur() ) + "Dur" + _padder.getEndPaddedString( "Dur", raxRecord.getIdur() + "/" + raxRecord.getDur() ); - String iDur = _padder.getFrontPaddedString( "" ) + "IDur" + _padder.getEndPaddedString( "IDur", raxRecord.getIdur() ); - String ts = _padder.getFrontPaddedString( ihfsRecord.getTs() ) + "TS" + _padder.getEndPaddedString( "TS", raxRecord.getT() + raxRecord.getS() ); - String extremum = _padder.getFrontPaddedString( ihfsRecord.getExtremum() ) + "Extremum" + _padder.getEndPaddedString( "Extremum", raxRecord.getE() ); - String beginDate = _padder.getFrontPaddedString( "" ) + "BeginDate" + _padder.getEndPaddedString( "BeginDate", DbTimeHelper.getDateStringFromLongTime( raxRecord.getBegin_date() ) ); - String divisor = _padder.getFrontPaddedString( ihfsRecord.getDivisor() ) + "Divisor" + _padder.getEndPaddedString( "Divisor", raxRecord.getDivisor() ); - String base = _padder.getFrontPaddedString( ihfsRecord.getBase() ) + "Base" + _padder.getEndPaddedString( "Base", raxRecord.getBase() ); - String multiplier = _padder.getFrontPaddedString( ihfsRecord.getMultiplier() ) + "Multiplier" + _padder.getEndPaddedString( "Multiplier", raxRecord.getMultiplier() ); - String adder = _padder.getFrontPaddedString( ihfsRecord.getAdder() ) + "Adder" + _padder.getEndPaddedString( "Adder", raxRecord.getAdder() ); - - recordStringList.add( lid ); - recordStringList.add( pe ); - recordStringList.add( dur ); - recordStringList.add( iDur ); - recordStringList.add( ts ); - recordStringList.add( extremum ); - recordStringList.add( beginDate ); - recordStringList.add( divisor ); - recordStringList.add( base ); - recordStringList.add( multiplier ); - recordStringList.add( adder ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "divisor" ) ) - { - highlightStringList.add( divisor ); - } - else if ( columnName.equalsIgnoreCase( "base" ) ) - { - highlightStringList.add( base ); - } - else if ( columnName.equalsIgnoreCase( "multiplier" ) ) - { - highlightStringList.add( multiplier ); - } - else if ( columnName.equalsIgnoreCase( "adder" ) ) - { - highlightStringList.add( adder ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob82krfx?user=pguser", "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - - ProcessAdjustFactorDifferencesDialog test = new ProcessAdjustFactorDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessCrestDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessCrestDifferencesDialog.java deleted file mode 100644 index 12485e072a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessCrestDifferencesDialog.java +++ /dev/null @@ -1,158 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.CrestRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb.generated.RaxCrestRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessCrestDifferencesDialog extends ProcessDifferencesDialog -{ - - public ProcessCrestDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process Crest", "Crest", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(Lid | DateCrest)"; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - CrestRecord ihfsRecord = (CrestRecord) _selectedRecordDiff.getIhfsRecord(); - RaxCrestRecord raxRecord = (RaxCrestRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = _padder.getFrontPaddedString( ihfsRecord.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRecord.getLid() ); - String datecrst = _padder.getFrontPaddedString( DbTimeHelper.getDateStringFromLongTime( ihfsRecord.getDatcrst() ) ) + "DateCrest" + _padder.getEndPaddedString( "DateCrest", DbTimeHelper.getDateStringFromLongTime( raxRecord.getDatecrst() ) ); - String timecrst = _padder.getFrontPaddedString( ihfsRecord.getTimcrst() ) + "TimeCrest" + _padder.getEndPaddedString( "TimeCrest", raxRecord.getCrstdatetime() ); - String stage = _padder.getFrontPaddedString( ihfsRecord.getStage() ) + "Stage" + _padder.getEndPaddedString( "Stage",raxRecord.getStage() ); - String stg_qual = _padder.getFrontPaddedString( "" ) + "StageQual" + _padder.getEndPaddedString( "StageQual", raxRecord.getStg_qual() ); - String flow = _padder.getFrontPaddedString( ihfsRecord.getQ() ) + "Flow" + _padder.getEndPaddedString( "Flow", raxRecord.getFlow() ); - String flow_qual = _padder.getFrontPaddedString( "" ) + "FlowQual" + _padder.getEndPaddedString( "FlowQual", raxRecord.getFlow_qual() ); - String hw = _padder.getFrontPaddedString( ihfsRecord.getHw() ) + "Hw" + _padder.getEndPaddedString( "Hw", raxRecord.getHw() ); - String jam = _padder.getFrontPaddedString( ihfsRecord.getJam() ) + "Jam" + _padder.getEndPaddedString( "Jam", raxRecord.getJam() ); - String oldDatum = _padder.getFrontPaddedString( ihfsRecord.getOlddatum() ) + "Old Datum" + _padder.getEndPaddedString( "Old Datum", raxRecord.getOlddatum() ); - String prelim = _padder.getFrontPaddedString( ihfsRecord.getPrelim() ) + "Prelim" + _padder.getEndPaddedString( "Prelim", raxRecord.getPrelim() ); - - recordStringList.add( lid ); - recordStringList.add( datecrst ); - recordStringList.add( timecrst ); - recordStringList.add( stage ); - recordStringList.add( stg_qual ); - recordStringList.add( flow ); - recordStringList.add( flow_qual ); - recordStringList.add( hw ); - recordStringList.add( jam ); - recordStringList.add( oldDatum ); - recordStringList.add( prelim ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "crstdatetime" ) ) - { - highlightStringList.add( timecrst ); - } - else if ( columnName.equalsIgnoreCase( "stage" ) ) - { - highlightStringList.add( stage ); - } - else if ( columnName.equalsIgnoreCase( "flow" ) ) - { - highlightStringList.add( flow ); - } - else if ( columnName.equalsIgnoreCase( "hw" ) ) - { - highlightStringList.add( hw ); - } - else if ( columnName.equalsIgnoreCase( "jam" ) ) - { - highlightStringList.add( jam ); - } - else if ( columnName.equalsIgnoreCase( "olddatum" ) ) - { - highlightStringList.add( oldDatum ); - } - else if ( columnName.equalsIgnoreCase( "prelim" ) ) - { - highlightStringList.add( prelim ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxCrestRecord record = (RaxCrestRecord) recordDiff.getRaxRecord(); - StringPadder padder = new StringPadder( 8, 8 ); - - cbString = padder.getFrontPaddedString( record.getLid() ) + " | " + DbTimeHelper.getDateStringFromLongTime( record.getDatecrst() ); - - return cbString; - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessCrestDifferencesDialog test = new ProcessCrestDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessDataLimitsDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessDataLimitsDifferencesDialog.java deleted file mode 100644 index 4ab9039f98..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessDataLimitsDifferencesDialog.java +++ /dev/null @@ -1,180 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.ihfsdb.generated.DataLimitsRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb.generated.RaxDataLimitsRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessDataLimitsDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessDataLimitsDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process DataLimits", "DataLimits", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(PE | Dur | IDur | MonthDayStart)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxDataLimitsRecord record = (RaxDataLimitsRecord) recordDiff.getRaxRecord(); - StringPadder padder = new StringPadder( 4, 8 ); - - cbString = PEManager.getPEFromPe1Pe2( record.getPe1(), record.getPe2() ) + - " | " + record.getDur() + " | " + - padder.getFrontPaddedString( record.getIdur() ) + - " | " + record.getMonthdaystart(); - - return cbString; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - DataLimitsRecord ihfsRecord = (DataLimitsRecord) _selectedRecordDiff.getIhfsRecord(); - RaxDataLimitsRecord raxRecord = (RaxDataLimitsRecord) _selectedRecordDiff.getRaxRecord(); - - String pe = _padder.getFrontPaddedString( ihfsRecord.getPe() ) + "PE" + _padder.getEndPaddedString( "PE", raxRecord.getPe1() + raxRecord.getPe2() ); - String dur = _padder.getFrontPaddedString( ihfsRecord.getDur() ) + "Dur" + _padder.getEndPaddedString( "Dur", raxRecord.getIdur() + "/" + raxRecord.getDur() ); - String iDur = _padder.getFrontPaddedString( "" ) + "IDur" + _padder.getEndPaddedString( "IDur", raxRecord.getIdur() ); - String monthDayStart = _padder.getFrontPaddedString( ihfsRecord.getMonthdaystart() ) + "MonthDayStart" + _padder.getEndPaddedString( "MonthDayStart", raxRecord.getMonthdaystart() ); - String monthDayEnd = _padder.getFrontPaddedString( ihfsRecord.getMonthdayend() ) + "MonthDayEnd" + _padder.getEndPaddedString( "MonthDayEnd", raxRecord.getMonthdayend() ); - String grossRangeMin = _padder.getFrontPaddedString( ihfsRecord.getGross_range_min() ) + "GrossRangeMin" + _padder.getEndPaddedString( "GrossRangeMin", raxRecord.getGross_range_min() ); - String grossRangeMax = _padder.getFrontPaddedString( ihfsRecord.getGross_range_max() ) + "GrossRangeMax" + _padder.getEndPaddedString( "GrossRangeMax", raxRecord.getGross_range_max() ); - String reasonRangeMin = _padder.getFrontPaddedString( ihfsRecord.getReason_range_min() ) + "ReasonRangeMin" + _padder.getEndPaddedString( "ReasonRangeMin", raxRecord.getReason_range_min() ); - String reasonRangeMax = _padder.getFrontPaddedString( ihfsRecord.getReason_range_max() ) + "ReasonRangeMax" + _padder.getEndPaddedString( "ReasonRangeMax", raxRecord.getReason_range_max() ); - String rocMax = _padder.getFrontPaddedString( ihfsRecord.getRoc_max() ) + "RocMax" + _padder.getEndPaddedString( "RocMax", raxRecord.getRoc_max() ); - String alertLimit = _padder.getFrontPaddedString( ihfsRecord.getAlert_upper_limit() ) + "AlertLimit" + _padder.getEndPaddedString( "AlertLimit", raxRecord.getAlert_limit() ); - String alertRocLimit = _padder.getFrontPaddedString( ihfsRecord.getAlert_roc_limit() ) + "AlertRocLimit" + _padder.getEndPaddedString( "AlertRocLimit", raxRecord.getAlert_roc_limit() ); - String alarmLimit = _padder.getFrontPaddedString( ihfsRecord.getAlarm_upper_limit() ) + "AlarmLimit" + _padder.getEndPaddedString( "AlarmLimit", raxRecord.getAlarm_limit() ); - String alarmRocLimit = _padder.getFrontPaddedString( ihfsRecord.getAlarm_roc_limit() ) + "AlarmRocLimit" + _padder.getEndPaddedString( "AlarmRocLimit", raxRecord.getAlarm_roc_limit() ); - - recordStringList.add( pe ); - recordStringList.add( dur ); - recordStringList.add( iDur ); - recordStringList.add( monthDayStart ); - recordStringList.add( monthDayEnd ); - recordStringList.add( grossRangeMin ); - recordStringList.add( grossRangeMax ); - recordStringList.add( reasonRangeMin ); - recordStringList.add( reasonRangeMax ); - recordStringList.add( rocMax ); - recordStringList.add( alertLimit ); - recordStringList.add( alertRocLimit ); - recordStringList.add( alarmLimit ); - recordStringList.add( alarmRocLimit ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "monthdayend" ) ) - { - highlightStringList.add( monthDayEnd ); - } - else if( columnName.equalsIgnoreCase( "gross_range_min" ) ) - { - highlightStringList.add( grossRangeMin ); - } - else if( columnName.equalsIgnoreCase( "gross_range_max" ) ) - { - highlightStringList.add( grossRangeMax ); - } - else if( columnName.equalsIgnoreCase( "reason_range_min" ) ) - { - highlightStringList.add( reasonRangeMin ); - } - else if( columnName.equalsIgnoreCase( "reason_range_max" ) ) - { - highlightStringList.add( reasonRangeMax ); - } - else if( columnName.equalsIgnoreCase( "roc_max" ) ) - { - highlightStringList.add( rocMax ); - } - else if( columnName.equalsIgnoreCase( "alert_limit" ) ) - { - highlightStringList.add( alertLimit ); - } - else if( columnName.equalsIgnoreCase( "alert_roc_limit" ) ) - { - highlightStringList.add( alertRocLimit ); - } - else if( columnName.equalsIgnoreCase( "alarm_limit" ) ) - { - highlightStringList.add( alarmLimit ); - } - else if( columnName.equalsIgnoreCase( "alarm_roc_limit" ) ) - { - highlightStringList.add( alarmRocLimit ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessDataLimitsDifferencesDialog test = new ProcessDataLimitsDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessDifferencesDialog.java deleted file mode 100644 index 4d402b4ebd..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessDifferencesDialog.java +++ /dev/null @@ -1,368 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb_sync.DiffSet; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.raxdb_sync.RecordDifferenceOriginType; -import ohd.hseb.rfc.util.listpanels.JListPanel; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; - -public abstract class ProcessDifferencesDialog extends JDialog -{ - private String _tableName = null; - - protected RaxSyncDataMgr _raxSyncDataMgr = null; - - private Container _dialogContentPane = getContentPane(); - - protected LabeledComboBox _selectionLCB = new LabeledComboBox( "Select Crest Record:" ); - - private Map _selectionStringToDifferenceMap = new HashMap(); - - private DiffSet _diffset = null; - protected RecordDifference _selectedRecordDiff = null; - - protected JListPanel _recordPanel = null; - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _processSingleRecordButton = new JButton( "Synchronize Selected Record" ); - private JButton _processAllRecordsButton = new JButton( "Synchronize All Records" ); - private JButton _closeButton = new JButton( "Close" ); - - protected String _keyString = ""; - - protected StringPadder _padder = null; - - protected Dimension _preferredSize = null; - - private StatusBar _statusBar = new StatusBar(); - - public ProcessDifferencesDialog( JFrame frame, String dialogTitle, String tableName, RaxSyncDataMgr syncDataMgr, StringPadder stringPadder, Dimension prefSizeDim ) - { - super( frame, dialogTitle, true ); - _raxSyncDataMgr = syncDataMgr; - _tableName = tableName; - _padder = stringPadder; - _preferredSize = prefSizeDim; - } - - public void displayGUI() - { - setPreferredSize( _preferredSize ); - initGUI(); - } - - protected String getPaddedString( String ihfsString, String colString, String raxString ) - { - return ( _padder.getFrontPaddedString( ihfsString ) + colString + _padder.getEndPaddedString( colString, raxString ) ); - } - - protected String getPaddedString( double ihfsValue, String colString, double raxValue ) - { - return ( _padder.getFrontPaddedString( ihfsValue ) + colString + _padder.getEndPaddedString( colString, raxValue ) ); - } - - protected String getPaddedString( String ihfsString, String colString, double raxValue ) - { - return ( _padder.getFrontPaddedString( ihfsString ) + colString + _padder.getEndPaddedString( colString, raxValue ) ); - } - - protected String getPaddedString( long ihfsValue, String colString, long raxValue ) - { - return ( _padder.getFrontPaddedString( ihfsValue ) + colString + _padder.getEndPaddedString( colString, raxValue ) ); - } - - protected String getPaddedDateString( long ihfsDate, String colString, long raxDate ) - { - return ( _padder.getFrontPaddedDateString( ihfsDate ) + colString + _padder.getEndPaddedDateString( colString, raxDate ) ); - } - - protected String getPaddedDateString( String ihfsDate, String colString, long raxDate ) - { - return ( _padder.getFrontPaddedString( ihfsDate ) + colString + _padder.getEndPaddedDateString( colString, raxDate ) ); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - processDifferences(); - if ( _diffset.getList().isEmpty() ) - { - DialogHelper.displayErrorDialog( this, "No differences found", "Synchronize " + _tableName + " Records" ); - closeWindow(); - } - else - { - updateSelectionComboBox(); - refreshRecordPanel(); - initButtonPanel(); - initFrameComponents(); - - addListeners(); - pack(); - setVisible( true ); - } - } - - protected abstract void refreshRecordPanel(); - - protected abstract String getSelectionComboBoxString( RecordDifference recordDiff ); - - public void processDifferences() - { - _diffset = _raxSyncDataMgr.findAllDifferences( _tableName ); - _statusBar.setText( "Number of differences found: " + _diffset.getList().size() ); - _raxSyncDataMgr.reportAllDifferences( _diffset ); - } - - private void updateSelectionComboBox() - { - List selectionComboBoxStringList = new ArrayList(); - - _selectionStringToDifferenceMap.clear(); - _selectionLCB.getComboBox().removeAllItems(); - List diffsetList = _diffset.getList(); - RecordDifference recordDiff = null; - - for ( int i = 0; i < diffsetList.size(); i++ ) - { - recordDiff = (RecordDifference) diffsetList.get( i ); - selectionComboBoxStringList.add( getSelectionComboBoxString( recordDiff ) ); - _selectionStringToDifferenceMap.put( getSelectionComboBoxString( recordDiff ), recordDiff ); - } - - if ( selectionComboBoxStringList.isEmpty() ) - { - selectionComboBoxStringList.add( "No differences found" ); - } - _selectionLCB.setComboBoxFromStringArray( selectionComboBoxStringList.toArray() ); - _selectionLCB.setLabel( "Select " + _tableName + " Entry:
    " + _keyString + ""); - _selectionLCB.setLabelPreferredSize( new Dimension( 250, 30 ) ); - _selectionLCB.setComboBoxPreferredSize( new Dimension( 375, 15 ) ); - - _selectionLCB.setComboBoxFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - - String selectedItem = _selectionLCB.getSelectedCBItem(); - - _selectedRecordDiff = (RecordDifference) _selectionStringToDifferenceMap.get( selectedItem ); - } - - protected String getHeaderString() - { - String headerString = null; - - if ( _selectedRecordDiff.getDiffType() == RecordDifferenceOriginType.MOD ) - { - headerString = "IHFS Record Existing Rax Record"; - } - else - { - headerString = "IHFS Record New Rax Record"; - } - - return headerString; - } - - protected void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _buttonPanel, _processSingleRecordButton, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _buttonPanel, _processAllRecordsButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - protected void initFrameComponents() - { - JPanel horizontalPanel = new JPanel(); - horizontalPanel.setPreferredSize(new Dimension( 50, 50 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _selectionLCB, 0, 1, 3, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _recordPanel, 0, 2, 3, 1, 1, 3, GridBagConstraints.VERTICAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 3, 3, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addFrameComponent( _dialogContentPane, horizontalPanel, 0, 4, 3, 1, 1, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _statusBar, 0, 5, 3, 1, 1, 0, GridBagConstraints.BOTH); - - - } - - public void setTableName( String tableName ) - { - _tableName = tableName; - } - - public String getTableName() - { - return _tableName; - } - - private void processAllRecords() - { - int numberOfErrors = _raxSyncDataMgr.proccessAllDifferences( _diffset, false ); - - if ( numberOfErrors == 0 ) - { - DialogHelper.displayMessageDialog( this, "Successfully synchronized " + _diffset.getList().size() + " record(s)", "Sync " + _tableName + " table" ); - } - else - { - DialogHelper.displayErrorDialog( this, "Failed to synchronize " + numberOfErrors + " record(s)\nPlease check the log " + _raxSyncDataMgr.getInsertUpdateLogFilename() + " for more details", "Sync " + _tableName + " table" ); - } - - processDifferences(); - updateSelectionComboBox(); - refreshRecordPanel(); - } - - private void processSingleRecord() - { - DiffSet diffSet = new DiffSet(); - String selectedItem = _selectionLCB.getSelectedCBItem(); - int numberOfErrors = 0; - - RecordDifference recordDiff = (RecordDifference) _selectionStringToDifferenceMap.get( selectedItem ); - - diffSet.addDifference( recordDiff ); - numberOfErrors = _raxSyncDataMgr.proccessAllDifferences( diffSet, false ); - if ( numberOfErrors == 0 ) - { - DialogHelper.displayMessageDialog( this, "Successfully synchronized 1 record", "Sync " + _tableName + " table" ); - } - else - { - DialogHelper.displayErrorDialog( this, "Failed to synchronize 1 record\nPlease check the log " + _raxSyncDataMgr.getInsertUpdateLogFilename() + " for more details", "Sync " + _tableName + " table" ); - } - processDifferences(); - updateSelectionComboBox(); - refreshRecordPanel(); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - MouseWheelListener itemSelectionMouseWheelListener = new ItemSelectionMouseWheelListener(); - - _closeButton.addActionListener( windowCloser ); - - _selectionLCB.addComboBoxActionListener( new ItemSelectionListener() ); - _selectionLCB.addComboBoxWheelListener( itemSelectionMouseWheelListener ); - _recordPanel.addMouseWheelListener( itemSelectionMouseWheelListener ); - _processSingleRecordButton.addActionListener( new ProcessSingleRecordButtonListener() ); - _processAllRecordsButton.addActionListener( new ProcessAllRecordButtonListener() ); - this.addMouseWheelListener( itemSelectionMouseWheelListener ); - } - - private class ProcessSingleRecordButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - processSingleRecord(); - } - } - - private class ProcessAllRecordButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - processAllRecords(); - } - } - - private class ItemSelectionMouseWheelListener implements MouseWheelListener - { - public void mouseWheelMoved( MouseWheelEvent e ) - { - int index = _selectionLCB.getSelectedIndex(); - int newIndex = 0; - - if ( e.getWheelRotation() > 0 ) - { - if ( ( _selectionLCB.getItemCount() - 1 ) == index ) - { - newIndex = 0; - } - else - { - newIndex = index + 1; - } - } - else - { - if ( index == 0 ) - { - newIndex = _selectionLCB.getItemCount() - 1; - } - else - { - newIndex = index - 1; - } - } - _selectionLCB.setSelectedIndex( newIndex ); - } - } - - private class ItemSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e) - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - _selectedRecordDiff = (RecordDifference) _selectionStringToDifferenceMap.get( selectedItem ); - - if ( _selectedRecordDiff != null ) - { - refreshRecordPanel(); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessIngestFilterDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessIngestFilterDifferencesDialog.java deleted file mode 100644 index 982d611270..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessIngestFilterDifferencesDialog.java +++ /dev/null @@ -1,155 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.RaxIngestFilterRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessIngestFilterDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessIngestFilterDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process IngestFilter", "IngestFilter", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(Lid | PE | Dur | IDur | TS | Extremum)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxIngestFilterRecord record = (RaxIngestFilterRecord) recordDiff.getRaxRecord(); - StringPadder lidPadder = new StringPadder( 8, 8 ); - StringPadder idurPadder = new StringPadder( 4, 8 ); - - cbString = lidPadder.getFrontPaddedString( record.getLid() ) + " | " + - PEManager.getPEFromPe1Pe2( record.getPe1(), record.getPe2() ) + " | " + - record.getDur() + " | " + - idurPadder.getFrontPaddedString( record.getIdur() ) + " | " + - TSManager.getTSFromTandS( record.getT(), record.getS() ) + " | " + - record.getE(); - - return cbString; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - IngestFilterRecord ihfsRecord = (IngestFilterRecord) _selectedRecordDiff.getIhfsRecord(); - RaxIngestFilterRecord raxRecord = (RaxIngestFilterRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = _padder.getFrontPaddedString( ihfsRecord.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRecord.getLid() ); - String pe = _padder.getFrontPaddedString( ihfsRecord.getPe() ) + "PE" + _padder.getEndPaddedString( "PE", raxRecord.getPe1() + raxRecord.getPe2() ); - String dur = _padder.getFrontPaddedString( ihfsRecord.getDur() ) + "Dur" + _padder.getEndPaddedString( "Dur", raxRecord.getIdur() + "/" + raxRecord.getDur() ); - String iDur = _padder.getFrontPaddedString( "" ) + "IDur" + _padder.getEndPaddedString( "IDur", raxRecord.getIdur() ); - String ts = _padder.getFrontPaddedString( ihfsRecord.getTs() ) + "TS" + _padder.getEndPaddedString( "TS", raxRecord.getT() + raxRecord.getS() ); - String extremum = _padder.getFrontPaddedString( ihfsRecord.getExtremum() ) + "Extremum" + _padder.getEndPaddedString( "Extremum", raxRecord.getE() ); - String tsRank = _padder.getFrontPaddedString( ihfsRecord.getTs_rank() ) + "TS Rank" + _padder.getEndPaddedString( "TS Rank", raxRecord.getTs_rank() ); - String det = _padder.getFrontPaddedString( "" ) + "Det" + _padder.getEndPaddedString( "Det", raxRecord.getDet() ); - String ingest = _padder.getFrontPaddedString( ihfsRecord.getIngest() ) + "Ingest" + _padder.getEndPaddedString( "Ingest", raxRecord.getIngest() ); - String newReport = _padder.getFrontPaddedString( "" ) + "New Report" + _padder.getEndPaddedString( "New Report", raxRecord.getNew_report() ); - String active = _padder.getFrontPaddedString( "" ) + "Active" + _padder.getEndPaddedString( "Active", raxRecord.getActive() ); - String ofsInput = _padder.getFrontPaddedString( ihfsRecord.getOfs_input() ) + "OFS Input" + _padder.getEndPaddedString( "OFS Input", raxRecord.getOfs_input() ); - String obsTime = _padder.getFrontPaddedString( "" ) + "ObsTime" + _padder.getEndPaddedString( "ObsTime", raxRecord.getObstime() ); - String ownag = _padder.getFrontPaddedString( "" ) + "Ownag" + _padder.getEndPaddedString( "Ownag", raxRecord.getOwnag() ); - String ownloc = _padder.getFrontPaddedString( "" ) + "Ownloc" + _padder.getEndPaddedString( "Ownloc", raxRecord.getOwnloc() ); - String mpeInput = _padder.getFrontPaddedString( ihfsRecord.getStg2_input() ) + "MPE Input" + _padder.getEndPaddedString( "MPE Input", raxRecord.getMpe_input() ); - - recordStringList.add( lid ); - recordStringList.add( pe ); - recordStringList.add( dur ); - recordStringList.add( iDur ); - recordStringList.add( ts ); - recordStringList.add( extremum ); - recordStringList.add( tsRank ); - recordStringList.add( det ); - recordStringList.add( ingest ); - recordStringList.add( newReport ); - recordStringList.add( active ); - recordStringList.add( ofsInput ); - recordStringList.add( obsTime ); - recordStringList.add( ownag ); - recordStringList.add( ownloc ); - recordStringList.add( mpeInput ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "ts_rank" ) ) - { - highlightStringList.add( tsRank ); - } - else if ( columnName.equalsIgnoreCase( "ingest" ) ) - { - highlightStringList.add( ingest ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessIngestFilterDifferencesDialog test = new ProcessIngestFilterDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessLocDataLimitsDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessLocDataLimitsDifferencesDialog.java deleted file mode 100644 index 74e94678ef..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessLocDataLimitsDifferencesDialog.java +++ /dev/null @@ -1,183 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.ihfsdb.generated.LocDataLimitsRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb.generated.RaxLocDataLimitsRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessLocDataLimitsDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessLocDataLimitsDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process LocDataLimits", "LocDataLimits", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(LID | PE | Dur | IDur | MonthDayStart)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxLocDataLimitsRecord record = (RaxLocDataLimitsRecord) recordDiff.getRaxRecord(); - StringPadder lidPadder = new StringPadder( 8, 8 ); - StringPadder idurPadder = new StringPadder( 4, 8 ); - - cbString = lidPadder.getFrontPaddedString( record.getLid() ) + " | " + - PEManager.getPEFromPe1Pe2( record.getPe1(), record.getPe2() ) + " | " + - record.getDur() + " | " + - idurPadder.getFrontPaddedString( record.getIdur() ) + " | " + - record.getMonthdaystart(); - - return cbString; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - LocDataLimitsRecord ihfsRecord = (LocDataLimitsRecord) _selectedRecordDiff.getIhfsRecord(); - RaxLocDataLimitsRecord raxRecord = (RaxLocDataLimitsRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = _padder.getFrontPaddedString( ihfsRecord.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRecord.getLid() ); - String pe = _padder.getFrontPaddedString( ihfsRecord.getPe() ) + "PE" + _padder.getEndPaddedString( "PE", raxRecord.getPe1() + raxRecord.getPe2() ); - String dur = _padder.getFrontPaddedString( ihfsRecord.getDur() ) + "Dur" + _padder.getEndPaddedString( "Dur", raxRecord.getIdur() + "/" + raxRecord.getDur() ); - String iDur = _padder.getFrontPaddedString( "" ) + "IDur" + _padder.getEndPaddedString( "IDur", raxRecord.getIdur() ); - String monthDayStart = _padder.getFrontPaddedString( ihfsRecord.getMonthdaystart() ) + "MonthDayStart" + _padder.getEndPaddedString( "MonthDayStart", raxRecord.getMonthdaystart() ); - String monthDayEnd = _padder.getFrontPaddedString( ihfsRecord.getMonthdayend() ) + "MonthDayEnd" + _padder.getEndPaddedString( "MonthDayEnd", raxRecord.getMonthdayend() ); - String grossRangeMin = _padder.getFrontPaddedString( ihfsRecord.getGross_range_min() ) + "GrossRangeMin" + _padder.getEndPaddedString( "GrossRangeMin", raxRecord.getGross_range_min() ); - String grossRangeMax = _padder.getFrontPaddedString( ihfsRecord.getGross_range_max() ) + "GrossRangeMax" + _padder.getEndPaddedString( "GrossRangeMax", raxRecord.getGross_range_max() ); - String reasonRangeMin = _padder.getFrontPaddedString( ihfsRecord.getReason_range_min() ) + "ReasonRangeMin" + _padder.getEndPaddedString( "ReasonRangeMin", raxRecord.getReason_range_min() ); - String reasonRangeMax = _padder.getFrontPaddedString( ihfsRecord.getReason_range_max() ) + "ReasonRangeMax" + _padder.getEndPaddedString( "ReasonRangeMax", raxRecord.getReason_range_max() ); - String rocMax = _padder.getFrontPaddedString( ihfsRecord.getRoc_max() ) + "RocMax" + _padder.getEndPaddedString( "RocMax", raxRecord.getRoc_max() ); - String alertLimit = _padder.getFrontPaddedString( ihfsRecord.getAlert_upper_limit() ) + "AlertLimit" + _padder.getEndPaddedString( "AlertLimit", raxRecord.getAlert_limit() ); - String alertRocLimit = _padder.getFrontPaddedString( ihfsRecord.getAlert_roc_limit() ) + "AlertRocLimit" + _padder.getEndPaddedString( "AlertRocLimit", raxRecord.getAlert_roc_limit() ); - String alarmLimit = _padder.getFrontPaddedString( ihfsRecord.getAlarm_upper_limit() ) + "AlarmLimit" + _padder.getEndPaddedString( "AlarmLimit", raxRecord.getAlarm_limit() ); - String alarmRocLimit = _padder.getFrontPaddedString( ihfsRecord.getAlarm_roc_limit() ) + "AlarmRocLimit" + _padder.getEndPaddedString( "AlarmRocLimit", raxRecord.getAlarm_roc_limit() ); - - recordStringList.add( lid ); - recordStringList.add( pe ); - recordStringList.add( dur ); - recordStringList.add( iDur ); - recordStringList.add( monthDayStart ); - recordStringList.add( monthDayEnd ); - recordStringList.add( grossRangeMin ); - recordStringList.add( grossRangeMax ); - recordStringList.add( reasonRangeMin ); - recordStringList.add( reasonRangeMax ); - recordStringList.add( rocMax ); - recordStringList.add( alertLimit ); - recordStringList.add( alertRocLimit ); - recordStringList.add( alarmLimit ); - recordStringList.add( alarmRocLimit ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "monthdayend" ) ) - { - highlightStringList.add( monthDayEnd ); - } - else if( columnName.equalsIgnoreCase( "gross_range_min" ) ) - { - highlightStringList.add( grossRangeMin ); - } - else if( columnName.equalsIgnoreCase( "gross_range_max" ) ) - { - highlightStringList.add( grossRangeMax ); - } - else if( columnName.equalsIgnoreCase( "reason_range_min" ) ) - { - highlightStringList.add( reasonRangeMin ); - } - else if( columnName.equalsIgnoreCase( "reason_range_max" ) ) - { - highlightStringList.add( reasonRangeMax ); - } - else if( columnName.equalsIgnoreCase( "roc_max" ) ) - { - highlightStringList.add( rocMax ); - } - else if( columnName.equalsIgnoreCase( "alert_limit" ) ) - { - highlightStringList.add( alertLimit ); - } - else if( columnName.equalsIgnoreCase( "alert_roc_limit" ) ) - { - highlightStringList.add( alertRocLimit ); - } - else if( columnName.equalsIgnoreCase( "alarm_limit" ) ) - { - highlightStringList.add( alarmLimit ); - } - else if( columnName.equalsIgnoreCase( "alarm_roc_limit" ) ) - { - highlightStringList.add( alarmRocLimit ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessLocDataLimitsDifferencesDialog test = new ProcessLocDataLimitsDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessLocationDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessLocationDifferencesDialog.java deleted file mode 100644 index cf86503b72..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessLocationDifferencesDialog.java +++ /dev/null @@ -1,198 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb.generated.RaxLocationRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.raxdb_sync.RecordDifferenceOriginType; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessLocationDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessLocationDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process Location", "Location", syncDataMgr, new StringPadder( 45, 45 ), new Dimension( 850, 550 ) ); - _keyString = "(LID | BeginDate)"; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getLidHeaderString(); - - LocationRecord ihfsRecord = (LocationRecord) _selectedRecordDiff.getIhfsRecord(); - RaxLocationRecord raxRecord = (RaxLocationRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = _padder.getFrontPaddedString( ihfsRecord.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRecord.getLid() ); - String sbd = _padder.getFrontPaddedString( "" ) + "Sbd" + _padder.getEndPaddedDateString( "Sbd", raxRecord.getSbd() ); - String sed = _padder.getFrontPaddedString( "" ) + "Sed" + _padder.getEndPaddedDateString( "Sed", raxRecord.getSed() ); - String goes = _padder.getFrontPaddedString( "" ) + "Goes" + _padder.getEndPaddedString( "Goes", raxRecord.getGoes() ); - String name = _padder.getFrontPaddedString( ihfsRecord.getName() ) + "Name" + _padder.getEndPaddedString( "Name", raxRecord.getName() ); - String det = _padder.getFrontPaddedString( ihfsRecord.getDet() ) + "Det" + _padder.getEndPaddedString( "Det", raxRecord.getDet() ); - String lat = _padder.getFrontPaddedString( ihfsRecord.getLat() ) + "Lat" + _padder.getEndPaddedString( "Lat", raxRecord.getLat() ); - String lon = _padder.getFrontPaddedString( ihfsRecord.getLon() ) + "Lon" + _padder.getEndPaddedString( "Lon", raxRecord.getLon() ); - String elev = _padder.getFrontPaddedString( ihfsRecord.getElev() ) + "Elev" + _padder.getEndPaddedString( "Elev", raxRecord.getElev() ); - String state = _padder.getFrontPaddedString( ihfsRecord.getState() ) + "State" + _padder.getEndPaddedString( "State", raxRecord.getState() ); - String huc = _padder.getFrontPaddedString( "" ) + "HUC" + _padder.getEndPaddedString( "HUC", raxRecord.getHuc() ); - String countyFips = _padder.getFrontPaddedString( ihfsRecord.getCounty() ) + "CountyFips" + _padder.getEndPaddedString( "CountyFips", raxRecord.getCountyfips() ); - String zon = _padder.getFrontPaddedString( "" ) + "Zon" + _padder.getEndPaddedString( "Zon", raxRecord.getZon() ); - String hsa = _padder.getFrontPaddedString( ihfsRecord.getHsa() ) + "HSA" + _padder.getEndPaddedString( "HSA", raxRecord.getHsa() ); - String wfo = _padder.getFrontPaddedString( ihfsRecord.getWfo() ) + "WFO" + _padder.getEndPaddedString( "WFO", raxRecord.getWfo() ); - String post = _padder.getFrontPaddedString( ihfsRecord.getPost() ) + "Post" + _padder.getEndPaddedString( "Post", raxRecord.getPost() ); - String dbSource = _padder.getFrontPaddedString( "" ) + "DbSource" + _padder.getEndPaddedString( "DbSource", raxRecord.getDbsource() ); - String rfc = _padder.getFrontPaddedString( ihfsRecord.getRfc() ) + "RFC" + _padder.getEndPaddedString( "RFC", raxRecord.getRfc() ); - String countryFips = _padder.getFrontPaddedString( "" ) + "CountryFips" + _padder.getEndPaddedString( "CountryFips", raxRecord.getCountryfips() ); - - recordStringList.add( lid ); - recordStringList.add( sbd ); - recordStringList.add( sed ); - recordStringList.add( goes ); - recordStringList.add( name ); - recordStringList.add( det ); - recordStringList.add( lat ); - recordStringList.add( lon ); - recordStringList.add( elev ); - recordStringList.add( state ); - recordStringList.add( huc ); - recordStringList.add( countyFips ); - recordStringList.add( zon ); - recordStringList.add( hsa ); - recordStringList.add( wfo ); - recordStringList.add( post ); - recordStringList.add( dbSource ); - recordStringList.add( rfc ); - recordStringList.add( countryFips ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "name" ) ) - { - highlightStringList.add( name ); - } - else if ( columnName.equalsIgnoreCase( "det" ) ) - { - highlightStringList.add( det ); - } - else if ( columnName.equalsIgnoreCase( "lat" ) ) - { - highlightStringList.add( lat ); - } - else if ( columnName.equalsIgnoreCase( "lon" ) ) - { - highlightStringList.add( lon ); - } - else if ( columnName.equalsIgnoreCase( "elev" ) ) - { - highlightStringList.add( elev ); - } - else if ( columnName.equalsIgnoreCase( "state" ) ) - { - highlightStringList.add( state ); - } - else if ( columnName.equalsIgnoreCase( "hsa" ) ) - { - highlightStringList.add( hsa ); - } - else if ( columnName.equalsIgnoreCase( "wfo" ) ) - { - highlightStringList.add( wfo ); - } - else if ( columnName.equalsIgnoreCase( "rfc" ) ) - { - highlightStringList.add( rfc ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - StringPadder padder = new StringPadder( 8, 8 ); - - RaxLocationRecord record = (RaxLocationRecord) recordDiff.getRaxRecord(); - - cbString = padder.getFrontPaddedString( record.getLid() ) + " | " + padder.getFrontPaddedDateString( record.getSbd() ); - - return cbString; - } - - protected String getLidHeaderString() - { - String headerString = null; - - if ( _selectedRecordDiff.getDiffType() == RecordDifferenceOriginType.MOD ) - { - headerString = "IHFS Record Existing Rax Record"; - } - else - { - headerString = "IHFS Record New Rax Record"; - } - - return headerString; - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessLocationDifferencesDialog test = new ProcessLocationDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessRatingDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessRatingDifferencesDialog.java deleted file mode 100644 index 90c482d7b4..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessRatingDifferencesDialog.java +++ /dev/null @@ -1,285 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.model.RaxRating; -import ohd.hseb.raxbase.model.RaxRatingOffset; -import ohd.hseb.raxbase.model.RaxRatingPoint; -import ohd.hseb.raxbase.model.RaxRatingShift; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RatingCurveHolder; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; -import ohd.hseb.util.StringDataConverter; - -public class ProcessRatingDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessRatingDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process Rating", "Rating", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(LID | PE | tbl | ValidDate | Src)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RatingCurveHolder ratingCurveHolder = (RatingCurveHolder) recordDiff.getRaxRecord(); - RaxRating raxRating = ratingCurveHolder.getRatingCurve(); - - StringPadder lidPadder = new StringPadder( 8, 8 ); - - cbString = lidPadder.getFrontPaddedString( raxRating.getLid() ) + " | " + - raxRating.getPe() + " | " + - raxRating.getTable() + " | " + - DbTimeHelper.getDateStringFromLongTime( raxRating.getValidDate() ) + " | " + - raxRating.getSrc(); - - return cbString; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - StringDataConverter converter = new StringDataConverter(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - RatingCurveHolder ihfsRatingCurveHolder = (RatingCurveHolder) _selectedRecordDiff.getIhfsRecord(); - RatingCurveHolder raxRatingCurveHolder = (RatingCurveHolder) _selectedRecordDiff.getRaxRecord(); - - RaxRating ihfsRating = (RaxRating) ihfsRatingCurveHolder.getRatingCurve(); - RaxRating raxRating = (RaxRating) raxRatingCurveHolder.getRatingCurve(); - - List ihfsRatingPointList = ihfsRating.getRaxRatingPointList(); - List raxRatingPointList = raxRating.getRaxRatingPointList(); - - String lid = _padder.getFrontPaddedString( ihfsRating.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRating.getLid() ); - String pe = _padder.getFrontPaddedString( "" ) + "PE" + _padder.getEndPaddedString( "PE", raxRating.getPe() ); - String tbl = _padder.getFrontPaddedString( "" ) + "Table" + _padder.getEndPaddedString( "Table", raxRating.getTable() ); - String validDate = _padder.getFrontPaddedString( "" ) + "ValidDate" + _padder.getEndPaddedDateString( "ValidDate", raxRating.getValidDate() ); - String src = _padder.getFrontPaddedString( "" ) + "Src" + _padder.getEndPaddedString( "Src", raxRating.getSrc() ); - String othagid = _padder.getFrontPaddedString( "" ) + "OthAgId" + _padder.getEndPaddedString( "OthAgId", raxRating.getOthagid() ); - String rfsInput = _padder.getFrontPaddedString( "" ) + "RFSInput" + _padder.getEndPaddedString( "RFSInput", raxRating.isRfsInput() ); - String units = _padder.getFrontPaddedString( "" ) + "Units" + _padder.getEndPaddedString( "Units", raxRating.getUnits() ); - String interpolate = _padder.getFrontPaddedString( "" ) + "Interpolate" + _padder.getEndPaddedString( "Interpolate", raxRating.getInterpolate() ); - String allowStg = _padder.getFrontPaddedString( "" ) + "AllowStage" + _padder.getEndPaddedString( "AllowStage", raxRating.getAllowStage() ); - - recordStringList.add( lid ); - recordStringList.add( pe ); - recordStringList.add( tbl ); - recordStringList.add( validDate ); - recordStringList.add( src ); - recordStringList.add( othagid ); - recordStringList.add( rfsInput ); - recordStringList.add( units ); - recordStringList.add( interpolate ); - recordStringList.add( allowStg ); - - recordStringList.add( " " ); - recordStringList.add( _padder.getFrontPaddedString( "Discharge" ) + "Stage" + _padder.getEndPaddedString( "Stage", "Discharge" ) ); - recordStringList.add( _padder.getFrontPaddedString( "---------" ) + "-----" + _padder.getEndPaddedString( "-----", "---------" ) ); - - List stageList = getCombinedStageList( ihfsRatingPointList, raxRatingPointList ); - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - for ( int i = 0; i < stageList.size(); i++ ) - { - double stageValue = (Double) stageList.get( i ); - - String ihfsStageDischargeString = getStageDischargeString( stageValue, ihfsRatingPointList ); - String raxStageDischargeString = getStageDischargeString( stageValue, raxRatingPointList ); - String stgFlow = _padder.getFrontPaddedString( ihfsStageDischargeString ) + stageValue + _padder.getEndPaddedString( "" + stageValue, raxStageDischargeString ); - recordStringList.add( stgFlow ); - - if ( ( fieldDifferenceList != null ) && ( isStageValueDifferent( stageValue, fieldDifferenceList ) ) ) - { - highlightStringList.add( stgFlow ); - } - } - - recordStringList.add( " " ); - List offSetsList = raxRating.getOffsets(); - - if ( ( offSetsList != null ) && ( ! offSetsList.isEmpty() ) ) - { - recordStringList.add( _padder.getFrontPaddedString( "Offset" ) + "Stage" + _padder.getEndPaddedString( "Stage", "Discharge" ) ); - recordStringList.add( _padder.getFrontPaddedString( "---------" ) + "-----" + _padder.getEndPaddedString( "-----", "---------" ) ); - - - for ( int i = 0; i < offSetsList.size(); i++ ) - { - RaxRatingOffset offset = (RaxRatingOffset) offSetsList.get( i ); - - String offsetString = _padder.getFrontPaddedString( "" ) + "Offset" + _padder.getEndPaddedString( "Offset", getOffsetString( offset ) ); - } - } - - RaxRatingShift raxRatingShift = raxRatingCurveHolder.getRatingShift(); - RaxRatingShift ihfsRatingShift = ihfsRatingCurveHolder.getRatingShift(); - - if ( raxRatingShift.getLid().equalsIgnoreCase( "LWAW4" ) ) - { - System.out.println( "MEOW" ); - } - if ( raxRatingShift != null ) - { - String lidShiftString = ""; - String shiftAString = ""; - String beginDateTimeString = ""; - - if ( ihfsRatingShift != null ) - { - lidShiftString = ihfsRatingShift.getLid(); - shiftAString = "" + ihfsRatingShift.getShiftA(); - beginDateTimeString = converter.getDateTimeStringFromDateTimeLong( ihfsRatingShift.getBeginDate() ); - } - - recordStringList.add( " " ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "-- RatingShift --" + _padder.getEndPaddedString( "-- RatingShift --", "" ) ); - recordStringList.add( _padder.getFrontPaddedString( lidShiftString ) + "LID" + _padder.getEndPaddedString( "LID", raxRatingShift.getLid() ) ); - recordStringList.add( _padder.getFrontPaddedString( beginDateTimeString ) + "BeginDate" + _padder.getEndPaddedDateTimeString( "BeginDate", raxRatingShift.getBeginDate() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "PE" + _padder.getEndPaddedString( "PE", raxRatingShift.getPe() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "Table" + _padder.getEndPaddedString( "Table", raxRatingShift.getRatingTableNumber() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "Src" + _padder.getEndPaddedString( "Src", raxRatingShift.getSource() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ValA" + _padder.getEndPaddedString( "ValA", raxRatingShift.getValA() ) ); - recordStringList.add( _padder.getFrontPaddedString( shiftAString ) + "ShiftA" + _padder.getEndPaddedString( "ShiftA", raxRatingShift.getShiftA() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ValB" + _padder.getEndPaddedString( "ValB", raxRatingShift.getValB() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ShiftB" + _padder.getEndPaddedString( "ShiftB", raxRatingShift.getShiftB() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ValC" + _padder.getEndPaddedString( "ValC", raxRatingShift.getValC() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ShiftC" + _padder.getEndPaddedString( "ShiftC", raxRatingShift.getShiftC() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ValD" + _padder.getEndPaddedString( "ValD", raxRatingShift.getValD() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "ShiftD" + _padder.getEndPaddedString( "ShiftD", raxRatingShift.getShiftD() ) ); - recordStringList.add( _padder.getFrontPaddedString( "" ) + "DatumAdj" + _padder.getEndPaddedString( "DatumAdj", raxRatingShift.getDatumAdjustment() ) ); - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - private String getOffsetString( RaxRatingOffset offset ) - { - return offset.getStage() + "," + offset.getOffset(); - } - - private boolean isStageValueDifferent( double stageValue, List fieldDifferencesList ) - { - boolean different = false; - - for ( int i = 0; i < fieldDifferencesList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferencesList.get( i ); - if ( Double.parseDouble( fieldDifference.getName() ) == stageValue ) - { - different = true; - break; - } - } - - return different; - } - - private String getStageDischargeString( double stageValue, List stageDischargeList ) - { - String stageDischargeString = ""; - double discharge = -9999; - - for ( int i = 0; i < stageDischargeList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) stageDischargeList.get( i ); - if ( raxRatingPoint.getStage() == stageValue ) - { - discharge = raxRatingPoint.getDischarge(); - break; - } - } - - if ( discharge != -9999 ) - { - stageDischargeString = "" + discharge; - } - else - { - } - - return stageDischargeString; - } - - private List getCombinedStageList( List ihfsRatingPointList, List raxRatingPointList ) - { - List combinedStageList = new ArrayList(); - Set combinedStageTreeSet = new TreeSet(); - - for ( int i = 0; i < ihfsRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) ihfsRatingPointList.get( i ); - combinedStageTreeSet.add( raxRatingPoint.getStage() ); - } - for ( int i = 0; i < raxRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) raxRatingPointList.get( i ); - combinedStageTreeSet.add( raxRatingPoint.getStage() ); - } - - for ( Iterator iterator = combinedStageTreeSet.iterator(); iterator.hasNext(); ) - { - combinedStageList.add( (Double) iterator.next() ); - } - - return combinedStageList; - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob82krfx?user=pguser", "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - - ProcessRatingDifferencesDialog test = new ProcessRatingDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessReservoirDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessReservoirDifferencesDialog.java deleted file mode 100644 index 62cdff1447..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessReservoirDifferencesDialog.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.ReservoirRecord; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb.generated.RaxReservoirRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessReservoirDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessReservoirDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process Reservoir", "Reservoir", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 650, 550 ) ); - _keyString = "(LID | BeginDate)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxReservoirRecord record = (RaxReservoirRecord) recordDiff.getRaxRecord(); - StringPadder lidPadder = new StringPadder( 8, 8 ); - - cbString = lidPadder.getFrontPaddedString( record.getLid() ) + " | " + - DbTimeHelper.getDateStringFromLongTime( record.getSbd() ); - - return cbString; - } - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - ReservoirRecord ihfsRecord = (ReservoirRecord) _selectedRecordDiff.getIhfsRecord(); - RaxReservoirRecord raxRecord = (RaxReservoirRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = _padder.getFrontPaddedString( ihfsRecord.getLid() ) + "LID" + _padder.getEndPaddedString( "LID", raxRecord.getLid() ); - String sbd = _padder.getFrontPaddedString( "" ) + "Sbd" + _padder.getEndPaddedDateString( "Sbd", raxRecord.getSbd() ); - String sed = _padder.getFrontPaddedString( "" ) + "Sed" + _padder.getEndPaddedDateString( "Sed", raxRecord.getSed() ); - String name = _padder.getFrontPaddedString( ihfsRecord.getName() ) + "Name" + _padder.getEndPaddedString( "Name", raxRecord.getName() ); - String type = _padder.getFrontPaddedString( ihfsRecord.getType() ) + "Type" + _padder.getEndPaddedString( "Type", raxRecord.getType() ); - String owner = _padder.getFrontPaddedString( ihfsRecord.getOwner() ) + "Owner" + _padder.getEndPaddedString( "Owner", raxRecord.getOwner() ); - String deadPool = _padder.getFrontPaddedString( ihfsRecord.getDeadpool() ) + "Dead Pool" + _padder.getEndPaddedString( "Dead Pool", raxRecord.getDeadpool() ); - String conserPool = _padder.getFrontPaddedString( ihfsRecord.getConserpool() ) + "Conser Pool" + _padder.getEndPaddedString( "Conser Pool", raxRecord.getConserpool() ); - String floodPool = _padder.getFrontPaddedString( ihfsRecord.getFloodpool() ) + "Flood Pool" + _padder.getEndPaddedString( "Flood Pool", raxRecord.getFloodpool() ); - String spillWay = _padder.getFrontPaddedString( ihfsRecord.getSpillway() ) + "Spillway" + _padder.getEndPaddedString( "Spillway", raxRecord.getSpillway() ); - String sill = _padder.getFrontPaddedString( ihfsRecord.getSill() ) + "Sill" + _padder.getEndPaddedString( "Sill", raxRecord.getSill() ); - String top = _padder.getFrontPaddedString( ihfsRecord.getTop() ) + "Top" + _padder.getEndPaddedString( "Top", raxRecord.getTop() ); - String surchg = _padder.getFrontPaddedString( ihfsRecord.getSurchg() ) + "Surchg" + _padder.getEndPaddedString( "Surchg", raxRecord.getSurchg() ); - String elev = _padder.getFrontPaddedString( ihfsRecord.getElev() ) + "Elev" + _padder.getEndPaddedString( "Elev", raxRecord.getElev() ); - String gates = _padder.getFrontPaddedString( ihfsRecord.getGates() ) + "Gates" + _padder.getEndPaddedString( "Gates", raxRecord.getGates() ); - String impounded = _padder.getFrontPaddedDateString( ihfsRecord.getImpounded() ) + "Impounded" + _padder.getEndPaddedDateString( "Impounded", raxRecord.getImpounded() ); - String uses = _padder.getFrontPaddedString( ihfsRecord.getUses() ) + "Uses" + _padder.getEndPaddedString( "Uses", raxRecord.getUses() ); - - recordStringList.add( lid ); - recordStringList.add( sbd ); - recordStringList.add( sed ); - recordStringList.add( name ); - recordStringList.add( type ); - recordStringList.add( owner ); - recordStringList.add( deadPool ); - recordStringList.add( conserPool ); - recordStringList.add( floodPool ); - recordStringList.add( spillWay ); - recordStringList.add( sill ); - recordStringList.add( top ); - recordStringList.add( surchg ); - recordStringList.add( elev ); - recordStringList.add( gates ); - recordStringList.add( impounded ); - recordStringList.add( uses ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "name" ) ) - { - highlightStringList.add( name ); - } - else if ( columnName.equalsIgnoreCase( "type" ) ) - { - highlightStringList.add( type ); - } - else if ( columnName.equalsIgnoreCase( "owner" ) ) - { - highlightStringList.add( owner ); - } - else if ( columnName.equalsIgnoreCase( "deadpool" ) ) - { - highlightStringList.add( deadPool ); - } - else if ( columnName.equalsIgnoreCase( "conserpool" ) ) - { - highlightStringList.add( conserPool ); - } - else if ( columnName.equalsIgnoreCase( "floodpool" ) ) - { - highlightStringList.add( floodPool ); - } - else if ( columnName.equalsIgnoreCase( "spillway" ) ) - { - highlightStringList.add( spillWay ); - } - else if ( columnName.equalsIgnoreCase( "sill" ) ) - { - highlightStringList.add( sill ); - } - else if ( columnName.equalsIgnoreCase( "top" ) ) - { - highlightStringList.add( top ); - } - else if ( columnName.equalsIgnoreCase( "surchg" ) ) - { - highlightStringList.add( surchg ); - } - else if ( columnName.equalsIgnoreCase( "elev" ) ) - { - highlightStringList.add( elev ); - } - else if ( columnName.equalsIgnoreCase( "gates" ) ) - { - highlightStringList.add( gates ); - } - else if ( columnName.equalsIgnoreCase( "impounded" ) ) - { - highlightStringList.add( impounded ); - } - else if ( columnName.equalsIgnoreCase( "uses" ) ) - { - highlightStringList.add( uses ); - } - } - } - } - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83raxtest?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessReservoirDifferencesDialog test = new ProcessReservoirDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessRiverCritDifferencesDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessRiverCritDifferencesDialog.java deleted file mode 100644 index 4cb0b3b6a5..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProcessRiverCritDifferencesDialog.java +++ /dev/null @@ -1,365 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.ListCellRenderer; -import javax.swing.border.LineBorder; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.model.RaxRiverCrit; -import ohd.hseb.raxbase.util.JListPanelSuperCellRenderer; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.StringPadder; -import ohd.hseb.raxdb.generated.RaxRiverCritRecord; -import ohd.hseb.raxdb_sync.FieldDifference; -import ohd.hseb.raxdb_sync.RaxSyncDataMgr; -import ohd.hseb.raxdb_sync.RecordDifference; -import ohd.hseb.raxdb_sync.RiverCritHolder; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -public class ProcessRiverCritDifferencesDialog extends ProcessDifferencesDialog -{ - public ProcessRiverCritDifferencesDialog( JFrame frame, RaxSyncDataMgr syncDataMgr ) - { - super( frame, "Process RiverCrit", "RiverCrit", syncDataMgr, new StringPadder( 25, 35 ), new Dimension( 1024, 800 ) ); - _keyString = "(LID | PE | VDTime)"; - } - - protected String getSelectionComboBoxString( RecordDifference recordDiff ) - { - String cbString = null; - - RaxRiverCritRecord record = (RaxRiverCritRecord) recordDiff.getRaxRecord(); - StringPadder lidPadder = new StringPadder( 8, 4 ); - - cbString = lidPadder.getFrontPaddedString( record.getLid() ) + " | " + - PEManager.getPEFromPe1Pe2( record.getPe1(), record.getPe2() ) + " | " + - DbTimeHelper.getDateStringFromLongTime( record.getVdtime() ); - - return cbString; - } - - - protected void refreshRecordPanel() - { - List recordStringList = new ArrayList(); - String headerString = null; - List highlightStringList = new ArrayList(); - double nullDouble = DbTable.getNullDouble(); - long nullLong = DbTable.getNullLong(); - - if ( _selectedRecordDiff != null ) - { - headerString = getHeaderString(); - - RiverCritHolder riverCritHolder = (RiverCritHolder) _selectedRecordDiff.getIhfsRecord(); - RaxRiverCrit raxRiverCrit = riverCritHolder.getRaxRiverCrit(); - RaxRiverCritRecord raxRecord = (RaxRiverCritRecord) _selectedRecordDiff.getRaxRecord(); - - String lid = getPaddedString( raxRiverCrit.getLid(), "LID", raxRecord.getLid() ); - String pe = getPaddedString( raxRiverCrit.getPe(), "PE", raxRecord.getPe1() + raxRecord.getPe2() ); - String vdTime = getPaddedDateString( "", "ValidTime", raxRecord.getVdtime() ); - String lowScreen = getPaddedString( "", "LowScreen", raxRecord.getLowscreen() ); - String sigrate = getPaddedString( "", "SigRate", raxRecord.getSigrate() ); - String screenrate = getPaddedString( "", "ScreenRate", raxRecord.getScreenrate() ); - String fis = getPaddedString( raxRiverCrit.getFis(), "Fis", raxRecord.getFis() ); - String action = getPaddedString( raxRiverCrit.getAction(), "Action", raxRecord.getAction() ); - String alert = getPaddedString( "", "Alert", raxRecord.getAlert() ); - String bank = getPaddedString( raxRiverCrit.getBank(), "Bank", raxRecord.getBank() ); - String flood = getPaddedString( raxRiverCrit.getMinorFloodStage(), "Flood", raxRecord.getFlood() ); - String modflood = getPaddedString( raxRiverCrit.getModerateFloodStage(), "ModFlood", raxRecord.getModflood() ); - String majflood = getPaddedString( raxRiverCrit.getMajorFloodStage(), "MajFlood", raxRecord.getMajflood() ); - String record = getPaddedString( "", "Record", raxRecord.getRecord() ); - String highscreen = getPaddedString( "", "HighScreen", raxRecord.getHighscreen() ); - String damscreen = getPaddedString( "", "DamScreen", raxRecord.getDamscreen() ); - String lowscreenf = getPaddedString( "", "LowScreenF", raxRecord.getLowscreenf() ); - String sigratef = getPaddedString( "", "SigRateF", raxRecord.getSigratef() ); - String screenratef = getPaddedString( "", "ScreenRateF", raxRecord.getScreenratef() ); - String fisf = getPaddedString( raxRiverCrit.getFisF(), "FisF", raxRecord.getFisf() ); - String actionf = getPaddedString( raxRiverCrit.getActionF(), "ActionF", raxRecord.getActionf() ); - String alertf = getPaddedString( "", "AlertF", raxRecord.getAlertf() ); - String bankf = getPaddedString( "", "BankF", raxRecord.getBankf() ); - String floodf = getPaddedString( raxRiverCrit.getMinorFloodFlow(), "FloodF", raxRecord.getFloodf() ); - String modfloodf = getPaddedString( raxRiverCrit.getModerateFloodFlow(), "ModFloodF", raxRecord.getModfloodf() ); - String majfloodf = getPaddedString( raxRiverCrit.getMajorFloodFlow(), "MajFloodF", raxRecord.getMajfloodf() ); - String recordf = getPaddedString( "", "RecordF", raxRecord.getRecordf() ); - String highscreenf = getPaddedString( "", "HighScreenF", raxRecord.getHighscreenf() ); - String damscreenf = getPaddedString( "", "DamScreenF", raxRecord.getDamscreenf() ); - String sigratet = getPaddedString( "", "SigRateT", raxRecord.getSigratet() ); - String screenratet = getPaddedString( "", "ScreenRateT", raxRecord.getScreenratet() ); - String lowscreenq = getPaddedString( "", "LowScreenQ", raxRecord.getLowscreenq() ); - String sigrateq = getPaddedString( "", "SigRateQ", raxRecord.getSigrateq() ); - String screenrateq = getPaddedString( "", "ScreenRateQ", raxRecord.getScreenrateq() ); - String fisq = getPaddedString( "", "FisQ", raxRecord.getFisq() ); - String actionq = getPaddedString( "", "ActionQ", raxRecord.getActionq() ); - String alertq = getPaddedString( "", "AlertQ", raxRecord.getAlertq() ); - String bankq = getPaddedString( "", "BankQ", raxRecord.getBankq() ); - String floodq = getPaddedString( "", "FloodQ", raxRecord.getFloodq() ); - String modfloodq = getPaddedString( "", "ModFloodQ", raxRecord.getModfloodq() ); - String majfloodq = getPaddedString( "", "MajFloodQ", raxRecord.getMajfloodq() ); - String recordq = getPaddedString( "", "RecordQ", raxRecord.getRecordq() ); - String highscreenq = getPaddedString( "", "HighScreenQ", raxRecord.getHighscreenq() ); - String damscreenq = getPaddedString( "", "DamScreenQ", raxRecord.getDamscreenq() ); - String stream = getPaddedString( raxRiverCrit.getStream(), "Stream", raxRecord.getStream() ); - String lat = getPaddedString( _raxSyncDataMgr.formatLatLon( raxRiverCrit.getLatitude() ), "Lat", _raxSyncDataMgr.formatLatLon( raxRecord.getLat() ) ); - String lon = getPaddedString( _raxSyncDataMgr.formatLatLon( raxRiverCrit.getLongitude() ), "Lon", _raxSyncDataMgr.formatLatLon( raxRecord.getLon() ) ); - String da = getPaddedString( raxRiverCrit.getDa(), "Da", raxRecord.getDa() ); - String mile = getPaddedString( raxRiverCrit.getMile(), "Mile", raxRecord.getMile() ); - String zd = getPaddedString( raxRiverCrit.getZd(), "Zd", raxRecord.getZd() ); - String vdatum = getPaddedString( raxRiverCrit.getVdatum(), "VDatum", raxRecord.getVdatum() ); - String cb = getPaddedString( raxRiverCrit.getCb(), "Cb", raxRecord.getCb() ); - String level = getPaddedString( raxRiverCrit.getLevel(), "Level", raxRecord.getLevel() ); - String pool = getPaddedString( raxRiverCrit.getPool(), "Pool", raxRecord.getPool() ); - String por = getPaddedString( raxRiverCrit.getPor(), "Por", raxRecord.getPor() ); - String tide = getPaddedString( raxRiverCrit.getTide(), "Tide", raxRecord.getTide() ); - String backwater = getPaddedString( raxRiverCrit.getBackwater(), "Backwater", raxRecord.getBackwater() ); - String rrevise = getPaddedDateString( raxRiverCrit.getRrevise(), "RRevise", raxRecord.getRrevise() ); - String rsource = getPaddedString( raxRiverCrit.getRsource(), "RSource", raxRecord.getRsource() ); - String responseTime = getPaddedString( raxRiverCrit.getResponseTime(), "ResponseTime", raxRecord.getResponse_time() ); - String thresholdRunoff = getPaddedString( raxRiverCrit.getThresholdRunoff(), "ThresholdRunoff", raxRecord.getThreshold_runoff() ); - String uhgdur = getPaddedString( raxRiverCrit.getUhgdur(), "UhgDur", raxRecord.getUhgdur() ); - String remark = getPaddedString( raxRiverCrit.getRemark(), "Remark", raxRecord.getRemark() ); - - - recordStringList.add( lid ); - recordStringList.add( pe ); - recordStringList.add( vdTime ); - recordStringList.add( lowScreen ); - recordStringList.add( sigrate ); - recordStringList.add( screenrate ); - recordStringList.add( fis ); - recordStringList.add( action ); - recordStringList.add( alert ); - recordStringList.add( bank ); - recordStringList.add( flood ); - recordStringList.add( modflood ); - recordStringList.add( majflood ); - recordStringList.add( record ); - recordStringList.add( highscreen ); - recordStringList.add( damscreen ); - recordStringList.add( lowscreenf ); - recordStringList.add( sigratef ); - recordStringList.add( screenratef ); - recordStringList.add( fisf ); - recordStringList.add( actionf ); - recordStringList.add( alertf ); - recordStringList.add( bankf ); - recordStringList.add( floodf ); - recordStringList.add( modfloodf ); - recordStringList.add( majfloodf ); - recordStringList.add( recordf ); - recordStringList.add( highscreenf ); - recordStringList.add( damscreenf ); - recordStringList.add( sigratet ); - recordStringList.add( screenratet ); - recordStringList.add( lowscreenq ); - recordStringList.add( sigrateq ); - recordStringList.add( screenrateq ); - recordStringList.add( fisq ); - recordStringList.add( actionq ); - recordStringList.add( alertq ); - recordStringList.add( bankq ); - recordStringList.add( floodq ); - recordStringList.add( modfloodq ); - recordStringList.add( majfloodq ); - recordStringList.add( recordq ); - recordStringList.add( highscreenq ); - recordStringList.add( damscreenq ); - recordStringList.add( stream ); - recordStringList.add( lat ); - recordStringList.add( lon ); - recordStringList.add( da ); - recordStringList.add( mile ); - recordStringList.add( zd ); - recordStringList.add( vdatum ); - recordStringList.add( cb ); - recordStringList.add( level ); - recordStringList.add( pool ); - recordStringList.add( por ); - recordStringList.add( tide ); - recordStringList.add( backwater ); - recordStringList.add( rrevise ); - recordStringList.add( rsource ); - recordStringList.add( responseTime ); - recordStringList.add( thresholdRunoff ); - recordStringList.add( uhgdur ); - recordStringList.add( remark ); - - List fieldDifferenceList = _selectedRecordDiff.getFieldDifferenceList(); - - if ( fieldDifferenceList != null ) - { - for ( int i = 0; i < fieldDifferenceList.size(); i++ ) - { - FieldDifference fieldDifference = (FieldDifference) fieldDifferenceList.get( i ); - String columnName = fieldDifference.getName(); - - if ( columnName.equalsIgnoreCase( "fis" ) ) - { - highlightStringList.add( fis ); - } - else if ( columnName.equalsIgnoreCase( "action" ) ) - { - highlightStringList.add( action ); - } - else if ( columnName.equalsIgnoreCase( "bank" ) ) - { - highlightStringList.add( bank ); - } - else if ( columnName.equalsIgnoreCase( "flood" ) ) - { - highlightStringList.add( flood ); - } - else if ( columnName.equalsIgnoreCase( "modflood" ) ) - { - highlightStringList.add( modflood ); - } - else if ( columnName.equalsIgnoreCase( "majflood" ) ) - { - highlightStringList.add( majflood ); - } - else if ( columnName.equalsIgnoreCase( "fisf" ) ) - { - highlightStringList.add( fisf ); - } - else if ( columnName.equalsIgnoreCase( "actionf" ) ) - { - highlightStringList.add( actionf ); - } - else if ( columnName.equalsIgnoreCase( "floodf" ) ) - { - highlightStringList.add( floodf ); - } - else if ( columnName.equalsIgnoreCase( "modfloodf" ) ) - { - highlightStringList.add( modfloodf ); - } - else if ( columnName.equalsIgnoreCase( "majfloodf" ) ) - { - highlightStringList.add( majfloodf ); - } - else if ( columnName.equalsIgnoreCase( "stream" ) ) - { - highlightStringList.add( stream ); - } - else if ( columnName.equalsIgnoreCase( "lat" ) ) - { - highlightStringList.add( lat ); - } - else if ( columnName.equalsIgnoreCase( "lon" ) ) - { - highlightStringList.add( lon ); - } - else if ( columnName.equalsIgnoreCase( "da" ) ) - { - highlightStringList.add( da ); - } - else if ( columnName.equalsIgnoreCase( "mile" ) ) - { - highlightStringList.add( mile ); - } - else if ( columnName.equalsIgnoreCase( "zd" ) ) - { - highlightStringList.add( zd ); - } - else if ( columnName.equalsIgnoreCase( "vdatum" ) ) - { - highlightStringList.add( vdatum ); - } - else if ( columnName.equalsIgnoreCase( "cb" ) ) - { - highlightStringList.add( cb ); - } - else if ( columnName.equalsIgnoreCase( "level" ) ) - { - highlightStringList.add( level ); - } - else if ( columnName.equalsIgnoreCase( "pool" ) ) - { - highlightStringList.add( pool ); - } - else if ( columnName.equalsIgnoreCase( "por" ) ) - { - highlightStringList.add( por ); - } - else if ( columnName.equalsIgnoreCase( "tide" ) ) - { - highlightStringList.add( tide ); - } - else if ( columnName.equalsIgnoreCase( "backwater" ) ) - { - highlightStringList.add( backwater ); - } - else if ( columnName.equalsIgnoreCase( "rrevise" ) ) - { - highlightStringList.add( rrevise ); - } - else if ( columnName.equalsIgnoreCase( "rsource" ) ) - { - highlightStringList.add( rsource ); - } - else if ( columnName.equalsIgnoreCase( "reponse_time" ) ) - { - highlightStringList.add( responseTime ); - } - else if ( columnName.equalsIgnoreCase( "threshold_runoff" ) ) - { - highlightStringList.add( thresholdRunoff ); - } - else if ( columnName.equalsIgnoreCase( "uhgdur" ) ) - { - highlightStringList.add( uhgdur ); - } - else if ( columnName.equalsIgnoreCase( "remark" ) ) - { - highlightStringList.add( remark ); - } - } - } - } - - if ( _recordPanel == null ) - { - _recordPanel = new JListPanel( "", recordStringList, false, Color.LIGHT_GRAY, - false, false, null ); - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - - } - else - { - _recordPanel.setBorder( new TitledBorder( new LineBorder( Color.LIGHT_GRAY), headerString ) ); - _recordPanel.updateListData( recordStringList ); - _recordPanel.refreshJList(); - } - - _recordPanel.setPreferredSize( new Dimension( 900, 400 ) ); - ListCellRenderer renderer = new JListPanelSuperCellRenderer( _recordPanel, highlightStringList, "", "" ); - _recordPanel.getTheJList().setCellRenderer(renderer); - - _recordPanel.getTheJList().setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); - _recordPanel.refreshJList(); - - _recordPanel.setVisible( false ); - if ( ! recordStringList.isEmpty() ) - { - _recordPanel.setVisible( true ); - } - } - - public static void main( String[] args ) - { - JFrame frame = new JFrame(); - - RaxSyncDataMgr syncDataMgr = new RaxSyncDataMgr( "jdbc:postgresql://lx5:5432/hd_ob83fwr?user=pguser", "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - - ProcessRiverCritDifferencesDialog test = new ProcessRiverCritDifferencesDialog( frame, syncDataMgr ); - test.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProdEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProdEditor.java deleted file mode 100644 index e62f5309dc..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ProdEditor.java +++ /dev/null @@ -1,393 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Prod; -import ohd.hseb.raxbase.table.ArcBaseProdJTableRowData; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ProdEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _prodTableManager = null; - private List _prodColumnDescriptorList = null; - private List _prodRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _prodSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _idLTF = new LabeledTextField( "ID:", "", "Product identifier", 11 ); - private LabeledTextField _pmaxLTF = new LabeledTextField( "PMax:", "", "Number of versions to store", 15 ); - private JCheckBox _papCB = new JCheckBox( "Pap:" ); - private String[] errStringArray = { "-1", "0", "1" }; - private LabeledComboBox _errCB = new LabeledComboBox( "Err:", errStringArray, "Parse & post error print flag: -1=no, 0=yes if errors, 1=yes" ); - private JCheckBox _graCB = new JCheckBox( "Gra:" ); - private JCheckBox _pr1CB = new JCheckBox( "Pr1:" ); - private JCheckBox _netCB = new JCheckBox( "Net:" ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _prodRowDataToProdMap = null; - - public ProdEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Prod Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 500 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initProdSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initProdSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _prodSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Prod" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _idLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _pmaxLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _papCB, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _errCB, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _graCB, 0, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _pr1CB, 0, 5, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _netCB, 0, 6, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _prodRowDataToProdMap = _dataMgr.getProdRowDataToProdMap(); - } - - private void initJTable() - { - _prodRowDataList = _dataMgr.getProdRowDataList(); - setCEColumnDescriptorList(); - _prodTableManager = new ComplexJTableManager( _prodColumnDescriptorList, _prodRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _prodTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _prodTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _prodTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 525, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _prodSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _prodRowDataList = _dataMgr.getProdRowDataList(); - _prodTableManager.setChangedAllRowDataList( _prodRowDataList ); - _prodTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _prodColumnDescriptorList = new ArrayList(); - - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "Id", true, 100, "center" ) ); - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "PMax", true, 100, "center" ) ); - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "Pap", true, 60, "center" ) ); - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "Err", true, 60, "center" ) ); - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "Gra", true, 80, "center" ) ); - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "Pr1", true, 60, "center" ) ); - _prodColumnDescriptorList.add(new JTableColumnDescriptor( "Net", true, 60, "center" ) ); - } - - private void populateDataInputPanel( Prod prod ) - { - if ( prod != null ) - { - _idLTF.setTextField( prod.getId() ); - _pmaxLTF.setTextField( prod.getPmax() ); - _papCB.setSelected( getBooleanValue( prod.getPap() ) ); - _errCB.setSelectedItem( getErrValue( prod.getErr() ) ); - _graCB.setSelected( getBooleanValue( prod.getGra() ) ); - _pr1CB.setSelected( getBooleanValue( prod.getPr1() ) ); - _netCB.setSelected( getBooleanValue( prod.getNet() ) ); - } - } - - private String getErrValue( int errValue ) - { - String returnString = null; - - if ( errValue == -1 ) - { - returnString = "-1"; - } - else if ( errValue == 0 ) - { - returnString = "0"; - } - else if ( errValue == 1 ) - { - returnString = "1"; - } - - return returnString; - } - - private boolean getBooleanValue( String stringValue ) - { - boolean returnValue = false; - - if ( stringValue.equalsIgnoreCase( "Y" ) ) - { - returnValue = true; - } - - return returnValue; - } - - private String getStringValue( boolean booleanValue ) - { - String returnValue = "N"; - - if ( booleanValue ) - { - returnValue = "Y"; - } - - return returnValue; - } - - private int getIntValue( boolean booleanValue ) - { - int intValue = 0; - - if ( booleanValue ) - { - intValue = 1; - } - - return intValue; - } - - private boolean getBooleanValue( int intValue ) - { - boolean returnValue = false; - - if ( intValue == 1 ) - { - returnValue = true; - } - - return returnValue; - } - - private void clearDataInputPanel() - { - _idLTF.setTextField( "" ); - _pmaxLTF.setTextField( "" ); - _papCB.setSelected( false ); - _errCB.setSelectedItem( "-1" ); - _graCB.setSelected( false ); - _pr1CB.setSelected( false ); - _netCB.setSelected( false ); - } - - private boolean saveProd() - { - boolean saved = false; - StringDataConverter converter = new StringDataConverter(); - - Prod prod = new Prod(); - - prod.setId( _idLTF.getTextFieldText() ); - prod.setPmax( converter.getIntValue( _pmaxLTF.getTextFieldText() ) ); - prod.setPap( getIntValue( _papCB.isSelected() ) ); - prod.setErr( Integer.parseInt( (String) _errCB.getSelectedItem() ) ); - prod.setGra( getStringValue( _graCB.isSelected() ) ); - prod.setPr1( getStringValue( _pr1CB.isSelected() ) ); - prod.setNet( getStringValue( _netCB.isSelected() ) ); - - saved = _dataMgr.saveProd( prod ); - - updateJTable(); - - return saved; - } - - private void deleteProd() - { - Prod prod = null; - List selectedRowsData = _prodTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseProdJTableRowData rowData = (ArcBaseProdJTableRowData) selectedRowsData.get( 0 ); - prod = (Prod) _prodRowDataToProdMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + prod.keyString(), "Delete Prod" ) ) - { - _dataMgr.deleteProdFromDataBase( prod ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Prod", "Delete Prod" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _prodTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveProd(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveProd() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteProd(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Prod prod = null; - - ArcBaseProdJTableRowData rowData = (ArcBaseProdJTableRowData) _prodTableManager.getSelectedRowsData().get( 0 ); - prod = (Prod) _prodRowDataToProdMap.get( rowData ); - populateDataInputPanel( prod ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ProdEditor prodEditor = new ProdEditor( frame, dataMgr ); - prodEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RatingCurveEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RatingCurveEditor.java deleted file mode 100644 index cad7fd9b21..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RatingCurveEditor.java +++ /dev/null @@ -1,1210 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ChartDirector.Chart; - -import ohd.hseb.color_chooser.ColorHolder; -import ohd.hseb.color_chooser.ColorPickerDialog; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxRating; -import ohd.hseb.raxbase.model.RaxRatingOffset; -import ohd.hseb.raxbase.model.RaxRatingPoint; -import ohd.hseb.raxbase.model.RaxRatingShift; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.table.ArcBaseRatingJTableRowData; -import ohd.hseb.raxbase.table.ArcBaseRatingOffsetsJTableRowData; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.raxbase.util.RaxRatingShiftCalculator; -import ohd.hseb.rfc.chart.ChartCreationException; -import ohd.hseb.rfc.chart.ChartDataSourceException; -import ohd.hseb.rfc.chart.ChartDrawer; -import ohd.hseb.rfc.chart.DefaultChartDrawer; -import ohd.hseb.rfc.chart.DefaultChartViewer; -import ohd.hseb.rfc.chart.DefaultDataSource; -import ohd.hseb.rfc.chart.props.SeriesProperty; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RatingCurveEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private String _lid = null; - - private List _ratingCurveList = null; - private List _ratingShiftList = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( true ); - - private RaxRating _selectedRaxRating = new RaxRating(); - private List _shiftedRaxRatingPointList = new ArrayList(); - - private StringDataConverter _converter = new StringDataConverter(); - - private RaxRatingShiftCalculator ratingShiftCalculator = new RaxRatingShiftCalculator(); - - private RaxRatingShift _selectedRaxRatingShift = new RaxRatingShift(); - - private Map _selectedRatingStringToRaxRating = new HashMap(); - - private JButton _ratingColorButton = new JButton( "Unshifted Curve Color" ); - private JButton _shiftedRatingColorButton = new JButton( "Shifted Curve Color" ); - private Color _ratingColor = null; - private Color _shiftedRatingColor = null; - - private LabeledComboBox _selectRatingLCB = new LabeledComboBox( "Select Rating Curve:" ); - - private DefaultChartViewer _viewer = null; - - private List _peCBStringList = new ArrayList(); - private Map _peCBStringToPeMap = new HashMap(); - - private enum axis { DISCHARGE, STAGE }; - private enum lineColor { UNSHIFTED, SHIFTED }; - -// JTable variables - private JTableManager _RCERatingTableManager = null; - private List _RCERatingColumnDescriptorList = null; - private List _ratingCurveRowDataList = null; - private JScrollPane _ratingTableScrollPane = null; - private JPanel _ratingJPanel = new JPanel( new GridBagLayout() ); - -// JTable variables - private JTableManager _RCEOffsetsTableManager = null; - private List _RCEOffsetsColumnDescriptorList = null; - private List _offsetsRowDataList = null; - private JScrollPane _offsetsTableScrollPane = null; - private JPanel _offsetsJPanel = new JPanel( new GridBagLayout() ); - - private JPanel _ratingCurvePanel = new JPanel( new GridBagLayout() ); - private JButton _updateInsertRatingPointButton = new JButton( "Update/Insert" ); - private JButton _removeRatingPointButton = new JButton( "Remove Point" ); - private LabeledTextField _stageCurveLTF = new LabeledTextField( " Stage:", "", 8 ); - private LabeledTextField _dischargeLTF = new LabeledTextField( "Discharge:", "", 8 ); - - private JPanel _offsetsPanel = new JPanel( new GridBagLayout() ); - private JButton _updateInsertOffsetButton = new JButton( "Update/Insert" ); - private JButton _removeOffsetButton = new JButton( "Remove Offset" ); - private LabeledTextField _stageOffsetLTF = new LabeledTextField( " Stage:", "", 8 ); - private LabeledTextField _offsetLTF = new LabeledTextField( "Offset:", "", 8 ); - - private JPanel _dataInputPanel = new JPanel( new GridBagLayout() ); - private LabeledComboBox _peLCB = null; - private LabeledTextField _tblLTF = new LabeledTextField( " Table:", "", "Number of rating table", 6 ); - private LabeledTextField _validDateLTF = new LabeledTextField( "Valid Date:", "", "Valid date and time of rating curve", 15 ); - private LabeledTextField _srcLTF = new LabeledTextField( " Source:", "", "Source of rating table, for example:
    USGS,
    ALERT,
    CODWR,
    USBR,
    USACE,
    OFS, etc.", 3 ); - private LabeledTextField _otherAgencyIDLTF = new LabeledTextField( " Other Agency ID:", "", "Other Agency ID", 16 ); - private JCheckBox _rfsInput = new JCheckBox( "RFS Input" ); - private LabeledTextField _unitsLTF = new LabeledTextField( " Units:", "", "Units", 4 ); - private LabeledTextField _allowStgLTF = new LabeledTextField( " Allow Stage:", "", "Minimum allowable stage to which a rating curve may be extended", 10 ); - private LabeledComboBox _interpolationLCB = new LabeledComboBox( "Interpolation method:", "Method of interpolation/extrapolation used, LIN or LOG" ); - - private JPanel _shiftPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _shiftStageALTF = new LabeledTextField( "Stage A:", "", "Stage value for first shift", 10 ); - private LabeledTextField _shiftStageBLTF = new LabeledTextField( "Stage B:", "", "Stage value for second shift", 10 ); - private LabeledTextField _shiftStageCLTF = new LabeledTextField( "Stage C:", "", "Stage value for third shift", 10 ); - private LabeledTextField _shiftStageDLTF = new LabeledTextField( "Stage D:", "", "Stage value for fourth shift", 10 ); - private LabeledTextField _shiftALTF = new LabeledTextField( "Shift A:", "", "First Shift", 10 ); - private LabeledTextField _shiftBLTF = new LabeledTextField( "Shift B:", "", "Second Shift", 10 ); - private LabeledTextField _shiftCLTF = new LabeledTextField( "Shift C:", "", "Third Shift", 10 ); - private LabeledTextField _shiftDLTF = new LabeledTextField( "Shift D:", "", "Fourth Shift", 10 ); - private LabeledTextField _datumAdjLTF = new LabeledTextField( "Datum Adjustment:", "", "Datum adjustment", 10 ); - - private JPanel _ratingButtonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveRatingButton = new JButton( "Save Rating" ); - private JButton _clearRatingButton = new JButton( "Clear Rating" ); - - private JButton _saveShiftsButton = new JButton( "Save Rating Shifts" ); - private JButton _clearShiftsButton = new JButton( "Clear Rating Shifts" ); - - private JPanel _mainButtonPanel = new JPanel( new GridBagLayout() ); - private JButton _closeButton = new JButton( "Close" ); - - private ActionListener _selectionLCBListener = new SelectRatingListener(); - - public static final short MISSING = -9999; - - public RatingCurveEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "Rating Curve Editor - " + title, true ); - _dataMgr = dataMgr; - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1200, 875 ) ); - initGUI(); - populateDataPanel(); - } - - private void initGUI() - { - setTitle( "Rating Curve Editor - " + _lid ); - setLayout( new GridBagLayout() ); - updateRatingCurveShiftList(); - populateSelectionComboBoxes(); - setSelectedRaxRating(); - setSelectedRaxRatingShift(); - initRatingJTable(); - initOffsetsJTable(); - initRatingCurvePanel(); - initOffsetsPanel(); - initDataInputPanel(); - initShiftPanel(); - initRatingCurveGraph(); - initFrameComponents(); - initRatingButtonPanel(); - initMainButtonPanel(); - setColorLabels(); - addListeners(); - populateDataPanel(); - pack(); - setVisible( true ); - } - - private void updateRatingCurveShiftList() - { - _ratingCurveList = _dataMgr.getRatingCurveList( _lid ); - _ratingShiftList = _dataMgr.getRatingShiftList( _lid ); - } - - private void initOffsetsPanel() - { - _offsetsPanel.setBorder( BorderFactory.createTitledBorder( "Offsets" ) ); - - JPanel hPanel1 = new JPanel(); - JPanel hPanel2 = new JPanel(); - JPanel hPanel3 = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _offsetsPanel, _offsetsJPanel, 0, 0, 2, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _offsetsPanel, hPanel1, 0, 21, 2, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _offsetsPanel, _stageOffsetLTF, 0, 22, 2, 1, 0, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _offsetsPanel, _offsetLTF, 0, 23, 2, 1, 0, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _offsetsPanel, hPanel2, 0, 24, 2, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _offsetsPanel, _updateInsertOffsetButton, 0, 25, 1, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _offsetsPanel, _removeOffsetButton, 1, 25, 1, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _offsetsPanel, hPanel3, 0, 26, 2, 1, 1, 0, GridBagConstraints.NONE ); - } - - private void initRatingCurvePanel() - { - _ratingCurvePanel.setBorder( BorderFactory.createTitledBorder( "Rating Points" ) ); - - JPanel hPanel1 = new JPanel(); - JPanel hPanel2 = new JPanel(); - JPanel hPanel3 = new JPanel(); - _ratingJPanel.setBackground( Color.YELLOW ); - - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingCurvePanel, _ratingJPanel, 0, 0, 2, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, hPanel1, 0, 21, 2, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, _stageCurveLTF, 0, 22, 2, 1, 1, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, _dischargeLTF, 0, 23, 2, 1, 1, 0, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, hPanel2, 0, 24, 2, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, _updateInsertRatingPointButton, 0, 25, 1, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, _removeRatingPointButton, 1, 25, 1, 1, 1, 0, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurvePanel, hPanel3, 0, 26, 2, 1, 1, 0, GridBagConstraints.NONE ); - } - - private void initDataInputPanel() - { - _dataInputPanel.setBorder( BorderFactory.createTitledBorder( "Misc Data" ) ); - - String[] interpolationStringArray = { "LIN", "LOG" }; - - _interpolationLCB.setComboBox( interpolationStringArray ); - setupPEComboBox(); - - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataInputPanel, _peLCB, 0, 0, 2, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _dataInputPanel, _tblLTF, 0, 1, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataInputPanel, _validDateLTF, 0, 2, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataInputPanel, _srcLTF, 0, 3, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataInputPanel, _unitsLTF, 0, 4, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataInputPanel, _allowStgLTF, 0, 5, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataInputPanel, _otherAgencyIDLTF, 0, 6, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataInputPanel, _rfsInput, 0, 7, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataInputPanel, _interpolationLCB, 0, 8, 2, 1, 1, 1, GridBagConstraints.BOTH ); - _hDateChooser.addOwner( this ); - _validDateLTF.setEditTextField( false ); - } - - private void setupPEComboBox() - { - List shefPeStringList = new ArrayList(); - List shefPeList = _dataMgr.getShefPeList(); - - for ( int i = 0; i < shefPeList.size(); i++ ) - { - ShefPE shefPE = (ShefPE) shefPeList.get( i ); - shefPeStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringToPeMap.put( getShefPEComboBoxString( shefPE ), shefPE.getPe() ); - } - - _peLCB = new LabeledComboBox( "PE:", shefPeStringList ); - } - - private String getShefPEComboBoxString( ShefPE shefPE ) - { - String shefPEString = shefPE.getPe() + " " + shefPE.getName(); - - return shefPEString; - } - - private void initShiftPanel() - { - _shiftPanel.setBorder( BorderFactory.createTitledBorder( BorderFactory.createLineBorder( Color.DARK_GRAY, 2 ), "Rating Shift" ) ); - - JPanel bPanel = new JPanel(); - - bPanel.add( _saveShiftsButton ); - bPanel.add( _clearShiftsButton ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shiftPanel, _shiftStageALTF, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftStageBLTF, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftStageCLTF, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftStageDLTF, 0, 3, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftALTF, 2, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftBLTF, 2, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftCLTF, 2, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _shiftDLTF, 2, 3, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, _datumAdjLTF, 0, 4, 4, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _shiftPanel, bPanel, 0, 5, 4, 1, 1, 1, GridBagConstraints.NONE ); - - } - - private void initRatingButtonPanel() - { - _ratingButtonPanel.setBorder( BorderFactory.createTitledBorder( "Rating Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _ratingButtonPanel, _saveRatingButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _ratingButtonPanel, _clearRatingButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - } - - private void initMainButtonPanel() - { - JPanel hPanel = new JPanel(); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _mainButtonPanel, _closeButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _mainButtonPanel, hPanel, 0, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponents() - { - JPanel hPanel = new JPanel(); - JPanel hPanel2 = new JPanel(); - JPanel hPanel3 = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _selectRatingLCB, 0, 0, 6, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, hPanel, 0, 1, 6, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _viewer, 0, 2, 4, 20, 1, 5, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _ratingCurvePanel, 4, 2, 2, 10, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _offsetsPanel, 4, 12, 2, 10, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _shiftPanel, 0, 23, 4, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _dataInputPanel, 4, 23, 2, 5, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, hPanel3, 4, 28, 2, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _ratingButtonPanel, 4, 29, 2, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, hPanel2, 0, 30, 6, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _mainButtonPanel, 0, 31, 6, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - _viewer.setBackground( Color.YELLOW ); - _viewer.setPreferredSize( _viewer.getChartDrawer().getChartProperties().getChartDimensions().getDimensions() ); - } - - private void setColorLabels() - { - _ratingColor = _viewer.getChartDrawer().getChartProperties().getLegendProps().getEntry( 0 ).getColor(); - _shiftedRatingColor =_viewer.getChartDrawer().getChartProperties().getLegendProps().getEntry( 1 ).getColor(); - } - - private void setRatingColor( Color color ) - { - _viewer.getChartDrawer().getChartProperties().getLegendProps().getEntry( 0 ).setColor( color ); - setColorLabels(); - _viewer.refresh(); - } - - private void setShiftedRatingColor( Color color ) - { - _viewer.getChartDrawer().getChartProperties().getLegendProps().getEntry( 1 ).setColor( color ); - setColorLabels(); - _viewer.refresh(); - } - - private double[] getStageArray( List raxRatingPointList, axis xyaxis ) - { - double[] doubleArray = new double[ raxRatingPointList.size() ]; - - if ( xyaxis == axis.STAGE ) - { - for ( int i = 0; i < raxRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) raxRatingPointList.get( i ); - - doubleArray[ i ] = raxRatingPoint.getStage(); - } - } - else - { - for ( int i = 0; i < raxRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) raxRatingPointList.get( i ); - - doubleArray[ i ] = raxRatingPoint.getDischarge(); - } - } - return doubleArray; - } - - private void calculateRatingShift() - { - if ( _selectedRaxRating != null ) - { - List raxRatingPointList = _selectedRaxRating.getRaxRatingPointList(); - - ratingShiftCalculator.setUnShiftedRaxRatingPointList( raxRatingPointList ); - ratingShiftCalculator.setRaxRatingShift( _selectedRaxRatingShift ); - ratingShiftCalculator.initRatingShift(); - _shiftedRaxRatingPointList = ratingShiftCalculator.getShiftedRaxRatingList(); - } - } - - private void updateGraph() - { - List raxRatingPointList = _selectedRaxRating.getRaxRatingPointList(); - - calculateRatingShift(); - - double[] unShiftedStageArray = getStageArray( raxRatingPointList, axis.STAGE ); - double[] unShiftedDischargeArray = getStageArray( raxRatingPointList, axis.DISCHARGE ); - double[] shiftedStageArray = getStageArray( _shiftedRaxRatingPointList, axis.STAGE ); - double[] shiftedDischargeArray = getStageArray( _shiftedRaxRatingPointList, axis.DISCHARGE ); - - ChartDrawer drawer = _viewer.getChartDrawer(); - - ( (DefaultDataSource) drawer.getPrimaryPlotData() ).setXAxisSeries( 0, unShiftedDischargeArray ); - ( (DefaultDataSource) drawer.getPrimaryPlotData() ).setYAxisSeries( 0, unShiftedStageArray ); - ( (DefaultDataSource) drawer.getPrimaryPlotData() ).setXAxisSeries( 1, shiftedDischargeArray ); - ( (DefaultDataSource) drawer.getPrimaryPlotData() ).setYAxisSeries( 1, shiftedStageArray ); - try - { - drawer.dataChanged( false ); - } - catch ( ChartCreationException e ) - { - e.printStackTrace(); - } - - _viewer.refresh(); - } - - private void initRatingCurveGraph() - { - DefaultDataSource primaryDataSource = new DefaultDataSource(); - Chart.setLicenseCode("DIST-0000-05a9-b536-41d2"); - List raxRatingPointList = new ArrayList(); - - if ( _selectedRaxRating != null ) - { - raxRatingPointList = _selectedRaxRating.getRaxRatingPointList(); - } - - calculateRatingShift(); - - double[] unShiftedStageArray = getStageArray( raxRatingPointList, axis.STAGE ); - double[] unShiftedDischargeArray = getStageArray( raxRatingPointList, axis.DISCHARGE ); - double[] shiftedStageArray = getStageArray( _shiftedRaxRatingPointList, axis.STAGE ); - double[] shiftedDischargeArray = getStageArray( _shiftedRaxRatingPointList, axis.DISCHARGE ); - - try - { - primaryDataSource.addNumericalSeries( - "Series 1", - unShiftedDischargeArray, - unShiftedStageArray, - SeriesProperty.LINE_PLOT); - - primaryDataSource.addNumericalSeries( - "Series 2", - shiftedDischargeArray, - shiftedStageArray, - SeriesProperty.LINE_PLOT); - - - DefaultChartDrawer drawer = new DefaultChartDrawer(primaryDataSource, null); - drawer.getChartProperties().getPlotTitle().setTextAndChangeDefault("Rating Curve"); - drawer.getChartProperties().getXAxisProps().getAxisLabelProps().setText("CFS"); - drawer.getChartProperties().getPrimaryYAxisProps().getAxisLabelProps().setText("Feet"); - drawer.getChartProperties().getLegendProps().getLegendTitleProps().setText("Rating Curves
    (Click entry to change color)"); - drawer.getChartProperties().getLegendProps().getEntry(0).setText("UnShifted Curve"); - drawer.getChartProperties().getLegendProps().getEntry(1).setText("Shifted Curve"); - drawer.getChartProperties().getLegendProps().getEntry(0).setShapeStr("CIRCLE"); - drawer.getGeneralColorProperties().setPlotExteriorBGColor( Color.LIGHT_GRAY ); - drawer.setBackgroundImageFileName( "/fs/hseb/pda/users/gsood/java/trunk/ohd-common/externaljar/chart_bg.png" ); - _viewer = new DefaultChartViewer( drawer, false ); - _viewer.setPreferredSize( null ); - } - - catch ( ChartCreationException e ) - { - e.printStackTrace(); - } - catch ( ChartDataSourceException e ) - { - e.printStackTrace(); - } - } - - - private void populateDataPanel() - { - if ( _selectedRaxRating != null ) - { - long validDate = 0; - String validDateString = null; - - ShefPE shefPE = (ShefPE) _dataMgr.getShefPEMap().get( _selectedRaxRating.getPe() ); - if ( shefPE != null ) - { - _peLCB.setSelectedItem( getShefPEComboBoxString( shefPE ) ); - } - else - { - _peLCB.setSelectedItem( "" ); - } - - validDate = _selectedRaxRating.getValidDate(); - - if ( validDate == MISSING ) - { - validDate = System.currentTimeMillis(); - } - - validDateString = DbTimeHelper.getDateTimeStringFromLongTime( validDate ); - - setNumberFields( _tblLTF, _selectedRaxRating.getTable() ); - _validDateLTF.setTextField( validDateString ); - _srcLTF.setTextField( _selectedRaxRating.getSrc() ); - _unitsLTF.setTextField( _selectedRaxRating.getUnits() ); - setNumberFields( _allowStgLTF, _selectedRaxRating.getAllowStage() ); - _otherAgencyIDLTF.setTextField( _selectedRaxRating.getOthagid() ); - _rfsInput.setSelected( _selectedRaxRating.isRfsInput() ); - - String interpolateString = _selectedRaxRating.getInterpolate(); - - if ( interpolateString != null ) - { - if ( interpolateString.equalsIgnoreCase( "LIN" ) ) - { - _interpolationLCB.setSelectedIndex( 0 ); - } - else - { - _interpolationLCB.setSelectedIndex( 1 ); - } - } - } - setNumberFields( _shiftALTF, _selectedRaxRatingShift.getShiftA() ); - setNumberFields( _shiftBLTF, _selectedRaxRatingShift.getShiftB() ); - setNumberFields( _shiftCLTF, _selectedRaxRatingShift.getShiftC() ); - setNumberFields( _shiftDLTF, _selectedRaxRatingShift.getShiftD() ); - setNumberFields( _shiftStageALTF, _selectedRaxRatingShift.getValA() ); - setNumberFields( _shiftStageBLTF, _selectedRaxRatingShift.getValB() ); - setNumberFields( _shiftStageCLTF, _selectedRaxRatingShift.getValC() ); - setNumberFields( _shiftStageDLTF, _selectedRaxRatingShift.getValD() ); - setNumberFields( _datumAdjLTF, _selectedRaxRatingShift.getDatumAdjustment() ); - } - - private void setNumberFields( LabeledTextField labeledTextField, double doubleValue ) - { - if ( ( DbTable.isNull( doubleValue ) ) || ( doubleValue == MISSING ) ) - { - labeledTextField.setTextField( "" ); - } - else - { - labeledTextField.setTextField( Double.toString( doubleValue ) ); - } - } - - private void setSelectedRaxRating() - { - String selectionComboBoxString = _selectRatingLCB.getSelectedCBItem(); - - _selectedRaxRating = (RaxRating) _selectedRatingStringToRaxRating.get( selectionComboBoxString ); - if ( _selectedRaxRating == null ) - { - _selectedRaxRating = new RaxRating(); - _selectedRaxRating.setLid( _lid ); - _selectedRaxRating.setRaxRatingPointList( new ArrayList() ); - _selectedRaxRating.setOffsets( new ArrayList() ); - } - } - - private void setSelectedRaxRatingShift() - { - RaxRatingShift raxRatingShift = new RaxRatingShift(); - - for ( int i = 0; i < _ratingShiftList.size(); i++ ) - { - raxRatingShift = (RaxRatingShift) _ratingShiftList.get( i ); - - if ( ( _selectedRaxRating.getLid().equalsIgnoreCase( raxRatingShift.getLid() ) ) && - ( _selectedRaxRating.getPe().equalsIgnoreCase( raxRatingShift.getPe() ) ) && - ( _selectedRaxRating.getTable() == raxRatingShift.getRatingTableNumber() ) && - ( _selectedRaxRating.getValidDate() == raxRatingShift.getBeginDate() ) && - ( _selectedRaxRating.getSrc().equalsIgnoreCase( raxRatingShift.getSource() ) ) ) - { - _selectedRaxRatingShift = raxRatingShift; - break; - } - } - } - - private void populateSelectionComboBoxes() - { - RaxRating raxRating = null; - String selectedRatingString = null; - List selectedRatingStringList = new ArrayList(); - - _selectedRatingStringToRaxRating.clear(); - - _selectRatingLCB.getComboBox().removeAllItems(); - - for ( int i = 0; i < _ratingCurveList.size(); i++ ) - { - raxRating = (RaxRating) _ratingCurveList.get( i ); - selectedRatingString = getSelectedRatingString( raxRating ); - selectedRatingStringList.add( selectedRatingString ); - _selectedRatingStringToRaxRating.put( selectedRatingString, raxRating ); - } - _selectRatingLCB.setComboBox( selectedRatingStringList ); - } - - private void updateSelectionComboBoxes() - { - _selectRatingLCB.getComboBox().removeActionListener( _selectionLCBListener ); - populateSelectionComboBoxes(); - _selectRatingLCB.addComboBoxActionListener( _selectionLCBListener ); - } - - private String getSelectedRatingString( RaxRating raxRating ) - { - return "PE = " + raxRating.getPe() + " | Tbl = " + raxRating.getTable() + " | ValidDate = " + - DbTimeHelper.getDateTimeStringFromLongTime( raxRating.getValidDate() ) + " | Src = " + - raxRating.getSrc(); - } - - - private void updateRatingJTable() - { - _ratingCurveRowDataList = _dataMgr.getRatingCurveRowDataList( _selectedRaxRating ); - calculateRatingShift(); - updateRatingCurveRowDataList(); - _RCERatingTableManager.setChangedAllRowDataList( _ratingCurveRowDataList ); - _RCERatingTableManager.refreshDisplay(); - } - - private void updateOffsetsJTable() - { - _offsetsRowDataList = _dataMgr.getOffsetsRowDataList( _selectedRaxRating ); - _RCEOffsetsTableManager.setChangedAllRowDataList( _offsetsRowDataList ); - _RCEOffsetsTableManager.refreshDisplay(); - } - - private void updateRatingCurveRowDataList() - { - for ( int i = 0; i < _ratingCurveRowDataList.size(); i++ ) - { - ArcBaseRatingJTableRowData rowData = (ArcBaseRatingJTableRowData) _ratingCurveRowDataList.get( i ); - RaxRatingPoint shiftedRaxRatingPoint = (RaxRatingPoint) _shiftedRaxRatingPointList.get( i ); - rowData.setShiftedStage( shiftedRaxRatingPoint.getStage() ); - rowData.addAllCellsToMap(); - } - } - - - private void initRatingJTable() - { - _ratingCurveRowDataList = _dataMgr.getRatingCurveRowDataList( _selectedRaxRating ); - calculateRatingShift(); - updateRatingCurveRowDataList(); - setRatingCurveColumnDescriptorList(); - _RCERatingTableManager = new ComplexJTableManager( _RCERatingColumnDescriptorList, _ratingCurveRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _RCERatingTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _RCERatingTableManager.setDisplayableColumns( columnsSelected, true, true ); - _ratingTableScrollPane = _RCERatingTableManager.getJScrollPane(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingJPanel, _ratingTableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void initOffsetsJTable() - { - _offsetsRowDataList = _dataMgr.getOffsetsRowDataList( _selectedRaxRating ); - setOffsetsColumnDescriptorList(); - _RCEOffsetsTableManager = new ComplexJTableManager( _RCEOffsetsColumnDescriptorList, _offsetsRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String selectedColumns[] = _RCEOffsetsTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _RCEOffsetsTableManager.setDisplayableColumns( selectedColumns, true, true ); - _offsetsTableScrollPane = _RCEOffsetsTableManager.getJScrollPane(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _offsetsJPanel, _offsetsTableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - - } - - private void setRatingCurveColumnDescriptorList() - { - _RCERatingColumnDescriptorList = new ArrayList(); - - _RCERatingColumnDescriptorList.add(new JTableColumnDescriptor( "Stage", true, 100, "center" ) ); - _RCERatingColumnDescriptorList.add(new JTableColumnDescriptor( "Shifted Stage", true, 100, "center" ) ); - _RCERatingColumnDescriptorList.add(new JTableColumnDescriptor( "Discharge", true, 100, "center" ) ); - } - - private void setOffsetsColumnDescriptorList() - { - _RCEOffsetsColumnDescriptorList = new ArrayList(); - - _RCEOffsetsColumnDescriptorList.add(new JTableColumnDescriptor( "Stage", true, 100, "center" ) ); - _RCEOffsetsColumnDescriptorList.add(new JTableColumnDescriptor( "Offset", true, 100, "center" ) ); - } - - private void populateRatingPanel( ArcBaseRatingJTableRowData rowData ) - { - setNumberFields( _stageCurveLTF, rowData.getStage() ); - setNumberFields( _dischargeLTF, rowData.getDischarge() ); - } - - private void populateOffsetsPanel( ArcBaseRatingOffsetsJTableRowData rowData ) - { - setNumberFields( _stageOffsetLTF, rowData.getStage() ); - setNumberFields( _offsetLTF, rowData.getOffset() ); - } - - private void launchDateWindow() - { - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = 0; - - if ( _validDateLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - dateLong = System.currentTimeMillis(); - } - else - { - dateLong = DbTimeHelper.getLongTimeFromDateString( _validDateLTF.getTextFieldText() ) + dayInMillis; - } - - calendar.setTimeInMillis( dateLong ); - - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - } - - public void dateChosen( JDialog jDialog ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateTimeStringFromCalendar( calendar ); - } - - _validDateLTF.setTextField( dateString ); - } - - private void removeRatingPoint() - { - ArcBaseRatingJTableRowData rowData = null; - try - { - rowData = (ArcBaseRatingJTableRowData) _RCERatingTableManager.getSelectedRowsData().get( 0 ); - - RaxRatingPoint raxRatingPoint = new RaxRatingPoint( rowData.getStage(), rowData.getDischarge() ); - - _selectedRaxRating.removeRatingPoint( raxRatingPoint ); - - updateRatingJTable(); - updateGraph(); - } - catch ( IndexOutOfBoundsException e ) - { - DialogHelper.displayErrorDialog( this, "A Rating Point must be selected", "Delete Rating Point" ); - } - } - - private void removeOffset() - { - ArcBaseRatingOffsetsJTableRowData rowData = null; - - try - { - rowData = (ArcBaseRatingOffsetsJTableRowData) _RCEOffsetsTableManager.getSelectedRowsData().get( 0 ); - - RaxRatingOffset offset = new RaxRatingOffset( rowData.getStage(), rowData.getOffset() ); - - _selectedRaxRating.removeOffset( offset ); - - updateOffsetsJTable(); - } - catch ( IndexOutOfBoundsException e ) - { - DialogHelper.displayErrorDialog( this, "An offset must be selected", "Delete Offset" ); - } - } - - private void updateInsertOffset() - { - try - { - double stage = Double.parseDouble( _stageOffsetLTF.getTextFieldText() ); - double offset = Double.parseDouble( _offsetLTF.getTextFieldText() ); - - RaxRatingOffset raxRatingOffset = new RaxRatingOffset( stage, offset ); - - _selectedRaxRating.addOffset( raxRatingOffset ); - - updateOffsetsJTable(); - } - catch ( NumberFormatException error ) - { - DialogHelper.displayErrorDialog( this, "A valid stage/offset must be entered", "Update/Insert Offset error" ); - } - catch ( NullPointerException error ){} - } - - private void updateInsertRatingPoint() - { - try - { - double stage = Double.parseDouble( _stageCurveLTF.getTextFieldText() ); - double discharge = Double.parseDouble( _dischargeLTF.getTextFieldText() ); - - RaxRatingPoint raxRatingPoint = new RaxRatingPoint( stage, discharge ); - - _selectedRaxRating.addRatingPoint( raxRatingPoint ); - - calculateRatingShift(); - updateRatingJTable(); - updateGraph(); - } - catch ( NumberFormatException error ) - { - DialogHelper.displayErrorDialog( this, "A valid stage/discharge must be entered", "Update/Insert Rating Point error" ); - } - catch ( NullPointerException error ) - { - } - } - private void saveShift() - { - RaxRatingShift raxRatingShift = new RaxRatingShift(); - - raxRatingShift.setLid( _selectedRaxRating.getLid() ); - raxRatingShift.setPe( _selectedRaxRating.getPe() ); - raxRatingShift.setRatingTableNumber( _selectedRaxRating.getTable() ); - raxRatingShift.setBeginDate( _selectedRaxRating.getValidDate() ); - raxRatingShift.setSource( _selectedRaxRating.getSrc() ); - - raxRatingShift.setValA( _converter.getDoubleValue( _shiftStageALTF.getTextFieldText() ) ); - raxRatingShift.setValB( _converter.getDoubleValue( _shiftStageBLTF.getTextFieldText() ) ); - raxRatingShift.setValC( _converter.getDoubleValue( _shiftStageCLTF.getTextFieldText() ) ); - raxRatingShift.setValD( _converter.getDoubleValue( _shiftStageDLTF.getTextFieldText() ) ); - raxRatingShift.setShiftA( _converter.getDoubleValue( _shiftALTF.getTextFieldText() ) ); - raxRatingShift.setShiftB( _converter.getDoubleValue( _shiftBLTF.getTextFieldText() ) ); - raxRatingShift.setShiftC( _converter.getDoubleValue( _shiftCLTF.getTextFieldText() ) ); - raxRatingShift.setShiftD( _converter.getDoubleValue( _shiftDLTF.getTextFieldText() ) ); - raxRatingShift.setDatumAdjustment( _converter.getDoubleValue( _datumAdjLTF.getTextFieldText() ) ); - - _dataMgr.saveRaxRatingShift( raxRatingShift ); - _selectedRaxRatingShift = raxRatingShift; - - populateDataPanel(); - calculateRatingShift(); - updateRatingJTable(); - updateGraph(); - } - - private void clearRating() - { - _selectedRaxRating = new RaxRating(); - _selectedRaxRating.setTable( DbTable.getNullDouble() ); - _selectedRaxRating.setAllowStage( DbTable.getNullDouble() ); - _selectedRaxRating.setValidDate( 0 ); - populateDataPanel(); - updateRatingJTable(); - updateOffsetsJTable(); - updateGraph(); - } - - private void saveRating() - { - RaxRating raxRating = new RaxRating(); - boolean primaryKeyEntered = false; - - if ( verifyPrimaryKey() ) - { - raxRating.setLid( _selectedRaxRating.getLid() ); - String pe = (String) _peLCB.getSelectedItem(); - - raxRating.setPe( (String) _peCBStringToPeMap.get( pe ) ); - raxRating.setTable( _converter.getDoubleValue( _tblLTF.getTextFieldText() ) ); - raxRating.setValidDate( _converter.getLongDateTimeValue( _validDateLTF.getTextFieldText() ) ); - raxRating.setSrc( _converter.getString( _srcLTF.getTextFieldText() ) ); - raxRating.setOthagid( _converter.getString( _otherAgencyIDLTF.getTextFieldText() ) ); - raxRating.setRfsInput( _rfsInput.isSelected() ); - raxRating.setRaxRatingPointList( _selectedRaxRating.getRaxRatingPointList() ); - raxRating.setUnits( _converter.getString( _unitsLTF.getTextFieldText() ) ); - raxRating.setInterpolate( _interpolationLCB.getSelectedCBItem() ); - raxRating.setOffsets( _selectedRaxRating.getOffsets() ); - raxRating.setAllowStage( _converter.getDoubleValue( _allowStgLTF.getTextFieldText() ) ); - - _dataMgr.saveRaxRating( raxRating ); - - updateRatingCurveShiftList(); - updateSelectionComboBoxes(); -// updateRatingJTable(); -// updateOffsetsJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "PE, Table, ValidDate, and Src must be entered", "Error Saving Rating" ); - } - } - - private boolean verifyPrimaryKey() - { - boolean valid = true; - String pe = (String) _peLCB.getSelectedItem(); - - if ( ( pe == null ) || ( pe.equalsIgnoreCase( "" ) ) ) - { - valid = false; - } - else if ( ( _tblLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || ( _tblLTF.getTextFieldText() == null ) ) - { - valid = false; - } - else if ( ( _validDateLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || ( _validDateLTF.getTextFieldText() == null ) ) - { - valid = false; - } - else if ( ( _srcLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || ( _srcLTF.getTextFieldText() == null ) ) - { - valid = false; - } - return valid; - } - - private void clearShift() - { - _shiftStageALTF.setTextField( "0" ); - _shiftStageBLTF.setTextField( "0" ); - _shiftStageCLTF.setTextField( "0" ); - _shiftStageDLTF.setTextField( "0" ); - _shiftALTF.setTextField( "0" ); - _shiftBLTF.setTextField( "0" ); - _shiftCLTF.setTextField( "0" ); - _shiftDLTF.setTextField( "0" ); - _datumAdjLTF.setTextField( "0" ); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - addWindowListener( windowCloser ); - - _RCERatingTableManager.addTableListener( new RCERatingTableListener() ); - _RCEOffsetsTableManager.addTableListener( new RCEOffsetsListener() ); - - _validDateLTF.addTextFieldMouseListener( new DateFieldMouseListener() ); - - _selectRatingLCB.addComboBoxActionListener( _selectionLCBListener ); - - _ratingColorButton.addActionListener( new RatingColorButtonListener() ); - _shiftedRatingColorButton.addActionListener( new ShiftedRatingColorButtonListener() ); - - _updateInsertRatingPointButton.addActionListener( new UpdateInsertRatingPointButtonListener() ); - _removeRatingPointButton.addActionListener( new RemoveRatingPointButtionListener() ); - - _saveShiftsButton.addActionListener( new SaveShiftsButtonListener() ); - _clearShiftsButton.addActionListener( new ClearShiftsButtonListener() ); - - _updateInsertOffsetButton.addActionListener( new UpdateInsertOffsetButtonListener() ); - _removeOffsetButton.addActionListener( new RemoveOffsetButtonListener() ); - - _saveRatingButton.addActionListener( new SaveRatingButton() ); - _clearRatingButton.addActionListener( new ClearRatingButton() ); - _viewer.addMouseListener( new ViewMouserListener() ); - - _closeButton.addActionListener( windowCloser ); - } - - private void displayColorPickerDialog( lineColor line ) - { - if ( line == lineColor.UNSHIFTED ) - { - ColorHolder colorHolder = new ColorHolder( _ratingColor ); - - ColorPickerDialog colorPicker = new ColorPickerDialog( this, colorHolder ); - colorPicker.setPreferredSize( new Dimension( 300, 300 ) ); - colorPicker.setVisible( true ); - setRatingColor( colorHolder.getColor() ); - } - else - { - ColorHolder colorHolder = new ColorHolder( _shiftedRatingColor ); - - ColorPickerDialog colorPicker = new ColorPickerDialog( this, colorHolder ); - colorPicker.setPreferredSize( new Dimension( 300, 300 ) ); - colorPicker.setVisible( true ); - setShiftedRatingColor( colorHolder.getColor() ); - } - } - - private class ViewMouserListener implements MouseListener - { - - public void mouseClicked( MouseEvent arg0 ) - { - int index = _viewer.getChartDrawer().retrieveSeriesLabelIndex( arg0.getPoint() ); - - if ( index == 0 ) - { - displayColorPickerDialog( lineColor.UNSHIFTED ); - } - else if ( index == 1 ) - { - displayColorPickerDialog( lineColor.SHIFTED ); - } - } - - public void mouseEntered( MouseEvent arg0 ){} - public void mouseExited( MouseEvent arg0 ){} - public void mousePressed( MouseEvent e ){} - public void mouseReleased( MouseEvent e ){} - } - - private class SaveRatingButton implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveRating(); - } - } - - private class ClearRatingButton implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clearRating(); - } - } - - private class RatingColorButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - displayColorPickerDialog( lineColor.UNSHIFTED ); - } - } - - private class ShiftedRatingColorButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - displayColorPickerDialog( lineColor.SHIFTED ); - } - } - - private class UpdateInsertRatingPointButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateInsertRatingPoint(); - } - } - - private class UpdateInsertOffsetButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateInsertOffset(); - } - } - - private class SaveShiftsButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShift(); - } - } - - private class ClearShiftsButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - clearShift(); - } - } - - private class RemoveRatingPointButtionListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - removeRatingPoint(); - } - } - - private class RemoveOffsetButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - removeOffset(); - } - } - - private class SelectRatingListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - setSelectedRaxRating(); - setSelectedRaxRatingShift(); - populateDataPanel(); - updateRatingJTable(); - updateOffsetsJTable(); - updateGraph(); - } - } - - private class RCERatingTableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ArcBaseRatingJTableRowData rowData = (ArcBaseRatingJTableRowData) _RCERatingTableManager.getSelectedRowsData().get( 0 ); - populateRatingPanel( rowData ); - } - } - } - - private class RCEOffsetsListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - ArcBaseRatingOffsetsJTableRowData rowData = (ArcBaseRatingOffsetsJTableRowData) _RCEOffsetsTableManager.getSelectedRowsData().get( 0 ); - populateOffsetsPanel( rowData ); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class DateFieldMouseListener implements MouseListener - { - public void mouseClicked( MouseEvent e ){} - public void mouseEntered( MouseEvent e ){} - public void mouseExited( MouseEvent e ){} - public void mouseReleased( MouseEvent e ){} - public void mousePressed( MouseEvent e ) - { - launchDateWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://lx5:5432/adb_ob83raxtest?user=pguser" ); - String title = "ABOVE_FS"; - String name = dataMgr.getRaxLocation( "ABOVE_FS" ).getName(); - - if ( name != null ) - { - title += " - " + name; - } - - - RatingCurveEditor ratingCurveEditor = new RatingCurveEditor( frame, dataMgr, "ABOVE_FS", title ); -// RatingCurveEditor ratingCurveEditor = new RatingCurveEditor( frame, dataMgr, "WFRC2" ); - ratingCurveEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ReservoirEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ReservoirEditor.java deleted file mode 100644 index f9898fc0b9..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ReservoirEditor.java +++ /dev/null @@ -1,681 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxReservoir; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; - -public class ReservoirEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private List _raxReservoirList = null; - - private LabeledComboBox _selectionLCB = new LabeledComboBox(); - private Map _selectionStringToRaxReservoirMap = new HashMap(); - private String _lid = null; - private RaxBaseDataMgr _dataMgr = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - private int _clickedDateField = -9999; - - private JPanel _informationPanel = new JPanel( new GridBagLayout() ); - - private long _beginDate = -9999; - private StringDataConverter _converter = new StringDataConverter(); - - private JPanel _metaDataPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Name", 22 ); - private LabeledTextField _beginDateLTF = new LabeledTextField( "Begin Date:", "", "Begin Date", 10 ); - private LabeledTextField _endDateLTF = new LabeledTextField( "End Date:", "", "End Date", 10 ); - private LabeledTextField _impoundDateLTF = new LabeledTextField( "Impound Date:", "", "The date that water was initially impounded by this reservoir", 12 ); - private LabeledTextField _gatesLTF = new LabeledTextField( "Gates:", "", "Number of gates", 10 ); - private LabeledTextField _typeLTF = new LabeledTextField( "Type:", "", "Type of dam construction (eg, earthen, concrete, levee, gravity, arch)", 12 ); - private LabeledTextField _ownerLTF = new LabeledTextField( "Owner:", "", "Owner of the dam", 12 ); - - private JPanel _elevationPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _maxSurchargeLTF = new LabeledTextField( "Max Surcharge:", "", "Maximum elevation (ft MSL) for water stored in a reservoir before release is required", 10 ); - private LabeledTextField _topLTF = new LabeledTextField( "Top:", "", "Elevation (ft MSL) of the top of dam", 10 ); - private LabeledTextField _sillLTF = new LabeledTextField( "Sill:", "", "Elevation of the sill structure of the dam that holds a reservoir (ft MSL)", 10 ); - private LabeledTextField _reservoirLTF = new LabeledTextField( "Reservoir:", "", "Elevation (ft MSL)", 10 ); - - private JPanel _poolsPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _floodLTF = new LabeledTextField( "Flood:", "", "Flood pool elevation (ft MSL)", 10 ); - private LabeledTextField _spillwayLTF = new LabeledTextField( "Spillway:", "", "Elevation of the dam spillway structure", 10 ); - private LabeledTextField _conservationLTF = new LabeledTextField( "Conservation:", "", "The minimum water level of a reservoir to be conserved in order to serve the needs of downstream water users during non-rainy times of the year (ft MSL)", 10 ); - private LabeledTextField _deadLTF = new LabeledTextField( "Dead:", "", "Lowest water level allowed for a reservoir through normal operations (ft MSL)", 10 ); - - private JPanel _usesPanel = new JPanel( new GridBagLayout() ); - private JCheckBox _floodControlCB = new JCheckBox( "Flood Control" ); - private JCheckBox _hydroCB = new JCheckBox( "Hydroelectric" ); - private JCheckBox _lowFlowCB = new JCheckBox( "Low Flow Augmentation" ); - private JCheckBox _navigationCB = new JCheckBox( "Navigation" ); - private JCheckBox _recreationCB = new JCheckBox( "Recreation" ); - private JCheckBox _waterSupplyCB = new JCheckBox( "Water Supply" ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - public ReservoirEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "Reservoir Editor - " + title, true ); - _dataMgr = dataMgr; - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 475 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - updateRaxReservoirList(); - updateSelectionComboBox(); - initInformationPanel(); - initElevationPanel(); - initPoolsPanel(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - initPopulateInformationPanel(); - - pack(); - setVisible( true ); - } - - private void updateRaxReservoirList() - { - _raxReservoirList = _dataMgr.getRaxReservoirListFromRaxLocation( _lid ); - } - - private void initPopulateInformationPanel() - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - RaxReservoir raxReservoir = (RaxReservoir) _selectionStringToRaxReservoirMap.get( selectedItem ); - - if ( raxReservoir != null ) - { - _beginDate = raxReservoir.getBeginDate(); - } - else - { - _beginDate = 0; - } - if ( raxReservoir != null ) - { - populateDataFields( raxReservoir ); - } - } - - private void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _buttonPanel, _saveButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _buttonPanel, _closeButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - - } - - - private void updateSelectionComboBox() - { - RaxReservoir raxReservoir = null; - List selectionComboBoxStringList = new ArrayList(); - String dateString = null; - - _selectionStringToRaxReservoirMap.clear(); - _selectionLCB.getComboBox().removeAllItems(); - - for ( int i = 0; i < _raxReservoirList.size(); i++ ) - { - raxReservoir = (RaxReservoir) _raxReservoirList.get( i ); - dateString = DbTimeHelper.getDateStringFromLongTime( raxReservoir.getBeginDate() ); - selectionComboBoxStringList.add( dateString ); - _selectionStringToRaxReservoirMap.put( dateString, raxReservoir ); - } - - if ( selectionComboBoxStringList.isEmpty() ) - { - selectionComboBoxStringList.add( "No entries found" ); - } - _selectionLCB.setComboBoxFromStringArray( selectionComboBoxStringList.toArray() ); - _selectionLCB.setLabel( "Service Begin Date:" ); - _selectionLCB.setLabelPreferredSize( new Dimension( 125, 15 ) ); - _selectionLCB.setComboBoxPreferredSize( new Dimension( 125, 15 ) ); - } - - private void initInformationPanel() - { - _informationPanel.setBorder( BorderFactory.createTitledBorder( "Information for " + _lid ) ); - - initUsesPanel(); - _beginDateLTF.setEditTextField( false ); - _endDateLTF.setEditTextField( false ); - _impoundDateLTF.setEditTextField( false ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _metaDataPanel, _nameLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _metaDataPanel, _beginDateLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _metaDataPanel, _endDateLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _metaDataPanel, _impoundDateLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _metaDataPanel, _gatesLTF, 0, 4, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _metaDataPanel, _typeLTF, 0, 5, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _metaDataPanel, _ownerLTF, 0, 6, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addFrameComponent( _informationPanel, _metaDataPanel, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _informationPanel, _usesPanel, 1, 0, 1, 1, GridBagConstraints.NONE ); - - _hDateChooser.addOwner( this ); - } - - private void initElevationPanel() - { - _elevationPanel.setBorder( BorderFactory.createTitledBorder( "Elevations" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _elevationPanel, _maxSurchargeLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _elevationPanel, _topLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _elevationPanel, _sillLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _elevationPanel, _reservoirLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - } - - private void initPoolsPanel() - { - _poolsPanel.setBorder( BorderFactory.createTitledBorder( "Pools" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _poolsPanel, _floodLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _poolsPanel, _spillwayLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _poolsPanel, _conservationLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _poolsPanel, _deadLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - } - - private void initUsesPanel() - { - _usesPanel.setBorder( BorderFactory.createTitledBorder( "Uses" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _usesPanel, _floodControlCB, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _usesPanel, _hydroCB, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _usesPanel, _lowFlowCB, 0, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _usesPanel, _navigationCB, 0, 3, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _usesPanel, _recreationCB, 0, 4, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _usesPanel, _waterSupplyCB, 0, 5, 1, 1, GridBagConstraints.BOTH ); - - } - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _selectionLCB, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addFrameComponent( _dialogContentPane, _informationPanel, 0, 1, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _elevationPanel, 0, 2, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _poolsPanel, 1, 2, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 3, 2, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void populateDataFields( RaxReservoir raxReservoir ) - { - _nameLTF.setTextField( raxReservoir.getName() ); - setDateField( _beginDateLTF, raxReservoir.getBeginDate() ); - setDateField( _endDateLTF, raxReservoir.getEndDate() ); - setDateField( _impoundDateLTF, raxReservoir.getImpounded() ); - _gatesLTF.setTextField( raxReservoir.getGates() ); - _typeLTF.setTextField( raxReservoir.getType() ); - _ownerLTF.setTextField( raxReservoir.getOwner() ); - _maxSurchargeLTF.setTextField( raxReservoir.getSurchg() ); - _topLTF.setTextField( raxReservoir.getTop() ); - _sillLTF.setTextField( raxReservoir.getSill() ); - _reservoirLTF.setTextField( raxReservoir.getElev() ); - _floodLTF.setTextField( raxReservoir.getFloodPool() ); - _spillwayLTF.setTextField( raxReservoir.getSpillWay() ); - _conservationLTF.setTextField( raxReservoir.getConserPool() ); - _deadLTF.setTextField( raxReservoir.getDeadPool() ); - - populateCheckBoxes( raxReservoir ); - } - - public void setDateField( LabeledTextField ltf, long dateLongValue ) - { - if ( dateLongValue == DbTable.getNullLong() ) - { - ltf.setTextField( "" ); - } - else - { - ltf.setTextField( DbTimeHelper.getDateStringFromLongTime( dateLongValue ) ); - } - } - - - private void populateCheckBoxes( RaxReservoir raxReservoir ) - { - String uses = raxReservoir.getUses(); - if ( uses != null ) - { - if ( uses.indexOf( "F" ) != -1 ) - { - _floodControlCB.setSelected( true ); - } - else - { - _floodControlCB.setSelected( false ); - } - - if ( uses.indexOf( "H" ) != -1 ) - { - _hydroCB.setSelected( true ); - } - else - { - _hydroCB.setSelected( false ); - } - - if ( uses.indexOf( "L" ) != -1 ) - { - _lowFlowCB.setSelected( true ); - } - else - { - _lowFlowCB.setSelected( false ); - } - - if ( uses.indexOf( "N" ) != -1 ) - { - _navigationCB.setSelected( true ); - } - else - { - _navigationCB.setSelected( false ); - } - - if ( uses.indexOf( "R" ) != -1 ) - { - _recreationCB.setSelected( true ); - } - else - { - _recreationCB.setSelected( false ); - } - - if ( uses.indexOf( "W" ) != -1 ) - { - _waterSupplyCB.setSelected( true ); - } - else - { - _waterSupplyCB.setSelected( false ); - } - } - } - - private void launchDateWindow( int clickedDateField ) - { - _clickedDateField = clickedDateField; - - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = 0; - String dateString = null; - - switch ( _clickedDateField ) - { - case 0: dateString = _beginDateLTF.getTextFieldText(); break; - case 1: dateString = _endDateLTF.getTextFieldText(); break; - case 2: dateString = _impoundDateLTF.getTextFieldText(); break; - } - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - dateLong = DbTimeHelper.getLongTimeFromDateString( dateString ) + dayInMillis; - } - else - { - dateLong = System.currentTimeMillis(); - } - - calendar.setTimeInMillis( dateLong ); - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - - } - - public void dateChosen( JDialog jDialog ) - { - if ( _clickedDateField != -9999 ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - switch ( _clickedDateField ) - { - case 0: _beginDateLTF.setTextField( dateString ); break; - case 1: _endDateLTF.setTextField( dateString ); break; - case 2: _impoundDateLTF.setTextField( dateString ); break; - } - _clickedDateField = -9999; - } - } - - private RaxReservoir getRaxReservoirToSave() - { - RaxReservoir reservoir = new RaxReservoir(); - StringBuffer usesStringBuffer = new StringBuffer(); - - reservoir.setLid( _lid ); - reservoir.setBeginDate( _converter.getLongDateValue( _beginDateLTF.getTextFieldText() ) ); - reservoir.setEndDate( _converter.getLongDateValue( _endDateLTF.getTextFieldText() ) ); - reservoir.setName( _nameLTF.getTextFieldText() ); - reservoir.setType( _typeLTF.getTextFieldText() ); - reservoir.setOwner( _ownerLTF.getTextFieldText() ); - reservoir.setDeadPool( _converter.getDoubleValue( _deadLTF.getTextFieldText() ) ); - reservoir.setConserPool( _converter.getDoubleValue( _conservationLTF.getTextFieldText() ) ); - reservoir.setFloodPool( _converter.getDoubleValue( _floodLTF.getTextFieldText() ) ); - reservoir.setSpillWay( _converter.getDoubleValue( _spillwayLTF.getTextFieldText() ) ); - reservoir.setSill( _converter.getDoubleValue( _sillLTF.getTextFieldText() ) ); - reservoir.setTop( _converter.getDoubleValue( _topLTF.getTextFieldText() ) ); - reservoir.setSurchg( _converter.getDoubleValue( _maxSurchargeLTF.getTextFieldText() ) ); - reservoir.setElev( _converter.getDoubleValue( _reservoirLTF.getTextFieldText() ) ); - reservoir.setGates( _converter.getIntValue( _gatesLTF.getTextFieldText() ) ); - reservoir.setImpounded( _converter.getLongDateValue( _impoundDateLTF.getTextFieldText() ) ); - - if ( _floodControlCB.isSelected() ) - { - usesStringBuffer.append( "F" ); - } - - if ( _hydroCB.isSelected() ) - { - usesStringBuffer.append( "H" ); - } - - if ( _lowFlowCB.isSelected() ) - { - usesStringBuffer.append( "L" ); - } - - if ( _navigationCB.isSelected() ) - { - usesStringBuffer.append( "N" ); - } - - if ( _recreationCB.isSelected() ) - { - usesStringBuffer.append( "R" ); - } - - if ( _waterSupplyCB.isSelected() ) - { - usesStringBuffer.append( "W" ); - } - - reservoir.setUses( usesStringBuffer.toString() ); - - return reservoir; - } - - private void deleteReservoir() - { - RaxReservoir raxReservoir = (RaxReservoir) _selectionStringToRaxReservoirMap.get( _beginDateLTF.getTextFieldText() ); - - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxReservoir.keyString(), "Delete Reservoir Entry" ) ) - { - _dataMgr.deleteRaxReservoirFromDatabase( raxReservoir ); - raxReservoir = new RaxReservoir(); - populateDataFields( raxReservoir ); -// clearDataInputPanel(); - updateRaxReservoirList(); - updateSelectionComboBox(); - } - } - - private void saveReservoir() - { - if ( _converter.getLongDateValue( _beginDateLTF.getTextFieldText() ) != DbTable.getNullDouble() ) - { - RaxReservoir reservoir = getRaxReservoirToSave(); - RaxReservoir extractedReservoir = (RaxReservoir) _selectionStringToRaxReservoirMap.get( _beginDateLTF.getTextFieldText() ); - boolean startDateChanged = true; - - long endDate = _converter.getLongDateValue( _endDateLTF.getTextFieldText() ); - - if ( reservoir.getBeginDate() == _beginDate ) - { - startDateChanged = false; - } - - boolean recordExists = _dataMgr.doesRaxReservoirExist( reservoir ); - - if ( recordExists ) // record exists in database (lid/sbd) - { - if ( endDate != DbTable.getNullDouble() ) // end date is specified - { - if ( startDateChanged ) // Start date has been changed since the gui popped up - { - if ( DialogHelper.displayConfirmDialog( this, "A record already exists for " + reservoir + "\n Are you sure you want to save", "Save RaxReservoir" ) ); - { - _dataMgr.saveReservoir( reservoir ); //User confirms that they want to overwrite the changes - } - } - else // Start date has not been changed - { - _dataMgr.saveReservoir( reservoir ); - } - } - else // End date is not specified - { - boolean newerRecordExists = _dataMgr.doesNewerRaxReservoirExist( reservoir ); - - if ( startDateChanged ) - { - if ( newerRecordExists ) - { - DialogHelper.displayErrorDialog( this, "A record with a newer Sbd and null Sed exists", "Save RaxReservoir" ); - } - else // Newer record does not exist - { - if ( DialogHelper.displayConfirmDialog( this, "A record with a newer Sbd and null Sed exists", "Save RaxReservoir" ) ); - { - _dataMgr.saveReservoir( reservoir ); //User confirms that they want to overwrite the changes - } - } - } - else // Start date has not been changed - { - if ( newerRecordExists ) - { - if ( DialogHelper.displayConfirmDialog( this, "A record with a newer Sbd and null Sed exists", "Save RaxReservoir" ) ); - { - _dataMgr.saveReservoir( reservoir ); //User confirms that they want to overwrite the changes - } - } - else // Newer record does not exist - { - _dataMgr.saveReservoir( reservoir ); - } - } - } - } - else // Record does not exist - { - boolean newerRecordExists = _dataMgr.doesNewerRaxReservoirExist( reservoir ); - - if ( endDate != DbTable.getNullDouble() ) // end date is specified - { - _dataMgr.saveReservoir( reservoir ); - } - else // end date is not specified - { - if ( newerRecordExists ) - { - DialogHelper.displayErrorDialog( this, "A record with a newer Sbd and null Sed exists", "Save RaxReservoir" ); - } - else - { - _dataMgr.saveReservoir( reservoir ); - _dataMgr.setEndDateForLidInReservoir( reservoir ); - } - } - } - } - - updateRaxReservoirList(); - updateSelectionComboBox(); - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - DateFieldMouseListener beginDateMouseListener = new DateFieldMouseListener( 0 ); - DateFieldMouseListener endDateMouseListener = new DateFieldMouseListener( 1 ); - DateFieldMouseListener impoundDateMouseListener = new DateFieldMouseListener( 2 ); - - _selectionLCB.addComboBoxActionListener( new ItemSelectionListener() ); - _closeButton.addActionListener( windowCloser ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _beginDateLTF.addTextFieldMouseListener( beginDateMouseListener ); - _endDateLTF.addTextFieldMouseListener( endDateMouseListener ); - _impoundDateLTF.addTextFieldMouseListener( impoundDateMouseListener ); - addWindowListener( windowCloser ); - } - - private class DateFieldMouseListener implements MouseListener - { - private int __clickedDateField = -9999; - - public DateFieldMouseListener( int clickedDateField ) - { - __clickedDateField = clickedDateField; - } - public void mouseClicked( MouseEvent e ){} - public void mouseEntered( MouseEvent e ){} - public void mouseReleased( MouseEvent e ){} - public void mouseExited( MouseEvent e ){} - public void mousePressed( MouseEvent e ) - { - launchDateWindow( __clickedDateField ); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveReservoir(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteReservoir(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - private class ItemSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e) - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - RaxReservoir raxReservoir = (RaxReservoir) _selectionStringToRaxReservoirMap.get( selectedItem ); - - if ( raxReservoir != null ) - { - populateDataFields( raxReservoir ); - } - } - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - - String title = "MLDN1"; - String name = dataMgr.getRaxLocation( "MLDN1" ).getName(); - - if ( name != null ) - { - title += " - " + name; - } - - - ReservoirEditor reservoirEditorGUI = new ReservoirEditor( frame, dataMgr, "MLDN1", title ); - reservoirEditorGUI.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RfcEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RfcEditor.java deleted file mode 100644 index 096c92e414..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RfcEditor.java +++ /dev/null @@ -1,284 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Rfc; -import ohd.hseb.raxbase.table.ArcBaseRfcJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RfcEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _rfcTableManager = null; - private List _rfcColumnDescriptorList = null; - private List _rfcRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _rfcSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _rfcLTF = new LabeledTextField( "RFC:", "", "First 2 characters of the RFC acronym (upper case) (eg, MB for MBRFC)", 3 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _rfcRowDataToRfcMap = null; - - public RfcEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "Rfc Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 240, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initRfcSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initRfcSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _rfcSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected Rfc" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _rfcLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _rfcRowDataToRfcMap = _dataMgr.getRfcRowDataToRfcMap(); - } - - private void initJTable() - { - _rfcRowDataList = _dataMgr.getRfcRowDataList(); - setCEColumnDescriptorList(); - _rfcTableManager = new ComplexJTableManager( _rfcColumnDescriptorList, _rfcRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _rfcTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _rfcTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _rfcTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 90, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _rfcSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _rfcRowDataList = _dataMgr.getRfcRowDataList(); - _rfcTableManager.setChangedAllRowDataList( _rfcRowDataList ); - _rfcTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _rfcColumnDescriptorList = new ArrayList(); - - _rfcColumnDescriptorList.add(new JTableColumnDescriptor( "RFC", true, 70, "center" ) ); - } - - private void populateDataInputPanel( Rfc rfc ) - { - if ( rfc != null ) - { - _rfcLTF.setTextField( rfc.getRfc() ); - } - } - - private void clearDataInputPanel() - { - _rfcLTF.setTextField( "" ); - } - - private boolean saveRfc() - { - boolean saved = false; - - Rfc rfc = new Rfc(); - - rfc.setRfc( _rfcLTF.getTextFieldText() ); - - saved = _dataMgr.saveRfc( rfc ); - - updateJTable(); - - return saved; - } - - private void deleteRfc() - { - Rfc rfc = null; - List selectedRowsData = _rfcTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseRfcJTableRowData rowData = (ArcBaseRfcJTableRowData) selectedRowsData.get( 0 ); - rfc = (Rfc) _rfcRowDataToRfcMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + rfc.keyString(), "Delete Rfc" ) ) - { - _dataMgr.deleteRfcFromDataBase( rfc ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a Rfc", "Delete Rfc" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _rfcTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveRfc(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveRfc() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteRfc(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - Rfc rfc = null; - - ArcBaseRfcJTableRowData rowData = (ArcBaseRfcJTableRowData) _rfcTableManager.getSelectedRowsData().get( 0 ); - rfc = (Rfc) _rfcRowDataToRfcMap.get( rowData ); - populateDataInputPanel( rfc ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - RfcEditor rfcEditor = new RfcEditor( frame, dataMgr ); - rfcEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RiverCritEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RiverCritEditor.java deleted file mode 100644 index 6bd9e9cafb..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/RiverCritEditor.java +++ /dev/null @@ -1,746 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextArea; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxRiverCrit; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; - -public class RiverCritEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - - private int _clickedDateField = -9999; - - private JPanel _floodCatPanel = new JPanel( new GridBagLayout() ); - private JPanel _procQCPanel = new JPanel( new GridBagLayout() ); - private JPanel _miscPanel = new JPanel( new GridBagLayout() ); - private JPanel _remarkPanel = new JPanel( new GridBagLayout() ); - private String _lid = null; - private JComboBox _riverCritSelectionCB = new JComboBox(); - private List _raxRiverCritList = null; - private Map _raxRiverCritToRiverCritSelectionCBMap = new HashMap(); - - private StringDataConverter _converter = new StringDataConverter(); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private LabeledTextField _lidLTF = new LabeledTextField( "Lid:", "", "Location ID", 8 ); - private LabeledTextField _peLTF = new LabeledTextField( "PE:", "", "Physical Element", 4 ); - private LabeledTextField _validTimeLTF = new LabeledTextField( "Vdtime:", "", "Valid Time", 12 ); - private LabeledTextField _lowScreenLTF = new LabeledTextField( "LowScreen:", "", "Lower Screen Stage (ft):", 10 ); - private LabeledTextField _sigRateLTF = new LabeledTextField( "SigRate:", "", "Signifant Rise", 10 ); - private LabeledTextField _screenRateLTF = new LabeledTextField( "ScreenRate:", "", "Maximum Rise (rate of change) allowed for stage (ft)", 10 ); - private LabeledTextField _fisLTF = new LabeledTextField( "Fis:", "", "Forecast issuance stage (ft)", 10 ); - private LabeledTextField _actionLTF = new LabeledTextField( "Action:", "", "Action Stage (ft)", 10 ); - private LabeledTextField _alertLTF = new LabeledTextField( "Alert:", "", "Alert Stage (ft)", 10 ); - private LabeledTextField _bankLTF = new LabeledTextField( "Bank:", "", "Bankful Stage (ft)", 10 ); - private LabeledTextField _minorFloodStageLTF = new LabeledTextField( "Flood:", "", "Flood Stage (ft)", 10 ); - private LabeledTextField _moderateFloodStageLTF = new LabeledTextField( "ModFlood:", "", "Moderate Floodcat Stage (ft)", 10 ); - private LabeledTextField _majorFloodStageLTF = new LabeledTextField( "MajFlood:", "", "Major Floodcat Stage (ft)", 10 ); - private LabeledTextField _recordLTF = new LabeledTextField( "Record:", "", "Stage of Record (ft)", 10 ); - private LabeledTextField _highScreenLTF = new LabeledTextField( "HighScreen:", "", "Upper Limit Screen Stage (ft)", 10 ); - private LabeledTextField _damScreenLTF = new LabeledTextField( "DamScreen:", "", "Maximum Stage during Dam Break", 10 ); - private LabeledTextField _lowScreenFLTF = new LabeledTextField( "LowScreenF:", "", "Lower Screen Flow (cfs)", 10 ); - private LabeledTextField _sigRateFLTF = new LabeledTextField( "SigRateF:", "", "Significant Rise (rate of change) value for flow (cfs)", 10 ); - private LabeledTextField _screenRateFLTF = new LabeledTextField( "ScreenRateF:", "", "Maximum Rise (rate of change) allowed for flow (cfs)", 10 ); - private LabeledTextField _fisFLTF = new LabeledTextField( "FisF:", "", "Flow at forecast issuance stage (cfs)", 10 ); - private LabeledTextField _actionFLTF = new LabeledTextField( "ActionF:", "", "Flow at Action Stage (cfs)", 10 ); - private LabeledTextField _alertFLTF = new LabeledTextField( "AlertF:", "", "Flow for Alert Stage (cfs)", 10 ); - private LabeledTextField _bankFLTF = new LabeledTextField( "BankF:", "", "Flow at bankful Stage (cfs)", 10 ); - private LabeledTextField _minorFloodFlowLTF = new LabeledTextField( "FloodF:", "", "Flow at Flood Stage (cfs)", 10 ); - private LabeledTextField _moderateFloodFlowLTF = new LabeledTextField( "ModFloodF:", "", "Flow of Moderate floodcat stage (cfs)", 10 ); - private LabeledTextField _majorFloodFlowLTF = new LabeledTextField( "MajFloodF:", "", "Flow of Major floodcat stage (cfs)", 10 ); - private LabeledTextField _recordFLTF = new LabeledTextField( "RecordF:", "", "Flow of Record (cfs)", 10 ); - private LabeledTextField _highScreenFLTF = new LabeledTextField( "HighScreenF:", "", "Upper Limit Screen Flow (cfs)", 10 ); - private LabeledTextField _damScreenFLTF = new LabeledTextField( "DamScreenF:", "", "Maximum Flow during Dam Break", 10 ); - private LabeledTextField _sigRateTLTF = new LabeledTextField( "SigRateT:", "", "Time interval for sigrate/sgratef (hours or fractional hours)", 10 ); - private LabeledTextField _screenRateTLTF = new LabeledTextField( "ScreenRateT:", "", "Time interval for screenrate/screenratef (hours or fractional hours)", 10 ); - private LabeledTextField _lowScreenQLTF = new LabeledTextField( "LowScreenQ:", "", "Source of lowscreen/lowscreenf:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _sigRateQLTF = new LabeledTextField( "SigRateQ:", "", "Source for sigrate/sigratf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _screenRateQLTF = new LabeledTextField( "ScreenRateQ:", "", "Source for screenrate/screenratef:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _fisQLTF = new LabeledTextField( "FisQ:", "", "Source of fis/fisf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _actionQLTF = new LabeledTextField( "ActionQ:", "", "Source of action/actionf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _alertQLTF = new LabeledTextField( "AlertQ", "", "Source of alert/alertf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _bankQLTF = new LabeledTextField( "BankQ:", "", "Source of bank/bankf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _floodQLTF = new LabeledTextField( "FloodQ:", "", "Source of flood/floodf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _modFloodQLTF = new LabeledTextField( "ModFloodQ:", "", "Source of modflood/modfloodq:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _majFloodQLTF = new LabeledTextField( "MajFloodQ:", "", "Source of majflood/majfloodf:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _recordQLTF = new LabeledTextField( "RecordQ:", "", "Source of record/recordf, valid values:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _highScreenQLTF = new LabeledTextField( "HighScreenQ:", "", "Source of highscreen/highscreenf:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _damScreenQLTF = new LabeledTextField( "DamScreenQ:", "", "Source of damscreen/damscreenf:
    E=e-19
    M=memo" + - "
    P=personal communication (i.e. phone)
    I=internal (i.e. RFC determined)" + - "
    U=unknown", 10 ); - private LabeledTextField _streamLTF = new LabeledTextField( "Stream:", "", "Same of river/stream (mixed case)", 10 ); - private LabeledTextField _latitudeLTF = new LabeledTextField( "Latitude:", "", "Latitude (degrees decimal)", 10 ); - private LabeledTextField _longitudeLTF = new LabeledTextField( "Longitude:", "", "Longitude (degrees decimal)", 10 ); - private LabeledTextField _daLTF = new LabeledTextField( "Da:", "", "Drainage area (square miles)", 10 ); - private LabeledTextField _mileLTF = new LabeledTextField( "Mile:", "", "River Mile", 10 ); - private LabeledTextField _zdLTF = new LabeledTextField( "Zd:", "", "Elevation of the gage zero (i.e. when the gage reads zero) (ft MSL) (usually reported to the nearest 0.01 ft)", 10 ); - private LabeledTextField _vdatumLTF = new LabeledTextField( "VDatum:", "", "Reference value on which the gage zero (zd) is based. This generally is the National " + - "Geodetic Vertical Datum of 1929 (NGVD 1929) or the North American Vertical Datum of 1988 " + - "(NAVD 88). Not all locations use these datums (for example, river gages on the Ohio River " + - "use NGVD 1913, also referred to as the Ohio River Datum).", 10 ); - private LabeledTextField _cbLTF = new LabeledTextField( "Cb:", "", "Gage is set for gage calibration purposes at a river station (ft)", 10 ); - private LabeledTextField _levelLTF = new LabeledTextField( "Level:", "", "", 10 ); - private LabeledTextField _poolLTF = new LabeledTextField( "Pool:", "", "Normal pool elevation (ft MSL) at a river station (desired elevation for water supply purposes, " + - "is really the same as conserpool in the Reservoir table)", 10 ); - private LabeledTextField _porLTF = new LabeledTextField( "Por:", "", "Period of Record", 10 ); - private LabeledTextField _tideLTF = new LabeledTextField( "Tide:", "", "Indicator of tidal effects applicable to a river station, valid values: NONE, MINOR, MODERATE, MAJOR", 10 ); - private LabeledTextField _backwaterLTF = new LabeledTextField( "BackWater:", "", "Indicator of any backwater effects at a river gage site, valid values: NONE, MINOR, MODERATE, MAJOR", 10 ); - private LabeledTextField _rreviseLTF = new LabeledTextField( "RRevise:", "", "The date when E-19 data was last updated for a river station", 10 ); - private LabeledTextField _rsourceLTF = new LabeledTextField( "RSource:", "", "", 10 ); - private LabeledTextField _responseTimeLTF = new LabeledTextField( "ResponseTime:", "", "Typical or average response time (hours) for flooding to occur at this river station from " + - "a precipitation event", 10 ); - private LabeledTextField _thresholdRunoffLTF = new LabeledTextField( "ThresholdRunOff:", "", "Threshold runoff value (inches) for a site (used by the Site-Specific Model)", 10 ); - private LabeledTextField _uhgDurLTF = new LabeledTextField( "uhgDur:", "", "Unit hydrograph duration (hours)", 10 ); - - private JLabel _remarkLabel = new JLabel( "Remark:" ); - private JTextArea _remarkTextArea = new JTextArea( 3, 80 ); - - public RiverCritEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "RiverCrit Editor - " + title, true ); - _dataMgr = dataMgr; - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1024, 768 ) ); - populateFields(); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - setupRiverCritSelectionComboBox(); - initDataPanel(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - populateFields(); - pack(); - setVisible( true ); - } - - private void setupRiverCritSelectionComboBox() - { - _raxRiverCritList = _dataMgr.setupAndGetRaxRiverCritList( _lid ); - RaxRiverCrit raxRiverCrit = null; - - if ( _raxRiverCritList.isEmpty() ) - { - _riverCritSelectionCB.addItem( "No entries found in the database" ); - } - else - { - for ( int i = 0; i < _raxRiverCritList.size(); i++ ) - { - raxRiverCrit = (RaxRiverCrit) _raxRiverCritList.get( i ); - - _riverCritSelectionCB.addItem( getLidPEVdateComboBoxString( raxRiverCrit ) ); - _raxRiverCritToRiverCritSelectionCBMap.put( raxRiverCrit, getLidPEVdateComboBoxString( raxRiverCrit ) ); - _raxRiverCritToRiverCritSelectionCBMap.put( getLidPEVdateComboBoxString( raxRiverCrit ), raxRiverCrit ); - } - } - } - - private String getLidPEVdateComboBoxString( RaxRiverCrit raxRiverCrit ) - { - return ( "LID: " + raxRiverCrit.getLid() + " - PE: " + raxRiverCrit.getPe() + " - VDTIME: " + DbTimeHelper.getDateStringFromLongTime( raxRiverCrit.getValidTime() ) ); - } - - private RaxRiverCrit getRaxRiverCritFromLidPEVdateComboBoxString( String lidPeVdateString ) - { - return (RaxRiverCrit) _raxRiverCritToRiverCritSelectionCBMap.get( lidPeVdateString ); - } - - private void initDataPanel() - { - initGUIItems(); - initFloodCatPanel(); - initProcQCPanel(); - initMiscPanel(); - initRemarkPanel(); - } - - private void initGUIItems() - { - _floodCatPanel.setBorder( BorderFactory.createTitledBorder( "Flood Category Data" ) ); - _procQCPanel.setBorder( BorderFactory.createTitledBorder( "Processors Quality Control" ) ); - _miscPanel.setBorder( BorderFactory.createTitledBorder( "Misc Data" ) ); - _hDateChooser.addOwner( this ); - } - - private void initFloodCatPanel() - { - _lidLTF.setEditTextField( false ); - _validTimeLTF.setEditTextField( false ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _floodCatPanel, _lidLTF, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _peLTF, 0, 1, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _validTimeLTF, 0, 2, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _fisLTF, 0, 3, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _fisFLTF, 0, 4, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _fisQLTF, 0, 5, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _actionLTF, 0, 6, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _actionFLTF, 0, 7, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _actionQLTF, 0, 8, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _alertLTF, 0, 9, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _alertFLTF, 0, 10, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _alertQLTF, 0, 11, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _bankLTF, 0, 12, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _bankFLTF, 0, 13, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _bankQLTF, 0, 14, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _minorFloodStageLTF, 0, 15, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _minorFloodFlowLTF, 0, 16, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _floodQLTF, 0, 17, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _floodCatPanel, _moderateFloodStageLTF, 0, 18, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _moderateFloodFlowLTF, 0, 19, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _modFloodQLTF, 0, 20, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _floodCatPanel, _majorFloodStageLTF, 0, 21, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _majorFloodFlowLTF, 0, 22, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _majFloodQLTF, 0, 23, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _floodCatPanel, _recordLTF, 0, 24, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _recordFLTF, 0, 25, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _floodCatPanel, _recordQLTF, 0, 26, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - } - - private void initProcQCPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _procQCPanel, _lowScreenLTF, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _lowScreenFLTF, 0, 1, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _lowScreenQLTF, 0, 2, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _procQCPanel, _highScreenLTF, 0, 3, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _highScreenFLTF, 0, 4, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _highScreenQLTF, 0, 5, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _procQCPanel, _damScreenLTF, 0, 6, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _damScreenFLTF, 0, 7, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _damScreenQLTF, 0, 8, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _procQCPanel, _sigRateLTF, 0, 9, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _sigRateFLTF, 0, 10, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _sigRateQLTF, 0, 11, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _sigRateTLTF, 0, 12, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - - ComponentHelper.addFrameComponent( _procQCPanel, _screenRateLTF, 0, 13, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _screenRateFLTF, 0, 14, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _screenRateQLTF, 0, 15, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _procQCPanel, _screenRateTLTF, 0, 16, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - } - - private void initMiscPanel() - { - _rreviseLTF.setEditTextField( false ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _miscPanel, _streamLTF, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _latitudeLTF, 0, 1, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _longitudeLTF, 0, 2, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _daLTF, 0, 3, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _mileLTF, 0, 4, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _zdLTF, 0, 5, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _vdatumLTF, 0, 6, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _cbLTF, 0, 7, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _levelLTF, 0, 8, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _poolLTF, 0, 9, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _porLTF, 0, 10, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _tideLTF, 0, 11, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _backwaterLTF, 0, 12, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _rreviseLTF, 0, 13, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _rsourceLTF, 0, 14, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _responseTimeLTF, 0, 15, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _thresholdRunoffLTF, 0, 16, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _miscPanel, _uhgDurLTF, 0, 17, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - } - - private void initRemarkPanel() - { - _remarkLabel.setToolTipText( "Stores any type of documentation or commentary in a free text format" ); - ComponentHelper.addFrameComponent( _remarkPanel, _remarkLabel, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - ComponentHelper.addFrameComponent( _remarkPanel, _remarkTextArea, 0, 1, 3, 3, 1, 1, GridBagConstraints.BOTH ); - -// ComponentHelper.addFrameComponent( _remarkPanel, _remarkLTF, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL ); - } - - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 3, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _riverCritSelectionCB, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _floodCatPanel, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _procQCPanel, 1, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _miscPanel, 2, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _remarkPanel, 0, 2, 3, 4, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 6, 3, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void deleteRiverCrit() - { - String riverCritSelectionCBString = (String) _riverCritSelectionCB.getSelectedItem(); - RaxRiverCrit raxRiverCrit = getRaxRiverCritFromLidPEVdateComboBoxString( riverCritSelectionCBString ); - - - if ( raxRiverCrit != null ) - { - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + raxRiverCrit.keyString(), "Delete River Crit" ) ) - { - _dataMgr.deleteRaxRiverCrit( raxRiverCrit ); - _riverCritSelectionCB.removeAllItems(); - setupRiverCritSelectionComboBox(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a crest", "Delete River Crit" ); - } - } - - private boolean saveRiverCrit() - { - RaxRiverCrit raxRiverCrit = new RaxRiverCrit(); - boolean saved = false; - - raxRiverCrit.setLid( _lidLTF.getTextFieldText() ); - raxRiverCrit.setPe( _peLTF.getTextFieldText() ); - raxRiverCrit.setValidTime( _converter.getLongDateValue( _validTimeLTF.getTextFieldText() ) ); - raxRiverCrit.setFis( _converter.getDoubleValue( _fisLTF.getTextFieldText() ) ); - raxRiverCrit.setFisF( _converter.getDoubleValue( _fisFLTF.getTextFieldText() ) ); - raxRiverCrit.setFisQ( _fisQLTF.getTextFieldText()); - raxRiverCrit.setAction( _converter.getDoubleValue( _actionLTF.getTextFieldText() ) ); - raxRiverCrit.setActionF( _converter.getDoubleValue( _actionFLTF.getTextFieldText() ) ); - raxRiverCrit.setActionQ( _actionQLTF.getTextFieldText() ); - raxRiverCrit.setAlert( _converter.getDoubleValue( _alertLTF.getTextFieldText() ) ); - raxRiverCrit.setAlertF( _converter.getDoubleValue( _alertFLTF.getTextFieldText() ) ); - raxRiverCrit.setAlertQ( _alertQLTF.getTextFieldText() ); - raxRiverCrit.setBank( _converter.getDoubleValue( _bankLTF.getTextFieldText() ) ); - raxRiverCrit.setBankF( _converter.getDoubleValue( _bankFLTF.getTextFieldText() ) ); - raxRiverCrit.setBankQ( _bankQLTF.getTextFieldText() ); - raxRiverCrit.setMinorFloodStage( _converter.getDoubleValue( _minorFloodStageLTF.getTextFieldText() ) ); - raxRiverCrit.setMinorFloodFlow( _converter.getDoubleValue( _minorFloodFlowLTF.getTextFieldText() ) ); - raxRiverCrit.setFloodQ( _floodQLTF.getTextFieldText() ); - raxRiverCrit.setModerateFloodStage( _converter.getDoubleValue( _moderateFloodStageLTF.getTextFieldText() ) ); - raxRiverCrit.setModerateFloodFlow( _converter.getDoubleValue( _moderateFloodFlowLTF.getTextFieldText() ) ); - raxRiverCrit.setModFloodQ( _modFloodQLTF.getTextFieldText() ); - raxRiverCrit.setMajorFloodStage( _converter.getDoubleValue( _majorFloodStageLTF.getTextFieldText() ) ); - raxRiverCrit.setMajorFloodFlow( _converter.getDoubleValue( _majorFloodFlowLTF.getTextFieldText() ) ); - raxRiverCrit.setMajFloodQ( _majFloodQLTF.getTextFieldText() ); - raxRiverCrit.setRecord( _converter.getDoubleValue( _recordLTF.getTextFieldText() ) ); - raxRiverCrit.setRecordF( _converter.getDoubleValue( _recordFLTF.getTextFieldText() ) ); - raxRiverCrit.setRecordQ( _recordQLTF.getTextFieldText() ); - - raxRiverCrit.setLowScreen( _converter.getDoubleValue( _lowScreenLTF.getTextFieldText() ) ); - raxRiverCrit.setLowScreenF( _converter.getDoubleValue( _lowScreenFLTF.getTextFieldText() ) ); - raxRiverCrit.setLowScreenQ( _lowScreenQLTF.getTextFieldText() ); - raxRiverCrit.setHighScreen( _converter.getDoubleValue( _highScreenLTF.getTextFieldText() ) ); - raxRiverCrit.setHighScreenF( _converter.getDoubleValue( _highScreenFLTF.getTextFieldText() ) ); - raxRiverCrit.setHighScreenQ( _highScreenQLTF.getTextFieldText() ); - raxRiverCrit.setDamScreen( _converter.getDoubleValue( _damScreenLTF.getTextFieldText() ) ); - raxRiverCrit.setDamScreenF( _converter.getDoubleValue( _damScreenFLTF.getTextFieldText() ) ); - raxRiverCrit.setDamScreenQ( _damScreenQLTF.getTextFieldText() ); - raxRiverCrit.setSigRate( _converter.getDoubleValue( _sigRateLTF.getTextFieldText() ) ); - raxRiverCrit.setSigRateF( _converter.getDoubleValue( _sigRateFLTF.getTextFieldText() ) ); - raxRiverCrit.setSigRateQ( _sigRateQLTF.getTextFieldText() ); - raxRiverCrit.setSigRateT( _converter.getDoubleValue( _sigRateTLTF.getTextFieldText() ) ); - raxRiverCrit.setScreenRate( _converter.getDoubleValue( _screenRateLTF.getTextFieldText() ) ); - raxRiverCrit.setScreenRateF( _converter.getDoubleValue( _screenRateFLTF.getTextFieldText() ) ); - raxRiverCrit.setScreenRateQ( _screenRateQLTF.getTextFieldText() ); - raxRiverCrit.setScreenRateT( _converter.getDoubleValue( _screenRateTLTF.getTextFieldText() ) ); - - raxRiverCrit.setStream( _streamLTF.getTextFieldText() ); - raxRiverCrit.setLatitude( _converter.getDoubleValue( _latitudeLTF.getTextFieldText() ) ); - raxRiverCrit.setLongitude( _converter.getDoubleValue( _longitudeLTF.getTextFieldText() ) ); - raxRiverCrit.setDa( _converter.getDoubleValue( _daLTF.getTextFieldText() ) ); - raxRiverCrit.setMile( _converter.getDoubleValue( _mileLTF.getTextFieldText() ) ); - raxRiverCrit.setZd( _converter.getDoubleValue( _zdLTF.getTextFieldText() ) ); - raxRiverCrit.setVdatum( _vdatumLTF.getTextFieldText() ); - raxRiverCrit.setCb( _converter.getDoubleValue( _cbLTF.getTextFieldText() ) ); - raxRiverCrit.setLevel( _levelLTF.getTextFieldText() ); - raxRiverCrit.setPool( _converter.getDoubleValue( _poolLTF.getTextFieldText() ) ); - raxRiverCrit.setPor( _porLTF.getTextFieldText() ); - raxRiverCrit.setTide( _tideLTF.getTextFieldText() ); - raxRiverCrit.setBackwater( _backwaterLTF.getTextFieldText() ); - - raxRiverCrit.setRrevise( _converter.getLongDateValue( _rreviseLTF.getTextFieldText() ) ); - raxRiverCrit.setRsource( _rsourceLTF.getTextFieldText() ); - raxRiverCrit.setResponseTime( _converter.getDoubleValue( _responseTimeLTF.getTextFieldText() ) ); - raxRiverCrit.setThresholdRunoff( _converter.getDoubleValue( _thresholdRunoffLTF.getTextFieldText() ) ); - raxRiverCrit.setUhgdur( _converter.getIntValue( _uhgDurLTF.getTextFieldText() ) ); - raxRiverCrit.setRemark( _remarkTextArea.getText() ); - - saved = _dataMgr.saveRaxRiverCrit( raxRiverCrit ); - - _riverCritSelectionCB.removeAllItems(); - setupRiverCritSelectionComboBox(); - - return saved; - } - - private void populateFields() - { - _lidLTF.setTextField( _lid ); - - String riverCritSelectionCBString = (String) _riverCritSelectionCB.getSelectedItem(); - RaxRiverCrit raxRiverCrit = getRaxRiverCritFromLidPEVdateComboBoxString( riverCritSelectionCBString ); - if ( raxRiverCrit != null ) - { - _peLTF.setTextField( raxRiverCrit.getPe() ); - setDateFields( _validTimeLTF, raxRiverCrit.getValidTime() ); - setNumberFields( _fisLTF, raxRiverCrit.getFis() ); - setNumberFields( _fisFLTF, raxRiverCrit.getFisF() ); - _fisQLTF.setTextField( raxRiverCrit.getFisQ() ); - setNumberFields( _actionLTF, raxRiverCrit.getAction() ); - setNumberFields( _actionFLTF, raxRiverCrit.getActionF() ); - _actionQLTF.setTextField( raxRiverCrit.getActionQ() ); - setNumberFields( _alertLTF, raxRiverCrit.getAlert() ); - setNumberFields( _alertFLTF, raxRiverCrit.getAlertF() ); - _alertQLTF.setTextField( raxRiverCrit.getAlertQ() ); - setNumberFields( _bankLTF, raxRiverCrit.getBank() ); - setNumberFields( _bankFLTF, raxRiverCrit.getBankF() ); - _bankQLTF.setTextField( raxRiverCrit.getBankQ() ); - setNumberFields( _minorFloodStageLTF, raxRiverCrit.getMinorFloodStage() ); - setNumberFields( _minorFloodFlowLTF, raxRiverCrit.getMinorFloodFlow() ); - _floodQLTF.setTextField( raxRiverCrit.getFloodQ() ); - setNumberFields( _moderateFloodStageLTF, raxRiverCrit.getModerateFloodStage() ); - setNumberFields( _moderateFloodFlowLTF, raxRiverCrit.getModerateFloodFlow() ); - _modFloodQLTF.setTextField( raxRiverCrit.getModFloodQ() ); - setNumberFields( _majorFloodStageLTF, raxRiverCrit.getMajorFloodStage() ); - setNumberFields( _majorFloodFlowLTF, raxRiverCrit.getMajorFloodFlow() ); - _majFloodQLTF.setTextField( raxRiverCrit.getMajFloodQ() ); - setNumberFields( _recordLTF, raxRiverCrit.getRecord() ); - setNumberFields( _recordFLTF, raxRiverCrit.getRecordF() ); - _recordQLTF.setTextField( raxRiverCrit.getRecordQ() ); - - setNumberFields( _lowScreenLTF, raxRiverCrit.getLowScreen() ); - setNumberFields( _lowScreenFLTF, raxRiverCrit.getLowScreenF() ); - _lowScreenQLTF.setTextField( raxRiverCrit.getLowScreenQ() ); - setNumberFields( _highScreenLTF, raxRiverCrit.getHighScreen() ); - setNumberFields( _highScreenFLTF, raxRiverCrit.getHighScreenF() ); - _highScreenQLTF.setTextField( raxRiverCrit.getHighScreenQ() ); - setNumberFields( _damScreenLTF, raxRiverCrit.getDamScreen() ); - setNumberFields( _damScreenFLTF, raxRiverCrit.getDamScreenF() ); - _damScreenQLTF.setTextField( raxRiverCrit.getDamScreenQ() ); - setNumberFields( _sigRateLTF, raxRiverCrit.getSigRate() ); - setNumberFields( _sigRateFLTF, raxRiverCrit.getSigRateF() ); - _sigRateQLTF.setTextField( raxRiverCrit.getSigRateQ() ); - setNumberFields( _sigRateTLTF, raxRiverCrit.getSigRateT() ); - setNumberFields( _screenRateLTF, raxRiverCrit.getScreenRate() ); - setNumberFields( _screenRateFLTF, raxRiverCrit.getScreenRateF() ); - _screenRateQLTF.setTextField( raxRiverCrit.getScreenRateQ() ); - setNumberFields( _screenRateTLTF, raxRiverCrit.getScreenRateT() ); - - _streamLTF.setTextField( raxRiverCrit.getStream() ); - setNumberFields( _latitudeLTF, raxRiverCrit.getLatitude() ); - setNumberFields( _longitudeLTF, raxRiverCrit.getLongitude() ); - setNumberFields( _daLTF, raxRiverCrit.getDa() ); - setNumberFields( _mileLTF, raxRiverCrit.getMile() ); - setNumberFields( _zdLTF, raxRiverCrit.getZd() ); - _vdatumLTF.setTextField( raxRiverCrit.getVdatum() ); - setNumberFields( _cbLTF, raxRiverCrit.getCb() ); - _levelLTF.setTextField( raxRiverCrit.getLevel() ); - setNumberFields( _poolLTF, raxRiverCrit.getPool() ); - _porLTF.setTextField( raxRiverCrit.getPor() ); - _tideLTF.setTextField( raxRiverCrit.getTide() ); - _backwaterLTF.setTextField( raxRiverCrit.getBackwater() ); - setDateFields( _rreviseLTF, raxRiverCrit.getRrevise() ); - _rsourceLTF.setTextField( raxRiverCrit.getRsource() ); - setNumberFields( _responseTimeLTF, raxRiverCrit.getResponseTime() ); - setNumberFields( _thresholdRunoffLTF, raxRiverCrit.getThresholdRunoff() ); - setNumberFields( _uhgDurLTF, raxRiverCrit.getUhgdur() ); - _remarkTextArea.setText( raxRiverCrit.getRemark() ); - } - } - - private void launchDateWindow( int clickedDateField ) - { - _clickedDateField = clickedDateField; - - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = 0; - String dateString = null; - - switch ( _clickedDateField ) - { - case 0: dateString = _validTimeLTF.getTextFieldText(); break; - case 1: dateString = _rreviseLTF.getTextFieldText(); break; - } - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - dateLong = DbTimeHelper.getLongTimeFromDateString( dateString ) + dayInMillis; - } - else - { - dateLong = System.currentTimeMillis(); - } - - calendar.setTimeInMillis( dateLong ); - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - } - - public void dateChosen( JDialog jDialog ) - { - if ( _clickedDateField != -9999 ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - switch ( _clickedDateField ) - { - case 0: _validTimeLTF.setTextField( dateString ); break; - case 1: _rreviseLTF.setTextField( dateString ); break; - } - _clickedDateField = -9999; - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - DateFieldMouseListener vdatumMouseListener = new DateFieldMouseListener( 0 ); - DateFieldMouseListener rreviseMouseListener = new DateFieldMouseListener( 1 ); - - _riverCritSelectionCB.addActionListener( new RiverCritSelectionComboBoxListener() ); - _validTimeLTF.addTextFieldMouseListener( vdatumMouseListener ); - _rreviseLTF.addTextFieldMouseListener( rreviseMouseListener ); - - _closeButton.addActionListener( windowCloser ); - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - addWindowListener( windowCloser ); - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteRiverCrit(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveRiverCrit(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveRiverCrit() ) - { - closeWindow(); - } - } - } - - private class DateFieldMouseListener implements MouseListener - { - private int __clickedDateField = -9999; - - public DateFieldMouseListener( int clickedDateField ) - { - __clickedDateField = clickedDateField; - } - - public void mouseClicked( MouseEvent e ) - { - } - - public void mouseEntered( MouseEvent e ) - { - } - - public void mouseExited( MouseEvent e ) - { - } - - public void mousePressed( MouseEvent e ) - { - launchDateWindow( __clickedDateField ); - } - - public void mouseReleased( MouseEvent e ) - { - } - } - - private class RiverCritSelectionComboBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - populateFields(); - } - } - - private void setNumberFields( LabeledTextField LTF, double doubleValue ) - { - if ( DbTable.isNull( doubleValue ) ) - { - LTF.setTextField( "" ); - } - else - { - LTF.setTextField( Double.toString( doubleValue ) ); - } - } - - private void setNumberFields( LabeledTextField LTF, int intValue ) - { - if ( DbTable.isNull( intValue ) ) - { - LTF.setTextField( "" ); - } - else - { - LTF.setTextField( Integer.toString( intValue ) ); - } - } - - private void setDateFields( LabeledTextField LTF, long dateValue ) - { - if ( DbTable.isNull( dateValue ) ) - { - LTF.setTextField( "" ); - } - else - { - LTF.setTextFieldDate( dateValue ); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - String title = "LUDN8"; - String name = dataMgr.getRaxLocation( "LUDN8" ).getName(); - - if ( name != null ) - { - title += " - " + name; - } - - - RiverCritEditor riverCritEditorGUI = new RiverCritEditor( frame, dataMgr, "LUDN8", name ); - riverCritEditorGUI.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/SensOKEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/SensOKEditor.java deleted file mode 100644 index bae1923c2d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/SensOKEditor.java +++ /dev/null @@ -1,458 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.Sensok; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.model.ShefProb; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.raxbase.util.PEDTSEPManager; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; - -public class SensOKEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private List _sensokList = null; - - private Sensok _selectedSensok = null; - - private LabeledComboBox _selectionLCB = new LabeledComboBox(); - private Map _selectionStringToSensokMap = new HashMap(); - private String _lid = null; - private RaxBaseDataMgr _dataMgr = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( true ); - - private StringDataConverter _converter = new StringDataConverter(); - - private PEDTSEPManager _pedtsepManager = null; - - private JPanel _dataPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _lidLTF = new LabeledTextField( "LID:", "", "Location ID", 9 ); - private LabeledComboBox _peLCB = null; - private LabeledComboBox _durLCB = null; - private LabeledComboBox _tsLCB = null; - private LabeledComboBox _extremumLCB = null; - private LabeledComboBox _probLCB = null; - private LabeledTextField _oktimeLTF = new LabeledTextField( "OKTime:", "", "Date and time of change in status", 15 ); - private JCheckBox _okCheckBox = new JCheckBox( "OK:"); - private LabeledTextField _initLTF = new LabeledTextField( "Initials:", "", "Initials of person making the entry", 4 ); - private LabeledTextField _reasonLTF = new LabeledTextField( "Reason:", "", "Reason for change in status (optional)", 80 ); - private LabeledTextField _agcodeLTF = new LabeledTextField( "Agency:", "", "Abbreviation for agency", 7 ); - private LabeledTextField _aglocLTF = new LabeledTextField( "Agency Location:", "", "Location of agency", 4 ); - private LabeledTextField _commentLTF = new LabeledTextField( "Comment:", "", "Notification comment (optional)", 41 ); - - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete from Database" ); - - public SensOKEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "Sensok Editor - " + title, true ); - _dataMgr = dataMgr; - _pedtsepManager = new PEDTSEPManager( _dataMgr ); - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1024, 550 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - updateSensokList(); - - updateSelectionComboBox(); - initComboBoxes(); - initDataPanel(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - populateDataPanel( _selectedSensok ); - pack(); - setVisible( true ); - } - - private void initDataPanel() - { - _dataPanel.setBorder( BorderFactory.createTitledBorder( "Selected Entry" ) ); - _oktimeLTF.setEditTextField( false ); - _hDateChooser.addOwner( this ); - _lidLTF.setEditTextField( false ); - _lidLTF.setTextField( _lid ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataPanel, _lidLTF, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _peLCB, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _durLCB, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _tsLCB, 0, 3, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _extremumLCB, 0, 4, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _probLCB, 0, 5, 2, 1, 1, 1, GridBagConstraints.NONE ); - - ComponentHelper.addPanelComponent( _dataPanel, _oktimeLTF, 0, 6, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _okCheckBox, 0, 7, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _initLTF, 0, 8, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _reasonLTF, 0, 9, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _agcodeLTF, 0, 10, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _aglocLTF, 0, 11, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _commentLTF, 0, 12, 2, 1, 1, 1, GridBagConstraints.NONE ); - - _okCheckBox.setToolTipText( "Checked=Y, Unchecked=N" ); - } - - private void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _selectionLCB, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _dataPanel, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void populateDataPanel( Sensok sensok ) - { - if ( sensok != null ) - { - _lidLTF.setTextField( sensok.getLid() ); - - ShefPE shefPE = (ShefPE) _dataMgr.getShefPEMap().get( sensok.getPe() ); - _peLCB.setSelectedItem( _pedtsepManager.getShefPEComboBoxString( shefPE ) ); - - ShefDuration shefDur = (ShefDuration) _dataMgr.getShefDurationMap().get( sensok.getDur() ); - _durLCB.setSelectedItem( _pedtsepManager.getShefDurationComboBoxString( shefDur ) ); - - ShefTS shefTS = (ShefTS) _dataMgr.getShefTSMap().get( sensok.getTs() ); - _tsLCB.setSelectedItem( _pedtsepManager.getShefTSString( shefTS ) ); - - ShefExtremum shefEx = (ShefExtremum) _dataMgr.getShefExtremumMap().get( sensok.getExtremum() ); - _extremumLCB.setSelectedItem( _pedtsepManager.getShefExtremumComboBoxString( shefEx ) ); - - ShefProb shefProb = (ShefProb) _dataMgr.getShefProbMap().get( sensok.getP() ); - _probLCB.setSelectedItem( _pedtsepManager.getShefProbComboBoxString( shefProb ) ); - - _oktimeLTF.setTextField( _converter.getDateTimeStringFromDateTimeLong( sensok.getOktime() ) ); - - if ( sensok.getOk().equalsIgnoreCase( "Y" ) ) - { - _okCheckBox.setSelected( true ); - } - else - { - _okCheckBox.setSelected( false ); - } - _initLTF.setTextField( sensok.getInit() ); - _reasonLTF.setTextField( sensok.getReason() ); - _agcodeLTF.setTextField( sensok.getAgcode() ); - _aglocLTF.setTextField( sensok.getAgloc() ); - _commentLTF.setTextField( sensok.getComment() ); - } - } - - private void initComboBoxes() - { - _peLCB = _pedtsepManager.getPeLCB(); - _durLCB = _pedtsepManager.getDurLCB(); - _tsLCB = _pedtsepManager.getTsLCB(); - _extremumLCB = _pedtsepManager.getExtremumLCB(); - _probLCB = _pedtsepManager.getProbLCB(); - } - - - private void updateSelectionComboBox() - { - Sensok sensok = null; - List selectionComboBoxStringList = new ArrayList(); - String dateString = null; - - _selectionStringToSensokMap.clear(); - _selectionLCB.getComboBox().removeAllItems(); - - for ( int i = 0; i < _sensokList.size(); i++ ) - { - sensok = (Sensok) _sensokList.get( i ); - selectionComboBoxStringList.add( getSelectedSensokString( sensok ) ); - _selectionStringToSensokMap.put( getSelectedSensokString( sensok ), sensok ); - } - - if ( selectionComboBoxStringList.isEmpty() ) - { - selectionComboBoxStringList.add( "No entries found" ); - } - _selectionLCB.setComboBoxFromStringArray( selectionComboBoxStringList.toArray() ); - _selectionLCB.setLabel( "Select Sensok Entry:" ); - _selectionLCB.setLabelPreferredSize( new Dimension( 150, 15 ) ); - _selectionLCB.setComboBoxPreferredSize( new Dimension( 600, 15 ) ); - - String selectedItem = _selectionLCB.getSelectedCBItem(); - - _selectedSensok = (Sensok) _selectionStringToSensokMap.get( selectedItem ); - } - - private String getSelectedSensokString( Sensok sensok ) - { - return "LID = " + sensok.getLid() + " | PE = " + sensok.getPe() + " | Dur = " + sensok.getDur() + " | TS = " + - sensok.getTs() + " | Extremum = " + sensok.getExtremum() + " | P = " + sensok.getP() + " | OKTime = " + DbTimeHelper.getDateStringFromLongTime( sensok.getOktime() ); - } - - private void updateSensokList() - { - _sensokList = _dataMgr.getSensokList( _lid ); - } - - private void launchDateWindow() - { - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = System.currentTimeMillis(); - - if ( ! _oktimeLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - dateLong = _converter.getLongDateValue( _oktimeLTF.getTextFieldText() ) + dayInMillis; - } - - calendar.setTimeInMillis( dateLong ); - - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - } - - public void dateChosen( JDialog jdialog ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateTimeStringFromCalendar( calendar ); - } - _oktimeLTF.setTextField( dateString ); - } - - private boolean saveSensok() - { - boolean saved = false; - Sensok sensok = new Sensok(); - - String pe = (String) _peLCB.getSelectedItem(); - String ts = (String) _tsLCB.getSelectedItem(); - String extremum = (String) _extremumLCB.getSelectedItem(); - String duration = (String) _durLCB.getSelectedItem(); - String prob = (String) _probLCB.getSelectedItem(); - short iDuration = (Short) _pedtsepManager.getDurCBStringToIDurMap().get( duration ); - - - sensok.setLid( _lidLTF.getTextFieldText() ); - sensok.setPe( (String) _pedtsepManager.getPeCBStringToPeMap().get( pe ) ); - sensok.setDur( (String) _pedtsepManager.getDurCBStringToDurMap().get( duration ) ); - sensok.setIdur( iDuration ); - sensok.setTs( (String) _pedtsepManager.getTsCBStringToTSMap().get( ts ) ); - sensok.setExtremum( (String) _pedtsepManager.getExtremumCBStringToExtremumMap().get( extremum ) ); - sensok.setP( (String) _pedtsepManager.getProbCBStringToProbMap().get( prob ) ); - - sensok.setOktime( _converter.getLongDateTimeValue( _oktimeLTF.getTextFieldText() ) ); - if ( _okCheckBox.isSelected() ) - { - sensok.setOk( "Y" ); - } - else - { - sensok.setOk( "N" ); - } - sensok.setInit( _initLTF.getTextFieldText() ); - sensok.setReason( _reasonLTF.getTextFieldText() ); - sensok.setAgcode( _agcodeLTF.getTextFieldText() ); - sensok.setAgloc( _aglocLTF.getTextFieldText() ); - sensok.setComment( _commentLTF.getTextFieldText() ); - - saved = _dataMgr.saveSensok( sensok ); - updateSensokList(); - updateSelectionComboBox(); - - return saved; - } - - private void deleteSensok() - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - Sensok sensok = (Sensok) _selectionStringToSensokMap.get( selectedItem ); - - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + sensok.keyString(), "Delete Sensok" ) ) - { - boolean success = _dataMgr.deleteSensokFromDatabase( sensok ); - if ( ! success ) - { - DialogHelper.displayErrorDialog( this, "Unable to delete Sensok entry", "Delete Sensok Error" ); - } - updateSensokList(); - updateSelectionComboBox(); - } - - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _selectionLCB.addComboBoxActionListener( new ItemSelectionListener() ); - - _closeButton.addActionListener( windowCloser ); - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - - _oktimeLTF.addTextFieldMouseListener( new DateFieldMouseListener() ); - } - - private class DateFieldMouseListener implements MouseListener - { - public void mouseReleased( MouseEvent e ){} - public void mouseClicked( MouseEvent e ){} - public void mouseEntered( MouseEvent e ){} - public void mouseExited( MouseEvent e ){} - public void mousePressed( MouseEvent e ) - { - launchDateWindow(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteSensok(); - } - } - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveSensok(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveSensok() ) - { - closeWindow(); - } - else - { - DialogHelper.displayErrorDialog( SensOKEditor.this, "Unable to save the Sensok entry", "Error Saving Sensok" ); - } - } - } - - private class ItemSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e) - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - Sensok sensok = (Sensok) _selectionStringToSensokMap.get( selectedItem ); - - if ( sensok != null ) - { - populateDataPanel( sensok ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - String title = "ALEC2"; - String name = dataMgr.getRaxLocation( "ALEC2" ).getName(); - - if ( name != null ) - { - title += " - " + name; - } - - - SensOKEditor sensOKEditor = new SensOKEditor( frame, dataMgr, "ALEC2", title ); - sensOKEditor.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefDurationEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefDurationEditor.java deleted file mode 100644 index 22e02f2eeb..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefDurationEditor.java +++ /dev/null @@ -1,306 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.table.ArcBaseShefDurationJTableRowData; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefDurationEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefDurTableManager = null; - private List _shefDurColumnDescriptorList = null; - private List _shefDurRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefDurSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _durationLTF = new LabeledTextField( "Duration:", "", "SHEF Duration code", 2 ); - private LabeledTextField _iDurationLTF = new LabeledTextField( "IDuration:", "", "Numeric value of SHEF Duration code", 9 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefDurRowDataToShefDurMap = null; - - public ShefDurationEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefDuration Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 330, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefDurationSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefDurationSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefDurSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefDur" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _durationLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _iDurationLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefDurRowDataToShefDurMap = _dataMgr.getShefDurRowDataToShefDurMap(); - } - - private void initJTable() - { - _shefDurRowDataList = _dataMgr.getShefDurRowDataList(); - setCEColumnDescriptorList(); - _shefDurTableManager = new ComplexJTableManager( _shefDurColumnDescriptorList, _shefDurRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefDurTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefDurTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefDurTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefDurSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _shefDurRowDataList = _dataMgr.getShefDurRowDataList(); - _shefDurTableManager.setChangedAllRowDataList( _shefDurRowDataList ); - _shefDurTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefDurColumnDescriptorList = new ArrayList(); - - _shefDurColumnDescriptorList.add(new JTableColumnDescriptor( "Dur", true, 50, "center" ) ); - _shefDurColumnDescriptorList.add(new JTableColumnDescriptor( "IDur", true, 50, "center" ) ); - _shefDurColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 200, "center" ) ); - } - - private void populateDataInputPanel( ShefDuration shefDur ) - { - if ( shefDur != null ) - { - _durationLTF.setTextField( shefDur.getDuration() ); - _iDurationLTF.setTextField( shefDur.getIduration() ); - _nameLTF.setTextField( shefDur.getName() ); - } - } - - private void clearDataInputPanel() - { - _durationLTF.setTextField( "" ); - _iDurationLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - } - - private boolean saveShefDuration() - { - boolean saved = false; - StringDataConverter converter = new StringDataConverter(); - - if ( ! ( ( _iDurationLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || - ( _durationLTF.getTextFieldText().equalsIgnoreCase( "" ) ) ) ) - { - ShefDuration shefDur = new ShefDuration(); - - shefDur.setDuration( _durationLTF.getTextFieldText() ); - shefDur.setIduration( converter.getShortValue( _iDurationLTF.getTextFieldText() ) ); - shefDur.setName( _nameLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefDur( shefDur ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for IDuration/Duration", "Save Duration" ); - } - - return saved; - } - - private void deleteShefDuration() - { - ShefDuration shefDur = null; - List selectedRowsData = _shefDurTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefDurationJTableRowData rowData = (ArcBaseShefDurationJTableRowData) selectedRowsData.get( 0 ); - shefDur = (ShefDuration) _shefDurRowDataToShefDurMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefDur.keyString(), "Delete ShefDuration" ) ) - { - _dataMgr.deleteShefDurationFromDataBase( shefDur ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefDuration", "Delete ShefDuration" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefDurTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefDuration(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefDuration() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefDuration(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefDuration shefDuration = null; - - ArcBaseShefDurationJTableRowData rowData = (ArcBaseShefDurationJTableRowData) _shefDurTableManager.getSelectedRowsData().get( 0 ); - shefDuration = (ShefDuration) _shefDurRowDataToShefDurMap.get( rowData ); - populateDataInputPanel( shefDuration ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefDurationEditor shefDurationEditor = new ShefDurationEditor( frame, dataMgr ); - shefDurationEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefExtremumEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefExtremumEditor.java deleted file mode 100644 index 3d71049fbe..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefExtremumEditor.java +++ /dev/null @@ -1,300 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.table.ArcBaseShefExtremumJTableRowData; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefExtremumEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefExTableManager = null; - private List _shefExColumnDescriptorList = null; - private List _shefExRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefExSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _extremumLTF = new LabeledTextField( "Extremum:", "", "SHEF Extremum code of adjuster", 2 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefExRowDataToShefExMap = null; - - public ShefExtremumEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefExtremum Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 300, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefExtremumSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefExtremumSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefExSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefEx" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _extremumLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefExRowDataToShefExMap = _dataMgr.getShefExRowDataToShefExMap(); - } - - private void initJTable() - { - _shefExRowDataList = _dataMgr.getShefExRowDataList(); - setCEColumnDescriptorList(); - _shefExTableManager = new ComplexJTableManager( _shefExColumnDescriptorList, _shefExRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefExTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefExTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefExTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 330, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefExSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _dataMgr.initShefExtremumList(); - _shefExRowDataList = _dataMgr.getShefExRowDataList(); - _shefExTableManager.setChangedAllRowDataList( _shefExRowDataList ); - _shefExTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefExColumnDescriptorList = new ArrayList(); - - _shefExColumnDescriptorList.add(new JTableColumnDescriptor( "Extremum", true, 50, "center" ) ); - _shefExColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 200, "center" ) ); - } - - private void populateDataInputPanel( ShefExtremum shefEx ) - { - if ( shefEx != null ) - { - _extremumLTF.setTextField( shefEx.getExtremum() ); - _nameLTF.setTextField( shefEx.getName() ); - } - } - - private void clearDataInputPanel() - { - _extremumLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - } - - private boolean saveShefExtremum() - { - boolean saved = false; - StringDataConverter converter = new StringDataConverter(); - - if ( ! _extremumLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - ShefExtremum shefEx = new ShefExtremum(); - - shefEx.setExtremum( _extremumLTF.getTextFieldText() ); - shefEx.setName( _nameLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefEx( shefEx ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for Extremum", "Save Extremum" ); - } - - return saved; - } - - private void deleteShefExtremum() - { - ShefExtremum shefEx = null; - List selectedRowsData = _shefExTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefExtremumJTableRowData rowData = (ArcBaseShefExtremumJTableRowData) selectedRowsData.get( 0 ); - shefEx = (ShefExtremum) _shefExRowDataToShefExMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefEx.keyString(), "Delete ShefExtremum" ) ) - { - _dataMgr.deleteShefExtremumFromDataBase( shefEx ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefExtremum", "Delete ShefExtremum" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefExTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefExtremum(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefExtremum() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefExtremum(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefExtremum shefExtremum = null; - - ArcBaseShefExtremumJTableRowData rowData = (ArcBaseShefExtremumJTableRowData) _shefExTableManager.getSelectedRowsData().get( 0 ); - shefExtremum = (ShefExtremum) _shefExRowDataToShefExMap.get( rowData ); - populateDataInputPanel( shefExtremum ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefExtremumEditor shefExtremumEditor = new ShefExtremumEditor( frame, dataMgr ); - shefExtremumEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPE1Editor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPE1Editor.java deleted file mode 100644 index 3cf9c1cb35..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPE1Editor.java +++ /dev/null @@ -1,298 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefPE1; -import ohd.hseb.raxbase.table.ArcBaseShefPE1JTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefPE1Editor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefPe1TableManager = null; - private List _shefPe1ColumnDescriptorList = null; - private List _shefPe1RowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefPe1SelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _pe1LTF = new LabeledTextField( "PE1:", "", "SHEF PE code", 3 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefPe1RowDataToShefPe1Map = null; - - public ShefPE1Editor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefPE1 Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefPe1SelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefPe1SelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefPe1SelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefPE1" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _pe1LTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefPe1RowDataToShefPe1Map = _dataMgr.getShefPe1RowDataToShefPe1Map(); - } - - private void initJTable() - { - _shefPe1RowDataList = _dataMgr.getShefPe1RowDataList(); - setCEColumnDescriptorList(); - _shefPe1TableManager = new ComplexJTableManager( _shefPe1ColumnDescriptorList, _shefPe1RowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefPe1TableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefPe1TableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefPe1TableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 320, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefPe1SelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _dataMgr.initShefPeList(); - _shefPe1RowDataList = _dataMgr.getShefPe1RowDataList(); - _shefPe1TableManager.setChangedAllRowDataList( _shefPe1RowDataList ); - _shefPe1TableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefPe1ColumnDescriptorList = new ArrayList(); - - _shefPe1ColumnDescriptorList.add(new JTableColumnDescriptor( "PE1", true, 50, "center" ) ); - _shefPe1ColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 250, "center" ) ); - } - - private void populateDataInputPanel( ShefPE1 shefPe1 ) - { - if ( shefPe1 != null ) - { - _pe1LTF.setTextField( shefPe1.getPe1() ); - _nameLTF.setTextField( shefPe1.getName() ); - } - } - - private void clearDataInputPanel() - { - _pe1LTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - } - - private boolean saveShefPe1() - { - boolean saved = false; - - if ( ! _pe1LTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - ShefPE1 shefPe1 = new ShefPE1(); - - shefPe1.setPe1( _pe1LTF.getTextFieldText() ); - shefPe1.setName( _nameLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefPe1( shefPe1 ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for PE1", "Save ShefPE1" ); - } - - return saved; - } - - private void deleteShefPe1() - { - ShefPE1 shefPe1 = null; - List selectedRowsData = _shefPe1TableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefPE1JTableRowData rowData = (ArcBaseShefPE1JTableRowData) selectedRowsData.get( 0 ); - shefPe1 = (ShefPE1) _shefPe1RowDataToShefPe1Map.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefPe1.keyString(), "Delete ShefPE1" ) ) - { - _dataMgr.deleteShefPe1FromDataBase( shefPe1 ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefPE1", "Delete ShefPE1" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefPe1TableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefPe1(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefPe1() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefPe1(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefPE1 shefPe1 = null; - - ArcBaseShefPE1JTableRowData rowData = (ArcBaseShefPE1JTableRowData) _shefPe1TableManager.getSelectedRowsData().get( 0 ); - shefPe1 = (ShefPE1) _shefPe1RowDataToShefPe1Map.get( rowData ); - populateDataInputPanel( shefPe1 ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefPE1Editor shefPE1Editor = new ShefPE1Editor( frame, dataMgr ); - shefPE1Editor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPEEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPEEditor.java deleted file mode 100644 index 55eb13efdc..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPEEditor.java +++ /dev/null @@ -1,310 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.table.ArcBaseShefPEJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefPEEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefPeTableManager = null; - private List _shefPeColumnDescriptorList = null; - private List _shefPeRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefPeSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _peLTF = new LabeledTextField( "PE:", "", "SHEF PE code", 3 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 31 ); - private LabeledTextField _engUnitLTF = new LabeledTextField( "English Unit:", "", "Abbreviation of the English unit for the specified SHEF PE. (eg, ft for feet)", 9 ); - private LabeledTextField _metUnitLTF = new LabeledTextField( "Metric Unit:", "", "Abbreviation of the Metric unit for the specified SHEF PE (eg, deg C)", 9 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefPeRowDataToShefPeMap = null; - - public ShefPEEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefPE Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefPeSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefPeSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefPeSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefPE" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _peLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _engUnitLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _metUnitLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefPeRowDataToShefPeMap = _dataMgr.getShefPeRowDataToShefPeMap(); - } - - private void initJTable() - { - _shefPeRowDataList = _dataMgr.getShefPeRowDataList(); - setCEColumnDescriptorList(); - _shefPeTableManager = new ComplexJTableManager( _shefPeColumnDescriptorList, _shefPeRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefPeTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefPeTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefPeTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 520, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefPeSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _dataMgr.initShefPeList(); - _shefPeRowDataList = _dataMgr.getShefPeRowDataList(); - _shefPeTableManager.setChangedAllRowDataList( _shefPeRowDataList ); - _shefPeTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefPeColumnDescriptorList = new ArrayList(); - - _shefPeColumnDescriptorList.add(new JTableColumnDescriptor( "PE", true, 50, "center" ) ); - _shefPeColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 250, "center" ) ); - _shefPeColumnDescriptorList.add(new JTableColumnDescriptor( "MetUnit", true, 100, "center" ) ); - _shefPeColumnDescriptorList.add(new JTableColumnDescriptor( "EngUnit", true, 100, "center" ) ); - } - - private void populateDataInputPanel( ShefPE shefPe ) - { - if ( shefPe != null ) - { - _peLTF.setTextField( shefPe.getPe() ); - _nameLTF.setTextField( shefPe.getName() ); - _engUnitLTF.setTextField( shefPe.getEngUnit() ); - _metUnitLTF.setTextField( shefPe.getMetUnit() ); - } - } - - private void clearDataInputPanel() - { - _peLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - _engUnitLTF.setTextField( "" ); - _metUnitLTF.setTextField( "" ); - } - - private boolean saveShefPe() - { - boolean saved = false; - - if ( ! _peLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - ShefPE shefPe = new ShefPE(); - - shefPe.setPe( _peLTF.getTextFieldText() ); - shefPe.setName( _nameLTF.getTextFieldText() ); - shefPe.setEngUnit( _engUnitLTF.getTextFieldText() ); - shefPe.setMetUnit( _metUnitLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefPe( shefPe ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for PE", "Save ShefPE" ); - } - - return saved; - } - - private void deleteShefPe() - { - ShefPE shefPe = null; - List selectedRowsData = _shefPeTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefPEJTableRowData rowData = (ArcBaseShefPEJTableRowData) selectedRowsData.get( 0 ); - shefPe = (ShefPE) _shefPeRowDataToShefPeMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefPe.keyString(), "Delete ShefPE" ) ) - { - _dataMgr.deleteShefPeFromDataBase( shefPe ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefPE", "Delete ShefPE" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefPeTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefPe(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefPe() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefPe(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefPE shefPe = null; - - ArcBaseShefPEJTableRowData rowData = (ArcBaseShefPEJTableRowData) _shefPeTableManager.getSelectedRowsData().get( 0 ); - shefPe = (ShefPE) _shefPeRowDataToShefPeMap.get( rowData ); - populateDataInputPanel( shefPe ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefPEEditor shefPEEditor = new ShefPEEditor( frame, dataMgr ); - shefPEEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPETransEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPETransEditor.java deleted file mode 100644 index 330acc31a1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefPETransEditor.java +++ /dev/null @@ -1,347 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefPETrans; -import ohd.hseb.raxbase.table.ArcBaseShefPETransJTableRowData; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefPETransEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefPeTransTableManager = null; - private List _shefPeTransColumnDescriptorList = null; - private List _shefPeTransRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefPeTransSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _peLTF = new LabeledTextField( "PE:", "", "SHEF PE code", 3 ); - private LabeledTextField _codePositionLTF = new LabeledTextField( "CodePosition:", "", "Position of code within value sent with certain SHEF PE codes (specifically IR and SR), valid values are \" \" (space), 1, 2, 3,and 4 (depending on the SHEF PE code)", 2 ); - private LabeledTextField _codedValueLTF = new LabeledTextField( "CodedValue:", "", "Integer code used by SHEF PEs (AF, AM, GR, GS, HI, IR, NC, PE, PT, SR, XP, and XW) that are not data values but rather translate into English phrases (see the V1.3 SHEF Manual)", 9 ); - private LabeledTextField _valueTransLTF = new LabeledTextField( "ValueTrans:", "", "Description of what the coded value translates to", 81 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefPeTransRowDataToShefPeTransMap = null; - - public ShefPETransEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefPETrans Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 1000, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefPeTransSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefPeTransSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefPeTransSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefPETrans" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _peLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _codePositionLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _codedValueLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _valueTransLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - - _codePositionLTF.setTextFieldWidth( 2 ); - } - - - private void initHashMaps() - { - _shefPeTransRowDataToShefPeTransMap = _dataMgr.getShefPeTransRowDataToShefPeTransMap(); - } - - private void initJTable() - { - _shefPeTransRowDataList = _dataMgr.getShefPeTransRowDataList(); - setCEColumnDescriptorList(); - _shefPeTransTableManager = new ComplexJTableManager( _shefPeTransColumnDescriptorList, _shefPeTransRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefPeTransTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefPeTransTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefPeTransTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 270, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefPeTransSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _shefPeTransRowDataList = _dataMgr.getShefPeTransRowDataList(); - _shefPeTransTableManager.setChangedAllRowDataList( _shefPeTransRowDataList ); - _shefPeTransTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefPeTransColumnDescriptorList = new ArrayList(); - - _shefPeTransColumnDescriptorList.add(new JTableColumnDescriptor( "PE", true, 50, "center" ) ); - _shefPeTransColumnDescriptorList.add(new JTableColumnDescriptor( "CodePosition", true, 100, "center" ) ); - _shefPeTransColumnDescriptorList.add(new JTableColumnDescriptor( "CodedValue", true, 100, "center" ) ); - } - - private void populateDataInputPanel( ShefPETrans shefPeTrans ) - { - if ( shefPeTrans != null ) - { - _peLTF.setTextField( shefPeTrans.getPe() ); - _codePositionLTF.setTextField( shefPeTrans.getCodePosition() ); - _codedValueLTF.setTextField( shefPeTrans.getCodedValue() ); - _valueTransLTF.setTextField( shefPeTrans.getValueTrans() ); - } - } - - private void clearDataInputPanel() - { - _peLTF.setTextField( "" ); - _codePositionLTF.setTextField( "" ); - _codedValueLTF.setTextField( "" ); - _valueTransLTF.setTextField( "" ); - } - - private boolean saveShefPeTrans() - { - boolean saved = false; - boolean validNumber = true; - StringDataConverter converter = new StringDataConverter(); - - if ( ! ( ( _peLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || - ( _codePositionLTF.getTextFieldText().equalsIgnoreCase( "" ) ) || - ( _codedValueLTF.getTextFieldText().equalsIgnoreCase( "" ) ) ) ) - { - ShefPETrans shefPeTrans = new ShefPETrans(); - - shefPeTrans.setPe( _peLTF.getTextFieldText() ); - shefPeTrans.setCodePosition( _codePositionLTF.getTextFieldText() ); - try - { - shefPeTrans.setCodedValue( converter.getIntValue( _codedValueLTF.getTextFieldText() ) ); - } - catch ( NumberFormatException e ) - { - DialogHelper.displayErrorDialog( this, "Please enter a valid numeric value for Coded Value", "Save ShefPETrans" ); - validNumber = false; - } - - if ( validNumber ) - { - shefPeTrans.setValueTrans( _valueTransLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefPeTrans( shefPeTrans ); - - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for PE/CodePosition/CodedValue", "Save ShefPETrans" ); - } - - return saved; - } - - private void deleteShefPeTrans() - { - ShefPETrans shefPeTrans = null; - List selectedRowsData = _shefPeTransTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefPETransJTableRowData rowData = (ArcBaseShefPETransJTableRowData) selectedRowsData.get( 0 ); - shefPeTrans = (ShefPETrans) _shefPeTransRowDataToShefPeTransMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefPeTrans.keyString(), "Delete ShefPETrans" ) ) - { - _dataMgr.deleteShefPeTransFromDataBase( shefPeTrans ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefPETrans", "Delete ShefPETrans" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefPeTransTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _codePositionLTF.addTextFieldKeyListener( new CodePositionKeyAdapter() ); - } - - private class CodePositionKeyAdapter implements KeyListener - { - - public void keyPressed( KeyEvent arg0 ){} - public void keyTyped( KeyEvent e ){} - public void keyReleased( KeyEvent arg0 ) - { - String codePositionString = _codePositionLTF.getTextFieldText(); - int length = codePositionString.length(); - if ( length > 1 ) - { - _codePositionLTF.setTextField( codePositionString.substring( 0, 1 ) ); - } - } - - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefPeTrans(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefPeTrans() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefPeTrans(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefPETrans shefPeTrans = null; - - ArcBaseShefPETransJTableRowData rowData = (ArcBaseShefPETransJTableRowData) _shefPeTransTableManager.getSelectedRowsData().get( 0 ); - shefPeTrans = (ShefPETrans) _shefPeTransRowDataToShefPeTransMap.get( rowData ); - populateDataInputPanel( shefPeTrans ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefPETransEditor shefPETransEditor = new ShefPETransEditor( frame, dataMgr ); - shefPETransEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefProbEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefProbEditor.java deleted file mode 100644 index 6430ee9546..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefProbEditor.java +++ /dev/null @@ -1,307 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefProb; -import ohd.hseb.raxbase.table.ArcBaseShefProbJTableRowData; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefProbEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefProbTableManager = null; - private List _shefProbColumnDescriptorList = null; - private List _shefProbRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefProbSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _pLTF = new LabeledTextField( "P:", "", "Owner agency location", 2 ); - private LabeledTextField _probLTF = new LabeledTextField( "Probability:", "", "Numerical value of forecast probability as defined in Table 6 of the SHEF manual (two codes do not have assigned probability values in the SHEF Manual, M (mean) and Z (filler); the SHEF Parser program assigns values of M = -0.5, Z = 1.0)", 15 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefProbRowDataToShefProbMap = null; - - public ShefProbEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefProb Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefProbSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefProbSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefProbSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefProb" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _pLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _probLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefProbRowDataToShefProbMap = _dataMgr.getShefProbRowDataToShefProbMap(); - } - - private void initJTable() - { - _shefProbRowDataList = _dataMgr.getShefProbRowDataList(); - setCEColumnDescriptorList(); - _shefProbTableManager = new ComplexJTableManager( _shefProbColumnDescriptorList, _shefProbRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefProbTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefProbTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefProbTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 345, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefProbSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _dataMgr.initShefProbList(); - _shefProbRowDataList = _dataMgr.getShefProbRowDataList(); - _shefProbTableManager.setChangedAllRowDataList( _shefProbRowDataList ); - _shefProbTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefProbColumnDescriptorList = new ArrayList(); - - _shefProbColumnDescriptorList.add(new JTableColumnDescriptor( "P", true, 50, "center" ) ); - _shefProbColumnDescriptorList.add(new JTableColumnDescriptor( "Probability", true, 100, "center" ) ); - _shefProbColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 175, "center" ) ); - } - - private void populateDataInputPanel( ShefProb shefProb ) - { - if ( shefProb != null ) - { - _pLTF.setTextField( shefProb.getP() ); - _probLTF.setTextField( shefProb.getProbability() ); - _nameLTF.setTextField( shefProb.getName() ); - } - } - - private void clearDataInputPanel() - { - _pLTF.setTextField( "" ); - _probLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - } - - private boolean saveShefProb() - { - boolean saved = false; - - StringDataConverter converter = new StringDataConverter(); - - if ( ! _pLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - ShefProb shefProb = new ShefProb(); - - shefProb.setP( _pLTF.getTextFieldText() ); - shefProb.setName( _nameLTF.getTextFieldText() ); - shefProb.setProbability( converter.getFloatValue( _probLTF.getTextFieldText() ) ); - - saved = _dataMgr.saveShefProb( shefProb ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for P", "Save ShefProb" ); - } - - return saved; - } - - private void deleteShefProb() - { - ShefProb shefProb = null; - List selectedRowsData = _shefProbTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefProbJTableRowData rowData = (ArcBaseShefProbJTableRowData) selectedRowsData.get( 0 ); - shefProb = (ShefProb) _shefProbRowDataToShefProbMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefProb.keyString(), "Delete ShefProb" ) ) - { - _dataMgr.deleteShefProbFromDataBase( shefProb ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefProb", "Delete ShefProb" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefProbTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefProb(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefProb() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefProb(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefProb shefProb = null; - - ArcBaseShefProbJTableRowData rowData = (ArcBaseShefProbJTableRowData) _shefProbTableManager.getSelectedRowsData().get( 0 ); - shefProb = (ShefProb) _shefProbRowDataToShefProbMap.get( rowData ); - populateDataInputPanel( shefProb ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefProbEditor shefProbEditor = new ShefProbEditor( frame, dataMgr ); - shefProbEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefQCEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefQCEditor.java deleted file mode 100644 index 6cb4a29c34..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefQCEditor.java +++ /dev/null @@ -1,306 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefQC; -import ohd.hseb.raxbase.table.ArcBaseShefQCJTableRowData; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefQCEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefQCTableManager = null; - private List _shefQCColumnDescriptorList = null; - private List _shefQCRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefQCSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _shefQualifierCodeLTF = new LabeledTextField( "Shef Qualifier Code:", "", "SHEF Qualifier code", 2 ); - private LabeledTextField _powerLTF = new LabeledTextField( "Ranking Power:", "", "Ranking order of quality codes", 15 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefQCRowDataToShefQCMap = null; - - public ShefQCEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefQC Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefQCSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefQCSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefQCSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.VERTICAL ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefQC" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _shefQualifierCodeLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _powerLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefQCRowDataToShefQCMap = _dataMgr.getShefQCRowDataToShefQCMap(); - } - - private void initJTable() - { - _shefQCRowDataList = _dataMgr.getShefQCRowDataList(); - setCEColumnDescriptorList(); - _shefQCTableManager = new ComplexJTableManager( _shefQCColumnDescriptorList, _shefQCRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefQCTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefQCTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefQCTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 420, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefQCSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _shefQCRowDataList = _dataMgr.getShefQCRowDataList(); - _shefQCTableManager.setChangedAllRowDataList( _shefQCRowDataList ); - _shefQCTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefQCColumnDescriptorList = new ArrayList(); - - _shefQCColumnDescriptorList.add(new JTableColumnDescriptor( "ShefQCCode", true, 100, "center" ) ); - _shefQCColumnDescriptorList.add(new JTableColumnDescriptor( "Power", true, 50, "center" ) ); - _shefQCColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 250, "center" ) ); - } - - private void populateDataInputPanel( ShefQC shefQC ) - { - if ( shefQC != null ) - { - _shefQualifierCodeLTF.setTextField( shefQC.getShefQualifierCode() ); - _powerLTF.setTextField( shefQC.getPower() ); - _nameLTF.setTextField( shefQC.getName() ); - } - } - - private void clearDataInputPanel() - { - _shefQualifierCodeLTF.setTextField( "" ); - _powerLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - } - - private boolean saveShefQC() - { - boolean saved = false; - - StringDataConverter converter = new StringDataConverter(); - - if ( ! _powerLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - ShefQC shefQC = new ShefQC(); - - shefQC.setShefQualifierCode( _shefQualifierCodeLTF.getTextFieldText() ); - shefQC.setPower( converter.getIntValue( _powerLTF.getTextFieldText() ) ); - shefQC.setName( _nameLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefQC( shefQC ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for Power", "Save ShefQC" ); - } - - return saved; - } - - private void deleteShefQC() - { - ShefQC shefQC = null; - List selectedRowsData = _shefQCTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefQCJTableRowData rowData = (ArcBaseShefQCJTableRowData) selectedRowsData.get( 0 ); - shefQC = (ShefQC) _shefQCRowDataToShefQCMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefQC.keyString(), "Delete ShefQC" ) ) - { - _dataMgr.deleteShefQCFromDataBase( shefQC ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefQC", "Delete ShefQC" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefQCTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefQC(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefQC() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefQC(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefQC shefQC = null; - - ArcBaseShefQCJTableRowData rowData = (ArcBaseShefQCJTableRowData) _shefQCTableManager.getSelectedRowsData().get( 0 ); - shefQC = (ShefQC) _shefQCRowDataToShefQCMap.get( rowData ); - populateDataInputPanel( shefQC ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefQCEditor shefQCEditor = new ShefQCEditor( frame, dataMgr ); - shefQCEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefTSEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefTSEditor.java deleted file mode 100644 index c0529488ef..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/ShefTSEditor.java +++ /dev/null @@ -1,298 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.raxbase.table.ArcBaseShefTSJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class ShefTSEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _shefTSTableManager = null; - private List _shefTSColumnDescriptorList = null; - private List _shefTSRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _shefTSSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _tsLTF = new LabeledTextField( "TS:", "", "SHEF TypeSource Code", 3 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name:", "", "Description (mixed case)", 21 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _shefTsRowDataToShefTsMap = null; - - public ShefTSEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "ShefTS Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 300, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initShefTSSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initShefTSSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _shefTSSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected ShefTS" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _tsLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _shefTsRowDataToShefTsMap = _dataMgr.getShefTsRowDataToShefTsMap(); - } - - private void initJTable() - { - _shefTSRowDataList = _dataMgr.getShefTsRowDataList(); - setCEColumnDescriptorList(); - _shefTSTableManager = new ComplexJTableManager( _shefTSColumnDescriptorList, _shefTSRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _shefTSTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _shefTSTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _shefTSTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 100, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _shefTSSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _dataMgr.initShefTSList(); - _shefTSRowDataList = _dataMgr.getShefTsRowDataList(); - _shefTSTableManager.setChangedAllRowDataList( _shefTSRowDataList ); - _shefTSTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _shefTSColumnDescriptorList = new ArrayList(); - - _shefTSColumnDescriptorList.add(new JTableColumnDescriptor( "TS", true, 50, "center" ) ); - _shefTSColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 200, "center" ) ); - } - - private void populateDataInputPanel( ShefTS shefTs ) - { - if ( shefTs != null ) - { - _tsLTF.setTextField( shefTs.getTs() ); - _nameLTF.setTextField( shefTs.getName() ); - } - } - - private void clearDataInputPanel() - { - _tsLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - } - - private boolean saveShefTs() - { - boolean saved = false; - - if ( ! _tsLTF.getTextFieldText().equalsIgnoreCase( "" ) ) - { - ShefTS shefTs = new ShefTS(); - - shefTs.setTs( _tsLTF.getTextFieldText() ); - shefTs.setName( _nameLTF.getTextFieldText() ); - - saved = _dataMgr.saveShefTs( shefTs ); - - updateJTable(); - } - else - { - DialogHelper.displayErrorDialog( this, "Please enter a value for TS", "Save ShefTS" ); - } - - return saved; - } - - private void deleteShefTs() - { - ShefTS shefTs = null; - List selectedRowsData = _shefTSTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseShefTSJTableRowData rowData = (ArcBaseShefTSJTableRowData) selectedRowsData.get( 0 ); - shefTs = (ShefTS) _shefTsRowDataToShefTsMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + shefTs.keyString(), "Delete ShefTS" ) ) - { - _dataMgr.deleteShefTsFromDataBase( shefTs ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a ShefTS", "Delete ShefTS" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _shefTSTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveShefTs(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveShefTs() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteShefTs(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - ShefTS shefTs = null; - - ArcBaseShefTSJTableRowData rowData = (ArcBaseShefTSJTableRowData) _shefTSTableManager.getSelectedRowsData().get( 0 ); - shefTs = (ShefTS) _shefTsRowDataToShefTsMap.get( rowData ); - populateDataInputPanel( shefTs ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - ShefTSEditor shefTSEditor = new ShefTSEditor( frame, dataMgr ); - shefTSEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/SlopeProfileEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/SlopeProfileEditor.java deleted file mode 100644 index 6ca889f177..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/SlopeProfileEditor.java +++ /dev/null @@ -1,673 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.RaxLocation; -import ohd.hseb.raxbase.model.SlopeProfile; -import ohd.hseb.raxbase.util.DateManager; -import ohd.hseb.raxbase.util.HDateSuperChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.util.StringDataConverter; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledComboBox; -import ohd.hseb.util.gui.LabeledTextField; - -public class SlopeProfileEditor extends JDialog implements HDateChooserOwner -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - - private HDateSuperChooser _hDateChooser = new HDateSuperChooser( false ); - private int _clickedDateField = -9999; - - private LabeledComboBox _selectionLCB = new LabeledComboBox(); - - private JPanel _dataPanel = new JPanel( new GridBagLayout() ); - private JPanel _distancePanel = new JPanel( new GridBagLayout() ); - private JPanel _elevationPanel = new JPanel( new GridBagLayout() ); - - private StringDataConverter _converter = new StringDataConverter(); - - private Map _selectionStringToSlopeProfileMap = new HashMap(); - private String _lid = null; - - private List _slopeProfileList = null; - private SlopeProfile _selectedSlopeProfile = null; - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private LabeledTextField _lidLTF = new LabeledTextField( "LID:", "", "Location ID", 8 ); - private LabeledTextField _markerLTF = new LabeledTextField( "Marker:", "", "Marker used to measure distance to water in slope profile (eg. marker a)", 2 ); - private LabeledTextField _beginDateLTF = new LabeledTextField( "BeginDate:", "", "Begin Date", 12 ); - private LabeledTextField _endDateLTF = new LabeledTextField( "EndDate:", "", "End Date", 12 ); - - private LabeledTextField _distance01LTF = new LabeledTextField( "Distance01:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance02LTF = new LabeledTextField( "Distance02:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance03LTF = new LabeledTextField( "Distance03:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance04LTF = new LabeledTextField( "Distance04:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance05LTF = new LabeledTextField( "Distance05:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance06LTF = new LabeledTextField( "Distance06:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance07LTF = new LabeledTextField( "Distance07:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance08LTF = new LabeledTextField( "Distance08:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance09LTF = new LabeledTextField( "Distance09:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance10LTF = new LabeledTextField( "Distance10:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance11LTF = new LabeledTextField( "Distance11:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance12LTF = new LabeledTextField( "Distance12:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance13LTF = new LabeledTextField( "Distance13:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance14LTF = new LabeledTextField( "Distance14:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance15LTF = new LabeledTextField( "Distance15:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance16LTF = new LabeledTextField( "Distance16:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance17LTF = new LabeledTextField( "Distance17:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance18LTF = new LabeledTextField( "Distance18:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance19LTF = new LabeledTextField( "Distance19:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance20LTF = new LabeledTextField( "Distance20:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance21LTF = new LabeledTextField( "Distance21:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance22LTF = new LabeledTextField( "Distance22:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance23LTF = new LabeledTextField( "Distance23:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance24LTF = new LabeledTextField( "Distance24:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance25LTF = new LabeledTextField( "Distance25:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance26LTF = new LabeledTextField( "Distance26:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance27LTF = new LabeledTextField( "Distance27:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance28LTF = new LabeledTextField( "Distance28:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance29LTF = new LabeledTextField( "Distance29:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - private LabeledTextField _distance30LTF = new LabeledTextField( "Distance30:", "", "Slope distances (ft and tenths of ft) measured from specified marker to the waters edge", 8 ); - - private LabeledTextField _elevation01LTF = new LabeledTextField( "Elevation01:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation02LTF = new LabeledTextField( "Elevation02:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation03LTF = new LabeledTextField( "Elevation03:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation04LTF = new LabeledTextField( "Elevation04:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation05LTF = new LabeledTextField( "Elevation05:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation06LTF = new LabeledTextField( "Elevation06:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation07LTF = new LabeledTextField( "Elevation07:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation08LTF = new LabeledTextField( "Elevation08:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation09LTF = new LabeledTextField( "Elevation09:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation10LTF = new LabeledTextField( "Elevation10:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation11LTF = new LabeledTextField( "Elevation11:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation12LTF = new LabeledTextField( "Elevation12:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation13LTF = new LabeledTextField( "Elevation13:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation14LTF = new LabeledTextField( "Elevation14:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation15LTF = new LabeledTextField( "Elevation15:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation16LTF = new LabeledTextField( "Elevation16:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation17LTF = new LabeledTextField( "Elevation17:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation18LTF = new LabeledTextField( "Elevation18:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation19LTF = new LabeledTextField( "Elevation19:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation20LTF = new LabeledTextField( "Elevation20:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation21LTF = new LabeledTextField( "Elevation21:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation22LTF = new LabeledTextField( "Elevation22:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation23LTF = new LabeledTextField( "Elevation23:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation24LTF = new LabeledTextField( "Elevation24:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation25LTF = new LabeledTextField( "Elevation25:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation26LTF = new LabeledTextField( "Elevation26:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation27LTF = new LabeledTextField( "Elevation27:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation28LTF = new LabeledTextField( "Elevation28:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation29LTF = new LabeledTextField( "Elevation29:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - private LabeledTextField _elevation30LTF = new LabeledTextField( "Elevation30:", "", "Stage height corresponding to slope distance (distance01 - distance 30) (ft)", 8 ); - - - public SlopeProfileEditor( JFrame frame, RaxBaseDataMgr dataMgr, String lid, String title ) - { - super( frame, "Slope Profile Editor - " + title, true ); - _dataMgr = dataMgr; - _lid = lid; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 600, 900 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - updateSlopeProfileList(); - - updateSelectionComboBox(); - initDataPanel(); - initButtonPanel(); - initFrameComponents(); - addListeners(); - populateDataPanel( _selectedSlopeProfile ); - pack(); - setVisible( true ); - } - - private void initButtonPanel() - { - _buttonPanel.setBorder( BorderFactory.createTitledBorder( "Database Controls" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initDataPanel() - { - _dataPanel.setBorder( BorderFactory.createTitledBorder( "Selected Item" ) ); - - initDistancePanel(); - initElevationPanel(); - _beginDateLTF.setEditTextField( false ); - _endDateLTF.setEditTextField( false ); - _lidLTF.setEditTextField( false ); - _lidLTF.setTextField( _lid ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataPanel, _lidLTF, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _markerLTF, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _beginDateLTF, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _endDateLTF, 0, 3, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _distancePanel, 0, 4, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, _elevationPanel, 1, 4, 1, 1, 1, 1, GridBagConstraints.NONE ); - - } - - private void initElevationPanel() - { - _elevationPanel.setBorder( BorderFactory.createTitledBorder( "Elevation Values" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _elevationPanel, _elevation01LTF, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation02LTF, 0, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation03LTF, 0, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation04LTF, 0, 3, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation05LTF, 0, 4, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation06LTF, 0, 5, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation07LTF, 0, 6, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation08LTF, 0, 7, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation09LTF, 0, 8, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation10LTF, 0, 9, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation11LTF, 0, 10, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation12LTF, 0, 11, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation13LTF, 0, 12, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation14LTF, 0, 13, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation15LTF, 0, 14, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation16LTF, 0, 15, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation17LTF, 0, 16, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation18LTF, 0, 17, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation19LTF, 0, 18, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation20LTF, 0, 19, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation21LTF, 0, 20, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation22LTF, 0, 21, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation23LTF, 0, 22, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation24LTF, 0, 23, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation25LTF, 0, 24, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation26LTF, 0, 25, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation27LTF, 0, 26, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation28LTF, 0, 27, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation29LTF, 0, 28, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _elevationPanel, _elevation30LTF, 0, 29, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initDistancePanel() - { - _distancePanel.setBorder( BorderFactory.createTitledBorder( "Distance Values" ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _distancePanel, _distance01LTF, 0, 0, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance02LTF, 0, 1, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance03LTF, 0, 2, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance04LTF, 0, 3, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance05LTF, 0, 4, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance06LTF, 0, 5, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance07LTF, 0, 6, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance08LTF, 0, 7, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance09LTF, 0, 8, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance10LTF, 0, 9, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance11LTF, 0, 10, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance12LTF, 0, 11, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance13LTF, 0, 12, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance14LTF, 0, 13, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance15LTF, 0, 14, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance16LTF, 0, 15, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance17LTF, 0, 16, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance18LTF, 0, 17, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance19LTF, 0, 18, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance20LTF, 0, 19, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance21LTF, 0, 20, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance22LTF, 0, 21, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance23LTF, 0, 22, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance24LTF, 0, 23, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance25LTF, 0, 24, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance26LTF, 0, 25, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance27LTF, 0, 26, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance28LTF, 0, 27, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance29LTF, 0, 28, 1, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _distancePanel, _distance30LTF, 0, 29, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _selectionLCB, 0, 0, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _dataPanel, 0, 1, 2, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 2, 2, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void updateSelectionComboBox() - { - SlopeProfile slopeProfile = null; - List selectionComboBoxStringList = new ArrayList(); - String dateString = null; - - _selectionStringToSlopeProfileMap.clear(); - _selectionLCB.getComboBox().removeAllItems(); - - for ( int i = 0; i < _slopeProfileList.size(); i++ ) - { - slopeProfile = (SlopeProfile) _slopeProfileList.get( i ); - selectionComboBoxStringList.add( getSelectedSlopeProfileString( slopeProfile ) ); - _selectionStringToSlopeProfileMap.put( getSelectedSlopeProfileString( slopeProfile ), slopeProfile ); - } - - if ( selectionComboBoxStringList.isEmpty() ) - { - selectionComboBoxStringList.add( "No entries found" ); - } - _selectionLCB.setComboBoxFromStringArray( selectionComboBoxStringList.toArray() ); - _selectionLCB.setLabel( "Select Average Entry:" ); - _selectionLCB.setLabelPreferredSize( new Dimension( 150, 15 ) ); - _selectionLCB.setComboBoxPreferredSize( new Dimension( 375, 15 ) ); - - String selectedItem = _selectionLCB.getSelectedCBItem(); - - _selectedSlopeProfile = (SlopeProfile) _selectionStringToSlopeProfileMap.get( selectedItem ); - } - - private String getSelectedSlopeProfileString( SlopeProfile slopeProfile ) - { - return "LID = " + slopeProfile.getLid() + " | Marker = " + slopeProfile.getMarker() + " | BeginDate = " + DbTimeHelper.getDateStringFromLongTime( slopeProfile.getBegdate() ); - } - - - private void updateSlopeProfileList() - { - _slopeProfileList = _dataMgr.getSlopeProfileList( _lid ); - } - - private void populateDataPanel( SlopeProfile e ) - { - if ( e != null ) - { - _lidLTF.setTextField( e.getLid() ); - _markerLTF.setTextField( e.getMarker() ); - _beginDateLTF.setTextField( _converter.getDateStringFromDateLong( e.getBegdate() ) ); - _endDateLTF.setTextField( _converter.getDateStringFromDateLong( e.getEnddate() ) ); - - _distance01LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance01() ) ); - _distance02LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance02() ) ); - _distance03LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance03() ) ); - _distance04LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance04() ) ); - _distance05LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance05() ) ); - _distance06LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance06() ) ); - _distance07LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance07() ) ); - _distance08LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance08() ) ); - _distance09LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance09() ) ); - _distance10LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance10() ) ); - _distance11LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance11() ) ); - _distance12LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance12() ) ); - _distance13LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance13() ) ); - _distance14LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance14() ) ); - _distance15LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance15() ) ); - _distance16LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance16() ) ); - _distance17LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance17() ) ); - _distance18LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance18() ) ); - _distance19LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance19() ) ); - _distance20LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance20() ) ); - _distance21LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance21() ) ); - _distance22LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance22() ) ); - _distance23LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance23() ) ); - _distance24LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance24() ) ); - _distance25LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance25() ) ); - _distance26LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance26() ) ); - _distance27LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance27() ) ); - _distance28LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance28() ) ); - _distance29LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance29() ) ); - _distance30LTF.setTextField( _converter.getFormattedFloatValue( e.getDistance30() ) ); - - _elevation01LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation01() ) ); - _elevation02LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation02() ) ); - _elevation03LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation03() ) ); - _elevation04LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation04() ) ); - _elevation05LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation05() ) ); - _elevation06LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation06() ) ); - _elevation07LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation07() ) ); - _elevation08LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation08() ) ); - _elevation09LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation09() ) ); - _elevation10LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation10() ) ); - _elevation11LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation11() ) ); - _elevation12LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation12() ) ); - _elevation13LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation13() ) ); - _elevation14LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation14() ) ); - _elevation15LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation15() ) ); - _elevation16LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation16() ) ); - _elevation17LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation17() ) ); - _elevation18LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation18() ) ); - _elevation19LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation19() ) ); - _elevation20LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation20() ) ); - _elevation21LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation21() ) ); - _elevation22LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation22() ) ); - _elevation23LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation23() ) ); - _elevation24LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation24() ) ); - _elevation25LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation25() ) ); - _elevation26LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation26() ) ); - _elevation27LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation27() ) ); - _elevation28LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation28() ) ); - _elevation29LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation29() ) ); - _elevation30LTF.setTextField( _converter.getFormattedFloatValue( e.getElevation30() ) ); - - } - _hDateChooser.addOwner( this ); - - } - - private void launchDateWindow( int clickedDateField ) - { - _clickedDateField = clickedDateField; - - GregorianCalendar calendar = new GregorianCalendar(); - long dayInMillis = 60*60*24*1000; - long dateLong = 0; - String dateString = null; - - switch ( _clickedDateField ) - { - case 0: dateString = _beginDateLTF.getTextFieldText(); break; - case 1: dateString = _endDateLTF.getTextFieldText(); break; - } - - if ( ! dateString.equalsIgnoreCase( "" ) ) - { - dateLong = DbTimeHelper.getLongTimeFromDateString( dateString ) + dayInMillis; - } - else - { - dateLong = System.currentTimeMillis(); - } - - calendar.setTimeInMillis( dateLong ); - _hDateChooser.setDate( calendar ); - _hDateChooser.setModal( true ); - _hDateChooser.setVisible( true ); - - } - - public void dateChosen( JDialog jDialog ) - { - if ( _clickedDateField != -9999 ) - { - Calendar calendar = _hDateChooser.getDate(); - String dateString = null; - - if ( _hDateChooser.isClearDate() ) - { - dateString = ""; - } - else - { - dateString = DateManager.getDateStringFromCalendar( calendar ); - } - - switch ( _clickedDateField ) - { - case 0: _beginDateLTF.setTextField( dateString ); break; - case 1: _endDateLTF.setTextField( dateString ); break; - } - _clickedDateField = -9999; - } - } - - private void deleteSlopeProfile() - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - SlopeProfile slopeProfile = (SlopeProfile) _selectionStringToSlopeProfileMap.get( selectedItem ); - - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + slopeProfile.keyString(), "Delete SlopeProfile" ) ) - { - boolean success = _dataMgr.deleteSlopeProfileFromDatabase( slopeProfile ); - if ( ! success ) - { - DialogHelper.displayErrorDialog( this, "Unable to delete SlopeProfile entry", "Delete SlopeProfile Error" ); - } - updateSlopeProfileList(); - updateSelectionComboBox(); - } - } - - private boolean saveSlopeProfile() - { - boolean saved = false; - SlopeProfile slopeProfile = new SlopeProfile(); - - slopeProfile.setLid( _lidLTF.getTextFieldText() ); - slopeProfile.setMarker( _markerLTF.getTextFieldText() ); - slopeProfile.setBegdate( _converter.getLongDateValue( _beginDateLTF.getTextFieldText() ) ); - slopeProfile.setEnddate( _converter.getLongDateValue( _endDateLTF.getTextFieldText() ) ); - - slopeProfile.setDistance01( _converter.getFloatValue( _distance01LTF.getTextFieldText() ) ); - slopeProfile.setDistance02( _converter.getFloatValue( _distance02LTF.getTextFieldText() ) ); - slopeProfile.setDistance03( _converter.getFloatValue( _distance03LTF.getTextFieldText() ) ); - slopeProfile.setDistance04( _converter.getFloatValue( _distance04LTF.getTextFieldText() ) ); - slopeProfile.setDistance05( _converter.getFloatValue( _distance05LTF.getTextFieldText() ) ); - slopeProfile.setDistance06( _converter.getFloatValue( _distance06LTF.getTextFieldText() ) ); - slopeProfile.setDistance07( _converter.getFloatValue( _distance07LTF.getTextFieldText() ) ); - slopeProfile.setDistance08( _converter.getFloatValue( _distance08LTF.getTextFieldText() ) ); - slopeProfile.setDistance09( _converter.getFloatValue( _distance09LTF.getTextFieldText() ) ); - slopeProfile.setDistance10( _converter.getFloatValue( _distance10LTF.getTextFieldText() ) ); - slopeProfile.setDistance11( _converter.getFloatValue( _distance11LTF.getTextFieldText() ) ); - slopeProfile.setDistance12( _converter.getFloatValue( _distance12LTF.getTextFieldText() ) ); - slopeProfile.setDistance13( _converter.getFloatValue( _distance13LTF.getTextFieldText() ) ); - slopeProfile.setDistance14( _converter.getFloatValue( _distance14LTF.getTextFieldText() ) ); - slopeProfile.setDistance15( _converter.getFloatValue( _distance15LTF.getTextFieldText() ) ); - slopeProfile.setDistance16( _converter.getFloatValue( _distance16LTF.getTextFieldText() ) ); - slopeProfile.setDistance17( _converter.getFloatValue( _distance17LTF.getTextFieldText() ) ); - slopeProfile.setDistance18( _converter.getFloatValue( _distance18LTF.getTextFieldText() ) ); - slopeProfile.setDistance19( _converter.getFloatValue( _distance19LTF.getTextFieldText() ) ); - slopeProfile.setDistance20( _converter.getFloatValue( _distance20LTF.getTextFieldText() ) ); - slopeProfile.setDistance21( _converter.getFloatValue( _distance21LTF.getTextFieldText() ) ); - slopeProfile.setDistance22( _converter.getFloatValue( _distance22LTF.getTextFieldText() ) ); - slopeProfile.setDistance23( _converter.getFloatValue( _distance23LTF.getTextFieldText() ) ); - slopeProfile.setDistance24( _converter.getFloatValue( _distance24LTF.getTextFieldText() ) ); - slopeProfile.setDistance25( _converter.getFloatValue( _distance25LTF.getTextFieldText() ) ); - slopeProfile.setDistance26( _converter.getFloatValue( _distance26LTF.getTextFieldText() ) ); - slopeProfile.setDistance27( _converter.getFloatValue( _distance27LTF.getTextFieldText() ) ); - slopeProfile.setDistance28( _converter.getFloatValue( _distance28LTF.getTextFieldText() ) ); - slopeProfile.setDistance29( _converter.getFloatValue( _distance29LTF.getTextFieldText() ) ); - slopeProfile.setDistance30( _converter.getFloatValue( _distance30LTF.getTextFieldText() ) ); - - slopeProfile.setElevation01( _converter.getFloatValue( _elevation01LTF.getTextFieldText() ) ); - slopeProfile.setElevation02( _converter.getFloatValue( _elevation02LTF.getTextFieldText() ) ); - slopeProfile.setElevation03( _converter.getFloatValue( _elevation03LTF.getTextFieldText() ) ); - slopeProfile.setElevation04( _converter.getFloatValue( _elevation04LTF.getTextFieldText() ) ); - slopeProfile.setElevation05( _converter.getFloatValue( _elevation05LTF.getTextFieldText() ) ); - slopeProfile.setElevation06( _converter.getFloatValue( _elevation06LTF.getTextFieldText() ) ); - slopeProfile.setElevation07( _converter.getFloatValue( _elevation07LTF.getTextFieldText() ) ); - slopeProfile.setElevation08( _converter.getFloatValue( _elevation08LTF.getTextFieldText() ) ); - slopeProfile.setElevation09( _converter.getFloatValue( _elevation09LTF.getTextFieldText() ) ); - slopeProfile.setElevation10( _converter.getFloatValue( _elevation10LTF.getTextFieldText() ) ); - slopeProfile.setElevation11( _converter.getFloatValue( _elevation11LTF.getTextFieldText() ) ); - slopeProfile.setElevation12( _converter.getFloatValue( _elevation12LTF.getTextFieldText() ) ); - slopeProfile.setElevation13( _converter.getFloatValue( _elevation13LTF.getTextFieldText() ) ); - slopeProfile.setElevation14( _converter.getFloatValue( _elevation14LTF.getTextFieldText() ) ); - slopeProfile.setElevation15( _converter.getFloatValue( _elevation15LTF.getTextFieldText() ) ); - slopeProfile.setElevation16( _converter.getFloatValue( _elevation16LTF.getTextFieldText() ) ); - slopeProfile.setElevation17( _converter.getFloatValue( _elevation17LTF.getTextFieldText() ) ); - slopeProfile.setElevation18( _converter.getFloatValue( _elevation18LTF.getTextFieldText() ) ); - slopeProfile.setElevation19( _converter.getFloatValue( _elevation19LTF.getTextFieldText() ) ); - slopeProfile.setElevation20( _converter.getFloatValue( _elevation20LTF.getTextFieldText() ) ); - slopeProfile.setElevation21( _converter.getFloatValue( _elevation21LTF.getTextFieldText() ) ); - slopeProfile.setElevation22( _converter.getFloatValue( _elevation22LTF.getTextFieldText() ) ); - slopeProfile.setElevation23( _converter.getFloatValue( _elevation23LTF.getTextFieldText() ) ); - slopeProfile.setElevation24( _converter.getFloatValue( _elevation24LTF.getTextFieldText() ) ); - slopeProfile.setElevation25( _converter.getFloatValue( _elevation25LTF.getTextFieldText() ) ); - slopeProfile.setElevation26( _converter.getFloatValue( _elevation26LTF.getTextFieldText() ) ); - slopeProfile.setElevation27( _converter.getFloatValue( _elevation27LTF.getTextFieldText() ) ); - slopeProfile.setElevation28( _converter.getFloatValue( _elevation28LTF.getTextFieldText() ) ); - slopeProfile.setElevation29( _converter.getFloatValue( _elevation29LTF.getTextFieldText() ) ); - slopeProfile.setElevation30( _converter.getFloatValue( _elevation30LTF.getTextFieldText() ) ); - - saved = _dataMgr.saveSlopeProfile( slopeProfile ); - updateSlopeProfileList(); - updateSelectionComboBox(); - - return saved; - } - - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - DateFieldMouseListener beginDateMouseListener = new DateFieldMouseListener( 0 ); - DateFieldMouseListener endDateMouseListener = new DateFieldMouseListener( 1 ); - - _selectionLCB.addComboBoxActionListener( new ItemSelectionListener() ); - - _beginDateLTF.addTextFieldMouseListener( beginDateMouseListener ); - _endDateLTF.addTextFieldMouseListener( endDateMouseListener ); - _closeButton.addActionListener( windowCloser ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveSlopeProfile() ) - { - closeWindow(); - } - else - { - DialogHelper.displayErrorDialog( SlopeProfileEditor.this, "Unable to save the SlopeProfile entry", "Error Saving SlopeProfile" ); - } - } - } - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteSlopeProfile(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveSlopeProfile(); - } - } - - private class DateFieldMouseListener implements MouseListener - { - private int __clickedDateField = -9999; - - public DateFieldMouseListener( int clickedDateField ) - { - __clickedDateField = clickedDateField; - } - public void mouseClicked( MouseEvent e ){} - public void mouseEntered( MouseEvent e ){} - public void mouseReleased( MouseEvent e ){} - public void mouseExited( MouseEvent e ){} - public void mousePressed( MouseEvent e ) - { - launchDateWindow( __clickedDateField ); - } - } - - private class ItemSelectionListener implements ActionListener - { - public void actionPerformed( ActionEvent e) - { - String selectedItem = _selectionLCB.getSelectedCBItem(); - - SlopeProfile slopeProfile = (SlopeProfile) _selectionStringToSlopeProfileMap.get( selectedItem ); - - if ( slopeProfile != null ) - { - populateDataPanel( slopeProfile ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob82krf?user=pguser" ); - String name = null; - - String title = "ATLA2"; - RaxLocation location = dataMgr.getRaxLocation( title ); - if ( location != null ) - { - name = location.getName(); - } - - if ( name != null ) - { - title += " - " + name; - } - - - SlopeProfileEditor slopeProfileEditor = new SlopeProfileEditor( frame, dataMgr, "ACTL2", title ); - slopeProfileEditor.displayGUI(); - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/StateEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/StateEditor.java deleted file mode 100644 index f97df9a4b8..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/StateEditor.java +++ /dev/null @@ -1,308 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.State; -import ohd.hseb.raxbase.table.ArcBaseStateJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class StateEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _stateTableManager = null; - private List _stateColumnDescriptorList = null; - private List _stateRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _stateSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _stateLTF = new LabeledTextField( "State: ", "", "State", 3 ); - private LabeledTextField _countryFipsLTF = new LabeledTextField( "CountryFips: ", "", "2 char country FIPS code (for \"counties\" table the default value is \"US\") (upper case)", 3 ); - private LabeledTextField _nameLTF = new LabeledTextField( "Name: ", "", "Name of state (mixed case)", 20 ); - private LabeledTextField _ncdcLTF = new LabeledTextField( "NCDC: ", "", "NCDC number for state", 3 ); - private LabeledTextField _stateFipsLTF = new LabeledTextField( "StateFips: ", "", "State FIPS code", 3 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _stateRowDataToStateMap = null; - - public StateEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "State Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 370, 500 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initStateSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initStateSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _stateSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 2, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected State" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _stateLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _countryFipsLTF, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _nameLTF, 0, 2, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _ncdcLTF, 0, 3, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _selectedItemPanel, _stateFipsLTF, 0, 4, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _stateRowDataToStateMap = _dataMgr.getStateRowDataToStateMap(); - } - - private void initJTable() - { - _stateRowDataList = _dataMgr.getStateRowDataList(); - setStateEColumnDescriptorList(); - _stateTableManager = new ComplexJTableManager( _stateColumnDescriptorList, _stateRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _stateTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _stateTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _stateTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 300, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _stateSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH ); - } - - private void updateJTable() - { - _stateRowDataList = _dataMgr.getStateRowDataList(); - _stateTableManager.setChangedAllRowDataList( _stateRowDataList ); - _stateTableManager.refreshDisplay(); - } - - private void setStateEColumnDescriptorList() - { - _stateColumnDescriptorList = new ArrayList(); - - _stateColumnDescriptorList.add(new JTableColumnDescriptor( "State", true, 50, "center" ) ); - _stateColumnDescriptorList.add(new JTableColumnDescriptor( "CountryFips", true, 60, "center" ) ); - _stateColumnDescriptorList.add(new JTableColumnDescriptor( "Name", true, 120, "center" ) ); - _stateColumnDescriptorList.add(new JTableColumnDescriptor( "Ncdc", true, 50, "center" ) ); - _stateColumnDescriptorList.add(new JTableColumnDescriptor( "StateFips", true, 60, "center" ) ); - } - - private void populateDataInputPanel( State state ) - { - if ( state != null ) - { - _stateLTF.setTextField( state.getState() ); - _countryFipsLTF.setTextField( state.getCountryFips() ); - _nameLTF.setTextField( state.getName() ); - _ncdcLTF.setTextField( state.getNcdc() ); - _stateFipsLTF.setTextField( state.getStateFips() ); - } - } - - private void clearDataInputPanel() - { - _stateLTF.setTextField( "" ); - _countryFipsLTF.setTextField( "" ); - _nameLTF.setTextField( "" ); - _ncdcLTF.setTextField( "" ); - _stateFipsLTF.setTextField( "" ); - } - - private boolean saveState() - { - boolean saved = false; - - State state = new State(); - - state.setState( _stateLTF.getTextFieldText() ); - state.setCountryFips( _countryFipsLTF.getTextFieldText() ); - state.setName( _nameLTF.getTextFieldText() ); - state.setNcdc( _ncdcLTF.getTextFieldText() ); - state.setStateFips( _stateFipsLTF.getTextFieldText() ); - - saved = _dataMgr.saveState( state ); - - updateJTable(); - - return saved; - } - - private void deleteState() - { - State state = null; - List selectedRowsData = _stateTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseStateJTableRowData rowData = (ArcBaseStateJTableRowData) selectedRowsData.get( 0 ); - state = (State) _stateRowDataToStateMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + state.keyString(), "Delete State" ) ) - { - _dataMgr.deleteStateFromDataBase( state ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a State", "Delete State" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _stateTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveState(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveState() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteState(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - State state = null; - - ArcBaseStateJTableRowData rowData = (ArcBaseStateJTableRowData) _stateTableManager.getSelectedRowsData().get( 0 ); - state = (State) _stateRowDataToStateMap.get( rowData ); - populateDataInputPanel( state ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - StateEditor stateEditor = new StateEditor( frame, dataMgr ); - stateEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/StatusBar.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/StatusBar.java deleted file mode 100644 index 24d49f5f31..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/StatusBar.java +++ /dev/null @@ -1,23 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Dimension; - -import javax.swing.JLabel; - - public class StatusBar extends JLabel - { - - /** Creates a new instance of StatusBar */ - public StatusBar() - { - super(); - super.setPreferredSize(new Dimension(100, 16)); - setMessage("Ready"); - } - - public void setMessage(String message) - { - setText(" "+message); - setAlignmentY( JLabel.RIGHT_ALIGNMENT ); - } - } \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/WfoHsaEditor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/WfoHsaEditor.java deleted file mode 100644 index 08c0f8082a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/gui/WfoHsaEditor.java +++ /dev/null @@ -1,284 +0,0 @@ -package ohd.hseb.raxbase.gui; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.WfoHsa; -import ohd.hseb.raxbase.table.ArcBaseWfoHsaJTableRowData; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.LabeledTextField; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class WfoHsaEditor extends JDialog -{ - private Container _dialogContentPane = getContentPane(); - - private RaxBaseDataMgr _dataMgr = null; - -// JTable variables - private JTableManager _wfoHsaTableManager = null; - private List _wfoHsaColumnDescriptorList = null; - private List _wfoHsaRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JPanel _wfoHsaSelectionPanel = new JPanel( new GridBagLayout() ); - - private JPanel _selectedItemPanel = new JPanel( new GridBagLayout() ); - private LabeledTextField _wfoHsaLTF = new LabeledTextField( "WfoHsa:", "", "WFO identifier (upper case)", 4 ); - - private JPanel _buttonPanel = new JPanel( new GridBagLayout() ); - private JButton _saveAndCloseButton = new JButton( "Save and Close" ); - private JButton _saveButton = new JButton( "Save" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _deleteButton = new JButton( "Delete" ); - - private Map _wfoHsaRowDataToWfoHsaMap = null; - - public WfoHsaEditor( JFrame frame, RaxBaseDataMgr dataMgr ) - { - super( frame, "WfoHsa Editor", true ); - _dataMgr = dataMgr; - } - - public void displayGUI() - { - setPreferredSize( new Dimension ( 240, 400 ) ); - initGUI(); - } - - private void initGUI() - { - setLayout( new GridBagLayout() ); - initWfoHsaSelectionPanel(); - initSelectedItemPanel(); - initButtonPanel(); - initFrameComponents(); - initHashMaps(); - addListeners(); - pack(); - setVisible( true ); - } - - private void initWfoHsaSelectionPanel() - { - initJTable(); - } - - private void initFrameComponents() - { -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _dialogContentPane, _wfoHsaSelectionPanel, 0, 0, 4, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _selectedItemPanel, 0, 21, 4, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _dialogContentPane, _buttonPanel, 0, 22, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - } - private void initButtonPanel() - { -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveAndCloseButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 1, 1, 1, 1, GridBagConstraints.NONE ); - } - - private void initSelectedItemPanel() - { - _selectedItemPanel.setBorder( BorderFactory.createTitledBorder( "Info for Selected WfoHsa" ) ); - JPanel vPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _selectedItemPanel, _wfoHsaLTF, 0, 0, 1, 1, GridBagConstraints.NONE ); - } - - - private void initHashMaps() - { - _wfoHsaRowDataToWfoHsaMap = _dataMgr.getWfoHsaRowDataToWfoHsaMap(); - } - - private void initJTable() - { - _wfoHsaRowDataList = _dataMgr.getWfoHsaRowDataList(); - setCEColumnDescriptorList(); - _wfoHsaTableManager = new ComplexJTableManager( _wfoHsaColumnDescriptorList, _wfoHsaRowDataList, ListSelectionModel.SINGLE_SELECTION ); - String columnsSelected[] = _wfoHsaTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _wfoHsaTableManager.setDisplayableColumns( columnsSelected, true, true ); - _tableScrollPane = _wfoHsaTableManager.getJScrollPane(); - _tableScrollPane.setPreferredSize( new Dimension( 90, 100 ) ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _wfoHsaSelectionPanel, _tableScrollPane, 0, 1, 1, 1, 1, 1, GridBagConstraints.VERTICAL ); - } - - private void updateJTable() - { - _wfoHsaRowDataList = _dataMgr.getWfoHsaRowDataList(); - _wfoHsaTableManager.setChangedAllRowDataList( _wfoHsaRowDataList ); - _wfoHsaTableManager.refreshDisplay(); - } - - private void setCEColumnDescriptorList() - { - _wfoHsaColumnDescriptorList = new ArrayList(); - - _wfoHsaColumnDescriptorList.add(new JTableColumnDescriptor( "WfoHsa", true, 70, "center" ) ); - } - - private void populateDataInputPanel( WfoHsa wfoHsa ) - { - if ( wfoHsa != null ) - { - _wfoHsaLTF.setTextField( wfoHsa.getWfoHsa() ); - } - } - - private void clearDataInputPanel() - { - _wfoHsaLTF.setTextField( "" ); - } - - private boolean saveWfoHsa() - { - boolean saved = false; - - WfoHsa wfoHsa = new WfoHsa(); - - wfoHsa.setWfoHsa( _wfoHsaLTF.getTextFieldText() ); - - saved = _dataMgr.saveWfoHsa( wfoHsa ); - - updateJTable(); - - return saved; - } - - private void deleteWfoHsa() - { - WfoHsa wfoHsa = null; - List selectedRowsData = _wfoHsaTableManager.getSelectedRowsData(); - - if ( ! selectedRowsData.isEmpty() ) - { - ArcBaseWfoHsaJTableRowData rowData = (ArcBaseWfoHsaJTableRowData) selectedRowsData.get( 0 ); - wfoHsa = (WfoHsa) _wfoHsaRowDataToWfoHsaMap.get( rowData ); - if ( DialogHelper.displayConfirmDialog( this, "Are you sure you want to delete " + wfoHsa.keyString(), "Delete WfoHsa" ) ) - { - _dataMgr.deleteWfoHsaFromDataBase( wfoHsa ); - clearDataInputPanel(); - updateJTable(); - } - } - else - { - DialogHelper.displayErrorDialog( this, "You must select a WfoHsa", "Delete WfoHsa" ); - } - } - - private void addListeners() - { - WindowCloserListener windowCloser = new WindowCloserListener(); - - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - _wfoHsaTableManager.addTableListener( new MCETableListener() ); - - _saveButton.addActionListener( new SaveButtonListener() ); - _saveAndCloseButton.addActionListener( new SaveAndCloseButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveWfoHsa(); - } - } - - private class SaveAndCloseButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - if ( saveWfoHsa() ) // If the save is successful, close the window - { - closeWindow(); - } - } - } - - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - deleteWfoHsa(); - } - } - - private class MCETableListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent e ) - { - if ( e.getValueIsAdjusting() ) - { - WfoHsa wfoHsa = null; - - ArcBaseWfoHsaJTableRowData rowData = (ArcBaseWfoHsaJTableRowData) _wfoHsaTableManager.getSelectedRowsData().get( 0 ); - wfoHsa = (WfoHsa) _wfoHsaRowDataToWfoHsaMap.get( rowData ); - populateDataInputPanel( wfoHsa ); - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - /******************** - Purpose: Exits the program gracefully - *********************/ - { - this.dispose(); - } - - public static void main( String args[] ) - { - JFrame frame = new JFrame(); - frame.setSize( new Dimension( 1024, 768 ) ); - RaxBaseDataMgr dataMgr = new RaxBaseDataMgr( "jdbc:postgresql://ax2:5432/adb_ob72krf?user=pguser" ); - - WfoHsaEditor wfoHsaEditor = new WfoHsaEditor( frame, dataMgr ); - wfoHsaEditor.displayGUI(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Agency.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Agency.java deleted file mode 100644 index b24dd640c2..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Agency.java +++ /dev/null @@ -1,85 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.AgencyRecord; - -public class Agency -{ - private String _agCode = null; - private String _agLoc = null; - private String _des = null; - - public Agency(){} - - public Agency( Agency agency ) - { - setAgCode( agency.getAgCode() ); - setAgLoc( agency.getAgLoc() ); - setDes( agency.getDes() ); - } - - public Agency( AgencyRecord record ) - { - setAgCode( record.getAgcode() ); - setAgLoc( record.getAgloc() ); - setDes( record.getDes() ); - } - - public static Agency getAgency( AgencyRecord record ) - { - return new Agency( record ); - } - - public static AgencyRecord getAgencyRecord( Agency agency ) - { - AgencyRecord record = new AgencyRecord(); - - record.setAgcode( agency.getAgCode() ); - record.setAgloc( agency.getAgLoc() ); - record.setDes( agency.getDes() ); - - return record; - } - - public String toString() - { - return "AgCode = " + _agCode + - " | AgLoc = " + _agLoc + - " | Des = " + _des; - } - - public String keyString() - { - return "AgCode = " + _agCode + - " | AgLoc = " + _agLoc; - } - - public void setAgCode( String agCode ) - { - _agCode = agCode; - } - - public String getAgCode() - { - return _agCode; - } - - public void setAgLoc( String agLoc ) - { - _agLoc = agLoc; - } - - public String getAgLoc() - { - return _agLoc; - } - - public void setDes( String des ) - { - _des = des; - } - - public String getDes() - { - return _des; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Average.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Average.java deleted file mode 100644 index 7a22021db1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Average.java +++ /dev/null @@ -1,353 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.AvgRecord; - -public class Average -{ - private String _lid = null; - private String _pe = null; - private String _dur = null; - private short _idur; - private String _ts = null; - private String _extremum = null; - private String _p = null; - private double _jan; - private double _feb; - private double _mar; - private double _apr; - private double _may; - private double _jun; - private double _jul; - private double _aug; - private double _sep; - private double _oct; - private double _nov; - private double _dec; - private long _calcdate; - - public Average(){} - - public Average( Average average ) - { - _lid = average.getLid(); - _pe = average.getPe(); - _dur = average.getDur(); - _idur = average.getIdur(); - _ts = average.getTs(); - _extremum = average.getExtremum(); - _p = average.getP(); - _jan = average.getJan(); - _feb = average.getFeb(); - _mar = average.getMar(); - _apr = average.getApr(); - _may = average.getMay(); - _jun = average.getJun(); - _jul = average.getJul(); - _aug = average.getAug(); - _sep = average.getSep(); - _oct = average.getOct(); - _nov = average.getNov(); - _dec = average.getDec(); - _calcdate = average.getCalcdate(); - } - - public Average( AvgRecord averageRecord ) - { - _lid = averageRecord.getLid(); - _pe = PEManager.getPEFromPe1Pe2( averageRecord.getPe1(), averageRecord.getPe2() ); - _dur = averageRecord.getDur(); - _idur = averageRecord.getIdur(); - _ts = TSManager.getTSFromTandS( averageRecord.getT(), averageRecord.getS() ); - _extremum = averageRecord.getE(); - _p = averageRecord.getP(); - _jan = averageRecord.getJan(); - _feb = averageRecord.getFeb(); - _mar = averageRecord.getMar(); - _apr = averageRecord.getApr(); - _may = averageRecord.getMay(); - _jun = averageRecord.getJun(); - _jul = averageRecord.getJul(); - _aug = averageRecord.getAug(); - _sep = averageRecord.getSep(); - _oct = averageRecord.getOct(); - _nov = averageRecord.getNov(); - _dec = averageRecord.getDec(); - _calcdate = averageRecord.getCalcdate(); - } - - public static Average getAverage( AvgRecord record ) - { - return ( new Average( record ) ); - } - - public static AvgRecord getAverageRecord( Average average ) - { - AvgRecord averageRecord = new AvgRecord(); - - averageRecord.setLid( average.getLid() ); - averageRecord.setPe1( PEManager.getPe1FromPE( average.getPe() ) ); - averageRecord.setPe2( PEManager.getPe2FromPE( average.getPe() ) ); - averageRecord.setDur( average.getDur() ); - averageRecord.setIdur( average.getIdur() ); - averageRecord.setT( TSManager.getTFromTS( average.getTs() ) ); - averageRecord.setS( TSManager.getSFromTS( average.getTs() ) ); - averageRecord.setE( average.getExtremum() ); - averageRecord.setP( average.getP() ); - averageRecord.setJan( average.getJan() ); - averageRecord.setFeb( average.getFeb() ); - averageRecord.setMar( average.getMar() ); - averageRecord.setApr( average.getApr() ); - averageRecord.setMay( average.getMay() ); - averageRecord.setJun( average.getJun() ); - averageRecord.setJul( average.getJul() ); - averageRecord.setAug( average.getAug() ); - averageRecord.setSep( average.getSep() ); - averageRecord.setOct( average.getOct() ); - averageRecord.setNov( average.getNov() ); - averageRecord.setDec( average.getDec() ); - averageRecord.setCalcdate( average.getCalcdate() ); - - return averageRecord; - } - - public String toString() - { - String returnString = "LID = " + _lid + " | PE = " + _pe + " | Dur = " + _dur + " | IDur = " + _idur + - " | TS = " + _ts + " | Extremum = " + _extremum + " | P = " + _p + - " | Jan = " + _jan + " | Feb = " + _feb + " | Mar = " + _mar + - " | Apr = " + _apr + " | May = " + _may + " | Jun = " + _jun + - " | Jul = " + _jul + " | Aug = " + _aug + " | Sep = " + _sep + - " | Oct = " + _oct + " | Nov = " + _nov + " | Dec = " + _dec + - " | CalcDate = " + _calcdate; - - return returnString; - } - - public String keyString() - { - String keyString = "LID = " + getKeyValue( _lid ) + " | PE = " + getKeyValue( _pe ) + " | Dur = " + getKeyValue( _dur ) + - " | IDur = " + getKeyValue( _idur ) + " | TS = " + getKeyValue( _ts ) + " | Extremum = " + getKeyValue( _extremum ) + - " | P = " + getKeyValue( _p ); - - return keyString; - } - - private String getKeyValue( String str ) - { - String returnValue = "NULL"; - - if ( str != null ) - { - returnValue = str; - } - - return returnValue; - } - - private String getKeyValue( short number ) - { - return ( getKeyValue( number + "" ) ); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( String dur ) - { - _dur = dur; - } - - public String getDur() - { - return _dur; - } - - public void setIdur( short idur ) - { - _idur = idur; - } - - public short getIdur() - { - return _idur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setP( String p ) - { - _p = p; - } - - public String getP() - { - return _p; - } - - public void setJan( double jan ) - { - _jan = jan; - } - - public double getJan() - { - return _jan; - } - - public void setFeb( double feb ) - { - _feb = feb; - } - - public double getFeb() - { - return _feb; - } - - public void setMar( double mar ) - { - _mar = mar; - } - - public double getMar() - { - return _mar; - } - - public void setApr( double apr ) - { - _apr = apr; - } - - public double getApr() - { - return _apr; - } - - public void setMay( double may ) - { - _may = may; - } - - public double getMay() - { - return _may; - } - - public void setJun( double jun ) - { - _jun = jun; - } - - public double getJun() - { - return _jun; - } - - public void setJul( double jul ) - { - _jul = jul; - } - - public double getJul() - { - return _jul; - } - - public void setAug( double aug ) - { - _aug = aug; - } - - public double getAug() - { - return _aug; - } - - public void setSep( double sep ) - { - _sep = sep; - } - - public double getSep() - { - return _sep; - } - - public void setOct( double oct ) - { - _oct = oct; - } - - public double getOct() - { - return _oct; - } - - public void setNov( double nov ) - { - _nov = nov; - } - - public double getNov() - { - return _nov; - } - - public void setDec( double dec ) - { - _dec = dec; - } - - public double getDec() - { - return _dec; - } - - public void setCalcdate( long calcdate ) - { - _calcdate = calcdate; - } - - public long getCalcdate() - { - return _calcdate; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Counties.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Counties.java deleted file mode 100644 index c8837a9349..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Counties.java +++ /dev/null @@ -1,132 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.CountiesRecord; - -public class Counties -{ - private String _county = null; - private String _state = null; - private String _countryFips = null; - private String _countyFips = null; - private String _wfo = null; - private String _zon = null; - - public Counties(){} - - public Counties( Counties counties ) - { - setCounty( counties.getCounty() ); - setState( counties.getState() ); - setCountryFips( counties.getCountryFips() ); - setCountyFips( counties.getCountyFips() ); - setWfo( counties.getWfo() ); - setZon( counties.getZon() ); - } - - public Counties( CountiesRecord countiesRecord ) - { - setCounty( countiesRecord.getCounty() ); - setState( countiesRecord.getState() ); - setCountryFips( countiesRecord.getCountryfips() ); - setCountyFips( countiesRecord.getCountyfips() ); - setWfo( countiesRecord.getWfo() ); - setZon( countiesRecord.getZon() ); - } - - public static Counties getCounties( CountiesRecord record ) - { - return new Counties( record ); - } - - public static CountiesRecord getCountiesRecord( Counties counties ) - { - CountiesRecord record = new CountiesRecord(); - - record.setCounty( counties.getCounty() ); - record.setState( counties.getState() ); - record.setCountryfips( counties.getCountryFips() ); - record.setCountyfips( counties.getCountyFips() ); - record.setWfo( counties.getWfo() ); - record.setZon( counties.getZon() ); - - return record; - } - - public String toString() - { - return "County = " + _county + - " | State = " + _state + - " | CountryFips = " + _countryFips + - " | CountyFips = " + _countyFips + - " | Wfo = " + _wfo + - " | Zon = " + _zon; - } - - public String keyString() - { - return "CountryFips = " + _countryFips + - " | State = " + _state + - " | CountyFips = " + _countyFips; - } - - public String getCounty() - { - return _county; - } - - public void setCounty(String county) - { - _county = county ; - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - _state = state ; - } - - public String getCountryFips() - { - return _countryFips; - } - - public void setCountryFips(String countryfips) - { - _countryFips = countryfips ; - } - - public String getCountyFips() - { - return _countyFips; - } - - public void setCountyFips(String countyfips) - { - _countyFips = countyfips ; - } - - public String getWfo() - { - return _wfo; - } - - public void setWfo(String wfo) - { - _wfo = wfo ; - } - - public String getZon() - { - return _zon; - } - - public void setZon(String zon) - { - _zon = zon ; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Country.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Country.java deleted file mode 100644 index e400bde447..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Country.java +++ /dev/null @@ -1,64 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.CountryRecord; - -public class Country -{ - private String _country = null; - private String _countryFips = null; - - - public Country(){} - - public Country( Country country ) - { - setCountry( country.getCountry() ); - setCountryFips( country.getCountryFips() ); - } - - public Country( CountryRecord record ) - { - setCountry( record.getCountry() ); - setCountryFips( record.getCountryfips() ); - } - - public static Country getCountry( CountryRecord record ) - { - return ( new Country( record ) ); - } - - public static CountryRecord getCountryRecord( Country country ) - { - CountryRecord record = new CountryRecord(); - - record.setCountry( country.getCountry() ); - record.setCountryfips( country.getCountryFips() ); - - return record; - } - - public String keyString() - { - return "Country = " + _country; - } - - public void setCountry( String country ) - { - _country = country; - } - - public String getCountry() - { - return _country; - } - - public void setCountryFips( String countryFips ) - { - _countryFips = countryFips; - } - - public String getCountryFips() - { - return _countryFips; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc2.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc2.java deleted file mode 100644 index 4fdcf90f5a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc2.java +++ /dev/null @@ -1,81 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.Huc2Record; - -public class Huc2 -{ - private String _code2 = null; - private String _code12 = null; - private String _desreg = null; - - public Huc2(){} - - public Huc2( Huc2 huc2 ) - { - setCode2( huc2.getCode2() ); - setCode12( huc2.getCode12() ); - setDesreg( huc2.getDesreg() ); - } - - public Huc2( Huc2Record huc2Record ) - { - setCode2( huc2Record.getCode2() ); - setCode12( huc2Record.getCode12() ); - setDesreg( huc2Record.getDesreg() ); - } - - public static Huc2 getHuc2( Huc2Record record ) - { - return new Huc2( record ); - } - - public static Huc2Record getHuc2Record( Huc2 huc2 ) - { - Huc2Record record = new Huc2Record(); - - record.setCode2( huc2.getCode2() ); - record.setCode12( huc2.getCode12() ); - record.setDesreg( huc2.getDesreg() ); - - return record; - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code2 = " + _code2 + - " | Desreg = " + _desreg; - } - - public String keyString() - { - return "Code12 = " + _code12; - } - - public void setCode2( String code2 ) - { - _code2 = code2; - } - public String getCode2() - { - return _code2; - } - public void setCode12( String code12 ) - { - _code12 = code12; - } - public String getCode12() - { - return _code12; - } - public void setDesreg( String desreg ) - { - _desreg = desreg; - } - public String getDesreg() - { - return _desreg; - } - - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc4.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc4.java deleted file mode 100644 index b3ccb3da8b..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc4.java +++ /dev/null @@ -1,97 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.Huc4Record; - -public class Huc4 -{ - private String _code4 = null; - private String _code12 = null; - private String _code34 = null; - private String _dessubreg = null; - - public Huc4(){} - - public Huc4( Huc4 huc4 ) - { - setCode4( huc4.getCode4() ); - setCode12( huc4.getCode12() ); - setCode34( huc4.getCode34() ); - setDessubreg( huc4.getDessubreg() ); - } - - public Huc4( Huc4Record huc4Record ) - { - setCode4( huc4Record.getCode4() ); - setCode12( huc4Record.getCode12() ); - setCode34( huc4Record.getCode34() ); - setDessubreg( huc4Record.getDessubreg() ); - } - - public static Huc4 getHuc4( Huc4Record record ) - { - return new Huc4( record ); - } - - public static Huc4Record getHuc4Record( Huc4 huc4 ) - { - Huc4Record record = new Huc4Record(); - - record.setCode4( huc4.getCode4() ); - record.setCode12( huc4.getCode12() ); - record.setCode34( huc4.getCode34() ); - record.setDessubreg( huc4.getDessubreg() ); - - return record; - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code4 = " + _code4 + - " | Code34 = " + _code34 + - " | Desreg = " + _dessubreg; - } - - public String keyString() - { - return "Code12 = " + _code12 + " | Code34 = " + _code34; - } - - public void setCode4( String code4 ) - { - _code4 = code4; - } - public String getCode4() - { - return _code4; - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - public String getCode12() - { - return _code12; - } - - public void setCode34( String code34 ) - { - _code34 = code34; - } - - public String getCode34() - { - return _code34; - } - - public void setDessubreg( String dessubreg ) - { - _dessubreg = dessubreg; - } - - public String getDessubreg() - { - return _dessubreg; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc6.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc6.java deleted file mode 100644 index 6904aaa6ed..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc6.java +++ /dev/null @@ -1,113 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.Huc6Record; - -public class Huc6 -{ - private String _code6 = null; - private String _code12 = null; - private String _code34 = null; - private String _code56 = null; - private String _desacct = null; - - public Huc6(){} - - public Huc6( Huc6 huc6 ) - { - setCode6( huc6.getCode6() ); - setCode12( huc6.getCode12() ); - setCode34( huc6.getCode34() ); - setCode56( huc6.getCode56() ); - setDesacct( huc6.getDesacct() ); - } - - public Huc6( Huc6Record huc6Record ) - { - setCode6( huc6Record.getCode6() ); - setCode12( huc6Record.getCode12() ); - setCode34( huc6Record.getCode34() ); - setCode56( huc6Record.getCode56() ); - setDesacct( huc6Record.getDesacct() ); - } - - public static Huc6 getHuc6( Huc6Record record ) - { - return new Huc6( record ); - } - - public static Huc6Record getHuc6Record( Huc6 huc6 ) - { - Huc6Record record = new Huc6Record(); - - record.setCode6( huc6.getCode6() ); - record.setCode12( huc6.getCode12() ); - record.setCode34( huc6.getCode34() ); - record.setCode56( huc6.getCode56() ); - record.setDesacct( huc6.getDesacct() ); - - return record; - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code6 = " + _code6 + - " | Code34 = " + _code34 + - " | Code56 = " + _code56 + - " | Desreg = " + getDesacct(); - } - - public String keyString() - { - return "Code12 = " + _code12 + " | Code34 = " + _code34 + " | Code56 = " + _code56; - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - public String getCode12() - { - return _code12; - } - - public void setCode34( String code34 ) - { - _code34 = code34; - } - - public String getCode34() - { - return _code34; - } - - public void setCode56( String code56 ) - { - _code56 = code56; - } - - public String getCode56() - { - return _code56; - } - - public void setCode6( String code6 ) - { - _code6 = code6; - } - - public String getCode6() - { - return _code6; - } - - public void setDesacct( String desacct ) - { - this._desacct = desacct; - } - - public String getDesacct() - { - return _desacct; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc8.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc8.java deleted file mode 100644 index 86876f3240..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Huc8.java +++ /dev/null @@ -1,128 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.Huc8Record; - -public class Huc8 -{ - private String _code8 = null; - private String _code12 = null; - private String _code34 = null; - private String _code56 = null; - private String _code78 = null; - private String _descat = null; - - public Huc8(){} - - public Huc8( Huc8 huc8 ) - { - setCode8( huc8.getCode8() ); - setCode12( huc8.getCode12() ); - setCode34( huc8.getCode34() ); - setCode56( huc8.getCode56() ); - setCode78( huc8.getCode78() ); - setDescat( huc8.getDescat() ); - } - - public Huc8( Huc8Record huc8Record ) - { - setCode8( huc8Record.getCode8() ); - setCode12( huc8Record.getCode12() ); - setCode34( huc8Record.getCode34() ); - setCode56( huc8Record.getCode56() ); - setCode78( huc8Record.getCode78() ); - setDescat( huc8Record.getDescat() ); - } - - public static Huc8 getHuc8( Huc8Record record ) - { - return new Huc8( record ); - } - - public static Huc8Record getHuc8Record( Huc8 huc8 ) - { - Huc8Record record = new Huc8Record(); - - record.setCode8( huc8.getCode8() ); - record.setCode12( huc8.getCode12() ); - record.setCode34( huc8.getCode34() ); - record.setCode56( huc8.getCode56() ); - record.setCode78( huc8.getCode78() ); - record.setDescat( huc8.getDescat() ); - - return record; - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code8 = " + _code8 + - " | Code34 = " + _code34 + - " | Code56 = " + _code56 + - " | Code78 = " + _code78 + - " | Descat = " + _descat; - } - - public String keyString() - { - return "Code12 = " + _code12 + " | Code34 = " + _code34 + " | Code56 = " + _code56 + " | Code78 = " + _code78; - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - public String getCode12() - { - return _code12; - } - - public void setCode34( String code34 ) - { - _code34 = code34; - } - - public String getCode34() - { - return _code34; - } - - public void setCode56( String code56 ) - { - _code56 = code56; - } - - public String getCode56() - { - return _code56; - } - - public void setCode78( String code78 ) - { - _code78 = code78; - } - - public String getCode78() - { - return _code78; - } - - public void setDescat( String descat ) - { - _descat = descat; - } - - public String getDescat() - { - return _descat; - } - - public void setCode8( String code8 ) - { - _code8 = code8; - } - - public String getCode8() - { - return _code8; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ModCtrl.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ModCtrl.java deleted file mode 100644 index 0b0c1fb860..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ModCtrl.java +++ /dev/null @@ -1,122 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.ModctrlRecord; - -public class ModCtrl -{ - private String _modName = null; - private boolean _load = false; - private boolean _fetchOper = false; - private boolean _fetchSpin = false; - - public ModCtrl(){} - - public ModCtrl( ModCtrl modCtrl ) - { - setModName( modCtrl.getModName() ); - setLoad( modCtrl.isLoad() ); - setFetchOper( modCtrl.isFetchOper() ); - setFetchSpin( modCtrl.isFetchSpin() ); - } - - public ModCtrl( ModctrlRecord modCtrlRecord ) - { - setModName( modCtrlRecord.getMod_name() ); - setLoad( getBooleanFromInt( modCtrlRecord.getLoad() ) ); - setFetchOper( getBooleanFromInt( modCtrlRecord.getFetch_oper() ) ); - setFetchSpin( getBooleanFromInt( modCtrlRecord.getFetch_spin() ) ); - } - - public static ModCtrl getModCtrl( ModctrlRecord modCtrlRecord ) - { - return ( new ModCtrl( modCtrlRecord ) ); - } - - public static ModctrlRecord getModCtrlRecord( ModCtrl modCtrl ) - { - ModctrlRecord record = new ModctrlRecord(); - - record.setMod_name( modCtrl.getModName() ); - record.setLoad( getIntFromBoolean( modCtrl.isLoad() ) ); - record.setFetch_oper( getIntFromBoolean( modCtrl.isFetchOper() ) ); - record.setFetch_spin( getIntFromBoolean( modCtrl.isFetchSpin() ) ); - - return record; - } - - public String toString() - { - return "ModName = " + _modName + - " | Load = " + _load + - " | FetchOper = " + _fetchOper + - " | FetchSpin = " + _fetchSpin; - } - - public String keyString() - { - return "ModName = " + _modName; - } - - private boolean getBooleanFromInt( int intValue ) - { - boolean booleanValue = false; - - if ( intValue == 1 ) - { - booleanValue = true; - } - return booleanValue; - } - - private static int getIntFromBoolean( boolean booleanValue ) - { - int intValue = 0; - - if ( booleanValue == true ) - { - intValue = 1; - } - - return intValue; - } - - public void setModName( String modName ) - { - _modName = modName; - } - - public String getModName() - { - return _modName; - } - - public void setLoad( boolean load ) - { - _load = load; - } - - public boolean isLoad() - { - return _load; - } - - public void setFetchOper( boolean fetchOper ) - { - _fetchOper = fetchOper; - } - - public boolean isFetchOper() - { - return _fetchOper; - } - - public void setFetchSpin( boolean fetchSpin ) - { - _fetchSpin = fetchSpin; - } - - public boolean isFetchSpin() - { - return _fetchSpin; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Prod.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Prod.java deleted file mode 100644 index 1758f0b06e..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Prod.java +++ /dev/null @@ -1,146 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.ProdRecord; - -public class Prod -{ - private static final short MISSING = -9999; - - private String _id = null; - private int _pmax = MISSING; - private int _pap = MISSING; - private int _err = MISSING; - private String _gra = null; - private String _pr1 = null; - private String _net = null; - - public Prod(){} - - public Prod( Prod prod ) - { - setId( prod.getId() ); - setPmax( prod.getPmax() ); - setPap( prod.getPap() ); - setErr( prod.getErr() ); - setGra( prod.getGra() ); - setPr1( prod.getPr1() ); - setNet( prod.getNet() ); - } - - public Prod( ProdRecord prodRecord ) - { - setId( prodRecord.getId() ); - setPmax( prodRecord.getPmax() ); - setPap( prodRecord.getPap() ); - setErr( prodRecord.getErr() ); - setGra( prodRecord.getGra() ); - setPr1( prodRecord.getPr1() ); - setNet( prodRecord.getNet() ); - } - - public static Prod getProd( ProdRecord prodRecord ) - { - return new Prod( prodRecord ); - } - - public static ProdRecord getProdRecord( Prod prod ) - { - ProdRecord record = new ProdRecord(); - - record.setId( prod.getId() ); - record.setPmax( prod.getPmax() ); - record.setPap( prod.getPap() ); - record.setErr( prod.getErr() ); - record.setGra( prod.getGra() ); - record.setPr1( prod.getPr1() ); - record.setNet( prod.getNet() ); - - return record; - } - - public String toString() - { - return "Id = " + _id + - " | Pmax = " + _pmax + - " | Pap = " + _pap + - " | Err = " + _err + - " | Gra = " + _gra + - " | Pr1 = " + _pr1 + - " | Net = " + _net; - } - - public String keyString() - { - return "Id = " + _id; - } - - public String getId() - { - return _id; - } - - public void setId(String id) - { - _id = id ; - } - - public int getPmax() - { - return _pmax; - } - - public void setPmax(int pmax) - { - _pmax = pmax ; - } - - public int getPap() - { - return _pap; - } - - public void setPap(int pap) - { - _pap = pap ; - } - - public int getErr() - { - return _err; - } - - public void setErr(int err) - { - _err = err ; - } - - public String getGra() - { - return _gra; - } - - public void setGra(String gra) - { - _gra = gra ; - } - - public String getPr1() - { - return _pr1; - } - - public void setPr1(String pr1) - { - _pr1 = pr1 ; - } - - public String getNet() - { - return _net; - } - - public void setNet(String net) - { - _net = net ; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxAdjustFactor.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxAdjustFactor.java deleted file mode 100644 index 7dd1ab0973..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxAdjustFactor.java +++ /dev/null @@ -1,173 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.RaxAdjustFactorRecord; - -public class RaxAdjustFactor -{ - private String _lid; - private String _pe; - private String _dur; - private short _idur; - private String _ts; - private String _extremum; - private long _beginDate; - private double _divisor; - private double _base; - private double _multiplier; - private double _adder; - - public RaxAdjustFactor(){} - - public RaxAdjustFactor( RaxAdjustFactorRecord record ) - { - setLid( record.getLid() ); - setPe( record.getPe1() + record.getPe2() ); - setDur( record.getDur() ); - setIdur( record.getIdur() ); - setTs( record.getT() + record.getS() ); - setExtremum( record.getE() ); - setBeginDate( record.getBegin_date() ); - setDivisor( record.getDivisor() ); - setBase( record.getBase() ); - setMultiplier( record.getMultiplier() ); - setAdder( record.getAdder() ); - } - - public RaxAdjustFactor( RaxAdjustFactor raxAdjustFactor ) - { - setLid( raxAdjustFactor.getLid() ); - setPe( raxAdjustFactor.getPe() ); - setDur( raxAdjustFactor.getDur() ); - setIdur( raxAdjustFactor.getIdur() ); - setTs( raxAdjustFactor.getTs() ); - setExtremum( raxAdjustFactor.getExtremum() ); - setBeginDate( raxAdjustFactor.getBeginDate() ); - setDivisor( raxAdjustFactor.getDivisor() ); - setBase( raxAdjustFactor.getBase() ); - setMultiplier( raxAdjustFactor.getMultiplier() ); - setAdder( raxAdjustFactor.getAdder() ); - } - - public static RaxAdjustFactor getRaxAdjustFactor( RaxAdjustFactorRecord record ) - { - return ( new RaxAdjustFactor( record ) ); - } - - public static RaxAdjustFactorRecord getRaxAdjustFactorRecord( RaxAdjustFactor raxAdjustFactor ) - { - RaxAdjustFactorRecord record = new RaxAdjustFactorRecord(); - - record.setLid( raxAdjustFactor.getLid() ); - record.setPe1( PEManager.getPe1FromPE( raxAdjustFactor.getPe() ) ); - record.setPe2( PEManager.getPe2FromPE( raxAdjustFactor.getPe() ) ); - record.setDur( raxAdjustFactor.getDur() ); - record.setIdur( raxAdjustFactor.getIdur() ); - record.setT( TSManager.getTFromTS( raxAdjustFactor.getTs() ) ); - record.setS( TSManager.getSFromTS( raxAdjustFactor.getTs() ) ); - record.setE( raxAdjustFactor.getExtremum() ); - record.setBegin_date( raxAdjustFactor.getBeginDate() ); - record.setDivisor( raxAdjustFactor.getDivisor() ); - record.setBase( raxAdjustFactor.getBase() ); - record.setMultiplier( raxAdjustFactor.getMultiplier() ); - record.setAdder( raxAdjustFactor.getAdder() ); - - return record; - } - - public String keyString() - { - return "Lid = " + _lid + " | Pe = " + _pe + " | Dur = " + _dur + " | IDur = " + _idur + " | Ts = " + _ts + " | Extremum = " + _extremum; - } - - - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setPe( String pe ) - { - _pe = pe; - } - public String getPe() - { - return _pe; - } - public void setDur( String dur ) - { - _dur = dur; - } - public String getDur() - { - return _dur; - } - public void setIdur( short idur ) - { - _idur = idur; - } - public short getIdur() - { - return _idur; - } - public void setTs( String ts ) - { - _ts = ts; - } - public String getTs() - { - return _ts; - } - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - public String getExtremum() - { - return _extremum; - } - public void setBeginDate( long beginDate ) - { - _beginDate = beginDate; - } - public long getBeginDate() - { - return _beginDate; - } - public void setDivisor( double divisor ) - { - _divisor = divisor; - } - public double getDivisor() - { - return _divisor; - } - public void setBase( double base ) - { - _base = base; - } - public double getBase() - { - return _base; - } - public void setMultiplier( double multiplier ) - { - _multiplier = multiplier; - } - public double getMultiplier() - { - return _multiplier; - } - public void setAdder( double adder ) - { - _adder = adder; - } - public double getAdder() - { - return _adder; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxCrest.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxCrest.java deleted file mode 100644 index 4c928b9ff8..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxCrest.java +++ /dev/null @@ -1,179 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxdb.generated.RaxCrestRecord; - -public class RaxCrest -{ - private static final short MISSING = -9999; - - private String _lid = null; - private long _dateCrest = MISSING; - private String _crestDateTime = null; - private double _stage = MISSING; - private String _stgQual = null; - private double _flow = MISSING; - private String _flowQual = null; - private String _hw = null; - private String _jam = null; - private String _oldDatum = null; - private String _prelim = null; - - public RaxCrest(){} - - public RaxCrest( RaxCrest raxCrest ) - { - setLid( raxCrest.getLid() ); - setDateCrest( raxCrest.getDateCrest() ); - setCrestDateTime( raxCrest.getCrestDateTime() ); - setStage( raxCrest.getStage() ); - setStgQual( raxCrest.getStgQual() ); - setFlow( raxCrest.getFlow() ); - setFlowQual( raxCrest.getFlowQual() ); - setHw( raxCrest.getHw() ); - setJam( raxCrest.getJam() ); - setOldDatum( raxCrest.getOldDatum() ); - setPrelim( raxCrest.getPrelim() ); - } - - public RaxCrest( RaxCrestRecord raxCrestRecord ) - { - setLid( raxCrestRecord.getLid() ); - setDateCrest( raxCrestRecord.getDatecrst() ); - setCrestDateTime( raxCrestRecord.getCrstdatetime() ); - setStage( raxCrestRecord.getStage() ); - setStgQual( raxCrestRecord.getStg_qual() ); - setFlow( raxCrestRecord.getFlow() ); - setFlowQual( raxCrestRecord.getFlow_qual() ); - setHw( raxCrestRecord.getHw() ); - setJam( raxCrestRecord.getJam() ); - setOldDatum( raxCrestRecord.getOlddatum() ); - setPrelim( raxCrestRecord.getPrelim() ); - } - - public static RaxCrest getRaxCrest( RaxCrestRecord record ) - { - return ( new RaxCrest( record ) ); - } - - public static RaxCrestRecord getRaxCrestRecord( RaxCrest raxCrest ) - { - RaxCrestRecord raxCrestRecord = new RaxCrestRecord(); - - raxCrestRecord.setLid( raxCrest.getLid() ); - raxCrestRecord.setDatecrst( raxCrest.getDateCrest() ); - raxCrestRecord.setCrstdatetime( raxCrest.getCrestDateTime() ); - raxCrestRecord.setStage( raxCrest.getStage() ); - raxCrestRecord.setStg_qual( raxCrest.getStgQual() ); - raxCrestRecord.setFlow( raxCrest.getFlow() ); - raxCrestRecord.setFlow_qual( raxCrest.getFlowQual() ); - raxCrestRecord.setHw( raxCrest.getHw() ); - raxCrestRecord.setJam( raxCrest.getJam() ); - raxCrestRecord.setOlddatum( raxCrest.getOldDatum() ); - raxCrestRecord.setPrelim( raxCrest.getPrelim() ); - - return raxCrestRecord; - } - - public String toString() - { - return "Lid = " + _lid + " | Datecrst = " + _dateCrest + " | Crstdatetime = " + _crestDateTime + - " | Stage = " + _stage + " | Stg_qual = " + _stgQual + " | Flow = " + _flow + - " | Flow_qual = " + _flowQual + " | Hw = " + _hw + " | Jam = " + _jam + - " | Olddatum = " + _oldDatum + " | Prelim = " + _prelim; - } - - public String keyString() - { - return "Lid = " + _lid + " | Datecrst = " + DbTimeHelper.getDateStringFromLongTime( _dateCrest ); - } - - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setDateCrest( long dateCrest ) - { - _dateCrest = dateCrest; - } - public long getDateCrest() - { - return _dateCrest; - } - public void setCrestDateTime( String crestDateTime ) - { - _crestDateTime = crestDateTime; - } - public String getCrestDateTime() - { - return _crestDateTime; - } - public void setStage( double stage ) - { - _stage = stage; - } - public double getStage() - { - return _stage; - } - public void setStgQual( String stgQual ) - { - _stgQual = stgQual; - } - public String getStgQual() - { - return _stgQual; - } - public void setFlow( double flow ) - { - _flow = flow; - } - public double getFlow() - { - return _flow; - } - public void setFlowQual( String flowQual ) - { - _flowQual = flowQual; - } - public String getFlowQual() - { - return _flowQual; - } - public void setHw( String hw ) - { - _hw = hw; - } - public String getHw() - { - return _hw; - } - public void setJam( String jam ) - { - _jam = jam; - } - public String getJam() - { - return _jam; - } - public void setOldDatum( String oldDatum ) - { - _oldDatum = oldDatum; - } - public String getOldDatum() - { - return _oldDatum; - } - public void setPrelim( String prelim ) - { - _prelim = prelim; - } - public String getPrelim() - { - return _prelim; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxDataLimits.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxDataLimits.java deleted file mode 100644 index d3dafac5b0..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxDataLimits.java +++ /dev/null @@ -1,236 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.RaxDataLimitsRecord; -import ohd.hseb.raxdb.generated.RaxLocDataLimitsRecord; - - -public class RaxDataLimits -{ - private static final short MISSING = -9999; - - private String _pe; - private String _dur; - private short _idur; - private String _monthDayStart; - private String _monthDayEnd; - private double _grossRangeMin; - private double _grossRangeMax; - private double _reasonRangeMin; - private double _reasonRangeMax; - private double _roc; - private double _alertLimit; - private double _alertRocLimit; - private double _alarmLimit; - private double _alarmRocLimit; - - public RaxDataLimits(){} - - public RaxDataLimits( RaxDataLimits raxDataLimits ) - { - setPe( raxDataLimits.getPe() ); - setDur( raxDataLimits.getDur() ); - setIdur( raxDataLimits.getIdur() ); - setMonthDayStart( raxDataLimits.getMonthDayStart() ); - setMonthDayEnd( raxDataLimits.getMonthDayEnd() ); - setGrossRangeMin( raxDataLimits.getGrossRangeMin() ); - setGrossRangeMax( raxDataLimits.getGrossRangeMax() ); - setReasonRangeMin( raxDataLimits.getReasonRangeMin() ); - setReasonRangeMax( raxDataLimits.getReasonRangeMax() ); - setRoc( raxDataLimits.getRoc() ); - setAlertLimit( raxDataLimits.getAlertLimit() ); - setAlertRocLimit( raxDataLimits.getAlertRocLimit() ); - setAlarmLimit( raxDataLimits.getAlarmLimit() ); - setAlarmRocLimit( raxDataLimits.getAlarmRocLimit() ); - } - - public RaxDataLimits( RaxDataLimitsRecord raxDataLimits ) - { - setPe( PEManager.getPEFromPe1Pe2( raxDataLimits.getPe1(), raxDataLimits.getPe2() ) ); - setDur( raxDataLimits.getDur() ); - setIdur( raxDataLimits.getIdur() ); - setMonthDayStart( raxDataLimits.getMonthdaystart() ); - setMonthDayEnd( raxDataLimits.getMonthdayend() ); - setGrossRangeMin( raxDataLimits.getGross_range_min() ); - setGrossRangeMax( raxDataLimits.getGross_range_max() ); - setReasonRangeMin( raxDataLimits.getReason_range_min() ); - setReasonRangeMax( raxDataLimits.getReason_range_max() ); - setRoc( raxDataLimits.getRoc_max() ); - setAlertLimit( raxDataLimits.getAlert_limit() ); - setAlertRocLimit( raxDataLimits.getAlert_roc_limit() ); - setAlarmLimit( raxDataLimits.getAlarm_limit() ); - setAlarmRocLimit( raxDataLimits.getAlarm_roc_limit() ); - } - - public RaxDataLimits( RaxLocDataLimitsRecord raxLocDataLimits ) - { - setPe( PEManager.getPEFromPe1Pe2( raxLocDataLimits.getPe1(), raxLocDataLimits.getPe2() ) ); - setDur( raxLocDataLimits.getDur() ); - setIdur( raxLocDataLimits.getIdur() ); - setMonthDayStart( raxLocDataLimits.getMonthdaystart() ); - setMonthDayEnd( raxLocDataLimits.getMonthdayend() ); - setGrossRangeMin( raxLocDataLimits.getGross_range_min() ); - setGrossRangeMax( raxLocDataLimits.getGross_range_max() ); - setReasonRangeMin( raxLocDataLimits.getReason_range_min() ); - setReasonRangeMax( raxLocDataLimits.getReason_range_max() ); - setRoc( raxLocDataLimits.getRoc_max() ); - setAlertLimit( raxLocDataLimits.getAlert_limit() ); - setAlertRocLimit( raxLocDataLimits.getAlert_roc_limit() ); - setAlarmLimit( raxLocDataLimits.getAlarm_limit() ); - setAlarmRocLimit( raxLocDataLimits.getAlarm_roc_limit() ); - } - - public String toString() - { - return "PE = " + _pe + " | Dur = " + _dur + " | idur = " + _idur + " | MonthDayStart = " + _monthDayStart + - " | MonthDayEnd = " + _monthDayEnd + " | GrossRangeMin = " + _grossRangeMin + " | GrossRangeMax = " + _grossRangeMax + - " | ReasonRangeMin = " + _reasonRangeMin + " | ReasonRangeMax = " + _reasonRangeMax + " Roc = " + _roc + - " | AlertLimit = " + _alertLimit + " | AlertRocLimit = " + _alertRocLimit + " | AlarmLimit = " + _alarmLimit + " | AlarmRocLimit = " + _alarmRocLimit; - } - - public String keyString() - { - return "PE = " + _pe + " | Dur = " + _dur + " | idur = " + _idur + " | MonthDayStart = " + _monthDayStart; - } - - public static RaxDataLimits getRaxDataLimits( RaxDataLimitsRecord raxDataLimitsRecord ) - { - return ( new RaxDataLimits( raxDataLimitsRecord ) ); - } - - public static RaxDataLimitsRecord getRaxDataLimitsRecord( RaxDataLimits raxDataLimits ) - { - RaxDataLimitsRecord raxDataLimitsRecord = new RaxDataLimitsRecord(); - - raxDataLimitsRecord.setPe1( PEManager.getPe1FromPE( raxDataLimits.getPe() ) ); - raxDataLimitsRecord.setPe2( PEManager.getPe2FromPE( raxDataLimits.getPe() ) ); - raxDataLimitsRecord.setDur( raxDataLimits.getDur() ); - raxDataLimitsRecord.setIdur( raxDataLimits.getIdur() ); - raxDataLimitsRecord.setMonthdaystart( raxDataLimits.getMonthDayStart() ); - raxDataLimitsRecord.setMonthdayend( raxDataLimits.getMonthDayEnd() ); - raxDataLimitsRecord.setGross_range_min( raxDataLimits.getGrossRangeMin() ); - raxDataLimitsRecord.setGross_range_max( raxDataLimits.getGrossRangeMax() ); - raxDataLimitsRecord.setReason_range_min( raxDataLimits.getReasonRangeMin() ); - raxDataLimitsRecord.setReason_range_max( raxDataLimits.getReasonRangeMax() ); - raxDataLimitsRecord.setRoc_max( raxDataLimits.getRoc() ); - raxDataLimitsRecord.setAlert_limit( raxDataLimits.getAlertLimit() ); - raxDataLimitsRecord.setAlert_roc_limit( raxDataLimits.getAlertRocLimit() ); - raxDataLimitsRecord.setAlarm_limit( raxDataLimits.getAlarmLimit() ); - raxDataLimitsRecord.setAlarm_roc_limit( raxDataLimits.getAlarmRocLimit() ); - - return raxDataLimitsRecord; - } - - public void setPe( String pe ) - { - _pe = pe; - } - public String getPe() - { - return _pe; - } - public void setDur( String dur ) - { - _dur = dur; - } - public String getDur() - { - return _dur; - } - public void setIdur( short idur ) - { - _idur = idur; - } - public short getIdur() - { - return _idur; - } - public void setMonthDayStart( String monthdaystart ) - { - _monthDayStart = monthdaystart; - } - public String getMonthDayStart() - { - return _monthDayStart; - } - public void setMonthDayEnd( String monthdayend ) - { - _monthDayEnd = monthdayend; - } - public String getMonthDayEnd() - { - return _monthDayEnd; - } - public void setGrossRangeMin( double grossRangeMin ) - { - _grossRangeMin = grossRangeMin; - } - public double getGrossRangeMin() - { - return _grossRangeMin; - } - public void setGrossRangeMax( double grossRangeMax ) - { - _grossRangeMax = grossRangeMax; - } - public double getGrossRangeMax() - { - return _grossRangeMax; - } - public void setReasonRangeMin( double reasonRangeMin ) - { - _reasonRangeMin = reasonRangeMin; - } - public double getReasonRangeMin() - { - return _reasonRangeMin; - } - public void setReasonRangeMax( double reasonRangeMax ) - { - _reasonRangeMax = reasonRangeMax; - } - public double getReasonRangeMax() - { - return _reasonRangeMax; - } - public void setRoc( double roc ) - { - _roc = roc; - } - public double getRoc() - { - return _roc; - } - public void setAlertLimit( double alertLimit ) - { - _alertLimit = alertLimit; - } - public double getAlertLimit() - { - return _alertLimit; - } - public void setAlertRocLimit( double alertRocLimit ) - { - _alertRocLimit = alertRocLimit; - } - public double getAlertRocLimit() - { - return _alertRocLimit; - } - public void setAlarmLimit( double alarmLimit ) - { - _alarmLimit = alarmLimit; - } - public double getAlarmLimit() - { - return _alarmLimit; - } - public void setAlarmRocLimit( double alarmRocLimit ) - { - _alarmRocLimit = alarmRocLimit; - } - public double getAlarmRocLimit() - { - return _alarmRocLimit; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxIngestFilter.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxIngestFilter.java deleted file mode 100644 index 3f0480a2df..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxIngestFilter.java +++ /dev/null @@ -1,367 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.RaxIngestFilterRecord; - -public class RaxIngestFilter -{ - private static final int MISSING = -9999; - - private String _lid = null; - private String _pe = null; - private String _dur = null; - private short _idur = MISSING; - private String _ts = null; - private String _extremum = null; - private short _tsRank = MISSING; - private String _detailInfo = null; - private boolean _ingest = false; - private boolean _newReport = false; - private boolean _active = true; - private boolean _ofsInput = false; - private long _obsTime = 0; - private String _ownerAgency = null; - private String _ownerLocation = null; - private boolean _mpeInput = false; - - public RaxIngestFilter(){} - - public RaxIngestFilter( RaxIngestFilter raxIngestFilter ) - { - setLid( raxIngestFilter.getLid() ); - setPe( raxIngestFilter.getPe() ); - setDur( raxIngestFilter.getDur() ); - setIdur( raxIngestFilter.getIdur() ); - setTs( raxIngestFilter.getTs() ); - setExtremum( raxIngestFilter.getExtremum() ); - setTsRank( raxIngestFilter.getTsRank() ); - setDetailInfo( raxIngestFilter.getDetailInfo() ); - setIngest( raxIngestFilter.isIngest() ); - setNewReport( raxIngestFilter.isNewReport() ); - setActive( raxIngestFilter.isActive() ); - setOfsInput( raxIngestFilter.isOfsInput() ); - setObsTime( raxIngestFilter.getObsTime() ); - setOwnerAgency( raxIngestFilter.getOwnerAgency() ); - setOwnerLocation( raxIngestFilter.getOwnerLocation() ); - setMpeInput( raxIngestFilter.isMpeInput() ); - } - - public String toString() - { - return "Lid = " + _lid + " | PE = " + _pe + " | Dur = " + _dur + " | IDur = " + _idur + " | TS = " + _ts + " | Extremum = " + _extremum + - " | TsRank = " + _tsRank + " | DetailInfo = " + _detailInfo + " | Ingest = " + _ingest + " | NewReport = " + _newReport + - " | Active = " + _active + " | OfsInput = " + _ofsInput + " | ObsTime = " + _obsTime + " | OwnerAgency = " + _ownerAgency + - " | OwnerLocation = " + _ownerLocation + " | MpeInput = " + _mpeInput; - } - - public String keyString() - { - return "Lid = " + _lid + " | PE = " + _pe + " | Dur = " + _dur + " | IDur = " + _idur + " | TS = " + _ts + " | Extremum = " + _extremum; - } - - public RaxIngestFilter( RaxIngestFilterRecord raxIngestFilter ) - { - setLid( raxIngestFilter.getLid() ); - setPe( PEManager.getPEFromPe1Pe2( raxIngestFilter.getPe1(), raxIngestFilter.getPe2() ) ); - setDur( raxIngestFilter.getDur() ); - setIdur( raxIngestFilter.getIdur() ); - setTs( TSManager.getTSFromTandS( raxIngestFilter.getT(), raxIngestFilter.getS() ) ); - setExtremum( raxIngestFilter.getE() ); - setTsRank( raxIngestFilter.getTs_rank() ); - setDetailInfo( raxIngestFilter.getDet() ); - - if ( raxIngestFilter.getIngest() == 0 ) - { - setIngest( false ); - } - else - { - setIngest( true ); - } - - if ( ( raxIngestFilter.getNew_report() == null ) || - ( raxIngestFilter.getNew_report().equalsIgnoreCase( "N" ) ) ) - - { - setNewReport( false ); - } - else - { - setNewReport( true ); - } - - if ( ( raxIngestFilter.getActive() == null ) || - ( raxIngestFilter.getActive().equalsIgnoreCase( "N" ) ) ) - { - setActive( false ); - } - else - { - setActive( true ); - } - - if ( ( raxIngestFilter.getOfs_input() == null ) || - ( raxIngestFilter.getOfs_input().equalsIgnoreCase( "0" ) ) || - ( raxIngestFilter.getOfs_input().equalsIgnoreCase( "F" ) ) ) - - { - setOfsInput( false ); - } - else - { - setOfsInput( true ); - } - - setObsTime( raxIngestFilter.getObstime() ); - setOwnerAgency( raxIngestFilter.getOwnag() ); - setOwnerLocation( raxIngestFilter.getOwnloc() ); - - if ( ( raxIngestFilter.getMpe_input() == null ) || - ( raxIngestFilter.getMpe_input().equalsIgnoreCase( "0" ) ) || - ( raxIngestFilter.getMpe_input().equalsIgnoreCase( "F" ) ) ) - { - setMpeInput( false ); - } - else - { - setMpeInput( true ); - } - } - - public static RaxIngestFilter getRaxIngestFilter( RaxIngestFilterRecord raxIngestFilterRecord ) - { - return ( new RaxIngestFilter( raxIngestFilterRecord ) ); - } - - public static RaxIngestFilterRecord getRaxIngestFilterRecord( RaxIngestFilter raxIngestFilter ) - { - RaxIngestFilterRecord raxIngestFilterRecord = new RaxIngestFilterRecord(); - - raxIngestFilterRecord.setLid( raxIngestFilter.getLid() ); - raxIngestFilterRecord.setPe1( PEManager.getPe1FromPE( raxIngestFilter.getPe() ) ); - raxIngestFilterRecord.setPe2( PEManager.getPe2FromPE( raxIngestFilter.getPe() ) ); - raxIngestFilterRecord.setDur( raxIngestFilter.getDur() ); - raxIngestFilterRecord.setIdur( raxIngestFilter.getIdur() ); - raxIngestFilterRecord.setT( TSManager.getTFromTS( raxIngestFilter.getTs() ) ); - raxIngestFilterRecord.setS( TSManager.getSFromTS( raxIngestFilter.getTs() ) ); - raxIngestFilterRecord.setE( raxIngestFilter.getExtremum() ); - raxIngestFilterRecord.setTs_rank( raxIngestFilter.getTsRank() ); - raxIngestFilterRecord.setDet( raxIngestFilter.getDetailInfo() ); - - if ( raxIngestFilter.isIngest() ) - { - raxIngestFilterRecord.setIngest( (short) 1 ); - } - else - { - raxIngestFilterRecord.setIngest( (short) 0 ); - } - - if ( raxIngestFilter.isNewReport() ) - { - raxIngestFilterRecord.setNew_report( "Y" ); - } - else - { - raxIngestFilterRecord.setNew_report( "N" ); - } - - if ( raxIngestFilter.isActive() ) - { - raxIngestFilterRecord.setActive( "Y" ); - } - else - { - raxIngestFilterRecord.setActive( "N" ); - } - - if ( raxIngestFilter.isOfsInput() ) - { - raxIngestFilterRecord.setOfs_input( "1" ); - } - else - { - raxIngestFilterRecord.setOfs_input( "0" ); - } - - raxIngestFilterRecord.setObstime( raxIngestFilter.getObsTime() ); - raxIngestFilterRecord.setOwnag( raxIngestFilter.getOwnerAgency() ); - raxIngestFilterRecord.setOwnloc( raxIngestFilter.getOwnerLocation() ); - - if ( raxIngestFilter.isMpeInput() ) - { - raxIngestFilterRecord.setMpe_input( "1" ); - } - else - { - raxIngestFilterRecord.setMpe_input( "0" ); - } - - return raxIngestFilterRecord; - } - - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( String dur ) - { - _dur = dur; - } - - public String getDur() - { - return _dur; - } - - public void setIdur( short idur ) - { - _idur = idur; - } - - public short getIdur() - { - return _idur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setTsRank( short tsRank ) - { - _tsRank = tsRank; - } - - public short getTsRank() - { - return _tsRank; - } - - public void setDetailInfo( String detailInfo ) - { - _detailInfo = detailInfo; - } - - public String getDetailInfo() - { - return _detailInfo; - } - - public void setIngest( boolean ingest ) - { - _ingest = ingest; - } - - public boolean isIngest() - { - return _ingest; - } - - public void setNewReport( boolean newReport ) - { - _newReport = newReport; - } - - public boolean isNewReport() - { - return _newReport; - } - - public void setActive( boolean active ) - { - _active = active; - } - - public boolean isActive() - { - return _active; - } - - public void setOfsInput( boolean ofsInput ) - { - _ofsInput = ofsInput; - } - - public boolean isOfsInput() - { - return _ofsInput; - } - - public void setObsTime( long obsTime ) - { - _obsTime = obsTime; - } - - public long getObsTime() - { - return _obsTime; - } - - public void setOwnerAgency( String ownerAgency ) - { - _ownerAgency = ownerAgency; - } - - public String getOwnerAgency() - { - return _ownerAgency; - } - - public void setOwnerLocation( String ownerLocation ) - { - _ownerLocation = ownerLocation; - } - - public String getOwnerLocation() - { - return _ownerLocation; - } - - public void setMpeInput( boolean mpeInput ) - { - _mpeInput = mpeInput; - } - - public boolean isMpeInput() - { - return _mpeInput; - } - - public String getPrimaryKey() - { - return ( _lid + "|" + _pe + "|" + _dur + "|" + _ts + "|" + _extremum ); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxLocDataLimits.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxLocDataLimits.java deleted file mode 100644 index 1d92adf05d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxLocDataLimits.java +++ /dev/null @@ -1,78 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.RaxLocDataLimitsRecord; - -public class RaxLocDataLimits extends RaxDataLimits -{ - private String _lid = null; - - public RaxLocDataLimits(){} - - public RaxLocDataLimits( RaxDataLimits raxDataLimits ) - { - super( raxDataLimits ); - } - - public RaxLocDataLimits( RaxLocDataLimits raxLocDataLimits ) - { - super( raxLocDataLimits ); - setLid( raxLocDataLimits.getLid() ); - } - - public RaxLocDataLimits( RaxLocDataLimitsRecord raxLocDataLimitsRecord ) - { - super( raxLocDataLimitsRecord ); - setLid( raxLocDataLimitsRecord.getLid() ); - } - - public static RaxLocDataLimits getRaxLocDataLimits( RaxLocDataLimitsRecord raxLocDataLimitsRecord ) - { - return ( new RaxLocDataLimits( raxLocDataLimitsRecord ) ); - } - - public static RaxLocDataLimitsRecord getRaxLocDataLimitsRecord( RaxLocDataLimits raxLocDataLimits ) - { - RaxLocDataLimitsRecord raxLocDataLimitsRecord = new RaxLocDataLimitsRecord(); - - raxLocDataLimitsRecord.setLid( raxLocDataLimits.getLid() ); - raxLocDataLimitsRecord.setPe1( PEManager.getPe1FromPE( raxLocDataLimits.getPe() ) ); - raxLocDataLimitsRecord.setPe2( PEManager.getPe2FromPE( raxLocDataLimits.getPe() ) ); - raxLocDataLimitsRecord.setDur( raxLocDataLimits.getDur() ); - raxLocDataLimitsRecord.setIdur( raxLocDataLimits.getIdur() ); - raxLocDataLimitsRecord.setMonthdaystart( raxLocDataLimits.getMonthDayStart() ); - raxLocDataLimitsRecord.setMonthdayend( raxLocDataLimits.getMonthDayEnd() ); - raxLocDataLimitsRecord.setGross_range_min( raxLocDataLimits.getGrossRangeMin() ); - raxLocDataLimitsRecord.setGross_range_max( raxLocDataLimits.getGrossRangeMax() ); - raxLocDataLimitsRecord.setReason_range_min( raxLocDataLimits.getReasonRangeMin() ); - raxLocDataLimitsRecord.setReason_range_max( raxLocDataLimits.getReasonRangeMax() ); - raxLocDataLimitsRecord.setRoc_max( raxLocDataLimits.getRoc() ); - raxLocDataLimitsRecord.setAlert_limit( raxLocDataLimits.getAlertLimit() ); - raxLocDataLimitsRecord.setAlert_roc_limit( raxLocDataLimits.getAlertRocLimit() ); - raxLocDataLimitsRecord.setAlarm_limit( raxLocDataLimits.getAlarmLimit() ); - raxLocDataLimitsRecord.setAlarm_roc_limit( raxLocDataLimits.getAlarmRocLimit() ); - - return raxLocDataLimitsRecord; - } - - public String toString() - { - return ( "Lid = " + _lid + " | " + super.toString() ); - } - - public String keyString() - { - return ( "Lid = " + _lid + " | " + super.keyString() ); - } - - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxLocation.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxLocation.java deleted file mode 100644 index fa38a2b826..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxLocation.java +++ /dev/null @@ -1,312 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.RaxLocationRecord; -import ohd.hseb.util.StringDataConverter; - -public class RaxLocation -{ - private static final int MISSING = -9999; - - private String _lid = null; - private long _beginDate = MISSING; - private long _endDate = MISSING; - private double _latitude = MISSING; - private double _longitude = MISSING; - private String _name = null; - private String _detailInfo = null; - private String _hsa = null; - private int _elevation = MISSING; - private String _state = null; - private String _countyFips = null; - private String _wfo = null; - private short _postCode = MISSING; - private String _rfc = null; - private String _goes = null; - private String _huc = null; - private String _zone = null; - private String _dbsource = null; - private String _countryfips = null; - - public RaxLocation(){} - - public RaxLocation( RaxLocation raxLocation ) - { - setLid( raxLocation.getLid() ); - setBeginDate( raxLocation.getBeginDate() ); - setEndDate( raxLocation.getEndDate() ); - setLatitude( raxLocation.getLatitude() ); - setLongitude( raxLocation.getLongitude() ); - setName( raxLocation.getName() ); - setDetailInfo( raxLocation.getDetailInfo() ); - setHsa( raxLocation.getHsa() ); - setElevation( raxLocation.getElevation() ); - setState( raxLocation.getState() ); - setCountyFips( raxLocation.getCountyFips() ); - setWfo( raxLocation.getWfo() ); - setPostCode( raxLocation.getPostCode() ); - setRfc( raxLocation.getRfc() ); - setGoes( raxLocation.getGoes() ); - setHuc( raxLocation.getHuc() ); - setZone( raxLocation.getZone() ); - setDbsource( raxLocation.getDbsource() ); - setCountryfips( raxLocation.getCountryfips() ); - } - - public String toString() - { - StringDataConverter converter = new StringDataConverter(); - - return "Lid = " + _lid + " | BeginDate = " + converter.getDateStringFromDateLong( _beginDate ) + " | EndDate = " + converter.getDateStringFromDateLong( _endDate ) + "\n" + - " | Latitude = " + _latitude + " | Longitude = " + _longitude + " | Name = " + _name + "\n" + - " | DetailInfo = " + _detailInfo + " | HSA = " + _hsa + " | Elevation = " + _elevation + "\n" + - " | State = " + _state + " | CountyFips = " + _countyFips + " Wfo = " + _wfo + "\n" + - " | PostCode = " + _postCode + " | RFC = " + _rfc + " | Goes = " + _goes + "\n" + - " | Huc = " + _huc + " | Zone = " + _zone + " | DbSource = " + _dbsource + "\n" + - " | CountryFips = " + _countryfips; - } - - public RaxLocation( RaxLocationRecord raxLocationRecord ) - { - setLid( raxLocationRecord.getLid() ); - setBeginDate( raxLocationRecord.getSbd() ); - setEndDate( raxLocationRecord.getSed() ); - setLatitude( raxLocationRecord.getLat() ); - setLongitude( raxLocationRecord.getLon() ); - setName( raxLocationRecord.getName() ); - setDetailInfo( raxLocationRecord.getDet() ); - setHsa( raxLocationRecord.getHsa() ); - setElevation( raxLocationRecord.getElev() ); - setState( raxLocationRecord.getState() ); - setCountyFips( raxLocationRecord.getCountyfips() ); - setWfo( raxLocationRecord.getWfo() ); - setPostCode( raxLocationRecord.getPost() ); - setRfc( raxLocationRecord.getRfc() ); - setGoes( raxLocationRecord.getGoes() ); - setHuc( raxLocationRecord.getHuc() ); - setZone( raxLocationRecord.getZon() ); - setDbsource( raxLocationRecord.getDbsource() ); - setCountryfips( raxLocationRecord.getCountryfips() ); - } - - public static RaxLocation getRaxLocation( RaxLocationRecord record ) - { - return ( new RaxLocation( record ) ); - } - - public static RaxLocationRecord getRaxLocationRecord( RaxLocation raxLocation ) - { - RaxLocationRecord raxLocationRecord = new RaxLocationRecord(); - - raxLocationRecord.setLid( raxLocation.getLid() ); - raxLocationRecord.setSbd( raxLocation.getBeginDate() ); - raxLocationRecord.setSed( raxLocation.getEndDate() ); - raxLocationRecord.setLat( raxLocation.getLatitude() ); - raxLocationRecord.setLon( raxLocation.getLongitude() ); - raxLocationRecord.setName( raxLocation.getName() ); - raxLocationRecord.setDet( raxLocation.getDetailInfo() ); - raxLocationRecord.setHsa( raxLocation.getHsa() ); - raxLocationRecord.setElev( raxLocation.getElevation() ); - raxLocationRecord.setState( raxLocation.getState() ); - raxLocationRecord.setCountyfips( raxLocation.getCountyFips() ); - raxLocationRecord.setWfo( raxLocation.getWfo() ); - raxLocationRecord.setPost( raxLocation.getPostCode() ); - raxLocationRecord.setRfc( raxLocation.getRfc() ); - raxLocationRecord.setGoes( raxLocation.getGoes() ); - raxLocationRecord.setHuc( raxLocation.getHuc() ); - raxLocationRecord.setZon( raxLocation.getZone() ); - raxLocationRecord.setDbsource( raxLocation.getDbsource() ); - raxLocationRecord.setCountryfips( raxLocation.getCountryfips() ); - - return raxLocationRecord; - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setBeginDate( long beginDate ) - { - _beginDate = beginDate; - } - - public long getBeginDate() - { - return _beginDate; - } - - public void setEndDate( long endDate ) - { - _endDate = endDate; - } - - public long getEndDate() - { - return _endDate; - } - - public void setLatitude( double latitude ) - { - _latitude = latitude; - } - - public double getLatitude() - { - return _latitude; - } - - public void setLongitude( double longitude ) - { - _longitude = longitude; - } - - public double getLongitude() - { - return _longitude; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setDetailInfo( String detailInfo ) - { - _detailInfo = detailInfo; - } - - public String getDetailInfo() - { - return _detailInfo; - } - - public void setHsa( String hsa ) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } - - public void setElevation( int elevation ) - { - _elevation = elevation; - } - - public int getElevation() - { - return _elevation; - } - - public void setState( String state ) - { - _state = state; - } - - public String getState() - { - return _state; - } - - public void setCountyFips( String countyFips ) - { - _countyFips = countyFips; - } - - public String getCountyFips() - { - return _countyFips; - } - - public void setWfo( String wfo ) - { - _wfo = wfo; - } - - public String getWfo() - { - return _wfo; - } - - public void setPostCode( short postCode ) - { - _postCode = postCode; - } - - public short getPostCode() - { - return _postCode; - } - - public void setRfc( String rfc ) - { - _rfc = rfc; - } - - public String getRfc() - { - return _rfc; - } - - public void setGoes( String goes ) - { - _goes = goes; - } - - public String getGoes() - { - return _goes; - } - - public void setHuc( String huc ) - { - _huc = huc; - } - - public String getHuc() - { - return _huc; - } - - public void setZone( String zone ) - { - _zone = zone; - } - - public String getZone() - { - return _zone; - } - - public void setDbsource( String dbsource ) - { - _dbsource = dbsource; - } - - public String getDbsource() - { - return _dbsource; - } - - public void setCountryfips( String countryfips ) - { - _countryfips = countryfips; - } - - public String getCountryfips() - { - return _countryfips; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRating.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRating.java deleted file mode 100644 index 61c4b1aab3..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRating.java +++ /dev/null @@ -1,522 +0,0 @@ -package ohd.hseb.raxbase.model; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.RaxRatingRecord; -import ohd.hseb.util.StringDataConverter; - - -public class RaxRating -{ - public static final short MISSING = -9999; - - private String _lid = null; - private String _pe = null; - private double _table = MISSING; - private long _validDate = MISSING; - private String _src = null; - private String _othagid = null; - private boolean _rfsInput = false; - private List _raxRatingPointList = new ArrayList(); - private String _units = null; - private String _interpolate = null; - private List _raxRatingOffsetList = new ArrayList(); - private double _allowStage = MISSING; - - public RaxRating(){} - - public RaxRating( String lid, List raxRatingPointList ) - { - setLid( lid ); - setRaxRatingPointList( raxRatingPointList ); - } - - public RaxRating( RaxRating raxRating ) - { - setLid( raxRating.getLid() ); - setPe( raxRating.getPe() ); - setTable( raxRating.getTable() ); - setValidDate( raxRating.getValidDate() ); - setSrc( raxRating.getSrc() ); - setOthagid( raxRating.getOthagid() ); - setRfsInput( raxRating.isRfsInput() ); - setRaxRatingPointList( raxRating.getRaxRatingPointList() ); - setUnits( raxRating.getUnits() ); - setInterpolate( raxRating.getInterpolate() ); - setOffsets( raxRating.getOffsets() ); - setAllowStage( raxRating.getAllowStage() ); - } - - public String toString() - { - return "Lid = " + _lid + " | Pe = " + _pe + " | RatingTableNumber = " + _table + - " | ValidDate = " + DbTimeHelper.getDateTimeStringFromLongTime( _validDate ) + - " | Source = " + _src + " | OthAgID = " + _othagid + " | RfsInput = " + _rfsInput + - " | RaxRatingPointList = " + _raxRatingPointList + " | Units = " + _units + - " | Interpolate = " + _interpolate + " | Offsets = " + _raxRatingOffsetList + - " | AllowStage = " + _allowStage; - } - - public RaxRating( RaxRatingRecord raxRatingRecord ) - { - String rfsInput = raxRatingRecord.getRfs_input(); - List raxRatingPointRecordsList = new ArrayList(); - - setLid( raxRatingRecord.getLid() ); - setPe( PEManager.getPEFromPe1Pe2( raxRatingRecord.getPe1(), raxRatingRecord.getPe2() ) ); - setTable( raxRatingRecord.getTbl() ); - setValidDate( raxRatingRecord.getValid_date() ); - setSrc( raxRatingRecord.getSrc() ); - setOthagid( raxRatingRecord.getOthagid() ); - if ( ( rfsInput != null ) && - ( rfsInput.equalsIgnoreCase( "Y" ) || - ( rfsInput.equalsIgnoreCase( "1" ) ) ) ) - { - setRfsInput( true ); - } - else - { - setRfsInput( false ); - } - - setRaxRatingPointList( getRaxRatingPointListFromRecord( raxRatingRecord.getStgflow() ) ); - - setUnits( raxRatingRecord.getUnits() ); - setInterpolate( raxRatingRecord.getInterpolate() ); - setOffsets( getRaxRatingOffsetListFromRecord( raxRatingRecord.getOffsets() ) ); - setAllowStage( raxRatingRecord.getAllowstg() ); - } - - public static RaxRating getRaxRating( RaxRatingRecord record ) - { - return ( new RaxRating( record ) ); - } - - public String keyString() - { - return "Lid = " + _lid + " | PE = " + _pe + " Tbl = " + _table + " ValidDate = " + DbTimeHelper.getDateStringFromLongTime( _validDate ) + " Src = " + _src; - } - - public static RaxRatingRecord getRaxRatingRecord( RaxRating raxRating ) - { - RaxRatingRecord record = new RaxRatingRecord(); - boolean rfsInput = raxRating.isRfsInput(); - - record.setLid( raxRating.getLid() ); - record.setPe1( PEManager.getPe1FromPE( raxRating.getPe() ) ); - record.setPe2( PEManager.getPe2FromPE( raxRating.getPe() ) ); - record.setTbl( raxRating.getTable() ); - record.setValid_date( raxRating.getValidDate() ); - record.setSrc( raxRating.getSrc() ); - record.setOthagid( raxRating.getOthagid() ); - - if ( rfsInput ) - { - record.setRfs_input( "Y" ); - } - else - { - record.setRfs_input( "N" ); - } - - record.setStgflow( getStgFlowFromRaxRatingPointList( raxRating.getRaxRatingPointList() ) ); - record.setUnits( raxRating.getUnits() ); - record.setInterpolate( raxRating.getInterpolate() ); - record.setOffsets( getOffSetsFromRaxOffsetsList( raxRating.getOffsets() ) ); - record.setAllowstg( raxRating.getAllowStage() ); - - return record; - } - - private static String getStgFlowFromRaxRatingPointList( List raxRatingPointList ) - { - StringBuffer stgFlowStringBuffer = null; - RaxRatingPoint raxRatingPoint = new RaxRatingPoint(); - String returnString = null; - - if ( ( raxRatingPointList != null ) && ( ! raxRatingPointList.isEmpty() ) ) - { - stgFlowStringBuffer = new StringBuffer(); - stgFlowStringBuffer.append( "{{" ); - - for ( int i = 0; i < raxRatingPointList.size(); i++ ) - { - raxRatingPoint = (RaxRatingPoint) raxRatingPointList.get( i ); - - stgFlowStringBuffer.append( raxRatingPoint.getStage() + "," + raxRatingPoint.getDischarge() + "}" ); - - if ( i == ( raxRatingPointList.size() - 1 ) ) - { - stgFlowStringBuffer.append( "}" ); - } - else - { - stgFlowStringBuffer.append( ",{" ); - } - } - } - - if ( stgFlowStringBuffer != null ) - { - returnString = stgFlowStringBuffer.toString(); - } - return returnString; - } - - private static String getOffSetsFromRaxOffsetsList( List raxOffsetsList ) - { - StringBuffer offsetsStringBuffer = null; - RaxRatingOffset raxRatingOffset = new RaxRatingOffset(); - String returnString = null; - - if ( ( raxOffsetsList != null ) && ( ! raxOffsetsList.isEmpty() ) ) - { - offsetsStringBuffer = new StringBuffer(); - - offsetsStringBuffer.append( "{{" ); - - for ( int i = 0; i < raxOffsetsList.size(); i++ ) - { - raxRatingOffset = (RaxRatingOffset) raxOffsetsList.get( i ); - - offsetsStringBuffer.append( raxRatingOffset.getStage() + "," + raxRatingOffset.getOffset() + "}" ); - - if ( i == ( raxOffsetsList.size() - 1 ) ) - { - offsetsStringBuffer.append( "}" ); - } - else - { - offsetsStringBuffer.append( ",{" ); - } - } - } - if ( offsetsStringBuffer != null ) - { - returnString = offsetsStringBuffer.toString(); - } - return returnString; - } - - private List getRaxRatingPointListFromRecord( String stageFlowString ) - { - List raxRatingPointList = new ArrayList(); - RaxRatingPoint ratingPoint = new RaxRatingPoint(); - StringDataConverter converter = new StringDataConverter(); - - if ( stageFlowString != null ) - { - StringTokenizer tokens = new StringTokenizer( stageFlowString, "},{" ); - - // {{-5.36,0},{16.5,58529},{18,64562},{20,72081},{21,79601}} - - while ( tokens.hasMoreTokens() ) - { - ratingPoint = new RaxRatingPoint(); - - ratingPoint.setStage( converter.getDoubleValue( tokens.nextToken() ) ); - ratingPoint.setDischarge( converter.getDoubleValue( tokens.nextToken() ) ); - - raxRatingPointList.add( ratingPoint ); - } - } - return raxRatingPointList; - } - - private List getRaxRatingOffsetListFromRecord( String offSetsString ) - { - List raxRatingOffsetsList = new ArrayList(); - - if ( offSetsString != null ) - { - RaxRatingOffset offset = new RaxRatingOffset(); - StringDataConverter converter = new StringDataConverter(); - - StringTokenizer tokens = new StringTokenizer( offSetsString, "},{" ); - - while ( tokens.hasMoreTokens() ) - { - offset = new RaxRatingOffset(); - - offset.setStage( converter.getDoubleValue( tokens.nextToken() ) ); - offset.setOffset( converter.getDoubleValue( tokens.nextToken() ) ); - - raxRatingOffsetsList.add( offset ); - } - } - return raxRatingOffsetsList; - } - -/** - * - * @param stage - Stage value - * @return discharge - Extracts the discharge value for the given Stage from the RaxRatingPointList. If the stage is not found, a value of MISSING (-9999) is returned - */ - public double getDischarge( double stage ) - { - double discharge = MISSING; - - for ( int i = 0; i < _raxRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) _raxRatingPointList.get( i ); - - if ( raxRatingPoint.getStage() == stage ) - { - discharge = raxRatingPoint.getDischarge(); - break; - } - } - - return discharge; - } - - public void addOffset( RaxRatingOffset raxRatingOffset ) - { - int index = getStageIndexFromOffsetsList( raxRatingOffset.getStage() ); - - if ( index != MISSING ) - { - if ( doesStageExistInOffsetList( raxRatingOffset.getStage() ) ) - { - _raxRatingOffsetList.set( index, raxRatingOffset ); - } - else - { - _raxRatingOffsetList.add( index, raxRatingOffset ); - } - } - else - { - _raxRatingOffsetList.add( raxRatingOffset ); - } - } - - private boolean doesStageExistInOffsetList( double stage ) - { - boolean exists = false; - - for ( int i = 0; i < _raxRatingOffsetList.size(); i++ ) - { - RaxRatingOffset raxRatingOffset = (RaxRatingOffset) _raxRatingOffsetList.get( i ); - - if ( raxRatingOffset.getStage() == stage ) - { - exists = true; - break; - } - } - return exists; - } - - private int getStageIndexFromOffsetsList( double stage ) - { - int index = MISSING; - - for ( int i = 0; i < _raxRatingOffsetList.size(); i++ ) - { - RaxRatingOffset raxRatingOffset = (RaxRatingOffset) _raxRatingOffsetList.get( i ); - - if ( raxRatingOffset.getStage() >= stage ) - { - index = i; - break; - } - } - return index; - } - - public void addRatingPoint( RaxRatingPoint raxRatingPoint ) - { - int index = getStageIndexFromRatingPointList( raxRatingPoint.getStage() ); - - if ( index != MISSING ) - { - if ( doesStageExistInRatingPointList( raxRatingPoint.getStage() ) ) - { - _raxRatingPointList.set( index, raxRatingPoint ); - } - else - { - _raxRatingPointList.add( index, raxRatingPoint ); - } - } - else - { - _raxRatingPointList.add( raxRatingPoint ); - } - } - - private int getStageIndexFromRatingPointList( double stage ) - { - int index = MISSING; - - for ( int i = 0; i < _raxRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) _raxRatingPointList.get( i ); - - if ( raxRatingPoint.getStage() >= stage ) - { - index = i; - break; - } - } - return index; - } - - private boolean doesStageExistInRatingPointList( double stage ) - { - boolean exists = false; - - for ( int i = 0; i < _raxRatingPointList.size(); i++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) _raxRatingPointList.get( i ); - - if ( raxRatingPoint.getStage() == stage ) - { - exists = true; - break; - } - } - return exists; - } - - - public void removeRatingPoint( RaxRatingPoint raxRatingPoint ) - { - int index = getStageIndexFromRatingPointList( raxRatingPoint.getStage() ); - - _raxRatingPointList.remove( index ); - } - - public void removeOffset( RaxRatingOffset raxRatingOffset ) - { - int index = getStageIndexFromOffsetsList( raxRatingOffset.getStage() ); - - _raxRatingOffsetList.remove( index ); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setTable( double table ) - { - _table = table; - } - - public double getTable() - { - return _table; - } - - public void setValidDate( long validDate ) - { - _validDate = validDate; - } - - public long getValidDate() - { - return _validDate; - } - - public void setSrc( String src ) - { - _src = src; - } - - public String getSrc() - { - return _src; - } - - public void setOthagid( String othagid ) - { - _othagid = othagid; - } - - public String getOthagid() - { - return _othagid; - } - - public void setRfsInput( boolean rfsInput ) - { - _rfsInput = rfsInput; - } - - public boolean isRfsInput() - { - return _rfsInput; - } - - public void setRaxRatingPointList( List raxRatingPointList ) - { - _raxRatingPointList = raxRatingPointList; - } - - public List getRaxRatingPointList() - { - return _raxRatingPointList; - } - - public void setUnits( String units ) - { - _units = units; - } - - public String getUnits() - { - return _units; - } - - public void setInterpolate( String interpolate ) - { - _interpolate = interpolate; - } - - public String getInterpolate() - { - return _interpolate; - } - - public void setOffsets( List raxRatingOffsets ) - { - _raxRatingOffsetList = raxRatingOffsets; - } - - public List getOffsets() - { - return _raxRatingOffsetList; - } - - public void setAllowStage( double allowStage ) - { - _allowStage = allowStage; - } - - public double getAllowStage() - { - return _allowStage; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingOffset.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingOffset.java deleted file mode 100644 index 6e78690872..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingOffset.java +++ /dev/null @@ -1,72 +0,0 @@ -package ohd.hseb.raxbase.model; - -public class RaxRatingOffset -{ - private static final short MISSING = -9999; - - private double _stage = MISSING; - private double _offset = MISSING; - -// ------------------------------------------------------------------------------------------ - - public RaxRatingOffset() - { - this( MISSING, MISSING ); - } - -// ------------------------------------------------------------------------------------------ - - public RaxRatingOffset( double stage, double offset ) - { - setStage( stage ); - setOffset( offset ); - } -// ------------------------------------------------------------------------------------------ - - public void setStage( double stage ) - { - _stage = stage; - } -// ------------------------------------------------------------------------------------------ - - public double getStage() - { - return _stage; - } -// ------------------------------------------------------------------------------------------ - public void setOffset( double offset ) - { - _offset = offset; - } -// ------------------------------------------------------------------------------------------ - - public double getOffset() - { - return _offset; - } -// ------------------------------------------------------------------------------------------ - public boolean equals( RaxRatingOffset raxRatingOffset ) - { - boolean result = false; - - if ( ( _stage == raxRatingOffset.getStage() ) && - ( _offset == raxRatingOffset.getOffset() ) ) - { - result = true; - } - - return result; - - } -// ------------------------------------------------------------------------------------------ - - public String toString() - { - String outString = " Stage = " + getStage() + - " Offset = " + getOffset(); - - return outString; - } -// ------------------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingPoint.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingPoint.java deleted file mode 100644 index c032c655d7..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingPoint.java +++ /dev/null @@ -1,72 +0,0 @@ -package ohd.hseb.raxbase.model; - -public class RaxRatingPoint -{ - private static final short MISSING = -9999; - - private double _stage = MISSING; - private double _discharge = MISSING; - -// ------------------------------------------------------------------------------------------ - - public RaxRatingPoint() - { - this( MISSING, MISSING ); - } - -// ------------------------------------------------------------------------------------------ - - public RaxRatingPoint( double stage, double discharge ) - { - setStage( stage ); - setDischarge( discharge ); - } -// ------------------------------------------------------------------------------------------ - - public void setStage(double stage) - { - _stage = stage; - } -// ------------------------------------------------------------------------------------------ - - public double getStage() - { - return _stage; - } -// ------------------------------------------------------------------------------------------ - public void setDischarge(double discharge) - { - _discharge = discharge; - } -// ------------------------------------------------------------------------------------------ - - public double getDischarge() - { - return _discharge; - } -// ------------------------------------------------------------------------------------------ - public boolean equals( RaxRatingPoint point ) - { - boolean result = false; - - if ( ( _stage == point.getStage() ) && - ( _discharge == point.getDischarge() ) ) - { - result = true; - } - - return result; - - } -// ------------------------------------------------------------------------------------------ - - public String toString() - { - String outString = " Stage = " + getStage() + - " Discharge = " + getDischarge(); - - return outString; - } -// ------------------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingShift.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingShift.java deleted file mode 100644 index 0c95f80503..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRatingShift.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Created on Jun 9, 2004 - * - * Filename : RatingShiftEntry.java - * Author : Gautam Sood - * Last Revision Date : Jun 9, 2004 - * - */ -/** - * @author Gautam Sood -*/ - -package ohd.hseb.raxbase.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.RaxRatingShiftRecord; - - -public class RaxRatingShift -{ - private String _lid = null; - private String _pe = null; - private double _ratingTableNumber = 0.00; - private long _beginDate = 0; - private String _source = null; - private double _valA = 0; - private double _valB = 0; - private double _valC = 0; - private double _valD = 0; - private double _shiftA = 0; - private double _shiftB = 0; - private double _shiftC = 0; - private double _shiftD = 0; - private double _datumAdjustment = 0; - - public RaxRatingShift() - { - } - - public RaxRatingShift( RaxRatingShift raxRatingShift ) - { - setLid( raxRatingShift.getLid() ); - setPe( raxRatingShift.getPe() ); - setRatingTableNumber( raxRatingShift.getRatingTableNumber() ); - setBeginDate( raxRatingShift.getBeginDate() ); - setSource( raxRatingShift.getSource() ); - setValA( raxRatingShift.getValA() ); - setValB( raxRatingShift.getValB() ); - setValC( raxRatingShift.getValC() ); - setValD( raxRatingShift.getValD() ); - setShiftA( raxRatingShift.getShiftA() ); - setShiftB( raxRatingShift.getShiftB() ); - setShiftC( raxRatingShift.getShiftC() ); - setShiftD( raxRatingShift.getShiftD() ); - setDatumAdjustment( raxRatingShift.getDatumAdjustment() ); - } - - public String toString() - { - return "Lid = " + _lid + " | Pe = " + _pe + " | RatingTableNumber = " + _ratingTableNumber + - " | BeginDate = " + DbTimeHelper.getDateTimeStringFromLongTime( _beginDate ) + - " | Source = " + _source + " | ValA-D = " + _valA + "|" + _valB + "|" + - "|" + _valC + "|" + _valD + " | ShiftA-D = " + _shiftA + "|" + _shiftB + - "|" + _shiftC + "|" + _shiftC + " | DatumAdjustment = " + _datumAdjustment; - } - - public RaxRatingShift( RaxRatingShiftRecord raxRatingShiftRecord ) - { - setLid( raxRatingShiftRecord.getLid() ); - setPe( PEManager.getPEFromPe1Pe2( raxRatingShiftRecord.getPe1(), raxRatingShiftRecord.getPe2() ) ); - setRatingTableNumber( raxRatingShiftRecord.getTbl_ver() ); - setBeginDate( raxRatingShiftRecord.getBegin_date() ); - setSource( raxRatingShiftRecord.getSrc() ); - setValA( raxRatingShiftRecord.getVal_a() ); - setValB( raxRatingShiftRecord.getVal_b() ); - setValC( raxRatingShiftRecord.getVal_c() ); - setValD( raxRatingShiftRecord.getVal_d() ); - setShiftA( raxRatingShiftRecord.getSh_a() ); - setShiftB( raxRatingShiftRecord.getSh_b() ); - setShiftC( raxRatingShiftRecord.getSh_c() ); - setShiftD( raxRatingShiftRecord.getSh_d() ); - setDatumAdjustment( raxRatingShiftRecord.getDatum_adj() ); - } - - public static RaxRatingShift getRaxRatingShift( RaxRatingShiftRecord raxRatingShiftRecord ) - { - return ( new RaxRatingShift( raxRatingShiftRecord ) ); - } - - public static RaxRatingShiftRecord getRaxRatingShiftRecord( RaxRatingShift raxRatingShift ) - { - RaxRatingShiftRecord raxRatingShiftRecord = new RaxRatingShiftRecord(); - - raxRatingShiftRecord.setLid( raxRatingShift.getLid() ); - raxRatingShiftRecord.setPe1( PEManager.getPe1FromPE( raxRatingShift.getPe() ) ); - raxRatingShiftRecord.setPe2( PEManager.getPe2FromPE( raxRatingShift.getPe() ) ); - raxRatingShiftRecord.setTbl_ver( raxRatingShift.getRatingTableNumber() ); - raxRatingShiftRecord.setBegin_date( raxRatingShift.getBeginDate() ); - raxRatingShiftRecord.setSrc( raxRatingShift.getSource() ); - raxRatingShiftRecord.setVal_a( raxRatingShift.getValA() ); - raxRatingShiftRecord.setVal_b( raxRatingShift.getValB() ); - raxRatingShiftRecord.setVal_c( raxRatingShift.getValC() ); - raxRatingShiftRecord.setVal_d( raxRatingShift.getValD() ); - raxRatingShiftRecord.setSh_a( raxRatingShift.getShiftA() ); - raxRatingShiftRecord.setSh_b( raxRatingShift.getShiftB() ); - raxRatingShiftRecord.setSh_c( raxRatingShift.getShiftC() ); - raxRatingShiftRecord.setSh_d( raxRatingShift.getShiftD() ); - raxRatingShiftRecord.setDatum_adj( raxRatingShift.getDatumAdjustment() ); - - return raxRatingShiftRecord; - } - - public void setLid(String lid) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setRatingTableNumber( double ratingTableNumber ) - { - _ratingTableNumber = ratingTableNumber; - } - - public double getRatingTableNumber() - { - return _ratingTableNumber; - } - - public void setBeginDate( long beginDate ) - { - _beginDate = beginDate; - } - - public long getBeginDate() - { - return _beginDate; - } - - public void setSource( String source ) - { - _source = source; - } - - public String getSource() - { - return _source; - } - - public void setValA( double valA ) - { - _valA = valA; - } - - public double getValA() - { - return _valA; - } - - public void setValB( double valB ) - { - _valB = valB; - } - - public double getValB() - { - return _valB; - } - - public void setValC( double valC ) - { - _valC = valC; - } - - public double getValC() - { - return _valC; - } - - public void setValD( double valD ) - { - _valD = valD; - } - - public double getValD() - { - return _valD; - } - - public void setShiftA( double shiftA ) - { - _shiftA = shiftA; - } - - public double getShiftA() - { - return _shiftA; - } - - public void setShiftB( double shiftB ) - { - _shiftB = shiftB; - } - - public double getShiftB() - { - return _shiftB; - } - - public void setShiftC( double shiftC ) - { - _shiftC = shiftC; - } - - public double getShiftC() - { - return _shiftC; - } - - public void setShiftD( double shiftD ) - { - _shiftD = shiftD; - } - - public double getShiftD() - { - return _shiftD; - } - - public void setDatumAdjustment( double datumAdjustment ) - { - _datumAdjustment = datumAdjustment; - } - - public double getDatumAdjustment() - { - return _datumAdjustment; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxReservoir.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxReservoir.java deleted file mode 100644 index f71d89cfae..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxReservoir.java +++ /dev/null @@ -1,257 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.RaxReservoirRecord; -import ohd.hseb.util.StringDataConverter; - -public class RaxReservoir -{ - private String _lid; - private long _beginDate; - private long _endDate; - private String _name; - private String _type; - private String _owner; - private double _deadPool; - private double _conserPool; - private double _floodPool; - private double _spillWay; - private double _sill; - private double _top; - private double _surchg; - private double _elev; - private int _gates; - private long _impounded; - private String _uses; - - - public RaxReservoir(){} - - public RaxReservoir( RaxReservoir raxReservoir ) - { - setLid( raxReservoir.getLid() ); - setBeginDate( raxReservoir.getBeginDate() ); - setEndDate( raxReservoir.getEndDate() ); - setName( raxReservoir.getName() ); - setType( raxReservoir.getType() ); - setOwner( raxReservoir.getOwner() ); - setDeadPool( raxReservoir.getDeadPool() ); - setConserPool( raxReservoir.getConserPool() ); - setFloodPool( raxReservoir.getFloodPool() ); - setSpillWay( raxReservoir.getSpillWay() ); - setSill( raxReservoir.getSill() ); - setTop( raxReservoir.getTop() ); - setSurchg( raxReservoir.getSurchg() ); - setElev( raxReservoir.getElev() ); - setGates( raxReservoir.getGates() ); - setImpounded( raxReservoir.getImpounded() ); - setUses( raxReservoir.getUses() ); - } - - public RaxReservoir( RaxReservoirRecord raxReservoirRecord ) - { - setLid( raxReservoirRecord.getLid() ); - setBeginDate( raxReservoirRecord.getSbd() ); - setEndDate( raxReservoirRecord.getSed() ); - setName( raxReservoirRecord.getName() ); - setType( raxReservoirRecord.getType() ); - setOwner( raxReservoirRecord.getOwner() ); - setDeadPool( raxReservoirRecord.getDeadpool() ); - setConserPool( raxReservoirRecord.getConserpool() ); - setFloodPool( raxReservoirRecord.getFloodpool() ); - setSpillWay( raxReservoirRecord.getSpillway() ); - setSill( raxReservoirRecord.getSill() ); - setTop( raxReservoirRecord.getTop() ); - setSurchg( raxReservoirRecord.getSurchg() ); - setElev( raxReservoirRecord.getElev() ); - setGates( raxReservoirRecord.getGates() ); - setImpounded( raxReservoirRecord.getImpounded() ); - setUses( raxReservoirRecord.getUses() ); - } - - public String toString() - { - StringDataConverter converter = new StringDataConverter(); - - return "Lid = " + _lid + " | BeginDate = " + converter.getDateStringFromDateLong( _beginDate ) + " | EndDate = " + converter.getDateStringFromDateLong( _endDate ) + "\n" + - " | Name = " + _name + "\n" + " | Type = " + _type + " | Owner = " + _owner + "\n" + - " | DeadPool = " + _deadPool + " | ConserPool = " + _conserPool + " | FloodPool = " + _floodPool + "\n" + - " | SpillWay = " + _spillWay + " | Sill = " + _sill + " | Top = " + _top + "\n" + - " | Surchg = " + _surchg + " | Elev = " + _elev + " | Gates = " + _gates + "\n" + - " | Impounded = " + _impounded + " | Uses = " + _uses; - } - - public String keyString() - { - StringDataConverter converter = new StringDataConverter(); - - return "Lid = " + _lid + " | BeginDate = " + converter.getDateStringFromDateLong( _beginDate ); - } - - public static RaxReservoir getRaxReservoir( RaxReservoirRecord raxReservoirRecord ) - { - return ( new RaxReservoir( raxReservoirRecord ) ); - } - - public static RaxReservoirRecord getRaxReservoirRecord( RaxReservoir raxReservoir ) - { - RaxReservoirRecord raxReservoirRecord = new RaxReservoirRecord(); - - raxReservoirRecord.setLid( raxReservoir.getLid() ); - raxReservoirRecord.setSbd( raxReservoir.getBeginDate() ); - raxReservoirRecord.setSed( raxReservoir.getEndDate() ); - raxReservoirRecord.setName( raxReservoir.getName() ); - raxReservoirRecord.setType( raxReservoir.getType() ); - raxReservoirRecord.setOwner( raxReservoir.getOwner() ); - raxReservoirRecord.setDeadpool( raxReservoir.getDeadPool() ); - raxReservoirRecord.setConserpool( raxReservoir.getConserPool() ); - raxReservoirRecord.setFloodpool( raxReservoir.getFloodPool() ); - raxReservoirRecord.setSpillway( raxReservoir.getSpillWay() ); - raxReservoirRecord.setSill( raxReservoir.getSill() ); - raxReservoirRecord.setTop( raxReservoir.getTop() ); - raxReservoirRecord.setSurchg( raxReservoir.getSurchg() ); - raxReservoirRecord.setElev( raxReservoir.getElev() ); - raxReservoirRecord.setGates( raxReservoir.getGates() ); - raxReservoirRecord.setImpounded( raxReservoir.getImpounded() ); - raxReservoirRecord.setUses( raxReservoir.getUses() ); - - return raxReservoirRecord; - } - - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setBeginDate( long beginDate ) - { - _beginDate = beginDate; - } - public long getBeginDate() - { - return _beginDate; - } - public void setEndDate( long endDate ) - { - _endDate = endDate; - } - public long getEndDate() - { - return _endDate; - } - public void setName( String name ) - { - _name = name; - } - public String getName() - { - return _name; - } - public void setType( String type ) - { - _type = type; - } - public String getType() - { - return _type; - } - public void setOwner( String owner ) - { - _owner = owner; - } - public String getOwner() - { - return _owner; - } - public void setDeadPool( double deadPool ) - { - _deadPool = deadPool; - } - public double getDeadPool() - { - return _deadPool; - } - public void setConserPool( double conserPool ) - { - _conserPool = conserPool; - } - public double getConserPool() - { - return _conserPool; - } - public void setFloodPool( double floodPool ) - { - _floodPool = floodPool; - } - public double getFloodPool() - { - return _floodPool; - } - public void setSpillWay( double spillWay ) - { - _spillWay = spillWay; - } - public double getSpillWay() - { - return _spillWay; - } - public void setSill( double sill ) - { - _sill = sill; - } - public double getSill() - { - return _sill; - } - public void setTop( double top ) - { - _top = top; - } - public double getTop() - { - return _top; - } - public void setSurchg( double surchg ) - { - _surchg = surchg; - } - public double getSurchg() - { - return _surchg; - } - public void setElev( double elev ) - { - _elev = elev; - } - public double getElev() - { - return _elev; - } - public void setGates( int gates ) - { - _gates = gates; - } - public int getGates() - { - return _gates; - } - public void setImpounded( long impounded ) - { - _impounded = impounded; - } - public long getImpounded() - { - return _impounded; - } - public void setUses( String uses ) - { - _uses = uses; - } - public String getUses() - { - return _uses; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRiverCrit.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRiverCrit.java deleted file mode 100644 index ab0677451e..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/RaxRiverCrit.java +++ /dev/null @@ -1,829 +0,0 @@ - package ohd.hseb.raxbase.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.RaxRiverCritRecord; - -public class RaxRiverCrit -{ - private static final int MISSING = -9999; - - private String _lid = null; - private String _pe = null; - private long _validTime = MISSING; - private double _lowScreen = MISSING; - private double _sigRate = MISSING; - private double _screenRate = MISSING; - private double _fis = MISSING; - private double _action = MISSING; - private double _alert = MISSING; - private double _bank = MISSING; - private double _minorFloodStage = MISSING; - private double _moderateFloodStage = MISSING; - private double _majorFloodStage = MISSING; - private double _record = MISSING; - private double _highScreen = MISSING; - private double _damScreen = MISSING; - private double _lowScreenF = MISSING; - private double _sigRateF = MISSING; - private double _screenRateF = MISSING; - private double _fisf = MISSING; - private double _actionF = MISSING; - private double _alertF = MISSING; - private double _bankF = MISSING; - private double _minorFloodFlow = MISSING; - private double _moderateFloodFlow = MISSING; - private double _majorFloodFlow = MISSING; - private double _recordF = MISSING; - private double _highScreenF = MISSING; - private double _damScreenF = MISSING; - private double _sigRateT = MISSING; - private double _screenRateT = MISSING; - private String _lowScreenQ = null; - private String _sigRateQ = null; - private String _screenRateQ = null; - private String _fisQ = null; - private String _actionQ = null; - private String _alertQ = null; - private String _bankQ = null; - private String _floodQ = null; - private String _modFloodQ = null; - private String _majFloodQ = null; - private String _recordQ = null; - private String _highScreenQ = null; - private String _damScreenQ = null; - private String _stream = null; - private double _latitude = MISSING; - private double _longitude = MISSING; - private double _da = MISSING; - private double _mile = MISSING; - private double _zd = MISSING; - private String _vdatum = null; - private double _cb = MISSING; - private String _level = null; - private double _pool = MISSING; - private String _por = null; - private String _tide = null; - private String _backwater = null; - private long _rrevise = MISSING; - private String _rsource = null; - private double _responseTime = MISSING; - private double _thresholdRunoff = MISSING; - private int _uhgDur = MISSING; - private String _remark = null; - - public RaxRiverCrit() {} - - public RaxRiverCrit( RaxRiverCritRecord record ) - { - setLid( record.getLid() ); - setPe( record.getPe1() + record.getPe2() ); - setValidTime( record.getVdtime() ); - setLowScreen( record.getLowscreen() ); - setSigRate( record.getSigrate() ); - setScreenRate( record.getScreenrate() ); - setFis( record.getFis() ); - setAction( record.getAction() ); - setAlert( record.getAlert() ); - setBank( record.getBank() ); - setMinorFloodStage( record.getFlood() ); - setModerateFloodStage( record.getModflood() ); - setMajorFloodStage( record.getMajflood() ); - setRecord( record.getRecord() ); - setHighScreen( record.getHighscreen() ); - setDamScreen( record.getDamscreen() ); - setLowScreenF( record.getLowscreenf() ); - setSigRateF( record.getSigratef() ); - setScreenRateF( record.getScreenratef() ); - setFisF( record.getFisf() ); - setActionF( record.getActionf() ); - setAlertF( record.getAlertf() ); - setBankF( record.getBankf() ); - setMinorFloodFlow( record.getFloodf() ); - setModerateFloodFlow( record.getModfloodf() ); - setMajorFloodFlow( record.getMajfloodf() ); - setRecordF( record.getRecordf() ); - setHighScreenF( record.getHighscreenf() ); - setDamScreenF( record.getDamscreenf() ); - setSigRateT( record.getSigratet() ); - setScreenRateT( record.getScreenratet() ); - setLowScreenQ( record.getLowscreenq() ); - setSigRateQ( record.getSigrateq() ); - setScreenRateQ( record.getScreenrateq() ); - setFisQ( record.getFisq() ); - setActionQ( record.getActionq() ); - setAlertQ( record.getAlertq() ); - setBankQ( record.getBankq() ); - setFloodQ( record.getFloodq() ); - setModFloodQ( record.getModfloodq() ); - setMajFloodQ( record.getMajfloodq() ); - setRecordQ( record.getRecordq() ); - setHighScreenQ( record.getHighscreenq() ); - setDamScreenQ( record.getDamscreenq() ); - setStream( record.getStream() ); - setLatitude( record.getLat() ); - setLongitude( record.getLon() ); - setDa( record.getDa() ); - setMile( record.getMile() ); - setZd( record.getZd() ); - setVdatum( record.getVdatum() ); - setCb( record.getCb() ); - setLevel( record.getLevel() ); - setPool( record.getPool() ); - setPor( record.getPor() ); - setTide( record.getTide() ); - setBackwater( record.getBackwater() ); - setRrevise( record.getRrevise() ); - setRsource( record.getRsource() ); - setResponseTime( record.getResponse_time() ); - setThresholdRunoff( record.getThreshold_runoff() ); - setUhgdur( record.getUhgdur() ); - setRemark( record.getRemark() ); - } - - public RaxRiverCrit( RaxRiverCrit raxRiverCrit ) - { - setLid( raxRiverCrit.getLid() ); - setPe( raxRiverCrit.getPe() ); - setValidTime( raxRiverCrit.getValidTime() ); - setLowScreen( raxRiverCrit.getLowScreen() ); - setSigRate( raxRiverCrit.getSigRate() ); - setScreenRate( raxRiverCrit.getScreenRate() ); - setFis( raxRiverCrit.getFis() ); - setAction( raxRiverCrit.getAction() ); - setAlert( raxRiverCrit.getAlert() ); - setBank( raxRiverCrit.getBank() ); - setMinorFloodStage( raxRiverCrit.getMinorFloodStage() ); - setModerateFloodStage( raxRiverCrit.getModerateFloodStage() ); - setMajorFloodStage( raxRiverCrit.getMajorFloodStage() ); - setRecord( raxRiverCrit.getRecord() ); - setHighScreen( raxRiverCrit.getHighScreen() ); - setDamScreen( raxRiverCrit.getDamScreen() ); - setLowScreenF( raxRiverCrit.getLowScreenF() ); - setSigRateF( raxRiverCrit.getSigRateF() ); - setScreenRateF( raxRiverCrit.getScreenRateF() ); - setFisF( raxRiverCrit.getFisF() ); - setActionF( raxRiverCrit.getActionF() ); - setAlertF( raxRiverCrit.getAlertF() ); - setBankF( raxRiverCrit.getBankF() ); - setMinorFloodFlow( raxRiverCrit.getMinorFloodFlow() ); - setModerateFloodFlow( raxRiverCrit.getModerateFloodFlow() ); - setMajorFloodFlow( raxRiverCrit.getMajorFloodFlow() ); - setRecordF( raxRiverCrit.getRecordF() ); - setHighScreenF( raxRiverCrit.getHighScreenF() ); - setDamScreenF( raxRiverCrit.getDamScreenF() ); - setSigRateT( raxRiverCrit.getSigRateT() ); - setScreenRateT( raxRiverCrit.getScreenRateT() ); - setLowScreenQ( raxRiverCrit.getLowScreenQ() ); - setSigRateQ( raxRiverCrit.getSigRateQ() ); - setScreenRateQ( raxRiverCrit.getScreenRateQ() ); - setFisQ( raxRiverCrit.getFisQ() ); - setActionQ( raxRiverCrit.getActionQ() ); - setAlertQ( raxRiverCrit.getAlertQ() ); - setBankQ( raxRiverCrit.getBankQ() ); - setFloodQ( raxRiverCrit.getFloodQ() ); - setModFloodQ( raxRiverCrit.getModFloodQ() ); - setMajFloodQ( raxRiverCrit.getMajFloodQ() ); - setRecordQ( raxRiverCrit.getRecordQ() ); - setHighScreenQ( raxRiverCrit.getHighScreenQ() ); - setDamScreenQ( raxRiverCrit.getDamScreenQ() ); - setStream( raxRiverCrit.getStream() ); - setLatitude( raxRiverCrit.getLatitude() ); - setLongitude( raxRiverCrit.getLongitude() ); - setDa( raxRiverCrit.getDa() ); - setMile( raxRiverCrit.getMile() ); - setZd( raxRiverCrit.getZd() ); - setVdatum( raxRiverCrit.getVdatum() ); - setCb( raxRiverCrit.getCb() ); - setLevel( raxRiverCrit.getLevel() ); - setPool( raxRiverCrit.getPool() ); - setPor( raxRiverCrit.getPor() ); - setTide( raxRiverCrit.getTide() ); - setBackwater( raxRiverCrit.getBackwater() ); - setRrevise( raxRiverCrit.getRrevise() ); - setRsource( raxRiverCrit.getRsource() ); - setResponseTime( raxRiverCrit.getResponseTime() ); - setThresholdRunoff( raxRiverCrit.getThresholdRunoff() ); - setUhgdur( raxRiverCrit.getUhgdur() ); - setRemark( raxRiverCrit.getRemark() ); - } - - public static RaxRiverCrit getRaxRiverCrit( RaxRiverCritRecord record ) - { - return ( new RaxRiverCrit( record ) ); - } - - public static RaxRiverCritRecord getRaxRiverCritRecord( RaxRiverCrit raxRiverCrit ) - { - RaxRiverCritRecord record = new RaxRiverCritRecord(); - - record.setLid( raxRiverCrit.getLid() ); - record.setPe1( PEManager.getPe1FromPE( raxRiverCrit.getPe() ) ); - record.setPe2( PEManager.getPe2FromPE( raxRiverCrit.getPe() ) ); - record.setVdtime( raxRiverCrit.getValidTime() ); - record.setLowscreen( raxRiverCrit.getLowScreen() ); - record.setSigrate(raxRiverCrit.getSigRate()); - record.setScreenrate(raxRiverCrit.getScreenRate()); - record.setFis(raxRiverCrit.getFis()); - record.setAction(raxRiverCrit.getAction()); - record.setAlert(raxRiverCrit.getAlert()); - record.setBank(raxRiverCrit.getBank()); - record.setFlood(raxRiverCrit.getMinorFloodStage()); - record.setModflood(raxRiverCrit.getModerateFloodStage()); - record.setMajflood( raxRiverCrit.getMajorFloodStage() ); - record.setRecord( raxRiverCrit.getRecord() ); - record.setHighscreen( raxRiverCrit.getHighScreen() ); - record.setDamscreen( raxRiverCrit.getDamScreen() ); - record.setLowscreenf( raxRiverCrit.getLowScreenF() ); - record.setSigratef( raxRiverCrit.getSigRateF() ); - record.setScreenratef( raxRiverCrit.getScreenRateF() ); - record.setFisf( raxRiverCrit.getFisF() ); - record.setActionf( raxRiverCrit.getActionF() ); - record.setAlertf( raxRiverCrit.getAlertF() ); - record.setBankf( raxRiverCrit.getBankF() ); - record.setFloodf( raxRiverCrit.getMinorFloodFlow() ); - record.setModfloodf( raxRiverCrit.getModerateFloodFlow() ); - record.setMajfloodf( raxRiverCrit.getMajorFloodFlow() ); - record.setRecordf( raxRiverCrit.getRecordF() ); - record.setHighscreenf( raxRiverCrit.getHighScreenF() ); - record.setDamscreenf( raxRiverCrit.getDamScreenF() ); - record.setSigratet( raxRiverCrit.getSigRateT() ); - record.setScreenratet( raxRiverCrit.getScreenRateT() ); - record.setLowscreenq( raxRiverCrit.getLowScreenQ() ); - record.setSigrateq( raxRiverCrit.getSigRateQ() ); - record.setScreenrateq( raxRiverCrit.getScreenRateQ() ); - record.setFisq( raxRiverCrit.getFisQ() ); - record.setActionq( raxRiverCrit.getActionQ() ); - record.setAlertq( raxRiverCrit.getAlertQ() ); - record.setBankq( raxRiverCrit.getBankQ() ); - record.setFloodq( raxRiverCrit.getFloodQ() ); - record.setModfloodq( raxRiverCrit.getModFloodQ() ); - record.setMajfloodq( raxRiverCrit.getMajFloodQ() ); - record.setRecordq( raxRiverCrit.getRecordQ() ); - record.setHighscreenq( raxRiverCrit.getHighScreenQ() ); - record.setDamscreenq( raxRiverCrit.getDamScreenQ() ); - record.setStream( raxRiverCrit.getStream() ); - record.setLat( raxRiverCrit.getLatitude() ); - record.setLon( raxRiverCrit.getLongitude() ); - record.setDa( raxRiverCrit.getDa() ); - record.setMile( raxRiverCrit.getMile() ); - record.setZd( raxRiverCrit.getZd() ); - record.setVdatum( raxRiverCrit.getVdatum() ); - record.setCb( raxRiverCrit.getCb() ); - record.setLevel( raxRiverCrit.getLevel() ); - record.setPool( raxRiverCrit.getPool() ); - record.setPor( raxRiverCrit.getPor() ); - record.setTide( raxRiverCrit.getTide() ); - record.setBackwater( raxRiverCrit.getBackwater() ); - record.setRrevise( raxRiverCrit.getRrevise() ); - record.setRsource( raxRiverCrit.getRsource() ); - record.setResponse_time( raxRiverCrit.getResponseTime() ); - record.setThreshold_runoff( raxRiverCrit.getThresholdRunoff() ); - record.setUhgdur( raxRiverCrit.getUhgdur() ); - record.setRemark( raxRiverCrit.getRemark()); - - return record; - } - - public String keyString() - { - return "Lid = " + _lid + " | Pe = " + _pe + " ValidTime = " + DbTimeHelper.getDateStringFromLongTime( _validTime ); - } - - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setPe( String pe ) - { - _pe = pe; - } - public String getPe() - { - return _pe; - } - public void setValidTime( long validTime ) - { - _validTime = validTime; - } - public long getValidTime() - { - return _validTime; - } - public void setLowScreen( double lowScreen ) - { - _lowScreen = lowScreen; - } - public double getLowScreen() - { - return _lowScreen; - } - - public void setSigRate( double sigrate ) - { - _sigRate = sigrate; - } - - public double getSigRate() - { - return _sigRate; - } - - public void setScreenRate( double screenRate ) - { - _screenRate = screenRate; - } - - public double getScreenRate() - { - return _screenRate; - } - - public void setFis( double fis ) - { - _fis = fis; - } - - public double getFis() - { - return _fis; - } - - public void setAction( double action ) - { - _action = action; - } - - public double getAction() - { - return _action; - } - - public void setAlert( double alert ) - { - _alert = alert; - } - - public double getAlert() - { - return _alert; - } - public void setBank( double bank ) - { - _bank = bank; - } - public double getBank() - { - return _bank; - } - public void setMinorFloodStage( double minorFloodStage ) - { - _minorFloodStage = minorFloodStage; - } - public double getMinorFloodStage() - { - return _minorFloodStage; - } - public void setModerateFloodStage( double moderateFloodStage ) - { - _moderateFloodStage = moderateFloodStage; - } - public double getModerateFloodStage() - { - return _moderateFloodStage; - } - public void setMajorFloodStage( double majorFloodStage ) - { - _majorFloodStage = majorFloodStage; - } - public double getMajorFloodStage() - { - return _majorFloodStage; - } - public void setRecord( double record ) - { - _record = record; - } - public double getRecord() - { - return _record; - } - public void setHighScreen( double highscreen ) - { - _highScreen = highscreen; - } - public double getHighScreen() - { - return _highScreen; - } - public void setDamScreen( double damscreen ) - { - _damScreen = damscreen; - } - public double getDamScreen() - { - return _damScreen; - } - public void setLowScreenF( double lowscreenf ) - { - _lowScreenF = lowscreenf; - } - public double getLowScreenF() - { - return _lowScreenF; - } - public void setSigRateF( double sigratef ) - { - _sigRateF = sigratef; - } - public double getSigRateF() - { - return _sigRateF; - } - public void setScreenRateF( double screenratef ) - { - _screenRateF = screenratef; - } - public double getScreenRateF() - { - return _screenRateF; - } - public void setFisF( double fisf ) - { - _fisf = fisf; - } - public double getFisF() - { - return _fisf; - } - public void setActionF( double actionf ) - { - _actionF = actionf; - } - public double getActionF() - { - return _actionF; - } - public void setAlertF( double alertf ) - { - _alertF = alertf; - } - public double getAlertF() - { - return _alertF; - } - public void setBankF( double bankf ) - { - _bankF = bankf; - } - public double getBankF() - { - return _bankF; - } - public void setMinorFloodFlow( double minorFloodFlow ) - { - _minorFloodFlow = minorFloodFlow; - } - public double getMinorFloodFlow() - { - return _minorFloodFlow; - } - public void setModerateFloodFlow( double moderateFloodFlow ) - { - _moderateFloodFlow = moderateFloodFlow; - } - public double getModerateFloodFlow() - { - return _moderateFloodFlow; - } - - public void setMajorFloodFlow( double majorFloodFlow ) - { - _majorFloodFlow = majorFloodFlow; - } - - public double getMajorFloodFlow() - { - return _majorFloodFlow; - } - - public void setRecordF( double recordf ) - { - _recordF = recordf; - } - - public double getRecordF() - { - return _recordF; - } - - public void setHighScreenF( double highscreenf ) - { - _highScreenF = highscreenf; - } - - public double getHighScreenF() - { - return _highScreenF; - } - - public void setDamScreenF( double damscreenf ) - { - _damScreenF = damscreenf; - } - - public double getDamScreenF() - { - return _damScreenF; - } - - public void setSigRateT( double sigratet ) - { - _sigRateT = sigratet; - } - - public double getSigRateT() - { - return _sigRateT; - } - - public void setScreenRateT( double screenratet ) - { - _screenRateT = screenratet; - } - - public double getScreenRateT() - { - return _screenRateT; - } - - public void setLowScreenQ( String lowscreenq ) - { - _lowScreenQ = lowscreenq; - } - - public String getLowScreenQ() - { - return _lowScreenQ; - } - - public void setSigRateQ( String sigrateq ) - { - _sigRateQ = sigrateq; - } - - public String getSigRateQ() - { - return _sigRateQ; - } - - public void setScreenRateQ( String screenrateq ) - { - _screenRateQ = screenrateq; - } - - public String getScreenRateQ() - { - return _screenRateQ; - } - - public void setFisQ( String fisq ) - { - _fisQ = fisq; - } - - public String getFisQ() - { - return _fisQ; - } - - public void setActionQ( String actionq ) - { - _actionQ = actionq; - } - - public String getActionQ() - { - return _actionQ; - } - public void setAlertQ( String alertq ) - { - _alertQ = alertq; - } - public String getAlertQ() - { - return _alertQ; - } - public void setBankQ( String bankq ) - { - _bankQ = bankq; - } - public String getBankQ() - { - return _bankQ; - } - public void setFloodQ( String floodq ) - { - _floodQ = floodq; - } - public String getFloodQ() - { - return _floodQ; - } - public void setModFloodQ( String modfloodq ) - { - _modFloodQ = modfloodq; - } - public String getModFloodQ() - { - return _modFloodQ; - } - public void setMajFloodQ( String majfloodq ) - { - _majFloodQ = majfloodq; - } - public String getMajFloodQ() - { - return _majFloodQ; - } - public void setRecordQ( String recordq ) - { - _recordQ = recordq; - } - public String getRecordQ() - { - return _recordQ; - } - public void setHighScreenQ( String highscreenq ) - { - _highScreenQ = highscreenq; - } - public String getHighScreenQ() - { - return _highScreenQ; - } - public void setDamScreenQ( String damscreenq ) - { - _damScreenQ = damscreenq; - } - public String getDamScreenQ() - { - return _damScreenQ; - } - public void setStream( String stream ) - { - _stream = stream; - } - public String getStream() - { - return _stream; - } - public void setLatitude( double latitude ) - { - _latitude = latitude; - } - public double getLatitude() - { - return _latitude; - } - public void setLongitude( double longitude ) - { - _longitude = longitude; - } - public double getLongitude() - { - return _longitude; - } - public void setDa( double da ) - { - _da = da; - } - public double getDa() - { - return _da; - } - public void setMile( double mile ) - { - _mile = mile; - } - public double getMile() - { - return _mile; - } - public void setZd( double zd ) - { - _zd = zd; - } - public double getZd() - { - return _zd; - } - public void setVdatum( String vdatum ) - { - _vdatum = vdatum; - } - public String getVdatum() - { - return _vdatum; - } - public void setCb( double cb ) - { - _cb = cb; - } - public double getCb() - { - return _cb; - } - public void setLevel( String level ) - { - _level = level; - } - public String getLevel() - { - return _level; - } - public void setPool( double pool ) - { - _pool = pool; - } - public double getPool() - { - return _pool; - } - public void setPor( String por ) - { - _por = por; - } - public String getPor() - { - return _por; - } - public void setTide( String tide ) - { - _tide = tide; - } - public String getTide() - { - return _tide; - } - public void setBackwater( String backwater ) - { - _backwater = backwater; - } - public String getBackwater() - { - return _backwater; - } - public void setRrevise( long rrevise ) - { - _rrevise = rrevise; - } - public long getRrevise() - { - return _rrevise; - } - public void setRsource( String rsource ) - { - _rsource = rsource; - } - public String getRsource() - { - return _rsource; - } - public void setResponseTime( double responseTime ) - { - _responseTime = responseTime; - } - public double getResponseTime() - { - return _responseTime; - } - public void setThresholdRunoff( double thresholdRunoff ) - { - _thresholdRunoff = thresholdRunoff; - } - public double getThresholdRunoff() - { - return _thresholdRunoff; - } - public void setUhgdur( int uhgdur ) - { - _uhgDur = uhgdur; - } - public int getUhgdur() - { - return _uhgDur; - } - public void setRemark( String remark ) - { - _remark = remark; - } - public String getRemark() - { - return _remark; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Rfc.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Rfc.java deleted file mode 100644 index f1c6aaa987..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Rfc.java +++ /dev/null @@ -1,54 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.RfcRecord; - -public class Rfc -{ - private String _rfc = null; - - public Rfc(){} - - public Rfc( Rfc rfc ) - { - setRfc( rfc.getRfc() ); - } - - public Rfc( RfcRecord rfcRecord ) - { - setRfc( rfcRecord.getRfc() ); - } - - public static Rfc getRfc( RfcRecord record ) - { - return new Rfc( record ); - } - - public static RfcRecord getRfcRecord( Rfc rfc ) - { - RfcRecord record = new RfcRecord(); - - record.setRfc( rfc.getRfc() ); - - return record; - } - - public String toString() - { - return "Rfc = " + _rfc; - } - - public String keyString() - { - return "Rfc = " + _rfc; - } - - public void setRfc( String rfc ) - { - this._rfc = rfc; - } - - public String getRfc() - { - return _rfc; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Sensok.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Sensok.java deleted file mode 100644 index e76c8c241d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/Sensok.java +++ /dev/null @@ -1,260 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.SensokRecord; - -public class Sensok -{ - private static final short MISSING = -9999; - - private String _lid = null; - private String _pe = null; - private String _dur = null; - private short _idur = MISSING; - private String _ts = null; - private String _extremum = null; - private String _p = null; - private long _oktime = MISSING; - private String _ok = null; - private String _init = null; - private String _reason = null; - private String _agcode = null; - private String _agloc = null; - private String _comment = null; - - public Sensok(){} - - public Sensok( Sensok sensok ) - { - setLid( sensok.getLid() ); - setPe( sensok.getPe() ); - setDur( sensok.getDur() ); - setIdur( sensok.getIdur() ); - setTs( sensok.getTs() ); - setExtremum( sensok.getExtremum() ); - setP( sensok.getP() ); - setOktime( sensok.getOktime() ); - setOk( sensok.getOk() ); - setInit( sensok.getInit() ); - setReason( sensok.getReason() ); - setAgcode( sensok.getAgcode() ); - setAgloc( sensok.getAgloc() ); - setComment( sensok.getComment() ); - } - - public Sensok( SensokRecord sensokRecord ) - { - setLid( sensokRecord.getLid() ); - setPe( PEManager.getPEFromPe1Pe2( sensokRecord.getPe1(), sensokRecord.getPe2() ) ); - setDur( sensokRecord.getDur() ); - setIdur( sensokRecord.getIdur() ); - setTs( TSManager.getTSFromTandS( sensokRecord.getT(), sensokRecord.getS() ) ); - setExtremum( sensokRecord.getE() ); - setP( sensokRecord.getP() ); - setOktime( sensokRecord.getOktime() ); - setOk( sensokRecord.getOk() ); - setInit( sensokRecord.getInit() ); - setReason( sensokRecord.getReason() ); - setAgcode( sensokRecord.getAgcode() ); - setAgloc( sensokRecord.getAgloc() ); - setComment( sensokRecord.getComment() ); - } - - public static Sensok getSensok( SensokRecord sensokRecord ) - { - return ( new Sensok( sensokRecord ) ); - } - - public static SensokRecord getSensokRecord( Sensok sensok ) - { - SensokRecord sensokRecord = new SensokRecord(); - - sensokRecord.setLid( sensok.getLid() ); - sensokRecord.setPe1( PEManager.getPe1FromPE( sensok.getPe() ) ); - sensokRecord.setPe2( PEManager.getPe2FromPE( sensok.getPe() ) ); - sensokRecord.setDur( sensok.getDur() ); - sensokRecord.setIdur( sensok.getIdur() ); - sensokRecord.setT( TSManager.getTFromTS( sensok.getTs() ) ); - sensokRecord.setS( TSManager.getSFromTS( sensok.getTs() ) ); - sensokRecord.setE( sensok.getExtremum() ); - sensokRecord.setP( sensok.getP() ); - sensokRecord.setOktime( sensok.getOktime() ); - sensokRecord.setOk( sensok.getOk() ); - sensokRecord.setInit( sensok.getInit() ); - sensokRecord.setReason( sensok.getReason() ); - sensokRecord.setAgcode( sensok.getAgcode() ); - sensokRecord.setAgloc( sensok.getAgloc() ); - sensokRecord.setComment( sensok.getComment() ); - - return sensokRecord; - } - - public String keyString() - { - String keyString = "LID = " + getKeyValue( _lid ) + " | PE = " + getKeyValue( _pe ) + " | Dur = " + getKeyValue( _dur ) + - " | IDur = " + getKeyValue( _idur ) + " | TS = " + getKeyValue( _ts ) + " | Extremum = " + getKeyValue( _extremum ) + - " | P = " + getKeyValue( _p ) + " | OKTime: " + DbTimeHelper.getDateStringFromLongTime( _oktime ); - - return keyString; - } - - private String getKeyValue( String str ) - { - String returnValue = "NULL"; - - if ( str != null ) - { - returnValue = str; - } - - return returnValue; - } - - private String getKeyValue( short number ) - { - return ( getKeyValue( number + "" ) ); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( String dur ) - { - _dur = dur; - } - - public String getDur() - { - return _dur; - } - - public void setIdur( short idur ) - { - _idur = idur; - } - - public short getIdur() - { - return _idur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setP( String p ) - { - _p = p; - } - - public String getP() - { - return _p; - } - - public void setOktime( long oktime ) - { - _oktime = oktime; - } - - public long getOktime() - { - return _oktime; - } - - public void setOk( String ok ) - { - _ok = ok; - } - - public String getOk() - { - return _ok; - } - - public void setInit( String init ) - { - _init = init; - } - - public String getInit() - { - return _init; - } - - public void setReason( String reason ) - { - _reason = reason; - } - - public String getReason() - { - return _reason; - } - - public void setAgcode( String agcode ) - { - _agcode = agcode; - } - - public String getAgcode() - { - return _agcode; - } - - public void setAgloc( String agloc ) - { - _agloc = agloc; - } - - public String getAgloc() - { - return _agloc; - } - - public void setComment( String comment ) - { - _comment = comment; - } - - public String getComment() - { - return _comment; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefDuration.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefDuration.java deleted file mode 100644 index da0758f94b..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefDuration.java +++ /dev/null @@ -1,86 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.ShefdurRecord; - -public class ShefDuration -{ - private short _iduration; - private String _duration; - private String _name; - - public ShefDuration() - { - } - - public ShefDuration( ShefDuration shefDur ) - { - this( shefDur.getName(), shefDur.getDuration(), shefDur.getIduration() ); - } - - public ShefDuration( String name, String duration, short iduration ) - { - setName( name ); - setDuration( duration ); - setIduration( iduration ); - } - - public ShefDuration( ShefdurRecord record ) - { - setName( record.getName() ); - setDuration( record.getDur() ); - setIduration( record.getIdur() ); - } - - public static ShefDuration getShefDuration( ShefdurRecord record ) - { - return new ShefDuration( record ); - } - - public static ShefdurRecord getShefDurRecord( ShefDuration shefDuration ) - { - ShefdurRecord record = new ShefdurRecord(); - - record.setDur( shefDuration.getDuration() ); - record.setIdur( shefDuration.getIduration() ); - record.setName( shefDuration.getName() ); - - return record; - } - - public String toString() - { - return "Duration = " + _duration + - " | IDuration = " + _iduration + - " | Name = " + _name; - } - - public String keyString() - { - return "Duration = " + _duration; - } - - public void setIduration( short iduration ) - { - _iduration = iduration; - } - public short getIduration() - { - return _iduration; - } - public void setDuration( String duration ) - { - _duration = duration; - } - public String getDuration() - { - return _duration; - } - public void setName( String name ) - { - _name = name; - } - public String getName() - { - return _name; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefExtremum.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefExtremum.java deleted file mode 100644 index c0e1d0545e..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefExtremum.java +++ /dev/null @@ -1,72 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.ShefexRecord; - -public class ShefExtremum -{ - private String _extremum = null; - private String _name = null; - - public ShefExtremum(){} - - public ShefExtremum( String name, String extremum ) - { - setExtremum( extremum ); - setName( name ); - } - - public ShefExtremum( ShefExtremum shefExtremum ) - { - this( shefExtremum.getName(), shefExtremum.getExtremum() ); - } - - public ShefExtremum ( ShefexRecord shefExRecord ) - { - setExtremum( shefExRecord.getE() ); - setName( shefExRecord.getName() ); - } - - public static ShefExtremum getShefExtremum( ShefexRecord shefExRecord ) - { - return new ShefExtremum( shefExRecord ); - } - - public static ShefexRecord getShefExRecord( ShefExtremum shefExtremum ) - { - ShefexRecord record = new ShefexRecord(); - - record.setE( shefExtremum.getExtremum() ); - record.setName( shefExtremum.getName() ); - - return record; - } - - public String toString() - { - return "Extremum = " + _extremum + - " | Name = " + _name; - } - - public String keyString() - { - return "Extremum = " + _extremum; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - public String getExtremum() - { - return _extremum; - } - public void setName( String name ) - { - _name = name; - } - public String getName() - { - return _name; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPE.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPE.java deleted file mode 100644 index e1ca232347..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPE.java +++ /dev/null @@ -1,108 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.ShefpeRecord; - -public class ShefPE -{ - private String _pe = null; - private String _name = null; - private String _engUnit = null; - private String _metUnit = null; - - public ShefPE(){} - - public ShefPE( String name, String pe ) - { - setName( name ); - setPe( pe ); - } - - public ShefPE( ShefPE shefPE ) - { - setName( shefPE.getName() ); - setPe( shefPE.getPe() ); - setEngUnit( shefPE.getEngUnit() ); - setMetUnit( shefPE.getMetUnit() ); - } - - public ShefPE( ShefpeRecord shefPeRecord ) - { - setName( shefPeRecord.getName() ); - setPe( PEManager.getPEFromPe1Pe2( shefPeRecord.getPe1(), shefPeRecord.getPe2() ) ); - setEngUnit( shefPeRecord.getEng_unit() ); - setMetUnit( shefPeRecord.getMet_unit() ); - } - - public static ShefPE getShefPE( ShefpeRecord shefPeRecord ) - { - return new ShefPE( shefPeRecord ); - } - - public static ShefpeRecord getShefPeRecord( ShefPE shefPE ) - { - ShefpeRecord record = new ShefpeRecord(); - - record.setPe1( PEManager.getPe1FromPE( shefPE.getPe() ) ); - record.setPe2( PEManager.getPe2FromPE( shefPE.getPe() ) ); - record.setName( shefPE.getName() ); - record.setEng_unit( shefPE.getEngUnit() ); - record.setMet_unit( shefPE.getMetUnit() ); - - return record; - } - - public String toString() - { - return "PE = " + _pe + - " | Name = " + _name + - " | EngUnit = " + _engUnit + - " | MetUnit = " + _metUnit; - } - - public String keyString() - { - return "PE = " + _pe; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setEngUnit( String engUnit ) - { - _engUnit = engUnit; - } - - public String getEngUnit() - { - return _engUnit; - } - - public void setMetUnit( String metUnit ) - { - _metUnit = metUnit; - } - - public String getMetUnit() - { - return _metUnit; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPE1.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPE1.java deleted file mode 100644 index 5b388e6683..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPE1.java +++ /dev/null @@ -1,69 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.Shefpe1Record; - -public class ShefPE1 -{ - private String _pe1 = null; - private String _name = null; - - public ShefPE1(){} - - public ShefPE1( ShefPE1 shefPE1 ) - { - setName( shefPE1.getName() ); - setPe1( shefPE1.getPe1() ); - } - - public ShefPE1( Shefpe1Record shefPe1Record ) - { - setName( shefPe1Record.getName() ); - setPe1( shefPe1Record.getPe1() ); - } - - public static ShefPE1 getShefPE1( Shefpe1Record shefPe1Record ) - { - return new ShefPE1( shefPe1Record ); - } - - public static Shefpe1Record getShefPe1Record( ShefPE1 shefPE1 ) - { - Shefpe1Record record = new Shefpe1Record(); - - record.setPe1( shefPE1.getPe1() ); - record.setName( shefPE1.getName() ); - - return record; - } - - public String toString() - { - return "PE1 = " + _pe1 + - " | Name = " + _name; - } - - public String keyString() - { - return "PE1 = " + _pe1; - } - - public void setPe1( String pe1 ) - { - _pe1 = pe1; - } - - public String getPe1() - { - return _pe1; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPETrans.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPETrans.java deleted file mode 100644 index 11e21eb5ae..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefPETrans.java +++ /dev/null @@ -1,106 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.PEManager; -import ohd.hseb.raxdb.generated.ShefpetransRecord; - -public class ShefPETrans -{ - private static final short MISSING = -9999; - - private String _pe = null; - private String _codePosition = null; - private int _codedValue = MISSING; - private String _valueTrans = null; - - public ShefPETrans(){} - - public ShefPETrans( ShefPETrans shefPeTrans ) - { - setPe( shefPeTrans.getPe() ); - setCodePosition( shefPeTrans.getCodePosition() ); - setCodedValue( shefPeTrans.getCodedValue() ); - setValueTrans( shefPeTrans.getValueTrans() ); - } - - public ShefPETrans( ShefpetransRecord shefPeTransRecord ) - { - setPe( PEManager.getPEFromPe1Pe2( shefPeTransRecord.getPe1(), shefPeTransRecord.getPe2() ) ); - setCodePosition( shefPeTransRecord.getCode_position() ); - setCodedValue( shefPeTransRecord.getCoded_value() ); - setValueTrans( shefPeTransRecord.getValue_trans() ); - } - - public static ShefPETrans getShefPeTrans( ShefpetransRecord shefPeTransRecord ) - { - return new ShefPETrans ( shefPeTransRecord ); - } - - public static ShefpetransRecord getShefPeTransRecord( ShefPETrans shefPeTrans ) - { - ShefpetransRecord record = new ShefpetransRecord(); - - record.setPe1( PEManager.getPe1FromPE( shefPeTrans.getPe() ) ); - record.setPe2( PEManager.getPe2FromPE( shefPeTrans.getPe() ) ); - record.setCode_position( shefPeTrans.getCodePosition() ); - record.setCoded_value( shefPeTrans.getCodedValue() ); - record.setValue_trans( shefPeTrans.getValueTrans() ); - - return record; - } - - public String toString() - { - return "PE = " + _pe + - " | CodePosition = " + _codePosition + - " | CodedValue = " + _codedValue + - " | ValueTrans = " + _valueTrans; - } - - public String keyString() - { - return "PE = " + _pe + - " | CodedValue = " + _codedValue + - " | CodePosition = " + _codePosition; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setCodePosition( String codePosition ) - { - _codePosition = codePosition; - } - - public String getCodePosition() - { - return _codePosition; - } - - public void setCodedValue( int codedValue ) - { - _codedValue = codedValue; - } - - public int getCodedValue() - { - return _codedValue; - } - - public void setValueTrans( String valueTrans ) - { - _valueTrans = valueTrans; - } - - public String getValueTrans() - { - return _valueTrans; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefProb.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefProb.java deleted file mode 100644 index ede3ba5455..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefProb.java +++ /dev/null @@ -1,89 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.ShefprobRecord; - -public class ShefProb -{ - private float _probability; - private String _p; - private String _name; - - public ShefProb(){} - - public ShefProb( ShefProb shefProb ) - { - this( shefProb.getName(), shefProb.getP(), shefProb.getProbability() ); - } - - public ShefProb( String name, String p, float probability ) - { - setName( name ); - setP( p ); - setProbability( probability ); - } - - public ShefProb( ShefprobRecord shefProbRecord ) - { - setName( shefProbRecord.getName() ); - setP( shefProbRecord.getP() ); - setProbability( shefProbRecord.getProbability() ); - } - - public static ShefProb getShefProb( ShefprobRecord shefProbRecord ) - { - return new ShefProb( shefProbRecord ); - } - - public static ShefprobRecord getShefProbRecord( ShefProb shefProb ) - { - ShefprobRecord record = new ShefprobRecord(); - - record.setName( shefProb.getName() ); - record.setP( shefProb.getP() ); - record.setProbability( shefProb.getProbability() ); - - return record; - } - - public String toString() - { - return "P = " + _p + - " | Probability = " + _probability + - " | Name = " + _name; - } - - public String keyString() - { - return "P = " + _p; - } - - public void setProbability( float probability ) - { - _probability = probability; - } - - public float getProbability() - { - return _probability; - } - - public void setP( String p ) - { - _p = p; - } - - public String getP() - { - return _p; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefQC.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefQC.java deleted file mode 100644 index 0c37bbdbc4..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefQC.java +++ /dev/null @@ -1,86 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.ShefqcRecord; - -public class ShefQC -{ - private static final short MISSING = -9999; - - private String _shefQualifierCode = null; - private int _power = MISSING; - private String _name = null; - - public ShefQC(){} - - public ShefQC( ShefQC shefQC ) - { - setShefQualifierCode( shefQC.getShefQualifierCode() ); - setPower( shefQC.getPower() ); - setName( shefQC.getName() ); - } - - public ShefQC( ShefqcRecord shefQCRecord ) - { - setShefQualifierCode( shefQCRecord.getShef_qualifier_code() ); - setPower( shefQCRecord.getPower() ); - setName( shefQCRecord.getName() ); - } - - public static ShefQC getShefProb( ShefqcRecord shefQCRecord ) - { - return new ShefQC( shefQCRecord ); - } - - public static ShefqcRecord getShefQCRecord( ShefQC shefQC ) - { - ShefqcRecord record = new ShefqcRecord(); - - record.setShef_qualifier_code( shefQC.getShefQualifierCode() ); - record.setPower( shefQC.getPower() ); - record.setName( shefQC.getName() ); - - return record; - } - - public String toString() - { - return "ShefQualifierCode = " + _shefQualifierCode + - " | Power = " + _power + - " | Name = " + _name; - } - - public String keyString() - { - return "Power = " + _power; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setShefQualifierCode( String shefQualifierCode ) - { - _shefQualifierCode = shefQualifierCode; - } - - public String getShefQualifierCode() - { - return _shefQualifierCode; - } - - public void setPower( int power ) - { - _power = power; - } - - public int getPower() - { - return _power; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefTS.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefTS.java deleted file mode 100644 index fb509a1419..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/ShefTS.java +++ /dev/null @@ -1,72 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxbase.util.TSManager; -import ohd.hseb.raxdb.generated.SheftsRecord; - -public class ShefTS -{ - private String _ts = null; - private String _name = null; - - public ShefTS(){} - - public ShefTS( String name, String ts ) - { - setTs( ts ); - setName( name ); - } - - public ShefTS( ShefTS shefTS ) - { - this( shefTS.getName(), shefTS.getTs() ); - } - - public ShefTS( SheftsRecord shefTSRecord ) - { - setTs( TSManager.getTSFromTandS( shefTSRecord.getT(), shefTSRecord.getS() ) ); - setName( shefTSRecord.getName() ); - } - - public static ShefTS getShefTS( SheftsRecord record ) - { - return new ShefTS( record ); - } - - public static SheftsRecord getShefTSRecord( ShefTS shefTS ) - { - SheftsRecord record = new SheftsRecord(); - - record.setT( TSManager.getTFromTS( shefTS.getTs() ) ); - record.setS( TSManager.getSFromTS( shefTS.getTs() ) ); - record.setName( shefTS.getName() ); - - return record; - } - - public String toString() - { - return "TS = " + _ts + - " | Name = " + _name; - } - - public String keyString() - { - return "TS = " + _ts; - } - public void setTs( String ts ) - { - _ts = ts; - } - public String getTs() - { - return _ts; - } - public void setName( String name ) - { - _name = name; - } - public String getName() - { - return _name; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/SlopeProfile.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/SlopeProfile.java deleted file mode 100644 index c8fdcd4883..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/SlopeProfile.java +++ /dev/null @@ -1,938 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.SlopeprofileRecord; - -public class SlopeProfile -{ - private String lid; - private String marker; - private long begdate; - private long enddate; - private float distance01; - private float distance02; - private float distance03; - private float distance04; - private float distance05; - private float distance06; - private float distance07; - private float distance08; - private float distance09; - private float distance10; - private float distance11; - private float distance12; - private float distance13; - private float distance14; - private float distance15; - private float distance16; - private float distance17; - private float distance18; - private float distance19; - private float distance20; - private float distance21; - private float distance22; - private float distance23; - private float distance24; - private float distance25; - private float distance26; - private float distance27; - private float distance28; - private float distance29; - private float distance30; - private float elevation01; - private float elevation02; - private float elevation03; - private float elevation04; - private float elevation05; - private float elevation06; - private float elevation07; - private float elevation08; - private float elevation09; - private float elevation10; - private float elevation11; - private float elevation12; - private float elevation13; - private float elevation14; - private float elevation15; - private float elevation16; - private float elevation17; - private float elevation18; - private float elevation19; - private float elevation20; - private float elevation21; - private float elevation22; - private float elevation23; - private float elevation24; - private float elevation25; - private float elevation26; - private float elevation27; - private float elevation28; - private float elevation29; - private float elevation30; - - - public SlopeProfile(){} - - public SlopeProfile(SlopeProfile slopeProfile) - { - setLid(slopeProfile.getLid()); - setMarker(slopeProfile.getMarker()); - setBegdate(slopeProfile.getBegdate()); - setEnddate(slopeProfile.getEnddate()); - setDistance01(slopeProfile.getDistance01()); - setDistance02(slopeProfile.getDistance02()); - setDistance03(slopeProfile.getDistance03()); - setDistance04(slopeProfile.getDistance04()); - setDistance05(slopeProfile.getDistance05()); - setDistance06(slopeProfile.getDistance06()); - setDistance07(slopeProfile.getDistance07()); - setDistance08(slopeProfile.getDistance08()); - setDistance09(slopeProfile.getDistance09()); - setDistance10(slopeProfile.getDistance10()); - setDistance11(slopeProfile.getDistance11()); - setDistance12(slopeProfile.getDistance12()); - setDistance13(slopeProfile.getDistance13()); - setDistance14(slopeProfile.getDistance14()); - setDistance15(slopeProfile.getDistance15()); - setDistance16(slopeProfile.getDistance16()); - setDistance17(slopeProfile.getDistance17()); - setDistance18(slopeProfile.getDistance18()); - setDistance19(slopeProfile.getDistance19()); - setDistance20(slopeProfile.getDistance20()); - setDistance21(slopeProfile.getDistance21()); - setDistance22(slopeProfile.getDistance22()); - setDistance23(slopeProfile.getDistance23()); - setDistance24(slopeProfile.getDistance24()); - setDistance25(slopeProfile.getDistance25()); - setDistance26(slopeProfile.getDistance26()); - setDistance27(slopeProfile.getDistance27()); - setDistance28(slopeProfile.getDistance28()); - setDistance29(slopeProfile.getDistance29()); - setDistance30(slopeProfile.getDistance30()); - setElevation01(slopeProfile.getElevation01()); - setElevation02(slopeProfile.getElevation02()); - setElevation03(slopeProfile.getElevation03()); - setElevation04(slopeProfile.getElevation04()); - setElevation05(slopeProfile.getElevation05()); - setElevation06(slopeProfile.getElevation06()); - setElevation07(slopeProfile.getElevation07()); - setElevation08(slopeProfile.getElevation08()); - setElevation09(slopeProfile.getElevation09()); - setElevation10(slopeProfile.getElevation10()); - setElevation11(slopeProfile.getElevation11()); - setElevation12(slopeProfile.getElevation12()); - setElevation13(slopeProfile.getElevation13()); - setElevation14(slopeProfile.getElevation14()); - setElevation15(slopeProfile.getElevation15()); - setElevation16(slopeProfile.getElevation16()); - setElevation17(slopeProfile.getElevation17()); - setElevation18(slopeProfile.getElevation18()); - setElevation19(slopeProfile.getElevation19()); - setElevation20(slopeProfile.getElevation20()); - setElevation21(slopeProfile.getElevation21()); - setElevation22(slopeProfile.getElevation22()); - setElevation23(slopeProfile.getElevation23()); - setElevation24(slopeProfile.getElevation24()); - setElevation25(slopeProfile.getElevation25()); - setElevation26(slopeProfile.getElevation26()); - setElevation27(slopeProfile.getElevation27()); - setElevation28(slopeProfile.getElevation28()); - setElevation29(slopeProfile.getElevation29()); - setElevation30(slopeProfile.getElevation30()); - } - - public SlopeProfile( SlopeprofileRecord origRecord ) - { - setLid(origRecord.getLid()); - setMarker(origRecord.getMarker()); - setBegdate(origRecord.getBegdate()); - setEnddate(origRecord.getEnddate()); - setDistance01(origRecord.getDistance01()); - setDistance02(origRecord.getDistance02()); - setDistance03(origRecord.getDistance03()); - setDistance04(origRecord.getDistance04()); - setDistance05(origRecord.getDistance05()); - setDistance06(origRecord.getDistance06()); - setDistance07(origRecord.getDistance07()); - setDistance08(origRecord.getDistance08()); - setDistance09(origRecord.getDistance09()); - setDistance10(origRecord.getDistance10()); - setDistance11(origRecord.getDistance11()); - setDistance12(origRecord.getDistance12()); - setDistance13(origRecord.getDistance13()); - setDistance14(origRecord.getDistance14()); - setDistance15(origRecord.getDistance15()); - setDistance16(origRecord.getDistance16()); - setDistance17(origRecord.getDistance17()); - setDistance18(origRecord.getDistance18()); - setDistance19(origRecord.getDistance19()); - setDistance20(origRecord.getDistance20()); - setDistance21(origRecord.getDistance21()); - setDistance22(origRecord.getDistance22()); - setDistance23(origRecord.getDistance23()); - setDistance24(origRecord.getDistance24()); - setDistance25(origRecord.getDistance25()); - setDistance26(origRecord.getDistance26()); - setDistance27(origRecord.getDistance27()); - setDistance28(origRecord.getDistance28()); - setDistance29(origRecord.getDistance29()); - setDistance30(origRecord.getDistance30()); - setElevation01(origRecord.getElevation01()); - setElevation02(origRecord.getElevation02()); - setElevation03(origRecord.getElevation03()); - setElevation04(origRecord.getElevation04()); - setElevation05(origRecord.getElevation05()); - setElevation06(origRecord.getElevation06()); - setElevation07(origRecord.getElevation07()); - setElevation08(origRecord.getElevation08()); - setElevation09(origRecord.getElevation09()); - setElevation10(origRecord.getElevation10()); - setElevation11(origRecord.getElevation11()); - setElevation12(origRecord.getElevation12()); - setElevation13(origRecord.getElevation13()); - setElevation14(origRecord.getElevation14()); - setElevation15(origRecord.getElevation15()); - setElevation16(origRecord.getElevation16()); - setElevation17(origRecord.getElevation17()); - setElevation18(origRecord.getElevation18()); - setElevation19(origRecord.getElevation19()); - setElevation20(origRecord.getElevation20()); - setElevation21(origRecord.getElevation21()); - setElevation22(origRecord.getElevation22()); - setElevation23(origRecord.getElevation23()); - setElevation24(origRecord.getElevation24()); - setElevation25(origRecord.getElevation25()); - setElevation26(origRecord.getElevation26()); - setElevation27(origRecord.getElevation27()); - setElevation28(origRecord.getElevation28()); - setElevation29(origRecord.getElevation29()); - setElevation30(origRecord.getElevation30()); - } - - public static SlopeProfile getSlopeProfile( SlopeprofileRecord record ) - { - return ( new SlopeProfile( record ) ); - } - - public static SlopeprofileRecord getSlopeProfileRecord( SlopeProfile slopeProfile ) - { - SlopeprofileRecord slopeProfileRecord = new SlopeprofileRecord(); - - slopeProfileRecord.setLid(slopeProfile.getLid()); - slopeProfileRecord.setMarker(slopeProfile.getMarker()); - slopeProfileRecord.setBegdate(slopeProfile.getBegdate()); - slopeProfileRecord.setEnddate(slopeProfile.getEnddate()); - slopeProfileRecord.setDistance01(slopeProfile.getDistance01()); - slopeProfileRecord.setDistance02(slopeProfile.getDistance02()); - slopeProfileRecord.setDistance03(slopeProfile.getDistance03()); - slopeProfileRecord.setDistance04(slopeProfile.getDistance04()); - slopeProfileRecord.setDistance05(slopeProfile.getDistance05()); - slopeProfileRecord.setDistance06(slopeProfile.getDistance06()); - slopeProfileRecord.setDistance07(slopeProfile.getDistance07()); - slopeProfileRecord.setDistance08(slopeProfile.getDistance08()); - slopeProfileRecord.setDistance09(slopeProfile.getDistance09()); - slopeProfileRecord.setDistance10(slopeProfile.getDistance10()); - slopeProfileRecord.setDistance11(slopeProfile.getDistance11()); - slopeProfileRecord.setDistance12(slopeProfile.getDistance12()); - slopeProfileRecord.setDistance13(slopeProfile.getDistance13()); - slopeProfileRecord.setDistance14(slopeProfile.getDistance14()); - slopeProfileRecord.setDistance15(slopeProfile.getDistance15()); - slopeProfileRecord.setDistance16(slopeProfile.getDistance16()); - slopeProfileRecord.setDistance17(slopeProfile.getDistance17()); - slopeProfileRecord.setDistance18(slopeProfile.getDistance18()); - slopeProfileRecord.setDistance19(slopeProfile.getDistance19()); - slopeProfileRecord.setDistance20(slopeProfile.getDistance20()); - slopeProfileRecord.setDistance21(slopeProfile.getDistance21()); - slopeProfileRecord.setDistance22(slopeProfile.getDistance22()); - slopeProfileRecord.setDistance23(slopeProfile.getDistance23()); - slopeProfileRecord.setDistance24(slopeProfile.getDistance24()); - slopeProfileRecord.setDistance25(slopeProfile.getDistance25()); - slopeProfileRecord.setDistance26(slopeProfile.getDistance26()); - slopeProfileRecord.setDistance27(slopeProfile.getDistance27()); - slopeProfileRecord.setDistance28(slopeProfile.getDistance28()); - slopeProfileRecord.setDistance29(slopeProfile.getDistance29()); - slopeProfileRecord.setDistance30(slopeProfile.getDistance30()); - slopeProfileRecord.setElevation01(slopeProfile.getElevation01()); - slopeProfileRecord.setElevation02(slopeProfile.getElevation02()); - slopeProfileRecord.setElevation03(slopeProfile.getElevation03()); - slopeProfileRecord.setElevation04(slopeProfile.getElevation04()); - slopeProfileRecord.setElevation05(slopeProfile.getElevation05()); - slopeProfileRecord.setElevation06(slopeProfile.getElevation06()); - slopeProfileRecord.setElevation07(slopeProfile.getElevation07()); - slopeProfileRecord.setElevation08(slopeProfile.getElevation08()); - slopeProfileRecord.setElevation09(slopeProfile.getElevation09()); - slopeProfileRecord.setElevation10(slopeProfile.getElevation10()); - slopeProfileRecord.setElevation11(slopeProfile.getElevation11()); - slopeProfileRecord.setElevation12(slopeProfile.getElevation12()); - slopeProfileRecord.setElevation13(slopeProfile.getElevation13()); - slopeProfileRecord.setElevation14(slopeProfile.getElevation14()); - slopeProfileRecord.setElevation15(slopeProfile.getElevation15()); - slopeProfileRecord.setElevation16(slopeProfile.getElevation16()); - slopeProfileRecord.setElevation17(slopeProfile.getElevation17()); - slopeProfileRecord.setElevation18(slopeProfile.getElevation18()); - slopeProfileRecord.setElevation19(slopeProfile.getElevation19()); - slopeProfileRecord.setElevation20(slopeProfile.getElevation20()); - slopeProfileRecord.setElevation21(slopeProfile.getElevation21()); - slopeProfileRecord.setElevation22(slopeProfile.getElevation22()); - slopeProfileRecord.setElevation23(slopeProfile.getElevation23()); - slopeProfileRecord.setElevation24(slopeProfile.getElevation24()); - slopeProfileRecord.setElevation25(slopeProfile.getElevation25()); - slopeProfileRecord.setElevation26(slopeProfile.getElevation26()); - slopeProfileRecord.setElevation27(slopeProfile.getElevation27()); - slopeProfileRecord.setElevation28(slopeProfile.getElevation28()); - slopeProfileRecord.setElevation29(slopeProfile.getElevation29()); - slopeProfileRecord.setElevation30(slopeProfile.getElevation30()); - - return slopeProfileRecord; - } - - public String keyString() - { - return "Lid = " + lid + - " | Marker = " + marker + - " | BeginDate = " + begdate; - } - - //----------------------------------------------------------------- - // get and set methods for all data items in a Slopeprofile record - - //----------------------------------------------------------------- - public String getLid() - { - return lid; - } - - public void setLid(String lid) - { - this.lid = lid ; - } - - public String getMarker() - { - return marker; - } - - public void setMarker(String marker) - { - this.marker = marker ; - } - - public long getBegdate() - { - return begdate; - } - - public void setBegdate(long begdate) - { - this.begdate = begdate ; - } - - public long getEnddate() - { - return enddate; - } - - public void setEnddate(long enddate) - { - this.enddate = enddate ; - } - - public float getDistance01() - { - return distance01; - } - - public void setDistance01(float distance01) - { - this.distance01 = distance01 ; - } - - public float getDistance02() - { - return distance02; - } - - public void setDistance02(float distance02) - { - this.distance02 = distance02 ; - } - - public float getDistance03() - { - return distance03; - } - - public void setDistance03(float distance03) - { - this.distance03 = distance03 ; - } - - public float getDistance04() - { - return distance04; - } - - public void setDistance04(float distance04) - { - this.distance04 = distance04 ; - } - - public float getDistance05() - { - return distance05; - } - - public void setDistance05(float distance05) - { - this.distance05 = distance05 ; - } - - public float getDistance06() - { - return distance06; - } - - public void setDistance06(float distance06) - { - this.distance06 = distance06 ; - } - - public float getDistance07() - { - return distance07; - } - - public void setDistance07(float distance07) - { - this.distance07 = distance07 ; - } - - public float getDistance08() - { - return distance08; - } - - public void setDistance08(float distance08) - { - this.distance08 = distance08 ; - } - - public float getDistance09() - { - return distance09; - } - - public void setDistance09(float distance09) - { - this.distance09 = distance09 ; - } - - public float getDistance10() - { - return distance10; - } - - public void setDistance10(float distance10) - { - this.distance10 = distance10 ; - } - - public float getDistance11() - { - return distance11; - } - - public void setDistance11(float distance11) - { - this.distance11 = distance11 ; - } - - public float getDistance12() - { - return distance12; - } - - public void setDistance12(float distance12) - { - this.distance12 = distance12 ; - } - - public float getDistance13() - { - return distance13; - } - - public void setDistance13(float distance13) - { - this.distance13 = distance13 ; - } - - public float getDistance14() - { - return distance14; - } - - public void setDistance14(float distance14) - { - this.distance14 = distance14 ; - } - - public float getDistance15() - { - return distance15; - } - - public void setDistance15(float distance15) - { - this.distance15 = distance15 ; - } - - public float getDistance16() - { - return distance16; - } - - public void setDistance16(float distance16) - { - this.distance16 = distance16 ; - } - - public float getDistance17() - { - return distance17; - } - - public void setDistance17(float distance17) - { - this.distance17 = distance17 ; - } - - public float getDistance18() - { - return distance18; - } - - public void setDistance18(float distance18) - { - this.distance18 = distance18 ; - } - - public float getDistance19() - { - return distance19; - } - - public void setDistance19(float distance19) - { - this.distance19 = distance19 ; - } - - public float getDistance20() - { - return distance20; - } - - public void setDistance20(float distance20) - { - this.distance20 = distance20 ; - } - - public float getDistance21() - { - return distance21; - } - - public void setDistance21(float distance21) - { - this.distance21 = distance21 ; - } - - public float getDistance22() - { - return distance22; - } - - public void setDistance22(float distance22) - { - this.distance22 = distance22 ; - } - - public float getDistance23() - { - return distance23; - } - - public void setDistance23(float distance23) - { - this.distance23 = distance23 ; - } - - public float getDistance24() - { - return distance24; - } - - public void setDistance24(float distance24) - { - this.distance24 = distance24 ; - } - - public float getDistance25() - { - return distance25; - } - - public void setDistance25(float distance25) - { - this.distance25 = distance25 ; - } - - public float getDistance26() - { - return distance26; - } - - public void setDistance26(float distance26) - { - this.distance26 = distance26 ; - } - - public float getDistance27() - { - return distance27; - } - - public void setDistance27(float distance27) - { - this.distance27 = distance27 ; - } - - public float getDistance28() - { - return distance28; - } - - public void setDistance28(float distance28) - { - this.distance28 = distance28 ; - } - - public float getDistance29() - { - return distance29; - } - - public void setDistance29(float distance29) - { - this.distance29 = distance29 ; - } - - public float getDistance30() - { - return distance30; - } - - public void setDistance30(float distance30) - { - this.distance30 = distance30 ; - } - - public float getElevation01() - { - return elevation01; - } - - public void setElevation01(float elevation01) - { - this.elevation01 = elevation01 ; - } - - public float getElevation02() - { - return elevation02; - } - - public void setElevation02(float elevation02) - { - this.elevation02 = elevation02 ; - } - - public float getElevation03() - { - return elevation03; - } - - public void setElevation03(float elevation03) - { - this.elevation03 = elevation03 ; - } - - public float getElevation04() - { - return elevation04; - } - - public void setElevation04(float elevation04) - { - this.elevation04 = elevation04 ; - } - - public float getElevation05() - { - return elevation05; - } - - public void setElevation05(float elevation05) - { - this.elevation05 = elevation05 ; - } - - public float getElevation06() - { - return elevation06; - } - - public void setElevation06(float elevation06) - { - this.elevation06 = elevation06 ; - } - - public float getElevation07() - { - return elevation07; - } - - public void setElevation07(float elevation07) - { - this.elevation07 = elevation07 ; - } - - public float getElevation08() - { - return elevation08; - } - - public void setElevation08(float elevation08) - { - this.elevation08 = elevation08 ; - } - - public float getElevation09() - { - return elevation09; - } - - public void setElevation09(float elevation09) - { - this.elevation09 = elevation09 ; - } - - public float getElevation10() - { - return elevation10; - } - - public void setElevation10(float elevation10) - { - this.elevation10 = elevation10 ; - } - - public float getElevation11() - { - return elevation11; - } - - public void setElevation11(float elevation11) - { - this.elevation11 = elevation11 ; - } - - public float getElevation12() - { - return elevation12; - } - - public void setElevation12(float elevation12) - { - this.elevation12 = elevation12 ; - } - - public float getElevation13() - { - return elevation13; - } - - public void setElevation13(float elevation13) - { - this.elevation13 = elevation13 ; - } - - public float getElevation14() - { - return elevation14; - } - - public void setElevation14(float elevation14) - { - this.elevation14 = elevation14 ; - } - - public float getElevation15() - { - return elevation15; - } - - public void setElevation15(float elevation15) - { - this.elevation15 = elevation15 ; - } - - public float getElevation16() - { - return elevation16; - } - - public void setElevation16(float elevation16) - { - this.elevation16 = elevation16 ; - } - - public float getElevation17() - { - return elevation17; - } - - public void setElevation17(float elevation17) - { - this.elevation17 = elevation17 ; - } - - public float getElevation18() - { - return elevation18; - } - - public void setElevation18(float elevation18) - { - this.elevation18 = elevation18 ; - } - - public float getElevation19() - { - return elevation19; - } - - public void setElevation19(float elevation19) - { - this.elevation19 = elevation19 ; - } - - public float getElevation20() - { - return elevation20; - } - - public void setElevation20(float elevation20) - { - this.elevation20 = elevation20 ; - } - - public float getElevation21() - { - return elevation21; - } - - public void setElevation21(float elevation21) - { - this.elevation21 = elevation21 ; - } - - public float getElevation22() - { - return elevation22; - } - - public void setElevation22(float elevation22) - { - this.elevation22 = elevation22 ; - } - - public float getElevation23() - { - return elevation23; - } - - public void setElevation23(float elevation23) - { - this.elevation23 = elevation23 ; - } - - public float getElevation24() - { - return elevation24; - } - - public void setElevation24(float elevation24) - { - this.elevation24 = elevation24 ; - } - - public float getElevation25() - { - return elevation25; - } - - public void setElevation25(float elevation25) - { - this.elevation25 = elevation25 ; - } - - public float getElevation26() - { - return elevation26; - } - - public void setElevation26(float elevation26) - { - this.elevation26 = elevation26 ; - } - - public float getElevation27() - { - return elevation27; - } - - public void setElevation27(float elevation27) - { - this.elevation27 = elevation27 ; - } - - public float getElevation28() - { - return elevation28; - } - - public void setElevation28(float elevation28) - { - this.elevation28 = elevation28 ; - } - - public float getElevation29() - { - return elevation29; - } - - public void setElevation29(float elevation29) - { - this.elevation29 = elevation29 ; - } - - public float getElevation30() - { - return elevation30; - } - - public void setElevation30(float elevation30) - { - this.elevation30 = elevation30 ; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/State.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/State.java deleted file mode 100644 index ef64bf9154..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/State.java +++ /dev/null @@ -1,117 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.StateRecord; - -public class State -{ - private String _state = null; - private String _countryFips = null; - private String _name = null; - private String _ncdc = null; - private String _statefips = null; - - public State(){} - - public State( State state ) - { - setState( state.getState() ); - setCountryFips( state.getCountryFips() ); - setName( state.getName() ); - setNcdc( state.getNcdc() ); - setStateFips( state.getStateFips() ); - } - - public State( StateRecord stateRecord ) - { - setState( stateRecord.getState() ); - setCountryFips( stateRecord.getCountryfips() ); - setName( stateRecord.getName() ); - setNcdc( stateRecord.getNcdc() ); - setStateFips( stateRecord.getStatefips() ); - } - - public static State getState( StateRecord record ) - { - return new State( record ); - } - - public static StateRecord getStateRecord( State state ) - { - StateRecord record = new StateRecord(); - - record.setState( state.getState() ); - record.setCountryfips( state.getCountryFips() ); - record.setName( state.getName() ); - record.setNcdc( state.getNcdc() ); - record.setStatefips( state.getStateFips() ); - - return record; - } - - public String toString() - { - return "State = " + _state + - " | CountryFips = " + _countryFips + - " | Name = " + _name + - " | Ncdc = " + _ncdc + - " | StateFips = " + _statefips; - } - - public String keyString() - { - return "State = " + _state + - " | CountryFips = " + _countryFips; - } - - - public String getState() - { - return _state; - } - - public void setState(String state) - { - _state = state ; - } - - public String getCountryFips() - { - return _countryFips; - } - - public void setCountryFips(String countryfips) - { - _countryFips = countryfips ; - } - - public String getName() - { - return _name; - } - - public void setName(String name) - { - _name = name ; - } - - public String getNcdc() - { - return _ncdc; - } - - public void setNcdc(String ncdc) - { - _ncdc = ncdc ; - } - - public String getStateFips() - { - return _statefips; - } - - public void setStateFips(String statefips) - { - _statefips = statefips ; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/WfoHsa.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/WfoHsa.java deleted file mode 100644 index c8a1f3d272..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/model/WfoHsa.java +++ /dev/null @@ -1,54 +0,0 @@ -package ohd.hseb.raxbase.model; - -import ohd.hseb.raxdb.generated.Wfo_hsaRecord; - -public class WfoHsa -{ - private String _wfoHsa = null; - - public WfoHsa(){} - - public WfoHsa( WfoHsa wfoHsa ) - { - setWfoHsa( wfoHsa.getWfoHsa() ); - } - - public WfoHsa( Wfo_hsaRecord wfoHsaRecord ) - { - setWfoHsa( wfoHsaRecord.getWfo_hsa() ); - } - - public static WfoHsa getWfoHsa( WfoHsa record ) - { - return new WfoHsa( record ); - } - - public static Wfo_hsaRecord getWfoHsaRecord( WfoHsa wfoHsa ) - { - Wfo_hsaRecord record = new Wfo_hsaRecord(); - - record.setWfo_hsa( wfoHsa.getWfoHsa() ); - - return record; - } - - public String toString() - { - return "WfoHsa = " + _wfoHsa; - } - - public String keyString() - { - return "WfoHsa = " + _wfoHsa; - } - - public void setWfoHsa( String wfoHsa ) - { - this._wfoHsa = wfoHsa; - } - - public String getWfoHsa() - { - return _wfoHsa; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseAdjustFactorJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseAdjustFactorJTableRowData.java deleted file mode 100644 index 332587fd95..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseAdjustFactorJTableRowData.java +++ /dev/null @@ -1,167 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.raxbase.model.RaxAdjustFactor; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseAdjustFactorJTableRowData extends AbstractJTableRowData -{ - private static final short MISSING = -9999; - private String _missingRepresentation = ""; - - private RaxAdjustFactor _raxAdjustFactor = null; -/* - private String _lid = null; - private String _pe = null; - private String _duration = null; - private String _ts = null; - private String _extremum = null; - private long _beginDate = MISSING; - private double _divisor = MISSING; - private double _base = MISSING; - private double _multiplier = MISSING; - private double _adder = MISSING; -*/ - public ArcBaseAdjustFactorJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Lid = " + _raxAdjustFactor.getLid() + " PE = " + _raxAdjustFactor.getPe() + " dur = " + _raxAdjustFactor.getDur(); - } - -/* - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDuration( String duration ) - { - _duration = duration; - } - - public String getDuration() - { - return _duration; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setBeginDate( long beginDate ) - { - _beginDate = beginDate; - } - - public long getBeginDate() - { - return _beginDate; - } - - public void setDivisor( double divisor ) - { - _divisor = divisor; - } - - public double getDivisor() - { - return _divisor; - } - - public void setBase( double base ) - { - _base = base; - } - - public double getBase() - { - return _base; - } - - public void setMultiplier( double multiplier ) - { - _multiplier = multiplier; - } - - public double getMultiplier() - { - return _multiplier; - } - - public void setAdder( double adder ) - { - _adder = adder; - } - - public double getAdder() - { - return _adder; - } -*/ - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Location", CellType.STRING, _raxAdjustFactor.getLid(), _missingRepresentation ) ); - addCell( new BaseTableCell( "PE", CellType.STRING, _raxAdjustFactor.getPe(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Dur", CellType.STRING, _raxAdjustFactor.getIdur() + "/" + _raxAdjustFactor.getDur(), _missingRepresentation ) ); - addCell( new BaseTableCell( "TS", CellType.STRING, _raxAdjustFactor.getTs(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Extremum", CellType.STRING, _raxAdjustFactor.getExtremum(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Begin Date", CellType.DATE, _raxAdjustFactor.getBeginDate(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Divisor", CellType.DOUBLE, _raxAdjustFactor.getDivisor(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Base", CellType.DOUBLE, _raxAdjustFactor.getBase(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Multiplier", CellType.DOUBLE, _raxAdjustFactor.getMultiplier(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Adder", CellType.DOUBLE, _raxAdjustFactor.getAdder(), _missingRepresentation ) ); - } - - public void setRaxAdjustFactor( RaxAdjustFactor raxAdjustFactor ) - { - _raxAdjustFactor = raxAdjustFactor; - } - - public RaxAdjustFactor getRaxAdjustFactor() - { - return _raxAdjustFactor; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseAgencyJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseAgencyJTableRowData.java deleted file mode 100644 index 2fb8c5f1e9..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseAgencyJTableRowData.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseAgencyJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _agCode = null; - private String _agLoc = null; - private String _des = null; - - public ArcBaseAgencyJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "AgCode = " + _agCode + - " | AgLoc = " + _agLoc + - " | Des = " + _des; - } - - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "AgCode", CellType.STRING, getAgCode(), _missingRepresentation ) ); - addCell( new BaseTableCell( "AgLoc", CellType.STRING, getAgLoc(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Desc", CellType.STRING, getDes(), _missingRepresentation ) ); - } - public void setAgCode( String agCode ) - { - _agCode = agCode; - } - - public String getAgCode() - { - return _agCode; - } - - public void setAgLoc( String agLoc ) - { - _agLoc = agLoc; - } - - public String getAgLoc() - { - return _agLoc; - } - - public void setDes( String des ) - { - _des = des; - } - - public String getDes() - { - return _des; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCountiesJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCountiesJTableRowData.java deleted file mode 100644 index 12faae4e8a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCountiesJTableRowData.java +++ /dev/null @@ -1,107 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseCountiesJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _county = null; - private String _state = null; - private String _countryFips = null; - private String _countyFips = null; - private String _wfo = null; - private String _zon = null; - - public ArcBaseCountiesJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "County = " + _county + - " | State = " + _state + - " | CountryFips = " + _countryFips + - " | CountyFips = " + _countyFips + - " | Wfo = " + _wfo + - " | Zon = " + _zon; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "County", CellType.STRING, getCounty(), _missingRepresentation ) ); - addCell( new BaseTableCell( "State", CellType.STRING, getState(), _missingRepresentation ) ); - addCell( new BaseTableCell( "CountryFips", CellType.STRING, getCountryFips(), _missingRepresentation ) ); - addCell( new BaseTableCell( "CountyFips", CellType.STRING, getCountyFips(), _missingRepresentation ) ); - addCell( new BaseTableCell( "WFO", CellType.STRING, getWfo(), _missingRepresentation ) ); - addCell( new BaseTableCell( "ZON", CellType.STRING, getZon(), _missingRepresentation ) ); - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - _state = state ; - } - - public String getCountryFips() - { - return _countryFips; - } - - public void setCountryFips(String countryfips) - { - _countryFips = countryfips ; - } - - public String getCountyFips() - { - return _countyFips; - } - - public void setCountyFips(String countyfips) - { - _countyFips = countyfips ; - } - - public String getWfo() - { - return _wfo; - } - - public void setWfo(String wfo) - { - _wfo = wfo ; - } - - public String getZon() - { - return _zon; - } - - public void setZon(String zon) - { - _zon = zon ; - } - - public void setCounty( String county ) - { - _county = county; - } - - public String getCounty() - { - return _county; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCountryJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCountryJTableRowData.java deleted file mode 100644 index be68478648..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCountryJTableRowData.java +++ /dev/null @@ -1,54 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseCountryJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _country = null; - private String _countryFips = null; - - public ArcBaseCountryJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Country = " + _country + " CountryFips = " + _countryFips; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Country", CellType.STRING, getCountry(), _missingRepresentation ) ); - addCell( new BaseTableCell( "CountryFips", CellType.STRING, getCountryFips(), _missingRepresentation ) ); - } - - public void setCountry( String country ) - { - _country = country; - } - - public String getCountry() - { - return _country; - } - - public void setCountryFips( String countryFips ) - { - _countryFips = countryFips; - } - - public String getCountryFips() - { - return _countryFips; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCrestJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCrestJTableRowData.java deleted file mode 100644 index 88560ca189..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseCrestJTableRowData.java +++ /dev/null @@ -1,79 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseCrestJTableRowData extends AbstractJTableRowData -{ - private static final short MISSING = -9999; - private String _missingRepresentation = ""; - - private double _stage = MISSING; - private double _flow = MISSING; - private long _date = MISSING; - private String _time = null; - - public ArcBaseCrestJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Stage = " + _stage + " Flow = " + _flow + " Date = " + _date + " Time = " + _time; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Stage", CellType.DOUBLE, getStage(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Flow", CellType.DOUBLE, getFlow(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Date", CellType.DATE, getDate(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Time", CellType.STRING, getTime(), _missingRepresentation ) ); - } - - public void setStage( double stage ) - { - _stage = stage; - } - - public double getStage() - { - return _stage; - } - - public void setFlow( double flow ) - { - _flow = flow; - } - - public double getFlow() - { - return _flow; - } - - public void setDate( long date ) - { - _date = date; - } - - public long getDate() - { - return _date; - } - - public void setTime( String time ) - { - _time = time; - } - - public String getTime() - { - return _time; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseDataLimitsJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseDataLimitsJTableRowData.java deleted file mode 100644 index 1d748b3feb..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseDataLimitsJTableRowData.java +++ /dev/null @@ -1,201 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseDataLimitsJTableRowData extends AbstractJTableRowData -{ - private static final short MISSING = -9999; - private String _missingRepresentation = ""; - - private String _lid = null; - private String _pe = null; - private String _duration = null; - private String _monthDayStart = null; - private String _monthDayEnd = null; - private double _grossRangeMin = MISSING; - private double _grossRangeMax = MISSING; - private double _reasonRangeMin = MISSING; - private double _reasonRangeMax = MISSING; - private double _rocMax = MISSING; - private double _alertLimit = MISSING; - private double _alertRocLimit = MISSING; - private double _alarmLimit = MISSING; - private double _alarmRocLimit = MISSING; - - - public ArcBaseDataLimitsJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Lid = " + _lid + " PE = " + _pe + " dur = " + _duration; - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDuration( String duration ) - { - _duration = duration; - } - - public String getDuration() - { - return _duration; - } - - public void setMonthDayStart( String monthDayStart ) - { - _monthDayStart = monthDayStart; - } - - public String getMonthDayStart() - { - return _monthDayStart; - } - - public void setMonthDayEnd( String monthDayEnd ) - { - _monthDayEnd = monthDayEnd; - } - - public String getMonthDayEnd() - { - return _monthDayEnd; - } - - public void setGrossRangeMin( double grossRangeMin ) - { - _grossRangeMin = grossRangeMin; - } - - public double getGrossRangeMin() - { - return _grossRangeMin; - } - - public void setGrossRangeMax( double grossRangeMax ) - { - _grossRangeMax = grossRangeMax; - } - - public double getGrossRangeMax() - { - return _grossRangeMax; - } - - public void setReasonRangeMin( double reasonRangeMin ) - { - _reasonRangeMin = reasonRangeMin; - } - - public double getReasonRangeMin() - { - return _reasonRangeMin; - } - - public void setReasonRangeMax( double reasonRangeMax ) - { - _reasonRangeMax = reasonRangeMax; - } - - public double getReasonRangeMax() - { - return _reasonRangeMax; - } - - public void setRocMax( double rocMax ) - { - _rocMax = rocMax; - } - - public double getRocMax() - { - return _rocMax; - } - - public void setAlertLimit( double alertLimit ) - { - _alertLimit = alertLimit; - } - - public double getAlertLimit() - { - return _alertLimit; - } - - public void setAlertRocLimit( double alertRocLimit ) - { - _alertRocLimit = alertRocLimit; - } - - public double getAlertRocLimit() - { - return _alertRocLimit; - } - - public void setAlarmLimit( double alarmLimit ) - { - _alarmLimit = alarmLimit; - } - - public double getAlarmLimit() - { - return _alarmLimit; - } - - public void setAlarmRocLimit( double alarmRocLimit ) - { - _alarmRocLimit = alarmRocLimit; - } - - public double getAlarmRocLimit() - { - return _alarmRocLimit; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Location", CellType.STRING, getLid(), _missingRepresentation ) ); - addCell( new BaseTableCell( "PE", CellType.STRING, getPe(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Dur", CellType.STRING, getDuration(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Start", CellType.STRING, getMonthDayStart(), _missingRepresentation ) ); - addCell( new BaseTableCell( "End", CellType.STRING, getMonthDayEnd(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Gross Min", CellType.DOUBLE, getGrossRangeMin(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Gross Max", CellType.DOUBLE, getGrossRangeMax(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Reasonable
    Min", CellType.DOUBLE, getReasonRangeMin(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Reasonable
    Max", CellType.DOUBLE, getReasonRangeMax(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Rate of
    Change", CellType.DOUBLE, getRocMax(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Alert Limit", CellType.DOUBLE, getAlertLimit(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Alert Limit
    ROC", CellType.DOUBLE, getAlertRocLimit(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Alarm Limit", CellType.DOUBLE, getAlarmLimit(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Alarm Limit
    ROC", CellType.DOUBLE, getAlarmRocLimit(), _missingRepresentation ) ); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc2JTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc2JTableRowData.java deleted file mode 100644 index d8e2f47eb1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc2JTableRowData.java +++ /dev/null @@ -1,69 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseHuc2JTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _code2 = null; - private String _code12 = null; - private String _desreg = null; - - public ArcBaseHuc2JTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code2 = " + _code2 + - " | Desreg = " + _desreg; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Code12", CellType.STRING, getCode12(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code2", CellType.STRING, getCode2(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Desc", CellType.STRING, getDesreg(), _missingRepresentation ) ); - } - - public void setCode2( String code2 ) - { - _code2 = code2; - } - - public String getCode2() - { - return _code2; - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - - public String getCode12() - { - return _code12; - } - - public void setDesreg( String desreg ) - { - _desreg = desreg; - } - - public String getDesreg() - { - return _desreg; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc4JTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc4JTableRowData.java deleted file mode 100644 index 44e55df704..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc4JTableRowData.java +++ /dev/null @@ -1,82 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseHuc4JTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _code4 = null; - private String _code12 = null; - private String _code34 = null; - private String _dessubreg = null; - - public ArcBaseHuc4JTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code34 = " + _code34 + - " | Code4 = " + _code4 + - " | Dessubreg = " + _dessubreg; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Code12", CellType.STRING, getCode12(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code34", CellType.STRING, getCode34(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code4", CellType.STRING, getCode4(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Desc", CellType.STRING, getDesreg(), _missingRepresentation ) ); - } - - public void setCode4( String code4 ) - { - _code4 = code4; - } - - public String getCode4() - { - return _code4; - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - - public String getCode12() - { - return _code12; - } - - public void setDesreg( String desreg ) - { - _dessubreg = desreg; - } - - public String getDesreg() - { - return _dessubreg; - } - - public void setCode34( String code34 ) - { - _code34 = code34; - } - - public String getCode34() - { - return _code34; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc6JTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc6JTableRowData.java deleted file mode 100644 index 821a0ceab1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc6JTableRowData.java +++ /dev/null @@ -1,95 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseHuc6JTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _code6 = null; - private String _code12 = null; - private String _code34 = null; - private String _code56 = null; - private String _desacct = null; - - public ArcBaseHuc6JTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code34 = " + _code34 + - " | Code56 = " + getCode56() + - " | Code6 = " + _code6 + - " | Desacct = " + getDesacct(); - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Code12", CellType.STRING, getCode12(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code34", CellType.STRING, getCode34(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code56", CellType.STRING, getCode56(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code6", CellType.STRING, getCode6(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Desc", CellType.STRING, getDesacct(), _missingRepresentation ) ); - } - - public void setCode6( String code6 ) - { - _code6 = code6; - } - - public String getCode6() - { - return _code6; - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - - public String getCode12() - { - return _code12; - } - - public void setCode34( String code34 ) - { - _code34 = code34; - } - - public String getCode34() - { - return _code34; - } - - public void setCode56( String code56 ) - { - _code56 = code56; - } - - public String getCode56() - { - return _code56; - } - - public void setDesacct( String desacct ) - { - _desacct = desacct; - } - - public String getDesacct() - { - return _desacct; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc8JTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc8JTableRowData.java deleted file mode 100644 index f4f1303851..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseHuc8JTableRowData.java +++ /dev/null @@ -1,107 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseHuc8JTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _code8 = null; - private String _code12 = null; - private String _code34 = null; - private String _code56 = null; - private String _code78 = null; - private String _descat = null; - - public ArcBaseHuc8JTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Code12 = " + _code12 + - " | Code34 = " + _code34 + - " | Code56 = " + _code56 + - " | Code78 = " + _code78 + - " | Code8 = " + _code8 + - " | Descat = " + _descat; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Code12", CellType.STRING, getCode12(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code34", CellType.STRING, getCode34(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code56", CellType.STRING, getCode56(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code78", CellType.STRING, getCode78(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Code8", CellType.STRING, getCode8(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Desc", CellType.STRING, getDescat(), _missingRepresentation ) ); - } - - public void setCode12( String code12 ) - { - _code12 = code12; - } - - public String getCode12() - { - return _code12; - } - - public void setCode34( String code34 ) - { - _code34 = code34; - } - - public String getCode34() - { - return _code34; - } - - public void setCode56( String code56 ) - { - _code56 = code56; - } - - public String getCode56() - { - return _code56; - } - - public void setCode8( String code8 ) - { - _code8 = code8; - } - - public String getCode8() - { - return _code8; - } - - public void setCode78( String code78 ) - { - _code78 = code78; - } - - public String getCode78() - { - return _code78; - } - - public void setDescat( String descat ) - { - _descat = descat; - } - - public String getDescat() - { - return _descat; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseIngestFilterJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseIngestFilterJTableRowData.java deleted file mode 100644 index f49aeb2669..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseIngestFilterJTableRowData.java +++ /dev/null @@ -1,53 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.raxbase.model.RaxIngestFilter; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class ArcBaseIngestFilterJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private RaxIngestFilter _raxIngestFilter = null; - - public ArcBaseIngestFilterJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Lid = " + getRaxIngestFilter().getLid() + " PE = " + getRaxIngestFilter().getPe() + " dur = " + getRaxIngestFilter().getIdur() + " TS = " + getRaxIngestFilter().getTs() + " Extremum = " + getRaxIngestFilter().getExtremum(); - } - - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Location", CellType.STRING, _raxIngestFilter.getLid(), _missingRepresentation ) ); - addCell( new BaseTableCell( "PE", CellType.STRING, _raxIngestFilter.getPe(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Dur", CellType.STRING, _raxIngestFilter.getIdur() + "/" + _raxIngestFilter.getDur(), _missingRepresentation ) ); - addCell( new BaseTableCell( "TypeSrc", CellType.STRING, _raxIngestFilter.getTs(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Ext", CellType.STRING, _raxIngestFilter.getExtremum(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Rank", CellType.SHORT, _raxIngestFilter.getTsRank(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Master", CellType.BOOLEAN, _raxIngestFilter.isIngest(), _missingRepresentation ) ); - addCell( new BaseTableCell( "OFS", CellType.BOOLEAN, _raxIngestFilter.isOfsInput(), _missingRepresentation ) ); - addCell( new BaseTableCell( "MPE", CellType.BOOLEAN, _raxIngestFilter.isMpeInput(), _missingRepresentation ) ); - } - - - public String getStringValue(short value) - { - return String.valueOf(value); - } - - public void setRaxIngestFilter( RaxIngestFilter raxIngestFilter ) - { - _raxIngestFilter = raxIngestFilter; - } - - public RaxIngestFilter getRaxIngestFilter() - { - return _raxIngestFilter; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseLocationJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseLocationJTableRowData.java deleted file mode 100644 index 68cdfc1b0b..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseLocationJTableRowData.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.raxbase.model.RaxLocation; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class ArcBaseLocationJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private RaxLocation _raxLocation = null; - - public ArcBaseLocationJTableRowData() - { - setMissingRepresentation( "" ); - } - - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Station", CellType.STRING, _raxLocation.getLid(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Begin Date", CellType.DATE, _raxLocation.getBeginDate(), _missingRepresentation ) ); - addCell( new BaseTableCell( "End Date", CellType.DATE, _raxLocation.getEndDate(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Latitude", CellType.DOUBLE, _raxLocation.getLatitude(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Longitude", CellType.DOUBLE, _raxLocation.getLongitude(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Elevation", CellType.INTEGER, _raxLocation.getElevation(), _missingRepresentation ) ); - addCell( new BaseTableCell( "State", CellType.STRING, _raxLocation.getState(), _missingRepresentation ) ); - addCell( new BaseTableCell( "HUC", CellType.STRING, _raxLocation.getHuc(), _missingRepresentation ) ); - addCell( new BaseTableCell( "WFO", CellType.STRING, _raxLocation.getWfo(), _missingRepresentation ) ); - addCell( new BaseTableCell( "RFC", CellType.STRING, _raxLocation.getRfc(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, _raxLocation.getName(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Detailed Info", CellType.STRING, _raxLocation.getDetailInfo(), _missingRepresentation ) ); - addCell( new BaseTableCell( "HSA", CellType.STRING, _raxLocation.getHsa(), _missingRepresentation ) ); - } - - public String getStringValue(long value, long missingValue) - { - String result = getMissingRepresentation(); - if ( value != missingValue ) - { - result = String.valueOf( DbTimeHelper.getDateStringFromLongTime( value ) ); - } - return result; - } - - public void setRaxLocation( RaxLocation raxLocation ) - { - _raxLocation = raxLocation; - } - - public RaxLocation getRaxLocation() - { - return _raxLocation; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseModCtrlJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseModCtrlJTableRowData.java deleted file mode 100644 index fe8e00a6e3..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseModCtrlJTableRowData.java +++ /dev/null @@ -1,79 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseModCtrlJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _modName = null; - private boolean _load = false; - private boolean _fetchOper = false; - private boolean _fetchSpin = false; - - public ArcBaseModCtrlJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "ModName = " + _modName + " Load = " + _load + " FetchOper = " + _fetchOper + " FetchSpin = " + _fetchSpin; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "ModName", CellType.STRING, getModName(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Load", CellType.BOOLEAN, isLoad(), _missingRepresentation ) ); - addCell( new BaseTableCell( "FetchOper", CellType.BOOLEAN, isFetchOper(), _missingRepresentation ) ); - addCell( new BaseTableCell( "FetchSpin", CellType.BOOLEAN, isFetchSpin(), _missingRepresentation ) ); - } - - public void setModName( String modName ) - { - _modName = modName; - } - - public String getModName() - { - return _modName; - } - - public void setLoad( boolean load ) - { - _load = load; - } - - public boolean isLoad() - { - return _load; - } - - public void setFetchOper( boolean fetchOper ) - { - _fetchOper = fetchOper; - } - - public boolean isFetchOper() - { - return _fetchOper; - } - - public void setFetchSpin( boolean fetchSpin ) - { - _fetchSpin = fetchSpin; - } - - public boolean isFetchSpin() - { - return _fetchSpin; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseProdJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseProdJTableRowData.java deleted file mode 100644 index 0b7945decc..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseProdJTableRowData.java +++ /dev/null @@ -1,123 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseProdJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private static final short MISSING = -9999; - - private String _id = null; - private int _pmax = MISSING; - private int _pap = MISSING; - private int _err = MISSING; - private String _gra = null; - private String _pr1 = null; - private String _net = null; - - public ArcBaseProdJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Id = " + _id + - " | Pmax = " + _pmax + - " | Pap = " + _pap + - " | Err = " + _err + - " | Gra = " + _gra + - " | Pr1 = " + _pr1 + - " | Net = " + _net; - } - - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Id", CellType.STRING, getId(), _missingRepresentation ) ); - addCell( new BaseTableCell( "PMax", CellType.INTEGER, getPmax(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Pap", CellType.INTEGER, getPap(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Err", CellType.INTEGER, getErr(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Gra", CellType.STRING, getGra(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Pr1", CellType.STRING, getPr1(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Net", CellType.STRING, getNet(), _missingRepresentation ) ); - } - - public String getId() - { - return _id; - } - - public void setId(String id) - { - _id = id ; - } - - public int getPmax() - { - return _pmax; - } - - public void setPmax(int pmax) - { - _pmax = pmax ; - } - - public int getPap() - { - return _pap; - } - - public void setPap(int pap) - { - _pap = pap ; - } - - public int getErr() - { - return _err; - } - - public void setErr(int err) - { - _err = err ; - } - - public String getGra() - { - return _gra; - } - - public void setGra(String gra) - { - _gra = gra ; - } - - public String getPr1() - { - return _pr1; - } - - public void setPr1(String pr1) - { - _pr1 = pr1 ; - } - - public String getNet() - { - return _net; - } - - public void setNet(String net) - { - _net = net ; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRatingJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRatingJTableRowData.java deleted file mode 100644 index 7b99470f2d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRatingJTableRowData.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseRatingJTableRowData extends AbstractJTableRowData -{ - private static final short MISSING = -9999; - private String _missingRepresentation = ""; - - private double _stage = MISSING; - private double _shiftedStage = MISSING; - private double _discharge = MISSING; - - - public ArcBaseRatingJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Stage = " + _stage + " Shifted Stage = " + _shiftedStage + " Discharge = " + _discharge; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Stage", CellType.DOUBLE, getStage(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Shifted Stage", CellType.DOUBLE, getShiftedStage(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Discharge", CellType.DOUBLE, getDischarge(), _missingRepresentation ) ); - } - - public void setStage( double stage ) - { - _stage = stage; - } - - public double getStage() - { - return _stage; - } - - public void setShiftedStage( double shiftedStage ) - { - _shiftedStage = shiftedStage; - } - - public double getShiftedStage() - { - return _shiftedStage; - } - - public void setDischarge( double discharge ) - { - _discharge = discharge; - } - - public double getDischarge() - { - return _discharge; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRatingOffsetsJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRatingOffsetsJTableRowData.java deleted file mode 100644 index 8517399e61..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRatingOffsetsJTableRowData.java +++ /dev/null @@ -1,56 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseRatingOffsetsJTableRowData extends AbstractJTableRowData -{ - private static final short MISSING = -9999; - private String _missingRepresentation = ""; - - private double _stage = MISSING; - private double _offSet = MISSING; - - - public ArcBaseRatingOffsetsJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Stage = " + _stage + " Offset = " + _offSet; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Stage", CellType.DOUBLE, getStage(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Offset", CellType.DOUBLE, getOffset(), _missingRepresentation ) ); - } - - public void setStage( double stage ) - { - _stage = stage; - } - - public double getStage() - { - return _stage; - } - - public void setOffset( double offSet ) - { - _offSet = offSet; - } - - public double getOffset() - { - return _offSet; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRfcJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRfcJTableRowData.java deleted file mode 100644 index 7b5c260dce..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseRfcJTableRowData.java +++ /dev/null @@ -1,41 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class ArcBaseRfcJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _rfc = null; - - public ArcBaseRfcJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Rfc = " + _rfc; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "RFC", CellType.STRING, getRfc(), _missingRepresentation ) ); - } - - public void setRfc( String rfc ) - { - _rfc = rfc; - } - - public String getRfc() - { - return _rfc; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefDurationJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefDurationJTableRowData.java deleted file mode 100644 index a3f68651b4..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefDurationJTableRowData.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefDurationJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _duration = null; - private short _iDuration = 0; - private String _name = null; - - public ArcBaseShefDurationJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Duration = " + _duration + - " | IDuration = " + _iDuration + - " | Name = " + _name; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Dur", CellType.STRING, getDuration(), _missingRepresentation ) ); - addCell( new BaseTableCell( "IDur", CellType.SHORT, getIDuration(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - } - - public void setDuration( String duration ) - { - _duration = duration; - } - - public String getDuration() - { - return _duration; - } - - public void setIDuration( short iDuration ) - { - _iDuration = iDuration; - } - - public short getIDuration() - { - return _iDuration; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefExtremumJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefExtremumJTableRowData.java deleted file mode 100644 index 93762d0701..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefExtremumJTableRowData.java +++ /dev/null @@ -1,55 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefExtremumJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _extremum = null; - private String _name = null; - - public ArcBaseShefExtremumJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "Extremum = " + _extremum + - " | Name = " + _name; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "Extremum", CellType.STRING, getExtremum(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setExtremum( String extremum ) - { - this._extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPE1JTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPE1JTableRowData.java deleted file mode 100644 index ba66b2c794..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPE1JTableRowData.java +++ /dev/null @@ -1,55 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefPE1JTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _pe1 = null; - private String _name = null; - - public ArcBaseShefPE1JTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "PE1 = " + _pe1 + - " | Name = " + _name; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "PE1", CellType.STRING, getPe1(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - } - - public void setPe1( String pe1 ) - { - _pe1 = pe1; - } - - public String getPe1() - { - return _pe1; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPEJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPEJTableRowData.java deleted file mode 100644 index 09307c3e56..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPEJTableRowData.java +++ /dev/null @@ -1,81 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefPEJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _pe = null; - private String _name = null; - private String _metUnit = null; - private String _engUnit = null; - - public ArcBaseShefPEJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "PE = " + _pe + - " | Name = " + _name + - " | MetUnit = " + _metUnit + - " | EngUnit = " + _engUnit; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "PE", CellType.STRING, getPe(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - addCell( new BaseTableCell( "MetUnit", CellType.STRING, getMetUnit(), _missingRepresentation ) ); - addCell( new BaseTableCell( "EngUnit", CellType.STRING, getEngUnit(), _missingRepresentation ) ); - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setMetUnit( String metUnit ) - { - _metUnit = metUnit; - } - - public String getMetUnit() - { - return _metUnit; - } - - public void setEngUnit( String engUnit ) - { - _engUnit = engUnit; - } - - public String getEngUnit() - { - return _engUnit; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPETransJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPETransJTableRowData.java deleted file mode 100644 index fbe4880b4a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefPETransJTableRowData.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefPETransJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _pe = null; - private String _codePosition = null; - private int _codedValue = 0; - - public ArcBaseShefPETransJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "PE = " + _pe + - " | CodePosition = " + _codePosition + - " | CodedValue = " + _codedValue; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "PE", CellType.STRING, getPe(), _missingRepresentation ) ); - addCell( new BaseTableCell( "CodePosition", CellType.STRING, getCodePosition(), _missingRepresentation ) ); - addCell( new BaseTableCell( "CodedValue", CellType.INTEGER, getCodedValue(), _missingRepresentation ) ); - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setCodePosition( String codePosition ) - { - _codePosition = codePosition; - } - - public String getCodePosition() - { - return _codePosition; - } - - public void setCodedValue( int codedValue ) - { - _codedValue = codedValue; - } - - public int getCodedValue() - { - return _codedValue; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefProbJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefProbJTableRowData.java deleted file mode 100644 index dedb96c72d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefProbJTableRowData.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefProbJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _p = null; - private String _name = null; - private float _probability = 0; - - public ArcBaseShefProbJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "P = " + _p + - " | Probability = " + _probability + - " | Name = " + _name; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "P", CellType.STRING, getP(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Probability", CellType.FLOAT, getProbability(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - } - - public void setP( String p ) - { - _p = p; - } - - public String getP() - { - return _p; - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setProbability( float probability ) - { - _probability = probability; - } - - public float getProbability() - { - return _probability; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefQCJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefQCJTableRowData.java deleted file mode 100644 index cddd6bf3ba..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefQCJTableRowData.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefQCJTableRowData extends AbstractJTableRowData -{ - private static final short MISSING = -9999; - - private String _missingRepresentation = ""; - - private String _shefQualifierCode = null; - private int _power = MISSING; - private String _name = null; - - public ArcBaseShefQCJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "ShefQualifierCode = " + _shefQualifierCode + - " | Power = " + _power + - " | Name = " + _name; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "ShefQCCode", CellType.STRING, getShefQualifierCode(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Power", CellType.INTEGER, getPower(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setShefQualifierCode( String shefQualifierCode ) - { - _shefQualifierCode = shefQualifierCode; - } - - public String getShefQualifierCode() - { - return _shefQualifierCode; - } - - public void setPower( int power ) - { - _power = power; - } - - public int getPower() - { - return _power; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefTSJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefTSJTableRowData.java deleted file mode 100644 index 5b4c785d94..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseShefTSJTableRowData.java +++ /dev/null @@ -1,55 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseShefTSJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _ts = null; - private String _name = null; - - public ArcBaseShefTSJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "TS = " + _ts + - " | Name = " + _name; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "TS", CellType.STRING, getTS(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - } - - public void setName( String name ) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setTS( String ts ) - { - _ts = ts; - } - - public String getTS() - { - return _ts; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseStateJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseStateJTableRowData.java deleted file mode 100644 index ff22705b48..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseStateJTableRowData.java +++ /dev/null @@ -1,94 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseStateJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _state = null; - private String _countryFips = null; - private String _name = null; - private String _ncdc = null; - private String _stateFips = null; - - public ArcBaseStateJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "State = " + _state + - " | CountryFips = " + _countryFips + - " | Name = " + _name + - " | Ncdc = " + _ncdc + - " | StateFips = " + _stateFips; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "State", CellType.STRING, getState(), _missingRepresentation ) ); - addCell( new BaseTableCell( "CountryFips", CellType.STRING, getCountryFips(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Name", CellType.STRING, getName(), _missingRepresentation ) ); - addCell( new BaseTableCell( "Ncdc", CellType.STRING, getNcdc(), _missingRepresentation ) ); - addCell( new BaseTableCell( "StateFips", CellType.STRING, getStateFips(), _missingRepresentation ) ); - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - _state = state ; - } - - public String getCountryFips() - { - return _countryFips; - } - - public void setCountryFips(String countryfips) - { - _countryFips = countryfips ; - } - - public String getName() - { - return _name; - } - - public void setName(String name) - { - _name = name ; - } - - public String getNcdc() - { - return _ncdc; - } - - public void setNcdc(String ncdc) - { - _ncdc = ncdc ; - } - - public void setStateFips( String stateFips ) - { - _stateFips = stateFips; - } - - public String getStateFips() - { - return _stateFips; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseWfoHsaJTableRowData.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseWfoHsaJTableRowData.java deleted file mode 100644 index ce89f95f1e..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/table/ArcBaseWfoHsaJTableRowData.java +++ /dev/null @@ -1,42 +0,0 @@ -package ohd.hseb.raxbase.table; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - - -public class ArcBaseWfoHsaJTableRowData extends AbstractJTableRowData -{ - private String _missingRepresentation = ""; - - private String _wfoHsa = null; - - public ArcBaseWfoHsaJTableRowData() - { - setMissingRepresentation( "" ); - } - - public String toString() - { - return "WfoHsa = " + _wfoHsa; - } - - /** - * Creates the individual cells and specifies its properties, like data tpe, value etc. - * - */ - public void addAllCellsToMap() - { - addCell( new BaseTableCell( "WfoHsa", CellType.STRING, getWfoHsa(), _missingRepresentation ) ); - } - - public void setWfoHsa( String wfoHsa ) - { - this._wfoHsa = wfoHsa; - } - - public String getWfoHsa() - { - return _wfoHsa; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/CursorController.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/CursorController.java deleted file mode 100644 index 75a382f0c1..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/CursorController.java +++ /dev/null @@ -1,35 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.awt.Component; -import java.awt.Cursor; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; - - -public final class CursorController -{ - public final static Cursor busyCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); - public final static Cursor defaultCursor = Cursor.getDefaultCursor(); - - private CursorController(){} - - public static ActionListener createListener( final Component component, final ActionListener mainActionListener) - { - ActionListener actionListener = new ActionListener() - { - public void actionPerformed(ActionEvent ae) - { - try - { - component.setCursor(busyCursor); - mainActionListener.actionPerformed(ae); - } - finally - { - component.setCursor(defaultCursor); - } - } - }; - return actionListener; - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/DateManager.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/DateManager.java deleted file mode 100644 index 4946b324db..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/DateManager.java +++ /dev/null @@ -1,66 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.util.Calendar; - -public class DateManager -{ - public static String getDateTimeStringFromCalendar( Calendar calendar ) - { - String dateTimeString = getDateStringFromCalendar( calendar ); - int hour = calendar.get( Calendar.HOUR_OF_DAY ); - String hourString = "" + hour; - int minute = calendar.get( Calendar.MINUTE ); - String minuteString = "" + minute; - int second = calendar.get( Calendar.SECOND ); - String secondString = "" + second; - - - if ( hour < 10 ) - { - hourString = "0" + hour; - } - if ( minute < 10 ) - { - minuteString = "0" + minute; - } - if ( second < 10 ) - { - secondString = "0" + second; - } - - dateTimeString += " " + hourString + ":" + minuteString + ":" + secondString; - - return dateTimeString; - } - - public static String getDateStringFromCalendar( Calendar calendar ) - { - int year = calendar.get( Calendar.YEAR ); - int month = calendar.get( Calendar.MONTH ) + 1; - int day = calendar.get( Calendar.DAY_OF_MONTH ); - String monthString = null; - String dayString = null; - - if ( month < 10 ) - { - monthString = "0" + month; - } - else - { - monthString = Integer.toString( month ); - } - - if ( day < 10 ) - { - dayString = "0" + day; - } - else - { - dayString = Integer.toString( day ); - } - - String dateString = year + "-" + monthString + "-" + dayString; - - return dateString; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/HDateSuperChooser.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/HDateSuperChooser.java deleted file mode 100644 index 3c77ca3a9a..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/HDateSuperChooser.java +++ /dev/null @@ -1,62 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.awt.GridBagConstraints; -import java.awt.Insets; -import java.awt.event.ActionEvent; - -import javax.swing.BoxLayout; -import javax.swing.JButton; - -import ohd.hseb.rfc.util.graphics.HDateChooser; -import ohd.hseb.rfc.util.graphics.HDateChooserOwner; -import ohd.hseb.rfc.util.graphics.HSwingFactory; - -public class HDateSuperChooser extends HDateChooser -{ - protected final static int CLEAR_BUTTON = 2; - protected boolean _clearDate = false; - - public HDateSuperChooser( boolean arg0 ) - { - super( arg0 ); - JButton nullButton = new JButton( "Clear" ); - nullButton.setFont( _buttonFont); - String[] buttonStringArray = {"OK", "Cancel", "Clear"}; - int[] groupsizes = {3}; - Insets theinsets = new Insets(5,5,5,0); - - GridBagConstraints constraints = HSwingFactory.returnGridBagConstraints(0,3,1,1,1,1, - GridBagConstraints.WEST,GridBagConstraints.BOTH,theinsets,0,0); - - - _buttons = HSwingFactory.createJButtons(buttonStringArray, _buttonFont, this); - _buttonPanel.removeAll(); - _buttonPanel = HSwingFactory.createJButtonBox(_buttons, groupsizes, BoxLayout.X_AXIS); - - - _fullPanel.add(_buttonPanel, constraints); - -// _buttonPanel.add( nullButton); - } - - public void actionPerformed(ActionEvent e) - { - _clearDate = false; - super.actionPerformed( e ); - if ( e.getSource() == _buttons[CLEAR_BUTTON] ) - { - int i; - for ( i = 0; i < _owners.size(); i++ ) - { - _clearDate = true; - ( (HDateChooserOwner)(_owners.get( i ))).dateChosen( this ); - } - setVisible(false); - } - } - - public boolean isClearDate() - { - return _clearDate; - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/JListPanelSuperCellRenderer.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/JListPanelSuperCellRenderer.java deleted file mode 100644 index 6eb426a0dc..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/JListPanelSuperCellRenderer.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Created on Mar 7, 2007 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package ohd.hseb.raxbase.util; - -import java.awt.Color; -import java.awt.Component; -import java.util.List; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JLabel; -import javax.swing.JList; - -import ohd.hseb.rfc.util.batch.BatchProcessor; -import ohd.hseb.rfc.util.batch.SystemSettings; -import ohd.hseb.rfc.util.listpanels.JListPanel; - -/** - * Wrapper on DefaultListCellRenderer; it turns the backgroun to a color if the specified cell - * corresponds to a location that has data. - * @author hank - */ -public class JListPanelSuperCellRenderer extends DefaultListCellRenderer -{ - private static final long serialVersionUID = 1L; - final static String CLASSNAME="JListPanelCellRenderer"; - - public final static Color DEFAULT_LIST_ITEM_BG_COLOR = Color.WHITE; - public final static Color DEFAULT_LIST_ITEM_SELECTED_BG_COLOR = Color.YELLOW; - - /** - * The list of items to highlight, by name. - */ - private List _listItemsHighlighted; - - /** - * The color for highlighted items. - */ - private Color _highlightBGColor; - - /** - * The color for non-highlighted items. - */ - private Color _listItemBGColor; - - /** - * The panel that this renderer is attached to. - */ - private JListPanel _panelBeingRendered; - - /** - * Text added to components (JLabel) that are "highlighted". - * Default value is "". - */ - private String _highlightedPrefixText; - - /** - * Text added to components (JLabel) that are not "highlighted". - * Default value is "". - */ - private String _notHighlightedPrefixText; - - - /** - * @param panel The panel to which this renderer is attached. - * @param listItemsHighlighted List of String (MUST BE Strings!) - * @param listItemBGColor BG color for non-highlighted - * @param highlightBGColor BG color for highlighted. - */ - public JListPanelSuperCellRenderer( - JListPanel panel, - List listItemsHighlighted) - { - _panelBeingRendered = panel; - _listItemsHighlighted = listItemsHighlighted; - _highlightedPrefixText = ""; - _notHighlightedPrefixText = ""; - this.loadColors("", ""); - } - - - /** - * @param panel The panel to which this renderer is attached. - * @param listItemsHighlighted List of String (MUST BE Strings!) - * @param listItemBGColor BG color for non-highlighted - * @param highlightBGColor BG color for highlighted. - */ - public JListPanelSuperCellRenderer( - JListPanel panel, - List listItemsHighlighted, - String listItemBGSystemSetting, - String highlightBGSystemSetting) - { - _panelBeingRendered = panel; - _listItemsHighlighted = listItemsHighlighted; - _highlightedPrefixText = ""; - _notHighlightedPrefixText = ""; - this.loadColors(listItemBGSystemSetting, highlightBGSystemSetting); - } - - - private void loadColors(String listItemBGSystemSetting, String listItemSelectedBGSystemSetting) - { - _listItemBGColor = SystemSettings.retrieveSystemSettingColor( - listItemBGSystemSetting, DEFAULT_LIST_ITEM_BG_COLOR); - _highlightBGColor = SystemSettings.retrieveSystemSettingColor( - listItemSelectedBGSystemSetting, DEFAULT_LIST_ITEM_SELECTED_BG_COLOR); - } - - - /** - * Override DefaultListCellRenderer. - */ - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) - { - Component comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - - comp.setForeground( Color.BLUE ); - //Deal with the prefix - if (!((String)value).equalsIgnoreCase(BatchProcessor.NONE_STR)) - { - if ((_listItemsHighlighted == null) || - (_listItemsHighlighted.indexOf((String)value) < 0)) - { - ((JLabel)comp).setText(_notHighlightedPrefixText + ((JLabel)comp).getText()); - } - else - { - ((JLabel)comp).setText(_highlightedPrefixText + ((JLabel)comp).getText()); - } - } - - //Deal with the background color. - if (_listItemsHighlighted == null) - { - return comp; - } - if ((_listItemsHighlighted.indexOf((String)value) >= 0) && (!isSelected)) - { - comp.setBackground(_highlightBGColor); - } - else if (!isSelected) - { - comp.setBackground(_listItemBGColor); - } - return comp; - } - - public void setHighlightedPrefixText(String str) - { - this._highlightedPrefixText = str; - } - public void setNotHightlightedPrefixText(String str) - { - this._notHighlightedPrefixText = str; - } - public JListPanel getPanelBeingRendered() - { - return this._panelBeingRendered; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/ModalDialogRunner.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/ModalDialogRunner.java deleted file mode 100644 index 7eb153b611..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/ModalDialogRunner.java +++ /dev/null @@ -1,27 +0,0 @@ -package ohd.hseb.raxbase.util; - -import ohd.hseb.raxbase.RaxBaseDataMgr; - -/** -* Pass in a dialog to the constructor, and this is ready to be inserted into a Thread. When -* run, it just makes the dialog visible. This allows for a non-blocking modal dialog to be -* created that can display progress while allowing the underlying process to continue execution. -* Normally, when a modal dialog is made visible, it blocks the working processing until closed. -* @author hank -*/ -public class ModalDialogRunner extends Thread -{ - - private RaxBaseDataMgr _dataMgr = null; - - public ModalDialogRunner( RaxBaseDataMgr dataMgr ) - { - _dataMgr = dataMgr; - } - - public void run() - { - _dataMgr.setRaxIngestFilterRowDataList( _dataMgr.createIngestFilterRowDataList() ); - _dataMgr.finishProcess(); - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/PEDTSEPManager.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/PEDTSEPManager.java deleted file mode 100644 index 2ba8dcb55d..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/PEDTSEPManager.java +++ /dev/null @@ -1,192 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.raxbase.RaxBaseDataMgr; -import ohd.hseb.raxbase.model.ShefDuration; -import ohd.hseb.raxbase.model.ShefExtremum; -import ohd.hseb.raxbase.model.ShefPE; -import ohd.hseb.raxbase.model.ShefProb; -import ohd.hseb.raxbase.model.ShefTS; -import ohd.hseb.util.gui.LabeledComboBox; - -public class PEDTSEPManager -{ - private RaxBaseDataMgr _dataMgr = null; - private LabeledComboBox _peLCB = null; - private LabeledComboBox _durLCB = null; - private LabeledComboBox _tsLCB = null; - private LabeledComboBox _extremumLCB = null; - private LabeledComboBox _probLCB = null; - - private List _peCBStringList = new ArrayList(); - private List _tsCBStringList = new ArrayList(); - private Map _peCBStringToPeMap = new HashMap(); - private Map _durCBStringToDurMap = new HashMap(); - private Map _durCBStringToIDurMap = new HashMap(); - private Map _probCBStringToProbMap = new HashMap(); - private Map _tsCBStringToTSMap = new HashMap(); - private Map _extremumCBStringToExtremumMap = new HashMap(); - - public PEDTSEPManager( RaxBaseDataMgr dataMgr ) - { - _dataMgr = dataMgr; - initComboBoxes(); - } - - private void initComboBoxes() - { - List shefPeList = _dataMgr.getShefPeList(); - List shefDurationList = _dataMgr.getShefDurationList(); - List shefTypeSourceList = _dataMgr.getShefTSList(); - List shefExtremumList = _dataMgr.getShefExtremumList(); - List shefProbList = _dataMgr.getShefProbList(); - - List shefPeStringList = new ArrayList(); - List shefDurationStringList = new ArrayList(); - List shefTypeSourceStringList = new ArrayList(); - List shefExtremumStringList = new ArrayList(); - List shefProbStringList = new ArrayList(); - - for ( int i = 0; i < shefPeList.size(); i++ ) - { - ShefPE shefPE = (ShefPE) shefPeList.get( i ); - shefPeStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringList.add( getShefPEComboBoxString( shefPE ) ); - _peCBStringToPeMap.put( getShefPEComboBoxString( shefPE ), shefPE.getPe() ); - } - - for ( int i = 0; i < shefDurationList.size(); i++ ) - { - ShefDuration shefDur = (ShefDuration) shefDurationList.get( i ); - shefDurationStringList.add( getShefDurationComboBoxString( shefDur ) ); - _durCBStringToDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur.getDuration() ); - _durCBStringToIDurMap.put( getShefDurationComboBoxString( shefDur ), shefDur.getIduration() ); - } - - for ( int i = 0; i < shefProbList.size(); i++ ) - { - ShefProb shefProb = (ShefProb) shefProbList.get( i ); - shefProbStringList.add( getShefProbComboBoxString( shefProb ) ); - _probCBStringToProbMap.put( getShefProbComboBoxString( shefProb ), shefProb.getP() ); - } - - for ( int i = 0; i < shefTypeSourceList.size(); i++ ) - { - ShefTS shefTS = (ShefTS) shefTypeSourceList.get( i ); - shefTypeSourceStringList.add( getShefTSString( shefTS ) ); - _tsCBStringList.add( getShefTSString( shefTS ) ); - _tsCBStringToTSMap.put( getShefTSString( shefTS ), shefTS.getTs() ); - } - - for ( int i = 0; i < shefExtremumList.size(); i++ ) - { - ShefExtremum shefEx = (ShefExtremum) shefExtremumList.get( i ); - shefExtremumStringList.add( getShefExtremumComboBoxString(shefEx ) ); - _extremumCBStringToExtremumMap.put( getShefExtremumComboBoxString( shefEx ), shefEx.getExtremum() ); - } - - _peLCB = new LabeledComboBox( "PE:", shefPeStringList ); - _durLCB = new LabeledComboBox( "Duration:", shefDurationStringList ); - _tsLCB = new LabeledComboBox( "Type Source:", shefTypeSourceStringList ); - _extremumLCB = new LabeledComboBox( "Extremum:", shefExtremumStringList ); - _probLCB = new LabeledComboBox( "Probability:", shefProbStringList ); - } - - public String getShefExtremumComboBoxString( ShefExtremum shefEx ) - { - String shefExtremumString = shefEx.getName() + " (" + shefEx.getExtremum() + ")"; - - return shefExtremumString; - } - - public String getShefTSString( ShefTS shefTS ) - { - String shefTSString = shefTS.getName() + " (" + shefTS.getTs() + ")"; - - return shefTSString; - } - - public String getShefPEComboBoxString( ShefPE shefPE ) - { - String shefPEString = shefPE.getPe() + " " + shefPE.getName(); - - return shefPEString; - } - - public String getShefDurationComboBoxString( ShefDuration shefDuration ) - { - String shefDurationString = shefDuration.getName() + " ( " + shefDuration.getIduration() + "/" + shefDuration.getDuration() + " )"; - - return shefDurationString; - } - - public String getShefProbComboBoxString( ShefProb shefProb ) - { - String shefProbString = ""; - - if ( shefProb != null ) - { - shefProbString = shefProb.getP() + "/" + shefProb.getProbability(); - } - - return shefProbString; - } - - public LabeledComboBox getPeLCB() - { - return _peLCB; - } - - public LabeledComboBox getDurLCB() - { - return _durLCB; - } - - public LabeledComboBox getTsLCB() - { - return _tsLCB; - } - - public LabeledComboBox getExtremumLCB() - { - return _extremumLCB; - } - - public LabeledComboBox getProbLCB() - { - return _probLCB; - } - - public Map getPeCBStringToPeMap() - { - return _peCBStringToPeMap; - } - - public Map getDurCBStringToDurMap() - { - return _durCBStringToDurMap; - } - - public Map getDurCBStringToIDurMap() - { - return _durCBStringToIDurMap; - } - public Map getProbCBStringToProbMap() - { - return _probCBStringToProbMap; - } - - public Map getTsCBStringToTSMap() - { - return _tsCBStringToTSMap; - } - public Map getExtremumCBStringToExtremumMap() - { - return _extremumCBStringToExtremumMap; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/PEManager.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/PEManager.java deleted file mode 100644 index 66ba7804e7..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/PEManager.java +++ /dev/null @@ -1,32 +0,0 @@ -package ohd.hseb.raxbase.util; - -public class PEManager -{ - public static String getPEFromPe1Pe2( String p, String e ) - { - return p + e; - } - - public static String getPe1FromPE( String pe ) - { - String pe1 = null; - - if ( pe != null ) - { - pe1 = "" + pe.charAt( 0 ); - } - return ( pe1 ); - } - - public static String getPe2FromPE( String pe ) - { - String pe2 = null; - - if ( pe != null ) - { - pe2 = "" + pe.charAt( 1 ); - } - - return ( pe2 ); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/RaxRatingShiftCalculator.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/RaxRatingShiftCalculator.java deleted file mode 100644 index 9f4e6b2cdf..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/RaxRatingShiftCalculator.java +++ /dev/null @@ -1,146 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.raxbase.model.RaxRating; -import ohd.hseb.raxbase.model.RaxRatingPoint; -import ohd.hseb.raxbase.model.RaxRatingShift; - -public class RaxRatingShiftCalculator -{ - private List _unShiftedRaxRatingPointList = null; - private RaxRatingShift _raxRatingShift = null; - private double[][] _ratingShift = new double[ 5 ][ 2 ]; - - public RaxRatingShiftCalculator( List raxRatingPointList, RaxRatingShift raxRatingShift ) - { - _unShiftedRaxRatingPointList = raxRatingPointList; - _raxRatingShift = raxRatingShift; - - initRatingShift(); - } - - public RaxRatingShiftCalculator( RaxRating raxRating, RaxRatingShift raxRatingShift ) - { - this( raxRating.getRaxRatingPointList(), raxRatingShift ); - } - - public RaxRatingShiftCalculator() - { - } - - public List getShiftedRaxRatingList() - { - double shift = 0; - double shiftedStage = 0; - double highShift = 0; - double lowShift = 0; - int i = 1; - - List shiftedRaxRatingList = new ArrayList(); - RaxRatingPoint shiftedRaxRatingPoint = new RaxRatingPoint(); - - for ( int ratingPointIndex = 0; ratingPointIndex < _unShiftedRaxRatingPointList.size(); ratingPointIndex++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) _unShiftedRaxRatingPointList.get( ratingPointIndex ); - double unshiftedStage = raxRatingPoint.getStage(); - - - if ( unshiftedStage < ( _ratingShift[ 0 ][ 0 ] + _ratingShift[ 0 ][ 1 ] ) ) - { - shift = _ratingShift[ 0 ][ 1 ]; - } - else - { - for ( i = 1; i < 5; ++i ) - { - if ( unshiftedStage < ( _ratingShift[ i ][ 0 ] + _ratingShift[ i ][ 1 ] ) ) - { - lowShift = _ratingShift[ i - 1 ][ 0 ] + _ratingShift[ i - 1 ][ 1 ]; - highShift = _ratingShift[ i ][ 0 ] + _ratingShift[ i ][ 1 ]; - - double slope = ( highShift - lowShift ) / ( _ratingShift[ i ][ 1 ] - _ratingShift[ i - 1 ][ 1 ] ); - - double intercept = ( _ratingShift[ i ][ 0 ] + _ratingShift[ i ][ 1 ] ) - - ( _ratingShift[ i ][ 1 ] * slope ); - - shift = ( unshiftedStage - intercept ) / slope; - break; - } - } - - if ( i == 5 ) - { - shift = _ratingShift[ 5-1 ][ 1 ]; - } - } - - shiftedStage = unshiftedStage - shift; - - shiftedRaxRatingPoint.setStage( shiftedStage ); - shiftedRaxRatingPoint.setDischarge( raxRatingPoint.getDischarge() ); - - shiftedRaxRatingList.add( shiftedRaxRatingPoint ); - shiftedRaxRatingPoint = new RaxRatingPoint(); -// System.out.println( "Stage: " + unshiftedStage + "\nDischarge: " + raxRatingPoint.getDischarge() + -// "\nShift: " + shift + "\nShiftedStage: " + shiftedStage + "\n=======\n"); - } - return shiftedRaxRatingList; - } - - public void initRatingShift() - { - double zeroFlowStage = getZeroFlowStage(); - if ( _ratingShift[ 1 ][ 0 ] > zeroFlowStage ) - { - _ratingShift[ 0 ][ 0 ] = zeroFlowStage; - } - - _ratingShift[ 1 ][ 0 ] = _raxRatingShift.getValA(); - _ratingShift[ 1 ][ 1 ] = _raxRatingShift.getShiftA(); - _ratingShift[ 2 ][ 0 ] = _raxRatingShift.getValB(); - _ratingShift[ 2 ][ 1 ] = _raxRatingShift.getShiftB(); - _ratingShift[ 3 ][ 0 ] = _raxRatingShift.getValC(); - _ratingShift[ 3 ][ 1 ] = _raxRatingShift.getShiftC(); - _ratingShift[ 4 ][ 0 ] = _raxRatingShift.getValD(); - _ratingShift[ 4 ][ 1 ] = _raxRatingShift.getShiftD(); - } - - private double getZeroFlowStage() - { - double value = 0; - - for ( int i = 0; i < _unShiftedRaxRatingPointList.size(); i++ ) - { - RaxRatingPoint ratingPoint = (RaxRatingPoint) _unShiftedRaxRatingPointList.get( i ); - - if ( ratingPoint.getDischarge() == 0 ) - { - value = ratingPoint.getStage(); - } - } - return value; - } - - public void setUnShiftedRaxRatingPointList( List unShiftedRaxRatingPointList ) - { - _unShiftedRaxRatingPointList = unShiftedRaxRatingPointList; - } - - public List getUnShiftedRaxRatingPointList() - { - return _unShiftedRaxRatingPointList; - } - - public void setRaxRatingShift( RaxRatingShift raxRatingShift ) - { - _raxRatingShift = raxRatingShift; - } - - public RaxRatingShift getRaxRatingShift() - { - return _raxRatingShift; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/ShiftedStage.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/ShiftedStage.java deleted file mode 100644 index 1beadb4052..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/ShiftedStage.java +++ /dev/null @@ -1,154 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.raxbase.model.RaxRatingPoint; -import ohd.hseb.raxbase.model.RaxRatingShift; - -public class ShiftedStage -{ - private List unShiftedRaxRatingPointList = new ArrayList(); - private List shiftedRaxRatingPointList = new ArrayList(); - private RaxRatingShift raxRatingShift = new RaxRatingShift(); - private double shifts[][] = { { 0, 0 }, - { 0.7, 5.00 }, - { 1.4, 2.50 }, - { 2.9, 4.00 }, - { 3.3, 7.00 } }; - - private void initLists() - { - RaxRatingPoint raxRatingPoint = new RaxRatingPoint(); - - raxRatingPoint.setStage( 0.5 ); - raxRatingPoint.setDischarge( 0 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 1 ); - raxRatingPoint.setDischarge( 225 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 2 ); - raxRatingPoint.setDischarge( 240 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 3 ); - raxRatingPoint.setDischarge( 270 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 4 ); - raxRatingPoint.setDischarge( 290 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 5 ); - raxRatingPoint.setDischarge( 330 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 6 ); - raxRatingPoint.setDischarge( 400 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - raxRatingPoint.setStage( 7 ); - raxRatingPoint.setDischarge( 450 ); - unShiftedRaxRatingPointList.add( raxRatingPoint ); - raxRatingPoint = new RaxRatingPoint(); - - raxRatingShift.setValA( 0.7 ); - raxRatingShift.setValB( 1.4 ); - raxRatingShift.setValC( 2.9 ); - raxRatingShift.setValD( 3.3 ); - raxRatingShift.setShiftA( 5.0 ); - raxRatingShift.setShiftB( 2.5 ); - raxRatingShift.setShiftC( 4.0 ); - raxRatingShift.setShiftD( 7.0 ); - - - } - - private double getZeroFlowStage() - { - double value = -9999; - - for ( int i = 0; i < unShiftedRaxRatingPointList.size(); i++ ) - { - RaxRatingPoint ratingPoint = (RaxRatingPoint) unShiftedRaxRatingPointList.get( i ); - - if ( ratingPoint.getDischarge() == 0 ) - { - value = ratingPoint.getStage(); - } - } - return value; - } - - private void calculateShifts() - { - double shift = 0; - double shiftedStage = 0; - double highShift = 0; - double lowShift = 0; - int i = 1; - - double zeroFlowStage = getZeroFlowStage(); - if ( ( zeroFlowStage != -9999 ) && - ( shifts[ 1 ][ 0 ] > zeroFlowStage ) ) - { - shifts[ 0 ][ 0 ] = zeroFlowStage; - } - - System.out.println( shifts[ 0 ][ 0 ] ); - - for ( int ratingPointIndex = 1; ratingPointIndex < unShiftedRaxRatingPointList.size(); ratingPointIndex++ ) - { - RaxRatingPoint raxRatingPoint = (RaxRatingPoint) unShiftedRaxRatingPointList.get( ratingPointIndex ); - double unshiftedStage = raxRatingPoint.getStage(); - - - if ( unshiftedStage < ( shifts[ 0 ][ 0 ] + shifts[ 0 ][ 1 ] ) ) - { - shift = shifts[ 0 ][ 1 ]; - } - else - { - for ( i = 1; i < 5; ++i ) - { - if ( unshiftedStage < ( shifts[ i ][ 0 ] + shifts[ i ][ 1 ] ) ) - { - lowShift = shifts[ i - 1 ][ 0 ] + shifts[ i - 1 ][ 1 ]; - highShift = shifts[ i ][ 0 ] + shifts[ i ][ 1 ]; - - double slope = ( highShift - lowShift ) / ( shifts[ i ][ 1 ] - shifts[ i - 1 ][ 1 ] ); - - double intercept = ( shifts[ i ][ 0 ] + shifts[ i ][ 1 ] ) - - ( shifts[ i ][ 1 ] * slope ); - - shift = ( unshiftedStage - intercept ) / slope; - break; - } - } - - if ( i == 5 ) - { - shift = shifts[ 5-1 ][ 1 ]; - } - } - - shiftedStage = unshiftedStage - shift; - System.out.println( "Stage: " + unshiftedStage + "\nDischarge: " + raxRatingPoint.getDischarge() + - "\nShift: " + shift + "\nShiftedStage: " + shiftedStage + "\n=======\n"); - } - } - - - public ShiftedStage() - { - initLists(); - calculateShifts(); - } - - public static void main( String[] args ) - { - ShiftedStage shiftedStage = new ShiftedStage(); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/StatusDialog.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/StatusDialog.java deleted file mode 100644 index d233ece923..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/StatusDialog.java +++ /dev/null @@ -1,41 +0,0 @@ -package ohd.hseb.raxbase.util; - -import java.awt.GridLayout; - -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; - -public class StatusDialog extends JDialog -{ - private JLabel _label = new JLabel(); - - public StatusDialog( String message ) - { - super( (JFrame) null, true ); - _label.setText( message ); - getContentPane().setLayout( new GridLayout( 1, 1 ) ); - this.add( _label ); - setAlwaysOnTop( true ); - pack(); - } - - public void setMessage( String message ) - { - _label.setText( message ); - } - - public String getMessage() - { - return _label.getText(); - } - public JLabel getLabel() - { - return _label; - } - - public void firePropListener() - { - firePropertyChange( "DONE", null, null ); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/StringPadder.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/StringPadder.java deleted file mode 100644 index 967d428614..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/StringPadder.java +++ /dev/null @@ -1,233 +0,0 @@ -package ohd.hseb.raxbase.util; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; - -public class StringPadder -{ - private int _frontPaddingLength; - private int _endPaddingLength; - - public StringPadder( int frontPaddingLength, int endPaddingLength ) - { - _frontPaddingLength = frontPaddingLength; - _endPaddingLength = endPaddingLength; - } - - - public String getFrontPaddedString( String str ) - { - String blankString = ""; - int strLength = 0; - - if ( str == null ) - { - strLength = 4; - } - else - { - strLength = str.length(); - } - - for ( int i = 0; i < ( _frontPaddingLength - strLength); i++ ) - { - blankString += " "; - } - - return ( str + blankString ); - } - - public String getFrontPaddedString( double doubleValue ) - { - if ( doubleValue == DbTable.getNullDouble() ) - { - return ( getFrontPaddedString( null ) ); - } - else - { - return ( getFrontPaddedString( doubleValue + "" ) ); - } - } - - public String getFrontPaddedString( short shortValue ) - { - if ( shortValue == DbTable.getNullShort() ) - { - return ( getFrontPaddedString( null ) ); - } - else - { - return ( getFrontPaddedString( shortValue + "" ) ); - } - } - - public String getFrontPaddedString( int intValue ) - { - if ( intValue == DbTable.getNullInt() ) - { - return ( getFrontPaddedString( null ) ); - } - else - { - return ( getFrontPaddedString( intValue + "" ) ); - } - } - - public String getFrontPaddedString( long longValue ) - { - if ( longValue == DbTable.getNullLong() ) - { - return ( getFrontPaddedString( null ) ); - } - else - { - return ( getFrontPaddedString( longValue + "" ) ); - } - } - - public String getFrontPaddedDateString( long dateValue ) - { - if ( dateValue == DbTable.getNullDate() ) - { - return ( getFrontPaddedString( null ) ); - } - else - { - String dateString = DbTimeHelper.getDateStringFromLongTime( dateValue ); - return ( getFrontPaddedString( dateString ) ); - } - } - - public String getFrontPaddedDateTimeString( long dateTimeValue ) - { - if ( dateTimeValue == DbTable.getNullDate() ) - { - return ( getFrontPaddedString( null ) ); - } - else - { - String dateString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeValue ); - return ( getFrontPaddedString( dateString ) ); - } - } - - - public String getEndPaddedString( String colName, boolean booleanValue ) - { - String blankString = ""; - int strLength = 0; - - if ( booleanValue ) - { - strLength = 4 + colName.length(); - } - else - { - strLength = 5 + colName.length(); - } - - for ( int i = 0; i < ( _endPaddingLength - strLength); i++ ) - { - blankString += " "; - } - - return ( blankString + booleanValue ); - } - - public String getEndPaddedString( String colName, String str ) - { - String blankString = ""; - int strLength = 0; - - if ( str == null ) - { - strLength = 4 + colName.length(); - } - else - { - strLength = str.length() + colName.length(); - } - - for ( int i = 0; i < ( _endPaddingLength - strLength); i++ ) - { - blankString += " "; - } - - return ( blankString + str ); - } - - public String getEndPaddedString( String colName, double doubleValue ) - { - if ( doubleValue == DbTable.getNullDouble() ) - { - return ( getEndPaddedString( colName, null ) ); - } - else - { - return ( getEndPaddedString( colName, doubleValue + "" ) ); - } - } - - public String getEndPaddedString( String colName, short shortValue ) - { - if ( shortValue == DbTable.getNullShort() ) - { - return ( getEndPaddedString( colName, null ) ); - } - else - { - return ( getEndPaddedString( colName, shortValue + "" ) ); - } - } - - public String getEndPaddedString( String colName, int intValue ) - { - if ( intValue == DbTable.getNullInt() ) - { - return ( getEndPaddedString( colName, null ) ); - } - else - { - return ( getEndPaddedString( colName, intValue + "" ) ); - } - } - - public String getEndPaddedString( String colName, long longValue ) - { - if ( longValue == DbTable.getNullLong() ) - { - return ( getEndPaddedString( colName, null ) ); - } - else - { - return ( getEndPaddedString( colName, longValue + "" ) ); - } - } - - public String getEndPaddedDateString( String colName, long dateValue ) - { - if ( dateValue == DbTable.getNullDate() ) - { - return ( getEndPaddedString( colName, null ) ); - } - else - { - String dateString = DbTimeHelper.getDateStringFromLongTime( dateValue ); - return ( getEndPaddedString( colName, dateString ) ); - } - } - - public String getEndPaddedDateTimeString( String colName, long dateTimeValue ) - { - if ( dateTimeValue == DbTable.getNullDate() ) - { - return ( getEndPaddedString( colName, null ) ); - } - else - { - String dateString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeValue ); - return ( getEndPaddedString( colName, dateString ) ); - } - } - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/TSManager.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/TSManager.java deleted file mode 100644 index 764dfab973..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxbase/util/TSManager.java +++ /dev/null @@ -1,19 +0,0 @@ -package ohd.hseb.raxbase.util; - -public class TSManager -{ - public static String getTSFromTandS( String t, String s ) - { - return t + s; - } - - public static String getTFromTS( String ts ) - { - return ( "" + ts.charAt( 0 ) ); - } - - public static String getSFromTS( String ts ) - { - return ( "" + ts.charAt( 1 ) ); - } -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/AdjustFactorDifferenceMgr.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/AdjustFactorDifferenceMgr.java deleted file mode 100644 index 47cdb42254..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/AdjustFactorDifferenceMgr.java +++ /dev/null @@ -1,285 +0,0 @@ -package ohd.hseb.raxdb_sync; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbRecord; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.AdjustFactorRecord; -import ohd.hseb.raxdb.generated.RaxAdjustFactorRecord; -import ohd.hseb.raxdb.generated.RaxAdjustFactorTable; - -public class AdjustFactorDifferenceMgr extends BaseDifferenceMgr implements IDifferenceMgr -{ - - public AdjustFactorDifferenceMgr(RaxSyncDataMgr dm) - { - setDataMgr(dm); - - setupOutputFiles("AdjustFactor"); - - } // end of Constructor - - //---------------------------------------------------------------------------------------------- - public DiffSet findDifferences() - { - DiffSet tableDifferences = new DiffSet(); - - List ihfsRecordList = null; - List raxRecordList = null; - - RecordDifference oneDifference = null; - - logApplicationMessage("\n" + _dm.getDateTimeStamp() + " Begin Analyzing AdjustFactor Table records..."); - - ihfsRecordList = _dm.getIhfsAdjustFactorRecordList(); - _numberOfIhfsRecords = _numberOfIhfsRecords + ihfsRecordList.size(); - raxRecordList = _dm.getRaxAdjustFactorRecordList(); - - //add the RAX records to a Map - Map raxPrimaryKeyMap = new HashMap(); - for (int i=0; i < raxRecordList.size(); i++) - { - RaxAdjustFactorRecord record = (RaxAdjustFactorRecord) raxRecordList.get(i); - String raxMapKey = createKeyForMap(record); - raxPrimaryKeyMap.put(raxMapKey, record); - } // end of raxRecordList for loop - - // loop through IHFS record list and check if same key found in RAX - // if not, this needs to be added as new to RAX - // if same key found then check to see if they are "different" - for (int i=0; i 1) - { - if (subColumn == 1) - raxColumnValue = ihfsValue.substring(0,1); - else - raxColumnValue = ihfsValue.substring(1,2); - } - } - - return raxColumnValue; - - }// end of createRaxPeOrTsFromIhfs method - - //---------------------------------------------------------------------------------------------- - protected String setRaxDurFromIhfsDur(int ihfsDur) - { - String shefDur = "?"; - String raxDur = "V"; - - // set RAX dur field charater based on IHFS dur field number, - // if no match found then set it to "V" - - shefDur = ParamCode.getShefDurationCode(ihfsDur); - - if (shefDur.equalsIgnoreCase("?")) - raxDur = "V"; - else - raxDur = shefDur; - - return raxDur; - - }// end of setRaxDurFromIhfsDur method - - //---------------------------------------------------------------------------------------------- - protected double ConvertRaxLonFromIhfsLon(double ihfsLon) - { - double raxLon = 0.0; - - // get RAX lon field by multiplying IHFS lon by -1.0 - // if IHFS is null then leave it null - - if (DbTable.isNull(ihfsLon)) - raxLon = ihfsLon; - else - raxLon = ihfsLon * -1.0; - - return raxLon; - - }// end of ConvertRaxLonFromIhfsLon method - - //---------------------------------------------------------------------------------------------- - protected long currentTimeMillisTrimmedToSeconds() - { - long trimmedToWholeSecond = (System.currentTimeMillis() / 1000) * 1000; - - return trimmedToWholeSecond; - - }// end of currentTimeMillisTrimmedToSeconds method - - //---------------------------------------------------------------------------------------------- - protected String makeMixedCase(String upperCase) - { - String mixedCase = null; - - // Call the method in HSEB's StringHelper class to - // 1) convert the string to ALL lowercase - // 2) seperate into individual words - // 3) capitalize the first letter of each word - // 4) assmble it back into a string - if (upperCase != null) - { - mixedCase = StringHelper.capitalizeFirstLetterOfWords(upperCase); - } - - return mixedCase; - - }// end of makeMixedCase method - - //---------------------------------------------------------------------------------------------- - protected void displayEndOfFindDifferencesMessage(String tableName) - { - logApplicationMessage(_numberOfIhfsRecords + " = Number of " + tableName + " records found in the IHFS db"); - - if (_numberOfSkippedRecords > 0) - logApplicationMessage(_numberOfSkippedRecords + " = Number of IHFS " + tableName + " records which were NOT compared to those in the RAX db"); - - logApplicationMessage(_numberOfSameRecords + " = Number of IHFS " + tableName + " records which are 'The Same' as those in the RAX db"); - logApplicationMessage(_numberOfModRecords + " = Number of IHFS " + tableName + " records which are 'Different' than those in the RAX db"); - logApplicationMessage(_numberOfNewRecords + " = Number of IHFS " + tableName + " records which are NOT found in the RAX db"); - - if (_numberOfModRecords > 0) - logApplicationMessage("Listing of Differences found between " + tableName + " tables are found in file\n" + _diffRecordsLogFile); - - if (_numberOfNewRecords > 0) - logApplicationMessage("Listing of New " + tableName + " records to be added to the RAX db are found in file\n" + _newRecordsLogFile); - - logApplicationMessage(_dm.getDateTimeStamp() + " End of Analysis of " + tableName + " Table."); - - closeOutputFiles(); - - } // end of method - - //---------------------------------------------------------------------------------------------- - protected void displayInsertUpdateStatsMessage(String tableName) - { - logApplicationMessage(_numberOfRaxRecordsUpdated + " = Number of " + tableName + " records Updated in the RAX db"); - logApplicationMessage(_numberOfRaxRecordsInserted + " = Number of " + tableName + " records Inserted in the RAX db"); - } // end of method - - //--------------------------------------------------------------------- - protected void setupOutputFiles(String tableName) - { - String directoryName = null; - String debugLogFile = null; - - directoryName = _dm.getLogsDirectory(); - - _newRecordsLogFile = directoryName + "/" + tableName + "RecordsNew.out"; - _diffRecordsLogFile = directoryName + "/" + tableName + "RecordsDifferent.out"; - debugLogFile = directoryName + "/" + tableName + "Debug.out"; - - _loggerForNew = new RaxSyncFileMgr(_newRecordsLogFile, true, false); - _loggerForDiffs = new RaxSyncFileMgr(_diffRecordsLogFile, true, false); - _loggerForDebug = new RaxSyncFileMgr(debugLogFile, true, false); - - } // end of setupOutputFiles method - - //--------------------------------------------------------------------- - private void closeOutputFiles() - { - _loggerForNew.close(); - _loggerForDiffs.close(); - _loggerForDebug.close(); - - } // end of closeOutputFiles method - - //---------------------------------------------------------------------------------------------- - public int processRaxInsertUpdate(int transactionType, String tablename, DbTable raxTable, DbRecord raxRecord, DbRecord modifiedRaxRecord) - { - - int numberOfFailedUpdateInserts = 0; - String recordCountErrorMessage = null; - String exceptionMessage = null; - - try - { - int recordCount = 0; - logInsertUpdateMessage(""); - - if (transactionType == UPDATE) - { - recordCountErrorMessage = " records were Updated!"; - exceptionMessage = " ERROR - Unable to Update"; - recordCount = update(raxTable, raxRecord, modifiedRaxRecord); - } - else // Insert - { - recordCountErrorMessage = " records were Inserted!"; - exceptionMessage = " ERROR - Unable to Insert"; - recordCount = insert(raxTable, raxRecord); - } - - if (recordCount != 1) - { - logInsertUpdateMessage("\nERROR - " + recordCount + recordCountErrorMessage); - } - else // success - { - if (transactionType == UPDATE) - { - logInsertUpdateMessage(formatInsertUpdateMessage(" Replaced old ", tablename, formatColumnsForInsertUpdateDisplay(raxRecord))); - logInsertUpdateMessage(formatInsertUpdateMessage(" Updated with ", tablename, formatColumnsForInsertUpdateDisplay(modifiedRaxRecord))); - _numberOfRaxRecordsUpdated++; - } - else // insert - { - logInsertUpdateMessage(formatInsertUpdateMessage(" Inserted new ", tablename, formatColumnsForInsertUpdateDisplay(raxRecord))); - _numberOfRaxRecordsInserted++; - } - } - } - catch (SQLException e) - { - logInsertUpdateMessage(formatInsertUpdateMessage(exceptionMessage, tablename, formatColumnsForInsertUpdateDisplay(raxRecord))); - logInsertUpdateMessage("Postgres log output " + e.getMessage()); - numberOfFailedUpdateInserts++; - } - - return numberOfFailedUpdateInserts; - - } // end of processRaxInsertUpdate method - - //---------------------------------------------------------------------------------------------- - protected String formatInsertUpdateMessage(String type, String tableName, String formattedColumns) - { - String formattedMessage = new String(_dm.getDateTimeStamp() + type + " RAX " + tableName + " record = " + formattedColumns); - return formattedMessage; - } // end of method - -} // end of BaseDifferenceMgr Base (abstract) class diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/CrestDifferenceMgr.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/CrestDifferenceMgr.java deleted file mode 100644 index 3e440e7c05..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/CrestDifferenceMgr.java +++ /dev/null @@ -1,321 +0,0 @@ -package ohd.hseb.raxdb_sync; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbRecord; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.CrestRecord; -import ohd.hseb.raxdb.generated.RaxCrestRecord; -import ohd.hseb.raxdb.generated.RaxCrestTable; - -public class CrestDifferenceMgr extends BaseDifferenceMgr implements IDifferenceMgr -{ - public CrestDifferenceMgr(RaxSyncDataMgr dm) - { - - setDataMgr(dm); - - setupOutputFiles("Crest"); - - } // end of Constructor - - public DiffSet findDifferences() - { - DiffSet tableDifferences = new DiffSet(); - - List ihfsRecordList = null; - List raxRecordList = null; - - RecordDifference oneDifference = null; - - String previousRecordsKey = "RussErb"; - - logApplicationMessage("\n" + _dm.getDateTimeStamp() + " Begin Analyzing Crest Table records..."); - - ihfsRecordList = _dm.getIhfsCrestRecordList(); - _numberOfIhfsRecords = _numberOfIhfsRecords + ihfsRecordList.size(); - raxRecordList = _dm.getRaxCrestRecordList(); - - //add the RAX records to a Map - Map raxPrimaryKeyMap = new HashMap(); - for (int i=0; i < raxRecordList.size(); i++) - { - RaxCrestRecord record = (RaxCrestRecord) raxRecordList.get(i); - String raxMapKey = createKeyForMap(record); - raxPrimaryKeyMap.put(raxMapKey, record); - } // end of raxRecordList for loop - - // loop through IHFS record list and check if same key found in RAX - // if not, this needs to be added as new to RAX - // if same key found then check to see if they are "different" - // If there are more than one IHFS record for the same Lid then only process the first one - for (int i=0; i= " + first + " and < " + last + " has " + ihfsRecordList.size() + " Records"); - System.gc(); - raxRecordList = _dm.getRaxIngestFilterRecordList(first, last); -// logApplicationMessage("\ngetRaxIngestFilterRecordList for range of >= " + first + " and < " + last + " has " + raxRecordList.size() + " Records"); - - //add the RAX records to a Map - Map raxPrimaryKeyMap = new HashMap(); - for (int i=0; i < raxRecordList.size(); i++) - { - RaxIngestFilterRecord record = (RaxIngestFilterRecord) raxRecordList.get(i); - String raxMapKey = createKeyForMap(record); - raxPrimaryKeyMap.put(raxMapKey, record); - } // end of raxRecordList for loop - - // loop through IHFS record list and check if same key found in RAX - // if not, this needs to be added as new to RAX - // if same key found then check to see if they are "different" - for (int i=0; i= 5)) - { - if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("A1")) - raxLocationStateId = "AL"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("A2")) - raxLocationStateId = "AK"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("A3")) - raxLocationStateId = "AZ"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("A4")) - raxLocationStateId = "AR"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("C1")) - raxLocationStateId = "CA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("C2")) - raxLocationStateId = "CO"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("C3")) - raxLocationStateId = "CT"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("D1")) - raxLocationStateId = "DE"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("D2")) - raxLocationStateId = "DC"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("F1")) - raxLocationStateId = "FL"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("G1")) - raxLocationStateId = "GA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("H1")) - raxLocationStateId = "HI"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("I1")) - raxLocationStateId = "ID"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("I2")) - raxLocationStateId = "IL"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("I3")) - raxLocationStateId = "IN"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("I4")) - raxLocationStateId = "IA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("K1")) - raxLocationStateId = "KS"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("K2")) - raxLocationStateId = "KY"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("L1")) - raxLocationStateId = "LA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M1")) - raxLocationStateId = "ME"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M2")) - raxLocationStateId = "MD"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M3")) - raxLocationStateId = "MA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M4")) - raxLocationStateId = "MI"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M5")) - raxLocationStateId = "MN"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M6")) - raxLocationStateId = "MS"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M7")) - raxLocationStateId = "MO"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("M8")) - raxLocationStateId = "MT"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N1")) - raxLocationStateId = "NE"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N2")) - raxLocationStateId = "NV"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N3")) - raxLocationStateId = "NH"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N4")) - raxLocationStateId = "NJ"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N5")) - raxLocationStateId = "NM"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N6")) - raxLocationStateId = "NY"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N7")) - raxLocationStateId = "NC"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("N8")) - raxLocationStateId = "ND"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("O1")) - raxLocationStateId = "OH"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("O2")) - raxLocationStateId = "OK"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("O3")) - raxLocationStateId = "OR"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("P1")) - raxLocationStateId = "PA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("R1")) - raxLocationStateId = "RI"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("S1")) - raxLocationStateId = "SC"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("S2")) - raxLocationStateId = "SD"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("T1")) - raxLocationStateId = "TN"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("T2")) - raxLocationStateId = "TX"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("U1")) - raxLocationStateId = "UT"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("V1")) - raxLocationStateId = "VT"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("V2")) - raxLocationStateId = "VA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("W1")) - raxLocationStateId = "WA"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("W2")) - raxLocationStateId = "WV"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("W3")) - raxLocationStateId = "WI"; - else if (ihfsRecord.getLid().substring(3,5).equalsIgnoreCase("W4")) - raxLocationStateId = "WY"; - } - - return raxLocationStateId; - - }// end of makeRaxLocStateIdFromIhfsRecord method - - //---------------------------------------------------------------------------------------------- - private String makeRaxLocCountyfipsFromIhfsRecord(LocationRecord ihfsRecord) - { - String raxCountyfips = null; - - // search through the countyfips Map to find a match for county|state - // if a match is found then use its countynum - // No match then set to default - - String countyfipsMapKey = createKeyForMap(ihfsRecord); - - raxCountyfips = (String) _ihfsCountyfipsMap.get(countyfipsMapKey); - - if (DbTable.isNull(raxCountyfips)) // not found in list - { - raxCountyfips = "XXX"; - } - - return raxCountyfips; - - }// end of makeRaxLocCountyfipsFromIhfsRecord method - - //---------------------------------------------------------------------------------------------- - private short setRaxLocPostFromIhfsRecord(LocationRecord ihfsRecord) - { - short raxLocationPost = 0; - - // set RAX location post field to 2 if IHFS Location post field is 1 - // else set it to ZERO - if (ihfsRecord.getPost() == 1) - raxLocationPost = 2; - - return raxLocationPost; - - }// end of setRaxLocPostFromIhfsRecord method - - //---------------------------------------------------------------------------------------------- - private String makeRaxLocRfcIdFromIhfsRecord(LocationRecord ihfsRecord) - { - String raxLocationRfcId = null; - - // to create a RAX location RFC id from an IHFS location record - // just use the first 2 characters of the IHFS rfc field - if (ihfsRecord.getRfc() != null) - { - if (ihfsRecord.getRfc().length() > 1) - { - raxLocationRfcId = ihfsRecord.getRfc().substring(0,2); - } - } - - return raxLocationRfcId; - - } // end of makeRaxLocRfcIdFromIhfsRecord method - - //---------------------------------------------------------------------------------------------- - private String makeRaxLocCountryIdFromIhfsRecord(LocationRecord ihfsRecord) - { - String raxLocationCountryId = null; - - // create a RAX Country ID from an IHFS location record - // set Counrty ID to "US" and then see if it needs to be changed - raxLocationCountryId = "US"; - - if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("AB")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("BC")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("MB")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("NB")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("NF")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("NT")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("NS")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("ON")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("PE")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("PQ")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("SK")) - raxLocationCountryId = "CA"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("YT")) - raxLocationCountryId = "CA"; - - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("AG")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("CM")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("CH")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("CI")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("CZ")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("CL")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("DF")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("DU")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("GU")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("GE")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("HD")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("JA")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("MX")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("MC")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("MR")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("NA")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("NL")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("OA")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("PU")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("QA")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("QR")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("SI")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("SO")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("TB")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("TM")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("TL")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("VL")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("VU")) - raxLocationCountryId = "MX"; - else if (ihfsRecord.getState().substring(0,2).equalsIgnoreCase("ZA")) - raxLocationCountryId = "MX"; - - return raxLocationCountryId; - - }// end of makeRaxLocCountryIdFromIhfsRecord method - - //---------------------------------------------------------------------------------------------- - protected int insert(DbTable dbTable, DbRecord dbRecord) throws SQLException - { - RaxLocationTable table = (RaxLocationTable) dbTable; - RaxLocationRecord record = (RaxLocationRecord) dbRecord; - - return table.insert(record); - } - - //---------------------------------------------------------------------------------------------- - protected int update(DbTable dbTable, DbRecord dbRecordOld, DbRecord dbRecordNew) throws SQLException - { - RaxLocationTable table = (RaxLocationTable) dbTable; - RaxLocationRecord recordOld = (RaxLocationRecord) dbRecordOld; - RaxLocationRecord recordNew = (RaxLocationRecord) dbRecordNew; - - return table.update(recordOld, recordNew); - } - -} // end of LocationDifferenceMgr class diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RatingCurveHolder.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RatingCurveHolder.java deleted file mode 100644 index 48801bcfa7..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RatingCurveHolder.java +++ /dev/null @@ -1,50 +0,0 @@ -package ohd.hseb.raxdb_sync; - -import ohd.hseb.db.DbRecord; -import ohd.hseb.raxbase.model.RaxRating; -import ohd.hseb.raxbase.model.RaxRatingShift; - -public class RatingCurveHolder extends DbRecord -{ - - private RaxRating _ratingCurve = null; - private RaxRatingShift _ratingShift = null; - - public RatingCurveHolder() - { - } - - public RatingCurveHolder(RaxRating ratingCurve, RaxRatingShift ratingShift) - { - setRatingCurve(ratingCurve); - setRatingShift(ratingShift); - } - - private void setRatingCurve(RaxRating ratingCurve) - { - _ratingCurve = ratingCurve; - } - - public RaxRating getRatingCurve() - { - return _ratingCurve; - } - - private void setRatingShift(RaxRatingShift ratingShift) - { - _ratingShift = ratingShift; - } - - public RaxRatingShift getRatingShift() - { - return _ratingShift; - } - - @Override - public String toString() - { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RatingDifferenceMgr.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RatingDifferenceMgr.java deleted file mode 100644 index 309a610730..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RatingDifferenceMgr.java +++ /dev/null @@ -1,690 +0,0 @@ -package ohd.hseb.raxdb_sync; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbRecord; -import ohd.hseb.db.DbTable; - -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.raxbase.db.CustomRaxRatingTable; -import ohd.hseb.raxbase.model.RaxRating; -import ohd.hseb.raxbase.model.RaxRatingPoint; -import ohd.hseb.raxbase.model.RaxRatingShift; -import ohd.hseb.raxdb.generated.RaxRatingRecord; -import ohd.hseb.raxdb.generated.RaxRatingShiftRecord; -import ohd.hseb.raxdb.generated.RaxRatingTable; - -public class RatingDifferenceMgr extends BaseDifferenceMgr implements IDifferenceMgr -{ - - Map _riverstatGsnoMap = null; - - public RatingDifferenceMgr(RaxSyncDataMgr dm) - { - setDataMgr(dm); - - setupOutputFiles("Rating"); - - } // end of Constructor - - //---------------------------------------------------------------------------------------------- - public DiffSet findDifferences() - { - DiffSet tableDifferences = new DiffSet(); - - List ihfsRecordList = null; - List ihfsRatingShiftRecordList = null; - List raxRecordList = null; - List raxRatingShiftRecordList = null; - - RecordDifference oneDifference = null; - - - logApplicationMessage("\n" + _dm.getDateTimeStamp() + " Begin Analyzing Rating Table records..."); - String tokenName = "adb_sync_ihfs_units"; - logApplicationMessage("Apps_defaults Token " + tokenName + " set to: " + _dm.getRawTokenValue(tokenName) + - "\nValue being used by this application is " + _dm.getRatingCurveUnits()); - tokenName = "adb_sync_ihfs_interpolate"; - logApplicationMessage("Apps_defaults Token " + tokenName + " set to: " + _dm.getRawTokenValue(tokenName) + - "\nValue being used by this application is " + _dm.getInterpolateType()); - - // Organize ALL of the individual IHFS Rating table database records into RaxRatingPoint objects (pairs) - // Then take all of these pairs (RaxRatingPoints) for one lid and combine then in one RaxRating object (rating cure) - - // get a list of ALL of the individual IHFS Rating table records - ihfsRecordList = _dm.getIhfsRatingRecordList(); - - String previousIhfsLid = "RussErb"; - List listOfRatingPoints = null; - List listOfIhfsRatingCurves = new ArrayList(); - // Loop through ALL of the IHFS Rating table records - for (int i=0; i 0) - { - RaxRating oneIhfsRatingCurve = new RaxRating(previousIhfsLid, listOfRatingPoints); - listOfIhfsRatingCurves.add(oneIhfsRatingCurve); - _numberOfIhfsRecords = _numberOfIhfsRecords + 1; - } - - // get a list of ALL of the individual IHFS RatingShift table records - ihfsRatingShiftRecordList = _dm.getIhfsRatingShiftRecordList(); - // convert them to RaxRatingShiftRecord objects - // create a Hash Map of IHFS Rax Rating Shift records - Map ihfsRaxRatingShiftRecordMap = new HashMap(); - for (int i=0; i < ihfsRatingShiftRecordList.size(); i++) - { - RaxRatingShiftRecord record = createRaxRatingShiftRecordFromIHFS((RatingShiftRecord) ihfsRatingShiftRecordList.get(i)); - String ratingShiftMapKey = record.getLid(); - ihfsRaxRatingShiftRecordMap.put(ratingShiftMapKey, record); - } // end of ihfsRatingShiftRecordList for loop - - - // get a list of ALL of the individual RAX RatingShift table records - raxRatingShiftRecordList = _dm.getRaxRatingShiftRecordList(); - // create a Hash Map of RAX Rating Shift records - Map raxRaxRatingShiftRecordMap = new HashMap(); - for (int i=0; i < raxRatingShiftRecordList.size(); i++) - { - RaxRatingShiftRecord record = (RaxRatingShiftRecord) raxRatingShiftRecordList.get(i); - String ratingShiftMapKey = record.getLid(); - raxRaxRatingShiftRecordMap.put(ratingShiftMapKey, record); - } // end of raxRatingShiftRecordList for loop - - - // get a list of ALL of the RAX Rating table records - raxRecordList = _dm.getRaxRatingRecordList(); - // create Rax Rating Curve from a Rax Rating Record and add to a Hash Map - Map raxRatingCurveMap = new HashMap(); - for (int i=0; i < raxRecordList.size(); i++) - { - RaxRatingRecord record = (RaxRatingRecord) raxRecordList.get(i); - RaxRating oneRaxRatingCurve = new RaxRating(record); - String ratingCurveMapKey = oneRaxRatingCurve.getLid(); - raxRatingCurveMap.put(ratingCurveMapKey, oneRaxRatingCurve); - } // end of raxRecordList for loop - - // loop through IHFS rating curve list and check if same key found in RAX - // if not, this needs to be added as new to RAX - // if same key found then check to see if they are "different" - for (int i=0; i 0) - { - RaxRatingRecord record = (RaxRatingRecord) recordList.get(0); - System.out.println("In Database, record = " + record); - - RaxRatingRecord newRecord = new RaxRatingRecord(record); - newRecord.setLid(newLid); - - - //delete test record - table.delete(where); - - - //insert a copy of the first retrieved record, with the lid changed - table.insert(newRecord); - System.out.print("After insert: "); - selectAndPrint(table, where); - - - //update - RaxRatingRecord newerRecord = new RaxRatingRecord(newRecord); - newerRecord.setSrc("CHIP"); - newerRecord.setStgflow(null); - table.update(newRecord, newerRecord); - - System.out.print("After update: "); - selectAndPrint(table, where); - - System.out.println(" ----" + record); - } - /* - //print all records - // recordList = table.selectNRecords("order by lid ", 150); - recordList = table.selectNRecords(bluo2Where, 150); - - - for (int i=0; i 0) - returnString = tokenValue; - - return returnString; - - } // end of method - - //--------------------------------------------------------------------- - public String getRiverCritPreference() - { - String returnString = "ACTION"; - - String tokenValue = getRawTokenValue("adb_sync_rivercrit"); - - if (tokenValue.compareToIgnoreCase("FIS") == 0) - returnString = "FIS"; - else if (tokenValue.compareToIgnoreCase("BOTH") == 0) - returnString = "BOTH"; - - return returnString; - - } // end of method - - //--------------------------------------------------------------------- - public String getRatingCurveUnits() - { - String returnString = "ENGL"; - - String tokenValue = getRawTokenValue("adb_sync_ihfs_units"); - - if (tokenValue.compareToIgnoreCase("METR") ==0) - returnString = "METR"; - - return returnString; - - } // end of method - - //--------------------------------------------------------------------- - public String getInterpolateType() - { - String returnString = "LIN"; - - String tokenValue = getRawTokenValue("adb_sync_ihfs_interpolate"); - - if (tokenValue.compareToIgnoreCase("LOG") == 0) - returnString = "LOG"; - - return returnString; - - } // end of method - - //--------------------------------------------------------------------- - public boolean useIngestColumnForComparison() - { - boolean returnValue = true; - - String tokenValue = getRawTokenValue("adb_sync_ihfs_ingest"); - - if (tokenValue.compareToIgnoreCase("IGNORE") == 0) - returnValue = false; - - return returnValue; - - } // end of method - - //--------------------------------------------------------------------- - public boolean isDebugOutputOn() - { - boolean returnValue = false; - - String tokenValue = getRawTokenValue("adb_sync_ihfs_debug"); - - if (tokenValue.compareToIgnoreCase("ON") == 0) - returnValue = true; - - return returnValue; - - } // end of method - - //--------------------------------------------------------------------- - public String getRawTokenValue(String tokenName) - { - String returnString = ""; - String tokenValue = null; - - tokenValue = _ad.getToken(tokenName); - - if (tokenValue != null) - returnString = tokenValue; - - return returnString; - - } // end of method - - //--------------------------------------------------------------------- - private void setupMainLogFile(String filename) - { - String logDirectory = null; - String applicationLogFile = null; - - logDirectory = getLogsDirectory(); - applicationLogFile = logDirectory + "/" + filename + "." + getDateStamp(); - - _loggerForApp = new FileLogger(applicationLogFile, true, false); - - } // end of setupMainLogFile method - - //--------------------------------------------------------------------- - public FileLogger getMainAppLogger() - { - return _loggerForApp; - } // end of method - - //--------------------------------------------------------------------- - private void setupUpdateInsertLogFile() - { - String updateInsertLogFile = null; - - updateInsertLogFile = getInsertUpdateLogFilename(); - - _loggerForUpdates = new FileLogger(updateInsertLogFile, true, false); - - } // end of setupInsertupdateLogFile method - - //--------------------------------------------------------------------- - public String getInsertUpdateLogFilename() - { - String logDirectory = null; - String filename = null; - - logDirectory = getLogsDirectory(); - filename = logDirectory + "/RaxDbMods.log." + getDateStamp(); - - return filename; - } // end of method - - //--------------------------------------------------------------------- - public FileLogger getInsertUpdateLogger() - { - return _loggerForUpdates; - } // end of method - - //--------------------------------------------------------------------- - public String getLogsDirectory() - { - String logDirectory = null; - String returnString = null; - - logDirectory = _ad.getToken("adb_sync_logs_dir"); - - if (logDirectory != null) - returnString = logDirectory; - else - returnString = "/rfc_arc/logs/dbsync"; - - return returnString; - - } // end of method - - //--------------------------------------------------------------------- - public DiffSet findAllDifferences(String tablenames) - { - DiffSet allDiffSets = new DiffSet(); - List diffFinderList = getDifferenceFinderList(tablenames); - - for (int i=0; i < diffFinderList.size(); i++) - { - IDifferenceMgr diffFinder = (IDifferenceMgr) diffFinderList.get(i); - DiffSet diffSet = diffFinder.findDifferences(); - allDiffSets.addDiffSet(diffSet); - System.gc(); - } - - return allDiffSets; - - } // end of findAllDifferences method - - //--------------------------------------------------------------------- - public List getDifferenceFinderList(String tablenames) - { - List list = new ArrayList(); - - String splitTablenames[] = tablenames.split("\\s+"); - - Set nameSet = new HashSet(); - for (int i=0; i < splitTablenames.length; i++) - { - nameSet.add(splitTablenames[i].toUpperCase()); - } - - if (nameSet.contains("LOCATION") || nameSet.contains("ALL")) - list.add(new LocationDifferenceMgr(this)); - if (nameSet.contains("INGESTFILTER") || nameSet.contains("ALL")) - list.add(new IngestFilterDifferenceMgr(this)); - if (nameSet.contains("CREST") || nameSet.contains("ALL")) - list.add(new CrestDifferenceMgr(this)); - if (nameSet.contains("RESERVOIR") || nameSet.contains("ALL")) - list.add(new ReservoirDifferenceMgr(this)); - if (nameSet.contains("DATALIMITS") || nameSet.contains("ALL")) - list.add(new DataLimitsDifferenceMgr(this)); - if (nameSet.contains("LOCDATALIMITS") || nameSet.contains("ALL")) - list.add(new LocDataLimitsDifferenceMgr(this)); - if (nameSet.contains("ADJUSTFACTOR") || nameSet.contains("ALL")) - list.add(new AdjustFactorDifferenceMgr(this)); - if (nameSet.contains("RIVERCRIT") || nameSet.contains("ALL")) - list.add(new RiverCritDifferenceMgr(this)); - if (nameSet.contains("RATING") || nameSet.contains("ALL")) - list.add(new RatingDifferenceMgr(this)); - - return list; - - } // end of getDifferenceFinderList method - - //--------------------------------------------------------------------- - public void reportAllDifferences(DiffSet setOfAllDifferences) - { - RecordDifference oneRecordDifference = new RecordDifference(); - - for (int i=0; i 1) - { - if (subColumn == 1) - raxColumnValue = primaryPe.substring(0,1); - else - raxColumnValue = primaryPe.substring(1,2); - } - } - - return raxColumnValue; - - }// end of createRaxPeFromIhfsPrimaryPe method - - //---------------------------------------------------------------------------------------------- - protected int insert(DbTable dbTable, DbRecord dbRecord) throws SQLException - { - RaxRiverCritTable table = (RaxRiverCritTable) dbTable; - RaxRiverCritRecord record = (RaxRiverCritRecord) dbRecord; - - return table.insert(record); - } - - //---------------------------------------------------------------------------------------------- - protected int update(DbTable dbTable, DbRecord dbRecordOld, DbRecord dbRecordNew) throws SQLException - { - RaxRiverCritTable table = (RaxRiverCritTable) dbTable; - RaxRiverCritRecord recordOld = (RaxRiverCritRecord) dbRecordOld; - RaxRiverCritRecord recordNew = (RaxRiverCritRecord) dbRecordNew; - - return table.update(recordOld, recordNew); - } - -} // end of RiverCritDifferenceMgr class diff --git a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RiverCritHolder.java b/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RiverCritHolder.java deleted file mode 100644 index 08b07a47de..0000000000 --- a/javaUtilities/hydro/ohd.rax_apps/src/ohd/hseb/raxdb_sync/RiverCritHolder.java +++ /dev/null @@ -1,50 +0,0 @@ -package ohd.hseb.raxdb_sync; - -import ohd.hseb.db.DbRecord; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.raxbase.model.RaxRiverCrit; - -public class RiverCritHolder extends DbRecord -{ - - private RaxRiverCrit _riverCrit = null; - private RiverstatRecord _riverstatRecord = null; - - public RiverCritHolder() - { - } - - public RiverCritHolder(RaxRiverCrit riverCrit, RiverstatRecord riverstatRecord) - { - setRaxRiverCrit(riverCrit); - setRiverstatRecord(riverstatRecord); - } - - private void setRaxRiverCrit(RaxRiverCrit riverCrit) - { - _riverCrit = riverCrit; - } - - public RaxRiverCrit getRaxRiverCrit() - { - return _riverCrit; - } - - private void setRiverstatRecord(RiverstatRecord riverstatRecord) - { - _riverstatRecord = riverstatRecord; - } - - public RiverstatRecord getRiverstatRecord() - { - return _riverstatRecord; - } - - @Override - public String toString() - { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/javaUtilities/hydro/ohd.raxdb/.classpath b/javaUtilities/hydro/ohd.raxdb/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.raxdb/.project b/javaUtilities/hydro/ohd.raxdb/.project deleted file mode 100644 index 84315337ce..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.raxdb - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.raxdb/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.raxdb/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 2df17f0ec3..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:23:56 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.raxdb/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.raxdb/META-INF/MANIFEST.MF deleted file mode 100644 index 3b5fc9e7f3..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/META-INF/MANIFEST.MF +++ /dev/null @@ -1,6 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Raxdb -Bundle-SymbolicName: ohd.raxdb -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/javaUtilities/hydro/ohd.raxdb/build.properties b/javaUtilities/hydro/ohd.raxdb/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.raxdb/build.xml b/javaUtilities/hydro/ohd.raxdb/build.xml deleted file mode 100644 index 816e3e0501..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.raxdb/ohd.raxdb.ecl b/javaUtilities/hydro/ohd.raxdb/ohd.raxdb.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.raxdb/scripts/CustomPreferredTableNames.txt b/javaUtilities/hydro/ohd.raxdb/scripts/CustomPreferredTableNames.txt deleted file mode 100644 index a9248ef7ea..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/scripts/CustomPreferredTableNames.txt +++ /dev/null @@ -1,114 +0,0 @@ -Crest=RaxCrest -DataLimits=RaxDataLimits -Location=RaxLocation -LocDataLimits=RaxLocDataLimits -Reservoir=RaxReservoir -IngestFilter=RaxIngestFilter -AdjustFactor=RaxAdjustFactor -RatingShift=RaxRatingShift -Rating=RaxRating -RiverCrit=RaxRiverCrit -Agency -Aliasid -Area -Areasens -Avg -Cgroup -Commentvalue -Counties -Country -Drain -Fgroup -Fgroupseg -Flashflood -Huc2 -Huc4 -Huc6 -Huc8 -Modaeicqn -Modaescchng -Modaiadj -Modapicbasf -Modapicco -Modbublshft -Modchgblend -Modctrl -Modignorets -Modmatchng -Modmfc -Modqcshift -Modqpshift -Modrainsnow -Modrochng -Modromult -Modrrichng -Modrrimult -Modsacbasef -Modsacco -Modsetmsng -Modsetqmean -Modssarreg -Modswitchts -Modtsadd -Modtschng -Modtsmult -Modtsrepl -Moduadj -Moduhgadj -Moduhgchng -Modweadd -Modwechng -Modxinco -Modzerodiff -Ofsdatatrans -Ofsstntrans -Operapicont -Opersacsma -Opersnow17 -Opertype -Operunithg -Pairedvalues -Pecrsep -Pedcsep -Pedfsep -Pedpsep -Pedrsep -Pehfsep -Pehpsep -Pempsep -Pemrsep -Peoosep -Peqfsep -Peqpsep -Peirsep -Pos -Prod -Qadjust -Rfc -Seg -Segoper -Sensok -Shefdur -Shefex -Shefpe1 -Shefpe -Shefpetrans -Shefprob -Shefqc -Shefts -Slopeprofile -State -Statesapicont -Statessacsma -Statessnow17 -Swsmail -Unkstnvalue -Vaddadjust -Vfypairs -Vfyprocpairs -Vfyruninfo -Wfo_hsa -Wsequation -Wsfcst -Wshistorical -Wsperstats diff --git a/javaUtilities/hydro/ohd.raxdb/scripts/PreferredTableNames.txt b/javaUtilities/hydro/ohd.raxdb/scripts/PreferredTableNames.txt deleted file mode 100644 index a9248ef7ea..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/scripts/PreferredTableNames.txt +++ /dev/null @@ -1,114 +0,0 @@ -Crest=RaxCrest -DataLimits=RaxDataLimits -Location=RaxLocation -LocDataLimits=RaxLocDataLimits -Reservoir=RaxReservoir -IngestFilter=RaxIngestFilter -AdjustFactor=RaxAdjustFactor -RatingShift=RaxRatingShift -Rating=RaxRating -RiverCrit=RaxRiverCrit -Agency -Aliasid -Area -Areasens -Avg -Cgroup -Commentvalue -Counties -Country -Drain -Fgroup -Fgroupseg -Flashflood -Huc2 -Huc4 -Huc6 -Huc8 -Modaeicqn -Modaescchng -Modaiadj -Modapicbasf -Modapicco -Modbublshft -Modchgblend -Modctrl -Modignorets -Modmatchng -Modmfc -Modqcshift -Modqpshift -Modrainsnow -Modrochng -Modromult -Modrrichng -Modrrimult -Modsacbasef -Modsacco -Modsetmsng -Modsetqmean -Modssarreg -Modswitchts -Modtsadd -Modtschng -Modtsmult -Modtsrepl -Moduadj -Moduhgadj -Moduhgchng -Modweadd -Modwechng -Modxinco -Modzerodiff -Ofsdatatrans -Ofsstntrans -Operapicont -Opersacsma -Opersnow17 -Opertype -Operunithg -Pairedvalues -Pecrsep -Pedcsep -Pedfsep -Pedpsep -Pedrsep -Pehfsep -Pehpsep -Pempsep -Pemrsep -Peoosep -Peqfsep -Peqpsep -Peirsep -Pos -Prod -Qadjust -Rfc -Seg -Segoper -Sensok -Shefdur -Shefex -Shefpe1 -Shefpe -Shefpetrans -Shefprob -Shefqc -Shefts -Slopeprofile -State -Statesapicont -Statessacsma -Statessnow17 -Swsmail -Unkstnvalue -Vaddadjust -Vfypairs -Vfyprocpairs -Vfyruninfo -Wfo_hsa -Wsequation -Wsfcst -Wshistorical -Wsperstats diff --git a/javaUtilities/hydro/ohd.raxdb/scripts/PreferredTableNames.txt.temp b/javaUtilities/hydro/ohd.raxdb/scripts/PreferredTableNames.txt.temp deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.raxdb/scripts/create_table_names_file b/javaUtilities/hydro/ohd.raxdb/scripts/create_table_names_file deleted file mode 100644 index 7e7c2cc3b3..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/scripts/create_table_names_file +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/ksh - -export HOME_DIR=/fs/hseb/${DS_BUILD}/ohd -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. - - -export IHFS_TABLE_DIR=$HOME_DIR/whfs/schema/IHFS/tables -export VIEW_DIR=$HOME_DIR/whfs/schema/IHFS/views - -export TABLE_FILE_TEMP=$PROJECTS_DIR/raxdb/scripts/PreferredTableNames.txt.temp -export TABLE_IHFS_FILE=$PROJECTS_DIR/raxdb/scripts/PreferredTableNames.txt -export CUSTOM_TABLE_FILE_TEMP=$PROJECTS_DIR/raxdb/scripts/CustomPreferredTableNames.txt -export LS="ls" -export CAT="cat" - -$LS $IHFS_TABLE_DIR $VIEW_DIR > $TABLE_FILE_TEMP -$CAT $TABLE_FILE_TEMP | grep -v '^s\.' | grep '\.t' |/usr/bin/cut -d. -f1 > $TABLE_IHFS_FILE -$CAT $CUSTOM_TABLE_FILE_TEMP >> $TABLE_IHFS_FILE -echo TABLE_IHFS_FILE = $TABLE_IHFS_FILE diff --git a/javaUtilities/hydro/ohd.raxdb/scripts/run_raxdb_jdbgen b/javaUtilities/hydro/ohd.raxdb/scripts/run_raxdb_jdbgen deleted file mode 100644 index d90ba4777c..0000000000 --- a/javaUtilities/hydro/ohd.raxdb/scripts/run_raxdb_jdbgen +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/ksh - -export DRIVERPATH=/usr/lib/postgresql-8.2-506.jdbc3.jar -export RUN_FROM_DIR=`dirname $0` -export PROJECTS_DIR=$RUN_FROM_DIR/../.. - -export RAXDB_DIR=$PROJECTS_DIR/raxdb -export DB_DIR=$PROJECTS_DIR/db - -export BASEPATH=$DB_DIR/classes - -export CLASSPATH=./:$BASEPATH/:$DRIVERPATH -echo "CLASSPATH =" $CLASSPATH - -#db name -dbname=adb_ob83empty - -#The connection string -connecturl="jdbc:postgresql://genessee:5432/$dbname?user=pguser" - -#The location of the PreferredTableNames.txt file. -namingfile=$RAXDB_DIR/scripts/CustomPreferredTableNames.txt - -#The destination of the generated source files -targetdir=$RAXDB_DIR/src/ohd/hseb/raxdb/generated - -#package name -- NONE means no packaging -# Note: this does NOT affect directly in which the generated class is placed -package=ohd.hseb.raxdb.generated - -db_driver_class_name=org.postgresql.Driver - -$JAVADIR/bin/java ohd.hseb.dbgen.JDbGen $connecturl $namingfile $dbname $package $targetdir $db_driver_class_name - -return $? diff --git a/javaUtilities/hydro/ohd.rivermonitor/.classpath b/javaUtilities/hydro/ohd.rivermonitor/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.rivermonitor/.project b/javaUtilities/hydro/ohd.rivermonitor/.project deleted file mode 100644 index 2157f4f379..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.rivermonitor - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.rivermonitor/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.rivermonitor/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 278fa32701..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:27:58 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.rivermonitor/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.rivermonitor/META-INF/MANIFEST.MF deleted file mode 100644 index 52212ab721..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/META-INF/MANIFEST.MF +++ /dev/null @@ -1,12 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Rivermonitor -Bundle-SymbolicName: ohd.rivermonitor -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.tsl;bundle-version="1.0.0", - ohd.pdc_pp;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0", - ohd.ihfsdb;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.rivermonitor/build.properties b/javaUtilities/hydro/ohd.rivermonitor/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.rivermonitor/build.xml b/javaUtilities/hydro/ohd.rivermonitor/build.xml deleted file mode 100644 index 97678ad0d1..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rivermonitor/ohd.rivermonitor.ecl b/javaUtilities/hydro/ohd.rivermonitor/ohd.rivermonitor.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.rivermonitor/scripts/init_rivermon_tables.ksh b/javaUtilities/hydro/ohd.rivermonitor/scripts/init_rivermon_tables.ksh deleted file mode 100644 index 8e8115f4c5..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/scripts/init_rivermon_tables.ksh +++ /dev/null @@ -1,121 +0,0 @@ -#!/bin/ksh - -#Authors: Chip Gobs / Varalakshmi Rajaram -#Date : Sept 22, 2006 -#Initialize rivermonlocation and rivermongroup tables - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -###################### function -fill_rivermon_group_and_location(){ - $POSTGRESQLBINDIR/psql $DB_NAME -e << END - - --- create a table to hold the group information, --- we will later load this table into RiverMonGroup - - create table group_temp(group_id varchar(8), - group_name varchar(32), - ordinal integer, - hsa varchar(3)); - --- fill up the groups initially with what is in RpfFcstGroup - - insert into group_temp select * from RpfFcstGroup; - - --- add in the standard default group --- this is being done to prevent unknown side effects in its absence - insert into group_temp values('DEFAULT', 'DEFAULT GROUP', 1, (select hsa from admin limit 1) ); - - --- add in a default group per HSA - create table default_group_temp(group_id varchar(8), - group_name varchar(32), - ordinal integer, - hsa varchar(3)); - - insert into default_group_temp ( hsa ) - (select distinct(hsa) from location l, riverstat r - where l.lid = r.lid); - - update default_group_temp - set group_id = 'DEF_'||hsa, - group_name = hsa||' DEFAULT GROUP', - ordinal = 1; - - insert into group_temp - select group_id, group_name, ordinal, hsa from default_group_temp; - - - select * from group_temp; - - - --- add all locations to location_temp according to location and riverstat data - create table location_temp(lid varchar(8), - group_id varchar(8), - ordinal integer, - hsa varchar(3)); - - insert into location_temp(lid, hsa) - select lid, hsa from location - where (type <> 'I' or type is null) and - lid in(select lid from riverstat); - --- update locations according to RpfFcstPoint data - update location_temp set - group_id=(select group_id from rpffcstpoint where lid=location_temp.lid); - update location_temp set - ordinal=(select ordinal from rpffcstpoint where lid=location_temp.lid); - - --- for the non-grouped river data points, assign the default group information, based on the HSA of the point - update location_temp set - group_id=(select group_id from default_group_temp g - where hsa = location_temp.hsa) where group_id is null; - update location_temp set - ordinal=1 where ordinal is null; - - select * from location_temp; - - - --- update the hsa for the groups, based on their points - update group_temp set - hsa=(select hsa from location_temp where group_id=group_temp.group_id order by lid limit 1); - --- for the case of an empty group, give it the admin.hsa - update group_temp set hsa=(select hsa from admin) where hsa is NULL; - - - select * from group_temp; - - --- copy the temp table information to the real tables - delete from rivermonlocation; - delete from rivermongroup; - - insert into RiverMonGroup - select * from group_temp; - insert into RiverMonLocation - select lid, group_id, ordinal from location_temp; - - --- clean up the temp tables - drop table default_group_temp; - drop table location_temp; - drop table group_temp; - -END - -} - - -#fn - -fill_rivermon_group_and_location diff --git a/javaUtilities/hydro/ohd.rivermonitor/scripts/start_rivermonitor b/javaUtilities/hydro/ohd.rivermonitor/scripts/start_rivermonitor deleted file mode 100644 index 6adb3fbc74..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/scripts/start_rivermonitor +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/ksh - -# File name: start_rivermonitor -# Author : Varalakshmi Rajaram - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH:$PLUGINDIR:$WHFS_BIN_DIR/RiverMonitor.jar:$CLASSPATH - -MISSING_REPRESENTATION=' ' - -#Execute the RiverMonitor - -if [[ $# > 0 ]] -then -MONITOR_NAME="$1" -else -MONITOR_NAME="River" -fi - -xterm -T $MONITOR_NAME"Monitor" -iconic \ --e $SYS_JAVA_DIR/bin/java -Xms64m -Xmx512m ohd.hseb.monitor.Monitor $JDBCURL "$MISSING_REPRESENTATION" $MONITOR_NAME & - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmColumns.java deleted file mode 100644 index cb16bc457e..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmColumns.java +++ /dev/null @@ -1,68 +0,0 @@ -package ohd.hseb.alertalarm; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class AlertAlarmColumns -{ - public static String LID = "LocId"; - public static String PE = "PE"; - public static String DUR= "Dur"; - public static String TS = "TS"; - public static String EXT = "Ext"; - public static String PROB = "Prob"; - public static String VALID_TIME = "ValidTime"; - public static String BASIS_TIME = "BasisTime"; - public static String VALUE = "Value"; - public static String SUP_VALUE = "Sup Val"; - public static String SHEF_QUAL_CODE = "SQC"; - public static String QUAL_CODE = "QC"; - public static String REVISION = "Rev"; - public static String PRODUCT_ID = "ProdId"; - public static String PROD_TIME = "ProductTime"; - public static String POSTING_TIME = "PostingTime"; - public static String ACTION_TIME = "ActionTime"; - public static String DESC = "Desc"; - public static String THREAT = "Threat"; - - - /** - * Creates a list of alertalarm columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the alertalarm columns are added to it, - * if not the alertalarm columns are added to the list that is passed as argument. - * The created new list is returned. - * @param officeNotesColumnDescriptorList - * @return - */ - public List getAlertAlarmColumnsList(List alertAlarmColumnDescriptorList) - { - if( alertAlarmColumnDescriptorList == null) - { - alertAlarmColumnDescriptorList = new ArrayList(); - } - - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(LID, true, 50, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PE, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(DUR, true, 25, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(TS, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(EXT, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PROB, true, 35, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(VALID_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(BASIS_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(VALUE, true, 50, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(SUP_VALUE, true, 50, "right")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(SHEF_QUAL_CODE, true, 35, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(QUAL_CODE, true, 40, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(REVISION, true, 25, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_ID, true, 100, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(PROD_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(POSTING_TIME, true, 90, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(ACTION_TIME, true, 70, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(DESC, true, 45, "center")); - alertAlarmColumnDescriptorList.add(new JTableColumnDescriptor(THREAT, true, 45, "center")); - - return alertAlarmColumnDescriptorList; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmDataManager.java deleted file mode 100644 index 571d0f64c1..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmDataManager.java +++ /dev/null @@ -1,154 +0,0 @@ -package ohd.hseb.alertalarm; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.AlertAlarmValRecord; -import ohd.hseb.ihfsdb.generated.AlertAlarmValTable; -import ohd.hseb.util.SessionLogger; - -public class AlertAlarmDataManager -{ - private Database _db = null; - private SessionLogger _logger = null; - private String _missingRepresentation; - - public AlertAlarmDataManager(Database dbHandler, SessionLogger logger, String missingRepresentation) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","AlertAlarm Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public List readDataFromAlertAlarmVal() - { - List alertAlarmInfoList = null; - List dataList = null; - String header = "AlertAlarmDataManager.readDataFromAlertAlarmVal(): "; - AlertAlarmValTable alertAlarmValTable = new AlertAlarmValTable(_db); - AlertAlarmValRecord alertAlarmValRecord = null; - String whereClause = null; - try - { - whereClause = "order by lid"; - alertAlarmInfoList = alertAlarmValTable.select(whereClause); - _logger.log(header + " Where clause:"+ whereClause); - if(alertAlarmInfoList != null) - { - dataList = new ArrayList(); - for(int i=0;i < alertAlarmInfoList.size(); i++) - { - - alertAlarmValRecord = (AlertAlarmValRecord) alertAlarmInfoList.get(i); - AlertAlarmJTableRowData rowData = new AlertAlarmJTableRowData(_missingRepresentation); - //rowData.setAlertAlarmRecord(alertAlarmValRecord); - rowData.setLid(alertAlarmValRecord.getLid()); - rowData.setPe(alertAlarmValRecord.getPe()); - rowData.setTs(alertAlarmValRecord.getTs()); - - rowData.setDur(alertAlarmValRecord.getDur()); - - rowData.setExtremum(alertAlarmValRecord.getExtremum()); - - if(alertAlarmValRecord.getProbability() == -1.0) - { - rowData.setProbability(DbTable.getNullFloat()); - } - else - { - rowData.setProbability(alertAlarmValRecord.getProbability()); - } - - rowData.setValidTime(alertAlarmValRecord.getValidtime()); - rowData.setBasisTime(alertAlarmValRecord.getBasistime()); - - rowData.setValue(alertAlarmValRecord.getValue()); - - if(alertAlarmValRecord.getSuppl_value() == -9999.0) - { - rowData.setSupplValue(DbTable.getNullDouble()); - } - else - { - rowData.setSupplValue(alertAlarmValRecord.getSuppl_value()); - } - - rowData.setShefQualCode(alertAlarmValRecord.getShef_qual_code()); - - String result = null; - if(alertAlarmValRecord.getQuality_code() == DbTable.getNullInt()) - result = _missingRepresentation; - else if(alertAlarmValRecord.getQuality_code() >= 1610612736) - result = "Good"; - else if(alertAlarmValRecord.getQuality_code() >= 1073741824) - result = "Quest"; - else - result = "Bad"; - - rowData.setQualityCode(result); - - if(alertAlarmValRecord.getRevision() == DbTable.getNullShort()) - { - result = _missingRepresentation; - } - else if(alertAlarmValRecord.getRevision() == 1) - { - result = "Y"; - } - else - { - result = "N"; - } - rowData.setRevision(result); - - rowData.setProductId(alertAlarmValRecord.getProduct_id()); - - rowData.setProductTime(alertAlarmValRecord.getProducttime()); - - rowData.setPostingTime(alertAlarmValRecord.getPostingtime()); - - rowData.setActionTime(alertAlarmValRecord.getAction_time()); - - rowData.setAaCateg(alertAlarmValRecord.getAa_categ()); - rowData.setAaCheck(alertAlarmValRecord.getAa_check()); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" AlertAlarminfo list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmDialog.java deleted file mode 100644 index c60da12f47..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmDialog.java +++ /dev/null @@ -1,115 +0,0 @@ -package ohd.hseb.alertalarm; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; - -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class AlertAlarmDialog extends JDialog -{ - private List _alertAlarmColumnDescriptorList = null; - private JTableManager _alertAlarmTableManager = null; - private AlertAlarmDataManager _alertAlarmDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private SessionLogger _logger = null; - private int _previousRowToHighlight = -1; - private JFrame _mainFrame = null; - private JMenuBar _menuBar; - private JMenu _fileMenu; - private JMenuItem _selectColumnsMenuItem; - - public AlertAlarmDialog(JFrame mainFrame, AlertAlarmDataManager alertAlarmDataMgr, SessionLogger logger) - { - super(mainFrame, true); - _mainFrame = mainFrame; - _logger = logger; - this.setTitle("AlertAlarm"); - this.getContentPane().setLayout(new GridBagLayout()); - _alertAlarmDataMgr = alertAlarmDataMgr; - initialize(); - Dimension dim = new Dimension(1040,560); - new WindowResizingManager(this, dim, dim); - this.pack(); - this.setLocation(25, 25); - } - - public void showAlertAlarmDialog(String lid) - { - _allRowDataList = _alertAlarmDataMgr.readDataFromAlertAlarmVal(); - _alertAlarmTableManager.setChangedAllRowDataList(_allRowDataList); - _alertAlarmTableManager.refreshDisplay(); - - if(lid != null) - { - _alertAlarmTableManager.deselectRows(_previousRowToHighlight, _previousRowToHighlight); - int rowToHighLight = _alertAlarmTableManager.getTheRowIndexToHighLightBasedOnValue(lid); - if(rowToHighLight != -1) - { - System.out.println("Row to highlight:"+ rowToHighLight); - _alertAlarmTableManager.selectRows(rowToHighLight, rowToHighLight); - _previousRowToHighlight = rowToHighLight; - } - } - this.setVisible(true); - } - - private void initialize() - { - _alertAlarmColumnDescriptorList = new AlertAlarmColumns().getAlertAlarmColumnsList(_alertAlarmColumnDescriptorList); - _allRowDataList = _alertAlarmDataMgr.readDataFromAlertAlarmVal(); - _alertAlarmTableManager = new ComplexJTableManager(_alertAlarmColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _alertAlarmTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _alertAlarmTableManager.setDisplayableColumns(columnsSelected, true, true); - _alertAlarmTableManager.setPreferredSizeForJScrollPane(new Dimension(1020, 500)); - _tableScrollPane = _alertAlarmTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(1030,510)); - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - - _menuBar = new JMenuBar(); - this.setJMenuBar(_menuBar); - - _fileMenu = new JMenu("File"); - _selectColumnsMenuItem = new JMenuItem("Select Columns ..."); - _selectColumnsMenuItem.setMnemonic('S'); - _fileMenu.add(_selectColumnsMenuItem); - - _menuBar.add(_fileMenu); - - ChangeColumnsDisplayedMenuListener changeMenuListener = new - ChangeColumnsDisplayedMenuListener(); - _selectColumnsMenuItem.addActionListener(changeMenuListener); - - Container contentPane = this.getContentPane(); - contentPane.add(tablePanel); - } - - private class ChangeColumnsDisplayedMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _alertAlarmTableManager.invokeColumnSelector(_mainFrame); - - } - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmJTableRowData.java deleted file mode 100644 index 1dce67be70..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/alertalarm/AlertAlarmJTableRowData.java +++ /dev/null @@ -1,221 +0,0 @@ -package ohd.hseb.alertalarm; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class AlertAlarmJTableRowData extends AbstractJTableRowData -{ - private String _lid; - private String _pe; - private short _dur; - private String _ts; - private String _extremum; - private float _probability; - private long _validTime; - private long _basisTime; - private double _value; - private double _supplValue; - private String _shefQualCode; - private String _qualityCode; - private String _revision; - private String _productId; - private long _productTime; - private long _postingTime; - private long _actionTime; - private String _aaCateg; - private String _aaCheck; - - public AlertAlarmJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getAaCateg() - { - return _aaCateg; - } - public void setAaCateg(String aaCateg) - { - _aaCateg = aaCateg; - } - public String getAaCheck() - { - return _aaCheck; - } - public void setAaCheck(String aaCheck) - { - _aaCheck = aaCheck; - } - public long getActionTime() - { - return _actionTime; - } - public void setActionTime(long actionTime) - { - _actionTime = actionTime; - } - public long getBasisTime() - { - return _basisTime; - } - public void setBasisTime(long basisTime) - { - _basisTime = basisTime; - } - public short getDur() - { - return _dur; - } - public void setDur(short dur) - { - this._dur = dur; - } - public String getExtremum() - { - return _extremum; - } - public void setExtremum(String extremum) - { - this._extremum = extremum; - } - public String getLid() - { - return _lid; - } - public void setLid(String lid) - { - this._lid = lid; - } - public String getPe() - { - return _pe; - } - public void setPe(String pe) - { - this._pe = pe; - } - public long getPostingTime() - { - return _postingTime; - } - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - public float getProbability() - { - return _probability; - } - public void setProbability(float probability) - { - this._probability = probability; - } - public String getProductId() - { - return _productId; - } - public void setProductId(String productId) - { - _productId = productId; - } - public long getProductTime() - { - return _productTime; - } - public void setProductTime(long productTime) - { - _productTime = productTime; - } - public String getQualityCode() - { - return _qualityCode; - } - public void setQualityCode(String qualityCode) - { - _qualityCode = qualityCode; - } - public String getRevision() - { - return _revision; - } - public void setRevision(String revision) - { - this._revision = revision; - } - public String getShefQualCode() - { - return _shefQualCode; - } - public void setShefQualCode(String shefQualCode) - { - _shefQualCode = shefQualCode; - } - public double getSupplValue() - { - return _supplValue; - } - public void setSupplValue(double supplValue) - { - _supplValue = supplValue; - } - public String getTs() - { - return _ts; - } - public void setTs(String ts) - { - this._ts = ts; - } - public long getValidTime() - { - return _validTime; - } - public void setValidTime(long validTime) - { - _validTime = validTime; - } - public double getValue() - { - return _value; - } - public void setValue(double value) - { - this._value = value; - } - - // ----------------------------------------------------------------------------------- - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation(), "MM/dd - HH:mm"); - addCell(cell); - - } - - public void addAllCellsToMap() - { - addToCellMap(AlertAlarmColumns.LID, CellType.STRING, getLid()); - addToCellMap(AlertAlarmColumns.PE, CellType.STRING, getPe()); - addToCellMap(AlertAlarmColumns.DUR, CellType.SHORT, getDur()); - addToCellMap(AlertAlarmColumns.TS, CellType.STRING, getTs()); - addToCellMap(AlertAlarmColumns.EXT, CellType.STRING, getExtremum()); - addToCellMap(AlertAlarmColumns.PROB, CellType.FLOAT,getProbability()); - addToCellMap(AlertAlarmColumns.VALID_TIME,CellType.DATE_TIME, getValidTime()); - addToCellMap(AlertAlarmColumns.BASIS_TIME,CellType.DATE_TIME,getBasisTime()); - addToCellMap(AlertAlarmColumns.VALUE,CellType.DOUBLE, getValue()); - addToCellMap(AlertAlarmColumns.SUP_VALUE, CellType.DOUBLE, getSupplValue()); - addToCellMap(AlertAlarmColumns.SHEF_QUAL_CODE, CellType.STRING, getShefQualCode()); - addToCellMap(AlertAlarmColumns.QUAL_CODE,CellType.STRING, getQualityCode()); - addToCellMap(AlertAlarmColumns.REVISION, CellType.STRING, getRevision()); - addToCellMap(AlertAlarmColumns.PRODUCT_ID, CellType.STRING, getProductId()); - addToCellMap(AlertAlarmColumns.PROD_TIME, CellType.DATE_TIME, getProductTime()); - addToCellMap(AlertAlarmColumns.POSTING_TIME, CellType.DATE_TIME, getPostingTime()); - addToCellMap(AlertAlarmColumns.ACTION_TIME, CellType.DATE_TIME, getActionTime()); - addToCellMap(AlertAlarmColumns.DESC, CellType.STRING, getAaCateg()); - addToCellMap(AlertAlarmColumns.THREAT, CellType.STRING,getAaCheck()); - - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/DataFilter.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/DataFilter.java deleted file mode 100644 index d3ee26865b..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/DataFilter.java +++ /dev/null @@ -1,17 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableRowData; - -public interface DataFilter -{ - /** - * Returns the filtered row data list - * @param allRowDataList - * @return - */ - List filter(List allRowDataList); - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/LocationDataFilter.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/LocationDataFilter.java deleted file mode 100644 index 6fe4e96124..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/LocationDataFilter.java +++ /dev/null @@ -1,61 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.util.gui.jtable.JTableRowData; - -public abstract class LocationDataFilter implements DataFilter -{ - protected Map _locationDisplayMap; - - public LocationDataFilter(Map locationDisplayMap) - { - _locationDisplayMap = locationDisplayMap; - } - - public LocationDataFilter() - { - _locationDisplayMap = new HashMap(); - } - - public Map getLocationDisplayMap() - { - return _locationDisplayMap; - } - - /** - * Set this location to be displayed / not - * @param locationId - * @param shouldDisplay - true / false - */ - public void setDisplayStatus(String locationId, Boolean shouldDisplay) - { - _locationDisplayMap.put(locationId, shouldDisplay); - } - - /** - * Reset all locations in the location display map - * - */ - public void blockAllLocations() - { - Set locationIdSet = _locationDisplayMap.keySet(); - - Iterator iterator = locationIdSet.iterator(); - while(iterator.hasNext()) - { - String locationId = iterator.next().toString(); - _locationDisplayMap.put(locationId, false); - } - } - - /** - * Filter the allRowDataList based on the locationDisplayMap - */ - public abstract List filter(List allRowDataList); - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/LocationInfoColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/LocationInfoColumns.java deleted file mode 100644 index 4d9d1d966d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/LocationInfoColumns.java +++ /dev/null @@ -1,55 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class LocationInfoColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String GROUP_NAME = "Group Name"; - public static final String LOCATION_ID = "Location Id"; - public static final String LOCATION_NAME = "Location Name"; - public static final String HSA = "HSA"; - public static final String GROUP_ORDINAL = "Group Ordinal"; - public static final String LOCATION_ORDINAL = "Location Ordinal"; - public static final String COUNTY = "County"; - public static final String STATE = "State"; - public static final String RIVER_BASIN = "River Basin"; - - - /** - * Creates a list of location info columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the location info columns are added to it, - * if not the location info columns are added to the list that is passed as argument. - * The created new list is returned. - * @param locationInfoColumnDescriptorList - * @return - */ - public List getLocationInfoColumnsList(List locationInfoColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if( locationInfoColumnDescriptorList == null) - { - locationInfoColumnDescriptorList = new ArrayList(); - } - - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ID, textAlignment, "Group Identification")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_NAME, textAlignment, "Group Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ID, textAlignment, "Location Identification")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_NAME, textAlignment, "Location Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(HSA, textAlignment, "Hydrologic Service Area")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ORDINAL, numberAlignment, "Group Ordinal")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ORDINAL, numberAlignment, "Location Ordinal")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(COUNTY, textAlignment, "County Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(STATE, textAlignment, "State Name")); - locationInfoColumnDescriptorList.add(new JTableColumnDescriptor(RIVER_BASIN, textAlignment, "River Basin")); - - - return locationInfoColumnDescriptorList; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/Monitor.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/Monitor.java deleted file mode 100644 index ecc59ee81e..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/Monitor.java +++ /dev/null @@ -1,50 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.db.Database; -import ohd.hseb.monitor.precip.manager.PrecipMonitorAppManager; -import ohd.hseb.monitor.river.manager.RiverMonitorAppManager; - -public class Monitor -{ - public static void main(String args[]) - { - String connectionString = args[0]; - Database db = createDatabaseConnection(connectionString); - - String missingRepresentation = args[1]; - String version = "OB9.0"; - String versionDate = "September 19, 2008"; - - String monitorName = args[2]; - - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager = new MonitorTimeSeriesLiteManager(connectionString); - - if(monitorName.equalsIgnoreCase("PRECIP")) - { - new PrecipMonitorAppManager(db, missingRepresentation, version, versionDate, monitorTimeSeriesLiteManager); - } - else // RIVER - { - new RiverMonitorAppManager(db, missingRepresentation, version, versionDate, monitorTimeSeriesLiteManager); - } - } - - public static String getVersion() - { - return "OB8.3"; - } - - private static Database createDatabaseConnection(String connectionString) - { - Database db; - db = new Database(); - - if (connectionString == null) - { - System.out.println( "Monitor Application.........Database should be provided........"); - System.exit(0); - } - db.connectWithDriverSearch(connectionString); - return db; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorCell.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorCell.java deleted file mode 100644 index 7ca08c7976..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorCell.java +++ /dev/null @@ -1,166 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.util.gui.jtable.TableCellInterface; -import java.awt.Color; - -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class MonitorCell extends BaseTableCell -{ - private ThreatLevel _monitorThreatLevel = ThreatLevel.NO_THREAT; - - private static int defaultDecimalPointsForDisplay = 2; - - // ------------------------------------------------------------------------------------------------------- - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation) - { - super(columnName, cellType, value, missingRepresentation, defaultDecimalPointsForDisplay); - this.setThreatLevel(threatLevel); - } - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, Color cellBackgroundColor, - String missingRepresentation, - int decimalPointsForDisplay) - { - super(columnName, cellType, value, cellBackgroundColor, missingRepresentation,decimalPointsForDisplay); - this.setThreatLevel(threatLevel); - } - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - int decimalPointsForDisplay) - { - super(columnName, cellType, value, missingRepresentation,decimalPointsForDisplay); - this.setThreatLevel(threatLevel); - } - - public MonitorCell (String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - String dateFormatString) - { - super(columnName, cellType, value, missingRepresentation, dateFormatString); - this.setThreatLevel(threatLevel); - } - - public ThreatLevel getThreatLevel() - { - return _monitorThreatLevel; - } - - public void setThreatLevel(ThreatLevel rivermonitorThreatLevel) - { - _monitorThreatLevel = rivermonitorThreatLevel; - } - - public Color getCellBackgroundColor() - { - String header = "MonitorCell.getCellBackgroundColor(): "; - Color color = super.getCellBackgroundColor(); - - - if (color == null) - { - System.out.println(header + "color = " + color); - System.out.println(header + "Color was null for column name = " + getColumnName() + ". Setting to Color.WHITE."); - color = Color.WHITE; //bug fix for occasional, mysterious nullness - } - - if( color == Color.WHITE) - { - ThreatLevel threatLevel = getThreatLevel(); - - switch(threatLevel) - { - case MISSING_DATA: - color = Color.gray; - break; - - case AGED_DATA: - color = Color.gray; - break; - - case CAUTION: - color = Color.yellow; - break; - - case ALERT: - color = Color.red; - break; - - default: - color = Color.white; - } - } - return color; - } - - public Color getCellForegroundColor() - { - String header = "MonitorCell.getCellForegroundColor(): "; - Color color = Color.black; - - Color backgroundColor = getCellBackgroundColor(); - // System.out.println(header + "backgroundColor = " + backgroundColor); - - - if (backgroundColor.equals(Color.red) || (backgroundColor.equals(Color.gray) ) ) - { - color = Color.yellow; - } - - return color; - } - - public int compare(TableCellInterface otherCell) - { - int result = 0; - - if (getCellType() != CellType.EXTENSION) - { - result = super.compare(otherCell); - } - else - { - result = compareThreat(otherCell); - } - return result; - } - - private int compareThreat(TableCellInterface otherCell) - { - MonitorCell otherThreatCell = (MonitorCell) otherCell; - int result = 0; - result = getThreatLevel().compareTo(otherThreatCell.getThreatLevel()); - if(result == 0) - { - result = compareCells((String) getValue(), (String)otherCell.getValue()); - result *= -1; - } - - return result; - } - - public String getDisplayString() - { - String displayString = null; - - if (getCellType() != CellType.EXTENSION) - { - displayString = super.getDisplayString(); - } - else - { - displayString = getStringValue((String) getValue()); - } - return displayString; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorFrame.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorFrame.java deleted file mode 100644 index bc7874e7ae..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorFrame.java +++ /dev/null @@ -1,27 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Container; -import java.awt.Cursor; -import javax.swing.JFrame; - -public class MonitorFrame extends JFrame -{ - public MonitorFrame() - { - super(); - } - - public void setWaitCursor() - { - Container container = this.getContentPane(); // get the window's content pane - container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } - - public void setDefaultCursor() - { - Container container = this.getContentPane(); // get the window's content pane - container.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorMessage.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorMessage.java deleted file mode 100644 index 0aae954095..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorMessage.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.monitor.messaging.Message; -import ohd.hseb.monitor.messaging.MessageType; - -public class MonitorMessage extends Message -{ - private Object _messageData; - - public MonitorMessage(Object source, MessageType messageType, Object messageData) - { - super(source, messageType); - _messageData = messageData; - } - - public MonitorMessage(Object source, MessageType messageType) - { - super(source, messageType); - _messageData = null; - } - - public Object getMessageData() - { - return _messageData; - } - - public void setMessageData(Object messageData) - { - _messageData = messageData; - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorSplitPane.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorSplitPane.java deleted file mode 100644 index 7b024dcefe..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorSplitPane.java +++ /dev/null @@ -1,88 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Component; -//import java.awt.Graphics; - -import javax.swing.JSplitPane; - -public class MonitorSplitPane extends JSplitPane -{ - - public MonitorSplitPane (int newOrientation, - boolean newContinuousLayout) - { - super(newOrientation, newContinuousLayout); - } - - public void setDividerLocation(int location) - { - int currentDividerLocation = getDividerLocation(); - int adjustedLocation = location; - - - if (location < 30 ) - { - int difference = currentDividerLocation - location; - if (difference > 50) - { - adjustedLocation = currentDividerLocation; - } - } - super.setDividerLocation(adjustedLocation); - } - - public void setRightComponent(Component comp) - { - String header = "MonitorJSplitPane.setRightComponent() "; - - int beforeDividerLocation = getDividerLocation(); - - - - super.setRightComponent(comp); - - //int afterDividerLocation = getDividerLocation(); - - setDividerLocation(beforeDividerLocation); - - // System.out.println(header + " before divider location = " + beforeDividerLocation); - // System.out.println(header + " after divider location = " + afterDividerLocation); - - //setVisible(false); - //setVisible(true); - - } - - public void setLeftComponent(Component comp) - { - String header = "MonitorJSplitPane.setLeftComponent() "; - - int beforeDividerLocation = getDividerLocation(); - - super.setLeftComponent(comp); - - //int afterDividerLocation = getDividerLocation(); - - setDividerLocation(beforeDividerLocation); - - // System.out.println(header + " before divider location = " + beforeDividerLocation); - // System.out.println(header + " after divider location = " + afterDividerLocation); - - } - - /* - public void paint(Graphics g) - { - String header = "MonitorJSplitPane.paint() "; - super.paint(g); - - int dividerLocation = getDividerLocation(); - int lastDividerLocation = getLastDividerLocation(); - - System.out.println(header + " divider location = " + dividerLocation); - System.out.println(header + " last divider location = " + lastDividerLocation); - - } - */ -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorTimeSeriesLiteManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorTimeSeriesLiteManager.java deleted file mode 100644 index 2918dd34dd..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorTimeSeriesLiteManager.java +++ /dev/null @@ -1,132 +0,0 @@ -package ohd.hseb.monitor; - -import javax.swing.JOptionPane; - -import ohd.hseb.model.ParamCode; -import ohd.hseb.monitor.precip.PrecipMonitorJTableRowData; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.timeserieslite.TimeSeriesLite; - -public class MonitorTimeSeriesLiteManager -{ - private String _connectionString; - - public MonitorTimeSeriesLiteManager(String connectionString) - { - _connectionString = connectionString; - } - - public boolean displayTimeSeriesLite(MonitorFrame mainFrame, RiverMonitorJTableRowData rowData) - { - String obsTypeSource = rowData.getObsTypeSource(); - String fcstTypeSource = rowData.getFcstTypeSource(); - String primaryPe = rowData.getPrimaryRiverPe(); - String locationId = rowData.getLid(); - - String obsParamCode = null; - String fcstParamCode = null; - boolean result = false; - - if(obsTypeSource == null && fcstTypeSource == null) - { - result = false; - } - else - { - if(obsTypeSource != null) - obsParamCode = primaryPe+"I"+obsTypeSource+"Z"; - if(fcstTypeSource != null) - fcstParamCode = primaryPe +"I"+fcstTypeSource+"Z"; - - System.out.println("Obs:"+obsParamCode); - System.out.println("Fcst:"+fcstParamCode); - - String tslArgs[]= {"ohd.hseb.timeserieslite.rivermon.RiverMonDrawingMgr", - _connectionString, locationId, obsParamCode, fcstParamCode}; - - TimeSeriesLite tsl = new TimeSeriesLite(); - tsl.display(tslArgs, false); - result = true; - } - - if(!result) - { - String textMsg = "Latestobs and/or MaxFcst is unavailable.
    " + - "Unable to display TimeSeriesLite."; - JOptionPane.showMessageDialog(mainFrame, textMsg,"TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - return result; - } - - public boolean displayTimeSeriesLite(MonitorFrame mainFrame, PrecipMonitorJTableRowData rowData, int hour) - { - ParamCode paramCode = null; - switch(hour) - { - case 1: - paramCode = rowData.getPrecipData().getTohPrecip1HrParamCode(); - break; - case 3: - paramCode = rowData.getPrecipData().getTohPrecip3HrParamCode(); - break; - case 6: - paramCode = rowData.getPrecipData().getTohPrecip6HrParamCode(); - break; - case 24: - paramCode = rowData.getPrecipData().getTohPrecip24HrParamCode(); - break; - } - - String obsTypeSource = null; - - String pe = null; - String dur = null; - String extremum = null; - - if(paramCode != null) - { - obsTypeSource = paramCode.getTypeSource(); - pe = "PP"; - dur = "H"; - extremum = paramCode.getExtremum(); - } - - String locationId = rowData.getLid(); - - String obsParamCode = null; - String fcstParamCode = null; - boolean result = false; - - if(paramCode == null) - { - result = false; - } - else - { - if(obsTypeSource != null) - { - obsParamCode = pe+dur+obsTypeSource+extremum; - fcstParamCode = pe + dur + "FF"+ extremum; - } - - System.out.println("Obs:"+obsParamCode); - System.out.println("Fcst:"+fcstParamCode); - - String tslArgs[]= {"ohd.hseb.timeserieslite.pdc.PDCDrawingMgr", - _connectionString, locationId, obsParamCode, fcstParamCode}; - - TimeSeriesLite tsl = new TimeSeriesLite(); - tsl.display(tslArgs, false); - result = true; - } - - if(!result) - { - String textMsg = "Top-of-hour 1 hr Precip data is unavailable.
    " + - "Unable to display TimeSeriesLite."; - JOptionPane.showMessageDialog(mainFrame, textMsg,"TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - return result; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorToolBarManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorToolBarManager.java deleted file mode 100644 index 7622c2f21c..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/MonitorToolBarManager.java +++ /dev/null @@ -1,89 +0,0 @@ -package ohd.hseb.monitor; - -import java.awt.Image; -import java.awt.Toolkit; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JToolBar; - -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.util.AppsDefaults; - -public class MonitorToolBarManager -{ - private AppsDefaults _appsDefaults; - protected JButton _officeNotesButton; - private Icon _recordedOfficeNotesIcon, _emptyOfficeNotesIcon; - private JToolBar _toolBar; - private OfficeNotesDataManager _officeNotesDataMgr; - - public MonitorToolBarManager(JToolBar toolBar, AppsDefaults appsDefaults, - OfficeNotesDataManager officeNotesDataMgr) - { - _appsDefaults = appsDefaults; - _toolBar = toolBar; - _officeNotesDataMgr = officeNotesDataMgr; - - addToolBarComponents(); - } - - private void addToolBarComponents() - { - createOfficeNotesAccessButton(); - - _toolBar.setFloatable(false); - _toolBar.setRollover(true); - } - - public JButton getOfficeNotesButton() - { - return _officeNotesButton; - } - - private void createOfficeNotesAccessButton() - { - String iconsDir = _appsDefaults.getToken("rivermon_config_dir", HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - _officeNotesButton = new JButton() ; - _recordedOfficeNotesIcon = createIcon(iconsDir + "/OfficeNotes.GIF"); - _emptyOfficeNotesIcon = createIcon(iconsDir + "/EmptyOfficeNotes.GIF"); - - _officeNotesButton.setBorderPainted(false); - _officeNotesButton.setRolloverEnabled(true); - - _toolBar.add(_officeNotesButton); - - setOfficeNotesButtonIcon(_officeNotesDataMgr.getCountOfOfficeNotes()); - } - - public Icon createIcon(String fileName) - { - Icon icon = null; - int width = 25; - int height = 25; - Image image = Toolkit.getDefaultToolkit().getImage(fileName); - Image newImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); - icon = new ImageIcon(newImage); - return icon; - } - - public void setOfficeNotesButtonIcon(int numOfOfficeNotesRecs) - { - _officeNotesButton.setVisible(false); - if(numOfOfficeNotesRecs > 0) - { - _officeNotesButton.setToolTipText("You have " + numOfOfficeNotesRecs + " OfficeNotes"); - _officeNotesButton.setIcon(_recordedOfficeNotesIcon); - } - else - { - _officeNotesButton.setToolTipText("OfficeNotes is Empty"); - _officeNotesButton.setIcon(_emptyOfficeNotesIcon); - } - _officeNotesButton.setVisible(true); - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/ThreatLevel.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/ThreatLevel.java deleted file mode 100644 index deff13192e..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/ThreatLevel.java +++ /dev/null @@ -1,35 +0,0 @@ -package ohd.hseb.monitor; - -public enum ThreatLevel -{ - NO_THREAT, - MISSING_DATA, - AGED_DATA, - CAUTION, - ALERT; - - static boolean isDataMissingOrAged(ThreatLevel level) - { - boolean result = false; - - if ((level == ThreatLevel.AGED_DATA) || (level == ThreatLevel.MISSING_DATA) ) - { - result = true; - } - - return result; - } - // ------------------------------------------------------------------------------------- - public boolean isGreater( ThreatLevel otherLevel) - { - boolean result = false; - if (compareTo(otherLevel) > 0) - { - result = true; - } - - return result; - } -} - - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/TreeDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/TreeDataManager.java deleted file mode 100644 index 2ab9e2bb4a..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/TreeDataManager.java +++ /dev/null @@ -1,280 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -public class TreeDataManager -{ - - private Map _nodeMap = new HashMap(); - - public TreeDataManager() - { - - } - - private void addNode(DefaultMutableTreeNode baseNode, TreePath nodePath) - { - String header = "TreeDataManager.addNode(): "; - DefaultMutableTreeNode node = null; - DefaultMutableTreeNode parentNode = null; - - if(isRootPath(baseNode, nodePath)) - { -// is root node, so done - _nodeMap.put(nodePath.toString(), baseNode); - } - else //is not root node - { - //find the parent first - TreePath parentPath = nodePath.getParentPath(); - parentNode = findNode(baseNode, parentPath); - - if (parentNode != null) //found the node, so don't add it - { - //check to make sure this node does not already exist - node = findNode(parentNode, nodePath); //just search under parentNode for the child - - if (node == null) - { - DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodePath.getLastPathComponent()); - parentNode.add(childNode); - - TreePath childNodePath = getTreePathForNode(childNode); - - //System.out.println(header + "Inserting " + childNodePath.toString() + ", " + childNode + " into nodeMap"); - _nodeMap.put(childNodePath.toString(), childNode); - } - } - else //parentNode is null - { - //add the parent node - - // System.out.println(header + "Adding parent node " + parentPath.toString() + ", " + baseNode); - - addNode(baseNode, parentPath); - - //add the child node - - // System.out.println(header + "Adding childt node " + nodePath.toString() + ", " + baseNode); - - addNode(baseNode, nodePath); - } - } - } - - private boolean isRootPath(DefaultMutableTreeNode node, TreePath path) - { - boolean result = false; - - if(path != null) // is valid path - { - int pathCount = path.getPathCount(); - - if(pathCount == 1) - { - if (node.toString().equals(path.getPathComponent(0).toString())) - { - result = true; - } - } - } - - return result; - } - - private DefaultMutableTreeNode oldFindNode(DefaultMutableTreeNode node, TreePath targetPath) - { - DefaultMutableTreeNode resultNode = null; - DefaultMutableTreeNode testNode = null; - - if(node != null) - { - if(isNodeAMatchForPath(node, targetPath)) - { - resultNode = node; - } - else - { - if(isNodeInPath(node, targetPath)) - { - int childCount = node.getChildCount(); - for(int i=0; i < childCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); - - testNode = findNode(childNode, targetPath); - if (testNode != null) - { - resultNode = testNode; - break; - } - } - } - } - } - return (DefaultMutableTreeNode ) resultNode; - } - - private DefaultMutableTreeNode findNode2(DefaultMutableTreeNode node, TreePath targetPath) - { - String header = "TreeDataManager.findNode(): "; - DefaultMutableTreeNode resultNode = null; - DefaultMutableTreeNode testNode = null; - - if(node == null) - { - return null; - } - - if(isNodeInPath(node, targetPath)) - { - - if(isNodeAMatchForPath(node, targetPath)) - { - resultNode = node; - } - else //not a match - { - - int childCount = node.getChildCount(); - for(int i=0; i < childCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); - - if(isNodeInPath(childNode, targetPath)) - { - if(isNodeAMatchForPath(childNode, targetPath)) - { - // System.out.println(header + " childNode = " + - // childNode.toString() + " matches " + targetPath); - - - resultNode = childNode; - break; - } - else //not complete match, so keep looking from here on down - { - // System.out.println(header + " childNode = " + - // childNode.toString() + " is in " + targetPath); - - resultNode = findNode2(childNode, targetPath); - } - break; - } - - else //not a match and not in path - { - // System.out.println(header + " childNode = " + - // childNode.toString() + " is not in " + targetPath); - //do nothing - } - - } //end for - } //end else - - } - - return (DefaultMutableTreeNode ) resultNode; - } - - - private DefaultMutableTreeNode findNode(DefaultMutableTreeNode node, TreePath targetPath) - { - // String header = "TreeDataManager.findNode(): "; - DefaultMutableTreeNode resultNode = _nodeMap.get(targetPath.toString()); - - return resultNode; - } - - - private boolean isNodeInPath(DefaultMutableTreeNode node, TreePath targetPath) - { - boolean isInPath = false; - - TreePath nodePath = getTreePathForNode(node); - isInPath = isPathBeginningOfTargetPath(nodePath, targetPath); - - return isInPath; - } - - private boolean isPathBeginningOfTargetPath(TreePath nodePath, TreePath targetPath) - { - boolean isBeginning = false; - - String nodePathString = nodePath.toString(); - String targetPathString = targetPath.toString(); - - int length = nodePathString.length(); - nodePathString = nodePathString.substring(0, length - 1); - - isBeginning = targetPathString.startsWith(nodePathString); - - return isBeginning; - } - - private boolean isNodeAMatchForPath(DefaultMutableTreeNode node, TreePath targetPath) - { - TreePath nodePath = getTreePathForNode(node); - boolean isTargetNode = false; - - if (targetPath.toString().equals(nodePath.toString())) - { - isTargetNode = true; - } - - return isTargetNode; - } - - private TreePath getTreePathForNode(DefaultMutableTreeNode node) - { - TreePath nodePath = new TreePath(node.getPath()); - return nodePath; - } - - private List createTreePathList(List stringArrayList) - { - List treePathList = new ArrayList(); - - for(int i=0; i < stringArrayList.size(); i++) - { - String[] stringArray = (String[]) stringArrayList.get(i); - DefaultMutableTreeNode[] nodeArray = new DefaultMutableTreeNode[stringArray.length]; - for(int j=0; j < stringArray.length; j++) - { - nodeArray[j] = new DefaultMutableTreeNode(stringArray[j]); - } - TreePath path = new TreePath(nodeArray); - treePathList.add(path); - } - - return treePathList; - } - - public JTree createFilterTreeFromList(DefaultMutableTreeNode rootNode, List stringArrayList) - { - String header = "TreeDataManager.createFilterTreeFromList(): "; - - _nodeMap.clear(); - - List treePathList = createTreePathList(stringArrayList); - - for(int i=0; i < treePathList.size(); i++) - { - TreePath path = treePathList.get(i); - - addNode(rootNode, path); - } - - JTree tree = new JTree(rootNode); - - return tree; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/TreeFilterManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/TreeFilterManager.java deleted file mode 100644 index 4d6639af29..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/TreeFilterManager.java +++ /dev/null @@ -1,80 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.List; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.util.SessionLogger; - -public class TreeFilterManager -{ - private SessionLogger _logger; - private LocationDataFilter _locationDataFilter; - - public TreeFilterManager(SessionLogger logger, LocationDataFilter locationDataFilter) - { - _logger = logger; - _locationDataFilter = locationDataFilter; - } - - public LocationDataFilter getLocationDataFilter() - { - return _locationDataFilter; - } - - public List filter(List allRowDataList) - { - return (_locationDataFilter.filter(allRowDataList)); - } - - public void setDisplayStatus(String location, boolean shouldDisplay) - { - _locationDataFilter.setDisplayStatus(location, shouldDisplay); - } - - public void traversePathsToDisplayLocationSelected(TreePath paths[]) - { - String header = "TreeFilterManager.parsePathsToDisplayLocationSelected()"; - - _locationDataFilter.blockAllLocations(); - - if(paths != null) - { - for(int i=0; i < paths.length; i++) - { - if(paths[i] == null) - { - _logger.log(header + "Invalid path... Check ... "); - } - else - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent(); - setAllLocationsUnderThisNodeToBeDisplayed(node); - } - } - } - } - - public void setAllLocationsUnderThisNodeToBeDisplayed(DefaultMutableTreeNode node) - { - if(node != null) - { - if(node.isLeaf()) - { - setDisplayStatus(node.toString(), true); - } - else - { - int childCount = node.getChildCount(); - for(int i=0; i < childCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); - setAllLocationsUnderThisNodeToBeDisplayed(childNode); - } - } - } - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumn.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumn.java deleted file mode 100644 index ebc031af01..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumn.java +++ /dev/null @@ -1,103 +0,0 @@ -package ohd.hseb.monitor.derivedcolumns; - -import java.awt.Color; -import java.util.HashMap; -import java.util.Map; - -public class DerivedColumn -{ - private String _columnName; - private Color _color; - private String _equationForCellColor; - private String _returnType; - private String _equationForCellValue; - private Object _value; - private static Map _colorMap = new HashMap(); - - static - { - _colorMap.put("black", Color.BLACK); - _colorMap.put("blue", Color.BLUE); - _colorMap.put("cyan", Color.CYAN); - _colorMap.put("darkgray", Color.DARK_GRAY); - _colorMap.put("gray", Color.GRAY); - _colorMap.put("green", Color.GREEN); - _colorMap.put("lightgray", Color.LIGHT_GRAY); - _colorMap.put("magenta", Color.MAGENTA); - _colorMap.put("orange", Color.ORANGE); - _colorMap.put("pink", Color.PINK); - _colorMap.put("red", Color.RED); - _colorMap.put("white", Color.WHITE); - _colorMap.put("yellow", Color.YELLOW); - } - - public String getColumnName() - { - return _columnName; - } - - public void setColumnName(String columnName) - { - _columnName = columnName; - } - - public String getEquationForCellValue() - { - return _equationForCellValue; - } - - public void setEquationForCellValue(String valueEquation) - { - this._equationForCellValue = valueEquation; - } - - public String getEquationForCellColor() - { - return _equationForCellColor; - } - - public void setEquationForCellColor(String cellEquation) - { - this._equationForCellColor = cellEquation; - } - - public String getReturnType() - { - return _returnType; - } - - public void setReturnType(String returnType) - { - _returnType = returnType; - } - - public Object getValue() - { - return _value; - } - - public void setvalue(Object value) - { - _value = value; - } - - public void setCellBackgroundColor(Color color) - { - _color = color; - } - - public Color getCellBackgroundColor() - { - return _color; - } - - public void setCellBackgroundColor(String colorName) - { - Color color = (Color) _colorMap.get(colorName.toLowerCase()); - - if (color != null) - { - setCellBackgroundColor(color); - } - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumnsFileManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumnsFileManager.java deleted file mode 100644 index 73df5c8a26..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/derivedcolumns/DerivedColumnsFileManager.java +++ /dev/null @@ -1,137 +0,0 @@ -package ohd.hseb.monitor.derivedcolumns; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.util.SessionLogger; - -public class DerivedColumnsFileManager -{ - private String _derivedColumnsFile = null; - private List _derivedColumnsList = null; - private Map _derivedColumnMap = null; - private SessionLogger _logger = null; - - public DerivedColumnsFileManager(String derivedColumnsFile, SessionLogger logger) - { - _derivedColumnsFile = derivedColumnsFile; - _logger = logger; - } - - - private void printFileException(IOException exception) - { - _logger.log("RiverMonitorDerivedColumnsFileManager.printFileException(): ERROR = " + exception.getMessage()); - exception.printStackTrace(); - _logger.log("RiverMonitorDerivedColumnsFileManager.printFileException(): End of stack trace"); - } - - public List getDerivedColumns() - { - if(_derivedColumnsList == null) - _derivedColumnsList = new ArrayList(); - else - _derivedColumnsList.clear(); - - if(_derivedColumnMap == null) - _derivedColumnMap = new HashMap(); - else - _derivedColumnMap.clear(); - - Runtime.getRuntime().gc(); - File fileHandler = new File(_derivedColumnsFile); - - if(fileHandler.exists()) - { - BufferedReader in = null; - String line; - - try - { - in = new BufferedReader(new FileReader(fileHandler)); - while(( line = in.readLine()) != null) - { - String columnName; - String returnType; - String equationForValue; - String equationForColor; - - if(line.length() != 0) - { - line = line.trim(); - if(line.length() != 0 && line.charAt(0) != '#') - { - String splitStr[] = line.split("\\|"); - columnName = splitStr[0]; - returnType = splitStr[1].trim(); - equationForValue = splitStr[2]; - equationForColor = splitStr[3]; - DerivedColumn derivedColumns = new DerivedColumn(); - derivedColumns.setColumnName(columnName); - derivedColumns.setReturnType(returnType); - derivedColumns.setEquationForCellValue(equationForValue); - derivedColumns.setEquationForCellColor(equationForColor); - _derivedColumnsList.add(derivedColumns); - _derivedColumnMap.put(columnName, derivedColumns); - } - } - } - } - catch(IOException exception) - { - printFileException(exception); - } - } - else - { - _logger.log("Derived columns file doesnt exist :[" + fileHandler.getAbsolutePath() + "]"); - } - return _derivedColumnsList; - } - - protected Map getDerivedColumnMap() - { - return _derivedColumnMap; - } - - public String[] getDerivedColumnNames() - { - String derivedColumnNames[] = null; - getDerivedColumns(); - if(_derivedColumnsList.size() != 0) - { - derivedColumnNames = new String[_derivedColumnsList.size()]; - for(int i=0; i < _derivedColumnsList.size(); i++) - { - DerivedColumn derivedColumns = (DerivedColumn) _derivedColumnsList.get(i); - derivedColumnNames[i] = derivedColumns.getColumnName(); - } - } - return derivedColumnNames; - } - - public String[] getAlignmentForDerivedColumns() - { - String alignmentForDerivedColumns[] = null; - if(_derivedColumnsList.size() != 0) - { - alignmentForDerivedColumns = new String[_derivedColumnsList.size()]; - for(int i=0; i < _derivedColumnsList.size(); i++) - { - DerivedColumn derivedColumns = (DerivedColumn) _derivedColumnsList.get(i); - if(derivedColumns.getReturnType().equalsIgnoreCase("string")) - alignmentForDerivedColumns[i] = "center"; - else - alignmentForDerivedColumns[i] = "right"; - } - } - return alignmentForDerivedColumns; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/BaseManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/BaseManager.java deleted file mode 100644 index 8e7104549d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/BaseManager.java +++ /dev/null @@ -1,45 +0,0 @@ -package ohd.hseb.monitor.manager; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class BaseManager implements Manager -{ - public MessageSystemManager _msgSystemManager; - - public void setMessageSystemManager(MessageSystemManager msgSystemManager) - { - _msgSystemManager = msgSystemManager; - } - - public void send(MonitorMessage message) - { - _msgSystemManager.send(message); - } - - public void send(Manager manager, MessageType messageType) - { - MonitorMessage message = new MonitorMessage(manager, messageType); - System.out.println("Sending..." + message.getMessageType()); - send(message); - } - - public void send(Manager manager, MessageType messageType, JTableRowData selectedRowData) - { - MonitorMessage message = new MonitorMessage(manager, messageType, selectedRowData); - System.out.println("Sending..." + message.getMessageType()); - send(message); - } - - public String toString() - { - String className = this.getClass().toString(); - int lastIndexOfDot = className.lastIndexOf('.'); - String result = className.substring(lastIndexOfDot + 1, className.length()); - - return result; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/Manager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/Manager.java deleted file mode 100644 index 393cf27e5f..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/Manager.java +++ /dev/null @@ -1,13 +0,0 @@ -package ohd.hseb.monitor.manager; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.messaging.MessageSystemManager; - -public interface Manager -{ - public String toString(); - - public void send(MonitorMessage message); - - public void setMessageSystemManager(MessageSystemManager msgSystemManager); -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/MonitorMenuManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/MonitorMenuManager.java deleted file mode 100644 index 40e1496f86..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/MonitorMenuManager.java +++ /dev/null @@ -1,428 +0,0 @@ -package ohd.hseb.monitor.manager; - -import static ohd.hseb.util.TimeHelper.MILLIS_PER_MINUTE; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; - -import javax.swing.JButton; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.Timer; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipThresholdDialog; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; - -public abstract class MonitorMenuManager extends BaseManager -{ - private String _version; - private String _appName; - private String _date; - - protected MonitorFrame _mainFrame; - private JButton _refreshNowButton; - private JLabel _currentTimeLabel; - private JLabel _nextRefreshTimeLabel; - protected JSpinner _refreshTimeSpinner; - protected JPanel _timeDisplayPanel; - protected JLabel _dataTimeLabel; - protected JLabel _rowCountLabel; - - private Timer _refreshDisplayTimer = null; - - protected AppsDefaults _appsDefaults; - protected SessionLogger _logger; - - public MonitorMenuManager(MessageSystemManager msgSystemManager, AppsDefaults appsDefaults, - SessionLogger logger) - { - setMessageSystemManager(msgSystemManager); - _appsDefaults = appsDefaults; - _logger = logger; - } - - protected void setAboutInfo(String version, String date, String appName) - { - _version = version; - _date = date; - _appName = appName; - } - - public class AboutListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String aboutText = " Application : "+ _appName + "\n" + - " Version : " + _version + "\n" + - " Date : " + _date + "\n" + - " Developed by: \n"+ - " National Weather Service\n" + - " Office of Hydrologic Development\n" + - " Hydrology Laboratory"; - DialogHelper.displayMessageDialog(_mainFrame, aboutText, _appName); - } - } - - protected boolean confirmSaveOfficeSettings(String message) - { - boolean result = false; - int answer = JOptionPane.showConfirmDialog(_mainFrame, message,"Save Office Settings",JOptionPane.YES_NO_CANCEL_OPTION); - switch(answer) - { - case JOptionPane.YES_OPTION: - result = true; - break; - case JOptionPane.NO_OPTION: - case JOptionPane.CANCEL_OPTION: - case JOptionPane.CLOSED_OPTION: - result = false; - break; - } - return result ; - } - - protected void startMonitor(String appName, String monitorName) - { - Runtime rt = Runtime.getRuntime(); - - String binDir = _appsDefaults.getToken("whfs_bin_dir", - HydroappsDefaultDirs.WHFS_BIN_DIR); - String cmd[] = new String[2]; - cmd[0]= binDir + "/start_rivermonitor"; - - if(monitorName.equalsIgnoreCase("PRECIP")) - { - cmd[1] = "Precip"; - } - else //RIVER - { - cmd[1] = "River"; - } - - try - { - _mainFrame.setWaitCursor(); - rt.exec(cmd); - _logger.log("Launch " + monitorName + " Monitor [cmd:"+ cmd[0]+" "+cmd[1] +"]"); - _mainFrame.setDefaultCursor(); - } - catch(IOException ex) - { - _mainFrame.setDefaultCursor(); - String str = "Unable to launch " + monitorName + " Monitor:[cmd"+ cmd[0]+" "+cmd[1] + "] Exception:"+ ex; - JOptionPane.showMessageDialog(_mainFrame, str,appName, JOptionPane.PLAIN_MESSAGE); - } - } - - protected void launchTextEditor(String editorTitle, String file, String appName) - { - String editorDir = _appsDefaults.getToken("whfs_local_bin_dir", - HydroappsDefaultDirs.WHFS_LOCAL_BIN_DIR); - String editor = _appsDefaults.getToken("whfs_editor", "whfs_editor"); - - if(editorDir == null) - editorDir ="."; - if(editor == null) - editor = "whfs_editor"; - String script = editorDir.concat("/").concat(editor); - - Runtime rt = Runtime.getRuntime(); - String cmd[] = new String[3]; - cmd[0] = script; - cmd[1] = editorTitle; - cmd[2] = file; - try - { - _mainFrame.setWaitCursor(); - rt.exec(cmd); - _logger.log("Launch Text Editor [cmd:"+ cmd[0]+" "+cmd[1]+" "+cmd[2]+"]"); - _mainFrame.setDefaultCursor(); - } - catch(IOException ex) - { - _mainFrame.setDefaultCursor(); - String str = "Unable to launch text editor:[cmd"+ cmd[0]+" "+cmd[1]+" "+cmd[2]+ "] Exception:"+ ex; - JOptionPane.showMessageDialog(_mainFrame, str,appName, JOptionPane.PLAIN_MESSAGE); - } - - } - - protected void createRefreshComponents(int refreshInterval, JPanel timeDisplayPanel) - { - _timeDisplayPanel = timeDisplayPanel; - - JLabel refreshLabel = new JLabel("Update(in mins)"); - int maxValueForRefreshMins = 30; - int minValueForRefreshMins = 1; - int incrValueForRefreshMins = 1; - int initialValueForRefreshMins = refreshInterval; - - SpinnerModel spinnerModel = new SpinnerNumberModel(initialValueForRefreshMins, - minValueForRefreshMins, - maxValueForRefreshMins, - incrValueForRefreshMins); - _refreshTimeSpinner = new JSpinner(spinnerModel); - _refreshTimeSpinner.setPreferredSize(new Dimension(35,20)); - // Disable keyboard edits in the spinner - JFormattedTextField textField = - ((JSpinner.DefaultEditor)_refreshTimeSpinner.getEditor()).getTextField(); - textField.setEditable(false); - _refreshTimeSpinner.addChangeListener(new RefreshTimeSpinBoxListener()); - - _timeDisplayPanel.setLayout(new GridBagLayout()); - _currentTimeLabel = new JLabel(); - _currentTimeLabel.setBackground(Color.RED); - - _nextRefreshTimeLabel = new JLabel(); - _nextRefreshTimeLabel.setBackground(Color.GREEN); - JPanel nextRefreshTimePanel = new JPanel(); - nextRefreshTimePanel.add(_nextRefreshTimeLabel); - - JPanel refreshPanel = new JPanel(); - _refreshNowButton = new JButton("Update Now"); - _refreshNowButton.setPreferredSize(new Dimension(110,20)); - RefreshButtonListener refreshDisplayTimerListener = new RefreshButtonListener(); - _refreshNowButton.addActionListener(refreshDisplayTimerListener); - refreshPanel.add(refreshLabel); - refreshPanel.add(_refreshTimeSpinner); - refreshPanel.add(_refreshNowButton); - - _dataTimeLabel = new JLabel(); - _dataTimeLabel.setText("DEFAULT TEXT"); - - _rowCountLabel = new JLabel(); - - JPanel dummyPanel1 = new JPanel(); - JPanel dummyPanel1_25 = new JPanel(); - JPanel dummyPanel15 = new JPanel(); - JPanel dummyPanel2 = new JPanel(); - JPanel dummyPanel3 = new JPanel(); - dummyPanel1.setPreferredSize(new Dimension(50,20)); - dummyPanel1_25.setPreferredSize(new Dimension(50,20)); - dummyPanel15.setPreferredSize(new Dimension(50,20)); - dummyPanel2.setPreferredSize(new Dimension(60,20)); - dummyPanel3.setPreferredSize(new Dimension(50,20)); - - //col, row, width, height, weightx, weighty, fill - ComponentHelper.addFrameComponent(_timeDisplayPanel, - dummyPanel1, 0, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - _rowCountLabel, 1, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - dummyPanel1_25, 2, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - _dataTimeLabel, 3, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - dummyPanel15, 4, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - _currentTimeLabel, 5, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - dummyPanel2, 6, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - _nextRefreshTimeLabel,7, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - dummyPanel3, 8, 0, 1, 1, 0, 0, 1); - ComponentHelper.addFrameComponent(_timeDisplayPanel, - refreshPanel, 9, 0, 1, 1, 0, 0, 1); - - - } - - public void setInitialRefreshTimeInfo() - { - setRefreshTimeSpinnerValue(); - - - String curDateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis()); - _currentTimeLabel.setText(" Last Update: "+ curDateTimeString); - - Integer value = Integer.parseInt(_refreshTimeSpinner.getValue().toString()); - int refreshMilliSecs = (int) (value * MILLIS_PER_MINUTE); - System.out.println("Interval :"+ value); - - String nextDateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis() + refreshMilliSecs); - String timeString[] = nextDateTimeString.split(" "); - _nextRefreshTimeLabel.setText(" Next Update: "+timeString[1]); - - //time of the PDC file read - _dataTimeLabel.setText("Precip Data Time: N/A"); - - updateRecordCount(); - - } - - protected void updateRecordCount() - { - long recordCount = getDisplayedRecordCount(); - _rowCountLabel.setText(recordCount + " Locations"); - } - - private void changeTimeInformationDisplayed(long refreshMilliSecs, boolean changeLastUpdateTime) - { - long currentTime = System.currentTimeMillis(); - - if(changeLastUpdateTime) - { - String curDateTimeString = DbTimeHelper.getTimeToSecondsStringFromLongTime(currentTime); - _currentTimeLabel.setText(" Last Update: "+ curDateTimeString); - } - String nextDateTimeString = DbTimeHelper.getTimeToSecondsStringFromLongTime(currentTime + refreshMilliSecs); - // String timeString[] = nextDateTimeString.split(" "); - _nextRefreshTimeLabel.setText(" Next Update: " + nextDateTimeString); - - //time of the PDC file read - - long dataUpdateTime = getDataUpdateTime(); - _dataTimeLabel.setText("Precip Data Time: " + DbTimeHelper.getTimeToSecondsStringFromLongTime(dataUpdateTime)); - - - //updateRecordCount(); - - } - - protected abstract long getDataUpdateTime(); - protected abstract long getDisplayedRecordCount(); - - public abstract void setMenuSettingsRefreshInterval(int value); - - // Refresh time spin box listener - private class RefreshTimeSpinBoxListener implements ChangeListener - { - public void stateChanged(ChangeEvent e) - { - Integer value = Integer.parseInt(_refreshTimeSpinner.getValue().toString()); - setMenuSettingsRefreshInterval(value); - int refreshMilliSecs = (int) (value * MILLIS_PER_MINUTE); - changeTimeInformationDisplayed(refreshMilliSecs, false); - startTimer(refreshMilliSecs); - } - } - - // Is attached to the update now button - private class RefreshButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - refresh(); - } - } - - protected void startTimer(int delayMilliSecs) - { - if(_refreshDisplayTimer == null) - { - RefreshButtonListener refreshDisplayTimerListener = new RefreshButtonListener(); - _refreshDisplayTimer = new Timer(delayMilliSecs, refreshDisplayTimerListener); - } - else - { - _refreshDisplayTimer.stop(); - //This timer doesn't repeat, hence it always uses setInitialDelay and not setDelay - //which is used only if the timer is set to repeat - _refreshDisplayTimer.setInitialDelay(delayMilliSecs); - } - _refreshDisplayTimer.start(); - } - - public abstract void setRefreshTimeSpinnerValue(); - - protected void refreshTimeDisplay() - { - Object obj = _refreshTimeSpinner.getValue(); - int refreshMilliSecs =(int) (Integer.parseInt(obj.toString()) * MILLIS_PER_MINUTE); - startTimer(refreshMilliSecs); - - setRefreshTimeSpinnerValue(); - - changeTimeInformationDisplayed(refreshMilliSecs, true); - startTimer(refreshMilliSecs); - } - - protected void refresh() - { - String header = "MonitorMenuManager.refresh(): "; - - _mainFrame.setWaitCursor(); - - System.out.print(header); - send(this, MessageType.RELOAD_DATA); - refreshTimeDisplay(); - - _mainFrame.setDefaultCursor(); - } - - protected void sendMissingFilterChanged() - { - String header = "MonitorMenuManager.sendMissingFilterChanged(): "; - - System.out.print(header); - send(this, MessageType.REFRESH_DISPLAY); - - } - - protected void menuChange() - { - String header = "MonitorMenuManager.menuChange(): "; - - System.out.print(header); - send(this, MessageType.RELOAD_DATA); - refreshTimeDisplay(); - } - - protected class PrecipThresholdListener implements ActionListener - { - private PrecipColumnDataSettings _currentMenuSettings; - - - public PrecipThresholdListener(PrecipColumnDataSettings currentMenuSettings) - { - String header = "PrecipThresholdListener.PrecipThresholdListener()"; - _currentMenuSettings = currentMenuSettings; - System.out.println(header +"Current Settings: " + _currentMenuSettings); - } - - public void actionPerformed(ActionEvent e) - { - PrecipThresholdDialog precipThresholdDialog = new PrecipThresholdDialog(_mainFrame, _currentMenuSettings, _logger); - - String header = "PrecipThresholdListener.actionPerformed()"; - // PrecipColumnDataSettings currentMenuSettings = _menuSettings.getPrecipSettings(); - - System.out.println(header +"Before show Current Settings: " + _currentMenuSettings); - - PrecipColumnDataSettings savedPrecipSettings = precipThresholdDialog.showPrecipThresholdDialog(); - if(savedPrecipSettings != null) - { - _currentMenuSettings.setPrecipSettings(savedPrecipSettings); - System.out.println("Im here menu had changed"); - menuChange(); - } - else - { - System.out.println("Im here menu had not changed"); - } - System.out.println(header +"After show Current Settings: " + _currentMenuSettings); - } - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/MonitorRefreshManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/MonitorRefreshManager.java deleted file mode 100644 index c271124e8f..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/MonitorRefreshManager.java +++ /dev/null @@ -1,96 +0,0 @@ -package ohd.hseb.monitor.manager; - -import javax.swing.JSplitPane; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.SessionLogger; - -public abstract class MonitorRefreshManager extends BaseManager -{ - protected SessionLogger _logger; - protected JSplitPane _splitPane; - - public MonitorRefreshManager(MessageSystemManager msgSystemManager, SessionLogger logger, JSplitPane splitPane) - { - _logger = logger; - _splitPane = splitPane; - - setMessageSystemManager(msgSystemManager); - - MessageType outgoingMessageType = MessageType.REFRESH_DISPLAY; - RefreshReceiver reloadDataReceiver = new RefreshReceiver(outgoingMessageType); - _msgSystemManager.registerReceiver(reloadDataReceiver, MessageType.RELOAD_DATA); - - outgoingMessageType = MessageType.UPDATE_DISPLAY_WITH_SETTINGS; - RefreshReceiver reloadDataWithNewSettingsReceiver = new RefreshReceiver(outgoingMessageType); - _msgSystemManager.registerReceiver(reloadDataWithNewSettingsReceiver, MessageType.RELOAD_DATA_WITH_NEW_SETTINGS); - - } - - protected abstract void reloadData(MonitorMessage incomingMessage, MessageType outgoingMessageType); - - private void setSplitPaneDividerLocation() - { - String header = "MonitorRefreshManager.setSplitPaneDividerLocation(): "; - - int newDividerLocation = _splitPane.getDividerLocation(); - // int lastDividerLocation = _splitPane.getLastDividerLocation(); - - //System.out.println(header + "divider location = " + newDividerLocation); - //System.out.println(header + "last divider location = " + lastDividerLocation); - - _splitPane.setDividerLocation(newDividerLocation); - - //newDividerLocation = _splitPane.getDividerLocation(); - //lastDividerLocation = _splitPane.getLastDividerLocation(); - - // System.out.println(header + "after reset divider location, dividerLocation = " + newDividerLocation); - // System.out.println(header + "after reset divider location, lastDividerLocation = " + lastDividerLocation); - - return; - } - - private class RefreshReceiver implements Receiver - { - private MessageType _outgoingMessageType = null; - - public RefreshReceiver(MessageType outgoingMessageType) - { - _outgoingMessageType = outgoingMessageType; - } - - public void receive(MonitorMessage message) - { - String header = "MonitorRefreshManager.RefreshReceiver.receive(): "; - - //Note: setSplitPaneDividerLocation() is called to prevent the - //inadvertent shrinking of the Filter (left side of SplitPane) when, - //for example, the user maximizes the window while the - //application is refreshing. - //Why setting the divider location BEFORE actually refreshing the - //data and the JTable works is still a mystery to us as of 1/11/08. - //Mysteries are bad! - //Related code is in MonitorSplitPane. In that class, the setting of - //left and right SplitPane components occurs between calls to maintain the - //divider location (again, to avoid having the left side of the JSplitPane shrink.) - //That code is not a mystery. - - setSplitPaneDividerLocation(); - - - CodeTimer reloadTimer = new CodeTimer(); - reloadTimer.start(); - - reloadData(message, _outgoingMessageType); - - reloadTimer.stop(header + "reloadData took: "); - } - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/Receiver.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/Receiver.java deleted file mode 100644 index 3d3a8f5c64..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/manager/Receiver.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.monitor.manager; - -import ohd.hseb.monitor.MonitorMessage; - -public interface Receiver -{ - public void receive(MonitorMessage message); -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/Message.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/Message.java deleted file mode 100644 index 58548c5cff..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/Message.java +++ /dev/null @@ -1,33 +0,0 @@ -package ohd.hseb.monitor.messaging; - -public class Message -{ - private MessageType _messageType; - private Object _source; - - public Message(Object source, MessageType messageType) - { - _source = source; - _messageType = messageType; - } - - public MessageType getMessageType() - { - return _messageType; - } - - public Object getMessageSource() - { - return _source; - } - - public void setMessageType(MessageType messageType) - { - _messageType = messageType; - } - - public void setMessageSource(Object source) - { - _source = source; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/MessageSystemManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/MessageSystemManager.java deleted file mode 100644 index 40002ffdb6..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/MessageSystemManager.java +++ /dev/null @@ -1,63 +0,0 @@ -package ohd.hseb.monitor.messaging; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.Receiver; - -public class MessageSystemManager -{ - private Map> _messageTypeToReceiverListMap; - - public MessageSystemManager() - { - - _messageTypeToReceiverListMap = new HashMap>(); - } - - public void registerReceiver(Receiver receiver, MessageType messageType) - { - String header = "MessageSystemManager.addMeAsListener(): "; - - List receiverList = getReceiverList(messageType); - - receiverList.add(receiver); - } - - public void send(MonitorMessage message) - { - String header = "MessageSystemManager.send(): "; - - List receiverList = getReceiverList(message.getMessageType()); - - if(receiverList != null) - { - for(Receiver receiver : receiverList) - { - receiver.receive(message); - } - } - else - { - System.out.println(header + "ReceiverList is null"); - } - } - - private List getReceiverList(MessageType messageType) - { - String header = "MessageSystemManager.getReceiverList(): "; - - List receiverList = _messageTypeToReceiverListMap.get(messageType); - - if(receiverList == null) - { - receiverList = new ArrayList(); - _messageTypeToReceiverListMap.put(messageType, receiverList); - } - - return receiverList; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/MessageType.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/MessageType.java deleted file mode 100644 index 9ec781b75f..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/messaging/MessageType.java +++ /dev/null @@ -1,42 +0,0 @@ -package ohd.hseb.monitor.messaging; - -public enum MessageType -{ - RELOAD_DATA, // Read data from database. Sent by: lookback time menu filters and refresh/update now button. Received by refresh mgr. - - REFRESH_DISPLAY, // Read filter and menu settings and refresh display. Sent by filter mgr, when the check box is - // clicked and by menu mgr when the missing filter is changed - - RELOAD_DATA_WITH_NEW_SETTINGS, // Sent by settings mgr, when new settings are loaded. Received by Refresh mgr - - UPDATE_DISPLAY_WITH_SETTINGS, // Sent by Refresh mgr, when new settings are loaded. Received by view,menu & filter mgr and they are updated - // based on the settings - - LOAD_SETTINGS, // sent by load settings menu and received by settings mgr - - LOAD_OFFICE_SETTINGS, // sent by load office settings menu and received by settings mgr - - SAVE_SETTINGS,// sent by save settings menu and received by settings mgr - - SAVE_OFFICE_SETTINGS,// sent by save office settings menu and received by settings mgr - - FILTER_SELECT_ITEM, //sent when an location in the filter tree is highlighted; Received by view mgr to highlight the row in table - - VIEW_SELECT_ITEM, // sent by view mgr when a row is selected in the table along with the row data; - // Received by menu mgr to get the corresponding row data - - CREATE_TEXT_FROM_VIEW, // sent by export table to text menu, received by view manager - - UPDATE_SETTINGS, // sent by settings mgr before saving the settings to file, - // received by view mgr to set the current table settings in view settings - - CHANGE_COLUMNS, // sent by column change menu, received by view mgr - - APP_SORT, // sent by hsa-group-location sort menu, received by view mgr - - RIVER_THREAT_SORT, // sent by threat sort menu, received by view mgr - - PRECIP_THREAT_SORT,// sent by precip threat sort menu, received by view mgr - - CLEAR_SORT; // sent by clear sort menu, received by view mgr -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipColumns.java deleted file mode 100644 index b91236a212..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipColumns.java +++ /dev/null @@ -1,94 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -/** - * - * @author rajaramv - * - * The purpose of this class is to provide a consistent set of column names and to provide the - * Descriptor list of Precipitation-related required by the OHD Java Table Framework for the RiverMonitor and PrecipMonitor - * applications. (GobsC) - */ -public class PrecipColumns -{ - public static final String LATEST_30MIN = "Latest 30min Precip"; - public static final String LATEST_1HR = "Latest 1hr Precip"; - public static final String LATEST_3HR = "Latest 3hr Precip"; - public static final String LATEST_6HR = "Latest 6hr Precip"; - public static final String LATEST_12HR = "Latest 12hr Precip"; - public static final String LATEST_18HR = "Latest 18hr Precip"; - public static final String LATEST_24HR = "Latest 24hr Precip"; - - public static final String TOH_PRECIP_1HR = "1hr Precip"; - - public static final String FFG_1HR = "FFG 1hr"; - public static final String FFG_3HR = "FFG 3hr"; - public static final String FFG_6HR = "FFG 6hr"; - - public static final String DIFF_1HR = "Diff 1hr"; - public static final String DIFF_3HR = "Diff 3hr"; - public static final String DIFF_6HR = "Diff 6hr"; - - public static final String RATIO_1HR = "Ratio 1hr %"; - public static final String RATIO_3HR = "Ratio 3hr %"; - public static final String RATIO_6HR = "Ratio 6hr %"; - - public static final String PRECIP_THREAT = "Precip Threat"; - - public static final String LATEST_PRECIP_PARAM_CODE = "Latest Precip Param Code"; - - public static final String TOH_PRECIP_1HR_PARAM_CODE = "1hr Precip Param Code"; - - /** - * Creates a list of precip columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the location info columns & precip data columns are added to it, - * if not the precip data column's list is added to the list that is passed as argument. - * The created new list is returned. - * @param precipMonitorColumnDescriptorList - * @return - */ - public List getPrecipColumnsList(List precipMonitorColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if(precipMonitorColumnDescriptorList == null) - { - precipMonitorColumnDescriptorList = new ArrayList(); - precipMonitorColumnDescriptorList = new LocationInfoColumns().getLocationInfoColumnsList(precipMonitorColumnDescriptorList); - } - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_PRECIP_PARAM_CODE, textAlignment, "Latest Precip Param Code")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.TOH_PRECIP_1HR_PARAM_CODE, textAlignment, "Top-of-Hour 1hr Precip Param Code")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_30MIN, numberAlignment, "Latest 30min Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_1HR, numberAlignment, "Latest 1hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_3HR, numberAlignment, "Latest 3hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_6HR, numberAlignment, "Latest 6hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_12HR, numberAlignment, "Latest 12hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_18HR, numberAlignment, "Latest 18hr Precip")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.LATEST_24HR, numberAlignment, "Latest 24hr Precip")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.TOH_PRECIP_1HR, numberAlignment, "Top-of-Hour 1hr Precip")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.FFG_1HR, numberAlignment, "FFG 1hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.FFG_3HR, numberAlignment, "FFG 3hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.FFG_6HR, numberAlignment, "FFG 6hr")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.DIFF_1HR, numberAlignment, "Latest Precip 1hr - FFG 1hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.DIFF_3HR, numberAlignment, "Latest Precip 3hr - FFG 3hr")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.DIFF_6HR, numberAlignment, "Latest Precip 6hr - FFG 6hr")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.RATIO_1HR, numberAlignment, "(Latest Precip 1hr/FFG 1hr) * 100")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.RATIO_3HR, numberAlignment, "(Latest Precip 3hr/FFG 3hr) * 100")); - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.RATIO_6HR, numberAlignment, "(Latest Precip 6hr/FFG 6hr) * 100")); - - precipMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PrecipColumns.PRECIP_THREAT, textAlignment,"Precip Threat")); - - return precipMonitorColumnDescriptorList; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipData.java deleted file mode 100644 index 3c92f72891..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipData.java +++ /dev/null @@ -1,523 +0,0 @@ -package ohd.hseb.monitor.precip; - -import ohd.hseb.db.DbTable; -import ohd.hseb.model.ParamCode; - -public class PrecipData -{ - private double _ffg1Hr; - private double _ffg3Hr; - private double _ffg6Hr; - - private double _latestPrecip30Min; - private double _latestPrecip1Hr; - private double _latestPrecip3Hr; - private double _latestPrecip6Hr; - private double _latestPrecip12Hr; - private double _latestPrecip18Hr; - private double _latestPrecip24Hr; - - private double _tohPrecip1Hr; - //at the moment, with the synoptic time scales for the PDC preprocessor, - //these columns do not make sense. - // private double _tohPrecip3Hr; - // private double _tohPrecip6Hr; - // private double _tohPrecip24Hr; - - private double _diff1Hr; - private double _diff3Hr; - private double _diff6Hr; - - private int _ratio1Hr; - private int _ratio3Hr; - private int _ratio6Hr; - - private ParamCode _latestPrecipParamCode; - - private ParamCode _tohPrecip1HrParamCode; - private ParamCode _tohPrecip3HrParamCode; - private ParamCode _tohPrecip6HrParamCode; - private ParamCode _tohPrecip24HrParamCode; - - public PrecipData() - { - _ffg1Hr = DbTable.getNullDouble(); - _ffg3Hr = DbTable.getNullDouble(); - _ffg6Hr = DbTable.getNullDouble(); - - _latestPrecip30Min = DbTable.getNullDouble(); - _latestPrecip1Hr = DbTable.getNullDouble(); - _latestPrecip3Hr = DbTable.getNullDouble(); - _latestPrecip6Hr = DbTable.getNullDouble(); - _latestPrecip12Hr = DbTable.getNullDouble(); - _latestPrecip18Hr = DbTable.getNullDouble(); - _latestPrecip24Hr = DbTable.getNullDouble(); - - _tohPrecip1Hr = DbTable.getNullDouble(); - // _tohPrecip3Hr = DbTable.getNullDouble(); - // _tohPrecip6Hr = DbTable.getNullDouble(); - // _tohPrecip24Hr = DbTable.getNullDouble(); - - _diff1Hr = DbTable.getNullDouble(); - _diff3Hr = DbTable.getNullDouble(); - _diff6Hr = DbTable.getNullDouble(); - - _ratio1Hr = DbTable.getNullInt(); - _ratio3Hr = DbTable.getNullInt(); - _ratio6Hr = DbTable.getNullInt(); - } - - public double getFFG1Hr() - { - return _ffg1Hr; - } - - public void setFFG1Hr(double ffg1Hr) - { - _ffg1Hr = ffg1Hr; - } - - public double getFFG3Hr() - { - return _ffg3Hr; - } - - public void setFFG3Hr(double ffg3Hr) - { - _ffg3Hr = ffg3Hr; - } - - public double getFFG6Hr() - { - return _ffg6Hr; - } - - public void setFFG6Hr(double ffg6Hr) - { - _ffg6Hr = ffg6Hr; - } - - public double getTohPrecip1Hr() - { - return _tohPrecip1Hr; - } - - public void setTohPrecip1Hr(double tohPrecip1Hr) - { - _tohPrecip1Hr = tohPrecip1Hr; - } - /* - - public double getTohPrecip3Hr() - { - return _tohPrecip3Hr; - } - - public void setTohPrecip3Hr(double tohPrecip3Hr) - { - _tohPrecip3Hr = tohPrecip3Hr; - } - - public double getTohPrecip6Hr() - { - return _tohPrecip6Hr; - } - - public void setTohPrecip6Hr(double tohPrecip6Hr) - { - _tohPrecip6Hr = tohPrecip6Hr; - } - - public double getTohPrecip24Hr() - { - return _tohPrecip24Hr; - } - - public void setTohPrecip24Hr(double tohPrecip24Hr) - { - _tohPrecip24Hr = tohPrecip24Hr; - } - - */ - - - public double getLatestPrecip30Min() - { - return _latestPrecip30Min; - } - - public void setLatestPrecip30Min(double latestPrecip30Min) - { - _latestPrecip30Min = latestPrecip30Min; - } - - - public double getLatestPrecip1Hr() - { - return _latestPrecip1Hr; - } - - public void setLatestPrecip1Hr(double latestPrecip1Hr) - { - _latestPrecip1Hr = latestPrecip1Hr; - } - - public double getLatestPrecip3Hr() - { - return _latestPrecip3Hr; - } - - public void setLatestPrecip3Hr(double latestPrecip3Hr) - { - _latestPrecip3Hr = latestPrecip3Hr; - } - - public double getLatestPrecip6Hr() - { - return _latestPrecip6Hr; - } - - public void setLatestPrecip6Hr(double latestPrecip6Hr) - { - _latestPrecip6Hr = latestPrecip6Hr; - } - - public double getLatestPrecip12Hr() - { - return _latestPrecip12Hr; - } - - public void setLatestPrecip12Hr(double latestPrecip12Hr) - { - _latestPrecip12Hr = latestPrecip12Hr; - } - - public double getLatestPrecip18Hr() - { - return _latestPrecip18Hr; - } - - public void setLatestPrecip18Hr(double latestPrecip18Hr) - { - _latestPrecip18Hr = latestPrecip18Hr; - } - - public double getLatestPrecip24Hr() - { - return _latestPrecip24Hr; - } - - public void setLatestPrecip24Hr(double latestPrecip24Hr) - { - _latestPrecip24Hr = latestPrecip24Hr; - } - - public int getRatio1Hr() - { - return _ratio1Hr; - } - - public void setRatio1Hr(int ratio1Hr) - { - _ratio1Hr = ratio1Hr; - } - public int getRatio3Hr() - { - return _ratio3Hr; - } - - public void setRatio3Hr(int ratio3Hr) - { - _ratio3Hr = ratio3Hr; - } - public int getRatio6Hr() - { - return _ratio6Hr; - } - - public void setRatio6Hr(int ratio6Hr) - { - _ratio6Hr = ratio6Hr; - } - public double getDiff1Hr() - { - return _diff1Hr; - } - - public void setDiff1Hr(double diff1Hr) - { - _diff1Hr = diff1Hr; - } - public double getDiff3Hr() - { - return _diff3Hr; - } - - public void setDiff3Hr(double diff3Hr) - { - _diff3Hr = diff3Hr; - } - - public double getDiff6Hr() - { - return _diff6Hr; - } - - public void setDiff6Hr(double diff6Hr) - { - _diff6Hr = diff6Hr; - } - - public ParamCode getLatestPrecipParamCode() - { - return _latestPrecipParamCode; - } - - public String getLatestPrecipParamCodeString() - { - if(_latestPrecipParamCode != null) - return _latestPrecipParamCode.toString(); - else - return null; - } - - public void setLatestPrecipParamCode(ParamCode latestPrecipParamCode) - { - _latestPrecipParamCode = latestPrecipParamCode; - } - - public ParamCode getTohPrecip1HrParamCode() - { - return _tohPrecip1HrParamCode; - } - - public String getTohPrecip1HrParamCodeString() - { - if(_tohPrecip1HrParamCode != null) - return _tohPrecip1HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip1HrParamCode(ParamCode tohPrecip1HrParamCode) - { - _tohPrecip1HrParamCode = tohPrecip1HrParamCode; - } - - public ParamCode getTohPrecip3HrParamCode() - { - return _tohPrecip3HrParamCode; - } - - public String getTohPrecip3HrParamCodeString() - { - if(_tohPrecip3HrParamCode != null) - return _tohPrecip3HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip3HrParamCode(ParamCode tohPrecip3HrParamCode) - { - _tohPrecip3HrParamCode = tohPrecip3HrParamCode; - } - - public ParamCode getTohPrecip6HrParamCode() - { - return _tohPrecip6HrParamCode; - } - - public String getTohPrecip6HrParamCodeString() - { - if(_tohPrecip6HrParamCode != null) - return _tohPrecip6HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip6HrParamCode(ParamCode tohPrecip6HrParamCode) - { - _tohPrecip6HrParamCode = tohPrecip6HrParamCode; - } - - public ParamCode getTohPrecip24HrParamCode() - { - return _tohPrecip24HrParamCode; - } - - public String getTohPrecip24HrParamCodeString() - { - if(_tohPrecip24HrParamCode != null) - return _tohPrecip24HrParamCode.toString(); - else - return null; - } - - public void setTohPrecip24HrParamCode(ParamCode tohPrecip24HrParamCode) - { - _tohPrecip24HrParamCode = tohPrecip24HrParamCode; - } - - public boolean isDataAvailable() - { - boolean result = true; - if( - DbTable.isNull(getLatestPrecip30Min()) && - DbTable.isNull(getLatestPrecip1Hr()) && - DbTable.isNull(getLatestPrecip3Hr()) && - DbTable.isNull(getLatestPrecip6Hr()) && - DbTable.isNull(getLatestPrecip12Hr()) && - DbTable.isNull(getLatestPrecip18Hr()) && - DbTable.isNull(getLatestPrecip24Hr()) && - DbTable.isNull(getTohPrecip1Hr()) - - /* - && getTohPrecip3Hr() == DbTable.getNullDouble() && - getTohPrecip6Hr() == DbTable.getNullDouble() && - getTohPrecip24Hr() == DbTable.getNullDouble() - */ - ) - { - result = false; - } - - return result; - } - - public void setTohParamCodeByHour(int hour, ParamCode paramCode) - { - switch(hour) - { - case 1: - setTohPrecip1HrParamCode(paramCode); - break; - case 3: - setTohPrecip3HrParamCode(paramCode); - break; - case 6: - setTohPrecip6HrParamCode(paramCode); - break; - case 24: - setTohPrecip24HrParamCode(paramCode); - break; - } - } - - public void setTohPrecipByHour(int hour, double precipTotal) - { - switch(hour) - { - case 1: - setTohPrecip1Hr(precipTotal); - break; - - /* - case 3: - setTohPrecip3Hr(precipTotal); - break; - case 6: - setTohPrecip6Hr(precipTotal); - break; - case 24: - setTohPrecip24Hr(precipTotal); - break; - */ - } - } - - public double getTohPrecipByHour(int hour) - { - double returnValue = DbTable.getNullDouble(); - switch (hour) - { - case 1: - returnValue = getTohPrecip1Hr(); - break; - /* - case 3: - returnValue = getTohPrecip3Hr(); - break; - case 6: - returnValue = getTohPrecip6Hr(); - break; - case 24: - returnValue = getTohPrecip24Hr(); - break; - */ - } - return returnValue; - } - - public void setLatestPrecipByHour(float hour, double precipTotal) - { - - if (hour == 0.5) - { - setLatestPrecip30Min(precipTotal); - } - else if (hour == 1) - { - setLatestPrecip1Hr(precipTotal); - } - else if (hour == 3) - { - setLatestPrecip3Hr(precipTotal); - } - else if (hour == 6) - { - setLatestPrecip6Hr(precipTotal); - } - else if (hour == 12) - { - setLatestPrecip12Hr(precipTotal); - } - else if (hour == 18) - { - setLatestPrecip18Hr(precipTotal); - } - else if (hour == 24) - { - setLatestPrecip24Hr(precipTotal); - } - - return; - } - - public double getLatestPrecipByHour(float hour) - { - double returnValue = DbTable.getNullDouble(); - - if (hour == 0.5) - { - returnValue = getLatestPrecip30Min(); - } - if (hour == 1) - { - returnValue = getLatestPrecip1Hr(); - } - else if (hour == 3) - { - returnValue = getLatestPrecip3Hr(); - } - else if (hour == 6) - { - returnValue = getLatestPrecip6Hr(); - } - else if (hour == 12) - { - returnValue = getLatestPrecip12Hr(); - } - else if (hour == 18) - { - returnValue = getLatestPrecip18Hr(); - } - else if (hour == 24) - { - returnValue = getLatestPrecip24Hr(); - } - - - return returnValue; - } -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipDataManager.java deleted file mode 100644 index 3ea7d68e91..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipDataManager.java +++ /dev/null @@ -1,936 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.geomap.model.HrapRowColToLatLonConverter; -import ohd.hseb.geomap.model.LatLonPoint; -import ohd.hseb.geomap.model.RowColumnPoint; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.model.ParamCode; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.pdc_pp.PDCFileReader; -import ohd.hseb.pdc_pp.RegularObsTimeSeries; -import ohd.hseb.pdc_pp.TimeValuePair; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.MemoryLogger; -import ohd.hseb.util.SessionLogger; -import ucar.ma2.IndexIterator; -import ucar.nc2.NetcdfFile; -import ucar.nc2.Variable; - -public class PrecipDataManager -{ - private AppsDefaults _appsDefaults; - - private double _missingDoubleValue = -9999.0; - - private SessionLogger _logger; - private Database _db; - - private PDCFileReader _pdcFileReaderForPrecipInstant; - private PDCFileReader _pdcFileReaderForPrecip1Hour; - private PDCFileReader _pdcFileReaderForPrecip3Hour; - private PDCFileReader _pdcFileReaderForPrecip6Hour; - private PDCFileReader _pdcFileReaderForPrecip24Hour; - private long _pdcFileUpdateLongTime = 0; //this is the time of file creation - - private String _pdcPreprocessorFilesDir; - private Map> _lidToLatestPrecipMap = null; - - private Map> _lidToTohPrecipMapFor1Hr = null; - private Map> _lidToTohPrecipMapFor3Hr = null; - private Map> _lidToTohPrecipMapFor6Hr = null; - private Map> _lidToTohPrecipMapFor24Hr = null; - - private Map _lidToLatLonPointMap = null; - - private HrapRowColToLatLonConverter _hrapRowColToLatLonConverter = null; - private int _baseNationalHrapRowSW; - private int _baseNationalHrapColSW; - - private XmrgGrid _xmrgGridFor1hrFFG = null; - private XmrgGrid _xmrgGridFor3hrFFG = null; - private XmrgGrid _xmrgGridFor6hrFFG = null; - - public PrecipDataManager(Database db, AppsDefaults appsDefaults, String missingRepresentation, SessionLogger logger) - { - _logger = logger; - - _db = db; - _appsDefaults = appsDefaults; - _pdcPreprocessorFilesDir = _appsDefaults.getToken("pdc_pp_dir", - HydroappsDefaultDirs.PDC_PP_DIR); - } -// --------------------------------------------------------------------------------------------------- - protected Map getLidToPrecipTotalsMapFromPreprocessorFile(PDCFileReader pdcFileReader, Map lidToPrecipTotalsMap) - { - String header = "PrecipDataManager.getLidToPrecipTotalsMapFromPreprocessorFile(): "; - - //this block of code attempts to help Garbage collection reduce the amount of memory required - if(lidToPrecipTotalsMap == null) - { - lidToPrecipTotalsMap = new HashMap(); - } - else //clear out the map and its contents - { - Set lidSet = lidToPrecipTotalsMap.keySet(); - - //run through each List associated with each lid and clear it - for (String lid : lidSet) - { - List regularObsTimeSeriesForAllTSList =(List)lidToPrecipTotalsMap.get(lid); - regularObsTimeSeriesForAllTSList.clear(); - } - - lidToPrecipTotalsMap.clear(); - } - - checkMemoryAndGarbageCollectLog(header +"G.065 before pdcFileReader.read(), before GC"); - - //read precip data from the PDC file - List regularObsTimeSeriesList = pdcFileReader.read(); - - checkMemoryAndGarbageCollectLog(header +"G.07 after pdcFileReader.read(), before GC"); - - // put the list of RegularObsTimeSeries for each lid in the lidToPrecipTotalsMap - if( regularObsTimeSeriesList != null ) - { - List regularObsTimeSeriesForAllTSList = null; - - for (RegularObsTimeSeries regularObsTimeSeries: regularObsTimeSeriesList) - { - String lid = regularObsTimeSeries.getDescriptor().getLid(); - - regularObsTimeSeriesForAllTSList = (List) lidToPrecipTotalsMap.get(lid); - - if(regularObsTimeSeriesForAllTSList == null) - { - regularObsTimeSeriesForAllTSList = new ArrayList(); - - lidToPrecipTotalsMap.put(lid, regularObsTimeSeriesForAllTSList); - } - - regularObsTimeSeriesForAllTSList.add(regularObsTimeSeries); - - } //end for each regularObsTimeSeries - - checkMemoryAndGarbageCollectLog(header +"G.08, after for loop " ); - - } - - checkMemoryAndGarbageCollectLog(header +"Here G.09 after if loop " ); - - return lidToPrecipTotalsMap; - } - - //--------------------------------------------------------------------------------------- -/* - private String getFFGFileName(int hour) - { - final String header = "PrecipDataManager.getFFGFileName(): "; - String ffgDir; - String ffgFileName = null; - String st3RfcTokenValue = _appsDefaults.getToken("st3_rfc"); - - //System.out.println(header + "st3_rfc token value = " + st3RfcTokenValue); - File filesForhrMentioned[] ; - - File dir; - - if(st3RfcTokenValue.equalsIgnoreCase("host")) - { - ffgDir = _appsDefaults.getToken("gaff_mosaic_dir", HydroappsDefaultDirs.GAFF_MOSAIC_DIR) + "/"; - dir = new File(ffgDir); - - FilenameFilter filter = new NetCdfFileNameFilter(1); - - //TODO we should get rid of this switch statement - switch(hour) - { - case 1: - filter = new NetCdfFileNameFilter(1); - break; - case 3: - filter = new NetCdfFileNameFilter(3); - break; - case 6: - filter = new NetCdfFileNameFilter(6); - break; - } - filesForhrMentioned = dir.listFiles(filter); - - } - else //RFC grids - { - String gafInputDir = _appsDefaults.getToken("gaff_input_dir"); - ffgDir = gafInputDir + "/" + new String(st3RfcTokenValue.toUpperCase()) + "/" - + hour+"hr"+"/"; - dir = new File(ffgDir); - filesForhrMentioned = dir.listFiles(); - } - - System.out.println(header + "ffgDir = " + ffgDir); - - if(filesForhrMentioned != null && filesForhrMentioned.length > 0 && - filesForhrMentioned[0].length() > 0) - { - File lastModifiedFile = findTheLatestModifiedFile(filesForhrMentioned); - //System.out.println(header + " lastmodifiedfile:" + lastModifiedFile); - ffgFileName = lastModifiedFile.toString(); - } - else - { - _logger.log(header + "No ffg files found in directory [" + dir.getAbsolutePath() +"]"); - } - - return ffgFileName; - } -*/ - private String getFFGFileName(int hour) - { - String header = "PrecipDataManager.getFFGFileName(): "; - String ffgFileName = null; - - File[] mosaicFileArray = getGaffMosaicFileArray(hour); - - if ((mosaicFileArray != null ) && (mosaicFileArray.length > 0)) - { - ffgFileName = getNameOfLastModifiedFile(mosaicFileArray); - } - - else //if I didn't find any GAFF output mosaic files, use GAFF input files - { - - File[] gaffInputFileArray = getGaffInputFileArray(hour); - if ((gaffInputFileArray != null) && (gaffInputFileArray.length > 0)) - { - ffgFileName = getNameOfLastModifiedFile(gaffInputFileArray); - } - - } - - System.out.println(header + "ffgFileName = " + ffgFileName); - - return ffgFileName; - - } - - private String getNameOfLastModifiedFile(File[] fileArray) - { - String header = "PrecipDataManager.getNameOfLastModifiedFile(): "; - String nameOfLastModifiedFile = null; - - if(fileArray != null && fileArray.length > 0 && - fileArray[0].length() > 0) - { - File lastModifiedFile = findTheLatestModifiedFile(fileArray); - //System.out.println(header + " lastmodifiedfile:" + lastModifiedFile); - nameOfLastModifiedFile = lastModifiedFile.toString(); - } - else - { - _logger.log(header + "No ffg files found."); - } - - return nameOfLastModifiedFile; - } -// ------------------------------------------------------------------------------------------------------------ - private File[] getGaffMosaicFileArray(int hour) - { - File filesForHour[] ; - String ffgDirString = _appsDefaults.getToken("gaff_mosaic_dir", HydroappsDefaultDirs.GAFF_MOSAIC_DIR) + "/"; - File dir = new File(ffgDirString); - - FilenameFilter filter = new NetCdfFileNameFilter(hour); - - filesForHour = dir.listFiles(filter); - - return filesForHour; - } - - private File[] getGaffInputFileArray(int hour) - { - File filesForHour[] ; - File dir = null; - String st3RfcTokenValue = _appsDefaults.getToken("st3_rfc"); - - String gafInputDirString = _appsDefaults.getToken("gaff_input_dir"); - String ffgDirString = gafInputDirString + "/" + new String(st3RfcTokenValue.toUpperCase()) + "/" - + hour+"hr"+"/"; - dir = new File(ffgDirString); - filesForHour = dir.listFiles(); - - return filesForHour; - } -// ------------------------------------------------------------------------------------------------------------ - - - private File findTheLatestModifiedFile(File filesForHrMentioned[]) - { - File lastModifiedFile = filesForHrMentioned[0]; - for(int i=1 ; i < filesForHrMentioned.length; i++) - { - if(filesForHrMentioned[i].lastModified() > lastModifiedFile.lastModified()) - { - lastModifiedFile = filesForHrMentioned[i]; - } - } - return lastModifiedFile; - } - - -// ------------------------------------------------------------------------------------------------------------ - - private void readFFGInfoForMentionedHr(int hour) - { - String ffgFileName = getFFGFileName(hour); - - String header = "PrecipDataManager.readFFGInfoForMentionedHr(): "; - if(ffgFileName != null) - { - NetcdfFile netCdfFile = null; - try - { - netCdfFile = NetcdfFile.open(ffgFileName); - - readNetCdfFileAndCreateXmargGridForMentionedHr(netCdfFile, hour); - - } - catch (Exception ioe) - { - _logger.log(header + "Trying to open netcdf files" + ffgFileName +" " +ioe); - } - finally - { - if (null != netCdfFile) - { - try - { - netCdfFile.close(); - } - catch (IOException ioe) - { - System.out.println(header + "Trying to close netcdf files" + ffgFileName+" " +ioe); - } - } - - } - } - } -// ----------------------------------------------------------------------------------------------- - - - private void createLidToLatLongMap() - { - if(_lidToLatLonPointMap == null) - { - String whereClause = "order by lid"; - LocationTable locationTable = new LocationTable(_db); - LocationRecord locationRecord = new LocationRecord(); - List locationList = null; - try - { - locationList = locationTable.select(whereClause); - } - catch(SQLException e) - { - _logger.log("Error while reading location table for lat/long values:" + e); - } - - if(locationList != null) - { - LatLonPoint latLonPoint; - _lidToLatLonPointMap = new HashMap(); - for(int i=0; i < locationList.size(); i++) - { - locationRecord = (LocationRecord) locationList.get(i); - String lid = locationRecord.getLid(); - double lat = locationRecord.getLat(); - double lon = locationRecord.getLon(); - latLonPoint = new LatLonPoint(lat, lon); - _lidToLatLonPointMap.put(lid, latLonPoint); - } - } - } - } - -// ----------------------------------------------------------------------------------------------- - private void readNetCdfFileAndCreateXmargGridForMentionedHr(NetcdfFile netCdfFile, int hour) - { - createLidToLatLongMap(); - - try - { - //read the netcdf file for values of x & y - //ie., the numOfLocalHrapCols & numOfLocalHrapRows - int numOfLocalHrapCols = netCdfFile.findDimension("x").getLength() ; - int numOfLocalHrapRows = netCdfFile.findDimension("y").getLength() ; - // System.out.println("[y, x] ie., [numOfLocalHrapRows ,numOfLocalHrapCols]:["+numOfLocalHrapRows+","+ numOfLocalHrapCols+"]"); - - //read netcdf file for all the ffg values in an array - //ie., read the netcdf file for values of image - ucar.ma2.Array imageArray = (ucar.ma2.Array) netCdfFile.read("image", false); - // System.out.println("Array:["+imageArray+"]"); - - // read netcdf file for valid time - Variable validTimeVariable = netCdfFile.findVariable("validTime"); - ucar.ma2.Array validTimeArray = validTimeVariable.read(); - - IndexIterator indexIterator = validTimeArray.getIndexIterator(); - long validTimeLong = indexIterator.getLongNext(); - - // System.out.println("valid time:"+ validTimeArray +" long:"+ validTimeLong); - - // read netcdf file for latitude and longitude values of the grid area. - // this is the NW point (top left corner) point in the whole grid area represented by the netcdf file - ucar.nc2.Attribute lat = (ucar.nc2.Attribute) netCdfFile.findGlobalAttribute("lat00"); - ucar.nc2.Attribute lon = (ucar.nc2.Attribute) netCdfFile.findGlobalAttribute("lon00"); - - double latitude = lat.getNumericValue().doubleValue(); - double longitude = lon.getNumericValue().doubleValue(); - - // System.out.println("[latitude,longitude]:["+latitude+","+ longitude+"]"); - - createHrapRowColToLatLonConverter(latitude, longitude,numOfLocalHrapRows ); - - createXmrgGridAndSetGridValues(validTimeLong, numOfLocalHrapRows, numOfLocalHrapCols, imageArray, hour); - } - catch(Exception e) - { - System.out.println("Error while reading netcdf file:"+ e); - e.printStackTrace(); - } - } - -// ----------------------------------------------------------------------------------------------- - - private void createXmrgGridAndSetGridValues(long validTime, int numOfLocalHrapRows, - int numOfLocalHrapCols, ucar.ma2.Array array, int hour ) - { - - XmrgGrid xmargGrid = new XmrgGrid(validTime, _baseNationalHrapRowSW, _baseNationalHrapColSW, numOfLocalHrapRows, numOfLocalHrapCols); - - //create a xmrggrid with the given validtime - - switch(hour) - { - case 1: - _xmrgGridFor1hrFFG = xmargGrid; - break; - case 3: - _xmrgGridFor3hrFFG = xmargGrid; - break; - case 6: - _xmrgGridFor6hrFFG = xmargGrid; - break; - default: - _xmrgGridFor1hrFFG = xmargGrid; - } - - - //populate the xmrggrid with values read from netcdf file - //note: netcdf values are is read from NW and it is left to right in consecutive line ( top to bottom ) ie., usual way - // xmrggrid values are read from SW and it is also left to right in consecutive line ( bottom to top) ie., not usual way - int xmrgRowNumber = 0; - IndexIterator indexIterator = array.getIndexIterator(); - - for(int rowIndex=numOfLocalHrapRows -1; rowIndex >=0; rowIndex--) - { - for(int columnIndex=0; columnIndex < numOfLocalHrapCols; columnIndex++ ) - { - if(indexIterator.hasNext()) - { - - // double value = indexIterator.getDoubleNext(); - int value = indexIterator.getIntNext(); - double convertedValue = convertFfgValue(value); - - // System.out.println("Try to enter:["+ rowIndex+","+ columnIndex+"]" + value); - xmargGrid.setValue(rowIndex + _baseNationalHrapRowSW, columnIndex + _baseNationalHrapColSW, convertedValue); - } - } - xmrgRowNumber++; - } - - } - -// ----------------------------------------------------------------------------------------------- - /* - * This method is replicated from ffconv method in ffconv.c - */ - private double convertFfgValue(double originalValue) - { - - String header = "PrecipDataManage.convertFfgValue(): "; - - double signFixedValue = originalValue; - double returnValue = 0.0; - final double lowerThreshold = 201; - final double upperThreshold = 253; - final double mFactor = 6; - final double inchPerMM = 0.03937; - - - // These are values from image file and they are byte counts. - //These are similar to an enhanced satellite image. - //So normally the values go from 0 to 255 (256 values). - //But, for values beyond 127, they turn negative. - //So value 128 is really 128 - 256 = -128 in the file - //hence you will need to add 256 for negative values to get the actual positive value - //This actual value is what is needed. - if (signFixedValue < 0) - { - signFixedValue += 256; - } - - //convert the coded value to actual precip amounts in inches - if (signFixedValue == 0) - { - returnValue = DbTable.getNullDouble(); - } - else if (signFixedValue <= lowerThreshold) - { - returnValue = signFixedValue - 1; - returnValue *= inchPerMM; - } - else if (signFixedValue <= upperThreshold) - { - returnValue = (lowerThreshold - 1) + ((signFixedValue - 1) - (lowerThreshold - 1))* mFactor ; - returnValue *= inchPerMM; - } - else if (signFixedValue >= upperThreshold) - { - returnValue = DbTable.getNullDouble(); - } - - - - return returnValue; - } -// ----------------------------------------------------------------------------------------------- - private void createHrapRowColToLatLonConverter(double latitude, double longitude, int numOfLocalHrapRows) - { - // with the NW(top left corner) latitude/longitude info - // get the national hrap cordinates for the NW (top left corner) - //TODO examine the negation of longitude - ask Bryon - - RowColumnPoint nationalHrapCoorinatesNW = HrapRowColToLatLonConverter.getNationalRowColumnPoint(latitude,-longitude); - - // with the national hrap coordinates for the NW (top left corner) - // and the num of local hrap rows and num of local hrap cols info read from the netcdf file - // determine the base national hrap row and base national hrap col - // ie., the base national SW point's row number and column number - // which is the bottom left corner's info - _baseNationalHrapRowSW = (int) (nationalHrapCoorinatesNW.getRow() - numOfLocalHrapRows) ; - _baseNationalHrapColSW = (int) nationalHrapCoorinatesNW.getCol(); - - if(_hrapRowColToLatLonConverter == null) - { - _hrapRowColToLatLonConverter = new HrapRowColToLatLonConverter(_baseNationalHrapRowSW, _baseNationalHrapColSW); - } -// LatLonPoint latLong = _hrapRowColToLatLonConverter.getLatLonPoint(numOfLocalHrapRows -1, 0); - // System.out.println("lat long:"+ latLong); - } - -// ----------------------------------------------------------------------------------------------- - - public void setTohPrecipDataForThisLidForMentionedHour(String lid, PrecipData precipData, int hour) - { - Map> lidToTohPrecipTimeSeriesMap = null; - - switch(hour) - { - case 1: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor1Hr; - break; - case 3: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor3Hr; - break; - case 6: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor6Hr; - break; - case 24: - lidToTohPrecipTimeSeriesMap = _lidToTohPrecipMapFor24Hr; - break; - } - if (lidToTohPrecipTimeSeriesMap.size() > 0) - { - List regularObsTimeSeriesForAllTSList = lidToTohPrecipTimeSeriesMap.get(lid); - - int count = 0; - if( regularObsTimeSeriesForAllTSList != null ) - { - for(RegularObsTimeSeries regularObsTimeSeries: regularObsTimeSeriesForAllTSList) - { - String paramCodeString = regularObsTimeSeries.getDescriptor().getShef_param_code(); - ParamCode paramCode = new ParamCode(paramCodeString); - - List timeValuePairsForParticularTSList = regularObsTimeSeries.getTimeValuePairList(true); - int indexOfLastTimeValuePair = timeValuePairsForParticularTSList.size() - 1; - - //The last period is a partially-completed period. - //The previous period the most recent complete period. - int indexOfOfLastCompletedPeriod = indexOfLastTimeValuePair - 1; - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfOfLastCompletedPeriod); - double precipTotal = timeValuePair.getValue(); - - boolean checkPrevValue = true; - if(count == 0) - { - checkPrevValue = false; - } - - if(precipTotal != _missingDoubleValue) - { - if(checkPrevValue) - { - if(precipTotal > precipData.getTohPrecipByHour(hour) ) - { - precipData.setTohPrecipByHour(hour, precipTotal); - precipData.setTohParamCodeByHour(hour, paramCode); - } - } - else - { - precipData.setTohPrecipByHour(hour, precipTotal); - precipData.setTohParamCodeByHour(hour, paramCode); - } - } - else // make sure that the param code is available for missing data - { - precipData.setTohParamCodeByHour(hour, paramCode); - } - count++; - }//end of for loop - }// end of if(regularobstimeseriesforallTSlist != null) - } - } - - -// ----------------------------------------------------------------------------------------------- - - public void setLatestPrecipDataForThisLid(String lid, PrecipData precipData) - { - if (_lidToLatestPrecipMap != null && _lidToLatestPrecipMap.size() > 0) - { - List regularObsTimeSeriesForAllTSList = _lidToLatestPrecipMap.get(lid); - - if( regularObsTimeSeriesForAllTSList != null ) - { - for(int i=0; i < regularObsTimeSeriesForAllTSList.size(); i++) - { - RegularObsTimeSeries regularObsTimeSeriesForParticularTS = regularObsTimeSeriesForAllTSList.get(i); - - String paramCodeString = regularObsTimeSeriesForParticularTS.getDescriptor().getShef_param_code(); - ParamCode paramCode = new ParamCode(paramCodeString); - - precipData.setLatestPrecipParamCode(paramCode); - - List timeValuePairsForParticularTSList = regularObsTimeSeriesForParticularTS.getTimeValuePairList(true); - - int indexOfLastTimeValuePair = timeValuePairsForParticularTSList.size() - 1; - boolean checkPrevValue = true; - if(i == 0) - { - checkPrevValue = false; - } - - - TimeValuePair timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair); - setLatestPrecipForHrMentioned(0.5f, timeValuePair, precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair - 1); - setLatestPrecipForHrMentioned(1, timeValuePair, precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair - 3); - setLatestPrecipForHrMentioned(3, timeValuePair, precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair - 6); - setLatestPrecipForHrMentioned(6, timeValuePair, precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair - 12); - setLatestPrecipForHrMentioned(12, timeValuePair, precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair - 18); - setLatestPrecipForHrMentioned(18, timeValuePair, precipData, checkPrevValue); - - timeValuePair = (TimeValuePair) timeValuePairsForParticularTSList.get(indexOfLastTimeValuePair - 24); - setLatestPrecipForHrMentioned(24, timeValuePair, precipData, checkPrevValue); - - } - } - } - } - -// ------------------------------------------------------------------------------------------------------------ - - public void setFFGDataForThisLid(String lid, PrecipData precipData) - { - if(_lidToLatLonPointMap != null) - { - LatLonPoint latLon = (LatLonPoint) _lidToLatLonPointMap.get(lid); - if(latLon != null) - { - double lat = latLon.getLat(); - double lon = latLon.getLon(); - // System.out.println("For lid:"+ lid + " [lat,lon]:"+ lat +"," + lon); - - RowColumnPoint rowColumnPoint = HrapRowColToLatLonConverter.getNationalRowColumnPoint(lat, lon); - int rowPoint = (int) rowColumnPoint.getRow(); - int colPoint = (int) rowColumnPoint.getCol(); - - double value = _xmrgGridFor1hrFFG.getValue(rowPoint, colPoint); - if(value != XmrgGrid.OFF_GRID_VALUE) - precipData.setFFG1Hr(value); - - value = _xmrgGridFor3hrFFG.getValue(rowPoint, colPoint); - if(value != XmrgGrid.OFF_GRID_VALUE) - precipData.setFFG3Hr(value); - - value = _xmrgGridFor6hrFFG.getValue(rowPoint, colPoint); - if(value != XmrgGrid.OFF_GRID_VALUE) - precipData.setFFG6Hr(value ); - - if(value == 0.00) - { - System.out.println("For lid:" + lid + " value is:"+ value); - } - } - - } - } - -// ----------------------------------------------------------------------------------------------- - public void set1Hr3Hr6HrRatio(PrecipData precipData) - { - precipData.setRatio1Hr( determinePrecipFFGRatio(precipData.getLatestPrecip1Hr(), precipData.getFFG1Hr())); - precipData.setRatio3Hr( determinePrecipFFGRatio(precipData.getLatestPrecip3Hr(), precipData.getFFG3Hr())); - precipData.setRatio6Hr( determinePrecipFFGRatio(precipData.getLatestPrecip6Hr(), precipData.getFFG6Hr())); - return; - } -// ----------------------------------------------------------------------------------------------- - - private int determinePrecipFFGRatio(double precip, double ffg) - { - int ratio = DbTable.getNullInt(); - - if( (ffg != 0.00 && ffg != DbTable.getNullDouble()) - && precip != DbTable.getNullDouble()) //to avoid divide by 0 value - { - ratio = (int)((precip / ffg) * 100); - } - - return ratio; - } - -// ----------------------------------------------------------------------------------------------- - - public Map> readPrecipFile(String fileName, PDCFileReader pdcFileReader, Map> lidToLatestPrecipMap) - { - if(pdcFileReader == null) - { - pdcFileReader = new PDCFileReader(_pdcPreprocessorFilesDir + fileName); - } - else - { - pdcFileReader.resetObsTimeSeriesList(); - } - - lidToLatestPrecipMap = getLidToPrecipTotalsMapFromPreprocessorFile(pdcFileReader, lidToLatestPrecipMap); - - return lidToLatestPrecipMap; - } - - public void readPDCPreprocessorPrecipFiles() - { - String header = "PrecipDataManager.readPDCPreprocessorPrecipFiles(): "; - - //determine the last update time for PDC Precip data - setPdcFileUpdateLongTime(0); - File file = new File(_pdcPreprocessorFilesDir + "/PrecipInstant.dat"); - if (file != null) - { - setPdcFileUpdateLongTime(file.lastModified()); - System.out.println(header + " the last modified file time = " + - DbTimeHelper.getDateTimeStringFromLongTime(getPdcFileUpdateLongTime())); - file = null; - } - - //read the - _lidToLatestPrecipMap = readPrecipFile("/PrecipInstant.dat", _pdcFileReaderForPrecipInstant, _lidToLatestPrecipMap); - checkMemoryAndGarbageCollectLog(header +"Here after reading precip instant"); - - _lidToTohPrecipMapFor1Hr = readPrecipFile("/Precip1Hour.dat", _pdcFileReaderForPrecip1Hour, _lidToTohPrecipMapFor1Hr); - checkMemoryAndGarbageCollectLog(header +"Here after reading precip 1 hour :"); - - _lidToTohPrecipMapFor3Hr = readPrecipFile("/Precip3Hour.dat", _pdcFileReaderForPrecip3Hour, _lidToTohPrecipMapFor3Hr); - checkMemoryAndGarbageCollectLog(header +"Here after reading precip 3 hour :"); - - _lidToTohPrecipMapFor6Hr = readPrecipFile("/Precip6Hour.dat", _pdcFileReaderForPrecip6Hour, _lidToTohPrecipMapFor6Hr); - checkMemoryAndGarbageCollectLog(header +"Here after reading precip 6 hour :"); - - _lidToTohPrecipMapFor24Hr = readPrecipFile("/Precip24Hour.dat", _pdcFileReaderForPrecip24Hour, _lidToTohPrecipMapFor24Hr); - checkMemoryAndGarbageCollectLog(header +"Here after reading precip 24 hour :"); - } - - public void checkMemoryAndGarbageCollectLog(String message) - { - Runtime runtime = Runtime.getRuntime(); - String text = null; - - long freeMemory = runtime.freeMemory(); - - final long SMALL_AMOUNT_OF_MEMORY = 30000000; - - if (freeMemory < SMALL_AMOUNT_OF_MEMORY) - { - text = message + "Free:" + freeMemory + " Max:"+ runtime.maxMemory()+ " total:"+ runtime.totalMemory(); - MemoryLogger.log(text); - - runtime.gc(); - } - } -// ------------------------------------------------------------------------------------------------------------ - - public void readPrecipData(List rowDataList, String tag) - { - String header = "PrecipDataManager.readLatestPrecipData(): "; - - System.out.println(header + "Reading precip data"); - readPDCPreprocessorPrecipFiles(); - - readFFGInfoForMentionedHr(1); - readFFGInfoForMentionedHr(3); - readFFGInfoForMentionedHr(6); - - for(int i=0; i < rowDataList.size(); i++) - { - String lid = null; - PrecipData precipData = new PrecipData(); - if(tag.compareTo("PRECIP") == 0) - { - PrecipMonitorJTableRowData precipMonitorRowData = (PrecipMonitorJTableRowData) rowDataList.get(i); - lid = (String) precipMonitorRowData.getLid(); - precipMonitorRowData.setPrecipData(precipData); - } - else - { - RiverMonitorJTableRowData riverMonitorRowData = (RiverMonitorJTableRowData) rowDataList.get(i); - lid = (String) riverMonitorRowData.getLid(); - riverMonitorRowData.setPrecipData(precipData); - } - setLatestPrecipDataForThisLid(lid, precipData); - - setFFGDataForThisLid(lid, precipData); - - setTohPrecipDataForThisLidForMentionedHour( lid, precipData, 1 ); - setTohPrecipDataForThisLidForMentionedHour( lid, precipData, 3 ); - setTohPrecipDataForThisLidForMentionedHour( lid, precipData, 6 ); - setTohPrecipDataForThisLidForMentionedHour( lid, precipData, 24 ); - - setFfgDifferenceValues(precipData); - - set1Hr3Hr6HrRatio(precipData); - - }//end of for loop - checkMemoryAndGarbageCollectLog(header +"End of read precip method " ); - } - - -// ------------------------------------------------------------------------------------------------------------ - private void setFfgDifferenceValues(PrecipData precipData) - { - precipData.setDiff1Hr(determineFfgDifferenceValue(precipData.getLatestPrecip1Hr(), precipData.getFFG1Hr())); - precipData.setDiff3Hr(determineFfgDifferenceValue(precipData.getLatestPrecip3Hr(), precipData.getFFG3Hr())); - precipData.setDiff6Hr(determineFfgDifferenceValue(precipData.getLatestPrecip6Hr(), precipData.getFFG6Hr())); - } - -// ------------------------------------------------------------------------------------------------------------ - - private double determineFfgDifferenceValue(double precipValue, double ffgValue) - { - - double diffValue = DbTable.getNullDouble(); - - if ( (DbTable.isNull(precipValue)) || (DbTable.isNull(ffgValue)) ) - { - //no good - } - else - { - diffValue = precipValue - ffgValue; - } - - return diffValue; - } - - - // ------------------------------------------------------------------------------------------------------------ - - private void setLatestPrecipForHrMentioned(float hour, TimeValuePair timeValuePair, PrecipData precipData, boolean checkPrevValue) - { - double precipTotal = timeValuePair.getValue(); - - if(precipTotal != _missingDoubleValue) // used since the pdc preprocessor represents missing as -9999.0 - { - if(checkPrevValue) - { - if(precipTotal > precipData.getLatestPrecipByHour(hour)) - precipData.setLatestPrecipByHour(hour, precipTotal); - } - else - precipData.setLatestPrecipByHour(hour, precipTotal); - } - } - - - public void setPdcFileUpdateLongTime(long pdcFileUpdateLongTime) - { - _pdcFileUpdateLongTime = pdcFileUpdateLongTime; - } - - public long getPdcFileUpdateLongTime() - { - return _pdcFileUpdateLongTime; - } - - - //-------------------------------------------------------------------------------- - class NetCdfFileNameFilter implements FilenameFilter - { - String _pattern = "0"; // <---removed the leading underscore "_0" - public NetCdfFileNameFilter(int hour) - { - _pattern += hour+".ffg"; - } - public boolean accept(String name) - { - return name.contains(_pattern); - } - public boolean accept(File arg0, String name) - { - return name.contains(_pattern); - } - public String toString() - { - return _pattern; - } - - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipLocationDataFilter.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipLocationDataFilter.java deleted file mode 100644 index 9ba4df2420..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipLocationDataFilter.java +++ /dev/null @@ -1,59 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.util.BooleanHolder; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class PrecipLocationDataFilter extends LocationDataFilter -{ - - private BooleanHolder _showMissingBooleanHolder = null; - - public PrecipLocationDataFilter(Map locationDisplayMap, BooleanHolder showMissingBooleanHolder) - { - _locationDisplayMap = locationDisplayMap; - _showMissingBooleanHolder = showMissingBooleanHolder; - } - - /** - * Filter the allRowDataList based on the locationDisplayMap - */ - public List filter(List allRowDataList) - { - boolean showMissing = _showMissingBooleanHolder.getValue(); - List filteredRowDataList = new ArrayList(); - - if (_locationDisplayMap != null) - { - for (int i = 0; i < allRowDataList.size(); i++) - { - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData) allRowDataList.get(i); - String lid = rowData.getLid(); - Boolean shouldDisplay = _locationDisplayMap.get(lid); - if ((shouldDisplay != null) && (shouldDisplay) ) //based on selection in the tree - { - if (showMissing) //based on menu selection - { - filteredRowDataList.add(rowData); - } - else //don't show missing - { - if (rowData.getPrecipData().isDataAvailable()) - { - filteredRowDataList.add(rowData); - } - } - } //end if shouldDisplay - } //end for - } - - - return filteredRowDataList; - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipMonitorDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipMonitorDataManager.java deleted file mode 100644 index eed630bae5..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipMonitorDataManager.java +++ /dev/null @@ -1,679 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.awt.Color; -import java.io.FileWriter; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.bsf.BSFEngine; -import org.apache.bsf.BSFManager; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.AdminRecord; -import ohd.hseb.ihfsdb.generated.AdminTable; -import ohd.hseb.ihfsdb.generated.LocRiverMonRecord; -import ohd.hseb.ihfsdb.generated.LocRiverMonView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.rivermonlocgroup.RiverMonLocGroupDataManager; -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.monitor.TreeFilterManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; - -public class PrecipMonitorDataManager -{ - - private Database _db; - - private AppsDefaults _appsDefaults; - - private SessionLogger _logger; - - private String _defaultHsa; - - private Set _precipLidSet = null; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - private List _derivedColumnsList; - private BSFManager _bsfManager; - private BSFEngine _beanShellEngine; - - private String _missingRepresentation; - - private List _precipMonitorRowDataList; - private List _missingPrecipMonitorRowDataList = new ArrayList(); - - private Map _lidDescDetailsMap; - private Map _lidToRiverBasinMap = new HashMap(); - private TreeFilterManager _treeFilterManager; - - private String _lidOfCurrentInterest; - - private PrecipMonitorMenuSettings _menuSettings; - - private RiverMonLocGroupDataManager _riverMonLocGroupDataManager; - private OfficeNotesDataManager _officeNotesDataManager; - private PrecipDataManager _precipDataManager; - - public PrecipMonitorDataManager(Database db, AppsDefaults appsDefaults, String missingRepresentation, - SessionLogger logger, PrecipMonitorMenuSettings menuSettings, - DerivedColumnsFileManager derivedColumnsFileManager) - { - _appsDefaults = appsDefaults; - _menuSettings = menuSettings; - - _db = db; - _missingRepresentation = missingRepresentation; - _logger = logger; - - _precipDataManager = new PrecipDataManager(_db, _appsDefaults, _missingRepresentation, _logger); - readAdminTable(); - - _riverMonLocGroupDataManager = new RiverMonLocGroupDataManager(db, _logger, missingRepresentation, getDefaultHsa()); - - _derivedColumnsFileManager = derivedColumnsFileManager; - - _officeNotesDataManager = new OfficeNotesDataManager(db,_logger, missingRepresentation); - - try - { - initializeBSF(); - } - catch (Exception e) - { - _logger.log("PrecipMonitorDataManager.PrecipMonitorDataManager(): Error while initialize BSF..." + e); - } - } - - public RiverMonLocGroupDataManager getRiverMonLocGroupDataManager() - { - return _riverMonLocGroupDataManager; - } - - public OfficeNotesDataManager getOfficeNotesDataManager() - { - return _officeNotesDataManager; - } - - public TreeFilterManager getTreeFilterManager() - { - if(_treeFilterManager == null) - { - _treeFilterManager = new TreeFilterManager(_logger, getLocationDataFilter()); - } - return _treeFilterManager; - } - - public void setLidOfCurrentInterest(String lid) - { - _lidOfCurrentInterest = lid; - } - - public String getLidOfCurrentInterest() - { - return _lidOfCurrentInterest; - } - - public long getPdcUpdateTime() - { - return _precipDataManager.getPdcFileUpdateLongTime(); - } - - public long getDisplayedRecordCount() - { - String header = "PrecipMonitorDataManager.getDisplayedRecordCount(): "; - printLocationCounts(header + "_precipMonitorRowDataList "); - - - // System.out.println(header + " _precipMonitorRowDataList count = " + _precipMonitorRowDataList.size()); - - List selectedRowDataList = getTreeFilterManager().filter(_precipMonitorRowDataList); - long displayedCount = selectedRowDataList.size(); - - // printLocationCounts(header + " after filter applied "); - - // System.out.println(header + " selectedRowDataList count = " + displayedCount); - - return displayedCount; - - } - - public void disconnect() - { - _db.disconnect(); - } - - public boolean getShowMissing() - { - return _menuSettings.shouldShowMissingPrecip(); - } - - public PrecipColumnDataSettings getPrecipSettings() - { - return _menuSettings.getPrecipSettings(); - } - - private void printLocationCounts(String header) - { - System.out.println(header + "There are " + _precipMonitorRowDataList.size() + - " displayed with " + _missingPrecipMonitorRowDataList.size() + " non-displayed missing locations." ); - - writeLidsToFile(); - - } - - private void writeLidsToFile() - { - FileWriter writer = null; - String whfsBinDir = - this._appsDefaults.getToken("whfs_bin_dir", - HydroappsDefaultDirs.WHFS_BIN_DIR); - - try - { - writer = new FileWriter( - whfsBinDir + "/PrecipMonitorLocations.txt"); - for (PrecipMonitorJTableRowData row : _precipMonitorRowDataList) - { - writer.write(row.getLid() + "\n"); - } - - writer.close(); - } - - catch (IOException e) - { - e.printStackTrace(); - } - - } - - public Map getLidToCriticalColorMap() - { - String header = "PrecipMonitorDataManager.getLidToCriticalColorMap(): "; - - Map lidToCriticalColorMap = new HashMap(); - for(PrecipMonitorJTableRowData rowData : _precipMonitorRowDataList) - { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - for(PrecipMonitorJTableRowData rowData : _missingPrecipMonitorRowDataList) - { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - printLocationCounts(header); - - return lidToCriticalColorMap; - } - - public List getLidList() - { - String header = "PrecipMonitorDataManager.getLidList(): "; - List lidList = new ArrayList(); - for(PrecipMonitorJTableRowData rowData: _precipMonitorRowDataList) - { - String lid = rowData.getLid(); - lidList.add(lid); - } - - System.out.println(header + "_precipMonitorRowDataList.size() = " + _precipMonitorRowDataList.size()); - - return lidList; - } - - - private List getFullListOfLocationIds() - { - List locationIdList = new ArrayList(); - - for (PrecipMonitorJTableRowData rowData : _precipMonitorRowDataList) - { - locationIdList.add(rowData.getLid()); - } - - return locationIdList; - - } - -// --------------------------------------------------------------------------------------------------- - - - private LocationDataFilter getLocationDataFilter() - { - PrecipLocationDataFilter locationDataFilter; - List lidList = getFullListOfLocationIds(); - Map locationDisplayMap = new HashMap(); - - for(String lid:lidList) - { - locationDisplayMap.put(lid, false); - } - - locationDataFilter = new PrecipLocationDataFilter(locationDisplayMap, _menuSettings.getShowMissingPrecipBooleanHolder()); - return locationDataFilter; - } - - private void readAdminTable() - { - AdminTable adminTable = new AdminTable(_db); - List adminList = null; - try - { - adminList = adminTable.select(""); - } - catch (SQLException e) - { - logSQLException(e); - } - _defaultHsa = ((AdminRecord) adminList.get(0)).getHsa(); - } - - protected void readCurrentRiverMonTableData() - { - /** - * Delegate to the RiverMonLocGroupDataManager the initialization of the location and group definitions and ordering. - */ - _riverMonLocGroupDataManager.initializeRiverMonTableData(); - - } - - /** - * Reads the location table and creates the list of PrecipMonitorJtableRowdata objects for each location - * and fills in its name, state , county info - * @return - */ - private List readPrecipLocationInfo() - { - if(_precipLidSet == null) - _precipLidSet = new HashSet (); - else - _precipLidSet.clear(); - - if(_precipMonitorRowDataList != null) - { - for(PrecipMonitorJTableRowData precipMonitorRowData: _precipMonitorRowDataList) - { - precipMonitorRowData.resetCellMap(); - } - _precipMonitorRowDataList.clear(); - } - - Runtime.getRuntime().gc(); - List precipMonitorRowDataList = new ArrayList(); - - LocationTable locationTable = new LocationTable(_db); - - List locationRecordList; - - loadRiverBasinData(); - - try - { - String whereClause = "where lid in (select distinct(lid) from ingestfilter where pe in('PC', 'PP') and ingest='T')"; - locationRecordList = locationTable.select(whereClause); - if(locationRecordList != null) - { - for(LocationRecord locationRecord : locationRecordList) - { - PrecipMonitorJTableRowData precipMonitorRowData = new PrecipMonitorJTableRowData(_missingRepresentation, this, _logger); - - precipMonitorRowData.setLid(locationRecord.getLid()); - precipMonitorRowData.setName(locationRecord.getName()); - precipMonitorRowData.setCounty(locationRecord.getCounty()); - precipMonitorRowData.setState(locationRecord.getState()); - precipMonitorRowData.setHsa(locationRecord.getHsa()); - - setRiverBasinData(precipMonitorRowData); - - precipMonitorRowDataList.add(precipMonitorRowData); - _precipLidSet.add(locationRecord.getLid()); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - return precipMonitorRowDataList; - } - - public List getPrecipMonitorRowDataList() - { - return _precipMonitorRowDataList; - } - - private void loadRiverBasinData() - { - LocationTable table = new LocationTable(_db); - String whereClause = "order by lid"; - List recordList = null; - - _lidToRiverBasinMap.clear(); - try - { - recordList = (List) table.select(whereClause); - for (LocationRecord record : recordList) - { - _lidToRiverBasinMap.put(record.getLid(), record.getRb()); - } - } - catch (SQLException e) - { - - } - - } - - private void setRiverBasinData(PrecipMonitorJTableRowData rowData) - { - String riverBasin = _lidToRiverBasinMap.get(rowData.getLid()); - - rowData.setRiverBasin(riverBasin); - - return; - } - - - public boolean isPrecipLocation(String lid) - { - boolean result = false; - - if(_precipLidSet != null) - { - if(_precipLidSet.contains(lid)) - { - result = true; - } - } - return result; - } - - public void alterPrecipMonitorRowDataListBasedOnMissingPrecipFilter() - { - - _missingPrecipMonitorRowDataList.clear(); - - // _fullPrecipMonitorRowDataList = _precipMonitorRowDataList; - - if(! _menuSettings.shouldShowMissingPrecip() ) // show missing precip is set to false(ie., skip missing precip) - { - System.out.println("Show missing is false"); - List finalPrecipMonitorRowDataList = new ArrayList(); - - for(PrecipMonitorJTableRowData precipMonitorRowData: _precipMonitorRowDataList) - { - PrecipData precipData = precipMonitorRowData.getPrecipData(); - - // precip is available add this lid - if( precipData.isDataAvailable() ) - { - finalPrecipMonitorRowDataList.add(precipMonitorRowData); - } - else - { - _missingPrecipMonitorRowDataList.add(precipMonitorRowData); - } - } - _precipMonitorRowDataList = finalPrecipMonitorRowDataList; - finalPrecipMonitorRowDataList = null; - Runtime.getRuntime().gc(); - } - } - - public void createPrecipMonitorRowDataList() - { - - CodeTimer methodTimer = new CodeTimer(); - methodTimer.start(); - CodeTimer timer = new CodeTimer(); - - - String header = "PrecipMonitorDataManager.createPrecipMonitorRowDataList(): "; - - _logger.log(header +" Memory Info before creating rowdata list:" + printMemoryInfo()); - Runtime.getRuntime().gc(); - - timer.start(); - _precipMonitorRowDataList = readPrecipLocationInfo(); - timer.stop(header + "readPrecipLocationInfo took: "); - - if(_precipMonitorRowDataList != null) - { - timer.start(); - readCurrentRiverMonTableData(); - timer.stop(header + "readCurrentRiverMonTableData took: "); - - _logger.log(header +" 1:" + printMemoryInfo()); - Runtime.getRuntime().gc(); - - timer.start(); - _precipDataManager.readPrecipData(_precipMonitorRowDataList, "PRECIP"); - timer.stop(header + "readPrecipData took: "); - - Runtime.getRuntime().gc(); - _logger.log(header +" 2:" + printMemoryInfo()); - _derivedColumnsList = _derivedColumnsFileManager.getDerivedColumns(); - - timer.start(); - - for(PrecipMonitorJTableRowData precipMonitorRowData: _precipMonitorRowDataList) - { - String groupId = _riverMonLocGroupDataManager.getGroupId(precipMonitorRowData.getLid()); - String groupName = _riverMonLocGroupDataManager.getGroupName(groupId); - int groupOrdinal = _riverMonLocGroupDataManager.getGroupOrdinal(groupId); - //String hsa = _riverMonLocGroupDataManager.getHsa(groupId); - int locationOrdinal = _riverMonLocGroupDataManager.getLocationOrdinal(precipMonitorRowData.getLid()); - - // precipMonitorRowData.setLid(precipMonitorRowData.getLid()); - precipMonitorRowData.setLocationOrdinal(locationOrdinal); - // precipMonitorRowData.setHsa(hsa); - precipMonitorRowData.setGroupName(groupName); - precipMonitorRowData.setGroupId(groupId); - precipMonitorRowData.setGroupOrdinal(groupOrdinal); - - /* _logger.log(precipMonitorRowData.getLid() + "|" + precipMonitorRowData.getName() + "|" - + precipMonitorRowData.getGroupId() + "|" + precipMonitorRowData.getGroupName() + "|" - + precipMonitorRowData.getLocationOrdinal() + "|" - + precipMonitorRowData.getGroupOrdinal() );*/ - - - precipMonitorRowData.addAllCellsToMap(); - - getDerivedColumnsInfo(precipMonitorRowData); - - precipMonitorRowData.addDerivedDataToCellMap(); - - - } - - int count = _precipMonitorRowDataList.size(); - - timer.stop(header + " for loop with " + count + " iterations took: "); - - _logger.log(header + "Before missing precip filter is applied, alllocationinfo list size:" + _precipMonitorRowDataList.size()); - - //timer.start(); - // alterPrecipMonitorRowDataListBasedOnMissingPrecipFilter(); - // timer.stop(header + "alterPrecipMonitorRowDataListBasedOnMissingPrecipFilter took: "); - - _logger.log(header + "After missing precip filter is applied, alllocationinfo list size:" + _precipMonitorRowDataList.size()); - } - Runtime.getRuntime().gc(); - _logger.log(header +" Memory Info after creating rowdata list:" + printMemoryInfo()); - - methodTimer.stop(header + " the whole method took: "); - - } - -// --------------------------------------------------------------------------------------------------- - - public String printMemoryInfo() - { - String str = "Free:" + Runtime.getRuntime().freeMemory()+ " Max:"+ Runtime.getRuntime().maxMemory()+ " total:"+ Runtime.getRuntime().totalMemory(); - return str; - } - - private double roundTo2DecimalPlaces(double number) - { - double result = DbTable.getNullDouble(); - if (number != DbTable.getNullDouble()) - result = MathHelper.roundToNDecimalPlaces(number, 2); - - return result; - } - -// --------------------------------------------------------------------------------------------------- - - private void initializeBSF() throws Exception - { - _bsfManager = new BSFManager(); - BSFManager.registerScriptingEngine("beanshell", "bsh.util.BeanShellBSFEngine", null); - _beanShellEngine = _bsfManager.loadScriptingEngine("beanshell"); - } -// --------------------------------------------------------------------------------------------------- - - protected void getDerivedColumnsInfo(PrecipMonitorJTableRowData precipMonitorRowData) - { - String header = "PrecipMonitorDataManger.getDerivedColumnsInfo():" ; - - if(_derivedColumnsList != null) - { - try - { - _bsfManager.declareBean("row", precipMonitorRowData, PrecipMonitorJTableRowData.class); - _bsfManager.declareBean("precip", precipMonitorRowData.getPrecipData(), PrecipData.class); - - for (int j = _derivedColumnsList.size() - 1; j >= 0; j--) - { - DerivedColumn derivedColumnDesc = (DerivedColumn) _derivedColumnsList.get(j); - String equationForCellValue = ((String) derivedColumnDesc.getEquationForCellValue()); - Object returnValueForCell = _beanShellEngine.eval("rowtest", 1, 1, equationForCellValue); - if (derivedColumnDesc.getReturnType().equalsIgnoreCase("double")) - { - double value = roundTo2DecimalPlaces(Double.parseDouble(returnValueForCell.toString())); - derivedColumnDesc.setvalue(Double.valueOf(value)); - } - else - { - derivedColumnDesc.setvalue(returnValueForCell); - } - - String equationForCellColor = ((String) derivedColumnDesc.getEquationForCellColor()); - Object returnColorForCell = _beanShellEngine.eval("rowtest", 1, 1, equationForCellColor); - if (returnColorForCell != null) - { - derivedColumnDesc.setCellBackgroundColor(returnColorForCell.toString()); - } - else - { - System.out.println(header + " equationForCellColor = " + equationForCellColor + - " returnColorForCell = " + returnColorForCell); - derivedColumnDesc.setCellBackgroundColor("WHITE"); - } - - } - _bsfManager.undeclareBean("row"); - _bsfManager.undeclareBean("precip"); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - precipMonitorRowData.setDerivedColumnsDetailsList(_derivedColumnsList); - } - -// --------------------------------------------------------------------------------------------------- - public List createStringArrayListOfFilterItems() - { - String header = "PrecipMonitorDataManager.createStringArrayListOfFilterItems(): "; - - List locationIdList = getFullListOfLocationIds(); - - List listOfNodePathStringArray = - _riverMonLocGroupDataManager.createStringArrayListOfFilterItems(locationIdList); - - return listOfNodePathStringArray; - } - -// --------------------------------------------------------------------------------------------------- - - public String getDefaultHsa() - { - return _defaultHsa; - } - - - protected void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public Map getLidDescDetails() - { - if (_lidDescDetailsMap == null) - { - LocRiverMonView riverMonView = new LocRiverMonView(_db); - try - { - List riverMonViewList = (List) riverMonView.select(""); - if (riverMonViewList != null) - { - if (riverMonViewList.size() > 0) - { - _lidDescDetailsMap = new HashMap(); - for (int i = 0; i < riverMonViewList.size(); i++) - { - LocRiverMonRecord record = (LocRiverMonRecord) riverMonViewList.get(i); - String name = record.getName(); - if (name != null) - { - if (name.length() > 0) - { - if (name.length() > 50) - { - name = name.substring(0, 50); - } - } - } - String desc = name + ";" + record.getState() + ";" + record.getCounty(); - _lidDescDetailsMap.put(record.getLid(), desc); - } - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - } - return _lidDescDetailsMap; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipMonitorJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipMonitorJTableRowData.java deleted file mode 100644 index 406567b211..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipMonitorJTableRowData.java +++ /dev/null @@ -1,822 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTable; -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.MonitorCell; -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.precip.PrecipData; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.CellType; - -public class PrecipMonitorJTableRowData extends AbstractJTableRowData -{ - private int _defaultDecimalPoints = 2; - - private static Map _derivedReturnTypeToCellTypeMap = new HashMap(); - - private String _groupName; - private String _lid; - private String _name; - private String _county; - private String _state; - private String _hsa; - private String _riverBasin; - private String _groupId; - private int _groupOrdinal; - private int _locationOrdinal; - private double _obsFcstMax; - private SessionLogger _logger; - - protected PrecipMonitorDataManager _precipMonitorDataManager; - - private String _toolTipTextForPrecipThreatSummary; - private List _derivedColumnsDetailsList; - - private PrecipData _precipData; - private PrecipColumnDataSettings _precipSettings; - - static - { - _derivedReturnTypeToCellTypeMap.put("boolean", CellType.BOOLEAN); - _derivedReturnTypeToCellTypeMap.put("double", CellType.DOUBLE); - _derivedReturnTypeToCellTypeMap.put("float", CellType.FLOAT); - _derivedReturnTypeToCellTypeMap.put("long", CellType.LONG); - _derivedReturnTypeToCellTypeMap.put("int", CellType.INTEGER); - _derivedReturnTypeToCellTypeMap.put("string", CellType.STRING); - - } - - public PrecipMonitorJTableRowData(String missingRepresentation, PrecipMonitorDataManager precipMonitorDataManager, - SessionLogger logger) - { - setMissingRepresentation(missingRepresentation); - _logger = logger; - _precipMonitorDataManager = precipMonitorDataManager; - } - - public String getLid() - { - return _lid; - } - - public void setLid(String lid) - { - this._lid = lid ; - } - - public String getName() - { - return _name; - } - - public void setName(String name) - { - this._name = name ; - } - - public String getCounty() - { - return _county; - } - - public void setCounty(String county) - { - this._county = county ; - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - this._state = state ; - } - - public String getHsa() - { - return _hsa; - } - - public void setHsa(String hsa) - { - this._hsa = hsa ; - } - - public String getGroupName() - { - return _groupName; - } - - public void setGroupName(String groupName) - { - this._groupName = groupName ; - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - this._groupId = groupId ; - } - - public int getGroupOrdinal() - { - return _groupOrdinal; - } - - public void setGroupOrdinal(int groupOrdinal) - { - this._groupOrdinal = groupOrdinal ; - } - - public int getLocationOrdinal() - { - return _locationOrdinal; - } - - public void setLocationOrdinal(int locationOrdinal) - { - this._locationOrdinal = locationOrdinal ; - } - - public void setObsFcstMax(double obsFcstMax) - { - this._obsFcstMax = obsFcstMax; - } - - public double getObsFcstMax() - { - return _obsFcstMax; - } - - public PrecipData getPrecipData() - { - return _precipData; - } - - public void setPrecipData(PrecipData precipData) - { - _precipData = precipData; - } - - public void setDerivedColumnsDetailsList(List list) - { - _derivedColumnsDetailsList = list; - } - - public List getDerivedColumnsDetailsList() - { - return _derivedColumnsDetailsList; - } - - - public String getStringValue(long value, long missingValue) - { - String result = super.getStringValue(value, missingValue); - if(result != super.getMissingRepresentation()) - { - String tempStr = result.substring(5, result.length()-3); - tempStr = tempStr.replace('-','/'); - tempStr = tempStr.replace(' ', '-'); - result = tempStr; - } - return result; - } - - public String getToolTipTextForPrecipThreatSummary() - { - return _toolTipTextForPrecipThreatSummary; - } - - public void setToolTipTextForPrecipThreatSummary(String toolTipText) - { - _toolTipTextForPrecipThreatSummary = toolTipText; - } - - public void resetCellMap() - { - super.resetCellMap(); - } - - public void addAllCellsToMap() - { - ThreatLevel defaultThreatLevel = ThreatLevel.NO_THREAT; - String header = "RiverMonitorJTableRowData2.addAllCellsToMap(): "; - - String dateTimeFormatString = "MM/dd - HH:mm"; - - _precipSettings = _precipMonitorDataManager.getPrecipSettings(); - - //static data - - addToCellMap(LocationInfoColumns.GROUP_NAME, CellType.STRING, getGroupName() ); - addToCellMap(LocationInfoColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(LocationInfoColumns.GROUP_ORDINAL, CellType.INTEGER, getGroupOrdinal()); - - addToCellMap(LocationInfoColumns.LOCATION_ID, CellType.STRING, getLid() ); - addToCellMap(LocationInfoColumns.LOCATION_NAME, CellType.STRING, getName() ); - addToCellMap(LocationInfoColumns.LOCATION_ORDINAL, CellType.INTEGER, getLocationOrdinal()); - - addToCellMap(LocationInfoColumns.COUNTY, CellType.STRING, getCounty() ); - addToCellMap(LocationInfoColumns.STATE, CellType.STRING, getState() ); - - addToCellMap(LocationInfoColumns.HSA, CellType.STRING, getHsa() ); - - addToCellMap(LocationInfoColumns.RIVER_BASIN, CellType.STRING, getRiverBasin()); - - addToCellMap(PrecipColumns.LATEST_PRECIP_PARAM_CODE, CellType.STRING, getPrecipData().getLatestPrecipParamCodeString() ); - - addToCellMap(PrecipColumns.LATEST_30MIN, CellType.DOUBLE, getPrecipData().getLatestPrecip30Min()); - addToCellMap(PrecipColumns.LATEST_1HR, CellType.DOUBLE, getPrecipData().getLatestPrecip1Hr(), getThreatLevelForPrecipColumn("LATEST", 1)); - addToCellMap(PrecipColumns.LATEST_3HR, CellType.DOUBLE, getPrecipData().getLatestPrecip3Hr(), getThreatLevelForPrecipColumn("LATEST", 3)); - addToCellMap(PrecipColumns.LATEST_6HR, CellType.DOUBLE, getPrecipData().getLatestPrecip6Hr(), getThreatLevelForPrecipColumn("LATEST", 6)); - addToCellMap(PrecipColumns.LATEST_12HR, CellType.DOUBLE, getPrecipData().getLatestPrecip12Hr()); - addToCellMap(PrecipColumns.LATEST_18HR, CellType.DOUBLE, getPrecipData().getLatestPrecip18Hr()); - addToCellMap(PrecipColumns.LATEST_24HR, CellType.DOUBLE, getPrecipData().getLatestPrecip24Hr()); - - addToCellMap(PrecipColumns.TOH_PRECIP_1HR_PARAM_CODE, CellType.STRING, getPrecipData().getTohPrecip1HrParamCodeString() ); - addToCellMap(PrecipColumns.TOH_PRECIP_1HR, CellType.DOUBLE, getPrecipData().getTohPrecip1Hr(), getThreatLevelForPrecipColumn("TOH", 1)); - - addToCellMap(PrecipColumns.FFG_1HR, CellType.DOUBLE, getPrecipData().getFFG1Hr()); - addToCellMap(PrecipColumns.FFG_3HR, CellType.DOUBLE, getPrecipData().getFFG3Hr()); - addToCellMap(PrecipColumns.FFG_6HR, CellType.DOUBLE, getPrecipData().getFFG6Hr()); - - addToCellMap(PrecipColumns.DIFF_1HR, CellType.DOUBLE, getPrecipData().getDiff1Hr(), getThreatLevelForPrecipColumn("DIFF", 1)); - addToCellMap(PrecipColumns.DIFF_3HR, CellType.DOUBLE, getPrecipData().getDiff3Hr(), getThreatLevelForPrecipColumn("DIFF", 3)); - addToCellMap(PrecipColumns.DIFF_6HR, CellType.DOUBLE, getPrecipData().getDiff6Hr(), getThreatLevelForPrecipColumn("DIFF", 6)); - - addToCellMap(PrecipColumns.RATIO_1HR, CellType.INTEGER, getPrecipData().getRatio1Hr(), getThreatLevelForPrecipColumn("RATIO", 1)); - addToCellMap(PrecipColumns.RATIO_3HR, CellType.INTEGER, getPrecipData().getRatio3Hr(), getThreatLevelForPrecipColumn("RATIO", 3)); - addToCellMap(PrecipColumns.RATIO_6HR, CellType.INTEGER, getPrecipData().getRatio6Hr(), getThreatLevelForPrecipColumn("RATIO", 6)); - - ThreatLevel threatLevel = getThreatLevelForPrecipThreatSummary(); - addToCellMap(PrecipColumns.PRECIP_THREAT, CellType.EXTENSION, - getPrecipThreatSummary(), threatLevel, - getMissingRepresentation()); - - } //end addAllCellsToMap - - // ----------------------------------------------------------------------------------- - - public double round(double value, int decimalPlacesToMaintain) - { - return MathHelper.roundToNDecimalPlaces(value, decimalPlacesToMaintain); - } - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value) - { - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, getMissingRepresentation()); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, Color cellBackgroundColor) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, cellBackgroundColor, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } -// ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, missingRepresentation, _defaultDecimalPoints); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel,Color cellBackgroundColor, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, cellBackgroundColor, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - String dateFormatString) - { - - MonitorCell cell = new MonitorCell (columnName, cellType, value, threatLevel, - missingRepresentation, dateFormatString); - - - // addToCellMap(cell); - addCell(cell); - - - return cell; - } - - // ----------------------------------------------------------------------------------- - - protected void addDerivedDataToCellMap() - { - // add all derived columns as well - List derivedColumnsDetailsList = this.getDerivedColumnsDetailsList(); - for(int i=0 ; i < derivedColumnsDetailsList.size(); i++) - { - DerivedColumn desc1 = (DerivedColumn) derivedColumnsDetailsList.get(i); - - CellType cellType = getCellTypeFromReturnType(desc1.getReturnType()); - - addToCellMap(desc1.getColumnName(), cellType, desc1.getValue(), desc1.getCellBackgroundColor()); - } - } - // ----------------------------------------------------------------------------------- - - private CellType getCellTypeFromReturnType(String derivedColumnReturnType) - { - CellType cellType = null; - - cellType = (CellType) _derivedReturnTypeToCellTypeMap.get(derivedColumnReturnType.toLowerCase()); - - return cellType; - } - - - public Color getCellBackgroundColor(String columnName) - { - Color color = Color.white; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellBackgroundColor(); - } - - return color; - } - - // ----------------------------------------------------------------------------------- - - public Color getCellForegroundColor(String columnName) - { - Color color = Color.black; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellForegroundColor(); - } - return color; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getPrecipMonitorThreatLevel() - { - //Find the max threat levels for all cells in this row - ThreatLevel maxCellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = new ArrayList( getCellMap().values()); - maxCellThreatLevel = getMaxRowThreatLevel(cellList); - - ThreatLevel rowThreatLevel = maxCellThreatLevel; - - //If the rowThreatLevel == missing, we want to make sure that ALL of the important columns have missing data. - //If there is any data in these columns, then we want to use NO_THREAT - if (rowThreatLevel == ThreatLevel.MISSING_DATA) - { - if (_precipData.isDataAvailable()) - { - rowThreatLevel = ThreatLevel.NO_THREAT; - } - } - - return rowThreatLevel; - } - // helper methods - - // ----------------------------------------------------------------------------------- - public Color getCriticalColorForThisRow() - { - Color color = Color.WHITE; - ThreatLevel level = getPrecipMonitorThreatLevel(); - if(level == ThreatLevel.ALERT) - { - color = Color.RED; - } - else if(level == ThreatLevel.CAUTION) - { - color = Color.YELLOW; - } - else if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - color = Color.GRAY; - } - - return color; - } - - // ----------------------------------------------------------------------------------- - public ThreatLevel getThreatLevelForPrecipThreatSummary() - { - ThreatLevel level = getPrecipThreatLevelForPrecipThreatSummary(); - - //Threat cell should be color red/yellow/white. So skip threat aged / missing threat level - if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - - return level; - } - -// ----------------------------------------------------------------------------------- - public ThreatLevel getMaxRowThreatLevel(List cellList) - { - //this method assumes that the threat column has not yet been added to the cell map, when this - // method is invoked - ThreatLevel level = ThreatLevel.NO_THREAT; - ThreatLevel maxLevel = ThreatLevel.ALERT; - - //make sure the threat cell's threat level does not get used to calculate row's threat level, so clear it to zero - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - //iterate through each cell, and set the level to the max threat level found - for (int i = 0; i < cellList.size(); i++) - { - - MonitorCell cell = (MonitorCell) cellList.get(i); - - if (cell == null) - { - continue; - } - else - { - cellThreatLevel = cell.getThreatLevel(); - - if (cellThreatLevel.isGreater(level)) - { - level = cellThreatLevel; - if (level == maxLevel) - { - break; //quit looking, because we have determined it is maxed out - } - } - } - } - return level; - } - // ----------------------------------------------------------------------------------- - - - public List getPrecipCells() - { - List cellList = new ArrayList(); - - addCell(cellList, PrecipColumns.LATEST_30MIN); - addCell(cellList, PrecipColumns.LATEST_1HR); - addCell(cellList, PrecipColumns.LATEST_3HR ); - addCell(cellList, PrecipColumns.LATEST_6HR ); - - addCell(cellList, PrecipColumns.TOH_PRECIP_1HR ); - - addCell(cellList, PrecipColumns.DIFF_1HR ); - addCell(cellList, PrecipColumns.DIFF_3HR ); - addCell(cellList, PrecipColumns.DIFF_6HR ); - - addCell(cellList, PrecipColumns.RATIO_1HR ); - addCell(cellList, PrecipColumns.RATIO_3HR ); - addCell(cellList, PrecipColumns.RATIO_6HR ); - - return cellList; - } - - // ----------------------------------------------------------------------------------- - - private void addCell(List cellList, String columnName ) - { - MonitorCell cell = null; - - cell = (MonitorCell) getCellMap().get(columnName); - if(cell != null) - { - cellList.add(cell); - } - - return; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getPrecipThreatLevelForPrecipThreatSummary() - { - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = getPrecipCells(); - cellThreatLevel = getMaxRowThreatLevel(cellList); - - return cellThreatLevel; - } - //-------------------------------------------------------------------------------------- - /* - * Returns true if the data is aged, by checking the time with earliestAcceptableTime - */ - protected boolean isDataAged(long time, long earliestAcceptableTime) - { - boolean result = false; - - if (time < earliestAcceptableTime) - { - result = true; - } - - return result; - } - - private ThreatLevel getPrecipThreatLevel(double value, double alert, double caution) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(! DbTable.isNull(value)) - { - if(value >= alert) - level = ThreatLevel.ALERT; - else if(value >= caution) - level = ThreatLevel.CAUTION; - } - else //value isNull() - { - level = ThreatLevel.MISSING_DATA; - } - - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipValueThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings, String type) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double missing = DbTable.getNullDouble(); - double value; - switch(hour) - { - - case 1: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip1Hr(); - else - value = _precipData.getTohPrecip1Hr(); - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert1Hr(), precipSettings.getPrecipCaution1Hr()); - break; - - case 3: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip3Hr(); - else - // value = _precipData.getTohPrecip3Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert3Hr(), precipSettings.getPrecipCaution3Hr()); - break; - case 6: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip6Hr(); - else - //value = _precipData.getTohPrecip6Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert6Hr(), precipSettings.getPrecipCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipRatioThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - int value; - switch(hour) - { - - case 1: - value = _precipData.getRatio1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert1Hr(), precipSettings.getRatioCaution1Hr()); - break; - case 3: - value = _precipData.getRatio3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert3Hr(), precipSettings.getRatioCaution6Hr()); - break; - case 6: - value = _precipData.getRatio6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert6Hr(), precipSettings.getRatioCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipDiffThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double value; - - switch(hour) - { - case 1: - value = _precipData.getDiff1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert1Hr(), precipSettings.getDiffCaution1Hr()); - break; - case 3: - value = _precipData.getDiff3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert3Hr(), precipSettings.getDiffCaution3Hr()); - break; - case 6: - value = _precipData.getDiff6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert6Hr(), precipSettings.getDiffCaution6Hr()); - break; - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForPrecipColumn(String type, int hour) - { - - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(type.compareTo("LATEST") == 0) // LATEST precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _precipSettings, "LATEST"); - } - else if(type.compareTo("TOH") == 0) // toh precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _precipSettings, "TOH"); - } - else if(type.compareTo("RATIO") == 0) - { - level = getPrecipRatioThreatLevelForHrMentioned(hour, _precipSettings); - } - else //type is DIFF - { - level = getPrecipDiffThreatLevelForHrMentioned(hour, _precipSettings); - } - return level; - } - - -// ------------------------------------------------------------------------------------- - - public ThreatLevel getCellThreatLevelForColumn(String columnName) - { - // String header = "PrecipMonitorJTableRowData.getCellThreatLevelForColumn(): "; - ThreatLevel level; - - MonitorCell cell = (MonitorCell) getCellMap().get(columnName); - - // System.out.println(header + "columnName = " + columnName); - - level = cell.getThreatLevel(); - - return level; - } - -// ------------------------------------------------------------------------------------- - - - public String getPrecipThreatSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - - ThreatLevel level; - ThreatLevel level1Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_1HR); - ThreatLevel level3Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_3HR); - ThreatLevel level6Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("L"); - toolTipStringBuffer.append("L: Latest Precip Exceeded the threshold
    "); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_1HR); - // level3Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_3HR); - // level6Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_6HR); - if ( - ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) - /* || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) - */ - ) - { - summaryStringBuffer = summaryStringBuffer.append("T"); - toolTipStringBuffer.append("T: Top Of The Hour Precip Exceeded the threshold
    "); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("D"); - toolTipStringBuffer.append("D: Latest Precip - FFG Difference Exceeded the threshold
    "); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("R"); - toolTipStringBuffer.append("R: Latest Precip / FFG Ratio Exceeded the threshold
    "); - } - - summary = summaryStringBuffer.toString(); - _toolTipTextForPrecipThreatSummary = toolTipStringBuffer.toString(); - return summary; - } -// ------------------------------------------------------------------------------------- - - public void setRiverBasin(String riverBasin) - { - _riverBasin = riverBasin; - } - - public String getRiverBasin() - { - return _riverBasin; - } - -} //end class - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipThresholdDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipThresholdDialog.java deleted file mode 100644 index d980149525..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/PrecipThresholdDialog.java +++ /dev/null @@ -1,392 +0,0 @@ -package ohd.hseb.monitor.precip; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import javax.swing.border.TitledBorder; - -import ohd.hseb.db.DbTable; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.WindowResizingManager; - -public class PrecipThresholdDialog extends JDialog -{ - private JSpinner _precipAlert1HrSpinBox ; - private JSpinner _precipAlert3HrSpinBox ; - private JSpinner _precipAlert6HrSpinBox ; - - private JSpinner _precipCaution1HrSpinBox ; - private JSpinner _precipCaution3HrSpinBox ; - private JSpinner _precipCaution6HrSpinBox ; - - private JSpinner _ratioAlert1HrSpinBox ; - private JSpinner _ratioAlert3HrSpinBox ; - private JSpinner _ratioAlert6HrSpinBox ; - - private JSpinner _ratioCaution1HrSpinBox ; - private JSpinner _ratioCaution3HrSpinBox ; - private JSpinner _ratioCaution6HrSpinBox ; - - private JSpinner _diffAlert1HrSpinBox ; - private JSpinner _diffAlert3HrSpinBox ; - private JSpinner _diffAlert6HrSpinBox ; - - private JSpinner _diffCaution1HrSpinBox ; - private JSpinner _diffCaution3HrSpinBox ; - private JSpinner _diffCaution6HrSpinBox ; - - private JButton _applyButton; - private JButton _closeButton; - - private SessionLogger _logger; - - private PrecipColumnDataSettings _prevMenuSettings = null; - private PrecipColumnDataSettings _savedMenuSettings = null; - - public PrecipThresholdDialog( JFrame mainFrame, PrecipColumnDataSettings menuSettings, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - _prevMenuSettings = menuSettings; - createPrecipSettingsDialog(); - } - - public void setMenuSettingsForDialog(PrecipColumnDataSettings menuSettings) - { - _prevMenuSettings = menuSettings; - createPrecipSettingsDialog(); - } - - public PrecipColumnDataSettings showPrecipThresholdDialog() - { - _savedMenuSettings = null; - this.setVisible(true); - return _savedMenuSettings; - } - - public void createPrecipSettingsDialog() - { - JPanel precipPanel = new JPanel(new GridBagLayout()); - TitledBorder precipTitledBorder = BorderFactory.createTitledBorder("Precip Threshold"); - precipPanel.setBorder(precipTitledBorder); - precipPanel.setToolTipText("Applied to 1hr, 3hr, 6hr Latest Precip and TOH Precip"); - - if(_prevMenuSettings == null) - { - _prevMenuSettings = new PrecipColumnDataSettings(); - } - - JLabel precip1HrLabel = new JLabel("1 Hr"); - precip1HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel precip3HrLabel = new JLabel("3 Hr"); - precip3HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel precip6HrLabel = new JLabel("6 Hr"); - precip6HrLabel.setPreferredSize(new Dimension(40, 30)); - - JPanel precipLabelPanel = new JPanel(); - precipLabelPanel.setPreferredSize(new Dimension(150, 40)); - precipLabelPanel.add(precip1HrLabel); - precipLabelPanel.add(precip3HrLabel); - precipLabelPanel.add(precip6HrLabel); - - //initial value, min value, max value, incr value - _precipAlert1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipAlert1Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_1HR, 0.01)); - _precipAlert1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipAlert3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipAlert3Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_3HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_3HR, 0.01)); - _precipAlert3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipAlert6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipAlert6Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_6HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_6HR, 0.01)); - _precipAlert6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel precipAlertPanel = new JPanel(); - precipAlertPanel.setPreferredSize(new Dimension(150, 40)); - precipAlertPanel.add(_precipAlert1HrSpinBox); - precipAlertPanel.add(_precipAlert3HrSpinBox); - precipAlertPanel.add(_precipAlert6HrSpinBox); - - _precipCaution1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipCaution1Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_1HR, 0.01)); - _precipCaution1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipCaution3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipCaution3Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_3HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_3HR, 0.01)); - _precipCaution3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _precipCaution6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getPrecipCaution6Hr(), PrecipColumnDataSettings.DEFAULT_PRECIP_MIN_THRESHOLD_6HR,PrecipColumnDataSettings.DEFAULT_PRECIP_MAX_THRESHOLD_6HR, 0.01)); - _precipCaution6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel precipCautionPanel = new JPanel(); - precipCautionPanel.setPreferredSize(new Dimension(150, 40)); - precipCautionPanel.add(_precipCaution1HrSpinBox); - precipCautionPanel.add(_precipCaution3HrSpinBox); - precipCautionPanel.add(_precipCaution6HrSpinBox); - - JPanel precipDummyPanel = new JPanel(); - precipDummyPanel.setPreferredSize(new Dimension(150, 10)); - ComponentHelper.addPanelComponent(precipPanel, precipLabelPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(precipPanel, precipAlertPanel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(precipPanel, precipDummyPanel, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(precipPanel, precipCautionPanel, 0, 3, 1, 1, 1); - - JPanel ratioPanel = new JPanel(new GridBagLayout()); - TitledBorder ratioTitledBorder = BorderFactory.createTitledBorder("Ratio(%) Threshold"); - ratioPanel.setBorder(ratioTitledBorder); - ratioPanel.setToolTipText("Applied to ((Latest Precip / FFG) * 100) columns"); - - JLabel ratio1HrLabel = new JLabel("1 Hr"); - ratio1HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel ratio3HrLabel = new JLabel("3 Hr"); - ratio3HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel ratio6HrLabel = new JLabel("6 Hr"); - ratio6HrLabel.setPreferredSize(new Dimension(40, 30)); - - JPanel ratioLabelPanel = new JPanel(); - ratioLabelPanel.setPreferredSize(new Dimension(150, 40)); - ratioLabelPanel.add(ratio1HrLabel); - ratioLabelPanel.add(ratio3HrLabel); - ratioLabelPanel.add(ratio6HrLabel); - - // initial value, min value, max value, incr value - _ratioAlert1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioAlert1Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioAlert1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioAlert3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioAlert3Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioAlert3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioAlert6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioAlert6Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioAlert6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel ratioAlertPanel = new JPanel(); - ratioAlertPanel.setPreferredSize(new Dimension(150, 40)); - ratioAlertPanel.add(_ratioAlert1HrSpinBox); - ratioAlertPanel.add(_ratioAlert3HrSpinBox); - ratioAlertPanel.add(_ratioAlert6HrSpinBox); - - // initial value, min value, max value, incr value - _ratioCaution1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioCaution1Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioCaution1HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioCaution3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioCaution3Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioCaution3HrSpinBox.setPreferredSize(new Dimension(45, 30)); - _ratioCaution6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getRatioCaution6Hr(), PrecipColumnDataSettings.DEFAULT_RATIO_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_RATIO_MAX_THRESHOLD_1HR, 1)); - _ratioCaution6HrSpinBox.setPreferredSize(new Dimension(45, 30)); - - JPanel ratioCautionPanel = new JPanel(); - ratioCautionPanel.setPreferredSize(new Dimension(150, 40)); - ratioCautionPanel.add(_ratioCaution1HrSpinBox); - ratioCautionPanel.add(_ratioCaution3HrSpinBox); - ratioCautionPanel.add(_ratioCaution6HrSpinBox); - - JPanel ratioDummyPanel = new JPanel(); - ratioDummyPanel.setPreferredSize(new Dimension(150, 10)); - ComponentHelper.addPanelComponent(ratioPanel, ratioLabelPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(ratioPanel, ratioAlertPanel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(ratioPanel, ratioDummyPanel, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(ratioPanel, ratioCautionPanel, 0, 3, 1, 1, 1); - - JPanel diffPanel = new JPanel(new GridBagLayout()); - TitledBorder diffTitledBorder = BorderFactory.createTitledBorder("Diff Threshold"); - diffPanel.setBorder(diffTitledBorder); - diffPanel.setToolTipText("Applied to (Latest Precip - FFG) columns"); - - JLabel diff1HrLabel = new JLabel("1 Hr"); - diff1HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel diff3HrLabel = new JLabel("3 Hr"); - diff3HrLabel.setPreferredSize(new Dimension(40, 30)); - JLabel diff6HrLabel = new JLabel("6 Hr"); - diff6HrLabel.setPreferredSize(new Dimension(40, 30)); - - JPanel diffLabelPanel = new JPanel(); - diffLabelPanel.setPreferredSize(new Dimension(150, 40)); - diffLabelPanel.add(diff1HrLabel); - diffLabelPanel.add(diff3HrLabel); - diffLabelPanel.add(diff6HrLabel); - - // initial value, min value, max value, incr value - _diffAlert1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffAlert1Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffAlert1HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffAlert3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffAlert3Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffAlert3HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffAlert6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffAlert6Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffAlert6HrSpinBox.setPreferredSize(new Dimension(55, 30)); - - JPanel diffAlertPanel = new JPanel(); - diffAlertPanel.setPreferredSize(new Dimension(180, 40)); - diffAlertPanel.add(_diffAlert1HrSpinBox); - diffAlertPanel.add(_diffAlert3HrSpinBox); - diffAlertPanel.add(_diffAlert6HrSpinBox); - - _diffCaution1HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffCaution1Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffCaution1HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffCaution3HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffCaution3Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffCaution3HrSpinBox.setPreferredSize(new Dimension(55, 30)); - _diffCaution6HrSpinBox = new JSpinner(new SpinnerNumberModel(_prevMenuSettings.getDiffCaution6Hr(), PrecipColumnDataSettings.DEFAULT_DIFF_MIN_THRESHOLD_1HR,PrecipColumnDataSettings.DEFAULT_DIFF_MAX_THRESHOLD_1HR, 0.05)); - _diffCaution6HrSpinBox.setPreferredSize(new Dimension(55, 30)); - - JPanel diffCautionPanel = new JPanel(); - diffCautionPanel.setPreferredSize(new Dimension(180, 40)); - diffCautionPanel.add(_diffCaution1HrSpinBox); - diffCautionPanel.add(_diffCaution3HrSpinBox); - diffCautionPanel.add(_diffCaution6HrSpinBox); - - JPanel diffDummyPanel = new JPanel(); - diffDummyPanel.setPreferredSize(new Dimension(180, 10)); - ComponentHelper.addPanelComponent(diffPanel, diffLabelPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(diffPanel, diffAlertPanel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(diffPanel, diffDummyPanel, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(diffPanel, diffCautionPanel, 0, 3, 1, 1, 1); - - JLabel alertLabel = new JLabel("Alert :"); - alertLabel.setOpaque(true); - alertLabel.setBackground(Color.RED); - JLabel cautionLabel = new JLabel("Caution :"); - cautionLabel.setOpaque(true); - cautionLabel.setBackground(Color.YELLOW); - - JPanel alertCautionPanel = new JPanel(new GridBagLayout()); - - JPanel dummyPanel1 = new JPanel(); - dummyPanel1.setPreferredSize(new Dimension(60, 40)); - - alertLabel.setPreferredSize(new Dimension(60, 40)); - - JPanel dummyPanel2 = new JPanel(); - dummyPanel2.setPreferredSize(new Dimension(60, 10)); - - cautionLabel.setPreferredSize(new Dimension(60, 40)); - - ComponentHelper.addPanelComponent(alertCautionPanel, dummyPanel1, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(alertCautionPanel, alertLabel, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(alertCautionPanel, dummyPanel2, 0, 2, 1, 1, 1); - ComponentHelper.addPanelComponent(alertCautionPanel, cautionLabel, 0, 3, 1, 1, 1); - - JPanel thresholdPanel = new JPanel(new GridBagLayout()); - ComponentHelper.addPanelComponent(thresholdPanel, alertCautionPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(thresholdPanel, precipPanel, 1, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(thresholdPanel, ratioPanel, 2, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(thresholdPanel, diffPanel, 3, 0, 1, 1, 1); - - JPanel buttonPanel = new JPanel(new GridBagLayout()); - - JPanel dummyPanel3 = new JPanel(); - dummyPanel3.setPreferredSize(new Dimension(20,20)); - - _closeButton = new JButton("Close"); - _applyButton = new JButton ("Apply"); - _applyButton.addActionListener(new ApplyMenuSettingsListener()); - _closeButton.addActionListener(new ClosePrecipSettingsDialogListener()); - - ComponentHelper.addPanelComponent(buttonPanel, _applyButton, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(buttonPanel, dummyPanel3, 1, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(buttonPanel, _closeButton, 2, 0, 1, 1, 1); - - JPanel dummyPanel5 = new JPanel(); - dummyPanel5.setPreferredSize(new Dimension(200,40)); - - JPanel outerPanel = new JPanel(new GridBagLayout()); - ComponentHelper.addPanelComponent(outerPanel, thresholdPanel, 0, 0, 1, 1, 1); - ComponentHelper.addPanelComponent(outerPanel, dummyPanel5, 0, 1, 1, 1, 1); - ComponentHelper.addPanelComponent(outerPanel, buttonPanel, 0, 2, 1, 1, 1); - - this.getContentPane().add(outerPanel); - this.setLocation(25, 25); - Dimension dim = new Dimension(600,450); - new WindowResizingManager(this, dim, dim); - - this.pack(); - this.setTitle("Precip Alert/Caution Threshold Values"); - } - - private void closePrecipSettingsDialog() - { - this.setVisible(false); - this.dispose(); - } - -// --------------------------------------------------------------------------------------------------- - - private double roundTo2DecimalPlaces(double number) - { - double result = DbTable.getNullDouble(); - if (number != DbTable.getNullDouble()) - result = MathHelper.roundToNDecimalPlaces(number, 2); - - return result; - } - - private PrecipColumnDataSettings getPrecipSettingsFromDialog() - { - PrecipColumnDataSettings menuSettings = new PrecipColumnDataSettings(); - - menuSettings.setPrecipAlert1Hr(roundTo2DecimalPlaces((Double)_precipAlert1HrSpinBox.getValue())); - menuSettings.setPrecipAlert3Hr(roundTo2DecimalPlaces((Double)_precipAlert3HrSpinBox.getValue())); - menuSettings.setPrecipAlert6Hr(roundTo2DecimalPlaces((Double)_precipAlert6HrSpinBox.getValue())); - menuSettings.setPrecipCaution1Hr(roundTo2DecimalPlaces((Double)_precipCaution1HrSpinBox.getValue())); - menuSettings.setPrecipCaution3Hr(roundTo2DecimalPlaces((Double)_precipCaution3HrSpinBox.getValue())); - menuSettings.setPrecipCaution6Hr(roundTo2DecimalPlaces((Double)_precipCaution6HrSpinBox.getValue())); - - menuSettings.setRatioAlert1Hr((Integer)_ratioAlert1HrSpinBox.getValue()); - menuSettings.setRatioAlert3Hr((Integer)_ratioAlert3HrSpinBox.getValue()); - menuSettings.setRatioAlert6Hr((Integer)_ratioAlert6HrSpinBox.getValue()); - menuSettings.setRatioCaution1Hr((Integer)_ratioCaution1HrSpinBox.getValue()); - menuSettings.setRatioCaution3Hr((Integer)_ratioCaution3HrSpinBox.getValue()); - menuSettings.setRatioCaution6Hr((Integer)_ratioCaution6HrSpinBox.getValue()); - - menuSettings.setDiffAlert1Hr(roundTo2DecimalPlaces((Double)_diffAlert1HrSpinBox.getValue())); - menuSettings.setDiffAlert3Hr(roundTo2DecimalPlaces((Double)_diffAlert3HrSpinBox.getValue())); - menuSettings.setDiffAlert6Hr(roundTo2DecimalPlaces((Double)_diffAlert6HrSpinBox.getValue())); - menuSettings.setDiffCaution1Hr(roundTo2DecimalPlaces((Double)_diffCaution1HrSpinBox.getValue())); - menuSettings.setDiffCaution3Hr(roundTo2DecimalPlaces((Double)_diffCaution3HrSpinBox.getValue())); - menuSettings.setDiffCaution6Hr(roundTo2DecimalPlaces((Double)_diffCaution6HrSpinBox.getValue())); - - return menuSettings; - } - - private class ApplyMenuSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - PrecipColumnDataSettings currentMenuSettings = getPrecipSettingsFromDialog(); - - if( (_prevMenuSettings.getPrecipAlert1Hr() != currentMenuSettings.getPrecipAlert1Hr()) || - (_prevMenuSettings.getPrecipAlert3Hr() != currentMenuSettings.getPrecipAlert3Hr()) || - (_prevMenuSettings.getPrecipAlert6Hr() != currentMenuSettings.getPrecipAlert6Hr()) || - (_prevMenuSettings.getRatioAlert1Hr() != currentMenuSettings.getRatioAlert1Hr()) || - (_prevMenuSettings.getRatioAlert3Hr() != currentMenuSettings.getRatioAlert3Hr()) || - (_prevMenuSettings.getRatioAlert6Hr() != currentMenuSettings.getRatioAlert6Hr()) || - (_prevMenuSettings.getDiffAlert1Hr() != currentMenuSettings.getDiffAlert1Hr()) || - (_prevMenuSettings.getDiffAlert3Hr() != currentMenuSettings.getDiffAlert3Hr()) || - (_prevMenuSettings.getDiffAlert6Hr() != currentMenuSettings.getDiffAlert6Hr()) || - (_prevMenuSettings.getPrecipCaution1Hr() != currentMenuSettings.getPrecipCaution1Hr()) || - (_prevMenuSettings.getPrecipCaution3Hr() != currentMenuSettings.getPrecipCaution3Hr()) || - (_prevMenuSettings.getPrecipCaution6Hr() != currentMenuSettings.getPrecipCaution6Hr()) || - (_prevMenuSettings.getRatioCaution1Hr() != currentMenuSettings.getRatioCaution1Hr()) || - (_prevMenuSettings.getRatioCaution3Hr() != currentMenuSettings.getRatioCaution3Hr()) || - (_prevMenuSettings.getRatioCaution6Hr() != currentMenuSettings.getRatioCaution6Hr()) || - (_prevMenuSettings.getDiffCaution1Hr() != currentMenuSettings.getDiffCaution1Hr()) || - (_prevMenuSettings.getDiffCaution3Hr() != currentMenuSettings.getDiffCaution3Hr()) || - (_prevMenuSettings.getDiffCaution6Hr() != currentMenuSettings.getDiffCaution6Hr())) - { - _prevMenuSettings = currentMenuSettings; - _savedMenuSettings = currentMenuSettings; - _logger.log("PrecipThresholdDialog.ApplyMenuSettingsListener : New precip settings applied"); - } - } - } - - private class ClosePrecipSettingsDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closePrecipSettingsDialog(); - } - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorAppManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorAppManager.java deleted file mode 100644 index ccf74e994a..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorAppManager.java +++ /dev/null @@ -1,220 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Graphics; -import java.awt.GridBagLayout; - -import javax.swing.JPanel; -import javax.swing.JSplitPane; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.db.Database; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorSplitPane; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.MemoryLogger; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; - -public class PrecipMonitorAppManager -{ - private MessageSystemManager _msgSystemManager; - - private PrecipMonitorDataManager _precipMonitorDataManager; - - private AppsDefaults _appsDefaults; - - public static final String DEFAULT_PRECIP_SETTINGS_FILE = "DefaultPrecipMonitorSettings.txt"; - public static final String SITE_PRECIP_SETTINGS_FILE = "PrecipMonitorSettings.txt"; - - private SessionLogger _logger; - private MonitorFrame _mainFrame; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private String _appName = "PrecipMonitor"; - - public static String DERIVED_COLUMNS_FILE = "PrecipDerivedColumns.txt"; - - public PrecipMonitorAppManager(Database db, String missingRepresentation, String version, String versionDate, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) - { - _appsDefaults = new AppsDefaults(); - - createLogger(); - - ViewSettings viewSettings = new ViewSettings(); - FilterSettings filterSettings = new FilterSettings(); - PrecipMonitorMenuSettings menuSettings = new PrecipMonitorMenuSettings(); - - createFrame(db, version); - - JSplitPane splitPane = new MonitorSplitPane(JSplitPane.HORIZONTAL_SPLIT, true); - - JPanel timeDisplayPanel = new JPanel(); - JToolBar toolBar = new JToolBar(); - - OfficeNotesDataManager officeNotesDataMgr = new OfficeNotesDataManager(db,_logger, missingRepresentation); - AlertAlarmDataManager alertAlarmDataMgr = new AlertAlarmDataManager(db, _logger, missingRepresentation); - - String settingsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - _derivedColumnsFileManager = new DerivedColumnsFileManager(settingsDir + "/" + DERIVED_COLUMNS_FILE, _logger); - - MemoryLogger.setLogger(_logger); - _precipMonitorDataManager = new PrecipMonitorDataManager(db, _appsDefaults, missingRepresentation, - _logger, menuSettings, _derivedColumnsFileManager); - - _msgSystemManager = new MessageSystemManager(); - - - //These objects remain in without a variable, because they register listeners to the _msgSystemManager - new PrecipMonitorRefreshManager(_msgSystemManager, _logger, _precipMonitorDataManager, splitPane); - - new PrecipMonitorFilterManager(_msgSystemManager, _logger, _mainFrame, _precipMonitorDataManager, splitPane, _appsDefaults, filterSettings); - - new PrecipMonitorMenuManager(_msgSystemManager, _logger, _mainFrame, version, versionDate, _appsDefaults, - toolBar, _precipMonitorDataManager, officeNotesDataMgr,alertAlarmDataMgr, menuSettings, - timeDisplayPanel, _appName, monitorTimeSeriesLiteManager); - - new PrecipMonitorViewManager(_mainFrame, _msgSystemManager, _logger, _precipMonitorDataManager, splitPane, - viewSettings, _derivedColumnsFileManager, monitorTimeSeriesLiteManager, _appsDefaults); - - PrecipMonitorSettingsManager settingsManager = new PrecipMonitorSettingsManager(_msgSystemManager, _appsDefaults, _logger, _mainFrame, viewSettings, - filterSettings, menuSettings); - - settingsManager.startPrecipMonitor(); - - Container frameContentPane = _mainFrame.getContentPane(); - _mainFrame.setLayout(new GridBagLayout()); - - - //col, row, width, height, weightx, weighty, fill - ComponentHelper.addFrameComponent(frameContentPane, - toolBar, 0, 0, 1, 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, - timeDisplayPanel, 1, 0, 1, 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, - splitPane, 0, 1, 2, 1, 1, 1, 1); - - - _mainFrame.pack(); - _mainFrame.setVisible(true); - } - - private class MonitorJSplitPane extends JSplitPane - { - - - - public MonitorJSplitPane (int newOrientation, - boolean newContinuousLayout) - { - super(newOrientation, newContinuousLayout); - } - - public void setDividerLocation(int location) - { - int currentDividerLocation = getDividerLocation(); - int adjustedLocation = location; - - - if (location < 30 ) - { - int difference = currentDividerLocation - location; - if (difference > 50) - { - adjustedLocation = currentDividerLocation; - } - } - super.setDividerLocation(adjustedLocation); - } - - public void setRightComponent(Component comp) - { - String header = "MonitorJSplitPane.setRightComponent() "; - - int beforeDividerLocation = getDividerLocation(); - - // setDividerLocation(beforeDividerLocation); - super.setRightComponent(comp); - - int afterDividerLocation = getDividerLocation(); - - setDividerLocation(beforeDividerLocation); - - System.out.println(header + " before divider location = " + beforeDividerLocation); - System.out.println(header + " after divider location = " + afterDividerLocation); - - } - - public void setLeftComponent(Component comp) - { - String header = "MonitorJSplitPane.setLeftComponent() "; - - int beforeDividerLocation = getDividerLocation(); - setDividerLocation(beforeDividerLocation); - - super.setLeftComponent(comp); - - int afterDividerLocation = getDividerLocation(); - - setDividerLocation(beforeDividerLocation); - - System.out.println(header + " before divider location = " + beforeDividerLocation); - System.out.println(header + " after divider location = " + afterDividerLocation); - - } - - - public void paint(Graphics g) - { - String header = "MonitorJSplitPane.paint() "; - super.paint(g); - - int dividerLocation = getDividerLocation(); - int lastDividerLocation = getLastDividerLocation(); - - System.out.println(header + " divider location = " + dividerLocation); - System.out.println(header + " last divider location = " + lastDividerLocation); - - // if (lastDividerLocation > dividerLocation) - // { - // setDividerLocation(lastDividerLocation); - // } - } - } - - private void createLogger() - { - String logDir = _appsDefaults.getToken("rivermon_log_dir", - HydroappsDefaultDirs.RIVERMON_LOG_DIR); - String logFile = logDir + "/" + _appName; - - _logger = new SessionLogger(_appName, logFile, true, true, null); - _logger.log(null); - _logger.log(_appName + " Started"); - - } - - private void createFrame(Database db, String version) - { - _mainFrame = new MonitorFrame(); - String title = _appName + " DbName : " + db.getDatabaseName() + - " Session : "+ _logger.getSessionId(); - _mainFrame.setTitle(title); - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorFilterManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorFilterManager.java deleted file mode 100644 index d9737922db..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorFilterManager.java +++ /dev/null @@ -1,277 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; -import java.util.Map; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.TreeDataManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeManager; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeSelectionModel; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; - -public class PrecipMonitorFilterManager extends BaseManager -{ - private SessionLogger _logger; - - private PrecipMonitorDataManager _precipMonitorDataManager; - private FilterSettings _filterSettings; - - private JSplitPane _splitPane; - - private AppsDefaults _appsDefaults; - - private MonitorCheckTreeManager _checkTreeManager; - - private JScrollPane _treeScrollPane; - - private JPopupMenu _popupMenuForTree; - private JMenuItem _expandTreeMenuItem; - private JMenuItem _collapseTreeMenuItem; - - private MonitorFrame _mainFrame; - private String _iconsDir; - - public PrecipMonitorFilterManager(MessageSystemManager msgSystemManager,SessionLogger logger, - MonitorFrame mainFrame, PrecipMonitorDataManager precipMonitorDataManager, JSplitPane splitPane, - AppsDefaults appsDefaults, FilterSettings filterSettings) - { - _precipMonitorDataManager = precipMonitorDataManager; - _splitPane = splitPane; - _appsDefaults = appsDefaults; - _mainFrame = mainFrame; - _filterSettings = filterSettings; - _iconsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - createPopupMenuForTree(); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), MessageType.REFRESH_DISPLAY); - } - - private void createTreeAndApplySettings(MonitorMessage message) - { - final String header = "PrecipMonitorFilterManager.createTreeAndApplySettings(): "; - System.out.println(header + " thread = " + Thread.currentThread().getId()); - - _mainFrame.setWaitCursor(); - if(message.getMessageSource() != this) - { - System.out.println(header +" Invoked" + "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - List stringArrayListOfFilterItems = _precipMonitorDataManager.createStringArrayListOfFilterItems(); - - TreeDataManager treeDataManager = new TreeDataManager(); - - DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("HSA"); - - JTree tree = treeDataManager.createFilterTreeFromList(rootNode, stringArrayListOfFilterItems); - - tree.setBackground(Color.BLACK); - - TreePath[] preSelectedPaths = _filterSettings.getSelectedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preSelectedPaths :"); - - TreePath[] preExpandedPaths = _filterSettings.getExpandedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preExpandedPaths :"); - - Map lidToCriticalColorMap = _precipMonitorDataManager.getLidToCriticalColorMap(); - - _checkTreeManager = new MonitorCheckTreeManager(tree, preSelectedPaths, preExpandedPaths, lidToCriticalColorMap, _iconsDir); - CheckTreeSelectionListener treeListener = new CheckTreeSelectionListener(); - tree.addMouseListener(treeListener); - - _treeScrollPane = new JScrollPane(tree); - _treeScrollPane.setPreferredSize(new Dimension(300,645)); - - _splitPane.setLeftComponent(_treeScrollPane); - - // printTreePathArray(_checkTreeManager.getSelectionModel().getSelectionPaths(), "Create Tree: "); - - _precipMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(_checkTreeManager.getValidTreePaths(preSelectedPaths)); - - } - _mainFrame.setDefaultCursor(); - } - - private void highlightThisRow() - { - String header = "PrecipMonitorFilterManager.highlightThisRow(): "; - - System.out.print(header ); - send(this, MessageType.FILTER_SELECT_ITEM); - } - - private void sendRefreshDisplayMessage() - { - String header = "PrecipMonitorFilterManager.sendRefreshDisplayMessage(): "; - - System.out.print(header); - send(this, MessageType.REFRESH_DISPLAY); - } - - private void setFilterSettings() - { - String header = "PrecipMonitorFilterManager.setFilterSettings(): "; - System.out.println(header); - - TreePath[] paths = _checkTreeManager.getSelectionModel().getSelectionPaths(); - _filterSettings.setSelectedPaths(paths); - - // printTreePathArray(paths, header + " selected path in "); - - TreePath[] expandedPaths = _checkTreeManager.getAllExpandedPaths(); - _filterSettings.setExpandedPaths(expandedPaths); - - } - - private void createPopupMenuForTree() - { - _popupMenuForTree = new JPopupMenu(); - _expandTreeMenuItem = new JMenuItem("Expand Entire Tree"); - _expandTreeMenuItem.setMnemonic('E'); - _collapseTreeMenuItem = new JMenuItem("Collapse Entire Tree"); - _collapseTreeMenuItem.setMnemonic('C'); - _popupMenuForTree.add(_expandTreeMenuItem); - _popupMenuForTree.add(_collapseTreeMenuItem); - - TreePopupMenuListener treePopupMenuListener = new TreePopupMenuListener(); - _expandTreeMenuItem.addActionListener(treePopupMenuListener); - _collapseTreeMenuItem.addActionListener(treePopupMenuListener); - } - - private void printTreePathArray(TreePath[] treePathArray, String message) - { - if (message != null) - { - System.out.println(message); - } - - if (treePathArray != null) - { - for (TreePath treePath : treePathArray) - { - System.out.println(treePath); - } - } - - return; - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - - private class TreePopupMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - TreePath[] allAvailablePaths = _checkTreeManager.getAllAvailablePaths(); - if(e.getSource().toString().contains("Expand Entire Tree")) - { - _checkTreeManager.expandThesePaths(allAvailablePaths); - } - else //collapse tree - { - _checkTreeManager.collapseEntireTree(); - } - - setFilterSettings(); - } - } - - class CheckTreeSelectionListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - MonitorCheckTreeSelectionModel selectionModel = (MonitorCheckTreeSelectionModel) (_checkTreeManager.getSelectionModel()); - - selectionModel.printInstanceId(); - - TreePath paths[] = selectionModel.getSelectionPaths(); - - // printTreePathArray(paths, "CheckTreeSelectionListener.mouseClicked(): "); - - setFilterSettings(); - - _precipMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(paths); - sendRefreshDisplayMessage(); - - if(SwingUtilities.isLeftMouseButton(e)) - { - JTree tree = (JTree) e.getSource(); - int row = tree.getRowForLocation(e.getX(), e.getY()); - TreePath path = tree.getPathForRow(row); - String itemClickedOnJtree = null; - if(path != null) - { - if(path.getPathCount() == 4) - { - itemClickedOnJtree = path.getLastPathComponent().toString(); - System.out.println("Item of interest:"+ itemClickedOnJtree); - _precipMonitorDataManager.setLidOfCurrentInterest(itemClickedOnJtree); - highlightThisRow(); - } - } - } - } - public void mousePressed(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - - public void mouseReleased(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorMenuManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorMenuManager.java deleted file mode 100644 index 5987883548..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorMenuManager.java +++ /dev/null @@ -1,789 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.alertalarm.AlertAlarmDialog; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.MonitorToolBarManager; -import ohd.hseb.monitor.manager.MonitorMenuManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.precip.PrecipMonitorJTableRowData; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.officenotes.OfficeNotesDialog; -import ohd.hseb.rivermonlocgroup.RiverMonGroupDialog; -import ohd.hseb.rivermonlocgroup.RiverMonLocationDialog; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; - -public class PrecipMonitorMenuManager extends MonitorMenuManager -{ - private JMenuBar _menuBar; - private JMenu _fileMenu, _displayMenu, _sortMenu, _configMenu, _detailsMenu, _helpMenu; - private JMenuItem _selectColumnsMenuItem; - private JCheckBoxMenuItem _showMissingPrecipMenuItem; - private JMenuItem _saveColumnSettingsMenuItem; - private JMenuItem _loadSettingsMenuItem; - private JMenuItem _loadOfficeSettingsMenuItem; - private JMenuItem _saveOfficeSettingsMenuItem; - private JMenuItem _refreshColumnMenuItem; - private JMenuItem _exportTableToTextMenuItem; - private JMenuItem _riverMonitorMenuItem; - private JMenuItem _exitApplicationMenuItem; - - private JMenuItem _officeNotesMenuItem; - private JMenuItem _alertAlarmMenuItem; - private JMenuItem _timeSeriesLiteMenuItem; - private JMenuItem _riverMonGroupMenuItem; - private JMenuItem _riverMonLocationMenuItem; - private JMenuItem _derivedColumnsMenuItem; - private JMenuItem _hsagrplocSortMenuItem; - private JMenuItem _precipThreatSortMenuItem; - private JMenuItem _clearSortMenuItem; - private JMenuItem _precipThresholdForThreatColorMenuItem; - private JMenuItem _aboutMenuItem; - - private RiverMonGroupDialog _riverMonGroupDialog = null; - private RiverMonLocationDialog _riverMonLocationDialog; - - private AlertAlarmDialog _alertAlarmDialog; - private AlertAlarmDataManager _alertAlarmDataMgr; - - private PrecipMonitorDataManager _precipMonitorDataManager; - private PrecipMonitorMenuSettings _menuSettings; - - private OfficeNotesDialog _officeNotesDialog; - private OfficeNotesDataManager _officeNotesDataMgr; - - private String _settingsDir; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - private PrecipMonitorJTableRowData _selectedRowData; - - private MonitorToolBarManager _toolBarManager; - - public PrecipMonitorMenuManager(MessageSystemManager msgSystemManager, - SessionLogger logger, MonitorFrame mainFrame, String version, - String versionDate, AppsDefaults appsDefaults, JToolBar toolBar, - PrecipMonitorDataManager precipMonitorDataManager, OfficeNotesDataManager officeNotesDataMgr, - AlertAlarmDataManager alertAlarmDataMgr, - PrecipMonitorMenuSettings menuSettings, JPanel timeDisplayPanel, String appName, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) - { - super(msgSystemManager, appsDefaults, logger); - _appsDefaults = appsDefaults; - - _menuSettings = menuSettings; - - _precipMonitorDataManager = precipMonitorDataManager; - _alertAlarmDataMgr = alertAlarmDataMgr; - - _officeNotesDataMgr = officeNotesDataMgr; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - int defaultRefreshInterval = 15; - createRefreshComponents(defaultRefreshInterval, timeDisplayPanel); - - _toolBarManager = new MonitorToolBarManager(toolBar, _appsDefaults, _officeNotesDataMgr); - _toolBarManager.getOfficeNotesButton().addActionListener(new OfficeNotesDialogListener()); - - setAboutInfo(version, versionDate, appName); - _mainFrame = mainFrame; - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new ViewSelectItemReceiver(), MessageType.VIEW_SELECT_ITEM); - - _msgSystemManager.registerReceiver(new UpdateDisplayReceiver(), MessageType.REFRESH_DISPLAY); - - createMenus(); - - setFrameListener(); - } - - protected long getDataUpdateTime() - { - return _precipMonitorDataManager.getPdcUpdateTime(); - } - - protected long getDisplayedRecordCount() - { - return _precipMonitorDataManager.getDisplayedRecordCount(); - } - - public void setMenuSettingsRefreshInterval(int value) - { - _menuSettings.setRefreshInterval(value); - } - - public void setRefreshTimeSpinnerValue() - { - _refreshTimeSpinner.setValue(_menuSettings.getRefreshInterval()); - } - - private void createMenus() - { - _menuBar = new JMenuBar(); - _mainFrame.setJMenuBar(_menuBar); - - _toolBarManager.getOfficeNotesButton().addActionListener(new OfficeNotesDialogListener()); - - _fileMenu = new JMenu("File"); - _configMenu = new JMenu("Config"); - _displayMenu = new JMenu("Display"); - _sortMenu = new JMenu("Sort"); - _detailsMenu = new JMenu("Details"); - _helpMenu = new JMenu("Help"); - - _fileMenu.setMnemonic('F'); - _configMenu.setMnemonic('C'); - _displayMenu.setMnemonic('D'); - _sortMenu.setMnemonic('S'); - _detailsMenu.setMnemonic('E'); - _helpMenu.setMnemonic('H'); - - - //File Menu - _refreshColumnMenuItem = new JMenuItem("Refresh"); - _refreshColumnMenuItem.setMnemonic('R'); - _refreshColumnMenuItem.setToolTipText("Update screen with latest available data. Same as Update Now"); - _fileMenu.add(_refreshColumnMenuItem); - - _fileMenu.add(new JSeparator()); - - _saveColumnSettingsMenuItem = new JMenuItem("Save Custom Settings ..."); - _saveColumnSettingsMenuItem.setMnemonic('S'); - _fileMenu.add(_saveColumnSettingsMenuItem); - - _saveOfficeSettingsMenuItem = new JMenuItem("Save Office Settings"); - _saveOfficeSettingsMenuItem.setMnemonic('F'); - _saveOfficeSettingsMenuItem.setToolTipText("Save office settings to PrecipMonitorSettings.txt"); - _fileMenu.add(_saveOfficeSettingsMenuItem); - - _loadSettingsMenuItem = new JMenuItem("Load Custom Settings ..."); - _loadSettingsMenuItem.setMnemonic('L'); - _fileMenu.add(_loadSettingsMenuItem); - - _loadOfficeSettingsMenuItem = new JMenuItem("Load Office Settings"); - _loadOfficeSettingsMenuItem.setMnemonic('O'); - _loadOfficeSettingsMenuItem.setToolTipText("Load office settings from PrecipMonitorSettings.txt"); - _fileMenu.add(_loadOfficeSettingsMenuItem); - - _fileMenu.add(new JSeparator()); - - _exportTableToTextMenuItem = new JMenuItem("Export Data To Text File ..."); - _exportTableToTextMenuItem.setMnemonic('x'); - _fileMenu.add(_exportTableToTextMenuItem); - - _fileMenu.add(new JSeparator()); - - _riverMonitorMenuItem = new JMenuItem("RiverMonitor ..."); - _riverMonitorMenuItem.setMnemonic('M'); - _fileMenu.add(_riverMonitorMenuItem); - - _fileMenu.add(new JSeparator()); - - - _exitApplicationMenuItem = new JMenuItem("Exit"); - _exitApplicationMenuItem.setMnemonic('E'); - _fileMenu.add(_exitApplicationMenuItem); - - //Display Menu - _selectColumnsMenuItem = new JMenuItem("Select Columns ..."); - _selectColumnsMenuItem.setMnemonic('S'); - _displayMenu.add(_selectColumnsMenuItem); - - _displayMenu.add(new JSeparator()); - - _precipThresholdForThreatColorMenuItem = new JMenuItem("Precip Threshold ..."); - _precipThresholdForThreatColorMenuItem.setMnemonic('P'); - _displayMenu.add(_precipThresholdForThreatColorMenuItem); - - _showMissingPrecipMenuItem = new JCheckBoxMenuItem("Show Locations with Missing Precip Data"); - _showMissingPrecipMenuItem.setMnemonic('M'); - _displayMenu.add(_showMissingPrecipMenuItem); - - //Config Menu - _riverMonGroupMenuItem = new JMenuItem("Group Definitions ..."); - _riverMonGroupMenuItem.setMnemonic('G'); - _configMenu.add(_riverMonGroupMenuItem); - - _riverMonLocationMenuItem = new JMenuItem("Location Grouping/Ordering ..."); - _riverMonLocationMenuItem.setMnemonic('L'); - _configMenu.add(_riverMonLocationMenuItem); - - _configMenu.add(new JSeparator()); - - _derivedColumnsMenuItem = new JMenuItem("Derived Columns ..."); - _derivedColumnsMenuItem.setMnemonic('D'); - _configMenu.add(_derivedColumnsMenuItem); - - //Sort Menu - _clearSortMenuItem = new JMenuItem("Clear Sort"); - _clearSortMenuItem.setMnemonic('C'); - _clearSortMenuItem.setToolTipText("Clear All Sorts"); - _sortMenu.add(_clearSortMenuItem); - - _sortMenu.add(new JSeparator()); - - _hsagrplocSortMenuItem = new JMenuItem("Sort by HSA | Group | Location Columns"); - _hsagrplocSortMenuItem.setMnemonic('O'); - _hsagrplocSortMenuItem.setToolTipText("Sort by HSA, group id, location id"); - _sortMenu.add(_hsagrplocSortMenuItem); - - _precipThreatSortMenuItem = new JMenuItem("PrecipThreat Sort"); - _precipThreatSortMenuItem.setMnemonic('P'); - _precipThreatSortMenuItem.setToolTipText("Sort by PrecipThreat"); - _sortMenu.add(_precipThreatSortMenuItem); - - - - //Details Memu - _officeNotesMenuItem = new JMenuItem("Office Notes ..."); - _officeNotesMenuItem.setMnemonic('O'); - _detailsMenu.add(_officeNotesMenuItem); - - _alertAlarmMenuItem = new JMenuItem("Alert Alarm ..."); - _alertAlarmMenuItem.setMnemonic('A'); - _detailsMenu.add(_alertAlarmMenuItem); - - - _detailsMenu.add(new JSeparator()); - - - _timeSeriesLiteMenuItem = new JMenuItem("Time Series Lite..."); - _timeSeriesLiteMenuItem.setMnemonic('T'); - _detailsMenu.add(_timeSeriesLiteMenuItem); - - - //Help Menu - _aboutMenuItem = new JMenuItem("About ..."); - _aboutMenuItem.setMnemonic('A'); - _helpMenu.add(_aboutMenuItem); - - - setMenuListeners(); - - _menuBar.add(_fileMenu); - _menuBar.add(_displayMenu); - _menuBar.add(_configMenu); - _menuBar.add(_sortMenu); - _menuBar.add(_detailsMenu); - _menuBar.add(_helpMenu); - } - - private void setMenuListeners() - { - ChangeColumnsDisplayedMenuListener changeMenuListener = new - ChangeColumnsDisplayedMenuListener(); - _selectColumnsMenuItem.addActionListener(changeMenuListener); - - ShowMissingPrecipMenuListener showMissingPrecipMenuListener = new - ShowMissingPrecipMenuListener(); - _showMissingPrecipMenuItem.addItemListener(showMissingPrecipMenuListener); - - SaveSettingsListener saveMenuListener = new - SaveSettingsListener(); - _saveColumnSettingsMenuItem.addActionListener(saveMenuListener); - - LoadSettingsListener loadMenuListener = new LoadSettingsListener(); - _loadSettingsMenuItem.addActionListener(loadMenuListener); - - LoadOfficeSettingsListener loadOfficeSettingsListener = new LoadOfficeSettingsListener(); - _loadOfficeSettingsMenuItem.addActionListener(loadOfficeSettingsListener); - - SaveOfficeSettingsListener saveOfficeSettingsListener = new SaveOfficeSettingsListener(); - _saveOfficeSettingsMenuItem.addActionListener(saveOfficeSettingsListener); - - ExitApplicationListener exitApplicationListener = new ExitApplicationListener(); - _exitApplicationMenuItem.addActionListener(exitApplicationListener); - - RefreshMenuListener RefreshMenuListener = new - RefreshMenuListener(); - _refreshColumnMenuItem.addActionListener(RefreshMenuListener); - - SaveTableListener saveTableListener = new SaveTableListener(); - _exportTableToTextMenuItem.addActionListener(saveTableListener); - - RiverMonitorListener riverMonitorListener = new RiverMonitorListener(); - _riverMonitorMenuItem.addActionListener(riverMonitorListener); - - AppSortListener appSortListener = new AppSortListener(); - _hsagrplocSortMenuItem.addActionListener(appSortListener); - - PrecipThreatSortListener precipThreatSortListener = new PrecipThreatSortListener(); - _precipThreatSortMenuItem.addActionListener(precipThreatSortListener); - - ClearSortListener clearSortListener = new ClearSortListener(); - _clearSortMenuItem.addActionListener(clearSortListener); - - AlertAlarmDialogListener alertAlarmDialogListener = new AlertAlarmDialogListener(); - _alertAlarmMenuItem.addActionListener(alertAlarmDialogListener); - - OfficeNotesDialogListener officeNotesDialogListener = new OfficeNotesDialogListener(); - _officeNotesMenuItem.addActionListener(officeNotesDialogListener); - - TimeSeriesLiteMenuItemListener timeSeriesLiteMenuItemListener = new TimeSeriesLiteMenuItemListener(); - _timeSeriesLiteMenuItem.addActionListener(timeSeriesLiteMenuItemListener); - - RiverMonGroupDialogListener riverMonGroupDialogListener = new RiverMonGroupDialogListener(); - _riverMonGroupMenuItem.addActionListener(riverMonGroupDialogListener); - - RiverMonLocationDialogListener riverMonLocationDialogListener = new RiverMonLocationDialogListener(); - _riverMonLocationMenuItem.addActionListener(riverMonLocationDialogListener); - - PrecipThresholdListener precipThresholdListener = new PrecipThresholdListener(_menuSettings.getPrecipSettings()); - _precipThresholdForThreatColorMenuItem.addActionListener(precipThresholdListener); - - DerivedColumnsEditorListener derivedColumnsEditorListener = new DerivedColumnsEditorListener(); - _derivedColumnsMenuItem.addActionListener(derivedColumnsEditorListener); - - AboutListener aboutListener = new AboutListener(); - _aboutMenuItem.addActionListener(aboutListener); - - } - - private class DerivedColumnsEditorListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String editorTitle = ("\"").concat("Derived Columns").concat("\""); - String file = _settingsDir + "/" + PrecipMonitorAppManager.DERIVED_COLUMNS_FILE; - launchTextEditor(editorTitle, file, "PrecipMonitor Application"); - } - } - - private void setFrameListener() - { - FrameListener frameListener = new FrameListener(); - _mainFrame.addWindowListener(frameListener); - } - - public void closeApplication() - { - _logger.log("PrecipMonitor Application Exiting...."); - _logger.log("===================================="); - _precipMonitorDataManager.disconnect(); - _mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - System.exit(0); - } - - private void createOfficeNotesDialog() - { - List lidList = _precipMonitorDataManager.getLidList(); - String lids[] = new String[lidList.size()]; - for(int i=0; i < lidList.size(); i++) - { - lids[i] = lidList.get(i).toString(); - } - Arrays.sort(lids); - System.out.println("Create officenotes lids size:"+ lidList.size()); - Map lidDescDetailsMap = _precipMonitorDataManager.getLidDescDetails(); - if(_officeNotesDialog == null) - _officeNotesDialog = new OfficeNotesDialog(_mainFrame, _officeNotesDataMgr, "RIVERMON", lids, lidDescDetailsMap, _logger); - } - - public void loadSettings() - { - String header = "PrecipMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - - private void loadOfficeSettings() - { - String header = "PrecipMonitorMenuManager.loadOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_OFFICE_SETTINGS); - } - - public void viewSelectItem(MonitorMessage message) - { - String header = "PrecipMonitorMenuManager.viewSelectItem(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - _selectedRowData = (PrecipMonitorJTableRowData) message.getMessageData(); - } - - public void updateDisplayWithSettings(MonitorMessage message) - { - String header = "PrecipMonitorMenuManager.updateDisplayWithSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - refreshTimeDisplay(); - updateMenuWithNewSettings(); - } - - private void updateMenuWithNewSettings() - { - if(_menuSettings.shouldShowMissingPrecip()) - _showMissingPrecipMenuItem.setSelected(true); - else - _showMissingPrecipMenuItem.setSelected(false); - } - - public void saveSettings() - { - String header = "PrecipMonitorMenuManager.saveSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_SETTINGS); - } - - private void saveOfficeSettings() - { - String header = "PrecipMonitorMenuManager.saveOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_OFFICE_SETTINGS); - } - - public void loadSettings(File fileHandler) - { - if(fileHandler != null) - { - String header = "PrecipMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - } - - public void loadSettingsFromFile(File fileHandler) - { - String header = "PrecipMonitorMenuManager.loadSettingsFromFile(): "; - if(fileHandler != null) - { - _logger.log(header + "Read settings from " + fileHandler.getAbsolutePath()); - loadSettings(fileHandler); - } - } - - private void saveTable() - { - String header = "PrecipMonitorMenuManager.saveTable(): "; - - System.out.print(header); - send(this, MessageType.CREATE_TEXT_FROM_VIEW); - } - - private void changeColumns() - { - String header = "PrecipMonitorMenuManager.changeColumns(): "; - - System.out.print(header); - send(this, MessageType.CHANGE_COLUMNS); - } - - private void precipThreatSort() - { - String header = "PrecipMonitorMenuManager.precipThreatSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.PRECIP_THREAT_SORT); - } - - private void appSort() - { - String header = "PrecipMonitorMenuManager.appSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.APP_SORT); - } - - private void clearSort() - { - String header = "PrecipMonitorMenuManager.clearSort(): "; - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - } - - private void createAlertAlarmDialog() - { - if(_alertAlarmDialog == null) - _alertAlarmDialog = new AlertAlarmDialog(_mainFrame, _alertAlarmDataMgr, _logger); - } - - - private void createRiverMonGroupDialog() - { - String defaultHsa = _precipMonitorDataManager.getDefaultHsa(); - if(_riverMonGroupDialog == null) - _riverMonGroupDialog = new RiverMonGroupDialog(_mainFrame, - _precipMonitorDataManager.getRiverMonLocGroupDataManager(), _logger, defaultHsa); - } - - private void createRiverMonLocationDialog() - { - if(_riverMonLocationDialog == null) - _riverMonLocationDialog = new RiverMonLocationDialog(_mainFrame, - _precipMonitorDataManager.getRiverMonLocGroupDataManager(), _logger); - } - - private class ExitApplicationListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeApplication(); - } - } - - public class ShowMissingPrecipMenuListener implements ItemListener - { - public void itemStateChanged(ItemEvent e) - { - String header = "PrecipMonitorMenuManager.ShowMissingPrecipMenuListener.itemStateChanged()"; - - boolean prevValue = _menuSettings.shouldShowMissingPrecip(); - boolean newValue = false; - if( e.getStateChange() == ItemEvent.SELECTED) - { - newValue = true; - } - - _menuSettings.setShowMissingPrecip(newValue); - - if( prevValue != newValue) - { - sendMissingFilterChanged(); - } - } - } - - public class ChangeColumnsDisplayedMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - changeColumns(); - } - } - - private class ClearSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - clearSort(); - } - } - - private class PrecipThreatSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - precipThreatSort(); - } - } - - private class AppSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - appSort(); - } - } - - private class RiverMonitorListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - startMonitor("RiverMonitor Application", "RIVER"); - } - } - - private class SaveTableListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - saveTable(); - } - } - - private class RefreshMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - refresh(); - } - } - - private class AlertAlarmDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createAlertAlarmDialog(); - if(_selectedRowData != null) - { - _alertAlarmDialog.showAlertAlarmDialog(_selectedRowData.getLid()); - } - else - _alertAlarmDialog.showAlertAlarmDialog(null); - } - } - - private class TimeSeriesLiteMenuItemListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - if(_selectedRowData != null) - { - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, _selectedRowData, 1); - } - else - { - String textMsg = " Unable to display TimeSeriesLite
    "+ - "Please highlight a row... "; - JOptionPane.showMessageDialog(_mainFrame, textMsg,"TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - } - } - - private class RiverMonGroupDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createRiverMonGroupDialog(); - boolean hasTableChanged = _riverMonGroupDialog.showRiverMonGroupDialog(); - if(hasTableChanged) - { - menuChange(); - } - } - } - - private class RiverMonLocationDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createRiverMonLocationDialog(); - boolean hasTableChanged = _riverMonLocationDialog.showRiverMonLocationDialog(); - System.out.println("Rivermonlocation table changed:"+ hasTableChanged); - if(hasTableChanged) - { - menuChange(); - } - } - } - - private class LoadOfficeSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - loadOfficeSettings(); - } - } - - private class SaveOfficeSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String message = " This will overwrite standard office settings for PrecipMonitor.
    " + - "Are you sure ?
    "; - if(confirmSaveOfficeSettings(message)) - saveOfficeSettings(); - } - } - - private class LoadSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - loadSettings(); - } - } - - private class FrameListener extends WindowAdapter - { - public void windowClosing(WindowEvent event) - { - closeApplication(); - } - } - - private class OfficeNotesDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createOfficeNotesDialog(); - if(_selectedRowData != null) - { - _officeNotesDialog.showOfficeNotesDialog(_selectedRowData.getLid()); - } - else - _officeNotesDialog.showOfficeNotesDialog(null); - - _toolBarManager.setOfficeNotesButtonIcon(_officeNotesDataMgr.getCountOfOfficeNotes()); - } - } - - private class SaveSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - saveSettings(); - } - } - - private class UpdateDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - updateRecordCount(); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - setInitialRefreshTimeInfo(); - updateDisplayWithSettings(message); - } - } - - private class ViewSelectItemReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - viewSelectItem(message); - } - } - - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorRefreshManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorRefreshManager.java deleted file mode 100644 index e969bebb75..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorRefreshManager.java +++ /dev/null @@ -1,44 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import javax.swing.JSplitPane; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.MonitorRefreshManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.DialogHelper; - -public class PrecipMonitorRefreshManager extends MonitorRefreshManager -{ - private PrecipMonitorDataManager _precipMonitorDataManager; - - public PrecipMonitorRefreshManager(MessageSystemManager msgSystemManager, SessionLogger logger, - PrecipMonitorDataManager precipMonitorDataManager, JSplitPane splitPane) - { - super(msgSystemManager, logger, splitPane); - - _precipMonitorDataManager = precipMonitorDataManager; - } - - protected void reloadData(MonitorMessage incomingMessage, MessageType outgoingMessageType) - { - DialogHelper.setWaitCursor(_splitPane); - - String header = "MonitorRefreshManager.reloadData(): "; - System.out.println(header +" Invoked"+ "...Source:" + incomingMessage.getMessageSource() + - " Type:" + incomingMessage.getMessageType()); - - Runtime.getRuntime().gc(); - _precipMonitorDataManager.createPrecipMonitorRowDataList(); - Runtime.getRuntime().gc(); - - System.out.println(header); - send(this, outgoingMessageType); - - DialogHelper.setDefaultCursor(_splitPane); - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorSettingsManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorSettingsManager.java deleted file mode 100644 index a31b300dd0..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorSettingsManager.java +++ /dev/null @@ -1,201 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.io.File; - -import javax.swing.JFileChooser; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.settings.PrecipMonitorMenuSettings; -import ohd.hseb.monitor.precip.settings.PrecipMonitorSettingsFileManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; - -public class PrecipMonitorSettingsManager extends BaseManager -{ - private String _settingsDir; - private AppsDefaults _appsDefaults; - private SessionLogger _logger; - - private JFileChooser _fileChooser; - - private MonitorFrame _mainFrame; - private ViewSettings _viewSettings; - private FilterSettings _filterSettings; - private PrecipMonitorMenuSettings _menuSettings; - - private PrecipMonitorSettingsFileManager _precipMonitorSettingsFileManger; - - private String _officeSettingsFile ; - private String _defaultSettingsFile; - - public PrecipMonitorSettingsManager(MessageSystemManager msgSystemManager, AppsDefaults appsDefaults, - SessionLogger logger, MonitorFrame mainFrame, ViewSettings viewSettings, - FilterSettings filterSettings, PrecipMonitorMenuSettings menuSettings) - { - _appsDefaults = appsDefaults; - _logger = logger; - _viewSettings = viewSettings; - _filterSettings = filterSettings; - _menuSettings = menuSettings; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - _precipMonitorSettingsFileManger = new PrecipMonitorSettingsFileManager(_logger, _viewSettings, _filterSettings, _menuSettings); - - _mainFrame = mainFrame; - - _officeSettingsFile = _settingsDir.concat("/").concat(PrecipMonitorAppManager.SITE_PRECIP_SETTINGS_FILE); - _defaultSettingsFile = _settingsDir.concat("/").concat(PrecipMonitorAppManager.DEFAULT_PRECIP_SETTINGS_FILE); - - setMessageSystemManager(msgSystemManager); - - _msgSystemManager.registerReceiver(new LoadSettingsReceiver(), MessageType.LOAD_SETTINGS); - _msgSystemManager.registerReceiver(new LoadOfficeSettingsReceiver(), MessageType.LOAD_OFFICE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveSettingsReceiver(), MessageType.SAVE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveOfficeSettingsReceiver(), MessageType.SAVE_OFFICE_SETTINGS); - } - - private void saveSettings(MonitorMessage message) - { - String header = "PrecipMonitorSettingsManager.saveSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File fileHandler = null; - _fileChooser = new JFileChooser(); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = _fileChooser.showSaveDialog(_mainFrame); - if(result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveOfficeSettings(MonitorMessage message) - { - String header = "PrecipMonitorSettingsManager.saveOfficeSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveSettingsToFile(File fileHandler) - { - send(this, MessageType.UPDATE_SETTINGS); - - if(fileHandler != null) - { - _precipMonitorSettingsFileManger.saveSettingsToFile(fileHandler); - } - } - - private void loadSettings(MonitorMessage message) - { - String header = "PrecipMonitorSettingsManager.loadSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - if(message.getMessageSource() != this) - { - File fileHandler = null; - _fileChooser = new JFileChooser(); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - int result = _fileChooser.showOpenDialog(_mainFrame); - - if(result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - loadSettings(fileHandler); - } - } - - public void startPrecipMonitor() - { - String header = "PrecipMonitorSettings.startPrecipMonitor(): "; - File fileHandler = new File(_officeSettingsFile); - if(fileHandler == null || (! fileHandler.exists() )) - { - fileHandler = new File(_defaultSettingsFile); - } - - _logger.log(header + "Trying to load from file :" + fileHandler.getAbsolutePath()); - loadSettings(fileHandler); - } - - private void loadSettings(File fileHandler) - { - String header = "PrecipMonitorSettingsManager.loadSettings(): "; - if(fileHandler != null) - { - _precipMonitorSettingsFileManger.setSettingsFromFile(fileHandler); - - System.out.print(header); - send(this, MessageType.RELOAD_DATA_WITH_NEW_SETTINGS); - } - } - - private void loadOfficeSettings(MonitorMessage message) - { - String header = "PrecipMonitorSettingsManager.loadOfficeSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - loadSettings(fileHandler); - } - - private class SaveOfficeSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveOfficeSettings(message); - } - } - - private class LoadOfficeSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - loadOfficeSettings(message); - } - } - - private class LoadSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - loadSettings(message); - } - } - - private class SaveSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveSettings(message); - } - } - - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorViewManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorViewManager.java deleted file mode 100644 index 38fbbebd0d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/manager/PrecipMonitorViewManager.java +++ /dev/null @@ -1,543 +0,0 @@ -package ohd.hseb.monitor.precip.manager; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.util.List; - -import javax.swing.JFileChooser; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.monitor.precip.PrecipMonitorDataManager; -import ohd.hseb.monitor.precip.PrecipMonitorJTableRowData; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableColumnDisplaySettings; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class PrecipMonitorViewManager extends BaseManager -{ - private SessionLogger _logger; - - private PrecipMonitorDataManager _precipMonitorDataManager; - private JTableManager _precipMonitorTableManager; - private ViewSettings _viewSettings; - - private JSplitPane _splitPane; - - private List _precipMonitorAllRowDataList; - - private String _columnNamesCurrentlyDisplayed[]; - private DerivedColumnsFileManager _derivedColumnsFileManager; - private MonitorFrame _mainFrame; - - private AppsDefaults _appsDefaults; - - private PrecipMonitorJTableRowData _selectedRowData; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - public PrecipMonitorViewManager(MonitorFrame mainFrame, MessageSystemManager msgSystemManager, SessionLogger logger, - PrecipMonitorDataManager precipMonitorDataManager, JSplitPane splitPane, ViewSettings viewSettings, - DerivedColumnsFileManager derivedColumnsFileManager, MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager, - AppsDefaults appsDefaults) - { - _logger = logger; - _precipMonitorDataManager = precipMonitorDataManager; - _splitPane = splitPane; - _mainFrame = mainFrame; - _viewSettings = viewSettings; - - _derivedColumnsFileManager = derivedColumnsFileManager; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - _appsDefaults = appsDefaults; - - List precipColumnsList = new PrecipColumns().getPrecipColumnsList(null); - - _derivedColumnsFileManager.getDerivedColumns(); - String derivedColumnNames[] = _derivedColumnsFileManager.getDerivedColumnNames(); - String alignmentForDerivedColumns[] = _derivedColumnsFileManager.getAlignmentForDerivedColumns(); - if(derivedColumnNames != null) - { - addDerivedColumnNames(precipColumnsList, derivedColumnNames, alignmentForDerivedColumns); - } - - Dimension columnHeaderPreferredSize = new Dimension(100, 50); - _precipMonitorTableManager = new ComplexJTableManager(precipColumnsList, _precipMonitorAllRowDataList, columnHeaderPreferredSize); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new SelectViewItemReceiver(), MessageType.FILTER_SELECT_ITEM); - _msgSystemManager.registerReceiver(new ChangeColumnsReceiver(), MessageType.CHANGE_COLUMNS); - _msgSystemManager.registerReceiver(new AppSortReceiver(), MessageType.APP_SORT); - _msgSystemManager.registerReceiver(new PrecipThreatSortReceiver(), MessageType.PRECIP_THREAT_SORT); - _msgSystemManager.registerReceiver(new ClearSortReceiver(), MessageType.CLEAR_SORT); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), MessageType.REFRESH_DISPLAY); - _msgSystemManager.registerReceiver(new SaveViewReceiver(), MessageType.CREATE_TEXT_FROM_VIEW); - _msgSystemManager.registerReceiver(new UpdateSettingsReceiver(), MessageType.UPDATE_SETTINGS); - - } - - private void addDerivedColumnNames(List precipColumnsList, String derivedColumnNames[], String alignmentForDerivedColumns[]) - { - for(int i=0; i < derivedColumnNames.length; i++) - { - precipColumnsList.add(new JTableColumnDescriptor(derivedColumnNames[i], alignmentForDerivedColumns[i], derivedColumnNames[i])); - } - } - - private void createTableAndApplySettings(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.createTableAndApplySettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _precipMonitorAllRowDataList = _precipMonitorDataManager.getPrecipMonitorRowDataList(); - - _columnNamesCurrentlyDisplayed = null; - String columnDisplaySettingsString = _viewSettings.getColumnDisplaySettings(); - JTableColumnDisplaySettings columnDisplaySettings = _precipMonitorTableManager.getTableSettings(); - columnDisplaySettings.setSettingsFromString(columnDisplaySettingsString); - - _columnNamesCurrentlyDisplayed = _precipMonitorTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - if(_columnNamesCurrentlyDisplayed == null) - { - _columnNamesCurrentlyDisplayed = new String[] {LocationInfoColumns.LOCATION_ID, LocationInfoColumns.GROUP_NAME}; - } - - List selectedRowDataList = _precipMonitorDataManager.getTreeFilterManager().filter(_precipMonitorAllRowDataList); - _precipMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _precipMonitorTableManager.setDisplayableColumns(_columnNamesCurrentlyDisplayed, true, true); - _precipMonitorTableManager.setPreferredSizeForJScrollPane(new Dimension(690, 645)); - - JScrollPane tableScrollPane = _precipMonitorTableManager.getJScrollPane(); - _splitPane.setRightComponent(tableScrollPane); - - _precipMonitorTableManager.addTableListener(new TableMouseMotionListener()); - _precipMonitorTableManager.addTableListener(new TableListSelectionListener()); - _precipMonitorTableManager.addTableListener(new TableMouseListener()); - } - - - public void refreshDisplay(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.refreshDisplay(): "; - - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _precipMonitorAllRowDataList = _precipMonitorDataManager.getPrecipMonitorRowDataList(); - List selectedRowDataList = _precipMonitorDataManager.getTreeFilterManager().filter(_precipMonitorAllRowDataList); - _precipMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _precipMonitorTableManager.refreshDisplay(); - - JScrollPane tableScrollPane = _precipMonitorTableManager.getJScrollPane(); - - _splitPane.setRightComponent(tableScrollPane); - } - - private void setSplitPaneDividerLocation() - { - String header = "PrecipMonitorViewManager.setSplitPaneDividerLocation(): "; - - int newDividerLocation = _splitPane.getDividerLocation(); - - _splitPane.setDividerLocation(newDividerLocation); - - return; - } - - private void updateSettings(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.updateSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - updateSettings(); - } - - private void updateSettings() - { - String header = "PrecipMonitorViewManager.updateSettings(): "; - JTableColumnDisplaySettings columnDisplaySettings = _precipMonitorTableManager.getTableSettings(); - String settings = columnDisplaySettings.getSettingsString(); - _viewSettings.setColumnDisplaySettings(settings); - } - - private void selectViewItem(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.selectViewItem(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - String lidOfInterest = _precipMonitorDataManager.getLidOfCurrentInterest(); - int rowToHighLight = _precipMonitorTableManager.getTheRowIndexToHighLightBasedOnValue(lidOfInterest, LocationInfoColumns.LOCATION_ID); - System.out.println("Row to highlight:" + rowToHighLight); - if(rowToHighLight != -1) - _precipMonitorTableManager.selectRows(rowToHighLight, rowToHighLight); - } - - public void printFileException(IOException exception, String header) - { - header = header+".printFileException(): "; - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - _logger.log(header+"End of stack trace"); - } - - private void saveTableToFile(String fileName) - { - File fileHandler = new File(fileName); - String header = "PrecipMonitorViewManager.saveTableToFile(): "; - String displayedColumns[] = _precipMonitorTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - String rowData[][] = _precipMonitorTableManager.getDisplayRowDataArray(); - BufferedWriter out = null; - int maxStringLen = 33; - try - { - FileOutputStream fileOutput = new FileOutputStream(fileName, false); - OutputStreamWriter outputStream = new OutputStreamWriter(fileOutput); - out = new BufferedWriter(outputStream); - } - catch(IOException exception) - { - printFileException(exception, header); - } - if(displayedColumns != null) - { - try - { - out.newLine(); - StringBuffer columnNameStringBuffer = new StringBuffer(); - for(int i=0; i < displayedColumns.length; i++) - { - columnNameStringBuffer.append(getTrimmedOrPaddedString(displayedColumns[i], maxStringLen)); - columnNameStringBuffer.append(" |"); - } - out.write(columnNameStringBuffer.toString()); - out.newLine(); - } - catch(IOException exception) - { - printFileException(exception, header); - } - } - try - { - for(int i=0; i < rowData.length; i++) - { - out.newLine(); - StringBuffer dataStringBuffer = new StringBuffer(); - for(int j=0; j < rowData[i].length; j++) - { - dataStringBuffer.append(getTrimmedOrPaddedString(rowData[i][j], maxStringLen)); - dataStringBuffer.append(" |"); - } - out.write(dataStringBuffer.toString()); - } - } - catch(IOException exception) - { - printFileException(exception,header); - } - - try - { - out.close(); - } - catch(IOException exception) - { - _logger.log(header+ "Unable to close file["+ - fileHandler.getAbsolutePath()+"]"); - printFileException(exception, header); - } - } - - private String getTrimmedOrPaddedString(String origString, int desiredLength) - { - String newString = origString; - - String formatString = "%-"+ String.valueOf(desiredLength) +"s"; - - newString = String.format(formatString, origString); - - if (newString.length() > desiredLength) - { - newString = newString.substring(0, desiredLength); - } - - return newString; - } - - private void saveView(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.saveView(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File file = null; - JFileChooser saveFileChooser = new JFileChooser(); - String settingsDir = _appsDefaults.getToken("whfs_report_dir", - HydroappsDefaultDirs.WHFS_REPORT_DIR); - saveFileChooser.setDialogTitle("Export Table To Text File"); - saveFileChooser.setCurrentDirectory(new File(settingsDir)); - saveFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = saveFileChooser.showSaveDialog(_mainFrame); - if(result == JFileChooser.CANCEL_OPTION) - file = null; - else - file = saveFileChooser.getSelectedFile(); - - if(file != null) - { - saveTableToFile(file.toString()); - } - } - - private void changeColumns(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.changeColumns(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _precipMonitorTableManager.invokeColumnSelector(_mainFrame); - - updateSettings(); - } - - private void updateSort(String[] columnNamesToSort,int[] columnSortNumber,boolean[] columnSortOrder) - { - _precipMonitorTableManager.setSortInfoNotBasedOnUserClicks(columnNamesToSort, columnSortOrder, columnSortNumber); - updateSettings(); - } - - private void precipThreatSort(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.precipThreatSort(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = {PrecipColumns.PRECIP_THREAT}; - int columnSortNumber[] = {0}; - boolean columnSortOrder[] = {false}; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void appSort(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.appSort(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = {LocationInfoColumns.HSA, LocationInfoColumns.GROUP_ORDINAL, - LocationInfoColumns.LOCATION_ORDINAL}; - int columnSortNumber[] = {0,1,2}; - boolean columnSortOrder[] = {true, true, true}; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void clearSort() - { - _precipMonitorTableManager.clearSort(); - } - - private void clearSort(MonitorMessage message) - { - String header = "PrecipMonitorViewManager.clearSort(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - clearSort(); - updateSettings(); - } - - private void rowSelected(PrecipMonitorJTableRowData selectedRowData) - { - String header = "PrecipMonitorViewManager.rowSelected(): "; - - System.out.print(header); - send(this, MessageType.VIEW_SELECT_ITEM, selectedRowData); - } - -// ------------------------------------------------------------------------------------- - public String getToolTipForSelectedCell(String columnName, int rowIndex) - { - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData)_precipMonitorTableManager.getSelectedRowData(rowIndex); - String toolTip = ""; - if(columnName.equals(PrecipColumns.PRECIP_THREAT)) - { - toolTip = rowData.getToolTipTextForPrecipThreatSummary(); - } - if(toolTip.length() <= 12) // tooltip has "" only - { - String name = rowData.getName(); - String state = rowData.getState(); - String county = rowData.getCounty(); - String hsa = rowData.getHsa(); - - toolTip = "Name:["+ name+"]\n
    "+ - "County: ["+county+"] State: ["+state+"] HSA: ["+hsa+"]\n
    "; - } - return toolTip; - } - - private class ChangeColumnsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - changeColumns(message); - } - } - - private class ClearSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - clearSort(message); - } - } - - private class PrecipThreatSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - precipThreatSort(message); - } - } - - private class AppSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - appSort(message); - } - } - - private class SelectViewItemReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - selectViewItem(message); - } - } - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - refreshDisplay(message); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTableAndApplySettings(message); - } - } - - private class UpdateSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - updateSettings(message); - } - } - - private class SaveViewReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveView(message); - } - } - - private class TableListSelectionListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent e) - { - if(e.getValueIsAdjusting() == false) - { - List selectedRowData = _precipMonitorTableManager.getSelectedRowsData(); - for(int i=0; i < selectedRowData.size(); i++) - { - if(i == 0) - { - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData) selectedRowData.get(i); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - } - } - } - } - } - - private class TableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - //String header = "PrecipMonitorViewManager.TableMouseListener.mouseClicked(): "; - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _precipMonitorTableManager.getMousePointedRowIndex(p); - PrecipMonitorJTableRowData rowData = (PrecipMonitorJTableRowData) _precipMonitorTableManager.getSelectedRowData(rowIndex); - - if(e.getClickCount() == 2) - { - //System.out.println(header + " starting TSL for " + rowData.getLid()); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, _selectedRowData, 1); - } - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -// ------------------------------------------------------------------------------------- - class TableMouseMotionListener implements MouseMotionListener - { - public void mouseDragged(MouseEvent e) - { - } - public void mouseMoved(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _precipMonitorTableManager.getMousePointedRowIndex(p); - int colIndex = _precipMonitorTableManager.getMousePointedColumnIndex(p); - String columnName = _precipMonitorTableManager.getColumnNameAtIndex(colIndex); - String toolTip=""; - if(rowIndex != -1) - { - toolTip = getToolTipForSelectedCell(columnName, rowIndex); - _precipMonitorTableManager.setRowToolTipText(toolTip); - } - } - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipColumnDataSettings.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipColumnDataSettings.java deleted file mode 100644 index acd05c37f2..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipColumnDataSettings.java +++ /dev/null @@ -1,355 +0,0 @@ -package ohd.hseb.monitor.precip.settings; - -public class PrecipColumnDataSettings -{ - private double _precipAlert1Hr ; - private double _precipAlert3Hr ; - private double _precipAlert6Hr ; - - private double _precipCaution1Hr ; - private double _precipCaution3Hr ; - private double _precipCaution6Hr ; - - private int _ratioAlert1Hr ; - private int _ratioAlert3Hr ; - private int _ratioAlert6Hr ; - - private int _ratioCaution1Hr ; - private int _ratioCaution3Hr ; - private int _ratioCaution6Hr ; - - private double _diffAlert1Hr ; - private double _diffAlert3Hr ; - private double _diffAlert6Hr ; - - private double _diffCaution1Hr ; - private double _diffCaution3Hr ; - private double _diffCaution6Hr ; - - public static final String PRECIP_SETTINGS_BEGIN_TAG = "#Precip Settings Begin"; - public static final String PRECIP_SETTINGS_END_TAG = "#Precip Settings End"; - public static final String PRECIP_ALERT_TAG = "Precip Alert 1Hr | 3Hr | 6Hr"; - public static final String PRECIP_CAUTION_TAG = "Precip Caution 1Hr | 3Hr | 6Hr"; - public static final String RATIO_ALERT_TAG = "Ratio Alert 1Hr | 3Hr | 6Hr"; - public static final String RATIO_CAUTION_TAG = "Ratio Caution 1Hr | 3Hr | 6Hr"; - public static final String DIFF_ALERT_TAG = "Diff Alert 1Hr | 3Hr | 6Hr"; - public static final String DIFF_CAUTION_TAG = "Diff Caution 1Hr | 3Hr | 6Hr"; - - public static double DEFAULT_PRECIP_THRESHOLD_6HR = 1; - public static double DEFAULT_PRECIP_THRESHOLD_3HR = 1.25; - public static double DEFAULT_PRECIP_THRESHOLD_1HR = 1.15; - - public static double DEFAULT_PRECIP_MIN_THRESHOLD_6HR = 0; - public static double DEFAULT_PRECIP_MIN_THRESHOLD_3HR = 0; - public static double DEFAULT_PRECIP_MIN_THRESHOLD_1HR = 0; - - public static double DEFAULT_PRECIP_MAX_THRESHOLD_6HR = 5; - public static double DEFAULT_PRECIP_MAX_THRESHOLD_3HR = 5; - public static double DEFAULT_PRECIP_MAX_THRESHOLD_1HR = 5; - - public static double DEFAULT_DIFF_THRESHOLD_6HR = -0.25; - public static double DEFAULT_DIFF_THRESHOLD_3HR = -0.3; - public static double DEFAULT_DIFF_THRESHOLD_1HR = -0.35; - - public static double DEFAULT_DIFF_MIN_THRESHOLD_6HR = -5; - public static double DEFAULT_DIFF_MIN_THRESHOLD_3HR = -5; - public static double DEFAULT_DIFF_MIN_THRESHOLD_1HR = -5; - - public static double DEFAULT_DIFF_MAX_THRESHOLD_6HR = 5; - public static double DEFAULT_DIFF_MAX_THRESHOLD_3HR = 5; - public static double DEFAULT_DIFF_MAX_THRESHOLD_1HR = 5; - - public static int DEFAULT_RATIO_THRESHOLD_6HR = 90; - public static int DEFAULT_RATIO_THRESHOLD_3HR = 90; - public static int DEFAULT_RATIO_THRESHOLD_1HR = 90; - - public static int DEFAULT_RATIO_MIN_THRESHOLD_6HR = 0; - public static int DEFAULT_RATIO_MIN_THRESHOLD_3HR = 0; - public static int DEFAULT_RATIO_MIN_THRESHOLD_1HR = 0; - - public static int DEFAULT_RATIO_MAX_THRESHOLD_6HR = 400; - public static int DEFAULT_RATIO_MAX_THRESHOLD_3HR = 400; - public static int DEFAULT_RATIO_MAX_THRESHOLD_1HR = 400; - - public PrecipColumnDataSettings() - { - resetSettings(); - } - - public PrecipColumnDataSettings(double precipAlert1Hr, double precipAlert3Hr, double precipAlert6Hr, - double precipCaution1Hr, double precipCaution3Hr, double precipCaution6Hr, - int ratioAlert1Hr, int ratioAlert3Hr ,int ratioAlert6Hr, - int ratioCaution1Hr, int ratioCaution3Hr, int ratioCaution6Hr, - double diffAlert1Hr, double diffAlert3Hr, double diffAlert6Hr, - double diffCaution1Hr ,double diffCaution3Hr, double diffCaution6Hr) - { - _precipAlert1Hr = precipAlert1Hr; - _precipAlert3Hr = precipAlert3Hr; - _precipAlert6Hr = precipAlert6Hr; - - _precipCaution1Hr = precipCaution1Hr; - _precipCaution3Hr = precipCaution3Hr; - _precipCaution6Hr = precipCaution6Hr; - - _ratioAlert1Hr = ratioAlert1Hr; - _ratioAlert3Hr = ratioAlert3Hr; - _ratioAlert6Hr = ratioAlert6Hr; - - _ratioCaution1Hr = ratioCaution1Hr; - _ratioCaution3Hr = ratioCaution3Hr; - _ratioCaution6Hr = ratioCaution6Hr; - - _diffAlert1Hr = diffAlert1Hr; - _diffAlert3Hr = diffAlert3Hr; - _diffAlert6Hr = diffAlert6Hr; - - _diffCaution1Hr = diffCaution1Hr; - _diffCaution3Hr = diffCaution3Hr; - _diffCaution6Hr = diffCaution6Hr; - - } - - public void setPrecipSettings(double precipAlert1Hr, double precipAlert3Hr, double precipAlert6Hr, - double precipCaution1Hr, double precipCaution3Hr, double precipCaution6Hr, - int ratioAlert1Hr, int ratioAlert3Hr ,int ratioAlert6Hr, - int ratioCaution1Hr, int ratioCaution3Hr, int ratioCaution6Hr, - double diffAlert1Hr, double diffAlert3Hr, double diffAlert6Hr, - double diffCaution1Hr ,double diffCaution3Hr, double diffCaution6Hr) - { - _precipAlert1Hr = precipAlert1Hr; - _precipAlert3Hr = precipAlert3Hr; - _precipAlert6Hr = precipAlert6Hr; - - _precipCaution1Hr = precipCaution1Hr; - _precipCaution3Hr = precipCaution3Hr; - _precipCaution6Hr = precipCaution6Hr; - - _ratioAlert1Hr = ratioAlert1Hr; - _ratioAlert3Hr = ratioAlert3Hr; - _ratioAlert6Hr = ratioAlert6Hr; - - _ratioCaution1Hr = ratioCaution1Hr; - _ratioCaution3Hr = ratioCaution3Hr; - _ratioCaution6Hr = ratioCaution6Hr; - - _diffAlert1Hr = diffAlert1Hr; - _diffAlert3Hr = diffAlert3Hr; - _diffAlert6Hr = diffAlert6Hr; - - _diffCaution1Hr = diffCaution1Hr; - _diffCaution3Hr = diffCaution3Hr; - _diffCaution6Hr = diffCaution6Hr; - - } - - public void setPrecipSettings(PrecipColumnDataSettings precipSettings) - { - setPrecipSettings(precipSettings.getPrecipAlert1Hr(), precipSettings.getPrecipAlert3Hr(), precipSettings.getPrecipAlert6Hr(), - precipSettings.getPrecipCaution1Hr(), precipSettings.getPrecipCaution3Hr(), precipSettings.getPrecipCaution6Hr(), - precipSettings.getRatioAlert1Hr(), precipSettings.getRatioAlert3Hr (),precipSettings.getRatioAlert6Hr(), - precipSettings.getRatioCaution1Hr(), precipSettings.getRatioCaution3Hr(), precipSettings.getRatioCaution6Hr(), - precipSettings.getDiffAlert1Hr(), precipSettings.getDiffAlert3Hr(), precipSettings.getDiffAlert6Hr(), - precipSettings.getDiffCaution1Hr (),precipSettings.getDiffCaution3Hr(), precipSettings.getDiffCaution6Hr()); - } - - public void resetSettings() - { - _precipAlert1Hr = DEFAULT_PRECIP_THRESHOLD_1HR; - _precipAlert3Hr = DEFAULT_PRECIP_THRESHOLD_3HR; - _precipAlert6Hr = DEFAULT_PRECIP_THRESHOLD_6HR; - - _precipCaution1Hr = DEFAULT_PRECIP_THRESHOLD_1HR; - _precipCaution3Hr = DEFAULT_PRECIP_THRESHOLD_3HR; - _precipCaution6Hr = DEFAULT_PRECIP_THRESHOLD_6HR; - - _ratioAlert1Hr = DEFAULT_RATIO_THRESHOLD_1HR; - _ratioAlert3Hr = DEFAULT_RATIO_THRESHOLD_3HR; - _ratioAlert6Hr = DEFAULT_RATIO_THRESHOLD_6HR; - - _ratioCaution1Hr = DEFAULT_RATIO_THRESHOLD_1HR; - _ratioCaution3Hr = DEFAULT_RATIO_THRESHOLD_3HR; - _ratioCaution6Hr = DEFAULT_RATIO_THRESHOLD_6HR; - - _diffAlert1Hr = DEFAULT_DIFF_THRESHOLD_1HR; - _diffAlert3Hr = DEFAULT_DIFF_THRESHOLD_3HR; - _diffAlert6Hr = DEFAULT_DIFF_THRESHOLD_6HR; - - _diffCaution1Hr = DEFAULT_DIFF_THRESHOLD_1HR; - _diffCaution3Hr = DEFAULT_DIFF_THRESHOLD_3HR; - _diffCaution6Hr = DEFAULT_DIFF_THRESHOLD_6HR; - } - - public double getDiffAlert1Hr() - { - return _diffAlert1Hr; - } - public void setDiffAlert1Hr(double diffAlert1Hr) - { - _diffAlert1Hr = diffAlert1Hr; - } - public double getDiffAlert3Hr() - { - return _diffAlert3Hr; - } - public void setDiffAlert3Hr(double diffAlert3Hr) - { - _diffAlert3Hr = diffAlert3Hr; - } - public double getDiffAlert6Hr() - { - return _diffAlert6Hr; - } - public void setDiffAlert6Hr(double diffAlert6Hr) - { - _diffAlert6Hr = diffAlert6Hr; - } - public double getDiffCaution1Hr() - { - return _diffCaution1Hr; - } - public void setDiffCaution1Hr(double diffCaution1Hr) - { - _diffCaution1Hr = diffCaution1Hr; - } - public double getDiffCaution3Hr() - { - return _diffCaution3Hr; - } - public void setDiffCaution3Hr(double diffCaution3Hr) - { - _diffCaution3Hr = diffCaution3Hr; - } - public double getDiffCaution6Hr() - { - return _diffCaution6Hr; - } - public void setDiffCaution6Hr(double diffCaution6Hr) - { - _diffCaution6Hr = diffCaution6Hr; - } - public double getPrecipAlert1Hr() - { - return _precipAlert1Hr; - } - public void setPrecipAlert1Hr(double precipAlert1Hr) - { - _precipAlert1Hr = precipAlert1Hr; - } - public double getPrecipAlert3Hr() - { - return _precipAlert3Hr; - } - public void setPrecipAlert3Hr(double precipAlert3Hr) - { - _precipAlert3Hr = precipAlert3Hr; - } - public double getPrecipAlert6Hr() - { - return _precipAlert6Hr; - } - public void setPrecipAlert6Hr(double precipAlert6Hr) - { - _precipAlert6Hr = precipAlert6Hr; - } - public double getPrecipCaution1Hr() - { - return _precipCaution1Hr; - } - public void setPrecipCaution1Hr(double precipCaution1Hr) - { - _precipCaution1Hr = precipCaution1Hr; - } - public double getPrecipCaution3Hr() - { - return _precipCaution3Hr; - } - public void setPrecipCaution3Hr(double precipCaution3Hr) - { - _precipCaution3Hr = precipCaution3Hr; - } - public double getPrecipCaution6Hr() - { - return _precipCaution6Hr; - } - public void setPrecipCaution6Hr(double precipCaution6Hr) - { - _precipCaution6Hr = precipCaution6Hr; - } - public int getRatioAlert1Hr() - { - return _ratioAlert1Hr; - } - public void setRatioAlert1Hr(int ratioAlert1Hr) - { - _ratioAlert1Hr = ratioAlert1Hr; - } - public int getRatioAlert3Hr() - { - return _ratioAlert3Hr; - } - public void setRatioAlert3Hr(int ratioAlert3Hr) - { - _ratioAlert3Hr = ratioAlert3Hr; - } - public int getRatioAlert6Hr() - { - return _ratioAlert6Hr; - } - public void setRatioAlert6Hr(int ratioAlert6Hr) - { - _ratioAlert6Hr = ratioAlert6Hr; - } - public int getRatioCaution1Hr() - { - return _ratioCaution1Hr; - } - public void setRatioCaution1Hr(int ratioCaution1Hr) - { - _ratioCaution1Hr = ratioCaution1Hr; - } - public int getRatioCaution3Hr() - { - return _ratioCaution3Hr; - } - public void setRatioCaution3Hr(int ratioCaution3Hr) - { - _ratioCaution3Hr = ratioCaution3Hr; - } - public int getRatioCaution6Hr() - { - return _ratioCaution6Hr; - } - public void setRatioCaution6Hr(int ratioCaution6Hr) - { - _ratioCaution6Hr = ratioCaution6Hr; - } - - public PrecipColumnDataSettings getMenuSettings() - { - return this; - } - - public String toString() - { - String result = _precipAlert1Hr + "|" + - _precipAlert3Hr + "|" + - _precipAlert6Hr + "|" + - _precipCaution1Hr + "|" + - _precipCaution3Hr + "|" + - _precipCaution6Hr + "|" + - _ratioAlert1Hr + "|" + - _ratioAlert3Hr + "|" + - _ratioAlert6Hr + "|" + - _ratioCaution1Hr + "|" + - _ratioCaution3Hr + "|" + - _ratioCaution6Hr + "|" + - _diffAlert1Hr + "|" + - _diffAlert3Hr + "|" + - _diffAlert6Hr + "|" + - _diffCaution1Hr + "|" + - _diffCaution3Hr + "|" + - _diffCaution6Hr ; - - return result; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorMenuSettings.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorMenuSettings.java deleted file mode 100644 index 859ac66164..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorMenuSettings.java +++ /dev/null @@ -1,81 +0,0 @@ -package ohd.hseb.monitor.precip.settings; - -import ohd.hseb.util.BooleanHolder; - -public class PrecipMonitorMenuSettings -{ - private int _refreshInterval; - - public static final String REFRESH_INTERVAL_TAG = "RefreshInterval"; - - public static final String SHOW_MISSING_PRECIP_TAG = "ShowMissingPrecip"; - - public static int DEFAULT_REFRESH_INTERVAL = 15; - - private BooleanHolder _showMissingPrecipBooleanHolder = new BooleanHolder(true); - - private PrecipColumnDataSettings _precipSettings; - - public PrecipMonitorMenuSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingPrecip(false); - _precipSettings = new PrecipColumnDataSettings(); - } - - public void resetSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingPrecip(false); - _precipSettings.resetSettings(); - } - - public PrecipMonitorMenuSettings(int refreshInterval, boolean showMissingPrecip) - { - _refreshInterval = refreshInterval; - setShowMissingPrecip(showMissingPrecip); - _precipSettings = new PrecipColumnDataSettings(); - } - - public void setPrecipSettings(PrecipColumnDataSettings precipSettings) - { - _precipSettings = precipSettings; - } - - public PrecipColumnDataSettings getPrecipSettings() - { - return _precipSettings; - } - - public boolean shouldShowMissingPrecip() - { - return _showMissingPrecipBooleanHolder.getValue(); - } - - public void setShowMissingPrecip(boolean showMissingPrecip) - { - _showMissingPrecipBooleanHolder.setValue(showMissingPrecip); - } - - public void setRefreshInterval(int refreshInterval) - { - _refreshInterval = refreshInterval; - } - - public int getRefreshInterval() - { - return _refreshInterval; - } - - private void setShowMissingPrecipBooleanHolder(BooleanHolder showMissingPrecipBooleanHolder) - { - _showMissingPrecipBooleanHolder = showMissingPrecipBooleanHolder; - } - - public BooleanHolder getShowMissingPrecipBooleanHolder() - { - return _showMissingPrecipBooleanHolder; - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorSettingsFileManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorSettingsFileManager.java deleted file mode 100644 index a51f2a1d89..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/precip/settings/PrecipMonitorSettingsFileManager.java +++ /dev/null @@ -1,241 +0,0 @@ -package ohd.hseb.monitor.precip.settings; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.MonitorSettingsFileManager; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; - -public class PrecipMonitorSettingsFileManager extends MonitorSettingsFileManager -{ - private PrecipMonitorMenuSettings _menuSettings; - - public PrecipMonitorSettingsFileManager(SessionLogger logger, ViewSettings viewSettings, - FilterSettings filterSettings, PrecipMonitorMenuSettings menuSettings) - { - super(logger, "#PrecipMonitorSettings File", viewSettings, filterSettings); - _menuSettings = menuSettings; - _logger = logger; - createDisplayTokenSet(); - createMenuTokenSet(); - } - - public Set createMenuTokenSet() - { - _menuTokenSet = new HashSet(); - - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_CAUTION_TAG); - _menuTokenSet.add(PrecipMonitorMenuSettings.REFRESH_INTERVAL_TAG); - _menuTokenSet.add(PrecipMonitorMenuSettings.SHOW_MISSING_PRECIP_TAG); - - return _displayTokenSet; - } - - public boolean setSettingsFromFile(File fileHandler) - { - String header = "PrecipMonitorSettingsFileManager.setSettingsFromFile(): "; - boolean isReadCompleted = true; - - resetSettings(); - - if(isValidSettingsFile(_logger, fileHandler, _settingsFileBeginTag )) - { - BufferedReader in = null; - String line; - try - { - in = new BufferedReader(new FileReader(fileHandler)); - - while(( line = in.readLine()) != null) - { - line = line.trim(); - processLine(line); - } - - } - catch(IOException e) - { - printFileException(_logger, e,header); - isReadCompleted = false ; - } - } - else - { - isReadCompleted = false; - } - - setViewAndFilterSettings(); - return isReadCompleted; - } - - private void resetSettings() - { - _tableDisplaySettingsList = null; - _expandPathTokenValuesList = null; - _pathTokenValuesList = null; - - setViewAndFilterSettings(); - _menuSettings.resetSettings(); - } - - - public void saveSettingsToFile(File fileHandler) - { - createSettingsFile(fileHandler); - - BufferedWriter out = null; - String header = "PrecipMonitorSettingsFileManager.saveSettingsToFile(): "; - try - { - out = new BufferedWriter(new FileWriter(fileHandler)); - } - catch(IOException exception) - { - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - } - - saveDisplaySettings(out); - - saveMenuSettingsToFile(out); - } - - public void processMenuToken(String tokenName, String tokenValue) - { - if(tokenName.compareTo(PrecipMonitorMenuSettings.REFRESH_INTERVAL_TAG) == 0) - { - _menuSettings.setRefreshInterval(new Integer(tokenValue)); - System.out.println("Setting in menu refresh interval:" + tokenValue); - } - if(tokenName.compareTo(PrecipMonitorMenuSettings.SHOW_MISSING_PRECIP_TAG) == 0) - { - _menuSettings.setShowMissingPrecip(new Boolean(tokenValue)); - System.out.println("Setting Show Missing Precip Flag:" + tokenValue); - } - else - { - String spiltStr[] = tokenValue.split("\\|"); - String hr1, hr3, hr6; - - if(spiltStr != null) - { - if(spiltStr.length == 3) // we have 3 values 1hr | 3hr | 6hr correctly - { - hr1 = null; hr3 = null; hr6 = null; - - hr1 = spiltStr[0].trim(); - hr3 = spiltStr[1].trim(); - hr6 = spiltStr[2].trim(); - - if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipCaution6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioAlert1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioAlert3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioAlert6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioCaution1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioCaution3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioCaution6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffCaution6Hr(new Double(hr6)); - } - } - } - } - } - - public void saveMenuSettingsToFile(BufferedWriter writer) - { - String header = "PrecipMonitorSettingsFileManager.saveMenuSettingsToFile(): "; - try - { - if(_menuSettings != null) - { - writer.newLine(); - writer.write(PrecipMonitorMenuSettings.REFRESH_INTERVAL_TAG + " : " + _menuSettings.getRefreshInterval()); - writer.newLine(); - - writer.newLine(); - writer.write(PrecipMonitorMenuSettings.SHOW_MISSING_PRECIP_TAG + " : " + _menuSettings.shouldShowMissingPrecip()); - writer.newLine(); - - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_BEGIN_TAG); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getRatioAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getDiffAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert6Hr() ); - writer.newLine(); - - writer.write(PrecipColumnDataSettings.PRECIP_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getRatioCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getDiffCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_END_TAG); - - writer.close(); - } - } - catch(IOException exception) - { - printFileException(_logger, exception,header); - } - - } - - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/LookBackTimeDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/LookBackTimeDialog.java deleted file mode 100644 index 45f8ac64a8..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/LookBackTimeDialog.java +++ /dev/null @@ -1,152 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.river.settings.RiverColumnDataSettings; -import ohd.hseb.util.gui.WindowResizingManager; - -public class LookBackTimeDialog extends JDialog -{ - private JSpinner _timeSpinBox; - private JLabel _validTimeLabel; - private JButton _closeButton; - private String _settingsTokenName; - private RiverColumnDataSettings _riverSettings; - - public LookBackTimeDialog( MonitorFrame mainFrame, RiverColumnDataSettings riverSettings, - String dialogTitle, - JLabel label, - String settingsTokenName, - int maxNumOfHrs, - int minNumOfHrs) - { - super(mainFrame, true); - _settingsTokenName = settingsTokenName; - _riverSettings = riverSettings; - this.setTitle(dialogTitle); - createDialogComponents(label, maxNumOfHrs, minNumOfHrs); - this.pack(); - this.setVisible(true); - } - - public void createDialogComponents(JLabel label, int maxNumOfHrs, int minNumOfHrs) - { - _validTimeLabel = label; - int incrNumOfHrs = 1; - int initialNumOfHrs = 1; - - if(_settingsTokenName.equals(RiverColumnDataSettings.VALID_TIME_TAG)) - initialNumOfHrs = _riverSettings.getAlertAlarmLookBack(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG)) - initialNumOfHrs = _riverSettings.getVtecEventProductTimeLookBack(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG)) - initialNumOfHrs = _riverSettings.getVtecEventEndTimeApproach(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG)) - initialNumOfHrs = _riverSettings.getUgcExpireTimeApproach(); - else if(_settingsTokenName.equals(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG)) - initialNumOfHrs = _riverSettings.getLatestFcstBasisTimeLookBack(); - else // LatestObs_Time - initialNumOfHrs = _riverSettings.getLatestObsLookBack(); - - SpinnerModel spinnerModel = new SpinnerNumberModel(initialNumOfHrs, - minNumOfHrs, - maxNumOfHrs, - incrNumOfHrs); - - _timeSpinBox = new JSpinner(spinnerModel); - JPanel spinnerPanel = new JPanel(); - spinnerPanel.setLayout(new GridLayout(3,1)); - spinnerPanel.add(createDummyPanel()); - spinnerPanel.add(_timeSpinBox); - spinnerPanel.add(createDummyPanel()); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(1,3)); - infoPanel.add(_validTimeLabel); - infoPanel.add(spinnerPanel); - infoPanel.add(createDummyPanel()); - - _closeButton = new JButton("Close"); - JPanel closePanel = new JPanel(); - closePanel.setLayout(new GridLayout(3,1)); - closePanel.add(createDummyPanel()); - closePanel.add(_closeButton); - closePanel.add(createDummyPanel()); - - JPanel actionPanel = new JPanel(); - actionPanel.setLayout(new GridLayout(1,3)); - actionPanel.add(createDummyPanel()); - actionPanel.add(closePanel); - actionPanel.add(createDummyPanel()); - - JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(2,1)); - panel.add(infoPanel); - panel.add(actionPanel); - - this.setLocation(25, 25); - Dimension dim = new Dimension(300,200); - new WindowResizingManager(this, dim, dim); - this.getContentPane().add(panel); - - CloseButtonListener closeButtonListener = new CloseButtonListener(); - _closeButton.addActionListener(closeButtonListener); - - DialogListener dialogListener = new DialogListener(); - this.addWindowListener(dialogListener); - } - - private JPanel createDummyPanel() - { - JPanel dummyPanel = new JPanel(); - return dummyPanel; - } - - private void closeTimeDialog() - { - this.setVisible(false); - - if(_settingsTokenName.equals(RiverColumnDataSettings.VALID_TIME_TAG)) - _riverSettings.setAlertAlarmLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG)) - _riverSettings.setVtecEventProductTimeLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG)) - _riverSettings.setVtecEventEndTimeApproach(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG)) - _riverSettings.setUgcExpireTimeApproach(Integer.parseInt(_timeSpinBox.getValue().toString())); - else if(_settingsTokenName.equals(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG)) - _riverSettings.setLatestFcstBasisTimeLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - else // LatestObs_Time - _riverSettings.setLatestObsLookBack(Integer.parseInt(_timeSpinBox.getValue().toString())); - } - - class CloseButtonListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeTimeDialog(); - } - } - - class DialogListener extends WindowAdapter - { - public void windowClosing(WindowEvent e) - { - closeTimeDialog(); - } - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverColumns.java deleted file mode 100644 index 28f9721f11..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverColumns.java +++ /dev/null @@ -1,104 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class RiverColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String GROUP_NAME = "Group Name"; - public static final String LOCATION_ID = "Location Id"; - public static final String LOCATION_NAME = "Location Name"; - public static final String HSA = "HSA"; - public static final String GROUP_ORDINAL = "Group Ordinal"; - public static final String LOCATION_ORDINAL = "Location Ordinal"; - public static final String COUNTY = "County"; - public static final String STATE = "State"; - public static final String STREAM = "Stream"; - public static final String RIVER_BASIN = "River Basin"; - public static final String BANK_FULL = "Bank Full"; - - public static final String PRIMARY_RIVER_PE = "Primary River PE"; - - public static final String FLD_STG = "Flood Stage"; - public static final String ACT_STG = "Action Stage"; - public static final String FLD_FLOW = "Flood Flow"; - public static final String ACT_FLOW = "Action Flow"; - public static final String MIN_STG = "Minor Stage"; - public static final String MAJ_STG = "Major Stage"; - public static final String MOD_STG = "Moderate Stage"; - public static final String LAT_OBS_VALUE = "LatestObs Value"; - public static final String LAT_OBS_TIME = "LatestObs Time"; - public static final String MAX_FCST_VALUE = "MaxFcst Value"; - public static final String MAX_FCST_VALID_TIME = "MaxFcst ValidTime"; - public static final String MAX_FCST_BASIS_TIME = "MaxFcst BasisTime"; - public static final String OBSFCST_MAX = "ObsFcstMax"; - public static final String LAT_STG_VALUE = "Latest StgValue"; - public static final String LAT_STG_TIME = "Latest StgTime";; - public static final String LAT_FLOW_VALUE = "Latest FlowValue"; - public static final String LAT_FLOW_TIME = "Latest FlowTime"; - public static final String FLD_STG_DEP = "FldStg Departure"; - public static final String ACT_STG_DEP = "ActStg Departure"; - public static final String THREAT = "Threat"; - public static final String ALERT_ALARM = "AlertAlarm"; - public static final String VTEC_SUMMARY = "VTEC Summary"; - public static final String EVENT_END_TIME = "Event EndTime"; - public static final String UGC_EXPIRE_TIME = "UGCExpire Time"; - public static final String SSHP_MAX_FCST_VALUE = "SSHP MaxFcstValue"; - public static final String SSHP_MAX_FCST_VALID_TIME = "SSHP MaxFcstValidTime"; - public static final String SSHP_FCST_BASIS_TIME = "SSHP FcstBasisTime"; - public static final String SSHP_FCST_FLD_TIME = "SSHP FcstFloodTime"; - - - public List getRiverColumnsList(List riverMonitorColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - String timeAlignment = "center"; - - if(riverMonitorColumnDescriptorList == null) - { - riverMonitorColumnDescriptorList = new ArrayList(); - riverMonitorColumnDescriptorList = new LocationInfoColumns().getLocationInfoColumnsList(riverMonitorColumnDescriptorList); - riverMonitorColumnDescriptorList = new PrecipColumns().getPrecipColumnsList(riverMonitorColumnDescriptorList); - } - - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(PRIMARY_RIVER_PE, textAlignment, "Primary River PE")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(STREAM, textAlignment, "Stream Name")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(BANK_FULL, numberAlignment, "Bank Full Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(FLD_STG, numberAlignment, "Flood Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ACT_STG, numberAlignment, "Warning Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(FLD_FLOW, numberAlignment, "Flood Flow")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ACT_FLOW, numberAlignment, "Action Flow")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MIN_STG, numberAlignment, "Minor Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAJ_STG, numberAlignment, "Major Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MOD_STG, numberAlignment, "Moderate Stage")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_OBS_VALUE, numberAlignment, "Latest Observed Value")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_OBS_TIME, timeAlignment, "Latest Observed Time")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAX_FCST_VALUE, numberAlignment, "MaxFcst Value")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAX_FCST_VALID_TIME, timeAlignment, "MaxFcst ValidTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(MAX_FCST_BASIS_TIME, timeAlignment, "MaxFcst BasisTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(OBSFCST_MAX, numberAlignment, "ObsFcstMax")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_STG_VALUE, numberAlignment, "Latest StgValue")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_STG_TIME, timeAlignment, "Latest StgTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_FLOW_VALUE, numberAlignment, "Latest FlowValue")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(LAT_FLOW_TIME, timeAlignment, "Latest FlowTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(FLD_STG_DEP, numberAlignment, "FldStg Departure")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ACT_STG_DEP, numberAlignment, "ActStg Departure")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(THREAT, textAlignment,"Threat")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(ALERT_ALARM, textAlignment, "AlertAlarm")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(VTEC_SUMMARY, textAlignment, "VTEC Summary")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(EVENT_END_TIME, timeAlignment, "Event EndTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(UGC_EXPIRE_TIME, timeAlignment, "UGCExpire Time")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_MAX_FCST_VALUE, numberAlignment, "SSHP MaxFcstValue")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_MAX_FCST_VALID_TIME, timeAlignment, "SSHP MaxFcstValidTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_FCST_BASIS_TIME, timeAlignment, "SSHP FcstBasisTime")); - riverMonitorColumnDescriptorList.add(new JTableColumnDescriptor(SSHP_FCST_FLD_TIME, timeAlignment, "SSHP FcstFloodTime")); - - return riverMonitorColumnDescriptorList; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverLocationDataFilter.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverLocationDataFilter.java deleted file mode 100644 index d5ba53ac51..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverLocationDataFilter.java +++ /dev/null @@ -1,74 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTable; -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.util.BooleanHolder; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class RiverLocationDataFilter extends LocationDataFilter -{ - - private BooleanHolder _showMissingBooleanHolder = null; - - public RiverLocationDataFilter(Map locationDisplayMap, BooleanHolder showMissingBooleanHolder) - { - _locationDisplayMap = locationDisplayMap; - _showMissingBooleanHolder = showMissingBooleanHolder; - } - - - public List filter(List allRowDataList) - { - boolean showMissing = _showMissingBooleanHolder.getValue(); - List filteredRowDataList = new ArrayList(); - - if (_locationDisplayMap != null) - { - for (int i = 0; i < allRowDataList.size(); i++) - { - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) allRowDataList.get(i); - String lid = rowData.getLid(); - Boolean shouldDisplay = _locationDisplayMap.get(lid); - if ((shouldDisplay != null) && (shouldDisplay) ) //based on selection in the tree - { - // String header = "RiverLocationDataFilter.filter(): "; - // System.out.println(header + " lid = " + lid + "hsa = " + rowData.getHsa() + " groupId = " + rowData.getGroupId()); - - if (showMissing) //based on menu selection - { - filteredRowDataList.add(rowData); - } - else //don't show missing - { - if (isDataAvailable(rowData)) - { - filteredRowDataList.add(rowData); - } - } - } //end if shouldDisplay - } //end for - - } //end if (_locationDisplayMap != null) - return filteredRowDataList; - } - - private boolean isDataAvailable(RiverMonitorJTableRowData rowData) - { - boolean result = false; - - if (rowData.getLatestObsValue() != DbTable.getNullDouble() || - rowData.getMaxFcstValue() != DbTable.getNullDouble()) - { - result = true; - } - - return result; - } - - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorDataManager.java deleted file mode 100644 index 3ef2e2f24c..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorDataManager.java +++ /dev/null @@ -1,1776 +0,0 @@ -package ohd.hseb.monitor.river; - -import static ohd.hseb.util.TimeHelper.MILLIS_PER_HOUR; - -import java.awt.Color; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.AdminRecord; -import ohd.hseb.ihfsdb.generated.AdminTable; -import ohd.hseb.ihfsdb.generated.AlertAlarmValRecord; -import ohd.hseb.ihfsdb.generated.AlertAlarmValTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LocRiverMonRecord; -import ohd.hseb.ihfsdb.generated.LocRiverMonView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RiverStatusRecord; -import ohd.hseb.ihfsdb.generated.RiverStatusTable; -import ohd.hseb.ihfsdb.generated.ShefPeRecord; -import ohd.hseb.ihfsdb.generated.ShefPeTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.ihfsdb.generated.VTECeventTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.monitor.LocationDataFilter; -import ohd.hseb.monitor.TreeFilterManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.precip.PrecipData; -import ohd.hseb.monitor.precip.PrecipDataManager; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.rivermonlocgroup.RiverMonLocGroupDataManager; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeSeriesFileManager; - -import org.apache.bsf.BSFEngine; -import org.apache.bsf.BSFManager; - -public class RiverMonitorDataManager -{ - private Database _db; - - private AppsDefaults _appsDefaults; - - private SessionLogger _logger; - - private String _defaultHsa; - private Set _riverLidSet = null; - - private String _peConfigFileName; - private List _validHeightAndDischargePEList; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - private List _derivedColumnsList; - private BSFManager _bsfManager; - private BSFEngine _beanShellEngine; - - private String _missingRepresentation; - - private List _riverMonitorRowDataList; - private List _missingRiverMonitorRowDataList = new ArrayList(); - private Map _lidToRiverBasinMap = new HashMap(); - - private Map _lidDescDetailsMap; - - private TreeFilterManager _treeFilterManager; - - private String _lidOfCurrentInterest; - - private RiverMonitorMenuSettings _menuSettings; - - private RiverMonLocGroupDataManager _riverMonLocGroupDataManager; - private OfficeNotesDataManager _officeNotesDataManager; - - private Map _sshpLidFcstMap; - private String _sshpFcstDataDir; - - private PrecipDataManager _precipDataManager; - - private Map _lidHeightPEMap = null; - private Map _lidDischargePEMap = null; - - public RiverMonitorDataManager(Database db, AppsDefaults appsDefaults, String missingRepresentation, - SessionLogger logger, RiverMonitorMenuSettings menuSettings, - DerivedColumnsFileManager derivedColumnsFileManager) - { - _appsDefaults = appsDefaults; - _menuSettings = menuSettings; - _db = db; - _missingRepresentation = missingRepresentation; - _logger = logger; - - readValidHeightAndDischargePE(); - _precipDataManager = new PrecipDataManager(_db, _appsDefaults, _missingRepresentation, _logger); - - _sshpFcstDataDir = _appsDefaults.getToken("sshp_background_forecast_output_dir", - HydroappsDefaultDirs.SSHP_BACKGROUND_FORECAST_OUTPUT_DIR); - String settingsDir = _appsDefaults.getToken("rivermon_config_dir", "awips/hydroapps/whfs/local/data/app/rivermon"); - - _peConfigFileName = settingsDir + "/" + "RiverMonitorPEConfig.txt"; - - readAdminTable(); - _derivedColumnsFileManager = derivedColumnsFileManager; - - _riverMonLocGroupDataManager = new RiverMonLocGroupDataManager(db, _logger, missingRepresentation, getDefaultHsa()); - - _officeNotesDataManager = new OfficeNotesDataManager(db,_logger, missingRepresentation); - - try - { - initializeBSF(); - } - catch (Exception e) - { - _logger.log("PrecipMonitorDataManager.PrecipMonitorDataManager(): Error while initialize BSF..." + e); - } - } - - public RiverMonLocGroupDataManager getRiverMonLocGroupDataManager() - { - return _riverMonLocGroupDataManager; - } - - public OfficeNotesDataManager getOfficeNotesDataManager() - { - return _officeNotesDataManager; - } - - public TreeFilterManager getTreeFilterManager() - { - if(_treeFilterManager == null) - { - _treeFilterManager = new TreeFilterManager(_logger, getLocationDataFilter()); - } - return _treeFilterManager; - } - - public void setLidOfCurrentInterest(String lid) - { - _lidOfCurrentInterest = lid; - } - - public String getLidOfCurrentInterest() - { - return _lidOfCurrentInterest; - } - - public long getPdcUpdateTime() - { - return _precipDataManager.getPdcFileUpdateLongTime(); - } - - public long getDisplayedRecordCount() - { - - List selectedRowDataList = getTreeFilterManager().filter(_riverMonitorRowDataList); - long displayedCount = selectedRowDataList.size(); - - return displayedCount; - } - - public void disconnect() - { - _db.disconnect(); - } - - private void printLocationCounts(String header) - { - System.out.println(header + "There are " + _riverMonitorRowDataList.size() + - " displayed with " + _missingRiverMonitorRowDataList.size() + " non-displayed missing locations." ); - - } - - - public Map getLidToCriticalColorMap() - { - String header = "RiverMonitorDataManager.getLidToCriticalColorMap(): " ; - - Map lidToCriticalColorMap = new HashMap(); - - for(RiverMonitorJTableRowData rowData:_riverMonitorRowDataList) - { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - for(RiverMonitorJTableRowData rowData:_missingRiverMonitorRowDataList) - { - String lid = rowData.getLid(); - Color criticalColor = rowData.getCriticalColorForThisRow(); - lidToCriticalColorMap.put(lid, criticalColor); - } - - return lidToCriticalColorMap; - } - - private void readAdminTable() - { - AdminTable adminTable = new AdminTable(_db); - List adminList = null; - try - { - adminList = adminTable.select(""); - } - catch (SQLException e) - { - logSQLException(e); - } - _defaultHsa = ((AdminRecord) adminList.get(0)).getHsa(); - } - - protected void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + exception.getErrorCode() + " " + exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - private LocationDataFilter getLocationDataFilter() - { - RiverLocationDataFilter locationDataFilter; - List lidList = getLidList(); - Map locationDisplayMap = new HashMap(); - - for(String lid:lidList) - { - locationDisplayMap.put(lid, false); - } - - locationDataFilter = new RiverLocationDataFilter(locationDisplayMap, _menuSettings.getShowMissingDataBooleanHolder()); - return locationDataFilter; - } - - public List getLidList() - { - List lidList = new ArrayList(); - for(RiverMonitorJTableRowData rowData:_riverMonitorRowDataList) - { - String lid = rowData.getLid(); - lidList.add(lid); - } - return lidList; - } - -// --------------------------------------------------------------------------------------------------- - - private void initializeBSF() throws Exception - { - _bsfManager = new BSFManager(); - BSFManager.registerScriptingEngine("beanshell", "bsh.util.BeanShellBSFEngine", null); - _beanShellEngine = _bsfManager.loadScriptingEngine("beanshell"); - } -// --------------------------------------------------------------------------------------------------- - - protected void getDerivedColumnsInfo(RiverMonitorJTableRowData riverMonitorRowData) - { - - String header = "RiverMonitorDataManger.getDerivedColumnsInfo():" ; - - if(_derivedColumnsList != null) - { - try - { - _bsfManager.declareBean("row", riverMonitorRowData, RiverMonitorJTableRowData.class); - _bsfManager.declareBean("precip", riverMonitorRowData.getPrecipData(), PrecipData.class); - for (int j = _derivedColumnsList.size() - 1; j >= 0; j--) - { - DerivedColumn derivedColumnDesc = (DerivedColumn) _derivedColumnsList.get(j); - String equationForCellValue = ((String) derivedColumnDesc.getEquationForCellValue()); - - Object returnValueForCell = _beanShellEngine.eval("rowtest", 1, 1, equationForCellValue); - if (derivedColumnDesc.getReturnType().equalsIgnoreCase("double")) - { - double value = roundTo2DecimalPlaces(Double.parseDouble(returnValueForCell.toString())); - derivedColumnDesc.setvalue(Double.valueOf(value)); - } - else - { - derivedColumnDesc.setvalue(returnValueForCell); - } - - String equationForCellColor = ((String) derivedColumnDesc.getEquationForCellColor()); - Object returnColorForCell = _beanShellEngine.eval("rowtest", 1, 1, equationForCellColor); - if (returnColorForCell != null) - { - derivedColumnDesc.setCellBackgroundColor(returnColorForCell.toString()); - } - else - { - System.out.println(header + " equationForCellColor = " + equationForCellColor + - " returnColorForCell = " + returnColorForCell); - derivedColumnDesc.setCellBackgroundColor("WHITE"); - } - - } - _bsfManager.undeclareBean("row"); - _bsfManager.undeclareBean("precip"); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - riverMonitorRowData.setDerivedColumnsDetailsList(_derivedColumnsList); - } - - public void alterRiverMonitorRowDataListBasedOnMissingPrecipFilter() - { - _missingRiverMonitorRowDataList.clear(); - - if(! _menuSettings.shouldShowMissingRiver() ) // show missing river is set to false(ie., skip missing river) - { - List finalRiverMonitorRowDataList = new ArrayList(); - - //for each point, check to see if it has some data, if so, then add it to the list. - //at the end, replace the _riverMonitorRowDataList with the filtered list. - for(RiverMonitorJTableRowData riverMonitorRowData: _riverMonitorRowDataList) - { - if(riverMonitorRowData.getLatestObsValue() != DbTable.getNullDouble() || - riverMonitorRowData.getMaxFcstValue() != DbTable.getNullDouble()) - { - finalRiverMonitorRowDataList.add(riverMonitorRowData); - } - else - { - //add to the missing list so that the RiverMonitorDataManager.getLidToCriticalColorMap() method can - //give a complete list - _missingRiverMonitorRowDataList.add(riverMonitorRowData); - } - } - _riverMonitorRowDataList = finalRiverMonitorRowDataList; - finalRiverMonitorRowDataList = null; - Runtime.getRuntime().gc(); - } - } - - /** - * Reads the locrivermon view and creates the list of RiverMonitorJtableRowdata objects for each location - * and fills in its name, state , county info - * @return - */ - public List readRiverLocationInfo() - { - if(_riverLidSet == null) - _riverLidSet = new HashSet (); - else - _riverLidSet.clear(); - - if(_riverMonitorRowDataList != null) - { - for(RiverMonitorJTableRowData riverMonitorRowData: _riverMonitorRowDataList) - { - riverMonitorRowData.resetCellMap(); - } - _riverMonitorRowDataList.clear(); - } - - Runtime.getRuntime().gc(); - List riverMonitorRowDataList = new ArrayList(); - - LocRiverMonView locRivermonView = new LocRiverMonView(_db); - List locRiverMonRecordList; - - loadRiverBasinData(); - - try - { - String whereClause = "order by lid"; - locRiverMonRecordList = locRivermonView.select(whereClause); - if(locRiverMonRecordList != null) - { - for(LocRiverMonRecord locRiverMonRecord : locRiverMonRecordList) - { - RiverMonitorJTableRowData riverMonitorRowData = new RiverMonitorJTableRowData(_missingRepresentation, - this, _logger, _menuSettings); - riverMonitorRowData.setLid(locRiverMonRecord.getLid()); - - riverMonitorRowData.setName(locRiverMonRecord.getName()); - riverMonitorRowData.setCounty(locRiverMonRecord.getCounty()); - riverMonitorRowData.setState(locRiverMonRecord.getState()); - riverMonitorRowData.setStream(locRiverMonRecord.getStream()); - riverMonitorRowData.setHsa(locRiverMonRecord.getHsa()); - - String primaryRiverPe = locRiverMonRecord.getPrimary_pe(); - if (primaryRiverPe == null || primaryRiverPe.length() < 2) - { - primaryRiverPe = "HG"; - } - riverMonitorRowData.setPrimaryRiverPe(primaryRiverPe); - - - riverMonitorRowData.setBankFull(roundTo2DecimalPlaces(locRiverMonRecord.getBankfull())); - - double processedValue = 0.0; - - processedValue = getRiverLevelProcessedValue (locRiverMonRecord.getAction_stage()); - riverMonitorRowData.setActionStage( processedValue ); - - processedValue = getRiverLevelProcessedValue (locRiverMonRecord.getFlood_stage()); - riverMonitorRowData.setFloodStage( processedValue ); - - processedValue = getRiverLevelProcessedValue (locRiverMonRecord.getAction_flow()); - riverMonitorRowData.setActionFlow( processedValue ); - - processedValue = getRiverLevelProcessedValue (locRiverMonRecord.getFlood_flow()); - riverMonitorRowData.setFloodFlow( processedValue ); - - riverMonitorRowData.setMinorStage(roundTo2DecimalPlaces(locRiverMonRecord.getMinor())); - riverMonitorRowData.setMajorStage(roundTo2DecimalPlaces(locRiverMonRecord.getMajor())); - riverMonitorRowData.setModerateStage(roundTo2DecimalPlaces(locRiverMonRecord.getModerate())); - - setRiverBasinData(riverMonitorRowData); - - riverMonitorRowDataList.add(riverMonitorRowData); - - - _riverLidSet.add(locRiverMonRecord.getLid()); - } - } - - - - - } - catch(SQLException e) - { - logSQLException(e); - } - return riverMonitorRowDataList; - } - - - // ----------------------------------------------------------------------------------------- - private double getRiverLevelProcessedValue(double value) - { - double returnValue = value; - - if(value == 0.0) - { - returnValue = DbTable.getNullDouble(); - } - else - { - returnValue = roundTo2DecimalPlaces(value); - } - - return returnValue; - } - - // ----------------------------------------------------------------------------------------- - - private void setRiverBasinData(RiverMonitorJTableRowData rowData) - { - String riverBasin = _lidToRiverBasinMap.get(rowData.getLid()); - - rowData.setRiverBasin(riverBasin); - - return; - } - - private void loadRiverBasinData() - { - LocationTable table = new LocationTable(_db); - String whereClause = "order by lid"; - List recordList = null; - - _lidToRiverBasinMap.clear(); - try - { - recordList = (List) table.select(whereClause); - for (LocationRecord record : recordList) - { - _lidToRiverBasinMap.put(record.getLid(), record.getRb()); - } - } - catch (SQLException e) - { - - } - - } - - public boolean isRiverLocation(String lid) - { - boolean result = false; - - if(_riverLidSet != null) - { - if(_riverLidSet.contains(lid)) - { - result = true; - } - } - return result; - } - - protected void readCurrentRiverMonTableData() - { - /* String header = "RiverMonitorDataManager.readCurrentRiverMonTableData(): "; - _riverMonLocGroupDataManager.readLocationHsaMap(); - _riverMonLocGroupDataManager.readGroupInfo(); - _riverMonLocGroupDataManager.readLocationInfo(); - _riverMonLocGroupDataManager.readGroupHsaMap(); - _riverMonLocGroupDataManager.updateRiverMonitorGroupWithAppropriateHsa(); - */ - _riverMonLocGroupDataManager.initializeRiverMonTableData(); - } - - public List getRiverMonitorRowDataList() - { - return _riverMonitorRowDataList; - } - - public void createRiverMonitorRowDataList() - { - String header = "RiverMonitorDataManager.createRiverMonitorRowDataList(): "; - - _logger.log(header +" Memory Info before creating rowdata list:" + printMemoryInfo()); - Runtime.getRuntime().gc(); - _riverMonitorRowDataList = readRiverLocationInfo(); - - String fcstTs = _menuSettings.getRiverSettings().getFcstTypeSource(); - - readConfigFileToFormLidHeightPEAndLidDischargePEMap(); - - Map lidRowDataMap = new HashMap(); - if(_riverMonitorRowDataList != null) - { - String dischargePE = null; - String heightPE = null; - - readCurrentRiverMonTableData(); - - Runtime.getRuntime().gc(); - _logger.log(header + " Here 1: " + printMemoryInfo()); - _precipDataManager.readPrecipData(_riverMonitorRowDataList, "RIVER"); - Runtime.getRuntime().gc(); - _logger.log(header + " Here 2: "+ printMemoryInfo()); - - Map vtecMap = createGeoIdToVtecEventListMap(); - Map alertAlarmMap = createAlertAlarmInfoToLidMap(); - determineLidToSshpFcstMap(); - - _derivedColumnsList = _derivedColumnsFileManager.getDerivedColumns(); - - for(RiverMonitorJTableRowData riverMonitorRowData: _riverMonitorRowDataList) - { - String lid = riverMonitorRowData.getLid(); - String groupId = _riverMonLocGroupDataManager.getGroupId(lid); - String groupName = _riverMonLocGroupDataManager.getGroupName(groupId); - int groupOrdinal = _riverMonLocGroupDataManager.getGroupOrdinal(groupId); - //String hsa = _riverMonLocGroupDataManager.getHsa(groupId); - int locationOrdinal = _riverMonLocGroupDataManager.getLocationOrdinal(lid); - - riverMonitorRowData.setLid(riverMonitorRowData.getLid()); - riverMonitorRowData.setLocationOrdinal(locationOrdinal); - //riverMonitorRowData.setHsa(hsa); - riverMonitorRowData.setGroupName(groupName); - riverMonitorRowData.setGroupId(groupId); - riverMonitorRowData.setGroupOrdinal(groupOrdinal); - - // Read the latest obs from riverstatus for this lid - RiverStatusRecord riverStatusRecordForObs = null; - riverStatusRecordForObs = determineObsOrFcstRecordFromRiverStatus(lid, - riverMonitorRowData.getPrimaryRiverPe(), "OBS", null); - - if (riverStatusRecordForObs == null) - { - riverMonitorRowData.setLatestObsValue(DbTable.getNullDouble()); - riverMonitorRowData.setLatestObsTime(DbTable.getNullLong()); - riverMonitorRowData.setObsTypeSource(null); - } - else - { - riverMonitorRowData - .setLatestObsValue(roundTo2DecimalPlaces(riverStatusRecordForObs.getValue())); - riverMonitorRowData.setLatestObsTime(riverStatusRecordForObs.getValidtime()); - riverMonitorRowData.setObsTypeSource(riverStatusRecordForObs.getTs()); - } - - // Read the max future forecast from riverstatus for this - // lid - RiverStatusRecord riverStatusRecordForFcst = determineObsOrFcstRecordFromRiverStatus(lid, - riverMonitorRowData.getPrimaryRiverPe(),"FCST", fcstTs); - if (riverStatusRecordForFcst == null) - { - riverMonitorRowData.setMaxFcstValidTime(DbTable.getNullLong()); - riverMonitorRowData.setMaxFcstBasisTime(DbTable.getNullLong()); - riverMonitorRowData.setMaxFcstValue(DbTable.getNullDouble()); - if (!fcstTs.equalsIgnoreCase("IngestFilter")) - riverMonitorRowData.setFcstTypeSource(fcstTs); - else - riverMonitorRowData.setFcstTypeSource(null); - } - else - { - riverMonitorRowData.setMaxFcstValue(roundTo2DecimalPlaces(riverStatusRecordForFcst.getValue())); - riverMonitorRowData.setMaxFcstValidTime(riverStatusRecordForFcst.getValidtime()); - riverMonitorRowData.setMaxFcstBasisTime(riverStatusRecordForFcst.getBasistime()); - riverMonitorRowData.setFcstTypeSource(riverStatusRecordForFcst.getTs()); - } - - dischargePE = null; - heightPE = null; - - // heightPE = ""; dischargePE = ""; - if (_lidHeightPEMap != null && _lidDischargePEMap != null) - { - if (_lidHeightPEMap.size() > 0 && _lidDischargePEMap.size() > 0) - { - heightPE = (String) _lidHeightPEMap.get(lid); - dischargePE = (String) _lidDischargePEMap.get(lid); - } - } - if (heightPE == null || dischargePE == null) // No entry - // found in - // file - { - char firstLetterInPrimaryPE = riverMonitorRowData.getPrimaryRiverPe().charAt(0); - - if (firstLetterInPrimaryPE == 'H') - { - heightPE = riverMonitorRowData.getPrimaryRiverPe(); - dischargePE = getEquivalentDischargePE(riverMonitorRowData.getPrimaryRiverPe()); - } - else - // firstLetterInPrimaryPE is 'Q' - { - dischargePE = riverMonitorRowData.getPrimaryRiverPe(); - heightPE = getEquivalentHeightPE(riverMonitorRowData.getPrimaryRiverPe()); - } - } - - riverStatusRecordForObs = null; - if (heightPE != null) // could be null if the user hasn't - // configured and if the primary pe - // is not QR, QT - riverStatusRecordForObs = determineObsOrFcstRecordFromRiverStatus(lid, heightPE, "OBS", null); - - if (riverStatusRecordForObs == null) - { - riverMonitorRowData.setLatestStgValue(DbTable.getNullDouble()); - riverMonitorRowData.setLatestStgTime(DbTable.getNullLong()); - } - else - { - riverMonitorRowData - .setLatestStgValue(roundTo2DecimalPlaces(riverStatusRecordForObs.getValue())); - riverMonitorRowData.setLatestStgTime(riverStatusRecordForObs.getValidtime()); - } - - riverStatusRecordForObs = null; - if (dischargePE != null) // could be null if the user - // hasn't configured and if the - // primary pe is not HG, HT - riverStatusRecordForObs = determineObsOrFcstRecordFromRiverStatus(lid, dischargePE, "OBS", null); - - if (riverStatusRecordForObs == null) - { - riverMonitorRowData.setLatestFlowValue(DbTable.getNullDouble()); - riverMonitorRowData.setLatestFlowTime(DbTable.getNullLong()); - } - else - { - riverMonitorRowData - .setLatestFlowValue(roundTo2DecimalPlaces(riverStatusRecordForObs.getValue())); - riverMonitorRowData.setLatestFlowTime(riverStatusRecordForObs.getValidtime()); - } - - SshpFcstDetails sshpFcstDetails = getSshpFcstDetailsForLid(riverMonitorRowData.getLid(), - riverMonitorRowData.getFloodStage()); - riverMonitorRowData.setSshpFcstDetails(sshpFcstDetails); - - int numOfHrsForObsLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - long earliestAcceptableTimeForObs = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForObsLookBack; - - if (riverMonitorRowData.getLatestObsTime() > earliestAcceptableTimeForObs) - { - riverMonitorRowData.setObsFcstMax(roundTo2DecimalPlaces(Math.max(riverMonitorRowData - .getLatestObsValue(), riverMonitorRowData.getMaxFcstValue()))); - } - else - { - riverMonitorRowData.setObsFcstMax(roundTo2DecimalPlaces(riverMonitorRowData.getMaxFcstValue())); - } - - if ((riverMonitorRowData.getObsFcstMax() != DbTable.getNullDouble()) - && (riverMonitorRowData.getFloodStage() != DbTable.getNullDouble())) - { - riverMonitorRowData.setFldStgDeparture(roundTo2DecimalPlaces(riverMonitorRowData.getObsFcstMax() - - riverMonitorRowData.getFloodStage())); - } - else - { - riverMonitorRowData.setFldStgDeparture(roundTo2DecimalPlaces(DbTable.getNullDouble())); - } - - if ((riverMonitorRowData.getObsFcstMax() != DbTable.getNullDouble()) - && (riverMonitorRowData.getActionStage() != DbTable.getNullDouble())) - riverMonitorRowData.setActStgDeparture(roundTo2DecimalPlaces(riverMonitorRowData - .getObsFcstMax() - - riverMonitorRowData.getActionStage())); - else - riverMonitorRowData.setActStgDeparture(roundTo2DecimalPlaces(DbTable.getNullDouble())); - - riverMonitorRowData.setVtecEventList(getVtecEventList(lid, vtecMap)); - - setAlertAlarmDetails(riverMonitorRowData, alertAlarmMap); - - /* _logger.log(precipMonitorRowData.getLid() + "|" + precipMonitorRowData.getName() + "|" - + precipMonitorRowData.getGroupId() + "|" + precipMonitorRowData.getGroupName() + "|" - + precipMonitorRowData.getLocationOrdinal() + "|" - + precipMonitorRowData.getGroupOrdinal() );*/ - - - riverMonitorRowData.addAllCellsToMap(); - - getDerivedColumnsInfo(riverMonitorRowData); - riverMonitorRowData.addDerivedDataToCellMap(); - - lidRowDataMap.put(riverMonitorRowData.getLid(), riverMonitorRowData); - - } - - /* - _logger.log(header + "Before missing precip filter is applied, alllocationinfo list size:" + _riverMonitorRowDataList.size()); - - alterRiverMonitorRowDataListBasedOnMissingPrecipFilter(); - - _logger.log(header + "After missing precip filter is applied, alllocationinfo list size:" + _riverMonitorRowDataList.size()); - */ - } - - Runtime.getRuntime().gc(); - _logger.log(header +" Memory Info after creating rowdata list:" + printMemoryInfo()); - - } - -// --------------------------------------------------------------------------------------------------- - - public String printMemoryInfo() - { - String str = "Free:" + Runtime.getRuntime().freeMemory()+ " Max:"+ Runtime.getRuntime().maxMemory()+ " total:"+ Runtime.getRuntime().totalMemory(); - return str; - } - - public PrecipColumnDataSettings getPrecipSettings() - { - return _menuSettings.getPrecipSettings(); - } - -// --------------------------------------------------------------------------------------------------- - - private List getListOfLocationIds() - { - List locationIdList = new ArrayList(); - - for (RiverMonitorJTableRowData rowData : _riverMonitorRowDataList) - { - locationIdList.add(rowData.getLid()); - } - - return locationIdList; - - } -// --------------------------------------------------------------------------------------------------- - - public List createStringArrayListOfFilterItems() - { - String header = "RiverMonitorDataManager.createStringArrayListOfFilterItems(): "; - - List locationIdList = getListOfLocationIds(); - - List listOfNodePathStringArray = - _riverMonLocGroupDataManager.createStringArrayListOfFilterItems(locationIdList); - - return listOfNodePathStringArray; - } - -// --------------------------------------------------------------------------------------------------- -/* - private List createStringArrayListOfFilterItemsOld() - { - List listOfStringArray = new ArrayList(); - - List locationIdList = getListOfLocationIds(); - - - String rootItem = "HSA"; - String firstLevelFilterItems[] = _riverMonLocGroupDataManager.getAllHsa(); - String[] currentStringArray; - - if(firstLevelFilterItems != null && firstLevelFilterItems.length > 0) - { - String currentFirstLevelFilterItem = null; - for(int i=0; i < firstLevelFilterItems.length; i++) - { - currentFirstLevelFilterItem = firstLevelFilterItems[i]; - String secondLevelFilterItems[] = _riverMonLocGroupDataManager.getGroupsForHsa(firstLevelFilterItems[i]); - if(secondLevelFilterItems != null && secondLevelFilterItems.length > 0) - { - String currentSecondLevelFilterItem = null; - for(int j=0; j < secondLevelFilterItems.length; j++) - { - currentSecondLevelFilterItem = _riverMonLocGroupDataManager.getGroupName(secondLevelFilterItems[j]); - String thirdLevelFilterItems[] = _riverMonLocGroupDataManager.getAllLocationsForGroup(secondLevelFilterItems[j], locationIdList); - if(thirdLevelFilterItems != null && thirdLevelFilterItems.length > 0) - { - for(int k=0; k < thirdLevelFilterItems.length; k++) - { - if(isRiverLocation(thirdLevelFilterItems[k])) - { - currentStringArray = new String[4]; - currentStringArray[0] = rootItem; - currentStringArray[1] = currentFirstLevelFilterItem; - currentStringArray[2] = currentSecondLevelFilterItem; - currentStringArray[3] = thirdLevelFilterItems[k]; - listOfStringArray.add(currentStringArray); - } - } - } - else - { - currentStringArray = new String[3]; - currentStringArray[0] = rootItem; - currentStringArray[1] = currentFirstLevelFilterItem; - currentStringArray[2] = currentSecondLevelFilterItem; - listOfStringArray.add(currentStringArray); - } - } - } - else - { - currentStringArray = new String[2]; - currentStringArray[0] = rootItem; - currentStringArray[1] = currentFirstLevelFilterItem; - listOfStringArray.add(currentStringArray); - } - } - } - else - { - currentStringArray = new String[1]; - currentStringArray[0] = rootItem; - listOfStringArray.add(currentStringArray); - } - - return listOfStringArray; - } - -*/ - - private Map createGeoIdToVtecEventListMap() - { - String header = "RiverMonitorDataManager.createGeoIdToVtecEventListMap():"; - Map vtecMap = new HashMap(); - VTECeventTable vtecEventTable = new VTECeventTable(_db); - String whereClause = null; - CodeTimer timer = new CodeTimer(); - try - { - timer.start(); - - // retrieve data for VTEC events which are not statements and the - // end time has been set - whereClause = " where signif != 'S' and endtime is not null order by geoid, endtime asc"; - _logger.log(header + " where clause:" + whereClause); - List tempVtecEventWhichArentStatementAndEndTimeIsNotNull = vtecEventTable.select(whereClause); - - // retrieve data for VTEC events which are not statements and the - // end time has NOT been set - whereClause = " where signif != 'S' and endtime is null order by geoid "; - _logger.log(header + " where clause:" + whereClause); - List tempVtecEventWhichArentStatementAndEndTimeIsNull = vtecEventTable.select(whereClause); - - // merge the two lists - List allVtecEventWhichArentStatementsList = new ArrayList(); - allVtecEventWhichArentStatementsList.addAll(tempVtecEventWhichArentStatementAndEndTimeIsNotNull); - allVtecEventWhichArentStatementsList.addAll(tempVtecEventWhichArentStatementAndEndTimeIsNull); - - timer.stop("Rivermonitor data mgr- read vtec event time elapsed:"); - - // assign each record to the map - for (int i = 0; i < allVtecEventWhichArentStatementsList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) allVtecEventWhichArentStatementsList.get(i); - String geoId = record.getGeoid(); - - List eventList = (List) vtecMap.get(geoId); - if (eventList == null) - { - eventList = new ArrayList(); - vtecMap.put(geoId, eventList); - } - eventList.add(record); - } - } - catch (SQLException e) - { - _logger.log(header); - logSQLException(e); - } - - return vtecMap; - } - - private List getVtecEventList(String lid, Map vtecMap) - { - List finalVtecEventList = null; - - if (vtecMap != null) - { - if (vtecMap.size() > 0) - { - finalVtecEventList = (List) vtecMap.get(lid); - } - } - return finalVtecEventList; - } - - protected String getEquivalentHeightPE(String pe) - { - String heightPE = null; - if (pe.equalsIgnoreCase("QR")) - heightPE = "HG"; - else if (pe.equalsIgnoreCase("QT")) - heightPE = "HT"; - return heightPE; - } - - protected String getEquivalentDischargePE(String pe) - { - String dischargePE = null; - if (pe.equalsIgnoreCase("HG")) - dischargePE = "QR"; - else if (pe.equalsIgnoreCase("HT")) - dischargePE = "QT"; - return dischargePE; - } - - private void readValidHeightAndDischargePE() - { - List shefPEInfoList = null; - - ShefPeTable shefPeTable = new ShefPeTable(_db); - String whereClause = null; - String header = "RiverMonitorDataManager.readValidHeightAndDischargePE(): "; - - CodeTimer timer = new CodeTimer(); - try - { - whereClause = "where pe like 'H%' or pe like 'Q%'"; - timer.start(); - shefPEInfoList = shefPeTable.select(whereClause); - timer.stop("Read from shefpe time elapsed:"); - _logger.log(header + " Where Clause:" + whereClause); - if (shefPEInfoList == null) - { - _logger.log(header + " height and discharge pe list is null"); - } - else - { - if (shefPEInfoList.size() > 0) - { - _validHeightAndDischargePEList = new ArrayList(); - for (int i = 0; i < shefPEInfoList.size(); i++) - { - - ShefPeRecord record = (ShefPeRecord) shefPEInfoList.get(i); - _validHeightAndDischargePEList.add(record.getPe()); - } - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - } - - - private boolean validatePE(String pe) - { - boolean result = false; - - if (_validHeightAndDischargePEList != null) - { - for (int i = 0; i < _validHeightAndDischargePEList.size(); i++) - { - String tempStr = (String) _validHeightAndDischargePEList.get(i); - if (pe.equals(tempStr)) - { - result = true; - break; - } - } - } - return result; - } - - private void readConfigFileToFormLidHeightPEAndLidDischargePEMap() - { - Map lidHeightPEMap = null; - Map lidDischargePEMap = null; - - String header = "RiverMonitorDataManager.readConfigFileAndFormConfigMap(): "; - File fileHandler = new File(_peConfigFileName); - - if (fileHandler.exists()) - { - BufferedReader in = null; - String str; - List stringList = new ArrayList(); - - try - { - in = new BufferedReader(new FileReader(fileHandler)); - while ((str = in.readLine()) != null) - { - stringList.add(str); - } - } - catch (IOException exception) - { - printFileException(exception, header); - } - if (stringList.size() > 0) - { - for (int i = 0; i < stringList.size(); i++) - { - String tempString = (String) stringList.get(i); - if (tempString.length() == 0) - continue; - if (tempString.charAt(0) == '#') - continue; - String splitStr[] = null; - splitStr = tempString.split("\\|"); - if (splitStr == null) - continue; - String lid, heightPE, dischargePE; - if (splitStr.length == 3) - { - splitStr[0] = splitStr[0].trim(); - splitStr[1] = splitStr[1].trim(); - splitStr[2] = splitStr[2].trim(); - if (splitStr[0].length() > 0 && splitStr[1].length() == 2 && splitStr[2].length() == 2) - { - lid = splitStr[0]; - heightPE = splitStr[1]; - dischargePE = splitStr[2]; - if (heightPE.charAt(0) != 'H' || dischargePE.charAt(0) != 'Q') - { - _logger.log(header + "Invalid height and discharge PE [" + heightPE + "|" + dischargePE - + "]"); - continue; - } - if ((!validatePE(heightPE)) || (!validatePE(dischargePE))) - { - _logger.log(header + "Invalid height and discharge PE [" + heightPE + "|" + dischargePE - + "]"); - continue; - } - else - { - if (lidHeightPEMap == null) - { - lidHeightPEMap = new HashMap(); - } - lidHeightPEMap.put(lid, heightPE); - if (lidDischargePEMap == null) - { - lidDischargePEMap = new HashMap(); - } - lidDischargePEMap.put(lid, dischargePE); - } - - } - else - // invalid entry - { - _logger.log(header + "1. Invalid entry[" + tempString + "] in ConfigFile "); - continue; - } - - } - else - // line not having the format lid|PETS|PETS - { - _logger.log(header + "2. Invalid entry[" + tempString + "] in ConfigFile "); - continue; - } - } - } - } - else - { - _logger.log(header + "ConfigFile [" + _peConfigFileName + "] doesn't exist"); - } - - _lidHeightPEMap = lidHeightPEMap; - _lidDischargePEMap = lidDischargePEMap; - } - - protected void printFileException(IOException exception, String header) - { - header = header+".printFileException(): "; - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - _logger.log(header+"End of stack trace"); - } -// --------------------------------------------------------------------------------------------------- - - private double roundTo2DecimalPlaces(double number) - { - double result = DbTable.getNullDouble(); - if (number != DbTable.getNullDouble()) - result = MathHelper.roundToNDecimalPlaces(number, 2); - - return result; - } - - public String getDefaultHsa() - { - return _defaultHsa; - } - - public Map getLidDescDetails() - { - if (_lidDescDetailsMap == null) - { - LocRiverMonView riverMonView = new LocRiverMonView(_db); - try - { - List riverMonViewList = (List) riverMonView.select(""); - if (riverMonViewList != null) - { - if (riverMonViewList.size() > 0) - { - _lidDescDetailsMap = new HashMap(); - for (int i = 0; i < riverMonViewList.size(); i++) - { - LocRiverMonRecord record = (LocRiverMonRecord) riverMonViewList.get(i); - String name = record.getName(); - if (name != null) - { - if (name.length() > 0) - { - if (name.length() > 50) - { - name = name.substring(0, 50); - } - } - } - String desc = name + ";" + record.getState() + ";" + record.getCounty(); - _lidDescDetailsMap.put(record.getLid(), desc); - } - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - } - return _lidDescDetailsMap; - } - - private void setAlertAlarmDetails(RiverMonitorJTableRowData rowData, Map alertAlarmMap) - { - String lid = rowData.getLid(); - AlertAlarmValRecord alertAlarmValRecord = (AlertAlarmValRecord) alertAlarmMap.get(lid); - if(alertAlarmValRecord != null) - { - if (alertAlarmValRecord.getPe().equals(rowData.getPrimaryRiverPe()) - && alertAlarmValRecord.getLid().equals(rowData.getLid())) - { - String categ = alertAlarmValRecord.getAa_categ(); - String check = alertAlarmValRecord.getAa_check(); - - if ((check.equalsIgnoreCase("Upper")) && categ.equalsIgnoreCase("alert")) - { - rowData.setAlertUpperLimit(true); - } - else if ((check.equalsIgnoreCase("Upper")) && categ.equalsIgnoreCase("alarm")) - { - rowData.setAlarmUpperLimit(true); - } - else if ((check.equalsIgnoreCase("Lower")) && categ.equalsIgnoreCase("alert")) - { - rowData.setAlertLowerLimit(true); - } - else if ((check.equalsIgnoreCase("Lower")) && categ.equalsIgnoreCase("alarm")) - { - rowData.setAlarmLowerLimit(true); - } - else if ((check.equalsIgnoreCase("Diff")) && categ.equalsIgnoreCase("alert")) - { - rowData.setAlertDiffLimit(true); - } - else if ((check.equalsIgnoreCase("Diff")) && categ.equalsIgnoreCase("alarm")) - { - rowData.setAlarmDiffLimit(true); - } - else if ((check.equalsIgnoreCase("Roc")) && categ.equalsIgnoreCase("alert")) - { - rowData.setAlertRocLimit(true); - } - else if ((check.equalsIgnoreCase("Roc")) && categ.equalsIgnoreCase("alarm")) - { - rowData.setAlarmRocLimit(true); - } - } - } - } - - private Map createAlertAlarmInfoToLidMap() - { - String header = "RiverMonitorDataManager.addAlertAlarmInfoToRowDataList(): "; - List alertAlarmList; - Map alertAlarmMap = new HashMap(); - AlertAlarmValTable alertAlarmValTable = new AlertAlarmValTable(_db); - int numOfHrsForAlertAlarmValidTimeLookBack = 1; - numOfHrsForAlertAlarmValidTimeLookBack = _menuSettings.getRiverSettings().getAlertAlarmLookBack(); - - _logger.log(header + "numOfHrsForValidTimeLookBack:" + numOfHrsForAlertAlarmValidTimeLookBack); - - String whereClause = null; - long tempTime = System.currentTimeMillis() - MILLIS_PER_HOUR * numOfHrsForAlertAlarmValidTimeLookBack; - String validTime = DbTimeHelper.getDateTimeStringFromLongTime(tempTime); - - try - { - whereClause = " where validtime >" + "'" + validTime + "'" + " order by lid, pe"; - _logger.log(header + "Where clause:" + whereClause); - - alertAlarmList = alertAlarmValTable.select(whereClause); - - for (int i = 0; i < alertAlarmList.size(); i++) - { - AlertAlarmValRecord alertAlarmValRecord = (AlertAlarmValRecord) alertAlarmList.get(i); - alertAlarmMap.put(alertAlarmValRecord.getLid(), alertAlarmValRecord); - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return alertAlarmMap; - } - -// ----------------------------------------------------------------------------------------------------------------------- - - private SshpFcstDetails getSshpFcstDetailsForLid(String lid, double floodStage) - { - - if (_sshpLidFcstMap == null) - determineLidToSshpFcstMap(); - SshpFcstDetails sshpFcstDetails = new SshpFcstDetails(); - RegularTimeSeries fcstRegularTimeSeries = (RegularTimeSeries) _sshpLidFcstMap.get(lid); - if (fcstRegularTimeSeries != null) - { - AbsTimeMeasurement maxMeasurement = (AbsTimeMeasurement) fcstRegularTimeSeries.getMaxMeasurement(); - if(maxMeasurement != null) - { - sshpFcstDetails.setCrestValue(roundTo2DecimalPlaces(maxMeasurement.getValue())); - sshpFcstDetails.setCrestTime(maxMeasurement.getTime()); - - for (int index = 0; index < fcstRegularTimeSeries.getMeasurementCount(); index++) - { - AbsTimeMeasurement forecastMeasurement = fcstRegularTimeSeries.getAbsTimeMeasurementByIndex(index); - - if (forecastMeasurement.getValue() >= floodStage) - { - sshpFcstDetails.setTimeAboveFldStg(fcstRegularTimeSeries.getMeasurementTimeByIndex(index)); - break; - } - } - // basis time will be the last modified time of the file - // basinid_fcst_stage.dat - sshpFcstDetails.setBasisTime(new File(_sshpFcstDataDir + "/" + lid + "_fcst_stage.dat").lastModified()); - } - - } - return sshpFcstDetails; - } - -// --------------------------------------------------------------------------------------------------------------- - private RegularTimeSeries loadForecastFileMapTimeSeries(String filePath) - { - TimeSeriesFileManager reader = new TimeSeriesFileManager(); - - RegularTimeSeries timeSeries = null; - - timeSeries = reader.readRegularTimeSeries(filePath, MeasuringUnit.inches); - - return timeSeries; - } - -// ----------------------------------------------------------------------------------------------------------------------- - - private void determineLidToSshpFcstMap() - { - _sshpLidFcstMap = new HashMap(); - - File sshpFcstDataPath = new File(_sshpFcstDataDir); - - if (!sshpFcstDataPath.exists()) - { - _logger.log("Sshp fcst data dir:[" + _sshpFcstDataDir - + "] doesn't exist...Check the token value for sshp_background_forecast_output_dir"); - } - else - { - File[] fcstFilesArray = sshpFcstDataPath.listFiles(); - - if (fcstFilesArray != null) - { - if (fcstFilesArray.length > 0) - { - // basis time look back window filter value - int numOfHrsForLatestFcstLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - long lookBackWindowTimeLong = System.currentTimeMillis() - MILLIS_PER_HOUR - * numOfHrsForLatestFcstLookBack; - - for (int i = 0; i < fcstFilesArray.length; i++) - { - // if file's last modified time is within the basis time - // look back window - if (fcstFilesArray[i].lastModified() >= lookBackWindowTimeLong) - { - String fileName = fcstFilesArray[i].getName(); - if (fileName.endsWith(".dat")) - { - RegularTimeSeries fcstRegularTimeSeries = loadForecastFileMapTimeSeries(fcstFilesArray[i] - .getAbsolutePath()); - - if (fcstRegularTimeSeries == null) - continue; - - int indexOfUnderScore = fileName.indexOf('_'); - String lid = fileName.substring(0, indexOfUnderScore); - _sshpLidFcstMap.put(lid, fcstRegularTimeSeries); - - // System.out.println("Read the sshp forecast - // file["+ fcstFilesArray[i].getAbsolutePath() - // +"] and added the time series to the map"); - } - } - } - } - else - { - _logger.log("Sshp fcst files are not available in the sshpfcst dir:[" + _sshpFcstDataDir + "]"); - } - } - } - } - -// ----------------------------------------------------------------------------------------------------------------------- - - private RiverStatusRecord determineObsOrFcstRecordFromRiverStatus(String lid, String primaryPe, String tag, - String fcstTs) - { - List riverStatusRecordList = new ArrayList(); - RiverStatusTable riverStatusTable = new RiverStatusTable(_db); - RiverStatusRecord riverStatusRecord = null; - Map tsRankMap = null; - List tsDurExtValTimeList = new ArrayList(); - String whereClause = null; - - if (tag.compareTo("OBS") == 0) - { - whereClause = " where lid = " + "'" + lid + "'" + " and pe='" + primaryPe + "' and (ts like 'R%')" - + " order by validtime desc"; - } - else - // Tag is FCST - { - int numOfHrsForBasisTimeLookBack = 1; - numOfHrsForBasisTimeLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - - long allowedBasisTime = System.currentTimeMillis() - (MILLIS_PER_HOUR * numOfHrsForBasisTimeLookBack); - - String allowedBasisTimeString = DbTimeHelper.getDateTimeStringFromLongTime(allowedBasisTime); - - if (fcstTs.compareTo("IngestFilter") == 0) - { - whereClause = " where lid = " + "'" + lid + "'" + " and pe='" + primaryPe + "' and (ts like 'F%')" - + " and basistime >= '" + allowedBasisTimeString + "' order by value desc"; - } - else - // TS for fcst recs is chosen to be 'FF' or 'FZ' - { - whereClause = " where lid = " + "'" + lid + "'" + " and pe='" + primaryPe + "' and ts='" + fcstTs + "'" - + " and basistime >= '" + allowedBasisTimeString + "'"; - } - } - - // ("Tag:"+tag +" clause:"+ whereClause); - try - { - riverStatusRecordList = riverStatusTable.select(whereClause); - } - catch (SQLException e) - { - logSQLException(e); - } - - if (riverStatusRecordList.size() == 0) - return riverStatusRecord; - - // Key for riverstatus table are lid, pe, ts. So we will get only one - // record if - // fcstTs is either FF or FZ .Hence the list size will be 1. So move to - // else part - // The below If logic will be used only if fcsTs has value IngestFilter. - // If more than one rec is found then use ingest filter decide based on - // ts rank - // Else return the single record in the list. - if (riverStatusRecordList.size() > 1) - { - for (int loopcnt = 0; loopcnt < riverStatusRecordList.size(); loopcnt++) - { - riverStatusRecord = (RiverStatusRecord) riverStatusRecordList.get(loopcnt); - TsDurExtValTime tsDurExtValTime = new TsDurExtValTime(); - - /* - * System.out.println("statusrec - * has:"+riverStatusRecord.getTs()+"|"+ - * riverStatusRecord.getDur()+"|"+ - * riverStatusRecord.getExtremum()+"|"+ - * riverStatusRecord.getValidtime()+"|"+ - * riverStatusRecord.getValue()); - */ - - tsDurExtValTime.setTs(riverStatusRecord.getTs()); - tsDurExtValTime.setDuration(riverStatusRecord.getDur()); - tsDurExtValTime.setExtremum(riverStatusRecord.getExtremum()); - tsDurExtValTime.setTime(riverStatusRecord.getValidtime()); - tsDurExtValTime.setValue(riverStatusRecord.getValue()); - tsDurExtValTimeList.add(tsDurExtValTime); - - tsDurExtValTime = (TsDurExtValTime) tsDurExtValTimeList.get(loopcnt); - /* - * System.out.println("After add In list - * loopcnt:"+loopcnt+"|"+tsDurExtValTime.getTs()+"|"+tsDurExtValTime.getDuration()+"|"+ - * tsDurExtValTime.getExtremum()); - */ - - } - tsRankMap = createIngestFilterTsRankMap(lid, tsDurExtValTimeList, primaryPe); - riverStatusRecord = compareTsRankAndRiverStatusInfo(tsRankMap, riverStatusRecordList, tsDurExtValTimeList); - - } - else - { - riverStatusRecord = null; - riverStatusRecord = (RiverStatusRecord) riverStatusRecordList.get(0); - } - /* - * System.out.println("Rec is:"+ riverStatusRecord.getLid()+"|"+ - * riverStatusRecord.getPe()+"|"+riverStatusRecord.getTs()+"|"+ - * riverStatusRecord.getValue()); - */ - - return riverStatusRecord; - } - - private Map createIngestFilterTsRankMap(String lid, List tsDurExtValTimeList, String pe) - { - Map tsRankMap = new HashMap(); - IngestFilterTable ingestFilterTable = new IngestFilterTable(_db); - IngestFilterRecord ingestFilterRecord = null; - List ingestFilterRecordList = new ArrayList(); - String whereClause = null; - String ts = null; - int duration = 0; - String extremum = null; - TsDurExtValTime tsDurExt = null; - Integer curTsRank = null; - - for (int loopcnt = 0; loopcnt < tsDurExtValTimeList.size(); loopcnt++) - { - tsDurExt = (TsDurExtValTime) tsDurExtValTimeList.get(loopcnt); - ts = tsDurExt.getTs(); - duration = tsDurExt.getDuration(); - extremum = tsDurExt.getExtremum(); - // System.out.println("For:ts|dur|ext:"+ts+"|"+duration+"|"+extremum); - try - { - whereClause = " where lid='" + lid + "' and pe='" + pe + "' and ts='" + ts + "' and dur=" + duration - + " and extremum='" + extremum + "'"; - - // System.out.println("ingestfilter whereclause:"+whereClause); - ingestFilterRecordList = ingestFilterTable.select(whereClause); - // System.out.println("after ingestfilter - // whereclause:"+whereClause); - if (ingestFilterRecordList.size() > 0) - { - ingestFilterRecord = (IngestFilterRecord) ingestFilterRecordList.get(0); - curTsRank = new Integer(ingestFilterRecord.getTs_rank()); - } - else - { - curTsRank = new Integer(-1); - } - /* - * System.out.println("Before add to map ts|dur|ext|curtsrank: "+ - * ts+"|"+duration+"|"+extremum+"|"+ curTsRank); - */ - - tsRankMap.put(new Integer(loopcnt), curTsRank); - - // System.out.println("After Add to rankmap"); - } - catch (SQLException e) - { - logSQLException(e); - } - } - - return tsRankMap; - } - - private RiverStatusRecord compareTsRankAndRiverStatusInfo(Map tsRankMap, List riverStatusRecordList, - List tsDurExtValTimeList) - { - RiverStatusRecord matchRiverStatusRecord = null; - int prevTsRank = -1; - int bestTsRank = -1; - int matchIndex = -1; - int cntOfSameTsRank = 0; - List indexOfSameTsRankList = new ArrayList(); - - // System.out.println("In compare function"); - for (int loopcnt = 0; loopcnt < riverStatusRecordList.size(); loopcnt++) - { - int curTsRank = new Integer(tsRankMap.get(new Integer(loopcnt)).toString()).intValue(); - if (curTsRank == -1) - continue; - if (bestTsRank == -1) - { - prevTsRank = curTsRank; - bestTsRank = curTsRank; - matchIndex = loopcnt; - // System.out.println("loop:[ "+ loopcnt+"]:"+ bestTsRank+ " "+ - // matchIndex); - } - else - { - // System.out.println("Comparing curTsRank < bestTsRank" + - // curTsRank + bestTsRank); - if (curTsRank < bestTsRank) - { - prevTsRank = curTsRank; - bestTsRank = curTsRank; - matchIndex = loopcnt; - // System.out.println("loop:[ "+ loopcnt+"]:"+ bestTsRank+ " - // "+ matchIndex); - } - else - { - bestTsRank = prevTsRank; - prevTsRank = curTsRank; - // System.out.print("False"); - // System.out.println("loop:[ "+ loopcnt+"]:"+ bestTsRank+ " - // "+ matchIndex); - } - } - } - - // Match is found for highest ts_rank. Now check if there are multiple - // ts with same ts rank. - // If so consider all the recs in riverstatus that have the same ts rank - // and decide as below. - // For obs data consider the rec that has latest valid time. - // For fcst data consider the rec that has max value. - if (matchIndex != -1) - { - int highestTsRank = bestTsRank; - int curTsRank; - - // System.out.println("riverstatsrecscnt:"+riverStatusRecordList.size()); - // System.out.println("tsranksize:"+tsRankMap.size()); - for (int loopcnt = 0; loopcnt < tsRankMap.size(); loopcnt++) - { - // System.out.println("here3:"+Integer.valueOf(tsRankMap.get(Integer.valueOf(loopcnt)).toString()).intValue()); - curTsRank = new Integer(tsRankMap.get(new Integer(loopcnt)).toString()).intValue(); - - if (curTsRank == highestTsRank) - { - cntOfSameTsRank++; - indexOfSameTsRankList.add(new Integer(loopcnt)); - } - } - if (cntOfSameTsRank == 1) - matchRiverStatusRecord = (RiverStatusRecord) riverStatusRecordList.get(matchIndex); - } - - // At this point more than 1 rec is got from riverstatus and - // either no match is found in ingestfilter and since - // Or multiple ts having same ts rank then do the following - if (matchIndex == -1 || cntOfSameTsRank > 1) - { - // since we query the riverstatus with valid time desc/ value desc - // for fcst/obs - // respectively we will use the - // first rec that match the highest rank ts amongst the recs - // obtained - int index = new Integer(indexOfSameTsRankList.get(0).toString()).intValue(); - matchRiverStatusRecord = (RiverStatusRecord) riverStatusRecordList.get(index); - } - - /* - * System.out.println("Final best match:"+ - * matchRiverStatusRecord.getLid()+"|"+ - * matchRiverStatusRecord.getPe()+"|"+ matchRiverStatusRecord.getTs()+ - * "|"+ matchRiverStatusRecord.getExtremum()+ - * "|"+matchRiverStatusRecord.getDur()+ - * "|"+matchRiverStatusRecord.getValue()+"|"+ "Rank: "+bestTsRank); - */ - return matchRiverStatusRecord; - } - - private class TsDurExtValTime - { - private String ts = null; - - private int duration = 0; - - private String extremum = null; - - private long time; - - private double value; - - protected void setTs(String ts) - { - this.ts = ts; - } - - protected String getTs() - { - return this.ts; - } - - protected void setDuration(int dur) - { - this.duration = dur; - } - - protected int getDuration() - { - return this.duration; - } - - protected void setExtremum(String ext) - { - this.extremum = ext; - } - - protected String getExtremum() - { - return this.extremum; - } - - protected long getTime() - { - return time; - } - - protected void setTime(long time) - { - this.time = time; - } - - protected double getValue() - { - return value; - } - - protected void setValue(double value) - { - this.value = value; - } - } - - public class SshpFcstDetails - { - private double _crestValue; - - private long _crestTime; - - private long _timeAboveFldStg; - - private long _basisTime; - - public SshpFcstDetails() - { - _crestValue = DbTable.getNullDouble(); - _crestTime = DbTable.getNullLong(); - _timeAboveFldStg = DbTable.getNullLong(); - _basisTime = DbTable.getNullLong(); - } - - public long getBasisTime() - { - return _basisTime; - } - - public void setBasisTime(long basisTime) - { - this._basisTime = basisTime; - } - - public long getCrestTime() - { - return _crestTime; - } - - public void setCrestTime(long crestTime) - { - this._crestTime = crestTime; - } - - public double getCrestValue() - { - return _crestValue; - } - - public void setCrestValue(double crestValue) - { - this._crestValue = crestValue; - } - - public long getTimeAboveFldStg() - { - return _timeAboveFldStg; - } - - public void setTimeAboveFldStg(long timeAboveFldStg) - { - this._timeAboveFldStg = timeAboveFldStg; - } - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorJTableRowData.java deleted file mode 100644 index ab60730094..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorJTableRowData.java +++ /dev/null @@ -1,1947 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.monitor.MonitorCell; -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.monitor.river.RiverMonitorDataManager.SshpFcstDetails; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.derivedcolumns.DerivedColumn; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.monitor.precip.PrecipData; -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.CellType; - -public class RiverMonitorJTableRowData extends AbstractJTableRowData /*implements JTableRowData */ -{ - private int _defaultDecimalPoints = 2; - - private static Map _derivedReturnTypeToCellTypeMap = new HashMap(); - - private String _groupName; - private String _lid; - private String _name; - private String _county; - private String _state; - private String _hsa; - private String _stream; - private String _riverBasin; - private double _bankFull; - private double _actionStage; - private double _floodStage; - private double _foodFlow; - private double _actionFlow; - private String _groupId; - private double _latestObsValue; - private long _latestObsTime; - private double _latestStgValue; - private long _latestStgTime; - private double _latestFlowValue; - private long _latestFlowTime; - private double _maxFcstValue; - private long _maxFcstValidTime; - private long _maxFcstBasisTime; - private double _sshpMaxFcstValue; - private long _sshpMaxFcstTime; - private long _sshpFcstBasisTime; - private long _sshpFcstFloodTime; - private int _groupOrdinal; - private int _locationOrdinal; - private double _obsFcstMax; - private double _fldStgDeparture; - private double _actStgDeparture; - private double _minorStage; - private double _majorStage; - private double _moderateStage; - private List _derivedColumnsDetailsList; - private List _vtecEventList; - private boolean _alertUpperLimit = false; - private boolean _alarmUpperLimit = false; - private boolean _alertLowerLimit = false; - private boolean _alarmLowerLimit = false; - private boolean _alertRocLimit = false; - private boolean _alarmRocLimit = false; - private boolean _alertDiffLimit = false; - private boolean _alarmDiffLimit = false; - private String _primaryRiverPe; - private String _obsTypeSource; - private String _fcstTypeSource; - protected RiverMonitorDataManager _riverMonitorDataManager; - protected RiverMonitorVtecEventDataManager _riverMonitorVtecEventDataManager; - private String _toolTipTextForAlertAlarmSummary; - private String _toolTipTextForThreatSummary; - private String _toolTipTextForPrecipThreatSummary; - private SshpFcstDetails _sshpFcstDetails; - - private PrecipData _precipData; - private SessionLogger _logger; - - private static Set _ignoreColumnNameForThreatSet = new HashSet(); - - private RiverMonitorMenuSettings _menuSettings; - - static - { - _derivedReturnTypeToCellTypeMap.put("boolean", CellType.BOOLEAN); - _derivedReturnTypeToCellTypeMap.put("double", CellType.DOUBLE); - _derivedReturnTypeToCellTypeMap.put("float", CellType.FLOAT); - _derivedReturnTypeToCellTypeMap.put("long", CellType.LONG); - _derivedReturnTypeToCellTypeMap.put("int", CellType.INTEGER); - _derivedReturnTypeToCellTypeMap.put("string", CellType.STRING); - - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_FLOW_TIME); - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_FLOW_VALUE); - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_STG_TIME); - _ignoreColumnNameForThreatSet.add(RiverColumns.LAT_STG_VALUE); - - } - - public RiverMonitorJTableRowData() - { - - } - - public RiverMonitorJTableRowData(String missingRepresentation, RiverMonitorDataManager riverMonitorDataManager, - SessionLogger logger, RiverMonitorMenuSettings menuSettings) - { - setMissingRepresentation(missingRepresentation); - _riverMonitorDataManager = riverMonitorDataManager; - _logger = logger; - - _menuSettings = menuSettings; - } - - //----------------------------------------------------------------- - // Copy constructor - //----------------------------------------------------------------- - public RiverMonitorJTableRowData(RiverMonitorJTableRowData origRecord) - { - setLid(origRecord.getLid()); - setName(origRecord.getName()); - setCounty(origRecord.getCounty()); - setState(origRecord.getState()); - setHsa(origRecord.getHsa()); - setStream(origRecord.getStream()); - setRiverBasin(origRecord.getRiverBasin()); - setBankFull(origRecord.getBankFull()); - setActionStage(origRecord.getActionStage()); - setFloodStage(origRecord.getFloodStage()); - setFloodFlow(origRecord.getFloodFlow()); - setActionFlow(origRecord.getActionFlow()); - setGroupId(origRecord.getGroupId()); - setGroupName(origRecord.getGroupName()); - } - - public String getLid() - { - return _lid; - } - - public void setLid(String lid) - { - this._lid = lid ; - } - - public String getName() - { - return _name; - } - - public void setName(String name) - { - this._name = name ; - } - - public String getCounty() - { - return _county; - } - - public void setCounty(String county) - { - this._county = county ; - } - - public String getState() - { - return _state; - } - - public void setState(String state) - { - this._state = state ; - } - - public String getHsa() - { - return _hsa; - } - - public void setHsa(String hsa) - { - this._hsa = hsa ; - } - - public String getStream() - { - return _stream; - } - - public void setStream(String stream) - { - this._stream = stream ; - } - - public double getBankFull() - { - return _bankFull; - } - - public void setBankFull(double bankFull) - { - this._bankFull = bankFull ; - } - - public double getActionStage() - { - return _actionStage; - } - - public void setActionStage(double actionStage) - { - this._actionStage = actionStage ; - } - - public double getFloodStage() - { - return _floodStage; - } - - public void setFloodStage(double floodStage) - { - this._floodStage = floodStage ; - } - - public double getFloodFlow() - { - return _foodFlow; - } - - public void setFloodFlow(double floodFlow) - { - this._foodFlow = floodFlow ; - } - - public double getActionFlow() - { - return _actionFlow; - } - - public void setActionFlow(double actionFlow) - { - this._actionFlow = actionFlow ; - } - - public String getGroupName() - { - return _groupName; - } - - public void setGroupName(String groupName) - { - this._groupName = groupName ; - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - this._groupId = groupId ; - } - - public double getLatestObsValue() - { - return _latestObsValue; - } - - public void setLatestObsValue(double latestObsValue) - { - this._latestObsValue = latestObsValue ; - } - - public long getLatestObsTime() - { - return _latestObsTime; - } - - public void setLatestObsTime(long latestObsTime) - { - this._latestObsTime = latestObsTime ; - } - - public double getLatestStgValue() - { - return _latestStgValue; - } - - public void setLatestStgValue(double latestStgValue) - { - this._latestStgValue = latestStgValue ; - } - - public long getLatestStgTime() - { - return _latestStgTime; - } - - public void setLatestStgTime(long latestStgTime) - { - this._latestStgTime = latestStgTime ; - } - - public double getLatestFlowValue() - { - return _latestFlowValue; - } - - public void setLatestFlowValue(double latestFlowValue) - { - this._latestFlowValue = latestFlowValue ; - } - - public long getLatestFlowTime() - { - return _latestFlowTime; - } - - public void setLatestFlowTime(long latestFlowTime) - { - this._latestFlowTime = latestFlowTime ; - } - - public double getMaxFcstValue() - { - return _maxFcstValue; - } - - public void setMaxFcstValue(double maxFcstValue) - { - this._maxFcstValue = maxFcstValue ; - } - - public long getMaxFcstValidTime() - { - return _maxFcstValidTime; - } - - public void setMaxFcstValidTime(long maxFcstValidTime) - { - this._maxFcstValidTime = maxFcstValidTime; - } - - public long getMaxFcstBasisTime() - { - return _maxFcstBasisTime; - } - - public void setMaxFcstBasisTime(long maxFcstBasisTime) - { - this._maxFcstBasisTime = maxFcstBasisTime; - } - - public long getSshpFcstBasisTime() - { - if(_sshpFcstDetails != null) - _sshpFcstBasisTime = _sshpFcstDetails.getBasisTime(); - else - _sshpFcstBasisTime = DbTable.getNullLong(); - return _sshpFcstBasisTime; - } - - public void setSshpFcstBasisTime(long sshpFcstBasisTime) - { - this._sshpFcstBasisTime = sshpFcstBasisTime; - } - - public long getSshpFcstFloodTime() - { - if(_sshpFcstDetails != null) - _sshpFcstFloodTime = _sshpFcstDetails.getTimeAboveFldStg(); - else - _sshpFcstFloodTime = DbTable.getNullLong(); - return _sshpFcstFloodTime; - } - - public void setSshpFcstFloodTime(long sshpFcstFloodTime) - { - this._sshpFcstFloodTime = sshpFcstFloodTime; - } - - public long getSshpMaxFcstValidTime() - { - if(_sshpFcstDetails != null) - _sshpMaxFcstTime = _sshpFcstDetails.getCrestTime(); - else - _sshpMaxFcstTime = DbTable.getNullLong(); - return _sshpMaxFcstTime; - } - - public void setSshpMaxFcstValidTime(long sshpMaxFcstTime) - { - this._sshpMaxFcstTime = sshpMaxFcstTime; - } - - public double getSshpMaxFcstValue() - { - if(_sshpFcstDetails != null) - _sshpMaxFcstValue = _sshpFcstDetails.getCrestValue(); - else - _sshpMaxFcstValue = DbTable.getNullDouble(); - return _sshpMaxFcstValue; - } - - public void setSshpMaxFcstValue(double sshpMaxFcstValue) - { - this._sshpMaxFcstValue = sshpMaxFcstValue; - } - - public int getGroupOrdinal() - { - return _groupOrdinal; - } - - public void setGroupOrdinal(int groupOrdinal) - { - this._groupOrdinal = groupOrdinal ; - } - - public int getLocationOrdinal() - { - return _locationOrdinal; - } - - public void setLocationOrdinal(int locationOrdinal) - { - this._locationOrdinal = locationOrdinal ; - } - - public void setObsFcstMax(double obsFcstMax) - { - this._obsFcstMax = obsFcstMax; - } - - public double getObsFcstMax() - { - return _obsFcstMax; - } - - public void setFldStgDeparture(double fldStgDeparture) - { - this._fldStgDeparture = fldStgDeparture; - } - - public double getFldStgDeparture() - { - return _fldStgDeparture; - } - - public void setActStgDeparture(double actStgDeparture) - { - this._actStgDeparture = actStgDeparture; - } - - public double getActStgDeparture() - { - return _actStgDeparture; - } - - public void setMinorStage(double minorStage) - { - this._minorStage = minorStage; - } - - public double getMinorStage() - { - return _minorStage; - } - - public void setMajorStage(double majorStage) - { - this._majorStage = majorStage; - } - - public double getMajorStage() - { - return _majorStage; - } - - public void setModerateStage(double moderateStage) - { - this._moderateStage = moderateStage; - } - - public double getModerateStage() - { - return _moderateStage; - } - - public void setDerivedColumnsDetailsList(List list) - { - _derivedColumnsDetailsList = list; - } - - public List getDerivedColumnsDetailsList() - { - return _derivedColumnsDetailsList; - } - - private List getVtecEventList() - { - return _vtecEventList; - } - - public void setVtecEventList(List list) - { - _vtecEventList = list; - _riverMonitorVtecEventDataManager = new RiverMonitorVtecEventDataManager(_vtecEventList); - } - - public RiverMonitorVtecEventDataManager getVtecEventDataManager() - { - return _riverMonitorVtecEventDataManager; - } - - public boolean getAlertUpperLimit() - { - return _alertUpperLimit; - } - - public void setAlertUpperLimit(boolean alertUpperLimit) - { - _alertUpperLimit = alertUpperLimit; - } - - public boolean getAlarmUpperLimit() - { - return _alarmUpperLimit; - } - - public void setAlarmUpperLimit(boolean alarmUpperLimit) - { - _alarmUpperLimit = alarmUpperLimit; - } - - public boolean getAlertLowerLimit() - { - return _alertLowerLimit; - } - - public void setAlertLowerLimit(boolean alertLowerLimit) - { - _alertLowerLimit = alertLowerLimit; - } - - public boolean getAlarmLowerLimit() - { - return _alarmLowerLimit; - } - - public void setAlarmLowerLimit(boolean alarmLowerLimit) - { - _alarmLowerLimit = alarmLowerLimit; - } - - public boolean getAlertRocLimit() - { - return _alertRocLimit; - } - - public void setAlertRocLimit(boolean alertRocLimit) - { - _alertRocLimit = alertRocLimit; - } - - public boolean getAlarmRocLimit() - { - return _alarmRocLimit; - } - - public void setAlarmRocLimit(boolean alarmRocLimit) - { - _alarmRocLimit = alarmRocLimit; - } - - public boolean getAlertDiffLimit() - { - return _alertDiffLimit; - } - - public void setAlertDiffLimit(boolean alertDiffLimit) - { - _alertDiffLimit = alertDiffLimit; - } - - public boolean getAlarmDiffLimit() - { - return _alarmDiffLimit; - } - - public void setAlarmDiffLimit(boolean alarmDiffLimit) - { - _alarmDiffLimit = alarmDiffLimit; - } - - public String getPrimaryRiverPe() - { - return _primaryRiverPe; - } - - public void setPrimaryRiverPe(String pe) - { - _primaryRiverPe = pe; - } - - public PrecipData getPrecipData() - { - return _precipData; - } - - public void setPrecipData(PrecipData precipData) - { - _precipData = precipData; - } - - public String getToolTipTextForAlertAlarmSummary() - { - return _toolTipTextForAlertAlarmSummary; - } - - public void setToolTipTextForAlertAlarmSummary(String toolTipText) - { - _toolTipTextForAlertAlarmSummary = toolTipText; - } - - public String getObsTypeSource() - { - return _obsTypeSource; - } - - public void setObsTypeSource(String obsTypeSource) - { - _obsTypeSource = obsTypeSource; - } - - public String getFcstTypeSource() - { - return _fcstTypeSource; - } - - public void setFcstTypeSource(String fcstTypeSource) - { - _fcstTypeSource = fcstTypeSource; - } - - public VTECeventRecord getVtecEventRecordForEndTime() - { - return _riverMonitorVtecEventDataManager.getVtecEventRecordForEndTime(); - } - - public VTECeventRecord getVtecEventRecordForExpireTime() - { - return _riverMonitorVtecEventDataManager.getVtecEventRecordForExpireTime(); - } - - public SshpFcstDetails getSshpFcstDetails() - { - return _sshpFcstDetails; - } - - public void setSshpFcstDetails(SshpFcstDetails sshpFcstDetails) - { - this._sshpFcstDetails = sshpFcstDetails; - } - - public String getStringValue(long value, long missingValue) - { - String result = super.getStringValue(value, missingValue); - if(result != super.getMissingRepresentation()) - { - String tempStr = result.substring(5, result.length()-3); - tempStr = tempStr.replace('-','/'); - tempStr = tempStr.replace(' ', '-'); - result = tempStr; - } - return result; - } - - // If primary pe is null assume it to be stage. - protected boolean isPrimaryPeStage() - { - boolean result = true; - if(_primaryRiverPe != null) - { - if(_primaryRiverPe.length() != 2) - { - System.out.println("Primarype:["+ _primaryRiverPe+"]"+ "lid:"+getLid()+ "len:"+ _primaryRiverPe.length()); - } - if(_primaryRiverPe.charAt(0) != 'H') - result = false; - } - return result; - } - - public String getVtecSummary() - { - return (_riverMonitorVtecEventDataManager.getVtecSummary()); - } - - public long getEventEndTime() - { - int numOfHrsForVtecEventProductTimeLookBack = _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack(); - long earliestAcceptableTimeForVtecEventProductTimeLookBack = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForVtecEventProductTimeLookBack; - - return (_riverMonitorVtecEventDataManager.getEventEndTime(earliestAcceptableTimeForVtecEventProductTimeLookBack)); - } - - public long getUGCExpireTime() - { - int numOfHrsForVtecEventProductTimeLookBack = _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack(); - long earliestAcceptableTimeForVtecEventProductTimeLookBack = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForVtecEventProductTimeLookBack; - - return (_riverMonitorVtecEventDataManager.getUGCExpireTime(earliestAcceptableTimeForVtecEventProductTimeLookBack)); - } - - public String getAlertAlarmSummary() - { - String summary = ""; - StringBuffer summaryStringBufffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - if(_alertUpperLimit || _alarmUpperLimit || _alertLowerLimit || _alarmLowerLimit|| _alertRocLimit || - _alarmRocLimit || _alertDiffLimit || _alarmDiffLimit) - { - toolTipStringBuffer.append(""); - } - _toolTipTextForAlertAlarmSummary = ""; - if(_alertUpperLimit) - { - summaryStringBufffer = summaryStringBufffer.append("u"); - toolTipStringBuffer.append("u: Value Exceeded Alert Upper Limit\n
    "); - } - else if(_alarmUpperLimit) - { - summaryStringBufffer = summaryStringBufffer.append("U"); - toolTipStringBuffer.append("U: Value Exceeded Alarm Upper Limit\n
    "); - } - if(_alertLowerLimit) - { - summaryStringBufffer = summaryStringBufffer.append("l"); - toolTipStringBuffer.append("l: Value Exceeded Alert Lower Limit\n
    "); - } - else if(_alarmLowerLimit) - { - summaryStringBufffer = summaryStringBufffer.append("L"); - toolTipStringBuffer.append("L: Value Exceeded Alarm Lower Limit\n
    "); - } - if(_alertRocLimit) - { - summaryStringBufffer = summaryStringBufffer.append("c"); - toolTipStringBuffer.append("c: Value Exceeded Alert ROC Limit
    "); - } - else if(_alarmRocLimit) - { - summaryStringBufffer = summaryStringBufffer.append("C"); - toolTipStringBuffer.append("C: Value Exceeded Alarm ROC Limit
    "); - } - if(_alertDiffLimit) - { - summaryStringBufffer = summaryStringBufffer.append("d"); - toolTipStringBuffer.append("d: Value Exceeded Alert Diff Limit\n
    "); - } - else if(_alarmDiffLimit) - { - summaryStringBufffer = summaryStringBufffer.append("D"); - toolTipStringBuffer.append("D: Value Exceeded Alarm Diff Limit\n
    "); - } - - summary = summaryStringBufffer.toString(); - _toolTipTextForAlertAlarmSummary = toolTipStringBuffer.toString(); - return summary; - } - - public String getToolTipTextForThreatSummary() - { - return _toolTipTextForThreatSummary; - } - - public void setToolTipTextForThreatSummary(String toolTipText) - { - _toolTipTextForThreatSummary = toolTipText; - } - - public String getToolTipTextForPrecipThreatSummary() - { - return _toolTipTextForPrecipThreatSummary; - } - - public void setToolTipTextForPrecipThreatSummary(String toolTipText) - { - _toolTipTextForPrecipThreatSummary = toolTipText; - } - - - public void addAllCellsToMap() - { - ThreatLevel defaultThreatLevel = ThreatLevel.NO_THREAT; - MonitorCell cell = null; - String header = "RiverMonitorJTableRowData2.addAllCellsToMap(): "; - - String dateTimeFormatString = "MM/dd - HH:mm"; - - //static data - - addToCellMap(RiverColumns.PRIMARY_RIVER_PE, CellType.STRING, getPrimaryRiverPe() ); - - addToCellMap(RiverColumns.GROUP_NAME, CellType.STRING, getGroupName() ); - addToCellMap(RiverColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(RiverColumns.GROUP_ORDINAL, CellType.INTEGER, getGroupOrdinal()); - - addToCellMap(RiverColumns.LOCATION_ID, CellType.STRING, getLid() ); - addToCellMap(RiverColumns.LOCATION_NAME, CellType.STRING, getName() ); - addToCellMap(RiverColumns.LOCATION_ORDINAL, CellType.INTEGER, getLocationOrdinal()); - - addToCellMap(RiverColumns.COUNTY, CellType.STRING, getCounty() ); - - addToCellMap(RiverColumns.STATE, CellType.STRING, getState() ); - addToCellMap(RiverColumns.STREAM, CellType.STRING, getStream() ); - addToCellMap(RiverColumns.RIVER_BASIN, CellType.STRING, getRiverBasin() ); - addToCellMap(RiverColumns.HSA, CellType.STRING, getHsa() ); - addToCellMap(RiverColumns.BANK_FULL, CellType.DOUBLE, getBankFull() ); - addToCellMap(RiverColumns.FLD_STG, CellType.DOUBLE, getFloodStage() ); - addToCellMap(RiverColumns.ACT_STG, CellType.DOUBLE, getActionStage() ); - - addToCellMap(RiverColumns.FLD_FLOW, CellType.DOUBLE, getFloodFlow(), defaultThreatLevel, getMissingRepresentation(), 0); - addToCellMap(RiverColumns.ACT_FLOW, CellType.DOUBLE, getActionFlow(), defaultThreatLevel, getMissingRepresentation(), 0); - - addToCellMap(RiverColumns.MIN_STG, CellType.DOUBLE, getMinorStage()); - addToCellMap(RiverColumns.MAJ_STG, CellType.DOUBLE, getMajorStage()); - addToCellMap(RiverColumns.MOD_STG, CellType.DOUBLE, getModerateStage()); - - //dynamic data - int numOfHrsForObsLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - long earliestAcceptableTimeForObs = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForObsLookBack; - - // latest obs value and time - ThreatLevel latestObsValueThreatLevel = getThreatLevelForLatestObsValue(earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_OBS_VALUE, CellType.DOUBLE, - getLatestObsValue(), latestObsValueThreatLevel, - getMissingRepresentation()); - - ThreatLevel latestObsTimeThreatLevel = getThreatLevelForThisTime(getLatestObsTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_OBS_TIME, CellType.DATE_TIME, - getLatestObsTime(), latestObsTimeThreatLevel, - getMissingRepresentation(), dateTimeFormatString ); - - - // latest stage value and time - ThreatLevel latestStageValueThreatLevel = getThreatLevelForStage(getLatestStgValue(),getLatestStgTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_STG_VALUE, CellType.DOUBLE, getLatestStgValue(), latestStageValueThreatLevel, getMissingRepresentation(), 2); - - ThreatLevel latestStageTimeThreatLevel = getThreatLevelForThisTime(getLatestStgTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_STG_TIME, CellType.DATE_TIME, getLatestStgTime(), latestStageTimeThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - - // latest flow value and time - ThreatLevel latestFlowValueThreatLevel = getThreatLevelForFlow(getLatestFlowValue(), getLatestFlowTime(), earliestAcceptableTimeForObs ); - addToCellMap(RiverColumns.LAT_FLOW_VALUE, CellType.DOUBLE, getLatestFlowValue(), latestFlowValueThreatLevel); - - ThreatLevel latestFlowTimeThreatLevel = getThreatLevelForThisTime(getLatestFlowTime(), earliestAcceptableTimeForObs); - addToCellMap(RiverColumns.LAT_FLOW_TIME, CellType.DATE_TIME, getLatestFlowTime(), latestFlowTimeThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - - int numOfHrsForFcstLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - long earliestAcceptableTimeForFcst = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsForFcstLookBack; - - //max forecast - ThreatLevel maxForecastThreatLevel = getThreatLevelForMaxFcstValue(earliestAcceptableTimeForFcst); - addToCellMap(RiverColumns.MAX_FCST_VALUE, CellType.DOUBLE, getMaxFcstValue(), maxForecastThreatLevel); - - addToCellMap(RiverColumns.MAX_FCST_VALID_TIME, CellType.DATE_TIME, getMaxFcstValidTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - addToCellMap(RiverColumns.MAX_FCST_BASIS_TIME, CellType.DATE_TIME, getMaxFcstBasisTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - //sshp forecast - addToCellMap(RiverColumns.SSHP_MAX_FCST_VALID_TIME, CellType.DATE_TIME, getSshpMaxFcstValidTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - addToCellMap(RiverColumns.SSHP_FCST_BASIS_TIME, CellType.DATE_TIME, getSshpFcstBasisTime(), defaultThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - ThreatLevel maxSshpForecastThreatLevel = getThreatLevelForSshpFcstValue(earliestAcceptableTimeForFcst); - addToCellMap(RiverColumns.SSHP_MAX_FCST_VALUE, CellType.DOUBLE, getSshpMaxFcstValue(), maxSshpForecastThreatLevel); - - ThreatLevel maxSshpFcstFloodTimeThreatLevel = getThreatLevelForSshpTimeAboveFloodLevel(earliestAcceptableTimeForFcst); - addToCellMap(RiverColumns.SSHP_FCST_FLD_TIME, CellType.DATE_TIME, getSshpFcstFloodTime(), maxSshpFcstFloodTimeThreatLevel, getMissingRepresentation(), dateTimeFormatString); - - ThreatLevel obsFcstMaxThreatLevel = getThreatLevelForObsFcstMax(); - addToCellMap(RiverColumns.OBSFCST_MAX, CellType.DOUBLE, getObsFcstMax(), obsFcstMaxThreatLevel, getMissingRepresentation(), 2); - - //stg departures - addToCellMap(RiverColumns.FLD_STG_DEP, CellType.DOUBLE, getFldStgDeparture()); - addToCellMap(RiverColumns.ACT_STG_DEP, CellType.DOUBLE, getActStgDeparture()); - - addToCellMap(PrecipColumns.LATEST_PRECIP_PARAM_CODE, CellType.STRING, getPrecipData().getLatestPrecipParamCodeString() ); - - addToCellMap(PrecipColumns.LATEST_30MIN, CellType.DOUBLE, getPrecipData().getLatestPrecip30Min()); - addToCellMap(PrecipColumns.LATEST_1HR, CellType.DOUBLE, getPrecipData().getLatestPrecip1Hr(), getThreatLevelForPrecipColumn("INSTANT", 1)); - addToCellMap(PrecipColumns.LATEST_3HR, CellType.DOUBLE, getPrecipData().getLatestPrecip3Hr(), getThreatLevelForPrecipColumn("INSTANT", 3)); - addToCellMap(PrecipColumns.LATEST_6HR, CellType.DOUBLE, getPrecipData().getLatestPrecip6Hr(), getThreatLevelForPrecipColumn("INSTANT", 6)); - - addToCellMap(PrecipColumns.LATEST_12HR, CellType.DOUBLE, getPrecipData().getLatestPrecip12Hr()); - addToCellMap(PrecipColumns.LATEST_18HR, CellType.DOUBLE, getPrecipData().getLatestPrecip18Hr()); - addToCellMap(PrecipColumns.LATEST_24HR, CellType.DOUBLE, getPrecipData().getLatestPrecip24Hr()); - - addToCellMap(PrecipColumns.TOH_PRECIP_1HR_PARAM_CODE, CellType.STRING, getPrecipData().getTohPrecip1HrParamCodeString() ); - - addToCellMap(PrecipColumns.TOH_PRECIP_1HR, CellType.DOUBLE, getPrecipData().getTohPrecip1Hr(), getThreatLevelForPrecipColumn("PRECIP", 1)); - - addToCellMap(PrecipColumns.FFG_1HR, CellType.DOUBLE, getPrecipData().getFFG1Hr()); - addToCellMap(PrecipColumns.FFG_3HR, CellType.DOUBLE, getPrecipData().getFFG3Hr()); - addToCellMap(PrecipColumns.FFG_6HR, CellType.DOUBLE, getPrecipData().getFFG6Hr()); - - addToCellMap(PrecipColumns.DIFF_1HR, CellType.DOUBLE, getPrecipData().getDiff1Hr(), getThreatLevelForPrecipColumn("DIFF", 1)); - addToCellMap(PrecipColumns.DIFF_3HR, CellType.DOUBLE, getPrecipData().getDiff3Hr(), getThreatLevelForPrecipColumn("DIFF", 3)); - addToCellMap(PrecipColumns.DIFF_6HR, CellType.DOUBLE, getPrecipData().getDiff6Hr(), getThreatLevelForPrecipColumn("DIFF", 6)); - - addToCellMap(PrecipColumns.RATIO_1HR, CellType.INTEGER, getPrecipData().getRatio1Hr(), getThreatLevelForPrecipColumn("RATIO", 1)); - addToCellMap(PrecipColumns.RATIO_3HR, CellType.INTEGER, getPrecipData().getRatio3Hr(), getThreatLevelForPrecipColumn("RATIO", 3)); - addToCellMap(PrecipColumns.RATIO_6HR, CellType.INTEGER, getPrecipData().getRatio6Hr(), getThreatLevelForPrecipColumn("RATIO", 6)); - - addToCellMap(RiverColumns.ALERT_ALARM, CellType.STRING, getAlertAlarmSummary(), getThreatLevelForAlertAlarmSummary()); - - int numOfHrsForVtecEventEndTimeLookAhead = 1; - numOfHrsForVtecEventEndTimeLookAhead = _menuSettings.getRiverSettings().getVtecEventEndTimeApproach(); - ThreatLevel vtecEventTimeThreatLevel = getThreatLevelForVtecTimeCell(getEventEndTime(), numOfHrsForVtecEventEndTimeLookAhead); - - addToCellMap(RiverColumns.VTEC_SUMMARY, CellType.STRING, getVtecSummary(),vtecEventTimeThreatLevel) ; - - // use a different missing representation - String vtecTimeMissingRepresentation = getEventEndTimeOrUgcExpireTimeMissingRepresentation(getMissingRepresentation()); - addToCellMap(RiverColumns.EVENT_END_TIME, CellType.DATE_TIME, getEventEndTime(), vtecEventTimeThreatLevel, vtecTimeMissingRepresentation, dateTimeFormatString ); - - int numOfHrsForExpireTimeLookAhead = 1; - numOfHrsForExpireTimeLookAhead = _menuSettings.getRiverSettings().getUgcExpireTimeApproach(); - ThreatLevel vtecUgcExpireTimeThreatLevel = getThreatLevelForVtecTimeCell(getUGCExpireTime(), numOfHrsForExpireTimeLookAhead); - - addToCellMap(RiverColumns.UGC_EXPIRE_TIME, CellType.DATE_TIME, getUGCExpireTime(), vtecUgcExpireTimeThreatLevel, vtecTimeMissingRepresentation, dateTimeFormatString); - - ThreatLevel threatLevel = getThreatLevelForPrecipThreatSummary(); - cell = addToCellMap(PrecipColumns.PRECIP_THREAT, CellType.EXTENSION, - getPrecipThreatSummary(), threatLevel, - getMissingRepresentation()); - - threatLevel = getThreatLevelForThreatSummary(); - cell = addToCellMap(RiverColumns.THREAT, CellType.EXTENSION, - getThreatSummary(), threatLevel, - getMissingRepresentation()); - - - // addCell(cell); - - } //end addAllCellsToMap - - // ----------------------------------------------------------------------------------- - public double round(double value, int decimalPlacesToMaintain) - { - return MathHelper.roundToNDecimalPlaces(value, decimalPlacesToMaintain); - } - - // ----------------------------------------------------------------------------------- - - public String getEventEndTimeOrUgcExpireTimeMissingRepresentation(String standardMissingRepresentation) - { - String missingRepresentationString = standardMissingRepresentation; - - if(_riverMonitorVtecEventDataManager.thereAreAnyActiveEventsForThisLocation()) - { - missingRepresentationString = "TBD"; - } - - return missingRepresentationString; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel,Color cellBackgroundColor, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, cellBackgroundColor, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, Color cellBackgroundColor) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, cellBackgroundColor, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - protected void addDerivedDataToCellMap() - { - // add all derived columns as well - List derivedColumnsDetailsList = this.getDerivedColumnsDetailsList(); - for(int i=0 ; i < derivedColumnsDetailsList.size(); i++) - { - DerivedColumn desc1 = (DerivedColumn) derivedColumnsDetailsList.get(i); - - CellType cellType = getCellTypeFromReturnType(desc1.getReturnType()); - - addToCellMap(desc1.getColumnName(), cellType, desc1.getValue(), desc1.getCellBackgroundColor()); - } - } - // ----------------------------------------------------------------------------------- - - public Color getCellBackgroundColorForThreatSummary() - { - return getCellBackgroundColor("Threat"); - } - - private CellType getCellTypeFromReturnType(String derivedColumnReturnType) - { - CellType cellType = null; - - cellType = (CellType) _derivedReturnTypeToCellTypeMap.get(derivedColumnReturnType.toLowerCase()); - - return cellType; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value) - { - MonitorCell cell = addToCellMap(columnName, cellType, - value, ThreatLevel.NO_THREAT, getMissingRepresentation()); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, getMissingRepresentation(), _defaultDecimalPoints); - - return cell; - } -// ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation) - { - - MonitorCell cell = addToCellMap(columnName, cellType, - value, threatLevel, missingRepresentation, _defaultDecimalPoints); - - return cell; - } - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - int decimalPointsForDisplay) - { - MonitorCell cell = new MonitorCell (columnName, cellType, - value, threatLevel, - missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - return cell; - } - - // ----------------------------------------------------------------------------------- - - private MonitorCell addToCellMap(String columnName, CellType cellType, - Object value, ThreatLevel threatLevel, - String missingRepresentation, - String dateFormatString) - { - - MonitorCell cell = new MonitorCell (columnName, cellType, value, threatLevel, - missingRepresentation, dateFormatString); - - - // addToCellMap(cell); - addCell(cell); - - - return cell; - } - - - // ----------------------------------------------------------------------------------- - - public Color getCellBackgroundColor(String columnName) - { - Color color = Color.white; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellBackgroundColor(); - } - - return color; - } - - // ----------------------------------------------------------------------------------- - - public Color getCellForegroundColor(String columnName) - { - Color color = Color.black; - - MonitorCell cell = (MonitorCell) getCell(columnName); - - if (cell != null) - { - color = cell.getCellForegroundColor(); - } - return color; - } - - - // helper methods - - // ----------------------------------------------------------------------------------- - public Color getCriticalColorForThisRow() - { - Color color = Color.WHITE; - ThreatLevel level = getRiverMonitorThreatLevel(); - if(level == ThreatLevel.ALERT) - { - color = Color.RED; - } - else if(level == ThreatLevel.CAUTION) - { - color = Color.YELLOW; - } - else if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - color = Color.GRAY; - } - else - { - boolean flowLevelIsPresent = false; - boolean stageLevelIsPresent = false; - - if( ! DbTable.isNull(getFloodFlow()) && ! DbTable.isNull(getActionFlow()) ) - { - flowLevelIsPresent = true; - } - if( ! DbTable.isNull(getFloodStage()) && ! DbTable.isNull(getActionStage()) ) - { - stageLevelIsPresent = true; - } - if(flowLevelIsPresent || stageLevelIsPresent) - { - color = new Color(0, 153, 0); // Dark green - } - } - - return color; - } - - // ----------------------------------------------------------------------------------- - public ThreatLevel getThreatLevelForThreatSummary() - { - ThreatLevel level = getRiverMonitorThreatLevel(); - - //Threat cell should be color red/yellow/white. So skip threat aged / missing threat level - if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - - return level; - } - - // ----------------------------------------------------------------------------------- - public ThreatLevel getThreatLevelForPrecipThreatSummary() - { - ThreatLevel level = getPrecipThreatLevelForPrecipThreatSummary(); - - //Threat cell should be color red/yellow/white. So skip threat aged / missing threat level - if(level == ThreatLevel.AGED_DATA || - level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - - return level; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getRiverMonitorThreatLevel() - { - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = new ArrayList( getCellMap().values()); - cellThreatLevel = getMaxRowThreatLevel(cellList); - - return cellThreatLevel; - } -// ----------------------------------------------------------------------------------- - public ThreatLevel getMaxRowThreatLevel(List cellList) - { - String header = "RiverMonitorJTableRowData.getMaxRowThreatLevel(): "; - //this method assumes that the threat column has not yet been added to the cell map, when this - // method is invoked - ThreatLevel level = ThreatLevel.NO_THREAT; - ThreatLevel maxLevel = ThreatLevel.ALERT; - - //make sure the threat cell's threat level does not get used to calculate row's threat level, so clear it to zero - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - //iterate through each cell, and set the level to the max threat level found - for (int i = 0; i < cellList.size(); i++) - { - - MonitorCell cell = (MonitorCell) cellList.get(i); - - if (cell == null) - { - continue; - } - else - { - cellThreatLevel = cell.getThreatLevel(); - - - if ( _ignoreColumnNameForThreatSet.contains(cell.getColumnName()) ) - { - //ignore this column - } - - else if (cellThreatLevel.isGreater(level)) - { - //System.out.println(header + "Cell " + cell.getColumnName() + " cellThreatLevel = " + cellThreatLevel); - level = cellThreatLevel; - if (level == maxLevel) - { - break; //quit looking, because we have determined it is maxed out - } - } - } - } - return level; - } - - // ----------------------------------------------------------------------------------- - - public List getPrecipCells() - { - List cellList = new ArrayList(); - - addCell(cellList, PrecipColumns.LATEST_30MIN); - addCell(cellList, PrecipColumns.LATEST_1HR); - addCell(cellList, PrecipColumns.LATEST_3HR ); - addCell(cellList, PrecipColumns.LATEST_6HR ); - - addCell(cellList, PrecipColumns.TOH_PRECIP_1HR ); - - addCell(cellList, PrecipColumns.DIFF_1HR ); - addCell(cellList, PrecipColumns.DIFF_3HR ); - addCell(cellList, PrecipColumns.DIFF_6HR ); - - addCell(cellList, PrecipColumns.RATIO_1HR ); - addCell(cellList, PrecipColumns.RATIO_3HR ); - addCell(cellList, PrecipColumns.RATIO_6HR ); - - return cellList; - } - - // ----------------------------------------------------------------------------------- - - private void addCell(List cellList, String columnName ) - { - MonitorCell cell = null; - - cell = (MonitorCell) getCellMap().get(columnName); - if(cell != null) - { - cellList.add(cell); - } - - return; - } - - // ----------------------------------------------------------------------------------- - - public ThreatLevel getPrecipThreatLevelForPrecipThreatSummary() - { - ThreatLevel cellThreatLevel = ThreatLevel.NO_THREAT; - - List cellList = getPrecipCells(); - cellThreatLevel = getMaxRowThreatLevel(cellList); - - return cellThreatLevel; - } - - //---------------------------------------------------------------------------------- - - public ThreatLevel getThreatLevelForValueAtThisTime(double value, long time, long earliestAcceptableTime, - double actionValue, double floodValue) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if (DbTable.isNull(value)) - { - level = ThreatLevel.MISSING_DATA; - //level = ThreatLevel.NO_THREAT; - } - else if(isDataAged(time, earliestAcceptableTime)) - { - level = ThreatLevel.AGED_DATA; - //level = ThreatLevel.NO_THREAT; - } - else if( ( ! DbTable.isNull(floodValue)) && value >= floodValue) - { - level = ThreatLevel.ALERT; - } - else if(( ! DbTable.isNull(actionValue)) && value >= actionValue) - { - level = ThreatLevel.CAUTION; - } - - return level; - } - // ------------------------------------------------------------------------------------- - - public ThreatLevel getThreatLevelForThisTime(long time, long earliestAcceptableTime) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - if (DbTable.isNull(time)) - { - level = ThreatLevel.MISSING_DATA; - } - else if(isDataAged(time, earliestAcceptableTime)) - { - level = ThreatLevel.AGED_DATA; - } - return level; - } - // ------------------------------------------------------------------------------------- - /* - * The sshp time above flood level cell is colored red if there is any value in it, - * or it is colored white if it is blank or if the basis time is outside the window - */ - public ThreatLevel getThreatLevelForSshpTimeAboveFloodLevel(long earliestAcceptableTime) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - if(isDataAged(getSshpFcstBasisTime(), earliestAcceptableTime)) - { - level = ThreatLevel.NO_THREAT; - } - else if (! DbTable.isNull(getSshpFcstFloodTime())) - { - level = ThreatLevel.ALERT; - } - return level; - } - - //-------------------------------------------------------------------------------------- - /* - * Returns true if the data is aged, by checking the time with earliestAcceptableTime - */ - protected boolean isDataAged(long time, long earliestAcceptableTime) - { - boolean result = false; - - if (time < earliestAcceptableTime) - { - result = true; - } - - return result; - } - - // ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelBasedOnPrimaryPe(double value, long time, long earliestAcceptableTime) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - if(isPrimaryPeStage()) - { - level = getThreatLevelForStage( value, time, earliestAcceptableTime); - } - else // 'Q'-- flow - { - level = getThreatLevelForFlow( value, time, earliestAcceptableTime); - - } - return level; - } - // ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForLatestObsValue(long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelBasedOnPrimaryPe(getLatestObsValue(), getLatestObsTime(), earliestAcceptableTime); - return level; - } - - // ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForStage(double value, long time, long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelForValueAtThisTime(value, time, earliestAcceptableTime, - getActionStage(), getFloodStage()); - - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForFlow(double value, long time, long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelForValueAtThisTime(value, time, earliestAcceptableTime, - getActionFlow(), getFloodFlow()); - return level; - } - // ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForMaxFcstValue(long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelBasedOnPrimaryPe(getMaxFcstValue(), getMaxFcstBasisTime(), earliestAcceptableTime); - if(level == ThreatLevel.MISSING_DATA) - { - level = ThreatLevel.NO_THREAT; - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForSshpFcstValue(long earliestAcceptableTime) - { - ThreatLevel level = getThreatLevelForStage(getSshpMaxFcstValue(), getSshpFcstBasisTime(), earliestAcceptableTime); - if(level == ThreatLevel.MISSING_DATA || level == ThreatLevel.AGED_DATA) - { - level = ThreatLevel.NO_THREAT; - } - return level; - } -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelBasedOnValue(double value, double floodLevel, double actionLevel) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(DbTable.isNull(value)) - { - level = ThreatLevel.MISSING_DATA; - } - else if(floodLevel != DbTable.getNullDouble() && value > floodLevel) - { - level = ThreatLevel.ALERT; - } - else if( actionLevel != DbTable.getNullDouble() && value > actionLevel) - { - level = ThreatLevel.CAUTION; - } - return level; - } - - -// ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForObsFcstMax() - { - ThreatLevel level = ThreatLevel.NO_THREAT; - int numOfHrsToLookBack ; - long earliestAcceptableTime ; - - if(getMaxFcstValue() == getLatestObsValue()) - { - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - ThreatLevel obslevel = getThreatLevelForLatestObsValue(earliestAcceptableTime); - - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - ThreatLevel fcstlevel = getThreatLevelForMaxFcstValue(earliestAcceptableTime); - - if(obslevel == fcstlevel && obslevel == ThreatLevel.AGED_DATA) - { - level = obslevel; - } - else if(obslevel.isGreater(fcstlevel)) - { - if(obslevel != ThreatLevel.AGED_DATA) - level = obslevel; - } - else - { - if(fcstlevel != ThreatLevel.AGED_DATA) - level = fcstlevel; - } - } - else if(getObsFcstMax() == getMaxFcstValue()) // Fcst data - { - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - level = getThreatLevelForMaxFcstValue(earliestAcceptableTime); - } - else // obs data - { - numOfHrsToLookBack = _menuSettings.getRiverSettings().getLatestObsLookBack(); - earliestAcceptableTime = System.currentTimeMillis() - TimeHelper.MILLIS_PER_HOUR * numOfHrsToLookBack; - level = getThreatLevelForLatestObsValue(earliestAcceptableTime); - } - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getThreatLevelForAlertAlarmSummary() - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - String summary = getAlertAlarmSummary(); - - int indexOfL, indexOfU, indexOfC, indexOfR, indexOfD; - indexOfL = -1; indexOfU = -1; indexOfC = -1; indexOfD = -1; indexOfR = -1; - - if(summary.length() > 0) - { - indexOfL = summary.indexOf('L'); - indexOfU = summary.indexOf('U'); - indexOfC = summary.indexOf('C'); - indexOfD = summary.indexOf('D'); - indexOfR = summary.indexOf('R'); - if(indexOfL != -1 || indexOfU != -1 || indexOfC != -1 || indexOfD != -1 || indexOfR != -1 ) - { - level = ThreatLevel.ALERT; - } - else - { - level = ThreatLevel.CAUTION; - } - } - - return level; - } -// ------------------------------------------------------------------------------------- - private ThreatLevel getPrecipThreatLevel(double value, double alert, double caution) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(! DbTable.isNull(value)) - { - if(value >= alert) - level = ThreatLevel.ALERT; - else if(value >= caution) - level = ThreatLevel.CAUTION; - } - - return level; - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipValueThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings, String type) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double missing = DbTable.getNullDouble(); - double value; - switch(hour) - { - - case 1: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip1Hr(); - else - value = _precipData.getTohPrecip1Hr(); - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert1Hr(), precipSettings.getPrecipCaution1Hr()); - break; - - case 3: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip3Hr(); - else - // value = _precipData.getTohPrecip3Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert3Hr(), precipSettings.getPrecipCaution3Hr()); - break; - case 6: - if(type.compareTo("LATEST") == 0) - value = _precipData.getLatestPrecip6Hr(); - else - //value = _precipData.getTohPrecip6Hr(); - value = missing; - - level = getPrecipThreatLevel( value, precipSettings.getPrecipAlert6Hr(), precipSettings.getPrecipCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipRatioThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - int value; - switch(hour) - { - - case 1: - value = _precipData.getRatio1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert1Hr(), precipSettings.getRatioCaution1Hr()); - break; - case 3: - value = _precipData.getRatio3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert3Hr(), precipSettings.getRatioCaution6Hr()); - break; - case 6: - value = _precipData.getRatio6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getRatioAlert6Hr(), precipSettings.getRatioCaution6Hr()); - break; - - } - return level; - - } -// ------------------------------------------------------------------------------------- - protected ThreatLevel getPrecipDiffThreatLevelForHrMentioned(int hour, PrecipColumnDataSettings precipSettings) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - double value; - - switch(hour) - { - case 1: - value = _precipData.getDiff1Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert1Hr(), precipSettings.getDiffCaution1Hr()); - break; - case 3: - value = _precipData.getDiff3Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert3Hr(), precipSettings.getDiffCaution3Hr()); - break; - case 6: - value = _precipData.getDiff6Hr(); - level = getPrecipThreatLevel( value, precipSettings.getDiffAlert6Hr(), precipSettings.getDiffCaution6Hr()); - break; - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForPrecipColumn(String type, int hour) - { - - ThreatLevel level = ThreatLevel.NO_THREAT; - - if(type.compareTo("INSTANT") == 0) // instant precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings(), "INSTANT"); - } - else if(type.compareTo("TOH") == 0) // toh precip - { - level = getPrecipValueThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings(), "TOH"); - } - else if(type.compareTo("RATIO") == 0) - { - level = getPrecipRatioThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings()); - } - else //type is DIFF - { - level = getPrecipDiffThreatLevelForHrMentioned(hour, _menuSettings.getPrecipSettings()); - } - return level; - } - -// ------------------------------------------------------------------------------------- - - protected ThreatLevel getThreatLevelForVtecTimeCell(long time, long lookAheadHrs) - { - ThreatLevel level = ThreatLevel.NO_THREAT; - - long curTime = System.currentTimeMillis(); - String summary = getVtecSummary(); - - if(summary.length() > 0) - { - if(time != DbTable.getNullLong()) - { - if((curTime + (TimeHelper.MILLIS_PER_HOUR*lookAheadHrs)) >= time) - { - level = ThreatLevel.ALERT; - } - else - { - level = ThreatLevel.CAUTION; - } - } - else - { - level = ThreatLevel.CAUTION; - } - } - return level; - } - -// ------------------------------------------------------------------------------------- - - public ThreatLevel getCellThreatLevelForColumn(String columnName) - { - ThreatLevel level; - - MonitorCell cell = (MonitorCell) getCellMap().get(columnName); - - level = cell.getThreatLevel(); - - return level; - } - -// ------------------------------------------------------------------------------------- - - - public String getThreatSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - - ThreatLevel level; - level = getCellThreatLevelForColumn(RiverColumns.ALERT_ALARM); - if(level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("A"); - toolTipStringBuffer.append(_toolTipTextForAlertAlarmSummary); - } - - level = getThreatLevelForPrecipThreatSummary(); - if(level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("P"); - String precipThreatSummary = getPrecipThreatSummary(); - if(precipThreatSummary.contains("L")) - { - toolTipStringBuffer.append("P: Latest Precip has exceeded threat level
    "); - } - if(precipThreatSummary.contains("T")) - { - toolTipStringBuffer.append("P: Top of the Hour Precip has exceeded threat level
    "); - } - if(precipThreatSummary.contains("D")) - { - toolTipStringBuffer.append("P: TOH Precip - FFG diff has exceeded threat level
    "); - } - if(precipThreatSummary.contains("R")) - { - toolTipStringBuffer.append("P: TOH Precip / FFG ratio has exceeded threat level
    "); - } - } - - level = getCellThreatLevelForColumn(RiverColumns.VTEC_SUMMARY); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("V"); - int lookBackHours = _menuSettings.getRiverSettings().getVtecEventEndTimeApproach(); - String tempStr; - String eventEndTimeString = getDataValue(RiverColumns.EVENT_END_TIME); - if(level == ThreatLevel.ALERT) - { - tempStr = "V: VTEC EndTime["+ eventEndTimeString +"] is within " + lookBackHours+ "hrs
    "; - } - else - { - tempStr = "V: VTEC EndTime["+ eventEndTimeString +"] is not within " + lookBackHours+ "hrs
    "; - } - toolTipStringBuffer.append(tempStr); - } - - level = getCellThreatLevelForColumn(RiverColumns.UGC_EXPIRE_TIME); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION ) - { - summaryStringBuffer = summaryStringBuffer.append("X"); - int lookBackHours = _menuSettings.getRiverSettings().getUgcExpireTimeApproach(); - String tempStr ; - String ugcExpireTimeString = getDataValue(RiverColumns.UGC_EXPIRE_TIME); - if(level == ThreatLevel.ALERT) - { - tempStr = "X: UGC ExpireTime["+ ugcExpireTimeString +"] is within " + lookBackHours + "hrs or in the past
    "; - } - else - { - tempStr = "X: UGC ExpireTime["+ ugcExpireTimeString +"] is not within " + lookBackHours+ "hrs
    "; - } - toolTipStringBuffer.append(tempStr); - } - - - level = getCellThreatLevelForColumn(RiverColumns.MAX_FCST_VALUE); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("F"); - if(level == ThreatLevel.ALERT) - { - toolTipStringBuffer.append("F: FcstValue exceeded the flood level
    "); - } - else - { - toolTipStringBuffer.append("F: FcstValue exceeded the action level
    "); - } - - } - - level = getCellThreatLevelForColumn(RiverColumns.SSHP_MAX_FCST_VALUE); - if( level == ThreatLevel.ALERT || level == ThreatLevel.CAUTION) - { - summaryStringBuffer = summaryStringBuffer.append("S"); - if(level == ThreatLevel.ALERT) - { - toolTipStringBuffer.append("S: Sshp FcstValue exceeded the flood level
    "); - } - else - { - toolTipStringBuffer.append("S: Sshp FcstValue exceeded the action level
    "); - } - - } - - level = ThreatLevel.NO_THREAT; // reset the threat level - - //check if any of the obs column are in alert threat - if((getCellThreatLevelForColumn(RiverColumns.LAT_OBS_VALUE) == ThreatLevel.ALERT) - || (getCellThreatLevelForColumn(RiverColumns.LAT_STG_VALUE) == ThreatLevel.ALERT) - || (getCellThreatLevelForColumn(RiverColumns.LAT_FLOW_VALUE) == ThreatLevel.ALERT)) - { - summaryStringBuffer = summaryStringBuffer.append("O"); - level = ThreatLevel.ALERT; - } - //check if any of the obs column are in caution threat - else if((getCellThreatLevelForColumn(RiverColumns.LAT_OBS_VALUE) == ThreatLevel.CAUTION) - || (getCellThreatLevelForColumn(RiverColumns.LAT_STG_VALUE) == ThreatLevel.CAUTION) - || (getCellThreatLevelForColumn(RiverColumns.LAT_FLOW_VALUE) == ThreatLevel.CAUTION)) - { - summaryStringBuffer = summaryStringBuffer.append("O"); - level = ThreatLevel.CAUTION; - } - - if(level == ThreatLevel.ALERT ) - { - toolTipStringBuffer.append("O: ObsValue exceeded the flood level
    "); - } - else if(level == ThreatLevel.CAUTION) - { - toolTipStringBuffer.append("O: ObsValue exceeded the action level
    "); - } - - summary = summaryStringBuffer.toString(); - _toolTipTextForThreatSummary = toolTipStringBuffer.toString(); - return summary; - } - - -// ------------------------------------------------------------------------------------- - - - public String getPrecipThreatSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - StringBuffer toolTipStringBuffer = new StringBuffer(""); - - ThreatLevel level; - ThreatLevel level1Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_1HR); - ThreatLevel level3Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_3HR); - ThreatLevel level6Hr = getCellThreatLevelForColumn(PrecipColumns.LATEST_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("L"); - toolTipStringBuffer.append("L: Latest Precip Exceeded the threshold
    "); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_1HR); - // level3Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_3HR); - // level6Hr = getCellThreatLevelForColumn(PrecipColumns.TOH_PRECIP_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) - /* - || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) - */ - ) - { - summaryStringBuffer = summaryStringBuffer.append("T"); - toolTipStringBuffer.append("T: Top Of The Hour Precip Exceeded the threshold
    "); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.DIFF_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("D"); - toolTipStringBuffer.append("D: TOH Precip - FFG Difference Exceeded the threshold
    "); - } - - level1Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_1HR); - level3Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_3HR); - level6Hr = getCellThreatLevelForColumn(PrecipColumns.RATIO_6HR); - if( ((level1Hr == ThreatLevel.ALERT || level1Hr == ThreatLevel.CAUTION)) || - ((level3Hr == ThreatLevel.ALERT || level3Hr == ThreatLevel.CAUTION)) || - ((level6Hr == ThreatLevel.ALERT || level6Hr == ThreatLevel.CAUTION)) ) - { - summaryStringBuffer = summaryStringBuffer.append("R"); - toolTipStringBuffer.append("R: TOH Precip / FFG Ratio Exceeded the threshold
    "); - } - - summary = summaryStringBuffer.toString(); - _toolTipTextForPrecipThreatSummary = toolTipStringBuffer.toString(); - return summary; - } -// ------------------------------------------------------------------------------------- - - public void setRiverBasin(String riverBasin) - { - _riverBasin = riverBasin; - } - - public String getRiverBasin() - { - return _riverBasin; - } - - -} //end class diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorVtecEventDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorVtecEventDataManager.java deleted file mode 100644 index 906c34e25d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/RiverMonitorVtecEventDataManager.java +++ /dev/null @@ -1,323 +0,0 @@ -package ohd.hseb.monitor.river; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; - -public class RiverMonitorVtecEventDataManager -{ - - private List _vtecAllEventList = null; - private List _mostRecentEventList = null; - private List _mostRecentActiveEventList = null; - private VTECeventRecord _vtecEventRecordForEndTime = null; - private VTECeventRecord _vtecEventRecordForExpireTime = null; - - public RiverMonitorVtecEventDataManager(List vtecAllEventList) - { - _vtecAllEventList = vtecAllEventList; - } - - public List getMostRecentEventList() - { - if(_mostRecentEventList == null) - _mostRecentEventList = calculateMostRecentEventList(); - return _mostRecentEventList; - } - - public List getMostRecentActiveEventList() - { - if(_mostRecentActiveEventList == null) - _mostRecentActiveEventList = calculateMostRecentActiveEventList(); - return _mostRecentActiveEventList; - } - - public VTECeventRecord getVtecEventRecordForEndTime() - { - return _vtecEventRecordForEndTime; - } - - public VTECeventRecord getVtecEventRecordForExpireTime() - { - return _vtecEventRecordForExpireTime; - } - - //Creates the list that contains the recent event info for each signif - public List calculateMostRecentEventList() - { - Map mostRecentEventMap = new HashMap(); - VTECeventRecord mostRecentEventRecord = null; - - if(_vtecAllEventList != null) - { - for(int i=0; i < _vtecAllEventList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) _vtecAllEventList.get(i); - String key = record.getSignif(); - - mostRecentEventRecord = (VTECeventRecord) mostRecentEventMap.get(key); - - //the first time, add the current record - if (mostRecentEventRecord == null) - { - mostRecentEventMap.put(key, record); - mostRecentEventRecord = record; - } - - else // this is not the first active record for this geoId|signif - { - //this one is more recent, so replace the old record. - if (record.getProducttime() > mostRecentEventRecord.getProducttime()) - { - mostRecentEventMap.put(key, record); - } - } - } - } - List mostRecentEventList = new ArrayList (mostRecentEventMap.values()); - - return mostRecentEventList; - } - - public List calculateMostRecentActiveEventList() - { - List mostRecentActiveEventList = null; - - getMostRecentEventList(); - - if(_mostRecentEventList != null) - { - for(int i=0;i < _mostRecentEventList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) _mostRecentEventList.get(i); - if(RiverMonitorVtecEventDataManager.checkIfEventActive(record)) - { - if(mostRecentActiveEventList == null) - { - mostRecentActiveEventList = new ArrayList(); - } - - mostRecentActiveEventList.add(record); - } - } - } - return mostRecentActiveEventList; - } - - public static boolean checkIfEventActive(VTECeventRecord record) - { - boolean active = false; - String action = record.getAction(); - long endTime = record.getEndtime(); - long curTime = System.currentTimeMillis(); - /* if the event is explicity expired or cancelled, - then the event tracking is not active. - also, all ROU events are considered inactive. - otherwise, see if the event end time has not passed yet */ - - if (action.equals("CAN") || action.equals("EXP") || - action.equals("ROU") || action.length() == 0) - { - active = false; - } - else - { - /* if the endtime is not specified, assume the event is still active. - unspecified can occur if the endtime has a missing value indicator - or is set to 0. A 0 value can occur because the time may be NULL in - the database, which is converted to a 0 value by the time conversion - functions. */ - - if (endTime == (long) DbTable.getNullLong()) - active = true; - else //end time is past the current time, so the event is still active. - { - if (endTime > curTime) - active = true; - else - active = false; - } - } - return(active); - } - - - public boolean thereAreAnyActiveEventsForThisLocation() - { - boolean result = false; - - getMostRecentActiveEventList(); - - if(_mostRecentActiveEventList != null)//there are active events - { - result = true; - } - return result; - } - - public String getVtecSummary() - { - String summary = ""; - StringBuffer summaryStringBuffer = new StringBuffer(""); - - getMostRecentActiveEventList(); - - if(thereAreAnyActiveEventsForThisLocation()) - { - for(int i=0;i < _mostRecentActiveEventList.size(); i++) - { - VTECeventRecord record = (VTECeventRecord) _mostRecentActiveEventList.get(i); - summaryStringBuffer = summaryStringBuffer.append(record.getSignif()); - } - } - summary = summaryStringBuffer.toString(); - return summary; - } - - public long getEventEndTime(long earliestAcceptableTimeForVtecEventProductTimeLookBack) - { - VTECeventRecord record = null; - long endTime = DbTable.getNullLong(); - - getMostRecentActiveEventList(); - - //if there are any active events among the recent event for various signif - //use the one that has the endtime close to current time (which is the earliest endtime in the most recent event list) - if(thereAreAnyActiveEventsForThisLocation()) - { - // loop thru the mostRecentActiveEventsList - // This list will have size 0 (min) size 3 (max- accouting for W A Y) - // Find the earliest endtime - // Ignore the record with missing endtime - - long tempEndTime = Long.MAX_VALUE; - for (int i = 0; i < _mostRecentActiveEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentActiveEventList.get(i); - - if(record.getEndtime() != DbTable.getNullLong()) - { - if(record.getEndtime() < tempEndTime) - { - tempEndTime = record.getEndtime(); - endTime = tempEndTime; - _vtecEventRecordForEndTime = record; - } - } - } - - if(endTime == DbTable.getNullLong()) //ie., The recent active list has 1 or more events and all of their endtime is null - { - _vtecEventRecordForEndTime = (VTECeventRecord)_mostRecentActiveEventList.get(0); - } - } - else if(_mostRecentEventList != null)//No active events going on, so consider the latest/most recent endtime(max of all endtime) - { - for (int i = 0; i < _mostRecentEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentEventList.get(i); - - if(i==0) - { - endTime = record.getEndtime(); - _vtecEventRecordForEndTime = record; - } - else - { - if(record.getEndtime() > endTime) - { - endTime = record.getEndtime(); - _vtecEventRecordForEndTime = record; - } - } - } - - //check if the record's product time is within the window - if( _vtecEventRecordForEndTime != null && - (_vtecEventRecordForEndTime.getProducttime() < earliestAcceptableTimeForVtecEventProductTimeLookBack)) - { - _vtecEventRecordForEndTime = null; - endTime = DbTable.getNullLong(); - } - } - - return endTime; - } - - public long getUGCExpireTime(long earliestAcceptableTimeForVtecEventProductTimeLookBack) - { - VTECeventRecord record = null; - long expireTime = DbTable.getNullLong(); - - getMostRecentActiveEventList(); - - //if there are any active events among the recent event for various signif - //use the one that has the expiretime close to current time (which is the earliest endtime in the most recent event list) - if(thereAreAnyActiveEventsForThisLocation()) - { - // loop thru the mostRecentActiveEventsList - // This list will have size 0 (min) size 3 (max- accouting for W A Y) - // Find the earliest expiretime - // Ignore the record with missing expiretime - - long tempExpireTime = Long.MAX_VALUE; - for (int i = 0; i < _mostRecentActiveEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentActiveEventList.get(i); - - if(record.getExpiretime() != DbTable.getNullLong()) - { - if(record.getExpiretime() < tempExpireTime) - { - tempExpireTime = record.getExpiretime(); - _vtecEventRecordForExpireTime = record; - expireTime = tempExpireTime; - } - } - } - - if(expireTime == DbTable.getNullLong()) //ie., The recent active list has 1 or more events and all of their expiretime is null - _vtecEventRecordForExpireTime = (VTECeventRecord) _mostRecentActiveEventList.get(0);// expiretime will be TBD - - } - else if(_mostRecentEventList != null)//No active events going on, so consider the latest/most recent expiretime(max of all expiretime) - { - for (int i = 0; i < _mostRecentEventList.size(); i++) - { - record = (VTECeventRecord) _mostRecentEventList.get(i); - - if(i==0) - { - expireTime = record.getExpiretime(); - _vtecEventRecordForExpireTime = record; - } - else - { - if(record.getExpiretime() > expireTime) - { - expireTime = record.getExpiretime(); - _vtecEventRecordForExpireTime = record; - } - } - } - - //check if the record's product time is within the window - if(_vtecEventRecordForExpireTime != null && - (_vtecEventRecordForExpireTime.getProducttime() < earliestAcceptableTimeForVtecEventProductTimeLookBack)) - { - _vtecEventRecordForExpireTime = null; - expireTime = DbTable.getNullLong(); - } - } - - return expireTime; - } - - -// ------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorAppManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorAppManager.java deleted file mode 100644 index 45077071bd..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorAppManager.java +++ /dev/null @@ -1,137 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.Container; -import java.awt.GridBagLayout; - -import javax.swing.JPanel; -import javax.swing.JSplitPane; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.db.Database; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorSplitPane; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.MemoryLogger; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.vtecevent.VtecEventDataManager; - -public class RiverMonitorAppManager -{ - private MessageSystemManager _msgSystemManager; - - private RiverMonitorDataManager _riverMonitorDataManager; - - private AppsDefaults _appsDefaults; - - public static final String DEFAULT_RIVER_SETTINGS_FILE = "DefaultRiverMonitorSettings.txt"; - public static final String SITE_RIVER_SETTINGS_FILE = "RiverMonitorSettings.txt"; - public static final String PE_CONFIG_FILE = "RiverMonitorPEConfig.txt"; - - private SessionLogger _logger; - private MonitorFrame _mainFrame; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private String _appName = "RiverMonitor"; - - public static String DERIVED_COLUMNS_FILE = "DerivedColumns.txt"; - - public RiverMonitorAppManager(Database db, String missingRepresentation, String version, - String versionDate, MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) - { - _appsDefaults = new AppsDefaults(); - - createLogger(); - - ViewSettings viewSettings = new ViewSettings(); - FilterSettings filterSettings = new FilterSettings(); - RiverMonitorMenuSettings menuSettings = new RiverMonitorMenuSettings(); - - createFrame(db, version); - - JSplitPane splitPane = new MonitorSplitPane(JSplitPane.HORIZONTAL_SPLIT, true); - - JPanel timeDisplayPanel = new JPanel(); - JToolBar toolBar = new JToolBar(); - - OfficeNotesDataManager officeNotesDataMgr = new OfficeNotesDataManager(db,_logger, missingRepresentation); - AlertAlarmDataManager alertAlarmDataMgr = new AlertAlarmDataManager(db, _logger, missingRepresentation); - VtecEventDataManager vtecEventDataMgr = new VtecEventDataManager(db, _logger, missingRepresentation); - - String settingsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - _derivedColumnsFileManager = new DerivedColumnsFileManager(settingsDir + "/" + DERIVED_COLUMNS_FILE, _logger); - - _riverMonitorDataManager = new RiverMonitorDataManager(db, _appsDefaults, missingRepresentation, - _logger, menuSettings, _derivedColumnsFileManager); - - _msgSystemManager = new MessageSystemManager(); - - MemoryLogger.setLogger(_logger); - - new RiverMonitorRefreshManager(_msgSystemManager, _logger, _riverMonitorDataManager, splitPane); - - new RiverMonitorFilterManager(_msgSystemManager, _logger, _mainFrame, _riverMonitorDataManager, splitPane, _appsDefaults, filterSettings); - - new RiverMonitorMenuManager(_msgSystemManager, _logger, _mainFrame, version, versionDate, _appsDefaults, - toolBar, _riverMonitorDataManager, officeNotesDataMgr, alertAlarmDataMgr, vtecEventDataMgr, - menuSettings, timeDisplayPanel, _appName, monitorTimeSeriesLiteManager); - - new RiverMonitorViewManager(_mainFrame, _msgSystemManager, _logger, _riverMonitorDataManager, splitPane, - viewSettings, _derivedColumnsFileManager, monitorTimeSeriesLiteManager, _appsDefaults); - - RiverMonitorSettingsManager settingsManager = new RiverMonitorSettingsManager(_msgSystemManager, _appsDefaults, _logger, _mainFrame, viewSettings, - filterSettings, menuSettings); - - settingsManager.startRiverMonitor(); - - Container frameContentPane = _mainFrame.getContentPane(); - _mainFrame.setLayout(new GridBagLayout()); - - - //col, row, width, height, weightx, weighty, fill - ComponentHelper.addFrameComponent(frameContentPane, - toolBar, 0, 0, 1, 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, - timeDisplayPanel, 1, 0, 1, 1, 1, 0, 1); - ComponentHelper.addFrameComponent(frameContentPane, - splitPane, 0, 1, 2, 1, 1, 1, 1); - - - _mainFrame.pack(); - _mainFrame.setVisible(true); - } - - private void createLogger() - { - String logDir = _appsDefaults.getToken("rivermon_log_dir", - HydroappsDefaultDirs.RIVERMON_LOG_DIR); - String logFile = logDir + "/" + _appName; - - _logger = new SessionLogger(_appName, logFile, true, true, null); - _logger.log(null); - _logger.log(_appName + " Started"); - - } - - private void createFrame(Database db, String version) - { - _mainFrame = new MonitorFrame(); - String title = _appName + " DbName : " + db.getDatabaseName() + - " Session : "+ _logger.getSessionId(); - _mainFrame.setTitle(title); - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorFilterManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorFilterManager.java deleted file mode 100644 index 4fa7038b2c..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorFilterManager.java +++ /dev/null @@ -1,278 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; -import java.util.Map; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.TreeDataManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeManager; -import ohd.hseb.monitor.treefilter.MonitorCheckTreeSelectionModel; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; - -public class RiverMonitorFilterManager extends BaseManager -{ - private SessionLogger _logger; - - private RiverMonitorDataManager _riverMonitorDataManager; - private FilterSettings _filterSettings; - - private JSplitPane _splitPane; - - private AppsDefaults _appsDefaults; - - private MonitorCheckTreeManager _checkTreeManager; - - private JScrollPane _treeScrollPane; - - private JPopupMenu _popupMenuForTree; - private JMenuItem _expandTreeMenuItem; - private JMenuItem _collapseTreeMenuItem; - - private MonitorFrame _mainFrame; - private String _iconsDir; - - - public RiverMonitorFilterManager(MessageSystemManager msgSystemManager,SessionLogger logger, - MonitorFrame mainFrame, RiverMonitorDataManager riverMonitorDataManager, JSplitPane splitPane, - AppsDefaults appsDefaults, FilterSettings filterSettings) - { - _riverMonitorDataManager = riverMonitorDataManager; - _splitPane = splitPane; - _appsDefaults = appsDefaults; - _mainFrame = mainFrame; - _filterSettings = filterSettings; - _iconsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - createPopupMenuForTree(); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), MessageType.REFRESH_DISPLAY); - } - - private void createTreeAndApplySettings(MonitorMessage message) - { - final String header = "RiverMonitorFilterManager.createTreeAndApplySettings(): "; - System.out.println(header + " thread = " + Thread.currentThread().getId()); - - _mainFrame.setWaitCursor(); - if(message.getMessageSource() != this) - { - System.out.println(header +" Invoked" + "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - List stringArrayListOfFilterItems = _riverMonitorDataManager.createStringArrayListOfFilterItems(); - - TreeDataManager treeDataManager = new TreeDataManager(); - - DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("HSA"); - - JTree tree = treeDataManager.createFilterTreeFromList(rootNode, stringArrayListOfFilterItems); - - tree.setBackground(Color.BLACK); - - TreePath[] preSelectedPaths = _filterSettings.getSelectedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preSelectedPaths :"); - - TreePath[] preExpandedPaths = _filterSettings.getExpandedPaths(); - - // printTreePathArray(preSelectedPaths, "CreateTree--- preExpandedPaths :"); - - Map lidToCriticalColorMap = _riverMonitorDataManager.getLidToCriticalColorMap(); - - _checkTreeManager = new MonitorCheckTreeManager(tree, preSelectedPaths, preExpandedPaths, lidToCriticalColorMap, _iconsDir); - CheckTreeSelectionListener treeListener = new CheckTreeSelectionListener(); - tree.addMouseListener(treeListener); - - _treeScrollPane = new JScrollPane(tree); - _treeScrollPane.setPreferredSize(new Dimension(300,645)); - - _splitPane.setLeftComponent(_treeScrollPane); - - // printTreePathArray(_checkTreeManager.getSelectionModel().getSelectionPaths(), "Create Tree: "); - - _riverMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(_checkTreeManager.getValidTreePaths(preSelectedPaths)); - - } - _mainFrame.setDefaultCursor(); - } - - private void highlightThisRow() - { - String header = "RiverMonitorFilterManager.highlightThisRow(): "; - - System.out.print(header ); - send(this, MessageType.FILTER_SELECT_ITEM); - } - - private void sendRefreshDisplayMessage() - { - String header = "RiverMonitorFilterManager.sendRefreshDisplayMessage(): "; - - System.out.print(header); - send(this, MessageType.REFRESH_DISPLAY); - } - - private void setFilterSettings() - { - String header = "RiverMonitorFilterManager.setFilterSettings(): "; - System.out.println(header); - - TreePath[] paths = _checkTreeManager.getSelectionModel().getSelectionPaths(); - _filterSettings.setSelectedPaths(paths); - - // printTreePathArray(paths, header + " selected path in "); - - TreePath[] expandedPaths = _checkTreeManager.getAllExpandedPaths(); - _filterSettings.setExpandedPaths(expandedPaths); - - } - - private void createPopupMenuForTree() - { - _popupMenuForTree = new JPopupMenu(); - _expandTreeMenuItem = new JMenuItem("Expand Entire Tree"); - _expandTreeMenuItem.setMnemonic('E'); - _collapseTreeMenuItem = new JMenuItem("Collapse Entire Tree"); - _collapseTreeMenuItem.setMnemonic('C'); - _popupMenuForTree.add(_expandTreeMenuItem); - _popupMenuForTree.add(_collapseTreeMenuItem); - - TreePopupMenuListener treePopupMenuListener = new TreePopupMenuListener(); - _expandTreeMenuItem.addActionListener(treePopupMenuListener); - _collapseTreeMenuItem.addActionListener(treePopupMenuListener); - } - - private void printTreePathArray(TreePath[] treePathArray, String message) - { - if (message != null) - { - System.out.println(message); - } - - if (treePathArray != null) - { - for (TreePath treePath : treePathArray) - { - System.out.println(treePath); - } - } - - return; - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTreeAndApplySettings(message); - } - } - - private class TreePopupMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - - TreePath[] allAvailablePaths = _checkTreeManager.getAllAvailablePaths(); - if(e.getSource().toString().contains("Expand Entire Tree")) - { - _checkTreeManager.expandThesePaths(allAvailablePaths); - } - else //collapse tree - { - _checkTreeManager.collapseEntireTree(); - } - - setFilterSettings(); - } - } - - class CheckTreeSelectionListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - - MonitorCheckTreeSelectionModel selectionModel = (MonitorCheckTreeSelectionModel) (_checkTreeManager.getSelectionModel()); - - selectionModel.printInstanceId(); - - TreePath paths[] = selectionModel.getSelectionPaths(); - - // printTreePathArray(paths, "CheckTreeSelectionListener.mouseClicked(): "); - - setFilterSettings(); - - _riverMonitorDataManager.getTreeFilterManager().traversePathsToDisplayLocationSelected(paths); - sendRefreshDisplayMessage(); - - if(SwingUtilities.isLeftMouseButton(e)) - { - JTree tree = (JTree) e.getSource(); - int row = tree.getRowForLocation(e.getX(), e.getY()); - TreePath path = tree.getPathForRow(row); - String itemClickedOnJtree = null; - if(path != null) - { - if(path.getPathCount() == 4) - { - itemClickedOnJtree = path.getLastPathComponent().toString(); - System.out.println("Item of interest:"+ itemClickedOnJtree); - _riverMonitorDataManager.setLidOfCurrentInterest(itemClickedOnJtree); - highlightThisRow(); - } - } - } - } - public void mousePressed(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - - public void mouseReleased(MouseEvent e) - { - if(e.isPopupTrigger()) - { - _popupMenuForTree.show(_treeScrollPane, e.getX(), e.getY()); - } - } - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorMenuManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorMenuManager.java deleted file mode 100644 index ed4725a73a..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorMenuManager.java +++ /dev/null @@ -1,1174 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.swing.ButtonGroup; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButtonMenuItem; -import javax.swing.JSeparator; -import javax.swing.JToolBar; - -import ohd.hseb.alertalarm.AlertAlarmDataManager; -import ohd.hseb.alertalarm.AlertAlarmDialog; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.MonitorToolBarManager; -import ohd.hseb.monitor.manager.MonitorMenuManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.officenotes.OfficeNotesDataManager; -import ohd.hseb.officenotes.OfficeNotesDialog; -import ohd.hseb.monitor.river.LookBackTimeDialog; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.river.settings.RiverColumnDataSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.rivermonlocgroup.RiverMonGroupDialog; -import ohd.hseb.rivermonlocgroup.RiverMonLocationDialog; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.vtecevent.VtecEventDataManager; -import ohd.hseb.vtecevent.VtecEventDialog; - -public class RiverMonitorMenuManager extends MonitorMenuManager -{ - private JMenuBar _menuBar; - private JMenu _fileMenu, _displayMenu, _sortMenu, _configMenu, _detailsMenu, _helpMenu; - private JMenu _fcstTsMenu; - private JRadioButtonMenuItem _fcstTsFZMenuItem; - private JRadioButtonMenuItem _fcstTsFFMenuItem; - private JRadioButtonMenuItem _fcstTsIngestFilterMenuItem; - private ButtonGroup _fcstTsGroup; - private JMenuItem _selectColumnsMenuItem; - private JCheckBoxMenuItem _showMissingRiverMenuItem; - private JMenuItem _saveColumnSettingsMenuItem; - private JMenuItem _loadSettingsMenuItem; - private JMenuItem _loadOfficeSettingsMenuItem; - private JMenuItem _saveOfficeSettingsMenuItem; - private JMenuItem _refreshColumnMenuItem; - private JMenuItem _exportTableToTextMenuItem; - private JMenuItem _precipMonitorMenuItem; - private JMenuItem _exitApplicationMenuItem; - private JMenuItem _officeNotesMenuItem; - private JMenuItem _alertAlarmMenuItem; - private JMenuItem _vtecEventMenuItem; - private JMenuItem _siteSpecificMenuItem; - private JMenuItem _timeSeriesLiteMenuItem; - private JMenuItem _riverMonitorPEConfigMenuItem; - private JMenuItem _riverMonGroupMenuItem; - private JMenuItem _riverMonLocationMenuItem; - private JMenuItem _derivedColumnsMenuItem; - private JMenuItem _hsagrplocSortMenuItem; - private JMenuItem _riverThreatSortMenuItem; - private JMenuItem _precipThreatSortMenuItem; - private JMenuItem _clearSortMenuItem; - - private JMenuItem _validTimeLookUpForAlertAlarmMenuItem; - private JMenuItem _endTimeLookUpForVTECEventMenuItem; - private JMenuItem _ugcExpireTimeLookUpMenuItem; - private JMenuItem _vtecEventProductTimeLookUpMenuItem; - private JMenuItem _obsTimeLookUpForLatestObsValueMenuItem; - private JMenuItem _fcstBasisTimeLookUpForMaxFcstValueMenuItem; - private JMenuItem _precipThresholdForThreatColorMenuItem; - - private JMenuItem _aboutMenuItem; - - private RiverMonGroupDialog _riverMonGroupDialog = null; - private RiverMonLocationDialog _riverMonLocationDialog; - - private RiverMonitorDataManager _rivermonitorDataManager; - private RiverMonitorMenuSettings _menuSettings; - - private OfficeNotesDialog _officeNotesDialog; - private OfficeNotesDataManager _officeNotesDataMgr; - private AlertAlarmDialog _alertAlarmDialog; - private AlertAlarmDataManager _alertAlarmDataMgr; - private VtecEventDataManager _vtecEventDataMgr; - private VtecEventDialog _vtecEventDialog; - - private String _settingsDir; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - private RiverMonitorJTableRowData _selectedRowData; - - private MonitorToolBarManager _toolBarManager; - - public RiverMonitorMenuManager(MessageSystemManager msgSystemManager, - SessionLogger logger, MonitorFrame mainFrame, String version, - String versionDate, AppsDefaults appsDefaults, JToolBar toolBar, - RiverMonitorDataManager riverMonitorDataManager, OfficeNotesDataManager officeNotesDataMgr, - AlertAlarmDataManager alertAlarmDataMgr, VtecEventDataManager vtecEventDataMgr, - RiverMonitorMenuSettings menuSettings, JPanel timeDisplayPanel, String appName, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager) - { - super(msgSystemManager, appsDefaults, logger); - _appsDefaults = appsDefaults; - _rivermonitorDataManager = riverMonitorDataManager; - - _menuSettings = menuSettings; - - _officeNotesDataMgr = officeNotesDataMgr; - _alertAlarmDataMgr = alertAlarmDataMgr; - _vtecEventDataMgr = vtecEventDataMgr; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - int defaultRefreshInterval = 15; - createRefreshComponents(defaultRefreshInterval, timeDisplayPanel); - - _toolBarManager = new MonitorToolBarManager(toolBar, _appsDefaults, _officeNotesDataMgr); - _toolBarManager.getOfficeNotesButton().addActionListener(new OfficeNotesDialogListener()); - - setAboutInfo(version, versionDate, appName); - _mainFrame = mainFrame; - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new UpdateDisplayWithSettingsReceiver(), MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new ViewSelectItemReceiver(), MessageType.VIEW_SELECT_ITEM); - - _msgSystemManager.registerReceiver(new UpdateDisplayReceiver(), MessageType.REFRESH_DISPLAY); - - - createMenus(); - setFrameListener(); - } - - protected long getDataUpdateTime() - { - return _rivermonitorDataManager.getPdcUpdateTime(); - } - - protected long getDisplayedRecordCount() - { - return _rivermonitorDataManager.getDisplayedRecordCount(); - } - - public void setMenuSettingsRefreshInterval(int value) - { - _menuSettings.setRefreshInterval(value); - } - - public void setRefreshTimeSpinnerValue() - { - _refreshTimeSpinner.setValue(_menuSettings.getRefreshInterval()); - } - - private void createMenus() - { - _menuBar = new JMenuBar(); - _mainFrame.setJMenuBar(_menuBar); - - _toolBarManager.getOfficeNotesButton().addActionListener(new OfficeNotesDialogListener()); - - _fileMenu = new JMenu("File"); - _configMenu = new JMenu("Config"); - _displayMenu = new JMenu("Display"); - _sortMenu = new JMenu("Sort"); - _detailsMenu = new JMenu("Details"); - _helpMenu = new JMenu("Help"); - - _fileMenu.setMnemonic('F'); - _configMenu.setMnemonic('C'); - _displayMenu.setMnemonic('D'); - _sortMenu.setMnemonic('S'); - _detailsMenu.setMnemonic('E'); - _helpMenu.setMnemonic('H'); - - - //File Menu - - _refreshColumnMenuItem = new JMenuItem("Refresh"); - _refreshColumnMenuItem.setMnemonic('R'); - _fileMenu.add(_refreshColumnMenuItem); - - _fileMenu.add(new JSeparator()); - - _saveColumnSettingsMenuItem = new JMenuItem("Save Custom Settings ..."); - _saveColumnSettingsMenuItem.setMnemonic('S'); - _fileMenu.add(_saveColumnSettingsMenuItem); - - _saveOfficeSettingsMenuItem = new JMenuItem("Save Office Settings"); - _saveOfficeSettingsMenuItem.setMnemonic('F'); - _saveOfficeSettingsMenuItem.setToolTipText("Save office settings to PrecipMonitorSettings.txt"); - _fileMenu.add(_saveOfficeSettingsMenuItem); - - _loadSettingsMenuItem = new JMenuItem("Load Custom Settings ..."); - _loadSettingsMenuItem.setMnemonic('L'); - _fileMenu.add(_loadSettingsMenuItem); - - _loadOfficeSettingsMenuItem = new JMenuItem("Load Office Settings"); - _loadOfficeSettingsMenuItem.setMnemonic('O'); - _loadOfficeSettingsMenuItem.setToolTipText("Load office settings from PrecipMonitorSettings.txt"); - _fileMenu.add(_loadOfficeSettingsMenuItem); - - _fileMenu.add(new JSeparator()); - - _exportTableToTextMenuItem = new JMenuItem("Export Data To Text File ..."); - _exportTableToTextMenuItem.setMnemonic('x'); - _fileMenu.add(_exportTableToTextMenuItem); - - _fileMenu.add(new JSeparator()); - - _precipMonitorMenuItem = new JMenuItem("PrecipMonitor ..."); - _precipMonitorMenuItem.setMnemonic('P'); - _fileMenu.add(_precipMonitorMenuItem); - - _fileMenu.add(new JSeparator()); - - - _exitApplicationMenuItem = new JMenuItem("Exit"); - _exitApplicationMenuItem.setMnemonic('E'); - _fileMenu.add(_exitApplicationMenuItem); - - //Display Menu - - - _selectColumnsMenuItem = new JMenuItem("Select Columns ..."); - _selectColumnsMenuItem.setMnemonic('S'); - _displayMenu.add(_selectColumnsMenuItem); - - _displayMenu.add(new JSeparator()); - - _fcstTsMenu = new JMenu("Forecast Source"); - _fcstTsMenu.setMnemonic('F'); - _displayMenu.add(_fcstTsMenu); - - _validTimeLookUpForAlertAlarmMenuItem = new JMenuItem("Alert Alarm ValidTime ..."); - _validTimeLookUpForAlertAlarmMenuItem.setMnemonic('A'); - _displayMenu.add(_validTimeLookUpForAlertAlarmMenuItem); - - _endTimeLookUpForVTECEventMenuItem = new JMenuItem("VTEC Event EndTime ..."); - _endTimeLookUpForVTECEventMenuItem.setMnemonic('V'); - _displayMenu.add(_endTimeLookUpForVTECEventMenuItem); - - _ugcExpireTimeLookUpMenuItem = new JMenuItem("UGCExpire Time ..."); - _ugcExpireTimeLookUpMenuItem.setMnemonic('U'); - _displayMenu.add(_ugcExpireTimeLookUpMenuItem); - - _vtecEventProductTimeLookUpMenuItem = new JMenuItem("VTEC Event Product Time ..."); - _vtecEventProductTimeLookUpMenuItem.setMnemonic('P'); - _displayMenu.add(_vtecEventProductTimeLookUpMenuItem); - - _obsTimeLookUpForLatestObsValueMenuItem = new JMenuItem("Latest ObsTime ..."); - _obsTimeLookUpForLatestObsValueMenuItem.setMnemonic('O'); - _displayMenu.add(_obsTimeLookUpForLatestObsValueMenuItem); - - _fcstBasisTimeLookUpForMaxFcstValueMenuItem = new JMenuItem("Latest Fcst Basis Time ..."); - _fcstBasisTimeLookUpForMaxFcstValueMenuItem.setMnemonic('B'); - _displayMenu.add(_fcstBasisTimeLookUpForMaxFcstValueMenuItem); - - _precipThresholdForThreatColorMenuItem = new JMenuItem("Precip Threshold ..."); - _precipThresholdForThreatColorMenuItem.setMnemonic('P'); - _displayMenu.add(_precipThresholdForThreatColorMenuItem); - - - _displayMenu.add(new JSeparator()); - - _showMissingRiverMenuItem = new JCheckBoxMenuItem("Show Locations with Missing Obs/Fcst Data"); - _showMissingRiverMenuItem.setMnemonic('M'); - _displayMenu.add(_showMissingRiverMenuItem); - - //Config Menu - - - _riverMonGroupMenuItem = new JMenuItem("Group Definitions ..."); - _riverMonGroupMenuItem.setMnemonic('G'); - _configMenu.add(_riverMonGroupMenuItem); - - _riverMonLocationMenuItem = new JMenuItem("Location Grouping/Ordering ..."); - _riverMonLocationMenuItem.setMnemonic('L'); - _configMenu.add(_riverMonLocationMenuItem); - - _configMenu.add(new JSeparator()); - - - _riverMonitorPEConfigMenuItem = new JMenuItem("River Data Type Override ..."); - _riverMonitorPEConfigMenuItem.setMnemonic('P'); - _configMenu.add(_riverMonitorPEConfigMenuItem); - - _configMenu.add(new JSeparator()); - - _derivedColumnsMenuItem = new JMenuItem("Derived Columns ..."); - _derivedColumnsMenuItem.setMnemonic('D'); - _configMenu.add(_derivedColumnsMenuItem); - - - - - //Sort Menu - - _clearSortMenuItem = new JMenuItem("Clear Sort"); - _clearSortMenuItem.setMnemonic('C'); - _clearSortMenuItem.setToolTipText("Clear All Sorts"); - _sortMenu.add(_clearSortMenuItem); - - _sortMenu.add(new JSeparator()); - - _hsagrplocSortMenuItem = new JMenuItem("Sort by HSA | Group | Location Columns"); - _hsagrplocSortMenuItem.setMnemonic('O'); - _hsagrplocSortMenuItem.setToolTipText("Sort by HSA, group id, location id"); - _sortMenu.add(_hsagrplocSortMenuItem); - - _riverThreatSortMenuItem = new JMenuItem("River Threat Sort"); - _riverThreatSortMenuItem.setMnemonic('R'); - _riverThreatSortMenuItem.setToolTipText("Sort by Threat Column"); - _sortMenu.add(_riverThreatSortMenuItem); - - _precipThreatSortMenuItem = new JMenuItem("Precip Threat Sort"); - _precipThreatSortMenuItem.setMnemonic('P'); - _precipThreatSortMenuItem.setToolTipText("Sort by Precip Threat Column"); - _sortMenu.add(_precipThreatSortMenuItem); - - - - - //Details Menu - - _officeNotesMenuItem = new JMenuItem("Office Notes ..."); - _officeNotesMenuItem.setMnemonic('O'); - _detailsMenu.add(_officeNotesMenuItem); - - _alertAlarmMenuItem = new JMenuItem("Alert Alarm ..."); - _alertAlarmMenuItem.setMnemonic('A'); - _detailsMenu.add(_alertAlarmMenuItem); - - _vtecEventMenuItem = new JMenuItem("VTEC Events ..."); - _vtecEventMenuItem.setMnemonic('V'); - _detailsMenu.add(_vtecEventMenuItem); - - _detailsMenu.add(new JSeparator()); - - _siteSpecificMenuItem = new JMenuItem("SiteSpecific App..."); - _siteSpecificMenuItem.setMnemonic('S'); - _detailsMenu.add(_siteSpecificMenuItem); - - _timeSeriesLiteMenuItem = new JMenuItem("Time Series Lite..."); - _timeSeriesLiteMenuItem.setMnemonic('T'); - _detailsMenu.add(_timeSeriesLiteMenuItem); - - // Help Menu - - _aboutMenuItem = new JMenuItem("About ..."); - _aboutMenuItem.setMnemonic('A'); - _helpMenu.add(_aboutMenuItem); - - - - //sub menus - _fcstTsGroup = new ButtonGroup(); - _fcstTsIngestFilterMenuItem = new JRadioButtonMenuItem("IngestFilter"); - _fcstTsIngestFilterMenuItem.setSelected(true); - FcstTsMenuItemListener fcstTsListener = new FcstTsMenuItemListener(); - _fcstTsIngestFilterMenuItem.addActionListener(fcstTsListener); - _fcstTsGroup.add(_fcstTsIngestFilterMenuItem); - _fcstTsMenu.add(_fcstTsIngestFilterMenuItem); - _fcstTsFFMenuItem = new JRadioButtonMenuItem("FF"); - _fcstTsFFMenuItem.addActionListener(fcstTsListener); - _fcstTsGroup.add(_fcstTsFFMenuItem); - _fcstTsMenu.add(_fcstTsFFMenuItem); - _fcstTsFZMenuItem = new JRadioButtonMenuItem("FZ"); - _fcstTsFZMenuItem.addActionListener(fcstTsListener); - _fcstTsGroup.add(_fcstTsFZMenuItem); - _fcstTsMenu.add(_fcstTsFZMenuItem); - - - - setMenuListeners(); - - _menuBar.add(_fileMenu); - _menuBar.add(_displayMenu); - _menuBar.add(_configMenu); - _menuBar.add(_sortMenu); - _menuBar.add(_detailsMenu); - _menuBar.add(_helpMenu); - } - - private void setMenuListeners() - { - ChangeColumnsDisplayedMenuListener changeMenuListener = new - ChangeColumnsDisplayedMenuListener(); - _selectColumnsMenuItem.addActionListener(changeMenuListener); - - ShowMissingRiverMenuListener showMissingPrecipMenuListener = new - ShowMissingRiverMenuListener(); - _showMissingRiverMenuItem.addItemListener(showMissingPrecipMenuListener); - - SaveSettingsListener saveMenuListener = new - SaveSettingsListener(); - _saveColumnSettingsMenuItem.addActionListener(saveMenuListener); - - LoadSettingsListener loadMenuListener = new LoadSettingsListener(); - _loadSettingsMenuItem.addActionListener(loadMenuListener); - - LoadOfficeSettingsListener loadOfficeSettingsListener = new LoadOfficeSettingsListener(); - _loadOfficeSettingsMenuItem.addActionListener(loadOfficeSettingsListener); - - SaveOfficeSettingsListener saveOfficeSettingsListener = new SaveOfficeSettingsListener(); - _saveOfficeSettingsMenuItem.addActionListener(saveOfficeSettingsListener); - - ExitApplicationListener exitApplicationListener = new ExitApplicationListener(); - _exitApplicationMenuItem.addActionListener(exitApplicationListener); - - RefreshMenuListener RefreshMenuListener = new - RefreshMenuListener(); - _refreshColumnMenuItem.addActionListener(RefreshMenuListener); - - SaveTableListener saveTableListener = new SaveTableListener(); - _exportTableToTextMenuItem.addActionListener(saveTableListener); - - PrecipMonitorListener precipMonitorListener = new PrecipMonitorListener(); - _precipMonitorMenuItem.addActionListener(precipMonitorListener); - - AppSortListener appSortListener = new AppSortListener(); - _hsagrplocSortMenuItem.addActionListener(appSortListener); - - PrecipThreatSortListener precipThreatSortListener = new PrecipThreatSortListener(); - _precipThreatSortMenuItem.addActionListener(precipThreatSortListener); - - RiverThreatSortListener riverThreatSortListener = new RiverThreatSortListener(); - _riverThreatSortMenuItem.addActionListener(riverThreatSortListener); - - ClearSortListener clearSortListener = new ClearSortListener(); - _clearSortMenuItem.addActionListener(clearSortListener); - - AlertAlarmDialogListener alertAlarmDialogListener = new AlertAlarmDialogListener(); - _alertAlarmMenuItem.addActionListener(alertAlarmDialogListener); - - VtecEventDialogListener vtecEventDialogListener = new VtecEventDialogListener(); - _vtecEventMenuItem.addActionListener(vtecEventDialogListener); - - SiteSpecificListener siteSpecificListener = new SiteSpecificListener(); - _siteSpecificMenuItem.addActionListener(siteSpecificListener); - - OfficeNotesDialogListener officeNotesDialogListener = new OfficeNotesDialogListener(); - _officeNotesMenuItem.addActionListener(officeNotesDialogListener); - - TimeSeriesLiteMenuItemListener timeSeriesLiteMenuItemListener = new TimeSeriesLiteMenuItemListener(); - _timeSeriesLiteMenuItem.addActionListener(timeSeriesLiteMenuItemListener); - - RiverMonitorPEConfigEditorListener riverMonitorPEConfigEditorListener = new RiverMonitorPEConfigEditorListener(); - _riverMonitorPEConfigMenuItem.addActionListener(riverMonitorPEConfigEditorListener); - - RiverMonGroupDialogListener riverMonGroupDialogListener = new RiverMonGroupDialogListener(); - _riverMonGroupMenuItem.addActionListener(riverMonGroupDialogListener); - - RiverMonLocationDialogListener riverMonLocationDialogListener = new RiverMonLocationDialogListener(); - _riverMonLocationMenuItem.addActionListener(riverMonLocationDialogListener); - - AlertAlarmValidTimeListener alertAlarmValidTimeListener = new AlertAlarmValidTimeListener(); - _validTimeLookUpForAlertAlarmMenuItem.addActionListener(alertAlarmValidTimeListener); - - VtecEventEndTimeListener vtecEventEndTimeListener = new VtecEventEndTimeListener(); - _endTimeLookUpForVTECEventMenuItem.addActionListener(vtecEventEndTimeListener); - - UGCExpireTimeListener ugcExpireTimeListener = new UGCExpireTimeListener(); - _ugcExpireTimeLookUpMenuItem.addActionListener(ugcExpireTimeListener); - - VtecEventProductTimeListener vtecEventProductTimeListener = new VtecEventProductTimeListener(); - _vtecEventProductTimeLookUpMenuItem.addActionListener(vtecEventProductTimeListener); - - LatestObsTimeListener latestObsTimeListener = new LatestObsTimeListener(); - _obsTimeLookUpForLatestObsValueMenuItem.addActionListener(latestObsTimeListener); - - LatestFcstBasisTimeListener latestFcstBasisTimeListener = new LatestFcstBasisTimeListener(); - _fcstBasisTimeLookUpForMaxFcstValueMenuItem.addActionListener(latestFcstBasisTimeListener); - - PrecipThresholdListener precipThresholdListener = new PrecipThresholdListener(_menuSettings.getPrecipSettings()); - _precipThresholdForThreatColorMenuItem.addActionListener(precipThresholdListener); - - DerivedColumnsEditorListener derivedColumnsEditorListener = new DerivedColumnsEditorListener(); - _derivedColumnsMenuItem.addActionListener(derivedColumnsEditorListener); - - AboutListener aboutListener = new AboutListener(); - _aboutMenuItem.addActionListener(aboutListener); - - } - - private class DerivedColumnsEditorListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String editorTitle = ("\"").concat("Derived Columns").concat("\""); - String file = _settingsDir + "/" + RiverMonitorAppManager.DERIVED_COLUMNS_FILE; - launchTextEditor(editorTitle, file, "RiverMonitor Application"); - } - } - - private void setFrameListener() - { - FrameListener frameListener = new FrameListener(); - _mainFrame.addWindowListener(frameListener); - } - - public void closeApplication() - { - _logger.log("RiverMonitor Application Exiting...."); - _logger.log("===================================="); - _rivermonitorDataManager.disconnect(); - _mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - System.exit(0); - } - - private void createOfficeNotesDialog() - { - List lidList = _rivermonitorDataManager.getLidList(); - String lids[] = new String[lidList.size()]; - for(int i=0; i < lidList.size(); i++) - { - lids[i] = lidList.get(i).toString(); - } - Arrays.sort(lids); - System.out.println("Create officenotes lids size:"+ lidList.size()); - Map lidDescDetailsMap = _rivermonitorDataManager.getLidDescDetails(); - if(_officeNotesDialog == null) - _officeNotesDialog = new OfficeNotesDialog(_mainFrame, _officeNotesDataMgr, "RIVERMON", lids, lidDescDetailsMap, _logger); - } - - public void loadSettings() - { - String header = "RiverMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - - private void loadOfficeSettings() - { - String header = "RiverMonitorMenuManager.loadOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_OFFICE_SETTINGS); - } - - public void viewSelectItem(MonitorMessage message) - { - String header = "RiverMonitorMenuManager.viewSelectItem(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - _selectedRowData = (RiverMonitorJTableRowData) message.getMessageData(); - } - - private class UpdateDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - updateRecordCount(); - } - } - - public void updateDisplayWithSettings(MonitorMessage message) - { - String header = "RiverMonitorMenuManager.updateDisplayWithSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - refreshTimeDisplay(); - updateMenuWithNewSettings(); - } - - private void updateMenuWithNewSettings() - { - String fcstTypeSource = _menuSettings.getRiverSettings().getFcstTypeSource(); - - if(fcstTypeSource != null) - { - if(fcstTypeSource.equals("IngestFilter")) - { - _fcstTsIngestFilterMenuItem.setSelected(true); - } - else if(fcstTypeSource.equals("FF")) - { - _fcstTsFFMenuItem.setSelected(true); - } - else - { - _fcstTsFZMenuItem.setSelected(true); - } - } - else - { - _fcstTsFZMenuItem.setActionCommand("IngestFilter"); - } - - if(_menuSettings.shouldShowMissingRiver()) - _showMissingRiverMenuItem.setSelected(true); - else - _showMissingRiverMenuItem.setSelected(false); - } - - public void saveSettings() - { - String header = "RiverMonitorMenuManager.saveSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_SETTINGS); - } - - private void saveOfficeSettings() - { - String header = "RiverMonitorMenuManager.saveOfficeSettings(): "; - - System.out.print(header); - send(this, MessageType.SAVE_OFFICE_SETTINGS); - } - - public void loadSettings(File fileHandler) - { - if(fileHandler != null) - { - String header = "RiverMonitorMenuManager.loadSettings(): "; - - System.out.print(header); - send(this, MessageType.LOAD_SETTINGS); - } - } - - public void loadSettingsFromFile(File fileHandler) - { - String header = "RiverMonitorMenuManager.loadSettingsFromFile(): "; - if(fileHandler != null) - { - _logger.log(header + "Read settings from " + fileHandler.getAbsolutePath()); - loadSettings(fileHandler); - } - } - - - private void changeColumns() - { - String header = "RiverMonitorMenuManager.changeColumns(): "; - - System.out.print(header); - send(this, MessageType.CHANGE_COLUMNS); - } - - private void saveTable() - { - String header = "RiverMonitorMenuManager.saveTable(): "; - - System.out.print(header); - send(this, MessageType.CREATE_TEXT_FROM_VIEW); - } - - private void precipThreatSort() - { - String header = "RiverMonitorMenuManager.precipThreatSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.PRECIP_THREAT_SORT); - } - - private void riverThreatSort() - { - String header = "RiverMonitorMenuManager.riverThreatSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.RIVER_THREAT_SORT); - } - - private void appSort() - { - String header = "RiverMonitorMenuManager.appSort(): "; - - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - - System.out.print(header); - send(this, MessageType.APP_SORT); - } - - private void clearSort() - { - String header = "RiverMonitorMenuManager.clearSort(): "; - System.out.print(header); - send(this, MessageType.CLEAR_SORT); - } - - private void createRiverMonGroupDialog() - { - String defaultHsa = _rivermonitorDataManager.getDefaultHsa(); - if(_riverMonGroupDialog == null) - _riverMonGroupDialog = new RiverMonGroupDialog(_mainFrame, - _rivermonitorDataManager.getRiverMonLocGroupDataManager(), _logger, defaultHsa); - } - - private void createRiverMonLocationDialog() - { - if(_riverMonLocationDialog == null) - _riverMonLocationDialog = new RiverMonLocationDialog(_mainFrame, - _rivermonitorDataManager.getRiverMonLocGroupDataManager(), _logger); - } - - private void createAlertAlarmDialog() - { - if(_alertAlarmDialog == null) - _alertAlarmDialog = new AlertAlarmDialog(_mainFrame, _alertAlarmDataMgr, _logger); - } - - private void createVtecEventDialog() - { - if(_vtecEventDialog == null) - _vtecEventDialog = new VtecEventDialog(_mainFrame, _vtecEventDataMgr, _logger); - } - - private class ExitApplicationListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeApplication(); - } - } - - private class VtecEventDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createVtecEventDialog(); - if(_selectedRowData != null) - { - _vtecEventDialog.showVtecEventDialog(_selectedRowData.getLid()); - } - else - _vtecEventDialog.showVtecEventDialog(null); - } - } - - private class AlertAlarmDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createAlertAlarmDialog(); - if(_selectedRowData != null) - { - _alertAlarmDialog.showAlertAlarmDialog(_selectedRowData.getLid()); - } - else - _alertAlarmDialog.showAlertAlarmDialog(null); - } - } - - private class TimeSeriesLiteMenuItemListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - if(_selectedRowData != null) - { - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, _selectedRowData); - } - else - { - String textMsg = " Unable to display TimeSeriesLite
    "+ - "Please highlight a row... "; - JOptionPane.showMessageDialog(_mainFrame, textMsg,"TimeSeriesLite", JOptionPane.PLAIN_MESSAGE); - } - } - } - - private class SiteSpecificListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String whfsBinDir = _appsDefaults.getToken("whfs_bin_dir", - HydroappsDefaultDirs.WHFS_BIN_DIR); - String siteSpecificExe = whfsBinDir + "/run_SiteSpecific"; - - Runtime rt = Runtime.getRuntime(); - - String cmd; - if(_selectedRowData != null) - cmd = siteSpecificExe + " "+ _selectedRowData.getLid(); - else - cmd = siteSpecificExe; - - try - { - _mainFrame.setWaitCursor(); - rt.exec(cmd); - _logger.log("SiteSpecific App is launched [cmd:"+ cmd +"]"); - _mainFrame.setDefaultCursor(); - } - catch(IOException ex) - { - _mainFrame.setDefaultCursor(); - String str = "Unable to launch SiteSpecific Appln:["+ cmd +"]" + "Exception:"+ ex; - JOptionPane.showMessageDialog(_mainFrame, str,"RiverMonitor Application",JOptionPane.PLAIN_MESSAGE); - } - } - } - - private class PrecipMonitorListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - startMonitor("PrecipMonitor Application", "PRECIP"); - } - } - - private class SaveTableListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - saveTable(); - } - } - - public class OLDShowMissingRiverMenuListener implements ItemListener - { - public void itemStateChanged(ItemEvent e) - { - boolean prevValue = _menuSettings.shouldShowMissingRiver(); - boolean newValue = false; - if( e.getStateChange() == ItemEvent.SELECTED) - { - newValue = true; - } - else if(e.getStateChange() == ItemEvent.DESELECTED) - { - newValue = false; - } - - _menuSettings.setShowMissingRiver(newValue); - - if( prevValue != newValue) - { - menuChange(); - } - } - } - - public class ShowMissingRiverMenuListener implements ItemListener - { - public void itemStateChanged(ItemEvent e) - { - String header = "RiverMonitorMenuManager.ShowMissingPrecipMenuListener.itemStateChanged()"; - - boolean prevValue = _menuSettings.shouldShowMissingRiver(); - boolean newValue = false; - if( e.getStateChange() == ItemEvent.SELECTED) - { - newValue = true; - } - - _menuSettings.setShowMissingRiver(newValue); - - if( prevValue != newValue) - { - sendMissingFilterChanged(); - } - } - } - - public class ChangeColumnsDisplayedMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - changeColumns(); - } - } - - private class ClearSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - clearSort(); - } - } - - private class PrecipThreatSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - precipThreatSort(); - } - } - - private class RiverThreatSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - riverThreatSort(); - } - } - - private class AppSortListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - appSort(); - } - } - - private class RefreshMenuListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - refresh(); - } - } - - private class AlertAlarmValidTimeListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int prevValue = _menuSettings.getRiverSettings().getAlertAlarmLookBack(); - - new LookBackTimeDialog( _mainFrame, _menuSettings.getRiverSettings(), - "AlertAlarm----ValidTime Filter", - new JLabel("
    Num Of Hrs To Lookback:
    "), - RiverColumnDataSettings.VALID_TIME_TAG, 168, 1); - - if(prevValue != _menuSettings.getRiverSettings().getAlertAlarmLookBack()) - { - menuChange(); - } - } - } - - private class VtecEventEndTimeListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int prevValue = _menuSettings.getRiverSettings().getVtecEventEndTimeApproach(); - - new LookBackTimeDialog( _mainFrame, _menuSettings.getRiverSettings(), - "VTEC Event----EndTime Filter", - new JLabel("
    Num Of Hrs To LookAhead:
    "), - RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG, 24, 1); - - if(prevValue != _menuSettings.getRiverSettings().getVtecEventEndTimeApproach()) - { - menuChange(); - } - } - } - - private class VtecEventProductTimeListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int prevValue = _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack(); - - new LookBackTimeDialog( _mainFrame, _menuSettings.getRiverSettings(), - "VTEC Event----Product Time Filter", - new JLabel("
    Num Of Hrs To Lookback:
    "), - RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG, 9000, 1); - - if(prevValue != _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack()) - { - menuChange(); - } - } - } - - private class UGCExpireTimeListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int prevValue = _menuSettings.getRiverSettings().getUgcExpireTimeApproach(); - - new LookBackTimeDialog( _mainFrame, _menuSettings.getRiverSettings(), - "UGC ExpireTime Filter", - new JLabel("
    Num Of Hrs To LookAhead:
    "), - RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG, 24, 1); - - if(prevValue != _menuSettings.getRiverSettings().getUgcExpireTimeApproach()) - { - menuChange(); - } - } - } - - private class LatestObsTimeListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int prevValue = _menuSettings.getRiverSettings().getLatestObsLookBack(); - - new LookBackTimeDialog( _mainFrame, _menuSettings.getRiverSettings(), - "Latest ObsTime Filter", - new JLabel("
    Num Of Hrs To Lookback:
    "), - RiverColumnDataSettings.LATEST_OBS_TIME_TAG, 720, 1); - - if(prevValue != _menuSettings.getRiverSettings().getLatestObsLookBack()) - { - menuChange(); - } - } - } - - private class LatestFcstBasisTimeListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - int prevValue = _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack(); - - new LookBackTimeDialog( _mainFrame, _menuSettings.getRiverSettings(), - "Latest Fcst BasisTime Filter", - new JLabel("
    Num Of Hrs To Lookback:
    "), - RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG, 720, 1); - - if(prevValue != _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack()) - { - menuChange(); - } - } - } - - private class FcstTsMenuItemListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String prevValue = _menuSettings.getRiverSettings().getFcstTypeSource(); - String selectedItem = e.getActionCommand(); - _menuSettings.getRiverSettings().setFcstTypeSource(selectedItem); - - if( ! prevValue.equalsIgnoreCase(_menuSettings.getRiverSettings().getFcstTypeSource())) - { - menuChange(); - } - } - } - - - - private class RiverMonitorPEConfigEditorListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String editorTitle = ("\"").concat("PEConfig File").concat("\""); - String file = _settingsDir + RiverMonitorAppManager.PE_CONFIG_FILE; - launchTextEditor(editorTitle, file, "RiverMonitor Application"); - } - } - - private class RiverMonGroupDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createRiverMonGroupDialog(); - boolean hasTableChanged = _riverMonGroupDialog.showRiverMonGroupDialog(); - if(hasTableChanged) - { - menuChange(); - } - } - } - - private class RiverMonLocationDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createRiverMonLocationDialog(); - boolean hasTableChanged = _riverMonLocationDialog.showRiverMonLocationDialog(); - System.out.println("Rivermonlocation table changed:"+ hasTableChanged); - if(hasTableChanged) - { - menuChange(); - } - } - } - - private class LoadOfficeSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - loadOfficeSettings(); - } - } - - private class SaveOfficeSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String message = " This will overwrite standard office settings for RiverMonitor.
    " + - "Are you sure ?
    "; - if(confirmSaveOfficeSettings(message)) - saveOfficeSettings(); - } - } - - private class LoadSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - loadSettings(); - } - } - - private class FrameListener extends WindowAdapter - { - public void windowClosing(WindowEvent event) - { - closeApplication(); - } - } - - private class OfficeNotesDialogListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - createOfficeNotesDialog(); - if(_selectedRowData != null) - { - _officeNotesDialog.showOfficeNotesDialog(_selectedRowData.getLid()); - } - else - _officeNotesDialog.showOfficeNotesDialog(null); - - _toolBarManager.setOfficeNotesButtonIcon(_officeNotesDataMgr.getCountOfOfficeNotes()); - } - } - - private class SaveSettingsListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - saveSettings(); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - setInitialRefreshTimeInfo(); - updateDisplayWithSettings(message); - } - } - - private class ViewSelectItemReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - viewSelectItem(message); - } - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorRefreshManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorRefreshManager.java deleted file mode 100644 index 172729d996..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorRefreshManager.java +++ /dev/null @@ -1,48 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import javax.swing.JSplitPane; - -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.MonitorRefreshManager; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.DialogHelper; - -public class RiverMonitorRefreshManager extends MonitorRefreshManager -{ - - private RiverMonitorDataManager _riverMonitorDataManager; - - public RiverMonitorRefreshManager(MessageSystemManager msgSystemManager, SessionLogger logger, - RiverMonitorDataManager riverMonitorDataManager, JSplitPane splitPane) - { - super(msgSystemManager, logger, splitPane); - - _riverMonitorDataManager = riverMonitorDataManager; - } - - protected void reloadData(MonitorMessage incomingMessage, MessageType outgoingMessageType) - { - - DialogHelper.setWaitCursor(_splitPane); - - String header = "MonitorRefreshManager.reloadData: "; - System.out.println(header +" Invoked"+ "...Source:" + incomingMessage.getMessageSource() + " Type:" + incomingMessage.getMessageType()); - - Runtime.getRuntime().gc(); - - _riverMonitorDataManager.createRiverMonitorRowDataList(); - - Runtime.getRuntime().gc(); - - System.out.println(header); - send(this, outgoingMessageType); - - DialogHelper.setDefaultCursor(_splitPane); - - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorSettingsManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorSettingsManager.java deleted file mode 100644 index edbdbd0a13..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorSettingsManager.java +++ /dev/null @@ -1,201 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.io.File; - -import javax.swing.JFileChooser; - -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.river.settings.RiverMonitorMenuSettings; -import ohd.hseb.monitor.river.settings.RiverMonitorSettingsFileManager; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; - -public class RiverMonitorSettingsManager extends BaseManager -{ - private String _settingsDir; - private AppsDefaults _appsDefaults; - private SessionLogger _logger; - - private JFileChooser _fileChooser; - - private MonitorFrame _mainFrame; - private ViewSettings _viewSettings; - private FilterSettings _filterSettings; - private RiverMonitorMenuSettings _menuSettings; - - private RiverMonitorSettingsFileManager _riverMonitorSettingsFileManger; - - private String _officeSettingsFile ; - private String _defaultSettingsFile; - - public RiverMonitorSettingsManager(MessageSystemManager msgSystemManager, AppsDefaults appsDefaults, - SessionLogger logger, MonitorFrame mainFrame, ViewSettings viewSettings, - FilterSettings filterSettings, RiverMonitorMenuSettings menuSettings) - { - _appsDefaults = appsDefaults; - _logger = logger; - _viewSettings = viewSettings; - _filterSettings = filterSettings; - _menuSettings = menuSettings; - - _settingsDir = _appsDefaults.getToken("rivermon_config_dir", - HydroappsDefaultDirs.RIVERMON_CONFIG_DIR); - - _riverMonitorSettingsFileManger = new RiverMonitorSettingsFileManager(_logger, _viewSettings, _filterSettings, _menuSettings); - - _mainFrame = mainFrame; - - _officeSettingsFile = _settingsDir.concat("/").concat(RiverMonitorAppManager.SITE_RIVER_SETTINGS_FILE); - _defaultSettingsFile = _settingsDir.concat("/").concat(RiverMonitorAppManager.DEFAULT_RIVER_SETTINGS_FILE); - - setMessageSystemManager(msgSystemManager); - - _msgSystemManager.registerReceiver(new LoadSettingsReceiver(), MessageType.LOAD_SETTINGS); - _msgSystemManager.registerReceiver(new LoadOfficeSettingsReceiver(), MessageType.LOAD_OFFICE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveSettingsReceiver(), MessageType.SAVE_SETTINGS); - _msgSystemManager.registerReceiver(new SaveOfficeSettingsReceiver(), MessageType.SAVE_OFFICE_SETTINGS); - } - - private void saveSettings(MonitorMessage message) - { - String header = "RiverMonitorSettingsManager.saveSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File fileHandler = null; - _fileChooser = new JFileChooser(); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = _fileChooser.showSaveDialog(_mainFrame); - if(result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveOfficeSettings(MonitorMessage message) - { - String header = "RiverMonitorSettingsManager.saveOfficeSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - System.out.print(header); - saveSettingsToFile(fileHandler); - } - - private void saveSettingsToFile(File fileHandler) - { - send(this, MessageType.UPDATE_SETTINGS); - - if(fileHandler != null) - { - _riverMonitorSettingsFileManger.saveSettingsToFile(fileHandler); - } - } - - private void loadSettings(MonitorMessage message) - { - String header = "RiverMonitorSettingsManager.loadSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - if(message.getMessageSource() != this) - { - File fileHandler = null; - _fileChooser = new JFileChooser(); - _fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - _fileChooser.setCurrentDirectory(new File(_settingsDir)); - int result = _fileChooser.showOpenDialog(_mainFrame); - - if(result == JFileChooser.CANCEL_OPTION) - fileHandler = null; - else - fileHandler = _fileChooser.getSelectedFile(); - - loadSettings(fileHandler); - } - } - - public void startRiverMonitor() - { - String header = "RiverMonitorSettings.startRiverMonitor(): "; - File fileHandler = new File(_officeSettingsFile); - if(fileHandler == null || (! fileHandler.exists() )) - { - fileHandler = new File(_defaultSettingsFile); - } - - _logger.log(header + "Trying to load from file :" + fileHandler.getAbsolutePath()); - loadSettings(fileHandler); - } - - private void loadSettings(File fileHandler) - { - String header = "RiverMonitorSettingsManager.loadSettings(): "; - if(fileHandler != null) - { - _riverMonitorSettingsFileManger.setSettingsFromFile(fileHandler); - - System.out.print(header); - send(this, MessageType.RELOAD_DATA_WITH_NEW_SETTINGS); - } - } - - private void loadOfficeSettings(MonitorMessage message) - { - String header = "RiverMonitorSettingsManager.loadOfficeSettings(): "; - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - File fileHandler = new File(_officeSettingsFile); - - loadSettings(fileHandler); - } - - private class SaveOfficeSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveOfficeSettings(message); - } - } - - private class LoadOfficeSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - loadOfficeSettings(message); - } - } - - private class LoadSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - loadSettings(message); - } - } - - private class SaveSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveSettings(message); - } - } - - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorViewManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorViewManager.java deleted file mode 100644 index e4a5fbdf0d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/manager/RiverMonitorViewManager.java +++ /dev/null @@ -1,704 +0,0 @@ -package ohd.hseb.monitor.river.manager; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.util.List; - -import javax.swing.JFileChooser; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.monitor.LocationInfoColumns; -import ohd.hseb.monitor.MonitorFrame; -import ohd.hseb.monitor.MonitorMessage; -import ohd.hseb.monitor.MonitorTimeSeriesLiteManager; -import ohd.hseb.monitor.derivedcolumns.DerivedColumnsFileManager; -import ohd.hseb.monitor.manager.BaseManager; -import ohd.hseb.monitor.manager.Receiver; -import ohd.hseb.monitor.messaging.MessageSystemManager; -import ohd.hseb.monitor.messaging.MessageType; -import ohd.hseb.monitor.precip.PrecipColumns; -import ohd.hseb.monitor.river.RiverColumns; -import ohd.hseb.monitor.river.RiverMonitorDataManager; -import ohd.hseb.monitor.river.RiverMonitorJTableRowData; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.monitor.util.HydroappsDefaultDirs; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; -import ohd.hseb.util.gui.jtable.JTableColumnDisplaySettings; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RiverMonitorViewManager extends BaseManager -{ - private SessionLogger _logger; - - private RiverMonitorDataManager _riverMonitorDataManager; - - private JTableManager _riverMonitorTableManager; - - private ViewSettings _viewSettings; - - private JSplitPane _splitPane; - - private List _riverMonitorAllRowDataList; - - private String _columnNamesCurrentlyDisplayed[]; - - private DerivedColumnsFileManager _derivedColumnsFileManager; - - private MonitorFrame _mainFrame; - - private RiverMonitorJTableRowData _selectedRowData; - - private MonitorTimeSeriesLiteManager _monitorTimeSeriesLiteManager; - - private AppsDefaults _appsDefaults; - - public RiverMonitorViewManager(MonitorFrame mainFrame, - MessageSystemManager msgSystemManager, SessionLogger logger, - RiverMonitorDataManager riverMonitorDataManager, - JSplitPane splitPane, ViewSettings viewSettings, - DerivedColumnsFileManager derivedColumnsFileManager, - MonitorTimeSeriesLiteManager monitorTimeSeriesLiteManager, - AppsDefaults appsDefaults) - { - _logger = logger; - _riverMonitorDataManager = riverMonitorDataManager; - _splitPane = splitPane; - _mainFrame = mainFrame; - _viewSettings = viewSettings; - - _derivedColumnsFileManager = derivedColumnsFileManager; - _monitorTimeSeriesLiteManager = monitorTimeSeriesLiteManager; - _appsDefaults = appsDefaults; - - List riverColumnsList = new RiverColumns() - .getRiverColumnsList(null); - - _derivedColumnsFileManager.getDerivedColumns(); - String derivedColumnNames[] = _derivedColumnsFileManager - .getDerivedColumnNames(); - String alignmentForDerivedColumns[] = _derivedColumnsFileManager - .getAlignmentForDerivedColumns(); - if (derivedColumnNames != null) - { - addDerivedColumnNames(riverColumnsList, derivedColumnNames, - alignmentForDerivedColumns); - } - - Dimension columnHeaderPreferredSize = new Dimension(100, 50); - _riverMonitorTableManager = new ComplexJTableManager(riverColumnsList, - _riverMonitorAllRowDataList, columnHeaderPreferredSize); - - setMessageSystemManager(msgSystemManager); - _msgSystemManager.registerReceiver(new SelectViewItemReceiver(), - MessageType.FILTER_SELECT_ITEM); - _msgSystemManager.registerReceiver(new ChangeColumnsReceiver(), - MessageType.CHANGE_COLUMNS); - _msgSystemManager.registerReceiver(new AppSortReceiver(), - MessageType.APP_SORT); - _msgSystemManager.registerReceiver(new RiverThreatSortReceiver(), - MessageType.RIVER_THREAT_SORT); - _msgSystemManager.registerReceiver(new PrecipThreatSortReceiver(), - MessageType.PRECIP_THREAT_SORT); - _msgSystemManager.registerReceiver(new ClearSortReceiver(), - MessageType.CLEAR_SORT); - _msgSystemManager.registerReceiver( - new UpdateDisplayWithSettingsReceiver(), - MessageType.UPDATE_DISPLAY_WITH_SETTINGS); - _msgSystemManager.registerReceiver(new RefreshDisplayReceiver(), - MessageType.REFRESH_DISPLAY); - _msgSystemManager.registerReceiver(new SaveViewReceiver(), - MessageType.CREATE_TEXT_FROM_VIEW); - _msgSystemManager.registerReceiver(new UpdateSettingsReceiver(), - MessageType.UPDATE_SETTINGS); - - } - - private void addDerivedColumnNames(List riverColumnsList, - String derivedColumnNames[], String alignmentForDerivedColumns[]) - { - for (int i = 0; i < derivedColumnNames.length; i++) - { - riverColumnsList.add(new JTableColumnDescriptor( - derivedColumnNames[i], alignmentForDerivedColumns[i], - derivedColumnNames[i])); - } - } - - private void createTableAndApplySettings(MonitorMessage message) - { - String header = "RiverViewManager.createTableAndApplySettings(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - _riverMonitorAllRowDataList = _riverMonitorDataManager - .getRiverMonitorRowDataList(); - - _columnNamesCurrentlyDisplayed = null; - String columnDisplaySettingsString = _viewSettings - .getColumnDisplaySettings(); - JTableColumnDisplaySettings columnDisplaySettings = _riverMonitorTableManager - .getTableSettings(); - columnDisplaySettings - .setSettingsFromString(columnDisplaySettingsString); - - _columnNamesCurrentlyDisplayed = _riverMonitorTableManager - .getColumnNamesThatAreCurrentlyDisplayed(); - if (_columnNamesCurrentlyDisplayed == null) - { - _columnNamesCurrentlyDisplayed = new String[] { - LocationInfoColumns.LOCATION_ID, - LocationInfoColumns.GROUP_NAME }; - } - - List selectedRowDataList = _riverMonitorDataManager - .getTreeFilterManager().filter(_riverMonitorAllRowDataList); - _riverMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _riverMonitorTableManager.setDisplayableColumns( - _columnNamesCurrentlyDisplayed, true, true); - _riverMonitorTableManager.setPreferredSizeForJScrollPane(new Dimension( - 690, 645)); - - JScrollPane tableScrollPane = _riverMonitorTableManager - .getJScrollPane(); - - _splitPane.setRightComponent(tableScrollPane); - - _riverMonitorTableManager - .addTableListener(new TableMouseMotionListener()); - _riverMonitorTableManager - .addTableListener(new TableListSelectionListener()); - _riverMonitorTableManager.addTableListener(new TableMouseListener()); - } - - public void refreshDisplay(MonitorMessage message) - { - String header = "RiverMonitorViewManager.refreshDisplay(): "; - - System.out.println(header +" Invoked"+ "...Source:" + message.getMessageSource() + " Type:" + message.getMessageType()); - - _riverMonitorAllRowDataList = _riverMonitorDataManager.getRiverMonitorRowDataList(); - List selectedRowDataList = _riverMonitorDataManager.getTreeFilterManager().filter(_riverMonitorAllRowDataList); - _riverMonitorTableManager.setChangedAllRowDataList(selectedRowDataList); - - _riverMonitorTableManager.refreshDisplay(); - - JScrollPane tableScrollPane = _riverMonitorTableManager.getJScrollPane(); - - _splitPane.setRightComponent(tableScrollPane); - - } - - private void updateSettings(MonitorMessage message) - { - String header = "RiverViewManager.selectViewItem(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - updateSettings(); - } - - private void updateSettings() - { - JTableColumnDisplaySettings columnDisplaySettings = _riverMonitorTableManager - .getTableSettings(); - String settings = columnDisplaySettings.getSettingsString(); - _viewSettings.setColumnDisplaySettings(settings); - } - - private void selectViewItem(MonitorMessage message) - { - String header = "RiverViewManager.selectViewItem(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - String lidOfInterest = _riverMonitorDataManager - .getLidOfCurrentInterest(); - int rowToHighLight = _riverMonitorTableManager - .getTheRowIndexToHighLightBasedOnValue(lidOfInterest, - LocationInfoColumns.LOCATION_ID); - System.out.println("Row to highlight:" + rowToHighLight); - if (rowToHighLight != -1) - _riverMonitorTableManager - .selectRows(rowToHighLight, rowToHighLight); - } - - public void printFileException(IOException exception, String header) - { - header = header + ".printFileException(): "; - _logger.log(header + "ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - _logger.log(header + "End of stack trace"); - } - - private void saveTableToFile(String fileName) - { - File fileHandler = new File(fileName); - String header = "RiverMonitorViewManager.saveTableToFile(): "; - String displayedColumns[] = _riverMonitorTableManager - .getColumnNamesThatAreCurrentlyDisplayed(); - String rowData[][] = _riverMonitorTableManager.getDisplayRowDataArray(); - BufferedWriter out = null; - int maxStringLen = 33; - try - { - FileOutputStream fileOutput = new FileOutputStream(fileName, false); - OutputStreamWriter outputStream = new OutputStreamWriter(fileOutput); - out = new BufferedWriter(outputStream); - } - catch (IOException exception) - { - printFileException(exception, header); - } - if (displayedColumns != null) - { - try - { - out.newLine(); - StringBuffer columnNameStringBuffer = new StringBuffer(); - for (int i = 0; i < displayedColumns.length; i++) - { - columnNameStringBuffer.append(getTrimmedOrPaddedString( - displayedColumns[i], maxStringLen)); - columnNameStringBuffer.append(" |"); - } - out.write(columnNameStringBuffer.toString()); - out.newLine(); - } - catch (IOException exception) - { - printFileException(exception, header); - } - } - try - { - for (int i = 0; i < rowData.length; i++) - { - out.newLine(); - StringBuffer dataStringBuffer = new StringBuffer(); - for (int j = 0; j < rowData[i].length; j++) - { - dataStringBuffer.append(getTrimmedOrPaddedString( - rowData[i][j], maxStringLen)); - dataStringBuffer.append(" |"); - } - out.write(dataStringBuffer.toString()); - } - } - catch (IOException exception) - { - printFileException(exception, header); - } - - try - { - out.close(); - } - catch (IOException exception) - { - _logger.log(header + "Unable to close file[" - + fileHandler.getAbsolutePath() + "]"); - printFileException(exception, header); - } - } - - private String getTrimmedOrPaddedString(String origString, int desiredLength) - { - String newString = origString; - - String formatString = "%-" + String.valueOf(desiredLength) + "s"; - - newString = String.format(formatString, origString); - - if (newString.length() > desiredLength) - { - newString = newString.substring(0, desiredLength); - } - - return newString; - } - - private void saveView(MonitorMessage message) - { - String header = "RiverMonitorViewManager.saveView(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - File file = null; - JFileChooser saveFileChooser = new JFileChooser(); - String settingsDir = _appsDefaults.getToken("whfs_report_dir", - HydroappsDefaultDirs.WHFS_REPORT_DIR); - saveFileChooser.setDialogTitle("Export Table To Text File"); - saveFileChooser.setCurrentDirectory(new File(settingsDir)); - saveFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - - int result = saveFileChooser.showSaveDialog(_mainFrame); - if (result == JFileChooser.CANCEL_OPTION) - file = null; - else - file = saveFileChooser.getSelectedFile(); - - if (file != null) - { - saveTableToFile(file.toString()); - } - } - - private void changeColumns(MonitorMessage message) - { - String header = "RiverMonitorViewManager.changeColumns(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - _riverMonitorTableManager.invokeColumnSelector(_mainFrame); - - updateSettings(); - } - - private void updateSort(String[] columnNamesToSort, int[] columnSortNumber, - boolean[] columnSortOrder) - { - _riverMonitorTableManager.setSortInfoNotBasedOnUserClicks( - columnNamesToSort, columnSortOrder, columnSortNumber); - updateSettings(); - } - - private void riverThreatSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.riverThreatSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = { RiverColumns.THREAT }; - int columnSortNumber[] = { 0 }; - boolean columnSortOrder[] = { false }; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void precipThreatSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.precipThreatSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = { PrecipColumns.PRECIP_THREAT }; - int columnSortNumber[] = { 0 }; - boolean columnSortOrder[] = { false }; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void appSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.appSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - - String columnNamesToSort[] = { LocationInfoColumns.HSA, - LocationInfoColumns.GROUP_ORDINAL, - LocationInfoColumns.LOCATION_ORDINAL }; - int columnSortNumber[] = { 0, 1, 2 }; - boolean columnSortOrder[] = { true, true, true }; - - updateSort(columnNamesToSort, columnSortNumber, columnSortOrder); - } - - private void clearSort() - { - _riverMonitorTableManager.clearSort(); - } - - private void clearSort(MonitorMessage message) - { - String header = "RiverMonitorViewManager.clearSort(): "; - System.out.println(header + " Invoked" + "...Source:" - + message.getMessageSource() + " Type:" - + message.getMessageType()); - - clearSort(); - updateSettings(); - } - - private void rowSelected(RiverMonitorJTableRowData selectedRowData) - { - String header = "RiverMonitorViewManager.rowSelected(): "; - - System.out.print(header); - send(this, MessageType.VIEW_SELECT_ITEM, selectedRowData); - } - - // ------------------------------------------------------------------------------------- - public String getToolTipForSelectedCell(String columnName, int rowIndex) - { - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) _riverMonitorTableManager - .getSelectedRowData(rowIndex); - String toolTip = ""; - VTECeventRecord record = null; - - if (columnName.equals(RiverColumns.UGC_EXPIRE_TIME)) - { - record = rowData.getVtecEventRecordForExpireTime(); - } - else if (columnName.equals(RiverColumns.EVENT_END_TIME) - || columnName.equals(RiverColumns.VTEC_SUMMARY)) - { - record = rowData.getVtecEventRecordForEndTime(); - } - - if (record != null) - { - long missingValue = DbTable.getNullLong(); - String beginTime = rowData.getStringValue(record.getBegintime(), - missingValue); - String endTime = rowData.getStringValue(record.getEndtime(), - missingValue); - String productTime = rowData.getStringValue( - record.getProducttime(), missingValue); - String expireTime = rowData.getStringValue(record.getExpiretime(), - missingValue); - - toolTip = "Action: [" + record.getAction() - + "] Signif: [" + record.getSignif() + "]\n
    " - + "BeginTime: [" + beginTime + "] EndTime: [" + endTime - + "]\n
    " + "ProductTime: [" + productTime - + "] ExpireTime: [" + expireTime + "]\n
    "; - } - else if (columnName.equals(RiverColumns.THREAT)) - { - toolTip = rowData.getToolTipTextForThreatSummary(); - } - else if (columnName.equals(PrecipColumns.PRECIP_THREAT)) - { - toolTip = rowData.getToolTipTextForPrecipThreatSummary(); - } - else if (columnName.equals(RiverColumns.ALERT_ALARM)) - { - toolTip = rowData.getToolTipTextForAlertAlarmSummary(); - } - - if (toolTip.length() <= 12) // tooltip has "" only - { - String name = rowData.getName(); - String state = rowData.getState(); - String county = rowData.getCounty(); - String hsa = rowData.getHsa(); - String stream = rowData.getStream(); - String bankfull = rowData.getDataValue(RiverColumns.BANK_FULL); - String actionStage = rowData.getDataValue(RiverColumns.ACT_STG); - String floodStage = rowData.getDataValue(RiverColumns.FLD_STG); - String actionFlow = rowData.getDataValue(RiverColumns.ACT_FLOW); - String floodFlow = rowData.getDataValue(RiverColumns.FLD_FLOW); - String modStage = rowData.getDataValue(RiverColumns.MOD_STG); - String minStage = rowData.getDataValue(RiverColumns.MIN_STG); - String majStage = rowData.getDataValue(RiverColumns.MAJ_STG); - - toolTip = "Name:[" + name + "]\n
    " + "County: [" - + county + "] State: [" + state + "] HSA: [" + hsa - + "]\n
    " + "Stream: [" + stream + "] BankFull: [" - + bankfull + "]\n
    " + "ActionStg: [" + actionStage - + "] FloodStg: [" + floodStage + "]\n
    " - + "ActionFlow: [" + actionFlow + "] FloodFlow: [" - + floodFlow + "]\n
    " + "MinStg: [" + minStage - + "] ModStg: [" + modStage + "] MajStg: [" + majStage - + "]\n
    "; - } - return toolTip; - } - - private class ChangeColumnsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - changeColumns(message); - } - } - - private class ClearSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - clearSort(message); - } - } - - private class PrecipThreatSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - precipThreatSort(message); - } - } - - private class RiverThreatSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - riverThreatSort(message); - } - } - - private class AppSortReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - appSort(message); - } - } - - private class SelectViewItemReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - selectViewItem(message); - } - } - - private class RefreshDisplayReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - refreshDisplay(message); - } - } - - private class UpdateDisplayWithSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - createTableAndApplySettings(message); - } - } - - private class UpdateSettingsReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - updateSettings(message); - } - } - - private class SaveViewReceiver implements Receiver - { - public void receive(MonitorMessage message) - { - saveView(message); - } - } - - private class TableListSelectionListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent e) - { - if (e.getValueIsAdjusting() == false) - { - List selectedRowData = _riverMonitorTableManager - .getSelectedRowsData(); - for (int i = 0; i < selectedRowData.size(); i++) - { - if (i == 0) - { - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) selectedRowData - .get(i); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - } - } - } - } - } - - private class TableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - // String header = - // "RiverMonitorViewManager.TableMouseListener.mouseClicked(): "; - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _riverMonitorTableManager.getMousePointedRowIndex(p); - RiverMonitorJTableRowData rowData = (RiverMonitorJTableRowData) _riverMonitorTableManager - .getSelectedRowData(rowIndex); - - if (e.getClickCount() == 2) - { - // System.out.println(header + " starting TSL for " + - // rowData.getLid()); - _selectedRowData = rowData; - rowSelected(_selectedRowData); - _monitorTimeSeriesLiteManager.displayTimeSeriesLite(_mainFrame, - _selectedRowData); - } - } - - public void mousePressed(MouseEvent e) - { - } - - public void mouseReleased(MouseEvent e) - { - } - - public void mouseEntered(MouseEvent e) - { - } - - public void mouseExited(MouseEvent e) - { - } - } - - // ------------------------------------------------------------------------------------- - class TableMouseMotionListener implements MouseMotionListener - { - public void mouseDragged(MouseEvent e) - { - } - - public void mouseMoved(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - int rowIndex = _riverMonitorTableManager.getMousePointedRowIndex(p); - int colIndex = _riverMonitorTableManager - .getMousePointedColumnIndex(p); - String columnName = _riverMonitorTableManager - .getColumnNameAtIndex(colIndex); - String toolTip = ""; - if (rowIndex != -1) - { - toolTip = getToolTipForSelectedCell(columnName, rowIndex); - _riverMonitorTableManager.setRowToolTipText(toolTip); - } - } - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverColumnDataSettings.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverColumnDataSettings.java deleted file mode 100644 index cd2a814bfd..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverColumnDataSettings.java +++ /dev/null @@ -1,106 +0,0 @@ -package ohd.hseb.monitor.river.settings; - -public class RiverColumnDataSettings -{ - private String _fcstTypeSource; - private int _alertalarmLookBack; - private int _latestObsLookBack; - private int _latestFcstBasisTimeLookBack; - private int _vtecEventEndTimeApproach; - private int _ugcExpireTimeApproach; - private int _vtecEventProductTimeLookBack; - - public static String DEFAULT_FCST_TYPESOURCE = "IngestFilter" ; - public static int DEFAULT_ALERTALARM_LOOKBACK = 8; - public static int DEFAULT_LATEST_OBS_LOOKBACK = 12 ; - public static int DEFAULT_LATEST_FCST_BASISTIME_LOOKBACK = 24; - public static int DEFAULT_VTEC_ENDTIME_APPROACH = 4; - public static int DEFAULT_UGC_EXPIRETIME_APPROACH = 4; - public static int DEFAULT_VTEC_EVENT_PRODUCT_TIME_LOOKBACK = 168; - - public static final String RIVER_SETTINGS_BEGIN_TAG = "#River Settings Begin"; - public static final String RIVER_SETTINGS_END_TAG = "#River Settings End"; - public static String FCST_TS_TAG = "FCST_TS"; - public static String VALID_TIME_TAG = "Valid_Time"; - public static String VTEC_EVENT_END_TIME_TAG = "VTECEventEnd_Time"; - public static String UGC_EXPIRE_TIME_TAG = "UGCExpire_Time"; - public static String VTEC_EVENT_PRODUCT_TIME_TAG = "VTECEventProduct_Time"; - public static String LATEST_FCST_BASIS_TIME_TAG = "LatestFcst_BasisTime"; - public static String LATEST_OBS_TIME_TAG = "LatestObs_Time"; - - public RiverColumnDataSettings() - { - resetSettings(); - } - - public void resetSettings() - { - _fcstTypeSource = DEFAULT_FCST_TYPESOURCE ; - _alertalarmLookBack = DEFAULT_ALERTALARM_LOOKBACK; - _latestObsLookBack = DEFAULT_LATEST_OBS_LOOKBACK; - _latestFcstBasisTimeLookBack = DEFAULT_LATEST_FCST_BASISTIME_LOOKBACK; - _vtecEventEndTimeApproach = DEFAULT_VTEC_ENDTIME_APPROACH; - _ugcExpireTimeApproach = DEFAULT_UGC_EXPIRETIME_APPROACH; - _vtecEventProductTimeLookBack = DEFAULT_VTEC_EVENT_PRODUCT_TIME_LOOKBACK; - } - - public String getFcstTypeSource() - { - return _fcstTypeSource; - } - public void setFcstTypeSource(String fcstTypeSource) - { - _fcstTypeSource = fcstTypeSource; - } - public int getAlertAlarmLookBack() - { - return _alertalarmLookBack; - } - public void setAlertAlarmLookBack(int alertalarmLookBack) - { - _alertalarmLookBack = alertalarmLookBack; - } - public int getLatestObsLookBack() - { - return _latestObsLookBack; - } - public void setLatestObsLookBack(int latestObsLookBack) - { - _latestObsLookBack = latestObsLookBack; - } - public int getLatestFcstBasisTimeLookBack() - { - return _latestFcstBasisTimeLookBack; - } - public void setLatestFcstBasisTimeLookBack(int fcstBasisTimeLookBack) - { - _latestFcstBasisTimeLookBack = fcstBasisTimeLookBack; - } - public int getVtecEventEndTimeApproach() - { - return _vtecEventEndTimeApproach; - } - public void setVtecEventEndTimeApproach(int vtecEventEndTimeApproach) - { - _vtecEventEndTimeApproach = vtecEventEndTimeApproach; - } - public int getUgcExpireTimeApproach() - { - return _ugcExpireTimeApproach; - } - public void setUgcExpireTimeApproach(int ugcExpireTimeApproach) - { - _ugcExpireTimeApproach = ugcExpireTimeApproach; - } - - public int getVtecEventProductTimeLookBack() - { - return _vtecEventProductTimeLookBack; - } - - public void setVtecEventProductTimeLookBack(int vtecEventProductTimeLookBack) - { - _vtecEventProductTimeLookBack = vtecEventProductTimeLookBack; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverMonitorMenuSettings.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverMonitorMenuSettings.java deleted file mode 100644 index 493a4288ec..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverMonitorMenuSettings.java +++ /dev/null @@ -1,99 +0,0 @@ -package ohd.hseb.monitor.river.settings; - -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.util.BooleanHolder; - -public class RiverMonitorMenuSettings -{ - private int _refreshInterval; - - public static final String REFRESH_INTERVAL_TAG = "RefreshInterval"; - - public static final String SHOW_MISSING_RIVER_TAG = "ShowMissingRiver"; - - public static int DEFAULT_REFRESH_INTERVAL = 15; - - private PrecipColumnDataSettings _precipSettings; - private RiverColumnDataSettings _riverSettings; - - // public boolean _showMissingRiver; - - private BooleanHolder _showMissingDataBooleanHolder = new BooleanHolder(true); - - - public RiverMonitorMenuSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingRiver(false); - _precipSettings = new PrecipColumnDataSettings(); - _riverSettings = new RiverColumnDataSettings(); - } - - public void resetSettings() - { - _refreshInterval = DEFAULT_REFRESH_INTERVAL; - setShowMissingRiver(false); - _precipSettings.resetSettings(); - _riverSettings.resetSettings(); - } - - public RiverMonitorMenuSettings(int refreshInterval, boolean showMissingPrecip) - { - _refreshInterval = refreshInterval; - setShowMissingRiver(showMissingPrecip); - _precipSettings = new PrecipColumnDataSettings(); - _riverSettings = new RiverColumnDataSettings(); - } - - public void setPrecipSettings(PrecipColumnDataSettings precipSettings) - { - _precipSettings = precipSettings; - } - - public PrecipColumnDataSettings getPrecipSettings() - { - return _precipSettings; - } - - public void setRiverSettings(RiverColumnDataSettings riverSettings) - { - _riverSettings = riverSettings; - } - - public RiverColumnDataSettings getRiverSettings() - { - return _riverSettings; - } - - public void setRefreshInterval(int refreshInterval) - { - _refreshInterval = refreshInterval; - } - - public int getRefreshInterval() - { - return _refreshInterval; - } - - public boolean shouldShowMissingRiver() - { - return getShowMissingDataBooleanHolder().getValue(); - } - - public void setShowMissingRiver(boolean showMissingRiver) - { - _showMissingDataBooleanHolder.setValue(showMissingRiver); - } - - private void setShowMissingDataBooleanHolder(BooleanHolder showMissingPrecipBooleanHolder) - { - _showMissingDataBooleanHolder = showMissingPrecipBooleanHolder; - } - - public BooleanHolder getShowMissingDataBooleanHolder() - { - return _showMissingDataBooleanHolder; - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverMonitorSettingsFileManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverMonitorSettingsFileManager.java deleted file mode 100644 index f0eccfb643..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/river/settings/RiverMonitorSettingsFileManager.java +++ /dev/null @@ -1,347 +0,0 @@ -package ohd.hseb.monitor.river.settings; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import ohd.hseb.monitor.precip.settings.PrecipColumnDataSettings; -import ohd.hseb.monitor.settings.FilterSettings; -import ohd.hseb.monitor.settings.MonitorSettingsFileManager; -import ohd.hseb.monitor.settings.ViewSettings; -import ohd.hseb.util.SessionLogger; - -public class RiverMonitorSettingsFileManager extends MonitorSettingsFileManager -{ - private RiverMonitorMenuSettings _menuSettings; - private Map _filterTokenValuesMap; - - public RiverMonitorSettingsFileManager(SessionLogger logger, ViewSettings viewSettings, - FilterSettings filterSettings, RiverMonitorMenuSettings menuSettings) - { - super(logger, "#RiverMonitorSettings File", viewSettings, filterSettings); - _menuSettings = menuSettings; - _logger = logger; - createDisplayTokenSet(); - createMenuTokenSet(); - } - - public Set createMenuTokenSet() - { - _menuTokenSet = new HashSet(); - - _menuTokenSet.add(RiverColumnDataSettings.FCST_TS_TAG); - _menuTokenSet.add(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.LATEST_OBS_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.VALID_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG); - _menuTokenSet.add(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG); - _menuTokenSet.add(RiverMonitorMenuSettings.REFRESH_INTERVAL_TAG); - _menuTokenSet.add(RiverMonitorMenuSettings.SHOW_MISSING_RIVER_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.DIFF_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.PRECIP_CAUTION_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_ALERT_TAG); - _menuTokenSet.add(PrecipColumnDataSettings.RATIO_CAUTION_TAG); - - return _displayTokenSet; - } - - public boolean setSettingsFromFile(File fileHandler) - { - String header = "RiverMonitorSettingsFileManager.setSettingsFromFile(): "; - boolean isReadCompleted = true; - - resetSettings(); - - if(isValidSettingsFile(_logger, fileHandler, _settingsFileBeginTag )) - { - BufferedReader in = null; - String line; - try - { - in = new BufferedReader(new FileReader(fileHandler)); - - while(( line = in.readLine()) != null) - { - line = line.trim(); - processLine(line); - } - } - catch(IOException e) - { - printFileException(_logger, e,header); - isReadCompleted = false ; - } - } - else - { - isReadCompleted = false; - } - - setViewAndFilterSettings(); - setRiverSettings(); - return isReadCompleted; - } - - private void resetSettings() - { - _tableDisplaySettingsList = null; - _expandPathTokenValuesList = null; - _pathTokenValuesList = null; - _filterTokenValuesMap = null; - - setViewAndFilterSettings(); - _menuSettings.resetSettings(); - } - - private void setRiverSettings() - { - - if(_filterTokenValuesMap != null) - { - Object object = _filterTokenValuesMap.get(RiverColumnDataSettings.FCST_TS_TAG); - if(object != null) - { - String fcstTypeSource = _filterTokenValuesMap.get(RiverColumnDataSettings.FCST_TS_TAG).toString(); - _menuSettings.getRiverSettings().setFcstTypeSource(fcstTypeSource); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.VALID_TIME_TAG); - if(object != null) - { - Integer alerAlarmLoookback = new Integer(object.toString()); - _menuSettings.getRiverSettings().setAlertAlarmLookBack(alerAlarmLoookback); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_OBS_TIME_TAG); - if(object != null) - { - Integer latestObsLookback = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_OBS_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setLatestObsLookBack(latestObsLookback); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG); - if(object != null) - { - Integer latestFcstBasisTime = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setLatestFcstBasisTimeLookBack(latestFcstBasisTime); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG); - if(object != null) - { - Integer vtecEventProductTimeLookback = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setVtecEventProductTimeLookBack(vtecEventProductTimeLookback); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG); - if(object != null) - { - Integer vtecEventEndTimeApproach = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setVtecEventEndTimeApproach(vtecEventEndTimeApproach); - } - - object = _filterTokenValuesMap.get(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG); - if(object != null) - { - Integer ugcExpireTimeApproach = new Integer(_filterTokenValuesMap.get(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG).toString()); - _menuSettings.getRiverSettings().setUgcExpireTimeApproach(ugcExpireTimeApproach); - } - } - } - - public void saveSettingsToFile(File fileHandler) - { - createSettingsFile(fileHandler); - - BufferedWriter out = null; - String header = "RiverMonitorSettingsFileManager.saveSettingsToFile(): "; - try - { - out = new BufferedWriter(new FileWriter(fileHandler)); - } - catch(IOException exception) - { - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - } - - saveDisplaySettings(out); - - saveMenuSettingsToFile(out); - } - - private void processPrecipToken(String tokenName, String tokenValue) - { - - String spiltStr[] = tokenValue.split("\\|"); - String hr1, hr3, hr6; - - if(spiltStr != null) - { - if(spiltStr.length == 3) // we have 3 values 1hr | 3hr | 6hr correctly - { - hr1 = null; hr3 = null; hr6 = null; - - hr1 = spiltStr[0].trim(); - hr3 = spiltStr[1].trim(); - hr6 = spiltStr[2].trim(); - - if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.PRECIP_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setPrecipCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setPrecipCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setPrecipCaution6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioAlert1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioAlert3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioAlert6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.RATIO_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setRatioCaution1Hr(new Integer(hr1)); - _menuSettings.getPrecipSettings().setRatioCaution3Hr(new Integer(hr3)); - _menuSettings.getPrecipSettings().setRatioCaution6Hr(new Integer(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_ALERT_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffAlert1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffAlert3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffAlert6Hr(new Double(hr6)); - } - else if(tokenName.compareTo(PrecipColumnDataSettings.DIFF_CAUTION_TAG) == 0) - { - _menuSettings.getPrecipSettings().setDiffCaution1Hr(new Double(hr1)); - _menuSettings.getPrecipSettings().setDiffCaution3Hr(new Double(hr3)); - _menuSettings.getPrecipSettings().setDiffCaution6Hr(new Double(hr6)); - } - } - } - } - - public void processMenuToken(String tokenName, String tokenValue) - { - if(tokenName.compareTo(RiverMonitorMenuSettings.REFRESH_INTERVAL_TAG) == 0) - { - _menuSettings.setRefreshInterval(new Integer(tokenValue)); - } - if(tokenName.compareTo(RiverMonitorMenuSettings.SHOW_MISSING_RIVER_TAG) == 0) - { - _menuSettings.setShowMissingRiver(new Boolean(tokenValue)); - } - else if( (tokenName.equals(PrecipColumnDataSettings.DIFF_ALERT_TAG) || - tokenName.equals(PrecipColumnDataSettings.DIFF_CAUTION_TAG) || - tokenName.equals(PrecipColumnDataSettings.PRECIP_ALERT_TAG) || - tokenName.equals(PrecipColumnDataSettings.PRECIP_CAUTION_TAG) || - tokenName.equals(PrecipColumnDataSettings.RATIO_ALERT_TAG) || - tokenName.equals(PrecipColumnDataSettings.RATIO_CAUTION_TAG) )) - { - processPrecipToken(tokenName, tokenValue); - } - else - { - if(_filterTokenValuesMap == null) - { - _filterTokenValuesMap = new HashMap(); - } - - if(tokenValue.length() > 0 && tokenValue.charAt(0) != '\n') - { - _filterTokenValuesMap.put(tokenName, tokenValue); - } - } - } - - public void saveMenuSettingsToFile(BufferedWriter writer) - { - String header = "SettingsFileManager.saveMenuSettingsToFile(): "; - try - { - if(_menuSettings != null) - { - writer.newLine(); - writer.write(RiverMonitorMenuSettings.REFRESH_INTERVAL_TAG + " : " + _menuSettings.getRefreshInterval()); - writer.newLine(); - - writer.newLine(); - writer.write(RiverMonitorMenuSettings.SHOW_MISSING_RIVER_TAG + " : " + _menuSettings.shouldShowMissingRiver()); - writer.newLine(); - - writer.newLine(); - writer.write(RiverColumnDataSettings.RIVER_SETTINGS_BEGIN_TAG); - writer.newLine(); - writer.write(RiverColumnDataSettings.FCST_TS_TAG + " : " + _menuSettings.getRiverSettings().getFcstTypeSource()); - writer.newLine(); - writer.write(RiverColumnDataSettings.LATEST_FCST_BASIS_TIME_TAG + " : " + _menuSettings.getRiverSettings().getLatestFcstBasisTimeLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.LATEST_OBS_TIME_TAG + " : " + _menuSettings.getRiverSettings().getLatestObsLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.VALID_TIME_TAG + " : " + _menuSettings.getRiverSettings().getAlertAlarmLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.VTEC_EVENT_PRODUCT_TIME_TAG + " : " + _menuSettings.getRiverSettings().getVtecEventProductTimeLookBack()); - writer.newLine(); - writer.write(RiverColumnDataSettings.VTEC_EVENT_END_TIME_TAG + " : " + _menuSettings.getRiverSettings().getVtecEventEndTimeApproach()); - writer.newLine(); - writer.write(RiverColumnDataSettings.UGC_EXPIRE_TIME_TAG + " : " + _menuSettings.getRiverSettings().getUgcExpireTimeApproach()); - writer.newLine(); - writer.write(RiverColumnDataSettings.RIVER_SETTINGS_END_TAG); - writer.newLine(); - - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_BEGIN_TAG); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getRatioAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioAlert6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_ALERT_TAG + " : " + _menuSettings.getPrecipSettings().getDiffAlert1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffAlert6Hr() ); - writer.newLine(); - - writer.write(PrecipColumnDataSettings.PRECIP_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getPrecipCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getPrecipCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.RATIO_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getRatioCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getRatioCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.DIFF_CAUTION_TAG + " : " + _menuSettings.getPrecipSettings().getDiffCaution1Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution3Hr() +" | " + - _menuSettings.getPrecipSettings().getDiffCaution6Hr() ); - writer.newLine(); - writer.write(PrecipColumnDataSettings.PRECIP_SETTINGS_END_TAG); - - writer.close(); - } - } - catch(IOException exception) - { - printFileException(_logger, exception,header); - } - - } - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/FilterSettings.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/FilterSettings.java deleted file mode 100644 index 0c98d6bc06..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/FilterSettings.java +++ /dev/null @@ -1,35 +0,0 @@ -package ohd.hseb.monitor.settings; - -import javax.swing.tree.TreePath; - -public class FilterSettings -{ - public static String PATH_TAG = "PATH"; - public static String EXPAND_PATH_TAG = "EXPANDPATH"; - - public static String TREE_SETTINGS_BEGIN_TAG = "#HSA-GROUP-LOCATION TREE SETTINGS"; - - private TreePath[] _selectedPaths; - private TreePath[] _expandedPaths; - - public TreePath[] getSelectedPaths() - { - return _selectedPaths; - } - - public void setSelectedPaths(TreePath[] selectedPaths) - { - _selectedPaths = selectedPaths; - } - - public TreePath[] getExpandedPaths() - { - return _expandedPaths; - } - - public void setExpandedPaths(TreePath[] expandedPaths) - { - _expandedPaths = expandedPaths; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/MonitorSettingsFileManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/MonitorSettingsFileManager.java deleted file mode 100644 index ac14d55b68..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/MonitorSettingsFileManager.java +++ /dev/null @@ -1,418 +0,0 @@ -package ohd.hseb.monitor.settings; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.util.SessionLogger; - -public abstract class MonitorSettingsFileManager -{ - protected SessionLogger _logger; - - protected FilterSettings _filterSettings; - protected ViewSettings _viewSettings; - - protected Set _displayTokenSet; - protected Set _menuTokenSet; - - protected List _tableDisplaySettingsList; - protected List _pathTokenValuesList; - protected List _expandPathTokenValuesList; - - protected String _settingsFileBeginTag; - - public MonitorSettingsFileManager(SessionLogger logger, String settingsFileBeginTag, - ViewSettings viewSettings, - FilterSettings filterSettings) - { - _logger = logger; - _settingsFileBeginTag = settingsFileBeginTag; - _viewSettings = viewSettings; - _filterSettings = filterSettings; - } - - public Set createDisplayTokenSet() - { - _displayTokenSet = new HashSet(); - - _displayTokenSet.add(FilterSettings.PATH_TAG); - _displayTokenSet.add(FilterSettings.EXPAND_PATH_TAG); - _displayTokenSet.add(ViewSettings.COLUMN_TAG); - _displayTokenSet.add(ViewSettings.SORT_TAG); - - return _displayTokenSet; - } - - public boolean isValidSettingsFile(SessionLogger logger, File fileHandler, String checkString) - { - boolean isValidFile = true; - String header = "SettingsFileManager.isValidSettingsFile(): "; - if(fileHandler.exists()) - { - BufferedReader in = null; - String str; - try - { - in = new BufferedReader(new FileReader(fileHandler)); - - if(( str = in.readLine()) != null) - { - if(!str.equals(checkString)) - { - isValidFile = false; - } - } - else - isValidFile = false; - } - catch(IOException exception) - { - printFileException(logger, exception, header); - isValidFile = false; - } - } - else - { - isValidFile = false; - logger.log(header + "[" + fileHandler.getAbsolutePath() +"] doesn't exist" ); - } - - return isValidFile; - } - - public void printFileException(SessionLogger logger, IOException exception, String header) - { - header = header+".printFileException(): "; - logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(logger.getPrintWriter()); - logger.log(header+"End of stack trace"); - } - - public void saveDisplaySettings(BufferedWriter out) - { - String columnDisplaySettings = _viewSettings.getColumnDisplaySettings(); - saveTableDisplaySettings(out, columnDisplaySettings); - - //Write the selected paths - TreePath[] selectedPaths = _filterSettings.getSelectedPaths(); - - saveTreeSettings(out, selectedPaths, FilterSettings.PATH_TAG); - - //Write the expanded paths - TreePath[] expandedPaths = _filterSettings.getExpandedPaths(); - - saveTreeSettings(out, expandedPaths, FilterSettings.EXPAND_PATH_TAG); - } - - public void createSettingsFile(File fileHandler) - { - boolean fileExist = false; - fileExist = fileHandler.exists(); - String header = "RiverMonitorApplicationSettingsManager.createSettingsFile(): "; - - if(!fileExist) - { - try - { - fileHandler.createNewFile(); - } - catch(IOException e) - { - _logger.log(header+ "Unable to Create file:"+ - fileHandler.getAbsolutePath()+ - " for saving table settings"); - } - } - else - { - boolean fileDelete = false; - fileDelete = fileHandler.delete(); - - if(!fileDelete) - { - _logger.log(header+"FileName [" + fileHandler.getAbsolutePath()+ - "]exists already" + - " and unable to delete inorder to" + - "create a new file"); - } - else - { - try - { - fileHandler.createNewFile(); - } - catch(IOException exception) - { - _logger.log(header+"Unable to Create file:"+ - fileHandler.getAbsolutePath()+ - " for saving column setting"); - _logger.log(header+"ERROR = " + exception.getMessage()); - exception.printStackTrace(_logger.getPrintWriter()); - } - } - } - } - - public FilterSettings getFilterSettings() - { - return _filterSettings; - } - - public ViewSettings getViewSettings() - { - return _viewSettings; - } - - public boolean isSettingsLine(String line) - { - boolean result = false; - - if(line.length() > 0) - { - if(line.charAt(0) != '\n') - { - if(line.charAt(0) != '#') - { - result = true; - } - } - } - return result; - } - - public void processTableDisplayToken(String line) - { - if(_tableDisplaySettingsList == null) - { - _tableDisplaySettingsList = new ArrayList(); - } - - _tableDisplaySettingsList.add(line); - } - - public void processPathToken(String tokenValue) - { - if(_pathTokenValuesList == null) - { - _pathTokenValuesList = new ArrayList(); - } - - if(tokenValue.length() > 0 && tokenValue.charAt(0) != '\n') - { - tokenValue = tokenValue.replace('[', ' ').replace(']', ' ').trim(); - _pathTokenValuesList.add(tokenValue); - } - } - - public void processExpandPathToken(String tokenValue) - { - if(_expandPathTokenValuesList == null) - { - _expandPathTokenValuesList = new ArrayList(); - } - if(tokenValue.length() > 0 && tokenValue.charAt(0) != '\n') - { - tokenValue = tokenValue.replace('[', ' ').replace(']', ' ').trim(); - _expandPathTokenValuesList.add(tokenValue); - } - } - - - public void processDisplayToken(String tokenName, String tokenValue) - { - if((tokenName.compareTo(ViewSettings.COLUMN_TAG) == 0) - || (tokenName.compareTo(ViewSettings.SORT_TAG) == 0)) - { - processTableDisplayToken(tokenName + ":" + tokenValue); - } - else if(tokenName.compareTo(FilterSettings.PATH_TAG) == 0) - { - processPathToken(tokenValue); - } - else if(tokenName.compareTo(FilterSettings.EXPAND_PATH_TAG) == 0) - { - processExpandPathToken(tokenValue); - } - } - - public void processLine(String line) - { - String tokenName; - String tokenValue; - - if(isSettingsLine(line)) - { - String[] splitString = line.split(":"); - - if(splitString != null) - { - if( splitString.length == 2 ) - { - tokenName = splitString[0].trim(); - tokenValue = splitString[1].trim(); - if(_menuTokenSet.contains(tokenName)) - { - processMenuToken(tokenName, tokenValue); - } - else if(_displayTokenSet.contains(tokenName)) - { - processDisplayToken(tokenName, tokenValue); - } // token is a valid token - - } // is a valid line line str1:str2 - - } // line has the delimiter : - - }// is a valid settings line - - } - - public void processMenuToken(String tokenName, String tokenValue) - { - - } - - public TreePath[] getTreePathArray(List pathList) - { - TreePath[] paths = null; - if(pathList != null) - { - paths = new TreePath[pathList.size()]; - for(int i=0; i < pathList.size(); i++) - { - String splitStr[] = pathList.get(i).toString().split(", "); - DefaultMutableTreeNode node[] = new DefaultMutableTreeNode[splitStr.length]; - for(int j=0; j < splitStr.length; j++) - { - node[j] = new DefaultMutableTreeNode(splitStr[j]); - } - paths[i] = new TreePath(node); - - } - } - return paths; - } - - public void setViewAndFilterSettings() - { - String header = "MonitorSettingsFileManager.setViewAndFilterSettings(): "; - System.out.println(header); - - String tableDisplaySettingsString = null; - - if(_tableDisplaySettingsList != null) - { - for(int i=0; i < _tableDisplaySettingsList.size(); i++) - { - String str = _tableDisplaySettingsList.get(i); - if(tableDisplaySettingsString == null) - tableDisplaySettingsString = str +"\n"; - else - tableDisplaySettingsString = tableDisplaySettingsString + str +"\n"; - } - } - - //TODO CHIP says: a StringBuffer should be used instead of tableDisplaySettingsString, which will create a lot of String objects - // - // System.out.println(header + "tableDisplaySettingsString = \n" + tableDisplaySettingsString); - _viewSettings.setColumnDisplaySettings(tableDisplaySettingsString); - - TreePath[] paths = getTreePathArray(_pathTokenValuesList); - _filterSettings.setSelectedPaths(paths); - - paths = getTreePathArray(_expandPathTokenValuesList); - _filterSettings.setExpandedPaths(paths); - } - - public void saveTableDisplaySettings(BufferedWriter out, String columnDisplaySettings) - { - String header = "DisplaySettingsFileManager.saveTableDisplaySettings(): "; - - if(columnDisplaySettings != null) - { - for(int i=0; i < columnDisplaySettings.length(); i++) - { - try - { - if(i==0) - { - out.write(_settingsFileBeginTag); - out.newLine(); - } - if(columnDisplaySettings.charAt(i) == '\n') - out.newLine(); - else - out.write(columnDisplaySettings.charAt(i)); - } - catch(IOException exception) - { - printFileException(_logger, exception,header); - return; - } - } - } - - } - - public void saveTreeSettings(BufferedWriter out, TreePath paths[], String settingsTag) - { - String header = "DisplaySettingsFileManager.saveFilterTreeSettings(): "; - - if(paths == null) - { - _logger.log(header + " Paths sent are null while Trying to save " + settingsTag); - return; - } - - for(int j=0; j < paths.length; j++) - { - try - { - if(j == 0) - { - out.newLine(); - out.write(FilterSettings.TREE_SETTINGS_BEGIN_TAG); - out.newLine(); - } - out.write(settingsTag); - out.write(":"); - } - catch(IOException exception) - { - printFileException(_logger,exception,header); - } - - String pathStr = paths[j].toString(); - for(int i=0; i < pathStr.length(); i++) - { - try - { - if(i==pathStr.length()-1) - { - out.write(pathStr.charAt(i)); - out.newLine(); - } - else - out.write(pathStr.charAt(i)); - } - catch(IOException exception) - { - printFileException(_logger,exception,header); - return; - } - } - } - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/ViewSettings.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/ViewSettings.java deleted file mode 100644 index 758a195554..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/settings/ViewSettings.java +++ /dev/null @@ -1,25 +0,0 @@ -package ohd.hseb.monitor.settings; - -public class ViewSettings -{ - public static String COLUMN_TAG = "COLUMN"; - public static String SORT_TAG = "SORT"; - - private String _columnDisplaySettings; - - public ViewSettings() - { - - } - - public String getColumnDisplaySettings() - { - return _columnDisplaySettings; - } - - public void setColumnDisplaySettings(String columnDisplaySettings) - { - _columnDisplaySettings = columnDisplaySettings; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeCellRenderer.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeCellRenderer.java deleted file mode 100644 index bcad199ea2..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeCellRenderer.java +++ /dev/null @@ -1,1052 +0,0 @@ -package ohd.hseb.monitor.treefilter; - -import javax.swing.*; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.ActionMapUIResource; -import java.awt.event.*; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Image; -import java.awt.Toolkit; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JPanel; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreeCellRenderer; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -import ohd.hseb.util.CodeTimer; - -public class MonitorCheckTreeCellRenderer extends JPanel implements TreeCellRenderer -{ - /** This is a type-safe enumerated type */ - public static class State { private State() { } } - public static final State NOT_SELECTED = new State(); - public static final State SELECTED = new State(); - public static final State DONT_CARE = new State(); - - private MonitorCheckTreeSelectionModel _selectionModel; - private TreeCellRenderer _delegate; - private TristateCheckBox _checkBox = new TristateCheckBox(); - - private String _greenLocationIconFile ; - private String _redLocationIconFile ; - private String _yellowLocationIconFile; - private String _darkGreenLocationIconFile; - private String _grayLocationIconFile; - - private String _greenGroupIconFile; - private String _yellowGroupIconFile; - private String _redGroupIconFile; - private String _darkGreenGroupIconFile; - private String _grayGroupIconFile; - - private String _greenHsaIconFile; - private String _yellowHsaIconFile; - private String _redHsaIconFile; - private String _darkGreenHsaIconFile; - private String _grayHsaIconFile; - - private Icon _greenLocationIcon ; - private Icon _redLocationIcon ; - private Icon _yellowLocationIcon; - private Icon _darkGreenLocationIcon; - private Icon _grayLocationIcon; - - private Icon _greenGroupIcon ; - private Icon _redGroupIcon ; - private Icon _yellowGroupIcon; - private Icon _darkGreenGroupIcon; - private Icon _grayGroupIcon; - - private Icon _greenHsaIcon ; - private Icon _redHsaIcon ; - private Icon _yellowHsaIcon; - private Icon _darkGreenHsaIcon; - private Icon _grayHsaIcon; - - private JLabel _redLocationLabel = null; - private JLabel _greenLocationLabel = null; - private JLabel _yellowLocationLabel = null; - private JLabel _darkGreenLocationLabel = null; - private JLabel _grayLocationLabel = null; - private JLabel _redGroupLabel = null; - private JLabel _greenGroupLabel = null; - private JLabel _yellowGroupLabel = null; - private JLabel _darkGreenGroupLabel = null; - private JLabel _grayGroupLabel = null; - private JLabel _redHsaLabel = null; - private JLabel _greenHsaLabel = null; - private JLabel _yellowHsaLabel = null; - private JLabel _darkGreenHsaLabel = null; - private JLabel _grayHsaLabel = null; - - // private List _rowDataForAllLocationsList; - private Map _rowToCriticalColorMap = null; - - public MonitorCheckTreeCellRenderer(TreeCellRenderer delegate, MonitorCheckTreeSelectionModel selectionModel, - Map rowToCriticalColorMap, String iconsDir) - { - this._delegate = delegate; - this._selectionModel = selectionModel; - _rowToCriticalColorMap = rowToCriticalColorMap; - setLayout(new BorderLayout()); - setOpaque(false); - _checkBox.setOpaque(false); - - //createIcons(iconsDir); - createLabels(); - } - - public void setRowToCriticalColorMap(Map rowToCriticalColorMap) - { - _rowToCriticalColorMap = rowToCriticalColorMap; - } - - private void createLabels() - { - _redLocationLabel = new JLabel(); - _redLocationLabel.setIcon(_redLocationIcon); - _redLocationLabel.setForeground(Color.RED); - _greenLocationLabel = new JLabel(); - _greenLocationLabel.setIcon(_greenLocationIcon); - _greenLocationLabel.setForeground(Color.GREEN); - _yellowLocationLabel = new JLabel(); - _yellowLocationLabel.setIcon(_yellowLocationIcon); - _yellowLocationLabel.setForeground(Color.YELLOW); - _darkGreenLocationLabel = new JLabel(); - _darkGreenLocationLabel.setIcon(_darkGreenLocationIcon); - _darkGreenLocationLabel.setForeground(new Color(0, 153, 0)); - _grayLocationLabel = new JLabel(); - _grayLocationLabel.setIcon(_grayLocationIcon); - _grayLocationLabel.setForeground(Color.LIGHT_GRAY); - - _redGroupLabel = new JLabel(); - _redGroupLabel.setIcon(_redGroupIcon); - _redGroupLabel.setForeground(Color.RED); - _yellowGroupLabel = new JLabel(); - _yellowGroupLabel.setIcon(_yellowGroupIcon); - _yellowGroupLabel.setForeground(Color.YELLOW); - _greenGroupLabel = new JLabel(); - _greenGroupLabel.setIcon(_greenGroupIcon); - _greenGroupLabel.setForeground(Color.GREEN); - _darkGreenGroupLabel = new JLabel(); - _darkGreenGroupLabel.setIcon(_darkGreenGroupIcon); - _darkGreenGroupLabel.setForeground(new Color(0, 153, 0)); - _grayGroupLabel = new JLabel(); - _grayGroupLabel.setIcon(_grayGroupIcon); - _grayGroupLabel.setForeground(Color.LIGHT_GRAY); - - _redHsaLabel = new JLabel(); - _redHsaLabel.setIcon(_redHsaIcon); - _redHsaLabel.setForeground(Color.RED); - _yellowHsaLabel = new JLabel(); - _yellowHsaLabel.setIcon(_yellowHsaIcon); - _yellowHsaLabel.setForeground(Color.YELLOW); - _greenHsaLabel = new JLabel(); - _greenHsaLabel.setIcon(_greenHsaIcon); - _greenHsaLabel.setForeground(Color.GREEN); - _darkGreenHsaLabel = new JLabel(); - _darkGreenHsaLabel.setIcon(_darkGreenHsaIcon); - _darkGreenHsaLabel.setForeground(new Color(0, 153, 0)); - _grayHsaLabel = new JLabel(); - _grayHsaLabel.setIcon(_grayHsaIcon); - _grayHsaLabel.setForeground(Color.LIGHT_GRAY); - } - - - private void createIcons(String iconsDir) - { - _greenHsaIconFile = iconsDir + "GreenHsa.GIF"; - _redHsaIconFile = iconsDir + "RedHsa.GIF"; - _yellowHsaIconFile = iconsDir + "YellowHsa.GIF"; - _darkGreenHsaIconFile = iconsDir + "DarkGreenHsa.GIF"; - _grayHsaIconFile = iconsDir + "GrayHsa.GIF"; - - _greenGroupIconFile = iconsDir + "GreenGroup.GIF"; - _redGroupIconFile = iconsDir + "RedGroup.GIF"; - _yellowGroupIconFile = iconsDir + "YellowGroup.GIF"; - _darkGreenGroupIconFile = iconsDir + "DarkGreenGroup.GIF"; - _grayGroupIconFile = iconsDir + "GrayGroup.GIF"; - - _greenLocationIconFile = iconsDir + "GreenLocation.GIF"; - _redLocationIconFile = iconsDir + "RedLocation.GIF"; - _yellowLocationIconFile = iconsDir + "YellowLocation.GIF"; - _darkGreenLocationIconFile = iconsDir + "DarkGreenLocation.GIF"; - _grayLocationIconFile = iconsDir + "GrayLocation.GIF"; - - _greenLocationIcon = createIcon(_greenLocationIconFile); - _redLocationIcon = createIcon(_redLocationIconFile); - _yellowLocationIcon = createIcon(_yellowLocationIconFile); - _darkGreenLocationIcon = createIcon(_darkGreenLocationIconFile); - _grayLocationIcon = createIcon(_grayLocationIconFile); - - _greenGroupIcon= createIcon(_greenGroupIconFile); - _yellowGroupIcon= createIcon(_yellowGroupIconFile); - _redGroupIcon= createIcon(_redGroupIconFile); - _darkGreenGroupIcon= createIcon(_darkGreenGroupIconFile); - _grayGroupIcon= createIcon(_grayGroupIconFile); - - _greenHsaIcon= createIcon(_greenHsaIconFile); - _yellowHsaIcon= createIcon(_yellowHsaIconFile); - _redHsaIcon= createIcon(_redHsaIconFile); - _darkGreenHsaIcon= createIcon(_darkGreenHsaIconFile); - _grayHsaIcon= createIcon(_grayHsaIconFile); - - } - - public Component getTreeCellRendererComponent(JTree tree, Object value, - boolean selected, boolean expanded, - boolean leaf, int row, boolean hasFocus) - { - Component renderer = _delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); - TreePath path = tree.getPathForRow(row); - Component returnedComponent = null; - DefaultTreeCellRenderer tempRenderer = (DefaultTreeCellRenderer) renderer; - returnedComponent = getAppropriateLabel(leaf, path, tempRenderer, value); - if(path!=null) - { - if(_selectionModel.isPathSelected(path, true)) - { - _checkBox.setState(SELECTED); - } - else - { - _checkBox.setState(_selectionModel.isPartiallySelected(path) ? null : NOT_SELECTED); - } - } - removeAll(); - add(_checkBox, BorderLayout.WEST); - add(returnedComponent, BorderLayout.CENTER); - return this; - } - - private JLabel getAppropriateLabelOld(boolean isLeaf, TreePath path, DefaultTreeCellRenderer renderer, Object value) - { - String header = "MonitorCheckTreeCellRenderer.getAppropriateLabelOld(): "; - - JLabel returnedComponent = null; - renderer.setLeafIcon(null); - renderer.setClosedIcon(null); - renderer.setOpenIcon(null); - CodeTimer timer = new CodeTimer(); - timer.restart(); - - if (path == null) - { - System.out.println(header + "null value for value = " + value); - } - - if (isLeaf) - { - // System.out.println(header + "Leaf: value = " + value); - - returnedComponent = getLabelComponentForChild(value); - if (returnedComponent == null) - { - - - _greenLocationLabel.setText(value.toString()); - returnedComponent = _greenLocationLabel; - } - } - else - { - if(path != null) - { - if(path.getPathCount() == 3) // group node - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - - JLabel groupLabel = null; - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(node); - if (locationLabel == _redLocationLabel) - { - groupLabel = _redGroupLabel; - } - else if (locationLabel == _yellowLocationLabel) - { - groupLabel = _yellowGroupLabel; - } - else if (locationLabel == _grayLocationLabel) - { - // groupLabel = _grayGroupLabel; - groupLabel = _greenGroupLabel; - } - else if (locationLabel == _darkGreenLocationLabel) - { - groupLabel = _darkGreenGroupLabel; - } - else - { - groupLabel = _greenGroupLabel; - } - groupLabel.setText(value.toString()); - returnedComponent = groupLabel; - }// else if pathCount == 3 ends here - else if(path.getPathCount() == 2) //hsa node - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - int groupCount = node.getChildCount(); - JLabel hsaLabel = null; - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _redLocationLabel) - { - hsaLabel = _redHsaLabel; - break; - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _yellowLocationLabel) - { - hsaLabel = _yellowHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _grayLocationLabel) - { - hsaLabel = _greenHsaLabel; - // hsaLabel = _grayHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _darkGreenLocationLabel) - { - hsaLabel = _darkGreenHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - hsaLabel = _greenHsaLabel; - } - hsaLabel.setText(value.toString()); - returnedComponent = hsaLabel; - }// else if pathCount == 2 ends here - }// path != null ends here - - if(returnedComponent == null) - returnedComponent = renderer; - } - // timer.stop("Time elapsed in getAppropriateLabel():"); - return returnedComponent; - } - - // ------------------------------------------------------------------------------------------------------------- - - private void analyzePathInfo(boolean isLeaf, TreePath path, Object value) - { - //This method is just for debugging purposes and can be commented out at will - String header = "MonitorCheckTreeCellRenderer.analyzePathInfo(): "; - - boolean path2 = false; - boolean path3 = false; - boolean path4 = false; - boolean nullPath = false; - - int pathCount = -1; - String pathString = null; - if (path != null) - { - pathCount = path.getPathCount(); - pathString = path.toString(); - } - - - System.out.println(header + "isLeaf = " + isLeaf + - " pathCount = " + pathCount + - " treePath = " + pathString + - " for nodeValue = " + value); - - /* - if (path != null) - { - pathCount = path.getPathCount(); - - switch(pathCount) - { - case 2: - path2 = true; - break; - case 3: - path3 = true; - break; - case 4: - path4 = true; - break; - } - } - else // (path == null) - { - nullPath = true; - } - - if (isLeaf != path4) - { - - System.out.print(header + "isLeaf = " + isLeaf + - " but path4 = " + path4 + - " pathCount = " + pathCount + - " treePath = " + path.toString() + - " for nodeValue = " + value); - - if (nullPath) - { - System.out.println(" nullPath is true"); - } - else - { - System.out.println(); - } - - } - else //isLeaf == path4 - { - // System.out.print(header + "isLeaf = " + isLeaf + - // " AND path4 = " + path4 + - // " for nodeValue = " + value); - - if (nullPath) - { - System.out.println(" nullPath is true"); - } - else - { - System.out.println(); - } - } - - */ - - } - - // ------------------------------------------------------------------------------------------------------------- - - - private JLabel getAppropriateLabel(boolean isLeaf, TreePath path, DefaultTreeCellRenderer renderer, Object value) - { - String header = "MonitorCheckTreeCellRenderer.getAppropriateLabel(): "; - - JLabel returnedComponent = null; - renderer.setLeafIcon(null); - renderer.setClosedIcon(null); - renderer.setOpenIcon(null); - CodeTimer timer = new CodeTimer(); - timer.restart(); - - - int pathCount = -1; - if (path != null) - { - pathCount = path.getPathCount(); - } - - // analyzePathInfo(isLeaf, path, value); - - if (isLeaf) - // if (path != null && path.getPathCount() == 4) - { - // System.out.println(header + "Leaf: value = " + value); - - if (pathCount == 4) - { - - returnedComponent = getLabelComponentForChild(value); - if (returnedComponent == null) - { - System.out.println(header + "********** - got here **************"); - _greenLocationLabel.setText(value.toString()); - returnedComponent = _greenLocationLabel; - } - } - else if (pathCount == 3) - { - returnedComponent = getGroupLabel(path, value); - } - else if (pathCount == 2) - { - returnedComponent = getHsaLabel(path, value); - } - else if (pathCount == -1) - { - returnedComponent = getLabelComponentForChild(value); - } - } - else //not a leaf - { - if(path != null) - { - if(path.getPathCount() == 3) // group node - { - returnedComponent = getGroupLabel(path, value); - } - else if(path.getPathCount() == 2) //hsa node - { - returnedComponent = getHsaLabel(path, value); - - } - }// path != null ends here - else //path == null - { - System.out.println(header + "value = " + value + " and the path == null !!!!!!!!!!!!!!!!!!!!!!!!"); - } - - if(returnedComponent == null) - returnedComponent = renderer; - } - // timer.stop("Time elapsed in getAppropriateLabel():"); - return returnedComponent; - } - - // --------------------------------------------------------------------------------------------------------------- - - private JLabel getGroupLabel(TreePath treePath, Object value) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - JLabel groupLabel = null; - - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(node); - if (locationLabel == _redLocationLabel) - { - groupLabel = _redGroupLabel; - } - else if (locationLabel == _yellowLocationLabel) - { - groupLabel = _yellowGroupLabel; - } - else if (locationLabel == _grayLocationLabel) - { - // groupLabel = _grayGroupLabel; - groupLabel = _greenGroupLabel; - } - else if (locationLabel == _darkGreenLocationLabel) - { - groupLabel = _darkGreenGroupLabel; - } - else - { - groupLabel = _greenGroupLabel; - } - groupLabel.setText(value.toString()); - - - return groupLabel; - } - - // ------------------------------------------------------------------------------------------------------- - - private JLabel getHsaLabel(TreePath treePath, Object value) - { - JLabel hsaLabel = null; - - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - int groupCount = node.getChildCount(); - - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _redLocationLabel, _redHsaLabel, node, groupCount); - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _yellowLocationLabel, _yellowHsaLabel, node, groupCount); - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _grayLocationLabel, _greenHsaLabel, node, groupCount); //gray to green on purpose - hsaLabel = getHsaLocationLabelChildByColorLabelMatch(hsaLabel, _darkGreenLocationLabel, _darkGreenHsaLabel, node, groupCount); - - if(hsaLabel == null) - { - hsaLabel = _greenHsaLabel; - } - hsaLabel.setText(value.toString()); - - - return hsaLabel; - - } - // --------------------------------------------------------------------------------------------------------------- - private JLabel getHsaLabelOld(TreePath treePath, Object value) - { - JLabel hsaLabel = null; - - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - int groupCount = node.getChildCount(); - - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _redLocationLabel) - { - hsaLabel = _redHsaLabel; - break; - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _yellowLocationLabel) - { - hsaLabel = _yellowHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _grayLocationLabel) - { - hsaLabel = _greenHsaLabel; - // hsaLabel = _grayHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(hsaLabel == null) - { - if(locationLabel == _darkGreenLocationLabel) - { - hsaLabel = _darkGreenHsaLabel; - break; - } - } - } - } - if(hsaLabel == null) - { - hsaLabel = _greenHsaLabel; - } - hsaLabel.setText(value.toString()); - - - return hsaLabel; - - } - // --------------------------------------------------------------------------------------------------------------- - private JLabel getHsaLocationLabelChildByColorLabelMatch(JLabel resultHsaLabel, JLabel targetLocationLabel, - JLabel targetHsaLabel, TreeNode node, int groupCount ) - { - if (resultHsaLabel == null) - { - for(int j=0; j< groupCount; j++) - { - DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) node.getChildAt(j); - JLabel locationLabel = getLocationLabelDenotingCurrentStateForParentNode(groupNode); - if(resultHsaLabel == null) - { - if(locationLabel == targetLocationLabel) - { - resultHsaLabel = targetHsaLabel; - break; - } - } - } //end for - } - - return resultHsaLabel; - } - - // --------------------------------------------------------------------------------------------------------------- - - private JLabel getLocationLabelDenotingCurrentStateForParentNode(DefaultMutableTreeNode groupNode) - { - // CodeTimer timer = new CodeTimer(); - // timer.restart(); - int locationCount = groupNode.getChildCount(); - JLabel locationLabelDenotingCurrentState = null; - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - - if(locationLabelDenotingCurrentState == _redLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - if(locationLabelDenotingCurrentState != _redLocationLabel) - { - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - if(locationLabelDenotingCurrentState == _yellowLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - } - if(locationLabelDenotingCurrentState != _yellowLocationLabel) - { - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - if(locationLabelDenotingCurrentState == _grayLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - } - if(locationLabelDenotingCurrentState != _grayLocationLabel) - { - for(int i=0; i < locationCount; i++) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) groupNode.getChildAt(i); - locationLabelDenotingCurrentState = getLabelComponentForChild(childNode); - if(locationLabelDenotingCurrentState == _darkGreenLocationLabel) - { - return locationLabelDenotingCurrentState; - } - } - } - locationLabelDenotingCurrentState = _greenLocationLabel; - // timer.stop("Time elapsed in getLocationLabelDenotingCurrentStateForParentNode():"); - return locationLabelDenotingCurrentState; - } - - private JLabel getLabelComponentForChild(Object value) - { - // _timer.restart(); - JLabel label = null; - Color darkGreen = new Color(0, 153, 0); - String lid = value.toString(); - - Color criticalColor = (Color) _rowToCriticalColorMap.get(lid); - if(criticalColor == Color.RED) - { - _redLocationLabel.setText(value.toString()); - label = _redLocationLabel; - } - else if(criticalColor == Color.YELLOW) - { - _yellowLocationLabel.setText(value.toString()); - label = _yellowLocationLabel; - } - else if(criticalColor == Color.GRAY) - { - _grayLocationLabel.setText(value.toString()); - label = _grayLocationLabel; - } - // else if(criticalColor.equals(new Color(0, 153, 0))) - else if(criticalColor == darkGreen) - { - _darkGreenLocationLabel.setText(value.toString()); - label = _darkGreenLocationLabel; - } - else - { - _greenLocationLabel.setText(value.toString()); - label = _greenLocationLabel; - } - - // _timer.stop("Time elapsed in getLabelComponentForChild()"); - return label; - } - - /* private JLabel getLabelComponentForChild(Object value) - { - // _timer.restart(); - JLabel label = null; - //List allRowDataList = _tableManager.getAllRowDataList(); - List rowDataForAllLocationsList = _rowDataForAllLocationsList; - for(int i=0; i < rowDataForAllLocationsList.size(); i++) - { - RiverMonitorJTableRowData2 rowData = (RiverMonitorJTableRowData2) rowDataForAllLocationsList.get(i); - if(rowData.getDataValue("Location Id").toString().equals(value.toString())) - { - Color criticalColor = rowData.getCriticalColorForThisRow(); - if(criticalColor == Color.RED) - { - _redLocationLabel.setText(value.toString()); - label = _redLocationLabel; - break; - } - else if(criticalColor == Color.YELLOW) - { - _yellowLocationLabel.setText(value.toString()); - label = _yellowLocationLabel; - break; - } - else if(criticalColor == Color.GRAY) - { - _grayLocationLabel.setText(value.toString()); - label = _grayLocationLabel; - break; - } - else if(criticalColor.equals(new Color(0, 153, 0))) - { - _darkGreenLocationLabel.setText(value.toString()); - label = _darkGreenLocationLabel; - break; - } - else - { - _greenLocationLabel.setText(value.toString()); - label = _greenLocationLabel; - break; - } - } - } - // _timer.stop("Time elapsed in getLabelComponentForChild()"); - return label; - } - */ - - private Icon createIcon(String fileName) - { - Icon icon = null; - int width = 15; - int height = 15; - Image image = Toolkit.getDefaultToolkit().getImage(fileName); - Image newImage = image.getScaledInstance(width, height, Image.SCALE_FAST); - icon = new ImageIcon(newImage); - return icon; - } - - - /** - * Maintenance tip - There were some tricks to getting this code - * working: - * - * 1. You have to overwite addMouseListener() to do nothing - * 2. You have to add a mouse event on mousePressed by calling - * super.addMouseListener() - * 3. You have to replace the UIActionMap for the keyboard event - * "pressed" with your own one. - * 4. You have to remove the UIActionMap for the keyboard event - * "released". - * 5. You have to grab focus when the next state is entered, - * otherwise clicking on the component won't get the focus. - * 6. You have to make a TristateDecorator as a button model that - * wraps the original button model and does state management. - */ - public class TristateCheckBox extends JCheckBox { - - private final TristateDecorator model; - - public TristateCheckBox(String text, Icon icon, State initial){ - super(text, icon); - // Add a listener for when the mouse is pressed - super.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e) { - grabFocus(); - model.nextState(); - } - }); - // Reset the keyboard action map - ActionMap map = new ActionMapUIResource(); - map.put("pressed", new AbstractAction() { - public void actionPerformed(ActionEvent e) { - grabFocus(); - model.nextState(); - } - }); - map.put("released", null); - SwingUtilities.replaceUIActionMap(this, map); - // set the model to the adapted model - model = new TristateDecorator(getModel()); - setModel(model); - setState(initial); - } - public TristateCheckBox(String text, State initial) { - this(text, null, initial); - } - public TristateCheckBox(String text) { - this(text, DONT_CARE); - } - public TristateCheckBox() { - this(null); - } - - /** No one may add mouse listeners, not even Swing! */ - public void addMouseListener(MouseListener l) { } - /** - * Set the new state to either SELECTED, NOT_SELECTED or - * DONT_CARE. If state == null, it is treated as DONT_CARE. - */ - public void setState(State state) { model.setState(state); } - /** Return the current state, which is determined by the - * selection status of the model. */ - public State getState() { return model.getState(); } - public void setSelected(boolean b) { - if (b) { - setState(SELECTED); - } else { - setState(NOT_SELECTED); - } - } - /** - * Exactly which Design Pattern is this? Is it an Adapter, - * a Proxy or a Decorator? In this case, my vote lies with the - * Decorator, because we are extending functionality and - * "decorating" the original model with a more powerful model. - */ - private class TristateDecorator implements ButtonModel { - private final ButtonModel other; - private TristateDecorator(ButtonModel other) { - this.other = other; - } - private void setState(State state) { - if (state == NOT_SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(false); - } else if (state == SELECTED) { - other.setArmed(false); - setPressed(false); - setSelected(true); - } else { // either "null" or DONT_CARE - other.setArmed(true); - setPressed(true); - setSelected(true); - } - } - /** - * The current state is embedded in the selection / armed - * state of the model. - * - * We return the SELECTED state when the checkbox is selected - * but not armed, DONT_CARE state when the checkbox is - * selected and armed (grey) and NOT_SELECTED when the - * checkbox is deselected. - */ - private State getState() { - if (isSelected() && !isArmed()) { - // normal black tick - return SELECTED; - } else if (isSelected() && isArmed()) { - // don't care grey tick - return DONT_CARE; - } else { - // normal deselected - return NOT_SELECTED; - } - } - /** We rotate between NOT_SELECTED, SELECTED and DONT_CARE.*/ - private void nextState() { - State current = getState(); - if (current == NOT_SELECTED) { - setState(SELECTED); - } else if (current == SELECTED) { - setState(DONT_CARE); - } else if (current == DONT_CARE) { - setState(NOT_SELECTED); - } - } - /** Filter: No one may change the armed status except us. */ - public void setArmed(boolean b) { - } - /** We disable focusing on the component when it is not - * enabled. */ - public void setEnabled(boolean b) { - setFocusable(b); - other.setEnabled(b); - } - /** All these methods simply delegate to the "other" model - * that is being decorated. */ - public boolean isArmed() { return other.isArmed(); } - public boolean isSelected() { return other.isSelected(); } - public boolean isEnabled() { return other.isEnabled(); } - public boolean isPressed() { return other.isPressed(); } - public boolean isRollover() { return other.isRollover(); } - public void setSelected(boolean b) { other.setSelected(b); } - public void setPressed(boolean b) { other.setPressed(b); } - public void setRollover(boolean b) { other.setRollover(b); } - public void setMnemonic(int key) { other.setMnemonic(key); } - public int getMnemonic() { return other.getMnemonic(); } - public void setActionCommand(String s) { - other.setActionCommand(s); - } - public String getActionCommand() { - return other.getActionCommand(); - } - public void setGroup(ButtonGroup group) { - other.setGroup(group); - } - public void addActionListener(ActionListener l) { - other.addActionListener(l); - } - public void removeActionListener(ActionListener l) { - other.removeActionListener(l); - } - public void addItemListener(ItemListener l) { - other.addItemListener(l); - } - public void removeItemListener(ItemListener l) { - other.removeItemListener(l); - } - public void addChangeListener(ChangeListener l) { - other.addChangeListener(l); - } - public void removeChangeListener(ChangeListener l) { - other.removeChangeListener(l); - } - public Object[] getSelectedObjects() { - return other.getSelectedObjects(); - } - } - } -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeManager.java deleted file mode 100644 index 49ae55609c..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeManager.java +++ /dev/null @@ -1,351 +0,0 @@ -package ohd.hseb.monitor.treefilter; - -import java.awt.Color; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.JCheckBox; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -public class MonitorCheckTreeManager extends MouseAdapter implements TreeSelectionListener -{ - private MonitorCheckTreeSelectionModel _selectionModel; - private JTree _tree = new JTree(); - int _hotspot = new JCheckBox().getPreferredSize().width; - - private List _allAvailablePathsList = null; - private TreePath[] _allAvailablePaths = null; - private Map _allAvailablePathsMap = new HashMap(); - - public MonitorCheckTreeManager(JTree tree, - TreePath[] preSelectedPaths, - TreePath[] preExpandedPaths, - Map rowToCriticalColorMap, - String iconsDir) - { - final String header = "MonitorCheckTreeManager - constructor()"; - - System.out.println("In "+ header); - this._tree = tree; - _selectionModel = new MonitorCheckTreeSelectionModel(tree.getModel()); - tree.setCellRenderer(new MonitorCheckTreeCellRenderer(tree.getCellRenderer(), _selectionModel, rowToCriticalColorMap, iconsDir)); - - _allAvailablePathsList = new ArrayList(); - TreeNode root = (TreeNode)tree.getModel().getRoot(); - determineAllAvailablePaths(new TreePath(root)); - _allAvailablePaths = (TreePath[]) (_allAvailablePathsList.toArray(new TreePath[0])); - - printTreePathArray(preSelectedPaths, header); - if(preSelectedPaths != null) - { - setPreSelectedPathsAsSelected(getValidTreePaths(preSelectedPaths)); -// printTreePathArray(getAppropriateTreePaths(preSelectedPaths), header + "getAppPaths(): "); - } - - if(preExpandedPaths != null) - { - expandThesePaths(getValidTreePaths(preExpandedPaths)); - } - - tree.addMouseListener(this); - _selectionModel.addTreeSelectionListener(this); - - } - - private void printTreePathArray(TreePath[] treePathArray, String message) - { - if (message != null) - { - System.out.println(message); - } - - if (treePathArray != null) - { - for (TreePath treePath : treePathArray) - { - System.out.println(treePath); - } - } - - return; - } - - public void setRowToCriticalColorMap(Map rowToCriticalColorMap) - { - MonitorCheckTreeCellRenderer renderer = (MonitorCheckTreeCellRenderer) _tree.getCellRenderer(); - renderer.setRowToCriticalColorMap(rowToCriticalColorMap); - } - - public TreePath[] getAllAvailablePaths() - { - return _allAvailablePaths; - } - - public void setPreSelectedPathsAsSelected(TreePath[] preSelectedPathArray) - { - String header = "MonitorCheckTreeManager.setPreSelectedPathsAsSelected(): "; - - //This is to prevent a whole bunch of defunct selectionModels from acting as listeners, - _selectionModel.removeTreeSelectionListener(this); - - for(int i=0 ; i < preSelectedPathArray.length; i++) - { - selectAPath(preSelectedPathArray[i]); - } - - _selectionModel.addTreeSelectionListener(this); - _tree.treeDidChange(); - } - -//------------------------------------------------------------------------------------------------- - - public TreePath[] getValidTreePaths(TreePath desiredPathArray[]) - { - String header = "MonitorCheckTreeManager.getAppropriateTreePaths(): "; - - if (desiredPathArray == null) - return null; - - TreePath pathsToReturn[] = null; - Set pathsToReturnSet = new HashSet(); - - // if the desiredPath is [HSA] then return all valid paths - if(desiredPathArray.length == 1 && desiredPathArray[0].toString().equals("[HSA]")) - { - for(int i=0 ; i< _allAvailablePathsList.size(); i++) - { - TreePath path = (TreePath) _allAvailablePathsList.get(i); - pathsToReturnSet.add(path); - } - } - else - { - //Create a set to search - Set desiredPathStringSet = new HashSet(); - for (TreePath desiredPath : desiredPathArray) - { - desiredPathStringSet.add(desiredPath.toString()); - } - - //check each path - for(int i=0 ; i< _allAvailablePathsList.size(); i++) - { - TreePath path = (TreePath) _allAvailablePathsList.get(i); - if ( withinTreeSet(path, desiredPathStringSet) ) - { - pathsToReturnSet.add(path); - } - } - } - - pathsToReturn = (TreePath[]) pathsToReturnSet.toArray(new TreePath[0]); - - // printTreePathArray(pathsToReturn, header); - - return pathsToReturn; - } - -// ------------------------------------------------------------------------------------------------- - - private void removeSelectedPaths() - { - _selectionModel.removeTreeSelectionListener(this); - - TreePath paths[] = _selectionModel.getSelectionPaths(); - if(paths != null) - { - for(int i=0; i < paths.length; i++) - { - - try - { - _selectionModel.removeSelectionPath(paths[i]); - } - finally - { - - _tree.treeDidChange(); - } - } - } - - _selectionModel.addTreeSelectionListener(this); - } - - private void selectAPath(TreePath path) - { - boolean selected = _selectionModel.isPathSelected(path, true); - - //TODO - What does the following line do? - //This was to prevent a whole bunch of defunct selectionModels from acting as listeners, - //although, it seems like overkill to be called that many times. - // _selectionModel.removeTreeSelectionListener(this); - try - { - if(!selected) - { - _selectionModel.addSelectionPath(path); - } - } - finally - { - - } - - } - - public void mouseClicked(MouseEvent me) - { - TreePath path = _tree.getPathForLocation(me.getX(), me.getY()); - if(path==null) - return; - if(me.getX()>_tree.getPathBounds(path).x+_hotspot) - return; - - boolean selected = _selectionModel.isPathSelected(path, true); - _selectionModel.removeTreeSelectionListener(this); - try - { - if(selected) - _selectionModel.removeSelectionPath(path); - else - _selectionModel.addSelectionPath(path); - } - finally - { - _selectionModel.addTreeSelectionListener(this); - _tree.treeDidChange(); - } - } - - public MonitorCheckTreeSelectionModel getSelectionModel() - { - return _selectionModel; - } - - public void valueChanged(TreeSelectionEvent e) - { - // Auto-generated method stub - } - - - private void determineAllAvailablePaths(TreePath parent) - { - // Traverse children - TreeNode node = (TreeNode) parent.getLastPathComponent(); - if (node.getChildCount() >= 0) - { - for (Enumeration e = node.children(); e.hasMoreElements();) - { - TreeNode n = (TreeNode) e.nextElement(); - - TreePath path = parent.pathByAddingChild(n); - determineAllAvailablePaths(path); - - if(_allAvailablePathsList != null) - { - _allAvailablePathsList.add(path); - _allAvailablePathsMap.put(path.toString(), path); - } - } - } - - } - - private boolean withinTreeSet(TreePath path, Set treePathStringSet) - { - boolean result = false; - - result = treePathStringSet.contains(path.toString()); - - return result; - } - - - private boolean withinTree(TreePath path, TreePath[] pathArray) - { - boolean result = false; - - Set set = new HashSet(); - - for (TreePath pathFromArray: pathArray) - { - set.add(pathFromArray.toString()); - } - - result = set.contains(path.toString()); - - return result; - } - - public void collapseEntireTree() - { - for(int i = 0; i < _allAvailablePathsList.size(); i++) - { - TreePath treePath = (TreePath) _allAvailablePathsList.get(i); - - Object[] pathArray = treePath.getPath(); - if (pathArray.length == 2) //just collapse the 2nd level. Collapsing this level collapses the rest. - { - _tree.collapsePath(treePath); - } - - } - } - - public void expandThesePaths(TreePath[] paths) - { String header = "MonitorCheckTreeManager.expandThesePaths(): "; - try - { - for(int i=0; i< paths.length ; i++) - { - _tree.expandPath(paths[i]); - } - - } - catch(Exception e) - { - System.out.println("Exception :"+e); - } - finally - { - } - - - } - - public TreePath[] getAllExpandedPaths() - { - TreePath[] allExpandedPaths = null; - List allExpandedPathList = new ArrayList(); - - for(int i=0; i < _allAvailablePaths.length; i++) - { - TreePath path = _allAvailablePaths[i]; - if(_tree.isExpanded(path)) - { - allExpandedPathList.add(path); - - } - else - continue; - } - - allExpandedPaths = (TreePath[]) allExpandedPathList.toArray(new TreePath[0]); - - return allExpandedPaths; - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeSelectionModel.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeSelectionModel.java deleted file mode 100644 index d20e95db4e..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/monitor/treefilter/MonitorCheckTreeSelectionModel.java +++ /dev/null @@ -1,206 +0,0 @@ -package ohd.hseb.monitor.treefilter; - -import java.util.ArrayList; -import java.util.Stack; - -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -public class MonitorCheckTreeSelectionModel extends DefaultTreeSelectionModel -{ - private static int _instanceCount = 0; - private int _instanceId = 0; - private TreeModel model; - - public MonitorCheckTreeSelectionModel(TreeModel model) - { - this.model = model; - setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - _instanceCount ++; - _instanceId = _instanceCount; - System.out.println("MonitorCheckTreeSelectionModel(): _instanceId = " + _instanceId); - } - - public TreePath[] getSelectionPaths() - { - // printInstanceId(); - - return super.getSelectionPaths(); - } - - public void printInstanceId() - { - System.out.println("MonitorCheckTreeSelectionModel.getSelectionPaths(): instanceId = " + _instanceId + "/" + _instanceCount); - } - - // tests whether there is any unselected node in the subtree of given path - public boolean isPartiallySelected(TreePath path) - { - if(isPathSelected(path, true)) - return false; - TreePath[] selectionPaths = getSelectionPaths(); - if(selectionPaths==null) - return false; - for(int j = 0; j getOfficeNotesColumnsList(List officeNotesColumnDescriptorList) - { - if( officeNotesColumnDescriptorList == null) - { - officeNotesColumnDescriptorList = new ArrayList(); - } - - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(TOPIC, true, 75, "center")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(ID, true, 75, "center")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(POSTING_TIME, true, 145, "center")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(NOTE, true, 640, "left")); - officeNotesColumnDescriptorList.add(new JTableColumnDescriptor(EXPIRE_TIME, true, 145, "center")); - - return officeNotesColumnDescriptorList; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesDataManager.java deleted file mode 100644 index 5148b69b14..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesDataManager.java +++ /dev/null @@ -1,125 +0,0 @@ -package ohd.hseb.officenotes; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.OfficeNotesRecord; -import ohd.hseb.ihfsdb.generated.OfficeNotesTable; -import ohd.hseb.util.SessionLogger; - -public class OfficeNotesDataManager -{ - private Database _db = null; - private SessionLogger _logger = null; - private String _missingRepresentation; - - public OfficeNotesDataManager(Database dbHandler, SessionLogger logger, String missingRepresentation) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public int delete(OfficeNotesRecord rec) - { - int ret = -1; - OfficeNotesTable officeNotesTable = new OfficeNotesTable(_db); - try - { - ret = officeNotesTable.delete(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public int updateOrInsert(OfficeNotesRecord rec) - { - int ret = -1; - OfficeNotesTable officeNotesTable = new OfficeNotesTable(_db); - try - { - ret = officeNotesTable.insertOrUpdate(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public List readDataFromOfficeNotes() - { - List officeNotesInfoList = null; - List dataList = null; - - OfficeNotesTable officeNotesTable = new OfficeNotesTable(_db); - OfficeNotesRecord officeNotesRecord = null; - String whereClause = null; - String header = "OfficeNotesDataManager.readDataFromOfficeNotes(): "; - - try - { - whereClause = "order by topic, id, postingtime"; - officeNotesInfoList = officeNotesTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(officeNotesInfoList != null) - { - dataList = new ArrayList(); - for(int i=0;i < officeNotesInfoList.size(); i++) - { - officeNotesRecord = (OfficeNotesRecord) officeNotesInfoList.get(i); - OfficeNotesJTableRowData rowData = new OfficeNotesJTableRowData(_missingRepresentation); - rowData.setOfficeNotesRecord(officeNotesRecord); - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" Officeinfo list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - public int getCountOfOfficeNotes() - { - int numOfOfficeNotes = -1; - List notesList = readDataFromOfficeNotes(); - if(notesList != null) - { - numOfOfficeNotes = notesList.size(); - } - return numOfOfficeNotes; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesDialog.java deleted file mode 100644 index 8afdaada43..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesDialog.java +++ /dev/null @@ -1,658 +0,0 @@ -package ohd.hseb.officenotes; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.text.JTextComponent; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.OfficeNotesRecord; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class OfficeNotesDialog extends JDialog -{ - private List _officeNotesColumnDescriptorList = null; - private JTableManager _officeNotesTableManager = null; - private OfficeNotesDataManager _officeNotesDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private JFrame _mainFrame; - private String _id; - private Map _lidDescDetailsMap; - private String _definedIds[]; - private int _selectedRowIndex; - private boolean _isUpdateOrDeleteToBeDone = false; - - private JLabel _topicLabel; - private JTextField _topicField ; - private JLabel _idLabel; - private JLabel _nameLabel; - private JLabel _countyLabel; - private JLabel _stateLabel; - private JTextField _nameField; - private JTextField _countyField; - private JTextField _stateField; - private JComboBox _idComboBox; - private JTextComponent _idComboBoxTextComponent; - private JLabel _noteLabel ; - private JTextArea _noteArea; - private JLabel _dataTimeLabel ; - private JTextField _dataTimeField; - private JLabel _postingTimeLabel ; - private JTextField _postingTimeField ; - private JLabel _updateTimeLabel ; - private JTextField _updateTimeField ; - private JLabel _expireTimeLabel; - private JTextField _expireTimeField ; - private JButton _updateButton; - private JButton _deleteButton ; - private JButton _closeButton ; - private String _missingRepresentation; - - private boolean _infoDialogShown = false; - private boolean _displayingSelectedRowData = false; - private SessionLogger _logger = null; - - private OfficeNotesJTableRowData _selectedRowData; - private TextFieldInputVerifier _textFieldInputVerifier = new TextFieldInputVerifier(); - - private int _previousRowToHighlight = -1; - - public OfficeNotesDialog(JFrame mainFrame, OfficeNotesDataManager officeNotesDataMgr, String topic, String[] ids, Map lidDescDetailsMap, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - _mainFrame = mainFrame; - _lidDescDetailsMap = lidDescDetailsMap; - _definedIds = ids; - this.setTitle("OfficeNotes"); - this.getContentPane().setLayout(new GridBagLayout()); - _officeNotesDataMgr = officeNotesDataMgr; - initialize(officeNotesDataMgr, topic, ids); - Dimension min = new Dimension(1100,570); - new WindowResizingManager(this, min, min); - this.pack(); - this.setLocation(25, 25); - } - - public void showOfficeNotesDialog(String id) - { - if(id != null) - { - _idComboBox.setSelectedItem(id); - _officeNotesTableManager.deselectRows(_previousRowToHighlight, _previousRowToHighlight); - int rowToHighLight = _officeNotesTableManager.getTheRowIndexToHighLightBasedOnValue(id); - if(rowToHighLight != -1) - { - _officeNotesTableManager.selectRows(rowToHighLight, rowToHighLight); - _previousRowToHighlight = rowToHighLight; - } - } - this.setVisible(true); - } - - private void initialize(OfficeNotesDataManager officeNotesDataMgr, String topic, String[] ids) - { - _officeNotesColumnDescriptorList = new OfficeNotesColumns().getOfficeNotesColumnsList(_officeNotesColumnDescriptorList); - _allRowDataList = officeNotesDataMgr.readDataFromOfficeNotes(); - _officeNotesTableManager = new ComplexJTableManager(_officeNotesColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _officeNotesTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _officeNotesTableManager.setDisplayableColumns(columnsSelected, true, true); - _officeNotesTableManager.setPreferredSizeForJScrollPane(new Dimension(1080, 300)); - _officeNotesTableManager.setVerifyInputWhenFocusTarget(false); - OfficeNotesTableMouseListener tableMouseListener = new OfficeNotesTableMouseListener(); - _officeNotesTableManager.addTableListener(tableMouseListener); - _tableScrollPane = _officeNotesTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(1090,310)); - - _topicLabel = new JLabel("Topic"); - _topicField = new JTextField(25); - _topicField.setInputVerifier(_textFieldInputVerifier); - if(topic != null) - { - _topicField.setText(topic); - } - - _idLabel = new JLabel("Id"); - _idLabel.setMaximumSize(_topicLabel.getPreferredSize()); - if(ids == null) - { - _idComboBox = new JComboBox(); - } - else - { - _idComboBox = new JComboBox(ids); - } - _idComboBoxTextComponent = (JTextComponent) _idComboBox.getEditor().getEditorComponent(); - _idComboBoxTextComponent.setInputVerifier(_textFieldInputVerifier); - _idComboBox.setEditable(true); - - _nameLabel = new JLabel(" Name"); - _countyLabel = new JLabel(" County"); - _stateLabel = new JLabel(" State"); - _nameField = new JTextField(); - _countyField = new JTextField(); - _stateField = new JTextField(); - _nameField.setEditable(false); - _countyField.setEditable(false); - _stateField.setEditable(false); - - _noteLabel = new JLabel("Note"); - _noteArea = new JTextArea(); - _noteArea.setLineWrap(true); - JScrollPane textPane = new JScrollPane(_noteArea); - - _dataTimeLabel = new JLabel("Data Time"); - _dataTimeField = new DateTimeTextField(System.currentTimeMillis(), _mainFrame, "Data Time", 20); - _dataTimeField.setInputVerifier(_textFieldInputVerifier); - - _postingTimeLabel = new JLabel("Posting Time"); - _postingTimeField = new JTextField(); - _postingTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _postingTimeField.setEditable(false); - - _updateTimeLabel = new JLabel("Update Time"); - _updateTimeField = new JTextField(); - _updateTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _updateTimeField.setEditable(false); - - _expireTimeLabel = new JLabel("Expire Time"); - _expireTimeField = new DateTimeTextField(System.currentTimeMillis(), _mainFrame, "Expire Time", 20); - _expireTimeField.setPreferredSize(new Dimension(100,30)); - _expireTimeField.setInputVerifier(_textFieldInputVerifier); - - JPanel idPanel = new JPanel(); - idPanel.setLayout(new GridLayout(1,2)); - idPanel.add(_idLabel); - idPanel.add(_idComboBox); - - JPanel nameLabelPanel = new JPanel(); - nameLabelPanel.setLayout(new GridLayout(1,1)); - nameLabelPanel.add(_nameLabel); - - JPanel nameFieldPanel = new JPanel(); - nameFieldPanel.setLayout(new GridLayout(1,1)); - nameFieldPanel.add(_nameField); - - JPanel countyPanel = new JPanel(); - countyPanel.setLayout(new GridLayout(1,2)); - countyPanel.add(_countyLabel); - countyPanel.add(_countyField); - - JPanel statePanel = new JPanel(); - statePanel.setLayout(new GridLayout(1,2)); - statePanel.add(_stateLabel); - statePanel.add(_stateField); - - JPanel idInfoCountyInfoStateInfoPanel = new JPanel(); - idInfoCountyInfoStateInfoPanel.setLayout(new GridLayout(1,3)); - idInfoCountyInfoStateInfoPanel.add(idPanel); - idInfoCountyInfoStateInfoPanel.add(countyPanel); - idInfoCountyInfoStateInfoPanel.add(statePanel); - - JPanel topicPanel = new JPanel(); - topicPanel.setLayout(new GridLayout(1,3)); - topicPanel.add(_topicLabel); - topicPanel.add(_topicField); - topicPanel.add(_nameLabel); - - JPanel topicNamePanel = new JPanel(); - topicNamePanel.setLayout(new GridLayout(1,2)); - topicNamePanel.add(topicPanel); - topicNamePanel.add(nameFieldPanel); - - JPanel noteLabelPanel = new JPanel(); - noteLabelPanel.setLayout(new GridLayout(1,1)); - noteLabelPanel.add(_noteLabel); - - JPanel topicInfoIdInfoNoteLabelPanel = new JPanel(); - topicInfoIdInfoNoteLabelPanel.setLayout(new GridLayout(3,1)); - topicInfoIdInfoNoteLabelPanel.add(topicNamePanel); - topicInfoIdInfoNoteLabelPanel.add(idInfoCountyInfoStateInfoPanel); - topicInfoIdInfoNoteLabelPanel.add(noteLabelPanel); - - JPanel noteFieldPanel = new JPanel(); - noteFieldPanel.setLayout(new GridLayout(1,1)); - noteFieldPanel.add(textPane); - - JPanel topicIdNotePanel = new JPanel(); - topicIdNotePanel.setLayout(new GridLayout(2,1)); - topicIdNotePanel.add(topicInfoIdInfoNoteLabelPanel); - topicIdNotePanel.add(noteFieldPanel); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(1,1)); - infoPanel.add(topicIdNotePanel); - - JPanel timePanel = new JPanel(); - timePanel.setLayout(new GridLayout(4,3)); - timePanel.add(createDummyPanel()); - timePanel.add(_dataTimeLabel); - _dataTimeField.setColumns(20); - timePanel.add(_dataTimeField); - timePanel.add(createDummyPanel()); - timePanel.add(_expireTimeLabel); - _expireTimeField.setColumns(20); - timePanel.add(_expireTimeField); - - timePanel.add(createDummyPanel()); - timePanel.add(_postingTimeLabel); - _postingTimeField.setColumns(20); - timePanel.add(_postingTimeField); - timePanel.add(createDummyPanel()); - timePanel.add(_updateTimeLabel); - _updateTimeField.setColumns(20); - timePanel.add(_updateTimeField); - - JPanel actionPanel = new JPanel(); - actionPanel = new JPanel(); - _updateButton = new JButton("Save"); - _deleteButton = new JButton("Delete"); - _closeButton = new JButton("Close"); - _closeButton.setVerifyInputWhenFocusTarget(false); - actionPanel.add(_updateButton); - actionPanel.add(_deleteButton); - actionPanel.add(_closeButton); - - JPanel editPanel = new JPanel(); - editPanel.setLayout(new GridLayout(1,2)); - editPanel.setBorder(BorderFactory.createTitledBorder("Details")); - - editPanel.add(infoPanel); - editPanel.add(timePanel); - - Container contentPane = this.getContentPane(); - ComponentHelper.addFrameComponent(contentPane, tableScrollPanePanel, 0, 0,1,1,1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, editPanel, 0, 1,1,1, 1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, actionPanel, 0, 2,1,1, 1, 1, 0); - - IdListener idListener = new IdListener(); - _idComboBox.addActionListener(idListener); - - UpdateListener updateListener = new UpdateListener(); - _updateButton.addActionListener(updateListener); - - DeleteListener deleteListener = new DeleteListener(); - _deleteButton.addActionListener(deleteListener); - - CloseListener closeListener = new CloseListener(); - _closeButton.addActionListener(closeListener); - - _idComboBox.setSelectedIndex(0); - } - - private JPanel createDummyPanel() - { - JPanel dummyPanel = new JPanel(); - return dummyPanel; - } - - private void closeOfficeNotesDialog() - { - this.setVisible(false); - } - - private void showCurrentRowData(String id) - { - if(_selectedRowData != null) - { - _displayingSelectedRowData = true; - _topicField.setText(_selectedRowData.getTopic()); - _idComboBox.setSelectedItem(_selectedRowData.getId()); - _noteArea.setText(_selectedRowData.getNote()); - - String timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getPostingTime()); - _postingTimeField.setText(timeStr); - - if(! _selectedRowData.getDataValue(OfficeNotesColumns.UPDATE_TIME).equals(_missingRepresentation)) - { - timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getUpdateTime()); - _updateTimeField.setText(timeStr); - } - else - _updateTimeField.setText("yyyy-mm-dd hh:mm:ss"); - - if(! _selectedRowData.getDataValue(OfficeNotesColumns.DATA_TIME).equals(_missingRepresentation)) - { - timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getDataTime()); - _dataTimeField.setText(timeStr); - } - else - _dataTimeField.setText("yyyy-mm-dd hh:mm:ss"); - - if(!_selectedRowData.getDataValue(OfficeNotesColumns.EXPIRE_TIME).equals(_missingRepresentation)) - { - timeStr = DbTimeHelper.getDateTimeStringFromLongTime(_selectedRowData.getExpireTime()); - _expireTimeField.setText(timeStr); - } - else - _expireTimeField.setText("yyyy-mm-dd hh:mm:ss"); - _displayingSelectedRowData = false; - } - else if(id == null) - { - String str=""; - _topicField.setText(str); - _idComboBox.setSelectedItem(_idComboBox.getSelectedItem().toString()); - _noteArea.setText(str); - _postingTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _updateTimeField.setText(_postingTimeField.getText()); - _dataTimeField.setText("yyyy-mm-dd hh:mm:ss"); - _expireTimeField.setText("yyyy-mm-dd hh:mm:ss"); - } - else // id is not null - { - _topicField.setText(_topicField.getText()); - _idComboBox.setSelectedItem(id); - _noteArea.setText(_noteArea.getText()); - _postingTimeField.setText(_postingTimeField.getText()); - _updateTimeField.setText(_updateTimeField.getText()); - _dataTimeField.setText(_dataTimeField.getText()); - _expireTimeField.setText(_expireTimeField.getText()); - } - } - - private OfficeNotesJTableRowData getMatchingRecordIfIdExistsInTable(String id) - { - OfficeNotesJTableRowData rowData = null; - for(int i=0; i < _allRowDataList.size(); i++) - { - OfficeNotesJTableRowData tempRec = (OfficeNotesJTableRowData) _allRowDataList.get(i); - if(tempRec.getId().equals(id)) - { - rowData = tempRec; - break; - } - } - return rowData; - } - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeOfficeNotesDialog(); - } - } - - private OfficeNotesRecord getOfficeNotesRecord() - { - OfficeNotesRecord record = new OfficeNotesRecord(); - if(!(_topicField.getInputVerifier().verify(_topicField))) - { - JOptionPane.showMessageDialog(null, "Topic length must be >=1 and <= 8","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setTopic(_topicField.getText()); - } - - if(!(_idComboBoxTextComponent.getInputVerifier().verify(_idComboBoxTextComponent))) - { - JOptionPane.showMessageDialog(null, "Id length must be >=1 and <= 8","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setId(_idComboBox.getSelectedItem().toString()); - } - - if(!(_dataTimeField.getInputVerifier().verify(_dataTimeField))) - { - JOptionPane.showMessageDialog(null, "Enter valid data time","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setDatatime(DbTimeHelper.getLongTimeFromDateTimeString(_dataTimeField.getText())); - } - if(!(_expireTimeField.getInputVerifier().verify(_expireTimeField))) - { - JOptionPane.showMessageDialog(null, "Enter valid expire time","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - long dataTime = DbTimeHelper.getLongTimeFromDateTimeString(_dataTimeField.getText()); - long expireTime = DbTimeHelper.getLongTimeFromDateTimeString(_expireTimeField.getText()); - if(dataTime > expireTime) - { - JOptionPane.showMessageDialog(null, "Expire Time should be Greater than Data Time","OfficeNotes Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setExpiretime(DbTimeHelper.getLongTimeFromDateTimeString(_expireTimeField.getText())); - _infoDialogShown = false; - } - } - record.setPostingtime(DbTimeHelper.getLongTimeFromDateTimeString(_postingTimeField.getText())); - record.setUpdatetime(DbTimeHelper.getLongTimeFromDateTimeString(_updateTimeField.getText())); - String note = _noteArea.getText(); - if(note.length() > 510) - note = note.substring(0, 510); - record.setNote(note); - return record; - } - - private class TextFieldInputVerifier extends InputVerifier - { - public boolean verify(JComponent component) - { - boolean returnValue = true; - - if(!_isUpdateOrDeleteToBeDone) - return returnValue; - - JTextField textField = (JTextField)component; - if(component == _topicField) - { - String topic= textField.getText(); - if(topic != null) - { - if(topic.length() == 0) - returnValue = false; - else if(topic.length() > 8) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _idComboBoxTextComponent) - { - String id= textField.getText(); - if(id != null) - { - if(id.length() == 0) - returnValue = false; - else if(id.length() > 8) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _dataTimeField) - { - String dataTime = textField.getText(); - if(dataTime != null) - { - if(_dataTimeField.getText().equals("yyyy-mm-dd hh:mm:ss")) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _expireTimeField) - { - String expireTime = textField.getText(); - if(expireTime != null) - { - if(_expireTimeField.getText().equals("yyyy-mm-dd hh:mm:ss")) - returnValue = false; - } - else - returnValue = false; - } - return returnValue; - } - } - - private void getCurrentDataFromDataMgr() - { - List dbInfoList = null; - String header = "OfficeNotesDialog.getCurrentDataFromDataMgr() "; - try - { - dbInfoList = _officeNotesDataMgr.readDataFromOfficeNotes(); - } - catch(Exception e) - { - _logger.log(header+ e); - } - _allRowDataList = dbInfoList; - _officeNotesTableManager.setChangedAllRowDataList(_allRowDataList); - } - - class IdListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _id = _idComboBox.getSelectedItem().toString(); - boolean isDefinedId = false; - for(int i=0; i < _definedIds.length; i++) - { - if(_definedIds[i].equals(_id)) - { - isDefinedId = true; - break; - } - } - if(isDefinedId) - { - String desc = (String)_lidDescDetailsMap.get(_id); - if(desc != null) - { - String splitStr[] = desc.split(";"); - _nameField.setText(splitStr[0]); - _countyField.setText(splitStr[2]); - _stateField.setText(splitStr[1]); - } - } - else - { - _nameField.setText(""); - _countyField.setText(""); - _stateField.setText(""); - } - - if(!_displayingSelectedRowData) - { - _selectedRowData = null; - showCurrentRowData(_id); - } - } - } - - class DeleteListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _isUpdateOrDeleteToBeDone = true; - String header = "OfficeNotesDialog.DeleteListener.actionPerformed(): "; - OfficeNotesRecord record = getOfficeNotesRecord(); - if(!_infoDialogShown) - { - _logger.log(header+" Delete record"+ record.toString()); - _officeNotesDataMgr.delete(record); - getCurrentDataFromDataMgr(); - _officeNotesTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(_idComboBox.getSelectedItem().toString()); - } - _isUpdateOrDeleteToBeDone = false; - - } - } - - class UpdateListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - _isUpdateOrDeleteToBeDone = true; - String header = "OfficeNotesDialog.UpdateListener.actionPerformed(): "; - if(getMatchingRecordIfIdExistsInTable(_idComboBox.getSelectedItem().toString()) == null) - { - _postingTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - _updateTimeField.setText(_postingTimeField.getText()); - } - else - { - _updateTimeField.setText(DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis())); - } - OfficeNotesRecord record = getOfficeNotesRecord(); - if(!_infoDialogShown) - { - _logger.log(header+" Update record"+ record.toString()); - _officeNotesDataMgr.updateOrInsert(record); - getCurrentDataFromDataMgr(); - _officeNotesTableManager.refreshDisplay(); - int rowToHighLight = _officeNotesTableManager.getTheRowIndexToHighLightBasedOnValue(_idComboBox.getSelectedItem().toString()); - _officeNotesTableManager.selectRows(rowToHighLight, rowToHighLight); - } - _isUpdateOrDeleteToBeDone = false; - } - - } - - class OfficeNotesTableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - _selectedRowIndex = _officeNotesTableManager.getMousePointedRowIndex(p); - _selectedRowData = (OfficeNotesJTableRowData) _officeNotesTableManager.getSelectedRowData(_selectedRowIndex); - showCurrentRowData(null); - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesJTableRowData.java deleted file mode 100644 index 6ed756c2a4..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/officenotes/OfficeNotesJTableRowData.java +++ /dev/null @@ -1,112 +0,0 @@ -package ohd.hseb.officenotes; - -import ohd.hseb.ihfsdb.generated.OfficeNotesRecord; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class OfficeNotesJTableRowData extends AbstractJTableRowData -{ - private String _topic; - private String _id; - private long _dataTime; - private long _postingTime; - private long _updateTime; - private long _expireTime; - private String _note; - - public OfficeNotesJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getTopic() - { - return _topic; - } - public void setTopic(String topic) - { - _topic = topic; - } - public long getDataTime() - { - return _dataTime; - } - public void setDataTime(long dataTime) - { - _dataTime = dataTime; - } - public long getExpireTime() - { - return _expireTime; - } - public void setExpireTime(long expireTime) - { - _expireTime = expireTime; - } - public String getId() - { - return _id; - } - public void setId(String id) - { - _id = id; - } - public String getNote() - { - return _note; - } - public void setNote(String note) - { - _note = note; - } - public long getPostingTime() - { - return _postingTime; - } - public void setPostingTime(long postingTime) - { - _postingTime = postingTime; - } - public long getUpdateTime() - { - return _updateTime; - } - public void setUpdateTime(long time) - { - _updateTime = time; - } - - public void setOfficeNotesRecord(OfficeNotesRecord officeNotesRecord) - { - setTopic(officeNotesRecord.getTopic()); - setId(officeNotesRecord.getId()); - setDataTime(officeNotesRecord.getDatatime()); - setPostingTime(officeNotesRecord.getPostingtime()); - setUpdateTime(officeNotesRecord.getUpdatetime()); - setExpireTime(officeNotesRecord.getExpiretime()); - setNote(officeNotesRecord.getNote()); - } - - public void addAllCellsToMap() - { - addToCellMap(OfficeNotesColumns.TOPIC, CellType.STRING, getTopic() ); - addToCellMap(OfficeNotesColumns.ID, CellType.STRING, getId() ); - addToCellMap(OfficeNotesColumns.NOTE, CellType.STRING, getNote()); - addToCellMap(OfficeNotesColumns.DATA_TIME, CellType.DATE_TIME, getDataTime()); - addToCellMap(OfficeNotesColumns.UPDATE_TIME, CellType.DATE_TIME, getUpdateTime()); - addToCellMap(OfficeNotesColumns.POSTING_TIME, CellType.DATE_TIME, getPostingTime()); - addToCellMap(OfficeNotesColumns.EXPIRE_TIME, CellType.DATE_TIME, getExpireTime()); - } - - // ----------------------------------------------------------------------------------- - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation(), "MM/dd - HH:mm"); - addCell(cell); - - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupColumns.java deleted file mode 100644 index 29e46fb97d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupColumns.java +++ /dev/null @@ -1,41 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class RiverMonGroupColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String GROUP_NAME = "Group Name"; - public static final String GROUP_ORDINAL = "Group Ordinal"; - public static final String HSA = "HSA"; - - /** - * Creates a list of rivermon group columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the rivermon group columns are added to it, - * if not the location info columns are added to the list that is passed as argument. - * The created new list is returned. - * @param riverMonGroupColumnDescriptorList - * @return - */ - public List getRiverMonGroupColumnsList(List riverMonGroupColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if( riverMonGroupColumnDescriptorList == null) - { - riverMonGroupColumnDescriptorList = new ArrayList(); - } - - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ID, true, 95, textAlignment)); - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_NAME, true, 335, textAlignment)); - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ORDINAL, true, 85, numberAlignment)); - riverMonGroupColumnDescriptorList.add(new JTableColumnDescriptor(HSA, true, 75, textAlignment)); - - return riverMonGroupColumnDescriptorList; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupDialog.java deleted file mode 100644 index 4e1241695a..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupDialog.java +++ /dev/null @@ -1,439 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.RiverMonGroupRecord; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.FrameCloseWindowListener; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RiverMonGroupDialog extends JDialog -{ - private List _riverMonGroupColumnDescriptorList = null; - private JTableManager _riverMonGroupTableManager = null; - private RiverMonLocGroupDataManager _riverMonLocGroupDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private int _selectedRowIndex; - private boolean _riverMonGroupTableChanged = false; - private String _defaultHsa = null; - - private JLabel _groupIdLabel; - private JTextField _groupIdField ; - private JLabel _groupNameLabel; - private JTextField _groupNameField ; - private JLabel _groupOrdinalLabel; - private JTextField _groupOrdinalField ; - private JLabel _hsaLabel; - private JTextField _hsaField; - private JButton _updateButton; - private JButton _deleteButton ; - private JButton _closeButton ; - - private boolean _infoDialogShown = false; - private SessionLogger _logger = null; - - private RiverMonGroupJTableRowData _selectedRowData; - private TextFieldInputVerifier _textFieldInputVerifier = new TextFieldInputVerifier(); - - public RiverMonGroupDialog(JFrame mainFrame, RiverMonLocGroupDataManager riverMonLocGroupDataMgr, SessionLogger logger, String defaultHsa) - { - super(mainFrame, true); - _logger = logger; - _defaultHsa = defaultHsa; - this.setTitle("RiverMonGroup"); - this.getContentPane().setLayout(new GridBagLayout()); - _riverMonLocGroupDataMgr = riverMonLocGroupDataMgr; - initialize(riverMonLocGroupDataMgr); - Dimension min = new Dimension(600,570); - Dimension max = new Dimension(700,570); - new WindowResizingManager(this, min, max); - this.pack(); - this.setLocation(25, 25); - } - - public boolean showRiverMonGroupDialog() - { - _riverMonGroupTableChanged = false; - _allRowDataList = _riverMonLocGroupDataMgr.readDataFromRiverMonGroup(); - _riverMonGroupTableManager.setChangedAllRowDataList(_allRowDataList); - _riverMonGroupTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(); - this.setVisible(true); - return _riverMonGroupTableChanged; - } - - private void initialize(RiverMonLocGroupDataManager riverMonLocGroupDataMgr) - { - _riverMonGroupColumnDescriptorList = new RiverMonGroupColumns().getRiverMonGroupColumnsList(_riverMonGroupColumnDescriptorList); - - _allRowDataList = riverMonLocGroupDataMgr.readDataFromRiverMonGroup(); - System.out.println("All row data list:"+ _allRowDataList.size()); - System.out.println("Column list:"+ _riverMonGroupColumnDescriptorList.size()); - - _riverMonGroupTableManager = new ComplexJTableManager(_riverMonGroupColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _riverMonGroupTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _riverMonGroupTableManager.setDisplayableColumns(columnsSelected, true, true); - _riverMonGroupTableManager.setPreferredSizeForJScrollPane(new Dimension(590, 300)); - _riverMonGroupTableManager.setVerifyInputWhenFocusTarget(false); - RiverMonitorGroupTableMouseListener tableMouseListener = new RiverMonitorGroupTableMouseListener(); - _riverMonGroupTableManager.addTableListener(tableMouseListener); - _tableScrollPane = _riverMonGroupTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(600,310)); - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - tablePanel.setMinimumSize(new Dimension(600,310)); - - _groupIdLabel = new JLabel("Group Id"); - _groupIdField = new JTextField(); - _groupIdField.setInputVerifier(_textFieldInputVerifier); - - _groupNameLabel = new JLabel("Group Name"); - _groupNameField = new JTextField(); - _groupNameField.setInputVerifier(_textFieldInputVerifier); - - _groupOrdinalLabel = new JLabel("Group Ordinal"); - _groupOrdinalField = new JTextField(); - _groupOrdinalField.setInputVerifier(_textFieldInputVerifier); - - _hsaLabel = new JLabel("HSA"); - _hsaField = new JTextField(); - _hsaField.setEditable(false); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(4,4)); - JPanel dummyPanel1 = createDummyPanel(); - infoPanel.add(dummyPanel1); - infoPanel.add(_groupIdLabel); - infoPanel.add(_groupIdField); - JPanel dummyPanel2 = createDummyPanel(); - infoPanel.add(dummyPanel2); - - JPanel dummyPanel3 = createDummyPanel(); - infoPanel.add(dummyPanel3); - infoPanel.add(_groupNameLabel); - infoPanel.add(_groupNameField); - JPanel dummyPanel4 = createDummyPanel(); - infoPanel.add(dummyPanel4); - - JPanel dummyPanel5 = createDummyPanel(); - infoPanel.add(dummyPanel5); - infoPanel.add(_groupOrdinalLabel); - infoPanel.add(_groupOrdinalField); - JPanel dummyPanel6 = createDummyPanel(); - infoPanel.add(dummyPanel6); - - JPanel dummyPanel7 = createDummyPanel(); - infoPanel.add(dummyPanel7); - infoPanel.add(_hsaLabel); - infoPanel.add(_hsaField); - JPanel dummyPanel8 = createDummyPanel(); - infoPanel.add(dummyPanel8); - - JPanel actionPanel = new JPanel(); - actionPanel = new JPanel(); - _updateButton = new JButton("Save"); - _deleteButton = new JButton("Delete"); - _closeButton = new JButton("Close"); - _closeButton.setVerifyInputWhenFocusTarget(false); - actionPanel.add(_updateButton); - actionPanel.add(_deleteButton); - actionPanel.add(_closeButton); - - JPanel editPanel = new JPanel(); - editPanel.setLayout(new GridLayout(1,2)); - editPanel.setBorder(BorderFactory.createTitledBorder("Details")); - - editPanel.add(infoPanel); - - Container contentPane = this.getContentPane(); - ComponentHelper.addFrameComponent(contentPane, tablePanel, 0, 0,1,1,1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, editPanel, 0, 1,1,1, 1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, actionPanel, 0, 2,1,1, 1, 1, 0); - - UpdateListener updateListener = new UpdateListener(); - _updateButton.addActionListener(updateListener); - - DeleteListener deleteListener = new DeleteListener(); - _deleteButton.addActionListener(deleteListener); - - CloseListener closeListener = new CloseListener(); - _closeButton.addActionListener(closeListener); - - } - - private JPanel createDummyPanel() - { - JPanel dummyPanel = new JPanel(); - return dummyPanel; - } - - private void closeRiverMonGroupDialog() - { - this.setVisible(false); - } - - private void showCurrentRowData() - { - if(_selectedRowData != null) - { - _groupIdField.setText(_selectedRowData.getGroupId()); - _groupNameField.setText(_selectedRowData.getGroupName()); - _groupOrdinalField.setText(new Integer(_selectedRowData.getGroupOrdinal()).toString()); - _hsaField.setText(_selectedRowData.getHsa()); - _selectedRowData = null; - } - else - { - _groupIdField.setText(""); - _groupNameField.setText(""); - _groupOrdinalField.setText(""); - _hsaField.setText(""); - } - } - - private RiverMonGroupRecord getRiverMonGroupRecord() - { - RiverMonGroupRecord record = new RiverMonGroupRecord(); - if(!(_groupIdField.getInputVerifier().verify(_groupIdField))) - { - JOptionPane.showMessageDialog(null, "Group Id length must be >=1 and <= 8","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setGroup_id(_groupIdField.getText().toUpperCase()); - } - if(!(_groupNameField.getInputVerifier().verify(_groupNameField))) - { - JOptionPane.showMessageDialog(null, "Group Name length must be >=1 and <= 32","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setGroup_name(_groupNameField.getText()); - } - if(!(_groupOrdinalField.getInputVerifier().verify(_groupOrdinalField))) - { - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setOrdinal(Integer.parseInt(_groupOrdinalField.getText())); - } - if(_hsaField.getText().length() > 0) - { - record.setHsa(_hsaField.getText().toUpperCase()); - } - else - { - _hsaField.setText(_defaultHsa); - record.setHsa(_defaultHsa); - } - - return record; - } - - private void getCurrentDataFromDataMgr() - { - List dbInfoList = null; - String header = "RiverMonGroupDialog.getCurrentDataFromDataMgr() "; - try - { - dbInfoList = _riverMonLocGroupDataMgr.readDataFromRiverMonGroup(); - } - catch(Exception e) - { - _logger.log(header+ e); - } - _allRowDataList = dbInfoList; - _riverMonGroupTableManager.setChangedAllRowDataList(_allRowDataList); - } - - private class TextFieldInputVerifier extends InputVerifier - { - public boolean verify(JComponent component) - { - boolean returnValue = true; - JTextField textField = (JTextField)component; - if(component == _groupIdField) - { - String id= textField.getText(); - if(id != null) - { - if(id.length() == 0) - returnValue = false; - else if(id.length() > 8) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _groupNameField) - { - String name = textField.getText(); - if(name != null) - { - if(name.length() == 0) - returnValue = false; - else if(name.length() > 32) - returnValue = false; - } - else - returnValue = false; - } - else if(component == _groupOrdinalField) - { - try - { - Integer.parseInt(textField.getText()); - returnValue = true; - } - catch (NumberFormatException e) - { - returnValue = false; - } - } - if(!returnValue) - { - if(component ==_groupIdField) - JOptionPane.showMessageDialog(null, "Group Id length must be >=1 and <= 8","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - else if(component == _groupNameField) - JOptionPane.showMessageDialog(null, "Group Name length must be >=1 and <= 32","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - else if(component == _groupOrdinalField) - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - } - return returnValue; - } - } - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeRiverMonGroupDialog(); - } - } - - private class DeleteListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonitorGroupDialog.DeleteListener.actionPerformed(): "; - RiverMonGroupRecord record = getRiverMonGroupRecord(); - if(!_infoDialogShown) - { - _logger.log(header+" Delete record"+ record.toString()); - _riverMonLocGroupDataMgr.delete(record); - getCurrentDataFromDataMgr(); - _riverMonGroupTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(); - _riverMonGroupTableChanged = true; - } - } - } - - private class UpdateListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonGroupDialog.UpdateListener.actionPerformed(): "; - RiverMonGroupRecord record = getRiverMonGroupRecord(); - boolean recordExists = _riverMonLocGroupDataMgr.checkIfRecordExists(record); - if(!recordExists) - { - record.setHsa(_defaultHsa); - _hsaField.setText(_defaultHsa); - } - if(!_infoDialogShown) - { - _logger.log(header+" Update record"+ record.toString()); - _riverMonLocGroupDataMgr.updateOrInsert(record); - getCurrentDataFromDataMgr(); - _riverMonGroupTableManager.refreshDisplay(); - int rowToHighLight = _riverMonGroupTableManager.getTheRowIndexToHighLightBasedOnValue(_groupIdField.getText()); - _riverMonGroupTableManager.selectRows(rowToHighLight, rowToHighLight); - _riverMonGroupTableChanged = true; - } - } - } - - private class RiverMonitorGroupTableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - _selectedRowIndex = _riverMonGroupTableManager.getMousePointedRowIndex(p); - _selectedRowData = (RiverMonGroupJTableRowData) _riverMonGroupTableManager.getSelectedRowData(_selectedRowIndex); - showCurrentRowData(); - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - - public static void main(String[] args) - { - /* - * This main is for testing purposes - */ - - String jdbcUrl = args[0]; - String baseLogFilePath = args[1]; - String defaultHsa = args[2]; - - System.out.println("jdbcUrl = " + jdbcUrl ); - - Database database = new Database(jdbcUrl); - - String messageId = "M1"; - SessionLogger logger = new SessionLogger("RiverMonGroup", baseLogFilePath, true, true, messageId); - - RiverMonLocGroupDataManager dataMgr = new RiverMonLocGroupDataManager(database, logger, "", defaultHsa ); - - JFrame frame = new JFrame(); - - FrameCloseWindowListener.addFrameCloseWindowListener(frame); - - RiverMonGroupDialog dialog = new RiverMonGroupDialog(frame, dataMgr, logger, defaultHsa); - dialog.setVisible(true); - frame.setVisible(true); - - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupJTableRowData.java deleted file mode 100644 index e190c9c3dc..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonGroupJTableRowData.java +++ /dev/null @@ -1,90 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class RiverMonGroupJTableRowData extends AbstractJTableRowData -{ - private String _groupId; - private String _groupName; - private int _groupOrdinal; - private String _hsa; - - public RiverMonGroupJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - _groupId = groupId; - } - - public String getGroupName() - { - return _groupName; - } - - public void setGroupName(String groupName) - { - _groupName = groupName; - } - - public String getHsa() - { - return _hsa; - } - - public void setHsa(String hsa) - { - _hsa = hsa; - } - - public int getGroupOrdinal() - { - return _groupOrdinal; - } - - public void setGroupOrdinal(int groupOrdinal) - { - _groupOrdinal = groupOrdinal; - } - - public void addAllCellsToMap() - { - addToCellMap(RiverMonGroupColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(RiverMonGroupColumns.GROUP_NAME, CellType.STRING, getGroupName() ); - addToCellMap(RiverMonGroupColumns.GROUP_ORDINAL, CellType.INTEGER, getGroupOrdinal()); - addToCellMap(RiverMonGroupColumns.HSA, CellType.STRING, getHsa() ); - } - - // ----------------------------------------------------------------------------------- - - // ----------------------------------------------------------------------------------- - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation()); - addCell(cell); - - } - - /* private void addToCellMap(String columnName, CellType cellType, - Object value) - { - int decimalPointsForDisplay = 2; - MonitorCell cell = new MonitorCell (columnName, cellType, - value, ThreatLevel.NO_THREAT, - _missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - }*/ - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocGroupDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocGroupDataManager.java deleted file mode 100644 index 13ce54f79e..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocGroupDataManager.java +++ /dev/null @@ -1,1436 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.LocRiverMonRecord; -import ohd.hseb.ihfsdb.generated.LocRiverMonView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RiverMonGroupRecord; -import ohd.hseb.ihfsdb.generated.RiverMonGroupTable; -import ohd.hseb.ihfsdb.generated.RiverMonLocationRecord; -import ohd.hseb.ihfsdb.generated.RiverMonLocationTable; -import ohd.hseb.rivermonlocgroup.RiverMonLocationJTableRowData; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.jtable.JTableRowData; - -public class RiverMonLocGroupDataManager -{ - private Database _db ; - private SessionLogger _logger; - private String _missingRepresentation; - - private Map _lidToRiverMonLocationMap; - private Map> _groupIdToLocationIdListMap = new HashMap>(); - private List _locationInfoList; - private String _defaultHsa; - private Map _locationIdToOrdinalMap; - - private Map _groupIdToRiverMonGroupMap = null; - private List _groupInfoList = null; - - private Map _groupHsaMap = null; - - private Set _hsaInfoSet = null; - private Map _locationHsaMap = null; - - private List _locationsUnderDefaultGroupList = null; - private int _locationOrdinalForDefaultLocations = 1; - - private final String _defaultGroupId = "DEFAULT"; - - public RiverMonLocGroupDataManager(Database dbHandler, SessionLogger logger, - String missingRepresentation, String defaultHsa) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - _defaultHsa = defaultHsa; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","RiverMonLocation Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void initializeRiverMonTableData() - { - String header = "RiverMonLocGroupDataManager.initializeRiverMonTableData()"; - - initLocationHsaMap(); - initRiverMonGroupMap(); - initRiverMonLocationMap(); - initGroupHsaMap(); - - //any undefined default hsa-based groups will be created here - //any defined hsa-based groups groups will be overwritten in the following for loop - initAllDefaultGroupsToMap(); - - //updateRiverMonitorGroupWithAppropriateHsa(); - } - - public List createStringArrayListOfFilterItems( List locationIdList) - { - return createStringArrayListOfFilterItemsNew(locationIdList); - } - - public List createStringArrayListOfFilterItemsNew( List locationIdList) - { - //This version of createStringArrayListOfFilterItems() does not create empty groups and HSAs - String header = "RiverMonLocGroupDataManager.createStringArrayListOfFilterItems(): "; - List listOfStringArray = new ArrayList(); - - String rootItem = "HSA"; - String hsaArray[] = getAllHsa(); - String[] nodePathStringArray; - - buildGroupIdToLocationIdListMap(locationIdList); - LocationOrdinalComparator locationComparator = new LocationOrdinalComparator(); - - if(hsaArray != null && hsaArray.length > 0) - { - String hsa = null; - for(int i=0; i < hsaArray.length; i++) - { - hsa = hsaArray[i]; - String groupIdArray[] = getGroupsForHsa(hsaArray[i]); - if(groupIdArray != null && groupIdArray.length > 0) - { - String groupName = null; - for(int j=0; j < groupIdArray.length; j++) - { - groupName = getGroupName(groupIdArray[j]); - String locationId[] = getAllLocationsForGroup(groupIdArray[j], locationIdList, locationComparator); - if(locationId != null && locationId.length > 0) - { - for(int k=0; k < locationId.length; k++) - { - nodePathStringArray = new String[4]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - nodePathStringArray[2] = groupName; - nodePathStringArray[3] = locationId[k]; - listOfStringArray.add(nodePathStringArray); - } //for k - } - } //for j - } - } //for i - } - else //it is the root - { - System.out.println(header + rootItem + " might be an empty root"); - nodePathStringArray = new String[1]; - nodePathStringArray[0] = rootItem; - listOfStringArray.add(nodePathStringArray); - } - - System.out.println(header + "listOfStringArray.size() = " + listOfStringArray.size()); - - return listOfStringArray; - } - - public List createStringArrayListOfFilterItemsOld( List locationIdList) - { - String header = "RiverMonLocGroupDataManager.createStringArrayListOfFilterItemsOrig(): "; - List listOfStringArray = new ArrayList(); - - String rootItem = "HSA"; - String hsaArray[] = getAllHsa(); - String[] nodePathStringArray; - - buildGroupIdToLocationIdListMap(locationIdList); - LocationOrdinalComparator locationComparator = new LocationOrdinalComparator(); - - if(hsaArray != null && hsaArray.length > 0) - { - String hsa = null; - for(int i=0; i < hsaArray.length; i++) - { - hsa = hsaArray[i]; - String groupIdArray[] = getGroupsForHsa(hsaArray[i]); - if(groupIdArray != null && groupIdArray.length > 0) - { - String groupName = null; - for(int j=0; j < groupIdArray.length; j++) - { - groupName = getGroupName(groupIdArray[j]); - String locationId[] = getAllLocationsForGroup(groupIdArray[j], locationIdList, locationComparator); - if(locationId != null && locationId.length > 0) - { - for(int k=0; k < locationId.length; k++) - { - nodePathStringArray = new String[4]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - nodePathStringArray[2] = groupName; - nodePathStringArray[3] = locationId[k]; - listOfStringArray.add(nodePathStringArray); - } - } - else //it is a group - { - System.out.println(header + groupName + " might be an empty group"); - nodePathStringArray = new String[3]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - nodePathStringArray[2] = groupName; - listOfStringArray.add(nodePathStringArray); - } - } - } - else //it is an hsa - { - System.out.println(header + hsa + " might be an empty hsa"); - nodePathStringArray = new String[2]; - nodePathStringArray[0] = rootItem; - nodePathStringArray[1] = hsa; - listOfStringArray.add(nodePathStringArray); - } - } - } - else //it is the root - { - System.out.println(header + rootItem + " might be an root"); - nodePathStringArray = new String[1]; - nodePathStringArray[0] = rootItem; - listOfStringArray.add(nodePathStringArray); - } - - System.out.println(header + "listOfStringArray.size() = " + listOfStringArray.size()); - - return listOfStringArray; - } - - - - private String getDefaultHsa() - { - return _defaultHsa; - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public int delete(RiverMonLocationRecord rec) - { - int ret = -1; - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - try - { - ret = riverMonLocationTable.delete(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public int updateOrInsert(RiverMonLocationRecord rec) - { - int ret = -1; - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - try - { - ret = riverMonLocationTable.insertOrUpdate(rec); - updateOrdinalValuesInRiverMonLocation(rec.getLid(), rec.getGroup_id(), rec.getOrdinal()); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public void updateOrdinalValuesInRiverMonLocation(String locationId, String groupId, int locationOrdinal) - { - - RiverMonLocationTable table = new RiverMonLocationTable(_db); - List recordList = null; - - String where = "WHERE group_id = '" + groupId + "' ORDER BY ordinal ASC, lid ASC"; - - try - { - recordList = table.select(where); - - int ordinalValue = locationOrdinal + 1; - for (RiverMonLocationRecord oldRecord : recordList) - { - //if the location is not the same as that passed in as argument - if (! oldRecord.getLid().equalsIgnoreCase(locationId)) - { - //if the ordinal is equal or higher than that passed in - if (oldRecord.getOrdinal() >= locationOrdinal) - { - //alter and insert the rest of the records. - RiverMonLocationRecord newRecord = new RiverMonLocationRecord(oldRecord); - - newRecord.setOrdinal(ordinalValue); - - table.update(oldRecord, newRecord); - - ordinalValue++; - } - - } - - } - - } - catch (SQLException e) - { - e.printStackTrace(); - } - - } - - /** - * Read loc rivermon view location and precip location ( lids which report PC / PP data and have - * ingest filter on) - * @return - */ - public String[] getAllLid() - { - String header = "RiverMonLocationDataManager.getAllLid(): "; - List lidList = null; - String lid[] = null; - List locRiverMonRecordList = null; - LocRiverMonView rivermonView = new LocRiverMonView(_db); - - LocationTable locationTable = new LocationTable(_db); - String whereClause = null; - - try - { - whereClause = " order by lid "; - locRiverMonRecordList = rivermonView.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(locRiverMonRecordList != null) - { - lidList = new ArrayList(); - - for(LocRiverMonRecord locRiverMonRecord: locRiverMonRecordList) - { - lidList.add(locRiverMonRecord.getLid()); - } - - whereClause = "where lid in (select distinct(lid) from ingestfilter where pe in('PC', 'PP') and ingest='T')"; - List locationRecordList = locationTable.select(whereClause); - if(locationRecordList != null) - { - for(LocationRecord locationRecord: locationRecordList) - { - lidList.add(locationRecord.getLid()); - } - } - - if(! lidList.isEmpty() ) - { - lid = new String[lidList.size()]; - int i=0; - for(String str: lidList) - { - lid[i++] = str; - } - } - else - { - _logger.log(header+"read location table for precip lids --- lid list is null"); - } - } - else - { - _logger.log(header+"read loc rivermon --- lid list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - //Sort the 2 merged lists - Arrays.sort(lid); - - return lid; - } - - private void initRiverMonLocationMap() - { - List riverMonLocationInfoList = null; - - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - String whereClause = null; - String header = "RiverMonitorLocGroupDataManager.initRiverMonLocationMap(): "; - - try - { - whereClause = "where group_id not like 'DEFAULT' order by ordinal"; - riverMonLocationInfoList = riverMonLocationTable.select(whereClause); - _logger.log(header + " Where Clause:" + whereClause); - if (riverMonLocationInfoList == null) - { - _logger.log(header + " RiverMonlocation list is null"); - } - else - { - _lidToRiverMonLocationMap = new HashMap(); - for (int i = 0; i < riverMonLocationInfoList.size(); i++) - { - RiverMonLocationRecord record = (RiverMonLocationRecord) riverMonLocationInfoList.get(i); - _lidToRiverMonLocationMap.put(record.getLid(), record); - } - } - } - catch (SQLException e) - { - _logger.log("In " + header); - logSQLException(e); - } - - _locationInfoList = riverMonLocationInfoList; - } - - public String[] getAllGroup() - { - String group[] = null; - List groupList = null; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - RiverMonGroupRecord riverMonGroupRecord = null; - String header = "RiverMonLocationDataManager.getAllGroup(): "; - String whereClause = null; - - try - { - whereClause = " order by group_id "; - groupList = riverMonGroupTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(groupList != null) - { - group = new String[groupList.size()]; - for(int i=0; i < groupList.size(); i++) - { - riverMonGroupRecord = (RiverMonGroupRecord) groupList.get(i); - group[i] = riverMonGroupRecord.getGroup_id(); - } - } - else - { - _logger.log(header+" Group list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return group; - } - - public boolean checkIfRiverMonLocationTableHasRecords() - { - boolean result = false; - List riverMonLocationInfoList = null; - - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - String whereClause = null; - String header = "RiverMonLocationDataManager.checkIfRiverMonLocationTableHasRecords()"; - try - { - whereClause = ""; - riverMonLocationInfoList = riverMonLocationTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonLocationInfoList != null) - { - if(riverMonLocationInfoList.size() > 0) - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - - public List readDataFromRiverMonLocation() - { - List riverMonLocationInfoList = null; - List dataList = null; - - _locationIdToOrdinalMap = new HashMap(); - - RiverMonLocationTable riverMonLocationTable = new RiverMonLocationTable(_db); - RiverMonLocationRecord riverMonLocationRecord = null; - String whereClause = null; - String header = "RiverMonLocationDataManager.readDataFromRiverMonLocation(): "; - - try - { - whereClause = "order by lid"; - riverMonLocationInfoList = riverMonLocationTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonLocationInfoList != null) - { - dataList = new ArrayList(); - - for(int i=0;i < riverMonLocationInfoList.size(); i++) - { - riverMonLocationRecord = (RiverMonLocationRecord) riverMonLocationInfoList.get(i); - RiverMonLocationJTableRowData rowData = new RiverMonLocationJTableRowData(_missingRepresentation); - - _locationIdToOrdinalMap.put(riverMonLocationRecord.getLid(), riverMonLocationRecord.getOrdinal()); - - rowData.setLid(riverMonLocationRecord.getLid()); - rowData.setGroupId(riverMonLocationRecord.getGroup_id()); - rowData.setLocationOrdinal(riverMonLocationRecord.getOrdinal()); - - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" RiverMonLocation list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - private class LocationOrdinalComparator implements Comparator - { - public LocationOrdinalComparator() - { - if(_locationIdToOrdinalMap == null) - { - readDataFromRiverMonLocation(); - } - } - - public int compare(Object obj1, Object obj2) - { - String lid1, lid2; - lid1 = (String) obj1; - lid2 = (String) obj2; - - Integer ordinal1 = (Integer) _locationIdToOrdinalMap.get(lid1); - Integer ordinal2 = (Integer) _locationIdToOrdinalMap.get(lid2); - - int ret; - - if(ordinal1 == null && ordinal2 == null) - { - ret = lid1.compareTo(lid2); - } - else if (ordinal1 == null) - { - return -1; // ordinal2 is greater - } - else if (ordinal2 == null) - { - return 1; // ordinal1 is greater - } - else // both ordinals are not null - { - return ordinal1.compareTo(ordinal2); - } - - return ret; - } - - } - - public int delete(RiverMonGroupRecord rec) - { - int ret = -1; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - try - { - ret = riverMonGroupTable.delete(rec); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public int updateOrInsert(RiverMonGroupRecord rec) - { - int ret = -1; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - try - { - ret = riverMonGroupTable.insertOrUpdate(rec); - updateOrdinalValuesInRiverMonGroup(rec.getGroup_id(), rec.getHsa(), rec.getOrdinal()); - } - catch(SQLException e) - { - logSQLException(e); - } - return ret; - } - - public void updateOrdinalValuesInRiverMonGroup(String groupId, String hsa, int groupOrdinal) - { - - RiverMonGroupTable table = new RiverMonGroupTable(_db); - List recordList = null; - - String where = "WHERE hsa = '" + hsa + "' ORDER BY ordinal ASC, group_id ASC"; - - try - { - recordList = table.select(where); - - int ordinalValue = groupOrdinal + 1; - for (RiverMonGroupRecord oldRecord : recordList) - { - //if the location is not the same as that passed in as argument - if (! oldRecord.getGroup_id().equalsIgnoreCase(groupId)) - { - //if the ordinal is equal or higher than that passed in - if (oldRecord.getOrdinal() >= groupOrdinal) - { - //alter and insert the rest of the records. - RiverMonGroupRecord newRecord = new RiverMonGroupRecord(oldRecord); - - newRecord.setOrdinal(ordinalValue); - - table.update(oldRecord, newRecord); - - ordinalValue++; - } - - } - - } - - } - catch (SQLException e) - { - e.printStackTrace(); - } - - } - - public boolean checkIfRecordExists(RiverMonGroupRecord record) - { - boolean exists = false; - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - String groupId = record.getGroup_id(); - String whereClause = "where group_id="+groupId ; - List recordList = null; - try - { - recordList = riverMonGroupTable.select(whereClause); - } - catch(SQLException e) - { - logSQLException(e); - } - - if(recordList != null) - { - if (recordList.size() > 0) - { - exists = true; - } - } - - return exists; - } - - public boolean checkIfRiverMonGroupTableHasRecords() - { - boolean result = false; - List riverMonGroupInfoList = null; - - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - String whereClause = null; - String header = "RiverMonGroupDataManager.checkIfRiverMonGroupTableHasRecords()"; - try - { - whereClause = ""; - riverMonGroupInfoList = riverMonGroupTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonGroupInfoList != null) - { - if(riverMonGroupInfoList.size() > 0) - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - - public List readDataFromRiverMonGroup() - { - List riverMonGroupInfoList = null; - List dataList = null; - - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - RiverMonGroupRecord riverMonGroupRecord = null; - String whereClause = null; - String header = "RiverMonGroupDataManager.readDataFromRiverMonGroup(): "; - - try - { - whereClause = "order by group_id"; - riverMonGroupInfoList = riverMonGroupTable.select(whereClause); - _logger.log(header+" Where Clause:"+ whereClause); - if(riverMonGroupInfoList != null) - { - dataList = new ArrayList(); - - for(int i=0;i < riverMonGroupInfoList.size(); i++) - { - riverMonGroupRecord = (RiverMonGroupRecord) riverMonGroupInfoList.get(i); - RiverMonGroupJTableRowData rowData = new RiverMonGroupJTableRowData(_missingRepresentation); - - rowData.setGroupId(riverMonGroupRecord.getGroup_id()); - rowData.setGroupName(riverMonGroupRecord.getGroup_name()); - rowData.setGroupOrdinal(riverMonGroupRecord.getOrdinal()); - rowData.setHsa(riverMonGroupRecord.getHsa()); - - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+" RiverMonGroup list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - private void initRiverMonGroupMap() - { - List riverMonGroupInfoList = null; - - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - String whereClause = null; - String header = "RiverMonLocGroupDataManager.initRiverMonGroupMap(): "; - - try - { - whereClause = "order by ordinal"; - riverMonGroupInfoList = riverMonGroupTable.select(whereClause); - - _logger.log(header + " Where Clause:" + whereClause); - if (riverMonGroupInfoList == null) - { - _logger.log(header + " RiverMonGroup list is null"); - } - else - { - _groupIdToRiverMonGroupMap = new HashMap(); - - for (int i = 0; i < riverMonGroupInfoList.size(); i++) - { - RiverMonGroupRecord record = (RiverMonGroupRecord) riverMonGroupInfoList.get(i); - _groupIdToRiverMonGroupMap.put(record.getGroup_id(), record); - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - - _groupInfoList = riverMonGroupInfoList; - } - - - public List getAllHsaCustom() - { - //new Chip - List fullHsaList = new ArrayList(_locationHsaMap.values()); - - Set hsaSet = new HashSet(); - - for (String hsa : fullHsaList) - { - hsaSet.add(hsa); - } - - List hsaList = new ArrayList(hsaSet); - - - return hsaList; - - } - - - private void initAllDefaultGroupsToMap() - { - - Map groupIdToGroupMap = _groupIdToRiverMonGroupMap; - Map groupToHsaMap = _groupHsaMap; - - - //new Chip - String header = "RiverMonLocGroupDataManager.initAllDefaultGroupsToMap(): "; - List hsaList = getAllHsaCustom(); - - for (String hsa : hsaList) - { - String groupId = "DEF_" + hsa; - String groupName = hsa + " DEFAULT GROUP"; - - // System.out.println(header + " groupId = " + groupId + " groupName = " + groupName); - - RiverMonGroupRecord group = new RiverMonGroupRecord(); - group.setGroup_id(groupId); - group.setGroup_name(groupName); - group.setOrdinal(0); - - _groupIdToRiverMonGroupMap.put(groupId, group); - _groupHsaMap.put(groupId, hsa); - _groupInfoList.add(group); - _hsaInfoSet.add(hsa); - } - } - - - private void initGroupHsaMap() - { - Set hsaInfoSet = new HashSet(); - Map groupHsaMap = null; - if (_groupInfoList != null) - groupHsaMap = new HashMap(); - - if (getDefaultHsa() != null) - hsaInfoSet.add(getDefaultHsa()); - else - _logger.log("RiverMonitorLocGroupDataManager.initGroupHsaMap() : Admin HSA is null"); - - - - for (int i = 0; i < _groupInfoList.size(); i++) - { - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(i); - String groupId = riverMonGroupRecord.getGroup_id(); - if (! (groupId.equals(_defaultGroupId))) - { - String lids[] = getLocationsForGroup(groupId); - String hsa = null; - if (lids != null) - { - hsa = riverMonGroupRecord.getHsa(); - - if (hsa == null) - { - if (lids.length > 0) - { - //the default hsa for a group is defined by the HSA of the first location in that group - hsa = _locationHsaMap.get(lids[0]).toString(); - } - else - { - hsa = getDefaultHsa(); - } - } - } - else - { - hsa = riverMonGroupRecord.getHsa(); - if (hsa == null) - { - hsa = getDefaultHsa(); - } - } - // System.out.println("For GroupId :"+groupId+" HSA Old:"+ - // riverMonGroupRecord.getHsa() +" New:"+hsa); - groupHsaMap.put(groupId, hsa); - hsaInfoSet.add(hsa); - } - else - { - String hsa = getDefaultHsa(); - // System.out.println("For GroupId :"+groupId+" HSA Old:"+ - // riverMonGroupRecord.getHsa() +" New:"+hsa); - groupHsaMap.put(groupId, hsa); - hsaInfoSet.add(hsa); - } - } - - //check if groupHsaMap has an entry for DEFAULT group - if not add one for DEFAULT group - if(groupHsaMap != null) - { - if(groupHsaMap.get(_defaultGroupId) == null) - { - // System.out.println("For GroupId :"+_defaultGroupId+" HSA "+getDefaultHsa()); - groupHsaMap.put(_defaultGroupId, getDefaultHsa()); - } - } - - _groupHsaMap = groupHsaMap; - _hsaInfoSet = hsaInfoSet; - } - - // -------------------------------------------------------------------------------------- - - public String[] getAllLocationsForGroup(String groupId, List locationIdList, LocationOrdinalComparator locationComparator) - { - String [] returnArray = null; - - /* if (_groupIdToLocationIdListMap.size() == 0) - { - buildGroupIdToLocationIdListMap(locationIdList); - locationComparator = new LocationOrdinalComparator(); - } - */ - List listOfLocationsInGroup = _groupIdToLocationIdListMap.get(groupId); - - if (listOfLocationsInGroup != null) - { - - Collections.sort(listOfLocationsInGroup, locationComparator); - //convert to String array - returnArray = new String[listOfLocationsInGroup.size()]; - int i = 0; - for (String locationId : listOfLocationsInGroup) - { - returnArray[i] = locationId; - i++; - } - } - - return returnArray; - } - - - // ------------------------------------------------------------------------------- - public void buildGroupIdToLocationIdListMap(List locationIdList) - { - - _groupIdToLocationIdListMap.clear(); - - for (String locationId : locationIdList ) - { - String groupId = getGroupId(locationId); - - List groupLocationIdList = _groupIdToLocationIdListMap.get(groupId); - if (groupLocationIdList == null) - { - groupLocationIdList = new ArrayList(); - _groupIdToLocationIdListMap.put(groupId, groupLocationIdList); - } - - groupLocationIdList.add(locationId); - - } - return; - } - - // ------------------------------------------------------------------------------- - public String[] getLocationsForGroup(String groupId) - { - String returnArray[] = null; - if (_lidToRiverMonLocationMap == null) - initRiverMonLocationMap(); - List locationList = new ArrayList(); - if(groupId.compareTo(_defaultGroupId) == 0) - { - returnArray = getLocationsUnderDefaultGroup(); - } - else - { - for (int i = 0; i < _locationInfoList.size(); i++) - { - RiverMonLocationRecord riverMonLocationRecord = (RiverMonLocationRecord) _locationInfoList.get(i); - String tempGroupId = riverMonLocationRecord.getGroup_id(); - if (tempGroupId.compareTo(groupId) == 0) - locationList.add(riverMonLocationRecord.getLid()); - } - if (locationList != null) - { - returnArray = new String[locationList.size()]; - for (int i = 0; i < locationList.size(); i++) - { - returnArray[i] = locationList.get(i).toString(); - } - } - } - return returnArray; - } - - protected String[] getLocationsUnderDefaultGroup() - { - String[] returnArray = null; - if(_locationsUnderDefaultGroupList != null) - { - returnArray = new String[_locationsUnderDefaultGroupList.size()]; - for (int i = 0; i < returnArray.length; i++) - returnArray[i] = (String) _locationsUnderDefaultGroupList.get(i); - } - return returnArray; - - } - - protected void addThisLocationToDefaultGroupList(String lid) - { - boolean isNewLocation = true; - if(_locationsUnderDefaultGroupList == null) - { - _locationsUnderDefaultGroupList = new ArrayList (); - } - else - { - for(String str: _locationsUnderDefaultGroupList) - { - if(str.compareTo(lid) == 0) - { - isNewLocation = false; - break; - } - } - } - - if(isNewLocation) - _locationsUnderDefaultGroupList.add(lid); - } - - - public void initLocationHsaMap() - { - Map locationHsaMap = null; - String header = "LocationInfoDataManager.readLocationHsaMap(): "; - LocationTable locationTable = new LocationTable(_db); - String whereClause = "order by lid"; - List locationList = null; - try - { - locationList = locationTable.select(whereClause); - if (locationList != null) - { - if (locationList.size() != 0) - { - locationHsaMap = new HashMap(); - for (int i = 0; i < locationList.size(); i++) - { - LocationRecord record = (LocationRecord) locationList.get(i); - String lid = record.getLid(); - String hsa = record.getHsa(); - locationHsaMap.put(lid, hsa); - } - } - else - { - _logger.log(header + "No Records found in LocationTable ..."); - } - } - else - { - _logger.log(header + "No Records found in LocationTable ..."); - } - } - catch (SQLException e) - { - logSQLException(e); - } - _locationHsaMap = locationHsaMap; - } - - - //------------------------------------------------------------------------------------ - - public void updateRiverMonitorGroupWithAppropriateHsa() - { - RiverMonGroupTable riverMonGroupTable = new RiverMonGroupTable(_db); - List riverMonGroupList = null; - String whereClause = ""; - CodeTimer timer = new CodeTimer(); - try - { - timer.start(); - riverMonGroupList = riverMonGroupTable.select(whereClause); - if (riverMonGroupList != null) - { - if (riverMonGroupList.size() > 0) - { - for (int i = 0; i < riverMonGroupList.size(); i++) - { - RiverMonGroupRecord oldRiverMonGroupRecord = (RiverMonGroupRecord) riverMonGroupList.get(i); - RiverMonGroupRecord newRiverMonGroupRecord = new RiverMonGroupRecord(); - newRiverMonGroupRecord.setGroup_id(oldRiverMonGroupRecord.getGroup_id()); - String hsa = (String) _groupHsaMap.get(oldRiverMonGroupRecord.getGroup_id()); - if(hsa != null) - newRiverMonGroupRecord.setHsa(hsa); - else - { - System.out.println("hsa is null for:"+ oldRiverMonGroupRecord.getGroup_id()); - } - newRiverMonGroupRecord.setOrdinal(oldRiverMonGroupRecord.getOrdinal()); - newRiverMonGroupRecord.setGroup_name(oldRiverMonGroupRecord.getGroup_name()); - riverMonGroupTable.update(oldRiverMonGroupRecord, newRiverMonGroupRecord); - } - } - } - timer.stop("Time elapsed in updating rivermongrouptable for hsa:"); - } - catch (SQLException e) - { - _logger.log("In " + " RiverMonitorLocGroupDataManager.updateRiverMonitorGroupWithAppropriateHsa()"); - logSQLException(e); - } - } - - public String[] getAllHsa() - { - String hsa[] = new String[_hsaInfoSet.size()]; // Stores the final hsa - // array in the - // alphabetical order, - // with default hsa as - // the first item - String tempHsaArray[] = new String[_hsaInfoSet.size() - 1]; - int i = 0; - Iterator it = _hsaInfoSet.iterator(); - - while (it.hasNext() && i < _hsaInfoSet.size()) - { - String tempHsa = it.next().toString(); - - if (tempHsa.equals(getDefaultHsa())) // if default hsa found then - // skip - { - continue; - } - else - tempHsaArray[i++] = tempHsa; - } - Arrays.sort(tempHsaArray); // Alphabetize the array - - // Assign default hsa to be the first - so it will be displayed as first - // in the tree, and the rest will be in alphabetical order - hsa[0] = getDefaultHsa(); - System.arraycopy(tempHsaArray, 0, hsa, 1, tempHsaArray.length); - - return hsa; - } - - private String[] getGroupsForHsa(String hsa) - { - String returnArray[] = null; - List groupList = new ArrayList(); - for (int i = 0; i < _groupInfoList.size(); i++) - { - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(i); - String groupId = riverMonGroupRecord.getGroup_id(); - String groupHsa = _groupHsaMap.get(groupId).toString(); - if (hsa.equals(groupHsa)) - { - groupList.add(groupId); - } - } - if (groupList != null) - { - returnArray = new String[groupList.size()]; - for (int i = 0; i < groupList.size(); i++) - { - returnArray[i] = groupList.get(i).toString(); - } - } - - return returnArray; - } - - - public String getGroupName(String groupId) - { - String groupName = null; - if (_groupIdToRiverMonGroupMap == null) - { - initRiverMonGroupMap(); - } - - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - try - { - groupName = riverMonGroupRecord.getGroup_name(); - } - catch (NullPointerException e) - { - System.out.println("groupId = " + groupId); - System.exit(1); - } - return groupName; - } - - public String getGroupId(String lid) - { - String groupId = null; - RiverMonLocationRecord riverMonlocationRecord = null; - - if (_lidToRiverMonLocationMap != null) - { - - - riverMonlocationRecord = (RiverMonLocationRecord) _lidToRiverMonLocationMap.get(lid); - - // pick the group for the location - if (riverMonlocationRecord != null) - { - groupId = riverMonlocationRecord.getGroup_id(); - } - else // (riverMonlocationRecord == null) - { - - String hsa = (String) _locationHsaMap.get(lid); - - if (hsa != null) - { - groupId = "DEF_" + hsa; - } - else //hsa == null - { - groupId = _defaultGroupId; - addThisLocationToDefaultGroupList(lid); - } - - } - - - } - - return groupId; - } - - public String getHsa(String groupId) - { - //return getHsaOrig(groupId); - return getHsa3(groupId); - } - - public String getHsaOrig(String groupId) - { - String hsa ; - RiverMonGroupRecord riverMonGroupRecord = null; - if (_groupIdToRiverMonGroupMap != null) - { - if (_groupIdToRiverMonGroupMap.size() > 0) - riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - } - - if (riverMonGroupRecord != null) - { - hsa = (String ) _groupHsaMap.get(riverMonGroupRecord.getGroup_id()); - } - else - { - hsa = getDefaultHsa(); - } - return hsa; - } - - public String getHsa2(String groupId) - { - String hsa = getDefaultHsa(); - - if (_groupIdToRiverMonGroupMap != null) - { - RiverMonGroupRecord riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - - if (riverMonGroupRecord != null) - { - hsa = _groupHsaMap.get(riverMonGroupRecord.getGroup_id()).toString(); - } - } - - return hsa; - } - - public String getHsa3(String groupId) - { - String hsa = (String) _groupHsaMap.get(groupId); - - if (hsa == null) - { - hsa = getDefaultHsa(); - } - - return hsa; - } - - public void resetLocationOrdinalForDefaultLocations() - { - _locationOrdinalForDefaultLocations = 1; - } - - public int getLocationOrdinal(String lid) - { - String header = "RiverMonLocGroupDataManager.getLocationOrdinal(): "; - int locationOrdinal = 1; - RiverMonLocationRecord riverMonlocationRecord = null; - - String groupId = getGroupId(lid); - - if (groupId == null) - { - System.out.println(header + "groupId was null for lid = " + lid); - } - - else - { - if( ! groupId.equals(_defaultGroupId)) - { - riverMonlocationRecord = (RiverMonLocationRecord) _lidToRiverMonLocationMap.get(lid); - - if (riverMonlocationRecord != null) - { - locationOrdinal = riverMonlocationRecord.getOrdinal(); - } - } - else // default group id - { - locationOrdinal = _locationOrdinalForDefaultLocations++; - } - } - - return locationOrdinal; - } - - - public int getGroupOrdinal(String groupId) - { - int groupOrdinal = 1; - - RiverMonGroupRecord riverMonGroupRecord = null; - if (_groupIdToRiverMonGroupMap != null) - { - riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - } - - if (riverMonGroupRecord != null) - { - groupOrdinal = riverMonGroupRecord.getOrdinal(); - } - else - { - // scenario where default group doesn't have entry in - // RivermonGroup - - if ((_groupInfoList != null) && (_groupInfoList.size() > 0) )// RiverMonGroup has - // some entries - { - - RiverMonGroupRecord tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(0); - int max = tempRiverMonGroupRecord.getOrdinal(); - - for (int k = 1; k < _groupInfoList.size(); k++) - { - tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(k); - if (max < tempRiverMonGroupRecord.getOrdinal()) - { - max = tempRiverMonGroupRecord.getOrdinal(); - } - } - groupOrdinal = max + 1; - } - } - - return groupOrdinal; - } - - private int getGroupOrdinalOld(String groupId) - { - int groupOrdinal = 1; - - RiverMonGroupRecord riverMonGroupRecord = null; - if (_groupIdToRiverMonGroupMap != null) - { - if (_groupIdToRiverMonGroupMap.size() > 0) - riverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap.get(groupId); - } - - if (riverMonGroupRecord != null) - { - groupOrdinal = riverMonGroupRecord.getOrdinal(); - } - else - // scenario where default group doesn't have entry in - // RivermonGroup - { - if (_groupIdToRiverMonGroupMap != null) - { - if (_groupIdToRiverMonGroupMap.size() > 0)// RiverMonGroup has - // some records - { - if (_groupInfoList != null) // RiverMonGroup has - // some entries - { - if (_groupInfoList.size() > 0) - { - RiverMonGroupRecord tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupIdToRiverMonGroupMap - .get(_defaultGroupId); - int max; - tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(0); - max = tempRiverMonGroupRecord.getOrdinal(); - for (int k = 1; k < _groupInfoList.size(); k++) - { - tempRiverMonGroupRecord = (RiverMonGroupRecord) _groupInfoList.get(k); - if (max < tempRiverMonGroupRecord.getOrdinal()) - max = tempRiverMonGroupRecord.getOrdinal(); - } - groupOrdinal = max + 1; - } - else - { - groupOrdinal = 1; - } - } - } - else - // No entries in RiverMonGroup - { - groupOrdinal = 1; - } - } - } - - return groupOrdinal; - } - -} - diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationColumns.java deleted file mode 100644 index f087abf40c..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationColumns.java +++ /dev/null @@ -1,39 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class RiverMonLocationColumns -{ - public static final String GROUP_ID = "Group Id"; - public static final String LOCATION_ID = "Location"; - public static final String LOCATION_ORDINAL = "Location Ordinal"; - - /** - * Creates a list of rivermon location columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the rivermon location columns are added to it, - * if not the location info columns are added to the list that is passed as argument. - * The created new list is returned. - * @param riverMonLocationColumnDescriptorList - * @return - */ - public List getRiverMonLocationColumnsList(List riverMonLocationColumnDescriptorList) - { - String textAlignment = "center"; - String numberAlignment = "right"; - - if( riverMonLocationColumnDescriptorList == null) - { - riverMonLocationColumnDescriptorList = new ArrayList(); - } - - riverMonLocationColumnDescriptorList.add(new JTableColumnDescriptor(GROUP_ID, true, 95, textAlignment, "Group Identification")); - riverMonLocationColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ID, true, 95, textAlignment, "Location Identification")); - riverMonLocationColumnDescriptorList.add(new JTableColumnDescriptor(LOCATION_ORDINAL, true, 105, numberAlignment, "Location Ordinal")); - - return riverMonLocationColumnDescriptorList; - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationDialog.java deleted file mode 100644 index 568720c3ca..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationDialog.java +++ /dev/null @@ -1,383 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.RiverMonLocationRecord; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.FrameCloseWindowListener; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class RiverMonLocationDialog extends JDialog -{ - private List _riverMonLocationColumnDescriptorList = null; - private JTableManager _riverMonLocationTableManager = null; - private RiverMonLocGroupDataManager _riverMonLocGroupDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private int _selectedRowIndex; - private boolean _riverMonLocationTableChanged = false; - - private JLabel _lidLabel; - private JComboBox _lidComboBox ; - private JLabel _lidOrdinalLabel; - private JTextField _lidOrdinalField ; - private JLabel _groupIdLabel; - private JComboBox _groupIdComboBox; - private JButton _updateButton; - private JButton _deleteButton ; - private JButton _closeButton ; - private String _groupIdArray[]; - private String _lidArray[]; - - private boolean _infoDialogShown = false; - private SessionLogger _logger = null; - - private RiverMonLocationJTableRowData _selectedRowData; - private TextFieldInputVerifier _textFieldInputVerifier = new TextFieldInputVerifier(); - - public RiverMonLocationDialog(JFrame mainFrame, RiverMonLocGroupDataManager riverMonLocGroupDataMgr, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - this.setTitle("RiverMonLocation"); - this.getContentPane().setLayout(new GridBagLayout()); - _riverMonLocGroupDataMgr = riverMonLocGroupDataMgr; - _groupIdArray = _riverMonLocGroupDataMgr.getAllGroup(); - discardDefaultGroupInGroupIdArray(); - _lidArray = _riverMonLocGroupDataMgr.getAllLid(); - initialize(riverMonLocGroupDataMgr); - Dimension min = new Dimension(300,570); - Dimension max = new Dimension(350,570); - new WindowResizingManager(this, min, max); - this.pack(); - this.setLocation(25, 25); - } - - public boolean showRiverMonLocationDialog() - { - _riverMonLocationTableChanged = false; - _allRowDataList = _riverMonLocGroupDataMgr.readDataFromRiverMonLocation(); - _riverMonLocationTableManager.setChangedAllRowDataList(_allRowDataList); - _riverMonLocationTableManager.refreshDisplay(); - - _groupIdArray = _riverMonLocGroupDataMgr.getAllGroup(); - _groupIdComboBox.removeAllItems(); - discardDefaultGroupInGroupIdArray(); - for(int i=0; i <_groupIdArray.length; i++) - { - _groupIdComboBox.addItem(_groupIdArray[i]); - } - - _lidArray = _riverMonLocGroupDataMgr.getAllLid(); - _lidComboBox.removeAllItems(); - for(int i=0; i <_lidArray.length; i++) - { - _lidComboBox.addItem(_lidArray[i]); - } - this.setVisible(true); - return(_riverMonLocationTableChanged); - } - - private void discardDefaultGroupInGroupIdArray() - { - List groupIdList = new ArrayList(); - for(int i=0; i < _groupIdArray.length; i++) - { - if(_groupIdArray[i].equalsIgnoreCase("default")) - continue; - else - groupIdList.add(_groupIdArray[i]); - } - String[] groupIdArray = new String[groupIdList.size()]; - for(int i=0; i < groupIdList.size(); i++) - { - groupIdArray[i] = (String) groupIdList.get(i); - } - _groupIdArray = groupIdArray; - } - - private void initialize(RiverMonLocGroupDataManager riverMonLocGroupDataMgr) - { - _riverMonLocationColumnDescriptorList = new RiverMonLocationColumns().getRiverMonLocationColumnsList(_riverMonLocationColumnDescriptorList); - - _allRowDataList = riverMonLocGroupDataMgr.readDataFromRiverMonLocation(); - _riverMonLocationTableManager = new ComplexJTableManager(_riverMonLocationColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _riverMonLocationTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - _riverMonLocationTableManager.setDisplayableColumns(columnsSelected, true, true); - _riverMonLocationTableManager.setPreferredSizeForJScrollPane(new Dimension(315, 300)); - _riverMonLocationTableManager.setVerifyInputWhenFocusTarget(false); - RiverMonitorLocationTableMouseListener tableMouseListener = new RiverMonitorLocationTableMouseListener(); - _riverMonLocationTableManager.addTableListener(tableMouseListener); - _tableScrollPane = _riverMonLocationTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - tableScrollPanePanel.setMinimumSize(new Dimension(315,310)); - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - tablePanel.setMinimumSize(new Dimension(315,310)); - - _lidLabel = new JLabel("Location"); - _lidComboBox = new JComboBox(_lidArray); - - _lidOrdinalLabel = new JLabel("Location Ordinal"); - _lidOrdinalField = new JTextField(); - _lidOrdinalField.setInputVerifier(_textFieldInputVerifier); - - _groupIdLabel = new JLabel("Group Id"); - _groupIdComboBox = new JComboBox(_groupIdArray); - - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new GridLayout(3,2)); - infoPanel.add(_lidLabel); - infoPanel.add(_lidComboBox); - - infoPanel.add(_groupIdLabel); - infoPanel.add(_groupIdComboBox); - - infoPanel.add(_lidOrdinalLabel); - infoPanel.add(_lidOrdinalField); - - JPanel actionPanel = new JPanel(); - actionPanel = new JPanel(); - _updateButton = new JButton("Save"); - _deleteButton = new JButton("Delete"); - _closeButton = new JButton("Close"); - _closeButton.setVerifyInputWhenFocusTarget(false); - actionPanel.add(_updateButton); - actionPanel.add(_deleteButton); - actionPanel.add(_closeButton); - - JPanel editPanel = new JPanel(); - editPanel.setLayout(new GridLayout(1,2)); - editPanel.setBorder(BorderFactory.createTitledBorder("Details")); - - editPanel.add(infoPanel); - - Container contentPane = this.getContentPane(); - ComponentHelper.addFrameComponent(contentPane, tablePanel, 0, 0,1,1,1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, editPanel, 0, 1,1,1, 1, 1, 1); - ComponentHelper.addFrameComponent(contentPane, actionPanel, 0, 2,1,1, 1, 1, 0); - - UpdateListener updateListener = new UpdateListener(); - _updateButton.addActionListener(updateListener); - - DeleteListener deleteListener = new DeleteListener(); - _deleteButton.addActionListener(deleteListener); - - CloseListener closeListener = new CloseListener(); - _closeButton.addActionListener(closeListener); - - } - - private void closeRiverMonLocationDialog() - { - this.setVisible(false); - } - - private void showCurrentRowData() - { - if(_selectedRowData != null) - { - _groupIdComboBox.setSelectedItem(_selectedRowData.getGroupId()); - _lidComboBox.setSelectedItem(_selectedRowData.getLid()); - _lidOrdinalField.setText(new Integer(_selectedRowData.getLocationOrdinal()).toString()); - } - } - - private RiverMonLocationRecord getRiverMonLocationRecord() - { - RiverMonLocationRecord record = new RiverMonLocationRecord(); - - record.setLid(_lidComboBox.getSelectedItem().toString()); - - if(!(_lidOrdinalField.getInputVerifier().verify(_lidOrdinalField))) - { - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - _infoDialogShown = true; - return null; - } - else - { - record.setOrdinal(Integer.parseInt(_lidOrdinalField.getText())); - } - record.setGroup_id(_groupIdComboBox.getSelectedItem().toString()); - - return record; - } - - private void getCurrentDataFromDataMgr() - { - List dbInfoList = null; - String header = "RiverMonLocationDialog.getCurrentDataFromDataMgr() "; - try - { - dbInfoList = _riverMonLocGroupDataMgr.readDataFromRiverMonLocation(); - } - catch(Exception e) - { - _logger.log(header+ e); - } - _allRowDataList = dbInfoList; - _riverMonLocationTableManager.setChangedAllRowDataList(_allRowDataList); - } - - private void delete() - { - String header = "RiverMonLocationDialog.delete(): "; - - RiverMonLocationRecord record = getRiverMonLocationRecord(); - - _logger.log(header+" Delete record"+ record.toString()); - _riverMonLocGroupDataMgr.delete(record); - getCurrentDataFromDataMgr(); - _riverMonLocationTableManager.refreshDisplay(); - _selectedRowData = null; - showCurrentRowData(); - _riverMonLocationTableChanged = true; - - } - - private void insertOrUpdate() - { - String header = "RiverMonLocationDialog.insertOrUpdate(): "; - - RiverMonLocationRecord record = getRiverMonLocationRecord(); - - _logger.log(header+" Update record"+ record.toString()); - _riverMonLocGroupDataMgr.updateOrInsert(record); - getCurrentDataFromDataMgr(); - _riverMonLocationTableManager.refreshDisplay(); - int rowToHighLight = _riverMonLocationTableManager.getTheRowIndexToHighLightBasedOnValue(_lidComboBox.getSelectedItem().toString()); - _riverMonLocationTableManager.selectRows(rowToHighLight, rowToHighLight); - _riverMonLocationTableChanged = true; - - } - - private class TextFieldInputVerifier extends InputVerifier - { - public boolean verify(JComponent component) - { - boolean returnValue = true; - JTextField textField = (JTextField)component; - try - { - Integer.parseInt(textField.getText()); - returnValue = true; - } - catch (NumberFormatException e) - { - returnValue = false; - } - if(!returnValue) - { - JOptionPane.showMessageDialog(null, "Ordinal Number must be a numeric value","RiverMonGroup Application", JOptionPane.PLAIN_MESSAGE); - } - return returnValue; - } - } - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - closeRiverMonLocationDialog(); - } - } - - private class DeleteListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonitorLocationDialog.DeleteListener.actionPerformed(): "; - if(!_infoDialogShown) - { - delete(); - } - } - } - - private class UpdateListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - String header = "RiverMonLocationDialog.UpdateListener.actionPerformed(): "; - if(!_infoDialogShown) - { - insertOrUpdate(); - } - } - } - - private class RiverMonitorLocationTableMouseListener implements MouseListener - { - public void mouseClicked(MouseEvent e) - { - Point p = new Point(e.getX(), e.getY()); - _selectedRowIndex = _riverMonLocationTableManager.getMousePointedRowIndex(p); - _selectedRowData = (RiverMonLocationJTableRowData) _riverMonLocationTableManager.getSelectedRowData(_selectedRowIndex); - showCurrentRowData(); - } - public void mousePressed(MouseEvent e){} - public void mouseReleased(MouseEvent e){} - public void mouseEntered(MouseEvent e){} - public void mouseExited(MouseEvent e){} - } - - public static void main(String[] args) - { - /* - * This main is for testing purposes - */ - - String jdbcUrl = args[0]; - String baseLogFilePath = args[1]; - String defaultHsa = args[2]; - - System.out.println("jdbcUrl = " + jdbcUrl ); - - Database database = new Database(jdbcUrl); - - String messageId = "M1"; - SessionLogger logger = new SessionLogger("RiverMonLocation", baseLogFilePath, true, true, messageId); - - RiverMonLocGroupDataManager dataMgr = new RiverMonLocGroupDataManager(database, logger, "", defaultHsa ); - - JFrame frame = new JFrame(); - - FrameCloseWindowListener.addFrameCloseWindowListener(frame); - - RiverMonLocationDialog dialog = new RiverMonLocationDialog(frame, dataMgr, logger); - dialog.setVisible(true); - frame.setVisible(true); - - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationJTableRowData.java deleted file mode 100644 index 7bdea0dae1..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/rivermonlocgroup/RiverMonLocationJTableRowData.java +++ /dev/null @@ -1,70 +0,0 @@ -package ohd.hseb.rivermonlocgroup; - -import ohd.hseb.monitor.MonitorCell; -import ohd.hseb.monitor.ThreatLevel; -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.CellType; - -public class RiverMonLocationJTableRowData extends AbstractJTableRowData -{ - private String _lid; - private String _groupId; - private int _locationOrdinal; - - public RiverMonLocationJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getLid() - { - return _lid; - } - - public void setLid(String lid) - { - _lid = lid; - } - - public String getGroupId() - { - return _groupId; - } - - public void setGroupId(String groupId) - { - _groupId = groupId; - } - - public int getLocationOrdinal() - { - return _locationOrdinal; - } - - public void setLocationOrdinal(int groupOrdinal) - { - _locationOrdinal = groupOrdinal; - } - - public void addAllCellsToMap() - { - addToCellMap(RiverMonLocationColumns.GROUP_ID, CellType.STRING, getGroupId() ); - addToCellMap(RiverMonLocationColumns.LOCATION_ID, CellType.STRING, getLid() ); - addToCellMap(RiverMonLocationColumns.LOCATION_ORDINAL, CellType.INTEGER, getLocationOrdinal()); - - } - - // ----------------------------------------------------------------------------------- - - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - int decimalPointsForDisplay = 2; - MonitorCell cell = new MonitorCell (columnName, cellType, - value, ThreatLevel.NO_THREAT, - _missingRepresentation, decimalPointsForDisplay); - addCell(cell); - - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventColumns.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventColumns.java deleted file mode 100644 index ed6f7b118e..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventColumns.java +++ /dev/null @@ -1,75 +0,0 @@ -package ohd.hseb.vtecevent; - -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.util.gui.jtable.JTableColumnDescriptor; - -public class VtecEventColumns -{ - public static String OFFICE_ID ="OffId"; - public static String LID = "LocId"; - public static String PRODUCT_MODE = "Mode"; - public static String ACTION = "Act"; - public static String PHENOMENON ="Ph"; - public static String SIGNIFICANCE ="Sig"; - public static String EVENT_TRACKING_NUMBER ="ETN"; - public static String BEGIN_TIME ="BeginTime"; - public static String END_TIME ="EndTime"; - public static String ACTIVE ="Active"; - public static String SEVERITY ="Sev"; - public static String IMMEDIATE_CAUSE ="ImC"; - public static String RISE_TIME ="RiseTime"; - public static String CREST_TIME ="CrestTime"; - public static String FALL_TIME ="FallTime"; - public static String PRODUCT_ID ="ProdId"; - public static String PRODUCT_TIME ="ProductTime"; - public static String UGC_EXPIRE_TIME ="UGCExpTime"; - public static String RECORD ="Rec"; - public static String RISE_TS ="TSr"; - public static String CREST_TS ="TSc"; - public static String FALL_TS ="TSf"; - public static String CREST_VALUE ="CrestVal"; - - /** - * Creates a list of vtecevent columns each of type JTableColumnDescriptor object. - * If the parameter passed is null then the new list is created and the vtecevent columns are added to it, - * if not the vtecevent columns are added to the list that is passed as argument. - * The created new list is returned. - * @param officeNotesColumnDescriptorList - * @return - */ - public List getVtecEventColumnsList(List vtecEventColumnDescriptorList) - { - if( vtecEventColumnDescriptorList == null) - { - vtecEventColumnDescriptorList = new ArrayList(); - } - - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(OFFICE_ID, true, 30, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(LID, true, 50, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_MODE, true, 35, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(ACTION, true, 35, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PHENOMENON, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(SIGNIFICANCE, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(EVENT_TRACKING_NUMBER, true, 35, "right")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(BEGIN_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(END_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(ACTIVE, true, 40, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(SEVERITY, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(IMMEDIATE_CAUSE, true, 35, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(RISE_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(CREST_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(FALL_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_ID, true, 100, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(PRODUCT_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(UGC_EXPIRE_TIME, true, 90, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(RECORD, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(RISE_TS, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(CREST_TS, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(FALL_TS, true, 25, "center")); - vtecEventColumnDescriptorList.add(new JTableColumnDescriptor(CREST_VALUE, true, 60, "right")); - - return vtecEventColumnDescriptorList; - } -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventDataManager.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventDataManager.java deleted file mode 100644 index b0897f421d..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventDataManager.java +++ /dev/null @@ -1,119 +0,0 @@ -package ohd.hseb.vtecevent; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import ohd.hseb.db.Database; -import ohd.hseb.ihfsdb.generated.VTECeventRecord; -import ohd.hseb.ihfsdb.generated.VTECeventTable; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.SessionLogger; -import ohd.hseb.monitor.river.RiverMonitorVtecEventDataManager; - -public class VtecEventDataManager -{ - private Database _db = null; - private SessionLogger _logger = null; - private String _missingRepresentation; - - public VtecEventDataManager(Database dbHandler, SessionLogger logger, String missingRepresentation) - { - super(); - _db = dbHandler; - _logger = logger; - _missingRepresentation = missingRepresentation; - - if (_db == null) - { - JOptionPane.showMessageDialog(null, "Database should be provided","Vtec Application", JOptionPane.PLAIN_MESSAGE); - System.exit(0); - } - } - - public void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - - public List readDataFromVtecEvent() - { - List vtecEventInfoList = null; - List dataList = null; - - VTECeventTable vtecEventTable = new VTECeventTable(_db); - VTECeventRecord vtecEventRecord = null; - String whereClause = null; - String header = "VtecEventDataManager.readDataFromVtecEvent(): "; - - CodeTimer timer = new CodeTimer(); - - try - { - whereClause = "order by geoid"; - timer.start(); - vtecEventInfoList = vtecEventTable.select(whereClause); - timer.stop("Read from vtec event elapsed time:"); - _logger.log(header+ "Where Clause:"+ whereClause); - if(vtecEventInfoList != null) - { - dataList = new ArrayList(); - for(int i=0;i < vtecEventInfoList.size(); i++) - { - vtecEventRecord = (VTECeventRecord) vtecEventInfoList.get(i); - VtecJTableRowData rowData = new VtecJTableRowData(_missingRepresentation); - String active = (RiverMonitorVtecEventDataManager.checkIfEventActive(vtecEventRecord)?"Y":""); - //rowData.setVtecRecord(vtecEventRecord, active); - - rowData.setGeoId(vtecEventRecord.getGeoid()); - rowData.setAction(vtecEventRecord.getAction()); - rowData.setBeginTime(vtecEventRecord.getBegintime()); - rowData.setCrests(vtecEventRecord.getCrests()); - rowData.setCrestTime(vtecEventRecord.getCresttime()); - rowData.setEndTime(vtecEventRecord.getEndtime()); - rowData.setUGCExpireTime(vtecEventRecord.getExpiretime()); - rowData.setEtn(vtecEventRecord.getEtn()); - rowData.setFallTime(vtecEventRecord.getFalltime()); - rowData.setFallts(vtecEventRecord.getFallts()); - rowData.setImmedCause(vtecEventRecord.getImmed_cause()); - rowData.setOfficeId(vtecEventRecord.getOffice_id()); - rowData.setPhenom(vtecEventRecord.getPhenom()); - rowData.setProductId(vtecEventRecord.getProduct_id()); - rowData.setProductMode(vtecEventRecord.getProductmode()); - rowData.setProductTime(vtecEventRecord.getProducttime()); - rowData.setRecord(vtecEventRecord.getRecord()); - rowData.setRiseTime(vtecEventRecord.getRisetime()); - rowData.setRisets(vtecEventRecord.getRisets()); - rowData.setSeverity(vtecEventRecord.getSeverity()); - rowData.setSignif(vtecEventRecord.getSignif()); - rowData.setCrestValue(vtecEventRecord.getCrest_value()); - - rowData.setActive(active); - - rowData.addAllCellsToMap(); - dataList.add(rowData); - } - } - else - { - _logger.log(header+"VtecEventinfo list is null"); - } - } - catch(SQLException e) - { - logSQLException(e); - } - return dataList; - } - - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventDialog.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventDialog.java deleted file mode 100644 index 8867785498..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecEventDialog.java +++ /dev/null @@ -1,88 +0,0 @@ -package ohd.hseb.vtecevent; - -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagLayout; -import java.util.List; - -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import ohd.hseb.util.SessionLogger; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.jtable.ComplexJTableManager; -import ohd.hseb.util.gui.jtable.JTableManager; - -public class VtecEventDialog extends JDialog -{ - private List _vtecEventColumnDescriptorList = null; - private JTableManager _vtecEventTableManager = null; - private VtecEventDataManager _vtecDataMgr = null; - private List _allRowDataList = null; - private JScrollPane _tableScrollPane = null; - private SessionLogger _logger; - private int _previousRowToHighlight = -1; - - public VtecEventDialog(JFrame mainFrame, VtecEventDataManager vtecDataMgr, SessionLogger logger) - { - super(mainFrame, true); - _logger = logger; - this.setTitle("Valid Time Event Code (VTEC) History"); - this.getContentPane().setLayout(new GridBagLayout()); - _vtecDataMgr = vtecDataMgr; - initialize(); - Dimension dim; - dim = new Dimension(1250,560); - new WindowResizingManager(this, dim, dim); - this.pack(); - this.setLocation(25, 25); - } - - public void showVtecEventDialog(String geoId) - { - _allRowDataList = _vtecDataMgr.readDataFromVtecEvent(); - _vtecEventTableManager.setChangedAllRowDataList(_allRowDataList); - _vtecEventTableManager.refreshDisplay(); - - if(geoId != null) - { - _vtecEventTableManager.deselectRows(_previousRowToHighlight, _previousRowToHighlight); - int rowToHighLight = _vtecEventTableManager.getTheRowIndexToHighLightBasedOnValue(geoId); - if(rowToHighLight != -1) - { - _vtecEventTableManager.selectRows(rowToHighLight, rowToHighLight); - _previousRowToHighlight = rowToHighLight; - } - } - this.setVisible(true); - } - - private void initialize() - { - _vtecEventColumnDescriptorList = new VtecEventColumns().getVtecEventColumnsList(_vtecEventColumnDescriptorList); - _allRowDataList = _vtecDataMgr.readDataFromVtecEvent(); - - _vtecEventTableManager = new ComplexJTableManager(_vtecEventColumnDescriptorList, _allRowDataList); - String columnsSelected[] = _vtecEventTableManager.getColumnNamesThatAreCurrentlyDisplayed(); - - _vtecEventTableManager.setDisplayableColumns(columnsSelected, true, true); - - _vtecEventTableManager.setPreferredSizeForJScrollPane(new Dimension(1230, 500)); - - _tableScrollPane = _vtecEventTableManager.getJScrollPane(); - - JPanel tableScrollPanePanel = new JPanel(); - tableScrollPanePanel.add(_tableScrollPane); - - tableScrollPanePanel.setMinimumSize(new Dimension(1240,510)); - - JPanel tablePanel = new JPanel(); - tablePanel.add(tableScrollPanePanel); - - Container contentPane = this.getContentPane(); - contentPane.add(tablePanel); - } - -} diff --git a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecJTableRowData.java b/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecJTableRowData.java deleted file mode 100644 index d00878b75a..0000000000 --- a/javaUtilities/hydro/ohd.rivermonitor/src/ohd/hseb/vtecevent/VtecJTableRowData.java +++ /dev/null @@ -1,309 +0,0 @@ -package ohd.hseb.vtecevent; - -import ohd.hseb.util.gui.jtable.AbstractJTableRowData; -import ohd.hseb.util.gui.jtable.BaseTableCell; -import ohd.hseb.util.gui.jtable.CellType; - -public class VtecJTableRowData extends AbstractJTableRowData -{ - private String _geoId; - private String _productId; - private long _productTime; - private long _ugcExpireTime; - private String _productMode; - private String _action; - private String _officeId; - private String _phenom; - private String _signif; - private short _etn; - private long _beginTime; - private long _endTime; - private String _severity; - private String _immedCause; - private long _riseTime; - private long _crestTime; - private long _fallTime; - private String _record; - private String _risets; - private String _crests; - private String _fallts; - private String _active; - private double _crestValue; - - public VtecJTableRowData(String missingRepresentation) - { - setMissingRepresentation(missingRepresentation); - } - - public String getAction() - { - return _action; - } - - public void setAction(String action) - { - this._action = action; - } - - public long getBeginTime() - { - return _beginTime; - } - - public void setBeginTime(long beginTime) - { - _beginTime = beginTime; - } - - public String getCrests() - { - return _crests; - } - - public void setCrests(String crests) - { - this._crests = crests; - } - - public long getCrestTime() - { - return _crestTime; - } - - public void setCrestTime(long crestTime) - { - _crestTime = crestTime; - } - - public long getEndTime() - { - return _endTime; - } - - public void setEndTime(long endTime) - { - _endTime = endTime; - } - - public short getEtn() - { - return _etn; - } - - public void setEtn(short etn) - { - this._etn = etn; - } - - public long getFallTime() - { - return _fallTime; - } - - public void setFallTime(long fallTime) - { - _fallTime = fallTime; - } - - public String getFallts() - { - return _fallts; - } - - public void setFallts(String fallts) - { - this._fallts = fallts; - } - - public String getGeoId() - { - return _geoId; - } - - public void setGeoId(String geoId) - { - _geoId = geoId; - } - - public String getImmedCause() - { - return _immedCause; - } - - public void setImmedCause(String immedCause) - { - _immedCause = immedCause; - } - - public String getOfficeId() - { - return _officeId; - } - - public void setOfficeId(String officeId) - { - _officeId = officeId; - } - - public String getPhenom() - { - return _phenom; - } - - public void setPhenom(String phenom) - { - this._phenom = phenom; - } - - public String getProductId() - { - return _productId; - } - - public void setProductId(String productId) - { - _productId = productId; - } - - public String getProductMode() - { - return _productMode; - } - - public void setProductMode(String productMode) - { - _productMode = productMode; - } - - public long getProductTime() - { - return _productTime; - } - - public void setProductTime(long productTime) - { - _productTime = productTime; - } - - public long getUGCExpireTime() - { - return _ugcExpireTime; - } - - public void setUGCExpireTime(long ugcExpireTime) - { - _ugcExpireTime = ugcExpireTime; - } - - public String getRecord() - { - return _record; - } - - public void setRecord(String record) - { - this._record = record; - } - - public long getRiseTime() - { - return _riseTime; - } - - public void setRiseTime(long riseTime) - { - _riseTime = riseTime; - } - - public String getRisets() - { - return _risets; - } - - public void setRisets(String risets) - { - this._risets = risets; - } - - public String getSeverity() - { - return _severity; - } - - public void setSeverity(String severity) - { - this._severity = severity; - } - - public String getSignif() - { - return _signif; - } - - public void setSignif(String signif) - { - this._signif = signif; - } - - public String getActive() - { - return _active; - } - - public void setActive(String active) - { - this._active = active; - } - - public double getCrestValue() - { - return _crestValue; - } - - public void setCrestValue(double crestValue) - { - _crestValue = crestValue; - } - - public String toString() - { - String str = null; - return str; - } - - private void addToCellMap(String columnName, CellType cellType, - Object value) - { - BaseTableCell cell = new BaseTableCell (columnName, cellType, value, getMissingRepresentation(), "MM/dd - HH:mm"); - addCell(cell); - - } - - public void addAllCellsToMap() - { - addToCellMap(VtecEventColumns.OFFICE_ID, CellType.STRING, getOfficeId()); - addToCellMap(VtecEventColumns.LID, CellType.STRING, getGeoId()); - addToCellMap(VtecEventColumns.PRODUCT_MODE, CellType.STRING, getProductMode()); - addToCellMap(VtecEventColumns.ACTION, CellType.STRING, getAction()); - addToCellMap(VtecEventColumns.PHENOMENON, CellType.STRING, getPhenom()); - addToCellMap(VtecEventColumns.SIGNIFICANCE, CellType.STRING,getSignif()); - addToCellMap(VtecEventColumns.EVENT_TRACKING_NUMBER,CellType.SHORT, getEtn()); - addToCellMap(VtecEventColumns.BEGIN_TIME,CellType.DATE_TIME, getBeginTime()); - addToCellMap(VtecEventColumns.END_TIME,CellType.DATE_TIME, getEndTime()); - addToCellMap(VtecEventColumns.ACTIVE, CellType.STRING, getActive()); - addToCellMap(VtecEventColumns.SEVERITY, CellType.STRING, getSeverity()); - addToCellMap(VtecEventColumns.IMMEDIATE_CAUSE,CellType.STRING, getImmedCause()); - addToCellMap(VtecEventColumns.RISE_TIME, CellType.DATE_TIME, getRiseTime()); - addToCellMap(VtecEventColumns.CREST_TIME, CellType.DATE_TIME, getCrestTime()); - addToCellMap(VtecEventColumns.FALL_TIME, CellType.DATE_TIME, getFallTime()); - addToCellMap(VtecEventColumns.PRODUCT_ID, CellType.STRING, getProductId()); - addToCellMap(VtecEventColumns.PRODUCT_TIME, CellType.DATE_TIME, getProductTime()); - addToCellMap(VtecEventColumns.UGC_EXPIRE_TIME, CellType.DATE_TIME, getUGCExpireTime()); - addToCellMap(VtecEventColumns.RECORD, CellType.STRING, getRecord()); - addToCellMap(VtecEventColumns.RISE_TS, CellType.STRING, getRisets()); - addToCellMap(VtecEventColumns.CREST_TS, CellType.STRING, getCrests()); - addToCellMap(VtecEventColumns.FALL_TS, CellType.STRING, getFallts()); - addToCellMap(VtecEventColumns.CREST_VALUE, CellType.DOUBLE,getCrestValue()); - } - -} diff --git a/javaUtilities/hydro/ohd.sshp/.classpath b/javaUtilities/hydro/ohd.sshp/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.sshp/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.sshp/.project b/javaUtilities/hydro/ohd.sshp/.project deleted file mode 100644 index 3ac54530f6..0000000000 --- a/javaUtilities/hydro/ohd.sshp/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.sshp - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.sshp/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.sshp/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 2ec74d4e3b..0000000000 --- a/javaUtilities/hydro/ohd.sshp/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:29:58 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.sshp/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.sshp/META-INF/MANIFEST.MF deleted file mode 100644 index 99de209f30..0000000000 --- a/javaUtilities/hydro/ohd.sshp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,15 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Sshp -Bundle-SymbolicName: ohd.sshp -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0", - ohd.ihfsdb;bundle-version="1.0.0" -Export-Package: ohd.hseb.sshp, - ohd.hseb.sshp.gui, - ohd.hseb.sshp.messaging, - ohd.hseb.sshp.precip, - ohd.hseb.sshp.window diff --git a/javaUtilities/hydro/ohd.sshp/build.properties b/javaUtilities/hydro/ohd.sshp/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.sshp/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.sshp/build.xml b/javaUtilities/hydro/ohd.sshp/build.xml deleted file mode 100644 index a20701f600..0000000000 --- a/javaUtilities/hydro/ohd.sshp/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/ohd.sshp.ecl b/javaUtilities/hydro/ohd.sshp/ohd.sshp.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.sshp/scripts/process_hydro_model_data b/javaUtilities/hydro/ohd.sshp/scripts/process_hydro_model_data deleted file mode 100644 index 264f81b9b9..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/process_hydro_model_data +++ /dev/null @@ -1,51 +0,0 @@ -#!/bin/ksh -# file name: process_hydro_model_data -# Created: 04/01/2004 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# setup the AWIPS environment -# -. $FXA_HOME/readenv.sh - -FILENAME=$1 -SUBJECT=$2 -MSGTYPE=$3 - -# use a shell function to extract the argument from the subject line -# the subject string is a quoted string with the a descriptive term, -# followed by a space, followed by the product identifier. -# -parseSubject() -{ -ORIGINAL_FILE_NAME=$1 -PRODUCTID=$2 -return -} -# -# get the product id from the subject -# -parseSubject $SUBJECT - -ORIGINAL_FILE_PATH=$SSHP_INCOMING_DIR/$ORIGINAL_FILE_NAME - -# Keeps the last 1200 lines of the log file - -LOGFILE=$SSHP_LOG_DIR/process_hydro_model_data.log -TMPFILE=$SSHP_LOG_DIR/process_hydro_model_data.tmp - -tail -1200 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - -cp -f $FILENAME $ORIGINAL_FILE_PATH - -# used to remove the header and ^Ms from the transferred XML file -sed '1,2d' $ORIGINAL_FILE_PATH > $SSHP_INCOMING_DIR/temp.xml -cat $SSHP_INCOMING_DIR/temp.xml | tr -d '\015' > $ORIGINAL_FILE_PATH -rm -f $SSHP_INCOMING_DIR/temp.xml - -ssh -oBatchMode=yes $SSHP_JAVA_PROCESS_HOST $WHFS_BIN_DIR/run_SSHP_data_decode >$LOGFILE 2>>$LOGFILE \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_HPN_preprocess b/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_HPN_preprocess deleted file mode 100644 index 1e4c06540e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_HPN_preprocess +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/ksh -# file name: run_SSHP_HPN_Preprocessor -# Created: 4/17/2008 -# Modified: 5/01/2008 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=. -CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - - -# Trims, but keeps the last 12000 lines of the internal, java-created log file -tail -12000 $SSHP_LOG_DIR/HPNPreprocessor.log > $SSHP_LOG_DIR/HPNPreprocessor.log.tmp -mv $SSHP_LOG_DIR/HPNPreprocessor.log.tmp $SSHP_LOG_DIR/HPNPreprocessor.log - -# Trims, but keeps the last 12000 lines of the stdout and stderr log file -export LOGFILE=$SSHP_LOG_DIR/HPNPreprocessor.stdout2.log -export TMPFILE=$SSHP_LOG_DIR/HPNPreprocessor.stdout2.tmp -tail -12000 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - -# run the HPN Preprocessor -$JBINDIR/java ohd.hseb.sshp.precip.HPNPreprocessor $JDBCURL $SSHP_LOG_DIR >>$LOGFILE 2>&1 diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_MAP_preprocess b/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_MAP_preprocess deleted file mode 100644 index 695b114564..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_MAP_preprocess +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/ksh -# file name: run_MapPreprocessor -# Created: 12/15/2003 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=. -CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - - -# Trims, but keeps the last 12000 lines of the internal, java-created log file -tail -12000 $SSHP_LOG_DIR/MAPPreprocessor.log > $SSHP_LOG_DIR/MAPPreprocessor.log.tmp -mv $SSHP_LOG_DIR/MAPPreprocessor.log.tmp $SSHP_LOG_DIR/MAPPreprocessor.log - -# Trims, but keeps the last 12000 lines of the stdout and stderr log file -export LOGFILE=$SSHP_LOG_DIR/MAPPreprocessor.stdout2.log -export TMPFILE=$SSHP_LOG_DIR/MAPPreprocessor.stdout2.tmp -tail -12000 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - -# run the MPEPreprocessor -$JBINDIR/java ohd.hseb.sshp.precip.MPEPreprocessor $JDBCURL $SSHP_LOG_DIR >>$LOGFILE 2>&1 - - diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_SAC_state_update b/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_SAC_state_update deleted file mode 100644 index fa40aa5e2d..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_SAC_state_update +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/ksh -# file name: run_SSHP_SAC_state_update -# Created: 12/15/2003 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=. -CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - -export WHFS_LOCAL_DATA_SSHP_DIR=$WHFS_BIN_DIR/../local/data/app/sshp - - -EXPIRATION_HOURS=$($GAD_DIR/get_apps_defaults$OS_SUFFIX sshp_sac_update_expiration_hours) -if [ -z "$EXPIRATION_HOURS" ] -then - EXPIRATION_HOURS=25 -fi - -HOURS_FORWARD=$($GAD_DIR/get_apps_defaults$OS_SUFFIX sshp_sac_update_hours_forward) -if [ -z "$HOURS_FORWARD" ] -then - HOURS_FORWARD=-2 -fi - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -# Keeps the last 1200 lines of the log file - -LOGFILE=$SSHP_LOG_DIR/SacStateUpdate.log -STDLOGFILE=$SSHP_LOG_DIR/SacStateUpdate.stdout.log -TMPFILE=$SSHP_LOG_DIR/SacStateUpdate.tmp - -tail -1200 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - -tail -1200 $STDLOGFILE > $TMPFILE -mv $TMPFILE $STDLOGFILE -# run the SacStateUpdater if on Linux or ssh to a linux machine if not. - -if [[ `uname` = "Linux" ]] -then - $JBINDIR/java ohd.hseb.sshp.SacStateUpdater $JDBCURL $EXPIRATION_HOURS $HOURS_FORWARD $LOGFILE >>$STDLOGFILE 2>>$STDLOGFILE -elif [[ `uname` = "HP-UX" ]] -then - ssh -oBatchMode=yes $SSHP_JAVA_PROCESS_HOST $WHFS_BIN_DIR/run_SSHP_SAC_state_update >>$STDLOGFILE 2>>$STDLOGFILE -fi diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_decode b/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_decode deleted file mode 100644 index 01e5b6349f..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_decode +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/ksh -# file name: run_SSHP_data_decoder -# Created: 12/15/2003 -# Modified: 04/01/2004 -# Modified: 03/30/2004 - added amIRunning - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -wait_time=$1 - -# Keeps the last 1200 lines of the log file - -LOGFILE=$SSHP_LOG_DIR/SacXMLDecoder.log - -# ensure that only 1 instance of this script runs on a machine -AMIRUNNING_DIR=$SSHP_LOG_DIR -. /awips/hydroapps/public/bin/amirunning - -if [[ $AmIRunning = "yes" ]] -then - messageDate=`date -u '+%Y/%m/%d %k:%M:%S.XXX'` - echo $messageDate: Startup of run_SSHP_data_decode cancelled because of prior running instance >> $LOGFILE - exit 1 -fi - -TMPFILE=$SSHP_LOG_DIR/SacXMLDecoder.tmp -tail -1200 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - -# set up an X Terminal window to write stdout and run the SacXMLDecoder application -$JBINDIR/java ohd.hseb.sshp.messaging.SacXMLDecoder $JDBCURL $SSHP_INCOMING_DIR $SSHP_INGEST_XML_DIR $SSHP_LOG_DIR $wait_time >>$LOGFILE 2>>$LOGFILE -exit diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_send b/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_send deleted file mode 100644 index 4cd9dbebf9..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_send +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/ksh -# file name: run_sshp_data_sender -# Purpose: this will contain the code to send a message over the AWIPS -# Message Handling System (MHS) -# For now, in order to test the overall system, though, it just does a copy -# Created: 03-05-2004 -# Last Modified: 04-01-2004 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# setup the AWIPS environment -# -. $FXA_HOME/readenv.sh - -FILEPATH=$1 -FILENAME=$2 -MHS_SITE_ID=$3 -PRODUCT_ID=$4 - -cp $FILEPATH SSHP_OUTGOING_DIR/. -# Keeps the last 1200 lines of the log file - -LOGFILE=$SSHP_LOG_DIR/SshpDataSender.log -TMPFILE=$SSHP_LOG_DIR/SshpDataSender.tmp - -tail -1200 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - - -# Send product to specific location -# add the one-word description and the office id -# -echo "Sending file:$FILENAME product_ID:$PRODUCT_ID to $MHS_SITE_ID via distributeProduct" >> $LOGFILE -SUBJECT="$FILENAME $PRODUCT_ID Hydro_Model_Data" -/awips/fxa/bin/distributeProduct -c HYDRO_MODEL_DATA -s "$SUBJECT" -a $MHS_SITE_ID $PRODUCT_ID $FILEPATH diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_transfer b/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_transfer deleted file mode 100644 index 6f3a592243..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SSHP_data_transfer +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/ksh -# file name: run_SSHP_data_transfer -# Created: 12/15/2003 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -export CONTROL_FILE=$SSHP_CONTROL_DIR/SSHPTransfer.xml - -# Keeps the last 1200 lines of the log file - -LOGFILE=$SSHP_LOG_DIR/SshpDataTransferMgr.log -STDLOGFILE=$SSHP_LOG_DIR/SshpDataTransferMgr.stdout.log -TMPFILE=$SSHP_LOG_DIR/SshpDataTransferMgr.tmp - -tail -1200 $LOGFILE > $TMPFILE -mv $TMPFILE $LOGFILE - -tail -1200 $STDLOGFILE > $TMPFILE -mv $TMPFILE $STDLOGFILE - -if [[ `uname` = "Linux" ]] -then - $JBINDIR/java ohd.hseb.sshp.messaging.SshpDataTransferMgr $CONTROL_FILE $SSHP_OFS_EXTRACT_TEXT_DIR $SSHP_OFS_EXTRACT_XML_DIR $SSHP_LOG_DIR >>$STDLOGFILE 2>>$STDLOGFILE -elif [[ `uname` = "HP-UX" ]] -then - ssh -oBatchMode=yes $SSHP_JAVA_PROCESS_HOST $WHFS_BIN_DIR/run_SSHP_data_transfer >>$STDLOGFILE 2>>$STDLOGFILE -fi \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_SiteSpecific b/javaUtilities/hydro/ohd.sshp/scripts/run_SiteSpecific deleted file mode 100644 index 6da9cafa0c..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_SiteSpecific +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/ksh -# file name: run_SiteSpecific -# Created: 12/15/2003 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -# trim log file -SSHPLOGFILE=$SSHP_LOG_DIR/SSHP.log -SSHPTMPFILE=$SSHP_LOG_DIR/SSHP.tmp -tail -1200 $SSHPLOGFILE > $SSHPTMPFILE -mv $SSHPTMPFILE $SSHPLOGFILE - -# set up an X Terminal window to write stdout and run the SiteSpecific -# application using java -xterm -T "SiteSpecific standard output window" -iconic \ --e $JBINDIR/java ohd.hseb.sshp.SSHP $JDBCURL $SSHP_LOG_DIR $LID_PASSED_IN & diff --git a/javaUtilities/hydro/ohd.sshp/scripts/run_UnitHydrographEditor b/javaUtilities/hydro/ohd.sshp/scripts/run_UnitHydrographEditor deleted file mode 100644 index 1ae0d78d9f..0000000000 --- a/javaUtilities/hydro/ohd.sshp/scripts/run_UnitHydrographEditor +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/ksh -# file name: run_UnitHydrographEditor -# Created: 10/07/2004 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/SiteSpecific.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -Dte=`date +%m%d%Y` - -LOG_FILE=$SSHP_LOG_DIR/UnitHydrographEditor_$Dte.log -TMPLOGFILE=$SSHP_LOG_DIR/UnitHydrographEditor.tmp - -tail -1200 $LOG_FILE > $TMPLOGFILE -mv $TMPLOGFILE $LOG_FILE - -# set up an X Terminal window to write stdout and run the SiteSpecific -# application using java -xterm -T UnitHydrographEditor -iconic -n UnitHydrographEditor -e $JBINDIR/java ohd.hseb.sshp.window.UnitHydrographEditor $JDBCURL $LID_PASSED_IN $LOG_FILE >$LOG_FILE 2>>$LOG_FILE & \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/AboutInfo.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/AboutInfo.java deleted file mode 100644 index 1cba8be66e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/AboutInfo.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Created on Aug 6, 2004 - * - * - */ -package ohd.hseb.sshp; - -/** - * @author GobsC - * - * - */ -public class AboutInfo -{ - private static final String _versionString = "OB 9.0"; - private static final String _aboutText = " Application : Site Specific Hydrologic Predictor\n" + - " Version : " + _versionString + "\n" + - " Date : 9/3/2008 " + "\n" + - " Developed by :\n" + - " National Weather Service\n" + - " Office of Hydrologic Development\n" + - " Hydrology Laboratory"; - - private AboutInfo() - { - - - } - - public static String getText() - { - return _aboutText; - } - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/AppController.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/AppController.java deleted file mode 100644 index 21c3fd373b..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/AppController.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Created on Sep 17, 2003 - * - */ -package ohd.hseb.sshp; - -import java.awt.Rectangle; - -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.sshp.window.AnalysisWindow; -import ohd.hseb.sshp.window.ControlWindow; -import ohd.hseb.util.gui.*; - -/** - * @author Chip Gobs - * - * This class is the controller under the Model-View-Controller pattern. - * It provides the "glue" application functionality. - * (as a separate concept from the GUI functionality.); -*/ -public class AppController -{ - - private DataMgr _dataMgr = null; - private ControlWindow _controlWindow = null; - // private FileLogger _logger = null; - private String _logDirName = null; - - private String _operatingSystemString = null; - -//----------------------------------------------------------- - - public AppController(DataMgr dataMgr, String logDirName) - { - _dataMgr = dataMgr; - - _logDirName = logDirName; - // _logger = new FileLogger(_logDirName, true, true); - - return; - } -// ----------------------------------------------------------- - /* - public FileLogger getLogger() - { - return _logger; - } - */ - -// ----------------------------------------------------------- - - public String getLogDirName() - { - return _logDirName; - } - -// ----------------------------------------------------------- - - private StreamModel createStreamModel(String locationId) - { - - RainfallRunoffModelType rrModelType = - _dataMgr.getPreferredRainfallRunoffModelType(locationId); - - StreamModel streamModel = new StreamModel(locationId, - rrModelType, - _dataMgr); - - return streamModel; - } - -// ----------------------------------------------------------- - - public void displayAnalysisWindow(String locationId) - { - //make sure that a launch window is available - displayControlWindowIfNotDisplayed(); - _controlWindow.enableLaunchButton(false); - - if (_dataMgr.isLocationIdValidForSSHP(locationId)) - { - - - ModelManager modelManager = new ModelManager(locationId, _dataMgr); - - StreamModel streamModel = createStreamModel(locationId); - modelManager.setPrimaryStreamModel(streamModel); - - AnalysisWindow analysisWindow = new AnalysisWindow(modelManager, this); - - Rectangle bounds = analysisWindow.getBounds(); - bounds.x = 80; - analysisWindow.setBounds(bounds); - - analysisWindow.setVisible(true); - } - else // this location is not valid for display in SSHP - { - String message = "Location :" + locationId + ": is not properly configured for use with SSHP."; - String dialogTitle = "SSHP Error Dialog"; - DialogHelper.displayErrorDialog(_controlWindow, message, dialogTitle); - } - - _controlWindow.enableLaunchButton(true); - } - -// ----------------------------------------------------------- - - - public void displayControlWindowIfNotDisplayed() - { - //displays launch window if one is not already displayed - if (_controlWindow == null) - { - - _controlWindow = new ControlWindow(_dataMgr, this); - - _controlWindow.setVisible(true); - - Rectangle bounds = _controlWindow.getBounds(); - bounds.x = 80; - _controlWindow.setBounds(bounds); - - _controlWindow.show(); - } - } //end displayLaunchWindow() -// ----------------------------------------------------------- - - - public void bringLaunchWindowToFront() - { - //displays launch window if one is not already displayed - if (_controlWindow != null) - { - _controlWindow.requestFocus(); - _controlWindow.setVisible(false); - _controlWindow.setVisible(true); - } - - } //end displayLaunchWindow() - - public boolean isRunningOnWindows() - { - boolean result = false; - - if (_operatingSystemString == null) - { - _operatingSystemString = System.getProperty("os.name").toLowerCase(); - } - - if ( (_operatingSystemString.indexOf("windows") > -1) || - (_operatingSystemString.indexOf("nt") > -1)) - { - // thanks to JuanFran for the xp fix! - result = true; - } - - return result; - } - -// ----------------------------------------------------------- - /* public void finalize() - { - if (_logger!= null) - { - _logger.close(); - } - } - */ -} //end class AppController diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/DataMgr.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/DataMgr.java deleted file mode 100644 index d6be68bb7e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/DataMgr.java +++ /dev/null @@ -1,6645 +0,0 @@ -/* - * Created on Jul 30, 2003 - * - * - */ -package ohd.hseb.sshp; - - -import ohd.hseb.db.*; -import ohd.hseb.util.*; - -//These are explicity imported in order to show what -//database tables are being used. - -import ohd.hseb.ihfsdb.generated.ArealFcstRecord; -import ohd.hseb.ihfsdb.generated.ArealFcstTable; -import ohd.hseb.ihfsdb.generated.ArealObsRecord; -import ohd.hseb.ihfsdb.generated.ArealObsTable; -import ohd.hseb.ihfsdb.generated.ContingencyValueRecord; -import ohd.hseb.ihfsdb.generated.ContingencyValueTable; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.FcstOtherRecord; -import ohd.hseb.ihfsdb.generated.FcstOtherTable; -import ohd.hseb.ihfsdb.generated.FcstPrecipRecord; -import ohd.hseb.ihfsdb.generated.FcstPrecipTable; -import ohd.hseb.ihfsdb.generated.FloodcatRecord; -import ohd.hseb.ihfsdb.generated.FloodcatTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LineSegsRecord; -import ohd.hseb.ihfsdb.generated.LineSegsTable; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.MonthlyValuesRecord; -import ohd.hseb.ihfsdb.generated.MonthlyValuesTable; -import ohd.hseb.ihfsdb.generated.ProcValueRecord; -import ohd.hseb.ihfsdb.generated.ProcValueTable; -import ohd.hseb.ihfsdb.generated.RWResultRecord; -import ohd.hseb.ihfsdb.generated.RWResultTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverStatusRecord; -import ohd.hseb.ihfsdb.generated.RiverStatusTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.SacSmaParamsRecord; -import ohd.hseb.ihfsdb.generated.SacSmaParamsTable; -import ohd.hseb.ihfsdb.generated.SacSmaStateRecord; -import ohd.hseb.ihfsdb.generated.SacSmaStateTable; -import ohd.hseb.ihfsdb.generated.ShefPeRecord; -import ohd.hseb.ihfsdb.generated.ShefPeTable; -import ohd.hseb.ihfsdb.generated.SshpConfigRecord; -import ohd.hseb.ihfsdb.generated.SshpConfigTable; -import ohd.hseb.ihfsdb.generated.UnitGraphRecord; -import ohd.hseb.ihfsdb.generated.UnitGraphTable; -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; -import ohd.hseb.model.sacsma.*; -import ohd.hseb.sshp.precip.*; - -//import whfs.db.gen.*; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.Date; -import java.io.*; -import java.sql.*; - - - - -/** - * @author Chip Gobs - * - * DataMgr manages the data for the SSHP application - */ -public class DataMgr -{ - public final double MISSING = -999.0; - - private static final int _defaultQualityCode = 1879048191; - private static final int _questionable_bad_threshold = 1073741824; - private static final long _millisPerHour = 60*60*1000; - private static final long _millisPerYear = (365L * 24L * 60L * 60L * 1000L); - - private Database _db = null; - private Logger _logger = null; - private Map _locationDescriptorMap = new HashMap();; - private Map _sshpConfigMap = new HashMap(); - private Map _basinHelperMap = new HashMap(); - private Map _priorRunoffRecordMap = new HashMap(); - private Map _ratingCurveMap = new HashMap(); - private Map _sigRiverLevelsMap = new HashMap(); - private Map _observedStageTimeSeriesMap = new HashMap(); - private Map _priorRunoffTimeSeriesMap = new HashMap(); - private Map _sacDescriptorListMap = new HashMap(); - private List _sshpConfigList = null; - private TimeSeriesFileManager _reader = new TimeSeriesFileManager(); - private AppsDefaults _appsDefaults = null; - - private boolean _shouldSaveCrestMeasurement = true; - private static final String SHOULD_SAVE_FCST_CREST_TOKEN_NAME_STRING = "sshp_should_save_fcst_crest"; - - private static int _referenceCount = 0; - - private static CodeTimer _priorRunoffCodeTimer = new CodeTimer(); - -// ------------------------------------------------------------------------ - - -// ------------------------------------------------------------------------ - - public DataMgr() - { - - this(null, null); - _logger = new FileLogger("DataMgr.log"); - - _referenceCount++; - - if (_referenceCount > 1) - { - throw new Error("Singleton violation error!"); - } - - } - -// ------------------------------------------------------------------------ - - public DataMgr(String baseConnectionString, Logger logger) - { - super(); - - _appsDefaults = new AppsDefaults(); - - _db = new Database(); - _logger = logger; - - if (baseConnectionString == null) - { - baseConnectionString = getBaseConnectionString(); - } - - _db.connectWithDriverSearch(baseConnectionString); - - _shouldSaveCrestMeasurement = - _appsDefaults.getBoolean(SHOULD_SAVE_FCST_CREST_TOKEN_NAME_STRING, true); - - } - - // ------------------------------------------------------------------------ - - public String getDatabaseName() - { - String dbName = _db.getDatabaseName(); - return dbName; - } - - // ------------------------------------------------------------------------ - - private String getBaseConnectionString() - { - //this is used in testing mode, not the production mode - String connectionURLPart = "jdbc:informix-sqli://ds1-nhdr:1530/hd_ob5ounx:informixserver=ONLINE;"; - return connectionURLPart; - } - - // ------------------------------------------------------------------------ - public void disconnect() - { - _db.disconnect(); - } - - // ------------------------------------------------------------------------ - public void finalize() - { - disconnect(); - } - - // ------------------------------------------------------------------------ - public String getLocationName(String locationId) - { - String locationName = null; - - LocationDescriptor desc = getLocationDescriptor(locationId); - if (desc != null) - { - locationName = desc.getLocationName(); - } - return locationName; - } -// ------------------------------------------------------------------------ - private void loadLocationInfo(LocationDescriptor desc, String locationId) - { - String locationName = null; - - LocationRecord record = null; - LocationTable table = new LocationTable(_db); - - try - { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - - if (recordList.size() > 0) - { - record = (LocationRecord) recordList.get(0); - desc.setLocationName(record.getName()); - desc.setHsa(record.getHsa()); - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return; - } - // ------------------------------------------------------------------------ - - private String loadStreamName(String locationId) - { - String streamName = null; - - RiverstatRecord record = null; - RiverstatTable table = new RiverstatTable(_db); - - try - { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - - if (recordList.size() > 0) - { - record = (RiverstatRecord) recordList.get(0); - streamName = record.getStream(); - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return streamName; - } - // ------------------------------------------------------------------------ - - public LocationDescriptor loadLocationDescriptor(String locationId) - { - LocationDescriptor desc = new LocationDescriptor(); - String basinId = null; - String modelPreference = null; - SSHPConfig config = null; - String streamName = null; - - loadLocationInfo(desc, locationId); //load name and hsa from Location Table - - streamName = loadStreamName(locationId); - - config = getSSHPConfig(locationId); - if (config != null) - { - basinId = config.getBasinId(); - modelPreference = config.getModelPref(); - } - - desc.setId(locationId); - desc.setStreamName(streamName); - desc.setBasinId(basinId); - desc.setModelPreference(modelPreference); - - return desc; - } - - // ------------------------------------------------------------------------ - - public LocationDescriptor getLocationDescriptor(String locationId) - { - LocationDescriptor desc = null; - - desc = (LocationDescriptor) _locationDescriptorMap.get(locationId); - - if (desc == null) - { - desc = loadLocationDescriptor(locationId); - _locationDescriptorMap.put(locationId, desc); - } - - return desc; - } - -// ------------------------------------------------------------------------ - - public List loadAllSshpBasinIds() - { - - String header = "DataMgr.loadAllSshpBasinIds(): "; - - // This method just reads in all the valid basinIds from the SshpConfig table - // and returns a list of the basins - HashSet basinSet = new HashSet(); - List basinIdList = new ArrayList(); - - List recordList = null; - - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = null; - - String whereClause = null; - - try - { - - whereClause = " ORDER BY basin_id "; - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (SshpConfigRecord) recordList.get(i); - String basinId = record.getBasin_id(); - - if (! basinSet.contains(basinId)) - { - basinSet.add(basinId); - basinIdList.add(basinId); - } - - // _logger.log(header + "basinId = " + record.getBasin_id()); - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - return basinIdList; - } - -// ------------------------------------------------------------------------ - public boolean isLocationIdValidForSSHP(String locationId) - { - boolean isValid = false; - String header = "DataMgr.isLocationIdValidForSSHP():"; - List validLocationIdList = loadLocationIdsForForecasts(); - - if (validLocationIdList != null) - { - isValid = validLocationIdList.contains(locationId); - _logger.log(header + " locationId = " + locationId); - } - - return isValid; - } - -// ----------------------------------------------------------------------- - public List loadLocationIdsForForecasts() - { - // much of this method's select clause taken from Russ Erb's version - List locationIdList = new ArrayList(); - - List recordList = null; - - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - String whereClause = null; - - try - { - whereClause = " WHERE lid IN (SELECT lid FROM SshpConfig)" + - " AND lid IN (SELECT distinct(lid) FROM Rating) " + - " AND lid IN (SELECT distinct(lid) FROM UnitGraph) " + - " AND ((fs IS NOT NULL) OR (fq is NOT NULL)) ORDER BY lid "; - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (RiverstatRecord) recordList.get(i); - - locationIdList.add(record.getLid()); - // _locationNameMap.add(record.getLid(), record.get()); - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - return locationIdList; - } -// ------------------------------------------------------- - public void saveRatingCurve(RatingCurve ratingCurve) - { - RatingTable table = new RatingTable(_db); - - RatingRecord record = new RatingRecord(); - - record.setLid(ratingCurve.getLocationId()); - - try - { - - for (int i = 0; i < ratingCurve.getRatingPointCount(); i++) - { - RatingPoint point = ratingCurve.getRatingPoint(i); - record.setStage(point.getUnshiftedStage()); - record.setDischarge(point.getDischarge()); - - table.insertOrUpdate(record); - - } - } - catch (SQLException e) - { - logSQLException(e); - } - - - return; - - - } -// ------------------------------------------------------- - public RatingCurve loadRatingCurve(String locationId) - { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - - try - { - ratingRecordList = ratingTable.select("WHERE LID = '" + - locationId + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" + - locationId + "' AND active = 'T' ORDER BY date desc", 1 ); - - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId + "'"); - - //determine total amount of active - //rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) - { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList.get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - //System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - - //initialize the RatingCurve object with data from the database, including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) - { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - //done by addRatingPoint - //ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } //end for - - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) - { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList.get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord.getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } - catch (SQLException e) - { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } -// ------------------------------------------------------- - public UnitHydrograph loadUnitHydrograph(String locationId, String areaId, String modelName) - { - // String header = "DataMgr.loadUnitHydrograph(): "; - // System.out.println(header + "loading unit hydrograph for modelName = " + modelName); - int intervalInHours = 1; - UnitHydrograph unitHydrograph = new UnitHydrograph(MeasuringUnit.cfs, - intervalInHours); - unitHydrograph.setLocationId(locationId); - unitHydrograph.setRainfallRunoffModel(modelName); - - UnitGraphTable table = new UnitGraphTable(_db); - String whereClause = "WHERE lid = '" + locationId + "' AND " + - " area_id = '" + areaId + "' AND " + - " model = '" + modelName + "' AND " + - " dur = 1001 " + - " ORDER BY area_id, ordinal"; - - List recordList = null; - - try - { - - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(i); - - long relativeTime = (i * _millisPerHour); - RelTimeMeasurement measurement = new RelTimeMeasurement(record.getDischarge(), - relativeTime, - MeasuringUnit.cfs); - - unitHydrograph.addMeasurement(measurement); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return unitHydrograph; - - } //end getUnitHydrograph() - -// ------------------------------------------------------- - - private UnitHydrograph loadUnitHydrograph_unused(String locationId) - { - int intervalInHours = 1; - UnitHydrograph unitHydrograph = new UnitHydrograph( - MeasuringUnit.cfs, - intervalInHours); - unitHydrograph.setLocationId(locationId); - - UnitGraphTable table = new UnitGraphTable(_db); - String whereClause = "WHERE lid = '" + locationId + - " ORDER BY area_id, ordinal"; - - List recordList = null; - - try - { - String areaId = null; - - recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(0); - areaId = record.getArea_id(); - unitHydrograph.setAreaId(areaId); - } - - for (int i = 0; i < recordList.size(); i++) - { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(i); - - //if a unithydrograph for a different area, but the same location, - // ignore the later ones. - if (! areaId.equals(record.getArea_id())) - { - break; - } - - long relativeTime = (i * _millisPerHour); - RelTimeMeasurement measurement = new RelTimeMeasurement(record.getDischarge(), - relativeTime, - MeasuringUnit.cfs); - - unitHydrograph.addMeasurement(measurement); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - // System.out.println(header + "ugh = " + unitHydrograph); - - return unitHydrograph; - - } //end getUnitHydrograph() - -// ----------------------------------------------------------------------- - /* - private RegularTimeSeries _unused_getFileBasedPrecipTimeSeries(long endTime, - double valueScaling) - { - MeasuringUnit unit = MeasuringUnit.mm; - RegularTimeSeries ts = null; - double[] precipArray = null; - - try - { - - String fileName = "D:/Data/code/exampleCode/sacsma/rainfile"; - precipArray = DataFileReader.readPrecipArray(fileName); - - int hoursBack = precipArray.length; - - long startTime = endTime - (hoursBack * _millisPerHour); - startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, 1); - - - int intervalInHours = 1; - - - ts = new RegularTimeSeries(startTime, - endTime, - intervalInHours, - unit); - - - long millisPerInterval = (intervalInHours *_millisPerHour); - - - //System.out.println("DataMgr.getFileBasedPrecipTimeSeries(): precipArray.length = " + precipArray.length ); - - long currentTime = startTime; - for (int i = 0; i < precipArray.length; i++) - { - // System.out.println("DataMgr.getFileBasedPrecipTimeSeries(): i = " + i + - // " currentTime = " + DbTimeHelper.getStringFromLongTime(currentTime)); - - double newValue = precipArray[i]* valueScaling; - Measurement measurement = new Measurement( newValue, unit); - - ts.setMeasurementByTime(measurement, currentTime); - - currentTime += millisPerInterval; - } - } - catch(IOException e) - { - e.printStackTrace(); - } - - return ts; - } // end getFileBasedPrecipTimeSeries() - -// ------------------------------------------------------- - private RegularTimeSeries _unused_getFileBasedEvaporationTimeSeries(long timeShift, - double valueScaling) - { - MeasuringUnit unit = MeasuringUnit.mm; - RegularTimeSeries ts = null; - double[] evapArray = null; - - try - { - int hoursBack = 72; - long startTime = System.currentTimeMillis() - (hoursBack * _millisPerHour); - startTime = TimeHelper.truncateTimeInMillisToNearestHour(startTime, 1); - - startTime += timeShift; - - String fileName = "D:/Data/code/exampleCode/sacsma/evapfile"; - evapArray = DataFileReader.readEvapArray(fileName); - - int intervalInHours = 1; - long intervalInMillis = intervalInHours * _millisPerHour; - - long endTime = startTime + ( intervalInMillis * (evapArray.length -1)); - - ts = new RegularTimeSeries(startTime, - endTime, - intervalInHours, - unit); - long currentTime = startTime; - - long millisPerInterval = (intervalInHours *_millisPerHour); - - - //System.out.println("DataMgr.getFileBasedEvapTimeSeries(): precipArray.length = " + precipArray.length ); - - - for (int i = 0; i < evapArray.length; i++) - { - - currentTime = startTime + (i * millisPerInterval); - // System.out.println("DataMgr.getFileBasedPrecipTimeSeries(): i = " + i + - // " currentTime = " + DbTimeHelper.getStringFromLongTime(currentTime)); - - double newValue = evapArray[i]* valueScaling; - Measurement measurement = new Measurement( newValue, unit); - - ts.setMeasurementByTime(measurement, currentTime); - } - } - catch(IOException e) - { - e.printStackTrace(); - } - - return ts; - } // end getFileBasedEvaporationTimeSeries() -*/ -// ------------------------------------------------------- - public double loadThresholdRunoffValue(String locationId) - { - double value = MISSING; - try - { - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - String whereClause = "WHERE lid = '" + locationId + - "' AND threshold_runoff is not null"; - - List list = table.selectNRecords(whereClause, 1); - if (list.size() > 0) - { - record = (RiverstatRecord) list.get(0); - value = record.getThreshold_runoff(); - } - - } - catch(SQLException e) - { - logSQLException(e); - } - - if (value != MISSING) - { - _logger.log("DataMgr.getThresholdRunoffValue(): value = " + value); - } - - - return value; - } - -// ------------------------------------------------------- - public SigRiverLevels getSigRiverLevels(String locationId) - { - SigRiverLevels sigRiverLevels = (SigRiverLevels) _sigRiverLevelsMap.get(locationId); - - if (sigRiverLevels == null) - { - sigRiverLevels = setUpSigRiverLevels(locationId); - _sigRiverLevelsMap.put(locationId, sigRiverLevels); - } - - return sigRiverLevels; - } - -// ------------------------------------------------------- - - public SigRiverLevels setUpSigRiverLevels(String locationId) - { - SigRiverLevels sigRiverLevels = null; - // if needed, retrieve and cache the data - // then return the value - - sigRiverLevels = loadSigRiverLevels(locationId); - - boolean stagesAreMissing = false; - if (! sigRiverLevels.hasFloodStage() || ! sigRiverLevels.hasActionStage()) - { - stagesAreMissing = true; - } - - // if the site is set up to use discharge (flow) instead of stage, - // convert from flow to stage and populate the floodStage and actionStage - //(if possible), - // so that they are available to other parts of the program - if (stagesAreMissing) - { - RatingCurve ratingCurve = getRatingCurve(locationId); - if (sigRiverLevels.hasFloodFlow()) - { - double floodFlow = sigRiverLevels.getFloodFlow(); - double floodStage = ratingCurve.getStageFromDischarge(floodFlow); - sigRiverLevels.setFloodStage(floodStage); - } - if (sigRiverLevels.hasActionFlow()) - { - double actionFlow = sigRiverLevels.getActionFlow(); - double actionStage = ratingCurve.getStageFromDischarge(actionFlow); - sigRiverLevels.setActionStage(actionStage); - } - } - - - - return sigRiverLevels; - } - -// ------------------------------------------------------- - public RatingCurve getRatingCurve(String locationId) - { - - RatingCurve ratingCurve = (RatingCurve) _ratingCurveMap.get(locationId); - - if (ratingCurve == null) - { - - ratingCurve = loadRatingCurve(locationId); - - _ratingCurveMap.put(locationId, ratingCurve); - } - - return ratingCurve; - - } - - -// ------------------------------------------------------- - public IrregularTimeSeries getCachedObservedStageTimeSeriesFromStageOrDischarge(String locationId, boolean reload) - { - IrregularTimeSeries observedStageTimeSeries = (IrregularTimeSeries) _observedStageTimeSeriesMap.get(locationId); - - - if ((observedStageTimeSeries == null) || (reload) ) - { - observedStageTimeSeries = loadObservedStageTimeSeriesFromStageOrDischarge(locationId); - _observedStageTimeSeriesMap.put(locationId, observedStageTimeSeries); - } - - return observedStageTimeSeries; - } - -// ------------------------------------------------------- - public IrregularTimeSeries loadObservedStageTimeSeriesFromStageOrDischarge(String locationId) - { - IrregularTimeSeries observedStageTimeSeries = null; - - if (getSigRiverLevels(locationId).useStage()) - { - observedStageTimeSeries = loadObservedStageTimeSeries(locationId); - } - else //use flow and then convert it - { - IrregularTimeSeries observedDischargeTimeSeries = null; - observedDischargeTimeSeries = loadObservedDischargeTimeSeries(locationId); - if (observedDischargeTimeSeries.getMeasurementCount() > 0) - { - observedStageTimeSeries = getRatingCurve(locationId).getStageTimeSeries(observedDischargeTimeSeries); - } - else //there is no discharge time series - { - observedStageTimeSeries = loadObservedStageTimeSeries(locationId); - } - } - - return observedStageTimeSeries; - } - -// ------------------------------------------------------- - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId) - { - String header = "DataMgr.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(MeasuringUnit.feet); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - _millisPerYear; - long lateTime = currentTime + _millisPerYear; - - /* - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + pe + "'" + - " AND dur = " + duration + - " AND ts = '" + typeSource + "'" + - " AND extremum = 'Z' ORDER by obstime ASC"; - */ - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe <> 'HI' " + - " AND dur = 0" + - " AND extremum = 'Z'" + - " AND quality_code >= " + _questionable_bad_threshold; - - // System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (HeightRecord) recordList.get(i); - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - MeasuringUnit.feet); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - - } -// ------------------------------------------------------- - public IrregularTimeSeries loadObservedStageTimeSeriesOld(String locationId) - { - //return the best observed stage time series available, that - // based on ts_rank usage - final String header = "DataMgr.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = null; - - String pe = "HG"; - int duration = 0; - - String[] preferredObsTsArray = loadPreferredObsTypeSourceArray(locationId, pe, duration); - - boolean success = false; - - for (int i = 0; i < preferredObsTsArray.length && !success; i++) - { - String ts = preferredObsTsArray[i]; - System.out.println(header + "locationId = " + locationId + " ts = " + ts); - stageTimeSeries = loadObservedStageTimeSeriesByTsOld(locationId, pe, duration, ts); - if (stageTimeSeries.getMeasurementCount() > 0) - { - System.out.println(header + "found " + stageTimeSeries.getMeasurementCount() + " records."); - success = true; - } - } - - return stageTimeSeries; - } - - -// ------------------------------------------------------- - -// ------------------------------------------------------- - public IrregularTimeSeries loadObservedStageTimeSeriesByTsOld(String locationId, String pe, int duration, String typeSource) - { - String header = "DataMgr.loadObservedStageTimeSeriesByTs(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(MeasuringUnit.feet); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - _millisPerYear; - long lateTime = currentTime + _millisPerYear; - //String earlyTimeString = DbTimeHelper.getDateTimeStringFromLongTime(earlyTime); - //String lateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(lateTime); - String earlyTimeString = "2001-01-01 00:00:00"; - String lateTimeString = "3001-01-01 00:00:00"; - - /* - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + pe + "'" + - " AND dur = " + duration + - " AND ts = '" + typeSource + "'" + - " AND extremum = 'Z' ORDER by obstime ASC"; - */ - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + pe + "'" + - " AND dur = " + duration + - " AND ts = '" + typeSource + "'" + - " AND extremum = 'Z'" + - " AND shef_qual_code != 'F' "; - - - - try - { - CodeTimer timer = new CodeTimer(); - timer.start(); - _db.getStatement().execute("SET EXPLAIN ON"); - recordList = table.select(whereClause); - _db.getStatement().execute("SET EXPLAIN OFF"); - timer.stop(header + "Height select with " + whereClause + "\n took "); - - for (int i = 0; i < recordList.size(); i++) - { - record = (HeightRecord) recordList.get(i); - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - MeasuringUnit.feet); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - - } - - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadObservedDischargeTimeSeries(String locationId) - - { - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries( - MeasuringUnit.cfs); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - - String whereClause = - " WHERE lid = '" + locationId + "'" + - " AND dur = 0" + - " AND extremum = 'Z'" + - " AND quality_code >= " + _questionable_bad_threshold; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (DischargeRecord) recordList.get(i); - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), MeasuringUnit.cfs); - - dischargeTimeSeries.insertMeasurement(measurement); - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return dischargeTimeSeries; - - } - - -// ----------------------------------------------------------------------------------- - public IrregularTimeSeries loadObservedDischargeTimeSeriesByTsOld( - String locationId, - String pe, - int duration, - String typeSource) - { - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries( - MeasuringUnit.cfs); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - - String whereClause = " WHERE lid = '" + locationId + "'" - + " AND pe = '" + pe + "'" + " AND dur = " + duration - + " AND ts = '" + typeSource + "'" - + " AND extremum = 'Z' ORDER by obstime ASC"; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (DischargeRecord) recordList.get(i); - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), MeasuringUnit.cfs); - - dischargeTimeSeries.insertMeasurement(measurement); - } - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return dischargeTimeSeries; - - } - - -// ------------------------------------------------------- - public IrregularTimeSeries loadObservedDischargeTimeSeriesOld(String locationId) - { - //return the best observed discharge time series available, that - // based on ts_rank usage - - IrregularTimeSeries dischargeTimeSeries = null; - - String pe = "QR"; - int duration = 0; - - String[] preferredObsTsArray = loadPreferredObsTypeSourceArray(locationId, pe, duration); - - boolean success = false; - - for (int i = 0; i < preferredObsTsArray.length && !success; i++) - { - String ts = preferredObsTsArray[i]; - dischargeTimeSeries = loadObservedDischargeTimeSeriesByTsOld(locationId, pe, duration, ts); - if (dischargeTimeSeries.getMeasurementCount() > 0) - { - success = true; - } - } - - return dischargeTimeSeries; - } - - -// ------------------------------------------------------- - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, String pe) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "DataMgr.loadFcstStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + pe + "'" + - " ORDER BY basistime DESC "; - - long originalBasisTime = 0; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - - - record = (FcstHeightRecord) recordList.get(i); - - if (i == 0) - { - originalBasisTime = record.getBasistime(); - } - else - { - if (record.getBasistime() != originalBasisTime) - { - break; - } - } - -// don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - -// System.out.println(header + "measurement = " + measurement); - - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - } - -// ----------------------------------------------------------------------------------- - - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - String pe) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstDischargeTimeSeries(): "; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" +pe + "'" + - " ORDER BY basistime DESC "; - - long originalBasisTime = 0; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - - - record = (FcstDischargeRecord) recordList.get(i); - - if (i == 0) - { - originalBasisTime = record.getBasistime(); - } - else - { - if (record.getBasistime() != originalBasisTime) - { - break; - } - } - -// don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - -// System.out.println(header + "measurement = " + measurement); - - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return dischargeTimeSeries; -} - - - // --------------------------------------------------------------------------------------------- - - public Measurement _unused_getHeightMeasurement2(String locationId) - { - RiverStatusTable table = new RiverStatusTable(_db); - RiverStatusRecord record = null; - List recordList = null; - Measurement measurement = null; - - String whereClause = " WHERE lid = '" + locationId + "'"; - - try - { - recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - record = (RiverStatusRecord) recordList.get(0); - - measurement = new Measurement(record.getValue(), MeasuringUnit.feet); - } - } - catch(Exception e) - { - System.err.println("error retrieving RiverStatusRecord " + whereClause); - e.printStackTrace(); - } - - return measurement; - - - } - -// ------------------------------------------------------- - - public SacSmaParameters loadSacSmaParameters(String basinId, long modelRunStartTime) - { - String header = "DataMgr.getSacSmaParameters(): "; - SacSmaParameters sacParams = null; - - - SacSmaParamsTable table = new SacSmaParamsTable(_db); - - String whereClause = "WHERE basin_id = '" + basinId + "' ORDER by validtime DESC"; - - try - { - List recordList = table.select(whereClause); - - - for (int i = 0 ; i < recordList.size(); i++) - { - - SacSmaParamsRecord record = (SacSmaParamsRecord) recordList.get(i); - - if (record.getValidtime() <= modelRunStartTime) - { - //String dateTime = DbTimeHelper.getDateTimeStringFromLongTime(record.getValidtime()); - - // System.out.println(header + " validtime found = " + dateTime); - sacParams = new SacSmaParameters(); - setSacSmaParametersFromRecord(sacParams, record); - break; - } - // else, keep looking for a record before the modelRunStartTime - } - } - catch(SQLException e) - { - logSQLException(e); - } - return sacParams; - } - -// ------------------------------------------------------- - public void setSacSmaParametersFromRecord(SacSmaParameters sacParams, - SacSmaParamsRecord record) - { - - sacParams.setBasinId(record.getBasin_id()); - sacParams.setSource(record.getSource()); - sacParams.setValidTime(record.getValidtime()); - sacParams.setPostingTime(record.getPostingtime()); - - sacParams.setUztwm(record.getUztwm()); - sacParams.setUzfwm(record.getUzfwm()); - sacParams.setUzk(record.getUzk()); - - sacParams.setPctim(record.getPctim()); - - sacParams.setAdimp(record.getAdimp()); - - sacParams.setRiva(record.getRiva()); - - sacParams.setZperc(record.getZperc()); - sacParams.setRexp(record.getRexp()); - sacParams.setLztwm(record.getLztwm()); - sacParams.setLzfsm(record.getLzfsm()); - - sacParams.setLzfpm(record.getLzfpm()); - - sacParams.setLzsk(record.getLzsk()); - sacParams.setLzpk(record.getLzpk()); - - sacParams.setPfree(record.getPfree()); - - sacParams.setRserv(record.getRserv()); - sacParams.setSide(record.getSide()); - - sacParams.setPeadj(record.getPeadj()); - sacParams.setPxadj(record.getPxadj()); - sacParams.setEfc(record.getEfc()); - - - return; - } -// ------------------------------------------------------- - public SacSmaState loadSacSmaState(String basinId, long modelRunStartTime) - { - SacSmaState sacState = loadSacSmaState(basinId, null, modelRunStartTime); - - return sacState; - } - -// ------------------------------------------------------- - - - public SacSmaState loadSacSmaState(String basinId, String source, long modelRunStartTime) - { - // returns null when no state is found - // String header = "DataMgr.loadSacSmaState(): "; - SacSmaState sacState = null; - SacSmaStateTable table = new SacSmaStateTable(_db); - - String sourceClause = null; - - if (source == null) - { - sourceClause = ""; - } - else // source is not null - { - sourceClause = " AND source = '" + source + "'"; - } - - String whereClause = "WHERE basin_id = '" + basinId + "'" + sourceClause + " ORDER by validtime DESC"; - - - try - { - List recordList = table.select(whereClause); - - for (int i = 0 ; i < recordList.size(); i++) - { - - SacSmaStateRecord record = (SacSmaStateRecord) recordList.get(i); - - if (record.getValidtime() <= modelRunStartTime) - { - String dateTime = DbTimeHelper.getDateTimeStringFromLongTime(record.getValidtime()); - - // System.out.println(header + " validtime found = " + dateTime); - - sacState= new SacSmaState(); - setSacSmaStateFromRecord(sacState, record); - break; - } - //else, keep looking for a record with a validtime before the modelRunStartTime - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return sacState; - } - - //------------------------------------------------------------------------------------------------------------------ - - - public SacSmaState loadOldestSacSmaState(String basinId, String source) - { - // returns null when no state is found - String header = "DataMgr.loadOldestSacSmaState(): "; - SacSmaState sacState = null; - SacSmaStateTable table = new SacSmaStateTable(_db); - - String sourceClause = null; - - if (source == null) - { - sourceClause = ""; - } - else // source is not null - { - sourceClause = " AND source = '" + source + "'"; - } - - String whereClause = "WHERE basin_id = '" + basinId + "'" + sourceClause + " ORDER by validtime ASC"; - - - try - { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - SacSmaStateRecord record = (SacSmaStateRecord) recordList.get(0); - - sacState= new SacSmaState(); - setSacSmaStateFromRecord(sacState, record); - } - - } - catch(SQLException e) - { - logSQLException(e); - } - - return sacState; - } - - - //------------------------------------------------------------------------------------------------------------------ - - public SacSmaState oldLoadSacSmaState(String basinId, long modelRunStartTime) - { - // returns null when no state is found - String header = "DataMgr.getSacSmaState(): "; - SacSmaState sacState = null; - - SacSmaStateTable table = new SacSmaStateTable(_db); - - String whereClause = "WHERE basin_id = '" + basinId + "' ORDER by validtime DESC"; - - try - { - List recordList = table.select(whereClause); - - for (int i = 0 ; i < recordList.size(); i++) - { - - SacSmaStateRecord record = (SacSmaStateRecord) recordList.get(i); - - if (record.getValidtime() <= modelRunStartTime) - { - String dateTime = DbTimeHelper.getDateTimeStringFromLongTime(record.getValidtime()); - - System.out.println(header + " validtime found = " + dateTime); - - sacState= new SacSmaState(); - setSacSmaStateFromRecord(sacState, record); - break; - } - //else, keep looking for a record with a validtime before the modelRunStartTime - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return sacState; - } - -// ------------------------------------------------------- - public long loadTimeOfBestRecentSacState(String locationId) - { - long bestTime = 0; - - long hourLimit = 25 ; // a little over 24 hours - - long preferredSourceValidTime = 0; - long allSourceValidTime = 0; - - // - SSHPConfig config = this.getSSHPConfig(locationId); - String basinId = null; - String preferredSource = null; - - if (config != null) - { - basinId = config.getBasinId(); - preferredSource = config.getSourcePref(); - } - else - { - throw new Error("DataMgr.getTimeOfBestRecentState(): no SSHPConfig record for locationId = " + locationId); - } - - String preferredSourceWhereClause = " WHERE basin_id = '" + basinId + "' " + - " AND source = '" + preferredSource + "' " + - " ORDER BY validtime DESC "; - - String allSourceWhereClause = " WHERE basin_id = '" + basinId + "' " + - " ORDER BY validtime DESC "; - - - SacSmaStateTable table = new SacSmaStateTable(_db); - - try - { - - //select the most recent record with the preferred source - List preferredRecordList = table.selectNRecords(preferredSourceWhereClause,1); - - if (preferredRecordList.size() > 0) - { - SacSmaStateRecord record = (SacSmaStateRecord) preferredRecordList.get(0); - - preferredSourceValidTime = record.getValidtime(); - } - - - // select all the records, regardless of source - List allRecordList = table.selectNRecords(allSourceWhereClause,1); - - if (allRecordList.size() > 0) - { - SacSmaStateRecord record = (SacSmaStateRecord) allRecordList.get(0); - - allSourceValidTime = record.getValidtime(); - } - - //get current system time - long currentTime = System.currentTimeMillis(); - - - // select the preferredSourceValidTime as the best if it is within the time window - long diffTime = currentTime - preferredSourceValidTime; - - if (diffTime < _millisPerHour * hourLimit) - { - bestTime = preferredSourceValidTime; - } - else //the preferred is not available, so use the next best thing - { - bestTime = allSourceValidTime; - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - - return bestTime; - } -// ------------------------------------------------------- - public SacSmaState loadBestRecentSacState(String locationId) - { - - SacSmaState preferredSourceState = null; - SacSmaState allSourceState = null; - SacSmaState bestState = null; - - long bestTime = 0; - - long hourLimit = 25 ; // a little over 24 hours - - long preferredSourceValidTime = 0; - long allSourceValidTime = 0; - - // - SSHPConfig config = this.getSSHPConfig(locationId); - String basinId = null; - String preferredSource = null; - - if (config != null) - { - basinId = config.getBasinId(); - preferredSource = config.getSourcePref(); - } - else - { - throw new Error("DataMgr.loadBestRecentSacState(): no SSHPConfig record for locationId = " + locationId); - } - - String preferredSourceWhereClause = " WHERE basin_id = '" + basinId + "' " + - " AND source = '" + preferredSource + "' " + - " ORDER BY validtime DESC "; - - String allSourceWhereClause = " WHERE basin_id = '" + basinId + "' " + - " ORDER BY validtime DESC, source "; - - - SacSmaStateTable table = new SacSmaStateTable(_db); - - try - { - - //select the most recent record with the preferred source - List preferredRecordList = table.selectNRecords(preferredSourceWhereClause,1); - - if (preferredRecordList.size() > 0) - { - SacSmaStateRecord record = (SacSmaStateRecord) preferredRecordList.get(0); - - preferredSourceState = getSacSmaStateFromRecord(record); - preferredSourceValidTime = record.getValidtime(); - } - - - // select all the records, regardless of source - List allRecordList = table.selectNRecords(allSourceWhereClause,1); - - if (allRecordList.size() > 0) - { - SacSmaStateRecord record = (SacSmaStateRecord) allRecordList.get(0); - allSourceState = getSacSmaStateFromRecord(record); - - allSourceValidTime = record.getValidtime(); - } - - //get current system time - long currentTime = System.currentTimeMillis(); - - - // select the preferredSourceValidTime as the best if it is within the time window - long diffTime = currentTime - preferredSourceValidTime; - - if (diffTime < _millisPerHour * hourLimit) - { - bestState = preferredSourceState; - bestTime = preferredSourceValidTime; - } - else //the preferred is not available, so use the next best thing - { - bestState = allSourceState; - bestTime = allSourceValidTime; - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - - - return bestState; - } -// ------------------------------------------------------- - - - public SacSmaState loadBestRecentSacStateForForecasts(String locationId) - { - SacSmaState state = null; - Map stateMap = new HashMap(); - - - long bestTime = 0; - - // load configuration data - SSHPConfig config = this.getSSHPConfig(locationId); - - String basinId = null; - boolean useAdjustment = false; - - if (config != null) - { - basinId = config.getBasinId(); - useAdjustment = config.useBlend(); - } - else - { - throw new Error("DataMgr.loadBestRecentSacStateForForecasts(): no SSHPConfig record for locationId = " + locationId); - } - - SacSmaStateTable table = new SacSmaStateTable(_db); - - String allSourceWhereClause = " WHERE basin_id = '" + basinId + "' " + - " ORDER BY validtime DESC, source "; - - - long latestValidTime = 0; - int maxRecords = 10; - - try - { - // select all the records, regardless of source - List allRecordList = table.selectNRecords(allSourceWhereClause, maxRecords); - - int recordCount = 0; - - // put all the records into a map - // also, record the time of the first record. - for (SacSmaStateRecord record : allRecordList) - { - state = getSacSmaStateFromRecord(record); - - String key = getStateMapKeyFromState(state); - - stateMap.put(key, state); - - if (recordCount == 0) - { - latestValidTime = state.getValidTime(); //use the first record to set the latest time - } - - recordCount++; - - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - - SacSmaState bestState = getBestState(stateMap, latestValidTime); - - - return bestState; - } -// ------------------------------------------------------- - private SacSmaState getBestState(Map stateMap, long latestValidTime) - { - //This method determines what is the best SAC-SMA state to use for the background forecast. - SacSmaState bestState = null; - List sshpSourceList = new ArrayList(); - - sshpSourceList.add(SSHPSource.ADJUSTED_VAR); - sshpSourceList.add(SSHPSource.RFC); - sshpSourceList.add(SSHPSource.UNADJUSTED_VAR); - sshpSourceList.add(SSHPSource.SSHP_UPDATER); - - - //run through the preferred order of state sources - // when find one that matches what I want, set it and break; - for (SSHPSource sshpSource : sshpSourceList) - { - SacSmaState state = getStateBySSHPSource(sshpSource, stateMap, latestValidTime); - if (state != null) - { - bestState = state; - break; - } - - } - - return bestState; - } -// ------------------------------------------------------- - private SacSmaState getStateBySSHPSource(SSHPSource sshpSource, - Map stateMap, - long latestValidTime) - { - String key = getStateMapKey(sshpSource.getSacSmaSource(), latestValidTime); - - SacSmaState state = stateMap.get(key); - - return state; - } - -// ------------------------------------------------------- - - private String getStateMapKeyFromState(SacSmaState state) - { - - return getStateMapKey(state.getSource(), state.getValidTime()); - } - - // ------------------------------------------------------- - - private String getStateMapKey(String source, long validTime) - { - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime(validTime); - - String key = source + "|" + validTimeString; - - return key; - } -// ------------------------------------------------------- - - public long getTimeOfBestRecentFFH(String locationId, String basinId) - { - long bestTime = 0; - - - - long currentTime = System.currentTimeMillis(); - AbsTimeMeasurement ffhMeasurement = loadMostCurrentFfhMeasurement(locationId, basinId, currentTime); - if (ffhMeasurement != null) - { - bestTime = ffhMeasurement.getTime(); - } - - return bestTime; - } - -// ------------------------------------------------------- - - public long getLatestHourTime() - { - return TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - } - -// ------------------------------------------------------- - - public void setSacSmaStateFromRecord(SacSmaState sacState, SacSmaStateRecord record) - { - - - sacState.setBasinId(record.getBasin_id()); - sacState.setSource(record.getSource()); - sacState.setBasisTime(record.getBasistime()); - sacState.setValidTime(record.getValidtime()); - sacState.setPostingTime(record.getPostingtime()); - - - sacState.setUztwc(record.getUztwc()); - sacState.setUzfwc(record.getUzfwc()); - sacState.setLztwc(record.getLztwc()); - sacState.setLzfsc(record.getLzfsc()); - sacState.setLzfpc(record.getLzfpc()); - sacState.setAdimc(record.getAdimc()); - - // System.out.println("DataMgr.setSacSmaStageFromRecord() sacState = " + sacState); - - return; - } - - -// ------------------------------------------------------- -/* - - public void testGeneratedCodeWithNulls() - { - TestHeightTable heightTable = new TestHeightTable(_db); - TestHeightRecord record = null; - List recordList = null; - CodeTimer timer = new CodeTimer(); - - try - { - timer.start(); - recordList = heightTable.select("where lid = 'BLUO2' order by obstime DESC "); - timer.stop("after Select from Height Table"); - - if (recordList.size() > 0) - { - record = (TestHeightRecord) recordList.get(0); - System.out.println("1 retrieved record = " + record); - - heightTable.delete("Where lid = 'CHIP1'"); - heightTable.delete("Where lid = 'CHIP3'"); - - record.setLid("CHIP1"); - - heightTable.insert(record); - - - recordList = heightTable.select("where lid = 'CHIP1'" ); - record = (TestHeightRecord) recordList.get(0); - - System.out.println("2 retrieved record = " + record); - - TestHeightRecord newRecord = new TestHeightRecord(record); - - System.out.println("3 after copy record orig = " + record); - System.out.println("4 after copy record new = " + newRecord); - - newRecord.setLid("CHIP3"); - newRecord.setNullDur(true); - - heightTable.update(record, newRecord ); - - recordList = heightTable.select("where lid = '" + newRecord.getLid() + "'" ); - record = (TestHeightRecord) recordList.get(0); - - System.out.println("5 retrieved updated record with null Dur = " + record); - - // insertOrUpdate Test - newRecord.setLid("Chip4"); - heightTable.insertOrUpdate(newRecord); - - recordList = heightTable.select("where lid = '" + newRecord.getLid() + "'" ); - record = (TestHeightRecord) recordList.get(0); - - System.out.println("6 retrieved insertedOrUpdated record = " + record); - - - timer.start(); - Measurement height2Measurement = - _dataMgr.getHeightMeasurementWithShortCircuit(_locationId); - timer.stop("AppController.runModel(): Short Circuited Height retrieval took"); - - - timer.start(); - heightMeasurement = _dataMgr.getHeightMeasurement(_locationId); - timer.stop("AppController.runModel(): Normal Height retrieval took"); - heightMeasurement.convert(MeasuringUnit.feet); - - - - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - } - */ -// ------------------------------------------------------- - public void testGeneratedCode() - { - HeightTable heightTable = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - CodeTimer timer = new CodeTimer(); - - try - { - timer.start(); - recordList = heightTable.select("where lid = 'BLUO2' order by obstime DESC "); - timer.stop("after Select from Height Table"); - - if (recordList.size() > 0) - { - record = (HeightRecord) recordList.get(0); - System.out.println("1 retrieved record = " + record); - - heightTable.delete("Where lid = 'CHIP1'"); - heightTable.delete("Where lid = 'CHIP3'"); - - record.setLid("CHIP1"); - - heightTable.insert(record); - - recordList = heightTable.select("where lid = 'CHIP1'" ); - record = (HeightRecord) recordList.get(0); - - System.out.println("2 retrieved record = " + record); - - HeightRecord newRecord = new HeightRecord(record); - System.out.println("3 after copy record orig = " + record); - System.out.println("4 after copy record new = " + newRecord); - - newRecord.setLid("CHIP3"); - - heightTable.update(record, newRecord ); - - recordList = heightTable.select("where lid = '" + newRecord.getLid() + "'" ); - record = (HeightRecord) recordList.get(0); - - System.out.println("5 retrieved updated record = " + record); - - // insertOrUpdate Test - newRecord.setLid("Chip4"); - heightTable.insertOrUpdate(newRecord); - - recordList = heightTable.select("where lid = '" + newRecord.getLid() + "'" ); - record = (HeightRecord) recordList.get(0); - - System.out.println("6 retrieved insertedOrUpdated record = " + record); - - /* - timer.start(); - Measurement height2Measurement = - _dataMgr.getHeightMeasurementWithShortCircuit(_locationId); - timer.stop("AppController.runModel(): Short Circuited Height retrieval took"); - - - timer.start(); - heightMeasurement = _dataMgr.getHeightMeasurement(_locationId); - timer.stop("AppController.runModel(): Normal Height retrieval took"); - heightMeasurement.convert(MeasuringUnit.feet); - - **/ - - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - } -// ------------------------------------------------------- - - -// ------------------------------------------------------- - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } - -// ------------------------------------------------------- - public SigRiverLevels loadSigRiverLevels(String locationId) - { - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (RiverstatRecord) recordList.get(0); - - String primaryPe = record.getPrimary_pe(); - if (primaryPe == null) - { - primaryPe = "HG"; - } - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - - levels = createSigRiverLevels(locationId, - primaryPe, - floodStage, - actionStage, - floodFlow, - actionFlow); - - loadFloodCategories(levels); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return levels; - } - -// ------------------------------------------------------- - private SigRiverLevels createSigRiverLevels(String locationId, String primaryPe, - double floodStage, double actionStage, - double floodFlow, double actionFlow) - { - RatingCurve ratingCurve = getRatingCurve(locationId); - SigRiverLevels levels = null; - - boolean isNullFloodStage = DbTable.isNull(floodStage); - boolean isNullActionStage = DbTable.isNull(actionStage); - boolean isNullFloodFlow = DbTable.isNull(floodFlow); - boolean isNullActionFlow = DbTable.isNull(actionFlow); - - - floodStage = getStage(locationId, floodFlow, floodStage); - actionStage = getStage(locationId, actionFlow, actionStage); - - - levels = new SigRiverLevels(locationId, - primaryPe, - floodStage, - actionStage, - floodFlow, - actionFlow); - - return levels; - } - - -// ------------------------------------------------------- - private double getStage(String locationId, double flow, double stage) - { - if ( (DbTable.isNull(stage)) && (! DbTable.isNull(flow)) ) - { - RatingCurve ratingCurve = getRatingCurve(locationId); - stage = ratingCurve.getStageFromDischarge(flow); - } - - return stage; - } - - // ------------------------------------------------------- - - - private void loadFloodCategories(SigRiverLevels levels) - { - FloodcatTable table = new FloodcatTable(_db); - FloodcatRecord record = null; - - String whereClause = "WHERE lid = '" + levels.getLocationId() + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (FloodcatRecord) recordList.get(0); - - levels.setMinorFloodFlow(record.getMinor_flow()); - levels.setModerateFloodFlow(record.getModerate_flow()); - levels.setMajorFloodFlow(record.getMajor_flow()); - - - double minorStage = getStage(levels.getLocationId(), record.getMinor_flow(), record.getMinor_stage()); - double moderateStage = getStage(levels.getLocationId(), record.getModerate_flow(), record.getModerate_stage()); - double majorStage = getStage(levels.getLocationId(), record.getMajor_flow(), record.getMajor_stage()); - - - levels.setMinorFloodStage(minorStage); - levels.setModerateFloodStage(moderateStage); - levels.setMajorFloodStage(majorStage); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return; - } - -// ------------------------------------------------------- - public String[] loadPhysicalElementArray(char firstLetterOfPhysicalElement) - { - String[] peArray = null; - - ShefPeTable table = new ShefPeTable(_db); - ShefPeRecord record = null; - - String primaryPe = null; - - String whereClause = "WHERE pe LIKE '" + - firstLetterOfPhysicalElement + - "%' ORDER BY pe"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - for (int i = 0; i < recordList.size(); i++) - { - record = (ShefPeRecord) recordList.get(i); - if (i == 0) - { - peArray = new String[recordList.size()]; - } - peArray[i] = record.getPe(); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return peArray; - } - -// ------------------------------------------------------- - public String loadPrimaryPe(String locationId) - { - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - String primaryPe = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (RiverstatRecord) recordList.get(0); - - primaryPe = record.getPrimary_pe(); - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return primaryPe; - } - -// ------------------------------------------------------- - - public long getLatestObsTimeForMAPPreprocessor() - { - ArealObsTable table = new ArealObsTable(_db); - - ArealObsRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - long latestPostingTime = 0; - - //String whereClause = "WHERE product_id like 'SSHP%' " + - // " ORDER BY postingtime DESC"; - - String whereClause = "WHERE product_id = 'SSHP_MAP' " + - " ORDER BY obstime DESC"; - - try - { - recordList = table.selectNRecords(whereClause, 1); - - if (recordList.size() > 0) - { - record = (ArealObsRecord ) recordList.get(0); - // latestPostingTime = record.getPostingtime(); - latestPostingTime = record.getObstime(); - } - - } - catch(SQLException e) - { - logSQLException(e); - } - - return latestPostingTime; - } - - -// ----------------------------------------------------------------------------------- - public long getLatestPostingTimeForMAPPreprocessor() - { - ArealObsTable table = new ArealObsTable(_db); - - ArealObsRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - long latestPostingTime = 0; - - String whereClause = "WHERE product_id like 'SSHP_MAP' " + - " ORDER BY postingtime DESC"; - - try - { - recordList = table.selectNRecords(whereClause, 1); - - if (recordList.size() > 0) - { - record = (ArealObsRecord ) recordList.get(0); - latestPostingTime = record.getPostingtime(); - // latestPostingTime = record.getObstime(); - } - - } - catch(SQLException e) - { - logSQLException(e); - } - - return latestPostingTime; - } - - -// ----------------------------------------------------------------------------------- - - - public RegularTimeSeries loadObsMapTimeSeriesFromDb(String areaId) - { - String header = "DataMgr.loadObsMapTimeSeriesFromDb(): "; - - MeasuringUnit precipUnit = MeasuringUnit.inches; - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - String whereClause = "WHERE lid = '" + areaId + "' AND dur = 1001 AND pe='PP' AND ts = 'PM' " + - " ORDER BY obstime ASC"; - - // System.out.println(header + " where string = " + whereClause); - - long startTime = 0; - long endTime = 0; - - try - { - recordList = table.select(whereClause); - - - if (recordList.size() > 0) - { - record = (ArealObsRecord ) recordList.get(0); - startTime = record.getObstime(); - - record = (ArealObsRecord ) recordList.get(recordList.size() - 1); - endTime = record.getObstime(); - } - else - { - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - } - - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - - - // System.out.println(header + " startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - // " endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - - - - // String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - //String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - for (int i = 0; i < recordList.size() ; i++) - { - - record = (ArealObsRecord) recordList.get(i); - double value = record.getValue(); - long time = record.getObstime(); - - if ((time >= startTime) && (time <= endTime)) - { - Measurement m = new Measurement(value, precipUnit); - - ts.setMeasurementByTime(m, time); - } - else if (time > endTime) - { - break; //done, since we went past the last one that we want - } - - } //end for - - } //end try - - catch(SQLException e) - { - logSQLException(e); - - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - } - - - return ts; - - } -// ---------------------------------------------------------------------------------- - - public RegularTimeSeries loadObsMapTimeSeriesFromDb_old(String areaId) - { -// we don't use ProcValue anymore for this; we use ArealObsPrecip. - String header = "DataMgr.loadObsMapTimeSeriesFromDb(): "; - - MeasuringUnit precipUnit = MeasuringUnit.inches; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - String whereClause = "WHERE lid = '" + areaId + "' AND dur = 1001 AND pe='PP' AND ts = 'PM' " + - " ORDER BY obstime ASC"; - - // System.out.println(header + " where string = " + whereClause); - - long startTime = 0; - long endTime = 0; - - try - { - recordList = table.select(whereClause); - - - if (recordList.size() > 0) - { - record = (ProcValueRecord ) recordList.get(0); - startTime = record.getObstime(); - - record = (ProcValueRecord ) recordList.get(recordList.size() - 1); - endTime = record.getObstime(); - } - else - { - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - } - - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - - - // System.out.println(header + " startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - // " endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - - - - // String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - //String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - for (int i = 0; i < recordList.size() ; i++) - { - - record = (ProcValueRecord) recordList.get(i); - double value = record.getValue(); - long time = record.getObstime(); - - if ((time >= startTime) && (time <= endTime)) - { - Measurement m = new Measurement(value, precipUnit); - - ts.setMeasurementByTime(m, time); - } - else if (time > endTime) - { - break; //done, since we went past the last one that we want - } - - } //end for - - } //end try - - catch(SQLException e) - { - logSQLException(e); - - endTime = getLatestHourTime(); - startTime = endTime - (3 * 24 * _millisPerHour); - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - } - - - return ts; - - } -// ------------------------------------------------------- - -// ------------------------------------------------------- - private RegularTimeSeries loadFcstMapTimeSeriesByTs(String areaId, long forecastStartTime, String typeSource, BooleanHolder successHolder) - { - String header = "DataMgr.loadFcstMapTimeSeriesByTs(): "; - - MeasuringUnit precipUnit = MeasuringUnit.inches; - - // System.out.println(header + "running"); - - ArealFcstTable table = new ArealFcstTable(_db); - ArealFcstRecord record = null; - List recordList = null; - RegularTimeSeries ts = null; - - - String whereClause = "WHERE lid = '" + areaId + - "' AND dur = 1001 AND pe= 'PP'" + - " AND ts = '" + typeSource + "'" + - " ORDER BY basistime DESC, validtime ASC"; - - // System.out.println(header + " where string = " + whereClause); - - - long startTime = 0; - long endTime = 0; - -// initialize the fcst time series - startTime = forecastStartTime; - endTime = startTime; - - ts = new RegularTimeSeries(startTime, endTime, 1, precipUnit); - - successHolder.setValue(false); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size() ; i++) - { - - record = (ArealFcstRecord) recordList.get(i); - double value = record.getValue(); - long time = record.getValidtime(); - - - if (time >= startTime) - { - Measurement m = new Measurement(value, precipUnit); - - ts.setMeasurementByTime(m, time); - successHolder.setValue(true); - } - else if (time > endTime) - { - break; //done, since we went past the last one that we want - } - } //end for - - } // end try - - catch(SQLException e) - { - logSQLException(e); - } - - return ts; - - - } // end loadFcstMapTimeSeriesByTs() -// ------------------------------------------------------- - public String[] loadPreferredFcstTypeSourceArray(String areaId, String physicalElement, int duration) - { - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - List recordList = null; - - String whereString = " WHERE lid = '" + areaId + - "' AND pe = '" + physicalElement + - "' AND dur = " + duration + - " AND ts LIKE 'F%'" + - " ORDER by ts_rank ASC "; - - String[] tsArray = new String[0]; - - try - { - recordList = table.select(whereString); - - int lowestRank = 0; - - tsArray = new String[recordList.size()]; - for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - - tsArray[i] = record.getTs(); - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - - return tsArray; - - } - -// ------------------------------------------------------- - public RegularTimeSeries loadFcstMapTimeSeries(String areaId, long forecastStartTime) - { - String header = "DataMgr.loadFcstMapTimeSeries(): "; - - RegularTimeSeries fcstPrecipTimeSeries = null; - MeasuringUnit precipUnit = MeasuringUnit.inches; - - ArealFcstTable table = new ArealFcstTable(_db); - ArealFcstRecord record = null; - List recordList = null; - BooleanHolder successHolder = new BooleanHolder(false); - - - String pe = "PP"; - int dur = 1001; - String[] preferredTypeSourceArray = loadPreferredFcstTypeSourceArray(areaId, pe, dur); - boolean success = false; - - // in priority of the preferred sources, try to load the FCST MAP time series - // stop after successfully loading the time series - for (int i = 0; i < preferredTypeSourceArray.length && !success; i++) - { - String preferredTypeSource = preferredTypeSourceArray[i]; - RegularTimeSeries tempFcstPrecipTimeSeries = loadFcstMapTimeSeriesByTs(areaId, forecastStartTime, preferredTypeSource, successHolder); - - - if (successHolder.getValue() == true) - { - fcstPrecipTimeSeries = tempFcstPrecipTimeSeries; - // System.out.println("chosen preferredTypeSource = " + preferredTypeSource); - success = true; - } - else - { - //System.out.println("NOT chosen preferredTypeSource = " + preferredTypeSource); - } - } - - if (!success) - { - fcstPrecipTimeSeries = new RegularTimeSeries(forecastStartTime, forecastStartTime, 1, precipUnit); - } - - return fcstPrecipTimeSeries; - } -// ------------------------------------------------------- - - public RegularTimeSeries loadFileMapTimeSeries(String filePath) - { - String header = "DataMgr.loadFileMapTimeSeries(): "; - - TimeSeriesFileManager reader = new TimeSeriesFileManager(); - - RegularTimeSeries precipTimeSeries = null; - MeasuringUnit precipUnit = MeasuringUnit.inches; - - precipTimeSeries = reader.readRegularTimeSeries(filePath, MeasuringUnit.inches); - - return precipTimeSeries; - } -// ------------------------------------------------------- - - public RegularTimeSeries loadFcstMapTimeSeries_old(String areaId, long forecastStartTime) - { - String header = "DataMgr.loadFcstMapTimeSeries(): "; - - RegularTimeSeries fcstPrecipTimeSeries = null; - MeasuringUnit precipUnit = MeasuringUnit.inches; - - FcstPrecipTable table = new FcstPrecipTable(_db); - FcstPrecipRecord record = null; - List recordList = null; - BooleanHolder successHolder = new BooleanHolder(false); - - - String pe = "PP"; - int dur = 1001; - String[] preferredTypeSourceArray = loadPreferredFcstTypeSourceArray(areaId, pe, dur); - boolean success = false; - - for (int i = 0; i < preferredTypeSourceArray.length; i++) - { - String preferredTypeSource = preferredTypeSourceArray[i]; - RegularTimeSeries tempFcstPrecipTimeSeries = loadFcstMapTimeSeriesByTs(areaId, forecastStartTime, preferredTypeSource, successHolder); - - - if (successHolder.getValue() == true) - { - fcstPrecipTimeSeries = tempFcstPrecipTimeSeries; - // System.out.println("chosen preferredTypeSource = " + preferredTypeSource); - success = true; - break; - } - else - { - //System.out.println("NOT chosen preferredTypeSource = " + preferredTypeSource); - } - } - - if (!success) - { - fcstPrecipTimeSeries = new RegularTimeSeries(forecastStartTime, forecastStartTime, 1, precipUnit); - } - - return fcstPrecipTimeSeries; - } -// ------------------------------------------------------- - - - -// ------------------------------------------------------- - /* public RegularTimeSeries loadMapTimeSeriesFromFiles(String areaId, long startTime, long endTime) - { - - String header = "DataMgr.getMapTimeSeriesFromFiles(): "; - - _logger.log(header + " startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(startTime) + - " endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - - CodeTimer timer = new CodeTimer(_logger); - - timer.start(); - MAP map = new MAP(_db, areaId, startTime, endTime); - timer.stop("reading xmrg files for " + areaId + " took"); - - RegularTimeSeries ts = map.getMpeMapTimeSeries(); - - - - return ts; - - } -*/ - -// ------------------------------------------------------- - public void saveMapTimeSeries_old(String areaId, RegularTimeSeries ts, Set timeSet, Logger localLogger) - { -// we don't use ProcValue anymore for this; we use ArealObsPrecip. - String header = "DataMgr.saveMapTimeSeries(): "; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - //make sure record is in ingestfilter - ProcTsDescriptor descriptor = new ProcTsDescriptor("ProcValue"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - saveToIngestFilterIfNeeded(descriptor); - - - // initialize the constant record fields - long productTime = System.currentTimeMillis(); - - record = new ProcValueRecord(); - record.setLid(areaId); - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); //one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_T2"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short)0); - record.setShef_qual_code("Z"); - - - for (int i = 0; i < ts.getMeasurementCount(); i++) - { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - - if (timeSet.contains(new Long(time))) - { - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try - { - if (value != MISSING) - { - if (value > 0.0) - { - localLogger.log(header + "record with precip = " + record); - } - else - { - //localLogger.log(header + "record with no precip = " + record); - } - - //only save records that might be different from before - // see the outer if block - table.insertOrUpdate(record); - - } - else - { - /* - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - localLogger.log(header + "missing data for period ending at " + - timeString + - ", so not saving (relying on previously saved data)"); - */ - } - } - catch (SQLException e) - { - logSQLException(e); - } - } - } //end for - } -// ------------------------------------------------------- - public void saveMapTimeSeries(String areaId, RegularTimeSeries ts, Set timeSet, Logger localLogger) - { - String header = "DataMgr.saveMapTimeSeries(): "; - - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - //make sure record is in ingestfilter - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - saveToIngestFilterIfNeeded(descriptor); - - - // initialize the constant record fields - long productTime = System.currentTimeMillis(); - - record = new ArealObsRecord(); - record.setLid(areaId); - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); //one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_T2"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short)0); - record.setShef_qual_code("Z"); - - - for (int i = 0; i < ts.getMeasurementCount(); i++) - { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - - if (timeSet.contains(new Long(time))) - { - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try - { - if (value != MISSING) - { - if (value > 0.0) - { - localLogger.log(header + "record with precip = " + record); - } - else - { - //localLogger.log(header + "record with no precip = " + record); - } - - //only save records that might be different from before - // see the outer if block - table.insertOrUpdate(record); - - } - else - { - /* - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - localLogger.log(header + "missing data for period ending at " + - timeString + - ", so not saving (relying on previously saved data)"); - */ - } - } - catch (SQLException e) - { - logSQLException(e); - } - } - } //end for - } - -// ---------------------------------------------------------------------------------- - public void saveMapTimeSeries_old(String areaId, RegularTimeSeries ts, Logger localLogger) - { -// we don't use ProcValue anymore for this; we use ArealObsPrecip. - String header = "DataMgr.saveMapTimeSeries(): "; - - ProcValueTable table = new ProcValueTable(_db); - ProcValueRecord record = null; - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - //make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ProcValue"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - saveToIngestFilterIfNeeded(descriptor); - - long productTime = System.currentTimeMillis(); - - // initial the record object - record = new ProcValueRecord(); - record.setLid(areaId); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); //one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_MAP"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short)0); - record.setShef_qual_code("Z"); - - for (int i = 0; i < ts.getMeasurementCount(); i++) - { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try - { - if (value != MISSING) - { - if (value > 0.0) - { - localLogger.log(header + "record with precip = " + record); - } - else - { - //localLogger.log(header + "record with no precip = " + record); - } - - table.insertOrUpdate(record); - } - else - { - /* - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - localLogger.log(header + "missing data for period ending at " + - timeString + - ", so not saving (relying on previously saved data)"); - */ - } - } - catch (SQLException e) - { - logSQLException(e); - } - } //end for - } - -// ---------------------------------------------------------------------------------- - public void saveMapTimeSeriesToFile(RegularTimeSeries regularTimeSeries, String filePath) - { - _reader.saveRegularTimeSeries(regularTimeSeries, filePath); - - return; - } - -// ---------------------------------------------------------------------------------- - - public void saveMapTimeSeries(String areaId, RegularTimeSeries ts, Logger localLogger) - { - String header = "DataMgr.saveMapTimeSeries(): "; - - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = null; - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = "PM"; - - //make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - descriptor.setLid(areaId); - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - saveToIngestFilterIfNeeded(descriptor); - - long productTime = System.currentTimeMillis(); - - // initial the record object - record = new ArealObsRecord(); - record.setLid(areaId); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); //one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id("SSHP_MAP"); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short)0); - record.setShef_qual_code("Z"); - - for (int i = 0; i < ts.getMeasurementCount(); i++) - { - - Measurement m = ts.getMeasurementByIndex(i); - long time = ts.getMeasurementTimeByIndex(i); - double value = m.getValue(MeasuringUnit.inches); - - record.setObstime(time); - record.setValue(value); - - try - { - if (value != MISSING) - { - if (value > 0.0) - { - localLogger.log(header + "record with precip = " + record); - } - else - { - //localLogger.log(header + "record with no precip = " + record); - } - - table.insertOrUpdate(record); - } - else - { - /* - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - localLogger.log(header + "missing data for period ending at " + - timeString + - ", so not saving (relying on previously saved data)"); - */ - } - } - catch (SQLException e) - { - logSQLException(e); - } - } //end for - } - -// ------------------------------------------------------- - public void saveMapRowsToIngestFilterAsNeeded(List areaIdList) - { - saveMapRowsToIngestFilterAsNeeded(areaIdList, "PM"); - } - -// ------------------------------------------------------------------------------------------------- - - public void saveMapRowsToIngestFilterAsNeeded(List areaIdList, String typeSourceCode) - { - CodeTimer timer = new CodeTimer(_logger); - timer.start(); - - String areaId = null; - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = typeSourceCode; - - //make sure record is in ingestfilter - - ProcTsDescriptor descriptor = new ProcTsDescriptor("ArealObsPrecip"); - - descriptor.setPe(peCode); - descriptor.setDur(durationCode); - descriptor.setExtremum(extremumCode); - descriptor.setTs(tsCode); - - //select all the MAP rows to Check - String whereString = "WHERE pe = '" + descriptor.getPe() + - "' AND dur = " + descriptor.getDur() + " AND extremum = '" + - descriptor.getExtremum() + "' AND ts = '" + descriptor.getTs() + "'"; - - - System.out.println("whereString = " + whereString); - - IngestFilterRecord record; - IngestFilterTable table = new IngestFilterTable(_db); - List recordList = null; - HashSet filterSet = new HashSet(); - - // select from the ingestfilter table and - //add all of the lids to a hashset - try - { - recordList = table.select(whereString); - for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - filterSet.add(record.getLid()); - _logger.log("Adding " + record.getLid() + " to the filter set"); - } - } - catch (SQLException e) - { - logSQLException(e); - } - - // for each areaId in the list, - // check to see if it is in the hashset (which indicates it is already in the db) - // if not, then add it to the db - for (int i = 0; i < areaIdList.size(); i++) - { - areaId = (String) areaIdList.get(i); - - System.out.println("areaId to check = :" + areaId + ":"); - - if (! filterSet.contains(areaId)) - { - // add it to the db - descriptor.setLid(areaId); - saveToIngestFilter(descriptor); - } - } - - timer.stop("DataMgr.saveMapRowsToIngestFilterAsNeeded for all ids took "); - - } - - -// ------------------------------------------------------- - - - public void saveMapMeasurement(String areaId, Measurement mapMeasurement, - long obsTime, Logger localLogger) - { - long productTime = System.currentTimeMillis(); - saveMapObsMeasurement(areaId, "PM", mapMeasurement, obsTime, productTime, localLogger); - - return; - } -// ------------------------------------------------------- - - public void saveMapMeasurement(String areaId, String typeSource, Measurement mapMeasurement, - long measurementTime, long basisTime, long productTime, Logger localLogger) - { - - if (typeSource.charAt(0) == 'F' ) - { - saveMapFcstMeasurement(areaId, typeSource, mapMeasurement, measurementTime, basisTime, productTime, localLogger); - } - else - { - saveMapObsMeasurement(areaId, typeSource, mapMeasurement, measurementTime, productTime, localLogger); - } - - } -// ------------------------------------------------------------------------------------------------ - - private void saveMapObsMeasurement(String areaId, String typeSource, Measurement mapMeasurement, - long obsTime, long productTime, Logger localLogger) - { - - final String productId = "SSHP_MAP"; - MeasuringUnit dbPrecipUnit = MeasuringUnit.inches; - String header = "DataMgr.saveMapObsMeasurement(): "; - - ArealObsTable table = new ArealObsTable(_db); - ArealObsRecord record = new ArealObsRecord(); - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = typeSource; - -// make sure record is in ingestfilter - - double value = mapMeasurement.getValue(dbPrecipUnit); - - record.setLid(areaId); - - record.setObstime(obsTime); - record.setValue(value); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); //one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id(productId); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setRevision((short)0); - record.setShef_qual_code("Z"); - - - try - { - if (value != MISSING) - { - if (value > 0.0) - { - localLogger.log(header + "record with precip = " + record); - } - else - { -// localLogger.log(header + "record with no precip = " + record); - } - - table.insertOrUpdate(record); - - } - else - { - /* -String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); -localLogger.log(header + "missing data for period ending at " + - timeString + - ", so not saving (relying on previously saved data)"); - */ - } - } - catch (SQLException e) - { - logSQLException(e); - } - - } //end saveMAPObsMeasurement -// ------------------------------------------------------------------------------------------------ - private void saveMapFcstMeasurement(String areaId, String typeSource, Measurement mapMeasurement, - long validTime, long basisTime, long productTime, Logger localLogger) - { - - - // saveMapFcstMeasurement(areaId, typeSource, mapMeasurement, measurementTime, basisTime, productTime, localLogger); - - final String productId = "SSHP_HPN"; - MeasuringUnit dbPrecipUnit = MeasuringUnit.inches; - String header = "DataMgr.saveMapFcstMeasurement(): "; - - ArealFcstTable table = new ArealFcstTable(_db); - ArealFcstRecord record = new ArealFcstRecord(); - - short durationCode = 1001; //one hour only - String peCode = "PP"; - String extremumCode = "Z"; - String tsCode = typeSource; - -// make sure record is in ingestfilter - - - double value = mapMeasurement.getValue(dbPrecipUnit); - - record.setLid(areaId); - - record.setValidtime(validTime); - record.setValue(value); - - record.setQuality_code(_defaultQualityCode); - - record.setDur(durationCode); //one hour - - record.setPe(peCode); - record.setTs(tsCode); - record.setExtremum(extremumCode); - - record.setProduct_id(productId); - record.setProducttime(productTime); - - long postingTime = System.currentTimeMillis(); - record.setPostingtime(postingTime); - - record.setBasistime(basisTime); - - record.setRevision((short)0); - record.setShef_qual_code("Z"); - record.setProbability(-1); - - - - - try - { - if (value != MISSING) - { - if (value > 0.0) - { - localLogger.log(header + "record with precip = " + record); - } - else - { -// localLogger.log(header + "record with no precip = " + record); - } - - table.insertOrUpdate(record); - - } - else - { - /* -String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); -localLogger.log(header + "missing data for period ending at " + - timeString + - ", so not saving (relying on previously saved data)"); - */ - } - } - catch (SQLException e) - { - logSQLException(e); - } - - } //end saveMAPFcstMeasurement -// ------------------------------------------------------------------------------------------------ - -// ------------------------------------------------------------------------------------------------- - - public AbsTimeMeasurement loadMostCurrentFfhMeasurement(String lid, - String basinId, - long endTime) - { - Measurement measurement = null; - AbsTimeMeasurement ffhMeasurement = null; - - List ffhDescriptorList = loadFfhDescriptorList(lid, basinId); - for (int i = 0; i < ffhDescriptorList.size(); i++) - { - FFHDescriptor descriptor = (FFHDescriptor) ffhDescriptorList.get(i); - if (descriptor.getTime() <= endTime) - { - measurement = descriptor.getFfhMeasurement(); - ffhMeasurement = new AbsTimeMeasurement(measurement, descriptor.getTime()); - break; - } - } - - return ffhMeasurement; - } -// ------------------------------------------------------- -/* - public AbsTimeMeasurement loadMostCurrentFfhMeasurement(String lid, long endTime) - { - //String header = "DataMgr.getFfgValue(): "; - - AbsTimeMeasurement measurement = null; - double ffhValue = -1.0; - - ContingencyValueTable table = new ContingencyValueTable(this._db); - ContingencyValueRecord record = null; - - // Go to UnitGraph table to get basin id - String whereClause = null; - // " WHERE lid='" + basinId + "' "; - - List recordList = null; - - // Go to ContingencyValue table to get the FFH - //whereClause = " WHERE lid='" + lid + "'" + - // " AND dur=1001 AND pe='PP' AND ts IN ('CF','CP') " + - // " AND validtime > (TODAY - 5) " + - // " ORDER BY validtime DESC, ts "; - - whereClause = " WHERE lid='" + lid + "'" + - " AND dur=1001 AND pe='PP' AND ts IN ('CF','CP') " + - " ORDER BY validtime DESC, basistime DESC, ts "; - - // System.out.println( "DataMgr.getFfhMeasurement.whereClause = " + whereClause ); - - try - { - recordList = table.select(whereClause); - - // find the value that is the latest that is before or equal to the end time - for (int i = 0; i < recordList.size(); i++) - { - record = (ContingencyValueRecord) recordList.get(i); - - if (record.getValidtime() <= endTime) - { - ffhValue = record.getValue(); - long time = record.getValidtime(); - measurement = new AbsTimeMeasurement(ffhValue, time, MeasuringUnit.inches); - break; //don't look anymore, since the first one is the one I want - } - } //end for i - - } - catch(SQLException e) - { - logSQLException(e); - } - - - return measurement; - } // end of loadFFHMeasurement method -*/ -// ------------------------------------------------------------------------- - - public List loadFfhDescriptorList(String lid, String basinId) - { - String header = "DataMgr.loadFfhDescriptorList(): "; - - FFHDescriptor descriptor = null; - AbsTimeMeasurement measurement = null; - double ffhValue = -1.0; - int durationCode = 0; - - ContingencyValueTable table = new ContingencyValueTable(this._db); - ContingencyValueRecord record = null; - - String whereClause = null; - - List recordList = null; - - List descriptorList = new ArrayList(); - - - whereClause = " WHERE (lid='" + lid + "' OR lid = '" + basinId + "') " + - " AND dur in (1001, 1003, 1006) AND pe='PP' AND ts IN ('CF','CP') " + - " ORDER BY validtime DESC, basistime DESC, ts, dur "; - - long oldValidTime = 0; - String oldTypeSource=""; - - try - { - recordList = table.select(whereClause); - - // find the value that is the latest that is before or equal to the end time - for (int i = 0; i < recordList.size(); i++) - { - record = (ContingencyValueRecord) recordList.get(i); - - // System.out.println(header + " FFH record = " + record); - - long validTime = record.getValidtime(); - String typeSource = record.getTs(); - - oldValidTime = validTime; - oldTypeSource = typeSource; - - ffhValue = record.getValue(); - - measurement = new AbsTimeMeasurement(ffhValue, validTime, MeasuringUnit.inches); - - durationCode = record.getDur(); - - boolean isGridded = false; - if ( record.getTs().toUpperCase().equals("CF")) //areal - { - isGridded = false; - } - else //gridded - { - isGridded = true; - } - - descriptor = new FFHDescriptor(lid, measurement, durationCode, isGridded); - descriptorList.add(descriptor); - - } //end for i - - } - catch(SQLException e) - { - logSQLException(e); - } - - - return descriptorList; - - } // end of load FFHDescriptor Listmethod - - -// ------------------------------------------------------- - - public void saveSacState( SacSmaState sacSmaState ) - { - - saveSacState(sacSmaState, sacSmaState.getSource()); - - return; - } - - // ------------------------------------------------------- - - public void saveSacState( SacSmaState sacSmaState, String source) - { - SacSmaStateTable table = new SacSmaStateTable( _db ); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id( sacSmaState.getBasinId() ); - record.setSource( source ); - record.setValidtime( sacSmaState.getValidTime() ); - record.setBasistime( sacSmaState.getBasisTime() ); - - long currentTime = System.currentTimeMillis(); - - record.setPostingtime( currentTime ); - - record.setUztwc( sacSmaState.getUztwc() ); - record.setUzfwc( sacSmaState.getUzfwc() ); - record.setLztwc( sacSmaState.getLztwc() ); - record.setLzfsc( sacSmaState.getLzfsc() ); - record.setLzfpc( sacSmaState.getLzfpc() ); - record.setAdimc( sacSmaState.getAdimc() ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } - -// ------------------------------------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------------------------------------ - public List getPriorRunoffRecordList(String locationId, String typeSource, boolean forceCacheRefresh) - { - - String key = locationId + '|' + typeSource; - - List list = (List) _priorRunoffRecordMap.get(key); - if ((list == null) || (forceCacheRefresh) ) - { - list = loadPriorRunoffRecordList(locationId, typeSource); - _priorRunoffRecordMap.put(key, list); - } - - return list; - } - - -// ------------------------------------------------------------------------------------------------------------------------------ - - public List loadPriorRunoffRecordList(String locationId, String typeSource) - { - - String header = "DataMgr.loadPriorRunoffRecordList(): "; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - - String typeSourceClause = null; - - if (typeSource == null) - { - typeSourceClause = ""; - } - else - { - typeSourceClause = " AND ts = '" + typeSource + "'"; - } - - - String whereClause = "WHERE lid = '" + locationId + "'" + - " AND pe = 'QB' AND dur = 1001" + - typeSourceClause + - " ORDER BY basistime DESC, validtime ASC"; - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - } - catch (SQLException e) - { - e.printStackTrace(); - } - - return recordList; - - - } - // ------------------------------------------------------------------------------------------------------------- - public void clearPriorRunoffTimeSeriesCache() - { - _priorRunoffTimeSeriesMap.clear(); - } - - // ------------------------------------------------------------------------------------------------------------- - - - public RegularTimeSeries getPriorRunoffTimeSeries(String locationId, - String typeSource, - long modelRunStartTime, - long unitHydrographWholeDuration) - { - - String header = "DataMgr.getPriorRunoffTimeSeries"; - - String key = locationId + "|" + typeSource + "|" + DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime); - RegularTimeSeries priorRunoffTimeSeries = (RegularTimeSeries) _priorRunoffTimeSeriesMap.get(key); - - System.out.println(header + " key = " + key); - - if (priorRunoffTimeSeries == null) - { - priorRunoffTimeSeries = loadPriorRunoffTimeSeries(locationId, typeSource, modelRunStartTime, unitHydrographWholeDuration); - - // this would access a cache of all PriorRunoffTimeSeries records, - // this is a problem when new records are being added while the user is runninng SSHP - // priorRunoffTimeSeries = loadPriorRunoffTimeSeries2(locationId, typeSource, modelRunStartTime, unitHydrographWholeDuration); - _priorRunoffTimeSeriesMap.put(key, priorRunoffTimeSeries); - } - - return priorRunoffTimeSeries; - } - // ------------------------------------------------------------------------------------------------------------- - - public RegularTimeSeries loadPriorRunoffTimeSeries2(String locationId, - String typeSource, - long modelRunStartTime, - long unitHydrographWholeDuration) - { - final String header = "DataMgr.loadPriorRunoffTimeSeries2(): "; - FcstDischargeRecord record = null; - - // _priorRunoffCodeTimer.restart(); - - List recordList = getPriorRunoffRecordList(locationId, typeSource, false); - // selectTimer.stop(header + " select() took "); - - // _priorRunoffCodeTimer.stop("getPriorRunoffRecordList() has so far taken: "); - - - - String typeSourceClause = null; - - - long initialTime = modelRunStartTime - (unitHydrographWholeDuration * _millisPerHour); - String initialTimeString = DbTimeHelper.getDateTimeStringFromLongTime(initialTime); - String modelRunStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime); - - - - RegularTimeSeries ts = null; - - long desiredBasisTime = 0; // use the most recent basistime returned from the db - long startTime = modelRunStartTime - (unitHydrographWholeDuration * _millisPerHour); - - - List subRecordList = getSubListForPriorRunoffTimeSeries(recordList, - initialTime, - modelRunStartTime); - - - final MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; - final MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - - if (subRecordList == null) - { - System.out.println(header + "subRecordList is null for " + locationId); - } - - else if (subRecordList.size() > 0) - { - - record = (FcstDischargeRecord) subRecordList.get(0); - //desiredBasisTime = record.getBasistime(); -// startTime = record.getValidtime(); - - long endTime = modelRunStartTime; - int intervalInHours = 1; - - ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, tsRunoffUnit); - - // System.out.println("******* " + header + "desiredBasisTime = " + DbTimeHelper.getDateTimeStringFromLongTime(desiredBasisTime)); - } - -// for the selected subRecordList, create a runoff time series - - - - boolean done = false; - for (int i = 0 ; !done && (subRecordList != null) && (i < subRecordList.size()); i++) - { - record = (FcstDischargeRecord) subRecordList.get(i); - - if (record.getValidtime() > modelRunStartTime) - { - done = true; - } - else - { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbRunoffUnit); - - // System.out.print(header + " m = " + m); - - ts.setMeasurementByTime(m, validTime); - } - } //end for i - - - return ts; - } - - // ------------------------------------------------------------------------------------------------------------- - - - public RegularTimeSeries loadPriorRunoffTimeSeriesNew(String locationId, - String typeSource, - long modelRunStartTime, - long unitHydrographWholeDuration) - { - String header = "DataMgr.loadPriorRunoffTimeSeries(): "; - - System.out.println(header + "loading prior runoff time series for type source = " + typeSource); - - final MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; - final MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - - String typeSourceClause = null; - - if (typeSource == null) - { - typeSourceClause = ""; - } - else - { - typeSourceClause = " AND ts = '" + typeSource + "'"; - } - - long initialTime = modelRunStartTime - (unitHydrographWholeDuration * _millisPerHour); - String initialTimeString = DbTimeHelper.getDateTimeStringFromLongTime(initialTime); - String modelRunStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime); - - // System.out.println(header + "validtimes must be between " + initialTimeString + " and " + modelRunStartTimeString); - -// create the select where clause - String whereClause = "WHERE lid = '" + locationId + "'" + - " AND pe = 'QB' AND dur = 1001" + - typeSourceClause + " AND " + - " basistime = '" + modelRunStartTimeString + "' " + - " ORDER BY basistime DESC, validtime ASC"; - - System.out.println(header + "whereClause = " + whereClause); - - RegularTimeSeries ts = null; - - long desiredBasisTime = 0; // use the most recent basistime returned from the db - long startTime = modelRunStartTime - - (unitHydrographWholeDuration * _millisPerHour); - - try - { - recordList = table.select(whereClause); - - List subRecordList = getSubListForPriorRunoffTimeSeries(recordList, - initialTime, - modelRunStartTime); - - - if (subRecordList == null) - { - System.out.println(header + "subRecordList is null for " + locationId); - } - - else if (subRecordList.size() > 0) - { - - record = (FcstDischargeRecord) subRecordList.get(0); - desiredBasisTime = record.getBasistime(); -// startTime = record.getValidtime(); - - long endTime = modelRunStartTime; - int intervalInHours = 1; - - ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, tsRunoffUnit); - } - -// for the selected subRecordList, create a runoff time series - - boolean done = false; - for (int i = 0 ; !done && (subRecordList != null) && (i < subRecordList.size()); i++) - { - record = (FcstDischargeRecord) subRecordList.get(i); - - if (record.getValidtime() > modelRunStartTime) - { - done = true; - } - else - { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbRunoffUnit); - - // System.out.print(header + " m = " + m); - - ts.setMeasurementByTime(m, validTime); - } - } //end for i - - } //end try - - catch ( SQLException e ) - { - logSQLException(e); - } - - return ts; - } - - // ------------------------------------------------------------------------------------------------------------- -// ----------------------------------------------------------------------------------------------------------------- - public RegularTimeSeries loadPriorRunoffTimeSeries(String locationId, - String typeSource, - long modelRunStartTime, - long unitHydrographWholeDuration) - { - String header = "DataMgr.loadPriorRunoffTimeSeries(): "; - - // System.out.println(header + "loading prior runoff time series for type source = " + typeSource); - - final MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; - final MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - - String typeSourceClause = null; - - if (typeSource == null) - { - typeSourceClause = ""; - } - else - { - typeSourceClause = " AND ts = '" + typeSource + "'"; - } - - long initialTime = modelRunStartTime - (unitHydrographWholeDuration * _millisPerHour); - String initialTimeString = DbTimeHelper.getDateTimeStringFromLongTime(initialTime); - String modelRunStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime); - - // System.out.println(header + "validtimes must be between " + initialTimeString + " and " + modelRunStartTimeString); - - -// create the select where clause - String whereClause = "WHERE lid = '" + locationId + "'" + - " AND pe = 'QB' AND dur = 1001" + - typeSourceClause + " AND " + - " validtime >= '" + initialTimeString + "' " + " AND " + - " validtime <= '" + modelRunStartTimeString + "' " + - " ORDER BY basistime DESC, validtime ASC"; - - // System.out.println(header + "whereClause = " + whereClause); - - RegularTimeSeries ts = null; - - long desiredBasisTime = 0; // use the most recent basistime returned from the db - long startTime = modelRunStartTime - - (unitHydrographWholeDuration * _millisPerHour); - - try - { - recordList = table.select(whereClause); - - List subRecordList = getSubListForPriorRunoffTimeSeries(recordList, - initialTime, - modelRunStartTime); - - - if (subRecordList == null) - { - System.out.println(header + "subRecordList is null for " + locationId); - } - - else if (subRecordList.size() > 0) - { - - record = (FcstDischargeRecord) subRecordList.get(0); - desiredBasisTime = record.getBasistime(); -// startTime = record.getValidtime(); - - long endTime = modelRunStartTime; - int intervalInHours = 1; - - ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, tsRunoffUnit); - } - -// for the selected subRecordList, create a runoff time series - - boolean done = false; - for (int i = 0 ; !done && (subRecordList != null) && (i < subRecordList.size()); i++) - { - record = (FcstDischargeRecord) subRecordList.get(i); - - if (record.getValidtime() > modelRunStartTime) - { - done = true; - } - else - { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbRunoffUnit); - - // System.out.print(header + " m = " + m); - - ts.setMeasurementByTime(m, validTime); - } - } //end for i - - } //end try - - catch ( SQLException e ) - { - logSQLException(e); - } - - return ts; - } - - // ------------------------------------------------------------------------------------------------------------- - public RegularTimeSeries loadPriorRunoffTimeSeriesOld(String locationId, - String typeSource, - long modelRunStartTime, - long unitHydrographWholeDuration) - { - - - - - String header = "DataMgr.loadPriorRunoffTimeSeries(): "; - - CodeTimer overallTimer = new CodeTimer(); - CodeTimer selectTimer = new CodeTimer(); - CodeTimer sublistTimer = new CodeTimer(); - - overallTimer.start(); - // System.out.println(header + "loading prior runoff time series"); - - final MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; - final MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - - String typeSourceClause = null; - - if (typeSource == null) - { - typeSourceClause = ""; - } - else - { - typeSourceClause = " AND ts = '" + typeSource + "'"; - } - - long initialTime = modelRunStartTime - (unitHydrographWholeDuration * _millisPerHour); - String initialTimeString = DbTimeHelper.getDateTimeStringFromLongTime(initialTime); - String modelRunStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime); - - //create the select where clause - String whereClause = "WHERE lid = '" + locationId + "'" + - " AND pe = 'QB' AND dur = 1001" + - typeSourceClause + - " ORDER BY basistime DESC, validtime ASC"; - - RegularTimeSeries ts = null; - - long desiredBasisTime = 0; // use the most recent basistime returned from the db - long startTime = modelRunStartTime - - (unitHydrographWholeDuration * _millisPerHour); - - try - { - - selectTimer.start(); - recordList = table.select(whereClause); - selectTimer.stop(header + " select() took "); - - - System.out.println(header + "validtimes must be between " + initialTimeString + " and " + modelRunStartTimeString); - - sublistTimer.start(); - - List subRecordList = getSubListForPriorRunoffTimeSeries(recordList, - initialTime, - modelRunStartTime); - sublistTimer.stop(header + " getSubListForPriorRunoffTimeSeries() took "); - - if (subRecordList == null) - { - System.out.println(header + "subRecordList is null for " + locationId); - } - - else if (subRecordList.size() > 0) - { - - record = (FcstDischargeRecord) subRecordList.get(0); - desiredBasisTime = record.getBasistime(); - startTime = record.getValidtime(); - - long endTime = modelRunStartTime; - int intervalInHours = 1; - - ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, tsRunoffUnit); - - //System.out.println(header + "record count = " + recordList.size()); - } - - // for the selected subRecordList, create a runoff time series - - boolean done = false; - for (int i = 0 ; !done && (subRecordList != null) && (i < subRecordList.size()); i++) - { - record = (FcstDischargeRecord) subRecordList.get(i); - - if (record.getValidtime() > modelRunStartTime) - { - done = true; - } - else - { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbRunoffUnit); - - ts.setMeasurementByTime(m, validTime); - } - } //end for i - } //end try - - catch ( SQLException e ) - { - logSQLException(e); - } - - - overallTimer.stop(header + "overall, took "); - return ts; - } - - // ------------------------------------------------------------------------------- - - private List createListOfFcstDischargeRecordLists( List recordList) - { - String header = "DataMgr.createListOfFcstDischargeRecordLists()"; - List listOfLists = new ArrayList(); - List subRecordList = null; - - long previousBasisTime = -1; - - for (FcstDischargeRecord record: recordList) - { - //if the record is the first one of its basistime, then create a new sublist and add it to the listOfLists - if (record.getBasistime() != previousBasisTime ) - { - subRecordList = new ArrayList(); - listOfLists.add(subRecordList); - previousBasisTime = record.getBasistime(); - //System.out.println(header + "basisTime = " + DbTimeHelper.getDateTimeStringFromLongTime(record.getBasistime())); - } - - //add the record to the current subRecordList, - //which itself has already been added to the listOfLists - subRecordList.add(record); - - } - - // System.out.println(header + "listOfLists has " +listOfLists.size() + " sublists."); - - return listOfLists; - } - - // ------------------------------------------------------------------------------- - - private List getSubListForPriorRunoffTimeSeries(List recordList, - long initialTime, - long endTime) - { - String header = "DataMgr.getSubListForPriorRunoffTimeSeries(): "; - //This method assumes: - //recordList is ordered by basistime DESC (most recent basistime first), validtime ASC (oldest first) - // - List subList = null; - - - //put all time series into a List of Lists - List> listOfFcstDischargeRecordLists = createListOfFcstDischargeRecordLists(recordList); - - - //iterate through the list of lists until you find the subList that includes a validtime - // set that overlaps the time from initialTime to endTime (inclusive) - //Take that sublist and quit - - for (List subRecordList : listOfFcstDischargeRecordLists) - { - int lastIndex = subRecordList.size() - 1; - if (lastIndex > -1) - { - FcstDischargeRecord firstRecord = subRecordList.get(0); - FcstDischargeRecord lastRecord = subRecordList.get(lastIndex); - - String time1String = DbTimeHelper.getDateTimeStringFromLongTime(firstRecord.getValidtime()); - String time2String = DbTimeHelper.getDateTimeStringFromLongTime(lastRecord.getValidtime()); - - // System.out.println(header + "subRecordList's validtime 1 = " + time1String + " validtime 2 = " + time2String); - - if ( - (firstRecord.getValidtime() <= initialTime) && - (lastRecord.getValidtime() >= endTime) - ) - { - subList = subRecordList; - break; - } - } - - } - - return subList; - } - - // ------------------------------------------------------------------------------- - /* public RegularTimeSeries oldLoadPriorRunoffTimeSeries(String locationId, - long modelRunStartTime, - long unitHydrographWholeDuration) - { -// String header = "DataMgr.getPriorRunoffTimeSeries(): "; -// System.out.println(header + "loading prior runoff time series"); - - MeasuringUnit tsRunoffUnit = MeasuringUnit.mm; - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - -// NOTE: We may at some point have to select based on the Type/source whose -// prior runoff is favored - String whereClause = "WHERE lid = '" + locationId + "'" + - " AND pe = 'QB' AND dur = 1001 " + - " ORDER BY basistime DESC, validtime ASC"; - - RegularTimeSeries ts = null; - - long desiredBasisTime = 0; // use the most recent basistime in the db - long startTime = modelRunStartTime - - (unitHydrographWholeDuration * _millisPerHour); - - try - { - recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - record = (FcstDischargeRecord) recordList.get(0); - desiredBasisTime = record.getBasistime(); - startTime = record.getValidtime(); - - long endTime = modelRunStartTime; - int intervalInHours = 1; - - ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, tsRunoffUnit); - -// System.out.println(header + "record count = " + recordList.size()); - } - -// for the desiredBasisTime, create a runoff time series - - boolean done = false; - for (int i = 0 ; !done && (i < recordList.size()); i++) - { -// System.out.println(header + "i = " + i); - record = (FcstDischargeRecord) recordList.get(i); - - if (record.getBasistime() != desiredBasisTime) - { -// System.out.println(header + "part1"); -// we are done, since the desiredBasisTime comes first in the -// list - done = true; - } - else if (record.getValidtime() > modelRunStartTime) - { -// System.out.println(header + "part2, validtime = " + -// DbTimeHelper.getDateTimeStringFromLongTime(record.getValidtime()) + -// " modelRunStartTime = " + DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime)); -// we only want PRIOR runoff to the model StartTime, so -// stop now - done = true; - } - else - { -// System.out.println(header + "part3"); - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbRunoffUnit); - - ts.setMeasurementByTime(m, validTime); - -// System.out.println(header + "measurement = " + m); - } - } //end for i - } //end try - - catch ( SQLException e ) - { - logSQLException(e); - } - - return ts; - } -*/ -// ------------------------------------------------------------------------------- - public String[] loadPreferredObsTypeSourceArray(String areaId, - String physicalElement, - int duration) - { - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - List recordList = null; - - String whereString = " WHERE lid = '" + areaId + "'" + " AND pe = '" - + physicalElement + "'" + " AND dur = " + duration - + " AND ts LIKE 'R%'" + " ORDER by ts_rank ASC "; - - String[] tsArray = new String[0]; - - try - { - recordList = table.select(whereString); - - int lowestRank = 0; - - tsArray = new String[recordList.size()]; - for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - - tsArray[i] = record.getTs(); - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - return tsArray; - } -// ------------------------------------------------------- - public RegularTimeSeries loadPotentialEvaporationTimeSeries(String basinId, - long modelRunStartTime, - long modelRunEndTime) - { - RegularTimeSeries ts = null; - MeasuringUnit tsEvapUnit = MeasuringUnit.mm; - MeasuringUnit dbEvapUnit = MeasuringUnit.inches; - - FcstOtherTable table = new FcstOtherTable(_db); - FcstOtherRecord record = null; - List recordList = null; - - long desiredBasisTime = 0; // use the most recent basistime in the db - long startTime = modelRunStartTime; - long endTime = modelRunEndTime; - - int intervalInHours = 1; - ts = new RegularTimeSeries(startTime, endTime, - intervalInHours, tsEvapUnit); - - String whereClause = " WHERE lid = '" + basinId + "' AND " + - "pe = 'EA' AND dur = 1001 ORDER BY basistime DESC, validtime ASC"; - - - try - { - recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - record = (FcstOtherRecord) recordList.get(0); - desiredBasisTime = record.getBasistime(); - } - - boolean done = false; - for (int i = 0 ; !done && (i < recordList.size()); i++) - { - record = (FcstOtherRecord) recordList.get(i); - - if (record.getBasistime() != desiredBasisTime) - { - // we are done, since the desiredBasisTime comes first in the - // list - done = true; - } - else if (record.getValidtime() > modelRunEndTime) - { - //we are done, since we don't need the data past this time - done = true; - } - else if (record.getValidtime() >= modelRunStartTime) - { - double value = record.getValue(); - long validTime = record.getValidtime(); - Measurement m = new Measurement(value, dbEvapUnit); - - ts.setMeasurementByTime(m, validTime); - } - //else, the data comes from before the modelRunStartTime and we are - // not interested. - - } //end for i - } - catch (SQLException e) - { - logSQLException(e); - } - - return ts; - - } - -// --------------------------------------------------------------------------------------- - - public void saveRunoffTimeSeries(String locationId, RegularTimeSeries runoffTimeSeries) - { - saveRunoffTimeSeries(locationId, "SSHPRUNOFF", runoffTimeSeries); - } //end saveRunoffTimeSeries (2 arg version) - - -// --------------------------------------------------------------------------------------- - public void saveRunoffTimeSeries(String locationId, String productId, RegularTimeSeries runoffTimeSeries) - { - long basisTime = System.currentTimeMillis(); - String typeSource = "FZ"; - saveRunoffTimeSeries(locationId, typeSource, basisTime, productId, runoffTimeSeries); - - return; - } //end saveRunoffTimeSeries (3 arg version) -// ---------------------------------------------------------------------------------------- - public void saveRunoffTimeSeries(String locationId, String typeSource, long basisTime, - String productId, RegularTimeSeries runoffTimeSeries) - { - - String header = "DataMgr.saveRunoffTimeSeries(): "; - - String basisTimeString = DbTimeHelper.getDateTimeStringFromLongTime(basisTime); - System.out.println(header + " basisTime = " + basisTimeString); - - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - - int length = runoffTimeSeries.getMeasurementCount(); - short durationCode = 1001; - record = new FcstDischargeRecord(); - record.setLid(locationId); - record.setPe("QB"); - - long currentTime = System.currentTimeMillis(); - record.setBasistime(basisTime); - record.setProducttime(basisTime); - record.setPostingtime(currentTime); - - record.setTs(typeSource); - record.setDur(durationCode); - record.setExtremum("Z"); - record.setProbability(-1.0f); - record.setProduct_id(productId); - record.setShef_qual_code(""); - - FcstTsDescriptor descriptor = new FcstTsDescriptor("FcstDischarge"); - descriptor.setLid(record.getLid()); - descriptor.setPe(record.getPe()); - descriptor.setTs(record.getTs()); - descriptor.setDur(record.getDur()); - descriptor.setExtremum(record.getExtremum()); - - saveToIngestFilterIfNeeded(descriptor); - - - // System.out.println(header + " runoff time series length = " + length); - - for (int i = 0; i < length; i++) - { - Measurement measurement = runoffTimeSeries.getMeasurementByIndex(i); - long time = runoffTimeSeries.getMeasurementTimeByIndex(i); - - //make sure my units are correct - measurement = measurement.getCopy(dbRunoffUnit); - - - double value = measurement.getValue(); - - /* - if (value > 0.0) - { - System.out.println(header + " value = " + value + " time = " + DbTimeHelper.getDateTimeStringFromLongTime(time)); - } - */ - - record.setValidtime(time); - record.setValue(value); - - - try - { - table.insertOrUpdate(record); - } - catch (SQLException e) - { - e.printStackTrace(); - _logger.log("Failed to save record = " + record ); - logSQLException(e); - } - - - } - - } //end saveRunoffTimeSeries (6 arg version) - -// ------------------------------------------------------- - - public void deleteLaterSacSmaVarStatesAndRunoff(String lid, String basinId, long validTime) throws SQLException - { - deleteLaterRunoff(lid, SSHPSource.UNADJUSTED_VAR, validTime); - deleteLaterRunoff(lid, SSHPSource.ADJUSTED_VAR, validTime); - - deleteLaterSacStates(basinId, SSHPSource.UNADJUSTED_VAR, validTime); - deleteLaterSacStates(basinId, SSHPSource.ADJUSTED_VAR, validTime); - } - - private void deleteLaterRunoff(String lid, SSHPSource source, long validTime) throws SQLException - { - FcstDischargeTable table = new FcstDischargeTable(_db); - - String whereString = " WHERE lid = '" + lid + "' AND pe = 'QB' AND ts = '" + source.getTypeSource() + "' AND validtime >" + - "'" + DbTimeHelper.getDateTimeStringFromLongTime(validTime) + "'"; - - table.delete(whereString); - - } - - private void deleteLaterSacStates(String basinId, SSHPSource source, long validTime) throws SQLException - { - SacSmaStateTable table = new SacSmaStateTable(_db); - - String whereString = " WHERE basin_id = '" + basinId + "' AND source = '" + source.getSacSmaSource() + "' AND validtime >" + - "'" + DbTimeHelper.getDateTimeStringFromLongTime(validTime) + "'"; - - table.delete(whereString); - - } - - -// ------------------------------------------------------- - public List loadSacSmaParamsList( String where ) - { - List sacSmaParamsRecordList = null; - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - - try - { - sacSmaParamsRecordList = table.select( where ); - } - catch( SQLException e ) - { - logSQLException(e); - } - - return getSacSmaParamsListFromSacSmaParamsRecordList( sacSmaParamsRecordList ); - } - -// ------------------------------------------------------- - private SacSmaState getSacSmaStateFromRecord(SacSmaStateRecord record) - { - SacSmaState state = new SacSmaState(); - - state.setBasinId(record.getBasin_id()); - - state.setValidTime(record.getValidtime()); - state.setBasisTime(record.getBasistime()); - state.setPostingTime(record.getPostingtime()); - - state.setSource(record.getSource()); - - state.setAdimc(record.getAdimc()); - state.setLzfpc(record.getLzfpc()); - state.setLzfsc(record.getLzfsc()); - state.setLztwc(record.getLztwc()); - - - state.setUzfwc(record.getUzfwc()); - state.setUztwc(record.getUztwc()); - - return state; - - } - - private List getSacSmaParamsListFromSacSmaParamsRecordList( List sacSmaParamsRecordList ) - { - List sacSmaParamsList = new ArrayList(); - - for( int i = 0; i < sacSmaParamsRecordList.size(); i++ ) - { - SacSmaParameters addSacSmaParams = new SacSmaParameters(); - SacSmaParamsRecord sacSmaParamsRecord = (SacSmaParamsRecord) sacSmaParamsRecordList.get( i ); - - addSacSmaParams.setBasinId(sacSmaParamsRecord.getBasin_id()); - addSacSmaParams.setSource(sacSmaParamsRecord.getSource()); - addSacSmaParams.setValidTime(sacSmaParamsRecord.getValidtime()); - addSacSmaParams.setPostingTime(sacSmaParamsRecord.getPostingtime()); - addSacSmaParams.setUztwm(sacSmaParamsRecord.getUztwm()); - addSacSmaParams.setUzfwm(sacSmaParamsRecord.getUzfwm()); - addSacSmaParams.setUzk(sacSmaParamsRecord.getUzk()); - addSacSmaParams.setPctim(sacSmaParamsRecord.getPctim()); - addSacSmaParams.setAdimp(sacSmaParamsRecord.getAdimp()); - addSacSmaParams.setRiva(sacSmaParamsRecord.getRiva()); - addSacSmaParams.setZperc(sacSmaParamsRecord.getZperc()); - addSacSmaParams.setRexp(sacSmaParamsRecord.getRexp()); - addSacSmaParams.setLztwm(sacSmaParamsRecord.getLztwm()); - addSacSmaParams.setLzfsm(sacSmaParamsRecord.getLzfsm()); - addSacSmaParams.setLzfpm(sacSmaParamsRecord.getLzfpm()); - addSacSmaParams.setLzsk(sacSmaParamsRecord.getLzsk()); - addSacSmaParams.setLzpk(sacSmaParamsRecord.getLzpk()); - addSacSmaParams.setPfree(sacSmaParamsRecord.getPfree()); - addSacSmaParams.setRserv(sacSmaParamsRecord.getRserv()); - addSacSmaParams.setSide(sacSmaParamsRecord.getSide()); - - addSacSmaParams.setPeadj(sacSmaParamsRecord.getPeadj()); - addSacSmaParams.setPxadj(sacSmaParamsRecord.getPxadj()); - addSacSmaParams.setEfc(sacSmaParamsRecord.getEfc()); - - sacSmaParamsList.add( addSacSmaParams ); - } - - return sacSmaParamsList; - } - -// ------------------------------------------------------- - public List getSacSmaStateDescriptorListByBasinId(String basinId) - { - return getSacSmaStateDescriptorListByBasinId(basinId, false); - } -// ------------------------------------------------------- - - public List getSacSmaStateDescriptorListByBasinId(String basinId, boolean forceCacheUpdate) - { - - List descriptorList = null; - if (forceCacheUpdate) - { - descriptorList = loadSacSmaStateDescriptorListByBasinId(basinId); - _sacDescriptorListMap.put(basinId, descriptorList); - } - else //may use the cache - { - descriptorList = (List) _sacDescriptorListMap.get(basinId); - } - - - if (descriptorList == null) - { - descriptorList = loadSacSmaStateDescriptorListByBasinId(basinId); - _sacDescriptorListMap.put(basinId, descriptorList); - } - - return descriptorList; - } -// ------------------------------------------------------- - public List loadSacSmaStateDescriptorListByBasinId(String basinId) - { - String whereString = "WHERE basin_id = '" + basinId + "' ORDER BY validtime desc, source"; - List stateList = loadSacSmaStateList(whereString); - - List descriptorList = new ArrayList(); - - for (int i = 0; i < stateList.size(); i++) - { - SacSmaState state = (SacSmaState) stateList.get(i); - - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - descriptorList.add(descriptor); - - } - - return descriptorList; - - } - - public List loadSacSmaStateList( String where ) - { - List sacSmaStateRecordList = null; - SacSmaStateTable table = new SacSmaStateTable( _db ); - - try - { - sacSmaStateRecordList = table.select( where ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - return getSacSmaStateListFromSacSmaStateRecordList( sacSmaStateRecordList ); - } - - // ------------------------------------------------------- - - - private List getSacSmaStateListFromSacSmaStateRecordList( List sacSmaStateRecordList ) - { - List sacSmaStateList = new ArrayList(); - - if (sacSmaStateRecordList != null) - { - for ( int i = 0; i < sacSmaStateRecordList.size(); i++ ) - { - SacSmaState addSacSmaState = new SacSmaState(); - SacSmaStateRecord sacSmaStateRecord = (SacSmaStateRecord) sacSmaStateRecordList.get( i ); - - addSacSmaState.setBasinId( sacSmaStateRecord.getBasin_id()); - addSacSmaState.setSource( sacSmaStateRecord.getSource()); - addSacSmaState.setValidTime( sacSmaStateRecord.getValidtime() ); - addSacSmaState.setBasisTime( sacSmaStateRecord.getBasistime() ); - addSacSmaState.setPostingTime( sacSmaStateRecord.getPostingtime() ); - addSacSmaState.setUztwc( sacSmaStateRecord.getUztwc() ); - addSacSmaState.setUzfwc( sacSmaStateRecord.getUzfwc() ); - addSacSmaState.setLztwc( sacSmaStateRecord.getLztwc() ); - addSacSmaState.setLzfsc( sacSmaStateRecord.getLzfsc() ); - addSacSmaState.setLzfpc( sacSmaStateRecord.getLzfpc() ); - addSacSmaState.setAdimc( sacSmaStateRecord.getAdimc() ); - - sacSmaStateList.add( addSacSmaState ); - } - } - - return sacSmaStateList; - } - - -// ------------------------------------------------------- - private SacSmaParamsRecord getSacSmaParamsRecord(SacSmaParameters sacSmaParams) - { - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - record.setBasin_id( sacSmaParams.getBasinId() ); - record.setSource(sacSmaParams.getSource()); - record.setValidtime(sacSmaParams.getValidTime() ); - record.setPostingtime(sacSmaParams.getPostingTime()); - - record.setUztwm(sacSmaParams.getUztwm()); - record.setUzfwm(sacSmaParams.getUzfwm()); - record.setUzk(sacSmaParams.getUzk()); - record.setPctim(sacSmaParams.getPctim()); - record.setAdimp(sacSmaParams.getAdimp()); - record.setRiva(sacSmaParams.getRiva()); - record.setZperc(sacSmaParams.getZperc()); - record.setRexp(sacSmaParams.getRexp()); - record.setLztwm(sacSmaParams.getLztwm()); - record.setLzfsm(sacSmaParams.getLzfsm()); - record.setLzfpm(sacSmaParams.getLzfpm()); - record.setLzsk(sacSmaParams.getLzsk()); - record.setLzpk(sacSmaParams.getLzpk()); - record.setPfree(sacSmaParams.getPfree()); - record.setRserv(sacSmaParams.getRserv()); - record.setSide(sacSmaParams.getSide()); - - - - record.setPeadj(sacSmaParams.getPeadj()); - record.setPxadj(sacSmaParams.getPxadj()); - record.setEfc(sacSmaParams.getEfc()); - - return record; - } - - -// ------------------------------------------------------- - - - public void saveParams( SacSmaParameters sacSmaParams ) - { - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - SacSmaParamsRecord record = getSacSmaParamsRecord(sacSmaParams); - - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } -// ------------------------------------------------------- - - public void saveState( SacSmaState sacSmaState ) - { - SacSmaStateTable table = new SacSmaStateTable( _db ); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id( sacSmaState.getBasinId() ); - record.setSource( sacSmaState.getSource() ); - record.setValidtime( sacSmaState.getValidTime() ); - record.setBasistime( sacSmaState.getBasisTime() ); - record.setPostingtime( sacSmaState.getPostingTime() ); - - record.setUztwc( sacSmaState.getUztwc() ); - record.setUzfwc( sacSmaState.getUzfwc() ); - record.setLztwc( sacSmaState.getLztwc() ); - record.setLzfsc( sacSmaState.getLzfsc() ); - record.setLzfpc( sacSmaState.getLzfpc() ); - record.setAdimc( sacSmaState.getAdimc() ); - - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } - -// ------------------------------------------------------- - public boolean saveFcstTimeSeries(FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, - int hoursToSave ) - { - - boolean result = false; - - if (descriptor.getTableName().equalsIgnoreCase("FcstHeight")) - { - result = saveFcstHeightTs(descriptor, timeSeries, hoursToSave); - } - else if (descriptor.getTableName().equalsIgnoreCase("FcstOther")) - { - result = saveFcstEvapTs(descriptor, timeSeries, hoursToSave); - } - else if (descriptor.getTableName().equalsIgnoreCase("FcstDischarge")) - { - result = saveFcstDischargeTs(descriptor, timeSeries, hoursToSave); - } - - return result; - } - -// ------------------------------------------------------- - - - private boolean saveFcstEvapTs( FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, - int hoursToSave) - { - MeasuringUnit dbUnit = MeasuringUnit.inches; - boolean success = false; - - saveToIngestFilterIfNeeded(descriptor); - - FcstOtherTable table = new FcstOtherTable( _db ); - FcstOtherRecord record = new FcstOtherRecord(); - - long startTime, endTime, interval; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - - //adjust the endtime - long possibleEndTime = startTime + ((hoursToSave-1)*HOUR_IN_MILLIS); - if (possibleEndTime <= endTime) - { - endTime = possibleEndTime; - } - - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - record.setLid( descriptor.getLid() ); - record.setPe( descriptor.getPe() ); - record.setTs( descriptor.getTs() ); - record.setExtremum( descriptor.getExtremum() ); - record.setShef_qual_code( descriptor.getShef_qual_code() ); - record.setProduct_id( descriptor.getProduct_id() ); - record.setProbability( descriptor.getProbability() ); - record.setQuality_code( descriptor.getQuality_code() ); - record.setRevision( descriptor.getRevision() ); - record.setDur( descriptor.getDur() ); - record.setProducttime( descriptor.getProducttime() ); - record.setBasistime( descriptor.getBasistime() ); - record.setPostingtime( System.currentTimeMillis() ); - - int recordCount = 0; - int insertOrUpdateCount = 0; - int failureCount = 0; - int skippedCount = 0; - - for ( long time = startTime; time <= endTime; time += interval ) - { - Measurement measurement = timeSeries.getMeasurementByTime( time ); - - record.setValidtime( time ); - record.setValue( measurement.getValue(dbUnit)); - - recordCount++; - - if ( record.getValue() >= 0.0) - { - - try - { - table.insertOrUpdate( record ); - insertOrUpdateCount++; - //System.out.println("count = " + count); - } - catch ( SQLException e ) - { - failureCount++; - logSQLException(e); - _logger.log("record # = " + recordCount); - } - } - else - { - skippedCount++; - _logger.log("DataMgr.saveFcstHeight(): measurement = " + - measurement + - " record = " + record); - } - } //end for - - _logger.log("DataMgr.saveFcstHeight(): " + - " recordCount = " + recordCount + - " insertOrUpdateCount = " + insertOrUpdateCount + - " failureCount = " + failureCount + - " skippedCount = " + skippedCount); - - if ((insertOrUpdateCount + skippedCount) == recordCount) - { - success = true; - } - - return success; - - } - -// ------------------------------------------------------- - - /** - * Publish data to the riverstatus table. - */ - private void postMaxFcst(String locationId, String physicalElement, - String typeSource) { - String table = null; - - _logger.log("Updating RiverStatus for: " + locationId + " " - + physicalElement); - - if (physicalElement.startsWith("H") || physicalElement.startsWith("h")) - table = "FcstHeight"; - else - table = "FcstDischarge"; - - ForecastPoster fcstPoster = new ForecastPoster(_db, _logger); - boolean status = fcstPoster.loadMaxFcstData(table, locationId, - physicalElement); - - if (status) - _logger.log("RiverStatus update complete !"); - else - _logger.log("RiverStatus update FAILED !!!"); - } - - /* - private void runLoadMaxFcst(String locationId, String physicalElement, String typeSource) - { -// get the database name and build the command line arguments for the - // load max forecast program - - String cmdLineArgString = null; - String dbName = _db.getDatabaseName(); - int returnCode = 0; - - // check if there is a value for db_name - if (dbName != null) - { - if (dbName.length() != 0) - { - cmdLineArgString = " -d" + dbName + - " -l" + locationId + - " -p" + physicalElement + - " -t" + typeSource; - } - - - String osSuffix = ".LX"; - - - EnvHelper envHelper = new EnvHelper(); - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - String programPath = dirString + "/load_maxfcst" + osSuffix; - - String commandString = programPath + " " + cmdLineArgString; - - - try - { - _logger.log("executing " + commandString); - Process process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - - _logger.log("Completed execution of " + commandString); - - returnCode = process.exitValue(); - } - catch(IOException e) - { - e.printStackTrace(); - } - - catch( InterruptedException e ) - { - e.printStackTrace(); - } - - if (returnCode != 0) - { - System.out.println("returnCode from loadMaxFcst=" + returnCode); - } - - } - - } //end runLoadMaxFcst - */ - - // ------------------------------------------------------- - - - private boolean saveFcstHeightTs( FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, - int hoursToSave ) - { - boolean success = false; - MeasuringUnit dbUnit = MeasuringUnit.feet; - - saveToIngestFilterIfNeeded(descriptor); - - FcstHeightTable table = new FcstHeightTable( _db ); - FcstHeightRecord record = new FcstHeightRecord(); - long startTime, endTime, interval; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - - //adjust the endtime - long possibleEndTime = startTime + ((hoursToSave-1)*HOUR_IN_MILLIS); - if (possibleEndTime <= endTime) - { - endTime = possibleEndTime; - } - - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - - record.setLid( descriptor.getLid() ); - record.setPe( descriptor.getPe() ); - record.setTs( descriptor.getTs() ); - record.setExtremum( descriptor.getExtremum() ); - record.setShef_qual_code( descriptor.getShef_qual_code() ); - record.setProduct_id( descriptor.getProduct_id() ); - record.setProbability( descriptor.getProbability() ); - record.setQuality_code( descriptor.getQuality_code() ); - record.setRevision( descriptor.getRevision() ); - record.setDur( descriptor.getDur() ); - record.setProducttime( descriptor.getProducttime() ); - record.setBasistime( descriptor.getBasistime() ); - record.setPostingtime( System.currentTimeMillis() ); - - int recordCount = 0; - int insertOrUpdateCount = 0; - int failureCount = 0; - int skippedCount = 0; - - - - for ( long time = startTime; time <= endTime; time += interval ) - { - Measurement measurement = timeSeries.getMeasurementByTime( time ); - - record.setValidtime( time ); - record.setValue( measurement.getValue(dbUnit) ); - - recordCount++; - - if ( record.getValue() >= 0.0) - { - - try - { - table.insertOrUpdate( record ); - insertOrUpdateCount++; - //System.out.println("count = " + count); - } - catch ( SQLException e ) - { - failureCount++; - logSQLException(e); - _logger.log("failed record # = " + recordCount); - } - } - else - { - skippedCount++; - //_logger.log("DataMgr.saveFcstHeight(): measurement = " + - // measurement + - // " record = " + record); - } - } - - _logger.log("DataMgr.saveFcstHeight(): " + - " recordCount = " + recordCount + - " insertOrUpdateCount = " + insertOrUpdateCount + - " failureCount = " + failureCount + - " skippedCount = " + skippedCount); - - if ((insertOrUpdateCount + skippedCount) == recordCount) - { - success = true; - } - - if (_shouldSaveCrestMeasurement) - { - saveHeightCrestMeasurement(table, record, startTime, endTime, timeSeries); - } - - postMaxFcst(descriptor.getLid(), descriptor.getPe(), descriptor.getTs()); - - - return success; - - } - - -// ------------------------------------------------------- - private boolean saveFcstDischargeTs( FcstTsDescriptor descriptor, - RegularTimeSeries timeSeries, - int hoursToSave) - { - boolean success = false; - MeasuringUnit dbUnit = MeasuringUnit.cfs; - - - saveToIngestFilterIfNeeded(descriptor); - - FcstDischargeTable table = new FcstDischargeTable( _db ); - FcstDischargeRecord record = new FcstDischargeRecord(); - long startTime, endTime, interval; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - -// adjust the endtime - long possibleEndTime = startTime + ((hoursToSave-1)*HOUR_IN_MILLIS); - if (possibleEndTime <= endTime) - { - endTime = possibleEndTime; - } - - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - - record.setLid( descriptor.getLid() ); - record.setPe( descriptor.getPe() ); - record.setTs( descriptor.getTs() ); - record.setExtremum( descriptor.getExtremum() ); - record.setShef_qual_code( descriptor.getShef_qual_code() ); - record.setProduct_id( descriptor.getProduct_id() ); - record.setProbability( descriptor.getProbability() ); - record.setQuality_code( descriptor.getQuality_code() ); - record.setRevision( descriptor.getRevision() ); - record.setDur( descriptor.getDur() ); - record.setProducttime( descriptor.getProducttime() ); - record.setBasistime( descriptor.getBasistime() ); - record.setPostingtime( System.currentTimeMillis() ); - - int recordCount = 0; - int insertOrUpdateCount = 0; - int failureCount = 0; - int skippedCount = 0; - - for ( long time = startTime; time <= endTime; time += interval ) - { - Measurement measurement = timeSeries.getMeasurementByTime( time ); - - record.setValidtime( time ); - record.setValue( measurement.getValue(dbUnit) ); - - recordCount++; - - if ( record.getValue() >= 0.0) - { - - try - { - table.insertOrUpdate( record ); - insertOrUpdateCount++; - //System.out.println("count = " + count); - } - catch ( SQLException e ) - { - failureCount++; - logSQLException(e); - _logger.log("failed record # = " + recordCount); - } - } - else - { - skippedCount++; - // _logger.log("DataMgr.saveFcstDischarge(): measurement = " + - // measurement + - // " record = " + record); - } - } - - _logger.log("DataMgr.saveFcstDischarge(): " + - " recordCount = " + recordCount + - " insertOrUpdateCount = " + insertOrUpdateCount + - " failureCount = " + failureCount + - " skippedCount = " + skippedCount); - - if ((insertOrUpdateCount + skippedCount) == recordCount) - { - success = true; - } - - if (_shouldSaveCrestMeasurement) - { - saveDischargeCrestMeasurement(table, record, startTime, endTime, timeSeries); - } - - postMaxFcst(descriptor.getLid(), descriptor.getPe(), descriptor.getTs()); - - - return success; - - } - -//------------------------------------------------------- - private void saveHeightCrestMeasurement(FcstHeightTable table, FcstHeightRecord record, - long startTime, long endTime, - RegularTimeSeries timeSeries) - { - - AbsTimeMeasurement crestMeasurement = timeSeries.getMaxMeasurement(startTime, endTime); - record.setValue(crestMeasurement.getValue()); - record.setValidtime(crestMeasurement.getTime()); - record.setExtremum("X"); - - FcstTsDescriptor descriptor = new FcstTsDescriptor("FcstHeight"); - descriptor.setLid(record.getLid()); - descriptor.setPe(record.getPe()); - descriptor.setTs(record.getTs()); - descriptor.setExtremum(record.getExtremum()); - descriptor.setDur(record.getDur()); - - saveToIngestFilterIfNeeded(descriptor); - - - try - { - table.insertOrUpdate(record); - } - catch(SQLException e) - { - logSQLException(e); - _logger.log("failed to insert crest for FcstHeight record = " + record); - } - return; - } - -// ------------------------------------------------------- - private void saveDischargeCrestMeasurement(FcstDischargeTable table, FcstDischargeRecord record, - long startTime, long endTime, - RegularTimeSeries timeSeries) - { - - AbsTimeMeasurement crestMeasurement = timeSeries.getMaxMeasurement(startTime, endTime); - record.setValue(crestMeasurement.getValue()); - record.setValidtime(crestMeasurement.getTime()); - record.setExtremum("X"); - - FcstTsDescriptor descriptor = new FcstTsDescriptor("FcstHeight"); - descriptor.setLid(record.getLid()); - descriptor.setPe(record.getPe()); - descriptor.setTs(record.getTs()); - descriptor.setExtremum(record.getExtremum()); - descriptor.setDur(record.getDur()); - - saveToIngestFilterIfNeeded(descriptor); - - try - { - table.insertOrUpdate(record); - } - catch(SQLException e) - { - logSQLException(e); - _logger.log("failed to insert crest for FcstDischarge record = " + record); - } - return; - } - -//------------------------------------------------------- - private void saveToIngestFilterIfNeeded(IngestFilterTsDescriptor descriptor) - { - String header = "DataMgr.saveToIngestFilterIfNeeded(): "; - // System.out.println(header + "inside"); - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = new IngestFilterRecord(); - - record.setLid( descriptor.getLid() ); - record.setPe( descriptor.getPe() ); - record.setTs( descriptor.getTs() ); - record.setExtremum( descriptor.getExtremum() ); - record.setDur( descriptor.getDur() ); - - record.setTs_rank((short)1); - record.setIngest("T"); - record.setOfs_input("F"); - record.setStg2_input("F"); - - try - { - String whereString = record.getWhereString(); - int recordCount = table.selectCount(whereString); - - - if (recordCount < 1) - { - System.out.println(header + " Attempting to insert" + record); - - table.insert(record); - } - } - catch(SQLException e) - { - logSQLException(e); - - } - - return; - } - -// ------------------------------------------------------- - private void saveToIngestFilter(IngestFilterTsDescriptor descriptor) - { - // String header = "DataMgr.saveToIngestFilter(): "; - - // System.out.println(header + "inside"); - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = new IngestFilterRecord(); - - record.setLid( descriptor.getLid() ); - record.setPe( descriptor.getPe() ); - record.setTs( descriptor.getTs() ); - record.setExtremum( descriptor.getExtremum() ); - record.setDur( descriptor.getDur() ); - - record.setTs_rank((short)1); - record.setIngest("T"); - record.setOfs_input("F"); - record.setStg2_input("F"); - - try - { - System.out.println("Attempting to insert" + record); - table.insert(record); - - } - catch(SQLException e) - { - logSQLException(e); - - } - - return; - } - -// ------------------------------------------------------- - - -// ------------------------------------------------------- - - - public void deleteState( SacSmaState sacSmaState ) - { - SacSmaStateTable table = new SacSmaStateTable( _db ); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id( sacSmaState.getBasinId() ); - record.setSource( sacSmaState.getSource() ); - record.setValidtime( sacSmaState.getValidTime() ); - record.setBasistime( sacSmaState.getBasisTime() ); - record.setPostingtime( sacSmaState.getPostingTime() ); - - record.setUztwc( sacSmaState.getUztwc() ); - record.setUzfwc( sacSmaState.getUzfwc() ); - record.setLztwc( sacSmaState.getLztwc() ); - record.setLzfsc( sacSmaState.getLzfsc() ); - record.setLzfpc( sacSmaState.getLzfpc() ); - record.setAdimc( sacSmaState.getAdimc() ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } - -// ------------------------------------------------------- - - - public void deleteParams( SacSmaParameters sacSmaParams ) - { - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - record.setBasin_id( sacSmaParams.getBasinId() ); - record.setSource(sacSmaParams.getSource()); - record.setValidtime(sacSmaParams.getValidTime() ); - record.setPostingtime(sacSmaParams.getPostingTime()); - - record.setUztwm(sacSmaParams.getUztwm()); - record.setUzfwm(sacSmaParams.getUzfwm()); - record.setUzk(sacSmaParams.getUzk()); - record.setPctim(sacSmaParams.getPctim()); - record.setAdimp(sacSmaParams.getAdimp()); - record.setRiva(sacSmaParams.getRiva()); - record.setZperc(sacSmaParams.getZperc()); - record.setRexp(sacSmaParams.getRexp()); - record.setLztwm(sacSmaParams.getLztwm()); - record.setLzfsm(sacSmaParams.getLzfsm()); - record.setLzfpm(sacSmaParams.getLzfpm()); - record.setLzsk(sacSmaParams.getLzsk()); - record.setLzpk(sacSmaParams.getLzpk()); - record.setPfree(sacSmaParams.getPfree()); - record.setRserv(sacSmaParams.getRserv()); - record.setSide(sacSmaParams.getSide()); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } - -// ------------------------------------------------------- - public boolean hasSacSmaParams(String basinId) - { - boolean result = false; - - SacSmaParamsTable table = new SacSmaParamsTable(_db); - - String whereClause = "where basin_id = '" + basinId + "'"; - int count = 0; - - - try - { - count = table.selectCount(whereClause); - } - catch (SQLException e) - { - logSQLException(e); - } - - if (count > 0) - { - result = true; - } - - return result; - } -// ------------------------------------------------------- - public MonthlyValues loadMonthlyValues(String locationId, boolean isAdjustment) - { -// String header = "loadMonthlyValues():"; - - MonthlyValues monthlyValues = null; - - String baseWhereClause = "WHERE lid = '" + locationId + "' AND pe='EA'" ; - String whereClause = null; - - String adjustmentClause = null; - if (isAdjustment) - { - adjustmentClause = " AND adjustment = 'Y' AND dur = 1001 "; - } - else - { - adjustmentClause = " AND adjustment != 'Y' AND dur = 2001 "; - } - - whereClause = baseWhereClause + adjustmentClause; - - List monthlyValuesList = loadMonthlyValuesList(whereClause); - - // System.out.println(header + " whereClause = " + whereClause); - - if (monthlyValuesList.size() > 0) - { - monthlyValues = (MonthlyValues) monthlyValuesList.get(0); - } - else - { - monthlyValues = new MonthlyValues(); - } - - return monthlyValues; - - } //end getMonthlyValues - -// ------------------------------------------------------- - - public List loadMonthlyValuesList( String where ) - { - List monthlyValuesRecordList = null; - MonthlyValuesTable table = new MonthlyValuesTable( _db ); - - try - { - - monthlyValuesRecordList = table.select( where ); - - } - catch( SQLException e ) - { - _logger.log("Error code = " + e.getMessage()); - _logger.log("error retrieving SacSmaStateRecord: " + where ); - } - - return getMonthlyValuesListFromMonthlyValuesRecordList( monthlyValuesRecordList ); - } - -// ------------------------------------------------------- - - private List getMonthlyValuesListFromMonthlyValuesRecordList( List monthlyValuesRecordList ) - { - List monthlyValuesList = new ArrayList(); - - for( int i = 0; i < monthlyValuesRecordList.size(); i++ ) - { - MonthlyValues addMonthlyValues = new MonthlyValues(); - MonthlyValuesRecord monthlyValuesRecord = (MonthlyValuesRecord) monthlyValuesRecordList.get( i ); - double[] valueArray = new double[ 12 ]; - - addMonthlyValues.setBasinId(monthlyValuesRecord.getLid()); - addMonthlyValues.setPe( monthlyValuesRecord.getPe() ); - addMonthlyValues.setDur( monthlyValuesRecord.getDur() ); - addMonthlyValues.setTs( monthlyValuesRecord.getTs() ); - addMonthlyValues.setExtremum( monthlyValuesRecord.getExtremum() ); - if ( monthlyValuesRecord.getAdjustment().equalsIgnoreCase( "Y" ) ) - { - addMonthlyValues.setAdjustment( true ); - } - else - { - addMonthlyValues.setAdjustment( false ); - } - addMonthlyValues.setPostingTime(monthlyValuesRecord.getPostingtime()); - - valueArray[ 0 ] = monthlyValuesRecord.getJan_value(); - valueArray[ 1 ] = monthlyValuesRecord.getFeb_value(); - valueArray[ 2 ] = monthlyValuesRecord.getMar_value(); - valueArray[ 3 ] = monthlyValuesRecord.getApr_value(); - valueArray[ 4 ] = monthlyValuesRecord.getMay_value(); - valueArray[ 5 ] = monthlyValuesRecord.getJun_value(); - valueArray[ 6 ] = monthlyValuesRecord.getJul_value(); - valueArray[ 7 ] = monthlyValuesRecord.getAug_value(); - valueArray[ 8 ] = monthlyValuesRecord.getSep_value(); - valueArray[ 9 ] = monthlyValuesRecord.getOct_value(); - valueArray[ 10 ] = monthlyValuesRecord.getNov_value(); - valueArray[ 11 ] = monthlyValuesRecord.getDec_value(); - - addMonthlyValues.setValues( valueArray ); - - monthlyValuesList.add( addMonthlyValues ); - } - - return monthlyValuesList; - } - -// ------------------------------------------------------- - - public void saveMonthlyValues( MonthlyValues monthlyValues ) - { - MonthlyValuesTable table = new MonthlyValuesTable( _db ); - MonthlyValuesRecord record = new MonthlyValuesRecord(); - long currentTime = System.currentTimeMillis(); - double[] valueArray = monthlyValues.getValueArray(); - - record.setLid( monthlyValues.getBasinId() ); - record.setPe( monthlyValues.getPe() ); - record.setDur( monthlyValues.getDur() ); - record.setTs( monthlyValues.getTs() ); - record.setExtremum( monthlyValues.getExtremum() ); - if ( monthlyValues.isAdjustment() ) - { - record.setAdjustment( "Y" ); - } - else - { - record.setAdjustment( "N" ); - } - record.setPostingtime( currentTime ); - record.setJan_value( valueArray[ 0 ] ); - record.setFeb_value( valueArray[ 1 ] ); - record.setMar_value( valueArray[ 2 ] ); - record.setApr_value( valueArray[ 3 ] ); - record.setMay_value( valueArray[ 4 ] ); - record.setJun_value( valueArray[ 5 ] ); - record.setJul_value( valueArray[ 6 ] ); - record.setAug_value( valueArray[ 7 ] ); - record.setSep_value( valueArray[ 8 ] ); - record.setOct_value( valueArray[ 9 ] ); - record.setNov_value( valueArray[ 10 ] ); - record.setDec_value( valueArray[ 11 ] ); - try - { - table.insertOrUpdate( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } - -// ------------------------------------------------------- - - public void deleteMonthlyValues( MonthlyValues monthlyValues ) - { - MonthlyValuesTable table = new MonthlyValuesTable( _db ); - MonthlyValuesRecord record = new MonthlyValuesRecord(); - double[] valueArray = monthlyValues.getValueArray(); - - record.setLid( monthlyValues.getBasinId() ); - record.setPe( monthlyValues.getPe() ); - record.setDur( monthlyValues.getDur() ); - record.setTs( monthlyValues.getTs() ); - record.setExtremum( monthlyValues.getExtremum() ); - if ( monthlyValues.isAdjustment() ) - { - record.setAdjustment( "Y" ); - } - else - { - record.setAdjustment( "N" ); - } - record.setPostingtime( monthlyValues.getPostingTime() ); - record.setJan_value( valueArray[ 0 ] ); - record.setFeb_value( valueArray[ 1 ] ); - record.setMar_value( valueArray[ 2 ] ); - record.setApr_value( valueArray[ 3 ] ); - record.setMay_value( valueArray[ 4 ] ); - record.setJun_value( valueArray[ 5 ] ); - record.setJul_value( valueArray[ 6 ] ); - record.setAug_value( valueArray[ 7 ] ); - record.setSep_value( valueArray[ 8 ] ); - record.setOct_value( valueArray[ 9 ] ); - record.setNov_value( valueArray[ 10 ] ); - record.setDec_value( valueArray[ 11 ] ); - - try - { - table.delete( record ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - } - -// ------------------------------------------------------- - - private SshpConfigRecord getSshpConfigRecord(SSHPConfig config) - { - SshpConfigRecord record = new SshpConfigRecord(); - - record.setLid(config.getLid()); - record.setBasin_id(config.getBasinId()); - record.setPostingtime(config.getPostingTime()); - - record.setModel_pref(config.getModelPref()); - record.setSource_pref(config.getSourcePref()); - - // convert and set boolean Y or N strings - record.setUse_static_evap(getStringFromBoolean(config.useStaticEvap())); - record.setAuto_process(getStringFromBoolean(config.isAutoProcess())); - record.setUse_blend(getStringFromBoolean(config.useBlend())); - - record.setBlend_method(config.getBlendMethod().getName()); - record.setBlend_hours(config.getBlendHours()); - - - - return record; - } - -// ------------------------------------------------------- - public SSHPConfig getSSHPConfig(String locationId) - { - String header = "DataMgr.getSshpConfig(): "; - SSHPConfig config = null; - - config = (SSHPConfig) _sshpConfigMap.get(locationId); - if (config == null) - { - String whereClause = " "; - loadSSHPConfigList(whereClause); //throw out the returned list, we don't need it - config = (SSHPConfig) _sshpConfigMap.get(locationId); - } - - return config; - - } - -// ------------------------------------------------------- - - - - private SSHPConfig getSshpConfigFromRecord(SshpConfigRecord record) - { - SSHPConfig config = new SSHPConfig(); - - config.setLid(record.getLid()); - - config.setBasinId( record.getBasin_id()); - config.setPostingTime( record.getPostingtime()); - - config.setModelPref( record.getModel_pref()); - config.setSourcePref( record.getSource_pref()); - - config.setUseStaticEvap(getBooleanFromString(record.getUse_static_evap())); - config.setAutoProcess(getBooleanFromString(record.getAuto_process())); - - config.setUseBlend(getBooleanFromString(record.getUse_blend())); - - - ForecastInterpolationMethod method = ForecastInterpolationMethod.getMethodByName(record.getBlend_method()); - config.setBlendMethod(method); - - - config.setBlendHours(record.getBlend_hours()); - - return config; - } - -// ------------------------------------------------------- - private boolean getBooleanFromString(String booleanString) - { - boolean result = false; - if (booleanString.equalsIgnoreCase("Y")) - { - result = true; - } - - return result; - } -// ------------------------------------------------------- - private String getStringFromBoolean(boolean value) - { - String resultString = null; - if (value) - { - resultString = "Y"; - } - else - { - resultString = "N"; - } - - return resultString; - } -// ------------------------------------------------------- - - public void saveSSHPConfig(SSHPConfig config) - { - - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = getSshpConfigRecord(config); - - record.setPostingtime(System.currentTimeMillis()); - - try - { - table.insertOrUpdate(record); - } - catch (SQLException e) - { - logSQLException(e); - } - - - return; - - } -// ------------------------------------------------------- - - public void deleteSSHPConfig(SSHPConfig config) - { - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = getSshpConfigRecord(config); - - try - { - table.delete(record); - _sshpConfigMap.remove(record.getLid()); - } - catch (SQLException e) - { - logSQLException(e); - } - - return; - - } - -// ------------------------------------------------------- - public List getSSHPConfigList() - { - if (_sshpConfigList == null) - { - _sshpConfigList = loadSSHPConfigList(" order by lid "); - } - - return _sshpConfigList; - - } - -// ------------------------------------------------------- - - public List loadSSHPConfigList(String whereClause) - { - SshpConfigTable table = new SshpConfigTable(_db); - SshpConfigRecord record = null; - List recordList = null; - - _sshpConfigList = new ArrayList(); - - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (SshpConfigRecord) recordList.get(i); - SSHPConfig config = getSshpConfigFromRecord(record); - _sshpConfigList.add(config); - _sshpConfigMap.put(config.getLid(), config); - } - - } - catch (SQLException e) - { - logSQLException(e); - } - - return _sshpConfigList; - - } -// ------------------------------------------------------- - - public List loadAllPreferredSacSmaBasinIds() - { - List locationIdList = new ArrayList(); - List sshpConfigList = getSSHPConfigList(); - - for (int i = 0 ; i < sshpConfigList.size(); i++) - { - SSHPConfig config = (SSHPConfig) sshpConfigList.get(i); - String basinId = config.getLid(); - - if ( config.getModelPref().equals(RainfallRunoffModelType.SAC_SMA.getName()) - ) - { - locationIdList.add(basinId); - } - } - - return locationIdList; - } -// ------------------------------------------------------- - public List loadAllLocationIdsToAutoUpdateSacStates() - { - List locationIdList = new ArrayList(); - List sshpConfigList = getSSHPConfigList(); - - for (int i = 0 ; i < sshpConfigList.size(); i++) - { - SSHPConfig config = (SSHPConfig) sshpConfigList.get(i); - String locationId = config.getLid(); - - if ( (config.getModelPref().equals(RainfallRunoffModelType.SAC_SMA.getName())) && - (config.isAutoProcess()) - ) - { - locationIdList.add(locationId); - } - } - - return locationIdList; - } -// ------------------------------------------------------- - - public RainfallRunoffModelType getPreferredRainfallRunoffModelType(String locationId) - { - String header = "DataMgr.getPreferredRainfallRunoffModelType(): "; - RainfallRunoffModelType type = RainfallRunoffModelType.API_MKC; - - SSHPConfig config = getSSHPConfig(locationId); - - if (config != null) - { - String modelPref = config.getModelPref(); - - _logger.log(header + "modelPref = :" + modelPref + ":"); - - type = RainfallRunoffModelType.getRainfallRunoffModelTypeByName(modelPref); - } - - _logger.log(header + "type = " + type); - - - return type; - } - -// --------------------------------------------------------------------------------------- - - public BasinHrapHelper getBasinHrapHelper(String basinId) - { - - BasinHrapHelper basinHrapHelper = (BasinHrapHelper) _basinHelperMap.get(basinId); - if (basinHrapHelper == null) - { - basinHrapHelper = loadBasinHrapHelper(basinId); - if (basinHrapHelper != null) - { - _basinHelperMap.put(basinId, basinHrapHelper); - } - - } - - return basinHrapHelper; - } - - // --------------------------------------------------------------------------------------- - - public BasinHrapHelper loadBasinHrapHelper(String basinId) - { - - BasinHrapHelper basinHrapHelper = initBasinHrapHelper(basinId); - - return basinHrapHelper; - } -// ---------------------------------------------------------------------------------------- - - private BasinHrapHelper initBasinHrapHelper(String basinId) - { - List recordList = null; - String whereClause = new String(); - - LineSegsTable table = new LineSegsTable(this._db); - LineSegsRecord record = null; - - BasinHrapHelper basinHrapSet = null; - - - // Go to LineSegs table to get number of rows and HRAP rows and columns - whereClause = " WHERE area_id='" + basinId + "' ORDER BY hrap_row ASC "; - - try - { - recordList = table.select(whereClause); - } - catch (SQLException e) - { - e.printStackTrace(); - } - - for (int i = 0; i < recordList.size(); i++) - { - record = (LineSegsRecord) recordList.get(i); - - if (i == 0) - { - basinHrapSet = new BasinHrapHelper(basinId, recordList.size()); - basinHrapSet.setIsValid(true); - basinHrapSet.setAreaSize( record.getArea() ); - } - - basinHrapSet.setBasinHrapRow(i, record.getHrap_row()); - basinHrapSet.setBasinHrapBegColumn(i, record.getHrap_beg_col()); - basinHrapSet.setBasinHrapEndColumn(i, record.getHrap_end_col()); - } - - if (basinHrapSet == null) - { - basinHrapSet = new BasinHrapHelper(basinId, 0); - basinHrapSet.setIsValid(false); - } - - return(basinHrapSet); - - } // end of getBasinRowsCols method - -// ------------------------------------------------------------------------------------------------- - public long getLatestVarSacSmaStatePostingTime(SSHPSource source) - { - long latestPostingTime = -1; - List recordList = null; - SacSmaStateTable table = new SacSmaStateTable(_db); - - String whereString = "WHERE source = '" + source.getSacSmaSource() + "' ORDER BY postingtime DESC "; - - try - { - recordList = table.selectNRecords(whereString, 1); - - if (recordList.size() > 0) - { - SacSmaStateRecord record = (SacSmaStateRecord) recordList.get(0); - latestPostingTime = record.getPostingtime(); - } - } - catch (SQLException exception) - { - logSQLException(exception); - } - - return latestPostingTime; - } -// ------------------------------------------------------------------------------------------------- - - /** - * This method is used by the SSHP MAP Preprocessor to determine what hours (if any) to rerun. - * It is also used by VAR to determine what hours (if any) to rerun. - */ - public List getNewerBestQpeXmrgFileTimeList(long lastPostingTime) - { - - String header = "DataMgr.getNewerBestQpeXmrgFileTimeList(): "; - - RWResultTable table = new RWResultTable(_db); - RWResultRecord record = null; - List recordList = null; - - List timeList = new ArrayList(); - - - try - { - String lastPostingTimeString = DbTimeHelper.getDateTimeStringFromLongTime(lastPostingTime); - String whereString = " WHERE last_save_time >= '" + lastPostingTimeString + "' ORDER BY obstime "; - - - System.out.println(header + " whereString = " + whereString); - recordList = table.select(whereString); - - for (int i = 0 ; i < recordList.size(); i++) - { - record = (RWResultRecord) recordList.get(i); - - long time = record.getObstime(); - timeList.add(new Long(time)); - } - - } - - catch (SQLException e) - { - logSQLException(e); - } - - - return timeList; - - } - -// ------------------------------------------------------------------------------------------------- - public List getNewerRfcXmrgFileTimeList(long lastPostingTime) - { - String header = "DataMgr.getNewerRfcXmrgTimeList(1 arg): "; - System.out.println(header); - - String rfcQpeGridDirName = _appsDefaults.getToken("gaq_xmrg_1hr_dir"); - - System.out.println(header + " after _appsDefaults"); - - // rfc mosaic file name format - SimpleDateFormat rfcXmrgFileDateFormat = new SimpleDateFormat("'RFCMOSAIC01'yyyyMMddHH'z'"); - rfcXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - return getNewerRfcXmrgFileTimeList(lastPostingTime, rfcQpeGridDirName, rfcXmrgFileDateFormat); - } - -// ------------------------------------------------------------------------------------------------- - - public List getNewerRfcXmrgFileTimeList(long lastPostingTime, - String gridDirectoryString, - SimpleDateFormat dateFormat) - { - String header = "DataMgr.getNewerRfcXmrgTimeList(3 args): "; - System.out.println(header); - List timeList = new ArrayList(); - - System.out.println(header + " lastPostingTime = " + lastPostingTime + - " gridDirectoryString = " + gridDirectoryString + - "dateFormat = " + dateFormat); - System.out.flush(); - - File[] fileArray = null; - File directory = new File(gridDirectoryString); - - if (directory != null) - { - fileArray = directory.listFiles(); - } - - // for each file in the directory - // examine the last update time, - // if it is newer than the last update time, - // then parse out its time and then add it to the list - // If it fails to parse, then we don't want it anyway; - // It is some other type of file that got in the directory somehow. - if (fileArray != null) - { - for (int i = 0 ; i < fileArray.length; i++) - { - File file = fileArray[i]; - long lastModTime = 0; - try - { - - - lastModTime = file.lastModified(); - if (lastModTime >= lastPostingTime) //is it new? - { - _logger.log(header + - "lastModTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(lastModTime) + - " fileName = " + file.getName() ); - - Date date = dateFormat.parse(file.getName()); - long gridTime = date.getTime(); - - _logger.log(header + - "gridTime = " + - DbTimeHelper.getDateTimeStringFromLongTime(gridTime) + - " fileName = " + file.getName() ); - - - timeList.add( (new Long(gridTime)) ); - } - } - catch (ParseException e) - { - //some other kind of file was parsed, - //we don't want it - } - } - } - - return timeList; - - } - -// ------------------------------------------------------------------------------------------------- - - - public List loadUnitHydrographEntryList( String lid, String orderClause ) - // Used by UnitHydrographEditor to retrieve data from the UnitGraph table - { - List unitHydrographRecordList = null; - String where = " WHERE lid='" + lid + "' " + orderClause; - UnitGraphTable table = new UnitGraphTable( _db ); - - try - { - unitHydrographRecordList = table.select( where ); - } - - catch( SQLException e ) - { - logSQLException(e); - } - - return getUnitHydrographEntryListFromUnitGraphRecordList( unitHydrographRecordList ); - } - -// ------------------------------------------------------------------------------------------------- - - public List loadUnitHydrographDescriptorList(String lid) - { - List descList = new ArrayList(); - UnitGraphTable table = new UnitGraphTable( _db ); - List recordList = null; - - String where = " WHERE lid='" + lid + "' ORDER BY area_id, model, dur "; - - String oldAreaId = null; - String oldModel = null; - int oldDur = 0; - - try - { - recordList = table.select( where ); - - boolean addToDescriptorList = false; - - for (int i = 0; i < recordList.size(); i++) - { - UnitGraphRecord record = (UnitGraphRecord) recordList.get(i); - - if (i > 0) - { - // if the record is not the same as the previous record then add it to the - //list - if ((! record.getArea_id().equals(oldAreaId)) || - (! record.getModel().equals(oldModel)) || - ( record.getDur() != oldDur)) - { - addToDescriptorList = true; - } - - } - else // i == 0, there are no "old" variables - { - addToDescriptorList = true; - - } - - if (addToDescriptorList) - { - UnitHydrographDescriptor desc = new UnitHydrographDescriptor(record.getLid(), - record.getArea_id(), record.getModel(), record.getDur()); - - descList.add(desc); - - addToDescriptorList = false; - } - - // set the "old" variables for next iteration - oldAreaId = record.getArea_id(); - oldModel = record.getModel(); - oldDur = record.getDur(); - - - } - } - - catch( SQLException e ) - { - logSQLException(e); - } - - /* - for (int i = 0; i < descList.size(); i++) - { - UnitHydrographDescriptor desc = (UnitHydrographDescriptor) descList.get(i); - System.out.println(desc); - } - */ - - return descList; - - } // loadUnitHydrographDescriptorList - -// ------------------------------------------------------------------------------------------------- - - private List getUnitHydrographEntryListFromUnitGraphRecordList( List unitGraphRecordList ) - { - List unitHydrographEntryList = new ArrayList(); - - for( int i = 0; i < unitGraphRecordList.size(); i++ ) - { - UnitHydrographEntry newUnitHydrographEntry = new UnitHydrographEntry(); - UnitGraphRecord unitGraphRecord = (UnitGraphRecord) unitGraphRecordList.get( i ); - - newUnitHydrographEntry.setLocationId( unitGraphRecord.getLid() ); - newUnitHydrographEntry.setAreaId( unitGraphRecord.getArea_id() ); - newUnitHydrographEntry.setModel(unitGraphRecord.getModel()); - newUnitHydrographEntry.setDur( unitGraphRecord.getDur() ); - newUnitHydrographEntry.setOrdinal( unitGraphRecord.getOrdinal() ); - - newUnitHydrographEntry.setDischarge( unitGraphRecord.getDischarge() ); - - - unitHydrographEntryList.add( newUnitHydrographEntry ); - } - - return unitHydrographEntryList; - } - -// ------------------------------------------------------------------------------------------------- - - - public List getRatingShift( String lid ) - // Used by RatingCurveEditor to retrieve data from the RatingShift table - { - List ratingShiftRecordList = null; - String where = " WHERE lid='" + lid + "' ORDER BY date desc"; - RatingShiftTable table = new RatingShiftTable( _db ); - - try - { - ratingShiftRecordList = table.select( where ); - } - catch( SQLException e ) - { - _logger.log("Error code = " + e.getMessage()); - _logger.log("error retrieving SacSmaStateRecord: " + where ); - } - - List ratingShiftEntryList = null; - - if (ratingShiftRecordList != null) - { - ratingShiftEntryList = getRatingShiftEntryListFromRatingShiftRecordList( ratingShiftRecordList ); - } - - return ratingShiftEntryList; - } - -// ------------------------------------------------------------------------------------------------- - - - private List getRatingShiftEntryListFromRatingShiftRecordList( List recordList ) - { - List ratingShiftEntryList = new ArrayList(); - - for( int i = 0; i < recordList.size(); i++ ) - { - RatingShift addRatingShiftEntry = new RatingShift(); - RatingShiftRecord record = (RatingShiftRecord) recordList.get( i ); - - addRatingShiftEntry.setLid( record.getLid() ); - addRatingShiftEntry.setDate( record.getDate() ); - addRatingShiftEntry.setShiftAmount( record.getShift_amount() ); - - if ( record.getActive().trim().equalsIgnoreCase( "T" ) ) - { - addRatingShiftEntry.setActive( true ); - } - else - { - addRatingShiftEntry.setActive( false ); - } - - ratingShiftEntryList.add( addRatingShiftEntry ); - } - return ratingShiftEntryList; - } - - -// ------------------------------------------------------------------------------------------------- - - - public void saveUnitHydrographEntry( UnitHydrographEntry entry ) - { - UnitGraphRecord record = new UnitGraphRecord(); - UnitGraphTable table = new UnitGraphTable( _db ); - - record = getUnitGraphRecordFromUnitHydrographEntry( entry ); - - try - { - table.insertOrUpdate( record ); - } - catch( SQLException e) - { - logSQLException(e); - } - } - - -// ------------------------------------------------------------------------------------------------- - - private UnitGraphRecord getUnitGraphRecordFromUnitHydrographEntry( UnitHydrographEntry entry ) - { - UnitGraphRecord returnRecord = new UnitGraphRecord(); - - returnRecord.setLid( entry.getLocationId() ); - returnRecord.setArea_id( entry.getAreaId() ); - returnRecord.setModel(entry.getModel()); - returnRecord.setDur( entry.getDur() ); - returnRecord.setOrdinal( entry.getOrdinal() ); - - returnRecord.setDischarge( entry.getDischarge() ); - - - return returnRecord; - } - -// ------------------------------------------------------------------------------------------------- - - - public void removeUnitHydrographEntry( UnitHydrographEntry entry ) - { - UnitGraphRecord record = new UnitGraphRecord(); - UnitGraphTable table = new UnitGraphTable( _db ); - - record = getUnitGraphRecordFromUnitHydrographEntry( entry ); - - try - { - table.delete( record ); - } - catch( SQLException e) - { - logSQLException(e); - } - } - -// ------------------------------------------------------------------------------------------------- - - - public void deleteUnitHydrograph( String lid, String basinId, String model, int duration ) - { - UnitGraphTable table = new UnitGraphTable( _db ); - String whereString = " WHERE lid='" + lid + "' AND area_id='" + basinId + "' AND model = '" + - model + "' AND dur = " + duration; - - try - { - table.delete( whereString ); - } - catch ( SQLException e ) - { - logSQLException( e ); - } - } - -// ------------------------------------------------------------------------------------------------- - - public void deleteRatingShift( RatingShift shift ) - { - RatingShiftRecord record = new RatingShiftRecord(); - RatingShiftTable table = new RatingShiftTable( _db ); - - record = getRatingShiftRecordFromRatingShift( shift ); - try - { - table.delete( record ); - } - catch( SQLException e) - { - logSQLException(e); - } - } - - public void saveRatingShift( RatingShift shift ) - { - RatingShiftRecord record = new RatingShiftRecord(); - RatingShiftTable table = new RatingShiftTable( _db ); - - record = getRatingShiftRecordFromRatingShift( shift ); - - try - { - table.insertOrUpdate( record ); - } - catch( SQLException e) - { - logSQLException(e); - } - - } - - private RatingShiftRecord getRatingShiftRecordFromRatingShift( RatingShift shift ) - { - RatingShiftRecord record = new RatingShiftRecord(); - - record.setLid( shift.getLid() ); - record.setDate( shift.getDate() ); - record.setShift_amount( shift.getShiftAmount() ); - if ( shift.isActive() ) - { - record.setActive( "T" ); - } - else - { - record.setActive( "F" ); - } - return record; - } - - /* private void insertParams(String locationId) - { - SacSmaParamsTable table = new SacSmaParamsTable(_db); - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - long currentTime = System.currentTimeMillis(); - - - record.setBasin_id(locationId); - - record.setValidtime(currentTime); - record.setPostingtime(currentTime); - - record.setUztwm(65.0); - record.setUzfwm(30.0); - record.setUzk(0.180); - record.setPctim(0.010); - record.setAdimp(0.130); - record.setRiva(0.03); - record.setZperc(125.0); - record.setRexp(3.5); - record.setLztwm(175.0); - record.setLzfsm(100.0); - record.setLzfpm(260.0); - record.setLzsk(0.0450); - record.setLzpk(0.0030); - record.setPfree(0.60); - record.setRserv(0.30); - record.setSide(0.00); - - try - { - table.insert(record); - } - catch (SQLException e) - { - logSQLException(e); - } - } -*/ -// ------------------------------------------------------- -/* private void insertState(String locationId) - { - SacSmaStateTable table = new SacSmaStateTable(_db); - SacSmaStateRecord record = new SacSmaStateRecord(); - - long currentTime = System.currentTimeMillis(); - - record.setBasin_id(locationId); - - record.setValidtime(currentTime); - record.setPostingtime(currentTime); - - record.setUztwc(63.33); - record.setUzfwc(0.090); - record.setLztwc(135.71); - record.setLzfsc(12.187); - record.setLzfpc(165.26); - record.setAdimc(215.75); - - try - { - table.insert(record); - } - catch (SQLException e) - { - logSQLException(e); - } - } -*/ - -} //end class DataMgr diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/FFHDescriptor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/FFHDescriptor.java deleted file mode 100644 index 2c54b93b2e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/FFHDescriptor.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Created on Apr 19, 2004 - * - * - */ -package ohd.hseb.sshp; - -import ohd.hseb.measurement.*; - -import java.util.Date; -import java.util.TimeZone; -import java.text.*; - -/** - * @author GobsC - * - * - */ -public class FFHDescriptor -{ - private String _locationId = null; - - private AbsTimeMeasurement _ffhMeasurement = null; - private int _ihfsDurationCode = 0; - - private boolean _isGridded = false; - private boolean _isDefaultValue = false; - - private String _description = null; - -// --------------------------------------------------------------- - - public FFHDescriptor(String locationId, - AbsTimeMeasurement measurement, - int ihfsDurationCode, - boolean isGridded) - { - _locationId = locationId; - _ffhMeasurement = measurement; - _ihfsDurationCode = ihfsDurationCode; - _isGridded = isGridded; - - return; - } - -// --------------------------------------------------------------- - - - - public void setFfhMeasurement(AbsTimeMeasurement ffhMeasurement) - { - _ffhMeasurement = ffhMeasurement; - } -// --------------------------------------------------------------- - - public Measurement getFfhMeasurement() - { - return _ffhMeasurement; - } -// --------------------------------------------------------------- - public double getValueInInches() - { - return _ffhMeasurement.getValue(MeasuringUnit.inches); - } -// --------------------------------------------------------------- - public long getTime() - { - return _ffhMeasurement.getTime(); - } - -// --------------------------------------------------------------- - - /** - * @param ihfsDurationCode The ihfsDurationCode to set. - */ - public void setIhfsDurationCode(int ihfsDurationCode) - { - _ihfsDurationCode = ihfsDurationCode; - } - -// --------------------------------------------------------------- - - /** - * @return Returns the ihfsDurationCode. - */ - public int getIhfsDurationCode() - { - return _ihfsDurationCode; - } - - -// --------------------------------------------------------------- - - public void setDescription(String description) - { - _description = description; - } -// --------------------------------------------------------------- - - public String getDescription() - { - return _description; - } -// --------------------------------------------------------------- - - public void setGridded(boolean isGridded) - { - _isGridded = isGridded; - } -// --------------------------------------------------------------- - - public boolean isGridded() - { - return _isGridded; - } - - //---------------------------------------------------------------------- - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + "Z"; - - return timeString; - } - - -// --------------------------------------------------------------- - public boolean equals(FFHDescriptor descriptor) - { - boolean result = false; - - if ( - - (this.getTime() == descriptor.getTime()) && - (this._isGridded == descriptor._isGridded)&& - (this._ffhMeasurement.equals(descriptor._ffhMeasurement) ) - - - ) - { - result = true; - } - - - return result; - - } - -// --------------------------------------------------------------- - public void setIsDefaultValue(boolean isDefaultValue) - { - _isDefaultValue = isDefaultValue; - } -// --------------------------------------------------------------- - - public boolean isDefaultValue() - { - return _isDefaultValue; - } -// --------------------------------------------------------------- - - public String toString() - { - String outString = null; - - String timeString = getDateTimeStringToMinutes(this.getTime()); - - double value = this.getValueInInches(); - - String ffhTypeString= null; - - if (this.isGridded()) - { - ffhTypeString = "Gridded"; - } - else if (! isDefaultValue() ) - { - ffhTypeString = "Areal"; - } - else - { - ffhTypeString = "BOGUS DEFAULT"; - } - - NumberFormat format = new DecimalFormat("0.00"); - - String formattedString = format.format(value); - - int duration = _ihfsDurationCode - 1000; - - outString = _locationId + " " + timeString + " " + - duration + " hr " + - ffhTypeString + " FFH=" + - formattedString; - - return outString; - } //end toString - - - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/FcstTsDescriptor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/FcstTsDescriptor.java deleted file mode 100644 index 274d169acd..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/FcstTsDescriptor.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Created on Dec 9, 2003 - * - * Filename : FcstTsDescriptor.java - * Author : Gautam Sood - * Last Revision Date : Dec 9, 2003 - * - */ -package ohd.hseb.sshp; - -import java.text.*; - - -public class FcstTsDescriptor implements IngestFilterTsDescriptor -{ - private String _tableName = null; - private String _lid = null; - private String _pe = null; - private String _ts = null; - private String _extremum = null; - private String _shef_qual_code = null; - private String _product_id = null; - private double _value = 0.0; - private float _probability = 0; - private int _quality_code = 0; - private short _revision = 0; - private short _dur = 0; - private long _producttime = 0; - private long _postingtime = 0; - private long _validtime = 0; - private long _basistime = 0; - - //***************************************************************************** - // Empty constructor - //***************************************************************************** - public FcstTsDescriptor(String tableName) - { - setTableName(tableName); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( short dur ) - { - _dur = dur; - } - - public short getDur() - { - return _dur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public void setValue ( double value ) - { - _value = value; - } - - public double getValue() - { - return _value; - } - - public void setShef_qual_code( String shef_qual_code ) - { - _shef_qual_code = shef_qual_code; - } - - public String getShef_qual_code() - { - return _shef_qual_code; - } - - public void setQuality_code( int quality_code ) - { - _quality_code = quality_code; - } - - public int getQuality_code() - { - return _quality_code; - } - - public void setRevision( short revision ) - { - _revision = revision; - } - - public short getRevision() - { - return _revision; - } - - public void setProduct_id( String product_id ) - { - _product_id = product_id; - } - - public String getProduct_id() - { - return _product_id; - } - - public void setProducttime( long producttime ) - { - _producttime = producttime; - } - - public long getProducttime() - { - return _producttime; - } - - public void setPostingtime( long postingtime ) - { - _postingtime = postingtime; - } - - public long getPostingtime() - { - return _postingtime; - } - - public void setProbability( float probability ) - { - _probability = probability; - } - - public float getProbability() - { - return _probability; - } - - public void setValidtime( long validtime ) - { - _validtime = validtime; - } - - public long getValidtime() - { - return _validtime; - } - - public void setBasistime( long basistime ) - { - _basistime = basistime; - } - - public long getBasistime() - { - return _basistime; - } - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat f = new DecimalFormat(formatString); - - String outString = "FcstHeight: " + - " Lid = " + _lid + - " Table NAme = " + _tableName + - " pe = " + _pe + - " ts = " + _ts + "\n" + - " Extremum = " + _extremum + - " Shef_qual_code = " + _shef_qual_code + - " Product ID = " + _product_id + "\n" + - " Value = " + f.format( _value ) + - " Probability = " + f.format( _probability ) + - " Quality Code = " + _quality_code + "\n" + - " Revision = " + _revision + - " Dur = " + _dur + - " Product Time = " + _producttime + "\n" + - " Posting Time = " + _postingtime + - " Valid Time = " + _validtime + - " Basis Time = " + _basistime; - return outString; - } - - public void setTableName(String tableName) - { - _tableName = tableName; - } - - public String getTableName() - { - return _tableName; - } -} - diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ForecastPoster.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ForecastPoster.java deleted file mode 100644 index a423be63be..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ForecastPoster.java +++ /dev/null @@ -1,1194 +0,0 @@ -/* This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package ohd.hseb.sshp; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.RiverStatusRecord; -import ohd.hseb.ihfsdb.generated.RiverStatusTable; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.RpfParamsTable; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -/** - * Provides functions to load the max fcst info into the RiverStatus table. - * - *
    - * 
    - * SOFTWARE HISTORY
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------
    - * May 13, 2011  8079       jnjanga
    - * 
    - * 
    - * - * @see com.raytheon.edex.plugin.shef.database.PostShef - * @author jnjanga - * @version 1.0 - */ - -public class ForecastPoster { - - private long basishrs = 72; - - private long fcsthrs = 72; - - private long obshrs = 72; - - private String basis_hours_str = null; - - private boolean isHoursLoad = false; - - private FileLogger logger = null; - - private Database db = null; - - public static final String MISSING = "-9999"; - - public static final int MISSING_VALUE = -9999; - - public static final int QUESTIONABLE_BAD_THRESHOLD = 1073741824; - - /** - * Constructor - * - * @param db - * @param logger - */ - public ForecastPoster(Database db, Logger logger) { - this.logger = (FileLogger) logger; - this.db = db; - } - - /** - * Loads the max fcst info into the RiverStatus table for the current - * location and pe. - * - * @param db - * The database - * - * @param lid - * The location id - * @param pe - * The physical element - * @param ts - * The type source - * @throws SQLException - */ - public void loadMaxFcstItem(String lid, String pe, String ts) - throws SQLException { - boolean useLatest = false; - long basisBeginTime = 0; - ArrayList fcstList = null; - Forecast maxFcstfcst = null; - int qcFilter = 1; - - /* - * get the setting for the use_latest_fcst field for the current - * location from the riverstat table. - */ - - String useLatestFcst = getUseLatestForecast(lid); - - if (useLatestFcst == null) { - useLatest = true; - } else { - if (useLatestFcst.equalsIgnoreCase("F")) { - useLatest = false; - } else { - useLatest = true; - } - } - - /* - * get the forecast time series for this location, pe, and ts using any - * instructions on any type-source to screen and whether to use only the - * latest basis time - */ - basisBeginTime = getBasisTime(); - - fcstList = (ArrayList) buildTsFcstRiv(lid, pe, ts, qcFilter, - useLatest, basisBeginTime); - - /* - * find the data for this location, pe, and ts given the forecast - * time-series and the count of values in it. if data found, determine - * its max and load the value - */ - if ((fcstList != null) && (fcstList.size() > 0)) { - maxFcstfcst = findMaxFcst(fcstList); - boolean updateFlag = updateRiverStatus(lid, pe, ts); - /* load the maxim data into the RiverStatus table */ - loadRiverStatus(maxFcstfcst, updateFlag); - } - - return; - } - - private long getBasisTime() { - - String hourQuery = "select obshrs,fcsthrs from RpfParams"; - long currentTime = System.currentTimeMillis(); - long basisBeginTime = 0; - Statement stmt = null; - ResultSet rs = null; - - /* - * This code sets the time values - */ - try { - if (!isHoursLoad) { - RpfParamsTable rpfTb = new RpfParamsTable(db); - stmt = db.newStmtForScrollableRset(); - rs = rpfTb.executeQuery(stmt, hourQuery); - if (rs.next()) { - obshrs = rs.getLong("obshrs"); - fcsthrs = rs.getLong("fcsthrs"); - } else { - logger.log("No fcsts in RpfParams table, using defaults"); - } - - rs.close(); - stmt.close(); - - if (basis_hours_str != null) { - basishrs = Long.parseLong(basis_hours_str); - if ((basishrs <= 0) || (basishrs > 480)) { - logger.log("invalid value for basis_hours_filter token: " - + basishrs); - basishrs = 72; - } - } - isHoursLoad = true; - } - } catch (Exception e) { - logger.log(" - PostgresSQL error in getBasisTime()"); - logger.printStackTrace(e); - } - - basisBeginTime = currentTime - (basishrs * 3600 * 1000); - return basisBeginTime; - } - - /** - * Determines if the lid,pe,ts already exists and whether or not the - * riverstatus table needs to be updated. - * - * @param lid - * - locationId - * @param pe - * - Physical Element - * @param ts - * - Timestamp - * @return - */ - - private boolean updateRiverStatus(String lid, String pe, String ts) { - Statement stmt = null; - boolean rval = false; - - String query = "select lid " + "from riverstatus where lid = '" + lid - + "' and " + "pe = '" + pe + "' and " + "ts = '" + ts + "'"; - - try { - RiverStatusTable rst = new RiverStatusTable(db); - stmt = db.newStmtForScrollableRset(); - ResultSet rs = rst.executeQuery(stmt, query); - - if (rs.next()) - rval = true; - rs.close(); - stmt.close(); - } catch (Exception e) { - logger.log(" - PostgresSQL error searching riverstatus"); - logger.log("Query = [" + query + "]"); - logger.printStackTrace(e); - - } - - return rval; - } - - /** - * Loads the max fcst info into the RiverStatus table for the current - * location and pe. - * - * @param fcst - * - Forecast fcst to load - * @param updateFlag - * - the boolean value if an update versus an insert should be - * performed - * @return - status of action, 1 is good, 0 is bad - */ - public synchronized int loadRiverStatus(Forecast fcst, Boolean updateFlag) { - - int status = -1; - - // turn fcst into a riverstatus record - RiverStatusRecord record = new RiverStatusRecord(); - record.setLid(fcst.getLid()); - record.setPe(fcst.getPe()); - record.setDur(fcst.getDur()); - record.setTs(fcst.getTs()); - record.setExtremum(fcst.getExtremum()); - record.setProbability(fcst.getProbability()); - record.setValidtime(fcst.getValidTime().getTime()); - record.setBasistime(fcst.getBasisTime().getTime()); - record.setValue(fcst.getValue()); - try { - RiverStatusTable rst = new RiverStatusTable(db); - - if (updateFlag) { - status = rst.insertOrUpdate(record); - } else { - status = rst.insert(record); - } - - } catch (Exception e) { - logger.log("lid = [" + fcst.getLid() + "]"); - logger.log("PE = [" + fcst.getPe() + "]"); - logger.log("Duration = [" + fcst.getDur() + "]"); - logger.log("TS = [" + fcst.getTs() + "]"); - logger.log("Extremum = [" + fcst.getExtremum() + "]"); - logger.log("Probability = [" + fcst.getProbability() + "]"); - logger.log("valid timestamp = [" + fcst.getValidTime() + "]"); - logger.log("basis timestamp = [" + fcst.getBasisTime() + "]"); - logger.log("Data Value = [" + fcst.getValue() + "]"); - - logger.printStackTrace(e); - if (updateFlag) { - logger.log(" - PostgresSQL error updating into riverstatus"); - } else { - logger.log(" - PostgresSQL error inserting into riverstatus"); - } - - } - - return status; - } - - /** - * Get the Use Latest Forecast flag from riverstat table. - * - * @param lid - * - The location id - * @return The use latest forecast flag, or null if nothing in db - */ - private String getUseLatestForecast(String lid) { - String sql = "select use_latest_fcst from riverstat where lid = '" - + lid + "'"; - String useLatest = null; - Statement stmt = null; - ResultSet rs = null; - - try { - RiverstatTable rstb = new RiverstatTable(db); - stmt = db.newStmtForScrollableRset(); - rs = rstb.executeQuery(stmt, sql); - if (rs.next()) - useLatest = rs.getString("use_latest_fcst"); - rs.close(); - stmt.close(); - } catch (SQLException e) { - logger.log("Error executing getUseLatestForecast(" + lid + ")"); - logger.printStackTrace(e); - } - return useLatest; - } - - /** - * This gets the max forecast value from a forecast time-series that has - * already been prepared. This function returns the ts, value, basistime, - * and validtime for the maximum forecast value. - * - * @param fcstList - * ArrayList of Forecast data - * @return The max Forecast object - */ - private Forecast findMaxFcst(ArrayList fcstList) { - Forecast max = null; - double maxValue = MISSING_VALUE; - int maxIndex = MISSING_VALUE; - - /* just in case */ - if ((fcstList == null) || (fcstList.size() == 0)) { - return null; - } - - /* loop and get the max */ - for (int i = 0; i < fcstList.size(); i++) { - if (fcstList.get(i).getValue() > maxValue) { - maxValue = fcstList.get(i).getValue(); - maxIndex = i; - } - } - - /* if for some bizarre reason, load the first fcst */ - if (maxIndex == MISSING_VALUE) { - logger.log("ERROR - find_maxfcst couldn't find max?!\n"); - maxIndex = 0; - } - - max = fcstList.get(maxIndex); - - return max; - } - - /** - * Processes forecast data for the given table, lid and pe. - * - * @param table - * - The table - * @param lid - * - The location id - * @param pe - * - The physical element - */ - public boolean loadMaxFcstData(String table, String lid, String pe) { - Statement stmt = null; - ResultSet rs = null; - boolean status = true; - - String sql = "select DISTINCT(ts) " + "from " + table - + " where lid = '" + lid + "' and " + "pe = '" + pe + "' and " - + "validtime > CURRENT_TIMESTAMP and " + "probability < 0.0"; - try { - FcstHeightTable fht = new FcstHeightTable(db); - stmt = db.newStmtForScrollableRset(); - rs = fht.executeQuery(stmt, sql); - while (rs.next()) { - loadMaxFcstItem(lid, pe, rs.getString("ts")); - } - rs.close(); - stmt.close(); - } catch (SQLException se) { - status = !status; - logger.log("Error executing loadMaxFcsftData(" + table + ", " + lid - + ", " + pe + ")"); - logger.printStackTrace(se); - } - return status; - } - - /** - * This function assembles a forecast time series for a given location and - * pe. The data are retrieved for: 1) either the specified type-source or - * for the type-source defined in the ingest filter as the one to use, based - * on its rank; and for 2) either all forecast values regardless of basis - * time or only those forecasts with the latest basis time. 3) for - * non-probabilistic values only. - * - * It returns a times series of values in an array of structures, and also - * returns the count of values. - * - * Presuming that the duration and extremum values in the forecast table - * never yield duplicates, then there can only be duplicates for the same - * validtime due to multiple basis times. - * - * There is a passed in limit regarding how far in the future data is - * considered, and how old the forecast (basistime) can be. - * - * This function is needed since some locations have short-term forecasts - * and long-term forecasts, both of which are valid and do not prempt the - * other. This avoids problems with the previous method where the software - * always used the forecast with the latest creation time and ignored all - * other forecasts, for certain purposes. - * - * The approach herein does NOT assume that the creation data corresponds to - * the valid time covered - i.e. it does NOT require that long-term forecast - * have the latest creation time. The heart of the logic for this function - * is contained in the adjust_startend() function. - * - * @param lid - * @param pe - * @param tsFilter - * @param qcFilter - * @param useLatest - * @param basisBegintime - * @return A list of forecast records - */ - private List buildTsFcstRiv(String lid, String pe, - String tsFilter, int qcFilter, boolean useLatest, - long basisBegintime) { - int fcstCount = 0; - int keepCount = 0; - String useTs = null; - String tableName = null; - String sql = null; - String sqlForecast = null; - java.sql.Timestamp basisTimeAnsi = null; - - int[] doKeep = null; - Statement stmt = null; - Statement stmt2 = null; - ResultSet ulHead = null; - int ulCount = 0; - List fcstHead = null; - Forecast fcstHght = null; - - List fcstList = new ArrayList(); - Forecast forecast = null; - DbTable dbTable = null; - - if ((tsFilter == null) || (tsFilter.length() == 0)) { - useTs = getBestTs(lid, pe, "F%", 0); - if (useTs == null) - return null; - } else { - useTs = tsFilter; - } - - try { - if (pe.startsWith("H") || pe.startsWith("h")) - tableName = "FcstHeight"; - else - tableName = "FcstDischarge"; - - dbTable = getDbTableInstance(db, tableName); - - basisTimeAnsi = new Timestamp(basisBegintime); - /* - * retrieve a list of unique basis times; use descending sort. only - * consider forecast data before some ending time, and with some - * limited basis time ago - */ - - sql = "SELECT DISTINCT(basistime) FROM " + tableName + " " - + "WHERE lid = '" + lid + "' and " + "pe = '" + pe - + "' and " + "ts = '" + useTs + "' and " - + "validtime >= CURRENT_TIMESTAMP and " + "basistime >= '" - + basisTimeAnsi + "' and " + "value != " + MISSING_VALUE - + " and " + "quality_code >= " + QUESTIONABLE_BAD_THRESHOLD - + " " + "ORDER BY basistime DESC "; - - stmt = db.newStmtForScrollableRset(); - ulHead = dbTable.executeQuery(stmt, sql); - ulCount = getResultSetSize(ulHead); - - /* - * retrieve the data; the ordering by validtime is important. as - * before, limit the forecast time valid time window and as needed, - * the age of the forecast (basistime). - */ - - sqlForecast = "SELECT lid,pe,dur,ts,extremum,probability,validtime,basistime,value " - + "FROM " - + tableName - + " " - + "WHERE lid = '" - + lid - + "' AND " - + "pe = '" - + pe - + "' AND " - + "ts = '" - + useTs - + "' AND " - + "validtime >= CURRENT_TIMESTAMP AND " - + "probability < 0.0 AND "; - - if (useLatest || ulCount == 1) { - java.sql.Timestamp tempStamp = null; - ulHead.next(); - tempStamp = ulHead.getTimestamp("basistime"); - sqlForecast += "basistime >= '" + tempStamp + "' AND "; - - } else { - sqlForecast += "basistime >= '" + basisTimeAnsi + "' AND "; - } - - sqlForecast += "value != " + Integer.parseInt(MISSING) + " AND " - + "quality_code >= " + Integer.parseInt(MISSING) + " " - + "ORDER BY validtime ASC"; - - stmt2 = db.newStmtForScrollableRset(); - ResultSet oa = dbTable.executeQuery(stmt2, sqlForecast); - - int soa = getResultSetSize(oa); - - if ((oa != null) && soa > 0) { - fcstHead = new ArrayList(soa); - while (oa.next()) { - fcstHght = new Forecast(); - Date tmpDate = null; - fcstHght.setLid(oa.getString("lid")); - fcstHght.setPe(oa.getString("Pe")); - fcstHght.setDur(oa.getShort("dur")); - fcstHght.setTs(oa.getString("ts")); - fcstHght.setExtremum(oa.getString("extremum")); - fcstHght.setProbability(oa.getFloat("probability")); - tmpDate = new Date(oa.getTimestamp("validtime").getTime()); - fcstHght.setValidTime(tmpDate); - tmpDate = new Date(oa.getTimestamp("basistime").getTime()); - fcstHght.setBasisTime(tmpDate); - fcstHght.setValue(oa.getDouble("value")); - fcstHead.add(fcstHght); - } - } - - if (fcstHead != null) { - fcstCount = fcstHead.size(); - } - - /* - * define a local array to determine which items in the time series - * to keep and return - */ - if (fcstCount > 0) { - doKeep = new int[fcstCount]; - } else { - return null; - } - - /* - * if only getting the latest basis time's data or only one basis - * time was found, then consider all; otherwise, need to adjoin/butt - * the time series together for the multiple basis times. - */ - - if (useLatest || ulCount <= 1) { - for (int i = 0; i < doKeep.length; i++) { - doKeep[i] = 1; - } - } else { - doKeep = setFcstKeep(ulHead, ulCount, fcstHead); - } - - /* - * now load the values and info to return, knowing which items to - * keep since all the values have been tagged. first get the count - * of the number of values to keep and allocate the data - */ - - for (int j = 0; j < fcstCount; j++) { - if (doKeep[j] == 1) { - keepCount++; - } - } - - for (int y = 0; y < fcstCount; y++) { - forecast = new Forecast(); - if (doKeep[y] == 1) { - forecast.setLid(fcstHead.get(y).getLid()); - forecast.setPe(fcstHead.get(y).getPe()); - convertDur(fcstHead.get(y).getDur(), forecast); - forecast.setTs(fcstHead.get(y).getTs()); - forecast.setExtremum(fcstHead.get(y).getExtremum()); - forecast.setValidTime(fcstHead.get(y).getValidTime()); - forecast.setBasisTime(fcstHead.get(y).getBasisTime()); - forecast.setValue(fcstHead.get(y).getValue()); - } - fcstList.add(forecast); - } - - stmt.close(); - stmt2.close(); - } catch (Error e) { - logger.log(" - SQL error in buildTsFcstRiv"); - logger.printStackTrace(e); - } catch (Exception e) { - logger.log("Query = [" + sql + "]"); - logger.log("Query = [" + sqlForecast + "]"); - logger.log(" - SQL Exception in buildTsFcstRiv"); - logger.printStackTrace(e); - } - - return fcstList; - } - - private int getResultSetSize(ResultSet rs) { - int rowcount = 0; - try { - if (rs.last()) { - rowcount = rs.getRow(); - rs.beforeFirst(); - } - } catch (SQLException e) { - logger.log("Error computing Resultset size !"); - logger.printStackTrace(e); - } - return rowcount; - } - - /** - * Converts duration int to String character. - * - * @param dur - * - The duration value - * @return The single character duration value - */ - private void convertDur(short dur, Forecast data) { - String value = null; - String durationCode = null; - - switch (dur) { - case 0: - value = "I"; - break; - case 1: - value = "U"; - break; - case 5: - value = "E"; - break; - case 10: - value = "G"; - break; - case 15: - value = "C"; - break; - case 30: - value = "J"; - break; - case 1001: - value = "H"; - break; - case 1002: - value = "B"; - break; - case 1003: - value = "T"; - break; - case 1004: - value = "F"; - break; - case 1006: - value = "Q"; - break; - case 1008: - value = "A"; - break; - case 1012: - value = "K"; - break; - case 1018: - value = "L"; - break; - case 2001: - value = "D"; - break; - case 2007: - value = "W"; - break; - // case 'N': - // Not sure what to return. Shef maunal explanation: - // N Mid month, duration for the period from the 1st day of the - // month to and ending on the - // 15th day of the same month - // break; - case 3001: - value = "M"; - break; - case 4001: - value = "Y"; - break; - case 5004: - value = "P"; - break; - case 5000: { - value = "Z"; - break; - } - case 5001: - value = "S"; - break; - case 5002: - value = "R"; - break; - case 5005: - value = "X"; - break; - default: { - // Anything that didn't get picked up above is - // probably a variable duration. - if (dur >= 7000) { - value = "V"; - durationCode = "S"; - } else if (dur < 1000) { - value = "V"; - durationCode = "N"; - } else if (dur < 2000) { - value = "V"; - durationCode = "H"; - } else if (dur < 3000) { - value = "V"; - durationCode = "D"; - } else if (dur < 4000) { - value = "V"; - durationCode = "M"; - } else if (dur < 5000) { - value = "V"; - durationCode = "Y"; - } else { - // Not sure what value this would be. - value = "Z"; - } - } - } - - data.setDur(dur); - } - - /** - * Determine which items in the forecast time series to keep, as there may - * be overlap due to multiple time_series. - * - * @param ulHead - * @param count - * @param fcstHead - * @return - * @throws SQLException - */ - private int[] setFcstKeep(ResultSet ulHead, int count, - List fcstHead) throws SQLException { - int fcstCount = fcstHead.size(); - int ulCount = count; - int[] doKeep = new int[fcstCount]; - int[] basisIndex = new int[fcstCount]; - int[] tsFirstChk = new int[ulCount]; - Timestamp[] startTime = new Timestamp[ulCount]; - Timestamp[] endTime = new Timestamp[ulCount]; - Timestamp[] basisTime = new Timestamp[ulCount]; - Timestamp fcstBasisTime = null; - Timestamp fcstValidTime = null; - Timestamp ulBasisTime = null; - - for (int i = 0; i < ulCount; i++) { - tsFirstChk[i] = 0; - } - - Timestamp validTime = null; - ulHead.beforeFirst(); - for (int i = 0; i < fcstCount; i++) { - - /* find out which basis time's time series this value belongs to */ - - fcstBasisTime = new Timestamp(fcstHead.get(i).getBasisTime() - .getTime()); - - basisIndex[i] = MISSING_VALUE; - - for (int j = 0; ((j < ulCount) && (basisIndex[i] == MISSING_VALUE)); j++) { - ulBasisTime = ulHead.getTimestamp("ts"); - - if (ulBasisTime.compareTo(fcstBasisTime) == 0) { - basisIndex[i] = j; - } - } - - if (basisIndex[i] == MISSING_VALUE) { - logger.log("Unexpected error assigning basis_index for " + i); - } - - /* - * check if the values constitute the start or end times for the - * time series and fcst these times if they do - */ - - validTime = new Timestamp(fcstHead.get(i).getValidTime().getTime()); - - if (tsFirstChk[basisIndex[i]] == 1) { - if (validTime.before(startTime[basisIndex[i]])) { - startTime[basisIndex[i]] = validTime; - } else if (validTime.after(endTime[basisIndex[i]])) { - endTime[basisIndex[i]] = validTime; - } - } else { - startTime[basisIndex[i]] = validTime; - endTime[basisIndex[i]] = validTime; - tsFirstChk[basisIndex[i]] = 1; - } - } - - /* - * for each of the unique basis times, assign the basis time in a - * convenient array for use in the adjust_startend function. - */ - - ulHead.beforeFirst(); - ArrayList bst = new ArrayList(); - while (ulHead.next()) { - bst.add(ulHead.getTimestamp("ts")); - } - basisTime = (Timestamp[]) bst.toArray(); - - /* - * knowing the actual start and end times for the multiple time series, - * loop thru the time series and adjust the start and end times so that - * they reflect the time span to use; i.e. there is no overlap. THIS IS - * THE KEY STEP IN THE PROCESS OF DEFINING AN AGGREGATE VIRTUAL TIME - * SERIES!!! - */ - Object[] tmp = adjustStartEnd(ulCount, basisTime, startTime, endTime); - startTime = (Timestamp[]) tmp[0]; - endTime = (Timestamp[]) tmp[1]; - - /* - * loop thru the complete retrieved time series and only keep the value - * if it lies between the start and end time for this basis time - */ - for (int i = 0; i < fcstCount; i++) { - fcstValidTime = new Timestamp(fcstHead.get(i).getValidTime() - .getTime()); - if ((fcstValidTime.compareTo(startTime[basisIndex[i]]) >= 0) - && (fcstValidTime.compareTo(endTime[basisIndex[i]]) <= 0)) { - doKeep[i] = 1; - } else { - doKeep[i] = 0; - } - } - return doKeep; - } - - /** - * This method uses the time series with the latest basis time first, and - * uses it in its entirety. Then the time series with the next latest basis - * time is used. If it overlaps portions of the already saved time series, - * then only that portion which doesn't overlap is used. This process - * continues until all time series have been considered. In essences, this - * method adjoins adjacent time series. - * - * @param count - * @param basisTime - * @param startValidTime - * @param endValidTime - * @return - */ - private Object[] adjustStartEnd(int count, Timestamp[] basisTime, - Timestamp[] startValidTime, Timestamp[] endValidTime) { - boolean found = false; - int currentIndex = 0; - int[] basisOrder = new int[count]; - Timestamp fullStartValidTime = null; - Timestamp fullEndValidTime = null; - Timestamp tmpTime = null; - Timestamp zero = new Timestamp((new Date(0)).getTime()); - Object[] rval = new Object[2]; // [startValidTime[]] [endValidTime[]] - - for (int i = 0; i < count; i++) { - basisOrder[i] = -1; - } - - /* - * find the order of the time series by their latest basis time. if two - * time series have the same basis time, use the one that has the - * earlier starting time. note that the order is such that the latest - * basis time is last in the resulting order array. - */ - - for (int i = 0; i < count; i++) { - tmpTime = zero; - currentIndex = 0; - - for (int j = 0; j < count; j++) { - /* - * only consider the time series if it hasn't been accounted for - * in the order array - */ - found = false; - - for (int k = 0; k < i; k++) { - if (j == basisOrder[k]) { - found = true; - break; - } - } - - if (!found) { - if (basisTime[j].compareTo(tmpTime) > 0) { - currentIndex = j; - tmpTime = basisTime[j]; - } else if (basisTime[j].compareTo(tmpTime) == 0) { - if (startValidTime[j] - .compareTo(startValidTime[currentIndex]) < 0) { - currentIndex = j; - tmpTime = basisTime[j]; - } - } - } - } - - basisOrder[i] = currentIndex; - } - - /* - * do NOT adjust the start and end time of the time series with the - * latest ending time. loop through all the other time series and adjust - * their start and end times as necessary so that they do not overlap - * the time limits of the being-built aggregate time series. - */ - - currentIndex = basisOrder[0]; - fullStartValidTime = startValidTime[currentIndex]; - fullEndValidTime = endValidTime[currentIndex]; - - for (int i = 1; i < count; i++) { - currentIndex = basisOrder[i]; - - /* - * each additional time series being considered is checked to see if - * it falls outside the time window already encompassed by the - * assembled time series. there are four cases that can occur; each - * is handled below. - */ - - if ((startValidTime[currentIndex].compareTo(fullStartValidTime) >= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) <= 0)) { - /* - * if the basis time series being considered is fully within the - * time of the already existing time series, then ignore it - * completely, and reset its times. - */ - startValidTime[currentIndex] = zero; - endValidTime[currentIndex] = zero; - } else if ((startValidTime[currentIndex] - .compareTo(fullStartValidTime) <= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) >= 0)) { - /* - * if the basis time series being considered covers time both - * before and after the existing time series, use the portion of - * it that is before the time series. it is not desirable to use - * both the before and after portion (this results in a - * non-contiguous time-series that is weird), and given a choice - * it is better to use the forecast data early on than the later - * forecast data, so use the before portion - */ - endValidTime[currentIndex] = new Timestamp( - fullStartValidTime.getTime() - 1000); - fullStartValidTime = startValidTime[currentIndex]; - - } else if ((startValidTime[currentIndex] - .compareTo(fullStartValidTime) <= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) <= 0)) { - /* - * if the basis time series being considered straddles the - * beginning or is completely before the existing time series, - * then use the portion of it that is before the time series. - */ - endValidTime[currentIndex] = new Timestamp( - fullStartValidTime.getTime() - 1000); - fullStartValidTime = startValidTime[currentIndex]; - } else if ((startValidTime[currentIndex] - .compareTo(fullStartValidTime) >= 0) - && (endValidTime[currentIndex].compareTo(fullEndValidTime) >= 0)) { - /* - * if the basis time series being considered straddles the end - * or is completely after the existing time series, then use the - * portion of it that is after the time series. - */ - startValidTime[currentIndex] = new Timestamp( - fullEndValidTime.getTime() + 1000); - fullEndValidTime = endValidTime[currentIndex]; - - } - } /* end for loop on the unique ordered basis times */ - - // Need to find a better way to do this - rval[0] = startValidTime; - rval[1] = endValidTime; - return rval; - } - - /** - * For a given location and pe code and type-source prefix, this function - * returns the type-source code with the lowest rank in IngestFilter. - * Alternatively, if a specific ordinal number is passed, then the Nth - * ranking ts is returned. If no (<= 0) ordinal number (i.e. 1st, 2nd) is - * requested, then the highest rank (1st) is returned. The type-source - * prefix is normally given as a one-character string, R for observed data - * and F for forecast data. - * - * The function argument returns a status variable indicating whether the - * request was satisfied. - * - * @param lid - * @param pe - * @param tsPrefix - * @param ordinal - * @return - */ - private String getBestTs(String lid, String pe, String tsPrefix, int ordinal) { - - int count = 0; - String tsFound = null; - String query = "SELECT ts_rank,ts FROM ingestfilter " + "WHERE lid = '" - + lid + "' AND " + "pe = '" + pe + "' AND " + "ts like '" - + tsPrefix + "' AND " + "ingest = 'T' " - + "ORDER BY ts_rank, ts"; - - try { - /* - * get the ingest filter entries for this location. note that the - * retrieval is ordered so that if multiple best ranks exist, there - * is some predicatibility for the identified best one. also note - * that this approach ignores the duration, extremum, and probabilty - * code. - */ - - IngestFilterTable ift = new IngestFilterTable(db); - Statement stmt = db.newStmtForScrollableRset(); - ResultSet rs = ift.executeQuery(stmt, query); - - if (rs.next()) { - /* - * if no specific ordinal number was requested, return with the - * highest rank. - */ - if (ordinal <= 0) { - tsFound = rs.getString("ts"); - } else { - /* - * get a count of the number of matching ts entries. if the - * requested ordinal number is greater than the number - * available then return with a not found status. - */ - - count = getResultSetSize(rs); - - if (ordinal <= count) { - rs.relative(ordinal - 1); - tsFound = rs.getString("ts"); - } - } - } - rs.close(); - stmt.close(); - } catch (Exception e) { - logger.log(" - PostgresSQL error retrieving from ingestfilter"); - logger.log("Query = [" + query + "]"); - logger.printStackTrace(e); - - } - - return tsFound; - } - - private class Forecast extends FcstHeightRecord { - - private Date validTime = null; - - private Date basisTime = null; - - public void setValidTime(Date validTime) { - this.validTime = validTime; - } - - public Date getValidTime() { - return validTime; - } - - public void setBasisTime(Date basisTime) { - this.basisTime = basisTime; - } - - public Date getBasisTime() { - return basisTime; - } - - public boolean equals(Object other) { - if ((this == other)) - return true; - if ((other == null)) - return false; - if (!(other instanceof Forecast)) - return false; - Forecast castOther = (Forecast) other; - - return ((this.getLid() == castOther.getLid()) || (this.getLid() != null - && castOther.getLid() != null && this.getLid().equals( - castOther.getLid()))) - && ((this.getPe() == castOther.getPe()) || (this.getPe() != null - && castOther.getPe() != null && this.getPe() - .equals(castOther.getPe()))) - && (this.getDur() == castOther.getDur()) - && ((this.getTs() == castOther.getTs()) || (this.getTs() != null - && castOther.getTs() != null && this.getTs() - .equals(castOther.getTs()))) - && ((this.getExtremum() == castOther.getExtremum()) || (this - .getExtremum() != null - && castOther.getExtremum() != null && this - .getExtremum().equals(castOther.getExtremum()))) - && (this.getProbability() == castOther.getProbability()) - && ((this.getValidTime() == castOther.getValidTime()) || (this - .getValidTime() != null - && castOther.getValidTime() != null && this - .getValidTime().equals(castOther.getValidTime()))) - && ((this.getBasisTime() == castOther.getBasisTime()) || (this - .getBasisTime() != null - && castOther.getBasisTime() != null && this - .getBasisTime().equals(castOther.getBasisTime()))); - } - - public int hashCode() { - int result = 17; - - result = 37 * result - + (getLid() == null ? 0 : this.getLid().hashCode()); - result = 37 * result - + (getPe() == null ? 0 : this.getPe().hashCode()); - result = 37 * result + this.getDur(); - result = 37 * result - + (getTs() == null ? 0 : this.getTs().hashCode()); - result = 37 - * result - + (getExtremum() == null ? 0 : this.getExtremum() - .hashCode()); - result = 37 * result + (int) this.getProbability(); - result = 37 - * result - + (getValidTime() == null ? 0 : this.getValidTime() - .hashCode()); - result = 37 - * result - + (getBasisTime() == null ? 0 : this.getBasisTime() - .hashCode()); - return result; - } - } - - /** - * A utility DbTable factory - * - * @param db - * @param table - * @return - */ - private DbTable getDbTableInstance(Database db, String table) { - if (table.equalsIgnoreCase("FcstHeight")) - return new FcstHeightTable(db); - else if (table.equalsIgnoreCase("FcstDischarge")) - return new FcstDischargeTable(db); - // Default for now is FcstHeight so we're never returning null. - return new FcstHeightTable(db); - } - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/IngestFilterTsDescriptor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/IngestFilterTsDescriptor.java deleted file mode 100644 index 5a949fedd8..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/IngestFilterTsDescriptor.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Created on Apr 15, 2004 - * - * - */ -package ohd.hseb.sshp; - -/** - * @author GobsC - * - * - */ -public interface IngestFilterTsDescriptor -{ - - public String getLid(); - - public String getPe(); - - public short getDur(); - - public String getTs(); - - public String getExtremum(); - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ModelManager.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ModelManager.java deleted file mode 100644 index f0c087fc78..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ModelManager.java +++ /dev/null @@ -1,756 +0,0 @@ -package ohd.hseb.sshp; - -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Map; - -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; - - -/** - * - * @author cgobs - * @date August 20, 2007 - * This class acts as the Manager of various StreamModels. - * Some StreamModels may be for alternate current time simulations, others for past model times. - */ -public class ModelManager -{ - private DataMgr _dataMgr = null; - private StreamModel _primaryStreamModel = null; - private Map _modelMap = new HashMap(); - - // private List _currentStreamModelList = new ArrayList(); - // private List _pastStreamModelList = new ArrayList(); - - private List _streamModelList = new ArrayList(); - - private boolean _showAlternateForecasts = false; - private boolean _showPastForecasts = false; - - private SSHPConfig _config = null; - - //location-specific info - private String _locationId = null; - private String _locationName = null; - private String _basinId = null; - - //model run time related variables - - private static final int MAX_DAYS_OF_TIME_SERIES = 100; - private static final int MILLIS_PER_HOUR = 60 * 60 * 1000; - private static final int MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; - - - private TimeHolder _modelStartTimeHolder = new TimeHolder(); - private TimeHolder _modelEndTimeHolder = new TimeHolder(); - - private static final int DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS = 24; - private static final int DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS = 120; - - private int _forecastLengthInHours = DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS; - private int _maxForecastLengthInHours = DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS; - - private int _hoursBackForPreviousForecastStates = 24; - private int _intervalInHoursForPreviousForecastStates = 6; - - - // ------------------------------------------------------------------------ - - public ModelManager(String locationId, DataMgr dataMgr) - { - _dataMgr = dataMgr; - - - //set up location-specific data - setLocationId(locationId); - - _config = _dataMgr.getSSHPConfig(_locationId); - - - //set the basin id associated with the locationId - if (_config != null) - { - _basinId = _config.getBasinId(); - } - else - { - _basinId = "BOGUS_BASIN"; - } - - //get the location name - _locationName = dataMgr.getLocationName(_locationId); - - - AppsDefaults ad = new AppsDefaults(); - - - //load the forecast length parameters - _forecastLengthInHours = ad.getInt("sshp_initial_forecast_length", - DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS); - - _maxForecastLengthInHours = ad.getInt("sshp_max_forecast_length", - DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS); - - if (_forecastLengthInHours > _maxForecastLengthInHours) - { - _maxForecastLengthInHours = _forecastLengthInHours; - } - - - - } - // ------------------------------------------------------------------------ - - public DataMgr getDataManager() - { - return _dataMgr; - } - // ----------------------------------------------------------- - - public String getLocationId() - { - return _locationId; - - } - - // ------------------------------------------------------------------------ - public void setLocationId(String locationId) - { - _locationId = locationId; - } - - // ------------------------------------------------------------------------ - public void setBasinId(String basinId) - { - _basinId = basinId; - } - - // ------------------------------------------------------------------------ - - public String getBasinId() - { - return _basinId; - } - - // ------------------------------------------------------------- - public void setPrimaryModelStartTime(long modelStartTime) - { - modelStartTime = TimeHelper.truncateTimeInMillisToNearestHour(modelStartTime, 1); - // trace(); - getPrimaryStreamModel().setModelStartTime(modelStartTime); - - _modelStartTimeHolder.setTime(modelStartTime); - - //sets the model end time - setForecastLengthInHours(_forecastLengthInHours); - - for (StreamModel streamModel : _streamModelList) - { - - if (streamModel.getRainfallRunoffModelType() == RainfallRunoffModelType.SAC_SMA) - { - streamModel.setModelStartTime(streamModel.getSacStateValidTime()); - } - } - - return; - } - // ------------------------------------------------------------------------ - public void setForecastLengthInHours(int lengthInHours) - { - // String header = "ModelManager.setForecastLengthInHours(): "; - - // System.out.println(header + "lengthInHours = " + lengthInHours); - - if (lengthInHours > 0) - { - _forecastLengthInHours = lengthInHours; - long duration = ((long)(lengthInHours) * (long)MILLIS_PER_HOUR); - long newEndTime = _modelStartTimeHolder.getTime() + duration; - - setModelEndTime(newEndTime); - } - - for (StreamModel streamModel : getCompleteStreamModelList()) - { - streamModel.setForecastLengthInHours(_forecastLengthInHours); - } - - return; - } - // ----------------------------------------------------------- - - public int getForecastHours() - { - return _forecastLengthInHours; - } - - // ----------------------------------------------------------- - - - public void setModelEndTime(long modelEndTime) - { - _modelEndTimeHolder.setTime(modelEndTime); - } - - // ----------------------------------------------------------- - - public void addStreamModel(StreamModel streamModel) - { - _streamModelList.add(streamModel); - } - // ------------------------------------------------------------------------ - public void removeAllPastStreamModels() - { - - String header = "ModelManager.removeAllPastStreamModels(): "; - - List modelsToRemoveList = new ArrayList(); - - //if the model has a different source than the primary stream model, then it is an alternate StreamModel - for (StreamModel streamModel : _streamModelList) - { - if (streamModel.getModelStartTime() != getPrimaryStreamModel().getModelStartTime()) //this line is just for efficiency - { - - modelsToRemoveList.add(streamModel); - - } - } - - //remove the past streamModels - for (StreamModel streamModel : modelsToRemoveList) - { - _streamModelList.remove(streamModel); - } - - System.out.println(header + " removed " + modelsToRemoveList.size() + " streamModels. " ); - - } //end removeAllAlternateStreamModels() - - - - // ------------------------------------------------------------------------ - public void removeAllStreamModels() - { - - - _streamModelList.clear(); - - // removeAllCurrentStreamModels(); - // removeAllPastStreamModels(); - - // printAllModels(); - } - // ------------------------------------------------------------------------ - public void removeAllStreamModelsExceptPrimary() - { - _streamModelList.clear(); - setPrimaryStreamModel(getPrimaryStreamModel()); - } - // ------------------------------------------------------------------------ - public void setPrimaryStreamModel(StreamModel primaryStreamModel) - { - this._primaryStreamModel = primaryStreamModel; - - primaryStreamModel.setIsAlternateStreamModel(false); - - // add to the list of currentStreamModels - if (! _streamModelList.contains(primaryStreamModel)) - { - _streamModelList.add(primaryStreamModel); - } - } - // ------------------------------------------------------------------------ - - public StreamModel getPrimaryStreamModel() - { - return _primaryStreamModel; - } - // ------------------------------------------------------------------------ - public List getCompleteStreamModelList() - { - return _streamModelList; - } - - // ------------------------------------------------------------------------ - - public void runStreamModels() - { - String header = "ModelManager.runStreamModels(): "; - int count = 0; - - for (StreamModel model : _streamModelList) - { - //System.out.println(header + " model[" + count + "] = " + model); - model.runModel(); - // count++; - } - - } - // ------------------------------------------------------------------------ - public List getActualSacSmaStateDescriptorList() - { - boolean forceCacheUpdate = true; - List list = _dataMgr.getSacSmaStateDescriptorListByBasinId(getBasinId(), forceCacheUpdate); - return list; - } - - // ------------------------------------------------------------------------ - - public List getSacSmaStateDescriptorListWithBogusStateIfEmpty(boolean showUnadjustedStates) - { - List list = getActualSacSmaStateDescriptorList(); - - - if (! showUnadjustedStates) - { - list = filterOutUnadjustedStates(list); - } - - - if (list.size() == 0) - { - SacSmaState state = getDefaultSacSmaState(); - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - - list.add(descriptor); - } - return list; - } - - // ---------------------------------------------------------------------------- - public List filterOutUnadjustedStates(List sacStateDescriptorList) - { - - List filteredList = new ArrayList(); - - String header = "ModelManager.filterOutUnadjustedStates(): "; - - final String unadjustedSourceString = SSHPSource.UNADJUSTED_VAR.getSacSmaSource(); - - - for (SacSmaStateDescriptor descriptor : sacStateDescriptorList) - { - String stateSourceString = descriptor.getState().getSource(); - - if (! stateSourceString.equals(unadjustedSourceString)) - { - filteredList.add(descriptor); - } - - } - return filteredList; - - } - - // ---------------------------------------------------------------------------- - private SacSmaState getDefaultSacSmaState() - { - SacSmaState state = new SacSmaState(); - state.setSource("BOGUS DEFAULT"); - - state.setBasinId(_basinId); - state.setValidTime(getLatestHourTime()); - - state.setUztwc(0); - state.setUzfwc(0); - state.setLztwc(0); - state.setLzfsc(0); - state.setLzfpc(0); - state.setAdimc(0); - - return state; - } - // ---------------------------------------------------------------------------- - public long getLatestHourTime() - { - return TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - } - // ----------------------------------------------------------- - - public void removeAllAlternateStreamModels() - { - - String header = "ModelManager.removeAllAlternateStreamModels(): "; - List modelsToRemoveList = new ArrayList(); - - //if the model has a different source than the primary stream model, then it is an alternate StreamModel - for (StreamModel streamModel : _streamModelList) - { - if (streamModel != getPrimaryStreamModel()) //this line is just for efficiency, it doesn't really change anything - { - if (! haveSameSource(streamModel, getPrimaryStreamModel())) - { - modelsToRemoveList.add(streamModel); - } - } - } - - //remove the alternate streamModels - for (StreamModel streamModel : modelsToRemoveList) - { - if (streamModel != getPrimaryStreamModel()) - { - _streamModelList.remove(streamModel); - } - } - - System.out.println(header + " removed " + modelsToRemoveList.size() + " streamModels. " ); - - } //end removeAllAlternateStreamModels() - - // ----------------------------------------------------------- - public boolean haveSameSource(SacSmaStateDescriptor descriptor1, - SacSmaStateDescriptor descriptor2) - { - boolean result = false; - - String sourceString1 = descriptor1.getState().getSource(); - String sourceString2 = descriptor2.getState().getSource(); - - if (sourceString1.equals(sourceString2)) - { - result = true; - } - - return result; - } - // ----------------------------------------------------------- - public boolean haveSameSource(StreamModel model1, - StreamModel model2) - { - boolean result = false; - - String sourceString1 = model1.getSacState().getSource(); - String sourceString2 = model2.getSacState().getSource(); - - if (sourceString1.equals(sourceString2)) - { - result = true; - } - - - return result; - } -// ----------------------------------------------------------- - - public void printAllModels() - { - String header = "ModelManager.printAllModels();"; - - int i = 0; - - for (StreamModel streamModel : _streamModelList) - { - System.out.println(header + "model[ " + i + "] = " + streamModel); - i++; - } - - } - - // ----------------------------------------------------------- - public void setHoursBackAndIntervalForPreviousForecastStates(int hoursBack, int intervalInHours) - { - _hoursBackForPreviousForecastStates = hoursBack; - _intervalInHoursForPreviousForecastStates = intervalInHours; - - StreamModel primaryStreamModel = getPrimaryStreamModel(); - SacSmaState state = primaryStreamModel.getSacState(); - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - - configureStreamModelsForSacSma(primaryStreamModel, descriptor, _showAlternateForecasts, _showPastForecasts); - - return; - } - - // ----------------------------------------------------------- - - - // ----------------------------------------------------------- - public void setShowAlternateForecasts(boolean showAlternateForecasts) - { - String header = "ModelManager.setShowAlternateForecasts(): "; - - _showAlternateForecasts = showAlternateForecasts; - - if (_showAlternateForecasts) - { - StreamModel primaryStreamModel = getPrimaryStreamModel(); - SacSmaState state = primaryStreamModel.getSacState(); - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - - configureStreamModelsForSacSma(primaryStreamModel, descriptor, _showAlternateForecasts, _showPastForecasts); - } - else //set not to display the alternate forecasts - { - System.out.println(header + "removing all alternate StreamModels. "); - removeAllAlternateStreamModels(); - } - - } - // ----------------------------------------------------------- - public void setShowPastForecasts(boolean showPastForecasts) - { - String header = "ModelManager.setShowPastForecasts(): "; - - _showPastForecasts = showPastForecasts; - - if (_showPastForecasts) //changed to display the states - { - StreamModel primaryStreamModel = getPrimaryStreamModel(); - SacSmaState state = primaryStreamModel.getSacState(); - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - - CodeTimer timer = new CodeTimer(); - timer.start(); - configureStreamModelsForSacSma(primaryStreamModel, descriptor, _showAlternateForecasts, _showPastForecasts); - timer.stop(header + " configureStreamModelsForSacSma() took"); - } - else //changed not to display the alternate forecasts - { - removeAllPastStreamModels(); - } - - } - - // ----------------------------------------------------------- - - public void configureStreamModelsForSacSma(StreamModel primaryStreamModel, - SacSmaStateDescriptor primaryDescriptor, - boolean showAlternateForecasts, boolean showPastForecasts) - { - String header = "ModelManager.configureCurrentStreamModelsForSacSma(): "; - - // System.out.println(header + "---------------------------------------------at the top of the method"); - - removeAllStreamModels(); - -// for each SacSmaStateDescriptor -// if the descriptor is not the primary descriptor, but has the same time, then -// create a StreamModel for it and set the descriptor. -// add the stream model to the current stream model list - - -// add in streamModels that have the same time as the primary streamModel - - if (primaryStreamModel.getRainfallRunoffModelType() == RainfallRunoffModelType.SAC_SMA) - { - // System.out.println(header + "using SAC-SMA Rainfall-Runoff model"); - - // System.out.println(header + " --------------------------------------------------------"); - // System.out.println(header + "primaryDescriptor = " + primaryDescriptor); - // System.out.println(header + "primaryDescriptor state = " + primaryDescriptor.getState()); - - for (SacSmaStateDescriptor descriptor : getActualSacSmaStateDescriptorList()) - { - if (! sameTimeAndSource(descriptor, primaryDescriptor) ) - { - if (showAlternateForecasts) //if should show alternate forecasts - { - if (descriptor.getValidTime() == primaryDescriptor.getValidTime() ) - { - - //create a StreamModel for this time and add to the list of models - getAndAddAlternateStreamModel(getLocationId(), descriptor, primaryDescriptor, primaryStreamModel); - - } //end if times are the same - } //end if showAllCurrentForecasts - - - if (showPastForecasts) - { - final int millisBack = _hoursBackForPreviousForecastStates * MILLIS_PER_HOUR; - final int intervalInMillis = _intervalInHoursForPreviousForecastStates * MILLIS_PER_HOUR; - - if ( - (descriptor.getValidTime() < primaryDescriptor.getValidTime() ) && - (descriptor.getValidTime() >= (primaryDescriptor.getValidTime() - millisBack) ) - ) - { - long timeDiff = primaryDescriptor.getValidTime() - descriptor.getValidTime(); - - //if at the right interval - if ( ( timeDiff >= intervalInMillis) && (timeDiff % intervalInMillis) == 0) - { - - if (showAlternateForecasts) //show alternate and other past forecasts - { - //create a StreamModel for this time and add to the list of models - getAndAddAlternateStreamModel(getLocationId(), descriptor, primaryDescriptor, primaryStreamModel); - } - - else //just show ones that match the primary Source - { - if (haveSameSource(descriptor, primaryDescriptor)) - { - //create a StreamModel for this time and add to the list of models - getAndAddAlternateStreamModel(getLocationId(), descriptor, primaryDescriptor, primaryStreamModel); - } - } - } - } //end if times are the same - } - - } //end if not sameTimeAndSource, meaning -> not the primaryStreamModel - - else //this is the primaryStreamModel - { - CodeTimer timer = new CodeTimer(); - // timer.start(); - primaryStreamModel.setSacSmaStateDescriptor(descriptor); - // timer.stop(header + " primaryStreamModel.setSacSmaStateDescriptor() took: "); - addStreamModel(primaryStreamModel); - // System.out.println(header + "resetting descriptor = primaryDescriptor " + descriptor); - - } - } //end for - - } //end if using SAC-SMA - else - { - System.out.println(header + "using a different Rainfall-Runoff model, so doing nothing here"); - } - - - // printAllModels(); - - // System.out.println(header + " --------------------------------------------------------"); - - - - - } // end configureCurrentStreamModelsForSacSma -// ----------------------------------------------------------------- - public void configureStreamModelsForMkcApi(StreamModel primaryStreamModel, - FFHDescriptor primaryDescriptor) - { - String header = "ModelManager.configureStreamModelsMkcApi(): "; - - removeAllStreamModels(); - - addStreamModel(primaryStreamModel); - - } // end configureStreamModelsForMkcApi -// ----------------------------------------------------------------- - private void getAndAddAlternateStreamModel(String locationId, - SacSmaStateDescriptor descriptor, - SacSmaStateDescriptor primaryDescriptor, - StreamModel primaryStreamModel - ) - { - - String header = "ModelManager.getAndAddAlternateStreamModel(): "; - CodeTimer getAndAddAlternateStreamModelTimer = new CodeTimer(); - getAndAddAlternateStreamModelTimer.start(); - - // System.out.println(header + "alternateDescriptor = " + descriptor); - // System.out.println(header + "descriptor state = " + descriptor.getState()); - - StreamModel streamModel = null; - - //first look for the stream model in the cache, if not there, create it - streamModel = getStreamModelFromCache(descriptor); - - if (streamModel == null) - { - CodeTimer createAlternateStreamModelTimer = new CodeTimer(); - createAlternateStreamModelTimer.start(); - streamModel = createAlternateStreamModel(locationId, descriptor, primaryDescriptor, primaryStreamModel); - createAlternateStreamModelTimer.stop(header + "createAlternateStreamModel() took "); - _modelMap.put(descriptor, streamModel); - - // System.out.println(header + "did NOT find in cache, alternateDescriptor = " + descriptor); - } - else - { - // System.out.println(header + "found in cache, alternateDescriptor = " + descriptor); - } - - - if (streamModel != null) - { - streamModel.setForecastLengthInHours(_forecastLengthInHours); - - addStreamModel(streamModel); - } - - getAndAddAlternateStreamModelTimer.stop(header + " took "); - - } -// ----------------------------------------------------------------- - - private StreamModel createAlternateStreamModel(String locationId, - SacSmaStateDescriptor descriptor, - SacSmaStateDescriptor primaryDescriptor, - StreamModel primaryStreamModel) - { - - String header = "ModelManager.createAlternateStreamModel(): "; - - - final boolean isAlternateStreamModel = true; - - - StreamModel streamModel = new StreamModel(locationId, - primaryStreamModel.getRainfallRunoffModelType(), - getDataManager(), - isAlternateStreamModel); - - - System.out.println(header + "descriptor = " + descriptor); - - streamModel.setSacSmaStateDescriptor(descriptor); - streamModel.setModelStartTime(descriptor.getValidTime()); - - System.out.println(header + "before loadPriorRunoffTimeSeries, alternate streamModel = " + streamModel + "\n"); - - streamModel.loadPriorRunoffTimeSeries("loadPriorRunoffTimeSeries called from configureCurrentStreamModelsForSacSma()"); - - System.out.println(header + "after loadPriorRunoffTimeSeries, alternate streamModel = " + streamModel + "\n"); - - - streamModel.setPrecipTimeSeriesHolder(primaryStreamModel.getPrecipTimeSeriesHolder()); - - return streamModel; - } - -// ----------------------------------------------------------------- - StreamModel getStreamModelFromCache(SacSmaStateDescriptor descriptor) - { - StreamModel streamModel = _modelMap.get(descriptor); - - return streamModel; - } - -// ----------------------------------------------------------------- - - private boolean sameTimeAndSource(SacSmaStateDescriptor desc1, SacSmaStateDescriptor desc2) - { - boolean result = false; - - String source1 = desc1.getState().getSource(); - String source2 = desc2.getState().getSource(); - - if (desc1.getValidTime() == desc2.getValidTime()) - { - - if (source1.equals(source2)) - { - result = true; - } - - } - - return result; - } -// ----------------------------------------------------------------- - -} //end ModelManager diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ProcTsDescriptor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ProcTsDescriptor.java deleted file mode 100644 index ecda76b4ea..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/ProcTsDescriptor.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Created on Dec 9, 2003 - * - * Filename : Height.java - * Author : Gautam Sood - * Last Revision Date : Dec 9, 2003 - * - */ -package ohd.hseb.sshp; - -import java.text.*; - - -public class ProcTsDescriptor implements IngestFilterTsDescriptor -{ - - private String _tableName = null; - private String _lid = null; - private String _pe = null; - private String _ts = null; - private short _dur= 0; - private String _extremum = null; - - - //***************************************************************************** - // Empty constructor - //***************************************************************************** - public ProcTsDescriptor(String tableName) - { - setTableName(tableName); - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setPe( String pe ) - { - _pe = pe; - } - - public String getPe() - { - return _pe; - } - - public void setDur( short dur ) - { - _dur = dur; - } - - public short getDur() - { - return _dur; - } - - public void setTs( String ts ) - { - _ts = ts; - } - - public String getTs() - { - return _ts; - } - - public void setExtremum( String extremum ) - { - _extremum = extremum; - } - - public String getExtremum() - { - return _extremum; - } - - public String toString() - { - String formatString = "#####.#####"; - NumberFormat f = new DecimalFormat(formatString); - - String outString = "FcstHeight: " + - " Lid = " + _lid + - " Table NAme = " + _tableName + - " pe = " + _pe + - " ts = " + _ts + "\n" + - " Extremum = " + _extremum + - " dur = " + _dur; - return outString; - } - - public void setTableName(String tableName) - { - _tableName = tableName; - } - - public String getTableName() - { - return _tableName; - } -} - diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHP.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHP.java deleted file mode 100644 index 021bdbe2e9..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHP.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Created on Oct 3, 2003 - * - * - */ -package ohd.hseb.sshp; - -import javax.swing.UIManager; - -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -/** - * @author Chip Gobs - * - * This is the driver class for the SSHP Application - */ -public class SSHP -{ - - public static void main(String[] args) - { - try - { - //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); - } - catch (Exception e) - { - System.err.print(e.getMessage()); - e.printStackTrace(); - } - - if (args.length < 2) - { - System.err.println("Usage: ohd.hseb.sshp.SSHP connection_string logFileDir [location_id] "); - System.exit(0); - } - - - String baseConnectionString = args[0]; - - String logDirName = args[1]; - - - String logFileName = logDirName + "/SSHP.log"; - - Logger logger = new FileLogger(logFileName, true, true); - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - - AppController controller = new AppController(dataMgr, logDirName); - - if (args.length >= 3) - { - String locationId = args[2]; - controller.displayAnalysisWindow(locationId); - } - else - { - controller.displayControlWindowIfNotDisplayed(); - } - } //end main - -} //end class SSHP diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHPConfig.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHPConfig.java deleted file mode 100644 index bc0ed1658d..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHPConfig.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Created on Feb 4, 2004 - * - * Filename : SshpConfig.java - * Author : Gautam Sood - * Last Revision Date : Feb 4, 2004 - * - */ -//package ohd.hseb.model; -package ohd.hseb.sshp; - -import ohd.hseb.model.ForecastInterpolationMethod; - -public class SSHPConfig -{ - private String _lid = null; - private String _basinId = null; - private long _postingTime = 0; - private String _modelPref = null; - private boolean _autoProcess = false; - private String _sourcePref = null; - private boolean _useStaticEvap = false; - private boolean _useBlend = false; - private ForecastInterpolationMethod _blendMethod = null; - private int _blendHours = 0; - - public SSHPConfig() - { - } - - public SSHPConfig( SSHPConfig sshpConfig ) - { - - - _lid = sshpConfig.getLid(); - _basinId = sshpConfig.getBasinId(); - _postingTime = sshpConfig.getPostingTime(); - _modelPref = sshpConfig.getModelPref(); - _autoProcess = sshpConfig.isAutoProcess(); - _sourcePref = sshpConfig.getSourcePref(); - _useStaticEvap = sshpConfig.useStaticEvap(); - - _blendMethod = sshpConfig.getBlendMethod(); - - } - - public void setLid( String lid ) - { - _lid = lid; - } - - public String getLid() - { - return _lid; - } - - public void setBasinId( String basinId ) - { - _basinId = basinId; - } - - public String getBasinId() - { - return _basinId; - } - - public void setPostingTime( long postingTime ) - { - _postingTime = postingTime; - } - - public long getPostingTime() - { - return _postingTime; - } - - public void setModelPref( String modelPref ) - { - _modelPref = modelPref; - } - - public String getModelPref() - { - return _modelPref; - } - - public void setAutoProcess( boolean autoProcess ) - { - _autoProcess = autoProcess; - } - - public boolean isAutoProcess() - { - return _autoProcess; - } - - public void setSourcePref( String sourcePref ) - { - _sourcePref = sourcePref; - } - - public String getSourcePref() - { - return _sourcePref; - } - - public void setUseStaticEvap( boolean useStaticEvap ) - { - _useStaticEvap = useStaticEvap; - } - - public boolean useStaticEvap() - { - return _useStaticEvap; - } - - - public String toString() - { - return "Lid = " + _lid + - "Basin id = " + _basinId + - "Posting Time = " + _postingTime + - "Model Pref = " + _modelPref + - "Auto Process = " + _autoProcess + - "Source Pref = " + _sourcePref + - "Use Static Evap = " + _useStaticEvap; - } - - /** - * @param useBlend The useBlend to set. - */ - public void setUseBlend(boolean useBlend) - { - _useBlend = useBlend; - } - - /** - * @return Returns the useBlend. - */ - public boolean useBlend() - { - return _useBlend; - } - - /** - * @param blendMethod The blendMethod to set. - */ - public void setBlendMethod(ForecastInterpolationMethod blendMethod) - { - _blendMethod = blendMethod; - } - - /** - * @return Returns the blendMethod. - */ - public ForecastInterpolationMethod getBlendMethod() - { - return _blendMethod; - } - - /** - * @param blendHours The blendHours to set. - */ - public void setBlendHours(int blendHours) - { - _blendHours = blendHours; - } - - /** - * @return Returns the blendHours. - */ - public int getBlendHours() - { - return _blendHours; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHPSource.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHPSource.java deleted file mode 100644 index 733da7bac0..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SSHPSource.java +++ /dev/null @@ -1,124 +0,0 @@ -package ohd.hseb.sshp; - -import java.util.ArrayList; -import java.util.List; - -public class SSHPSource -{ - // ----------------------------------------------------------------------------------------- - - public final static SSHPSource ADJUSTED_VAR = new SSHPSource("adjusted var" , "ADJ_VAR" , "FA", "ADJRUNOFF"); - public final static SSHPSource UNADJUSTED_VAR = new SSHPSource("unadjusted var", "UNADJ_VAR", "FU", "UADJRUNOFF"); - - public final static SSHPSource RFC = new SSHPSource("RFC", "RFC", "FZ", "RFCRUNOFF"); - public final static SSHPSource SSHP_UPDATER = new SSHPSource("SSHP_Updater", "LOCAL", "FZ", "SSHPRUNOFF" ); - - public final static SSHPSource GENE_VAR = new SSHPSource("GENETIC VAR", "GENE_VAR", "FG", "GENERUNOFF" ); - // public final static SSHPSource GENE_VAR = new SSHPSource("GENETIC VAR", "GENE_VAR", "FA", "ADJRUNOFF" ); - - - private String _name = null; - private String _productId = null; - private String _sacSmaSource = null; //this is to be used for SacSmaStates - private String _typeSource = null; //this is to be used for TimeSeries info such as PriorComputerRunoff - - // ----------------------------------------------------------------------------------------- - - private static List _sourceList = new ArrayList(); - - static - { - _sourceList.add(ADJUSTED_VAR); - _sourceList.add(UNADJUSTED_VAR); - _sourceList.add(RFC); - _sourceList.add(SSHP_UPDATER); - _sourceList.add(GENE_VAR); - } - // ----------------------------------------------------------------------------------------- - - private SSHPSource(String name, String sacSmaSource, String typeSource, String productId) - { - setName(name); - setSacSmaSource(sacSmaSource); - setTypeSource(typeSource); - setProductId(productId); - } - // ----------------------------------------------------------------------------------------- - - public static SSHPSource findMatchingSSHPSourceBySacSmaSource(String sacSmaSource) - { - String header = "SSHPSource.findMatchingSSHPSourceBySacSmaSource(): "; - - SSHPSource matchingSource = null; - - for ( SSHPSource source : _sourceList) - { - if (sacSmaSource.equals(source.getSacSmaSource())) - { - matchingSource = source; - break; - } - } - - if (matchingSource != null) - { - System.out.println(header + " matchingSource = " + matchingSource.getSacSmaSource() ); - } - - return matchingSource; - } - - // ----------------------------------------------------------------------------------------- - - public void setName(String name) - { - _name = name; - } - - // ----------------------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - - // ----------------------------------------------------------------------------------------- - - public void setSacSmaSource(String sacSmaSource) - { - _sacSmaSource = sacSmaSource; - } - - // ----------------------------------------------------------------------------------------- - - public String getSacSmaSource() - { - return _sacSmaSource; - } - - // ----------------------------------------------------------------------------------------- - - public void setTypeSource(String typeSource) - { - _typeSource = typeSource; - } - - // ----------------------------------------------------------------------------------------- - - public String getTypeSource() - { - return _typeSource; - } - // ----------------------------------------------------------------------------------------- - - public void setProductId(String productId) { - _productId = productId; - } - - // ----------------------------------------------------------------------------------------- - - public String getProductId() { - return _productId; - } - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SacSmaStateDescriptor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SacSmaStateDescriptor.java deleted file mode 100644 index 95ffab1410..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SacSmaStateDescriptor.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Created on Apr 22, 2004 - * - * - */ -package ohd.hseb.sshp; - -import java.util.Date; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -import ohd.hseb.model.sacsma.SacSmaState; - -/** - * @author GobsC - * - * This class is used to summarize the states available for use by - * SSHP. Instances of this class may be used as items in a ComboBox. - */ -public class SacSmaStateDescriptor -{ - - private SacSmaState _state = null; - private boolean _isDefaultValue = false; - private int _hashCode = -1; - -// ----------------------------------------------------------------- - - public SacSmaStateDescriptor(SacSmaState state) - { - _state = state; - - } -// ----------------------------------------------------------------- - public int hashCode() - { - if (_hashCode == -1) - { - _hashCode = _state.toString().hashCode(); - } - return _hashCode; - } - -// ----------------------------------------------------------------- - public boolean equals(Object otherObject) - { - - return equals((SacSmaStateDescriptor) otherObject); - - } - - public boolean equals(SacSmaStateDescriptor descriptor) - { - - boolean result = false; - - if ( ( descriptor != null) && - (this.getState().equals(descriptor.getState())) - ) - { - result = true; - } - - return result; - - } -// ----------------------------------------------------------------- - public long getValidTime() - { - long time = 0; - - if (_state != null) - { - time = _state.getValidTime(); - } - - return time; - } - -// ----------------------------------------------------------------- - - public void setIsDefaultValue(boolean isDefaultValue) - { - _isDefaultValue = isDefaultValue; - } -// --------------------------------------------------------------- - - public boolean isDefaultValue() - { - return _isDefaultValue; - } -// --------------------------------------------------------------- - -// ----------------------------------------------------------------- - - public void setState(SacSmaState state) - { - _state = state; - } -//----------------------------------------------------------------- - - public SacSmaState getState() - { - return _state; - } -// ----------------------------------------------------------------- - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + " Z"; - - return timeString; - } -// ----------------------------------------------------------------- - - public String toString() - { - String outString = null; - - if (!isDefaultValue()) - { - outString = String.format("%10s State at %15s ", - _state.getSource(), getDateTimeStringToMinutes(_state.getValidTime()) ); - - // String sourceString = _state.getSource(); - // outString = sourceString + " State " + "at " + - // getDateTimeStringToMinutes(_state.getValidTime()); - } - else //is bogus default value - { - outString = String.format("%10s State at %15s ", - "BOGUS DFLT", getDateTimeStringToMinutes(_state.getValidTime()) ); - // outString = "BOGUS DEFAULT" + " State " + "at " + - // getDateTimeStringToMinutes(_state.getValidTime()); - } - return outString; - } -// ----------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SacStateUpdater.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SacStateUpdater.java deleted file mode 100644 index 37a2d142ac..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/SacStateUpdater.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Created on Mar 16, 2004 - * - * - */ -package ohd.hseb.sshp; - -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.TimeSeriesFileManager; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - -/** - * @author GobsC - * - * The purpose of this class is to check the - * most recent saved Sacramento Model states and - * run the model from the last saved state if the - * states have aged too much. - * - * The class also is responsible for creating "background" forecasts for situational awareness. - */ -public class SacStateUpdater -{ - - private FileLogger _logger = null; - - private static final long _millisPerHour = 1000 * 60 * 60; - private long _timeDiffMax = 0; - - private int _hoursForward = 0; - - private DataMgr _dataMgr = null; - private String _backgroundFcstOutputDirectoryNameString = null; - private static final String SSHP_BACKGROUND_FORECAST_OUTPUT_DIR = "sshp_background_forecast_output_dir"; - - private static final int _defaultBackgroundFcstLengthInHours = 48; - private int _backgroundFcstLengthInHours = _defaultBackgroundFcstLengthInHours; - private static final String SSHP_BACKGROUND_FORECAST_FCST_LENGTH = "sshp_background_forecast_length"; - - // ------------------------------------------------------------- - - public SacStateUpdater(DataMgr dataMgr, int expirationHours, int hoursForward, String logFileName) - { - _dataMgr = dataMgr; - _timeDiffMax = expirationHours * _millisPerHour; - - _hoursForward = hoursForward; - - boolean keepFileOpen = true; - boolean appendDateTime = true; - - _logger = new FileLogger(logFileName, keepFileOpen, appendDateTime); - - AppsDefaults ad = new AppsDefaults(); - - _backgroundFcstOutputDirectoryNameString = ad.getToken(SSHP_BACKGROUND_FORECAST_OUTPUT_DIR); - _backgroundFcstLengthInHours = ad.getInt(SSHP_BACKGROUND_FORECAST_FCST_LENGTH, - _defaultBackgroundFcstLengthInHours); - - return; - } - - // ------------------------------------------------------------- - public void finalize() - { - _logger.close(); - } - - // ------------------------------------------------------------- - - public void updateAllStates() - { - /* - get list of locations to maintain (from SSHPConfig) - - for each locationId - time = _dataMgr.getTimeOfBestRecentState() - if more than expirationHours old, then run model - for that locationId - - save the SacState, and the prior runoff - */ - - - List locationIdList = _dataMgr.loadAllLocationIdsToAutoUpdateSacStates(); - - for (String locationId : locationIdList) - { - updateStatesByLocation(locationId, true); - } - - if (locationIdList.size() == 0) - { - _logger.log("There are no locations for which auto process has been set."); - } - - - } //update states - - // ------------------------------------------------------------- - public void updateStatesByLocation(String locationId, boolean saveStates) - { - String header = "updateStatesByLocation(): "; - _logger.log(header + "Checking states for " + locationId); - - SacSmaState bestState = _dataMgr.loadBestRecentSacState(locationId); - - - if (bestState != null) - { - long bestStateTime = bestState.getValidTime(); - - - //long bestStateTime = _dataMgr.loadTimeOfBestRecentSacState(locationId); - - long currentTime = System.currentTimeMillis(); - currentTime = TimeHelper.truncateTimeInMillisToNearestHour(currentTime, 1); - - long timeDiff = (currentTime - bestStateTime); - if (timeDiff > _timeDiffMax) - { - _logger.log("Updating states for " + locationId + "."); - - StreamModel model = new StreamModel(locationId, - RainfallRunoffModelType.SAC_SMA, - _dataMgr); - - model.setSacSmaStateDescriptor(new SacSmaStateDescriptor(bestState)); - model.setModelStartTime(bestState.getValidTime()); - - long modelEndTime = currentTime + (_hoursForward * _millisPerHour); - model.setModelEndTime(modelEndTime); - - - _logger.log("Last saved state time = " + DbTimeHelper.getDateTimeStringFromLongTime(bestStateTime)); - _logger.log("Model run end time = " + DbTimeHelper.getDateTimeStringFromLongTime(modelEndTime)); - - model.runModel(); - - - if (saveStates) - { - - _logger.log("Saving model states for " + locationId + "."); - model.saveModelStates(_logger); - - - _logger.log("Saving computed runoff time series for " + locationId + "."); - model.saveRunoffTimeSeries(_logger); - } - - } - else - { - _logger.log("Model States for " + locationId + " are up to date."); - } - } //end if bestState != null - else - { - _logger.log("No original model States for " + locationId + " are available. Unable to update."); - } - } - - // ------------------------------------------------------------- - public void updateAllBackgroundForecasts() - { - /* - get list of locations for which to compute forecasts - - for each locationId - run the model and update the latest forecast stored on disk as a flat file - */ - - - List locationIdList = _dataMgr.loadLocationIdsForForecasts(); - - for (String locationId : locationIdList) - { - _logger.log("Attempting to update a background forecast for " + locationId ); - updateForecastByLocation(locationId); - } - - - if (locationIdList.size() == 0) - { - _logger.log("There are no locations for which to update a background forecast."); - } - - - } //update states - - // ------------------------------------------------------------- - - public void updateForecastByLocation(String locationId) - { - String header = "updateForecastByLocation(): "; - // _logger.log(header + " search for valid model states for " + locationId); - - StreamModel model = null; - SSHPConfig config = _dataMgr.getSSHPConfig(locationId); - - long currentTime = System.currentTimeMillis(); - currentTime = TimeHelper.truncateTimeInMillisToNearestHour(currentTime, 1); - - boolean isStateAvailable = false; - - String modelPreference = config.getModelPref(); - - if (modelPreference.equals("SAC-SMA")) - { - SacSmaState bestState = _dataMgr.loadBestRecentSacStateForForecasts(locationId); - _logger.log(header + "bestState for " + locationId + " = " + bestState); - - if (bestState != null) - { - isStateAvailable = true; - - model = new StreamModel(locationId, - RainfallRunoffModelType.SAC_SMA, - _dataMgr); - - model.setSacSmaStateDescriptor(new SacSmaStateDescriptor(bestState)); - model.setModelStartTime(bestState.getValidTime()); - - long modelEndTime = currentTime + (_backgroundFcstLengthInHours * _millisPerHour); - model.setModelEndTime(modelEndTime); - } - } - else //API_MKC - { - AbsTimeMeasurement ffhMeasurement = _dataMgr.loadMostCurrentFfhMeasurement(locationId, - config.getBasinId(), - currentTime); - _logger.log(header + "Using KC-API for " + locationId); - - if (ffhMeasurement != null) - { - isStateAvailable = true; - - model = new StreamModel(locationId, - RainfallRunoffModelType.API_MKC, - _dataMgr); - - model.setModelStartTime(ffhMeasurement.getTime()); - - long modelEndTime = currentTime + (_backgroundFcstLengthInHours * _millisPerHour); - model.setModelEndTime(modelEndTime); - } - } - - - if (isStateAvailable) - { - _logger.log("Updating Forecasts for " + locationId + "."); - - - // _logger.log("Last saved state time = " + DbTimeHelper.getDateTimeStringFromLongTime(bestStateTime)); - // _logger.log("Model run end time = " + DbTimeHelper.getDateTimeStringFromLongTime(modelEndTime)); - - model.runModel(); - - //for situational awareness applications (e.g. RiverMonitor) - TimeSeriesFileManager fileManager = new TimeSeriesFileManager(); - RegularTimeSeries fcstStageTimeSeries = model.getForecastStageTimeSeriesHolder().getTimeSeries(); - - //This feature can be turned off by not setting the token - if (_backgroundFcstOutputDirectoryNameString != null) - { - String filePath = _backgroundFcstOutputDirectoryNameString + "/" - + model.getLocationId() + "_fcst_stage.dat"; - - - _logger.log(header + "saving forecasts for " + locationId + " to " + filePath); - - fileManager.saveRegularTimeSeries(fcstStageTimeSeries, - filePath, - MeasuringUnit.feet); - } - else - { - _logger.log(header + "_backgroundFcstOutputDirectoryNameString is null," + - " unable to save forecast timeseries to a file."); - } - - } //end isStateAvailable - else - { - _logger.log(header + "No valid " + modelPreference + " model states for " + locationId + - " are available. Unable to create and save a background forecast."); - } - } - - // ------------------------------------------------------------- - - - public static void main(String[] args) - { - - if (args.length < 4) - { - System.err.println("Usage: ohd.hseb.sshp.StateUpdater connection_string expirationHours hoursForward logFilePath"); - System.exit(0); - } - - - String baseConnectionString = args[0]; - - String expirationHoursString = args[1]; - String hoursForwardString = args[2]; - String logFilePath = args[3]; - - int expirationHours = Integer.parseInt(expirationHoursString); - - if (expirationHours <= 0) - { - System.err.println("expirationHours must be a number > 0"); - System.exit(0); - } - - int hoursForward = Integer.parseInt(hoursForwardString); - // zero is ok - - //String logFilePath = logFileDir + "/SacStateUpdater.log"; - Logger logger = new FileLogger(logFilePath); - - - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - SacStateUpdater updater = new SacStateUpdater(dataMgr, expirationHours, hoursForward, logFilePath); - - updater.updateAllStates(); - - updater.updateAllBackgroundForecasts(); - - dataMgr.disconnect(); - - } //end main() - - // ------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/StreamModel.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/StreamModel.java deleted file mode 100644 index dffe807b55..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/StreamModel.java +++ /dev/null @@ -1,2281 +0,0 @@ -/* - * Created on Nov 3, 2003 - * This class took over nearly all of AppController's old duties. - * AppController now is in charge of setting up the environment - * for handling multiple model windows. - * AppController was created on Sep 17, 2003 - * - */ -package ohd.hseb.sshp; - -import java.sql.SQLException; -import java.util.List; - - -//import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.model.sacsma.*; -import ohd.hseb.model.mkcapi.*; -import ohd.hseb.util.*; - - -/** - * @author Chip Gobs - * - * This class hooks together all the computational elements for - * running a hydrologic model. It is also in charge of making calls to - * the DataMgr. - * - * As of August 2007, it is being controlled (at least partially) by the ModelManager, which can handle - * multiple StreamModel instances. - */ -public class StreamModel -{ - public static final int DEFAULT_FFG_DURATION_CODE = 1001; // REPRESENTS 1 HOUR - - private static final MeasuringUnit _stageUnit = MeasuringUnit.feet; - private static final MeasuringUnit _dischargeUnit = MeasuringUnit.cfs; - - private static final int MAX_DAYS_OF_TIME_SERIES = 100; - private static final int MILLIS_PER_HOUR = 60 * 60 * 1000; - private static final int MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; - - - // FORECAST ADJUSTMENT PARAMETERS (THE BLENDING TIME IS IN THE DATABASE) - private static final int DEFAULT_ADJUSTMENT_PAIRING_MINUTES = 70; - private static final int DEFAULT_ADJUSTMENT_INTERPOLATION_HOURS = 3; - private static final int MAX_BLENDING_HOURS = 1000; - - private int _adjustmentPairingMinutes = 0; - private int _adjustmentInterpolationHours = 0; - - - - private DataMgr _dataMgr = null; - private SSHPConfig _config = null; - - private RainfallRunoffModelType _rainfallRunoffModelType = null; - private int _modelRunCount = 0; - - // location-related variables - private String _locationId = null; - private String _locationName = null; - private String _basinId = null; - - private String _primaryPe = null; // HG or QR, height or discharge - - private static final int DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS = 24; - private static final int DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS = 120; - - private int _forecastLengthInHours = DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS; - private int _maxForecastLengthInHours = DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS; - - - private boolean _needStateReload = false; - private boolean _isAlternateStreamModel = false; - - //various time series holders - - - // precip - private RegularTimeSeriesHolder _precipTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - // evaporation - needed by SAC-SMA model - private RegularTimeSeriesHolder _evaporationTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - // calculated runoff - private RegularTimeSeriesHolder _runoffTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - // prior runoff - private RegularTimeSeriesHolder _priorRunoffTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - - // stage - private IrregularTimeSeriesHolder _observedStageTimeSeriesHolder = - new IrregularTimeSeriesHolder(); - private RegularTimeSeriesHolder _simulatedStageTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - private RegularTimeSeriesHolder _forecastStageTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - private IrregularTimeSeriesHolder _priorForecastStageTimeSeriesHolder = - new IrregularTimeSeriesHolder(); - - //discharge - private RegularTimeSeriesHolder _simulatedDischargeTimeSeriesHolder = - new RegularTimeSeriesHolder(); - - - private SigRiverLevels _sigRiverLevels = null; - - // modeling objects - private RainfallToStageModel _rainfallToStageModel = null; - private RainfallRunoffModel _rainfallRunoffModel = null; - - private RatingCurve _ratingCurve = null; - private UnitHydrograph _unitHydrograph = null; - private UnitHydrograph _customUnitHydrograph = null; - private MeasurementHolder _initialStageMeasurementHolder = - new MeasurementHolder(); - - // a rating-related object - private StageToFlowValueMapper _stageToFlowValueMapper = null; - - - //SAC model variables - private List _sacStateDescriptorList = null; - private SacSmaParameters _sacParams = null; - private SacSmaState _sacState = null; - private SacSmaState _finalSacState = null; - private SacSmaStateDescriptor _sacSmaStateDescriptor = null; - private boolean _isAdjustmentOn = false; - private ForecastAdjuster _forecastAdjuster = null; - - - //KC model variables - private List _ffhDescriptorList = null; - private FFHDescriptor _ffhDescriptor = null; - private static final MeasuringUnit _ffhUnit = MeasuringUnit.inches; - private static final double _defaultFFHValue = 5.0; - private double _ffhValue = 0.0; - private double _thresholdRunoff = 0.0; - - - //basistime - private static final int _intervalInHours = 1; - // private static final int _hoursBack = 24; - private static final int _millisPerHour = 1000 * 60 * 60; - - // model run start and end times - // Note: the end time is currently hardcoded to go out some hours beyond - // the current time - private TimeHolder _modelStartTimeHolder = new TimeHolder(); - private TimeHolder _modelEndTimeHolder = new TimeHolder(); - - - - // for debugging - CodeTracer _tracer = null; - - static CodeTimer _overAllInitRainfallRunoffDataTimer = new CodeTimer(); - static CodeTimer _overAllLoadPriorRunoffTimeSeriesTimer = new CodeTimer(); - static CodeTimer _overAllLoadObservedStageTimeSeriesTimer = new CodeTimer(); - -// ----------------------------------------------------------- - public StreamModel(String locationId, - RainfallRunoffModelType modelType, - DataMgr dataMgr, - boolean isAlternateStreamModel) - { -// _tracer = new CodeTracer(); - - _locationId = locationId; - - _rainfallRunoffModelType = modelType; - - _dataMgr = dataMgr; - - setIsAlternateStreamModel(isAlternateStreamModel); - - - - _config = _dataMgr.getSSHPConfig(_locationId); - - AppsDefaults ad = new AppsDefaults(); - - // TODO consider a bundle to set all of this from ModelManager's data - - //load the forecast length parameters - _forecastLengthInHours = ad.getInt("sshp_initial_forecast_length", - DEFAULT_INITIAL_FORECAST_LENGTH_IN_HOURS); - - _maxForecastLengthInHours = ad.getInt("sshp_max_forecast_length", - DEFAULT_MAX_FORECAST_LENGTH_IN_HOURS); - - if (_forecastLengthInHours > _maxForecastLengthInHours) - { - _maxForecastLengthInHours = _forecastLengthInHours; - } - - - //load the adjustment parameters - _adjustmentPairingMinutes = ad.getInt("sshp_adjustment_pairing_minutes", DEFAULT_ADJUSTMENT_PAIRING_MINUTES); - _adjustmentInterpolationHours = ad.getInt("sshp_adjustment_interpolation_hours", DEFAULT_ADJUSTMENT_INTERPOLATION_HOURS); - - - //set the basin id associated with the locationId - if (_config != null) - { - _basinId = _config.getBasinId(); - } - else - { - _basinId = "BOGUS_BASIN"; - } - - //get the location name - _locationName = dataMgr.getLocationName(_locationId); - - - //set the model run start time - long modelStartTime = getTimeOfBestRecentState(_locationId, _basinId); - if (modelStartTime == 0) - { - modelStartTime = getLatestHourTime(); - } - else - { - modelStartTime = TimeHelper.truncateTimeInMillisToNearestHour(modelStartTime, 1); - } - - setModelStartTime(modelStartTime); - - - // init the model states, parameters and input time series data - - setNeedStateReload(true); - - initModelData(); - - initAllTimeSeries(); - - if (_sacState == null) - { - _sacState = getDefaultSacSmaState(); - } - - return; - } - -// ----------------------------------------------------------- - - public StreamModel(String locationId, - RainfallRunoffModelType modelType, - DataMgr dataMgr) - { - - this(locationId, modelType, dataMgr, false); - } -// ----------------------------------------------------------- - - private void trace() - { - try - { - throw new Exception("trace"); - } - catch (Exception e) - { - e.printStackTrace(); - } - } -// ------------------------------------------------------------------------------------- - public String[] getPeArray(char firstLetterOfPhysicalElement) - { - String[] peArray = null; - String[] heightArray = {"HG", "HP", "HT" }; - String[] dischargeArray = {"QR"}; - - peArray = _dataMgr.loadPhysicalElementArray(firstLetterOfPhysicalElement); - if (peArray == null) - { - if (firstLetterOfPhysicalElement == 'H') - { - peArray = heightArray; - } - else if (firstLetterOfPhysicalElement == 'Q') - { - peArray = dischargeArray; - } - } - - return peArray; - } - -// ------------------------------------------------------------------------------------- - public String getRainfallRunoffModelTypeName() - { - String modelTypeName = null; - if (_rainfallRunoffModelType != null) - { - modelTypeName = _rainfallRunoffModelType.getName(); - } - - return modelTypeName; - } -// ------------------------------------------------------------------------------------- - public RainfallRunoffModelType getRainfallRunoffModelType() - { - return _rainfallRunoffModelType; - - } - -// ------------------------------------------------------------------------------------- - - public double findThresholdRunoffValue() - { - - // _unitHydrograph = getBestUnitHydrograph(_unitHydrograph); - - if (_ratingCurve == null) - { - _ratingCurve = _dataMgr.loadRatingCurve(_locationId); - } - - - return findThresholdRunoffValue(_unitHydrograph, _ratingCurve); - } -// ------------------------------------------------------------------------------------- - - public boolean setRainfallRunoffModelType(RainfallRunoffModelType modelType) - { - boolean success = false; - - if (isValidModelTypeForLocation(modelType)) - { - success = true; - - _rainfallRunoffModelType = modelType; - - _customUnitHydrograph = null; - - initModelData(); - - initAllNonPrecipTimeSeries(); - } - - - return success; - - } -// ------------------------------------------------------------------------------------- - - private boolean isValidModelTypeForLocation(RainfallRunoffModelType type) - { - boolean valid = false; - - if (type == RainfallRunoffModelType.API_MKC) - { - valid = true; - } - // SshpConfig config = _dataMgr.loadSshpConfig(_locationId); - else - { - if (_config != null) - { - valid = true; - } - } - - return valid; - - } -// ------------------------------------------------------------------------------------- - - public void reloadModelData() - { - final String header = "StreamModel.reloadModelData():"; - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - - //System.out.println(header + "called"); - - _unitHydrograph = null; - _ratingCurve = null; - _stageToFlowValueMapper = null; - - initModelData(); - - // timer.stop(header + "took"); - - } - -// ------------------------------------------------------------------------------------- - - private long getTimeOfBestRecentState(String locationId, String basinId) - { - long bestStateTime = 0; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - SacSmaState state = getLatestSacSmaStateFromDescriptorList(); - bestStateTime = state.getValidTime(); - } - else if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) - { - bestStateTime = _dataMgr.getTimeOfBestRecentFFH(locationId, basinId); - } - - return bestStateTime; - - } - -// ------------------------------------------------------------------------------------- - - private void initModelData() - { - - String header = "StreamModel.initModelData(): "; - - CodeTimer initRainfallRunoffDataTimer = new CodeTimer(); - - - //System.out.println(header + "start. "); - - //this method is to be called when the model is going to - // be run for the first time with this set of settings - //it is called again when any modelData setting is changed - - //make sure that _unitHydrograph contains the best data available - if ( _customUnitHydrograph != null) - { - _unitHydrograph = _customUnitHydrograph; - } - else - { - _unitHydrograph = getBestUnitHydrograph(_unitHydrograph); - } - - - if (_ratingCurve == null) - { - _ratingCurve = _dataMgr.loadRatingCurve(_locationId); - } - - if (_stageToFlowValueMapper == null) - { - _stageToFlowValueMapper = new StageToFlowValueMapper(_ratingCurve); - } - - // init the forecastAdjust object - if (_forecastAdjuster == null) - { - ForecastAdjusterParams params = new ForecastAdjusterParams(); - - params.setPairingTimeMinutes(_adjustmentPairingMinutes); - params.setInterpolationHours(_adjustmentInterpolationHours); - params.setBlendingHours(_config.getBlendHours()); - - params.setBlendingMethod(_config.getBlendMethod()); - params.setShouldDoAdjustment(_config.useBlend()); - _forecastAdjuster = new ForecastAdjuster(params); - _isAdjustmentOn = _config.useBlend(); - } - - // _overAllInitRainfallRunoffDataTimer.restart(); - // initRainfallRunoffDataTimer.start(); - initRainfallRunoffModelData(); - // initRainfallRunoffDataTimer.stop( header + " initRainfallRunoffModeData() took this turn: " ); - // _overAllInitRainfallRunoffDataTimer.stop( header + " initRainfallRunoffModeData() took overall so far: " ); - - - } //end initModelData - -// ------------------------------------------------------------------------------------- - - private void initRainfallRunoffModelData() - { - - // String header = "initRainfallRunoffModelData(): "; - - if ( _rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) - { - if (_unitHydrograph == null) - { - trace(); - } - - _rainfallRunoffModel = initKcApiModelData(_unitHydrograph, _ratingCurve); - _rainfallToStageModel = new KcApiRainfallToStageModel(_rainfallRunoffModel, - _unitHydrograph, - _ratingCurve, - _initialStageMeasurementHolder, - _observedStageTimeSeriesHolder, - _forecastAdjuster, - _simulatedDischargeTimeSeriesHolder); - - } - else if ( _rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - - // CodeTimer priorRunoffTimerSeriesTimer = new CodeTimer(); - // priorRunoffTimerSeriesTimer.start(); - // loadPriorRunoffTimeSeries("called from " + header); - - - // priorRunoffTimerSeriesTimer.stop(header + " loadPriorRunoffTimeSeries() took: "); - - // System.out.println(header + "start. "); - - _rainfallRunoffModel = initSacSmaModelData(); - _rainfallToStageModel = - new SacRainfallToStageModel(_rainfallRunoffModel, - _unitHydrograph, - _ratingCurve, - _priorRunoffTimeSeriesHolder, - _observedStageTimeSeriesHolder, - _forecastAdjuster, - _simulatedDischargeTimeSeriesHolder); - - loadPriorRunoffTimeSeries(null); - } - - } -// ------------------------------------------------------------------------------------- - - - public String[] getUnitHydrographNameArray() - { - List uhgDescList = _dataMgr.loadUnitHydrographDescriptorList(getLocationId()); - UnitHydrographDescriptor descriptor; - - String[] nameArray = new String[uhgDescList.size() ]; - - for (int i = 0; i < uhgDescList.size(); i++) - { - descriptor = (UnitHydrographDescriptor) uhgDescList.get(i); - nameArray[i] = descriptor.getModel(); - } - - return nameArray; - } -// ------------------------------------------------------------------------------------- - public void changeUnitHydrograph(String unitHydrographName) - { - //String header = "StreamModel.changeUnitHydrograph() : "; - - //System.out.println(header + "inside"); - - //if there is a change, then load the different unitHydrograph - if (! _unitHydrograph.getRainfallRunoffModelTypeName().equals(unitHydrographName)) - { - - //System.out.println(header + "making UHG change to " + unitHydrographName); - _unitHydrograph = _dataMgr.loadUnitHydrograph(_locationId, - _basinId, - unitHydrographName); - _customUnitHydrograph = _unitHydrograph; - - initModelData(); - - } - else - { - // System.out.println(header + "REFUSING to making UHG change to " + unitHydrographName); - } - - return; - } - // ------------------------------------------------------------------------------------- - - public String getUnitHydrographSelectionName() - { - String currentName = null; - - currentName = _unitHydrograph.getRainfallRunoffModelTypeName(); - - return currentName; - } - -// ------------------------------------------------------------------------------------- - - private UnitHydrograph getBestUnitHydrograph(UnitHydrograph oldUnitHydrograph) - { - String header = "StreamModel.getBestUnitHydrograph() : "; - - - /* - * This method will just return the passed-in unit hydrograph if it is not null and - * its model type matches the current RainfallRunoffModel type. - * - * If the oldUnitHydrograph is null, then a UHG will be loaded. - * - * else if a customUnitHydrograph has been chosen, then the unitgraph will not change. - * - * else if the model types of the currently selected UHG (oldUnitHydrograph) does not match with the RainfallRunoff Model type, - * this routine loads the unithydrograph from the DataMgr. - * - * If after that, the unit hydrograph has no points, then the routine tries to - * load the unithydrograph for the same location and basin but for a different - * rainfall runoff model. It is anticipated that this last bit of functionality - * will be used mostly when the user is trying to use the SAC-SMA, and has not - * define a SAC-SMA unit hydrograph, but does have an API-MKC model unit hydrograph - * available. - */ - // final String header = "StreamModel.getBestUnitHydrograph(): "; - UnitHydrograph newUnitHydrograph = null; - - - String oldUnitHydrographModelType = null; - String modelTypeName = null; - - if (oldUnitHydrograph != null) - { - oldUnitHydrographModelType = oldUnitHydrograph.getRainfallRunoffModelTypeName(); - modelTypeName = _rainfallRunoffModelType.getName(); - } - - - // Determine if need to load new unit hydrograph - boolean needToChangeUhg = false; - - if (oldUnitHydrograph == null) - { - needToChangeUhg = true; - } - else if ( (_customUnitHydrograph == null) && - ( ! oldUnitHydrographModelType.equals(modelTypeName)) - ) - { - needToChangeUhg = true; - } - - - if ( needToChangeUhg) - { - newUnitHydrograph = _dataMgr.loadUnitHydrograph(_locationId, _basinId, _rainfallRunoffModelType.getName()); - _customUnitHydrograph = null; // clear out the custom unit hydrograph - - // if did not read any ordinates, try to load a different 1-hour UHG - if (newUnitHydrograph.getOrdinateCount() == 0) - { - String otherModelTypeName = null; - - newUnitHydrograph = _dataMgr.loadUnitHydrograph(_locationId, _basinId, "ANY"); - _customUnitHydrograph = null; - } - else - { - // System.out.println(header + "Unitgraph loaded successfully for the " + - // _rainfallRunoffModelType.getName() + " model."); - } - } - - else // not null and the rainfall-runoff model types match - { - newUnitHydrograph = oldUnitHydrograph; - } - - return newUnitHydrograph; - } - -// ------------------------------------------------------------------------------------- - - private void refreshModelData() - { - String header = "StreamModel.refreshModelData(): "; - //System.out.println(header + " started"); - - // This is to be called when the model is being re-run - - if ( _rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) - { - // _rainfallRunoffModel = initKcApiModelData(_unitHydrograph, _ratingCurve); - } - else if ( _rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - SacSmaRainfallRunoffModel sacModel = (SacSmaRainfallRunoffModel) _rainfallRunoffModel; - sacModel.setState(getSacState()); - } - - } //refreshModelData() -// ------------------------------------------------------------------------------------- - - private RainfallRunoffModel initSacSmaModelData() - { - // String header = "StreamModel.initSacSmaModelData():"; - - //CodeTimer timer1 = new CodeTimer(); - //timer1.start(); - - // long lastValidTime = getLatestHourTime(); - long lastValidTime = _modelStartTimeHolder.getTime(); - - _sacParams = _dataMgr.loadSacSmaParameters(_basinId, lastValidTime); - if (_sacParams == null) - { - _sacParams = getDefaultParams(); - } - - // System.out.println("sacParams = " + _sacParams); - - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - - - if (needStateReload()) - { - - SacSmaStateDescriptor descriptor = getSacSmaStateDescriptorFromDescriptorList(lastValidTime); - - // SacSmaState descriptorListState = getSacSmaStateFromDescriptorList(lastValidTime); - - // System.out.println(header + " before setting the sacState from the descriptor list to " + descriptorListState); - - setSacSmaStateDescriptor(descriptor); - // setSacState(descriptorListState); - - setNeedStateReload(false); - } - - - if (getSacState() == null) - { - setSacSmaStateDescriptor(getDefaultSacSmaStateDescriptor()); - // setSacState(getDefaultSacSmaState()); - } - - //_sacState = _dataMgr.loadSacSmaState(_basinId, lastValidTime); - - // System.out.println("sacState = " + _sacState); - - - - - // - boolean useStaticMape = true; - - if (_config != null) - { - useStaticMape =_config.useStaticEvap(); - } - - boolean isAdjustment = false; - - if (useStaticMape) //using the 12 monthly values straight - { - isAdjustment = false; - } - else //using the MAPE time series. Using the 12 monthly values as adjustment factors - { - isAdjustment = true; - } - - MonthlyValues monthlyValues = _dataMgr.loadMonthlyValues(_basinId, isAdjustment); - - double peAdjust = _sacParams.getPeadj(); - double pxAdjust = _sacParams.getPxadj(); - - RainfallRunoffModel rainfallRunoffModel = - new SacSmaRainfallRunoffModel(getSacState(), _sacParams, - peAdjust, - pxAdjust, - useStaticMape, - monthlyValues, - _evaporationTimeSeriesHolder); - - // timer1.stop(header + "model setup took"); - - return rainfallRunoffModel; - - } -// ------------------------------------------------------------------------------------- - - private RainfallRunoffModel initKcApiModelData(UnitHydrograph unitHydrograph, - RatingCurve ratingCurve) - { - String header = "StreamModel.initKcApiModelData():"; - - // CodeTimer timer1 = new CodeTimer(); - // timer1.start(); - - _thresholdRunoff = findThresholdRunoffValue(unitHydrograph, ratingCurve); - - // System.out.println(header + "before getFfgValue() ffhValue = " + _ffhValue); - _ffhValue = findFfhValue(_ffhDescriptor); - //System.out.println(header + "after getFfgValue() ffhValue = " + _ffhValue); - - RainfallRunoffModel rainfallRunoffModel = - new KcApiRainfallRunoffModel(_thresholdRunoff, _ffhValue); - - // timer1.stop(header + "model setup took"); - - return rainfallRunoffModel; - - } -// ------------------------------------------------------------------------------------- - public StageToFlowValueMapper getStageToFlowValueMapper() - { - return _stageToFlowValueMapper; - } -// ------------------------------------------------------------------------------------- - - public String getLocationName() - { - return _locationName; - } - -// ------------------------------------------------------------------------------------- - - public boolean hasSacSmaParams() - { - return _dataMgr.hasSacSmaParams(_basinId); - } - -// ------------------------------------------------------------------------------------- - - public long getSacParamsValidTime() - { - long time = 0; - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - time = _sacParams.getValidTime(); - - } - - return time; - } - -// ------------------------------------------------------------------------------------- - - public long getSacStateValidTime() - { - long time = 0; - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - time = getSacState().getValidTime(); - } - - return time; - } - -// ------------------------------------------------------------------------------------- - - private double findThresholdRunoffValue(UnitHydrograph unitHydrograph, - RatingCurve ratingCurve) - { - - String header = "StreamModel.getThresholdRunoffValue()"; - - double thresholdRunoff = _dataMgr.loadThresholdRunoffValue(_locationId); - - if (thresholdRunoff == _dataMgr.MISSING) - { - //System.out.println(header + "going to calculate the ThresholdRunoff value"); - SigRiverLevels sigStages = _dataMgr.loadSigRiverLevels(_locationId); - - if (sigStages != null) - { - thresholdRunoff = calculateThresholdRunoffValue( - sigStages.getFloodStage(), - unitHydrograph, - ratingCurve); - } - else - { - thresholdRunoff = _dataMgr.MISSING; - } - } - return thresholdRunoff; - } - - //---------------------------------------------------------------------------- - private double calculateThresholdRunoffValue(double floodStage, UnitHydrograph unitHydrograph, - RatingCurve ratingCurve) - { - String header = "StreamModel.calculateThresholdRunoffValue()"; - // System.out.println(header + " - just starting"); - - double thresholdRunoffValue = 0; - double peakFlow = _dataMgr.MISSING; - double floodFlow = ratingCurve.getDischargeFromStage(floodStage); - RelTimeMeasurement peakMeasurement = unitHydrograph.getPeakFlowMeasurement(); - - if (peakMeasurement != null) - { - peakFlow = peakMeasurement.getValue(); - thresholdRunoffValue = floodFlow/peakFlow; - } - - //System.out.println(header + "thresholdRunoff = " + thresholdRunoffValue); - return thresholdRunoffValue; - } - - //---------------------------------------------------------------------------- - public double findFfhValue() - { - return findFfhValue(_ffhDescriptor); - } - - //---------------------------------------------------------------------------- - - private double findFfhValue(FFHDescriptor descriptor) - { - double ffhValue = -999; - - if (descriptor != null) - { - ffhValue = descriptor.getValueInInches(); - } - - else // (descriptor == null) - { - AbsTimeMeasurement ffhMeasurement = - _dataMgr.loadMostCurrentFfhMeasurement(_locationId, _basinId, - _modelStartTimeHolder.getTime()); - - // System.out.println( "StreamModel.findFfhValue(): modelStartTimeHolder : " + _modelStartTimeHolder.getTime() ); - - if (ffhMeasurement != null) - { - ffhValue = ffhMeasurement.getValue(MeasuringUnit.inches); - } - else - { - ffhValue = getDefaultFFHDescriptor().getValueInInches(); - } - // System.out.println("StreamModel.getFfhValue() = " + ffhValue); - - } - - return ffhValue; - } - - //---------------------------------------------------------------------------- - public List getFFHDescriptorList() - { - _ffhDescriptorList = _dataMgr.loadFfhDescriptorList(_locationId, _basinId); - - if (_ffhDescriptorList.size() == 0) - { - _ffhDescriptorList.add(getDefaultFFHDescriptor()); - } - - return _ffhDescriptorList; - } - //---------------------------------------------------------------------------- - private SacSmaState getDefaultSacSmaState() - { - SacSmaState state = new SacSmaState(); - SacSmaParameters params = getSacParams(); - - if (params == null) - { - params = new SacSmaParameters(); //all zeroes - } - - double scalar = 0.5; - - state.setSource("BOGUS DFLT"); - - state.setBasinId(_basinId); - state.setValidTime(getLatestHourTime()); - - state.setUztwc(scalar * params.getUztwm()); - state.setUzfwc(scalar * params.getUztwm()); - state.setLztwc(scalar * params.getLztwm()); - state.setLzfsc(scalar * params.getLzfsm()); - state.setLzfpc(scalar * params.getLzfpm()); - state.setAdimc(scalar * (params.getUztwm() + params.getLztwm()) ); - - return state; - } - // ---------------------------------------------------------------------------- - private SacSmaStateDescriptor getDefaultSacSmaStateDescriptor() - { - return new SacSmaStateDescriptor(getDefaultSacSmaState()); - } - - // ---------------------------------------------------------------------------- - private FFHDescriptor getDefaultFFHDescriptor() - { - AbsTimeMeasurement measurement = new AbsTimeMeasurement(_defaultFFHValue, getLatestHourTime(), _ffhUnit); - FFHDescriptor descriptor = new FFHDescriptor(_locationId, measurement, DEFAULT_FFG_DURATION_CODE, false); - descriptor.setIsDefaultValue(true); - - return descriptor; - } - // ---------------------------------------------------------------------------- - public List getSacSmaStateDescriptorList() - { - return getSacSmaStateDescriptorList(false); - } - - public List getSacSmaStateDescriptorList(boolean forceCacheUpdate) - { - if (forceCacheUpdate) - { - _dataMgr.clearPriorRunoffTimeSeriesCache(); - } - - List list = _dataMgr.getSacSmaStateDescriptorListByBasinId(getBasinId(), forceCacheUpdate); - if (list.size() == 0) - { - SacSmaState state = getDefaultSacSmaState(); - SacSmaStateDescriptor descriptor = new SacSmaStateDescriptor(state); - - list.add(descriptor); - } - return list; - } - - // ---------------------------------------------------------------------------- - - private SacSmaStateDescriptor getSacSmaStateDescriptorFromDescriptorList(long modelRunStartTime) - { - //trace(); - String header = "StreamModel.getSacSmaStateDescriptorFromDescriptorList(): "; - SacSmaStateDescriptor returnStateDescriptor = null; - - if (_sacStateDescriptorList == null) - { - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - } - - for (int i = 0; i < _sacStateDescriptorList.size(); i++) - { - SacSmaStateDescriptor descriptor = (SacSmaStateDescriptor) _sacStateDescriptorList.get(i); - SacSmaState state = descriptor.getState(); - - // System.out.println(header + " modelRunStartTime = " + DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime)); - // System.out.println(header + " i = " + i + " state = " + state); - // System.out.println(header + " descriptor = " + descriptor); - - if (state.getValidTime() <= modelRunStartTime) - { - - //TODO fix this issue of loading and reloading state data, unnecessarily - returnStateDescriptor = descriptor; - break; - } - - } - - return returnStateDescriptor; - } - // ---------------------------------------------------------------------------- - - private SacSmaState getSacSmaStateFromDescriptorList(long modelRunStartTime) - { - //trace(); - String header = "StreamModel.getSacSmaStateFromDescriptorList(): "; - SacSmaState returnState = null; - - if (_sacStateDescriptorList == null) - { - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - } - - for (int i = 0; i < _sacStateDescriptorList.size(); i++) - { - SacSmaStateDescriptor descriptor = (SacSmaStateDescriptor) _sacStateDescriptorList.get(i); - SacSmaState state = descriptor.getState(); - - // System.out.println(header + " modelRunStartTime = " + DbTimeHelper.getDateTimeStringFromLongTime(modelRunStartTime)); - // System.out.println(header + " i = " + i + " state = " + state); - - if (state.getValidTime() <= modelRunStartTime) - { - - //TODO fix this issue of loading and reloading state data, unnecessarily - returnState = state; - //System.out.println(header + "will return this state i = " + i + " state = " + state); - - break; - - } - - } - - return returnState; - } - // ---------------------------------------------------------------------------- - private SacSmaState getLatestSacSmaStateFromDescriptorList() - { - //trace(); - String header = "StreamModel.getLatestSacSmaStateFromDescriptorList(): "; - SacSmaState returnState = null; - - if (_sacStateDescriptorList == null) - { - _sacStateDescriptorList = getSacSmaStateDescriptorList(); - } - - - if (_sacStateDescriptorList.size() > 0) - { - SacSmaStateDescriptor descriptor = (SacSmaStateDescriptor) _sacStateDescriptorList.get(0); - SacSmaState state = descriptor.getState(); - returnState = state; - // System.out.println(header + "will return state = " + state); - } - - return returnState; - } - - // ---------------------------------------------------------------------------- - - public static SacSmaParameters getDefaultParams() - { - //uses sept93 data for ELDO2) - /* - PXADJ = 1.000 - PEADJ = 1.000 - UZTWM = 60.000 - UZFWM = 25.000 - UZK = 0.350 - PCTIM = 0.000 - ADIMP = 0.000 - RIVA = 0.003 - ZPERC = 210.000 - REXP = 1.40 - LZTWM = 120.000 - LZFSM = 25.000 - LZFPM = 150.000 - LZSK = 0.080 - LZPK = 0.004 - PFREE = 0.250 - RSERV = 0.300 - SIDE = 0.000 - IOPTET=0 //we don't have this one, so ignore it - EFC = 0.50 - */ - - SacSmaParameters params = new SacSmaParameters(); - - params.setPxadj(1.0); - params.setPeadj(1.0); - params.setUztwm(60.0); - params.setUzfwm(25.0); - params.setUzk(0.35); - params.setPctim(0.000); - params.setAdimp(0.000); - params.setRiva(0.003); - params.setZperc(210.000); - params.setRexp(1.40); - params.setLztwm(120.000); - params.setLzfsm(25.0); - params.setLzfpm(150.000); - params.setLzsk(0.080); - params.setLzpk(0.004); - params.setPfree(0.250); - params.setRserv(0.300); - params.setSide(0.000); - params.setEfc(.50); - - return params; - } - - // ----------------------------------------------------------------------- - - public void reloadPrecipTimeSeries() - { - initDbPrecipTimeSeries(); - - return; - } - - // --------------------------------------------------------------------- - - public void reloadFilePrecipTimeSeries(String filePathString) - { - initFilePrecipTimeSeries(filePathString); - - return; - } - - // --------------------------------------------------------------------- - - private void initDbPrecipTimeSeries() - { - String header = "StreamModel.initDbPrecipTimeSeries() : "; - - long lastTimeSeriesHour = _modelEndTimeHolder.getTime(); - long firstTimeSeriesHour = lastTimeSeriesHour - MAX_DAYS_OF_TIME_SERIES * 24 * MILLIS_PER_HOUR; - - - // precip - long lastObsTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - long firstObsTime = lastObsTime - MAX_DAYS_OF_TIME_SERIES * 24 * MILLIS_PER_HOUR; - RegularTimeSeries obsPrecipTs = loadObservedPrecipTimeSeries(firstObsTime, lastObsTime); - obsPrecipTs.setName("Original Observed Precip Ts"); - //System.out.println(header + "after loadObservedPrecipTimeSeries, obs precip ts = " + obsPrecipTs); - - - // new code - // CodeTimer timer = new CodeTimer(); - // timer.start(); - RegularTimeSeries fcstPrecipTs = _dataMgr.loadFcstMapTimeSeries(_basinId, getLatestHourTime() + _millisPerHour); - // timer.stop("_dataMgr.loadFcstMapTimeSeries took "); - - RegularTimeSeries fullPrecipTs = RegularTimeSeries.concatenate(obsPrecipTs, fcstPrecipTs); - //end new code - - - long precipStartTime = obsPrecipTs.getStartTime(); - if ( - (precipStartTime < firstTimeSeriesHour) || - (precipStartTime > lastTimeSeriesHour) - ) - { - //System.out.println(header + " creating a new time series"); - // obsPrecipTs = new RegularTimeSeries(firstTimeSeriesHour, lastTimeSeriesHour, - // 1, MeasuringUnit.inches); - // System.out.println(header + "after re-creation obs precip ts = " + obsPrecipTs); - } - else - { - // System.out.println(header + "before stretching obs precip ts = " + obsPrecipTs); - - //obsPrecipTs.stretchTimeSeries(firstTimeSeriesHour, lastTimeSeriesHour, 0.0); - fullPrecipTs.stretchTimeSeries(firstTimeSeriesHour, lastTimeSeriesHour, 0.0); - - // System.out.println(header + "after stretching obs precip ts = " + obsPrecipTs); - } - - - // _precipTimeSeriesHolder.setTimeSeries(obsPrecipTs); - _precipTimeSeriesHolder.setTimeSeries(fullPrecipTs); - - - return; - } - - // ---------------------------------------------------------------------------- - - private void initFilePrecipTimeSeries(String filePathString) - { - String header = "StreamModel.initFilePrecipTimeSeries() : "; - - long lastTimeSeriesHour = _modelEndTimeHolder.getTime(); - long firstTimeSeriesHour = lastTimeSeriesHour - MAX_DAYS_OF_TIME_SERIES * 24 * MILLIS_PER_HOUR; - - - // precip - long lastObsTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - long firstObsTime = lastObsTime - MAX_DAYS_OF_TIME_SERIES * 24 * MILLIS_PER_HOUR; - RegularTimeSeries obsPrecipTs = loadObservedPrecipTimeSeries(firstObsTime, lastObsTime); - obsPrecipTs.setName("Original Observed Precip Ts"); - //System.out.println(header + "after loadObservedPrecipTimeSeries, obs precip ts = " + obsPrecipTs); - - - RegularTimeSeries fcstPrecipTs = - _dataMgr.loadFcstMapTimeSeries(_basinId, - getLatestHourTime() + _millisPerHour); - - RegularTimeSeries fullPrecipTs = _dataMgr.loadFileMapTimeSeries(filePathString); - - - long precipStartTime = obsPrecipTs.getStartTime(); - if ( - (precipStartTime < firstTimeSeriesHour) || - (precipStartTime > lastTimeSeriesHour) - ) - { - - } - else - { - fullPrecipTs.stretchTimeSeries(firstTimeSeriesHour, lastTimeSeriesHour, 0.0); - - } - - _precipTimeSeriesHolder.setTimeSeries(fullPrecipTs); - - - return; - } - // ---------------------------------------------------------------------------- - - private void initAllNonPrecipTimeSeries() - { - // long lastEvenHour = getLatestHourTime(); - long lastEvenHour = _modelStartTimeHolder.getTime(); - long nextEvenHour = lastEvenHour + _millisPerHour; - long endOfPrecipForecastTime = _modelEndTimeHolder.getTime(); - - //potential evaporation - RegularTimeSeries evaporationTimeSeries = - _dataMgr.loadPotentialEvaporationTimeSeries(_basinId, - _modelStartTimeHolder.getTime(), - _modelEndTimeHolder.getTime()); - - _evaporationTimeSeriesHolder.setTimeSeries(evaporationTimeSeries); - - - //stage - if (_observedStageTimeSeriesHolder.getTimeSeries() == null) - { - IrregularTimeSeries obsStageTimeSeries = loadObservedStageTimeSeries(); - _observedStageTimeSeriesHolder.setTimeSeries(obsStageTimeSeries); - - } - - //stage - if (_priorForecastStageTimeSeriesHolder.getTimeSeries() == null) - { - IrregularTimeSeries priorForecastTimeSeries = loadPriorForecastTimeSeries(); - _priorForecastStageTimeSeriesHolder.setTimeSeries(priorForecastTimeSeries); - - } - - //used for some rainfall-runoff models - setInitialStageMeasurement(findInitialStageMeasurement()); - - - //runoff, both calculated now and prior runoff read from the database - if (_runoffTimeSeriesHolder.getTimeSeries() == null) - { - RegularTimeSeries runoffTimeSeries = new RegularTimeSeries( - nextEvenHour, endOfPrecipForecastTime, _intervalInHours, - MeasuringUnit.mm); - - _runoffTimeSeriesHolder.setTimeSeries(runoffTimeSeries); - - } - - // used in initRainfallRunoffModelData() now - // remove after 6/1/07 - //loadPriorRunoffTimeSeries(); - - } - - // ---------------------------------------------------------------------------- - - public void loadPriorRunoffTimeSeries(String message) - { - // System.out.println(message); - - loadPriorRunoffTimeSeries(); - } - - public void loadPriorRunoffTimeSeries() - { - // String header= "StreamModel.loadPriorRunoffTimeSeries() "; - -// load prior runoff - String typeSource = determineTypeSourceForPriorRunoffTimeSeries(); - - - // System.out.println(header + " typeSource = " + typeSource); - - _unitHydrograph = getBestUnitHydrograph(_unitHydrograph); - - - // _overAllLoadPriorRunoffTimeSeriesTimer.restart(); - // CodeTimer loadPriorRunoffTimer = new CodeTimer(); - // loadPriorRunoffTimer.start(); - - - /*RegularTimeSeries priorRunoffTimeSeries = - _dataMgr.loadPriorRunoffTimeSeries2(_locationId, - typeSource, - getModelStartTime(), - _unitHydrograph.getOrdinateCount()); - */ - - - RegularTimeSeries priorRunoffTimeSeries = - _dataMgr.getPriorRunoffTimeSeries(_locationId, - typeSource, - getModelStartTime(), - _unitHydrograph.getOrdinateCount()); - - - // loadPriorRunoffTimer.stop(header + "loadPriorRunoffTimeSeries() took: "); - // _overAllLoadPriorRunoffTimeSeriesTimer.stop(header + "loadPriorRunoffTimeSeries2() overall total time was: "); - // System.out.println(header + " - called for streamModel = " + this.toString()); - // System.out.println(header + " priorRunoffTimeSeries = " + priorRunoffTimeSeries); - - - _priorRunoffTimeSeriesHolder.setTimeSeries(priorRunoffTimeSeries); - } - - // ---------------------------------------------------------------------------- - - private String determineTypeSourceForPriorRunoffTimeSeries() - { - String header = "StreamModel.determineTypeSourceForPriorRunoffTimeSeries(): "; - String typeSource = null; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - if (getSacState() != null) - { - SSHPSource source = SSHPSource.findMatchingSSHPSourceBySacSmaSource(getSacState().getSource()); - - //System.out.println(header + " from findMatchingSSHPSourceBySacSmaSource(), answer = " + source); - - if (source != null) - { - typeSource = source.getTypeSource(); - } - } - else - { - System.out.println(header + " getSacState() was null "); - } - } - - - //System.out.println(header + " typeSource = " + typeSource); - - return typeSource; - } - - // ---------------------------------------------------------------------------- - - private void initAllTimeSeries() - { - // _tracer.trace(); - - setModelStartTime(getLatestHourTime()); - - initDbPrecipTimeSeries(); - - initAllNonPrecipTimeSeries(); - - return; - } -// ----------------------------------------------------------- - public TimeHolder getModelStartTimeHolder() - { - return _modelStartTimeHolder; - } - - // ---------------------------------------------------------------------------- - - public long getModelStartTime() - { - return _modelStartTimeHolder.getTime(); - } - - // ---------------------------------------------------------------------------- - - public void setFFHProductDescriptor(FFHDescriptor descriptor) - { - _ffhDescriptor = descriptor; - - } - // ---------------------------------------------------------------------------- - public void setSacSmaStateDescriptor(SacSmaStateDescriptor descriptor) - { - String header = "StreamModel.setSacSmaStateDescriptor(): "; - _sacSmaStateDescriptor = descriptor; - - if (_sacSmaStateDescriptor == null) - { - _sacSmaStateDescriptor = getDefaultSacSmaStateDescriptor(); - } - - setSacState(_sacSmaStateDescriptor.getState()); - - return; - } - // ---------------------------------------------------------------------------- - - public void setModelStartTime(long modelStartTime) - { - // String header = "StreamModel.setModelStartTime(): "; - // System.out.println(header + " inside here "); - - modelStartTime = TimeHelper.truncateTimeInMillisToNearestHour(modelStartTime, 1); - // trace(); - _modelStartTimeHolder.setTime(modelStartTime); - - //sets the model end time - setForecastLengthInHours(_forecastLengthInHours); - - return; - } - - // ----------------------------------------------------------- - public void setForecastLengthInHours(int lengthInHours) - { - // String header = "StreamModel.setForecastLengthInHours(): "; - // System.out.println(header + "lengthInHours = " + lengthInHours); - - if (lengthInHours > 0) - { - _forecastLengthInHours = lengthInHours; - long duration = ((long)(lengthInHours) * (long)MILLIS_PER_HOUR); - long newEndTime = _modelStartTimeHolder.getTime() + duration; - - setModelEndTime(newEndTime); - } - - return; - } - - - // ----------------------------------------------------------- - - public int getForecastLengthInHours() - { - return _forecastLengthInHours; - } - - // ----------------------------------------------------------- - - - public void setModelEndTime(long modelEndTime) - { - _modelEndTimeHolder.setTime(modelEndTime); - } - - // ----------------------------------------------------------- - public long getLatestHourTime() - { - return TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - } - - // ----------------------------------------------------------- - - public String getLocationId() - { - return _locationId; - - } - - public String getBasinId() - { - return _basinId; - } - - // ------------------------------------------------------------- - - public SigRiverLevels getSigRiverLevels() - { - if (_sigRiverLevels == null) - { - _sigRiverLevels = _dataMgr.getSigRiverLevels(_locationId); - } - - return _sigRiverLevels; - } - -// ----------------------------------------------------------- - private IrregularTimeSeries loadPriorForecastTimeSeries() - { - IrregularTimeSeries forecastStageTimeSeries = null; - - forecastStageTimeSeries = _dataMgr.loadFcstStageTimeSeries(getLocationId(), getPrimaryPe()); - - return forecastStageTimeSeries; - } - -// ----------------------------------------------------------- - - private RegularTimeSeries loadObservedPrecipTimeSeries(long startTime, long endTime) - { - RegularTimeSeries observedPrecipTimeSeries = null; - - - // CodeTimer timer = new CodeTimer(); - // timer.start(); - observedPrecipTimeSeries = _dataMgr.loadObsMapTimeSeriesFromDb(_basinId); - - - if (observedPrecipTimeSeries == null) - { - observedPrecipTimeSeries = new RegularTimeSeries(startTime, endTime, 1, MeasuringUnit.inches); - } - - // timer.stop("StreamModel.loadObservedPrecipTimeSeries() called DataMgr.loadObsMapTimeSeries() which took "); - - //System.out.println("StreamModel.loadObservedPrecipTimeSeries() = " + observedPrecipTimeSeries); - - return observedPrecipTimeSeries; - } - -// --------------------------------------------------------------------------------------- - - public void reloadObservedStageTimeSeries() - { - IrregularTimeSeries obsStageTimeSeries = loadObservedStageTimeSeries(true); - _observedStageTimeSeriesHolder.setTimeSeries(obsStageTimeSeries); - - return; - } - - private IrregularTimeSeries loadObservedStageTimeSeries() - { - return loadObservedStageTimeSeries(false); - } - private IrregularTimeSeries loadObservedStageTimeSeries(boolean forceCacheRefresh) - { - String header = "StreamModel.loadObservedStageTimeSeries() "; - CodeTimer timer = new CodeTimer(); - // timer.start(); - - // _overAllLoadObservedStageTimeSeriesTimer.restart(); - //TODO make sure that I can load new observed data sometimes, will need to add a cached refresh feature at some point, maybe - IrregularTimeSeries observedStageTimeSeries = _dataMgr.getCachedObservedStageTimeSeriesFromStageOrDischarge(_locationId, forceCacheRefresh); - - setLastObservedTimeForAdjustment(observedStageTimeSeries.getEndTime()); - - // _overAllLoadObservedStageTimeSeriesTimer.stop(header + " overall took: "); - // timer.stop(header + "this time took:"); - - return observedStageTimeSeries; - } - - // ----------------------------------------------------------- - - public DataMgr getDataMgr() - { - return _dataMgr; - } - -// ----------------------------------------------------------- - public RegularTimeSeries getDischargeTimeSeries() - { - RegularTimeSeries fcstStageTimeSeries = _forecastStageTimeSeriesHolder.getTimeSeries(); - RegularTimeSeries timeSeries = _ratingCurve.getDischargeRegularTimeSeries(fcstStageTimeSeries); - - return timeSeries; - - } - -// ----------------------------------------------------------- - - public RegularTimeSeriesHolder getForecastStageTimeSeriesHolder() - { - return _forecastStageTimeSeriesHolder; - } - - public IrregularTimeSeriesHolder getPriorForecastStageTimeSeriesHolder() - { - return _priorForecastStageTimeSeriesHolder; - } - - // ----------------------------------------------------------- - public RegularTimeSeriesHolder getSimulationStageTimeSeriesHolder() - { - return _simulatedStageTimeSeriesHolder; - } -// ----------------------------------------------------------- - - /* - public RegularTimeSeriesHolder getObservedPrecipTimeSeriesHolder() - { - return _observedPrecipTimeSeriesHolder; - } - */ -// ----------------------------------------------------------- - public IrregularTimeSeriesHolder getObservedStageTimeSeriesHolder() - { - return _observedStageTimeSeriesHolder; - } - -// ----------------------------------------------------------- - public RegularTimeSeriesHolder getPrecipTimeSeriesHolder() - { - return _precipTimeSeriesHolder; - } -// ----------------------------------------------------------- - - public void setPrecipTimeSeriesHolder(RegularTimeSeriesHolder precipTimeSeriesHolder) - { - _precipTimeSeriesHolder = precipTimeSeriesHolder; - } -// ----------------------------------------------------------- - - public RegularTimeSeriesHolder getEvaporationTimeSeriesHolder() - { - return _evaporationTimeSeriesHolder; - } - -// ----------------------------------------------------------- - - public RegularTimeSeriesHolder getRunoffTimeSeriesHolder() - { - return _runoffTimeSeriesHolder; - } - - public RegularTimeSeriesHolder getPriorRunoffTimeSeriesHolder() - { - return _priorRunoffTimeSeriesHolder; - } - -// ----------------------------------------------------------- - public String getPrimaryPe() - { - - if (_primaryPe == null) - { - _primaryPe = _dataMgr.loadPrimaryPe(_locationId); - - } - - return _primaryPe; - } -// ----------------------------------------------------------- -// load the baseflow - - public Measurement findBaseflowMeasurementOld() - { - - String header = "StreamModel.getBaseflowMeasurementOld():"; - - long modelRunStartTime = _modelStartTimeHolder.getTime(); - IrregularTimeSeries observedStageTs = _observedStageTimeSeriesHolder.getTimeSeries(); - - AbsTimeMeasurement latestMeasurement = null; - Measurement baseflowMeasurement = null; - - boolean done = false; - - //find the latestHeightValue that is not beyond the modelRunStartTime - for (int i = 0; i < observedStageTs.getMeasurementCount() && (!done) ; i++) - { - AbsTimeMeasurement m = (AbsTimeMeasurement) - observedStageTs.getAbsTimeMeasurementByIndex(i); - - long measurementTime = m.getTime(); - - if (measurementTime < modelRunStartTime) - { - latestMeasurement = m; - } - else if(measurementTime > modelRunStartTime) - { - done = true; - } - - } //for i - - Measurement heightMeasurement = latestMeasurement; - - if ( heightMeasurement != null) - { - double heightValue = heightMeasurement.getValue(); - - if (_ratingCurve == null) - { - _ratingCurve = getRatingCurve(); - } - - if (_ratingCurve != null) - { - double baseflowValue = _ratingCurve.getDischargeFromStage(heightValue); - - //System.out.println(header + " heightValue = " + heightValue + - // " baseflowValue = " + baseflowValue ); - - // System.out.println(header + "stage measurement = " + latestMeasurement); - - baseflowMeasurement = new Measurement(baseflowValue, MeasuringUnit.cfs); - } - } - - // timer.stop(header + "baseflow retrieval took" ); - - if (baseflowMeasurement == null) - { - baseflowMeasurement = new Measurement(0.0, MeasuringUnit.cfs); - } - - return baseflowMeasurement; - - } //end getBaseflowMeasurement() - -// ----------------------------------------------------------- -// load the initial stage measurement from the time series - -public Measurement findInitialStageMeasurement() -{ - - String header = "StreamModel.findInitialStageMeasurement():"; - - long modelRunStartTime = _modelStartTimeHolder.getTime(); - IrregularTimeSeries observedStageTs = _observedStageTimeSeriesHolder.getTimeSeries(); - - AbsTimeMeasurement latestMeasurement = null; - Measurement initialStageMeasurement = null; - - boolean done = false; - - //find the latestHeightValue that is not beyond the modelRunStartTime - for (int i = 0; i < observedStageTs.getMeasurementCount() && (!done) ; i++) - { - AbsTimeMeasurement m = (AbsTimeMeasurement) - observedStageTs.getAbsTimeMeasurementByIndex(i); - - long measurementTime = m.getTime(); - - if (measurementTime <= modelRunStartTime) - { - latestMeasurement = m; - } - else if(measurementTime > modelRunStartTime) - { - done = true; - } - - } //for i - - initialStageMeasurement = latestMeasurement; - - if (initialStageMeasurement == null) - { - initialStageMeasurement = new Measurement(0.0, _stageUnit); - } - - return initialStageMeasurement; - -} //end findInitialStageMeasurement() - -//----------------------------------------------------------- - public void setBaseflowMeasurementByStageMeasurementOld(Measurement stageMeasurement) - { - double stageValue = 0.0; - double baseflowValue = 0.0; - - if (stageMeasurement != null) - { - stageValue = stageMeasurement.getValue(_stageUnit); - } - - if (_ratingCurve != null) - { - baseflowValue = _ratingCurve.getDischargeFromStage(stageValue); - } - - Measurement baseflowMeasurement = new Measurement(baseflowValue, _dischargeUnit); - _initialStageMeasurementHolder.setMeasurement(baseflowMeasurement); - } -// ----------------------------------------------------------- - public void setInitialStageMeasurement(Measurement stageMeasurement) - { - - if (stageMeasurement == null) - { - stageMeasurement = new Measurement(0.0, _stageUnit); - } - - _initialStageMeasurementHolder.setMeasurement(stageMeasurement); - } -// ----------------------------------------------------------- - public void setBaseflowMeasurementOld(Measurement baseflowMeasurement) - { - _initialStageMeasurementHolder.setMeasurement(baseflowMeasurement); - } -// ----------------------------------------------------------- - - public void setFfhValue(double ffhValue) - { - String header = "StreamModel.setFfhValue(): "; - System.out.println(header + " ffhValue = " + ffhValue); - _ffhValue = ffhValue; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) - { - KcApiRainfallRunoffModel model = (KcApiRainfallRunoffModel) _rainfallRunoffModel; - model.setFfhValue(_ffhValue); - } - } -// ----------------------------------------------------------- - - public RegularTimeSeries runModel() - { - final String header = "StreamModel.runModel() "; - - //make sure that model states start out fresh - refreshModelData(); - - _modelRunCount++; - - Measurement initialStageMeasurement = _initialStageMeasurementHolder.getMeasurement(); - - if (initialStageMeasurement == null) - { - initialStageMeasurement = findInitialStageMeasurement(); - - _initialStageMeasurementHolder.setMeasurement( initialStageMeasurement); - } - - - - // do the actual calculations - RegularTimeSeries forecastStageTimeSeries = _rainfallToStageModel.calculateStageTimeSeries( - _modelStartTimeHolder.getTime(), - _modelEndTimeHolder.getTime(), - _precipTimeSeriesHolder.getTimeSeries(), - _runoffTimeSeriesHolder); - - forecastStageTimeSeries = forecastStageTimeSeries.getSubTimeSeries( - _modelStartTimeHolder.getTime(), - _modelEndTimeHolder.getTime()); - - - forecastStageTimeSeries.setName("Forecast#" + _modelRunCount); - - _forecastStageTimeSeriesHolder.setTimeSeries(forecastStageTimeSeries); - - - - //trim the simulated dischargeTimeSeries - RegularTimeSeries simulatedDischargeTimeSeries = _simulatedDischargeTimeSeriesHolder.getTimeSeries(); - simulatedDischargeTimeSeries = simulatedDischargeTimeSeries.getSubTimeSeries( _modelStartTimeHolder.getTime(), - _modelEndTimeHolder.getTime()); - _simulatedDischargeTimeSeriesHolder.setTimeSeries(simulatedDischargeTimeSeries); - - - //convert simulated to stage and put in holder - RegularTimeSeries simulatedStageTimeSeries = _ratingCurve.getStageRegularTimeSeries(simulatedDischargeTimeSeries); - _simulatedStageTimeSeriesHolder.setTimeSeries(simulatedStageTimeSeries); - - - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - SacSmaRainfallRunoffModel sacModel = - (SacSmaRainfallRunoffModel) _rainfallRunoffModel; - - setFinalSacState(sacModel.getState()); - } - - //printAllTimeSeries(); - - - - return forecastStageTimeSeries; - - - } //end runModel - -// ----------------------------------------------------------- - public void printAllTimeSeries() - { - String header = "StreamModel.printAllTimeSeries(): "; - - System.out.println(header + "-----------------------------------------------------------------------------"); - - System.out.println(header + " For stream model: " + this.toString()); - - System.out.println(header + "Prior Runoff Time series = " + _priorRunoffTimeSeriesHolder.getTimeSeries()); - System.out.println(header + "Precip = " + _precipTimeSeriesHolder.getTimeSeries()); - System.out.println(header + "simulated stage= " + _simulatedStageTimeSeriesHolder.getTimeSeries()); - System.out.println(header + "forecast stage = " + _forecastStageTimeSeriesHolder.getTimeSeries()); - - System.out.println(header + "-----------------------------------------------------------------------------"); - - } - -// ----------------------------------------------------------- - public RatingCurve getRatingCurve() - { - - if (_ratingCurve == null) - { - _ratingCurve = _dataMgr.getRatingCurve(_locationId); - } - - return _ratingCurve; - } - -// ----------------------------------------------------------- - - public void setThresholdRunoff(double thresholdRunoff) - { - _thresholdRunoff = thresholdRunoff; - - if (_rainfallRunoffModelType == RainfallRunoffModelType.API_MKC) - { - KcApiRainfallRunoffModel model = (KcApiRainfallRunoffModel) _rainfallRunoffModel; - model.setThresholdRunoff(_thresholdRunoff); - } - } - - // ----------------------------------------------------------- - public void saveModelStates(Logger logger) - { - saveModelStates("LOCAL", logger); - } - - // ----------------------------------------------------------- - public void saveModelStates(String source, Logger logger) - { - if (_rainfallRunoffModelType == RainfallRunoffModelType.SAC_SMA) - { - SacSmaRainfallRunoffModel model = - (SacSmaRainfallRunoffModel) _rainfallRunoffModel; - - - SacSmaState state = model.getState(); - - - state.setSource(source); - logger.log("StreamModel.saveModelStates(): saved State = " + state); - - - _dataMgr.saveSacState(state); - - } - } -// ----------------------------------------------------------- - public void saveRunoffTimeSeries(Logger logger) - { - RegularTimeSeries runoffTimeSeries = getRunoffTimeSeriesHolder().getTimeSeries(); - RegularTimeSeries priorRunoffTimeSeries = getPriorRunoffTimeSeriesHolder().getTimeSeries(); - - RegularTimeSeries allRunoffTs = null; - - if ((runoffTimeSeries != null) && - (priorRunoffTimeSeries != null)) - { - allRunoffTs = RegularTimeSeries.concatenate(runoffTimeSeries, - priorRunoffTimeSeries); - } - else if (runoffTimeSeries != null) - { - allRunoffTs = runoffTimeSeries; - } - else if (priorRunoffTimeSeries != null) - { - allRunoffTs = priorRunoffTimeSeries; - } - - - logger.log("StreamModel.saveRunoffTimeSeries(): saved runoff time series = " + allRunoffTs); - - - - _dataMgr.saveRunoffTimeSeries(_locationId, allRunoffTs); - - - } - -// ----------------------------------------------------------- - - public void saveInitialSacSmaConditions(SSHPSource source) - { - - - RegularTimeSeriesHolder priorRunoffTimeSeriesHolder = getPriorRunoffTimeSeriesHolder(); - - - SacSmaState sacSmaState = getSacState(); - - long basisTime = sacSmaState.getBasisTime(); - - - if (priorRunoffTimeSeriesHolder.getTimeSeries() != null) - { - _dataMgr.saveRunoffTimeSeries(_locationId, source.getTypeSource(), basisTime, - source.getProductId(), priorRunoffTimeSeriesHolder.getTimeSeries()); - } - - _dataMgr.saveSacState(sacSmaState, source.getSacSmaSource()); - - try - { - _dataMgr.deleteLaterSacSmaVarStatesAndRunoff(getLocationId(), getBasinId(), sacSmaState.getValidTime()); - } - catch (SQLException e) - { - - } - - } - -// ----------------------------------------------------------- - public void savePrecipTimeSeriesToFile(String filePath) - { - RegularTimeSeries precipTimeSeries = getPrecipTimeSeriesHolder().getTimeSeries(); - - if (precipTimeSeries != null) - { - _dataMgr.saveMapTimeSeriesToFile(precipTimeSeries, filePath); - } - - return; - } -// ----------------------------------------------------------- - - /** - * @param isBlendingOn The isBlendingOn to set. - */ - public void setAdjustmentOn(boolean isAdjustmentOn) - { - - _isAdjustmentOn = isAdjustmentOn; - - - //Note: params refers to the same object, not a copy - ForecastAdjusterParams params = _forecastAdjuster.getParams(); - params.setShouldDoAdjustment(_isAdjustmentOn); - - // System.out.println("StreamModel.setAdjustmentOn(): new value = " + _isAdjustmentOn); - } - -// ----------------------------------------------------------- - public void setLastObservedTimeForAdjustment(long lastTime) - { - // String header = "StreamModel.setLastObservedTimeForAdjustment():"; - - // System.out.println(header + "lastTime = " + DbTimeHelper.getDateTimeStringFromLongTime(lastTime)); - if (_forecastAdjuster != null) - { - _forecastAdjuster.setLastObservedTimeToUseAsInput(lastTime); - } - } -// ----------------------------------------------------------- - public int getBlendingHours() - { - int hoursToAdjust = -1; - final String header = "StreamModel.getBlendingHours():"; - - if (_forecastAdjuster != null) - { - hoursToAdjust = _forecastAdjuster.getParams().getBlendingHours(); - } - - return hoursToAdjust; - } -// ----------------------------------------------------------- - public int getMaxBlendingHours() - { - return MAX_BLENDING_HOURS; - } -// ----------------------------------------------------------- - public void setAdjustmentHours(int hoursToAdjust) - { - //final String header = "StreamModel.setAdjustmentHours():"; - - if (_forecastAdjuster != null) - { - _forecastAdjuster.getParams().setBlendingHours(hoursToAdjust); - //System.out.println(header + "value = " + hoursToAdjust); - } - - return; - } - -// ----------------------------------------------------------- - - /** - * @return Returns the isBlendingOn. - */ - public boolean isAdjustmentOn() - { - return _isAdjustmentOn; - } - - /** - * @return Returns the sacParams. - */ - public SacSmaParameters getSacParams() - { - return _sacParams; - } - - - /** - * @return Returns the sacState. - */ - public SacSmaState getSacState() - { - // String header = "StreamModel.getSacState(): "; - // System.out.println(header + "retrieved state is :" + _sacState); - return _sacState; - } - - private void setSacState(SacSmaState state) - { - // String header = "StreamModel.setSacState(): "; - - // System.out.println(header + "old state was :" + _sacState); - - _sacState = state; - - // System.out.println(header + "new state was :" + state); - } - - /** - * @param maxForecastLengthInHours The maxForecastLengthInHours to set. - */ - public void setMaxForecastLengthInHours(int maxForecastLengthInHours) - { - _maxForecastLengthInHours = maxForecastLengthInHours; - } - - /** - * @return Returns the maxForecastLengthInHours. - */ - public int getMaxForecastLengthInHours() - { - return _maxForecastLengthInHours; - } - - public void setIsAlternateStreamModel(boolean isAlternateSimulation) - { - _isAlternateStreamModel = isAlternateSimulation; - } - - public boolean isAlternateStreamModel() - { - return _isAlternateStreamModel; - } - - public String toString() - { - - StringBuffer outBuffer = new StringBuffer(); - - - if (isAlternateStreamModel()) - { - outBuffer.append("Alternate StreamModel:"); - } - else - { - outBuffer.append("Primary StreamModel:"); - } - - //Rainfall-Runoff Model Type - outBuffer.append(_rainfallRunoffModelType.toString() + ": "); - - if (_rainfallRunoffModelType.equals(RainfallRunoffModelType.SAC_SMA)) - { - if (getSacState() != null) - { - outBuffer.append("\n State = " + getSacState().toString() + "\n"); - } - } - else - { - String stateString = null; - if (_ffhDescriptor != null) - { - stateString = _ffhDescriptor.toString(); - - } - outBuffer.append("\n State = " + stateString); - } - - - - - return outBuffer.toString(); - } - - private void setNeedStateReload(boolean needStateReload) - { - _needStateReload = needStateReload; - } - - private boolean needStateReload() - { - return _needStateReload; - } - - private void setFinalSacState(SacSmaState finalSacState) - { - _finalSacState = finalSacState; - } - - public SacSmaState getFinalSacState() - { - return _finalSacState; - } - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/GuiHelper.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/GuiHelper.java deleted file mode 100644 index 2a442a0b36..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/GuiHelper.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Created on Jul 23, 2004 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.awt.Color; -import java.awt.Dimension; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; - -/** - * @author GobsC - * - * - */ -public class GuiHelper -{ - private static final Color _comboBoxColor = new Color(194, 141,237); - private static final Color _buttonColor = new Color(158,244,252); - - private GuiHelper() - { - //does nothing. No one is allowed to call this. - } - - public static JComboBox getJComboBox(String[] contentArray) - { - String header = "AnalysisWindow.getJButton(): "; - - - JComboBox comboBox = new JComboBox(contentArray); - - // Color color = new Color(97, 166, 96); - - // comboBox.setBackground(_comboBoxColor); - - return comboBox; - - } - // ------------------------------------------------------------ - public static JComboBox getJComboBox() - { - String header = "AnalysisWindow.getJButton(): "; - - - JComboBox comboBox = new JComboBox(); - - // Color color = new Color(97, 166, 96); - - // comboBox.setBackground(_comboBoxColor); - - return comboBox; - - } - // ------------------------------------------------------------ - - - public static JButton getJButton(String text) - { - String header = "AnalysisWindow.getJButton(): "; - - int width = 150; - int height = 35; - - JButton button = new JButton(text); - - //button.setFont(_buttonFont); - - // Color color = new Color(158, 244, 252); - - // button.setBackground(_buttonColor); - - button.setSize(new Dimension(width, height)); - - return button; - - } - - // ------------------------------------------------------------ - - public static JButton getJButton(ImageIcon imageIcon) - { - JButton button = new JButton(imageIcon); - - //button.setBackground(Color.GRAY); - - return button; - - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PositionedText.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PositionedText.java deleted file mode 100644 index e5bbfa04a4..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PositionedText.java +++ /dev/null @@ -1,42 +0,0 @@ -package ohd.hseb.sshp.gui; - -import java.awt.Point; - -public class PositionedText -{ - private StringBuffer _stringBuffer = null; - private Point _position; - - public PositionedText() - { - _stringBuffer = new StringBuffer(); - _position = new Point(0, 0); - } - - public void clear() - { - _stringBuffer.delete(0, _stringBuffer.length()); - } - - public void setStringBuffer(StringBuffer stringBuffer) - { - _stringBuffer = stringBuffer; - } - - public StringBuffer getStringBuffer() - { - return _stringBuffer; - } - - public void setPosition(Point position) - { - _position = position; - } - - public Point getPosition() - { - return _position; - } - - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PrecipPainter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PrecipPainter.java deleted file mode 100644 index 35276eca8e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PrecipPainter.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.*; -import java.text.DecimalFormat; -import java.text.NumberFormat; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of precipitation data on a PaintableCanvas - */ -public class PrecipPainter implements TsCanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _barColor = null; - private Color _outlineColor = null; - - private RegularTimeSeriesHolder _precipTimeSeriesHolder = null; - private TsPaintableCanvas _canvas = null; - - private boolean _shouldDrawBars = true; - - private boolean _shouldPaint = true; - - private boolean _showPrecipAmounts = false; - - private static final Font _labelFont = new Font("Helvetica",Font.PLAIN,9); - - private static final double VERY_SMALL_NUMBER = 0.0000000000000001; - - private NumberFormat _numberFormat = null; - - // --------------------------------------------------------- - public PrecipPainter(Color barColor, - Color outlineColor, - RegularTimeSeriesHolder timeSeriesHolder, - boolean showPrecipAmounts, - TsPaintableCanvas canvas) - { - - _precipTimeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _barColor = barColor; - _outlineColor = outlineColor; - - setShowPrecipAmounts(showPrecipAmounts); - - _numberFormat = new DecimalFormat("#.0#"); - } - -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - - //System.out.println("PrecipPainter.paint(): precip ts = " + getTimeSeries()); - if (_shouldPaint) - { - drawDataBars(g); - } - } - -// ---------------------------------------------------- - private void drawDataBars( Graphics g ) - { - String header = "PrecipPainter.drawDataBars(): "; - // System.out.println(header + "-------------------------"); - int x1; - int y1; - int x2; - int y2; - g.setColor(_barColor); - - if (_showPrecipAmounts) - { - g.setFont( _labelFont ); - } - - //draw each data bar - for ( int i = 0; (getTimeSeries() != null) && - ( i < getTimeSeries().getMeasurementCount()); i++) - { - - Measurement measurement = (Measurement) - getTimeSeries().getMeasurementByIndex(i); - - Measurement convertedMeasurement = Measurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double value = convertedMeasurement.getValue(); - - if (value >= 0.0) - - { - - long endTime = getTimeSeries().getMeasurementTimeByIndex(i); - long startTime = endTime - MILLIS_PER_HOUR; - - /* - if (!_shouldDrawBars) - { - String timeString = CanvasHelper.getDateTimeStringFromLongTime(endTime); - System.out.println("Time = " + timeString + " value = " + value); - } - */ - - DataPoint dp1 = new DataPoint(startTime, 0); - DataPoint dp2 = new DataPoint(endTime, value); - - - if ( (getViewport().isViewable(dp1)) && - (getViewport().isViewable(dp2)) - ) - { - - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - - int barHeight = Math.abs(p1.y - p2.y); - int barWidth = Math.abs(p1.x - p2.x); - - if (_shouldDrawBars) - { - g.setColor(_barColor); - g.fillRect(p1.x, p2.y, barWidth, barHeight); - - g.setColor(_outlineColor); - g.drawRect(p1.x, p2.y, barWidth, barHeight); - - if ((_showPrecipAmounts) && (value > 0.0) ) - { - g.setColor(_outlineColor); - - g.drawString(_numberFormat.format(value), p1.x, p2.y -2); - } - } - else //draw Lines - { - g.setColor(_barColor); - g.drawLine(p1.x, p2.y, p1.x + barWidth, p2.y); - - } - } - - }//end if value > 0.0 - - } // for loop - - - } // end of drawDataBars method -// ---------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - private RegularTimeSeries getTimeSeries() - { - return _precipTimeSeriesHolder.getTimeSeries(); - } - -//--------------------------------------------------------- - public Measurement getMinMeasurement() - { - //force this method to return 0.0 always, since - //I always want 0 shown, regardless of the actual measurements - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - /* - - Measurement minMeasurement = null; - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - if (minMeasurement != null) - { - minMeasurement = new Measurement(minMeasurement); - } - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - - */ - return minMeasurement; - } -//---------------------------------------------------- - - public Measurement getMaxMeasurement() - { - - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - - String header = "PrecipPainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - if (maxMeasurement != null) - { - maxMeasurement = new Measurement(maxMeasurement); - - if ( maxMeasurement.getValue(_canvas.getDisplayedMeasuringUnit()) < 1.0) - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - //System.out.println(header + " time series was null, setting max measurement to 1.0 "); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - - - //System.out.println(header + " max measurement is " + maxMeasurement); - - return maxMeasurement; - } - -// ---------------------------------------------------- - - public void setShouldDrawBars(boolean shouldDrawBars) - { - _shouldDrawBars = shouldDrawBars; - } - -// ---------------------------------------------------- - - - public boolean shouldDrawBars() - { - return _shouldDrawBars; - } - - public void setShowPrecipAmounts(boolean showPrecipAmounts) - { - _showPrecipAmounts = showPrecipAmounts; - } - - public boolean isShowPrecipAmounts() - { - return _showPrecipAmounts; - } - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PrecipTotalTextPainter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PrecipTotalTextPainter.java deleted file mode 100644 index eb0eb46267..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/PrecipTotalTextPainter.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.*; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.HashMap; -import java.util.Map; - -/** - * @author GobsC - * - * This class extends CanvasPainter and encapsulates the - * drawing of precipitation total textual data on a PaintableCanvas - */ -public class PrecipTotalTextPainter implements CanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - private static final Font _labelFont = new Font("Helvetica",Font.PLAIN,12); - private static final int Y_OFFSET = 2; - private static final double VERY_SMALL_NUMBER = 0.0000000000000001; - - private RegularTimeSeriesHolder _precipTimeSeriesHolder = null; - private TsPaintableCanvas _canvas = null; - - private boolean _shouldPaint = true; - private boolean _showPrecipAmounts = false; - - private NumberFormat _numberFormat = null; - private Color _textColor = null; - - private RegularTimeSeries _sixHourTimeSeries = null; - private RegularTimeSeries _twelveHourTimeSeries = null; - private RegularTimeSeries _twentyFourHourTimeSeries = null; - - private Map _timeToPositionedTextMap = new HashMap(); - // --------------------------------------------------------- - public PrecipTotalTextPainter(Color textColor, - RegularTimeSeriesHolder timeSeriesHolder, - boolean shouldPaint, - TsPaintableCanvas canvas) - { - - _precipTimeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _textColor = textColor; - setShouldPaint(shouldPaint); - - _numberFormat = new DecimalFormat("#.0#"); - } - -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - //System.out.println("PrecipTotalTextPainter.paint(): precip ts = " + getTimeSeries()); - - if (_shouldPaint) - { - _timeToPositionedTextMap.clear(); - - - positionText(g, 6, 0, true); - // positionText(g, 12, 0, false); - - positionText(g, 24, 0, false); - positionText(g, 24, 6, false); - positionText(g, 24, 12, false); - positionText(g, 24, 18, false); - - drawText(g); - } - - } -// ---------------------------------------------------- - public void drawText(Graphics g) - { - FontHelper fontHelper = new FontHelper(_labelFont); - - RegularTimeSeries timeSeries = _precipTimeSeriesHolder.getTimeSeries(); - long startTime = timeSeries.getStartTime(); - long endTime = timeSeries.getEndTime(); - - for ( long t = startTime; (timeSeries != null) && - ( t <= endTime ); t+= MILLIS_PER_HOUR) - { - PositionedText positionedText = - getPositionedText(t); - - if (positionedText != null) - { - String text = positionedText.getStringBuffer().toString(); - int x = positionedText.getPosition().x; - int y = positionedText.getPosition().y; - - - int width = fontHelper.getWidth(g, text); - - x -= width/2; - - g.drawString(text, x, y ); - - } - } - } - -// ---------------------------------------------------- - - private void positionText( Graphics g, - int intervalInHours, - int shiftInHours, - boolean isFirst) - { - String header = "PrecipTotalTextPainter.positionText(): "; - - int y = _canvas.getHeight() - Y_OFFSET; - - g.setFont( _labelFont ); - - RegularTimeSeries precipTimeSeries = _precipTimeSeriesHolder.getTimeSeries(); - - RegularTimeSeries timeSeries = - TimeSeriesTotaller.getRegularTimeSeries(intervalInHours, - shiftInHours, - precipTimeSeries); - - - // System.out.println(header + "--------------------\n" + timeSeries.toString()); - // System.out.println(header + "-------end of time series-------------n" ); - - StringBuffer stringBuffer = new StringBuffer(); - //draw each data bar - for ( int i = 0; (timeSeries != null) && - ( i < timeSeries.getMeasurementCount()); i++) - { - - AbsTimeMeasurement measurement = (AbsTimeMeasurement) - timeSeries.getAbsTimeMeasurementByIndex(i); - - AbsTimeMeasurement convertedMeasurement = AbsTimeMeasurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double value = convertedMeasurement.getValue(); - - long endTime = convertedMeasurement.getTime(); - - // System.out.println(header + "value = " + value + " endTime = " + getTimeString(endTime)); - - DataPoint dp1 = new DataPoint(endTime, 0); - Point p1 = getViewport().getScreenPoint(dp1); - - g.setColor(_textColor); - - PositionedText positionedText = getPositionedText(endTime, true); - if (isFirst) - { - positionedText.clear(); - } - else - { - positionedText.getStringBuffer().append(" / "); - } - positionedText.getStringBuffer().append(_numberFormat.format(value)); - positionedText.setPosition(new Point(p1.x, y)); - - } // for loop - - - } // end of drawDataBars method - - // -------------------------------------------------------------------------------- - - private static String getTimeString(long time) - { - return DbTimeHelper.getDateTimeStringFromLongTime(time); - } - - // -------------------------------------------------------------------------------- - - private PositionedText getPositionedText(long time, boolean createNewOne) - { - // String header = "PrecipTotalTextPainter.getPositionedText(): "; - - PositionedText text = null; - text = (PositionedText) _timeToPositionedTextMap.get(new Long(time)); - if ((text == null) && (createNewOne)) - { - text = new PositionedText(); - _timeToPositionedTextMap.put(new Long(time), text); - // System.out.println(header + getTimeString(time)); - } - - return text; - } - -// ---------------------------------------------------- - - private PositionedText getPositionedText(long time) - { - return getPositionedText(time, false); - } -// ---------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - private RegularTimeSeries getTimeSeries() - { - return _precipTimeSeriesHolder.getTimeSeries(); - } - - public void setShowPrecipAmounts(boolean showPrecipAmounts) - { - _showPrecipAmounts = showPrecipAmounts; - } - - public boolean isShowPrecipAmounts() - { - return _showPrecipAmounts; - } - -//--------------------------------------------------------- - -} //end of PrecipPainter diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/SettingPanel.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/SettingPanel.java deleted file mode 100644 index 52933f7867..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/SettingPanel.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Created on Nov 12, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - - - -import javax.swing.*; - -/** - * @author GobsC - * - * This group of controls is used for an idiom in which - * a text field shows the value and allows the user to change it, - * a label tells the user what the value represents, - * and a buttom allows the user to reset the value - * to one retrieved from the database value. - */ -public class SettingPanel -{ - - private JLabel _label = null; - private JTextField _textField = null; - private JButton _button = null; - - - public SettingPanel(String labelString, int textFieldLength, String buttonString, String toolTipString) - { - initGui(labelString, textFieldLength, buttonString, toolTipString); - - } //end SettingPanel() - - // ----------------------------------------------------------------------------- - private void initGui(String labelString, int textFieldLength, String buttonString, String toolTipString) - { - - - - _label = new JLabel(labelString); - _textField = new JTextField(textFieldLength); - //_textField.setColumns(textFieldLength); - - _button = GuiHelper.getJButton(buttonString); - _button.setToolTipText(toolTipString); - - return; - - } //end initGui(); - - // --------------------------------------------------------- - - - // --------------------------------------------------------- - - - public JLabel getLabel() - { - return _label; - } - - // --------------------------------------------------------- - - public JTextField getTextField() - { - return _textField; - } - - // --------------------------------------------------------- - - public JButton getButton() - { - return _button; - } - // --------------------------------------------------------- - -} //end class SettingPanel diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/SigStageLinePainter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/SigStageLinePainter.java deleted file mode 100644 index 87fce2eaec..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/SigStageLinePainter.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.Viewport; -import ohd.hseb.util.gui.drawing.TsCanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -import java.awt.Graphics; -import java.awt.*; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of significant stage line data on a TsPaintableCanvas - */ -public class SigStageLinePainter implements TsCanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private Measurement _sigStageMeasurement = null; - - private boolean _shouldPaint = false; -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - - - // --------------------------------------------------------- - public SigStageLinePainter(Color lineColor, - Measurement sigStageMeasurement, - TsPaintableCanvas canvas) - { - - _lineColor = lineColor; - _canvas = canvas; - - _sigStageMeasurement = Measurement.getConvertedCopy(sigStageMeasurement, - _canvas.getDisplayedMeasuringUnit()); - - - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - MeasuringUnit unit = _canvas.getDisplayedMeasuringUnit(); - // convert again just in case the _canvas has had its units changed, - // even though this feature is not available at this time - if (_sigStageMeasurement.getUnit() != unit) - { - _sigStageMeasurement = - Measurement.getConvertedCopy(_sigStageMeasurement, unit); - - } - double value = _sigStageMeasurement.getValue(); - long minTime = (long) _canvas.getViewport().getMinDataPoint().getX(); - long maxTime = (long) _canvas.getViewport().getMaxDataPoint().getX(); - - DataPoint dp1 = new DataPoint(minTime, value); - DataPoint dp2 = new DataPoint(maxTime, value); - - if (getViewport().isViewable(dp1)) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - - } - - //--------------------------------------------------------------- - - - //--------------------------------------------------------------- - - - public Measurement getMaxMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _sigStageMeasurement; - } - - return measurement; - } - - - public Measurement getMinMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _sigStageMeasurement; - } - - return measurement; - } - -//---------------------------------------------------- - - -} //end of SigStageLinePainter diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/StagePainter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/StagePainter.java deleted file mode 100644 index 7617b783a5..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/StagePainter.java +++ /dev/null @@ -1,536 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.*; - - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of precipitation data on a TsPaintableCanvas - */ -public class StagePainter implements TsCanvasPainter -{ - - private static double MISSING_VALUE = -9999.0; - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _pointColor = null; - - private IrregularTimeSeriesHolder _timeSeriesHolder = null; - private RegularTimeSeriesHolder _regularTimeSeriesHolder = null; - - private TsPaintableCanvas _canvas = null; - - private boolean _isRegular = false; // distinguishes between the kind of time series - - private boolean _drawLinesBetweenPoints = false; - private boolean _shouldPaint = true; - - private String _pointString = null; - private Point _shiftAmount = new Point(0,0); - - private Font _pointLabelFont = new Font("Helvetica",Font.PLAIN,10); - private FontHelper _pointLabelFontHelper = new FontHelper(_pointLabelFont); - - // --------------------------------------------------------- - public StagePainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder, - TsPaintableCanvas canvas, - boolean drawLinesBetweenPoints) - { - - _isRegular = true; - - _regularTimeSeriesHolder = regularTimeSeriesHolder; - _canvas = canvas; - - _pointColor = pointColor; - - _drawLinesBetweenPoints = drawLinesBetweenPoints; - - } - // --------------------------------------------------------- - public StagePainter(Color pointColor, - IrregularTimeSeriesHolder timeSeriesHolder, - TsPaintableCanvas canvas, - boolean drawLinesBetweenPoints - ) - { - - _isRegular = false; - - _timeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _pointColor = pointColor; - - _drawLinesBetweenPoints = drawLinesBetweenPoints; - } - -// --------------------------------------------------------- - public StagePainter(Color pointColor, - IrregularTimeSeriesHolder timeSeriesHolder, - TsPaintableCanvas canvas) - { - - _isRegular = false; - - _timeSeriesHolder = timeSeriesHolder; - _canvas = canvas; - - _pointColor = pointColor; - } - - // --------------------------------------------------------- - public StagePainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder, - TsPaintableCanvas canvas) - { - this (pointColor, regularTimeSeriesHolder, canvas, false); - - } -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - // String header = "StagePainter.paint(): "; - - if (_shouldPaint) - { - - Graphics2D g2d = (Graphics2D) g; - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - drawDataPoints(g); - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_OFF); - - } - } - -// ---------------------------------------------------------- - private void drawDataPoints( Graphics g ) - { - String header = "StagePainter.drawDataPoints(): "; - g.setFont(_pointLabelFont); - - if (_isRegular) - { - //System.out.println(header + " painter's regular time series = " + _regularTimeSeriesHolder.getTimeSeries()); - - drawRegularDataPoints(g); - } - else - { - drawIrregularDataPoints(g); - } - } -// ---------------------------------------------------------- - private void drawRegularDataPoints( Graphics g ) - { - String header = "StagePainter.drawRegularDataPoints():"; - - - if (getRegularTimeSeries() == null ) - { - //System.out.println(header + " time series is null"); - return; - } - - long startTime = getRegularTimeSeries().getStartTime(); - long endTime = getRegularTimeSeries().getEndTime(); - - - g.setColor(_pointColor); - - - long hoursPerInterval = 1; - long millisPerInterval = MILLIS_PER_HOUR * hoursPerInterval; - - DataPoint previousDataPoint = null; - - final int pointsBetweenLabels = 6; - int pointCount = 0; - - //draw each data point - for ( long time = startTime; time <= endTime; time += millisPerInterval) - { - - Measurement measurement = getRegularTimeSeries().getMeasurementByTime(time); - - measurement = measurement.getCopy(getDisplayedMeasuringUnit()); - - - double value = measurement.getValue(); - - if (value != MISSING_VALUE) - { - DataPoint dp1 = new DataPoint(time, value); - - drawDataPoint(dp1, g, pointsBetweenLabels, pointCount); - pointCount++; - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - } - - } // for loop - - } // end of drawRegularDataPoints() method - - -// ---------------------------------------------------------- - - private void drawIrregularDataPoints( Graphics g ) - { - String header = "StagePainter.drawIrregularDataPoints():"; - //System.out.println(header + " at beginning"); - - if (getTimeSeries() == null) - { - //System.out.println(header + " time series is null"); - } - - g.setColor(_pointColor); - - //System.out.println(header + "time series = " + getTimeSeries()); - - DataPoint previousDataPoint = null; - - - //draw each data point - for ( int i = 0; (getTimeSeries() != null) && - i < getTimeSeries().getMeasurementCount(); i++) - { - - AbsTimeMeasurement measurement = (AbsTimeMeasurement) - getTimeSeries().getAbsTimeMeasurementByIndex(i); - - - - AbsTimeMeasurement convertedMeasurement = - AbsTimeMeasurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double convertedValue = convertedMeasurement.getValue(); - long time = measurement.getTime(); - - DataPoint dp1 = new DataPoint(time, convertedValue); - - drawDataPoint(dp1, g); - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - - - } // for loop - - } // end of drawIrregularDataPoints() method - -// --------------------------------------------------------- - private void drawSegment(DataPoint dp1, DataPoint dp2, Graphics g) - { - - Viewport viewport = getViewport(); - -// if it is viewable, then draw it - if ( (getViewport().isViewable(dp1)) && (getViewport().isViewable(dp2)) ) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - else - { - //System.out.println("StagePainter.drawSegment(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } - -// --------------------------------------------------------- - private void drawDataPoint(DataPoint dp, Graphics g, int pointsBetweenLabels, int pointCount) - { - - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - - if (_pointString == null) - { - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - } - else if (_pointString.equalsIgnoreCase("x")) - { - drawX(g, p1, radius); - } - else - { - String string = getPointString(); - - int xShift = - _pointLabelFontHelper.getWidth(g, string) /2 ; - - int x = p1.x + xShift; - int y = p1.y + _shiftAmount.y; - - - drawX(g, p1, radius); - - // g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - - //occasionally draw the special label for the time series - if (pointCount % pointsBetweenLabels == 0) - { - g.drawString(getPointString(), x, y ); - } - - } - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - } - - // -------------------------------------------------------------------------------- - - private void drawX(Graphics g, Point point, int radius) - { - int x1 = point.x - radius; - int y1 = point.y + radius; - int x2 = point.x + radius; - int y2 = point.y - radius; - - - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1, y2, x2, y1); - - return; - } - - // -------------------------------------------------------------------------------- - - private void drawDataPoint(DataPoint dp, Graphics g) - { - - - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - - if (_pointString == null) - { - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - } - else if (_pointString.equalsIgnoreCase("x")) - { - int x1 = p1.x - radius; - int y1 = p1.y + radius; - int x2 = p1.x + radius; - int y2 = p1.y - radius; - - g.drawLine(x1, y1, x2, y2); - g.drawLine(x1, y2, x2, y1); - } - else - { - String string = getPointString(); - - int x = p1.x + _shiftAmount.x; - int y = p1.y + _shiftAmount.y; - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - // g.drawString(getPointString(), x, y ); - - } - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } -// -------------------------------------------------------- - private IrregularTimeSeries getTimeSeries() - { - IrregularTimeSeries ts = null; - - if (_timeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _timeSeriesHolder.getTimeSeries(); - } - return ts; - } - -// --------------------------------------------------------- - - private RegularTimeSeries getRegularTimeSeries() - { - RegularTimeSeries ts = null; - - - if (_regularTimeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _regularTimeSeriesHolder.getTimeSeries(); - } - - return ts; - } -// --------------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - - public Measurement getMinMeasurement() - { - String header = "StagePainter.getMinMeasurement()"; - - Measurement minMeasurement = null; - - //extremes don't count unless displayed - if (_shouldPaint) - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - minMeasurement = getRegularTimeSeries().getMinMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - } - // System.out.println(header + "minMeasurement = " + minMeasurement); - - - return minMeasurement; - } - -// ---------------------------------------------------- - -// ---------------------------------------------------- - public Measurement getMaxMeasurement() - { - String header = "StagePainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - - if (_shouldPaint) //extremes don't count unless displayed - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - maxMeasurement = getRegularTimeSeries().getMaxMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - } - else - { - //System.out.println(header + "No time series found!!!!"); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - } - - return maxMeasurement; - } - public void setPointString(String pointString) - { - _pointString = pointString; - } - public String getPointString() - { - return _pointString; - } - public void setShiftAmount(Point shiftAmount) - { - _shiftAmount = shiftAmount; - } - public Point getShiftAmount() - { - return _shiftAmount; - } - - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TableAdapter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TableAdapter.java deleted file mode 100644 index 1aad6042a9..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TableAdapter.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.gui; - -import java.util.ArrayList; -import java.util.List; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; - -import ohd.hseb.sshp.window.SshpTableModel; -import ohd.hseb.util.gui.TableColumnComparator; -import ohd.hseb.util.gui.TableHelper2; - -/** - * @author Chip Gobs - * - * The purpose of this class is to wrap-up the usual way we use JTable, with all of its - * associated classes. - */ -abstract public class TableAdapter -{ - private JTable _table = null; - private List _dataList = null; - - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel = null; - private JScrollPane _scrollPane = null; - private TableHelper2 _tableHelper = null; - - private String[] _columnNameArray = null; - private String[][] _dataStringArray = null; - - abstract public String[][] getDataStringArrayFromDataList(List dataList); - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - - public TableAdapter(TableColumnComparator comparator, - String[] columnNameArray, - List dataList) - { - setColumnNameArray(columnNameArray); - - String[][] dataStringArray = getDataStringArrayFromDataList(dataList); - //setDataStringArray(dataStringArray); - - _dataList = dataList; - - _tableHelper = new TableHelper2(comparator, _columnNameArray); - - _tableModel = new SshpTableModel( _columnNameArray, dataStringArray ); - _table = new JTable(_tableModel); - _table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _table.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - - - int index = 0; - - Rectangle rect = _table.getCellRect(index, 0, true); - _scrollPane = new JScrollPane(_table); - - // a suggestion I read somewhere, said to try the following instead of - // _scrollPane = new JScrollPane(_table); - - // _scrollPane = new JScrollPane(); - // _scrollPane.setViewportView(_table); - // _scrollPane.revalidate(); - - - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - - _listSelectionModel = _table.getSelectionModel(); - _listSelectionModel.setSelectionInterval( 0, 0 ); - - - addListeners(); - } - // -------------------------------------------------------------------------------- - - - protected int[] getSelectedRowIndexArray() - { - //returns =1 if nothing selected - List selectedRowIndexList = new ArrayList(); - - for (int i = 0; i < selectedRowIndexList.size(); i++) - { - if (_listSelectionModel.isSelectedIndex(i)) - { - selectedRowIndexList.add(new Integer(i)); - } - - } - - int[] indexArray = new int[selectedRowIndexList.size()]; - - for (int i = 0; i < indexArray.length; i++ ) - { - Integer integer = (Integer)selectedRowIndexList.get(i); - indexArray[i] = integer.intValue(); - } - - return indexArray; - } - - public void setAllowMultipleSelection(boolean allowMultipleSelection) - { - if (allowMultipleSelection) - { - _table.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); - } - else - { - _table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - } - - return; - } - // -------------------------------------------------------------------------------- - - public void setColumnNameArray(String[] columnNameArray) - { - _columnNameArray = new String[columnNameArray.length]; - for (int i = 0; i < _columnNameArray.length; i++) - { - _columnNameArray[i] = columnNameArray[i]; - } - } - // -------------------------------------------------------------------------------- - public String[] getColumnNameArray() - { - return _columnNameArray; - } - -// -------------------------------------------------------------------------------- - private void addListeners() - { - //_listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _table.getTableHeader().addMouseListener( new TableSortingListener() ); - - return; - } -/** - * @param table The table to set. - */ - public void setTable(JTable table) - { - _table = table; - } - /** - * @return Returns the table. - */ - public JTable getTable() - { - return _table; - } - /** - * @param scrollPane The scrollPane to set. - */ - private void setScrollPane(JScrollPane scrollPane) - { - _scrollPane = scrollPane; - } - /** - * @return Returns the scrollPane. - */ - public JScrollPane getScrollPane() - { - return _scrollPane; - } - // -------------------------------------------------------------------------------- - public void refreshTableModel(List dataList) - { - // int index = 0; - - -// int[] indexArray = getSelectedRowIndexArray(); - - System.out.println("TableAdapter.refreshTableModel(): - should be calling same method in subclass "); - //_tableModel.updateData( _dataStringArray ); - //_tableModel.fireTableChanged( null ); - - - // reselect all the items that -// _listSelectionModel.setSelectionInterval() - - //make sure that the item is visible -// Rectangle rect = _table.getCellRect(index, 0, true); -// _scrollPane.getViewport().setViewPosition(rect.getLocation()); - - //load up the data entry fields -// loadTextFields(); - - //redraw the canvas - //_canvasMgr.refreshCanvas(_uhgList); - - return; - } - - // -------------------------------------------------------------------------------- - - /** - * @param dataList The dataList to set. - */ - public void setDataList(List dataList) - { - _dataList = dataList; - } - - /** - * @return Returns the dataList. - */ - public List getDataList() - { - return _dataList; - } - - /** - * @param listSelectionModel The listSelectionModel to set. - */ - protected void setListSelectionModel(ListSelectionModel listSelectionModel) - { - _listSelectionModel = listSelectionModel; - } - /** - * @return Returns the listSelectionModel. - */ - public ListSelectionModel getListSelectionModel() - { - return _listSelectionModel; - } - - /** - * @param tableModel The tableModel to set. - */ - public void setTableModel(SshpTableModel tableModel) - { - _tableModel = tableModel; - } - /** - * @return Returns the tableModel. - */ - public SshpTableModel getTableModel() - { - return _tableModel; - } - - //------------------------------------------------------------------------------ - public int getFirstSelectedIndex() - { - int index = -1; - - index = _table.getSelectedRow(); - - return index; - - } - //------------------------------------------------------------------------------ - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _table.getTableHeader().columnAtPoint( point ); - - _tableHelper.sortList( _dataList, column, true ); - refreshTableModel(_dataList); - } - } -// ------------------------------------------------------------------------------ -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TimeLinePainter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TimeLinePainter.java deleted file mode 100644 index 223bf175cf..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TimeLinePainter.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - - -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.Graphics; -import java.awt.*; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of the vertical time line indicator on a TsPaintableCanvas - */ -public class TimeLinePainter implements CanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private TimeHolder _timeHolder = null; - - // --------------------------------------------------------- - public TimeLinePainter(Color lineColor, - TimeHolder timeHolder, - TsPaintableCanvas canvas) - { - - _lineColor = lineColor; - _canvas = canvas; - - _timeHolder = timeHolder; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - - double dataX = _timeHolder.getTime(); - double maxDataY = getViewport().getMaxDataPoint().getY(); - double minDataY = getViewport().getMinDataPoint().getY(); - - DataPoint dp1 = new DataPoint(dataX, maxDataY); - DataPoint dp2 = new DataPoint(dataX, minDataY); - - if (getViewport().isViewable(dp1)) - { - - Point p1 = _canvas.getViewport().getScreenPoint(dp1); - Point p2 = _canvas.getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - - } // end of drawDataLine() - -//---------------------------------------------------- - - -} //end of TimeLinePainter diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TsBackgroundPainter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TsBackgroundPainter.java deleted file mode 100644 index b2b56a3f05..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/gui/TsBackgroundPainter.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.sshp.gui; - -//import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.Graphics; -import java.awt.*; -import java.text.*; - -/** - * @author Chip Gobs - * - * This class implements CanvasPainter and encapsulates the - * drawing of the X and Y axes and all the tick marks - */ -public class TsBackgroundPainter implements CanvasPainter -{ - - - private TsPaintableCanvas _canvas = null; - - private ValueMapper _rightLabelValueMapper = null; - - -// graphing hours - private int _hoursPerMajorXTick = 6; - private int _hoursPerMinorXTick = 1; - - //time constant - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - //number formatter - private NumberFormat _numberFormat = NumberFormat.getInstance(); - - // various colors - private static final Color _backgroundColor = Color.black; - - - // NOTE: future changes: - // will want to have multiple time series, so there needs - // to be a way to have different colors for timeseries - - //private Color _lineColor = null; - private static final Color _gridColor = Color.GRAY; - private Color _outlineColor = Color.WHITE; - private static final Color _labelColor = Color.WHITE; - private static final Color _currentTimeColor = Color.YELLOW; - - //unit labels - private String _leftUnitLabelString = null; - private String _rightUnitLabelString = null; - - -// fonts - private Font _titleFont = null; - private Font _labelFont = null; - - //FontHelper - custom class - private FontHelper _titleFontHelper = null; - private FontHelper _labelFontHelper = null; - - // margins and shifts - private final static int _titleYShift = - 20; - private int _leftLabelShift = 30; - private int _rightLabelShift = 10; - - private double _smallRoundingError = 0.000000001; - - - private boolean _showMinorTicks = true; - - // --------------------------------------------------------- - public TsBackgroundPainter(Color outlineColor, - TsPaintableCanvas canvas, - String leftUnitLabelString, - String rightUnitLabelString) - { - _outlineColor = outlineColor; - _canvas = canvas; - - _leftUnitLabelString = leftUnitLabelString; - _rightUnitLabelString = rightUnitLabelString; - - _numberFormat.setMaximumFractionDigits(2); - - _titleFont = new Font("TimesRoman",Font.BOLD,14); - _labelFont = new Font("Helvetica",Font.PLAIN,9); - - _titleFontHelper = new FontHelper(_titleFont); - _labelFontHelper = new FontHelper(_labelFont); - - _showMinorTicks = true; - - } //tsBackgroundPainter() - -// --------------------------------------------------------- - public void setShowMinorTicks(boolean showMinorTicks) - { - _showMinorTicks = showMinorTicks; - } -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawBackground(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// ---------------------------------------------------- - - public void setRightLabelValueMapper(ValueMapper rightLabelValueMapper) - { - _rightLabelValueMapper = rightLabelValueMapper; - } -// ---------------------------------------------------- - - private ValueMapper getRightLabelValueMapper() - { - return _rightLabelValueMapper; - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - public void drawBackground(Graphics g) - { - - Rectangle r = _canvas.getBounds(); - - //set the normal font to use - g.setFont( _labelFont ); - - //clear the image - g.setColor(_backgroundColor); - g.fillRect(0, 0, r.width, r.height); - - //draw the axis labels, ticks, and dotted lines - drawHorizontalLines( g ); - drawVerticalLines( g ); - - //draw the Title - drawTitle(g); - - int x = 0; - int y = 0; - - x = 10; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_leftUnitLabelString, g, x, y); - - x = _canvas.getViewport().getMaxScreenPoint().x + 20; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_rightUnitLabelString, g, x, y); - - - } - -//---------------------------------------------------- - private void drawTitle(Graphics g) - { - String titleString = _canvas.getTitle(); - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, titleString) / 2; - - int x = middleX - totalLeftShift; - int y = (_canvas.getTopMargin() + _titleYShift); - - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(titleString, x, y); - - return; - } //drawTitle - - private void drawUnitLabel(String unitLabel, Graphics g, int x, int y) - { - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(unitLabel, x, y); - - return; - } //drawTitle - -// -------------------------------------------------------------------------- - - private void drawVerticalLines(Graphics g) - { - // determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - Point point1 = null; - Point point2 = null; - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - // draw each tick line - double tickValue = minXValue; - - int minorTickHours = _hoursPerMinorXTick; - int majorTickHours = _hoursPerMajorXTick; - - for (; tickValue <= maxXValue; tickValue += minorTickHours * MILLIS_PER_HOUR) - { - point1 = getViewport().getScreenPoint(new DataPoint(tickValue, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(tickValue, maxYValue)); - - - //if on a majorTick - if (isOnATick((long)tickValue, majorTickHours)) - { - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on graph boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else //not on a graph boundary - { - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - } - - //draw the major tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+6, point2.x, point1.y); - - //draw a major tick - //build the labels - String hourLabelString = CanvasHelper.getHourString((long)tickValue) + "Z"; - String dateLabelString = CanvasHelper.getDateString((long)tickValue); - - // draw the labels - g.setColor(_labelColor); - g.drawString(hourLabelString, point1.x-5, point1.y + 15); - - //only draw the date string at 00Z - if (hourLabelString.equals("00Z")) - { - g.drawString(dateLabelString, point1.x-5, point1.y + 30); - } - } - else //on a minor tick - { - - //draw a minor tick - //draw the minor tick extension - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+2, point2.x, point1.y); - - } - } //end for i - - - // if applicable, draw current time line - long currentTime = System.currentTimeMillis(); - if ( (currentTime >= minXValue) && (currentTime <=maxXValue)) - { - point1 = getViewport().getScreenPoint(new DataPoint(currentTime, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(currentTime, maxYValue)); - - g.setColor(_currentTimeColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - } //end drawXAxis - -// -------------------------------------------------------------------------- - private boolean isOnATick(long timeValue, int hoursPerTick) - { - boolean result = false; - - long roundedTime = TimeHelper.truncateTimeInMillisToNearestHour((long)timeValue, hoursPerTick); - - // String timeValueString = DbTimeHelper.getDateTimeStringFromLongTime(timeValue); - // String roundedTimeString = DbTimeHelper.getDateTimeStringFromLongTime(roundedTime); - - if ( ( timeValue == roundedTime ) || - ( timeValue == roundedTime + (hoursPerTick*MILLIS_PER_HOUR)) - ) - { - result = true; - } - return result; - } //end isOnATick - - -// ------------------------------------------------------------------------------------------- - - private void drawHorizontalLines(Graphics g) - { - //determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - //String header = "TsBackgroundPainter.drawHorizontalLines(): "; - - //System.out.println(header + "minDataPoint = " + minDataPoint); - //System.out.println(header + "maxDataPoint = " + maxDataPoint); - - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - ScalingHelper scalingHelper = new ScalingHelper(minYValue, maxYValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - // int totalTickCount = majorTickCountMax * minorTickCount; - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minYValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_labelFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxYValue + _smallRoundingError); - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minYValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(minXValue, majorTickValue)); - point2 = getViewport().getScreenPoint(new DataPoint(maxXValue, majorTickValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not working due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - //CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - - } - - - //draw the left side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x-5, point1.y, point1.x, point2.y); - - // draw the label - String numberLabelString = _numberFormat.format(majorTickValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point1.x - _leftLabelShift , point1.y + 3); - - - - - //draw the right side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point2.x+5, point2.y, point2.x, point2.y); - - // draw the label - ValueMapper valueMapper = getRightLabelValueMapper(); - - double newValue = majorTickValue; - if (valueMapper != null) - { - Measurement m = new Measurement(majorTickValue, valueMapper.getInputMeasuringUnit()); - newValue = valueMapper.getResultMeasurement(m).getValue(); - } - - numberLabelString = _numberFormat.format(newValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point2.x + _rightLabelShift , point2.y + 3); - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minXValue, minorTickValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(maxXValue, minorTickValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, minorPoint1.x, minorPoint1.y, minorPoint2.x, minorPoint2.y); - - } - } - - } //end if _showMinorTicks - - } - - } //end drawYAxis - -// ------------------------------------------------------------------------------ - - - - -} //end of SigStageLinePainter diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/DecoderDataMgr.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/DecoderDataMgr.java deleted file mode 100644 index 388910086b..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/DecoderDataMgr.java +++ /dev/null @@ -1,621 +0,0 @@ -/* - * Created on Jul 30, 2003 - * - * - */ -package ohd.hseb.sshp.messaging; - -import ohd.hseb.db.*; -import ohd.hseb.sshp.FcstTsDescriptor; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstOtherRecord; -import ohd.hseb.ihfsdb.generated.FcstOtherTable; -import ohd.hseb.ihfsdb.generated.MonthlyValuesRecord; -import ohd.hseb.ihfsdb.generated.MonthlyValuesTable; -import ohd.hseb.ihfsdb.generated.SacSmaParamsRecord; -import ohd.hseb.ihfsdb.generated.SacSmaParamsTable; -import ohd.hseb.ihfsdb.generated.SacSmaStateRecord; -import ohd.hseb.ihfsdb.generated.SacSmaStateTable; -import ohd.hseb.measurement.*; -import ohd.hseb.model.*; -import ohd.hseb.model.sacsma.*; - -import java.util.*; -import java.sql.*; - -// These are explicity imported in order to show what -// database tables are being used. - - -public class DecoderDataMgr -{ - - public final double MISSING = -999.0; - private static final int RECORD_COUNT_FOR_RECONNECT = 500; - private FileLogger _logger = null; - private Database _db = null; - private String _connectionString = null; - private int _timeSeriesRecordInsertionCounter = 0; - - private Map _oldFcstDischargeMap = new HashMap(); - -// ------------------------------------------------------------------------ - - public DecoderDataMgr( FileLogger logger ) - { - this( null, logger ); - } - -// ------------------------------------------------------------------------ - - public DecoderDataMgr( String baseConnectionString, FileLogger logger ) - { - _db = new Database(); - - _logger = logger; - - _connectionString = baseConnectionString; - - _db.connect( _connectionString ); - } - - // ------------------------------------------------------------------------ - - public void disconnect() - { - _db.disconnect(); - } - -// ------------------------------------------------------------------------ - - public void finalize() - { - disconnect(); - } - -// ------------------------------------------------------- - - private void logSQLException( SQLException exception ) - { -/* - System.out.println("ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); -*/ - _logger.log( "ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - } - -// ------------------------------------------------------- - - public SacSmaParameters loadNewestSacSmaParams( String basinId, String source ) - { - List sacSmaParamsRecordList = null; - List sacSmaParamsList = null; - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - - String where = " WHERE basin_id='" + basinId + "' AND source='" + source + "' ORDER BY validTime desc "; - - try - { - sacSmaParamsRecordList = table.selectNRecords( where, 1 ); - } - catch( SQLException e ) - { - logSQLException(e); - } - sacSmaParamsList = getSacSmaParamsListFromSacSmaParamsRecordList( sacSmaParamsRecordList ); - - if ( sacSmaParamsList.size() == 0 ) - { - return null; - } - else - { - return (SacSmaParameters) sacSmaParamsList.get( 0 ); - } - } - -// ------------------------------------------------------- - - private List getSacSmaParamsListFromSacSmaParamsRecordList( List sacSmaParamsRecordList ) - { - List sacSmaParamsList = new ArrayList(); - - for( int i = 0; i < sacSmaParamsRecordList.size(); i++ ) - { - SacSmaParameters addSacSmaParams = new SacSmaParameters(); - SacSmaParamsRecord sacSmaParamsRecord = (SacSmaParamsRecord) sacSmaParamsRecordList.get( i ); - - addSacSmaParams.setBasinId(sacSmaParamsRecord.getBasin_id()); - addSacSmaParams.setSource(sacSmaParamsRecord.getSource()); - addSacSmaParams.setValidTime(sacSmaParamsRecord.getValidtime()); - addSacSmaParams.setPostingTime(sacSmaParamsRecord.getPostingtime()); - addSacSmaParams.setUztwm(sacSmaParamsRecord.getUztwm()); - addSacSmaParams.setUzfwm(sacSmaParamsRecord.getUzfwm()); - addSacSmaParams.setUzk(sacSmaParamsRecord.getUzk()); - addSacSmaParams.setPctim(sacSmaParamsRecord.getPctim()); - addSacSmaParams.setAdimp(sacSmaParamsRecord.getAdimp()); - addSacSmaParams.setRiva(sacSmaParamsRecord.getRiva()); - addSacSmaParams.setZperc(sacSmaParamsRecord.getZperc()); - addSacSmaParams.setRexp(sacSmaParamsRecord.getRexp()); - addSacSmaParams.setLztwm(sacSmaParamsRecord.getLztwm()); - addSacSmaParams.setLzfsm(sacSmaParamsRecord.getLzfsm()); - addSacSmaParams.setLzfpm(sacSmaParamsRecord.getLzfpm()); - addSacSmaParams.setLzsk(sacSmaParamsRecord.getLzsk()); - addSacSmaParams.setLzpk(sacSmaParamsRecord.getLzpk()); - addSacSmaParams.setPfree(sacSmaParamsRecord.getPfree()); - addSacSmaParams.setRserv(sacSmaParamsRecord.getRserv()); - addSacSmaParams.setSide(sacSmaParamsRecord.getSide()); - - addSacSmaParams.setPeadj(sacSmaParamsRecord.getPeadj()); - addSacSmaParams.setPxadj(sacSmaParamsRecord.getPxadj()); - addSacSmaParams.setEfc(sacSmaParamsRecord.getEfc()); - - sacSmaParamsList.add( addSacSmaParams ); - } - return sacSmaParamsList; - } - -// ------------------------------------------------------- - - - private SacSmaParamsRecord getSacSmaParamsRecord( SacSmaParameters sacSmaParams ) - { - SacSmaParamsRecord record = new SacSmaParamsRecord(); - - record.setBasin_id( sacSmaParams.getBasinId() ); - record.setSource(sacSmaParams.getSource()); - record.setValidtime(sacSmaParams.getValidTime() ); - record.setPostingtime(sacSmaParams.getPostingTime()); - - record.setUztwm(sacSmaParams.getUztwm()); - record.setUzfwm(sacSmaParams.getUzfwm()); - record.setUzk(sacSmaParams.getUzk()); - record.setPctim(sacSmaParams.getPctim()); - record.setAdimp(sacSmaParams.getAdimp()); - record.setRiva(sacSmaParams.getRiva()); - record.setZperc(sacSmaParams.getZperc()); - record.setRexp(sacSmaParams.getRexp()); - record.setLztwm(sacSmaParams.getLztwm()); - record.setLzfsm(sacSmaParams.getLzfsm()); - record.setLzfpm(sacSmaParams.getLzfpm()); - record.setLzsk(sacSmaParams.getLzsk()); - record.setLzpk(sacSmaParams.getLzpk()); - record.setPfree(sacSmaParams.getPfree()); - record.setRserv(sacSmaParams.getRserv()); - record.setSide(sacSmaParams.getSide()); - record.setPeadj(sacSmaParams.getPeadj()); - record.setPxadj(sacSmaParams.getPxadj()); - record.setEfc(sacSmaParams.getEfc()); - - return record; - } - - -// ------------------------------------------------------- - - - public void saveParams( SacSmaParameters sacSmaParams ) - { - SacSmaParamsTable table = new SacSmaParamsTable( _db ); - SacSmaParamsRecord record = getSacSmaParamsRecord( sacSmaParams ); - - try - { - table.insertOrUpdate( record ); - _logger.log( " Successfully inserted or updated Params for " + record.getBasin_id() ); - } - catch ( SQLException e ) - { - logSQLException(e); - _logger.log("failed to insert or update for " + record); - } - } -// ------------------------------------------------------- - - public void saveState( SacSmaState sacSmaState ) - { - SacSmaStateTable table = new SacSmaStateTable( _db ); - SacSmaStateRecord record = new SacSmaStateRecord(); - - record.setBasin_id( sacSmaState.getBasinId() ); - record.setSource( sacSmaState.getSource() ); - record.setValidtime( sacSmaState.getValidTime() ); - record.setBasistime( sacSmaState.getBasisTime() ); - record.setPostingtime( sacSmaState.getPostingTime() ); - - record.setUztwc( sacSmaState.getUztwc() ); - record.setUzfwc( sacSmaState.getUzfwc() ); - record.setLztwc( sacSmaState.getLztwc() ); - record.setLzfsc( sacSmaState.getLzfsc() ); - record.setLzfpc( sacSmaState.getLzfpc() ); - record.setAdimc( sacSmaState.getAdimc() ); - - try - { - table.insertOrUpdate( record ); - _logger.log( " Successfully inserted or updated State for " + record.getBasin_id() ); - } - catch ( SQLException e ) - { - logSQLException(e); - _logger.log("failed to insert or update for " + record); - } - } - -// ------------------------------------------------------- - - public void saveMonthlyValues( MonthlyValues monthlyValues ) - { - MonthlyValuesTable table = new MonthlyValuesTable( _db ); - MonthlyValuesRecord record = new MonthlyValuesRecord(); - long currentTime = System.currentTimeMillis(); - double[] valueArray = monthlyValues.getValueArray(); - - record.setLid( monthlyValues.getBasinId() ); - record.setPe( monthlyValues.getPe() ); - record.setDur( monthlyValues.getDur() ); - record.setTs( monthlyValues.getTs() ); - record.setExtremum( monthlyValues.getExtremum() ); - if ( monthlyValues.isAdjustment() ) - { - record.setAdjustment( "Y" ); - } - else - { - record.setAdjustment( "N" ); - } - record.setPostingtime( currentTime ); - record.setJan_value( valueArray[ 0 ] ); - record.setFeb_value( valueArray[ 1 ] ); - record.setMar_value( valueArray[ 2 ] ); - record.setApr_value( valueArray[ 3 ] ); - record.setMay_value( valueArray[ 4 ] ); - record.setJun_value( valueArray[ 5 ] ); - record.setJul_value( valueArray[ 6 ] ); - record.setAug_value( valueArray[ 7 ] ); - record.setSep_value( valueArray[ 8 ] ); - record.setOct_value( valueArray[ 9 ] ); - record.setNov_value( valueArray[ 10 ] ); - record.setDec_value( valueArray[ 11 ] ); - try - { - table.insertOrUpdate( record ); - _logger.log( " Successfully inserted or updated Monthly Values for " + record.getLid() ); - } - catch ( SQLException e ) - { - logSQLException(e); - _logger.log("failed to insert or update for " + record); - } - } -// ------------------------------------------------------- - public void saveFcstTimeSeries( FcstTsDescriptor descriptor, RegularTimeSeries timeSeries ) - { - _timeSeriesRecordInsertionCounter = 0; - - if ( descriptor.getTableName().equalsIgnoreCase( "FcstDischarge" ) ) - { - saveFcstRunoffTs( descriptor, timeSeries ); - } - else if ( descriptor.getTableName().equalsIgnoreCase( "FcstOther" ) ) - { - saveFcstOtherTs( descriptor, timeSeries ); - } - } - -// ------------------------------------------------------- - - private void saveFcstOtherTs( FcstTsDescriptor descriptor, RegularTimeSeries timeSeries ) - { - FcstOtherTable table = new FcstOtherTable(_db); - FcstOtherRecord record = new FcstOtherRecord(); - - FcstOtherRecord oldRecord = null; - - String space = " "; - long startTime = 0; - long endTime = 0; - long interval = 0; - long maxBasisTime = 0; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - CodeTimer timer1 = new CodeTimer( _logger ); - - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - - timer1.start(); - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - - - //initialize the record key fields to save from the descriptor - setRecordFromDescriptor(record, descriptor); - - //delete records from the same or previous basistime - String deleteWhereString = null; - deleteWhereString = getDeleteWhereString( descriptor ); - - try - { - table.delete( deleteWhereString ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - - - - int insertCount = 0; - - //insert records - for (long time = startTime; time <= endTime; time += interval) - { - reconnectIfNeeded(); - - Measurement newMeasurement = timeSeries.getMeasurementByTime(time); - double value = newMeasurement.getValue(dbRunoffUnit); - - record.setValue(value); - record.setValidtime(time); - - try - { - table.insert(record); - _timeSeriesRecordInsertionCounter++; //used for reconnections - insertCount++; - } - - catch ( SQLException e ) - { - logSQLException( e ); - _logger.log( space + "error with insert for FcstOther " + record); - _logger.log( space + "insertCount = " + insertCount); - } - } - - _logger.log( space + insertCount + " records inserted" + - " for " + record.getLid() + "." ); - - - } -// ------------------------------------------------------- - - -// ------------------------------------------------------- - private void setRecordFromDescriptor(FcstDischargeRecord record, FcstTsDescriptor descriptor) - { - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - return; - - } - -// ------------------------------------------------------- - private void setRecordFromDescriptor(FcstOtherRecord record, FcstTsDescriptor descriptor) - { - record.setLid(descriptor.getLid()); - record.setPe(descriptor.getPe()); - record.setTs(descriptor.getTs()); - record.setExtremum(descriptor.getExtremum()); - record.setShef_qual_code(descriptor.getShef_qual_code()); - record.setProduct_id(descriptor.getProduct_id()); - record.setProbability(descriptor.getProbability()); - record.setQuality_code(descriptor.getQuality_code()); - record.setRevision(descriptor.getRevision()); - record.setDur(descriptor.getDur()); - record.setProducttime(descriptor.getProducttime()); - record.setBasistime(descriptor.getBasistime()); - record.setPostingtime(System.currentTimeMillis()); - - return; - - } - - - -// ------------------------------------------------------- - - private void saveFcstRunoffTs( FcstTsDescriptor descriptor, RegularTimeSeries timeSeries ) - { - FcstDischargeTable table = new FcstDischargeTable( _db ); - FcstDischargeRecord record = new FcstDischargeRecord(); - - String space = " "; - long startTime = 0; - long endTime = 0; - long interval = 0; - long maxBasisTime = 0; - final long HOUR_IN_MILLIS = 60 * 60 * 1000; - CodeTimer timer1 = new CodeTimer( _logger ); - - MeasuringUnit dbRunoffUnit = MeasuringUnit.inches; - - - timer1.start(); - - startTime = timeSeries.getStartTime(); - endTime = timeSeries.getEndTime(); - interval = timeSeries.getIntervalInHours() * HOUR_IN_MILLIS; - - - - //initialize the record key fields to save from the descriptor - setRecordFromDescriptor(record, descriptor); - - - - //delete records from the same or previous basistime - String deleteWhereString = null; - - deleteWhereString = getDeleteWhereString( descriptor ); - - try - { - table.delete( deleteWhereString ); - } - catch ( SQLException e ) - { - logSQLException(e); - } - - - //insert all records - int insertCount = 0; - for (long time = startTime; time <= endTime; time += interval) - { - reconnectIfNeeded(); - - Measurement newMeasurement = timeSeries.getMeasurementByTime(time); - double value = newMeasurement.getValue(dbRunoffUnit); - - record.setValue(value); - record.setValidtime(time); - - try - { - table.insert(record); - _timeSeriesRecordInsertionCounter++; //used for reconnections - insertCount++; - } - - catch ( SQLException e ) - { - logSQLException( e ); - _logger.log( space + "error with insert for FcstOther " + record); - _logger.log( space + "insertCount = " + insertCount); - } - } - - - _logger.log( space + insertCount + " records inserted" + - " for " + record.getLid() + "." ); - - - - - } //end saveFcstDischarge - - -// ------------------------------------------ - - private String getDeleteWhereString( FcstTsDescriptor descriptor ) - { - String whereString = - "WHERE lid = '" + descriptor.getLid() + "'" - + " AND pe = '" + descriptor.getPe() + "'" - + " AND dur = '" + descriptor.getDur() + "'" - + " AND ts = '" + descriptor.getTs() + "'" - + " AND extremum = '" + descriptor.getExtremum() + "'" - + " AND probability = '" + descriptor.getProbability() + "'" - + " AND product_id = '" + descriptor.getProduct_id() + "'" - + " AND basistime <= '" + DbTimeHelper.getDateTimeStringFromLongTime( descriptor.getBasistime() ) + "'" ; - - return whereString; - } - - - -// ------------------------------------------------------- - - - - void addRecordToMap(FcstDischargeRecord record) - { - Long key = new Long(record.getValidtime()); - Object value = record; - - _oldFcstDischargeMap.put(key, value); - - return; - } - -//------------------------------------------------------- - - - - // ------------------------------------------------------------------------------- - - -// ------------------------------------------------------- - - -// ------------------------------------------------------- - - private void testFcstOtherRecordInsertion() - { - FcstOtherRecord record = null; - FcstOtherTable table = new FcstOtherTable( _db ); - String where = " WHERE PE='EA' "; - - try - { - List recordList = table.select( where ); - if ( recordList.size() > 0 ) - { - record = (FcstOtherRecord) recordList.get( 0 ); - System.out.println( "DecoderDataMgr.testFcst: record: " + record ); - table.insertOrUpdate( record ); - } - } - catch ( SQLException e ) - { - e.printStackTrace(); - } - - } - -// ------------------------------------------------------- - - private void reconnectIfNeeded() - { - // This was old code that was written only because the Informix JDBC driver had a memory leak that - // could only be fixed by disconnecting and reconnecting. - /* - int total = _timeSeriesRecordInsertionCounter; - if ( ( total > 0 ) && ( total % RECORD_COUNT_FOR_RECONNECT == 0 ) ) - { - reconnect(); - } - */ - } - -// ------------------------------------------------------- - - private void reconnect() - { - _db.disconnect(); - _db.connect( _connectionString ); - _logger.log( " Reconnected to the Database for performance reasons" ); - } - -// ------------------------------------------------------- - - - public static void main( String args[] ) - { - DecoderDataMgr decoderMgr = new DecoderDataMgr(new FileLogger( "DecoderDataMgrtesting.log" ) ); - decoderMgr.testFcstOtherRecordInsertion(); - } -} //end class DecoderDataMgr diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/OfsFileParserException.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/OfsFileParserException.java deleted file mode 100644 index 7d48a8ff9d..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/OfsFileParserException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Created on Apr 26, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Apr 26, 2004 - * - */ -package ohd.hseb.sshp.messaging; - -/** - * @author SoodG -*/ -public class OfsFileParserException extends Exception -{ - public OfsFileParserException( String message ) - { - super( message ); - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java deleted file mode 100644 index 612a5cad4d..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java +++ /dev/null @@ -1,751 +0,0 @@ -/* - * Created on Sep 11, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : March 16, 2004 - * Purpose: Decodes XML input files and posts the data to the database. - */ - -package ohd.hseb.sshp.messaging; - -import org.jdom.*; -import org.jdom.input.SAXBuilder; -import org.jdom.Document; -import org.jdom.JDOMException; -import org.jdom.output.XMLOutputter; - -import java.io.*; -import java.util.*; -import java.util.Date; - -import ohd.hseb.measurement.*; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.sacsma.*; -import ohd.hseb.db.*; -import ohd.hseb.sshp.FcstTsDescriptor; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; - - -public class SacXMLDecoder -{ - private String _inputDir = null; - private String _archiveDir = null; - private String _logFullPath = null; - private long _sleepTime = 0; - private Document _doc = null; - private boolean _isTest = false; - - private static final String PE_TIMESERIES_PE_CODE = "EA"; - private static final String RUNOFF_TIMESERIES_PE_CODE = "QB"; - private static final String TS = "FZ"; - private static final String EXTREMUM = "Z"; - private static final float PROBABILITY = -1.0f; - private static final String SHEF_QUAL_CODE = "Z"; - private static final int GOOD_QC = 1879048191; - private static final short REVISION = 0; - private static final String PRODUCT_ID = "SSHP_XFER"; - - private static final String MONTHLY_VALUES_TS = "FZ"; - private static final String MONTHLY_VALUES_EXTREMUM = "Z"; - private static final String MONTHLY_VALUES_PE = "EA"; - private static final short MONTHLY_VALUES_DUR = 2001; - private static final MeasuringUnit DB_MEASURING_UNIT = MeasuringUnit.inches; - private static final int INTERVAL_IN_HOURS = 1; - - private static Map _unitsMap = new HashMap(); - - private FileLogger _logger = null; - - private String _connectionString = null; - - private DecoderDataMgr _dataMgr = null; - - // --------------------------------------------------------------------------------------------------------- - - public SacXMLDecoder( String connectionString ) - { - _connectionString = connectionString; - } - - // --------------------------------------------------------------------------------------------------------- - - private void execute() - { - boolean executeProgram = true; - File localDirFile = null; - File[] localFileArray = null; - File backupInputFile = null; - localDirFile = new File( _inputDir ); - localFileArray = localDirFile.listFiles(); - SAXBuilder builder = new SAXBuilder(); - - File inputFile = null; - int badFileCounter = 0; - boolean keepFileOpen = true; - boolean appendDateTime = true; - - _logger = new FileLogger( _logFullPath, keepFileOpen, appendDateTime ); - CodeTimer timer1 = new CodeTimer( _logger ); - Set filesNotToProcessAgainSet = new HashSet(); - - - connect(); - - initUnitsMap(); - - while ( executeProgram ) - { - localFileArray = getFileList( localDirFile ); - - int validFileCount = localFileArray.length - filesNotToProcessAgainSet.size(); - - if (validFileCount > 0) - { - for (File file : localFileArray) - { - - if (! filesNotToProcessAgainSet.contains(file.getAbsoluteFile())) - { - - timer1.start(); - - _logger.log( "Processing " + file.getName() ); - - processFile(builder, file, filesNotToProcessAgainSet); - - _logger.log( "Finished Processing " + file.getName() ); - - timer1.stop( "Finished processing " + file.getName() + " in " ); - } - else - { - _logger.log( "Skipping " + file.getName() + "because it could not be moved earlier. Do not want to process it again." ); - - } - - } //end for - } - else // validFileCount <= 0 (No files found) - { - - if ( _isTest ) - { - _logger.log( "No more valid XML Files found. Moving back to sleep mode." ); - sleep(); - } - else - { - _logger.log( "No more valid XML Files found. Processing Complete." ); - executeProgram = false; - } - } - } // end While loop - - - disconnect(); - - } - - // --------------------------------------------------------------------------------------------------------- - - private boolean processFile(SAXBuilder builder, File file, Set filesNotToProcessAgain) - { - String fullFilePath = null; - String shortFileName = null; - boolean success = true; - - try - { - builder.setExpandEntities( true ); - - fullFilePath = file.getAbsolutePath(); - shortFileName = file.getName(); - - _doc = builder.build( fullFilePath ); - - parseXMLFile(); - - moveFile(shortFileName, fullFilePath, filesNotToProcessAgain); - - } - catch ( JDOMException e ) - { - _logger.log( " " + fullFilePath + " is not a valid XML file." ); - filesNotToProcessAgain.add(fullFilePath); - success = false; - } - - catch ( IOException e ) - { - e.printStackTrace(); - - _logger.log( " " + fullFilePath + " encountered an IOException -->" ); - e.printStackTrace(_logger.getPrintWriter()); - _logger.log("end IOException message"); - - filesNotToProcessAgain.add(fullFilePath); - } - finally - { - - } - - return success; - } - - // --------------------------------------------------------------------------------------------------------- - - private void moveFile(String shortFileName, String fullFilePath, Set filesUnableToBeMovedSet ) - { - - File backupInputFile = new File( _archiveDir + "/" + shortFileName); - - File inputFile = new File( fullFilePath ); - boolean successfulRename = inputFile.renameTo( backupInputFile ); - if (successfulRename) - { - _logger.log( "Success! Moved " + fullFilePath + " to " + backupInputFile); - } - else - { - _logger.log( "Error! - Unable to move " + fullFilePath + " to " + backupInputFile); - filesUnableToBeMovedSet.add(fullFilePath); - } - - return; - } - - // --------------------------------------------------------------------------------------------------------- - - - private File[] getFileList( File localDirFile ) - { - File[] returnFileArray = null; - File[] currentFileArray = null; - List tempFileList = new ArrayList(); - - currentFileArray = localDirFile.listFiles(); - - - for ( int i = 0; i < currentFileArray.length; i++ ) - { - if ( ! currentFileArray[ i ].isDirectory() ) - { - tempFileList.add( currentFileArray[ i ] ); - } - } - - returnFileArray = (File[]) tempFileList.toArray( new File[ tempFileList.size() ] ); - - return returnFileArray; - } - - // --------------------------------------------------------------------------------------------------------- - - private void initUnitsMap() - { - _unitsMap.put( new String( "mm" ), MeasuringUnit.mm ); - _unitsMap.put( new String( "cm" ), MeasuringUnit.cm ); - _unitsMap.put( new String( "m" ), MeasuringUnit.meters ); - _unitsMap.put( new String( "in" ), MeasuringUnit.inches ); - _unitsMap.put( new String( "ft" ), MeasuringUnit.feet ); - } - - // --------------------------------------------------------------------------------------------------------- - - private void sleep() - { - try - { -// System.out.println( "Sleeping for " + _sleepTime/1000 + " seconds..." ); - Thread.sleep( _sleepTime ); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------------------------------------------- - - private void parseXMLFile() - { - Element sacParamsListElement = _doc.getRootElement().getChild( "SacParamsList" ); - Element sacStateListElement = _doc.getRootElement().getChild( "SacStateList" ); - Element peTimeSeriesListElement = _doc.getRootElement().getChild( "PeTimeSeriesList" ); - Element runoffTimeSeriesListElement = _doc.getRootElement().getChild( "RunoffTimeSeriesList" ); - Element monthlyValuesListElement = _doc.getRootElement().getChild( "MonthlyValuesList" ); - - Element sacParamsElement = null; - Element sacStateElement = null; - Element peTimeSeriesElement = null; - Element runoffTimeSeriesElement = null; - Element monthlyValuesElement = null; - - SacSmaParameters sacSmaParams = new SacSmaParameters(); - SacSmaState sacSmaState = new SacSmaState(); - MonthlyValues monthlyValues = new MonthlyValues(); - - List elementList = null; - -// --------- Processing Sac Parameters - - elementList = sacParamsListElement.getChildren( "SacParams" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - SacSmaParameters latestParams = null; - String basinId = null; - String source = null; - - sacParamsElement = (Element) elementList.get( i ); - sacSmaParams = retrieveSacSmaParams( sacParamsElement ); - basinId = sacSmaParams.getBasinId(); - source = sacSmaParams.getSource(); - - latestParams = _dataMgr.loadNewestSacSmaParams(basinId, source ); - if ( latestParams == null ) - { - _dataMgr.saveParams( sacSmaParams ); - } - else if ( ! latestParams.equalsValues( sacSmaParams ) ) - { - _dataMgr.saveParams( sacSmaParams ); - } - } - -// --------- Processing Sac States - - elementList = sacStateListElement.getChildren( "SacState" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - sacStateElement = (Element) elementList.get( i ); - sacSmaState = retrieveSacSmaState( sacStateElement ); - _dataMgr.saveState( sacSmaState ); - } - -// --------- Processing Pe Timeseries - - elementList = peTimeSeriesListElement.getChildren( "PeTimeSeries" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - peTimeSeriesElement = (Element) elementList.get( i ); - processPeTimeSeries( peTimeSeriesElement ); - } -// --------- Processing Runoff Timeseries - - elementList = runoffTimeSeriesListElement.getChildren( "RunoffTimeSeries" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - runoffTimeSeriesElement = (Element) elementList.get( i ); - processRunoffTimeSeries( runoffTimeSeriesElement ); - } - -// --------- Processing MonthlyValues - - elementList = monthlyValuesListElement.getChildren( "MonthlyValues" ); - for ( int i = 0; i < elementList.size(); i++ ) - { - monthlyValuesElement = (Element) elementList.get( i ); - monthlyValues = retrieveMonthlyValues( monthlyValuesElement ); - _dataMgr.saveMonthlyValues( monthlyValues ); - } - } - -// ----------------------------------------------------------------------------- - - private SacSmaParameters retrieveSacSmaParams( Element e ) - { - SacSmaParameters currentSacSmaParams = new SacSmaParameters(); - - currentSacSmaParams.setBasinId( getElementStringValue( e, "basinId" ) ); - currentSacSmaParams.setSource( getElementStringValue( e, "source" ) ); - currentSacSmaParams.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaParams.setPostingTime( System.currentTimeMillis() ); - currentSacSmaParams.setUztwm( getElementDoubleValue( e, "uztwm" ) ); - currentSacSmaParams.setUzfwm( getElementDoubleValue( e, "uzfwm" ) ); - currentSacSmaParams.setUzk( getElementDoubleValue( e, "uzk" ) ); - currentSacSmaParams.setPctim( getElementDoubleValue( e, "pctim" ) ); - currentSacSmaParams.setAdimp( getElementDoubleValue( e, "adimp" ) ); - currentSacSmaParams.setRiva( getElementDoubleValue( e, "riva" ) ); - currentSacSmaParams.setZperc( getElementDoubleValue( e, "zperc" ) ); - currentSacSmaParams.setRexp( getElementDoubleValue( e, "rexp" ) ); - currentSacSmaParams.setLztwm( getElementDoubleValue( e, "lztwm" ) ); - currentSacSmaParams.setLzfsm( getElementDoubleValue( e, "lzfsm" ) ); - currentSacSmaParams.setLzfpm( getElementDoubleValue( e, "lzfpm" ) ); - currentSacSmaParams.setLzsk( getElementDoubleValue( e, "lzsk" ) ); - currentSacSmaParams.setLzpk( getElementDoubleValue( e, "lzpk" ) ); - currentSacSmaParams.setPfree( getElementDoubleValue( e, "pfree" ) ); - currentSacSmaParams.setRserv( getElementDoubleValue( e, "rserv" ) ); - currentSacSmaParams.setSide( getElementDoubleValue( e, "side" ) ); - currentSacSmaParams.setPxadj( getElementDoubleValue( e, "pxadj" ) ); - currentSacSmaParams.setPeadj( getElementDoubleValue( e, "peadj" ) ); - currentSacSmaParams.setEfc( getElementDoubleValue( e, "efc" ) ); - - - return currentSacSmaParams; - } - -// ----------------------------------------------------------------------------- - - private SacSmaState retrieveSacSmaState( Element e ) - { - SacSmaState currentSacSmaState = new SacSmaState(); - - currentSacSmaState.setBasinId( getElementStringValue( e, "basinId") ); - currentSacSmaState.setSource( getElementStringValue( e, "source") ); - currentSacSmaState.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaState.setBasisTime( getElementLongTimeValue( e, "basisTime" ) ); - currentSacSmaState.setPostingTime( System.currentTimeMillis() ); - currentSacSmaState.setUztwc( getElementDoubleValue( e, "uztwc" ) ); - currentSacSmaState.setUzfwc( getElementDoubleValue( e, "uzfwc" ) ); - currentSacSmaState.setLztwc( getElementDoubleValue( e, "lztwc" ) ); - currentSacSmaState.setLzfsc( getElementDoubleValue( e, "lzfsc" ) ); - currentSacSmaState.setLzfpc( getElementDoubleValue( e, "lzfpc" ) ); - currentSacSmaState.setAdimc( getElementDoubleValue( e, "adimc" ) ); - - return currentSacSmaState; - } - -// ----------------------------------------------------------------------------- - - private MonthlyValues retrieveMonthlyValues( Element e ) - { - MonthlyValues currentMonthlyValues = new MonthlyValues(); - double[] valueArray = new double[ 12 ]; - - currentMonthlyValues.setBasinId( getElementStringValue( e, "locationId" ) ); - currentMonthlyValues.setPe( MONTHLY_VALUES_PE ); - currentMonthlyValues.setDur(MONTHLY_VALUES_DUR ); - currentMonthlyValues.setTs( MONTHLY_VALUES_TS ); - currentMonthlyValues.setExtremum( MONTHLY_VALUES_EXTREMUM ); - if ( getElementStringValue( e, "isAdjustment" ).equalsIgnoreCase( "TRUE" ) ) - { - currentMonthlyValues.setAdjustment( true ); - } - else - { - currentMonthlyValues.setAdjustment( false ); - } - currentMonthlyValues.setPostingTime( System.currentTimeMillis() ); - - valueArray[ 0 ] = getElementDoubleValue( e, "janValue" ); - valueArray[ 1 ] = getElementDoubleValue( e, "febValue" ); - valueArray[ 2 ] = getElementDoubleValue( e, "marValue" ); - valueArray[ 3 ] = getElementDoubleValue( e, "aprValue" ); - valueArray[ 4 ] = getElementDoubleValue( e, "mayValue" ); - valueArray[ 5 ] = getElementDoubleValue( e, "junValue" ); - valueArray[ 6 ] = getElementDoubleValue( e, "julValue" ); - valueArray[ 7 ] = getElementDoubleValue( e, "augValue" ); - valueArray[ 8 ] = getElementDoubleValue( e, "sepValue" ); - valueArray[ 9 ] = getElementDoubleValue( e, "octValue" ); - valueArray[ 10 ] = getElementDoubleValue( e, "novValue" ); - valueArray[ 11 ] = getElementDoubleValue( e, "decValue" ); - currentMonthlyValues.setValues( valueArray ); - - return currentMonthlyValues; - } - -// ----------------------------------------------------------------------------- - - private void processPeTimeSeries( Element e ) - { - String usedString = getElementStringValue( e, "isUsed" ); - boolean process = false; // Determines whether or not to process the TS - RegularTimeSeries peTimeSeries = null; - FcstTsDescriptor descriptor = new FcstTsDescriptor( "FcstOther" ); - - if ( usedString.trim().equalsIgnoreCase( "true" ) ) - { - process = true; - } - else - { - process = false; - } - - if ( process ) - { - String xmlUnitString = getElementStringValue( e, "units" ); - Element measurementListElement = e.getChild( "MeasurementList" ); - Element measurementElement = null; - List elementList = new ArrayList(); - Measurement measurement = null; - MeasuringUnit xmlMeasuringUnit = (MeasuringUnit) _unitsMap.get( xmlUnitString ); - - descriptor.setLid( getElementStringValue( e, "basinId" ) ); - descriptor.setPe( PE_TIMESERIES_PE_CODE ); - descriptor.setDur( getElementShortValue( e, "duration" ) ); - descriptor.setTs( TS ); - descriptor.setExtremum( EXTREMUM ); - descriptor.setProbability( PROBABILITY ); - descriptor.setBasistime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setShef_qual_code( SHEF_QUAL_CODE ); - descriptor.setQuality_code( GOOD_QC ); - descriptor.setRevision( REVISION ); - descriptor.setProduct_id( PRODUCT_ID ); - descriptor.setProducttime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setPostingtime( System.currentTimeMillis() ); - - elementList = measurementListElement.getChildren( "Measurement" ); - - for ( int i = 0; i < elementList.size(); i++ ) - { - measurementElement = (Element) elementList.get( i ); - double xmlValue = getElementDoubleValue( measurementElement, "value" ); - measurement = new Measurement( xmlValue, xmlMeasuringUnit ); - long time = getElementLongTimeValue( measurementElement, "time" ); - - if ( i == 0 ) - { - peTimeSeries = new RegularTimeSeries( time, time, INTERVAL_IN_HOURS, - DB_MEASURING_UNIT ); - } - peTimeSeries.setMeasurementByTime( measurement, time ); - } - _dataMgr.saveFcstTimeSeries( descriptor, peTimeSeries ); - - } // end if (process) - } - -// ----------------------------------------------------------------------------- - - private void processRunoffTimeSeries( Element e ) - { - String processString = getElementStringValue( e, "exists" ); - boolean process = false; // Determines whether or not to process the TS - RegularTimeSeries runoffTimeSeries = null; - FcstTsDescriptor descriptor = new FcstTsDescriptor( "FcstDischarge" ); - - if ( processString.trim().equalsIgnoreCase( "true" ) ) - { - process = true; - } - else - { - process = false; - } - - if ( process ) - { - String xmlUnitString = getElementStringValue( e, "units" ); - Element measurementListElement = e.getChild( "MeasurementList" ); - Element measurementElement = null; - List elementList = new ArrayList(); - Measurement measurement = null; - MeasuringUnit xmlMeasuringUnit = (MeasuringUnit) _unitsMap.get( xmlUnitString ); - - descriptor.setLid( getElementStringValue( e, "basinId" ) ); - descriptor.setPe( RUNOFF_TIMESERIES_PE_CODE ); - descriptor.setDur( getElementShortValue( e, "duration" ) ); - descriptor.setTs( TS ); - descriptor.setExtremum( EXTREMUM ); - descriptor.setProbability( PROBABILITY ); - descriptor.setBasistime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setShef_qual_code( SHEF_QUAL_CODE ); - descriptor.setQuality_code( GOOD_QC ); - descriptor.setRevision( REVISION ); - descriptor.setProduct_id( PRODUCT_ID ); - descriptor.setProducttime( getElementLongTimeValue( e, "basisTime" ) ); - descriptor.setPostingtime( System.currentTimeMillis() ); - - elementList = measurementListElement.getChildren( "Measurement" ); - - for ( int i = 0; i < elementList.size(); i++ ) - { - measurementElement = (Element) elementList.get( i ); - double xmlValue = getElementDoubleValue( measurementElement, "value" ); - measurement = new Measurement( xmlValue, xmlMeasuringUnit ); - long time = getElementLongTimeValue( measurementElement, "time" ); - - if ( i == 0 ) - { - runoffTimeSeries = new RegularTimeSeries( time, time, INTERVAL_IN_HOURS, - DB_MEASURING_UNIT ); - } - runoffTimeSeries.setMeasurementByTime( measurement, time ); - } - //only save this time series to the database if the duration is correct - if (descriptor.getDur() == 1001) - { - _dataMgr.saveFcstTimeSeries( descriptor, runoffTimeSeries ); - } - } - } - -// ----------------------------------------------------------------------------- - - private String getElementStringValue( Element e, String subElementName ) - { - return e.getChildTextTrim( subElementName ); - } - -// ----------------------------------------------------------------------------- - - private double getElementDoubleValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Double.parseDouble( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private int getElementIntValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Integer.parseInt( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - private short getElementShortValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Short.parseShort( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private long getElementLongTimeValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return DbTimeHelper.getLongTimeFromDateTimeString( attributeValueString ); - } - -// ----------------------------------------------------------------------------- - - public String toString() - { - StringWriter stringWriter = new StringWriter(); - XMLOutputter outputter = new XMLOutputter(); - String returnValue = null; - - try - { - outputter.setTextTrim( true ); - outputter.setIndent( " " ); - outputter.setNewlines( true ); - outputter.output( _doc, stringWriter ); - returnValue = stringWriter.toString(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - - return returnValue; - } - -// ----------------------------------------------------------------------------- - - private void connect() - { - _dataMgr = new DecoderDataMgr( _connectionString, _logger ); - } - - private void disconnect() - { - _dataMgr = new DecoderDataMgr( _connectionString, _logger ); - } - - private boolean validateInputParameters( String[] args ) - { - String inputDir = null; - String archiveDir = null; - String logDir = null; - String sleepTimeString = null; - long sleepTimeLong = 0; - File directory = null; - boolean returnValue = true; - - if ( args.length < 3 ) - { - System.out.println( "SacXMLDecoder [ ] " ); - returnValue = false; - } - else - { - _connectionString = args[ 0 ]; - - inputDir = args[ 1 ]; - - directory = new File( inputDir ); - if ( directory.exists() ) - { - _inputDir = inputDir; - } - else - { - System.err.println( "You must specify a valid input directory" ); - returnValue = false; - } - - archiveDir = args[ 2 ]; - - directory = new File( archiveDir ); - if ( directory.exists() ) - { - _archiveDir = archiveDir; - } - else - { - System.err.println( "You must specify a valid archive directory" ); - returnValue = false; - } - - logDir = args[ 3 ]; - directory = new File( logDir ); - if ( directory.exists() ) - { - _logFullPath = logDir + "/SacXMLDecoder.log"; - } - else - { - System.err.println( "You must specify a valid log directory" ); - returnValue = false; - } - - - if ( args.length > 4 ) - { - sleepTimeString = args[ 4 ]; - try - { - sleepTimeLong = Long.parseLong( sleepTimeString ); - _sleepTime = sleepTimeLong; - _isTest = true; - } - catch ( NumberFormatException e ) - { - System.err.println( "Invalid sleep time specified. Defaulting to 60 seconds" ); - _sleepTime = 60000; - } - } - else - { - _isTest = false; - } - } // end else - - return returnValue; - } - - - - public static void main( String[] args ) - { - SacXMLDecoder sacDecoder = new SacXMLDecoder( args[ 0 ] ); - boolean validInputParameters = false; - - validInputParameters = sacDecoder.validateInputParameters( args ); - - if ( validInputParameters ) - { - sacDecoder.execute(); - } - - System.exit( 0 ); - } - - -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java deleted file mode 100644 index 8ad5edb10b..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java +++ /dev/null @@ -1,669 +0,0 @@ -/* - * Created on Feb 26, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : March 16, 2004 - * Revised: - * Chip Gobs March 16, 2005 (exactly 1 year later!) - * added variables _paramsValidTime and _timeSeriesBasisTime - * now use them instead of using _extractionTime directly for SacSmaParams validTime and - * PE and Runoff time series basistime. - * The _timeSeriesBasisTime variable is set to _extractionTime, but _paramsValidTime is the - * 00:00:00 of the same date as _extractionTime - */ - -package ohd.hseb.sshp.messaging; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.StringParser; - -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.output.XMLOutputter; - -import java.io.*; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -public class SacXMLEncoder -{ - private String _basinId = null; - private String _extractFileName = null; - private Document _doc = null; - - private BufferedReader _reader = null; - - private final long HOUR_IN_MILLIS = 1 * 60 * 60 * 1000; - private final long MILLIS_PER_DAY = 24 * HOUR_IN_MILLIS; - private final String SOURCE = "RFC"; - private long _extractionTime = 0; - private long _paramsValidTime = 0; - private long _timeSeriesBasisTime = 0; - // private String _executionTimeString = null; - private FileLogger _logger = null; - - // --------------------------------------------------------------------- - - public SacXMLEncoder( String basinId, String extractFileName, Document outputXMLDocument, FileLogger logger ) - { - _basinId = basinId; - _extractFileName = extractFileName; - _doc = outputXMLDocument; - _logger = logger; - _logger.log( "" ); - //_executionTimeString = DbTimeHelper.getDateTimeStringFromLongTime( System.currentTimeMillis() ); - } - - // --------------------------------------------------------------------- - - public void parse() throws OfsFileParserException - { -// writeXmlToFile( _doc, "D:/data/xmlencoderoutput.txt" ); - - try - { - _reader = new BufferedReader( new FileReader( _extractFileName ) ); - - Element rootElement = _doc.getRootElement(); - Element runoffTimeSeriesListElement = rootElement.getChild( "RunoffTimeSeriesList" ); - Element peTimeSeriesListElement = rootElement.getChild( "PeTimeSeriesList" ); - Element sacParamsListElement = rootElement.getChild( "SacParamsList" ); - Element sacStateListElement = rootElement.getChild( "SacStateList" ); - Element monthlyValuesListElement = rootElement.getChild( "MonthlyValuesList" ); - - String line = findLine( "Extracted on" ); - - if ( line == null ) - { - throw new OfsFileParserException( "line empty" ); - } - - int index = getNextCharIndex(line,"Extracted on"); - if ( index >= 0 ) - { - _extractionTime = parseTimeString( line.substring( index, line.length() ) ); - - //set to the same as the extraction time, since we don't have anything better - _timeSeriesBasisTime = _extractionTime; - - //round back to the beginning of the same day, - //so that whatever parameters we have for that day will be usable with - //the latest states of that day - _paramsValidTime = _extractionTime /= MILLIS_PER_DAY; - _paramsValidTime *= MILLIS_PER_DAY; - - - } - - _logger.log( "Parsing " + _extractFileName ); - _logger.log( "-----" ); - line = _reader.readLine(); - - if ( line == null ) - { - throw new OfsFileParserException( "line empty" ); - } - - parseRunoffTimeSeries( runoffTimeSeriesListElement ); - parsePeTimeSeries( peTimeSeriesListElement ); - parseMonthlyValues( monthlyValuesListElement ); - parseSacParams( sacParamsListElement ); - parseSacState( sacStateListElement ); - } - - catch ( OfsFileParserException e ) - { - _logger.log( _extractFileName + " is not a complete extracted file" ); - throw new OfsFileParserException( "line empty" ); - } - - catch ( FileNotFoundException e ) - { - _logger.log( _extractFileName + " not found." ); - e.printStackTrace( _logger.getPrintWriter() ); //we will add this to everything later - } - catch ( IOException e ) - { - _logger.log( "Unable to read from " + _extractFileName ); - e.printStackTrace( _logger.getPrintWriter() ); - } - - finally - { - try - { - _reader.close(); - } - catch ( IOException e ) - { - _logger.log( "Unable to close " + _extractFileName ); - } - } - - - } - - // --------------------------------------------------------------------- - - private long parseTimeString( String timeString ) - { - // example: String format = "yyyy-MM-dd HH:mm:ss" - String formatString = "MM/dd/yyyy HHmm"; - SimpleDateFormat sdf = new SimpleDateFormat( formatString ); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - long time = 0; - - try - { - time = sdf.parse( timeString ).getTime(); - } - catch ( ParseException e ) - { - e.printStackTrace(); - } - - return time; - } - - // --------------------------------------------------------------------- - private int getNextCharIndex(String line, String searchString) - { - int index = line.indexOf(searchString); - if (index > -1) - { - index += searchString.length(); - } - - return index; - } - // --------------------------------------------------------------------- - private void parseRunoffTimeSeries( Element runoffTimeSeriesListElement ) - { - String line = null; - int duration = 0; - - Element roTimeSeriesElement = new Element( "RunoffTimeSeries" ); - Element measurementListElement = new Element( "MeasurementList" ); - - findLine( "RO Time Series Begin" ); // Searches the input file for the string passed in - - try - { - //read next line - line = _reader.readLine(); - if ( line.startsWith( "No RO time series" ) ) - { - roTimeSeriesElement.addContent(getElement("basinId", _basinId)); - roTimeSeriesElement.addContent( getElement( "exists", "FALSE" ) ); - } - else // there is a Runoff time series - { - _logger.log( "Extracting RO Timeseries" ); - roTimeSeriesElement.addContent(getElement("exists", "TRUE")); - roTimeSeriesElement.addContent(getElement("basinId", _basinId)); - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( _timeSeriesBasisTime ); - roTimeSeriesElement.addContent(getElement("basisTime", timeString)); - - int index = getNextCharIndex( line, "Step=" ); - - if ( index > -1 ) - { - String durationString = line.substring( index, index + 2 ).trim(); - duration = Integer.parseInt( durationString ); - roTimeSeriesElement.addContent( getElement( "duration", getDuration( durationString ) ) ); - } - - index = getNextCharIndex( line,"Data Units=" ); - - if ( index > -1 ) - { - String unitsString = line.substring(index).toLowerCase().trim(); - roTimeSeriesElement.addContent(getElement("units", unitsString)); - } - - - roTimeSeriesElement.addContent( measurementListElement ); - - line = _reader.readLine(); - // parses the start and end time for the measurements - String measurementTimeString = null; - int startIndex = getNextCharIndex( line, "Time=" ); - int endIndex = getNextCharIndex( line, "Z" ); - measurementTimeString = line.substring( startIndex, endIndex - 1 ).trim(); - long measurementTimeLong = parseTimeString( measurementTimeString + "00" ); - - startIndex = getNextCharIndex( line, "Count=" ); - endIndex = startIndex + 2; - - line = _reader.readLine(); - index = getNextCharIndex( line, "Values=" ); - line = line.substring( index, line.length() ); - - while ( ! line.startsWith( "RO Time Series End" ) ) - { - String[] valueStringArray = StringParser.tokenize( line ); - - for ( int i = 0; i < valueStringArray.length; i++ ) - { - Element measurementElement = new Element( "Measurement" ); - measurementElement.addContent( getElement( "time", DbTimeHelper.getDateTimeStringFromLongTime( measurementTimeLong ) ) ); - measurementTimeLong += duration * HOUR_IN_MILLIS; - measurementElement.addContent( getElement( "value", valueStringArray[ i ] ) ); - measurementListElement.addContent( measurementElement ); - } - line = _reader.readLine(); - } - } // close bracket for else statement - - if ( duration == 1) //accept only 1-hour durations - { - runoffTimeSeriesListElement.addContent( roTimeSeriesElement ); - } - else //put in an empty time series, because the time series that exists has the wrong duration, usually 6 hours instead of 1 - { - Element emptyRoTimeSeriesElement = new Element( "RunoffTimeSeries" ); - emptyRoTimeSeriesElement.addContent(getElement("basinId", _basinId)); - emptyRoTimeSeriesElement.addContent( getElement( "exists", "FALSE" ) ); - runoffTimeSeriesListElement.addContent( emptyRoTimeSeriesElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - - // --------------------------------------------------------------------- - private void parsePeTimeSeries( Element peTimeSeriesListElement ) - { - String line = null; - int duration = 0; - - Element peTimeSeriesElement = new Element( "PeTimeSeries" ); - Element measurementListElement = new Element( "MeasurementList" ); - - findLine( "PE Time Series Begin" ); // Searches the input file for the string passed in - - try - { - //read next line - line = _reader.readLine(); - if ( line.startsWith( "No PE Time Series" ) ) - { - peTimeSeriesElement.addContent(getElement("basinId", _basinId)); - peTimeSeriesElement.addContent(getElement("isUsed", "FALSE")); - } - else // there is a PE time series - { - _logger.log( "Extracting PE Timeseries" ); - peTimeSeriesElement.addContent(getElement("isUsed", "TRUE")); - peTimeSeriesElement.addContent(getElement("basinId", _basinId)); - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( _timeSeriesBasisTime ); - peTimeSeriesElement.addContent(getElement("basisTime", timeString)); - - int index = getNextCharIndex( line, "Step=" ); - - if ( index > -1 ) - { - String durationString = line.substring( index, index + 2 ).trim(); - duration = Integer.parseInt( durationString ); - peTimeSeriesElement.addContent( getElement( "duration", getDuration( durationString ) ) ); - } - - index = getNextCharIndex( line,"Data Units=" ); - - if ( index > -1 ) - { - String unitsString = line.substring(index).toLowerCase().trim(); - peTimeSeriesElement.addContent(getElement("units", unitsString)); - } - - - peTimeSeriesElement.addContent( measurementListElement ); - - line = _reader.readLine(); - // parses the start and end time for the measurements - String measurementTimeString = null; - int startIndex = getNextCharIndex( line, "Time=" ); - int endIndex = getNextCharIndex( line, "Z" ); - measurementTimeString = line.substring( startIndex, endIndex - 1 ).trim(); - long measurementTimeLong = parseTimeString( measurementTimeString + "00" ); - - startIndex = getNextCharIndex( line, "Count=" ); - endIndex = startIndex + 2; - - line = _reader.readLine(); - index = getNextCharIndex( line, "Values=" ); - line = line.substring( index, line.length() ); - - while ( ! line.startsWith( "PE Time Series End" ) ) - { - String[] valueStringArray = StringParser.tokenize( line ); - - for ( int i = 0; i < valueStringArray.length; i++ ) - { - Element measurementElement = new Element( "Measurement" ); - measurementElement.addContent( getElement( "time", DbTimeHelper.getDateTimeStringFromLongTime( measurementTimeLong ) ) ); - measurementTimeLong += duration * HOUR_IN_MILLIS; - measurementElement.addContent( getElement( "value", valueStringArray[ i ] ) ); - measurementListElement.addContent( measurementElement ); - } - line = _reader.readLine(); - } - - } - peTimeSeriesListElement.addContent(peTimeSeriesElement); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - private Element getElement(String elementName, String elementText) - { - Element element = new Element(elementName); - element.setText(elementText); - - return element; - } - - // --------------------------------------------------------------------- - - private void parseMonthlyValues( Element monthlyValuesListElement ) - { - // this is not done yet - work on this Gautam - String line = null; - boolean done = false; - Element monthlyValuesElement = new Element( "MonthlyValues" ); - String[] valuesStringArray = null; - - findLine( "Monthly Values Begin" ); - - try - { - line = _reader.readLine(); - if ( line != null ) - { - if ( line.startsWith( "No Monthly Values" ) ) - { - done = true; - } - else // there are monthly Values - { - _logger.log( "Extracting MonthlyValues" ); - monthlyValuesElement.addContent( getElement( "locationId", _basinId ) ); - int index = getNextCharIndex( line, "Type=" ); - String isAdjustmentString = line.substring( index, line.length() ); - if ( isAdjustmentString.startsWith( "PE Adjustment" ) ) - { - monthlyValuesElement.addContent( getElement( "isAdjustment", "TRUE" ) ); - } - else - { - monthlyValuesElement.addContent( getElement( "isAdjustment", "FALSE" ) ); - } - - line = _reader.readLine(); - valuesStringArray = StringParser.tokenize( line ); - - monthlyValuesElement.addContent( getElement( "janValue", valuesStringArray[ 0 ] ) ); - monthlyValuesElement.addContent( getElement( "febValue", valuesStringArray[ 1 ] ) ); - monthlyValuesElement.addContent( getElement( "marValue", valuesStringArray[ 2 ] ) ); - monthlyValuesElement.addContent( getElement( "aprValue", valuesStringArray[ 3 ] ) ); - monthlyValuesElement.addContent( getElement( "mayValue", valuesStringArray[ 4 ] ) ); - monthlyValuesElement.addContent( getElement( "junValue", valuesStringArray[ 5 ] ) ); - monthlyValuesElement.addContent( getElement( "julValue", valuesStringArray[ 6 ] ) ); - monthlyValuesElement.addContent( getElement( "augValue", valuesStringArray[ 7 ] ) ); - monthlyValuesElement.addContent( getElement( "sepValue", valuesStringArray[ 8 ] ) ); - monthlyValuesElement.addContent( getElement( "octValue", valuesStringArray[ 9 ] ) ); - monthlyValuesElement.addContent( getElement( "novValue", valuesStringArray[ 10 ] ) ); - monthlyValuesElement.addContent( getElement( "decValue", valuesStringArray[ 11 ] ) ); - done = true; - } - } - if ( done ) - { - monthlyValuesListElement.addContent( monthlyValuesElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - private void parseSacParams(Element sacParamsListElement) - { - String line = null; - boolean done = false; - Element sacParamsElement = new Element( "SacParams" ); - - findLine( "SAC Params Begin" ); - - try - { - line = _reader.readLine(); - if ( line != null ) - { - _logger.log( "Extracting SacSmaParameters" ); - sacParamsElement.addContent( getElement( "basinId", _basinId ) ); - sacParamsElement.addContent( getElement( "source", SOURCE ) ); - sacParamsElement.addContent( getElement( "validTime", DbTimeHelper.getDateTimeStringFromLongTime( _paramsValidTime ) ) ); - - if ( ! line.startsWith( "No SAC Params" ) ) - { - while ( ! line.startsWith( "SAC Params End" ) ) - { - int index = getNextCharIndex( line, "=" ); - String paramString = line.substring( 0, index - 1 ).trim().toLowerCase(); - String valueString = line.substring( index, line.length() ).trim(); - sacParamsElement.addContent( getElement( paramString, valueString ) ); - line = _reader.readLine(); - } - done = true; - } - } - if ( done ) - { - sacParamsListElement.addContent( sacParamsElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - - } - - // --------------------------------------------------------------------- - private void parseSacState( Element sacStateListElement ) - { - String line = null; - boolean done = false; - Element sacStateElement = new Element( "SacState" ); - long validTime = 0; - - findLine( "SAC State Begin" ); - try - { - line = _reader.readLine(); - if ( line != null ) - { - _logger.log( "Extracting SacSmaState" ); - sacStateElement.addContent( getElement( "basinId", _basinId ) ); - sacStateElement.addContent( getElement( "source", SOURCE ) ); - int dateIndex = getNextCharIndex( line, "date=" ); - String dateString = line.substring( dateIndex, line.length() ).trim(); - dateString = dateString.substring( 0, dateString.length() - 1 ); - long nonRoundedCarryOverDateTimeLong = parseTimeString( dateString + "00" ); - - - long carryOverDateTimeLong = getRoundedValidTime( nonRoundedCarryOverDateTimeLong ); - if ( carryOverDateTimeLong != nonRoundedCarryOverDateTimeLong ) - { - _logger.log( "Original valid time was NOT 12Z!" ); - } - sacStateElement.addContent( getElement( "validTime", DbTimeHelper.getDateTimeStringFromLongTime( carryOverDateTimeLong ) ) ); - sacStateElement.addContent( getElement( "basisTime", DbTimeHelper.getDateTimeStringFromLongTime( carryOverDateTimeLong ) ) ); - - line = _reader.readLine(); - - if ( ! line.startsWith( "No SAC States" ) ) - { - while ( ! line.startsWith( "SAC State End" ) ) - { - int index = getNextCharIndex( line, "=" ); - String stateString = line.substring( 0, index - 1 ).trim().toLowerCase(); - String valueString = line.substring( index, line.length() ).trim(); - sacStateElement.addContent( getElement( stateString, valueString ) ); - line = _reader.readLine(); - } - done = true; - } - } - if ( done ) - { - sacStateListElement.addContent( sacStateElement ); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - private long getRoundedValidTime( long extractionTime ) - { - long validTime = extractionTime; - - validTime /= MILLIS_PER_DAY; - validTime *= MILLIS_PER_DAY; - validTime += ( MILLIS_PER_DAY / 2 ); - if ( validTime > extractionTime ) - { - validTime -= MILLIS_PER_DAY; - } - return validTime; - } - - // --------------------------------------------------------------------- - - private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) - { - XMLOutputter _xmlOutputter = new XMLOutputter(" ", true); - - try - { - FileWriter writer = new FileWriter(xmlFileName); - _xmlOutputter.output(outputXmlDoc, writer); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - - - private static Document getBaseDocument() - { - //this is used only for testing - - Document doc = new Document(); - - Element rootElement = new Element("SacModelMessage"); - - doc.setRootElement(rootElement); - - Element sacParamsListElement = new Element("SacParamsList"); - Element sacStateListElement = new Element("SacStateList"); - Element peTimeSeriesListElement = new Element("PeTimeSeriesList"); - Element runoffTimeSeriesElement = new Element("RunoffTimeSeriesList"); - Element monthlyValuesListElement = new Element("MonthlyValuesList"); - - rootElement.addContent(sacParamsListElement); - rootElement.addContent(sacStateListElement); - rootElement.addContent(peTimeSeriesListElement); - rootElement.addContent(runoffTimeSeriesElement); - rootElement.addContent(monthlyValuesListElement); - - return doc; - } - - // --------------------------------------------------------------------- - - private String findLine( String searchString ) - { - String line = null; - try - { - line = _reader.readLine(); - while ( ! line.startsWith( searchString ) ) - { - line = _reader.readLine(); - } - } - catch ( IOException e ) - { - e.printStackTrace(); - line = null; - } - return line; - } - - // --------------------------------------------------------------------- - - private String getDuration( String durationString ) - { - int duration = Integer.parseInt( durationString ); - duration += 1000; - return ( "" + duration ); - } - - // --------------------------------------------------------------------- - - public static void main(String[] args) - { - String extractedFileName = null; - String processedFileName = null; - SacXMLEncoder encoder = null; - - String basinId = null; - - Document xmlOutputDoc = getBaseDocument(); - - // file1 - extractedFileName = "D:/Data/SacEncoderInput/BLAS.txt"; -// extractedFileName = args[ 0 ]; - basinId = "BLASE"; - encoder = new SacXMLEncoder( basinId, extractedFileName, xmlOutputDoc, new FileLogger( "D:/data/log/SacXMLEncoder.log", true, true ) ); - try - { - encoder.parse(); - } - catch( OfsFileParserException e ) - { - } - - - // write out the output - processedFileName = "D:/Data/XMLFiles/BLASE.xml"; -// processedFileName = "/fs/home/gsood/processed_SJU.xml"; - encoder.writeXmlToFile( xmlOutputDoc, processedFileName ); - - } - - // --------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java deleted file mode 100644 index ef321f773d..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java +++ /dev/null @@ -1,544 +0,0 @@ -/* - * Created on Sep 11, 2003 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : March 16, 2004 - * Purpose: Decodes XML input files and posts the data to the database. - */ - -package ohd.hseb.sshp.messaging; - -import org.jdom.input.SAXBuilder; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.output.XMLOutputter; - -import java.io.*; -import java.util.*; -import java.util.Date; - -import ohd.hseb.measurement.*; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.sacsma.*; -import ohd.hseb.db.*; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.TimeHelper; - - -public class SacXMLTester -{ - private String _inputDir = null; - private String _archiveDir = null; - private String _logFullPath = null; - private long _sleepTime = 0; - private Document _inputXMLDoc = null; - private Document _outputXMLDoc = null; - private String backupInputFilePath = null; - private String _inputXMLFileName = null; - private boolean _isTest = true; - private String _basinID = null; - - private static final String PE_TIMESERIES_PE_CODE = "EA"; - private static final String RUNOFF_TIMESERIES_PE_CODE = "QB"; - private static final String TS = "FZ"; - private static final String EXTREMUM = "Z"; - private static final float PROBABILITY = -1.0f; - private static final String SHEF_QUAL_CODE = "Z"; - private static final int GOOD_QC = 1879048191; - private static final short REVISION = 0; - private static final String PRODUCT_ID = "SSHP_XFER"; - - private static final String MONTHLY_VALUES_TS = "FZ"; - private static final String MONTHLY_VALUES_EXTREMUM = "Z"; - private static final String MONTHLY_VALUES_PE = "EA"; - private static final short MONTHLY_VALUES_DUR = 2001; - private static final MeasuringUnit DB_MEASURING_UNIT = MeasuringUnit.inches; - private static final int INTERVAL_IN_HOURS = 1; - - private static Map _unitsMap = new HashMap(); - - private FileLogger _logger = null; - - private DecoderDataMgr _dataMgr = null; - - - - - - public SacXMLTester( String inputXMLFileName, Document xmlOutputDoc, String logFileName ) - { - _inputXMLFileName = inputXMLFileName; - _outputXMLDoc = xmlOutputDoc; - _logFullPath = logFileName; - } - - private void execute() - { - File backupInputFile = null; - SAXBuilder builder = new SAXBuilder(); - File inputFile = null; - Date time = new Date(); - boolean keepFileOpen = true; - boolean appendDateTime = true; - CodeTimer timer1 = null; - - _logger = new FileLogger( _logFullPath, keepFileOpen, appendDateTime ); - timer1 = new CodeTimer( _logger ); - - initUnitsMap(); - - try - { - builder.setExpandEntities( true ); - _logger.log( "Processing " + _inputXMLFileName ); - timer1.start(); - - _inputXMLDoc = builder.build( _inputXMLFileName ); - parseXMLFiles(); - backupInputFile = new File( _archiveDir + "/" + _inputXMLFileName ); - if ( backupInputFile.isFile() ) - { - backupInputFile = new File( backupInputFilePath + _inputXMLFileName + "_" + time.getTime() ); - } - inputFile = new File( _inputXMLFileName ); - inputFile.renameTo( backupInputFile ); - timer1.stop( "Finished processing " + _inputXMLFileName + " in " ); - } - catch ( JDOMException e ) - { - _logger.log( " " + _inputXMLFileName + " is not a valid XML file." ); - } - - catch ( IOException e ) - { - e.printStackTrace(); - } - } - - private void initUnitsMap() - { - _unitsMap.put( new String( "mm" ), MeasuringUnit.mm ); - _unitsMap.put( new String( "cm" ), MeasuringUnit.cm ); - _unitsMap.put( new String( "m" ), MeasuringUnit.meters ); - _unitsMap.put( new String( "in" ), MeasuringUnit.inches ); - _unitsMap.put( new String( "ft" ), MeasuringUnit.feet ); - } - - private void parseXMLFiles() - { - Element inputSacParamsListElement = _inputXMLDoc.getRootElement().getChild( "SacParamsList" ); - Element inputSacStateListElement = _inputXMLDoc.getRootElement().getChild( "SacStateList" ); - Element monthlyValuesListElement = _inputXMLDoc.getRootElement().getChild( "MonthlyValuesList" ); - - Element outputRootElement = _outputXMLDoc.getRootElement(); - Element outputSacParamsListElement = outputRootElement.getChild( "SacParamsList" ); - Element outputSacStateListElement = outputRootElement.getChild( "SacStateList" ); - Element outputMonthlyValuesListElement = outputRootElement.getChild( "MonthlyValuesList" ); - Element outputPETimeSeriesListElement = outputRootElement.getChild( "PeTimeSeriesList" ); - Element outputRunoffTimeSeriesElement = outputRootElement.getChild( "RunoffTimeSeriesList" ); - - Element sacParamsElement = null; - Element sacStateElement = null; - Element peTimeSeriesElement = null; - Element runoffTimeSeriesElement = null; - Element monthlyValuesElement = null; - - SacSmaParameters sacSmaParamsToBeCopied = new SacSmaParameters(); - SacSmaState sacSmaStateToBeCopied = new SacSmaState(); - RegularTimeSeries peTimeSeries = null; - RegularTimeSeries roTimeSeries = null; - - Random generator = new Random(); - - List elementList = null; - - - -// --------- Processing Sac Parameters - - elementList = inputSacParamsListElement.getChildren( "SacParams" ); - - Element outputSacParamsElement = null; - for ( int i = 0; i < elementList.size(); i++ ) - { - sacParamsElement = (Element) elementList.get( i ); - - sacSmaParamsToBeCopied = retrieveSacSmaParams( sacParamsElement ); - outputSacParamsElement = convertSacSmaParamsToSacSmaParamsElement( sacSmaParamsToBeCopied ); - outputSacParamsListElement.addContent( outputSacParamsElement ); - } - - _basinID = sacSmaParamsToBeCopied.getBasinId(); -// --------- Processing Sac States - elementList = inputSacStateListElement.getChildren( "SacState" ); - Element outputSacStateElement = null; - - for ( int i = 0; i < elementList.size(); i++ ) - { - sacStateElement = (Element) elementList.get( i ); - - sacSmaStateToBeCopied = retrieveSacSmaState( sacStateElement ); - outputSacStateElement = convertSacSmaStateToSacSmaStateElement( sacSmaStateToBeCopied ); - - outputSacStateListElement.addContent( outputSacStateElement ); - } - -// --------- Processing MonthlyValues - - elementList = monthlyValuesListElement.getChildren( "MonthlyValues" ); - Element outputMonthlyValuesElement = null; - - for ( int i = 0; i < elementList.size(); i++ ) - { - monthlyValuesElement = (Element) elementList.get( i ); - - outputMonthlyValuesElement = (Element) monthlyValuesElement.clone(); - - outputMonthlyValuesListElement.addContent( outputMonthlyValuesElement ); - } - -// --------- Processing Pe Timeseries - - long endTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - long startTime = endTime - ( 100 * TimeHelper.MILLIS_PER_HOUR ); - long validTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - Element measurementListElement = new Element( "MeasurementList" ); - - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime( validTime ); - - peTimeSeries = new RegularTimeSeries(startTime, endTime, INTERVAL_IN_HOURS, DB_MEASURING_UNIT ); - - peTimeSeriesElement = new Element( "PeTimeSeries" ); - peTimeSeriesElement.addContent( getElement( "isUsed", "TRUE" ) ); - peTimeSeriesElement.addContent( getElement( "basinId", _basinID ) ); - peTimeSeriesElement.addContent( getElement( "basisTime", validTimeString ) ); - peTimeSeriesElement.addContent( getElement( "duration", "1024" ) ); - peTimeSeriesElement.addContent( getElement( "units", "mm" ) ); - peTimeSeriesElement.addContent( measurementListElement ); - - for ( long timeIndex = startTime; timeIndex <= endTime; timeIndex += TimeHelper.MILLIS_PER_HOUR ) - { - double randomNumber = Math.random() * 3; - double value = ( Math.round ( randomNumber * 1000.0 ) ) / 1000.0; - - Element measurementElement = new Element( "Measurement" ); - - measurementElement.addContent( getElement ( "time", DbTimeHelper.getDateTimeStringFromLongTime( timeIndex ) ) ); - measurementElement.addContent( getElement( "value", Double.toString( value ) ) ); - measurementListElement.addContent( measurementElement ); - } - - outputPETimeSeriesListElement.addContent( peTimeSeriesElement ); - - -// --------- Processing Runoff Timeseries - - measurementListElement = new Element( "MeasurementList" ); - - roTimeSeries = new RegularTimeSeries(startTime, endTime, INTERVAL_IN_HOURS, DB_MEASURING_UNIT ); - - runoffTimeSeriesElement = new Element( "RunoffTimeSeries" ); - runoffTimeSeriesElement.addContent( getElement( "exists", "TRUE" ) ); - runoffTimeSeriesElement.addContent( getElement( "basinId", _basinID ) ); - runoffTimeSeriesElement.addContent( getElement( "basisTime", validTimeString ) ); - runoffTimeSeriesElement.addContent( getElement( "duration", "1024" ) ); - runoffTimeSeriesElement.addContent( getElement( "units", "mm" ) ); - runoffTimeSeriesElement.addContent( measurementListElement ); - - for ( long timeIndex = startTime; timeIndex <= endTime; timeIndex += TimeHelper.MILLIS_PER_HOUR ) - { - double randomNumber = Math.random() * 3; - double value = ( Math.round ( randomNumber * 1000.0 ) ) / 1000.0; - - Element measurementElement = new Element( "Measurement" ); - - measurementElement.addContent( getElement ( "time", DbTimeHelper.getDateTimeStringFromLongTime( timeIndex ) ) ); - measurementElement.addContent( getElement( "value", Double.toString( value ) ) ); - measurementListElement.addContent( measurementElement ); - } - - outputRunoffTimeSeriesElement.addContent( runoffTimeSeriesElement ); - - } - -// ----------------------------------------------------------------------------- - - private Element convertSacSmaParamsToSacSmaParamsElement( SacSmaParameters params ) - { - Element element = new Element ( "SacParams" ); - - long validTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime( validTime ); - - - element.addContent( getElement( "basinId", params.getBasinId() ) ); - element.addContent( getElement( "source", params.getSource() ) ); - element.addContent( getElement( "validTime", validTimeString ) ); - element.addContent( getElement( "pxadj", Double.toString( params.getPxadj() ) ) ); - element.addContent( getElement( "peadj", Double.toString( params.getPeadj() ) ) ); - element.addContent( getElement( "uztwm", Double.toString( params.getUztwm() ) ) ); - element.addContent( getElement( "uzfwm", Double.toString( params.getUzfwm() ) ) ); - element.addContent( getElement( "uzk", Double.toString( params.getUzk() ) ) ); - element.addContent( getElement( "pctim", Double.toString( params.getPctim() ) ) ); - element.addContent( getElement( "adimp", Double.toString( params.getAdimp() ) ) ); - element.addContent( getElement( "riva", Double.toString( params.getRiva() ) ) ); - element.addContent( getElement( "zperc", Double.toString( params.getZperc() ) ) ); - element.addContent( getElement( "rexp", Double.toString( params.getRexp() ) ) ); - element.addContent( getElement( "lztwm", Double.toString( params.getLztwm() ) ) ); - element.addContent( getElement( "lzfsm", Double.toString( params.getLzfsm() ) ) ); - element.addContent( getElement( "lzfpm", Double.toString( params.getLzfpm() ) ) ); - element.addContent( getElement( "lzsk", Double.toString( params.getLzsk() ) ) ); - element.addContent( getElement( "lzpk", Double.toString( params.getLzpk() ) ) ); - element.addContent( getElement( "pfree", Double.toString( params.getPfree() ) ) ); - element.addContent( getElement( "rserv", Double.toString( params.getRserv() ) ) ); - element.addContent( getElement( "side", Double.toString( params.getSide() ) ) ); -// element.addContent( getElement( "ioptet", Double.toString( params.get() ) ) ); - element.addContent( getElement( "efc", Double.toString( params.getEfc() ) ) ); - - return element; - } - - private Element convertSacSmaStateToSacSmaStateElement( SacSmaState state ) - { - Element element = new Element ( "SacState" ); - - long validTime = TimeHelper.roundTimeInMillisToNearestHour( System.currentTimeMillis() ); - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime( validTime ); - - element.addContent( getElement( "basinId", state.getBasinId() ) ); - element.addContent( getElement( "source", state.getSource() ) ); - element.addContent( getElement( "validTime", validTimeString ) ); - element.addContent( getElement( "basisTime", validTimeString ) ); - element.addContent( getElement( "uztwc", Double.toString( state.getUztwc() ) ) ); - element.addContent( getElement( "uzfwc", Double.toString( state.getUzfwc() ) ) ); - element.addContent( getElement( "lztwc", Double.toString( state.getLztwc() ) ) ); - element.addContent( getElement( "lzfsc", Double.toString( state.getLzfsc() ) ) ); - element.addContent( getElement( "lzfpc", Double.toString( state.getLzfpc() ) ) ); - element.addContent( getElement( "adimc", Double.toString( state.getAdimc() ) ) ); - - return element; - } - - private Element getElement(String elementName, String elementText) - { - Element element = new Element(elementName); - element.setText(elementText); - - return element; - } - - private SacSmaParameters retrieveSacSmaParams( Element e ) - { - SacSmaParameters currentSacSmaParams = new SacSmaParameters(); - - currentSacSmaParams.setBasinId( getElementStringValue( e, "basinId" ) ); - currentSacSmaParams.setSource( getElementStringValue( e, "source" ) ); - currentSacSmaParams.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaParams.setPostingTime( System.currentTimeMillis() ); - currentSacSmaParams.setUztwm( getElementDoubleValue( e, "uztwm" ) ); - currentSacSmaParams.setUzfwm( getElementDoubleValue( e, "uzfwm" ) ); - currentSacSmaParams.setUzk( getElementDoubleValue( e, "uzk" ) ); - currentSacSmaParams.setPctim( getElementDoubleValue( e, "pctim" ) ); - currentSacSmaParams.setAdimp( getElementDoubleValue( e, "adimp" ) ); - currentSacSmaParams.setRiva( getElementDoubleValue( e, "riva" ) ); - currentSacSmaParams.setZperc( getElementDoubleValue( e, "zperc" ) ); - currentSacSmaParams.setRexp( getElementDoubleValue( e, "rexp" ) ); - currentSacSmaParams.setLztwm( getElementDoubleValue( e, "lztwm" ) ); - currentSacSmaParams.setLzfsm( getElementDoubleValue( e, "lzfsm" ) ); - currentSacSmaParams.setLzfpm( getElementDoubleValue( e, "lzfpm" ) ); - currentSacSmaParams.setLzsk( getElementDoubleValue( e, "lzsk" ) ); - currentSacSmaParams.setLzpk( getElementDoubleValue( e, "lzpk" ) ); - currentSacSmaParams.setPfree( getElementDoubleValue( e, "pfree" ) ); - currentSacSmaParams.setRserv( getElementDoubleValue( e, "rserv" ) ); - currentSacSmaParams.setSide( getElementDoubleValue( e, "side" ) ); - currentSacSmaParams.setPxadj( getElementDoubleValue( e, "pxadj" ) ); - currentSacSmaParams.setPeadj( getElementDoubleValue( e, "peadj" ) ); - currentSacSmaParams.setEfc( getElementDoubleValue( e, "efc" ) ); - - - return currentSacSmaParams; - } - -// ----------------------------------------------------------------------------- - - private SacSmaState retrieveSacSmaState( Element e ) - { - SacSmaState currentSacSmaState = new SacSmaState(); - - currentSacSmaState.setBasinId( getElementStringValue( e, "basinId") ); - currentSacSmaState.setSource( getElementStringValue( e, "source") ); - currentSacSmaState.setValidTime( getElementLongTimeValue( e, "validTime" ) ); - currentSacSmaState.setBasisTime( getElementLongTimeValue( e, "basisTime" ) ); - currentSacSmaState.setPostingTime( System.currentTimeMillis() ); - currentSacSmaState.setUztwc( getElementDoubleValue( e, "uztwc" ) ); - currentSacSmaState.setUzfwc( getElementDoubleValue( e, "uzfwc" ) ); - currentSacSmaState.setLztwc( getElementDoubleValue( e, "lztwc" ) ); - currentSacSmaState.setLzfsc( getElementDoubleValue( e, "lzfsc" ) ); - currentSacSmaState.setLzfpc( getElementDoubleValue( e, "lzfpc" ) ); - currentSacSmaState.setAdimc( getElementDoubleValue( e, "adimc" ) ); - - return currentSacSmaState; - } - -// ----------------------------------------------------------------------------- - - private MonthlyValues retrieveMonthlyValues( Element e ) - { - MonthlyValues currentMonthlyValues = new MonthlyValues(); - double[] valueArray = new double[ 12 ]; - - currentMonthlyValues.setBasinId( getElementStringValue( e, "locationId" ) ); - currentMonthlyValues.setPe( MONTHLY_VALUES_PE ); - currentMonthlyValues.setDur(MONTHLY_VALUES_DUR ); - currentMonthlyValues.setTs( MONTHLY_VALUES_TS ); - currentMonthlyValues.setExtremum( MONTHLY_VALUES_EXTREMUM ); - if ( getElementStringValue( e, "isAdjustment" ).equalsIgnoreCase( "TRUE" ) ) - { - currentMonthlyValues.setAdjustment( true ); - } - else - { - currentMonthlyValues.setAdjustment( false ); - } - currentMonthlyValues.setPostingTime( System.currentTimeMillis() ); - - valueArray[ 0 ] = getElementDoubleValue( e, "janValue" ); - valueArray[ 1 ] = getElementDoubleValue( e, "febValue" ); - valueArray[ 2 ] = getElementDoubleValue( e, "marValue" ); - valueArray[ 3 ] = getElementDoubleValue( e, "aprValue" ); - valueArray[ 4 ] = getElementDoubleValue( e, "mayValue" ); - valueArray[ 5 ] = getElementDoubleValue( e, "junValue" ); - valueArray[ 6 ] = getElementDoubleValue( e, "julValue" ); - valueArray[ 7 ] = getElementDoubleValue( e, "augValue" ); - valueArray[ 8 ] = getElementDoubleValue( e, "sepValue" ); - valueArray[ 9 ] = getElementDoubleValue( e, "octValue" ); - valueArray[ 10 ] = getElementDoubleValue( e, "novValue" ); - valueArray[ 11 ] = getElementDoubleValue( e, "decValue" ); - currentMonthlyValues.setValues( valueArray ); - - return currentMonthlyValues; - } - -// ----------------------------------------------------------------------------- - - private String getElementStringValue( Element e, String subElementName ) - { - return e.getChildTextTrim( subElementName ); - } - -// ----------------------------------------------------------------------------- - - private double getElementDoubleValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Double.parseDouble( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private int getElementIntValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Integer.parseInt( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - private short getElementShortValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return Short.parseShort( attributeValueString.trim() ); - } - -// ----------------------------------------------------------------------------- - - private long getElementLongTimeValue( Element e, String subElementName ) - { - String attributeValueString = e.getChildTextTrim( subElementName ); - return DbTimeHelper.getLongTimeFromDateTimeString( attributeValueString ); - } - -// ----------------------------------------------------------------------------- - - public String toString() - { - StringWriter stringWriter = new StringWriter(); - XMLOutputter outputter = new XMLOutputter(); - String returnValue = null; - - try - { - outputter.setTextTrim( true ); - outputter.setIndent( " " ); - outputter.setNewlines( true ); - outputter.output( _inputXMLDoc, stringWriter ); - returnValue = stringWriter.toString(); - } - catch ( IOException e ) - { - e.printStackTrace(); - } - - return returnValue; - } - - private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) - { - XMLOutputter _xmlOutputter = new XMLOutputter(" ", true); - - try - { - FileWriter writer = new FileWriter(xmlFileName); - _xmlOutputter.output(outputXmlDoc, writer); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - private static Document getBaseDocument() - { - //this is used only for testing - - Document doc = new Document(); - - Element rootElement = new Element("SacModelMessage"); - - doc.setRootElement(rootElement); - - Element sacParamsListElement = new Element("SacParamsList"); - Element sacStateListElement = new Element("SacStateList"); - Element peTimeSeriesListElement = new Element("PeTimeSeriesList"); - Element runoffTimeSeriesElement = new Element("RunoffTimeSeriesList"); - Element monthlyValuesListElement = new Element("MonthlyValuesList"); - - rootElement.addContent(sacParamsListElement); - rootElement.addContent(sacStateListElement); - rootElement.addContent(peTimeSeriesListElement); - rootElement.addContent(runoffTimeSeriesElement); - rootElement.addContent(monthlyValuesListElement); - - return doc; - } -// ----------------------------------------------------------------------------- - - public static void main( String[] args ) - { - String inputFileName = args[ 0 ]; - String outputFileName = args[ 1 ]; - String logFileName = args [ 2 ]; - - Document xmlOutputDoc = getBaseDocument(); - - SacXMLTester sacDecoder = new SacXMLTester( inputFileName, xmlOutputDoc, logFileName ); - - sacDecoder.execute(); - - sacDecoder.writeXmlToFile( xmlOutputDoc, outputFileName ); - System.exit( 0 ); - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java deleted file mode 100644 index f3ec8c132a..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * Created on Feb 25, 2004 - * - * This is the main program for the extraction of OFS - * data, conversion to XML, and then sending to the WFO - */ -package ohd.hseb.sshp.messaging; - -import ohd.hseb.util.EnvHelper; -import ohd.hseb.util.FileLogger; - -//import ohd.hseb.db.*; - -import org.jdom.*; -import org.jdom.input.SAXBuilder; -import org.jdom.output.XMLOutputter; -import org.jdom.Document; -import org.jdom.JDOMException; - - - - -import java.io.*; -import java.util.*; -import java.text.*; - -/** - * @author GobsC - * - * - */ -public class SshpDataTransferMgr -{ - - private static String _controlFilePath = null; - private static String _extractedDirName = null; - private static String _processedDirName = null; - private static String _logDirName = null; - - private Document _controlDoc = null; - private SAXBuilder _builder = new SAXBuilder(); - private XMLOutputter _xmlOutputter = new XMLOutputter(" ", true); - - private FileLogger _logger = null; - private String _logFilePath = null; - - // -------------------------------------------------------------- - public SshpDataTransferMgr(String controlFilePath, - String extractedDirName, - String processedDirName, - String logDirName) - { - - _controlFilePath = controlFilePath; - _extractedDirName = extractedDirName; - _processedDirName = processedDirName; - - _logDirName = logDirName; - - _logFilePath = _logDirName + "/SshpDataTransferMgr.log"; - - _logger = new FileLogger(_logFilePath); - - loadControlFile(); - - return; - } - -// -------------------------------------------------------------- - public void execute() - { - String header = "SshpDataTransferMgr.execute(): "; - System.out.println("SshpDataTransferMgr logging to " + _logFilePath); - //using the control xml document - //for each wfo - - //for each forecast point - //extract all the segment data to a file - //translate the extract file and add contents to the live XML doc - //end for each forecast point - - //output live XML document object to a file - //send file using MHS - // end for each wfo - - Element controlRoot =_controlDoc.getRootElement(); - List wfoElementList = controlRoot.getChildren("wfo"); - int wfoCount = wfoElementList.size(); - - - long time = System.currentTimeMillis(); - String timeString = getDateTimeStringFromLongTime(time); - - - //for each wfo - for (int i = 0; i < wfoCount; i++) - { - Element wfoElement = (Element) wfoElementList.get(i); - String wfoName = wfoElement.getChildText("name"); - String mhsId = wfoElement.getChildText("mhsId"); - String productId = wfoElement.getChildText( "productId" ); - - _logger.log("processing wfoName = " + wfoName); - - List fcstPointElementList = wfoElement.getChildren("fcstPoint"); - int fcstPointCount = fcstPointElementList.size(); - - Document outputXmlDoc = getBaseDocument(); - - //for each forecast point - for (int j = 0; j < fcstPointCount; j++) - { - Element fcstPointElement = (Element) fcstPointElementList.get(j); - String segmentId = fcstPointElement.getChildText("ofsSegmentId"); - String locationId = fcstPointElement.getChildText("ihfsLocId"); - String basinId = fcstPointElement.getChildText("ihfsBasinId"); - - _logger.log("segmentId = " + segmentId + " locationId = " + locationId); - - String extractFileName = _extractedDirName + "/" + - segmentId + "." + timeString + ".txt"; - - // String extractFileName = _extractedDirName + "/" + - // segmentId + "_" + "1"; - - - // extract all the segment data to a file - extractOfsData(segmentId, extractFileName); - - - //translate the extract file and add contents to the live XML doc - translateToXml(basinId, extractFileName, outputXmlDoc); - } - - if (fcstPointCount < 1) - { - _logger.log("There were no forecast points defined in the control file: " + - _controlFilePath); - } - - //output the xml document to a file - String xmlFilePath = _processedDirName + "/" + - wfoName + "." + timeString + ".xml"; - - String xmlFileName = wfoName + "." + timeString + ".xml"; - - writeXmlToFile(outputXmlDoc, xmlFilePath); - - //send xml file to the site (WFO, usually) with this mhsId - sendXml(xmlFilePath, xmlFileName, mhsId, productId ); - } - - if ( wfoCount < 1 ) - { - _logger.log("There were no wfos defined in the control file: " + _controlFilePath); - } - - _logger.log("SshpDataTransferMgr completed."); - System.out.println("SshpDataTransferMgr completed."); - - } - -// -------------------------------------------------------------- - - private Document getBaseDocument() - { - Document doc = new Document(); - - Element rootElement = new Element("SacModelMessage"); - - doc.setRootElement(rootElement); - - Element sacParamsListElement = new Element("SacParamsList"); - Element sacStateListElement = new Element("SacStateList"); - Element peTimeSeriesListElement = new Element("PeTimeSeriesList"); - Element runoffTimeSeriesElement = new Element("RunoffTimeSeriesList"); - Element monthlyValuesListElement = new Element("MonthlyValuesList"); - - rootElement.addContent(sacParamsListElement); - rootElement.addContent(sacStateListElement); - rootElement.addContent(peTimeSeriesListElement); - rootElement.addContent(runoffTimeSeriesElement); - rootElement.addContent(monthlyValuesListElement); - - return doc; - } - -// -------------------------------------------------------------- - - private void loadControlFile() - { - try - { - _controlDoc = _builder.build( _controlFilePath ); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (JDOMException e2) - { - e2.printStackTrace(); - } - } - -// -------------------------------------------------------------- - - private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) - { - - try - { - FileWriter writer = new FileWriter(xmlFileName); - _xmlOutputter.output(outputXmlDoc, writer); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - -// -------------------------------------------------------------- - private static String getDateTimeStringFromLongTime(long time) - { - String timeString = getStringFromLongTime(time, "yyyy_MM_dd_HH_mm_ss"); - - return timeString; - } - - // ------------------------------------------------------- - - private static String getStringFromLongTime(long time, String dateFormat) - { - String timeString = null; - - //System.out.println("timeString = !" + timeString + "!"); - SimpleDateFormat utcSdf2 = new SimpleDateFormat(dateFormat); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - timeString = utcSdf2.format(new java.util.Date(time)); - - return timeString; - } -// -------------------------------------------------------------- - private void extractOfsData(String segmentId, String extractFileName) - { - String header = "SshpDataTransferMgr.extractOfsData(): "; - - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - - String commandString = dirString + "/run_SSHP_ofs_extract " + segmentId + " " + extractFileName; - // System.out.println(header + "making system call:" + commandString + ":"); - try - { - Process process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } - catch(IOException e) - { - e.printStackTrace(); - } - catch( InterruptedException e ) - { - e.printStackTrace(); - } - - } -// -------------------------------------------------------------- - private void translateToXml(String basinId, String extractFileName, Document outputXmlDoc) - { - File file = new File(extractFileName); - - int sleepLimit = 15; - int sleepCount = 0; - - boolean done = false; - long oldLength = 0; - long length = 0; - - while (!done && (sleepCount < sleepLimit) ) - { - try - { - Thread.sleep(1000); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - sleepCount++; - - if (file.exists()) - { - length = file.length(); - if (length > 0) - { - if (length == oldLength) - { - //_logger.log("length = oldlength = " + length); - done = true; - } - } - } - - oldLength = length; - } - - SacXMLEncoder encoder = new SacXMLEncoder(basinId, extractFileName, outputXmlDoc, _logger); - - try - { - encoder.parse(); - } - catch ( OfsFileParserException e ) - { - exitOnError(); - } - - } - -// -------------------------------------------------------------- - - private void exitOnError() - { - _logger.log( "Error parsing OFS extract file" ); - _logger.log( "Please check the OFS extract files for any problems" ); - _logger.log( "Exiting..." ); - System.exit( 0 ); - } - -// -------------------------------------------------------------- - private void sendXml(String xmlFilePath, String xmlFileName, String mhsId, String productId) - { - String header = "SshpDataTransferMgr.sendXml(): "; - - /* - # Send product to specific location - # add the one-word description and the office id - # - #echo "Sending file:$FILENAME product_ID:$PRODUCT_ID to *OFFICE* via distributeProduct" >> $LOGNAME - #SUBJECT="*DESCRIPTION* $PRODUCT_ID" - #/awips/fxa/bin/distributeProduct -c SHEFPRODUCT -s "$SUBJECT" -a *OFFICE* $PRODUCT_ID $FILENAME - #RETURN_STATUS=$? - */ - - // String commandString = "/awips/fxa/bin/distributeProduct -c HYDRO_MODEL_DATA -a " + - // mhsId + " " + productId + " " + xmlFileName; - - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - String commandString = dirString + "/run_SSHP_data_send " + xmlFilePath + " " + xmlFileName + " " + mhsId + " " + productId; - -// System.out.println(header + "making system call:" + commandString + ":"); - - try - { - Process process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } - catch(IOException e) - { - e.printStackTrace(); - } - catch( InterruptedException e ) - { - e.printStackTrace(); - } - return; - } -// -------------------------------------------------------------- - - public static void main(String[] argStringArray) - { - if (argStringArray.length >= 4) - { - String controlFilePath = argStringArray[0]; - String extractedDirName = argStringArray[1]; - String processedDirName = argStringArray[2]; - String logDirName = argStringArray[3]; - - SshpDataTransferMgr mgr = new SshpDataTransferMgr(controlFilePath, extractedDirName, processedDirName, logDirName); - - mgr.execute(); - } - else - { - System.out.println("usage: ohd.hseb.sshp.message.SSHPDataTransferManager controlFilePath extractedDirName processedDirName logDirName"); - } - } - -// -------------------------------------------------------------- - - -} //end class SshpDataTransferMgr diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/ArealPrecipPreprocessor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/ArealPrecipPreprocessor.java deleted file mode 100644 index 1ce560a287..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/ArealPrecipPreprocessor.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.sshp.precip; - -public interface ArealPrecipPreprocessor -{ - - public void preprocessAll(); - -} // end of ArealPrecipPreprocessor interface diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/BaseArealPrecipPreprocessor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/BaseArealPrecipPreprocessor.java deleted file mode 100644 index 6a7d953da5..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/BaseArealPrecipPreprocessor.java +++ /dev/null @@ -1,260 +0,0 @@ -package ohd.hseb.sshp.precip; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.Logger; - -public abstract class BaseArealPrecipPreprocessor implements ArealPrecipPreprocessor -{ - protected static final double _timeSeriesMissingValue = -9999.0; - - protected DataMgr _dataMgr = null; - - protected String _mpeQpeGridDirName = null; - protected String _rfcQpeGridDirName = null; - - protected String _bestQpeDateFormatFromToken = null; - protected String _sshpMapQpeToUseTokenValueString = null; - - SimpleDateFormat _localXmrgFileDateFormat = null; - SimpleDateFormat _rfcXmrgFileDateFormat = null; - SimpleDateFormat _hpeXmrgFileDateFormat = null; - - - // QPE usage - protected int _qpeUsage = MIXED_QPE; - - protected static final int RFC_QPE = 0; - protected static final int MIXED_QPE = 1; - protected static final int LOCAL_BEST_QPE = 2; - - protected static final String _rfcOnlyString = "RFC_ONLY"; - protected static final String _mixedString = "MIXED"; - protected static final String _localBestOnlyString = "LOCAL_BEST_ONLY"; - - - protected List _areaIdList = null; - protected List _basinHrapHelperList = null; - protected Logger _logger = null; - protected String _typeSourceCode = null; - - abstract protected void readAppsDefaults(); - - // ---------------------------------------------------------------------------- - - public void initialize(DataMgr dataMgr, Logger logger, String typeSourceCode) - { - _dataMgr = dataMgr; - _logger = logger; - _typeSourceCode = typeSourceCode; - - readAppsDefaults(); - - // load all the areas that are suitable for use as SSHP basins - _areaIdList = _dataMgr.loadAllSshpBasinIds(); - - //let the db manager add rows to ingest filter as needed - _dataMgr.saveMapRowsToIngestFilterAsNeeded(_areaIdList, _typeSourceCode); - - //load the basinHrapHelpers and return them in a List - _basinHrapHelperList = getBasinHrapHelperList(_areaIdList); - - } - - // ---------------------------------------------------------------------------- - - private List getBasinHrapHelperList(List areaIdList) - { - List basinHrapHelperList = new ArrayList(); - for (int i = 0; i < areaIdList.size(); i++) - { - String areaId = (String ) areaIdList.get(i); - - BasinHrapHelper helper = _dataMgr.loadBasinHrapHelper(areaId); - - if (helper != null) - { - //_logger.log(helper.toString()); - - basinHrapHelperList.add(helper); - } - } - - - return basinHrapHelperList; - - } - - // ---------------------------------------------------------------------------- - - protected void preprocessQpeFiles(List timeList, DateFormat dateFormat, String baseDirectory) - { - String header = "BaseArealPrecipPreprocessor.preprocessQpeFiles(): "; - // create an Xmrg file reader - XmrgReader reader = new XmrgReader(_logger); - - _logger.log(header + "baseDirectory = " + baseDirectory ); - - long productTime = System.currentTimeMillis(); - - // for each re-run hour of input - for (int i = 0; i < timeList.size(); i++) - { - Long timeLong = (Long) timeList.get(i); - long time = timeLong.longValue(); - - long basisTime = time; - - - String gridFileName = dateFormat.format(new Date(time)); - String fullGridPath = baseDirectory + "/" + gridFileName; - - long validTime = getValidTime(time); - - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(validTime); - - XmrgGrid grid = reader.loadGrid(validTime, fullGridPath); - - if (grid.isValid()) - { - _logger.log(header + "grid for time = " + timeString + " is VALID "); - - // for each basin, process its data - for (int j = 0; j < _basinHrapHelperList.size(); j++) - { - BasinHrapHelper basinHrapHelper = (BasinHrapHelper) _basinHrapHelperList.get(j); - - preprocess(basinHrapHelper, grid, basisTime, productTime); - } - } - else - { - // _logger.log(header + "grid for time = " + timeString + " is invalid"); - } - } // for loop - - } - - // ---------------------------------------------------------------------------- - - protected long getValidTime(long origTime) - { - return origTime; - } - - // ---------------------------------------------------------------------------- - - public void preprocess(BasinHrapHelper basinHrapHelper, XmrgGrid grid, long basisTime, long productTime) - { - - String areaId = basinHrapHelper.getBasinId(); - - Measurement mapMeasurement = getMAPMeasurementFromGrid(basinHrapHelper, grid); - - _dataMgr.saveMapMeasurement(areaId, _typeSourceCode, mapMeasurement, grid.getTime(), basisTime, productTime, _logger); - - return; - - } - - // ---------------------------------------------------------------------------- - - private Measurement getMAPMeasurementFromGrid(BasinHrapHelper basinHrapHelper, XmrgGrid grid) - { - String header = "BaseArealPrecipPreprocessor.getMAPMeasurementFromGrid(): "; - MeasuringUnit precipUnit = MeasuringUnit.inches; - double mapValue = -1.0; - double binValue = 0; - double totalValue = 0; - int validValueCount = 0; - - // CHANGE 8/23/05 - _logger.log(header + " for basinId = " + basinHrapHelper.getBasinId()); - - int rowCount = basinHrapHelper.getRowCount(); - - boolean gridAccessProblem = false; - - //for each row - for (int i = 0; (i < rowCount && !gridAccessProblem) ; i++) - { - int hrapRow = basinHrapHelper.getBasinHrapRow(i); - - // for each column - for (int hrapCol = basinHrapHelper.getBasinHrapBegColumn(i); - ( (hrapCol <= basinHrapHelper.getBasinHrapEndColumn(i)) && - (!gridAccessProblem)); - hrapCol++) - { - //yank out the bin value at that point - binValue = grid.getValue(hrapRow, hrapCol); - if (binValue >= 0.0) - { - totalValue += binValue; - validValueCount++; - } - else if (binValue == XmrgGrid.OFF_GRID_VALUE) - { - _logger.log(header + "Problem with basinId = " + basinHrapHelper.getBasinId() + - " attempting to access out of bounds grid location row = " + - hrapRow + " and column = " + hrapCol + "."); - gridAccessProblem = true; - - } - } - } - - - // if some kind of failure occured - Measurement mapMeasurement = null; - if ( (validValueCount < 1) || (gridAccessProblem) ) - { - mapValue = _timeSeriesMissingValue; - mapMeasurement = new Measurement(mapValue, precipUnit); - mapMeasurement.setIsMissing(true); - // System.out.println(header + "for " + basinHrapHelper.getBasinId() + " totalValue = " + totalValue + " validValueCount = " + validValueCount); - } - else //success occured, so create a decent measurement - { - // System.out.println(header + "for " + basinHrapHelper.getBasinId() + " totalValue = " + totalValue + " validValueCount = " + validValueCount); - mapValue = totalValue / validValueCount; - if (mapValue < 0.005) - { - mapValue = 0.0; - } - mapMeasurement = new Measurement(mapValue, precipUnit); - } - - - return mapMeasurement; - - } - - // ---------------------------------------------------------------------------- - - public void finalize() - { - try - { - _dataMgr.disconnect(); - _logger.close(); - } - catch (Throwable t) - { - System.err.println(t.getMessage()); - } - - } - - // ---------------------------------------------------------------------------- - -} // End of BaseArealPrecipPreprocessor abstract class \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/BasinHrapHelper.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/BasinHrapHelper.java deleted file mode 100644 index 2f028bb907..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/BasinHrapHelper.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Created on May 21, 2004 - * - * - */ -package ohd.hseb.sshp.precip; - -/** - * @author GobsC - * - * Encapsulates the LineSegment definition for a basin - * - */ - - -public class BasinHrapHelper -{ - -// --------------------------------------------------------------------------------------- - - private String _basinId = null; - //private String name = null; - - private double _areaSize = 0; - - private int _rowCount = 0; - - private int _basinHrapRowArray[]; - private int _basinHrapBegColumnArray[]; - private int _basinHrapEndColumnArray[]; - - private int _binCount = 0; - - - private boolean _isValid = false; - - -// --------------------------------------------------------------------------------------- - - public BasinHrapHelper(String basinId, int rowCount) - { - System.out.println("BasinHrapSet() for basinId = " + basinId); - _basinId = basinId; - - _rowCount = rowCount; - - - initializeArraysByRowCount(_rowCount); - - } - -// --------------------------------------------------------------------------------------- - - private void initializeArraysByRowCount(int rowCount) - { - String header = "BasinHrapSet.initializeArraysByRowCount()"; - System.out.println(header + " rowCount = " + rowCount); - - _basinHrapRowArray = new int[_rowCount]; - _basinHrapBegColumnArray = new int[_rowCount]; - _basinHrapEndColumnArray = new int[_rowCount]; - - return; - } - -// --------------------------------------------------------------------------------------- - public boolean isInBounds(int hrapRow, int hrapCol) - { - boolean inBounds = false; - boolean done = false; - - for (int r = 0; r < _basinHrapRowArray.length && (!done) ; r++) - { - int currentRow = _basinHrapRowArray[r]; - - if (currentRow == hrapRow) //note, there can be multiple partial rows for a single hrapRow - { - if ((hrapCol >= _basinHrapBegColumnArray[r]) && - (hrapCol <= _basinHrapEndColumnArray[r])) - { - //found the column we are looking for - inBounds = true; - done = true; - } - - } - else if (currentRow > hrapRow) // gone beyond hrapRow, so we are done - { - done = true; - } - } - - return inBounds; - } -// --------------------------------------------------------------------------------------- -/* - private boolean hasColumn(int hrapRow, int hrapColumn) - { - boolean foundRow = false; - - - for (int i = 0; i < _basinHrapRowArray.length && (! foundRow) ; i++) - { - if ( _basinHrapRowArray[i] == hrapRow) - { - foundRow = true; - - } - - } - return foundRow; - - } -*/ -// --------------------------------------------------------------------------------------- - - public void setBasinId(String basinId) - { - _basinId = basinId; - } -// --------------------------------------------------------------------------------------- - - public String getBasinId() - { - return _basinId; - } -// --------------------------------------------------------------------------------------- - public int getBasinHrapRow(int index) - { - return _basinHrapRowArray[index]; - - } -// --------------------------------------------------------------------------------------- - public void setBasinHrapRow(int index, int rowValue) - { - _basinHrapRowArray[index] = rowValue; - - } -// --------------------------------------------------------------------------------------- - public int getBasinHrapBegColumn(int index) - { - return _basinHrapBegColumnArray[index]; - - } -// --------------------------------------------------------------------------------------- - - public void setBasinHrapBegColumn(int index, int colValue) - { - _basinHrapBegColumnArray[index] = colValue; - - } - -/// --------------------------------------------------------------------------------------- - - - public int getBasinHrapEndColumn(int index) - { - return _basinHrapEndColumnArray[index]; - - } -// --------------------------------------------------------------------------------------- - - public void setBasinHrapEndColumn(int index, int colValue) - { - _basinHrapEndColumnArray[index] = colValue; - - } -// --------------------------------------------------------------------------------------- - - public int getBasinNorthernRow() - { - int lastIndex = _basinHrapRowArray.length - 1; - return _basinHrapRowArray[lastIndex]; - } -// --------------------------------------------------------------------------------------- - - public int getBasinSouthernRow() - { - - return _basinHrapRowArray[0]; - - } -// --------------------------------------------------------------------------------------- - public double getAreaSize() - { - return _areaSize; - - } - -// --------------------------------------------------------------------------------------- - public void setAreaSize(double areaSize) - { - _areaSize = areaSize; - - return; - } - -// --------------------------------------------------------------------------------------- - - public void setIsValid(boolean isValid) - { - _isValid = isValid; - } - -// --------------------------------------------------------------------------------------- - - public boolean isValid() - { - return _isValid; - } -// --------------------------------------------------------------------------------------- - - public void setRowCount(int rowCount) - { - _rowCount = rowCount; - } - // --------------------------------------------------------------------------------------- - - public int getRowCount() - { - return _rowCount; - } -// --------------------------------------------------------------------------------------- - - public void setBinCount(int binCount) - { - _binCount = binCount; - } - // --------------------------------------------------------------------------------------- - - public int getBinCount() - { - return _binCount; - } -// --------------------------------------------------------------------------------------- - public String toString() - { - - StringBuffer buffer = new StringBuffer(); - - buffer.append("BasinId = " + _basinId + "\n"); - - for (int i = 0; i < _rowCount; i++) - { - - buffer.append(" row = " + _basinHrapRowArray[i] + " cols = " + - _basinHrapBegColumnArray[i] + - " to " +_basinHrapEndColumnArray[i] + "\n"); - - - - } - - return buffer.toString(); - } - - -// --------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/HPNPreprocessor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/HPNPreprocessor.java deleted file mode 100644 index a531f0757e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/HPNPreprocessor.java +++ /dev/null @@ -1,237 +0,0 @@ -package ohd.hseb.sshp.precip; - -import java.io.File; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - - -public class HPNPreprocessor extends BaseArealPrecipPreprocessor implements ArealPrecipPreprocessor -{ - - private static final String _className = "HPNPreprocessor"; - private String _hpeGridDirName = null; - // private final long _tolerenceTime = 5 * TimeHelper.MILLIS_PER_MINUTE; - private long _millisBeforeTOTH = 0; - private long _millisAfterTOTH = 0; - - public HPNPreprocessor(DataMgr dataMgr, Logger logger, String typeSourceCode) - { - - initialize(dataMgr, logger, typeSourceCode); - - return; - } - - // ---------------------------------------------------------------------------- - - protected void readAppsDefaults() - { - String header = "HPNPreprocessor.readAppsDefaults(): "; - - final int MIN_MINUTES = 0; - final int MAX_MINUTES = 25; - final int DEFAULT_MINUTES = 5; - int minutesBefore = MIN_MINUTES; - int minutesAfter = MIN_MINUTES; - - AppsDefaults ad = new AppsDefaults(); - - //determine grid directories - _hpeGridDirName = ad.getToken("hpe_nowcast_dir", "."); - _logger.log(header + "Directory to search for HPN grid files = " + _hpeGridDirName); - - minutesBefore = ad.getInt("sshp_hpn_minutes_before", DEFAULT_MINUTES); - if (minutesBefore < MIN_MINUTES || minutesBefore > MAX_MINUTES) - minutesBefore = DEFAULT_MINUTES; - _logger.log(header + "Minutes to check before Top of the Hour = " + minutesBefore); - - minutesAfter = ad.getInt("sshp_hpn_minutes_after", DEFAULT_MINUTES); - if (minutesAfter < MIN_MINUTES || minutesAfter > MAX_MINUTES) - minutesAfter = DEFAULT_MINUTES; - _logger.log(header + "Minutes to check after Top of the Hour = " + minutesAfter); - - _millisBeforeTOTH = minutesBefore * TimeHelper.MILLIS_PER_MINUTE; - _millisAfterTOTH = minutesAfter * TimeHelper.MILLIS_PER_MINUTE; - - //create the appropriate SimpleDateFormat objects - _hpeXmrgFileDateFormat = new SimpleDateFormat("'ACC4kmH'yyyyMMddHHmm'z'"); - _hpeXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - } - - // ---------------------------------------------------------------------------- - - protected long getValidTime(long origTime) - { - String header = "HPNPreprocessor.getValidTime(): "; - - // Add the before TOTH window time (ie 5 minutes) plus another one hour. - long newTime = origTime + _millisBeforeTOTH + TimeHelper.MILLIS_PER_HOUR; - - // now trim it down to the top of hour - long validTime = TimeHelper.truncateTimeInMillisToNearestHour(newTime, 1); - String validTimeString = DbTimeHelper.getDateTimeStringFromLongTime(validTime); - _logger.log(header + "validTime = " + validTimeString); - - return validTime; - } - - // ---------------------------------------------------------------------------- - - public void preprocessAll() - { - - String header = "HPNPreprocessor.preprocessAll(): "; - _logger.log(header + "Beginning Preprocessing"); - CodeTimer timer = new CodeTimer(_logger); - - //get the time for right NOW to find the nearest hour - long currentRunTime = System.currentTimeMillis(); - String currentRunTimeString = DbTimeHelper.getDateTimeStringFromLongTime(currentRunTime); - _logger.log(header + "currentRunTime = " + currentRunTimeString); - - long topOfTheHour = TimeHelper.truncateTimeInMillisToNearestHour(currentRunTime, 1); - String tothTimeString = DbTimeHelper.getDateTimeStringFromLongTime(topOfTheHour); - _logger.log(header + "TopOfTheHourTime = " + tothTimeString); - - //handle the HPE ACC files - List hpeFileList = getHpnXmrgFileTimeList(topOfTheHour, _hpeGridDirName, _hpeXmrgFileDateFormat); - - //ACC4KmHyyyymmddhhMMz - preprocessQpeFiles(hpeFileList, _hpeXmrgFileDateFormat, _hpeGridDirName); - - _logger.log(header + "Preprocessing complete."); - - return; - - } // preprocessAll - - // ---------------------------------------------------------------------------- - - private List getHpnXmrgFileTimeList(long currentHourTime, String gridDirectoryString, SimpleDateFormat dateFormat) - { - String header = "HPNPreprocessor.getHpnXmrgFileTimeList(): "; - - File directory = new File(gridDirectoryString); - File[] fileArray = directory.listFiles(); - List timeList = new ArrayList(); - - // for each file in the directory - // read the filename and parse out its time - // if it falls within the time window then check if it is the "best time" found so far - // If it fails to parse, then we don't want it because - // it is some other type of file that got in the directory somehow. - final long beginingOfTimeWindow = currentHourTime - _millisBeforeTOTH; - final long endOfTimeWindow = currentHourTime + _millisAfterTOTH; - final long beyondTimeWindow = endOfTimeWindow + _millisBeforeTOTH + 1; - - _logger.log(header + - " Valid Time Window = " + DbTimeHelper.getDateTimeToMinutesStringFromLongTime(beginingOfTimeWindow) + - " through " + DbTimeHelper.getDateTimeToMinutesStringFromLongTime(endOfTimeWindow) ); - - if (fileArray != null) - { - long bestTimeFound = beyondTimeWindow; - for (int i = 0 ; i < fileArray.length; i++) - { - File file = fileArray[i]; - try - { - Date date = dateFormat.parse(file.getName()); - long gridTime = date.getTime(); - - if ( (gridTime >= beginingOfTimeWindow) && (gridTime <= endOfTimeWindow) ) - { - _logger.log(header + " fileName = " + file.getName() ); - _logger.log(header + " fileTime = " + DbTimeHelper.getDateTimeToMinutesStringFromLongTime(gridTime) ); - - bestTimeFound = getClosestToHourFileTime(currentHourTime, bestTimeFound, gridTime); - } - } - catch (ParseException e) - { - //some other filename format was found, - //we don't want it - } - - } //for list of file names - - if (bestTimeFound != beyondTimeWindow) - { - timeList.add( bestTimeFound ); - _logger.log(header + " bestTimeFound = " + DbTimeHelper.getDateTimeToMinutesStringFromLongTime(bestTimeFound) ); - } - else - { - _logger.log(header + - " No ACC4KmHyyyymmddhhMMz files were found within the time window " + DbTimeHelper.getDateTimeToMinutesStringFromLongTime(beginingOfTimeWindow) + - " - " + DbTimeHelper.getDateTimeToMinutesStringFromLongTime(endOfTimeWindow) ); - } - - } //if ANY files found in the directory - - return timeList; - - } // End of getHpeXmrgFileTimeList - - // ---------------------------------------------------------------------------- - - private Long getClosestToHourFileTime(long TopOfTheHourTime, long Time1, long Time2) - { - long timeDiffernce1 = Math.abs(TopOfTheHourTime - Time1); - long timeDiffernce2 = Math.abs(TopOfTheHourTime - Time2); - - if (timeDiffernce1 < timeDiffernce2) - return Time1; - else - return Time2; - } - - // ---------------------------------------------------------------------------- - - public static void main(String[] argArray) - { - HPNPreprocessor preprocessor = null; - String baseConnectionString = argArray[0]; - String typeSourceCode = "FL"; - - //initialize the logging - String logFileDir = argArray[1]; - String logFilePath = logFileDir + "/" + _className + ".log"; - Logger logger = new FileLogger(logFilePath, true, true); - - logger.log("Initializing " + _className); - - // start the clock on the timer - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - //initialize the database connection - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - //create a new HPN Preprocessor instance and process all ACC* XMRG files. - preprocessor = new HPNPreprocessor(dataMgr, logger, typeSourceCode); - preprocessor.preprocessAll(); - - timer.stop("All of Processing for " + _className + " took "); - - preprocessor.finalize(); - - return; - } // End of psvm - - // ---------------------------------------------------------------------------- - -} // End of HPNPreprocessor class diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java deleted file mode 100644 index 7194ee8837..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/MAPPreprocessor.java +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Created on 5/24/04 - * Last major change on 7/23/04 -*/ - -package ohd.hseb.sshp.precip; - - -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.measurement.*; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; - - -/** - * @author Chip Gobs - * This is the MAPPreprocessor for OB7.2. - * It not only can process the traditional MPE best estimate files, - * but can also process the RFC MOSAIC files. - * - */ -public class MAPPreprocessor -{ - private static final String _className = "MAPPreprocessor"; - private static final double _timeSeriesMissingValue = -9999.0; - - private DataMgr _dataMgr = null; - - private String _mpeQpeGridDirName = null; - private String _rfcQpeGridDirName = null; - private String _bestQpeDateFormatFromToken = null; - private String _sshpMapQpeToUseTokenValueString = null; - - SimpleDateFormat _localXmrgFileDateFormat = null; - SimpleDateFormat _rfcXmrgFileDateFormat = null; - - - // QPE usage - private int _qpeUsage = MIXED_QPE; - - private static final int RFC_QPE = 0; - private static final int MIXED_QPE = 1; - private static final int LOCAL_BEST_QPE = 2; - - private static final String _rfcOnlyString = "RFC_ONLY"; - private static final String _mixedString = "MIXED"; - private static final String _localBestOnlyString = "LOCAL_BEST_ONLY"; - - - private List _areaIdList = null; - private List _basinHrapHelperList = null; - private Logger _logger = null; - - // ---------------------------------------------------------------------------- - - public MAPPreprocessor(DataMgr dataMgr, Logger logger) - { - _dataMgr = dataMgr; - _logger = logger; - - readAppsDefaults(); - - // load all the areas that are suitable for use as SSHP basins - _areaIdList = _dataMgr.loadAllSshpBasinIds(); - - //let the db manager add rows to ingest filter as needed - _dataMgr.saveMapRowsToIngestFilterAsNeeded(_areaIdList); - - //load the basinHrapHelpers and return them in a List - _basinHrapHelperList = getBasinHrapHelperList(_areaIdList); - - - return; - } - - // ---------------------------------------------------------------------------- - - private void readAppsDefaults() - { - String header = "MAPPreprocessor.readAppsDefaults()"; - AppsDefaults ad = new AppsDefaults(); - - //determine grid directories - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir"); - _rfcQpeGridDirName = ad.getToken("gaq_xmrg_1hr_dir"); - - //create the appropriate SimpleDateFormat objects - _bestQpeDateFormatFromToken = ad.getToken("st3_date_form"); - if (_bestQpeDateFormatFromToken != null ) - { - if (_bestQpeDateFormatFromToken.equals("Ymd")) - { - _localXmrgFileDateFormat = new SimpleDateFormat("'xmrg'yyyyMMddHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - } - else //mdY , this is the way .Apps_Defaults delivers it. Strange, huh? - { - _localXmrgFileDateFormat = new SimpleDateFormat("'xmrg'MMddyyyyHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - } - } - else //token was null - { - _localXmrgFileDateFormat = new SimpleDateFormat("'xmrg'MMddyyyyHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - } - - // rfc mosaic file name format - _rfcXmrgFileDateFormat = new SimpleDateFormat("'RFCMOSAIC01'yyyyMMddHH'z'"); - _rfcXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - - //default value to use both best local and rfc data, - //with the rfc data favored - _qpeUsage = MIXED_QPE; - - _sshpMapQpeToUseTokenValueString = ad.getToken("sshp_map_qpe_to_use"); - - if (_sshpMapQpeToUseTokenValueString != null) - { - if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_mixedString) ) - { - _qpeUsage = MIXED_QPE; - _logger.log(header + "_qpeUsage is MIXED_QPE"); - } - else if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_localBestOnlyString) ) - { - _qpeUsage = LOCAL_BEST_QPE; - _logger.log(header + "_qpeUsage is LOCAL_BEST_QPE"); - } - else if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_rfcOnlyString) ) - { - _qpeUsage = RFC_QPE; - _logger.log(header + "_qpeUsage is RFC_QPE"); - } - } - } - - // ---------------------------------------------------------------------------- - - public void preprocessAll() - { - - String header = "MAPPreprocessor.preprocessAll():"; - _logger.log("Beginning Preprocessing"); - CodeTimer timer = new CodeTimer(_logger); - - //find the latest posting time in the ArealObs table - long latestPostingTime = _dataMgr.getLatestPostingTimeForMAPPreprocessor(); - - - String latestPostingTimeString = - DbTimeHelper.getDateTimeStringFromLongTime(latestPostingTime); - - _logger.log(header + "latestPostingTime = " + latestPostingTimeString); - - //handle the local best estimate qpe files - if ((_qpeUsage == LOCAL_BEST_QPE) || (_qpeUsage == MIXED_QPE)) - { - - // based on that latestPostingTime, find the times of all the newer - // Xmrg files from - // the locally-run MPE - List localFileTimeList = _dataMgr.getNewerBestQpeXmrgFileTimeList(latestPostingTime); - - preprocessQpeFiles(localFileTimeList, _localXmrgFileDateFormat, _mpeQpeGridDirName); - } - - - //handle the RFC files - if ((_qpeUsage == RFC_QPE) || (_qpeUsage == MIXED_QPE)) - { - - List rfcFileTimeList = _dataMgr.getNewerRfcXmrgFileTimeList(latestPostingTime, - _rfcQpeGridDirName, - _rfcXmrgFileDateFormat); - // // RFCMOSAIC012006060411 - preprocessQpeFiles(rfcFileTimeList, - _rfcXmrgFileDateFormat, - _rfcQpeGridDirName); - - } - _logger.log("Preprocessing complete."); - - - return; - } // preprocessAll - - // ---------------------------------------------------------------------------- - private void preprocessQpeFiles(List timeList, DateFormat dateFormat, String baseDirectory) - { - String header = "preprocessQpeFiles(): "; - // create an Xmrg file reader - XmrgReader reader = new XmrgReader(_logger); - - _logger.log(header + "baseDirectory = " + baseDirectory ); - - - // for each re-run hour of input - for (int i = 0; i < timeList.size(); i++) - { - Long timeLong = (Long) timeList.get(i); - long time = timeLong.longValue(); - - String gridFileName = dateFormat.format(new Date(time)); - String fullGridPath = baseDirectory + "/" + gridFileName; - - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - XmrgGrid grid = reader.loadGrid(time, fullGridPath); - - if (grid.isValid()) - { - _logger.log(header + "grid for time = " + timeString + " is VALID "); - - // for each basin, process its data - for (int j = 0; j < _basinHrapHelperList.size(); j++) - { - BasinHrapHelper basinHrapHelper = (BasinHrapHelper) _basinHrapHelperList.get(j); - - preprocess(basinHrapHelper, grid); - } - } - else - { - // _logger.log(header + "grid for time = " + timeString + " is invalid"); - } - } - - } - - // ---------------------------------------------------------------------------- - - public void preprocess(BasinHrapHelper basinHrapHelper, XmrgGrid grid) - { - String areaId = basinHrapHelper.getBasinId(); - - Measurement mapMeasurement = getMAPMeasurementFromGrid(basinHrapHelper, grid); - - _dataMgr.saveMapMeasurement(areaId, mapMeasurement, grid.getTime(), _logger); - - return; - - } - - // ---------------------------------------------------------------------------- - private Measurement getMAPMeasurementFromGrid(BasinHrapHelper basinHrapHelper, XmrgGrid grid) - { - String header = "MAPPreprocessor.getMAPMeasurementFromGrid(): "; - MeasuringUnit precipUnit = MeasuringUnit.inches; - double mapValue = -1.0; - double binValue = 0; - double totalValue = 0; - int validValueCount = 0; - - // CHANGE 8/23/05 - _logger.log(header + " for basinId = " + basinHrapHelper.getBasinId()); - - int rowCount = basinHrapHelper.getRowCount(); - - boolean gridAccessProblem = false; - - //for each row - for (int i = 0; (i < rowCount && !gridAccessProblem) ; i++) - { - int hrapRow = basinHrapHelper.getBasinHrapRow(i); - - // for each column - for (int hrapCol = basinHrapHelper.getBasinHrapBegColumn(i); - ( (hrapCol <= basinHrapHelper.getBasinHrapEndColumn(i)) && - (!gridAccessProblem)); - hrapCol++) - { - //yank out the bin value at that point - binValue = grid.getValue(hrapRow, hrapCol); - if (binValue >= 0.0) - { - totalValue += binValue; - validValueCount++; - } - else if (binValue == XmrgGrid.OFF_GRID_VALUE) - { - _logger.log(header + "Problem with basinId = " + basinHrapHelper.getBasinId() + - " attempting to access out of bounds grid location row = " + - hrapRow + " and column = " + hrapCol + "."); - gridAccessProblem = true; - - } - } - } - - - // if some kind of failure occured - Measurement mapMeasurement = null; - if ( (validValueCount < 1) || (gridAccessProblem) ) - { - mapValue = _timeSeriesMissingValue; - mapMeasurement = new Measurement(mapValue, precipUnit); - mapMeasurement.setIsMissing(true); - // System.out.println(header + "for " + basinHrapHelper.getBasinId() + " totalValue = " + totalValue + " validValueCount = " + validValueCount); - } - else //success occured, so create a decent measurement - { - //System.out.println(header + "for " + basinHrapHelper.getBasinId() + " totalValue = " + totalValue + " validValueCount = " + validValueCount); - mapValue = totalValue / validValueCount; - if (mapValue < 0.005) - { - mapValue = 0.0; - } - mapMeasurement = new Measurement(mapValue, precipUnit); - } - - - - return mapMeasurement; - - } - - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------- - private List getBasinHrapHelperList(List areaIdList) - { - List basinHrapHelperList = new ArrayList(); - for (int i = 0; i < areaIdList.size(); i++) - { - String areaId = (String ) areaIdList.get(i); - - BasinHrapHelper helper = _dataMgr.loadBasinHrapHelper(areaId); - - if (helper != null) - { - //_logger.log(helper.toString()); - - basinHrapHelperList.add(helper); - } - } - - - return basinHrapHelperList; - - } - // ---------------------------------------------------------------------------- - - public void finalize() - { - try - { - _dataMgr.disconnect(); - _logger.close(); - } - catch (Throwable t) - { - System.err.println(t.getMessage()); - } - - - } - // ---------------------------------------------------------------------------- - - public static void main(String[] argArray) - { - MAPPreprocessor preprocessor = null; - String baseConnectionString = argArray[0]; - - //initialize the logging - String logFileDir = argArray[1]; - String logFilePath = logFileDir + "/" + _className + ".log"; - Logger logger = new FileLogger(logFilePath, true, true); - - logger.log("Initializing " + _className); - - // start the clock on the timer - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - //initialize the database connection - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - //create a new MAPPreprocessor instance and preprocess all the unprocessed - //XMRG files. - preprocessor = new MAPPreprocessor(dataMgr, logger); - preprocessor.preprocessAll(); - - timer.stop("All of Processing for " + _className + " took "); - - preprocessor.finalize(); - - return; - } - // ---------------------------------------------------------------------------- - -} //MAPPreprocessor diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/MPEPreprocessor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/MPEPreprocessor.java deleted file mode 100644 index bb1c41d9de..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/MPEPreprocessor.java +++ /dev/null @@ -1,182 +0,0 @@ -package ohd.hseb.sshp.precip; - - -import java.text.SimpleDateFormat; - -import java.util.List; -import java.util.TimeZone; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; - -public class MPEPreprocessor extends BaseArealPrecipPreprocessor implements ArealPrecipPreprocessor -{ - - private static final String _className = "MPEPreprocessor"; - - public MPEPreprocessor(DataMgr dataMgr, Logger logger, String typeSourceCode) - { - - initialize(dataMgr, logger, typeSourceCode); - - return; - } - - // ---------------------------------------------------------------------------- - - protected void readAppsDefaults() - { - String header = "MPEPreprocessor.readAppsDefaults()"; - AppsDefaults ad = new AppsDefaults(); - - //determine grid directories - _mpeQpeGridDirName = ad.getToken("rfcwide_xmrg_dir"); - _rfcQpeGridDirName = ad.getToken("gaq_xmrg_1hr_dir"); - - //create the appropriate SimpleDateFormat objects - _bestQpeDateFormatFromToken = ad.getToken("st3_date_form"); - if (_bestQpeDateFormatFromToken != null ) - { - if (_bestQpeDateFormatFromToken.equals("Ymd")) - { - _localXmrgFileDateFormat = new SimpleDateFormat("'xmrg'yyyyMMddHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - } - else //mdY , this is the way .Apps_Defaults delivers it. Strange, huh? - { - _localXmrgFileDateFormat = new SimpleDateFormat("'xmrg'MMddyyyyHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - } - } - else //token was null - { - _localXmrgFileDateFormat = new SimpleDateFormat("'xmrg'MMddyyyyHH'z'"); - _localXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - } - - // rfc mosaic file name format - _rfcXmrgFileDateFormat = new SimpleDateFormat("'RFCMOSAIC01'yyyyMMddHH'z'"); - _rfcXmrgFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - - - //default value to use both best local and rfc data, - //with the rfc data favored - _qpeUsage = MIXED_QPE; - - _sshpMapQpeToUseTokenValueString = ad.getToken("sshp_map_qpe_to_use"); - - if (_sshpMapQpeToUseTokenValueString != null) - { - if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_mixedString) ) - { - _qpeUsage = MIXED_QPE; - _logger.log(header + "_qpeUsage is MIXED_QPE"); - } - else if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_localBestOnlyString) ) - { - _qpeUsage = LOCAL_BEST_QPE; - _logger.log(header + "_qpeUsage is LOCAL_BEST_QPE"); - } - else if (_sshpMapQpeToUseTokenValueString.equalsIgnoreCase(_rfcOnlyString) ) - { - _qpeUsage = RFC_QPE; - _logger.log(header + "_qpeUsage is RFC_QPE"); - } - } - } - - // ---------------------------------------------------------------------------- - - public void preprocessAll() - { - - String header = "MPEPreprocessor.preprocessAll(): "; - _logger.log(header + "Beginning Preprocessing"); - CodeTimer timer = new CodeTimer(_logger); - - //find the latest posting time in the ArealObs table - long latestPostingTime = _dataMgr.getLatestPostingTimeForMAPPreprocessor(); - - - String latestPostingTimeString = - DbTimeHelper.getDateTimeStringFromLongTime(latestPostingTime); - - _logger.log(header + "latestPostingTime = " + latestPostingTimeString); - - //handle the local best estimate qpe files - if ((_qpeUsage == LOCAL_BEST_QPE) || (_qpeUsage == MIXED_QPE)) - { - - // based on that latestPostingTime, find the times of all the newer - // Xmrg files from - // the locally-run MPE - List localFileTimeList = _dataMgr.getNewerBestQpeXmrgFileTimeList(latestPostingTime); - - preprocessQpeFiles(localFileTimeList, _localXmrgFileDateFormat, _mpeQpeGridDirName); - } - - - //handle the RFC files - if ((_qpeUsage == RFC_QPE) || (_qpeUsage == MIXED_QPE)) - { - - List rfcFileTimeList = _dataMgr.getNewerRfcXmrgFileTimeList(latestPostingTime, - _rfcQpeGridDirName, - _rfcXmrgFileDateFormat); - // // RFCMOSAIC012006060411 - preprocessQpeFiles(rfcFileTimeList, - _rfcXmrgFileDateFormat, - _rfcQpeGridDirName); - - } - _logger.log(header + "Preprocessing complete."); - - - return; - - } // preprocessAll - - // ---------------------------------------------------------------------------- - - public static void main(String[] argArray) - { - MPEPreprocessor preprocessor = null; - String baseConnectionString = argArray[0]; - String typeSourceCode = "PM"; - - //initialize the logging - String logFileDir = argArray[1]; - // For now have the log filename use MAP not MPE -// String logFilePath = logFileDir + "/" + _className + ".log"; - String logFilePath = logFileDir + "/" + "MAPPreprocessor" + ".log"; - Logger logger = new FileLogger(logFilePath, true, true); - - logger.log("Initializing " + _className); - - // start the clock on the timer - CodeTimer timer = new CodeTimer(logger); - timer.start(); - - //initialize the database connection - DataMgr dataMgr = new DataMgr(baseConnectionString, logger); - - //create a new MPEPreprocessor instance and preprocess all the unprocessed - //XMRG files. - preprocessor = new MPEPreprocessor(dataMgr, logger, typeSourceCode); - preprocessor.preprocessAll(); - - timer.stop("All of Processing for " + _className + " took "); - - preprocessor.finalize(); - - return; - } // End of psvm - - // ---------------------------------------------------------------------------- - -} // End of MPEPreprocessor class diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java deleted file mode 100644 index db7458b7b2..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/precip/XmrgReader.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Created on May 24, 2004 - * - * - */ -package ohd.hseb.sshp.precip; - - -//import java.util.*; // needed for Vector class -import java.io.*; // needed for ByteArrayInputStream - -import java.text.SimpleDateFormat; // needed for SimpleDateFormat class - -//import ohd.hseb.util.AppsDefaults; -import ohd.hseb.grid.XmrgGrid; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.EndianConverter; -import ohd.hseb.util.Logger; - -//import whfs.db.gen.*; - - -public class XmrgReader -{ - - // each value was stored in mm of precip times 100 - // Conversion factor needed to convert (mm x 100) to inches - // need to divide by 2540.0 (25.4mm/inch x 100) to get inches - private static final double _CONVERSION_FACTOR = 2540.0; - private static final double _missingValue = -999.0; - - private String _mpeQpeGridDirName = null; - private SimpleDateFormat _xmrgFileDateFormat = null; - private boolean _needEndianChange = false; - - // I may be able to turn these into local variables - private int _numBinsPerColXmrg=0; - private int _numBinsPerRowXmrg=0; - - private int _swHrapRowXmrg=0; - private int _swHrapColXmrg=0; - - private int _southernRowXmrg = 0; - private int _northernRowXmrg = 0; - private int _westernColXmrg = 0; - private int _easternColXmrg = 0; - - private Logger _logger; - //private CodeTimer _loadGridAccumulatedTimer = null; - //private CodeTimer _readLoopAccumulatedTimer = null; - //private CodeTimer _readSetAccumulatedTimer = null; - - -// ----------------------------------------------------------------------------------- - - public XmrgReader(Logger logger) - { - _logger = logger; - } -// ----------------------------------------------------------------------------------- - - public XmrgGrid loadGrid(long time, String gridFileName) - { - - XmrgGrid grid = readMPEGridFile(time, gridFileName); - - return grid; - } -// ----------------------------------------------------------------------------------- - private DataInputStream initDataInputStream(String fullGridFilePath) - { - String header = "XmrgReader.initDataInputStream: "; - - DataInputStream dis = null; - - boolean normalMode = true; - - CodeTimer timer = new CodeTimer(_logger); - - - try - { - - if (normalMode) - { - // timer.start(); - FileInputStream fis = new FileInputStream(fullGridFilePath); - BufferedInputStream bis = new BufferedInputStream(fis); - dis = new DataInputStream(bis); - //timer.stop(header + "init of 'normal' reading " ); - - } - - else // "faster" mode - { - // timer.start(); - - FileInputStream fis = new FileInputStream(fullGridFilePath); - - int byteCount = fis.available(); - byte[] byteArray = new byte[byteCount]; - - fis.read(byteArray); - fis.close(); - - ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); - dis = new DataInputStream(bais); - - //timer.stop(header + "init of 'faster' reading " + byteCount + " bytes from the file " + fullGridFilePath + " took "); - - } - } - catch (java.io.IOException e) - { - e.printStackTrace(_logger.getPrintWriter()); - } - - return dis; - - } -// ----------------------------------------------------------------------------------- - - private XmrgGrid readMPEGridFile(long gridTime, String gridFileName) - { - XmrgGrid grid = null; - - String header = "XmrgReaderFaster.readMPEGridFile(): "; - - String fullGridFilePath; - - if (_mpeQpeGridDirName != null) - fullGridFilePath = _mpeQpeGridDirName + "/" + gridFileName.trim(); - else - fullGridFilePath = gridFileName.trim(); - - File xmrgFile = new File(fullGridFilePath); - - - if (xmrgFile.exists()) - { - try - { - - DataInputStream dis = initDataInputStream(fullGridFilePath); - - int numBytesRecordBegin; - int numBytesRecordEnd; - - // read in the first header of the xmrg file which contains - // the SouthWest HRAP column, row, # of columns and # of rows - numBytesRecordBegin = dis.readInt(); - - // System.out.println(header + "raw numBytesRecordBegin = " + numBytesRecordBegin); - - - //determine endianess - if (numBytesRecordBegin == 16) - { - _needEndianChange = false; - // System.out.println(header + "good raw numBytesRecordBegin = " + numBytesRecordBegin); - - } - else - { - _needEndianChange = true; - numBytesRecordBegin = EndianConverter.convert(numBytesRecordBegin); - // System.out.println(header + "converted raw numBytesRecordBegin = " + numBytesRecordBegin); - } - - _swHrapColXmrg = readInt(dis); - _swHrapRowXmrg = readInt(dis); - - - - /* - System.out.println(header + "XOR = " + swHrapColXmrg + - " YOR = " + swHrapRowXmrg); - */ - - _numBinsPerRowXmrg = readInt(dis); - - if ( (_numBinsPerRowXmrg < 1) || (_numBinsPerRowXmrg > 1000) ) - { - _logger.log("Error: The number of HRAP Bins Per Row for " + fullGridFilePath + " is " + _numBinsPerRowXmrg); - _logger.log(" Note: This number should be in the range of 1 - 1000. This MPE xmrg file is being skipped."); - return XmrgGrid.getInvalidGrid(gridTime); - } - - _numBinsPerColXmrg = readInt(dis); - - - - - if ( (_numBinsPerColXmrg < 1) || (_numBinsPerColXmrg > 1000) ) - { - _logger.log("Error: The number of HRAP Bins Per Col for " + fullGridFilePath + " is " + _numBinsPerColXmrg); - _logger.log(" Note: This number should be in the range of 1 - 1000. This MPE xmrg file is being skipped."); - return( XmrgGrid.getInvalidGrid(gridTime)); - } - - numBytesRecordEnd = readInt(dis); - - // System.out.println("XOR=" + swHrapColXmrg + " YOR=" + swHrapRowXmrg + - // " MAXX=" + numBinsPerRowXmrg + " MAXY=" + numBinsPerColXmrg); - - // calculate the Southern and Northern most rows of the XMRG file - _southernRowXmrg = _swHrapRowXmrg; - _northernRowXmrg = _southernRowXmrg + _numBinsPerColXmrg - 1; - - // calculate the Western and Eastern most columns of the XMRG file - _westernColXmrg = _swHrapColXmrg; - _easternColXmrg = _westernColXmrg + _numBinsPerRowXmrg - 1; - - - int rowCount = _numBinsPerColXmrg; - int colCount = _numBinsPerRowXmrg; - - grid = new XmrgGrid(gridTime, - _southernRowXmrg, _westernColXmrg, - rowCount, colCount); - - // read in the second header of the xmrg file which contains - // the userid, saved date, process flag, valid date, - // maximum value and version number and throw them away - numBytesRecordBegin = readInt(dis); - numBytesRecordEnd = dis.skipBytes(numBytesRecordBegin); - numBytesRecordEnd = readInt(dis); - - double value = _missingValue; - - - // _readLoopAccumulatedTimer.restart(); - - for (int hrapRow = _southernRowXmrg; hrapRow <= _northernRowXmrg && grid.isValid(); hrapRow++) - { - numBytesRecordBegin = readInt(dis); - // IF numBytesRecordBegin NOT EQUAL TO TWICE numBinsPerRowXmrg THEN BAIL - if ( numBytesRecordBegin != (_numBinsPerRowXmrg * 2) ) - { - _logger.log("Error: The number of bytes per record " + numBytesRecordBegin + - " should be twice the number of bins per row " + _numBinsPerRowXmrg ); - grid.setIsValid(false); - - } - - // if ( (ctrRows < firstRowToBeRead) || (ctrRows > lastRowToBeRead) ) - // numBytesRecordEnd = dis.skipBytes(numBytesRecordBegin); - // else - - - - for (int hrapCol=_westernColXmrg; hrapCol <= _easternColXmrg && grid.isValid(); hrapCol++) - { - value = (double)readShort(dis); - - - if (value != _missingValue) - { - value /= _CONVERSION_FACTOR; - // _readSetAccumulatedTimer.restart(); - grid.setValue(hrapRow, hrapCol, value); - // _readSetAccumulatedTimer.stop(); - } - else - { - grid.setValue(hrapRow, hrapCol, _missingValue); - // System.out.println("value at " + hrapRow + ", " + hrapCol + " is missing"); - } - } - - numBytesRecordEnd = readInt(dis); - } - // _readLoopAccumulatedTimer.stop("The total time in the nested for loop took "); - // _logger.log("The total accumulated time of grid.setValue() is " + _readSetAccumulatedTimer.getElapsedTime()); - /* - for (int ctr=0; ctr 0.0) - System.out.println("gridValue[" + ctr + "]=" + gridValues[ctr]); - } - */ - - dis.close(); - } - catch(EOFException ioe) - { - _logger.log( "Read End Of File" + ioe); - grid.setIsValid(false); - } - catch(IOException ioe) - { - _logger.log( "Something went wrong trying to read " + ioe); - grid.setIsValid(false); - } - } - else - { - //_logger.log("\nWarning: file " + gridFileName + " does NOT Exist!"); - grid = XmrgGrid.getInvalidGrid(gridTime); - } - - - return grid; - - } // end of readMPEGridFile method - -// ----------------------------------------------------------------------------------- - - -// ---------------------------------------------------- - private int readInt(DataInputStream dis) throws IOException - { - int value = dis.readInt(); - - if (_needEndianChange) - { - value = EndianConverter.convert(value); - } - return value; - } -// ---------------------------------------------------- - - private short readShort(DataInputStream dis) throws IOException - { - short value = dis.readShort(); - - if (_needEndianChange) - { - value = EndianConverter.convert(value); - } - return value; - } - // ---------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/AnalysisWindow.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/AnalysisWindow.java deleted file mode 100644 index e12040b47c..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/AnalysisWindow.java +++ /dev/null @@ -1,5130 +0,0 @@ -/* - * Created on Jul 18, 2003 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.*; -import java.awt.event.*; -import java.awt.image.BufferedImage; - -import javax.imageio.*; -import javax.imageio.stream.*; -import javax.swing.*; -import javax.swing.border.Border; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.filechooser.FileFilter; - -import java.io.*; -import java.text.*; -import java.util.*; -import java.util.List; - -import ohd.hseb.sshp.*; -import ohd.hseb.sshp.gui.GuiHelper; -import ohd.hseb.sshp.gui.PrecipPainter; -import ohd.hseb.sshp.gui.PrecipTotalTextPainter; -import ohd.hseb.sshp.gui.SettingPanel; -import ohd.hseb.sshp.gui.SigStageLinePainter; -import ohd.hseb.sshp.gui.StagePainter; -import ohd.hseb.sshp.gui.TimeLinePainter; -import ohd.hseb.sshp.gui.TsBackgroundPainter; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.*; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; -import ohd.hseb.util.gui.StandardImageIcons; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.io.RGBTextFileReader; - - -/** - * @author Chip Gobs - * - * Main Frame for the Precip and Stage Canvases and the application itself. - */ -public class AnalysisWindow extends JFrame -{ - private static final String _className = "AnalysisWindow"; - - private static final double MIN_PRECIP_IN_INCHES_PER_HOUR = 0.0; - private static final double MAX_PRECIP_IN_INCHES_PER_HOUR = 20.0; - - private static final double MIN_STAGE_IN_FEET = -10.0; - private static final double MAX_STAGE_IN_FEET = 40000.0; - - private static final double MIN_EVAP_PER_HOUR = 0.0; - private static final double MAX_EVAP_PER_HOUR = 100.0; - - private static final double MIN_RUNOFF_IN_INCHES_PER_HOUR = 0.0; - private static final double MAX_RUNOFF_IN_INCHES_PER_HOUR = MAX_PRECIP_IN_INCHES_PER_HOUR; - - private static final long MILLIS_PER_HOUR = 1000 * 60 * 60; - - - // forecast length and spinner constants - //see StreamModel.java for the default length in hours - private static final int FORECAST_LENGTH_SPINNER_STEPS = 6; - - private static final MeasuringUnit _stageUnit = MeasuringUnit.feet; - - private static final String ALLOW_LIVE_SAC_STATE_ADJUSTMENT_TOKEN_NAME = - "sshp_allow_live_state_adjustment"; - - - //determines whether to default to showing the simulated time series or not - private static final String SHOW_SIMULATED_TS_TOKEN_NAME = - "sshp_show_simulated_timeseries"; - private static final boolean _default_show_simulated_timeseries = true; - - private static final String SHOW_UNADJUSTED_STATES_TOKEN_NAME = - "sshp_show_unadjusted_states"; - private static final boolean _default_show_unadjusted_states = false; - - - // application variables - // private StreamModel _streamModel = null; - private ModelManager _modelManager = null; - private AppController _controller = null; - - - - // image storage directory - private String _whfs_image_directoryString = null; - private String _sshp_precip_directoryString = null; - - - // window sizing data - private Dimension _maxDimension = new Dimension(1280, 1024); - private Dimension _initialDimension = new Dimension(1200, 944); - private Dimension _minDimension = new Dimension(800, 700); - - - // the canvases - private TsPaintableCanvas _precipCanvas = null; - private TsPaintableCanvas _stageCanvas = null; - - // data to be used with the canvases - private int _hoursToShowBeforeModelStartTime = 24; - private int _hoursToShowAfterModelStartTime = 72; - - // split pane and its direct contents - private JSplitPane _splitPane = null; - - // canvas value mappers - private ValueMapper _precipValueMapper = null; - private ValueMapper _stageValueMapper = null; - - // these Painters are in this class because of the ability to modify the way the canvases are - // painted. The modifications are made in this class. - // The painters have special options which are invoked. Then, upon repainting, the - // painter paints in the way dictated by those options. - private SigStageLinePainter _floodStageLinePainter = null; - private SigStageLinePainter _majorFloodStageLinePainter = null; - private StagePainter _observedStageTsPainter = null; - private StagePainter _simulatedStageTsPainter = null; - private StagePainter _forecastPainter = null; - private StagePainter _priorForecastPainter = null; - - - private PrecipPainter _precipPainter = null; - private PrecipTotalTextPainter _precipTextTotalPainter = null; - private TsBackgroundPainter _stageBackgroundPainter = null; - private TsBackgroundPainter _precipBackgroundPainter = null; - - private Font _buttonFont = null; - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - - - //vcr buttons - private JPanel _timeButtonPanel = null; - private JButton _forwardButton = null; - private JButton _forward1DayButton = null; - private JButton _backButton = null; - private JButton _back1DayButton = null; - private JButton _recenterButton = null; - - - //action buttons - private JButton _closeButton = null; - private JButton _windowLauncherButton = null; - private JPanel _windowButtonPanel = null; - private JButton _screenCaptureButton = null; - - - // model control panel - private JPanel _modelControlPanel = null; - private JLabel _modelControlPanelLabel = null; - private JLabel _modelTypeComboBoxLabel = null; - private JComboBox _modelTypeComboBox = null; - private String[] _modelTypeNameArray = null; - private JLabel _uhgComboBoxLabel = null; - private JComboBox _uhgComboBox = null; - - private JLabel _adjustmentCheckBoxLabel = null; - private JCheckBox _adjustmentCheckBox = null; - private JLabel _adjustmentLastObsInputTimeLabel = null; - private DateTimeTextField _adjustmentLastObsInputTimeTextField = null; - private JLabel _blendPeriodSpinnerLabel = null; - private JSpinner _blendPeriodSpinner = null; - - - //These share the same spot on the model control panel, depending on - // the model being used - private JComboBox _sacStartingStateComboBox = null; - private JButton _sacStateListRefreshButton = null; - private JComboBox _apiMkcStartingStateComboBox = null; - private JButton _apiMkcStateRefreshButton = null; - - private JLabel _forecastHoursSpinnerLabel = null; - private JSpinner _forecastHoursSpinner = null; - - - // loose on the button panel - private JLabel _modelRunStartTimeLabel = null; - private JLabel _modelRunStartTimeValueLabel = null; - - - // SAC_SMA control panel - private JPanel _sacControlPanel = null; - private JLabel _sacControlPanelLabel = null; - private JButton _sacParamsButton = null; - private JButton _sacStateButton = null; -// private JButton _sacMonthlyMapeValuesEditorButton = null; - - private JButton _sacLiveStateAdjustmentButton = null; - private boolean _allowLiveSacAdjustment = false; - - private JCheckBox _sacShowAlternateForecastsCheckBox = null; - private JCheckBox _sacShowPastForecastsCheckBox = null; - - private boolean _showAlternateForecasts = false; - private boolean _showPastForecasts = false; - - private JButton _sacSetVarInitialStateButton = null; - - // time series editing and saving panel - private JMenuBar _menuBar = null; - - private boolean _showUnadjustedStates = true; - - - - //API-MKC variable setting/resetting buttons for model settings - private JPanel _apiMkcControlPanel = null; - private JLabel _apiMkcSettingsLabel = null; - private JLabel _modelStateLabel = null; - - private SettingPanel _apiMkcInitialStagePanel = null; - private SettingPanel _apiMkcFfhPanel = null; - private SettingPanel _apiMkcThreshRPanel = null; - - private JCheckBox _apiMkcUseCustomModelRunTimeCheckBox = null; - private DateTimeTextField _apiMkcCustomModelRunDateTimeTextField = null; - private JButton _apiMkcApplySettingsButton = null; - - - // associated API-MKC variables - private boolean _apiMkcUseCustomModelRunTime = false; - - //used to help control how events are processed - private boolean _reloadingApiMkcStartingStateComboBox = false; - private boolean _reloadingSacStartingStateComboBox = false; - - - // graphing controls - private JPanel _graphControlPanel = null; - private JLabel _graphControlPanelLabel = null; - - private JCheckBox _showFloodStageCheckBox = null; - private JCheckBox _showMajorFloodStageCheckBox = null; - private JCheckBox _showObsHeightTsCheckBox = null; - private JCheckBox _showPrecipAmountsCheckBox = null; - private JCheckBox _delayRerunCheckBox = null; - private JCheckBox _showMinorPrecipTicksCheckBox = null; - private JCheckBox _showMinorStageTicksCheckBox = null; - private JCheckBox _showSimulatedStageCheckBox = null; - - // booleans related to visual controls - private boolean _forceShowFloodStage = true; - private boolean _forceShowMajorFloodStage = false; - private boolean _showPrecipAmounts = true; - private boolean _showObservedHeightData = true; - private boolean _delayRerunModelWhileDrawing = false; - private boolean _showMinorPrecipTicks = false; - private boolean _showMinorStageTicks = true; - private boolean _showSimulatedStage = true; - - //main window layer - private JPanel _mainPanel = null; - private JPanel _buttonPanel = null; - - // misc - private JFileChooser _imageFileChooser = null; - private FileChooserHelper _precipFileChooserHelper = null; - private FileChooserHelper _imageFileChooserHelper = null; - - // data - private TimeHolder _modelStartTimeHolder = null; - private int _intervalInHours = 1; - - private int _millisPerHour = 1000 * 60 * 60; - - private String _defaultFormatString = "0.00"; - private double _defaultMissingValue = -9999.0; - - - // model starting state descriptors - private SacSmaStateDescriptor _selectedSacStateDescriptor = null; - private FFHDescriptor _selectedFFHDescriptor = null; - - - //debugging - private CodeTracer _tracer = null; - - - private Map _colorMap = null; - private String _colorFilePath = null; - - // ----constructors------------------------------------- - - public AnalysisWindow(ModelManager modelManager, AppController controller) - { - //init the other application objects that this object talks to - //_streamModel = streamModel; - _modelManager = modelManager; - - _controller = controller; - - _tracer = new CodeTracer(); - - _modelStartTimeHolder = getPrimaryStreamModel().getModelStartTimeHolder(); - - getAppsDefaults(); - - RGBTextFileReader reader = new RGBTextFileReader(); - _colorMap = reader.read(_colorFilePath); - - - initGui(); - - } //AnalysisWindow - - // ------------------------------------------------------------ - private void getAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - - // determine if the secret adjustment window should be available - if (ad.getToken(ALLOW_LIVE_SAC_STATE_ADJUSTMENT_TOKEN_NAME) != null ) - { - _allowLiveSacAdjustment = true; - } - - // default value for the show simulated stage time series toggle button - _showSimulatedStage = ad.getBoolean(SHOW_SIMULATED_TS_TOKEN_NAME, - _default_show_simulated_timeseries); - - _showUnadjustedStates = ad.getBoolean(SHOW_UNADJUSTED_STATES_TOKEN_NAME, - _default_show_unadjusted_states); - - _sshp_precip_directoryString = ad.getToken("sshp_precip_dir"); - - _whfs_image_directoryString = ad.getToken("whfs_image_dir"); - - _colorFilePath = ad.getToken("color_file_path", "/usr/lib/X11/rgb.txt"); - - } - - // ------------------------------------------------------------ - - private void initGui() - { - - String header = "AnalysisWindow.initGui(): "; - // System.out.println(header + "starting."); - int x = 10; - int y = 10; - int width = 700; - int height = 200; - - int horizontalMargin = 50; - int verticalMargin = 40; - - Dimension prefSplitPaneSize = - new Dimension(width + horizontalMargin, - (2*height) + verticalMargin); - - initTitle(); - - initMenuBar(); - - //set up the 2 canvases and all of their containers - initPrecipCanvas(x, y, width, height, _modelStartTimeHolder); - initStageCanvas(x, y, width, height, _modelStartTimeHolder); - - _splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, - _precipCanvas, - _stageCanvas); - - - _splitPane.setOneTouchExpandable(true); - _splitPane.setPreferredSize(prefSplitPaneSize); - // _splitPane.setDividerLocation(.50); - - - //init "loose" GUI items - initStatusAndReloadControls(); - - // init model control panel - initModelControlPanel(); - - // create the window control button(s) - initWindowButtonPanel(); - - // SAC gui launch buttons - initSacControlPanel(); - - // init the KC-API model parameter controls - initApiMkcControlPanel(); - - // visual controls - initGraphControlPanel(); - - // add the buttons to the _buttonPanel - _buttonPanel = new JPanel(); - _buttonPanel.setLayout(new GridBagLayout()); - GridBagConstraints buttonGbc = new GridBagConstraints(); - - - //panel for the model run start time Labels - JPanel modelRunStartTimePanel = new JPanel(); - modelRunStartTimePanel.add(_modelRunStartTimeLabel); - modelRunStartTimePanel.add(_modelRunStartTimeValueLabel); - - -// col, row numCols numRows Wcol wrow - //row 0 - buttonGbc.insets = new Insets(5,2,5,2); - - addComponent(_buttonPanel, _modelControlPanel, buttonGbc, 0, 0, 1, 3, 0, 0); - addComponent(_buttonPanel, _graphControlPanel, buttonGbc, 1, 0, 1, 3, 0, 0); - //only 1 of the following panels shows at a time - - - - addComponent(_buttonPanel, _apiMkcControlPanel, buttonGbc, 2, 0, 1, 3, 0, 0); - addComponent(_buttonPanel, _sacControlPanel, buttonGbc, 2, 0, 1, 3, 0, 0); - - addComponent(_buttonPanel, modelRunStartTimePanel, buttonGbc, 0, 4, 1, 1, 0, 0); - - - // col, row numCols numRows Wcol wrow - - //row 6 - - buttonGbc.insets = new Insets(5,5,5,5); - buttonGbc.anchor = GridBagConstraints.WEST; - addComponent(_buttonPanel, _windowButtonPanel, buttonGbc, 1, 4, 1, 1, 1, 0); - - - //create the main panel - _mainPanel = new JPanel(); - - //add the components to the panel - GridBagLayout layoutMgr = new GridBagLayout(); - - GridBagConstraints mainGbc = new GridBagConstraints(); - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _mainPanel.setLayout(layoutMgr); - - // add components to the main panel - - // col, row numCols numRows Wcol wrow - - - setJMenuBar(_menuBar); - addComponent(_mainPanel, _splitPane, mainGbc, 0, 0, 3, 10, 1, 1); - addComponent(_mainPanel, _buttonPanel, mainGbc, 0, 10, 1, 2, 0, 0); - - - //set up initial bounds limitations - //see WindowResize listener for the minimum setting - - Rectangle maxBoundsRectangle = new Rectangle(_maxDimension); - this.setMaximizedBounds(maxBoundsRectangle); - - - //add the panel to the Frame and initialize the frame - this.getContentPane().add(_mainPanel); - this.pack(); - - - Rectangle initialBoundsRectangle = new Rectangle(_initialDimension); - this.setBounds(initialBoundsRectangle); - - //set up the KC-API settings - resetInitialStageMeasurementFromModel(); - resetFfhFromModel(); - resetThresholdRunoffFromModel(); - - - //make sure that the appropriate controls are visible - setComponentVisibility(); - - //add all of the event handlers - addListeners(); - - //select the RainfallRunoffModel - initModelChoice(); - } - - // ------------------------------------------------------------ - private String getCenteredText(String origText) - { - String centeredText = "
    " + origText + "
    "; - - return centeredText; - } -// ------------------------------------------------------------ - private String getVerticalText(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - buffer.append(charArray[i]); - - //don't do a break for the last one - if (i < charArray.length-1) - { - buffer.append("
    "); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } - // ------------------------------------------------------------ - - private void initTimeButtonPanel() - { - Dimension dimension = new Dimension(24, 28); - - Color buttonColor = this.getBackground(); - Color imageColor = Color.BLUE; - - ImageIcon rightArrowIcon = StandardImageIcons.getImageIcon(StandardImageIcons.RIGHT_ARROW, - imageColor, buttonColor, dimension); - ImageIcon leftArrowIcon = StandardImageIcons.getImageIcon(StandardImageIcons.LEFT_ARROW, - imageColor, buttonColor, dimension); - - - ImageIcon doubleRightArrowIcon = StandardImageIcons.getImageIcon(StandardImageIcons.DOUBLE_RIGHT_ARROW, - imageColor, buttonColor, dimension); - - ImageIcon doubleLeftArrowIcon = StandardImageIcons.getImageIcon(StandardImageIcons.DOUBLE_LEFT_ARROW, - imageColor, buttonColor, dimension); - - ImageIcon circleIcon = StandardImageIcons.getImageIcon(StandardImageIcons.CIRCLE, - imageColor, buttonColor, dimension); - - - _forwardButton = GuiHelper.getJButton(rightArrowIcon); - _forwardButton.setToolTipText("Slide display forward 1 hour.") ; - - _forward1DayButton = GuiHelper.getJButton(doubleRightArrowIcon); - _forward1DayButton.setToolTipText("Slide display forward 24 hours."); - - _recenterButton = GuiHelper.getJButton(circleIcon); - _recenterButton.setToolTipText("Recenter display around the model run start time."); - - _backButton = GuiHelper.getJButton(leftArrowIcon); - _backButton.setToolTipText("Slide display back 1 hour."); - - _back1DayButton = GuiHelper.getJButton(doubleLeftArrowIcon); - _back1DayButton.setToolTipText("Slide display back 24 hours."); - - - _timeButtonPanel = new JPanel(); - // _timeButtonPanel.setBorder(_panelBorder); - _timeButtonPanel.add(_back1DayButton); - _timeButtonPanel.add(_backButton); - _timeButtonPanel.add(_recenterButton); - _timeButtonPanel.add(_forwardButton); - _timeButtonPanel.add(_forward1DayButton); - - } //end initTimeButtonPanel - - //---------------------------------------------------------------------------------------------------- - private void initGraphControlPanel() - { - - // String header = "AnalysisWindow.initGraphControlPanel(): "; - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.weightx = 1; - gbc.weighty = 1; - - gbc.insets = new Insets(2,2,2,2); - - - _graphControlPanel = new JPanel(); - - JPanel panel = _graphControlPanel; - panel.setBorder(_panelBorder); - - - panel.setLayout(new GridBagLayout()); - - - _graphControlPanelLabel = new JLabel(getCenteredText("Graph Controls:")); - - initTimeButtonPanel(); - - //init the option buttons and the painters that are associated with them - _showFloodStageCheckBox = new JCheckBox("Scale To Flood Stage", - _forceShowFloodStage); - String text = "Display Horizontal Line to represent the flood stage"; - _showFloodStageCheckBox.setToolTipText(text); - - - if (_floodStageLinePainter != null) - { - _floodStageLinePainter.setShouldPaint(_forceShowFloodStage); - } - - //init the option buttons and the painters that are associated with them - _showMajorFloodStageCheckBox = new JCheckBox("Scale To Major Flood Stage", - _forceShowMajorFloodStage); - text = "Display Horizontal Line to represent the major flood stage"; - _showMajorFloodStageCheckBox.setToolTipText(text); - if (_majorFloodStageLinePainter != null) - { - _majorFloodStageLinePainter.setShouldPaint(_forceShowMajorFloodStage); - } - - - //init the option buttons and the painters that are associated with them - - //precip totals - _showPrecipAmountsCheckBox = new JCheckBox("Show Precip Amounts", - _showPrecipAmounts); - text = "Display precip totals (in inches) on the precip bars"; - _showPrecipAmountsCheckBox.setToolTipText(text); - _precipPainter.setShowPrecipAmounts(_showPrecipAmounts); - _precipTextTotalPainter.setShouldPaint(_showPrecipAmounts); - - //observed stages - _showObsHeightTsCheckBox = new JCheckBox("Show Obs Stages", - _showObservedHeightData); - text = "Toggle Observed Stage Time Series"; - _showObsHeightTsCheckBox.setToolTipText(text); - _observedStageTsPainter.setShouldPaint(_showObservedHeightData); - - - // add simulated stage checkbox - _showSimulatedStageCheckBox = new JCheckBox("Show Simulated Stages", _showSimulatedStage); - text = "Toggle Simulated Stage Time Series"; - _showSimulatedStageCheckBox.setToolTipText(text); - _simulatedStageTsPainter.setShouldPaint(_showSimulatedStage); - - - //add delay button - _delayRerunCheckBox = new JCheckBox("Delay Rerun While Drawing", - _delayRerunModelWhileDrawing); - text = "For graphical precip editing, postpones rerunning the model until after the button is released."; - _delayRerunCheckBox.setToolTipText(text); - - - //add minor precip tick checkbox - _showMinorPrecipTicksCheckBox = new JCheckBox("Show Minor Precip Lines", _showMinorPrecipTicks); - text = "Toggle minor precip lines"; - _showMinorPrecipTicksCheckBox.setToolTipText(text); - _precipBackgroundPainter.setShowMinorTicks(_showMinorPrecipTicks); - - // add minor stage tick checkbox - _showMinorStageTicksCheckBox = new JCheckBox("Show Minor Stage Lines", _showMinorStageTicks); - text = "Toggle minor stage lines"; - _showMinorStageTicksCheckBox.setToolTipText(text); - _stageBackgroundPainter.setShowMinorTicks(_showMinorStageTicks); - - - - - JPanel verticalSpacer = new JPanel(); - verticalSpacer.setPreferredSize(new Dimension(30, 34)); - - - // JPanel verticalSpacer2 = new JPanel(); - // verticalSpacer2.setPreferredSize(new Dimension(30, 8)); - - // col, row numCols numRows Wcol wrow - addComponent(panel, _graphControlPanelLabel, gbc, 0, 0, 2, 1, 0, 1); - - - addComponent(panel, _timeButtonPanel, gbc, 0, 1, 2, 1, 0, 1); - - // addComponent(panel, verticalSpacer, gbc, 0, 2, 2, 1, 0, 1); - - addComponent(panel, _showObsHeightTsCheckBox, gbc, 0, 2, 1, 1, 0, 1); - addComponent(panel, _showSimulatedStageCheckBox, gbc, 1, 2, 1, 1, 0, 1); - - - addComponent(panel, _delayRerunCheckBox, gbc, 0, 3, 1, 1, 0, 1); - addComponent(panel, _showFloodStageCheckBox, gbc, 1, 3, 1, 1, 0, 1); - - - addComponent(panel, _showPrecipAmountsCheckBox, gbc, 0, 4, 1, 1, 0, 1); - addComponent(panel, _showMajorFloodStageCheckBox, gbc, 1, 4, 1, 1, 0, 1); - - - addComponent(panel, _showMinorPrecipTicksCheckBox, gbc,0, 5, 1, 1, 0, 1); - addComponent(panel, _showMinorStageTicksCheckBox, gbc, 1, 5, 1, 1, 0, 1); - - - - // addComponent(panel, verticalSpacer2, gbc, 0, 6, 2, 1, 0, 1); - - - - return; - } //end initVisualControlPanel - - //---------------------------------------------------------------------------------------------------- - - - private void initWindowButtonPanel() - { - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.weightx = 1; - gbc.weighty = 1; - - _windowLauncherButton = GuiHelper.getJButton("Control Window..."); - - _screenCaptureButton = GuiHelper.getJButton("Capture Screen"); - - _closeButton = GuiHelper.getJButton("Close"); - - _windowButtonPanel = new JPanel(); - // _windowButtonPanel.setPreferredSize(new Dimension(150, 40)); - - JPanel panel = _windowButtonPanel; - -// JPanel spacingPanel = new JPanel(); -// spacingPanel.setPreferredSize(new Dimension(160, 40)); - - // spacingPanel.setBackground(Color.blue); - // panel.setBackground(Color.yellow); - - // col, row numCols numRows Wcol wrow - - addComponent(panel, _windowLauncherButton, gbc, 0, 0, 1, 1, 1, 0); - addComponent(panel, _screenCaptureButton, gbc, 1, 0, 1, 1, 1, 0); - addComponent(panel, _closeButton, gbc, 2, 0, 1, 1, 1, 0); -// addComponent(panel, spacingPanel, gbc, 1, 0, 1, 1, 1, 1); - - return; - } - - //---------------------------------------------------------------------------------------------------- - - private void initApiMkcControlPanel() - { - Dimension panelDimension = new Dimension(500, 120); - String toolTipText = null; - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.weightx = 1; - gbc.weighty = 1; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.ipadx = 5; - - _apiMkcControlPanel = new JPanel(); - JPanel panel = _apiMkcControlPanel; - panel.setPreferredSize(panelDimension); - - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - - //settings panels for KC-API - _apiMkcSettingsLabel = new JLabel(getCenteredText("API-MKC Settings:")); - - // _apiMkcBaseflowPanel = new SettingPanel("Baseflow (cfs):", 6, "Reload Baseflow"); - _apiMkcInitialStagePanel = new SettingPanel("Initial Stage(feet):", 6, "Reload", "Reload the initial stage from the time series."); - toolTipText = "Initial stage in feet is converted to baseflow in cfs during model run."; - _apiMkcInitialStagePanel.getLabel().setToolTipText(toolTipText); - - - // _apiMkcFfhPanel = new SettingPanel("FFH (inches):", 6, "Reload FFH"); - _apiMkcFfhPanel = new SettingPanel("FFH(inches):", 6, "Reload", "Reload the headwater guidance from the database."); - toolTipText = "Headwater guidance value in inches."; - _apiMkcFfhPanel.getLabel().setToolTipText(toolTipText); - - //Threshold Runoff SettingPanel - // _apiMkcThreshRPanel = new SettingPanel("Threshold Runoff (inches):", 6, "Reload T. Runoff"); - _apiMkcThreshRPanel = new SettingPanel("T.Runoff(inches):", 6, "Reload", "Reload the threshold runoff."); - toolTipText = "Threshold Runoff value in inches."; - _apiMkcThreshRPanel.getLabel().setToolTipText(toolTipText); - - - _apiMkcUseCustomModelRunTimeCheckBox = new JCheckBox("Use Custom Time", - _apiMkcUseCustomModelRunTime); - _apiMkcUseCustomModelRunTimeCheckBox.setToolTipText("Sets the Model Run Start Time by overriding the selected FFH time."); - - long latestHourTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(),1); - _apiMkcCustomModelRunDateTimeTextField = new DateTimeTextField(latestHourTime, - AnalysisWindow.this, - "Model Run Start Time", 20); - _apiMkcCustomModelRunDateTimeTextField.setAllowOnlyEvenHours(true); - _apiMkcCustomModelRunDateTimeTextField.setPreferredSize(new Dimension(150, 20)); - _apiMkcCustomModelRunDateTimeTextField.setMaximumSize(new Dimension(150, 20)); - _apiMkcCustomModelRunDateTimeTextField.setMinimumSize(new Dimension(150, 20)); - - - //apply button - _apiMkcApplySettingsButton = GuiHelper.getJButton(getVerticalText("Apply")); - _apiMkcApplySettingsButton.setToolTipText("Applies manual changes to settings on the left."); - - - //create a panel for vertical spacing purposes - JPanel verticalSpacer = new JPanel(); - Dimension verticalSpacerDimension = new Dimension (30, 15); - verticalSpacer.setPreferredSize(verticalSpacerDimension); - verticalSpacer.setMaximumSize(verticalSpacerDimension); - verticalSpacer.setMinimumSize(verticalSpacerDimension); - - - // JPanel for layout purposes of the dateTimeTextField - JPanel dateTimeTextFieldPanel = new JPanel(); - dateTimeTextFieldPanel.setLayout(new GridBagLayout()); - // dateTimeTextFieldPanel.setBackground(Color.yellow); - dateTimeTextFieldPanel.setPreferredSize(new Dimension (209, 30)); - - JPanel spacer1 = new JPanel(); - // spacer1.setBackground(Color.red); - Dimension spacer1Dimension = new Dimension (50, 30); - spacer1.setPreferredSize(spacer1Dimension); - spacer1.setMaximumSize(spacer1Dimension); - spacer1.setMinimumSize(spacer1Dimension); - - // add components to the special dateTimeTextFieldPanel - // col, row numCols numRows Wcol wrow - addComponent(dateTimeTextFieldPanel, - _apiMkcCustomModelRunDateTimeTextField, gbc, 0, 0, 3, 1, 1, 0); - addComponent(dateTimeTextFieldPanel, spacer1, gbc, 3, 0, 1, 1, 0, 0); - - - - // col, row numCols numRows Wcol wrow - - addComponent(panel, _apiMkcSettingsLabel, gbc, 0, 0, 2, 1, 0, 0); - - addComponent(panel, - _apiMkcUseCustomModelRunTimeCheckBox, gbc, 0, 2, 1, 1, 0, 0); - addComponent(panel, - dateTimeTextFieldPanel, gbc, 1, 2, 3, 1, 0, 0); - - - addComponent(panel, - _apiMkcInitialStagePanel.getLabel(), gbc, 0, 3, 1, 1, 0, 0); - addComponent(panel, - _apiMkcInitialStagePanel.getTextField(), gbc, 1, 3, 1, 1, 0, 0); - addComponent(panel, - _apiMkcInitialStagePanel.getButton(), gbc, 3, 3, 1, 1, 0, 0); - - addComponent(panel, _apiMkcFfhPanel.getLabel(), gbc, 0, 4, 1, 1, 0, 0); - addComponent(panel, _apiMkcFfhPanel.getTextField(), gbc, 1, 4, 1, 1, 0, 0); - addComponent(panel, _apiMkcFfhPanel.getButton(), gbc, 3, 4, 1, 1, 0, 0); - - addComponent(panel, _apiMkcThreshRPanel.getLabel(), gbc, 0, 5, 1, 1, 0, 0); - addComponent(panel, _apiMkcThreshRPanel.getTextField(),gbc, 1, 5, 1, 1, 0, 0); - addComponent(panel, _apiMkcThreshRPanel.getButton(), gbc, 3, 5, 1, 1, 0, 0); - - // gbc.insets = new Insets(3, 3, 3, 3); - addComponent(panel, _apiMkcApplySettingsButton, gbc, 2, 3, 1, 3, 0, 0); - - addComponent(panel, verticalSpacer, gbc, 1, 6, 1, 1, 0, 0); - - - } //end initApiModelPanel() - - // ---------------------------------------------------------------------------------------------------- - - private void initApiMkcStateComboBox(JComboBox comboBox) - { - String header = "AnalysisWindow.initApiMkcTimeComboBox(): "; - //System.out.println(header + "starting"); - - _reloadingApiMkcStartingStateComboBox = true; - - //load all of the possible values from the db - List ffhDescriptorList = getPrimaryStreamModel().getFFHDescriptorList(); - boolean foundMatch = false; - - FFHDescriptor localSelectedDescriptor = null; - - // get a list of strings for this descriptor list - - comboBox.removeAllItems(); - - - - // add the FFHDescriptors as items to the list - - // System.out.println(header + "initially selectedFFHDescriptor = " + _selectedFFHDescriptor); - - for (int i = 0; i < ffhDescriptorList.size(); i++) - { - FFHDescriptor descriptor = (FFHDescriptor) ffhDescriptorList.get(i); - - - // if the item being added equals the previously selected item, - // note the item. - if (_selectedFFHDescriptor != null) - { - //System.out.println(header + "selectedFFHDescriptor = " + _selectedFFHDescriptor); - //System.out.println(header + "testing equality against Descriptor = " + descriptor); - if - ( - (!foundMatch) && - (_selectedFFHDescriptor.equals(descriptor)) - ) - - { - localSelectedDescriptor = descriptor; - foundMatch = true; - //System.out.println(header + "localSelectedDescriptor = " + localSelectedDescriptor); - } - } - - // add it to the list - comboBox.addItem(descriptor); - } - - _reloadingApiMkcStartingStateComboBox = false; - - // select the already selected item, if there was one - if (localSelectedDescriptor != null) - { - comboBox.setSelectedItem(localSelectedDescriptor); - } - - - return; - - } //end initKcApiTimeComboBox() - - // ---------------------------------------------------------------------------------------------------- - /* - private long getModelRunTimeFromKcApiComboBox() - { - long time = 0; - FFHDescriptor descriptor =(FFHDescriptor)_apiMkcStartingStateComboBox.getSelectedItem(); - - if (descriptor != null) - { - time = descriptor.getTime(); - } - - return time; - } - */ - // ---------------------------------------------------------------------------------------------------- - - private void initSacStateComboBox(JComboBox comboBox) - { - String header = "AnalysisWindow.initSacStateComboBox(): "; - final int ROWS_IN_COMBOBOX_BEFORE_SCROLLING = 30; - - //prevent selection of the added items until it is done loading - _reloadingSacStartingStateComboBox = true; - - comboBox.removeAllItems(); - - List sacSmaStateDescriptorList = _modelManager.getSacSmaStateDescriptorListWithBogusStateIfEmpty(_showUnadjustedStates); - - SacSmaStateDescriptor localSelectedSacStateDescriptor = null; - boolean foundMatch = false; - - //load each descriptor into the comboBox. Also when you find the - //selected descriptor store a reference to it. - for (SacSmaStateDescriptor descriptor : sacSmaStateDescriptorList) - { - //System.out.println(header + "descriptor = " + descriptor); - - comboBox.addItem(descriptor); - - // look for the currently selected item - if ( (!foundMatch) && - (_selectedSacStateDescriptor != null) && - (descriptor.equals(_selectedSacStateDescriptor)) - ) - { - foundMatch = true; - localSelectedSacStateDescriptor = descriptor; - } - } //end for - - - // set the comboBox to the selected descriptor, if it exists - _reloadingSacStartingStateComboBox = false; - - if (localSelectedSacStateDescriptor != null) - { - comboBox.setSelectedItem(localSelectedSacStateDescriptor); - } - else - { - comboBox.setSelectedIndex(0); - } - - comboBox.setMaximumRowCount(ROWS_IN_COMBOBOX_BEFORE_SCROLLING); - - return; - - } - //---------------------------------------------------------------------------------- - private void initStatusAndReloadControls() - { - /* init the following controls - _modelRunStartTimeLabel - _modelRunStartTimeValueLabel - */ - Dimension buttonDimension = new Dimension(120, 30); - _modelRunStartTimeLabel = new JLabel("Model Run Start Time: "); - - //initialize the model run start time value label - JPanel panel = _buttonPanel; - - _modelRunStartTimeValueLabel = new JLabel(); - String dateTimeString = getDateTimeStringToMinutes(_modelStartTimeHolder.getTime()); - _modelRunStartTimeValueLabel.setText(dateTimeString); - - return; - } - //---------------------------------------------------------------------------------- - - private void initModelControlPanel() - { - Dimension panelDimension = new Dimension(400, 250); - Dimension buttonDimension = new Dimension(120, 30); - String text = null; - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - _modelControlPanel = new JPanel(); - _modelControlPanel.setPreferredSize(panelDimension); - - JPanel panel = _modelControlPanel; - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - _modelControlPanelLabel = new JLabel(getCenteredText("Model Controls:")); - - // init ComboBox panel - // _modelTypeComboBoxLabel = new JLabel("Rainfall-Runoff Model:"); - _modelTypeComboBoxLabel = new JLabel("Rainfall-Runoff Model:"); - initModelComboBox(); - // _modelTypeComboBox.setPreferredSize(new Dimension(100, 35)); - - _uhgComboBoxLabel = new JLabel("UHG:"); - initUHGComboBox(); - - - // API-MKC model state comboBox related controls - - //state refresh controls - - // _modelStateLabel = new JLabel("State:"); - _apiMkcStartingStateComboBox = GuiHelper.getJComboBox(); - initApiMkcStateComboBox(_apiMkcStartingStateComboBox); - - - _apiMkcStateRefreshButton = GuiHelper.getJButton("Refresh State List"); - text = "Reload available API-MKC states from the database."; - _apiMkcStateRefreshButton.setToolTipText(text); - _apiMkcStateRefreshButton.setPreferredSize(buttonDimension); - - - //SAC-SMA model state comboBox related controls - _sacStartingStateComboBox = GuiHelper.getJComboBox(); - initSacStateComboBox(_sacStartingStateComboBox); - _sacStateListRefreshButton = GuiHelper.getJButton("Refresh State List"); - text = "Reload available SAC-SMA states from the database."; - _sacStateListRefreshButton.setToolTipText(text); - _sacStateListRefreshButton.setPreferredSize(buttonDimension); - - // JSeparator separator1 = new JSeparator(); - - - // The forecast length spinner -// set up the spinner control for time - - - _forecastHoursSpinnerLabel = new JLabel("Fcst Hours:"); - - int initialValue = getPrimaryStreamModel().getForecastLengthInHours(); - int min = 1; - int max = getPrimaryStreamModel().getMaxForecastLengthInHours(); - int step = FORECAST_LENGTH_SPINNER_STEPS; - - SpinnerModel forecastHoursSpinnerModel = - new SpinnerNumberModel(initialValue, min, max, step); - - _forecastHoursSpinner = new JSpinner(forecastHoursSpinnerModel); - - JPanel spinnerPanel = new JPanel(); //used to get the controls to stick together nicely - spinnerPanel.add(_forecastHoursSpinnerLabel); - spinnerPanel.add(_forecastHoursSpinner); - - - //------- The forecast adjustment controls - - // Forecast Adjustment ON/OFF controls - _adjustmentCheckBoxLabel = new JLabel("Adjust by Observed"); - _adjustmentCheckBox = new JCheckBox(); - _adjustmentCheckBox.setSelected(getPrimaryStreamModel().isAdjustmentOn()); - - JPanel adjustmentCheckBoxPanel = new JPanel(); - adjustmentCheckBoxPanel.add(_adjustmentCheckBoxLabel); - adjustmentCheckBoxPanel.add(_adjustmentCheckBox); - - - - //Blending period hours Spinner - _blendPeriodSpinnerLabel = new JLabel("Blend Ahead Hours"); - String toolTipText = "Note: Zero hours blended can still result in 1 \"extra\" non-blended adjustment (by pairing)."; - _blendPeriodSpinnerLabel.setToolTipText(toolTipText); - - int initialAdjustmentHoursValue = getPrimaryStreamModel().getBlendingHours(); - - // Initialize spinner to select the blending hours - min = 0; - max = getPrimaryStreamModel().getMaxBlendingHours(); - step = 6; - - if (initialAdjustmentHoursValue < 0) - { - initialAdjustmentHoursValue = 0; - } - if (initialAdjustmentHoursValue > max) - { - max = initialAdjustmentHoursValue; - } - - SpinnerModel blendSpinnerModel = new SpinnerNumberModel(initialAdjustmentHoursValue, - min, max, step); - _blendPeriodSpinner = new JSpinner(blendSpinnerModel); - _blendPeriodSpinner.setToolTipText("The number of hours after the last observed input time to blend.\n" + - "Zero hours will blend the last observed input hour if there is a match with the forecast."); - - - JPanel adjustmentSpinnerPanel = new JPanel(); - adjustmentSpinnerPanel.add(_blendPeriodSpinnerLabel); - adjustmentSpinnerPanel.add(_blendPeriodSpinner); - - - // init the DateTimeTextField (our custom class) - - toolTipText = "Last Observed Input Time For Adjustment. Click on Text Box to edit."; - _adjustmentLastObsInputTimeLabel = new JLabel("Last Obs. Time For Adjust"); - _adjustmentLastObsInputTimeLabel.setToolTipText(toolTipText); - - _adjustmentLastObsInputTimeTextField = new DateTimeTextField(getLastObservedStageTime(), - AnalysisWindow.this, - "Last Observed Input Time For Adjustment", 20); - - _adjustmentLastObsInputTimeTextField.setPreferredSize(new Dimension(100, 30)); - - - // JSeparator separator2 = new JSeparator(); - - JPanel modelTypePanel = new JPanel(); - - modelTypePanel.add(_modelTypeComboBoxLabel); - modelTypePanel.add(_modelTypeComboBox); - modelTypePanel.add(_uhgComboBoxLabel); - modelTypePanel.add(_uhgComboBox); - - modelTypePanel.setPreferredSize(new Dimension(100, 40)); - //_modelTypeComboBox.setPreferredSize(new Dimension(100, 40)); - // _modelTypeComboBoxLabel.setPreferredSize(new Dimension(50, 40)); - - // col, row numCols numRows Wcol wrow - addComponent(panel, _modelControlPanelLabel, gbc, 0, 0, 1, 1, 1, 0); - - //addComponent(panel, _modelTypeComboBoxLabel, gbc, 0, 1, 1, 1, 0, 0); - //addComponent(panel, _modelTypeComboBox, gbc, 1, 1, 2, 1, 0, 0); - addComponent(panel, modelTypePanel, gbc, 0, 1, 4, 1, 0, 0); - - // addComponent(panel, _uhgComboBoxLabel, gbc, 3, 1, 1, 1, 0, 0); - // addComponent(panel, _uhgComboBox, gbc, 4, 1, 1, 1, 0, 0); - - - //API_MKC controls - - addComponent(panel, _apiMkcStartingStateComboBox, gbc,0, 2, 2, 1, 0, 0); - addComponent(panel, _apiMkcStateRefreshButton,gbc, 0, 3, 1, 1, 0, 0); - - ///SAC-SMA controls - addComponent(panel, _sacStartingStateComboBox, gbc, 0, 2, 2, 1, 0, 0); - addComponent(panel, _sacStateListRefreshButton, gbc, 0, 3, 1, 1, 0, 0); - - - addComponent(panel, spinnerPanel, gbc, 1, 3, 1, 1, 0, 0); - - - // addComponent(panel, _modelStateLabel, gbc, 0, 3, 1, 1, 0, 0); - //one or the other will be visible - - JSeparator separator = new JSeparator(JSeparator.HORIZONTAL); - addComponent(panel, separator, gbc, 0, 4, 2, 1, 0, 0); - - - //adjustment controls - addComponent(panel, adjustmentCheckBoxPanel, gbc, 0, 5, 1, 1, 0, 0); - - addComponent(panel, adjustmentSpinnerPanel, gbc, 1, 5, 1, 1, 0, 0); - - - addComponent(panel, - _adjustmentLastObsInputTimeLabel, gbc, 0, 6, 1, 1, 0, 0); - addComponent(panel, - _adjustmentLastObsInputTimeTextField, gbc, 1, 6, 1, 1, 0, 0); - - - return; - - } - - //---------------------------------------------------------------------------------- - private void initSacControlPanel() - { - Dimension panelDimension = new Dimension(500, 300); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(3, 3, 3, 3); - gbc.weightx = 1; - gbc.weighty = 1; - - - _sacControlPanel = new JPanel(); - - String toolTipText = null; - - JPanel panel = _sacControlPanel; - panel.setPreferredSize(new Dimension(325, 300)); - panel.setLayout(new GridBagLayout()); - panel.setBorder(_panelBorder); - - panel.setPreferredSize(panelDimension); - - // _sacControlPanelLabel = new JLabel(getCenteredText("SAC-SMA and VAR Settings:")); - _sacControlPanelLabel = new JLabel("SAC-SMA and VAR Settings:"); - - _sacParamsButton = new JButton("Edit Params..."); - _sacParamsButton.setToolTipText("Open the SAC-SMA Parameters Editor"); - - _sacStateButton = new JButton("Edit States..."); - _sacStateButton.setToolTipText("Open the SAC-SMA State Editor"); - - // _sacMonthlyMapeValuesEditorButton = new JButton("MAPE Monthly Values..."); - // _sacMonthlyMapeValuesEditorButton.setToolTipText("Open the MAPE Monthly Values Editor"); - - //init the (probably temporary) Setting adjustment button. - - _sacLiveStateAdjustmentButton = new JButton("Live Adjust State..."); - //_sacLiveStateAdjustmentButton.setPreferredSize(new Dimension(50, 30)); - _sacLiveStateAdjustmentButton.setToolTipText("Open the Live SAC-SMA State Adjuster."); - - //check box for showing alternate current time forecasts, where current time means, at the - //same time as the model run start time - _sacShowAlternateForecastsCheckBox = new JCheckBox("Show Alt. Fcsts"); - _sacShowAlternateForecastsCheckBox.setToolTipText("Show All Alternate forecasts created from model states at the same time."); - - _sacShowAlternateForecastsCheckBox.addActionListener(new ShowAlternateForecastsCheckBoxListener()); - - _sacShowAlternateForecastsCheckBox.setSelected(true); - _sacShowAlternateForecastsCheckBox.doClick(); //change it back to false - - - _sacShowPastForecastsCheckBox = new JCheckBox("Show Past Fcsts"); - _sacShowPastForecastsCheckBox.setToolTipText(" Show past forecasts created from all displayed model states.
    " + - "These are to be shown at the selected intervals
    up to the selected number of hours in the past. "); - - _sacShowPastForecastsCheckBox.setSelected(true); - _sacShowPastForecastsCheckBox.doClick(); //change it back to false - - _sacShowPastForecastsCheckBox.addActionListener(new ShowPastForecastsCheckBoxListener()); - - //Button for making a copy of currently-selected state - _sacSetVarInitialStateButton = new JButton("Reset VAR State..."); - _sacSetVarInitialStateButton.setToolTipText("Reset the VAR Starting State"); - - //Hours back setting panel - toolTipText = "Set the number of hours back in the past\n for which to show forecasts from prior states."; - SettingPanel hoursBackSettingPanel = new SettingPanel("Fcst Hours In Past:", 3, "Display", toolTipText); - hoursBackSettingPanel.getTextField().setToolTipText(toolTipText); - - - //Interval setting panel - toolTipText = "Set the interval in hours\n for which to show forecasts from prior states."; - SettingPanel intervalSettingPanel = new SettingPanel("Fcst Interval:", 3, "Display", toolTipText); - intervalSettingPanel.getTextField().setToolTipText(toolTipText); - - intervalSettingPanel.getButton().setVisible(false); - - - ActionListener listener = new SetHoursBackAndIntervalHoursForPreviousForecastsActionListener( - hoursBackSettingPanel.getTextField(), - intervalSettingPanel.getTextField()); - - hoursBackSettingPanel.getButton().addActionListener(listener); - - hoursBackSettingPanel.getTextField().setText(String.valueOf(24)); - intervalSettingPanel.getTextField().setText(String.valueOf(6)); - //the interval and the hoursBack will share a button, the one that belongs to hoursBackSettingPanel. - //the interval setting panel's button will be invisible. - - //panel to take up space - - -// Note: setMinimumSize() does not work for this purpose, use setPreferredSize() instead - - JPanel verticalSpaceFiller1 = new JPanel(); - verticalSpaceFiller1.setPreferredSize(new Dimension(50, 50)); - JPanel verticalSpaceFiller2 = new JPanel(); - verticalSpaceFiller2.setPreferredSize(new Dimension(85, 150)); - JPanel horizontalSpaceFiller1 = new JPanel(); - horizontalSpaceFiller1.setPreferredSize(new Dimension(85, 100)); - - JPanel verticalSpaceFiller3 = new JPanel(); - verticalSpaceFiller2.setPreferredSize(new Dimension(85, 150)); - - //just to make things look pretty - // gbc.insets = new Insets(5, 5, 5, 5); - - //Panel label at top - // col, row numCols numRows Wcol wrow - addComponent(panel, _sacControlPanelLabel, gbc, 0, 0, 1, 1, 1, 0); - - - //check boxes across 2nd row - addComponent(panel, - _sacShowAlternateForecastsCheckBox, gbc, 0, 1, 1, 1, 1, 0); - - - addComponent(panel, - _sacShowPastForecastsCheckBox, gbc, 1, 1, 1, 1, 1, 0); - - - //hours back controls across 3rd row - JPanel hoursBackPanel = new JPanel(); - hoursBackPanel.setLayout(new GridBagLayout()); - - hoursBackSettingPanel.getTextField().setPreferredSize(new Dimension(50, 50)); - - addComponent(hoursBackPanel, - hoursBackSettingPanel.getLabel(), gbc, 0, 0, 1, 1, 1, 0); - addComponent(hoursBackPanel, - hoursBackSettingPanel.getTextField(), gbc, 1, 0, 1, 1, 1, 0); - - - - //interval in hours controls - JPanel intervalPanel = new JPanel(); - - intervalPanel.setLayout(new GridBagLayout()); - - intervalSettingPanel.getTextField().setPreferredSize(new Dimension(50, 50)); - - addComponent(intervalPanel, - intervalSettingPanel.getLabel(), gbc, 0, 0, 1, 1, 1, 0); - addComponent(intervalPanel, - intervalSettingPanel.getTextField(), gbc, 1, 0, 1, 1, 1, 0); - - - - //add panels to the 3rd row - addComponent(panel, hoursBackPanel, gbc, 0, 2, 1, 1, 1, 0); - addComponent(panel, intervalPanel, gbc, 1, 2, 1, 1, 1, 0); - - - //add button across 4th row - - - JPanel buttonPanel = new JPanel(); - hoursBackSettingPanel.getButton().setPreferredSize(new Dimension(100, 30)); - JPanel leftFillerPanel = new JPanel(); - leftFillerPanel.setPreferredSize(new Dimension(90, 30)); - JPanel rightFillerPanel = new JPanel(); - rightFillerPanel.setPreferredSize(new Dimension(90, 30)); - - addComponent(buttonPanel, - leftFillerPanel, gbc, 0, 0, 1, 1, 1, 0); - addComponent(buttonPanel, - hoursBackSettingPanel.getButton(), gbc, 0, 1, 1, 1, 1, 0); - addComponent(buttonPanel, - rightFillerPanel, gbc, 0, 2, 1, 1, 1, 0); - - - addComponent(panel, - buttonPanel, gbc, 0, 3, 3, 1, 1, 0); - - - // col, row numCols numRows Wcol wrow - addComponent(panel, _sacParamsButton, gbc, 0, 4, 1, 1, 1, 0); - - addComponent(panel, _sacStateButton, gbc, 1, 4, 1, 1, 1, 0); - - - - addComponent(panel, - _sacSetVarInitialStateButton, gbc, 0, 5, 1, 1, 1, 0); - - - if (_allowLiveSacAdjustment) - { - - addComponent(panel, - _sacLiveStateAdjustmentButton, gbc, 1, 5, 1, 1, 1, 0); - } - - // addComponent(panel, - // _sacMonthlyMapeValuesEditorButton, gbc, 0, 5, 1, 1, 1, 0); - - - - } //end initSacButtonPanel() - - // ------------------------------------------------------------ - // ------------------------------------------------------------ - - private void initModelChoice() - { - // trace(); - - String header = "AnalysisWindow.initModelChoice(): "; - int initialIndex = 0; - String initialSelectedTypeName = getPrimaryStreamModel().getRainfallRunoffModelTypeName(); - - // System.out.println(header + "initialSelectedTypeName = " + initialSelectedTypeName); - - RainfallRunoffModelType[] modelTypeArray = - RainfallRunoffModelType.getModelTypeArray(); - - //find initialSelectedType - for (int i = 0; i < modelTypeArray.length; i++) - { - if (modelTypeArray[i].getName().equals(initialSelectedTypeName)) - { - initialIndex = i; - break; - } - } - - _modelTypeComboBox.setSelectedIndex(initialIndex); - - return; - } - - // ------------------------------------------------------------ - - private void initModelComboBox() - { - // note: at some point might want to separate the presentation of the - // name of the model from the built-in model type name - - RainfallRunoffModelType[] modelTypeArray = - RainfallRunoffModelType.getModelTypeArray(); - - _modelTypeNameArray = new String[modelTypeArray.length]; - - - // add the choices to the string array - for (int i = 0; i < modelTypeArray.length; i++) - { - _modelTypeNameArray[i] = modelTypeArray[i].getName(); - } - - //create the comboBox with all the choices in it - _modelTypeComboBox = GuiHelper.getJComboBox(_modelTypeNameArray); - - - return; - } - - // ------------------------------------------------------------ - private void initUHGChoice() - { - // trace(); - - String header = "AnalysisWindow.initUHGChoice(): "; - int initialIndex = 0; - String initialSelectedTypeName = getPrimaryStreamModel().getRainfallRunoffModelTypeName(); - - // System.out.println(header + "initialSelectedTypeName = " + initialSelectedTypeName); - - RainfallRunoffModelType[] modelTypeArray = - RainfallRunoffModelType.getModelTypeArray(); - - //find initialSelectedType - for (int i = 0; i < modelTypeArray.length; i++) - { - if (modelTypeArray[i].getName().equals(initialSelectedTypeName)) - { - initialIndex = i; - break; - } - } - - _uhgComboBox.setSelectedIndex(initialIndex); - - return; - } - -// ----------------------------------------------------------------- - - private void initUHGComboBox() - { - - String[] uhgNamesArray = getPrimaryStreamModel().getUnitHydrographNameArray(); - - //create the comboBox with all the choices in it - _uhgComboBox = GuiHelper.getJComboBox(uhgNamesArray); - - refreshUhgSelection(); - - - return; - } - - //----------------------------------------------------------------- - private void refreshUhgSelection() - { - String selectedUHGModelName =getPrimaryStreamModel().getUnitHydrographSelectionName(); - - _uhgComboBox.setSelectedItem(selectedUHGModelName); - - } - // ----------------------------------------------------------------- - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - //----------------------------------------------------------------- - - private void initTitle() - { - String locationId = getPrimaryStreamModel().getLocationId(); - String locationName = getPrimaryStreamModel().getLocationName(); - String basinId = getPrimaryStreamModel().getBasinId(); - - String rainfallRunoffModelName = getPrimaryStreamModel().getRainfallRunoffModelTypeName(); - - String titleString = "SSHP Analysis Window - Modeling " + locationId + ", " + locationName + - " With BASIN : " + basinId + " using the " + rainfallRunoffModelName + " model"; - setTitle(titleString); - - return; - } - - - - //----------------------------------------------------------------- - private void initPrecipCanvas(int x, int y, - int width, int height, - TimeHolder modelStartTimeHolder) - { - //_precipCanvas = new PrecipCanvas(x, y, width, height); - _precipCanvas = new TsPaintableCanvas(MeasuringUnit.inches, - x, y, - width, height); - - _precipCanvas.setPreferredSize(new Dimension(width, height)); - _precipCanvas.setMinimumSize(new Dimension(100, 10)); - - - MeasuringUnit unit = _precipCanvas.getDisplayedMeasuringUnit(); - - Color outlineColor = Color.WHITE; - - // background painter - _precipBackgroundPainter = - new TsBackgroundPainter(outlineColor, _precipCanvas, "inches", "mm"); - - _precipValueMapper = new UnitValueMapper(MeasuringUnit.inches, - MeasuringUnit.mm); - - _precipBackgroundPainter.setRightLabelValueMapper(_precipValueMapper); - _precipCanvas.addCanvasPainter(_precipBackgroundPainter); - - - - // precip bar painters ------------------------------ - -// add the precip painter - Color barColor = Color.BLUE; - _precipPainter = new PrecipPainter(barColor, - outlineColor, - getPrimaryStreamModel().getPrecipTimeSeriesHolder(), - _showPrecipAmounts, - _precipCanvas); - _precipCanvas.addTsCanvasPainter(_precipPainter); - - //add the precip text total painter - _precipTextTotalPainter = - new PrecipTotalTextPainter(Color.yellow, - getPrimaryStreamModel().getPrecipTimeSeriesHolder(), - _showPrecipAmounts, - _precipCanvas); - _precipCanvas.addCanvasPainter(_precipTextTotalPainter); - - - // add the prior runoff painter - Color runoffColor = Color.YELLOW; - PrecipPainter priorRunoffPrecipPainter = new PrecipPainter(runoffColor, - outlineColor, - getPrimaryStreamModel().getPriorRunoffTimeSeriesHolder(), - false, - _precipCanvas); - - priorRunoffPrecipPainter.setShouldDrawBars(false); - - _precipCanvas.addTsCanvasPainter(priorRunoffPrecipPainter); - - - // add the runoff painter - Color runoffColor2 = Color.MAGENTA; - PrecipPainter runoffPrecipPainter = new PrecipPainter(runoffColor2, - outlineColor, - getPrimaryStreamModel().getRunoffTimeSeriesHolder(), - false, - _precipCanvas); - - runoffPrecipPainter.setShouldDrawBars(false); - - _precipCanvas.addTsCanvasPainter(runoffPrecipPainter); - - - // Model time line color - Color timeLineColor = Color.MAGENTA; - TimeLinePainter modelStartTimeLinePainter = - new TimeLinePainter(timeLineColor, - _modelStartTimeHolder, - _precipCanvas); - - _precipCanvas.addCanvasPainter(modelStartTimeLinePainter); - - - - // set the display time window - setTimeWindowAroundModelStartTime(_precipCanvas); - - - _precipCanvas.setTitle("1-Hour Mean Areal Precipitation Time Series"); - - - } //end initPrecipCanvas - -// ----------------------------------------------------------------- - private void initStageCanvas(int x, int y, - int width, int height, - TimeHolder modelStartTimeHolder) - { - _stageCanvas = new TsPaintableCanvas(MeasuringUnit.feet, - x, y, - width, height); - - _stageCanvas.setPreferredSize(new Dimension(width, height)); - _stageCanvas.setMinimumSize(new Dimension(100, 10)); - - Color outlineColor = Color.WHITE; - - // background Painter - _stageBackgroundPainter = - new TsBackgroundPainter(outlineColor, _stageCanvas, "feet", "cfs"); - - - - _stageValueMapper = getPrimaryStreamModel().getStageToFlowValueMapper(); - - _stageBackgroundPainter.setRightLabelValueMapper(_stageValueMapper); - _stageCanvas.addCanvasPainter(_stageBackgroundPainter); - - - setUpSigRiverLevelDrawing(); - - setUpPrimaryHydrographPainters(); - -/* - // observed hydrograph painter - Color obsColor = Color.yellow; - _observedStageTsPainter = new StagePainter(obsColor, - getPrimaryStreamModel().getObservedStageTimeSeriesHolder(), - _stageCanvas); - _stageCanvas.addTsCanvasPainter(_observedStageTsPainter); - - - // simulated hydrograph painter - Color simulationColor = Color.blue; - _simulatedStageTsPainter = new StagePainter(simulationColor, - getPrimaryStreamModel().getSimulationStageTimeSeriesHolder(), - _stageCanvas, true - ); - _simulatedStageTsPainter.setPointString("X"); - _stageCanvas.addTsCanvasPainter(_simulatedStageTsPainter); - // _simulatedStageTsPainter.setShiftAmount(new Point(-4, 3)); - - - - // forecast hydrograph painter - Color forecastColor = Color.green; - _forecastPainter = new StagePainter(forecastColor, - getPrimaryStreamModel().getForecastStageTimeSeriesHolder(), - _stageCanvas, true - ); - _forecastPainter.setPointString("X"); - - _stageCanvas.addTsCanvasPainter(_forecastPainter); - - //prior forecast hydrograph painter - // Color priorForecastColor = new Color(154, 205, 50); //yellow green - Color priorForecastColor = new Color(160,32,240); //purple - _priorForecastPainter = new StagePainter(priorForecastColor, - getPrimaryStreamModel().getPriorForecastStageTimeSeriesHolder(), - _stageCanvas, true - ); - _priorForecastPainter.setPointString("X"); - _stageCanvas.addTsCanvasPainter(_priorForecastPainter); - - */ - - - // Model time line color - Color timeLineColor = Color.MAGENTA; - TimeLinePainter modelStartTimeLinePainter = - new TimeLinePainter(timeLineColor, - _modelStartTimeHolder, - _stageCanvas); - - _stageCanvas.addCanvasPainter(modelStartTimeLinePainter); - - - - //int intervalInHours = 1; - - long startTime = modelStartTimeHolder.getTime() - (24 * _millisPerHour); - int hoursForward = 72; - long endTime = startTime + (hoursForward * _millisPerHour); - - _stageCanvas.setTimeWindow(startTime, endTime); - - // set the display time window - setTimeWindowAroundModelStartTime(_stageCanvas); - - _stageCanvas.setTitle("Forecast Stage Time Series"); - - - } //end initStageCanvas - -// ----------------------------------------------------------------- - private void setUpHydrographTimeSeriesPainters() - { - - String header = "AnalysisWindow.setUpHydrographTimeSeriesPainters(): "; - // System.out.println(header + "begun"); - - // _stageCanvas.removeTsCanvasPaintersBetweenInclusive(_forecastPainter, _priorForecastPainter); - - _stageCanvas.removeTsCanvasPaintersBetweenInclusive(_observedStageTsPainter, _priorForecastPainter); - - setUpPrimaryHydrographPainters(); - setUpAdditionalHydrographPainters(); - } -// ----------------------------------------------------------------- - private void setUpPrimaryHydrographPainters() - { - String header = "AnalysisWindow.setUpPrimaryHydrographPainters(): "; - - // observed hydrograph painter - Color obsColor = Color.yellow; - - _observedStageTsPainter = new StagePainter(obsColor, - getPrimaryStreamModel().getObservedStageTimeSeriesHolder(), - _stageCanvas); - _stageCanvas.addTsCanvasPainter(_observedStageTsPainter); - - // System.out.println(header + " My _observedStageTsPainter is " + _observedStageTsPainter); - - - - // simulated hydrograph painter - Color simulationColor = Color.blue; - _simulatedStageTsPainter = new StagePainter(simulationColor, - getPrimaryStreamModel().getSimulationStageTimeSeriesHolder(), - _stageCanvas, true - ); - _simulatedStageTsPainter.setPointString("X"); - _stageCanvas.addTsCanvasPainter(_simulatedStageTsPainter); - // _simulatedStageTsPainter.setShiftAmount(new Point(-4, 3)); - - - - // forecast hydrograph painter - Color forecastColor = Color.green; - _forecastPainter = new StagePainter(forecastColor, - getPrimaryStreamModel().getForecastStageTimeSeriesHolder(), - _stageCanvas, true - ); - _forecastPainter.setPointString("X"); - - _stageCanvas.addTsCanvasPainter(_forecastPainter); - - //prior forecast hydrograph painter - // Color priorForecastColor = new Color(154, 205, 50); //yellow green - Color priorForecastColor = new Color(160,32,240); //purple - _priorForecastPainter = new StagePainter(priorForecastColor, - getPrimaryStreamModel().getPriorForecastStageTimeSeriesHolder(), - _stageCanvas, true - ); - _priorForecastPainter.setPointString("X"); - _stageCanvas.addTsCanvasPainter(_priorForecastPainter); - - } //end setUpPrimaryHydrographPainters() -// ----------------------------------------------------------------- - - private void setUpAdditionalHydrographPainters() - { - String header = "AnalysisWindow.setUpAdditionalHydrographPainters(): " ; - StreamModel primaryStreamModel = getPrimaryStreamModel(); - - // System.out.println(header + " _forecastPainter " + _forecastPainter + " _priorForecastPainter = " + _priorForecastPainter); - - //add in the new alternate painters to the _stageCanvas - int index = 0; - - StagePainter painterToAddAfter = _forecastPainter; - - for (StreamModel streamModel : _modelManager.getCompleteStreamModelList()) - { - - if (streamModel != primaryStreamModel) - { - String source = streamModel.getSacState().getSource(); - - - Color simulationColor = getColorByIndex(index); - // Color simulationColor = getColorBySource(source); - StagePainter painter = new StagePainter(simulationColor, - streamModel.getSimulationStageTimeSeriesHolder(), - _stageCanvas, true); - - String pointString = getPointStringByStreamModel(streamModel, index); - - //System.out.println(header + " pointString = " + pointString + " for streamModel = " + streamModel); - - painter.setPointString(pointString); - _stageCanvas.addTsCanvasPainterAfter(painter, painterToAddAfter); - painterToAddAfter = painter; - - //System.out.println(header + "adding painter " + painter + " to the stage canvas."); - - index++; - } - } - - - return; - } - -// ----------------------------------------------------------------- - private String getPointStringByStreamModel(StreamModel streamModel, int index) - { - StringBuffer resultBuffer = new StringBuffer(); - - /* - if (streamModel.isAlternateStreamModel()) - { - resultBuffer.append("A"); //alternate - } - else - { - resultBuffer.append("P"); //primary - } - */ - - //local, adjusted or unadjusted - String sourceOfState = streamModel.getSacState().getSource(); - - resultBuffer.append(sourceOfState.substring(0,1) + index); - - return resultBuffer.toString(); - } -// ----------------------------------------------------------------- - private Color getColorByIndex(int index) - { - - final Color[] colorArray = {Color.WHITE, Color.ORANGE, Color.PINK, Color.MAGENTA, Color.CYAN, Color.YELLOW }; - - int mod = index % colorArray.length; - - return colorArray[mod]; - } -// ---------------------------------------------------------------- - private Color getColorByName(String colorName) - { - return _colorMap.get(colorName.toUpperCase()); - } -// ----------------------------------------------------------------- - - private Color getColorBySource(String source) - { - Color color = null; - - - if (source.equalsIgnoreCase("UNADJ_VAR")) - { - color = getColorByName("cyan"); - } - - else if (source.equalsIgnoreCase("ADJ_VAR")) - { - color = getColorByName("DarkOrange"); - } - else if (source.equalsIgnoreCase("LOCAL")) - { - color = getColorByName("DarkPurple"); - } - else if (source.equalsIgnoreCase("RFC")) - { - color = getColorByName("HotPink"); - } - - else - { - color = Color.pink; - } - - if (color == null) - { - color = Color.white; - } - - return color; - } -// ----------------------------------------------------------------- - - private void setUpSigRiverLevelDrawing() - { -// set up painters for significant stages - SigRiverLevels sigStages = getPrimaryStreamModel().getSigRiverLevels(); - - - - // action stage painter - if ((sigStages != null) && (sigStages.hasActionStage())) - - { - Color actionStageColor = Color.yellow; - Measurement actionStageMeasurement = new Measurement(sigStages.getActionStage(), - MeasuringUnit.feet); - SigStageLinePainter actionStageLinePainter = - new SigStageLinePainter(actionStageColor, - actionStageMeasurement, - _stageCanvas); - - _stageCanvas.addTsCanvasPainter(actionStageLinePainter); - } - -// flood stage painter - if ((sigStages != null) && (sigStages.hasFloodStage())) - { - //this is a darker orange, more easily distinguished - //from Color.yellow than Color.orange - Color betterOrange = new Color(0xFF8C00); - Color floodStageColor = betterOrange ; - Measurement floodStageMeasurement = new Measurement(sigStages.getFloodStage(), - MeasuringUnit.feet); - - - _floodStageLinePainter = - new SigStageLinePainter(floodStageColor, - floodStageMeasurement, - _stageCanvas); - - _stageCanvas.addTsCanvasPainter(_floodStageLinePainter); - } - - if ((sigStages != null) && (sigStages.hasModerateFloodStage())) - { - Color moderateFloodStageColor = Color.red; - Measurement moderateFloodStageMeasurement = - new Measurement(sigStages.getModerateFloodStage(), - MeasuringUnit.feet); - - SigStageLinePainter moderateFloodStageLinePainter = - new SigStageLinePainter(moderateFloodStageColor, - moderateFloodStageMeasurement, - _stageCanvas); - - _stageCanvas.addTsCanvasPainter(moderateFloodStageLinePainter); - } - - if ((sigStages != null) && (sigStages.hasMajorFloodStage())) - { - Color majorFloodStageColor = Color.magenta; - Measurement majorFloodStageMeasurement = - new Measurement(sigStages.getMajorFloodStage(), - MeasuringUnit.feet); - - _majorFloodStageLinePainter = - new SigStageLinePainter(majorFloodStageColor, - majorFloodStageMeasurement, - _stageCanvas); - - _stageCanvas.addTsCanvasPainter(_majorFloodStageLinePainter); - } - - } -// ----------------------------------------------------------------- - private void recenterTimeWindowsAroundModelStartTime() - { - setTimeWindowAroundModelStartTime(_precipCanvas); - setTimeWindowAroundModelStartTime(_stageCanvas); - } - -// ----------------------------------------------------------------- - - private void setTimeWindowAroundModelStartTime(TsPaintableCanvas canvas) - { - int hoursBack = _hoursToShowBeforeModelStartTime; - int hoursForward = _hoursToShowAfterModelStartTime; - - long startTime = _modelStartTimeHolder.getTime() - - (hoursBack * _millisPerHour); - - long endTime = startTime + (hoursForward * _millisPerHour); - canvas.setTimeWindow(startTime, endTime); - - } - -// ----------------------------------------------------------------- - - - public void updateDataPointText(DataPoint dataPoint, ValueMapper valueMapper, TsPaintableCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String leftUnitString = canvas.getDisplayedMeasuringUnit().toString(); - String rightUnitString = valueMapper.getOutputMeasuringUnit().toString(); - - String message = getDataPointString(dataPoint, valueMapper, leftUnitString, rightUnitString); - - //textField.setText(message); - - canvas.setToolTipText(message); - - return; - } - - //----------------------------------------------------------------- - private void setComponentVisibility() - { - RainfallRunoffModelType modelType = getPrimaryStreamModel().getRainfallRunoffModelType(); - - boolean apiMkcVisible = false; - boolean sacSmaVisible = false; - - if (modelType == RainfallRunoffModelType.API_MKC) - { - apiMkcVisible = true; - sacSmaVisible = false; - } - else if (modelType == RainfallRunoffModelType.SAC_SMA) - { - apiMkcVisible = false; - sacSmaVisible = true; - } - - _apiMkcControlPanel.setVisible(apiMkcVisible); - _apiMkcStartingStateComboBox.setVisible(apiMkcVisible); - // _modelStateLabel.setVisible(apiMkcVisible); - _apiMkcStateRefreshButton.setVisible(apiMkcVisible); - - _sacControlPanel.setVisible(sacSmaVisible); - _sacStartingStateComboBox.setVisible(sacSmaVisible); - _sacStateListRefreshButton.setVisible(sacSmaVisible); - - - - return; - } - - //---------------------------------------------------------------------- - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + " Z"; - - return timeString; - } - - //---------------------------------------------------------------------- - private long getTimeOfLatestHour() - { - long time = System.currentTimeMillis(); - - time = TimeHelper.truncateTimeInMillisToNearestHour(time, 1); - - - return time; - } - - // --------------------------------------------------------------------- - private long getLastObservedStageTime() - { - long time = -1; - - try - { - time = getPrimaryStreamModel().getObservedStageTimeSeriesHolder().getTimeSeries().getEndTime(); - } - catch (Throwable t) - { - System.out.println("getLastObservedStageTime(): " + "caught a throwable, but don't worry"); - } - - return time; - } - - //------------------------------------------------------------------------ - -// //---------------------------------------------------------------------- - - private String getDataPointString(DataPoint dataPoint, - ValueMapper valueMapper, - String leftUnitString, - String rightUnitString) - { - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(dataPoint.getY()); - - String mappedValueString = ""; - - if (valueMapper != null) - { - MeasuringUnit inputUnit = valueMapper.getInputMeasuringUnit(); - Measurement inputMeasurement = new Measurement(dataPoint.getY(), inputUnit); - - Measurement mappedMeasurement = valueMapper.getResultMeasurement(inputMeasurement); - - double mappedValue = mappedMeasurement.getValue(); - - mappedValueString = nf.format(mappedValue); - } - - long time = (long) Math.floor( dataPoint.getX()); - - String timeString = getDateTimeStringToMinutes(time); - - String dataPointString = timeString + ", " + - valueString + " " + leftUnitString + ", " + - mappedValueString + " " + rightUnitString; - - return dataPointString; - } - - - // event handler -------------------------------------------------- - - - - //---------------------------------------------------------------------- - - private void replaceTimeSeriesValue(RegularTimeSeriesHolder timeSeriesHolder, - TimeIntervalMeasurement newMeasurement) - { - //String header = "AnalysisWindow.replaceTimeSeriesValue(): "; - - RegularTimeSeries timeSeries = - timeSeriesHolder.getTimeSeries(); - - // System.out.println(header + "before conversion, newMeasurement is " + newMeasurement); - - newMeasurement = TimeIntervalMeasurement.getConvertedCopy(newMeasurement, - timeSeries.getMeasuringUnit()); - - - // System.out.println(header + "after conversion, newMeasurement is " + newMeasurement); - - long endTimeInMillis = newMeasurement.getEndTime(); - - timeSeries.setMeasurementByTime(newMeasurement, endTimeInMillis); - - } //end replaceTimeSeriesValue() - - //---------------------------------------------------------------------- - - - private void replaceTimeSeriesValue(RegularTimeSeriesHolder timeSeriesHolder, - AbsTimeMeasurement newMeasurement) - { - String header = "AnalysisWindow.replaceTimeSeriesValue(): "; - - RegularTimeSeries timeSeries = - timeSeriesHolder.getTimeSeries(); - - - // System.out.println(header + "timeSeries = " + timeSeries); - - if (timeSeries != null) - { - newMeasurement = AbsTimeMeasurement.getConvertedCopy(newMeasurement, - timeSeries.getMeasuringUnit()); - - timeSeries.setMeasurementByTime(newMeasurement, newMeasurement.getTime()); - } - else - { - // System.err.println(header + " time series is null "); - } - - - } //end replaceTimeSeriesValue() - - // ---------------------------------------------------------------- - private void runModel() - { - - // String header = "AnalysisWindow.runModel(): "; - // System.out.println(header + "inside the method"); - _modelManager.runStreamModels(); - - redrawCanvases(); - - announceModelRun(); - - } - // ---------------------------------------------------------------- - - private void announceModelRun() - { - announceTimeSeriesChange("Model Run"); - } - - //----------------------------------------------------------------- - - private void announceForecastStageEdited() - { - String message = "Manually Edited Fcst Stage"; - TimeSeriesEvent event = new TimeSeriesEvent(message, AnalysisWindow.this); - - getPrimaryStreamModel().getForecastStageTimeSeriesHolder().forwardEvent(event); - } - - // ----------------------------------------------------------------- - private void announceTimeSeriesChange(String message) - { - TimeSeriesEvent event = new TimeSeriesEvent(message, AnalysisWindow.this); - - getPrimaryStreamModel().getPrecipTimeSeriesHolder().forwardEvent(event); - getPrimaryStreamModel().getForecastStageTimeSeriesHolder().forwardEvent(event); - - getPrimaryStreamModel().getEvaporationTimeSeriesHolder().forwardEvent(event); - getPrimaryStreamModel().getPriorRunoffTimeSeriesHolder().forwardEvent(event); - - getPrimaryStreamModel().getRunoffTimeSeriesHolder().forwardEvent(event); - - } - - // ----------------------------------------------------------------- - - private void setModelTypeToComboBoxSelection() - { - - int selectedIndex = _modelTypeComboBox.getSelectedIndex(); - - RainfallRunoffModelType[] typeArray = - RainfallRunoffModelType.getModelTypeArray(); - - - RainfallRunoffModelType type = typeArray[selectedIndex]; - - changeModelType(type); - } - - // ----------------------------------------------------------------- - - private void changeModelType(RainfallRunoffModelType newType) - { - - RainfallRunoffModelType oldType = getPrimaryStreamModel().getRainfallRunoffModelType(); - - String header = "AnalysisWindow.changeModelType()"; - // System.out.println(header +": changing type to " + newType); - - // _tracer.trace("in " + header); - - - - boolean success = getPrimaryStreamModel().setRainfallRunoffModelType(newType); - - if (success) - { - //get rid of old alternate models from the ModelManager - _modelManager.removeAllAlternateStreamModels(); - setUpHydrographTimeSeriesPainters(); - - - if ((oldType != null) && (oldType==newType)) - { - //System.out.println(header + "changing to same RR model type"); - } - - setComponentVisibility(); - - // the title needs to update because the - // model may have changed - initTitle(); - - // take any already graphically set parameters and put them back into the - // streamModel to be used for model runs - updateModelSettingsFromGui(); - - if (newType == RainfallRunoffModelType.API_MKC) - { - setApiMkcModelState(); - } - else if (newType == RainfallRunoffModelType.SAC_SMA) - { - setSacModelState(); - } - - //recenter the canvases around the model run start time - recenterTimeWindowsAroundModelStartTime(); - - //refresh the selected Unit HydroGraph - refreshUhgSelection(); - - //run the stream model again - //runModel(); - } - else //failed, so change it back to MKC_API - { - - String locationId = getPrimaryStreamModel().getLocationId(); - - String message = "Location: " + locationId + - " is not configured properly to run the SAC-SMA.\n" + - " Please add a record in the SSHPConfig Dialog to configure it."; - - String dialogTitle = locationId + " Configuration Message"; - DialogHelper.displayMessageDialog(this, message, dialogTitle); - - int index = getIndexOfModelType(RainfallRunoffModelType.API_MKC); - _modelTypeComboBox.setSelectedIndex(index); - - } - return; - } - //----------------------------------------------------------------- - private int getIndexOfModelType(RainfallRunoffModelType type) - { - int index = -1; - - for (int i = 0; i < _modelTypeNameArray.length; i++) - { - if (type.getName().equalsIgnoreCase(_modelTypeNameArray[i])) - { - index = i; - } - } - - return index; - } - // ----------------------------------------------------------------- - - private void setUnitHydrographToComboBoxSelection() - { - - Object selectedItem = _uhgComboBox.getSelectedItem(); - - String selectedUnitHydrographName = (String) selectedItem; - - getPrimaryStreamModel().changeUnitHydrograph(selectedUnitHydrographName); - - runModel(); - } - - //----------------------------------------------------------------- - - private void updateModelSettingsFromGui() - { - RainfallRunoffModelType modelType = - getPrimaryStreamModel().getRainfallRunoffModelType(); - - if (modelType == RainfallRunoffModelType.API_MKC) - { - setInitialStageMeasurementFromGui(); - setFfhFromGui(); - setThresholdRunoffFromGui(); - } - else if (modelType == RainfallRunoffModelType.SAC_SMA) - { - //do nothing - } - - - - return; - } - //----------------------------------------------------------------- - - -// add all of the event handlers - private void addListeners() - { - - //allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - // addComponentListener(new WindowResizeComponentListener()); - // this object does not get garbage collected right away, since in the - // constructor, it adds itself as a Window listener - WindowResizingManager mgr = new WindowResizingManager(this, _minDimension, _maxDimension); - - // set up the action to perform when the close button is pressed - _closeButton.addActionListener( new CloseListener()); - - //setup of the action for the screen capture button - _screenCaptureButton.addActionListener(new ScreenCaptureActionListener()); - - //set up the window launcher button - _windowLauncherButton.addActionListener(new ControlWindowFocusActionListener()); - - - // set up the action to perform when the forward button is pressed - _forwardButton.addActionListener( new TimeWindowSlideListener(1)); - - // set up the action to perform when the forward button is pressed - _forward1DayButton.addActionListener(new TimeWindowSlideListener(24)); - - //setup of the action to perform when the recenter button is pressed - _recenterButton.addActionListener(new TimeWindowRecenterActionListener()); - - // set up the action to perform when the back button is pressed - _back1DayButton.addActionListener( new TimeWindowSlideListener(-24)); - - // set up the action to perform when the back button is pressed - _backButton.addActionListener( new TimeWindowSlideListener(-1)); - - - - // set up the action to perform when the time mode check box is pressed - // _timeModeCheckBox.addActionListener( new TimeModeCheckBoxListener()); - - - // set up the action to perform when the show flood stage check box is pressed - _showFloodStageCheckBox.addActionListener( new FloodStageCheckBoxListener()); - - // set up the action to perform when the show major flood stage check box is pressed - _showMajorFloodStageCheckBox.addActionListener( new MajorFloodStageCheckBoxListener()); - - // set up the action to perform when the _showPrecipAmountsCheckBox is pressed - _showPrecipAmountsCheckBox.addActionListener( new ShowPrecipAmountsCheckBoxListener()); - - // set up the action to perform when the show obs stage time series check box is pressed - _showObsHeightTsCheckBox.addActionListener( new ShowObservedHeightTsCheckBoxListener()); - - - //addListener for the delayRerunCheckBox - _delayRerunCheckBox.addActionListener(new DelayRerunCheckBoxListener()); - - - // SHOW MINOR PRECIP TICKS - _showMinorPrecipTicksCheckBox.addActionListener(new ShowMinorPrecipTicksCheckBoxListener()); - - // SHOW MINOR STAGE TICKS - _showMinorStageTicksCheckBox.addActionListener(new ShowMinorStageTicksCheckBoxListener()); - - - // SHOW Simulated Stage - _showSimulatedStageCheckBox.addActionListener(new ShowSimulatedStageCheckBoxListener()); - - - //CANVAS LISTENERS - - - // addlistener for the PrecipCanvas - _precipCanvas.addMouseMotionListener( - new CanvasMouseMovedListener(_precipCanvas, _precipValueMapper)); - - - // addlistener for the StageCanvas - _stageCanvas.addMouseMotionListener( - new CanvasMouseMovedListener(_stageCanvas, _stageValueMapper)); - - - - //--- KC API model settings - - //baseflow reset - _apiMkcInitialStagePanel.getButton().addActionListener(new InitialStageResetListener()); - - //baseflow adjustment - _apiMkcInitialStagePanel.getTextField().addFocusListener(new InitalStageFocusListener()); - - //FFH reset - _apiMkcFfhPanel.getButton().addActionListener(new FfhResetListener()); - - //FFH adjustment - _apiMkcFfhPanel.getTextField().addFocusListener(new FfhFocusListener()); - - _apiMkcStartingStateComboBox.addActionListener( - new ModelRunStartingStateActionListener(_apiMkcStartingStateComboBox)); - - - //threshold Runoff reset - _apiMkcThreshRPanel.getButton().addActionListener(new ThreshRunoffResetListener()); - - - //threshold Runoff adjustment - _apiMkcThreshRPanel.getTextField().addFocusListener(new ThreshRunoffFocusListener()); - - _apiMkcUseCustomModelRunTimeCheckBox.addActionListener(new UseCustomModelRunStartTimeCheckBoxListener()); - - // the apply button for API-MKC - _apiMkcApplySettingsButton.addActionListener(new ApplySettingsActionListener()); - - // refresh button for API-MKC state/time list - _apiMkcStateRefreshButton.addActionListener(new RefreshApiMkcStateListActionListener()); - - _apiMkcCustomModelRunDateTimeTextField.getDocument().addDocumentListener(new CustomModelRunDateTimeChangedDocumentListener()); - - // add listener for Model Change - _modelTypeComboBox.addActionListener(new ModelChoiceListener()); - - // Unithydrograph manual change - _uhgComboBox.addActionListener(new UnitHydrographChoiceListener()); - - //add listener for the Mouse events from TsCanvas - AdjustPrecipMouseListener precipAdjustmentListener = new AdjustPrecipMouseListener(); - _precipCanvas.addMouseListener(precipAdjustmentListener); - _precipCanvas.addMouseMotionListener(precipAdjustmentListener); - _precipCanvas.addKeyListener(precipAdjustmentListener); - - // add listener for the Mouse events from TsCanvas - // _stageCanvas.addTsCanvasEventListener(new ModelTimeAdjustmentTsCanvasEventListener()); - AdjustStageMouseListener adjustStageListener = new AdjustStageMouseListener(); - _stageCanvas.addMouseListener(adjustStageListener); - _stageCanvas.addMouseMotionListener(adjustStageListener); - - //SAC_SMA controls - - // add Frame launching button actions - _sacParamsButton.addActionListener(new SacParamsLaunchActionListener()); - _sacStateButton.addActionListener(new SacStateLaunchActionListener()); - - _sacSetVarInitialStateButton.addActionListener(new SetInitialVarStateActionListener()); - - // _sacMonthlyMapeValuesEditorButton.addActionListener(new MonthlyMapeEditorLaunchActionListener()); - - _sacStartingStateComboBox.addActionListener( - new ModelRunStartingStateActionListener(_sacStartingStateComboBox)); - - - //model controls - // add listener for setting the length of forecast - _forecastHoursSpinner.addChangeListener(new ForecastHoursChangeListener()); - - - _adjustmentCheckBox.addActionListener( new AdjustToggleActionListener()); - - _adjustmentLastObsInputTimeTextField.getDocument().addDocumentListener(new LastObsTimeForAdjustmentChangedDocumentListener()); - - _blendPeriodSpinner.addChangeListener(new AdjustmentHoursChangeListener()); - - - //launches the LiveSacState editor dialog (the one with sliders) - _sacLiveStateAdjustmentButton.addActionListener(new LiveSacStateLaunchActionListener()); - - // refresh button for SAC_SMA state/time list - _sacStateListRefreshButton.addActionListener(new RefreshSacSmaStateListActionListener()); - - - // create listeners for the time series that can be editted - getPrimaryStreamModel().getEvaporationTimeSeriesHolder().addListener(new EvaporationTimeSeriesChangeListener()); - getPrimaryStreamModel().getPrecipTimeSeriesHolder().addListener(new PrecipTimeSeriesChangeListener()); - getPrimaryStreamModel().getForecastStageTimeSeriesHolder().addListener(new ForecastHeightTimeSeriesChangeListener()); - - - } //end addListeners - - //-------used by inner classes -------------------------------------------------------------------- - private void usePrecipFileChooserForReading() - { - String defaultDirectory = null; - - if (_precipFileChooserHelper == null) - { - String[] extensions = {"work" }; - _precipFileChooserHelper = new FileChooserHelper(_sshp_precip_directoryString, - extensions, - "Precip Work files .work"); - } - - String filePath = _precipFileChooserHelper.displayForOpen(AnalysisWindow.this); - - if (filePath != null) - { - getPrimaryStreamModel().reloadFilePrecipTimeSeries(filePath); - runModel(); - } - - return; - } - - // ----------------------------------------------------------------------------------- - private void usePrecipFileChooserForSaving() - { - String defaultDirectory = null; - - if (_precipFileChooserHelper == null) - { - String[] extensions = {"work" }; - _precipFileChooserHelper = new FileChooserHelper(_sshp_precip_directoryString, - extensions, - "Precip Work files .work"); - } - - String filePath = _precipFileChooserHelper.displayForSave(AnalysisWindow.this); - - if (filePath != null) - { - getPrimaryStreamModel().savePrecipTimeSeriesToFile(filePath); - } - - return; - } - - // ----------------------------------------------------------------------------------- - private void useCaptureScreenFileChooserForSaving() - { - BufferedImage image = captureScreenToImage(); - - String defaultDirectory = null; - - if (_imageFileChooserHelper == null) - { - String[] extensions = {"jpg", "JPEG", "JPG" }; - _imageFileChooserHelper = new FileChooserHelper(_whfs_image_directoryString, - extensions, - "JPEG files .jpg .JPEG .JPG "); - } - - String filePath = _imageFileChooserHelper.displayForSave(AnalysisWindow.this); - - if (filePath != null) - { - writeImageToFile(image, new File(filePath)); - } - - return; - } - - // -------------------------------------------------------------------------------- - private void displayCaptureScreenFileChooser() - { - BufferedImage image = captureScreenToImage(); - - if (_imageFileChooser == null) - { - _imageFileChooser = new JFileChooser(_whfs_image_directoryString); - } - - - //add a FileFilter for JPG files - List filterList = new ArrayList(); - - filterList.add( "JPEG" ); - filterList.add("JPG"); - FileFilter fileFilter = new ExtensionFileFilter( filterList, "JPEG Image Files (*.jpg, *.JPG) "); - - - //set the file filter - _imageFileChooser.setFileFilter( fileFilter ); - // _imageFileChooser.set - - - //open the dialog - int returnVal = _imageFileChooser.showSaveDialog(this); - - if (returnVal == JFileChooser.APPROVE_OPTION) - { - File file = _imageFileChooser.getSelectedFile(); - - //ensure ends in ".jpg" - if ( (! file.getName().endsWith(".jpg")) && - (! file.getName().endsWith(".JPG")) - ) - { - String newFilePath = file.getPath() + ".jpg"; - file = new File(newFilePath); - } - - writeImageToFile(image, file); - } - - else - { - //System.out.println("AnalysisWindow.displayCaptureScreenFileChooser(): "); - //JOptionPane.showMessageDialog(AnalysisWindow.this, "Image file not saved."); - DialogHelper.displayMessageDialog(AnalysisWindow.this, "Image file not saved."); - - } - - - - return; - } - - // ----------------------------------------------------------------- - private void sleep(int millis) - { - - try - { - Thread.sleep(millis); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - - } - - // ----------------------------------------------------------------- - private BufferedImage captureScreenToImage() - { - BufferedImage bufferedImage = null; - try - { - - Robot robot = new Robot(); - int x = AnalysisWindow.this.getX(); - int y = AnalysisWindow.this.getY(); - int width = AnalysisWindow.this.getWidth(); - int height = AnalysisWindow.this.getHeight(); - Rectangle rectangleBounds = new Rectangle(x, y, width, height); - - //System.out.println("bounds rectangle of image capture = " + rectangleBounds); - bufferedImage = robot.createScreenCapture(rectangleBounds); - - } //end try - - catch (AWTException e) - { - e.printStackTrace(); - } - - - return bufferedImage; - } - - // ----------------------------------------------------------------- - - private void writeImageToFile(BufferedImage image, File file) - { - try - { - ImageOutputStream imageOutputStream = new FileImageOutputStream(file); - ImageIO.write(image, "JPG", imageOutputStream); - imageOutputStream.close(); - } - - catch(java.io.IOException e ) - { - e.printStackTrace(); - } - - - } - // ----------------------------------------------------------------- - - private void setInitialStageMeasurementFromGui() - { - String valueString = _apiMkcInitialStagePanel.getTextField().getText(); - - setInitalStageMeasurementInModelFromString(valueString); - } - - // ----------------------------------------------------------------- - - - private void setInitalStageMeasurementInModelFromString(String initialStageString) - { - double value = Double.parseDouble(initialStageString); - - Measurement measurement = new Measurement(value, _stageUnit); - - getPrimaryStreamModel().setInitialStageMeasurement(measurement); - - } - - // ----------------------------------------------------------------- - - - private void resetInitialStageMeasurementFromModel() - { - //uses a streamModel call to get the Baseflow value, but does not change the - // value STORED by the streamModel object - Measurement initialStageMeasurement = getPrimaryStreamModel().findInitialStageMeasurement(); - - //set the value STORED by the streamModel - getPrimaryStreamModel().setInitialStageMeasurement(initialStageMeasurement); - - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(initialStageMeasurement.getValue()); - - _apiMkcInitialStagePanel.getTextField().setText("" + valueString); - } - - // ----------------------------------------------------------------- - - private void setFfhFromGui() - { - String valueString = _apiMkcFfhPanel.getTextField().getText(); - - setFfhFromString(valueString); - } - - // ----------------------------------------------------------------- - - private void setFfhFromString(String ffhString) - { - String header = "AnalysisWindow.setFfgFromString(): "; - double value = Double.parseDouble(ffhString); - - System.out.println(header + "value = " + value); - - getPrimaryStreamModel().setFfhValue(value); - } - - private void resetFfhFromModel() - { - //uses a streamModel call to get the FFH value, but does not change the - // value STORED by the streamModel object - double ffh = getPrimaryStreamModel().findFfhValue(); - - //set the value STORED by the streamModel - getPrimaryStreamModel().setFfhValue(ffh); - - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(ffh); - // System.out.println( "AnalysisWindow:resetFfhFromModel(): FFHValue = : " + valueString ); - _apiMkcFfhPanel.getTextField().setText(valueString); - } - - // ----------------------------------------------------------------- - private StreamModel getPrimaryStreamModel() - { - StreamModel model = _modelManager.getPrimaryStreamModel(); - - return model; - } - // ----------------------------------------------------------------- - - private void loadModelData() - { - getPrimaryStreamModel().reloadModelData(); - - if (getPrimaryStreamModel().getRainfallRunoffModelType() == - RainfallRunoffModelType.SAC_SMA) - { - //do nothing - } - else if (getPrimaryStreamModel().getRainfallRunoffModelType() == - RainfallRunoffModelType.API_MKC) - { - resetFfhFromModel(); - resetInitialStageMeasurementFromModel(); - resetThresholdRunoffFromModel(); - } - } - - // ----------------------------------------------------------------- - private void setApiMkcModelState() - { - - String header = "AnalysisWindow.setApiMkcModelState(): "; - - FFHDescriptor descriptorToUse = null; - MeasuringUnit ffhUnit = MeasuringUnit.inches; - - - if (_apiMkcUseCustomModelRunTime) - { - //should use some other method for this - double value = Double.parseDouble(_apiMkcFfhPanel.getTextField().getText()); - - long time = _apiMkcCustomModelRunDateTimeTextField.getTime(); - AbsTimeMeasurement measurement = new AbsTimeMeasurement(value, time, ffhUnit); - descriptorToUse = new FFHDescriptor(getPrimaryStreamModel().getLocationId(), - measurement, StreamModel.DEFAULT_FFG_DURATION_CODE, false); - - - System.out.println(header + "ffh measurement = " + measurement); - - } - else //use the standard selection method - { - - _selectedFFHDescriptor = (FFHDescriptor) - _apiMkcStartingStateComboBox.getSelectedItem(); - - descriptorToUse = _selectedFFHDescriptor; - } - - // if there are no products, - if (descriptorToUse == null) - { - - AbsTimeMeasurement fakeFfmMeasurement = new AbsTimeMeasurement(10, - getTimeOfLatestHour(), - MeasuringUnit.inches); - - String lid = getPrimaryStreamModel().getLocationId(); - descriptorToUse = new FFHDescriptor(lid, - fakeFfmMeasurement, - StreamModel.DEFAULT_FFG_DURATION_CODE, - false); - } - - - selectFFHProduct(descriptorToUse); - - System.out.println(header + "descriptorToUse = " + descriptorToUse); - - // System.out.println("AnalysisWindow.setApiMkcModelState : descriptor = " + - // descriptorToUse.toString()); - - long newTime = descriptorToUse.getTime(); - - System.out.println(header + "newTime = " + DbTimeHelper.getDateTimeStringFromLongTime(newTime)); - - setModelRunStartTime(newTime); - - recenterTimeWindowsAroundModelStartTime(); - - //runModel(); - } - - // ----------------------------------------------------------------- - - private void setSacModelState() - { - String header = "AnalysisWindow.setSacModelState():"; - - _selectedSacStateDescriptor = (SacSmaStateDescriptor) - _sacStartingStateComboBox.getSelectedItem(); - - - selectSacSmaStateDescriptor(_selectedSacStateDescriptor); - - //make sure that we reload the prior runoff time series, which happens in here - - // System.out.println(" ********* AnalysisWindow.setSacModelState() : descriptor = " + - // _selectedSacStateDescriptor.toString()); - //TODO the newTime = line seems redundant - long newTime = _selectedSacStateDescriptor.getValidTime(); - setModelRunStartTime(newTime); - - recenterTimeWindowsAroundModelStartTime(); - - //runModel(); - } - - - // ----------------------------------------------------------------- - private void selectFFHProduct(FFHDescriptor descriptor) - { - StreamModel primaryStreamModel = getPrimaryStreamModel(); - - primaryStreamModel.setFFHProductDescriptor(descriptor); - - _modelManager.configureStreamModelsForMkcApi(primaryStreamModel, descriptor); - } - - // ----------------------------------------------------------------- - private void selectSacSmaStateDescriptor(SacSmaStateDescriptor primaryDescriptor) - { - - String header = "AnalysisWindow.selectSacSmaStateDescriptor(): "; - //store the primaryModel and set the SAC-SMA Descriptor - StreamModel primaryModel = getPrimaryStreamModel(); - primaryModel.setSacSmaStateDescriptor(primaryDescriptor); - long primaryTime = primaryDescriptor.getValidTime(); - - - //setup the parallel stream models that start at the same time, but have alternate states - _modelManager.configureStreamModelsForSacSma(primaryModel, primaryDescriptor, _showAlternateForecasts, _showPastForecasts); - - //adjust the painters to paint this new stuff - setUpHydrographTimeSeriesPainters(); - } - - // --------------------------------------------------------------------------------------- - - - - private void setModelRunStartTime(long newStartTime) - { - // String header = "AnalysisWindow.setModelRunStartTime(): "; - - newStartTime = TimeHelper.truncateTimeInMillisToNearestHour(newStartTime, 1); - - _modelManager.setPrimaryModelStartTime(newStartTime); - - // getPrimaryStreamModel().setModelStartTime(newStartTime); - - //to make the response time to the clicking faster - // this will happen eventually, anyway after the model run - // _precipCanvas.refresh(); - - String dateTimeString = getDateTimeStringToMinutes(newStartTime); - - // _modelRunStartTimeValueLabel.setText("Model Run Start Time: " + dateTimeString); - _modelRunStartTimeValueLabel.setText(dateTimeString); - - - //reload the model data, so that the correct parameters and - // states are used. - - loadModelData(); - - runModel(); - - } - // ----------------------------------------------------------------- - - private void setThresholdRunoffFromGui() - { - String valueString = _apiMkcThreshRPanel.getTextField().getText(); - - setThresholdRunoffFromString(valueString); - } - - // ----------------------------------------------------------------- - - - private void setThresholdRunoffFromString(String thresholdRunoffString) - { - double value = Double.parseDouble(thresholdRunoffString); - getPrimaryStreamModel().setThresholdRunoff(value); - } - - // ----------------------------------------------------------------- - - - private void resetThresholdRunoffFromModel() - { - //uses a streamModel call to get the threshold Runoff value, - // but does not change the - // value STORED by the streamModel object - double thresholdRunoff = getPrimaryStreamModel().findThresholdRunoffValue(); - - //set the value STORED by the streamModel - getPrimaryStreamModel().setThresholdRunoff(thresholdRunoff); - - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(thresholdRunoff); - - _apiMkcThreshRPanel.getTextField().setText(valueString); - } - - // ----------------------------------------------------------------------- - - private void redrawCanvases() - { - String header = "AnalysisWindow.redrawCanvases()"; - - _precipCanvas.refresh(); - - _stageCanvas.refresh(); - } - - // ----------------------------------------------------------------------- - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new CloseListener()); - menu.add(menuItem); - - - // Edit/View Menu - menu = new JMenu("View/Edit"); - menu.setMnemonic(KeyEvent.VK_V); - menu.getAccessibleContext().setAccessibleDescription( - "View/Edit time series data."); - _menuBar.add(menu); - - - // edit menu items - - //Precip editor - menuItem = new JMenuItem("Precip Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_P, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new PrecipTimeSeriesLaunchActionListener()); - - - // Forecast Stage Editor - menuItem = new JMenuItem("Forecast Stage Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_I, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new ForecastHeightTimeSeriesLaunchActionListener()); - - - // ET Time Series editor - menuItem = new JMenuItem("Evapotranspiration Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_T, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new EvaporationTimeSeriesLaunchActionListener()); - - - - // Prior Computed Runoff Viewer - menuItem = new JMenuItem("Prior Runoff Viewer..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_O, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new PriorRunoffTimeSeriesLaunchActionListener()); - - - // Computed Runoff Viewer - menuItem = new JMenuItem("Runoff Viewer..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_R, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new RunoffTimeSeriesLaunchActionListener()); - - - // Toggle UNADJUSTED states - JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem("Show Unadjusted States"); - checkBoxMenuItem.setState(_showUnadjustedStates); - menuItem = checkBoxMenuItem; - - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_U, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new ShowUnadjustedStatesActionListener()); - - - // Save Menu - menu = new JMenu("Save"); - menu.setMnemonic(KeyEvent.VK_S); - menu.getAccessibleContext().setAccessibleDescription( - "Save time series changes to database."); - _menuBar.add(menu); - - - // Save Forecast Stage - menuItem = new JMenuItem("Save Forecast Stage..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_G, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new ForecastHeightSaveLaunchActionListener()); - - - // Save Forecast Discharge - menuItem = new JMenuItem("Save Forecast Discharge Time Series..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_D, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new ForecastDischargeSaveLaunchActionListener()); - - - // Save Evaporation Time Series - menuItem = new JMenuItem("Save Evap Time Series.."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_E, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new EvapSaveLaunchActionListener()); - - - // Save Edited MAP Time Series - menuItem = new JMenuItem("Save Edited MAP Time Series.."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_M, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - ""); - menu.add(menuItem); - - menuItem.addActionListener(new MAPSaveLaunchActionListener()); - - - //reloadPrecipButton directly on menuBar - Color menuBarColor = _menuBar.getBackground(); - Border invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - JButton button = new JButton(" Reload Precip "); - button.addActionListener(new ReloadPrecipTimeSeriesActionListener()); - button.setBorder(invisibleBorder); - button.setSize(60, 30); - String text = "Reload the MAP time series from the database.\n" + - "Changes will be lost."; - button.setToolTipText(text); - _menuBar.add(button); - - //reloadFilePrecipButton directly on menuBar - menuBarColor = _menuBar.getBackground(); - invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - button = new JButton(" Reload File Precip "); - button.addActionListener(new ReloadFilePrecipTimeSeriesActionListener()); - button.setBorder(invisibleBorder); - button.setSize(60, 30); - text = "Reload the MAP time series from a workfile.\n" + - "Changes will be lost."; - button.setToolTipText(text); - _menuBar.add(button); - - - // reloadObsStageButton directly on menuBar - button = new JButton(" Reload Stream Obs. "); - button.addActionListener(new ReloadObsStageTimeSeriesActionListener()); - button.setBorder(invisibleBorder); - button.setSize(80, 30); - text = "Reload the observed stage/discharge time series from the database."; - button.setToolTipText(text); - _menuBar.add(button); - - // separator - - // JSeparator menuSeparator = new JSeparator(); - // menuSeparator.setOrientation(SwingConstants.VERTICAL); - // _menuBar.add(menuSeparator); - - //acts as a separator to move the Help menu all the way to the right - menuItem = new JMenuItem(""); - menuItem.setEnabled(false); - _menuBar.add(menuItem); - - // Help Menu - - menu = new JMenu("Help"); - menu.setMnemonic(KeyEvent.VK_HELP); - menu.getAccessibleContext().setAccessibleDescription( - "Access help menu items."); - _menuBar.add(menu); - - menuItem = new JMenuItem("About..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_A, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Display the About Dialog."); - menu.add(menuItem); - - menuItem.addActionListener(new AboutLaunchListener()); - - - } - - // ----------------------------------------------------------------------- - - // -----inner classes ------------------------------------------------------ - private class AboutLaunchListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String aboutText = AboutInfo.getText(); - DialogHelper.displayMessageDialog(AnalysisWindow.this, aboutText, "About SSHP"); - } - } - - //----------------------------------------------------------------- - - private class InitialStageResetListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - resetInitialStageMeasurementFromModel(); - runModel(); - - } - } - - //----------------------------------------------------------------- - - private class InitalStageFocusListener implements FocusListener - { - - public InitalStageFocusListener() - { - - } - - public void focusGained(FocusEvent event) - { - - } - - public void focusLost(FocusEvent event) - { - //System.out.println("InitalStageFocusListener triggered"); - - JTextField textField = (JTextField) event.getSource(); - - String initialStageString = textField.getText().trim(); - if (initialStageString.length() == 0) - { - //consider putting an error dialog here - } - else - { - try - { - setInitalStageMeasurementInModelFromString(initialStageString); - } - catch (Throwable t) - { - //consider putting an error dialog here - } - } - - // the apply button does this now - //runModel(); - - } //end focusLost - - } - - //----------------------------------------------------------------- - - private class FfhResetListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - resetFfhFromModel(); - runModel(); - } - } - //----------------------------------------------------------------- - - private class ApplySettingsActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - // System.out.println("ApplySettingsActionListener triggered"); - updateModelSettingsFromGui(); - // setApiMkcModelState(); - runModel(); - } - } - //----------------------------------------------------------------- - - private class RefreshSacSmaStateListActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - //System.out.println("RefreshSacSmaStateListActionListener triggered"); - - - initSacStateComboBox(_sacStartingStateComboBox); - } - } - //----------------------------------------------------------------- - - private class RefreshApiMkcStateListActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - //System.out.println("RefreshApiMkcStateListActionListener triggered"); - - initApiMkcStateComboBox(_apiMkcStartingStateComboBox); - } - } - - private class ReloadPrecipTimeSeriesActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - DialogHelper.setWaitCursor(_menuBar); - getPrimaryStreamModel().reloadPrecipTimeSeries(); - runModel(); - DialogHelper.setDefaultCursor(_menuBar); - } - } - //----------------------------------------------------------------- - - private class ReloadFilePrecipTimeSeriesActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - DialogHelper.setWaitCursor(_menuBar); - - usePrecipFileChooserForReading(); - - DialogHelper.setDefaultCursor(_menuBar); - } - } - //----------------------------------------------------------------- - - private class ReloadObsStageTimeSeriesActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - DialogHelper.setWaitCursor(_menuBar); - - getPrimaryStreamModel().reloadObservedStageTimeSeries(); - runModel(); - - DialogHelper.setDefaultCursor(_menuBar); - - } - } - //----------------------------------------------------------------- - - private class FfhFocusListener implements FocusListener - { - - public FfhFocusListener () - { - - } - - public void focusGained(FocusEvent event) - { - - } - - public void focusLost(FocusEvent event) - { - //System.out.println("FfhFocusListener triggered"); - - JTextField textField = (JTextField) event.getSource(); - - - String ffhString = textField.getText().trim(); - if (ffhString.length() == 0) - { - resetFfhFromModel(); //just set it back to the value in the streamModel. - } - else - { - try - { - setFfhFromString(ffhString); - - } - catch (Throwable t) - { - resetFfhFromModel(); //just set it back to the value in the streamModel. - } - } - - // the apply button does this now - //runModel(); - - } //end focusLost - - } - //----------------------------------------------------------------- - - private class ThreshRunoffResetListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - resetThresholdRunoffFromModel(); - runModel(); - - } - } - //----------------------------------------------------------------- - - private class ThreshRunoffFocusListener implements FocusListener - { - - public ThreshRunoffFocusListener() - { - - } - - public void focusGained(FocusEvent event) - { - - } - - public void focusLost(FocusEvent event) - { - //System.out.println("ThreshRunoffFocusListener triggered"); - - JTextField textField = (JTextField) event.getSource(); - - //System.out.println("AnalysisWindow.ThreshRFocusLost listener activated"); - - String thresholdRunoffString = textField.getText().trim(); - if (thresholdRunoffString.length() == 0) - { - resetThresholdRunoffFromModel(); //just set it back to the value in the streamModel. - } - else - { - try - { - setThresholdRunoffFromString(thresholdRunoffString); - } - catch (Throwable t) - { - resetThresholdRunoffFromModel(); //just set it back to the value in the streamModel. - } - } - - // the apply button does this now - //runModel(); - - } //end focusLost - - } - - //----------------------------------------------------------------- - - - private class CanvasMouseMovedListener extends MouseMotionAdapter - { - private TsPaintableCanvas _canvas = null; - private ValueMapper _valueMapper = null; - - public CanvasMouseMovedListener(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - _canvas = canvas; - _valueMapper = valueMapper; - } - - public void mouseMoved(MouseEvent event) - { - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas.getViewport().getDataPoint(screenPoint); - - - if (_canvas.getViewport().isViewable(dataPoint)) - { - updateDataPointText(dataPoint, _valueMapper, _canvas); - } - } - - } - //----------------------------------------------------------------- - - private class FrameCloseWindowListener extends WindowAdapter - { - public void windowClosing(WindowEvent evt) - { - dispose(); - } - - } - - //----------------------------------------------------------------- - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - dispose(); - } - } - - //----------------------------------------------------------------- - private class ControlWindowFocusActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _controller.bringLaunchWindowToFront(); - } - } - - //----------------------------------------------------------------- - private class FloodStageCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _forceShowFloodStage = _showFloodStageCheckBox.isSelected(); - _floodStageLinePainter.setShouldPaint(_forceShowFloodStage); - redrawCanvases(); - } - - } - //----------------------------------------------------------------- - - private class MajorFloodStageCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - if (_majorFloodStageLinePainter != null) - { - _forceShowMajorFloodStage = _showMajorFloodStageCheckBox.isSelected(); - _majorFloodStageLinePainter.setShouldPaint(_forceShowMajorFloodStage); - redrawCanvases(); - } - } - } - - //----------------------------------------------------------------- - private class ShowPrecipAmountsCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _showPrecipAmounts = _showPrecipAmountsCheckBox.isSelected(); - _precipPainter.setShowPrecipAmounts(_showPrecipAmounts); - _precipTextTotalPainter.setShouldPaint(_showPrecipAmounts); - redrawCanvases(); - } - - } - //----------------------------------------------------------------- - private class ShowObservedHeightTsCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - String header = "ShowObservedHeightTsCheckBoxListener.actionPerformed(): "; - System.out.println(header + "I have been clicked. My _observedStageTsPainter is " + - _observedStageTsPainter); - - _showObservedHeightData = _showObsHeightTsCheckBox.isSelected(); - _observedStageTsPainter.setShouldPaint(_showObservedHeightData); - - - - redrawCanvases(); - } - } - - //----------------------------------------------------------------- - private class DelayRerunCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _delayRerunModelWhileDrawing = _delayRerunCheckBox.isSelected(); - } - - } - //----------------------------------------------------------------- - private class ShowMinorPrecipTicksCheckBoxListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _showMinorPrecipTicks = _showMinorPrecipTicksCheckBox.isSelected(); - _precipBackgroundPainter.setShowMinorTicks(_showMinorPrecipTicks); - redrawCanvases(); - } - - } - - //----------------------------------------------------------------- - private class ShowMinorStageTicksCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _showMinorStageTicks = _showMinorStageTicksCheckBox.isSelected(); - _stageBackgroundPainter.setShowMinorTicks(_showMinorStageTicks); - redrawCanvases(); - } - - } - - //----------------------------------------------------------------- - - private class ShowSimulatedStageCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - _showSimulatedStage = _showSimulatedStageCheckBox.isSelected(); - _simulatedStageTsPainter.setShouldPaint(_showSimulatedStage); - redrawCanvases(); - } - - } - - //----------------------------------------------------------------- - - private class ShowAlternateForecastsCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - DialogHelper.setWaitCursor(AnalysisWindow.this); - - - String header = "AnalysisWindow.ShowAlternateForecastsCheckBoxListener.actionPerformed(): "; - CodeTimer timer = new CodeTimer(); - timer.start(); - - _showAlternateForecasts = _sacShowAlternateForecastsCheckBox.isSelected(); - - // System.out.println(header + " adjust the model Manager and rerun the model"); - - CodeTimer setShowAlternateForecastsTimer = new CodeTimer(); - setShowAlternateForecastsTimer.start(); - _modelManager.setShowAlternateForecasts(_showAlternateForecasts); - setShowAlternateForecastsTimer.stop(header + "setShowAlternateForecasts() took: "); - - //adjust the painters to paint this new stuff - CodeTimer setUpHydrographTimeSeriesPaintersTimer = new CodeTimer(); - setUpHydrographTimeSeriesPaintersTimer.start(); - setUpHydrographTimeSeriesPainters(); - setUpHydrographTimeSeriesPaintersTimer.stop(header + "setUpHydrographTimeSeriesPainters() took: "); - - - CodeTimer runModelTimer = new CodeTimer(); - runModelTimer.start(); - runModel(); - runModelTimer.stop(header + "runModel() took "); - - - DialogHelper.setDefaultCursor(AnalysisWindow.this); - - timer.stop(header + ", the whole routine took "); - } - - } - - //----------------------------------------------------------------- - - private class ShowPastForecastsCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - DialogHelper.setWaitCursor(AnalysisWindow.this); - - String header = "AnalysisWindow.ShowPastForecastsCheckBoxListener(): "; - CodeTimer timer = new CodeTimer(); - timer.start(); - - _showPastForecasts = _sacShowPastForecastsCheckBox.isSelected(); - - System.out.println("ShowPastForecastsCheckBoxListener. adjust the model Manager and rerun the model"); - - CodeTimer setShowPastForecastsTimer = new CodeTimer(); - setShowPastForecastsTimer.restart(); - _modelManager.setShowPastForecasts(_showPastForecasts); - setShowPastForecastsTimer.stop(header + "setShowPastForecasts() took"); - - - //adjust the painters to paint this new stuff - - setUpHydrographTimeSeriesPainters(); - - runModel(); - - DialogHelper.setDefaultCursor(AnalysisWindow.this); - - timer.stop(header + " took "); - } - - } - - // -------------------------------------------------------------------------------------------------------------- - private class SetHoursBackAndIntervalHoursForPreviousForecastsActionListener implements ActionListener - { - - private JTextField _hoursBackJTextField = null; - private JTextField _intervalInHoursJTextField = null; - - - public SetHoursBackAndIntervalHoursForPreviousForecastsActionListener(JTextField hoursBackJTextField, - JTextField intervalInHoursJTextField ) - { - _hoursBackJTextField = hoursBackJTextField; - _intervalInHoursJTextField = intervalInHoursJTextField; - } - - public int getValueAndValidateTextField(JTextField textField, int defaultValue, int minValue, int maxValue) - { - - String text = textField.getText(); - - int value = defaultValue; - - try - { - value = Integer.parseInt(text); - if ( (value < minValue) || - (value > maxValue) - ) - { - value = defaultValue; - } - } - catch (NumberFormatException e) - { - value = defaultValue; - } - - textField.setText(String.valueOf(value)); - - return value; - } - - public void actionPerformed(ActionEvent evt) - { - String header = "AnalysisWindow.SetHoursBackAndIntervalHoursForPreviousForecastsActionListener(): "; - - DialogHelper.setWaitCursor(AnalysisWindow.this); - - int hoursInPast = getValueAndValidateTextField(_hoursBackJTextField, 0, 0, 120); - int intervalInHours = getValueAndValidateTextField(_intervalInHoursJTextField, 1, 1, 120); - - _modelManager.setHoursBackAndIntervalForPreviousForecastStates(hoursInPast, intervalInHours); - - //adjust the painters to paint this new stuff - - setUpHydrographTimeSeriesPainters(); - - runModel(); - - DialogHelper.setDefaultCursor(AnalysisWindow.this); - } - - } - // -------------------------------------------------------------------------------------------------------------- - //----------------------------------------------------------------- - private class UseCustomModelRunStartTimeCheckBoxListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - _apiMkcUseCustomModelRunTime = _apiMkcUseCustomModelRunTimeCheckBox.isSelected(); - setApiMkcModelState(); - runModel(); - } - - } - - //----------------------------------------------------------------- - private class TimeWindowRecenterActionListener implements ActionListener - { - - public void actionPerformed(ActionEvent evt) - { - recenterTimeWindowsAroundModelStartTime(); - } - - } //end TimeWindowRecenterActionListener - - //----------------------------------------------------------------- - private class TimeWindowSlideListener implements ActionListener - { - private int _slideHours = 0; - - public TimeWindowSlideListener(int slideHours) - { - _slideHours = slideHours; - } - - public void actionPerformed(ActionEvent evt) - { - - _precipCanvas.slideTimeWindow(_slideHours); - _stageCanvas.slideTimeWindow(_slideHours); - - } - - } //end TimeWindowSlideListener; - - //----------------------------------------------------------------- - private class AdjustStageMouseListener extends MouseAdapter implements MouseMotionListener - { - private boolean _button3Down = false; - private boolean _tipShownOnce = false; - - public void mouseDragged(MouseEvent event) - { - - if (_button3Down) - { - Point point = event.getPoint(); - adjustStage(point); - } - - } - - public void mouseMoved(MouseEvent event) - { - //do nothing - return; - } - - public void mouseReleased(MouseEvent event) - { - int button = event.getButton(); - - if (button == MouseEvent.BUTTON3) - { - _button3Down = false; - } - - return; - } - - public void mousePressed(MouseEvent event) - { - int button = event.getButton(); - - if (button == MouseEvent.BUTTON3) - { - _button3Down = true; - } - - return; - - } - - - public void mouseClicked(MouseEvent event) - { - if (event.getButton() == MouseEvent.BUTTON3) - { - adjustStage(event.getPoint()); - } - else if ( (event.getButton() == MouseEvent.BUTTON1) || - ( (event.getButton() == MouseEvent.BUTTON2))) - { - if (! _tipShownOnce) - { - _tipShownOnce = true; - DialogHelper.displayMessageDialog(AnalysisWindow.this, - "TIP: To avoid accidental editing of the forecast hydrograph,\n the" + - " application requires the user to click the right mouse\n button to edit the hydrograph."); - } - } - _button3Down = false; - - } //end mouseClicked - - private void adjustStage(Point point) - { - AbsTimeMeasurement measurement = _stageCanvas.getAbsTimeMeasurementByRounding(point); - - if (measurement.getValue() < 0.0) - { - measurement.setValue(0.0); - } - - if (measurement.getTime() >= _modelStartTimeHolder.getTime())//forecast precip - { - if (measurement.getValue(MeasuringUnit.feet) <= MAX_STAGE_IN_FEET) - { - replaceTimeSeriesValue(getPrimaryStreamModel().getForecastStageTimeSeriesHolder(), - measurement); - - //redraw the StageCanvas - _stageCanvas.refresh(); - - - //let any observer know of the change - announceForecastStageEdited(); - } - } - - - - - - } - - } //end StageAdjustmentTsCanvasEventListener - - //----------------------------------------------------------------- - private class AdjustPrecipMouseListener extends MouseAdapter implements MouseMotionListener, KeyListener - - { - private boolean _button1Down = false; - private boolean _tipShownOnce = false; - - //variables related to keyboard commands - private boolean _hasFocus = false; - private Point _mousePosition = null; - - //List _pointList = new ArrayList(); - - public void mouseDragged(MouseEvent event) - { - // Point point = event.getPoint(); - // _pointList.add(point); - - - if (_button1Down) - { - Point point = event.getPoint(); - // System.out.println("activated mouseDragged"); - // System.out.println("activated mouseDragged, button = " + button ); - adjustPrecip(point); - } - - } - - public void mouseMoved(MouseEvent event) - { - _mousePosition = event.getPoint(); - //do nothing - } - - public void mousePressed(MouseEvent event) - { - //System.out.println("Precip adjust listener: mousePressed()"); - int button = event.getButton(); - if (button == MouseEvent.BUTTON1) - { - _button1Down = true; - } - else - { - if (! _tipShownOnce) - { - _tipShownOnce = true; - DialogHelper.displayMessageDialog(AnalysisWindow.this, - "TIP: Use the left mouse button to edit precip."); - - } - } - - return; - - } - - - public void mouseReleased(MouseEvent event) - { - //System.out.println("Precip adjust listener: mouseReleased()"); - int button = event.getButton(); - - if (button == MouseEvent.BUTTON1) - { - _button1Down = false; - - adjustPrecip(event.getPoint()); - - //if I am delaying, I need to redraw when button released, - //otherwise, adjustPrecip - if (_delayRerunModelWhileDrawing) - { - runModel(); - } - } - - } - - - public void mouseEntered(MouseEvent event) - { - //get the focus on this canvas, so that the keyboard commands will work on it - AnalysisWindow.this._precipCanvas.requestFocusInWindow(); - // System.out.println("mouseEntered():" + " requested focus "); - _hasFocus = true; - } - - public void mouseExited(MouseEvent event) - { - // System.out.println("mouseExited():" + " requested focus elsewhere "); - //System.out.println("Precip adjust listener: mouseExited()"); - - //when exit the window, if was delaying drawing, stop delaying - if ((_delayRerunModelWhileDrawing) && (_button1Down)) - { - runModel(); - } - - //make sure that some other widget has focus, - //so that keyboard clicks are not registered by the - //precip canvas listeners - AnalysisWindow.this._stageCanvas.requestFocusInWindow(); - - _hasFocus = false; - } - - - public void keyPressed(KeyEvent e) - { - int keyCode = e.getKeyCode(); - char keyChar = e.getKeyChar(); - - System.out.println("keyPressed: " + keyChar); - - if ( ( keyCode == KeyEvent.VK_UP) || (keyCode == KeyEvent.VK_RIGHT) ) - { - System.out.println("Up typed"); - adjustPrecipByDeltaValue(0.01, _mousePosition); - } - - if ( ( keyCode == KeyEvent.VK_DOWN)|| (keyCode == KeyEvent.VK_LEFT) ) - { - System.out.println("Down typed"); - adjustPrecipByDeltaValue(-0.01, _mousePosition); - } - } - - public void keyReleased(KeyEvent e) - { - - } - - public void keyTyped(KeyEvent e) - { - - } - - private void adjustPrecipByDeltaValue(double changeInValue, Point point) - { - System.out.println("Precip adjust listener: adjustPrecipByDeltaValue()"); - - AbsTimeMeasurement measurement = _precipCanvas.getAbsTimeMeasurementByTruncation(point); - - // for precip, we are focused on the end time, so add an hour - long endTime = measurement.getTime() + ( _intervalInHours * MILLIS_PER_HOUR); - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel().getPrecipTimeSeriesHolder(); - - AbsTimeMeasurement oldMeasurement = tsHolder.getTimeSeries().getAbsTimeMeasurementByTime(endTime); - - measurement.setValue(oldMeasurement.getValue() + changeInValue); - measurement.setTime(endTime); - - if (measurement.getValue() < 0.0) - { - measurement.setValue(0.0); - } - - TimeIntervalMeasurement newMeasurement = - new TimeIntervalMeasurement(measurement.getValue(), - measurement.getTime(), - _intervalInHours, - measurement.getUnit()); - - - double value = measurement.getValue(MeasuringUnit.inches); - boolean valueIsInRange = false; - boolean timeIsInRange = false; - - if (value <= MAX_PRECIP_IN_INCHES_PER_HOUR) - { - valueIsInRange = true; - } - - - //ending time at or before model start time is not allowed, since the period is before - if (measurement.getTime() > getPrimaryStreamModel().getModelStartTime()) - { - timeIsInRange = true; - } - - if (valueIsInRange && timeIsInRange) - { - RegularTimeSeriesHolder timeSeriesHolder = null; - - timeSeriesHolder = getPrimaryStreamModel().getPrecipTimeSeriesHolder(); - replaceTimeSeriesValue(timeSeriesHolder, newMeasurement); - - - //redraw the PrecipCanvas - _precipCanvas.refresh(); - - // if not delaying, then rerun the model right now - if (! _delayRerunModelWhileDrawing) - { - runModel(); - } - } - - } //end adjustPrecipByValue - - - private void adjustPrecip(Point point) - { - //System.out.println("Precip adjust listener: adjustPrecip()"); - - AbsTimeMeasurement measurement = _precipCanvas.getAbsTimeMeasurementByTruncation(point); - - // System.out.println(header + measurement); - - if (measurement.getValue() < 0.0) - { - measurement.setValue(0.0); - } - - // for precip, we are focused on the end time, so add an hour - long endTime = measurement.getTime() + ( _intervalInHours * MILLIS_PER_HOUR); - measurement.setTime(endTime); - - TimeIntervalMeasurement newMeasurement = - new TimeIntervalMeasurement(measurement.getValue(), - measurement.getTime(), - _intervalInHours, - measurement.getUnit()); - - - double value = measurement.getValue(MeasuringUnit.inches); - boolean valueIsInRange = false; - boolean timeIsInRange = false; - - if (value <= MAX_PRECIP_IN_INCHES_PER_HOUR) - { - valueIsInRange = true; - } - - - //ending time at or before model start time is not allowed, since the period is before - if (measurement.getTime() > getPrimaryStreamModel().getModelStartTime()) - { - timeIsInRange = true; - } - - if (valueIsInRange && timeIsInRange) - { - RegularTimeSeriesHolder timeSeriesHolder = null; - - timeSeriesHolder = getPrimaryStreamModel().getPrecipTimeSeriesHolder(); - replaceTimeSeriesValue(timeSeriesHolder, newMeasurement); - - - //redraw the PrecipCanvas - _precipCanvas.refresh(); - - // if not delaying, then rerun the model right now - if (! _delayRerunModelWhileDrawing) - { - runModel(); - } - } - - } //end adjustPrecip - - } //end PrecipAdjustmentTsCanvasEventListener - - //-------------------------------------------------------------------- - private class ModelRunStartingStateActionListener implements ActionListener - { - - private JComboBox _comboBox = null; - - public ModelRunStartingStateActionListener(JComboBox comboBox) - { - _comboBox = comboBox; - } - - - public void actionPerformed(ActionEvent evt) - { - - DialogHelper.setWaitCursor(AnalysisWindow.this); - - - if (_comboBox == AnalysisWindow.this._apiMkcStartingStateComboBox) - { - if ( ! _reloadingApiMkcStartingStateComboBox ) - { - setApiMkcModelState(); - } - } - else if (_comboBox == AnalysisWindow.this._sacStartingStateComboBox) - { - if ( ! _reloadingSacStartingStateComboBox) - { - setSacModelState(); - } - } - - DialogHelper.setDefaultCursor(AnalysisWindow.this); - - } - - } //end ModelRunStartTimeActionListener; - - //-------------------------------------------------------------------- - private class CustomModelRunDateTimeChangedDocumentListener implements DocumentListener - { - - public void insertUpdate(DocumentEvent arg0) - { - //don't bother to rerun the model if you aren't supposed to use this time anyway - if (_apiMkcUseCustomModelRunTime) - { - setApiMkcModelState(); - runModel(); - } - } - - - public void removeUpdate(DocumentEvent arg0) - { - //System.out.println("CustomModelRunDateTimeChangedActionListener.removeUpdate()"); - - } - - - public void changedUpdate(DocumentEvent arg0) - { - // System.out.println("CustomModelRunDateTimeChangedActionListener.changedUpdate()"); - // setApiMkcModelState(); - // runModel(); - - } - - } - - private class LastObsTimeForAdjustmentChangedDocumentListener implements DocumentListener - { - - public void insertUpdate(DocumentEvent arg0) - { - - // String header = "LastObsTimeForAdjustmentChangedDocumentListener.insertUpdate(): "; - - - long lastTime = _adjustmentLastObsInputTimeTextField.getTime(); - - - // System.out.println(header + " lastTime = " + - // DbTimeHelper.getDateTimeStringFromLongTime(lastTime)); - - getPrimaryStreamModel().setLastObservedTimeForAdjustment(lastTime); - - //don't bother to rerun the model if you aren't supposed to use this time anyway - if (getPrimaryStreamModel().isAdjustmentOn()) - { - - runModel(); - } - } - - - public void removeUpdate(DocumentEvent arg0) - { - - } - - - public void changedUpdate(DocumentEvent arg0) - { - - } - - } - - //-------------------------------------------------------------------- - private class ModelChoiceListener implements ActionListener - { - //private int _invocationCount = 0; - - public void actionPerformed(ActionEvent event) - { - // _invocationCount ++; - // System.out.println("---------------ModelChoiceListener.actionPerformed() invoked " + _invocationCount + " times."); - - setModelTypeToComboBoxSelection(); - } - } - //-------------------------------------------------------------------- - private class UnitHydrographChoiceListener implements ActionListener - { - //private int _invocationCount = 0; - - public void actionPerformed(ActionEvent event) - { - setUnitHydrographToComboBoxSelection(); - } - } - - //-------------------------------------------------------------------- - private class ForecastHeightTimeSeriesLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel().getForecastStageTimeSeriesHolder(); - String titleString = "Forecast Stage Editor"; - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) - { - unitString = tsHolder.getTimeSeries().getMeasuringUnit().getName(); - } - String valueLabelString = "Stage (" + unitString + ")"; - ValueMapper valueMapper = new StageToFlowValueMapper(getPrimaryStreamModel().getRatingCurve()); - - String mappedUnitString = valueMapper.getOutputMeasuringUnit().getName(); - String mappedValueLabelString = "Discharge(" + mappedUnitString + ")"; - - boolean isModal = false; - boolean isEditable = true; - - long initialSearchTime = 0; - double missingValue = _defaultMissingValue; - - - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor(AnalysisWindow.this, - tsHolder, - titleString, valueLabelString, - _defaultFormatString, - isEditable, - isModal, - valueMapper, - mappedValueLabelString, - initialSearchTime, - missingValue, - MIN_STAGE_IN_FEET, - MAX_STAGE_IN_FEET); - - editor = new RegularTimeSeriesEditor(descriptor); - - // editor.addApplyActionListener(new ForecastHeightTimeSeriesApplyActionListener()); - editor.setVisible(true); - } - } - - //-------------------------------------------------------------------- - private class PrecipTimeSeriesLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel().getPrecipTimeSeriesHolder(); - String titleString = "Mean Areal Precip Editor"; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) - { - unitString = tsHolder.getTimeSeries().getMeasuringUnit().getName(); - } - String valueLabelString = "Precip (" + unitString + ")"; - - boolean isEditable = true; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - long initialSearchTime = getPrimaryStreamModel().getModelStartTime() + _millisPerHour; - double missingValue = _defaultMissingValue; - - - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor(AnalysisWindow.this, - tsHolder, - titleString, valueLabelString, - _defaultFormatString, - isEditable, - isModal, - valueMapper, - mappedValueLabelString, - initialSearchTime, - missingValue, - MIN_PRECIP_IN_INCHES_PER_HOUR, - MAX_PRECIP_IN_INCHES_PER_HOUR); - - editor = new RegularTimeSeriesEditor(descriptor); - editor.setVisible(true); - - return; - } - } - - //-------------------------------------------------------------------- - private class EvaporationTimeSeriesLaunchActionListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel() - .getEvaporationTimeSeriesHolder(); - String titleString = "Mean Areal Potential Evaporation"; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) - { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - } - String valueLabelString = "Evap. (" + unitString + ")"; - - //editor = new RegularTimeSeriesEditor(AnalysisWindow.this, tsHolder, title, valueLabelString); - - boolean isEditable = true; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - - long initialSearchTime = getPrimaryStreamModel().getModelStartTime(); - double missingValue = _defaultMissingValue; - - - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, MIN_EVAP_PER_HOUR, - MAX_EVAP_PER_HOUR); - - - editor = new RegularTimeSeriesEditor(descriptor); - - editor.setVisible(true); - - } - } - - //-------------------------------------------------------------------- - private class PriorRunoffTimeSeriesLaunchActionListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel() - .getPriorRunoffTimeSeriesHolder(); - String titleString = "Prior Computed Runoff "; - - RegularTimeSeries ts = tsHolder.getTimeSeries(); - MeasuringUnit unit = null; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) - { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - String valueLabelString = "Runoff (" + unitString + ")"; - - boolean isEditable = false; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - - long initialSearchTime = getPrimaryStreamModel().getModelStartTime(); - double missingValue = _defaultMissingValue; - - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, - MIN_RUNOFF_IN_INCHES_PER_HOUR, - MAX_RUNOFF_IN_INCHES_PER_HOUR); - - - editor = new RegularTimeSeriesEditor(descriptor); - - - //this is not editable, so there is no apply action listener - //editor.addApplyActionListener(new PriorRunoffTimeSeriesApplyActionListener()); - - editor.setVisible(true); - - } - - else - { - //JOptionPane.showMessageDialog(AnalysisWindow.this, "Sorry, there is no prior computed runoff."); - DialogHelper.displayMessageDialog(AnalysisWindow.this, - "Sorry, there is no prior computed runoff."); - } - - } - } - - //-------------------------------------------------------------------- - - private class ShowUnadjustedStatesActionListener implements ActionListener - { - - public void actionPerformed(ActionEvent event) - { - JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) event.getSource(); - _showUnadjustedStates = checkBox.getState(); - - initSacStateComboBox(_sacStartingStateComboBox); - } - } - - //-------------------------------------------------------------------- - - - private class RunoffTimeSeriesLaunchActionListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - RegularTimeSeriesEditor editor = null; - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel() - .getRunoffTimeSeriesHolder(); - String titleString = "Computed Runoff "; - - String unitString = "Unknown Units"; - if (tsHolder.getTimeSeries() != null) - { - unitString = tsHolder.getTimeSeries().getMeasuringUnit() - .getName(); - } - String valueLabelString = "Runoff (" + unitString + ")"; - - - - boolean isEditable = false; - boolean isModal = false; - - ValueMapper valueMapper = null; - String mappedValueLabelString = "BOGUS"; - - long initialSearchTime = getPrimaryStreamModel().getModelStartTime() - + _millisPerHour; - double missingValue = _defaultMissingValue; - - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( - AnalysisWindow.this, tsHolder, titleString, - valueLabelString, _defaultFormatString, isEditable, - isModal, valueMapper, mappedValueLabelString, - initialSearchTime, missingValue, - MIN_RUNOFF_IN_INCHES_PER_HOUR, - MAX_RUNOFF_IN_INCHES_PER_HOUR); - - editor = new RegularTimeSeriesEditor(descriptor); - editor.setVisible(true); - } - } - - //-------------------------------------------------------------------- - private class ForecastHeightSaveLaunchActionListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - ForecastTsSaveDialog dialog = null; - - RegularTimeSeriesHolder tsHolder = - getPrimaryStreamModel().getForecastStageTimeSeriesHolder(); - String title = "Forecast Height Time Series Save Dialog"; - String locId = getPrimaryStreamModel().getLocationId(); - - String tableName = "FcstHeight"; - // String[] physicalElementStringArray = {"HG", "HP", "HT"}; - - String[] physicalElementStringArray = getPrimaryStreamModel().getPeArray('H'); - - String primaryPe = getPrimaryStreamModel().getPrimaryPe(); - String preferredPhysicalElement = primaryPe; - - if (primaryPe.charAt(0) != 'H') - { - preferredPhysicalElement = "HG"; - } - - dialog = new ForecastTsSaveDialog(AnalysisWindow.this, locId, - title, tsHolder, getPrimaryStreamModel().getDataMgr(), tableName, - physicalElementStringArray, - preferredPhysicalElement); - - dialog.setVisible(true); - - } - } - - //-------------------------------------------------------------------- - private class ForecastDischargeSaveLaunchActionListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - ForecastTsSaveDialog dialog = null; - - RegularTimeSeries dischargeTimeSeries = getPrimaryStreamModel() - .getDischargeTimeSeries(); - RegularTimeSeriesHolder dischargeTimeSeriesHolder = new RegularTimeSeriesHolder(); - dischargeTimeSeriesHolder.setTimeSeries(dischargeTimeSeries); - - String title = "Forecast Discharge Time Series Save Dialog"; - String locId = getPrimaryStreamModel().getLocationId(); - - String tableName = "FcstDischarge"; - //String[] physicalElementStringArray = {"QR"}; - - String[] physicalElementStringArray = getPrimaryStreamModel().getPeArray('Q'); - - String primaryPe = getPrimaryStreamModel().getPrimaryPe(); - String preferredPhysicalElement = primaryPe; - if (primaryPe.charAt(0) != 'Q') - { - preferredPhysicalElement = "QR"; - } - - dialog = new ForecastTsSaveDialog(AnalysisWindow.this, locId, - title, dischargeTimeSeriesHolder, - getPrimaryStreamModel().getDataMgr(), tableName, - physicalElementStringArray, - preferredPhysicalElement); - - dialog.setVisible(true); - - } - } - - //-------------------------------------------------------------------- - private class EvapSaveLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - ForecastTsSaveDialog dialog = null; - - RegularTimeSeriesHolder tsHolder = getPrimaryStreamModel() - .getEvaporationTimeSeriesHolder(); - String title = "Evapotranspiration Time Series Save Dialog"; - String locId = getPrimaryStreamModel().getLocationId(); - - String tableName = "FcstOther"; - String[] physicalElementStringArray = {"EA"}; - String preferredPhysicalElement = "EA"; - - dialog = new ForecastTsSaveDialog(AnalysisWindow.this, locId, - title, tsHolder, getPrimaryStreamModel().getDataMgr(), tableName, - physicalElementStringArray, - preferredPhysicalElement); - dialog.addApplyActionListener(new ForecastOtherSaveCompleteListener()); - - dialog.setVisible(true); - - } - } - - // ---------------------------------------------------------------------------------------------- - - private class MAPSaveLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - usePrecipFileChooserForSaving(); - } - } - - //-------------------------------------------------------------------- - private class SacParamsLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - String basinId = getPrimaryStreamModel().getBasinId(); - - SacParamsEditor editor = null; - editor = new SacParamsEditor(AnalysisWindow.this, getPrimaryStreamModel().getDataMgr(), basinId); - - editor.addApplyActionListener(new SacParamsSaveCompleteActionListener()); - - editor.setVisible(true); - } - } - - - //-------------------------------------------------------------------- - - private class SetInitialVarStateActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - boolean confirmed = false; - - confirmed = DialogHelper.displayConfirmDialog(AnalysisWindow.this, - "Do you want to turn the currently selected model conditions into\n" + - "the initial VAR conditions (moving forward) ?", - "Confirm VAR state Reinitialization"); - - if (confirmed) - { - - DialogHelper.displayMessageDialog(AnalysisWindow.this, "Reinitializing initial VAR conditions"); - - SSHPSource source = SSHPSource.UNADJUSTED_VAR; - - StreamModel primaryStreamModel = getPrimaryStreamModel(); - primaryStreamModel.saveInitialSacSmaConditions(source); - - initSacStateComboBox(_sacStartingStateComboBox); - - } - else //rejected - { - DialogHelper.displayMessageDialog(AnalysisWindow.this, "Cancelling reinitialization of initial VAR conditions"); - } - - } - } - - //-------------------------------------------------------------------- - private class AdjustToggleActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - boolean isAdjustmentOn = _adjustmentCheckBox.isSelected(); - getPrimaryStreamModel().setAdjustmentOn(isAdjustmentOn); - runModel(); - } - } - //-------------------------------------------------------------------- - private class AdjustmentHoursChangeListener implements ChangeListener - { - public void stateChanged(ChangeEvent e) - { - - Integer integer =(Integer) _blendPeriodSpinner.getValue(); - - int newValue = integer.intValue(); - - // _blendPeriodValueLabel.setText(newValue + "" ); - - getPrimaryStreamModel().setAdjustmentHours(newValue); - - if (getPrimaryStreamModel().isAdjustmentOn()) - { - runModel(); - } - } - - - } - - //-------------------------------------------------------------------- - - private class LiveSacStatesAdjustmentActionListener implements ActionListener - { - public void actionPerformed(ActionEvent event) - { - // final String header = "LiveSacStatesAdjustmentActionListener.actionPeformed(): "; - // System.out.println(header + "message = " + event.getActionCommand()); - - runModel(); - } - } - //-------------------------------------------------------------------- - - private class ForecastHoursChangeListener implements ChangeListener - { - public void stateChanged(ChangeEvent e) - { - Integer integer =(Integer) _forecastHoursSpinner.getValue(); - int newValue = integer.intValue(); - - _modelManager.setForecastLengthInHours(newValue); - // getPrimaryStreamModel().setForecastLengthInHours(newValue); - runModel(); - - } - } - //-------------------------------------------------------------------- - - private class SacStateLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String basinId = getPrimaryStreamModel().getBasinId(); - - SacStateEditor editor = null; - editor = new SacStateEditor(AnalysisWindow.this, - getPrimaryStreamModel().getDataMgr(), basinId); - - editor.addApplyActionListener(new SacStateSaveCompleteActionListener()); - editor.setVisible(true); - - } - } - - - private class LiveSacStateLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - boolean isModal = false; - - //used by AnalysisWindow to call runModel(); - ActionListener liveSacStatesAdjustmentActionListener = - new LiveSacStatesAdjustmentActionListener(); - - LiveSacStateEditor editor = new LiveSacStateEditor(AnalysisWindow.this, - getPrimaryStreamModel().getSacState(), - getPrimaryStreamModel().getSacParams(), - isModal, - liveSacStatesAdjustmentActionListener); - - editor.setVisible(true); - - } - } - - //-------------------------------------------------------------------- - - private class SacStateSaveCompleteActionListener implements ActionListener - { - // make sure that the model settings are reloaded and - // then rerun the model - public void actionPerformed(ActionEvent evt) - { - - - getPrimaryStreamModel().reloadModelData(); - - - getPrimaryStreamModel().runModel(); - - } - } - - //-------------------------------------------------------------------- - - - private class SacParamsSaveCompleteActionListener implements ActionListener - { - // make sure that the model settings are reloaded and - // then rerun the model - public void actionPerformed(ActionEvent evt) - { - getPrimaryStreamModel().reloadModelData(); - - getPrimaryStreamModel().runModel(); - - } - } - - //-------------------------------------------------------------------- - - private class MonthlyMapeEditorLaunchActionListener implements - ActionListener - { - public void actionPerformed(ActionEvent evt) - { - MonthlyValueEditor editor = null; - - JFrame ownerFrame = AnalysisWindow.this; - DataMgr dataMgr = getPrimaryStreamModel().getDataMgr(); - String basinId = getPrimaryStreamModel().getBasinId(); - boolean isModal = false; - String pe = "EA"; - - editor = new MonthlyValueEditor(ownerFrame, dataMgr, basinId, pe, - isModal); - editor.setVisible(true); - - } - } - - //-------------------------------------------------------------------- - - private class ForecastOtherSaveCompleteListener implements ActionListener - { - // a listener for the forecast save dialog - public void actionPerformed(ActionEvent event) - { - //System.out.println("ForecastOtherSaveCompleteListener invoked"); - //do nothing, needed to fulfill editor class obligations - } - - } - - //-------------------------------------------------------------------- - - private class ForecastHeightTimeSeriesChangeListener implements - TimeSeriesListener - { - public Object getReceiver() - { - return AnalysisWindow.this; - } - - public void handleTimeSeriesEvent(TimeSeriesEvent event) - { - // String header = "ForecastHeightTimeSeriesChangeListener.handleTimeSeriesEvent()"; - // System.out.println(header + "event = " + event.toString()); - redrawCanvases(); - - } - } - - //-------------------------------------------------------------------- - - private class PrecipTimeSeriesChangeListener implements TimeSeriesListener - { - - public Object getReceiver() - { - return AnalysisWindow.this; - } - - // used for receiving events from precip tabular editing - public void handleTimeSeriesEvent(TimeSeriesEvent event) - { - //String header = "PrecipTimeSeriesChangeListener.handleTimeSeriesEvent()"; - // System.out.println(header + "event = " + event.toString()); - runModel(); - - } - - } - - // -------------------------------------------------------------------- - - private class EvaporationTimeSeriesChangeListener implements - TimeSeriesListener - { - - public Object getReceiver() - { - return AnalysisWindow.this; - } - - // used for tabular editing of the evaporation time series - public void handleTimeSeriesEvent(TimeSeriesEvent event) - { - //String header = "EvaporationTimeSeriesChangeListener.handleTimeSeriesEvent()"; - //System.out.println(header + "event = " + event.toString()); - runModel(); - - } - - } - - // -------------------------------------------------------------------- - - private class ScreenCaptureActionListener implements ActionListener - { - public void actionPerformed(ActionEvent event) - { - - useCaptureScreenFileChooserForSaving(); - // AnalysisWindow.this.displayCaptureScreenFileChooser(); - - } //end actionPerformed - - } //end ScreenCaptureActionListener - - //-------------------------------------------------------------------- - - // ----------------------------------------------------------------- -} //end class AnalysisWindow diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindow.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindow.java deleted file mode 100644 index d880fa35fc..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindow.java +++ /dev/null @@ -1,796 +0,0 @@ -/* - * Created on Dec 19, 2003 - * - * - */ -package ohd.hseb.sshp.window; - - -import java.awt.*; -import java.awt.event.*; - -import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableColumn; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.sshp.*; -import ohd.hseb.sshp.gui.GuiHelper; -import ohd.hseb.sshp.precip.MAPPreprocessor; -import ohd.hseb.util.EnvHelper; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableColumnComparator; -import ohd.hseb.util.gui.WindowResizingManager; - -/** - * @author GobsC - * This class is the startup window for the SSHP application when no argument for - * the location id is entered. It allows for the selection of a location. - */ -public class ControlWindow extends JFrame -{ - private Dimension _maxDimension = new Dimension(800, 700); - private Dimension _initialDimension = new Dimension(800, 400); - private Dimension _minDimension = new Dimension(600, 200); - - private AppController _controller = null; - private List _locationIdList = null; - private DataMgr _dataMgr = null; - - - // ---GUI items------------------------ - - private JMenuBar _menuBar = null; - private JPanel _mainPanel = null; - - private JPanel _selectionPanel = null; - private JLabel _locationLabel = null; - - private ControlWindowTableAdapter _tableAdapter = null; - - private JPanel _buttonPanel = null; - private JButton _exitButton = null; - private JButton _launchButton = null; - // private JButton _launchButton2 = null; - - public static final String LID = "Location Id"; - public static final String NAME = "Name"; - public static final String BASIN_ID = "Basin Id"; - public static final String STREAM_NAME= "Stream Name"; - public static final String HSA = "HSA"; - public static final String MODEL_PREFERENCE = "RR Model Pref"; //rainfall-runoff model preference - - private List _descriptorList = null; - private LocationDescriptor _selectedLocationDescriptor = null; - - // --------------------------------------------------------------------- - - public ControlWindow(DataMgr dataMgr, AppController controller) - { - _dataMgr = dataMgr; - _controller = controller; - - initGui(); - } - - // --------------------------------------------------------------------- - public void enableLaunchButton(boolean value) - { - _launchButton.setEnabled(value); - } - - // --------------------------------------------------------------------- - - private void initGui() - { - // Dimension scrolledPaneDimension = new Dimension(500, 300); - - - - initMenuBar(); - setJMenuBar(_menuBar); - - // String header = "LaunchWindow.initGui(): "; - setTitle("Site Specific Hydrologic Predictor Control Window on " + _dataMgr.getDatabaseName()); - - JPanel spaceFiller = new JPanel(); -// Note: setMinimumSize() does not work for this purpose - spaceFiller.setPreferredSize(new Dimension(300, 100)); - - //selection Panel - - createSelectionPanel(); - - // button Panel - _buttonPanel = new JPanel(); - - _launchButton = GuiHelper.getJButton("Analysis Window..."); - _exitButton = GuiHelper.getJButton("Exit Application"); - - - _buttonPanel.add(_launchButton); - _buttonPanel.add(_exitButton); - - - - // setup the main panel - - _mainPanel = new JPanel(); - // _mainPanel.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT)); - - GridBagLayout layoutMgr = new GridBagLayout(); - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _mainPanel.setLayout(layoutMgr); - // col, row numCols numRows Wcol wrow - addComponent(_mainPanel, spaceFiller, mainGbc, 0, 0, 1, 1, 0, 0); - addComponent(_mainPanel, _selectionPanel, mainGbc, 0, 1, 1, 1, 1, 1); - addComponent(_mainPanel, _buttonPanel, mainGbc, 0, 2, 2, 2, 0, 0); - - - - //set up initial bounds limitations - //see WindowResize listener for the minimum setting - - Rectangle maxBoundsRectangle = new Rectangle(_maxDimension); - this.setMaximizedBounds(maxBoundsRectangle); - - //hook up the mainPanel to the contentPane - - this.getContentPane().add(_mainPanel); - this.pack(); - - Rectangle initialBoundsRectangle = new Rectangle(_initialDimension); - this.setBounds(initialBoundsRectangle); - - - addListeners(); - - return; - } - // --------------------------------------------------------------------- - private void createSelectionPanel() - { - Dimension selectionPanelDimension = new Dimension(800,700); - - _locationLabel = new JLabel("Available Locations:"); - _locationIdList = _dataMgr.loadLocationIdsForForecasts(); - - int listSize = _locationIdList.size(); - _selectionPanel = new JPanel(); - _selectionPanel.setPreferredSize(selectionPanelDimension); - - - - // create the JTable from which to choose the Location - _descriptorList = createLocationDescriptorList(_locationIdList); - _tableAdapter = createDescriptorTableAdapter(_descriptorList); - - - GridBagLayout layoutMgr = new GridBagLayout(); - GridBagConstraints mainGbc = new GridBagConstraints(); - - mainGbc.fill = GridBagConstraints.BOTH; - mainGbc.anchor = GridBagConstraints.NORTHWEST; - mainGbc.weightx = 1; - mainGbc.weighty = 1; - - _selectionPanel.setLayout(layoutMgr); - - JScrollPane scrollPane = _tableAdapter.getScrollPane(); - - // col, row numCols numRows Wcol wrow - addComponent(_selectionPanel, _locationLabel, mainGbc, 0, 0, 1, 1, 0, 0); - addComponent(_selectionPanel, scrollPane, mainGbc, 0, 1, 1, 1, 1, 1); - - } - // --------------------------------------------------------------------- - private ControlWindowTableAdapter createDescriptorTableAdapter(List descriptorList) - { - - Dimension scrolledPaneDimension = new Dimension(500, 150); - Dimension scrolledPaneViewportDimension = new Dimension(300, 100); - - JTable table = null; - String[] columnNameArray = { LID, NAME, BASIN_ID, STREAM_NAME, HSA, MODEL_PREFERENCE }; - ControlWindowTableAdapter tableAdapter = null; - - TableColumnComparator comparator = new ControlWindowTableColumnComparator(); - tableAdapter = new ControlWindowTableAdapter(comparator, - columnNameArray, - descriptorList ); - - - JScrollPane tableScrollPane = tableAdapter.getScrollPane(); - tableScrollPane.setPreferredSize(scrolledPaneDimension); - tableScrollPane.setMinimumSize(scrolledPaneDimension); - - - //select the first descriptor in the list - if (tableAdapter.getDescriptorCount() > -1) - { - tableAdapter.setSelectedIndex(0); - LocationDescriptor descriptor = tableAdapter.getDescriptorByIndex(0); - } - - tableAdapter.getTable().setPreferredScrollableViewportSize( scrolledPaneViewportDimension ); - - - TableColumn col = tableAdapter.getTable().getColumnModel().getColumn(0); - int width = 20; - col.setPreferredWidth(width); - - - return tableAdapter; - - } - - // --------------------------------------------------------------------- - - private List createLocationDescriptorList(List locationIdList) - { - List locationDescriptorList = new ArrayList(); - final int maxNameStringLength = 20; - - // StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < locationIdList.size(); i++) - { - //clear out any old string - // buffer.setLength(0); - - String locationId = (String) locationIdList.get(i); - - LocationDescriptor descriptor = _dataMgr.getLocationDescriptor(locationId); - locationDescriptorList.add(descriptor); - - } - - return locationDescriptorList; - - } - // --------------------------------------------------------------------- - - // --------------------------------------------------------------------- - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Open Analysis Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_O, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Open a new Analysis Window"); - menu.add(menuItem); - menuItem.addActionListener(new AnalysisWindowLaunchListener()); - - - menuItem = new JMenuItem("Exit Application"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_E, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Exit the Application"); - menu.add(menuItem); - menuItem.addActionListener(new ExitListener()); - - - - // Configuration Menu - menu = new JMenu("Configuration"); - menu.setMnemonic(KeyEvent.VK_C); - menu.getAccessibleContext().setAccessibleDescription( - "Configure the forecast points"); - _menuBar.add(menu); - - menuItem = new JMenuItem("Configure Fcst Points for SSHP..."); - // menuItem.setAccelerator(KeyStroke.getKeyStroke( - // KeyEvent.VK_S, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Configure a point for SSHP"); - menu.add(menuItem); - - menuItem.addActionListener(new ConfigureLaunchListener()); - - - // monthly values menuItem - menuItem = new JMenuItem("MAPE Monthly Values Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_M, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit MAPE Monthly Values"); - menu.add(menuItem); - - menuItem.addActionListener(new MonthlyMapeEditorLaunchActionListener()); - - - //SAC-SMA parameters editor menu item - menuItem = new JMenuItem("SAC-SMA Parameters Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_P, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit SAC-SMA Parameters"); - menu.add(menuItem); - - menuItem.addActionListener(new SacParamsLaunchActionListener()); - - // SAC-SMA states editor menu Item - menuItem = new JMenuItem("SAC-SMA States Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_S, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit SAC-SMA States"); - menu.add(menuItem); - - menuItem.addActionListener(new SacStateLaunchActionListener()); - - - // Rating Curve editor menu Item - menuItem = new JMenuItem("Rating Curve Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_R, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit Rating Curves"); - menu.add(menuItem); - - menuItem.addActionListener(new RatingCurveLaunchActionListener()); - - - // UnitHydrograph editor menu Item - menuItem = new JMenuItem("Unit Hydrograph Editor..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_U, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "View and edit Unit Hyddrographs"); - menu.add(menuItem); - - menuItem.addActionListener(new UnitHydrographLaunchActionListener()); - - - // extra - menu = new JMenu("Extra"); - menu.setMnemonic(KeyEvent.VK_X); - menu.getAccessibleContext().setAccessibleDescription( - "Extra functionality"); - _menuBar.add(menu); - - // Run preprocessor - menuItem = new JMenuItem("Run MAP Preprocessor..."); - // menuItem.setAccelerator(KeyStroke.getKeyStroke( - // KeyEvent.VK_P, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Run MAP Preprocessor"); - menu.add(menuItem); - - menuItem.addActionListener(new MapPreprocessorRunListener()); - - // separator - - //JSeparator menuSeparator = new JSeparator(); - //_menuBar.add(menuSeparator); - - - //acts as a separator to move the Help menu all the way to the right - menuItem = new JMenuItem(""); - menuItem.setEnabled(false); - _menuBar.add(menuItem); - - - // Help Menu - - menu = new JMenu("Help"); - menu.setMnemonic(KeyEvent.VK_HELP); - menu.getAccessibleContext().setAccessibleDescription( - "Access help menu items."); - _menuBar.add(menu); - - menuItem = new JMenuItem("About..."); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_A, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Display the About Dialog."); - menu.add(menuItem); - - menuItem.addActionListener(new AboutLaunchListener()); - - - } - - // --------------------------------------------------------------------- - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - // --------------------------------------------------------------------- - private void runMAPPreprocessor() - { - final long millisPerHour = 1000 * 60 * 60; - MAPPreprocessor preprocessor = null; - - long endTime = System.currentTimeMillis(); - endTime = (endTime/millisPerHour) * millisPerHour; - - long startTime = endTime - (6 * 24 * millisPerHour) ; - - String fileDir = _controller.getLogDirName(); - String fileName = "/MAPPreprocessor.log"; - String filePath = null; - - if (fileDir != null) - { - filePath = fileDir + fileName; - } - else - { - filePath = fileName; - } - - - Logger logger = new FileLogger(filePath, true, true); - - // preprocessor = new MAPPreprocessor(_dataMgr, startTime, endTime, logger); - preprocessor = new MAPPreprocessor(_dataMgr, logger); - - System.out.println("Beginning MAP preprocessing"); - preprocessor.preprocessAll(); - System.out.println("Completed MAP preprocessing"); - - - } //runMAPPreprocessor (in same VM) - // --------------------------------------------------------------------- - - private void runMAPPreprocessorAsSeparateProcess() - { - String header = "ControlWindow.runMAPPreprocessorAsSeparateProcess(): "; - System.out.println("Beginning MAP preprocessing"); - EnvHelper envHelper = new EnvHelper(); - - String dirString = envHelper.getProperty("WHFS_BIN_DIR"); - - String commandString = dirString + "/run_SSHP_MAP_preprocess"; - - if (_controller.isRunningOnWindows()) - { - commandString += ".bat"; - } - - System.out.println(header + "making system call:" + commandString + ":"); - System.out.flush(); - try - { - Process process = Runtime.getRuntime().exec(commandString); - process.waitFor(); - } - catch(IOException e) - { - e.printStackTrace(); - } - catch( InterruptedException e ) - { - e.printStackTrace(); - } - - System.out.println("Completed MAP preprocessing"); - } - - // --------------------------------------------------------------------- - - - private void addListeners() - { - //allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - //hook up the configure launch button - // _configButton.addActionListener(new ConfigureLaunchListener()); - - //hook up the run MAP preprocessor button - // _mapPreprocessorButton.addActionListener(new MapPreprocessorRunListener()); - - //hook up the application launch button and the double click launching from the table - // _launchButton.addActionListener(new OldAnalysisWindowLaunchListener()); - _launchButton.addActionListener(new AnalysisWindowLaunchListener()); - _tableAdapter.getTable().addMouseListener(new DoubleClickAnalysisWindowLaunchListener()); - - // set up the action to perform when the close button is pressed - _exitButton.addActionListener( new ExitListener()); - - // sets up the minimum and maximum sizes for the window - WindowResizingManager mgr = new WindowResizingManager(this, _minDimension, _maxDimension); - - _tableAdapter.getListSelectionModel().addListSelectionListener( new DescriptorRowSelectionListener() ); - - } - -// --------------------------------------------------------------------------------- - public String getSelectedLocationId() - { - String locationId = null; - int listSize = _locationIdList.size(); - - int selectedIndex = _tableAdapter.getFirstSelectedIndex(); - if ( (selectedIndex >= 0) && (listSize > 0) ) - { - // locationId = (String) _locationIdList.get(selectedIndex); - - LocationDescriptor desc = (LocationDescriptor) _tableAdapter.getDataList().get(selectedIndex); - locationId = desc.getId(); - } - - return locationId; - } - - // --------------------------------------------------------------------- - private synchronized void launchAnalysisWindow() - { - DialogHelper.setWaitCursor(ControlWindow.this); - _launchButton.setEnabled(false); - - String locationId = getSelectedLocationId(); - - if (locationId != null) - { - _controller.displayAnalysisWindow(locationId); - - } - else - { - DialogHelper.displayErrorDialog(ControlWindow.this, - "You need to select a station in order to display the Analysis Window.", - "No Station Selected"); - } - - _launchButton.setEnabled(true); - - DialogHelper.setDefaultCursor(ControlWindow.this); - - } - // --------------------------------------------------------------------- - private class FrameCloseWindowListener extends WindowAdapter - { - public void windowClosing(WindowEvent evt) - { - dispose(); - _dataMgr.disconnect(); - System.exit(0); - } - - } - - // --------------------------------------------------------------------- - - private class MapPreprocessorRunListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - DialogHelper.setWaitCursor(_menuBar); - runMAPPreprocessorAsSeparateProcess(); - DialogHelper.setDefaultCursor(_menuBar); - } - } - // --------------------------------------------------------------------- - - private class ExitListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - dispose(); - System.exit(0); - } - } - - // --------------------------------------------------------------------- - private class AboutLaunchListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - //JOptionPane.showMessageDialog(LaunchWindow.this, _aboutText, "About SSHP", JOptionPane.INFORMATION_MESSAGE ); - String aboutText = AboutInfo.getText(); - DialogHelper.displayMessageDialog(ControlWindow.this, aboutText, "About SSHP"); - } - } - - // --------------------------------------------------------------------- - private class AnalysisWindowLaunchListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - launchAnalysisWindow(); - return; - } - } - - // --------------------------------------------------------------------- - - private class DoubleClickAnalysisWindowLaunchListener extends MouseAdapter - { - public void mouseClicked(MouseEvent event) - { - int button = event.getButton(); - if (button == MouseEvent.BUTTON1) - { - if (event.getClickCount() > 1) - { - launchAnalysisWindow(); - } - } - return; - } - } - // --------------------------------------------------------------------- - private class ConfigureLaunchListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - SSHPConfigDialog dialog = new SSHPConfigDialog(ControlWindow.this, _dataMgr); - - dialog.setVisible(true); - - } - } //ConfigureLaunchListener - - // --------------------------------------------------------------------- - - private class MonthlyMapeEditorLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - MonthlyValueEditor editor = null; - - JFrame ownerFrame = ControlWindow.this; - DataMgr dataMgr = _dataMgr; - String basinId = null; - boolean isModal = false; - String pe = "EA"; - - editor = new MonthlyValueEditor(ownerFrame, dataMgr, basinId, pe, isModal); - editor.setVisible(true); - - } - } - //-------------------------------------------------------------------- - - private class SacParamsLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - String basinId = null; - SacParamsEditor editor = null; - - editor = new SacParamsEditor(ControlWindow.this, _dataMgr, basinId); - editor.setVisible(true); - } - } - - //-------------------------------------------------------------------- - - private class SacStateLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String basinId = null; - - SacStateEditor editor = null; - editor = new SacStateEditor(ControlWindow.this, _dataMgr, basinId); - - editor.setVisible(true); - } - } - - //-------------------------------------------------------------------- - private class RatingCurveLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - String lid = getSelectedLocationId(); - - if (lid != null) - { - RatingCurveEditor editor = null; - // editor = new RatingCurveEditor(ControlWindow.this, _dataMgr, - // basinId); - boolean isModal = false; - editor = new RatingCurveEditor(ControlWindow.this, _dataMgr, - lid, isModal); - - - editor.setVisible(true); - } - } - } - - //-------------------------------------------------------------------- - - private class UnitHydrographLaunchActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - - String lid = getSelectedLocationId(); - - if (lid != null) - { - UnitHydrographEditor editor = null; - boolean isModal = false; - editor = new UnitHydrographEditor(ControlWindow.this, _dataMgr, lid, isModal ); - - editor.setVisible(true); - } - } - } - - //-------------------------------------------------------------------- - private class DescriptorRowSelectionListener implements - ListSelectionListener - { - - public void valueChanged(ListSelectionEvent event) - { - String header = "DescriptorRowSelectionListener.valueChanged(): "; - LocationDescriptor descriptor = null; - - int index = _tableAdapter.getFirstSelectedIndex(); - - if (index > -1) - { - _selectedLocationDescriptor = (LocationDescriptor)_descriptorList.get(index); - // System.out.println(header + "selected lid = " + - // _selectedLocationDescriptor.getId()); - } - else - { - _selectedLocationDescriptor = null; - } - - } - } - //-------------------------------------------------------------------- - -} //end LaunchWindow class diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindowTableAdapter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindowTableAdapter.java deleted file mode 100644 index 6caa4a1072..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindowTableAdapter.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.util.List; - -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.sshp.gui.TableAdapter; -import ohd.hseb.util.gui.TableColumnComparator; - - -/** - * @author GobsC - * - * - */ -public class ControlWindowTableAdapter extends TableAdapter -{ - - private LocationDescriptor _descriptor = null; - private List _descriptorList = null; - - // --------------------------------------------------------------------------------- - - - - public ControlWindowTableAdapter(TableColumnComparator comparator, - String[] columnNameArray, - List dataList) - { - super(comparator, columnNameArray, dataList); - - setAllowMultipleSelection(false); - - } - - // --------------------------------------------------------------------------------- - public String[][] getDataStringArrayFromDataList(List locationDescriptorList) - { - - //set alias for cut-and-paste-ability of code - List dataList = locationDescriptorList; - - int fieldCount = 6; - String[][] dataArray = new String[dataList.size()][fieldCount]; - - - for (int i = 0; i < dataList.size(); i++) - { - LocationDescriptor desc = (LocationDescriptor) dataList.get(i); - - dataArray[i][0] = desc.getId(); - dataArray[i][1] = desc.getLocationName(); - - dataArray[i][2] = desc.getBasinId(); - dataArray[i][3] = desc.getStreamName(); - dataArray[i][4] = desc.getHsa(); - dataArray[i][5] = desc.getModelPreference(); - } - - return dataArray; - - } - // --------------------------------------------------------------------------------- - public void refreshTableModel(List dataList) - { - setDataList(dataList);// for super class - - _descriptorList = dataList; - - String[][] dataStringArray = getDataStringArrayFromDataList(dataList); - getTableModel().updateData( dataStringArray ); - getTableModel().fireTableChanged( null ); - - - return; - - } - // --------------------------------------------------------------------------------- - - public int getDescriptorCount() - { - int count = getDataList().size(); - return count; - } - - // --------------------------------------------------------------------------------- - - public LocationDescriptor getDescriptorByIndex(int index) - { - List dataList = getDataList(); - LocationDescriptor desc = null; - - if ( dataList.size() > 0 ) - { - Object object = dataList.get(index); - desc = (LocationDescriptor) object; - } - return desc; - } - - // --------------------------------------------------------------------------------- - - private int findIndexOfDescriptor(LocationDescriptor desc) - { - int index = _descriptorList.indexOf(desc); - - return index; - } - // ------------------------------------------------------------------------------------- - public void setDataList(List dataList) - { - - super.setDataList(dataList); - _descriptorList = dataList; - - } - - // --------------------------------------------------------------------------------- - - - private void selectAll() - { - - getListSelectionModel().setSelectionInterval(0, getTable().getModel().getRowCount()-1); - } - - - // --------------------------------------------------------------------------------- - public void setSelectedIndex(int index) - { - - getListSelectionModel().setSelectionInterval(index, index); - - } - // --------------------------------------------------------------------------------- - - public void selectItems(List selectedDescriptorList) - { - getListSelectionModel().clearSelection(); - - for (int i = 0; i < selectedDescriptorList.size(); i++) - { - LocationDescriptor descriptor = (LocationDescriptor) selectedDescriptorList.get(i); - - int index = findIndexOfDescriptor(descriptor); - - if (index >= 0) - { - getListSelectionModel().setSelectionInterval(index, index); - } - } - } - // --------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindowTableColumnComparator.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindowTableColumnComparator.java deleted file mode 100644 index 32383f98aa..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ControlWindowTableColumnComparator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - - -import ohd.hseb.model.LocationDescriptor; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author GobsC - * - */ -public class ControlWindowTableColumnComparator extends TableColumnComparator -{ - public ControlWindowTableColumnComparator() - { - } - - public int compareLid( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - int result = compareStrings(desc1.getId(), desc2.getId()); - return result; - } - - public int compareName( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getLocationName(), desc2.getLocationName() ) ); - } - - public int compareStreamName( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getStreamName(), desc2.getStreamName() ) ); - } - - public int compareBasinId( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getBasinId(), desc2.getBasinId() ) ); - } - - public int compareHsa( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getHsa(), desc2.getHsa() ) ); - } - - public int compareModelPreference( LocationDescriptor desc1, LocationDescriptor desc2 ) - { - return( compareStrings( desc1.getModelPreference(), desc2.getModelPreference() ) ); - } - - public int compare(Object object1, Object object2) - { - LocationDescriptor desc1 = (LocationDescriptor) object1; - LocationDescriptor desc2 = (LocationDescriptor) object2; - - int returnValue = 0; - - - if( _columnName.equalsIgnoreCase( ControlWindow.LID ) ) - { - returnValue = compareLid( desc1, desc2 ); - } - else if ( _columnName.equalsIgnoreCase( ControlWindow.NAME ) ) - { - returnValue = compareName( desc1, desc2 ); - } - else if ( _columnName.equalsIgnoreCase( ControlWindow.STREAM_NAME)) - { - returnValue = compareStreamName( desc1, desc2 ); - } - else if (_columnName.equalsIgnoreCase( ControlWindow.BASIN_ID) ) - { - returnValue = compareBasinId( desc1, desc2 ); - } - - else if (_columnName.equalsIgnoreCase( ControlWindow.HSA) ) - { - returnValue = compareHsa( desc1, desc2 ); - } - - else if (_columnName.equalsIgnoreCase( ControlWindow.MODEL_PREFERENCE) ) - { - returnValue = compareModelPreference(desc1, desc2); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/FileChooserHelper.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/FileChooserHelper.java deleted file mode 100644 index ec8b8b8054..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/FileChooserHelper.java +++ /dev/null @@ -1,153 +0,0 @@ -package ohd.hseb.sshp.window; - -import java.awt.Window; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileFilter; - -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; - -public class FileChooserHelper -{ - - private String _lastUsedDirectory = null; - private JFileChooser _fileChooser = null; - private FileFilter _fileFilter = null; - private String[] _acceptableExtensionArray = null; - - private File _selectedFile; - - // ------------------------------------------------------------------------------ - - public FileChooserHelper(String defaultDirectory, - String[] acceptableExtensionArray, - String fileTypeDescriptionString) - { - _fileChooser = new JFileChooser(defaultDirectory); - - _acceptableExtensionArray = acceptableExtensionArray; - - //add a FileFilter - List filterList = new ArrayList(); - - for (int i = 0 ; i < _acceptableExtensionArray.length; i++) - { - filterList.add( _acceptableExtensionArray[i]); - } - - _fileFilter = new ExtensionFileFilter( filterList, fileTypeDescriptionString); - _fileChooser.setFileFilter( _fileFilter ); - - return; - } - - // ------------------------------------------------------------------------------ - private boolean endsWithProperExtension(String filePathString) - { - boolean hasProperExtension = false; - - for (int i = 0; i < _acceptableExtensionArray.length; i++) - { - String extension = "." + _acceptableExtensionArray[i]; - if (filePathString.endsWith(extension)) - { - hasProperExtension = true; - break; - } - } - - return hasProperExtension; - } - - // ------------------------------------------------------------------------------ - public String displayForOpen(Window window) - { - return display(window, true); - } - - // ------------------------------------------------------------------------------ - public String displayForSave(Window window) - { - return display(window, false); - } - - // ------------------------------------------------------------------------------ - - - private String display(Window window, boolean forOpening) - { - String header = "FileChooserHelper.display(): "; - - String filePath = null; - File file = null; - int returnValue = 0; - - if (forOpening) - { - returnValue = _fileChooser.showOpenDialog( window ); - } - else //for Saving - { - returnValue = _fileChooser.showSaveDialog( window ); - } - - if (returnValue == JFileChooser.APPROVE_OPTION) - { - file = _fileChooser.getSelectedFile(); - setSelectedFile(file); - - try - { - filePath = file.getCanonicalPath(); - - //ensure ends with a proper extension - if (! endsWithProperExtension(filePath) ) - { - String extension = ""; - if (_acceptableExtensionArray.length > 0) - { - extension = "." + _acceptableExtensionArray[0]; - filePath = filePath + extension; - } - - } - - } - catch (IOException e) - { - DialogHelper.displayMessageDialog(window, "Error: File not selected."); - } - } - else - { - DialogHelper.displayMessageDialog(window, "File not selected."); - } - - return filePath; - - } - - /** - * @param selectedFile The selectedFile to set. - */ - public void setSelectedFile(File selectedFile) - { - _selectedFile = selectedFile; - } - - /** - * @return Returns the selectedFile. - */ - public File getSelectedFile() - { - return _selectedFile; - } - - // ------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ForecastTsSaveDialog.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ForecastTsSaveDialog.java deleted file mode 100644 index 7247b3858a..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/ForecastTsSaveDialog.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Created on Dec 8, 2003 - * - * Filename : ForecastTsSaveDialog.java - * Author : Gautam Sood - * Last Revision Date : Dec 8, 2003 - * - */ -package ohd.hseb.sshp.window; - -import javax.swing.*; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import java.util.List; - -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeTextField; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.FcstTsDescriptor; -import ohd.hseb.measurement.*; -import ohd.hseb.util.gui.*; - -public class ForecastTsSaveDialog extends JDialog -{ - private static final long HOUR_IN_MILLIS = 60 * 60 * 1000; - private static final int GOOD_QC=1879048191; - private RegularTimeSeriesHolder _timeSeriesHolder = null; - private RegularTimeSeries _timeSeries = null; - private DataMgr _dataMgr = null; - - private static final int DEFAULT_WIDTH = 390; - - private static final int DEFAULT_HEIGHT = 390; - - private static final int MAX_WIDTH = DEFAULT_WIDTH; - private static final int MAX_HEIGHT = DEFAULT_HEIGHT; - - private static final int MIN_WIDTH = 266; - private static final int MIN_HEIGHT = 296; - - private static final int SAVE_HOURS_STEPS = 6; - - private String _extremum = "Z"; - private float _probability = -1.0f; - private int _revision = 0; - private String _physicalElement = null; - - private String[] _physicalElementStringArray = null; - - private String _lid = null; - private String _productId = ""; - private String _basisProductTime = null; - private String _tableName = null; - private String[] _typeSourceStringArray = { "FE", "FF", "FG", "FM", "FZ" }; - private String _sshpForecastTsToken = null; - private String[] _shefQualifierStringArray = { "Z", "E" }; - private long _productTime = 0; - private long _basisTime = 0; - - - - //used for custom notification - private List _applyListenerList = new ArrayList(); - -// GUI Components - private Container _frameContentPane = getContentPane(); - private JLabel _physicalElementLabel = new JLabel( "Physical Element: " ); - private JLabel _pElementValueLabel = new JLabel(); - private JComboBox _physicalElementComboBox = null; - - private JLabel _typeSourceLabel = new JLabel( "Type Source: " ); - private JLabel _shefQualifierLabel = new JLabel( "SHEF Qualifier: " ); - private JLabel _productIDLabel = new JLabel( "Product ID: " ); - private JLabel _basisTimeLabel = new JLabel( "Basis Time: " ); - private JLabel _productTimeLabel = new JLabel( "Product Time: " ); - private JTextField _productIDTextField = new JTextField(10); - - private DateTimeTextField _basisTimeTextField = null; - private DateTimeTextField _productTimeTextField = null; - - private JComboBox _typeSourceComboBox = new JComboBox( _typeSourceStringArray ); - private JComboBox _shefQualifierComboBox = new JComboBox( _shefQualifierStringArray ); - private JPanel _dataPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private JLabel _hoursToSaveLabel = new JLabel("Hours to Save:"); - private JSpinner _hoursToSaveSpinner = null; - - //private JButton _saveButton = new JButton( "
    Save to
    Database
    " ); - private JButton _saveButton = new JButton( "Save to Database" ); - private JButton _closeButton = new JButton( "Close" ); - -/* Empty Constructor - * Sets the basis and product time to the current system time - */ - - public ForecastTsSaveDialog( JFrame owner, String lid, String title, - RegularTimeSeriesHolder timeSeriesHolder, DataMgr dataMgr, - String tableName, - String[] physicalElementStringArray, - String preferredPhysicalElement ) - { - - this( owner, lid, title, timeSeriesHolder, - System.currentTimeMillis(), System.currentTimeMillis(), - dataMgr, tableName, - physicalElementStringArray, - preferredPhysicalElement, true ); - } - - public ForecastTsSaveDialog(JFrame owner, String lid, String title, - RegularTimeSeriesHolder timeSeriesHolder, - long productTime, long basisTime, - DataMgr dataMgr, String tableName, - String[] physicalElementStringArray, - String preferredPhysicalElement ) - { - this( owner, lid, - title, timeSeriesHolder, - productTime, basisTime, - dataMgr, tableName, - physicalElementStringArray, preferredPhysicalElement, - true ); - } - - public ForecastTsSaveDialog(JFrame owner, String lid, String title, - RegularTimeSeriesHolder timeSeriesHolder, - long productTime, long basisTime, - DataMgr dataMgr, String tableName, - String[] physicalElementStringArray, - String preferredPhysicalElement, - boolean isModal ) - { - super( owner, isModal ); - this.setTitle(title + ": " + lid ); - _timeSeriesHolder = timeSeriesHolder; - _timeSeries = _timeSeriesHolder.getTimeSeries(); - _basisTime = basisTime; - _productTime = productTime; - _lid = lid; - _dataMgr = dataMgr; - _tableName = tableName; - - - long currentTime = System.currentTimeMillis(); - long latestHourTime = TimeHelper.truncateTimeInMillisToNearestHour(currentTime,1); - _basisTimeTextField = new DateTimeTextField(latestHourTime, owner, "Basis Time", 19); - - _productTimeTextField = new DateTimeTextField(latestHourTime, owner, "Product Time", 19); - - - _physicalElementComboBox = new JComboBox(physicalElementStringArray); - _physicalElementComboBox.setSelectedItem(preferredPhysicalElement); - _physicalElement = preferredPhysicalElement; - - _pElementValueLabel.setText( _physicalElement ); - - //set up the spinner control for time - int initialValue = timeSeriesHolder.getTimeSeries().getMeasurementCount(); - int min = 1; - int max = initialValue; - int step = SAVE_HOURS_STEPS; - - SpinnerModel model = new SpinnerNumberModel(initialValue, min, max, step); - _hoursToSaveSpinner = new JSpinner(model); - - // load this token and set the initially selected type/source to this default value - AppsDefaults ad = new AppsDefaults(); - - _sshpForecastTsToken = ad.getToken("sshp_fcst_ts"); - if (_sshpForecastTsToken == null) - { - _sshpForecastTsToken = ad.getToken("SSHP_FCST_TS"); - } - // System.out.println("ForecastTsSaveDialog(): _sshpForecastTsToken = " + _sshpForecastTsToken); - initialize(); - } - - private void initialize() - { - - addDataPanelComponents(); - addButtonPanelComponents(); - addFrameComponents(); - - selectDefaultTypeSource(_sshpForecastTsToken); - - addListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void selectDefaultTypeSource(String typeSource) - { - - // System.out.println("ForecastTsSaveDialog.selectDefaultTypeSource() typeSource=" + typeSource); - if (typeSource == null) - { - //System.out.println("ForecastTsSaveDialog.selectDefaultTypeSource() since typeSource token was null, use value of FZ"); - typeSource = "FZ"; - } - - _typeSourceComboBox.setSelectedItem(typeSource); - - } - - private void addDataPanelComponents() - { - _dataPanel.setLayout( new GridBagLayout() ); - JPanel hSeparator[] = new JPanel[ 7 ]; - - for ( int i = 0; i < hSeparator.length; i++ ) - { - hSeparator[ i ] = new JPanel(); - hSeparator[ i ].setPreferredSize( new Dimension( 5, 15 ) ); - } - - _basisTimeTextField.setText( DbTimeHelper.getDateTimeStringFromLongTime( _basisTime ) ); - _productTimeTextField.setText( DbTimeHelper.getDateTimeStringFromLongTime( _productTime ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataPanel, _physicalElementLabel, 0, 0, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _physicalElementComboBox,3, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 0 ], 0, 1, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _typeSourceLabel, 0, 2, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _typeSourceComboBox, 3, 2, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 1 ], 0, 3, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _shefQualifierLabel, 0, 4, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _shefQualifierComboBox, 3, 4, 2, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 2 ], 0, 5, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _productIDLabel, 0, 6, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _productIDTextField, 3, 6, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 3 ], 0, 7, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _basisTimeLabel, 0, 8, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _basisTimeTextField, 3, 8, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 4 ], 0, 9, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _productTimeLabel, 0, 10, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _productTimeTextField, 3, 10, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 5 ], 0, 11, 4, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _dataPanel, _hoursToSaveLabel, 0, 12, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dataPanel, _hoursToSaveSpinner, 3, 12, 1, 1, GridBagConstraints.BOTH ); - - - ComponentHelper.addPanelComponent( _dataPanel, hSeparator[ 6 ], 0, 13, 4, 1, GridBagConstraints.BOTH ); - - _basisTimeTextField.setEditable( false ); - _productTimeTextField.setEditable( false ); - } - - private void addButtonPanelComponents() - { - _buttonPanel.setLayout( new GridBagLayout() ); - - JPanel horizSeparatorPanel = new JPanel(); - horizSeparatorPanel.setPreferredSize(new Dimension(30, 30)); - _saveButton.setPreferredSize(new Dimension(180, 30)); - _closeButton.setPreferredSize(new Dimension(80, 30)); - - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, horizSeparatorPanel, 1, 0, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 2, 0, 1, 1, GridBagConstraints.BOTH ); - } - - - - private void addFrameComponents() - { - JPanel hLine = new JPanel(); - JPanel hSeparator = new JPanel(); - - _frameContentPane.setLayout( new GridBagLayout() ); - hLine.setPreferredSize( new Dimension( 300, 1 ) ); - hSeparator.setPreferredSize( new Dimension( 300, 10 ) ); - hLine.setBackground( Color.BLACK ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _dataPanel, 0, 0, 4, 13, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, hLine, 0, 13, 4, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _frameContentPane, hSeparator, 0, 14, 4, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 15, 4, 1, GridBagConstraints.BOTH ); - } - - private FcstTsDescriptor getFcstTsDescriptor( String tableName ) - { - FcstTsDescriptor fcstTs = new FcstTsDescriptor( tableName ); - - fcstTs.setLid( _lid ); - fcstTs.setTableName( tableName ); - fcstTs.setPe((String) _physicalElementComboBox.getSelectedItem() ); - fcstTs.setTs( (String ) _typeSourceComboBox.getSelectedItem() ); - - fcstTs.setExtremum( _extremum ); - fcstTs.setShef_qual_code( (String) _shefQualifierComboBox.getSelectedItem() ); - fcstTs.setProduct_id( _productIDTextField.getText().trim() ); - - fcstTs.setProbability( _probability ); - fcstTs.setQuality_code( GOOD_QC ); - fcstTs.setRevision( (short) _revision ); - - if ( (tableName.equalsIgnoreCase("FcstHeight")) || - (tableName.equalsIgnoreCase("FcstDischarge")) - ) - { - fcstTs.setDur((short)0); - } - else // evapotranspiration - { - int dur = (1000 + _timeSeries.getIntervalInHours()); - fcstTs.setDur((short)dur); - } - - fcstTs.setProducttime( _productTimeTextField.getTime() ); - fcstTs.setBasistime( _basisTimeTextField.getTime() ); - - return fcstTs; - } - - private void addListeners() - { - _saveButton.addActionListener( new SaveButtonListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - addWindowListener( windowCloser ); - _closeButton.addActionListener( windowCloser ); - // _basisTimeTextField.addMouseListener( new TimeTextFieldListener() ); - // _productTimeTextField.addMouseListener( new TimeTextFieldListener() ); - addComponentListener( new WindowResizeComponentListener() ); - } - -/* - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if ( ! textField.getText().equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - - DateTimeDialog dateTimeGUI = null; - if ( textField == _basisTimeTextField ) - { - dateTimeGUI = new DateTimeDialog( ForecastTsSaveDialog.this, dateTime, "Basis Time" ); - - } - else - { - dateTimeGUI = new DateTimeDialog( ForecastTsSaveDialog.this, dateTime, "Product Time" ); - } - - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - _basisTime = DbTimeHelper.getLongTimeFromDateTimeString( _basisTimeTextField.getText().trim() ); - _productTime = DbTimeHelper.getLongTimeFromDateTimeString( _productTimeTextField.getText().trim() ); - } - } -*/ - /* - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } -*/ - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean success = false; - - FcstTsDescriptor fcstTs = new FcstTsDescriptor( _tableName ); - - fcstTs = getFcstTsDescriptor( _tableName ); - - Integer hoursToSaveInteger = (Integer) _hoursToSaveSpinner.getValue(); - int hoursToSave = hoursToSaveInteger.intValue(); - - success = _dataMgr.saveFcstTimeSeries( fcstTs, _timeSeries, hoursToSave ); - - if ( success ) - { - DialogHelper.displayMessageDialog( ForecastTsSaveDialog.this, "Insert Successful!" ); - } - else - { - DialogHelper.displayMessageDialog( ForecastTsSaveDialog.this, "Insert Failed!" ); - } - notifyAllApplyActionListeners(); - } - } - - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } - - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private void closeWindow() - { - this.dispose(); - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = ForecastTsSaveDialog.this.getHeight(); - int width = ForecastTsSaveDialog.this.getWidth(); - -// System.err.println( width + "\n" + height ); - if ( width < MIN_WIDTH ) - { - ForecastTsSaveDialog.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - ForecastTsSaveDialog.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - ForecastTsSaveDialog.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - ForecastTsSaveDialog.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - private static RegularTimeSeries getTestTimeSeries() - { - RegularTimeSeries testTimeSeries = null; - - Date date = new Date(); - long currentTime = date.getTime(); - - currentTime = TimeHelper.truncateTimeInMillisToNearestHour( currentTime, 1 ); - long startTime = currentTime - ( 24*HOUR_IN_MILLIS ); - long endTime = startTime + ( 10*HOUR_IN_MILLIS ); - testTimeSeries = new RegularTimeSeries( startTime, endTime, 1, MeasuringUnit.inches ); - for ( int i = 0; i < testTimeSeries.getMeasurementCount(); i++ ) - { - Measurement m = new Measurement( i, MeasuringUnit.inches ); - long time = startTime + (i * HOUR_IN_MILLIS); - testTimeSeries.setMeasurementByTime( m, time ); - } - return testTimeSeries; - } - - - public static void main(String[] args) - { - RegularTimeSeries timeSeries = ForecastTsSaveDialog.getTestTimeSeries(); - DataMgr dataMgr = new DataMgr(); - RegularTimeSeriesHolder holder = new RegularTimeSeriesHolder(); - holder.setTimeSeries( timeSeries ); - - String[] physicalElementStringArray = {"HG", "HP", "HT"}; - - ForecastTsSaveDialog saveForecast = - new ForecastTsSaveDialog( new JFrame(), "BLUO2", - "Save Fcst Time Series Dialog ", - holder, dataMgr, - "FcstHeight", physicalElementStringArray, "HG" ); - saveForecast.setVisible(true); - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/LiveSacStateEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/LiveSacStateEditor.java deleted file mode 100644 index 9565dad53e..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/LiveSacStateEditor.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * Created on Nov 12, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; - -import javax.swing.JPanel; - -import javax.swing.border.Border; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.gui.LabeledSlider; -import ohd.hseb.util.gui.WindowResizingManager; - - -/** - * @author Chip Gobs - * - * - */ -public class LiveSacStateEditor extends JDialog -{ - - private SacSmaState _state = null; - private SacSmaParameters _params = null; - - - // window sizing data - private Dimension _maxDimension = new Dimension(700, 300); - private Dimension _initialDimension = new Dimension(700, 300); - private Dimension _minDimension = new Dimension(300, 300); - - - private JPanel _mainPanel = null; - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - private JButton _closeButton = null; - - private LabeledSlider _uztwcLabeledSlider = null; - private LabeledSlider _uzfwcLabeledSlider = null; - - private LabeledSlider _lztwcLabeledSlider = null; - private LabeledSlider _lzfscLabeledSlider = null; - private LabeledSlider _lzfpcLabeledSlider = null; - - private LabeledSlider _adimcLabeledSlider = null; // 0.0 <= ADIMC <= UZTWM + LZTWM - - - private ActionListener _updateActionListener = null; - - // ----------------------------------------------------------------------------------- - public LiveSacStateEditor(Frame owner, - SacSmaState state, - SacSmaParameters params, - boolean isModal, - ActionListener listener) - { - super( owner, isModal ); - - _state = state; - _params = params; - - _updateActionListener = listener; - - initGui(); - - } - - // ----------------------------------------------------------------------------------- - public SacSmaState getCurrentSacSmaState() - { - return _state; - } - - // ----------------------------------------------------------------------------------- - - private void initGui() - { - - setTitle("LiveSacStateEditor Dialog"); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.insets = new Insets(2, 2, 2, 2); - gbc.weightx = 1; - gbc.weighty = 1; - - JPanel verticalSeparatorPanel = new JPanel(); - verticalSeparatorPanel.setPreferredSize(new Dimension(30, 30)); - - JPanel horizontalSeparatorPanel = new JPanel(); - horizontalSeparatorPanel.setPreferredSize(new Dimension(30, 30)); - - - JPanel horizontalSeparatorPanel2 = new JPanel(); - horizontalSeparatorPanel2.setPreferredSize(new Dimension(30, 30)); - - JPanel horizontalSeparatorPanel3 = new JPanel(); - horizontalSeparatorPanel3.setPreferredSize(new Dimension(30, 30)); - - - _mainPanel = new JPanel(); - JPanel panel = _mainPanel; - - _closeButton = new JButton("Close"); - _closeButton.setPreferredSize(new Dimension(50, 30)); - - _mainPanel.setLayout( new GridBagLayout() ); - - initSliders(); - - - //arrange the layout - - // X, Y, #Col, #Row - - addComponent(panel, _uztwcLabeledSlider, gbc, 0, 0, 3, 1, 1, 0); - addComponent(panel, _uzfwcLabeledSlider, gbc, 0, 1, 3, 1, 1, 0); - addComponent(panel, _lztwcLabeledSlider, gbc, 0, 2, 3, 1, 1, 0); - addComponent(panel, _lzfscLabeledSlider, gbc, 0, 3, 3, 1, 1, 0); - addComponent(panel, _lzfpcLabeledSlider, gbc, 0, 4, 3, 1, 1, 0); - addComponent(panel, _adimcLabeledSlider, gbc, 0, 5, 3, 1, 1, 0); - - addComponent(panel, horizontalSeparatorPanel,gbc, 1, 6, 1, 1, 1, 0); - - - addComponent(panel, horizontalSeparatorPanel2, gbc, 0, 7, 1, 1, 1, 0); - - addComponent(panel, _closeButton, gbc, 1, 7, 1, 1, 0, 0); - addComponent(panel, horizontalSeparatorPanel3, gbc, 2, 7, 1, 1, 1, 0); - - - - //set up initial bounds limitations - //see WindowResize listener for the minimum setting - - Rectangle maxBoundsRectangle = new Rectangle(_maxDimension); - // this.setMaximizedBounds(maxBoundsRectangle); - - //hook up the mainPanel to the contentPane - - this.getContentPane().add(_mainPanel); - this.pack(); - - Rectangle initialBoundsRectangle = new Rectangle(_initialDimension); - this.setBounds(initialBoundsRectangle); - - - - addListeners(); - } - // ----------------------------------------------------------------------------------- - private void setSacSlidersFromModel() - { - - SacSmaState state = _state; - - _uztwcLabeledSlider.setModelValue(state.getUztwc()); - _uzfwcLabeledSlider.setModelValue(state.getUzfwc()); - - _lztwcLabeledSlider.setModelValue( state.getLztwc()); - _lzfscLabeledSlider.setModelValue( state.getLzfsc()); - _lzfpcLabeledSlider.setModelValue( state.getLzfpc()); - - _adimcLabeledSlider.setModelValue( state.getAdimc()); - - - } - - // ----------------------------------------------------------------------------------- - - private void initSliders() - { - - int width = 150; - int height = 40; - - //UZTWC adjustment controls - // note: the slide values go from 0 to 100 and are mapped to - // a double - - SacSmaState state = getCurrentSacSmaState(); - SacSmaParameters params = _params; - - - _uztwcLabeledSlider = new LabeledSlider("UZTWC:", - state.getUztwc(), - 0.0, - params.getUztwm(), - width, - height ); - - - _uzfwcLabeledSlider = new LabeledSlider("UZFWC:", - state.getUzfwc(), - 0.0, - params.getUzfwm(), - width, - height ); - - - _lztwcLabeledSlider = new LabeledSlider("LZTWC:", - state.getLztwc(), - 0.0, - params.getLztwm(), - width, - height ); - - _lzfscLabeledSlider = new LabeledSlider("LZFSC:", - state.getLzfsc(), - 0.0, - params.getLzfsm(), - width, - height ); - - _lzfpcLabeledSlider = new LabeledSlider("LZFPC:", - state.getLzfpc(), - 0.0, - params.getLzfpm(), - width, - height ); - - - _adimcLabeledSlider = new LabeledSlider("ADIMC:", - state.getAdimc(), - 0.0, - params.getUztwm() + params.getLztwm(), - width, - height ); - - - } - - // ----------------------------------------------------------------------------------- - - private void addListeners() - { - WindowCloseListener windowCloser = new WindowCloseListener(); - _closeButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - - // this adds its own listener internally - WindowResizingManager resizingMgr = - new WindowResizingManager(LiveSacStateEditor.this, - _minDimension, - _maxDimension); - - - //slider listeners - - _uztwcLabeledSlider.addChangeListener(new ValueChangeListener("UZTWC")); - _uzfwcLabeledSlider.addChangeListener(new ValueChangeListener("UZFWC")); - - _lztwcLabeledSlider.addChangeListener(new ValueChangeListener("LZTWC")); - _lzfscLabeledSlider.addChangeListener(new ValueChangeListener("LZFSC")); - _lzfpcLabeledSlider.addChangeListener(new ValueChangeListener("LZFPC")); - - _adimcLabeledSlider.addChangeListener(new ValueChangeListener("ADIMC")); - - - return; - - } - - // ----------------------------------------------------------------------------------- - - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - // ------------------------------------------------------------ - - private void closeWindow() - { - this.dispose(); - } - // ------------------------------------------------------------ - - private void notifyListeners(String eventMessage) - { - ActionEvent event = new ActionEvent(LiveSacStateEditor.this, 0, eventMessage); - _updateActionListener.actionPerformed(event); - } - // ------------------------------------------------------------ - - - // Inner classes---------------------------------------------------------------------- - // - private class WindowCloseListener extends WindowAdapter implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - closeWindow(); - } - - public void windowClosing(WindowEvent evt) - { - closeWindow(); - } - - } - - // ----------------------------------------------------------------------------------- - private class ValueChangeListener implements ChangeListener - { - private String _valueName = null; - - public ValueChangeListener(String valueName) - { - _valueName = valueName; - } - - public void stateChanged(ChangeEvent e) - { - - - _state.setUztwc(_uztwcLabeledSlider.getModelValue()); - _state.setUzfwc(_uzfwcLabeledSlider.getModelValue()); - - _state.setLztwc(_lztwcLabeledSlider.getModelValue()); - _state.setLzfsc(_lzfscLabeledSlider.getModelValue()); - _state.setLzfpc(_lzfpcLabeledSlider.getModelValue()); - - _state.setAdimc(_adimcLabeledSlider.getModelValue()); - - - setSacSlidersFromModel(); - - notifyListeners(_valueName + " changed"); - } - } - - - - // ----------------------------------------------------------------------------------- - - - - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/MonthlyValueEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/MonthlyValueEditor.java deleted file mode 100644 index 2c46762707..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/MonthlyValueEditor.java +++ /dev/null @@ -1,708 +0,0 @@ -/* - * Created on Jan 22, 2004 - * - * Filename : MonthlyValueEditor.java - * Author : Gautam Sood - * Last Revision Date : Jan 22, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableHelper; -import ohd.hseb.db.DbTimeHelper; -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; -import javax.swing.event.*; -import java.util.List; -import java.util.*; - -public class MonthlyValueEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _monthlyValueListPanel = new JPanel(); - private JPanel _monthlyValueTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private DataMgr _dataMgr = null; - private MonthlyValues _monthlyValues = null; - - private List _monthlyValuesList = null; - - private static final int DEFAULT_WIDTH = 450; - private static final int DEFAULT_HEIGHT = 654; - - private static final int MAX_WIDTH = 500; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 430; - private static final int MIN_HEIGHT = 500; - - private static final int NUMBER_OF_MONTHS = 12; - - private String _pe = "EA"; - - private String[] _durStringArray = { "1 hour", "3 hours", "6 hours", "12 hours", "1 day" }; - private int[] _durDbValueIntArray = { 1001, 1003, 1006, 1012, 2001 }; - private Map _durationMap = new HashMap(); - - private String _basinId = null; - - private JFrame _owner = null; - - private JLabel _basinIdLabel = getJLabel( "Basin ID" ); - private JLabel _peLabel = getJLabel( "PE" ); - private JLabel _durLabel = getJLabel( "Duration" ); - private JLabel _tsLabel = getJLabel( "TS" ); - private JLabel _extremumLabel = getJLabel( "Extremum" ); - private JLabel _postingTimeLabel = getJLabel( "Posting Time" ); - private JLabel _adjustmentLabel = getJLabel( "Adjustment?" ); - private JLabel _janLabel = getJLabel( "January" ); - private JLabel _febLabel = getJLabel( "February" ); - private JLabel _marLabel = getJLabel( "March" ); - private JLabel _aprLabel = getJLabel( "April" ); - private JLabel _mayLabel = getJLabel( "May" ); - private JLabel _junLabel = getJLabel( "June" ); - private JLabel _julLabel = getJLabel( "July" ); - private JLabel _augLabel = getJLabel( "August" ); - private JLabel _sepLabel = getJLabel( "September" ); - private JLabel _octLabel = getJLabel( "October" ); - private JLabel _novLabel = getJLabel( "November" ); - private JLabel _decLabel = getJLabel( "December" ); - - private static final int TEXTFIELD_LENGTH = 17; - private JTextField _basinIdTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _peTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _tsTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _extremumTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _postingTimeTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _janTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _febTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _marTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _aprTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _mayTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _junTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _julTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _augTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _sepTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _octTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _novTextField = getJTextField( TEXTFIELD_LENGTH ); - private JTextField _decTextField = getJTextField( TEXTFIELD_LENGTH ); - - private JCheckBox _adjustmentCheckBox = new JCheckBox(); - - private JComboBox _durComboBox = new JComboBox( _durStringArray ); - - private JScrollPane _dataScrollPane = new JScrollPane( _monthlyValueTextPanel ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for the Table - private String[] _columnNames = { "Basin ID", "PE", "DUR", "TS", "Extremum", "Adjustment" }; - private String[] _dbColumnNames = { "lid", "pe", "dur", "ts", "extremum", "adjustment" }; - private String[][] _monthlyValuesStringArray = null; - private JTable _monthlyValuesTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel =null; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - - private MonthlyValueEditor( JFrame owner, DataMgr dataMgr ) - { - this( owner, dataMgr, "", "EA", true ); - } - - private MonthlyValueEditor( JFrame owner, DataMgr dataMgr, String basinId ) - { - this( owner, dataMgr, basinId, "EA", true ); - } - - public MonthlyValueEditor( JFrame owner, DataMgr dataMgr, String basinId, String pe, boolean isModal ) - { - super( owner, isModal ); - this.setTitle( "Monthly Value Editor" ); - - _owner = owner; - _basinId = basinId; - _dataMgr = dataMgr; - _pe = pe; - initialize(); - } - - private void initialize() - { - - long currentTime = System.currentTimeMillis(); - - setupDurationHashMap(); - setupTable(); - - AddMonthlyValueListPanelComponents(); - AddMonthlyValueDataPanelComponents(); - AddButtons(); - AddFrameComponents(); - AddListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - { - int index = -1; - boolean foundBasinId= false; - - _tableHelper.setOrderByClause( 0 ); - - String whereString = " WHERE pe='" + _pe + "' "; - - whereString += _tableHelper.getOrderByClause(); - _monthlyValuesList = _dataMgr.loadMonthlyValuesList( whereString ); - - _monthlyValuesStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _monthlyValuesStringArray ); - _monthlyValuesTable = new JTable( _tableModel ); - _monthlyValuesTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _monthlyValuesTable.setPreferredScrollableViewportSize( new Dimension( 380, 100 ) ); - _listSelectionModel = _monthlyValuesTable.getSelectionModel(); - _scrollPane = new JScrollPane( _monthlyValuesTable ); - if ( _basinId != null ) - { - for ( int i = 0; i < _monthlyValuesList.size(); i++ ) - { - MonthlyValues monthlyValues = (MonthlyValues) _monthlyValuesList.get( i ); - - if ( _basinId.equalsIgnoreCase( monthlyValues.getBasinId().trim() ) ) - { - index = i; - foundBasinId = true; - _monthlyValues = monthlyValues; - break; - } - } - } - - if ( ! foundBasinId ) // If no basin ID found in the Params list, selects the first one by default. - { - if (_monthlyValuesList.size() > 0) - { - _monthlyValues = (MonthlyValues) _monthlyValuesList.get( 0 ); - } - } - - - if ( foundBasinId ) // Checks if a Basin Id was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _monthlyValuesTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void setupDurationHashMap() - { - for ( int i = 0; i < _durStringArray.length; i++ ) - { - Integer key = new Integer( _durDbValueIntArray[ i ] ); - String value = _durStringArray[ i ] ; - _durationMap.put( key, value ); - } - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _monthlyValuesList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - Integer durationInteger = null; - - MonthlyValues monthlyValues = (MonthlyValues) _monthlyValuesList.get( i ); - - int duration = monthlyValues.getDur(); - durationInteger = new Integer( duration ); - String durationString = (String) _durationMap.get( durationInteger ); - - dataArray[ i ][ 0 ] = monthlyValues.getBasinId(); - dataArray[ i ][ 1 ] = monthlyValues.getPe(); - dataArray[ i ][ 2 ] = durationString; - dataArray[ i ][ 3 ] = monthlyValues.getTs(); - dataArray[ i ][ 4 ] = monthlyValues.getExtremum(); - dataArray[ i ][ 5 ] = "" + monthlyValues.isAdjustment(); - } - return dataArray; - } - - private void refreshMonthlyValuesTable() - { - int index = 0; - - String whereString = " WHERE pe='" + _pe + "' "; - - whereString += _tableHelper.getOrderByClause(); - - _monthlyValuesList = _dataMgr.loadMonthlyValuesList( whereString ); - - _monthlyValuesStringArray = convertListToArray(); - if ( _monthlyValues != null ) - { - for ( int i = 0; i < _monthlyValuesList.size(); i++ ) - { - MonthlyValues monthlyValues = (MonthlyValues) _monthlyValuesList.get( i ); - - if ( _monthlyValues.equals( monthlyValues ) ) - { - index = i; - break; - } - } - } - _tableModel.updateData( _monthlyValuesStringArray ); - _tableModel.fireTableChanged( null ); - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _monthlyValuesTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void AddMonthlyValueListPanelComponents() - /******************** - Purpose: Add's Components to the JTable Scroll Pane Panel - *********************/ - { - _monthlyValueListPanel.setLayout( new GridBagLayout() ); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _monthlyValueListPanel, _scrollPane, 0, 0, 5, 25, 0, 1, GridBagConstraints.BOTH ); - } - - private void AddMonthlyValueDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the _monthlyValueTextPanel - *********************/ - { - _monthlyValueTextPanel.setLayout( new GridBagLayout() ); - - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _basinIdLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _basinIdTextField, 10, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _peLabel, 0, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _peTextField, 10, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _durLabel, 0, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _durComboBox, 10, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _tsLabel, 0, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _tsTextField, 10, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _extremumLabel, 0, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _extremumTextField, 10, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _postingTimeLabel, 0, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _postingTimeTextField, 10, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _adjustmentLabel, 0, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _adjustmentCheckBox, 10, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _janLabel, 0, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _janTextField, 10, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _febLabel, 0, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _febTextField, 10, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _marLabel, 0, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _marTextField, 10, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _aprLabel, 0, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _aprTextField, 10, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _mayLabel, 0, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _mayTextField, 10, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _junLabel, 0, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _junTextField, 10, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _julLabel, 0, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _julTextField, 10, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _augLabel, 0, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _augTextField, 10, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _sepLabel, 0, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _sepTextField, 10, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _octLabel, 0, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _octTextField, 10, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _novLabel, 0, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _novTextField, 10, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _decLabel, 0, 180, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _monthlyValueTextPanel, _decTextField, 10, 180, 5, 1, GridBagConstraints.BOTH ); - - _postingTimeTextField.setEditable( false ); - _peTextField.setEditable( false ); - } - - private void AddButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _buttonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 3, 22, 2, GridBagConstraints.BOTH ); - } - - private void AddFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - _dataScrollPane.setPreferredSize( new Dimension( 150, 300 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _monthlyValueListPanel, 0, 0, 10, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 17, 20, 15, 0, .5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - - if ( _monthlyValues != null ) - { - double[] valueArray = _monthlyValues.getValueArray(); - - int duration = 0; - - _basinIdTextField.setText( _monthlyValues.getBasinId() ); - _postingTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _monthlyValues.getPostingTime() ) ); - _peTextField.setText( _monthlyValues.getPe() ); - - duration = _monthlyValues.getDur(); // Returns either 1001, 1003, 1006, or 1012 - - _durComboBox.setSelectedIndex( getDurationValueIndex( duration ) ); - - _tsTextField.setText( _monthlyValues.getTs() ); - _extremumTextField.setText( _monthlyValues.getExtremum() ); - _adjustmentCheckBox.setSelected( _monthlyValues.isAdjustment() ); - _janTextField.setText( Double.toString( valueArray[ 0 ] ) ); - _febTextField.setText( Double.toString( valueArray[ 1 ] ) ); - _marTextField.setText( Double.toString( valueArray[ 2 ] ) ); - _aprTextField.setText( Double.toString( valueArray[ 3 ] ) ); - _mayTextField.setText( Double.toString( valueArray[ 4 ] ) ); - _junTextField.setText( Double.toString( valueArray[ 5 ] ) ); - _julTextField.setText( Double.toString( valueArray[ 6 ] ) ); - _augTextField.setText( Double.toString( valueArray[ 7 ] ) ); - _sepTextField.setText( Double.toString( valueArray[ 8 ] ) ); - _octTextField.setText( Double.toString( valueArray[ 9 ] ) ); - _novTextField.setText( Double.toString( valueArray[ 10 ] ) ); - _decTextField.setText( Double.toString( valueArray[ 11 ] ) ); - } - else - { - _basinIdTextField.setText( "" ); - _postingTimeTextField.setText( "Not Posted Yet" ); - _peTextField.setText( _pe ); - _durComboBox.setSelectedIndex( 0 ); - _tsTextField.setText( "" ); - _extremumTextField.setText( "" ); - _adjustmentCheckBox.setSelected( false ); - _janTextField.setText( "" ); - _febTextField.setText( "" ); - _marTextField.setText( "" ); - _aprTextField.setText( "" ); - _mayTextField.setText( "" ); - _junTextField.setText( "" ); - _julTextField.setText( "" ); - _augTextField.setText( "" ); - _sepTextField.setText( "" ); - _octTextField.setText( "" ); - _novTextField.setText( "" ); - _decTextField.setText( "" ); - } - } - - private void AddListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _monthlyValuesTable.getTableHeader().addMouseListener( new TableSortingListener() ); - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _monthlyValuesTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshMonthlyValuesTable(); - } - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _monthlyValuesTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _monthlyValuesList.isEmpty() ) ) - { - _monthlyValues = (MonthlyValues) _monthlyValuesList.get( index ); - } - else - { - _monthlyValues = null; - } - loadTextFields(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - - MonthlyValues monthlyValues = new MonthlyValues(); - double[] valueArray = new double[ NUMBER_OF_MONTHS ]; - - if ( - ( ! isEmptyString( _basinIdTextField.getText() ) ) && - ( ! isEmptyString( _peTextField.getText() ) ) && - ( ! isEmptyString( _tsTextField.getText() ) ) && - ( ! isEmptyString( _extremumTextField.getText() ) ) - ) // Checks to make sure the basinID and source - // are not empty strings - { - try - { - int index = 0; - - monthlyValues.setBasinId( _basinIdTextField.getText().trim() ); - monthlyValues.setPe( _pe ); - - index = _durComboBox.getSelectedIndex(); - monthlyValues.setDur( (short) _durDbValueIntArray[ index ] ); - - monthlyValues.setTs( _tsTextField.getText().trim() ); - monthlyValues.setExtremum( _extremumTextField.getText().trim() ); - monthlyValues.setAdjustment( _adjustmentCheckBox.isSelected() ); - valueArray[ 0 ] = Double.parseDouble( _janTextField.getText().trim() ); - valueArray[ 1 ] = Double.parseDouble( _febTextField.getText().trim() ); - valueArray[ 2 ] = Double.parseDouble( _marTextField.getText().trim() ); - valueArray[ 3 ] = Double.parseDouble( _aprTextField.getText().trim() ); - valueArray[ 4 ] = Double.parseDouble( _mayTextField.getText().trim() ); - valueArray[ 5 ] = Double.parseDouble( _junTextField.getText().trim() ); - valueArray[ 6 ] = Double.parseDouble( _julTextField.getText().trim() ); - valueArray[ 7 ] = Double.parseDouble( _augTextField.getText().trim() ); - valueArray[ 8 ] = Double.parseDouble( _sepTextField.getText().trim() ); - valueArray[ 9 ] = Double.parseDouble( _octTextField.getText().trim() ); - valueArray[ 10 ] = Double.parseDouble( _novTextField.getText().trim() ); - valueArray[ 11 ] = Double.parseDouble( _decTextField.getText().trim() ); - - monthlyValues.setValues( valueArray ); - - _dataMgr.saveMonthlyValues( monthlyValues ); - _monthlyValues = monthlyValues; - refreshMonthlyValuesTable(); - } - catch ( NumberFormatException exception ) - { - - DialogHelper.displayMessageDialog(null, - "There is a parsing error in your input", - "Error Message" ); - - //JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - else - { - DialogHelper.displayMessageDialog(null, - "Empty Strings are not allowed", - "Error Message" ); - - //JOptionPane.showMessageDialog( null, "Empty Strings are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _monthlyValues = null; - loadTextFields(); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - if ( _monthlyValues != null ) - { - confirm = DialogHelper.displayConfirmDialog(null, "Are you sure you want to delete this Monthly Value?", - "Delete Monthly Value"); - /* - choice = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete this Monthly Value?", - "Delete Monthly Value", JOptionPane.YES_NO_OPTION, - JOptionPane.WARNING_MESSAGE ); - */ - //if ( choice == JOptionPane.YES_OPTION ) - /* User selected YES */ - - if (confirm) - { - _dataMgr.deleteMonthlyValues( _monthlyValues ); - _monthlyValues = null; - refreshMonthlyValuesTable(); - } - } - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = MonthlyValueEditor.this.getHeight(); - int width = MonthlyValueEditor.this.getWidth(); -// System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - MonthlyValueEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - MonthlyValueEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - MonthlyValueEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - MonthlyValueEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private int getDurationValueIndex( int duration ) - { - int index = 0; - - for( int i = 0; i < _durDbValueIntArray.length; i++ ) - { - if ( _durDbValueIntArray [ i ] == duration ) - { - index = i; - } - - } - return index; - } - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - public static void main( String[] args ) - { - String basin_Id = "BLUO2"; - JFrame frame = new JFrame(); - DataMgr dataMgr = new DataMgr(); - - MonthlyValueEditor editor = new MonthlyValueEditor( frame, dataMgr, basin_Id, "EA", true ); - editor.setVisible(true); - } -} \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingCurveDataPointCanvasAdapter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingCurveDataPointCanvasAdapter.java deleted file mode 100644 index 4e09d5e66c..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingCurveDataPointCanvasAdapter.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Created on Jul 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Comparator; -import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasurementPointComparator; -import ohd.hseb.measurement.MeasurementPointSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.DataPointCanvasBackgroundPainter; -import ohd.hseb.util.gui.drawing.DataCurvePainter; -import ohd.hseb.util.gui.drawing.DataPointCanvas; -import ohd.hseb.util.gui.drawing.ScalingHelper; - -/** - * @author GobsC - * - * - */ -public class RatingCurveDataPointCanvasAdapter -{ - private DataPointCanvas _canvas = null; - private DataPointCanvasBackgroundPainter _dataBackgroundPainter = null; - private DataCurvePainter _dataPointCurvePainter = null; - private MeasurementPointSeries _measurementPointSeries = null; - - MeasuringUnit _xUnit = MeasuringUnit.cfs; - MeasuringUnit _yUnit = MeasuringUnit.feet; - -//------------------------------------------------------------------------------------- - - - private class CanvasMouseMotionListener extends MouseMotionAdapter - { - private DataPointCanvas _canvas2 = null; - - public CanvasMouseMotionListener(DataPointCanvas canvas) - { - _canvas2 = canvas; - } - - public void mouseMoved(MouseEvent event) - { - - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas2.getViewport().getDataPoint(screenPoint); - - - if (_canvas2.getViewport().isViewable(dataPoint)) - { - updateCanvasDataPointText(dataPoint, _canvas); - } - } - - } - -// ------------------------------------------------------------------------------------- - - - public void updateCanvasDataPointText(DataPoint dataPoint, - DataPointCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String xUnitString = canvas.getDisplayedXMeasuringUnit().toString(); - String yUnitString = canvas.getDisplayedYMeasuringUnit().toString(); - - String message = getCanvasDataPointString(dataPoint, xUnitString, - yUnitString); - - canvas.setToolTipText(message); - - return; - } - -// ------------------------------------------------------------------------------------- - - private String getCanvasDataPointString(DataPoint dataPoint, - String xUnitString, - String yUnitString) - { - NumberFormat nfX = new DecimalFormat("###"); - - long hour = (long) Math.round(dataPoint.getX()); - String xValueString = nfX.format(hour); - - NumberFormat nfY = new DecimalFormat("###.##"); - String yValueString = nfY.format(dataPoint.getY()); - - String dataPointString = xValueString + " " + xUnitString + " , " - + yValueString + " " + yUnitString; - - return dataPointString; - } -// ------------------------------------------------------------------------------------- - public DataPointCanvas initCanvas() - { - - - // init the drawing variables - boolean compareXValues = true; - boolean ascendingOrder = true; - Comparator comparator = new MeasurementPointComparator(compareXValues, ascendingOrder); // compare X values - - _measurementPointSeries = new MeasurementPointSeries(_xUnit, _yUnit, comparator); - - int x = 0; - int y = 0; - int width = 1000; - int height = 700; - - - // scaling helpers end up affecting the overall viewport window and - // what numbers are displayed for major and minor tick marks by painter - ScalingHelper horizontalScalingHelper = new ScalingHelper(0.0, 0.0); - ScalingHelper verticalScalingHelper = new ScalingHelper(0.0, 0.0); - - /* - double[] niceMinorIncrementArray = {1, 2, 4, 8, 12, 24 }; - horizontalScalingHelper.setNiceMinorIncrementArray(niceMinorIncrementArray); - - double[] niceMajorIncrementArray = {6, 12, 24, 48, 96, 120 }; - horizontalScalingHelper.setNiceMajorIncrementArray(niceMajorIncrementArray); - */ - - _canvas = new DataPointCanvas(_xUnit, _yUnit, - x, y, - width, height, - horizontalScalingHelper, - verticalScalingHelper); - - _canvas.setPreferredSize(new Dimension(width, height)); - _canvas.setMinimumSize(new Dimension(width, height)); - - Color outlineColor = Color.WHITE; - boolean showMinorHorizontalTicks = true; - boolean showMinorVerticalTicks = true; - boolean showMinorVerticalLabels = false; - - // background Painter - _dataBackgroundPainter = - new DataPointCanvasBackgroundPainter(outlineColor, _canvas, - "cfs", "feet", - horizontalScalingHelper, verticalScalingHelper); - - _dataBackgroundPainter.setShowMinorHorizontalTicks(showMinorHorizontalTicks); - _dataBackgroundPainter.setShowMinorVerticalTicks(showMinorVerticalTicks); - _dataBackgroundPainter.setShowMinorVerticalLabels(showMinorVerticalLabels); - - // this painter is not to be used for determining scaling, - //so, this is just considered a plain-old CanvasPainter, - // instead of a DataPointCanvasPainter - _canvas.addCanvasPainter(_dataBackgroundPainter); - - - // data point curve painter - Color curveColor = Color.green; - _dataPointCurvePainter = new DataCurvePainter(_measurementPointSeries, _canvas, curveColor); - - _canvas.addDataPointCanvasPainter(_dataPointCurvePainter); - - _canvas.setTitle("Rating Curve"); - - _canvas.addMouseMotionListener(new CanvasMouseMotionListener(_canvas)); - - return _canvas; - - - - } //end initCanvas - - // ------------------------------------------------------------------------------------- - - public void refreshCanvas(Object dataObject) - { - List ratingPointList = (List) dataObject; - loadCanvasWithData(ratingPointList); - - _canvas.refresh(); - } - -// ------------------------------------------------------------------------------------ - - - private void loadCanvasWithData(List ratingPointList) - { - _measurementPointSeries.clear(); - - for ( int i = 0; i < ratingPointList.size(); i++ ) - { - RatingPoint ratingPoint = (RatingPoint) ratingPointList.get( i ); - - // add Measurement Points to the points for the unitHydrograph - Measurement dischargeMeasurement = new Measurement(ratingPoint.getDischarge(), _xUnit); - Measurement stageMeasurement = new Measurement(ratingPoint.getShiftedStage(), _yUnit); - - MeasurementPoint point = new MeasurementPoint(dischargeMeasurement, stageMeasurement); - - _measurementPointSeries.addPoint(point); - - } - - // System.out.println("loadCanvasWithData says it has " + - // _measurementPointSeries.getPointCount() + " points."); - } - -// ------------------------------------------------------------------------------------ - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingCurveEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingCurveEditor.java deleted file mode 100644 index 471f364339..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingCurveEditor.java +++ /dev/null @@ -1,1073 +0,0 @@ -/* - * Created on Jun 22, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 22, 2004 - * - */ - -/** - * @author SoodG -*/ - -package ohd.hseb.sshp.window; - -import javax.swing.*; -import javax.swing.event.*; - -import java.awt.*; -import java.awt.event.*; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - -import java.text.DecimalFormat; - -import java.util.List; -import java.util.*; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.RatingShift; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.StringParser; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DateTimeDialog; -import ohd.hseb.util.gui.DateTimeEvent; -import ohd.hseb.util.gui.DateTimeEventListener; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; -import ohd.hseb.util.gui.TableHelper2; -import ohd.hseb.util.gui.drawing.DataPointCanvas; - - -//------------------------------------------------------------------------------------ - -public class RatingCurveEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _ratingShiftPanel = new JPanel(); - private JPanel _ratingCurveDataPanel = new JPanel(); - private JPanel _ratingCurveButtonPanel = new JPanel(); - private JPanel _ratingCurveDisplayPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private DataMgr _dataMgr = null; - - private String _locationId = null; - - private RatingShift _ratingShift = null; - private RatingCurve _ratingCurve = null; - private RatingPoint _ratingPoint = null; - - //private double _shiftAmount = 0.0; - - private static final int DEFAULT_WIDTH = 1200; - private static final int DEFAULT_HEIGHT = 900; - - private static final int MAX_WIDTH = 5000; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 1075; - private static final int MIN_HEIGHT = 860; - - private List _ratingShiftList = null; -// private List _ratingPointList = new ArrayList(); - - //used for JFormattedTextFields - private static final String _decimalFormatString = "0.000"; - private DecimalFormat _decimalFormat = new DecimalFormat( _decimalFormatString ); - - //used for the rating shift entries - private JLabel _shiftDateLabel = getJLabel( "Shift Date" ); - private JLabel _shiftValueLabel = getJLabel( "Value" ); - private JLabel _shiftActiveLabel = getJLabel( "Active?" ); - - private JTextField _shiftDateTextField = getJTextField( 15 ); - private JTextField _shiftValueTextField = getJTextField( 15 ); - private JCheckBox _shiftActiveCheckBox = new JCheckBox(); - - private JButton _removeShiftButton = new JButton( "Remove Shift" ); - private JButton _saveShiftButton = new JButton( "Save Shift" ); - - // used for the rating curve entries - private JLabel _stageLabel = getJLabel( "Stage" ); - private JLabel _dischargeLabel = getJLabel( "Discharge" ); - private JLabel _tableHeaderLabel = getJLabel( "Active Rating Curve" ); - private JLabel _dateOfRatingLabel = null; - private JLabel _USGSRatingNumberLabel = null; - - private JTextField _stageTextField = getJTextField( 11 ); - private JTextField _dischargeTextField = getJTextField( 11 ); - - private JButton _importCurveButton = new JButton( "Import Curve" ); - private JButton _exportCurveButton = new JButton( "Export Curve" ); - private JButton _clearAllCurveButton = new JButton( "Clear All" ); - private JButton _removePointButton = new JButton( "Remove Point" ); - private JButton _updateInsertPointButton = new JButton( "Update/Insert" ); - private JButton _saveRatingCurveButton = new JButton( "Save Rating" ); - - // used for the buttonPanel - private JButton _closeButton = new JButton( "Close" ); - - //used for the ratingShift JTable - public static final String SHIFT_DATE = "Shift Date"; - public static final String VALUE = "Value"; - public static final String ACTIVE = "Active?"; - private String[] _shiftColumnNames = { SHIFT_DATE, VALUE, ACTIVE }; - - private String[][] _ratingShiftStringArray = null; - private JTable _ratingShiftJTable = null; - private JScrollPane _shiftScrollPane = null; - private SshpTableModel _shiftTableModel = null; - private ListSelectionModel _shiftListSelectionModel = null; - private RatingShiftComparator _shiftComparator = new RatingShiftComparator(); - private TableHelper2 _shiftTableHelper = new TableHelper2( _shiftComparator, _shiftColumnNames ); - - //used for the ratingCurve JTable - public static final String STAGE = "Stage"; - public static final String STAGE_WITH_SHIFT = "Stage w/ Shift"; - public static final String DISCHARGE = "Discharge"; - private String[] _ratingCurveColumnNames = { STAGE, STAGE_WITH_SHIFT, DISCHARGE }; - - private String[][] _ratingCurveStringArray = null; - private JTable _ratingCurveJTable = null; - private JScrollPane _curveScrollPane = null; - private SshpTableModel _curveTableModel = null; - private ListSelectionModel _curveListSelectionModel = null; -// private RatingPointComparator _pointComparator = new RatingPointComparator(); -// private TableHelper2 _curveTableHelper = new TableHelper2( _pointComparator, _ratingCurveColumnNames ); - - // ---------------------------------------------------------------------------------------------- - //drawing variables - - RatingCurveDataPointCanvasAdapter _canvasMgr = null; - DataPointCanvas _canvas = null; - // ---------------------------------------------------------------------------------------------- - - - public RatingCurveEditor( Frame owner, DataMgr dataMgr, String locationId, boolean isModal ) - { - super( owner, isModal ); - _locationId = locationId; - this.setTitle( "Rating Curve - " + _locationId ); - _dataMgr = dataMgr; - initialize(); - } -// ------------------------------------------------------------------------------------ - - private void initialize() - { - - // initialize the drawing area (canvas) - _canvasMgr = new RatingCurveDataPointCanvasAdapter(); - _canvas = _canvasMgr.initCanvas(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - - setupRatingShiftTable(); - setupRatingCurveTable(); - - addRatingShiftPanelComponents(); - addRatingCurvePanelComponents(); - addRatingCurveButtonPanelComponents(); - addButtonPanelComponents(); - addFrameComponents(); - - - - - addListeners(); - - // setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - - } -// ------------------------------------------------------------------------------------ - - - - private void addRatingShiftPanelComponents() - { - _ratingShiftPanel.setLayout( new GridBagLayout() ); - - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - JPanel horizontalSeparatorPanel3 = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - - horizontalSeparatorPanel3.setPreferredSize( new Dimension( 35, 40 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftScrollPane, 0, 0, 3, 5, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, horizontalSeparatorPanel, 0, 5, 3, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftDateLabel, 0, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftValueLabel, 1, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftActiveLabel, 2, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftDateTextField, 0, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftValueTextField, 1, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _shiftActiveCheckBox, 2, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, verticalSeparatorPanel, 3, 0, 1, 8, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, horizontalSeparatorPanel3, 4, 0, 2, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _removeShiftButton, 4, 1, 2, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, horizontalSeparatorPanel2, 4, 2, 2, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingShiftPanel, _saveShiftButton, 4, 3, 2, 1, GridBagConstraints.BOTH ); - - java.awt.Color background = _shiftDateTextField.getBackground(); //store the editable color - _shiftDateTextField.setEditable( false ); - _shiftDateTextField.setBackground(background); //make it appear editable - } -// ------------------------------------------------------------------------------------ - - private void addButtonPanelComponents() - { - _buttonPanel.setLayout( new GridBagLayout() ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 0, 0, 1, 1, GridBagConstraints.BOTH ); - - - } -// ------------------------------------------------------------------------------------ - - private void addRatingCurvePanelComponents() - { - JPanel horizontalSeparatorPanel = new JPanel(); - _ratingCurveDataPanel.setLayout( new GridBagLayout() ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _tableHeaderLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _dateOfRatingLabel, 0, 1, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _USGSRatingNumberLabel, 0, 2, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _curveScrollPane, 0, 3, 5, 10, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, horizontalSeparatorPanel, 0, 13, 5, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _importCurveButton, 0, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _exportCurveButton, 1, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _saveRatingCurveButton, 2, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _clearAllCurveButton, 3, 15, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveDataPanel, _removePointButton, 4, 15, 1, 1, GridBagConstraints.NONE ); - - if ( _ratingCurve.getRatingPointCount() > 0 ) - { - _importCurveButton.setEnabled( false ); - } - - } -// ------------------------------------------------------------------------------------ - - private void addRatingCurveButtonPanelComponents() - { - _ratingCurveButtonPanel.setLayout( new GridBagLayout() ); - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _updateInsertPointButton, 0, 1, 1, 1, GridBagConstraints.NONE ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, verticalSeparatorPanel, 1, 0, 1, 6, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _stageLabel, 2, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _dischargeLabel, 3, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _stageTextField, 2, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, _dischargeTextField, 3, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _ratingCurveButtonPanel, horizontalSeparatorPanel, 0, 2, 4, 4, 1, 1, GridBagConstraints.BOTH ); - } - -// ------------------------------------------------------------------------------------ - - - private void addFrameComponents() - { - _frameContentPane.setLayout( new GridBagLayout() ); - - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - JPanel horizontalSeparatorPanel3 = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - -/* - verticalSeparatorPanel.setBackground( Color.YELLOW ); - horizontalSeparatorPanel.setBackground( Color.YELLOW ); - horizontalSeparatorPanel2.setBackground( Color.YELLOW ); - horizontalSeparatorPanel3.setBackground( Color.YELLOW ); -*/ - _canvas.setPreferredSize( new Dimension( 300, 500 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _canvas, 0, 0, 10, 8, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, verticalSeparatorPanel, 10, 0, 2, 22, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 8, 10, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _ratingShiftPanel, 0, 17, 8, 5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _ratingCurveDataPanel, 12, 0, 9, 17, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel3, 12, 17, 9, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _ratingCurveButtonPanel, 12, 19, 9, 5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 24, 21, 3, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 27, 21, 1, GridBagConstraints.BOTH ); - - } -// ------------------------------------------------------------------------------------ - - private void setupRatingShiftTable() - { - int index = 0; - - _ratingShiftList = _dataMgr.getRatingShift( _locationId ); - if (_ratingShiftList == null) - { - _ratingShiftList = new ArrayList(); - } - - _ratingShiftStringArray = convertShiftListToArray(); - - if (_ratingShiftList != null && _ratingShiftList.size() != 0 ) - { - _ratingShift = (RatingShift) _ratingShiftList.get( 0 ); - } - - _shiftTableModel = new SshpTableModel( _shiftColumnNames, _ratingShiftStringArray ); - _ratingShiftJTable = new JTable( _shiftTableModel ); - _ratingShiftJTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _ratingShiftJTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - _shiftListSelectionModel = _ratingShiftJTable.getSelectionModel(); - _shiftScrollPane = new JScrollPane( _ratingShiftJTable ); - - _shiftListSelectionModel.setSelectionInterval( 0, 0 ); - - Rectangle rect = _ratingShiftJTable.getCellRect( index, 0, true ); - _shiftScrollPane.getViewport().setViewPosition( rect.getLocation() ); - - loadShiftTextFields(); - } -// ------------------------------------------------------------------------------------ - - private String[][] convertShiftListToArray() - { - int ratingShiftListSize = 0; - if (_ratingShiftList != null) - { - ratingShiftListSize = _ratingShiftList.size(); - } - - String[][] dataArray = new String[ ratingShiftListSize ][ _shiftColumnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - RatingShift entry = (RatingShift) _ratingShiftList.get( i ); - - dataArray[ i ][ 0 ] = DbTimeHelper.getDateStringFromLongTime( entry.getDate() ); - dataArray[ i ][ 1 ] = "" + entry.getShiftAmount(); - dataArray[ i ][ 2 ] = "" + entry.isActive(); - } - return dataArray; - } -// ------------------------------------------------------------------------------------ - - private void refreshShiftListJTable() - { - int index = 0; - - _ratingShiftStringArray = convertShiftListToArray(); - - if ( _ratingShift != null ) - { - if ( _ratingShiftList.size() != 0 ) - { - for ( int i = 0; i < _ratingShiftList.size(); i++ ) - { - RatingShift shift = (RatingShift) _ratingShiftList.get( i ); - - if ( shift.equals( _ratingShift ) ) - { - index = i; - break; - } - } - } - } - - _shiftTableModel.updateData( _ratingShiftStringArray ); - _shiftTableModel.fireTableChanged( null ); - - _shiftListSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _ratingShiftJTable.getCellRect(index, 0, true); - _shiftScrollPane.getViewport().setViewPosition(rect.getLocation()); - loadShiftTextFields(); - } -// ------------------------------------------------------------------------------------ - - private void setupRatingCurveTable() - { - int index = 0; - - _ratingCurve = _dataMgr.loadRatingCurve( _locationId ); - _ratingCurveStringArray = convertCurveListToArray(); - -/* - for ( int i = 0; i < _ratingCurve.getRatingPointCount(); i++ ) - { - _ratingPointList.add( _ratingCurve.getRatingPoint( i ) ); - } -*/ - - if ( _ratingCurve.getRatingPointCount() != 0 ) - { - _ratingPoint = _ratingCurve.getFirstRatingPoint(); - } - - _curveTableModel = new SshpTableModel( _ratingCurveColumnNames, _ratingCurveStringArray ); - _ratingCurveJTable = new JTable( _curveTableModel ); - _ratingCurveJTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _ratingCurveJTable.setPreferredScrollableViewportSize( new Dimension( 300, 400 ) ); - _curveListSelectionModel = _ratingCurveJTable.getSelectionModel(); - _curveScrollPane = new JScrollPane( _ratingCurveJTable ); - - _curveListSelectionModel.setSelectionInterval( 0, 0 ); - - Rectangle rect = _ratingCurveJTable.getCellRect( index, 0, true ); - _curveScrollPane.getViewport().setViewPosition( rect.getLocation() ); - - _dateOfRatingLabel = getJLabel( "Date of Rating: " + DbTimeHelper.getDateStringFromLongTime( _ratingCurve.getRatingDate() ) ); - _USGSRatingNumberLabel = getJLabel ( "USGS Rating No.: " + _ratingCurve.getUsgsRatingNumber() ); - loadCurveTextFields(); - - List ratingPointList = _ratingCurve.getRatingPointList(); - _canvasMgr.refreshCanvas(ratingPointList); - } - -// ------------------------------------------------------------------------------------ - - - private void refreshRatingCurveListJTable(boolean shouldReloadData) - { - int index = 0; - - if (shouldReloadData) - { - _ratingCurve = _dataMgr.loadRatingCurve( _locationId ); - } - _ratingCurveStringArray = convertCurveListToArray(); - - if ( ( _ratingCurve != null ) && ( _ratingPoint != null ) ) - { - if ( _ratingCurve.getRatingPointCount() > 0 ) - { - for ( int i = 0; i < _ratingCurve.getRatingPointCount(); i++ ) - { - RatingPoint point = (RatingPoint) _ratingCurve.getRatingPoint( i ); - - if ( point.equals( _ratingPoint ) ) - { - index = i; - break; - } - } - } - } - - _curveTableModel.updateData( _ratingCurveStringArray ); - _curveTableModel.fireTableChanged( null ); - - _curveListSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _ratingCurveJTable.getCellRect(index, 0, true); - _curveScrollPane.getViewport().setViewPosition(rect.getLocation()); - loadCurveTextFields(); - - _canvasMgr.refreshCanvas(_ratingCurve.getRatingPointList()); - } - -// ------------------------------------------------------------------------------------ - - private String[][] convertCurveListToArray() - { - String[][] dataArray = new String[ _ratingCurve.getRatingPointCount() ][ _ratingCurveColumnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - RatingPoint point = _ratingCurve.getRatingPoint( i ); - - dataArray[ i ][ 0 ] = "" + _decimalFormat.format( point.getUnshiftedStage() ); - dataArray[ i ][ 1 ] = "" + _decimalFormat.format( point.getShiftedStage() ); - dataArray[ i ][ 2 ] = "" + _decimalFormat.format( point.getDischarge() ); - } - return dataArray; - } -// ------------------------------------------------------------------------------------ - - private void loadCurveTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _ratingPoint != null ) - { - _stageTextField.setText( "" + _ratingPoint.getUnshiftedStage() ); - _dischargeTextField.setText( "" + _ratingPoint.getDischarge() ); - } - else - { - _stageTextField.setText( "" ); - _dischargeTextField.setText( "" ); - } - } -// ------------------------------------------------------------------------------------ - - private void loadShiftTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _ratingShift != null ) - { - _shiftDateTextField.setText( DbTimeHelper.getDateStringFromLongTime( _ratingShift.getDate() ) ); - _shiftValueTextField.setText( "" + _ratingShift.getShiftAmount() ); - _shiftActiveCheckBox.setSelected( _ratingShift.isActive() ); - } - else - { - _shiftDateTextField.setText( "" ); - _shiftValueTextField.setText( "" ); - _shiftActiveCheckBox.setSelected( false ); - } - } -// ------------------------------------------------------------------------------------ - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _closeButton.addActionListener( windowCloser ); - _removeShiftButton.addActionListener( new RemoveShiftButtonListener() ); - _saveShiftButton.addActionListener( new SaveShiftButtonListener() ); - _shiftDateTextField.addMouseListener( new TimeTextFieldListener() ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _shiftListSelectionModel.addListSelectionListener( new RatingShiftTableUpdateListener() ); - - _updateInsertPointButton.addActionListener( new UpdateInsertPointButtonListener() ); - _removePointButton.addActionListener( new RemovePointButtonListener() ); - _clearAllCurveButton.addActionListener( new ClearAllCurveButtonListener() ); - _saveRatingCurveButton.addActionListener( new SaveRatingCurveButtonListener() ); - _importCurveButton.addActionListener( new ImportRatingCurveButtonListener() ); - - _shiftListSelectionModel.addListSelectionListener( new RatingShiftTableUpdateListener() ); - _curveListSelectionModel.addListSelectionListener( new RatingCurveTableUpdateListener() ); - _ratingShiftJTable.getTableHeader().addMouseListener( new TableSortingListener( _ratingShiftJTable, true ) ); - _ratingCurveJTable.getTableHeader().addMouseListener( new TableSortingListener( _ratingCurveJTable, false ) ); - - } - -// ------------------------------------------------------------------------------------ - private boolean isNewEntry( RatingShift newShift ) - { - boolean isNew = true; - - if (_ratingShiftList != null) - { - for (int i = 0; i < _ratingShiftList.size(); i++) - { - RatingShift shift = (RatingShift) _ratingShiftList.get(i); - - if (shift.equals(newShift)) - { - isNew = false; - } - } - } - return isNew; - } - -// -------------------------------------------------------------------------------------- - - private void importRatingCurveFromFile( File importFile ) - { - boolean addToDatabase = true; - - try - { - BufferedReader _reader = new BufferedReader( new FileReader( importFile ) ); - String line = _reader.readLine(); - - // if ( ( _ratingCurve.getRatingPointCount() == 0) && ( _ratingPointList.size() == 0 ) ) - if ( ( _ratingCurve.getRatingPointCount() == 0)) - { - while( line != null ) - { - while( line.startsWith( "x" ) ) - { - line = _reader.readLine(); - } - String[] tokenizedLine = StringParser.tokenize( line ); - - RatingPoint point = new RatingPoint(); - - point.setUnshiftedStage( Double.parseDouble( tokenizedLine[ 0 ] ) ); - point.setDischarge( Double.parseDouble( tokenizedLine[ 1 ] ) ); - - _ratingCurve.addRatingPoint( point ); - // _ratingPointList.add( point ); - - line = _reader.readLine(); - } - } - _importCurveButton.setEnabled( false ); - - refreshRatingCurveListJTable(true); - } - catch( FileNotFoundException e ) - { - } - catch( IOException e ) - { - } - catch( ArrayIndexOutOfBoundsException e ) - { - System.out.println( "Invalid file format: " + importFile.getName() ); - } - - } -// -------------------------------------------------------------------------------------- - - private File displayImportFileChooser() - { - JFileChooser _importFileChooser = new JFileChooser( "d:/data/rating_curve" ); - File file = null; - List filterList = new ArrayList(); - - filterList.add( "rating" ); - - _importFileChooser.addChoosableFileFilter( new ExtensionFileFilter( filterList, "Rating Curve Files (RATING)" ) ); - - int returnVal = _importFileChooser.showOpenDialog( this ); - - if (returnVal == JFileChooser.APPROVE_OPTION) - { - file = _importFileChooser.getSelectedFile(); - } - else - { - DialogHelper.displayMessageDialog( RatingCurveEditor.this, "Rating Curve file not imported." ); - } - return file; - } -// -------------------------------------------------------------------------------------- - private void addOrReplacePointInRatingPointList(RatingPoint pointToInsert) - { - - _ratingCurve.addRatingPoint(pointToInsert); - - } - -// -------------------------------------------------------------------------------------- - - private class RemoveShiftButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete the rating shift for " - + _locationId + "?", "Delete Rating Shift"); - - if ( confirm ) - { - _dataMgr.deleteRatingShift( _ratingShift ); - _ratingShiftList.remove( _ratingShift ); - _ratingShift = null; - refreshShiftListJTable(); - refreshRatingCurveListJTable(true); - } - - } - - } -// -------------------------------------------------------------------------------------- - - private class RatingCurveTableUpdateListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent arg0 ) - { - int index = _ratingCurveJTable.getSelectedRow(); - if ( ( index >= 0 ) && ( _ratingCurve.getRatingPointCount() >= 1 ) ) - { - _ratingPoint = _ratingCurve.getRatingPoint( index ); - } - else - { - _ratingPoint = null; - } - loadCurveTextFields(); - } - } -// -------------------------------------------------------------------------------------- - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } -// -------------------------------------------------------------------------------------- - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = RatingCurveEditor.this.getHeight(); - int width = RatingCurveEditor.this.getWidth(); - // System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - RatingCurveEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - RatingCurveEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - RatingCurveEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - RatingCurveEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } -// -------------------------------------------------------------------------------------- - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } -// -------------------------------------------------------------------------------------- - -/* - private boolean isEmptyString( String testingString ) - // - //Purpose: Check's whether the string passed in is an empty string - // - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } -*/ -// -------------------------------------------------------------------------------------- - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( "
    " + label + "
    " ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } -// -------------------------------------------------------------------------------------- - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } -// -------------------------------------------------------------------------------------- - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } -// -------------------------------------------------------------------------------------- - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - - // ------------------------------------------------------------------------------------ - - private class TableSortingListener extends MouseAdapter - { - JTable __table = null; - boolean __isRatingShiftJTable; - - public TableSortingListener( JTable table, boolean ratingShiftJTable ) - { - __table = table; - __isRatingShiftJTable = ratingShiftJTable; - } - - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = __table.getTableHeader().columnAtPoint( point ); - - if ( __isRatingShiftJTable ) - { - _shiftTableHelper.sortList( _ratingShiftList, column, true ); - refreshShiftListJTable(); - } - else - { - - } - } - } -// ------------------------------------------------------------------------------------ - - private class RatingShiftTableUpdateListener implements ListSelectionListener - { - public void valueChanged( ListSelectionEvent arg0 ) - { - int index = _ratingShiftJTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _ratingShiftList.isEmpty() ) ) - { - _ratingShift = (RatingShift) _ratingShiftList.get( index ); - } - else - { - _ratingShift = null; - } - loadShiftTextFields(); - } - } -// ------------------------------------------------------------------------------------ - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - - if ( _shiftDateTextField.getText().trim().equals( "" ) ) - { - dateTime = System.currentTimeMillis(); - } - else - { - dateTime = DbTimeHelper.getLongTimeFromDateString( _shiftDateTextField.getText() ); - } - - JTextField textField = (JTextField) e.getSource(); - - DateTimeDialog dateTimeGUI = new DateTimeDialog( RatingCurveEditor.this, dateTime, "Rating Shift Date" ); - dateTimeGUI.setDateOnly(); - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - } - } -// ------------------------------------------------------------------------------------ - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } -// ------------------------------------------------------------------------------------ - - private class UpdateInsertPointButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - RatingPoint point = new RatingPoint(); - - point.setDischarge( Double.parseDouble( _dischargeTextField.getText() ) ); - point.setUnshiftedStage( Double.parseDouble( _stageTextField.getText() ) ); - point.setShiftAmount( _ratingCurve.getShiftAmount() ); - - - _ratingCurve.addRatingPoint( point ); - - addOrReplacePointInRatingPointList(point); - - if ( _importCurveButton.isEnabled() ) - { - _importCurveButton.setEnabled( false ); - } - refreshRatingCurveListJTable(false); - } - } -// ------------------------------------------------------------------------------------ - - private class RemovePointButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to remove the rating point from the rating curve?", - "Remove Rating Point"); - if ( confirm ) - { - // _ratingPointList.remove( _ratingPoint ); - _ratingCurve.removeRatingPoint( _ratingPoint ); - _ratingPoint = null; - - if ( _ratingCurve.getRatingPointCount() == 0 ) - { - _importCurveButton.setEnabled( true ); - } - else - { - _importCurveButton.setEnabled( false ); - } - refreshRatingCurveListJTable(false); - } - } - } -// ------------------------------------------------------------------------------------ - - private class ClearAllCurveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to remove all of the rating points?", - "Clear Rating Curve"); - - if ( confirm ) - { - int ratingPointCount = _ratingCurve.getRatingPointCount(); - - for ( int i = 0; i < ratingPointCount; i++ ) - { - _ratingCurve.removeRatingPoint( _ratingCurve.getFirstRatingPoint() ); - } - - // _ratingPointList.clear(); - - refreshRatingCurveListJTable(false); - - _importCurveButton.setEnabled( true ); - } - } - } -// ------------------------------------------------------------------------------------ - - private class SaveShiftButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean newEntry = false; - boolean validEntry = true; - - RatingShift newShift = new RatingShift(); - try - { - - newShift.setLid( _locationId ); - newShift.setDate( DbTimeHelper.getLongTimeFromDateString( _shiftDateTextField.getText().trim() ) ); - newShift.setShiftAmount( Double.parseDouble( _shiftValueTextField.getText().trim() ) ); - newShift.setActive( _shiftActiveCheckBox.isSelected() ); - } - catch( NumberFormatException error ) - { - DialogHelper.displayErrorDialog( RatingCurveEditor.this, "Illegal characters in the text fields", "Parsing Error" ); - validEntry = false; - } - - if ( validEntry ) - { - _dataMgr.saveRatingShift( newShift ); - - newEntry = isNewEntry( newShift ); - - if( newEntry ) - { - _ratingShift = newShift; - _ratingShiftList.add( _ratingShift ); - } - else - { - _ratingShiftList.remove( _ratingShift ); - _ratingShiftList.add( newShift ); - } - - _ratingCurve = _dataMgr.loadRatingCurve( _locationId ); - - refreshShiftListJTable(); - refreshRatingCurveListJTable(true); - } - } - } -// ------------------------------------------------------------------------------------ - - private class SaveRatingCurveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _dataMgr.saveRatingCurve( _ratingCurve ); - - DialogHelper.displayMessageDialog( null, - "Successfully saved Rating Curve", - "Save Successful" ); - } - } - -// ------------------------------------------------------------------------------------ - - private class ImportRatingCurveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - File importFile = RatingCurveEditor.this.displayImportFileChooser(); - if ( importFile != null ) - { - RatingCurveEditor.this.importRatingCurveFromFile( importFile ); - } - } - } -// ------------------------------------------------------------------------------------ - - - public static void main( String args[] ) - { - RatingCurveEditor editor = new RatingCurveEditor( new Frame(), new DataMgr(), "BLUO2", true ); - editor.show(); - } -// -------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingPointComparator.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingPointComparator.java deleted file mode 100644 index b79fad798f..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingPointComparator.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Created on Jun 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 14, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.RatingPoint; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author SoodG -*/ -public class RatingPointComparator extends TableColumnComparator -{ - public RatingPointComparator() - { - } - - public int compareUnshiftedStage( RatingPoint entry1, RatingPoint entry2 ) - { - return( numberComparison( entry1.getUnshiftedStage(), entry2.getUnshiftedStage() ) ); - } - - public int compareShiftedStage( RatingPoint entry1, RatingPoint entry2 ) - { - return( numberComparison( entry1.getUnshiftedStage(), entry2.getUnshiftedStage() ) ); - } - - public int compareDischarge( RatingPoint entry1, RatingPoint entry2 ) - { - return( numberComparison( entry1.getDischarge(), entry2.getDischarge() ) ); - } - - public int numberComparison( double value1, double value2 ) - { - int returnValue = 0; - - if ( value1 < value2 ) - { - returnValue = -1; - } - else if ( value1 == value2 ) - { - returnValue = 0; - } - else // value1 > value2 - { - returnValue = 1; - } - - return returnValue; - } - - - public int compare( Object object1, Object object2 ) - { - RatingPoint entry1 = (RatingPoint) object1; - RatingPoint entry2 = (RatingPoint) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( RatingCurveEditor.STAGE ) ) - { - returnValue = compareUnshiftedStage( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.STAGE_WITH_SHIFT) ) - { - returnValue = compareShiftedStage( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.DISCHARGE ) ) - { - returnValue = compareDischarge( entry1, entry2 ); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingShiftComparator.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingShiftComparator.java deleted file mode 100644 index 5dff68620f..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RatingShiftComparator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Created on Jun 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 14, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.RatingShift; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author SoodG -*/ -public class RatingShiftComparator extends TableColumnComparator -{ - public RatingShiftComparator() - { - } - - public int compareShiftDate( RatingShift entry1, RatingShift entry2 ) - { - return( numberComparison( entry1.getDate(), entry2.getDate() ) ); - } - - public int compareValue( RatingShift entry1, RatingShift entry2 ) - { - return( numberComparison( entry1.getShiftAmount(), entry2.getShiftAmount() ) ); - } - - public int compareActive( RatingShift entry1, RatingShift entry2 ) - { - String entry1Active = Boolean.toString( entry1.isActive() ); - String entry2Active = Boolean.toString(entry2.isActive() ); - - int result = entry1Active.compareTo( entry2Active ); - - return result; - } - - public int numberComparison( double value1, double value2 ) - { - int returnValue = 0; - - if ( value1 < value2 ) - { - returnValue = -1; - } - else if ( value1 == value2 ) - { - returnValue = 0; - } - else // value1 > value2 - { - returnValue = 1; - } - - return returnValue; - } - - - public int compare( Object object1, Object object2 ) - { - RatingShift entry1 = (RatingShift) object1; - RatingShift entry2 = (RatingShift) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( RatingCurveEditor.SHIFT_DATE ) ) - { - returnValue = compareShiftDate( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.VALUE ) ) - { - returnValue = compareValue( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( RatingCurveEditor.ACTIVE ) ) - { - returnValue = compareActive( entry1, entry2 ); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditor.java deleted file mode 100644 index f98c391ea8..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditor.java +++ /dev/null @@ -1,820 +0,0 @@ -/* - * Created on Nov 26, 2003 - * - * Filename : RegularTimeSeriesEditor.java - * Author : Gautam Sood - * Last Revision Date : Nov 26, 2003 - * - */ - -package ohd.hseb.sshp.window; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; - -import java.util.*; -import java.util.List; -import javax.swing.*; - -import java.awt.*; -import java.awt.event.*; -import java.text.DecimalFormat; - -public class RegularTimeSeriesEditor extends JDialog -{ - private RegularTimeSeriesHolder _timeSeriesHolder = new RegularTimeSeriesHolder(); - - private TimeSeriesListener _timeSeriesListener = null; - - private List _absTimeMeasurementAndFieldsList = new ArrayList(); - private AbsTimeMeasurementAndFields _absTimeMeasurementAndFields = null; - - //nice initial scrolling members - private AbsTimeMeasurementAndFields _searchAbsTimeMeasurementAndFields = null; - private JPanel _searchMeasurementAndFieldsPanel = null; - - - private boolean _isEditable = true; - private long _startTime = 0; - private long _endTime = 0; - private long _intervalInHours = 0; - private long _intervalInMillis = 0; - private long _searchTime = 0; - private static final long HOUR_IN_MILLIS = 60 * 60 * 1000; - private DecimalFormat _decimalFormat = null; - private static final String _defaultFormatString = "0.00"; - private String _formatString = _defaultFormatString; - private ValueMapper _valueMapper = null; - private String _mappedValueLabelString = null; - private double _missingValue = 0.0; - private boolean _displayMappedValue = false; - private boolean _wasWindowActivated = false; - private double _minValue = 0.0; - private double _maxValue = 0.0; - - private static final int DEFAULT_WIDTH = 550; - private static final int DEFAULT_HEIGHT = 450; - - private static final int MAX_WIDTH = 600; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 450; - private static final int MIN_HEIGHT = 312; - - private Container _frameContentPane = getContentPane(); - private JButton _applyButton = new JButton( "Apply" ); - private JButton _closeButton = new JButton( "Close" ); - private JLabel _timeLabel = new JLabel( "Time (GMT) " ); - private JLabel _valueLabel = null; - private JLabel _mappedValueLabel = null; - private JLabel _missingValueLabel = new JLabel( "
    Missing
    Value?
    " ); - private JPanel _dataPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - private JPanel _labelPanel = new JPanel(); - private JScrollPane _dataScrollPane = new JScrollPane( _dataPanel ); - - //used for custom notification - //private List _applyListenerList = new ArrayList(); - - // ------------------------------------------------------------------------------------------ - - public RegularTimeSeriesEditor( RegularTimeSeriesEditorDescriptor descriptor ) - { - super( descriptor.getOwner(), descriptor.isModal() ); - this.setTitle( descriptor.getTitleLabelString() ); - _valueLabel = new JLabel( descriptor.getValueLabelString() ); - _timeSeriesHolder = descriptor.getRegularTimeSeriesHolder(); - _isEditable = descriptor.isEditable(); - - _valueMapper = descriptor.getValueMapper(); - _mappedValueLabelString = descriptor.getMappedValueLabelString(); - - if ( _valueMapper != null ) - { - _mappedValueLabel = new JLabel( _mappedValueLabelString ); - _displayMappedValue = true; - } - _searchTime = descriptor.getInitialSearchTime(); - - String searchTimeString = DbTimeHelper.getDateTimeStringFromLongTime(_searchTime); - - _formatString = descriptor.getTextFieldFormatString(); - _missingValue = descriptor.getMissingValue(); - _decimalFormat = new DecimalFormat( _formatString ); - _minValue = descriptor.getMinValue(); - _maxValue = descriptor.getMaxValue(); - - initialize(); - } - -// ------------------------------------------------------------------------------------------ - - - private void initialize() - { - _startTime = getTimeSeries().getStartTime(); - _endTime = getTimeSeries().getEndTime(); - _intervalInHours = getTimeSeries().getIntervalInHours(); - _intervalInMillis = _intervalInHours * HOUR_IN_MILLIS; - - addLabelPanelComponents(); - addDataPanelComponents(); - addButtonPanelComponents(); - addFrameComponents(); - addListeners(); - - refreshDataPanel(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - -// ------------------------------------------------------------------------------------------ - - private void initializeScrollAmount() - { - - int fieldHeight = 50; - if (_absTimeMeasurementAndFieldsList.size() > 0) - { - AbsTimeMeasurementAndFields measurementAndFields = - (AbsTimeMeasurementAndFields) _absTimeMeasurementAndFieldsList.get(0); - fieldHeight = measurementAndFields._valueTextField.getHeight(); - } - - // set the amount to scroll when clicking on the slider bar - _dataScrollPane.getVerticalScrollBar().setUnitIncrement( 2* fieldHeight ); - - return; - } -// ------------------------------------------------------------------------------------------ - - private void initializeScrollPosition() - { -// initialize the location of the slider bar - if ( ( _searchTime != 0 ) && ( _searchAbsTimeMeasurementAndFields != null ) ) - { - // rect is set to the dimensions of one of the value Text Fields - // so that we can use the y value - Rectangle rect = _searchAbsTimeMeasurementAndFields._valueTextField.getBounds(); - - _searchAbsTimeMeasurementAndFields._valueTextField.requestFocus( true ); - - Rectangle parentPanelRect = _searchMeasurementAndFieldsPanel.getBounds(); - - // Sets the y value of rectangle to the middle of the visible screen. - - int newY = rect.y + parentPanelRect.y; - if (newY < 0) - { - newY = 0; - } - int newX = rect.x; - - Point viewLocation = new Point (newX, newY); - - // String header = "RegularTimeSeriesEditor.initializeScrollPosition()"; - // System.out.println(header + "trying to set viewPosition to " + viewLocation); - - // System.out.println(header + "before setting, getViewPosition() = " + _dataScrollPane.getViewport().getViewPosition()); - _dataScrollPane.getViewport().setViewPosition(viewLocation); - - - // System.out.println(header + "after setting, getViewPosition() = " + _dataScrollPane.getViewport().getViewPosition()); - } - - } -// ------------------------------------------------------------------------------------------ - - private void initializeScrolling() - { - // Sets the scroll bar increment to 2 text fields per click - initializeScrollAmount(); - - initializeScrollPosition(); - - return; - } -// ------------------------------------------------------------------------------------------ - - private void addFrameComponents() - { - _frameContentPane.setLayout( new GridBagLayout() ); - - JPanel hSeparatorPanel = new JPanel(); - JPanel hSeparatorPanel2 = new JPanel(); - - hSeparatorPanel.setPreferredSize( new Dimension( 300, 5 ) ); - hSeparatorPanel2.setPreferredSize( new Dimension( 300, 20 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _labelPanel, 0, 0, 11, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, hSeparatorPanel, 0, 1, 11, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 3, 11, 20, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, hSeparatorPanel2, 0, 23, 11, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 25, 11, 2, GridBagConstraints.BOTH ); - } -// ------------------------------------------------------------------------------------------ - - private void addLabelPanelComponents() - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - - _labelPanel.setLayout( new GridBagLayout() ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 100, 15 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 65, 15 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 65, 15 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _labelPanel, _timeLabel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, verticalSeparatorPanel, 1, 0, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, _valueLabel, 5, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, verticalSeparatorPanel2, 6, 0, 4, 1, GridBagConstraints.BOTH ); - if ( _mappedValueLabel != null ) - { - ComponentHelper.addFrameComponent( _labelPanel, _mappedValueLabel, 10, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, verticalSeparatorPanel3, 11, 0, 4, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _labelPanel, _missingValueLabel, 15, 0, 1, 1, GridBagConstraints.BOTH ); - } - else - { - ComponentHelper.addFrameComponent( _labelPanel, _missingValueLabel, 10, 0, 1, 1, GridBagConstraints.BOTH ); - } - } -// ------------------------------------------------------------------------------------------ - - private void addDataPanelComponents() - { - //String header = "RegularTimeSeriesEditor.addDataPanelComponents():"; - int counter = 0; - - int yCoor = 1; - int yPanelCounter = 0; - - _dataPanel.setLayout( new GridBagLayout() ); - - JPanel subDataPanel = new JPanel(); - - for ( long time = _startTime; time <= _endTime; time += _intervalInMillis ) - { - if ( ( counter % 400 ) == 0 ) - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 40, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 60, 20 ) ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 20, 25 ) ); - - subDataPanel = new JPanel(); - yCoor = 0; - counter = 0; - subDataPanel.setLayout( new GridBagLayout() ); - ComponentHelper.addPanelComponent( subDataPanel, verticalSeparatorPanel2, 2, 0, 2, 20, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, verticalSeparatorPanel, 6, 0, 1, 20, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, verticalSeparatorPanel3, 8, 0, 1, 20, GridBagConstraints.BOTH ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dataPanel, subDataPanel, 0, yPanelCounter, 1, 1, GridBagConstraints.BOTH ); - yPanelCounter++; - } - - Measurement measurement = getTimeSeries().getMeasurementByTime( time ); - double value = measurement.getValue(); - - _absTimeMeasurementAndFields = new AbsTimeMeasurementAndFields( time, value ); - _absTimeMeasurementAndFieldsList.add( _absTimeMeasurementAndFields ); - - if ( time == _searchTime ) - { - _searchAbsTimeMeasurementAndFields = _absTimeMeasurementAndFields; - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - _searchMeasurementAndFieldsPanel = subDataPanel; - // System.out.println(header + "timeString = " + timeString); - // System.out.println(header + "yPanelCounter = " + yPanelCounter); - } -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._valueDateTimeLabel, 0, yCoor, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._valueTextField, 4, yCoor, 1, 1, GridBagConstraints.BOTH ); - if ( _displayMappedValue ) - { - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._mappedValueTextField, 7, yCoor, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._missingValueCheckBox, 10, yCoor, 1, 1, GridBagConstraints.BOTH ); - } - else - { - ComponentHelper.addPanelComponent( subDataPanel, _absTimeMeasurementAndFields._missingValueCheckBox, 7, yCoor, 1, 1, GridBagConstraints.BOTH ); - } - yCoor++; - counter++; - } - _dataScrollPane.setPreferredSize( new Dimension( 375, 200 ) ); - } -// ------------------------------------------------------------------------------------------ - - private void addButtonPanelComponents() - { - JPanel verticalSeparatorPanel = new JPanel(); - - _buttonPanel.setLayout( new GridBagLayout() ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 80, 20 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _applyButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 2, 0, 3, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _closeButton, 5, 0, 2, 2, GridBagConstraints.BOTH ); - if ( ! _isEditable ) - { - _applyButton.setVisible( false ); - } - } -// ------------------------------------------------------------------------------------------ - - private RegularTimeSeries getTimeSeries() - { - return _timeSeriesHolder.getTimeSeries(); - } -// ------------------------------------------------------------------------------------------ - - private void addListeners() - { - _timeSeriesListener = new UpdateTimeSeriesListener(); - _timeSeriesHolder.addListener(_timeSeriesListener); - - _applyButton.addActionListener( new ApplyButtonListener() ); - - - - - - WindowEventManager windowEventManager = new WindowEventManager(); - _closeButton.addActionListener( windowEventManager ); - addWindowListener( windowEventManager ); - addComponentListener( new WindowResizeComponentListener() ); - } -// ------------------------------------------------------------------------------------------ - - private class ApplyButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - updateTimeSeries(); - refreshDataPanel(); - - //notification occurs in updateTimeSeries( - } - } - -// ------------------------------------------------------------------------------------------ - - private class ValueChangedFocusListener implements FocusListener - { - - public ValueChangedFocusListener () - { - - } - - public void focusGained(FocusEvent event) - { - - } - - public void focusLost(FocusEvent event) - { - updateTimeSeries(); - refreshDataPanel(); - - } //end focusLost - - } -// ------------------------------------------------------------------------------------------ -/* - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } -*/ -// ------------------------------------------------------------------------------------------ -/* - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } -*/ -// ------------------------------------------------------------------------------------------ - - private void updateTimeSeries() - { - int index = 0; - RegularTimeSeries timeSeries = new RegularTimeSeries(getTimeSeries().getStartTime(), - getTimeSeries().getEndTime(), - getTimeSeries().getIntervalInHours(), - getTimeSeries().getMeasuringUnit() ); - boolean success = true; - - for ( long time = _startTime; time <= _endTime ; time += _intervalInMillis ) - { - AbsTimeMeasurementAndFields absTimeMeasurementAndFields = null; - - absTimeMeasurementAndFields = - (AbsTimeMeasurementAndFields) _absTimeMeasurementAndFieldsList.get( index ); - try - { - String textFieldString = absTimeMeasurementAndFields._valueTextField.getText().trim(); - double value = Double.parseDouble( textFieldString ); - Measurement measurement = new Measurement( value , timeSeries.getMeasuringUnit() ); - timeSeries.setMeasurementByTime( measurement, time ); - - } - catch ( NumberFormatException e ) - { - DialogHelper.displayMessageDialog(null, - "Non-numerical values are not allowed!", - "Error Message" ); - success = false; - - //JOptionPane.showMessageDialog( null, "Non-numerical values are not allowed!", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - index++; - } - - if ( success ) - { - _timeSeriesHolder.setTimeSeries( timeSeries ); - - TimeSeriesEvent event = new TimeSeriesEvent("RegularTimeSeriesEditor Update", - RegularTimeSeriesEditor.this); - _timeSeriesHolder.forwardEvent(event); - } - } - - private class WindowEventManager extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - - public void windowActivated( WindowEvent e ) - { - if ( ! _wasWindowActivated ) - { - initializeScrolling(); - repaint(); - _wasWindowActivated = true; - } - } - } -// ------------------------------------------------------------------------------------------ - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = RegularTimeSeriesEditor.this.getHeight(); - int width = RegularTimeSeriesEditor.this.getWidth(); - -// System.err.println( width + "\n" + height ); - if ( width <= MIN_WIDTH ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - width = MIN_WIDTH; - } - if ( width >= MAX_WIDTH ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - width = MAX_WIDTH; - } - if ( height <= MIN_HEIGHT ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - height = MIN_HEIGHT; - } - if ( height >= MAX_HEIGHT ) - { - RegularTimeSeriesEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - height = MAX_HEIGHT; - } - } - } -// ------------------------------------------------------------------------------------------ - - private void closeWindow() - { - //don't want to get messages when this window is gone - _timeSeriesHolder.removeListener(_timeSeriesListener); - - //make it go away - this.dispose(); - } -// ------------------------------------------------------------------------------------------ - - private String getFormattedValue( double value ) - { - return _decimalFormat.format( value ); - } -// ------------------------------------------------------------------------------------------ - - private void refreshDataPanel() - { - // String header = "RegularTimeSeriesEditor.refreshDataPanel():"; - int index = 0; - - _startTime = getTimeSeries().getStartTime(); - _endTime = getTimeSeries().getEndTime(); - - //System.out.println(header + "called." ); - - for ( long time = _startTime; time <= _endTime; time += _intervalInMillis ) - { - Measurement measurement = getTimeSeries().getMeasurementByTime( time ); - double value = measurement.getValue(); - _absTimeMeasurementAndFields = (AbsTimeMeasurementAndFields) _absTimeMeasurementAndFieldsList.get( index ); - _absTimeMeasurementAndFields.refresh( time, value ); - index++; - } - // System.out.println(header + "getViewPosition() = " + _dataScrollPane.getViewport().getViewPosition()); - } -// ------------------------------------------------------------------------------------------ - - private static RegularTimeSeries getTestTimeSeries() - { - RegularTimeSeries testTimeSeries = null; - - Date date = new Date(); - long currentTime = date.getTime(); - - currentTime = TimeHelper.truncateTimeInMillisToNearestHour( currentTime, 1 ); - long startTime = currentTime - ( 24*HOUR_IN_MILLIS ); - long endTime = startTime + ( 100*HOUR_IN_MILLIS ); - testTimeSeries = new RegularTimeSeries( startTime, endTime, 1, MeasuringUnit.inches ); - for ( int i = 0; i < testTimeSeries.getMeasurementCount(); i++ ) - { - long time = startTime + (i * HOUR_IN_MILLIS); - Measurement m = new Measurement( i, MeasuringUnit.inches ); - testTimeSeries.setMeasurementByTime( m, time ); - } - return testTimeSeries; - } -// ------------------------------------------------------------------------------------------ - - private class AbsTimeMeasurementAndFields - { - private JLabel _valueDateTimeLabel = new JLabel(); - private JFormattedTextField _valueTextField = null; - private JFormattedTextField _mappedValueTextField = null; - private JCheckBox _missingValueCheckBox = new JCheckBox(); - private boolean _isMissingValue = false; - private long _time = 0; - - public AbsTimeMeasurementAndFields( long time, double value ) - { - _time = time; - - _valueTextField = new JFormattedTextField( _decimalFormat ); - _mappedValueTextField = new JFormattedTextField( _decimalFormat ); - _valueTextField.setColumns( 8 ); - _mappedValueTextField.setColumns( 8 ); - _mappedValueTextField.setEditable( false ); - _mappedValueTextField.setFocusable( false ); - - if ( _isEditable ) - { - _valueTextField.setEditable( true ); - } - else - { - _valueTextField.setEditable( false ); - _valueTextField.setFocusable( false ); - _missingValueCheckBox.setEnabled( false ); - } - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( time ); - _valueDateTimeLabel.setText( timeString ); - _valueTextField.setText( getFormattedValue( value ) ); - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - _missingValueCheckBox.setSelected( false ); - addListeners(); - } - - public void refresh( long time, double value ) - { - _time = time; - _valueTextField.setText( getFormattedValue( value ) ); - if ( _displayMappedValue ) - { - if ( ! _isMissingValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - } - } - - private String getMappedValueString( double value ) - { - double mappedValue = 0; - String mappedValueString = null; - - if ( value != _missingValue ) - { - Measurement measurement = new Measurement( value, getTimeSeries().getMeasuringUnit() ); - Measurement mappedMeasurement = _valueMapper.getResultMeasurement( measurement ); - mappedValue = mappedMeasurement.getValue(); - - } - else - { - mappedValue = _missingValue; - } - - mappedValueString = getFormattedValue( mappedValue ); - return mappedValueString; - } - - private void addListeners() - { - _missingValueCheckBox.addActionListener( new MissingValueCheckBoxListener() ); - _valueTextField.addKeyListener( new PrecipTextFieldListener() ); - _valueTextField.addFocusListener( new FocusLostFocusListener() ); - - //_valueTextField.addFocusListener(RegularTimeSeriesEditor.this._focusListener); - } - - private class MissingValueCheckBoxListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _isMissingValue = _missingValueCheckBox.isSelected(); - if ( _isMissingValue ) - { - _valueTextField.setText( "" + _missingValue ); - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( "" + _missingValue ); - } - } - else - { - double value = getTimeSeries().getMeasurementValueByTime( _time, getTimeSeries().getMeasuringUnit() ); - _valueTextField.setText( getFormattedValue( value ) ); - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - } - } - } - - private class PrecipTextFieldListener implements KeyListener - { - public void keyPressed(KeyEvent arg0) - { - _missingValueCheckBox.setSelected( false ); - _isMissingValue = _missingValueCheckBox.isSelected(); - } - - public void keyReleased(KeyEvent arg0) - { - } - - public void keyTyped(KeyEvent arg0) - { - } - } - - private class FocusLostFocusListener implements FocusListener - { - private double parseDouble(String valueString) - { - - double value = 0.0; - - try - { - value = Double.parseDouble( valueString ); - } - catch (java.lang.NumberFormatException e) - { - value = 0.0; - _valueTextField.setText(getFormattedValue(value)); - } - - return value; - } - - - public void focusGained(FocusEvent arg0) - { - } - - public void focusLost(FocusEvent arg0) - { - String valueString = _valueTextField.getText().trim(); - double value = parseDouble( valueString ); - - if ( valueString.length() == 0 ) - { - _valueTextField.setText( getFormattedValue(value)); - } - - if ( ! _missingValueCheckBox.isSelected() ) - { - if ( value < _minValue ) - { - _valueTextField.setText( "" + _minValue ); - } - - if ( value > _maxValue ) - { - _valueTextField.setText( "" + _maxValue ); - } - - valueString = _valueTextField.getText().trim(); - value = parseDouble( valueString ); - } - - if ( _displayMappedValue ) - { - _mappedValueTextField.setText( getMappedValueString( value ) ); - } - - //Allows for an immediate update of precip once values have been changed. - updateTimeSeries(); - //refreshDataPanel(); - - } - } - - } -// ------------------------------------------------------------------------------------------ - - private class UpdateTimeSeriesListener implements TimeSeriesListener - { - public Object getReceiver() - { - return RegularTimeSeriesEditor.this; - } - - public void handleTimeSeriesEvent(TimeSeriesEvent event) - { - if (event.getSource() != RegularTimeSeriesEditor.this) - { - // System.out.println("UpdateTimeSeriesListener event = " + event.toString()); - refreshDataPanel(); - } - } - - } -// ------------------------------------------------------------------------------------------ - - public static void main( String args[] ) - { - String valueLabel = null; - String titleLabel = null; - - RegularTimeSeries timeSeries = RegularTimeSeriesEditor.getTestTimeSeries(); - RegularTimeSeriesHolder holder = new RegularTimeSeriesHolder(); - holder.setTimeSeries( timeSeries ); - - valueLabel = "MAP(" + timeSeries.getMeasuringUnit() + ")"; - titleLabel = "Forecast Stage Editor"; - ValueMapper mapper = new UnitValueMapper( MeasuringUnit.feet, MeasuringUnit.mm ); - - RegularTimeSeriesEditorDescriptor descriptor = new RegularTimeSeriesEditorDescriptor( new Frame(), holder, valueLabel ); - descriptor.setValueMapper( mapper ); - descriptor.setMappedValueLabelString( "cfs" ); - descriptor.setTitleLabelString( titleLabel ); - descriptor.setInitialSearchTime( System.currentTimeMillis() ); - descriptor.setMissingValue( -9999.0 ); - descriptor.setMinValue( 0.0 ); - descriptor.setMaxValue( 20.0 ); - - RegularTimeSeriesEditor editor = new RegularTimeSeriesEditor( descriptor ); - editor.show(); - } -// ------------------------------------------------------------------------------------------ - -} - - diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditorDescriptor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditorDescriptor.java deleted file mode 100644 index 7379662ee1..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/RegularTimeSeriesEditorDescriptor.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Created on Apr 19, 2004 - * - * Filename : RegularTimeSeriesHelper.java - * Author : Gautam Sood - * Last Revision Date : Apr 19, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import java.awt.Frame; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.TimeHelper; - -public class RegularTimeSeriesEditorDescriptor -{ - private Frame _owner = null; - private RegularTimeSeriesHolder _regularTimeSeriesHolder = null; - private String _titleLabelString = "Timeseries Editor"; - private String _valueLabelString = null; - private String _textFieldFormatString = "0.00"; - private boolean _isEditable = true; - private boolean _isModal = true; - private ValueMapper _valueMapper = null; - private String _mappedValueLabelString = null; - private long _initialSearchTime = 0; - private double _missingValue = -9999.00; - private double _minValue = 0.0; - private double _maxValue = 20.0; - - - public RegularTimeSeriesEditorDescriptor( Frame owner, - RegularTimeSeriesHolder regularTimeSeriesHolder, - String titleLabelString, - String valueLabelString, - String textFieldFormatString, - boolean isEditable, - boolean isModal, - ValueMapper valueMapper, - String mappedValueLabelString, - long initialSearchTime, - double missingValue, - double minValue, - double maxValue ) - { - _owner = owner; - _regularTimeSeriesHolder = regularTimeSeriesHolder; - _titleLabelString = titleLabelString; - _valueLabelString = valueLabelString; - _textFieldFormatString = textFieldFormatString; - _isEditable = isEditable; - _isModal = isModal; - _valueMapper = valueMapper; - _mappedValueLabelString = mappedValueLabelString; - _missingValue = missingValue; - _minValue = minValue; - _maxValue = maxValue; - setInitialSearchTime( getRoundedTime( initialSearchTime ) ); - } - - public RegularTimeSeriesEditorDescriptor( Frame owner, - RegularTimeSeriesHolder regularTimeSeriesHolder, - String valueLabelString ) - { - _owner = owner; - _regularTimeSeriesHolder = regularTimeSeriesHolder; - _valueLabelString = valueLabelString; - } - - public long getRoundedTime( long initialSearchTime ) - { - return TimeHelper.truncateTimeInMillisToNearestHour( initialSearchTime, 1 ); - } - - public void setOwner( Frame owner ) - { - _owner = owner; - } - - public Frame getOwner() - { - return _owner; - } - - public void setRegularTimeSeriesHolder( RegularTimeSeriesHolder regularTimeSeriesHolder ) - { - _regularTimeSeriesHolder = regularTimeSeriesHolder; - } - - public RegularTimeSeriesHolder getRegularTimeSeriesHolder() - { - return _regularTimeSeriesHolder; - } - - public void setTitleLabelString( String titleLabelString ) - { - _titleLabelString = titleLabelString; - } - - public String getTitleLabelString() - { - return _titleLabelString; - } - - public void setValueLabelString( String valueLabelString ) - { - _valueLabelString = valueLabelString; - } - - public String getValueLabelString() - { - return _valueLabelString; - } - - public void setTextFieldFormatString( String textFieldFormatString ) - { - _textFieldFormatString = textFieldFormatString; - } - - public String getTextFieldFormatString() - { - return _textFieldFormatString; - } - - public void setEditable( boolean isEditable ) - { - _isEditable = isEditable; - } - - public boolean isEditable() - { - return _isEditable; - } - - public void setModal( boolean isModal ) - { - _isModal = isModal; - } - - public boolean isModal() - { - return _isModal; - } - - public void setValueMapper( ValueMapper valueMapper ) - { - _valueMapper = valueMapper; - } - - public ValueMapper getValueMapper() - { - return _valueMapper; - } - - public void setMappedValueLabelString( String mappedValueLabelString ) - { - _mappedValueLabelString = mappedValueLabelString; - } - - public String getMappedValueLabelString() - { - return _mappedValueLabelString; - } - - public void setInitialSearchTime( long initialSearchTime ) - { - _initialSearchTime = getRoundedTime( initialSearchTime ); - } - - public long getInitialSearchTime() - { - return _initialSearchTime; - } - - public void setMissingValue( double missingValue ) - { - _missingValue = missingValue; - } - - public double getMissingValue() - { - return _missingValue; - } - - public void setMinValue( double minValue ) - { - _minValue = minValue; - } - - public double getMinValue() - { - return _minValue; - } - - public void setMaxValue( double maxValue ) - { - _maxValue = maxValue; - } - - public double getMaxValue() - { - return _maxValue; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SSHPConfigDialog.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SSHPConfigDialog.java deleted file mode 100644 index 14839518ec..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SSHPConfigDialog.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * Created on Feb 4, 2004 - * - * Filename : SSHPConfigDialog.java - * Author : Gautam Sood - * Last Revision Date : Feb 4, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import ohd.hseb.model.ForecastInterpolationMethod; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.SSHPConfig; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.TableHelper; -import ohd.hseb.db.DbTimeHelper; -import java.awt.*; -import java.awt.event.*; - -import javax.swing.*; -import javax.swing.border.Border; -import javax.swing.event.*; -import javax.swing.table.TableColumn; - -import java.util.List; - -public class SSHPConfigDialog extends JDialog -{ - private static final int MAX_BLENDING_HOURS = 1000; - - private Container _frameContentPane = getContentPane(); - - private JPanel _sshpConfigListPanel = new JPanel(); - private JPanel _sshpConfigTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 12 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private DataMgr _dataMgr = null; - private SSHPConfig _sshpConfig = null; - - private List _sshpConfigList = null; - - private static final int DEFAULT_WIDTH = 850; - private static final int DEFAULT_HEIGHT = 654; - - private static final int MAX_WIDTH = 850; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 750; - private static final int MIN_HEIGHT = 500; - - private String[] _sourcePrefStringArray = { "LOCAL", "RFC" }; - private String[] _modelPrefStringArray = { RainfallRunoffModelType.API_MKC.getName(), - RainfallRunoffModelType.SAC_SMA.getName() }; - private String[] _blendMethodStringArray = { "DIFF", "RATIO" }; - - private String _lid = null; -// JComponents - -// JLabels for the Text Panel - private JLabel _lidLabel = getJLabel( "LID" ); - private JLabel _basinIdLabel = getJLabel( "Basin ID" ); - private JLabel _postingTimeLabel = getJLabel( "Posting Time" ); - private JLabel _modelPrefLabel = getJLabel( "Model Preference" ); - - // the subpanel for the SAC-SMA settings - private Border _panelBorder = BorderFactory.createLineBorder(Color.black); - private JPanel _sacSettingsPanel = new JPanel(); - private JLabel _sacSettingsPanelLabel = getJLabel("SAC-SMA settings"); - - private JLabel _autoProcessLabel = getJLabel( "Update States Locally?" ); - private JLabel _sourcePrefLabel = getJLabel( "Data Source Preference" ); - private JLabel _useStaticEvapLabel = getJLabel( "Use ET Demand Curve?" ); - - private JLabel _blendHoursLabel = getJLabel("Blending Hours"); - private JLabel _useBlendLabel = getJLabel("Use Adjustment?"); - private JLabel _blendMethodLabel = getJLabel("Adjustment Method"); - -// JTextFields for the Data Panel - private JTextField _lidTextField = getJTextField( 17 ); - private JTextField _basinIdTextField = getJTextField( 17 ); - private JTextField _postingTimeTextField = getJTextField( 17 ); - - private JSpinner _blendHoursSpinner = null; - -// JCheckboxes for the Data Panel - private JCheckBox _autoProcessCheckBox = new JCheckBox(); - private JCheckBox _useStaticEvapCheckBox = new JCheckBox(); - private JCheckBox _useBlendCheckBox = new JCheckBox(); - -// JComboboxes for the Data Panel - private JComboBox _sourcePrefComboBox = new JComboBox( _sourcePrefStringArray ); - private JComboBox _modelPrefComboBox = new JComboBox( _modelPrefStringArray ); - private JComboBox _blendMethodComboBox = new JComboBox( _blendMethodStringArray ); - - private JScrollPane _dataScrollPane = new JScrollPane( _sshpConfigTextPanel ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for the Table - private String[] _columnNames = { "LID", "Basin ID", "Model Pref", - "Update States Locally?", "Source Pref", - "ET-Demand Curve?", "Use Adjust?", - "Adjust Method", "Blend Hours"}; - - private String[][] _sshpConfigStringArray = null; - private JTable _sshpConfigTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel =null; - - //used for sorting the Table - private String[] _dbColumnNames = { "lid", "basin_id", "model_pref", "auto_process", "source_pref", "use_static_evap" }; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - public SSHPConfigDialog( Frame owner, DataMgr dataMgr ) - { - this( owner, dataMgr, null, true ); - } - - public SSHPConfigDialog( Frame owner, DataMgr dataMgr, String lid ) - { - this( owner, dataMgr, lid, true ); - } - - public SSHPConfigDialog( Frame owner, DataMgr dataMgr, String lid, boolean isModal ) - { - super( owner, isModal ); - this.setTitle( "SSHP Config" ); - _dataMgr = dataMgr; - _lid = lid; - - - //set up the spinner control for time - int initialValue = 0; - int min = 0; - int max = MAX_BLENDING_HOURS; - int step = 6; - - SpinnerModel model = new SpinnerNumberModel(initialValue, min, max, step); - _blendHoursSpinner = new JSpinner(model); - - - initialize(); - } - - private void initialize() - { - - setupTable(); - - - addSSHPConfigListPanelComponents(); - addSSHPConfigDataPanelComponents(); - addButtons(); - addFrameComponents(); - addListeners(); - - refreshSSHPConfigTable(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - /******************** - Purpose: Sets up the JTable - *********************/ - { - int index = -1; - boolean foundLid= false; - - _tableHelper.setOrderByClause( 0 ); - - _sshpConfigList = _dataMgr.loadSSHPConfigList( _tableHelper.getOrderByClause() ); - _sshpConfigStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _sshpConfigStringArray ); - _sshpConfigTable = new JTable( _tableModel ); - _sshpConfigTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _sshpConfigTable.setPreferredScrollableViewportSize( new Dimension( 600, 100 ) ); - _listSelectionModel = _sshpConfigTable.getSelectionModel(); - _scrollPane = new JScrollPane( _sshpConfigTable ); - if ( _lid != null ) - { - for ( int i = 0; i < _sshpConfigList.size(); i++ ) - { - SSHPConfig sshpConfig = (SSHPConfig) _sshpConfigList.get( i ); - - if ( _lid.equalsIgnoreCase( sshpConfig.getLid().trim() ) ) - { - index = i; - foundLid = true; - _sshpConfig = sshpConfig; - break; - } - } - } - - adjustColumnWidths(); - - - - - if ( foundLid ) // Checks if a Lid was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _sshpConfigTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void adjustColumnWidths() - { - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sshpConfigTable.getColumnModel().getColumn( i ); - if ( ( i == 3 ) || ( i == 5 ) ) - { - column.setPreferredWidth( 125 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - } - - private void refreshSSHPConfigTable() - { - int index = 0; - - _sshpConfigList = _dataMgr.loadSSHPConfigList( _tableHelper.getOrderByClause() ); - - _sshpConfigStringArray = convertListToArray(); - if ( _sshpConfig != null ) - { - for ( int i = 0; i < _sshpConfigList.size(); i++ ) - { - SSHPConfig sshpConfig = (SSHPConfig) _sshpConfigList.get( i ); - - if ( _sshpConfig.equals( sshpConfig ) ) - { - index = i; - break; - } - } - } - - _tableModel.updateData( _sshpConfigStringArray ); - _tableModel.fireTableChanged( null ); - - adjustColumnWidths(); - - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _sshpConfigTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _sshpConfigList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - SSHPConfig sshpConfig = (SSHPConfig) _sshpConfigList.get( i ); - - dataArray[ i ][ 0 ] = sshpConfig.getLid(); - dataArray[ i ][ 1 ] = sshpConfig.getBasinId(); - dataArray[ i ][ 2 ] = sshpConfig.getModelPref(); - dataArray[ i ][ 3 ] = "" + sshpConfig.isAutoProcess(); - dataArray[ i ][ 4 ] = sshpConfig.getSourcePref(); - dataArray[ i ][ 5 ] = "" + sshpConfig.useStaticEvap(); - dataArray[ i ][ 6 ] = "" + sshpConfig.useBlend(); - dataArray[ i ][ 7 ] = sshpConfig.getBlendMethod().getName(); - dataArray[ i ][ 8 ] = "" + sshpConfig.getBlendHours(); - } - return dataArray; - } - - - private void addSSHPConfigListPanelComponents() - /******************** - Purpose: Add's Components to the JList Scroll Pane Panel - *********************/ - { - _sshpConfigListPanel.setLayout( new GridBagLayout() ); - - ComponentHelper.addPanelComponent( _sshpConfigListPanel, _scrollPane, 0, 0, 2, 12, 1, 1, GridBagConstraints.BOTH ); - } - - private void addSSHPConfigDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the _sshpConfigTextPanel - *********************/ - { - _sshpConfigTextPanel.setLayout( new GridBagLayout() ); - -// XCol, YRow, ColCount, RowCount - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _lidLabel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _lidTextField, 1, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _basinIdLabel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _basinIdTextField, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _modelPrefLabel, 0, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _modelPrefComboBox, 1, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _useBlendLabel, 0, 3, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _useBlendCheckBox, 1, 3, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendMethodLabel, 0, 4, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendMethodComboBox, 1, 4, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendHoursLabel, 0, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _blendHoursSpinner, 1, 5, 1, 1, GridBagConstraints.BOTH ); - - - - // inside the SAC Settings sub panel - _sacSettingsPanel.setLayout(new GridBagLayout()); - _sacSettingsPanel.setBorder(_panelBorder); - - ComponentHelper.addPanelComponent( _sacSettingsPanel, _autoProcessLabel, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _autoProcessCheckBox, 1, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _sourcePrefLabel, 0, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _sourcePrefComboBox, 1, 1, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _useStaticEvapLabel, 0, 2, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacSettingsPanel, _useStaticEvapCheckBox, 1, 2, 1, 1, GridBagConstraints.BOTH ); - - - - - - //add the subpanel to the _sshpConfigTextPanel - JPanel separatorPanel1 = new JPanel(); - JPanel separatorPanel2 = new JPanel(); - - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, separatorPanel1, 0, 6, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _sacSettingsPanelLabel,0, 7, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _sacSettingsPanel, 0, 8, 4, 5, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, separatorPanel2, 0, 14, 1, 1, GridBagConstraints.BOTH ); - - - - //continue with more of the _sshpConfigTextPanel - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _postingTimeLabel, 0, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sshpConfigTextPanel, _postingTimeTextField, 1, 15, 1, 1, GridBagConstraints.BOTH ); - - _postingTimeTextField.setEditable( false ); - _postingTimeTextField.setToolTipText("Indicates the last time that this record was saved"); - } - - - private void addButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _buttonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 2, 22, 2, GridBagConstraints.BOTH ); - } - - private void addFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - _dataScrollPane.setPreferredSize( new Dimension( 150, 300 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _sshpConfigListPanel, 0, 0, 10, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 17, 20, 15, 0, .5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - - if ( _sshpConfig != null ) - { - _lidTextField.setText( _sshpConfig.getLid() ); - _basinIdTextField.setText( _sshpConfig.getBasinId() ); - _postingTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sshpConfig.getPostingTime() ) ); - _modelPrefComboBox.setSelectedItem( _sshpConfig.getModelPref().trim() ); - _autoProcessCheckBox.setSelected( _sshpConfig.isAutoProcess() ); - _sourcePrefComboBox.setSelectedItem( _sshpConfig.getSourcePref().trim() ); - _useStaticEvapCheckBox.setSelected( _sshpConfig.useStaticEvap() ); - _useBlendCheckBox.setSelected(_sshpConfig.useBlend()); - _blendMethodComboBox.setSelectedItem( _sshpConfig.getBlendMethod()); - _blendHoursSpinner.setValue(new Integer( _sshpConfig.getBlendHours())); - } - else - { - _lidTextField.setText( "" ); - _basinIdTextField.setText( "" ); - _postingTimeTextField.setText( "Not Posted Yet" ); - _modelPrefComboBox.setSelectedIndex( 0 ); - _autoProcessCheckBox.setSelected( false ); - _sourcePrefComboBox.setSelectedIndex( 0 ); - _useStaticEvapCheckBox.setSelected( false ); - _useBlendCheckBox.setSelected(false); - _blendMethodComboBox.setSelectedIndex(0); - _blendHoursSpinner.setValue(new Integer(999)); - } - } - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _sshpConfigTable.getTableHeader().addMouseListener( new TableSortingListener() ); - - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _sshpConfigTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _sshpConfigList.isEmpty() ) ) - { - _sshpConfig = (SSHPConfig) _sshpConfigList.get( index ); - } - else - { - _sshpConfig = null; - } - loadTextFields(); - } - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _sshpConfigTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshSSHPConfigTable(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - SSHPConfig sshpConfig = new SSHPConfig(); - - if ( - ( ! isEmptyString( _lidTextField.getText() ) ) && - ( ! isEmptyString( _basinIdTextField.getText() ) ) - ) // Checks to make sure the basinID and source - // are not empty strings - { - try - { - sshpConfig.setLid( _lidTextField.getText().trim() ); - sshpConfig.setBasinId( _basinIdTextField.getText().trim() ); - sshpConfig.setModelPref( (String) _modelPrefComboBox.getSelectedItem() ); - sshpConfig.setAutoProcess( _autoProcessCheckBox.isSelected() ); - sshpConfig.setSourcePref( (String) _sourcePrefComboBox.getSelectedItem() ); - sshpConfig.setUseStaticEvap( _useStaticEvapCheckBox.isSelected() ); - sshpConfig.setUseBlend(_useBlendCheckBox.isSelected()); - - - //get the method name and translate that to an actual ForecastBlendMethod object - String methodName = (String) _blendMethodComboBox.getSelectedItem(); - ForecastInterpolationMethod method = ForecastInterpolationMethod.getMethodByName(methodName); - sshpConfig.setBlendMethod ( method ); - - // get and parse the string from the blend hours text field - Integer hoursInteger = (Integer) _blendHoursSpinner.getValue(); - int hours = 0; - try - { - hours = hoursInteger.intValue(); - } - catch (NumberFormatException formatException) - { - hours = 999; - } - sshpConfig.setBlendHours(hours); - - - // save the configuration to the database and reload the JTable - _dataMgr.saveSSHPConfig( sshpConfig ); - _sshpConfig = sshpConfig; - refreshSSHPConfigTable(); - } - catch ( NumberFormatException exception ) - { - DialogHelper.displayMessageDialog(null, - "There is a parsing error in your input", - "Error Message"); - //JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - else - { - DialogHelper.displayMessageDialog(null, - "Empty Strings are not allowed", - "Error Message"); - - //JOptionPane.showMessageDialog( null, "Empty Strings are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - if ( _sshpConfig != null ) - { - // choice = JOptionPane.showConfirmDialog( null, "Are you sre you want to delete this Config?", - // "Delete SSHP Config", JOptionPane.YES_NO_OPTION, - // JOptionPane.WARNING_MESSAGE ); - - confirm = DialogHelper.displayConfirmDialog(null, "Are you sre you want to delete this Config?", - "Delete SSHP Config"); - - if ( confirm ) - /* User selected YES */ - { - _dataMgr.deleteSSHPConfig( _sshpConfig ); - _sshpConfig = null; - refreshSSHPConfigTable(); - } - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _sshpConfig = null; - loadTextFields(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = SSHPConfigDialog.this.getHeight(); - int width = SSHPConfigDialog.this.getWidth(); - -// System.err.println( "Width: " + width + " Height: " + height ); - if ( width < MIN_WIDTH ) - { - SSHPConfigDialog.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - SSHPConfigDialog.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - SSHPConfigDialog.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - SSHPConfigDialog.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private JLabel getJLabel( String label ) - /******************** - Purpose: Returns a JLabel set to the string passed in - *********************/ - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - /******************** - Purpose: Returns a JTextField using the size passed in - *********************/ - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - public static void main( String[] args ) - { - SSHPConfigDialog dialog = new SSHPConfigDialog( new Frame(), new DataMgr(), "BLUO2" ); - dialog.show(); - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SacParamsEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SacParamsEditor.java deleted file mode 100644 index fd6b9c2c55..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SacParamsEditor.java +++ /dev/null @@ -1,781 +0,0 @@ -/* - * Created on Oct 21, 2003 - * - * Filename : SacParamsEditor.java - * Author : Gautam Sood - * Last Revision Date : Oct 21, 2003 - * Purpose: Display GUI for the SacSMA Parameters. - */ - -package ohd.hseb.sshp.window; - -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.table.TableColumn; - -import java.awt.*; -import java.awt.event.*; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.TableHelper; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.util.gui.*; - -import java.text.DecimalFormat; -import java.util.List; -import java.util.*; - -public class SacParamsEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _sacParamsListPanel = new JPanel(); - private JPanel _sacParamsTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private List _sacParamsList = null; - - private DataMgr _dataMgr = null; - private SacSmaParameters _sacSmaParameters = null; - - private String _basinId = null; - - private static final int DEFAULT_WIDTH = 340; - private static final int DEFAULT_HEIGHT = 654; - - private static final int MAX_WIDTH = 500; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 340; - private static final int MIN_HEIGHT = 500; - - //used for JFormattedTextFields - private static final String _threeDecimalFormatString = "0.000"; - private DecimalFormat _decimalFormat = new DecimalFormat( _threeDecimalFormatString ); - - private JLabel _basinIDLabel = getJLabel( "Basin ID" ); - private JLabel _sourceLabel = getJLabel( "Source" ); - private JLabel _validTimeLabel = getJLabel( "Valid Time" ); - private JLabel _uztwmLabel = getJLabel( "UZTWM" ); - private JLabel _uzfwmLabel = getJLabel( "UZFWM" ); - private JLabel _uzkLabel = getJLabel( "UZK" ); - private JLabel _pctimLabel = getJLabel( "PCTIM" ); - private JLabel _adimpLabel = getJLabel( "ADIMP" ); - private JLabel _rivaLabel = getJLabel( "RIVA" ); - private JLabel _zpercLabel = getJLabel( "ZPERC" ); - private JLabel _rexpLabel = getJLabel( "REXP" ); - private JLabel _lztwmLabel = getJLabel( "LZTWM" ); - private JLabel _lzfsmLabel = getJLabel( "LZFSM" ); - private JLabel _lzfpmLabel = getJLabel( "LZFPM" ); - private JLabel _lzskLabel = getJLabel( "LZSK" ); - private JLabel _lzpkLabel = getJLabel( "LZPK" ); - private JLabel _pfreeLabel = getJLabel( "PFREE" ); - private JLabel _rservLabel = getJLabel( "RSERV" ); - private JLabel _sideLabel = getJLabel( "SIDE" ); - private JLabel _peAdjustLabel = getJLabel( "PEADJ" ); - private JLabel _pxAdjustLabel = getJLabel( "PXADJ" ); - private JLabel _efcLabel = getJLabel( "EFC" ); - - private JTextField _basinIDTextField = getJTextField( 17 ); - private JTextField _sourceTextField = getJTextField( 17 ); - private JTextField _validTimeTextField = getJTextField( 17 ); - private JFormattedTextField _uztwmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _uzfwmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _uzkTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _pctimTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _adimpTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _rivaTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _zpercTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _rexpTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lztwmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfsmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfpmTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzskTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzpkTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _pfreeTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _rservTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _sideTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _peAdjustTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _pxAdjustTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _efcTextField = getJFormattedTextField( _threeDecimalFormatString ); - - private JScrollPane _dataScrollPane = new JScrollPane( _sacParamsTextPanel ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for custom notification - private List _applyListenerList = new ArrayList(); - - //used for the Table - private String[] _columnNames = { "Basin ID", "Source", "Valid Time" }; - private String[][] _sacParamsStringArray = null; - private JTable _sacSmaParamsTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel = null; - - //used for sorting the Table - private String[] _dbColumnNames = { "basin_id", "source", "validtime" }; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - public SacParamsEditor( Frame owner, DataMgr dataMgr ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, null, false ); - } - - - public SacParamsEditor( Frame owner, DataMgr dataMgr, String basinId ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, basinId, false ); - } - - public SacParamsEditor( Frame owner, DataMgr dataMgr, String basinId, boolean isModal ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, isModal ); - this.setTitle( "SacSma Parameters" ); - _basinId = basinId; - _dataMgr = dataMgr; - initialize(); - } - - private void initialize() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - setupTable(); - - AddSacParamsListPanelComponents(); - AddSacParamsDataPanelComponents(); - AddButtons(); - AddFrameComponents(); - AddListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - { - int index = -1; - boolean foundBasinId= false; - - _tableHelper.setOrderByClause( 0 ); - - _sacParamsList = _dataMgr.loadSacSmaParamsList( _tableHelper.getOrderByClause() ); - _sacParamsStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _sacParamsStringArray ); - _sacSmaParamsTable = new JTable( _tableModel ); - _sacSmaParamsTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _sacSmaParamsTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - _listSelectionModel = _sacSmaParamsTable.getSelectionModel(); - _scrollPane = new JScrollPane( _sacSmaParamsTable ); - if ( _basinId != null ) - { - for ( int i = 0; i < _sacParamsList.size(); i++ ) - { - SacSmaParameters sacSmaParams = (SacSmaParameters) _sacParamsList.get( i ); - - if ( _basinId.equalsIgnoreCase( sacSmaParams.getBasinId().trim() ) ) - { - index = i; - foundBasinId = true; - _sacSmaParameters = sacSmaParams; - break; - } - } - } - - if ( ! foundBasinId ) // If no basin ID found in the Params list, selects the first one by default. - { - if (_sacParamsList.size() > 0) - { - _sacSmaParameters = (SacSmaParameters) _sacParamsList.get( 0 ); - } - } - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaParamsTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - if ( foundBasinId ) // Checks if a Basin Id was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _sacSmaParamsTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void refreshSacSmaParamsTable() - { - int index = 0; - - _sacParamsList = _dataMgr.loadSacSmaParamsList( _tableHelper.getOrderByClause() ); - - _sacParamsStringArray = convertListToArray(); - if ( _sacSmaParameters != null ) - { - for ( int i = 0; i < _sacParamsList.size(); i++ ) - { - SacSmaParameters sacSmaParams = (SacSmaParameters) _sacParamsList.get( i ); - - if ( _sacSmaParameters.equals( sacSmaParams ) ) - { - index = i; - break; - } - } - } - _tableModel.updateData( _sacParamsStringArray ); - _tableModel.fireTableChanged( null ); - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaParamsTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _sacSmaParamsTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _sacParamsList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - SacSmaParameters sacParams = (SacSmaParameters) _sacParamsList.get( i ); - - dataArray[ i ][ 0 ] = sacParams.getBasinId(); - dataArray[ i ][ 1 ] = sacParams.getSource(); - dataArray[ i ][ 2 ] = "" + DbTimeHelper.getDateTimeStringFromLongTime( sacParams.getValidTime() ); - } - return dataArray; - } - - private void AddFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - _dataScrollPane.setPreferredSize( new Dimension( 150, 300 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _sacParamsListPanel, 0, 0, 10, 15, 1, .5, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _dataScrollPane, 0, 17, 20, 15, 0, .8, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private void AddSacParamsListPanelComponents() - /******************** - Purpose: Add's Components to the JList Scroll Pane Panel - *********************/ - { - _sacParamsListPanel.setLayout( new GridBagLayout() ); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _sacParamsListPanel, _scrollPane, 0, 0, 5, 25, 1, 1, GridBagConstraints.BOTH ); - - } - - - private void AddSacParamsDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the sacParamsTextPanel - *********************/ - { - _sacParamsTextPanel.setLayout( new GridBagLayout() ); - - java.awt.Color backgroundColor = _validTimeTextField.getBackground(); - _validTimeTextField.setEditable( false ); - _validTimeTextField.setBackground(backgroundColor); - - - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _basinIDLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _basinIDTextField, 10, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sourceLabel, 0, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sourceTextField, 10, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _validTimeLabel, 0, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _validTimeTextField, 10, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uztwmLabel, 0, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uztwmTextField, 10, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzfwmLabel, 0, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzfwmTextField, 10, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzkLabel, 0, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _uzkTextField, 10, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pctimLabel, 0, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pctimTextField, 10, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _adimpLabel, 0, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _adimpTextField, 10, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rivaLabel, 0, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rivaTextField, 10, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _zpercLabel, 0, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _zpercTextField, 10, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rexpLabel, 0, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rexpTextField, 10, 100, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lztwmLabel, 0, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lztwmTextField, 10, 110, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfsmLabel, 0, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfsmTextField, 10, 120, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfpmLabel, 0, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzfpmTextField, 10, 130, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzskLabel, 0, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzskTextField, 10, 140, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzpkLabel, 0, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _lzpkTextField, 10, 150, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pfreeLabel, 0, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pfreeTextField, 10, 160, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rservLabel, 0, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _rservTextField, 10, 170, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sideLabel, 0, 180, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _sideTextField, 10, 180, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _peAdjustLabel, 0, 190, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _peAdjustTextField, 10, 190, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pxAdjustLabel, 0, 200, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _pxAdjustTextField, 10, 200, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _efcLabel, 0, 210, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacParamsTextPanel, _efcTextField, 10, 210, 5, 1, GridBagConstraints.BOTH ); - } - - private void AddButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _buttonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 2, 22, 2, GridBagConstraints.BOTH ); - } - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _sacSmaParameters != null ) - { - _basinIDTextField.setText( _sacSmaParameters.getBasinId() ); - _sourceTextField.setText( _sacSmaParameters.getSource() ); - _validTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sacSmaParameters.getValidTime() ) ); - - _uztwmTextField.setText( getFormattedValue( _sacSmaParameters.getUztwm() ) ); - _uzfwmTextField.setText( getFormattedValue( _sacSmaParameters.getUzfwm() ) ); - _uzkTextField.setText( getFormattedValue( _sacSmaParameters.getUzk() ) ); - _pctimTextField.setText( getFormattedValue( _sacSmaParameters.getPctim() ) ); - _adimpTextField.setText( getFormattedValue( _sacSmaParameters.getAdimp() ) ); - _rivaTextField.setText( getFormattedValue( _sacSmaParameters.getRiva() ) ); - _zpercTextField.setText( getFormattedValue( _sacSmaParameters.getZperc() ) ); - _rexpTextField.setText( getFormattedValue( _sacSmaParameters.getRexp() ) ); - _lztwmTextField.setText( getFormattedValue( _sacSmaParameters.getLztwm() ) ); - _lzfsmTextField.setText( getFormattedValue( _sacSmaParameters.getLzfsm() ) ); - _lzfpmTextField.setText( getFormattedValue( _sacSmaParameters.getLzfpm() ) ); - _lzskTextField.setText( getFormattedValue( _sacSmaParameters.getLzsk() ) ); - _lzpkTextField.setText( getFormattedValue( _sacSmaParameters.getLzpk() ) ); - _pfreeTextField.setText( getFormattedValue( _sacSmaParameters.getPfree() ) ); - _rservTextField.setText( getFormattedValue( _sacSmaParameters.getRserv() ) ); - _sideTextField.setText( getFormattedValue( _sacSmaParameters.getSide() ) ); - _peAdjustTextField.setText( getFormattedValue( _sacSmaParameters.getPeadj() ) ); - _pxAdjustTextField.setText( getFormattedValue( _sacSmaParameters.getPxadj() ) ); - _efcTextField.setText( getFormattedValue( _sacSmaParameters.getEfc() ) ); - } - else - { - _basinIDTextField.setText( "" ); - _sourceTextField.setText( "" ); - _validTimeTextField.setText( "yyyy-mm-dd hh:mm:ss" ); - _uztwmTextField.setText( "" ); - _uzfwmTextField.setText( "" ); - _uzkTextField.setText( "" ); - _pctimTextField.setText( "" ); - _adimpTextField.setText( "" ); - _rivaTextField.setText( "" ); - _zpercTextField.setText( "" ); - _rexpTextField.setText( "" ); - _lztwmTextField.setText( "" ); - _lzfsmTextField.setText( "" ); - _lzfpmTextField.setText( "" ); - _lzskTextField.setText( "" ); - _lzpkTextField.setText( "" ); - _pfreeTextField.setText( "" ); - _rservTextField.setText( "" ); - _sideTextField.setText( "" ); - _peAdjustTextField.setText( "" ); - _pxAdjustTextField.setText( "" ); - _efcTextField.setText( "" ); - } - } - - private void AddListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - _validTimeTextField.addMouseListener( new TimeTextFieldListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _sacSmaParamsTable.getTableHeader().addMouseListener( new TableSortingListener() ); - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _sacSmaParamsTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshSacSmaParamsTable(); - } - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _sacSmaParamsTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _sacParamsList.isEmpty() ) ) - { - _sacSmaParameters = (SacSmaParameters) _sacParamsList.get( index ); - } - else - { - _sacSmaParameters = null; - } - loadTextFields(); - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _sacSmaParameters = null; - loadTextFields(); - } - } - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - SacSmaParameters params = new SacSmaParameters(); - - if ( - ( ! isEmptyString( _basinIDTextField.getText() ) ) && - ( ! isEmptyString( _sourceTextField.getText() ) ) && - ( ! _validTimeTextField.getText().trim().equals( "yyyy-mm-dd hh:mm:ss" ) ) - ) // Checks to make sure the basinID and source - // are not empty strings - { - try - { - params.setBasinId( _basinIDTextField.getText().trim() ); - params.setSource( _sourceTextField.getText().trim() ); - params.setValidTime( DbTimeHelper.getLongTimeFromDateTimeString( _validTimeTextField.getText() ) ); - params.setPostingTime( getCurrentTime() ); - params.setUztwm( Double.parseDouble( _uztwmTextField.getText() ) ); - params.setUzfwm( Double.parseDouble( _uzfwmTextField.getText() ) ); - params.setUzk( Double.parseDouble( _uzkTextField.getText() ) ); - params.setPctim( Double.parseDouble( _pctimTextField.getText() ) ); - params.setAdimp( Double.parseDouble( _adimpTextField.getText() ) ); - params.setRiva( Double.parseDouble( _rivaTextField.getText() ) ); - params.setZperc( Double.parseDouble( _zpercTextField.getText() ) ); - params.setRexp( Double.parseDouble( _rexpTextField.getText() ) ); - params.setLztwm( Double.parseDouble( _lztwmTextField.getText() ) ); - params.setLzfsm( Double.parseDouble( _lzfsmTextField.getText() ) ); - params.setLzfpm( Double.parseDouble( _lzfpmTextField.getText() ) ); - params.setLzsk( Double.parseDouble( _lzskTextField.getText() ) ); - params.setLzpk( Double.parseDouble( _lzpkTextField.getText() ) ); - params.setPfree( Double.parseDouble( _pfreeTextField.getText() ) ); - params.setRserv( Double.parseDouble( _rservTextField.getText() ) ); - params.setSide( Double.parseDouble( _sideTextField.getText() ) ); - params.setPeadj( Double.parseDouble( _peAdjustTextField.getText() ) ); - params.setPxadj( Double.parseDouble( _pxAdjustTextField.getText() ) ); - params.setEfc( Double.parseDouble( _efcTextField.getText() ) ); - - _dataMgr.saveParams( params ); - _sacSmaParameters = params; - refreshSacSmaParamsTable(); - - notifyAllApplyActionListeners(); // notifies all the listeners - } - catch ( NumberFormatException exception ) - { - DialogHelper.displayErrorDialog(null, - "There is a parsing error in your input", - "Error Message"); - - /* - JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - "Error Message", JOptionPane.ERROR_MESSAGE ); - */ - } - } - else - { - DialogHelper.displayErrorDialog(null, "Empty Strings are not allowed", - "Error Message"); - //JOptionPane.showMessageDialog( null, "Empty Strings are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - - private long getCurrentTime() - { - // Get's the current system time truncated to the nearest second. - long time = System.currentTimeMillis(); - - time /= 1000; - time *= 1000; - return time; - } - - } - - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } - - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - if ( _sacSmaParameters != null ) - { - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete this Parameter?", - "Delete Parameter"); - - if ( confirm ) - /* User selected YES */ - { - _dataMgr.deleteParams( _sacSmaParameters ); - _sacSmaParameters = null; - refreshSacSmaParamsTable(); - } - } - } - } - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } - - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if ( ! textField.getText().equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - DateTimeDialog dateTimeGUI = new DateTimeDialog( SacParamsEditor.this, dateTime, "Valid Time" ); - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - } - } - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = SacParamsEditor.this.getHeight(); - int width = SacParamsEditor.this.getWidth(); -// System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - SacParamsEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - SacParamsEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - SacParamsEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - SacParamsEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - public static void main(String[] args) - { - SacParamsEditor sacParamsGUI = new SacParamsEditor( new Frame(), new DataMgr(), "BLUZ2" ); - sacParamsGUI.show(); - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SacStateEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SacStateEditor.java deleted file mode 100644 index 0dc15bb27d..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SacStateEditor.java +++ /dev/null @@ -1,723 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * Filename : SacStateEditor.java - * Author : Gautam Sood - * Last Revision Date : Oct 23, 2003 - * - * - */ -package ohd.hseb.sshp.window; - - -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.table.TableColumn; - -import java.awt.*; -import java.awt.event.*; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.gui.*; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.sshp.DataMgr; - -import java.text.DecimalFormat; -import java.util.List; -import java.util.*; - -public class SacStateEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _sacStateListPanel = new JPanel(); - private JPanel _sacStateTextPanel = new JPanel(); - private JPanel _buttonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 14 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private List _sacStateList = null; - - private DataMgr _dataMgr = null; - private SacSmaState _sacSmaState = null; - - private static final int DEFAULT_WIDTH = 340; - private static final int DEFAULT_HEIGHT = 470; - - private static final int MAX_WIDTH = 500; - private static final int MAX_HEIGHT = 5000; - - private static final int MIN_WIDTH = 340; - private static final int MIN_HEIGHT = 450; - - - //JFrame owner - private JFrame _owner = null; - - //used for JFormattedTextFields - private static final String _threeDecimalFormatString = "0.000"; - private DecimalFormat _decimalFormat = new DecimalFormat( _threeDecimalFormatString ); - - private String _basinId = null; - - private JLabel _basinIDLabel = getJLabel( "Basin ID" ); - private JLabel _sourceLabel = getJLabel( "Source" ); - private JLabel _validTimeLabel = getJLabel( "Valid Time" ); - private JLabel _basisTimeLabel = getJLabel( "Basis Time" ); - private JLabel _uztwcLabel = getJLabel( "UZTWC" ); - private JLabel _uzfwcLabel = getJLabel( "UZFWC" ); - private JLabel _lztwcLabel = getJLabel( "LZTWC" ); - private JLabel _lzfscLabel = getJLabel( "LZFSC" ); - private JLabel _lzfpcLabel = getJLabel( "LZFPC" ); - private JLabel _adimcLabel = getJLabel( "ADIMC" ); - - private JTextField _basinIDTextField = getJTextField( 17 ); - private JTextField _sourceTextField = getJTextField( 17 ); - -// private JTextField _validTimeTextField = getJTextField( 17 ); -// private JTextField _basisTimeTextField = getJTextField( 17 ); - - private DateTimeTextField _validTimeTextField = null; - private DateTimeTextField _basisTimeTextField = null; - - private JFormattedTextField _uztwcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _uzfwcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lztwcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfscTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _lzfpcTextField = getJFormattedTextField( _threeDecimalFormatString ); - private JFormattedTextField _adimcTextField = getJFormattedTextField( _threeDecimalFormatString ); - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _exitButton = new JButton( "Close" ); - private JButton _clearButton = new JButton( "Clear" ); - - //used for custom notification - private List _applyListenerList = new ArrayList(); - - //used for the Table - private String[] _columnNames = { "Basin ID", "Source", "Valid Time" }; - private String[][] _sacStateStringArray = null; - private JTable _sacSmaStateTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _tableModel = null; - private ListSelectionModel _listSelectionModel = null; - - //used for sorting purposes - private String[] _dbColumnNames = { "basin_id", "source", "validtime" }; - private TableHelper _tableHelper = new TableHelper( _dbColumnNames ); - - public SacStateEditor( JFrame owner, DataMgr dataMgr ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, null, false ); - } - - public SacStateEditor( JFrame owner, DataMgr dataMgr, String basinId ) - /******************** - Purpose: Constructor - *********************/ - { - this( owner, dataMgr, basinId, false ); - } - - public SacStateEditor( JFrame owner, DataMgr dataMgr, String basinId, boolean isModal ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, isModal ); - this.setTitle( "SacSma State" ); - - _owner = owner; - _basinId = basinId; - _dataMgr = dataMgr; - initialize(); - } - - private void initialize() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - - long latestHourTime = TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(),1); - - _validTimeTextField = new DateTimeTextField(latestHourTime, _owner, "Valid Time", 17); - _basisTimeTextField = new DateTimeTextField(latestHourTime, _owner, "Basis Time", 17); - - - setupTable(); - - addSacStateListPanelComponents(); - addSacStateDataPanelComponents(); - addButtons(); - addFrameComponents(); - addListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - } - - private void setupTable() - { - int index = -1; - boolean foundBasinId= false; - - _tableHelper.setOrderByClause( 0 ); - _sacStateList = _dataMgr.loadSacSmaStateList( _tableHelper.getOrderByClause() ); - _sacStateStringArray = convertListToArray(); - - _tableModel = new SshpTableModel( _columnNames, _sacStateStringArray ); - _sacSmaStateTable = new JTable( _tableModel ); - _sacSmaStateTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _sacSmaStateTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - _listSelectionModel = _sacSmaStateTable.getSelectionModel(); - _scrollPane = new JScrollPane( _sacSmaStateTable ); - if ( _basinId != null ) - { - for ( int i = 0; i < _sacStateList.size(); i++ ) - { - SacSmaState sacSmaState = (SacSmaState) _sacStateList.get( i ); - - if ( _basinId.equalsIgnoreCase( sacSmaState.getBasinId().trim() ) ) - { - index = i; - foundBasinId = true; - _sacSmaState = sacSmaState; - break; - } - } - } - - if ( ! foundBasinId ) // If no basin ID found in the Params list, selects the first one by default. - { - if (_sacStateList.size() > 0) - { - _sacSmaState = (SacSmaState) _sacStateList.get( 0 ); - } - } - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaStateTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - if ( foundBasinId ) // Checks if a Basin Id was found - { - _listSelectionModel.setSelectionInterval( index, index ); - } - else - { - _listSelectionModel.setSelectionInterval( 0, 0 ); - } - Rectangle rect = _sacSmaStateTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - private void refreshSacSmaStateTable() - { - int index = 0; - - _sacStateList = _dataMgr.loadSacSmaStateList( _tableHelper.getOrderByClause() ); - - _sacStateStringArray = convertListToArray(); - - if ( _sacSmaState != null ) - { - for ( int i = 0; i < _sacStateList.size(); i++ ) - { - SacSmaState sacSmaState = (SacSmaState) _sacStateList.get( i ); - - if ( _sacSmaState.equals( sacSmaState ) ) - { - index = i; - break; - } - } - } - - _tableModel.updateData( _sacStateStringArray ); - _tableModel.fireTableChanged( null ); - - for( int i = 0; i < _columnNames.length; i++ ) - { - TableColumn column = _sacSmaStateTable.getColumnModel().getColumn( i ); - if ( i == 2 ) - { - column.setPreferredWidth( 150 ); - } - else - { - column.setPreferredWidth( 75 ); - } - } - - _listSelectionModel.setSelectionInterval( index, index ); - - Rectangle rect = _sacSmaStateTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - } - - private void addFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - _frameContentPane.setLayout( new GridBagLayout() ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _sacStateListPanel, 0, 0, 10, 15, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 15, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _sacStateTextPanel, 0, 17, 20, 15, 0, .4, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 32, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _buttonPanel, 0, 34, 20, 20, GridBagConstraints.BOTH ); - } - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _sacStateList.size() ][ _columnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - SacSmaState sacState = (SacSmaState) _sacStateList.get( i ); - - dataArray[ i ][ 0 ] = sacState.getBasinId(); - dataArray[ i ][ 1 ] = sacState.getSource(); - dataArray[ i ][ 2 ] = "" + DbTimeHelper.getDateTimeStringFromLongTime( sacState.getValidTime() ); - } - return dataArray; - } - - - private void addSacStateListPanelComponents() - /******************** - Purpose: Add's Components to the JTable Scroll Pane Panel - *********************/ - { - _sacStateListPanel.setLayout( new GridBagLayout() ); - - ComponentHelper.addPanelComponent( _sacStateListPanel, _scrollPane, 0, 0, 5, 25, 1, 1, GridBagConstraints.BOTH ); - - } - - - private void addSacStateDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the sacStateTextPanel - *********************/ - { - _sacStateTextPanel.setLayout( new GridBagLayout() ); - - _validTimeTextField.setEditable( false ); - _basisTimeTextField.setEditable( false ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basinIDLabel, 0, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basinIDTextField, 10, 0, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _sourceLabel, 0, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _sourceTextField, 10, 10, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _validTimeLabel, 0, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _validTimeTextField, 10, 20, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basisTimeLabel, 0, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _basisTimeTextField, 10, 30, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uztwcLabel, 0, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uztwcTextField, 10, 40, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uzfwcLabel, 0, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _uzfwcTextField, 10, 50, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lztwcLabel, 0, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lztwcTextField, 10, 60, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfscLabel, 0, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfscTextField, 10, 70, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfpcLabel, 0, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _lzfpcTextField, 10, 80, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _adimcLabel, 0, 90, 5, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _sacStateTextPanel, _adimcTextField, 10, 90, 5, 1, GridBagConstraints.BOTH ); - } - - private void addButtons() - /******************** - Purpose: add's the buttons to the button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - _buttonPanel.setLayout( new GridBagLayout() ); - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 20 ) ); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _buttonPanel, _saveButton, 2, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel, 4, 3, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _deleteButton, 8, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel2, 10, 3, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _clearButton, 14, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, verticalSeparatorPanel3, 16, 3, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, _exitButton, 20, 2, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _buttonPanel, horizontalSeparatorPanel, 0, 4, 22, 2, GridBagConstraints.BOTH ); - } - - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _sacSmaState != null ) - { - _basinIDTextField.setText( _sacSmaState.getBasinId() ); - _sourceTextField.setText( _sacSmaState.getSource() ); - _validTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sacSmaState.getValidTime() ) ); - _basisTimeTextField.setText( "" + DbTimeHelper.getDateTimeStringFromLongTime( _sacSmaState.getBasisTime() ) ); - _uztwcTextField.setText( getFormattedValue( _sacSmaState.getUztwc() ) ); - _uzfwcTextField.setText( getFormattedValue( _sacSmaState.getUzfwc() ) ); - _lztwcTextField.setText( getFormattedValue( _sacSmaState.getLztwc() ) ); - _lzfscTextField.setText( getFormattedValue( _sacSmaState.getLzfsc() ) ); - _lzfpcTextField.setText( getFormattedValue( _sacSmaState.getLzfpc() ) ); - _adimcTextField.setText( getFormattedValue( _sacSmaState.getAdimc() ) ); - } - else - { - _basinIDTextField.setText( "" ); - _sourceTextField.setText( "" ); - _validTimeTextField.setText( "yyyy-mm-dd hh:mm:ss" ); - _basisTimeTextField.setText( "yyyy-mm-dd hh:mm:ss" ); - _uztwcTextField.setText( "" ); - _uzfwcTextField.setText( "" ); - _lztwcTextField.setText( "" ); - _lzfscTextField.setText( "" ); - _lzfpcTextField.setText( "" ); - _adimcTextField.setText( "" ); - } - } - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - _clearButton.addActionListener( new ClearButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - // _basisTimeTextField.addMouseListener( new TimeTextFieldListener() ); - // _validTimeTextField.addMouseListener( new TimeTextFieldListener() ); - WindowCloserListener windowCloser = new WindowCloserListener(); - _exitButton.addActionListener( windowCloser ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _listSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _sacSmaStateTable.getTableHeader().addMouseListener( new TableSortingListener() ); - } - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _sacSmaStateTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _sacStateList.isEmpty() ) ) - { - _sacSmaState = (SacSmaState) _sacStateList.get( index ); - } - else - { - _sacSmaState = null; - } - loadTextFields(); - } - } - - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - int column = _sacSmaStateTable.getTableHeader().columnAtPoint( point ); - - _tableHelper.setOrderByClause( column ); - refreshSacSmaStateTable(); - } - } - - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - SacSmaState state = new SacSmaState(); - - if ( - ( ! isEmptyString( _basinIDTextField.getText() ) ) && - ( ! isEmptyString( _sourceTextField.getText() ) ) && - ( ! _validTimeTextField.getText().trim().equals( "yyyy-mm-dd hh:mm:ss" ) ) && - ( ! _basisTimeTextField.getText().trim().equals( "yyyy-mm-dd hh:mm:ss" ) ) - ) - { - try - { - state.setBasinId( _basinIDTextField.getText().trim() ); - state.setSource( _sourceTextField.getText().trim() ); - state.setValidTime( DbTimeHelper.getLongTimeFromDateTimeString( - _validTimeTextField.getText().trim() ) ); - state.setBasisTime( DbTimeHelper.getLongTimeFromDateTimeString( - _basisTimeTextField.getText().trim() ) ); - state.setPostingTime( getCurrentTime() ); - state.setUztwc( Double.parseDouble( _uztwcTextField.getText() ) ); - state.setUzfwc( Double.parseDouble( _uzfwcTextField.getText() ) ); - state.setLztwc( Double.parseDouble( _lztwcTextField.getText() ) ); - state.setLzfsc( Double.parseDouble( _lzfscTextField.getText() ) ); - state.setLzfpc( Double.parseDouble( _lzfpcTextField.getText() ) ); - state.setAdimc( Double.parseDouble( _adimcTextField.getText() ) ); - _dataMgr.saveState( state ); - _sacSmaState = state; - refreshSacSmaStateTable(); - notifyAllApplyActionListeners(); // notifies all the listeners - - } - catch ( NumberFormatException exception ) - { - DialogHelper.displayMessageDialog(null, - "There is a parsing error in your input", - "Error Message"); - //JOptionPane.showMessageDialog( null, "There is a parsing error in your input", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - else - { - DialogHelper.displayMessageDialog(null, - "Empty Strings/Dates are not allowed", - "Error Message"); - - //JOptionPane.showMessageDialog( null, "Empty Strings/Dates are not allowed", - // "Error Message", JOptionPane.ERROR_MESSAGE ); - } - } - - private long getCurrentTime() - { - // Get's the current system time truncated to the nearest second. - long time = System.currentTimeMillis(); - - time /= 1000; - time *= 1000; - return time; - } - } - - public void addApplyActionListener(ActionListener listener) - { - _applyListenerList.add(listener); - } - - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - if ( _sacSmaState != null ) - { - //choice = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete this State?", - // "Delete State", JOptionPane.YES_NO_OPTION, - // JOptionPane.WARNING_MESSAGE ); - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete this State?", - "Delete State" ); - - if ( confirm ) - { - _dataMgr.deleteState( _sacSmaState ); - _sacSmaState = null; - refreshSacSmaStateTable(); - } - } - } - } - - private class ClearButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - _sacSmaState = null; - loadTextFields(); - } - } - - private class DateTimeListener implements DateTimeEventListener - { - private JTextField _timeTextField = null; - - public DateTimeListener( JTextField timeTextField ) - { - _timeTextField = timeTextField; - } - - public void dateTimeEntered( DateTimeEvent dateTimeEvent ) - { - if ( dateTimeEvent.isGoodDate() ) - { - String timeString = DbTimeHelper.getDateTimeStringFromLongTime( dateTimeEvent.getDateTimeLong() ); - _timeTextField.setText( timeString ); - } - } - } - - /* - private class TimeTextFieldListener extends MouseAdapter - { - public void mousePressed( MouseEvent e ) - { - long dateTime = 0; - JTextField textField = (JTextField) e.getSource(); - - if ( ! textField.getText().equals( "yyyy-mm-dd hh:mm:ss" ) ) - { - dateTime = DbTimeHelper.getLongTimeFromDateTimeString( textField.getText() ); - } - else - { - dateTime = new Date().getTime(); - } - DateTimeDialog dateTimeGUI = null; - - if ( textField == _basisTimeTextField ) - { - dateTimeGUI = new DateTimeDialog( SacStateEditor.this, dateTime, "Basis Time" ); - } - else - { - dateTimeGUI = new DateTimeDialog( SacStateEditor.this, dateTime, "Valid Time" ); - } - dateTimeGUI.addDateTimeEventListener( new DateTimeListener( textField ) ); - dateTimeGUI.show(); - } - } - */ - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = SacStateEditor.this.getHeight(); - int width = SacStateEditor.this.getWidth(); - -// System.err.println( width + "\n" + height ); - if ( width < MIN_WIDTH ) - { - SacStateEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - SacStateEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - SacStateEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - SacStateEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - } - } - - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - - private void closeWindow() - /******************** - Purpose: closes the window - *********************/ - { - this.dispose(); - } - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - return returnJTextField; - } - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - public static void main(String[] args) - { - SacStateEditor sacStateGUI = new SacStateEditor( new JFrame(), new DataMgr(), "BLUO2" ); - sacStateGUI.show(); - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SshpTableModel.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SshpTableModel.java deleted file mode 100644 index 61f09fa575..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/SshpTableModel.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Created on Feb 12, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Feb 12, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import javax.swing.table.DefaultTableModel; - -public class SshpTableModel extends DefaultTableModel -{ - private String[] _columnNames = null; - - private Object[][] _data = null; - - public SshpTableModel( String[] colNames, String[][] dataStringArray ) - { - _columnNames = colNames; - _data = dataStringArray; - } - - public void updateData( String[][] dataStringArray ) - { - _data = dataStringArray; - } - - public int getColumnCount() - { - return _columnNames.length; - } - - public int getRowCount() - { - if ( _data != null ) - { - return _data.length; - } - else - { - return 0; - } - } - - public String getColumnName(int col) - { - return _columnNames[col]; - } - - public Object getValueAt(int row, int col) - { - return _data[row][col]; - } - - public boolean isCellEditable(int row, int col) - { - return false; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographCanvasPanel.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographCanvasPanel.java deleted file mode 100644 index b191694935..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographCanvasPanel.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Created on Aug 23, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.TableColumnComparator; -import ohd.hseb.util.gui.drawing.DataPointCanvas; - -/** - * @author GobsC - * This class owns and controls the UnitHydrographCanvasAdapter and the - * UnitHydrographDescriptorTableAdapter, and so, by delegation, - * owns their Canvas and Table. It also is the messenger between the - * rest of the UnitHydrographEditor and its components. - * - */ -public class UnitHydrographCanvasPanel extends JPanel -{ - private List _descriptorList = null; - - //This is needed by the UnitHydrographDataPointCanvasAdapter - //and the UnitHydrographDescriptorTableAdapter, so - //this class will manage it. - private List _displayedDescriptorList = null; - - private UnitHydrographDescriptorTableAdapter _tableAdapter = null; - //private JPanel _canvasButtonPanel = new JPanel(); - - - - private UnitHydrographDataPointCanvasAdapter _canvasAdapter = null; - private DataPointCanvas _canvas = null; - - public static final String AREA_ID = "Area ID"; - public static final String MODEL = "Model"; - public static final String DURATION = "Duration"; - - - public UnitHydrographCanvasPanel(List unitHydrographEntryList) - { - Dimension minCanvasSize = new Dimension( 700, 750 ); - Dimension minScrollPaneSize = new Dimension( 700, 250 ); - Dimension minCanvasPanelSize = new Dimension( 700, 1000 ); - - - Dimension prefCanvasSize = new Dimension( 700, 750 ); - Dimension prefScrollPaneSize = new Dimension( 700, 250 ); - Dimension prefCanvasPanelSize = new Dimension( 700, 1000 ); - - - - // - this.setLayout( new GridBagLayout() ); - this.setPreferredSize( prefCanvasPanelSize ); - this.setMinimumSize(minCanvasPanelSize); - // this.setBackground(Color.blue); - - _descriptorList = - UnitHydrographDescriptor.createUnitHydrographDescriptorList( - unitHydrographEntryList); - - _displayedDescriptorList = new ArrayList(); - - //objects for the drawing - _canvasAdapter = new UnitHydrographDataPointCanvasAdapter(); - _canvas = _canvasAdapter.initCanvas(_descriptorList); - _canvas.setPreferredSize(prefCanvasSize ); - _canvas.setMinimumSize(minCanvasSize ); - - _tableAdapter = createDescriptorTableAdapter(_descriptorList); - JScrollPane tableScrollPane = _tableAdapter.getScrollPane(); - tableScrollPane.setPreferredSize(prefScrollPaneSize); - tableScrollPane.setMinimumSize(minScrollPaneSize); - - //select the first descriptor in the list - - if (_tableAdapter.getDescriptorCount() > -1) - { - _tableAdapter.setSelectedIndex(0); - UnitHydrographDescriptor descriptor = _tableAdapter.getDescriptorByIndex(0); - _displayedDescriptorList.add(descriptor); - } - - //button panel for the canvas - // _canvasButtonPanel.setLayout(new GridBagLayout() ); - // _canvasButtonPanel.setLayout(new FlowLayout() ); - // _canvasButtonPanel.setPreferredSize(prefCanvasButtonPanelSize ); - // _canvasButtonPanel.setMinimumSize(minCanvasButtonPanelSize ); - - //separators for appearance - JPanel horizontalSeparatorPanel = new JPanel(); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - - JPanel verticalSeparatorPanel = new JPanel(); - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - - GridBagConstraints gbc = new GridBagConstraints(); - //gbc.insets = new Insets(20, 0, 20, 0); - - - gbc.fill = 1; - gbc.insets = new Insets(0, 0, 0, 0); - gbc.weightx = 1.0; - gbc.weighty = 1.0; - - //add components to the canvasPanel - ComponentHelper.addPanelComponent( this, _canvas, gbc, 0, 0, 1, 10, GridBagConstraints.BOTH ); - - - gbc.anchor = GridBagConstraints.NORTH; - ComponentHelper.addPanelComponent( this, tableScrollPane , gbc, 0, 11, 1, 8, GridBagConstraints.BOTH ); - - - addListeners(); - - } - - public void addListeners() - { - _tableAdapter.getListSelectionModel().addListSelectionListener( new DescriptorRowSelectionListener() ); - } - - - - private UnitHydrographDescriptorTableAdapter createDescriptorTableAdapter(List descriptorList) - { - JTable table = null; - String[] columnNameArray = { AREA_ID, MODEL, DURATION }; - UnitHydrographDescriptorTableAdapter tableAdapter = null; - - TableColumnComparator comparator = new UnitHydrographDescriptorComparator(); - - - tableAdapter = new UnitHydrographDescriptorTableAdapter(comparator, columnNameArray, descriptorList ); - - return tableAdapter; - - } - // ------------------------------------------------------------------------------------- - - public void refreshData(List unitHydrographEntryList) - { - //CodeTracer tracer = new CodeTracer(); - //tracer.trace(); - - _descriptorList = UnitHydrographDescriptor.createUnitHydrographDescriptorList(unitHydrographEntryList); - - //save off this list, since the refreshTableModel command will call the - //listener, which will overwrite the contents of _displayDiscriptorList - List tempDisplayDescriptorList = new ArrayList(_displayedDescriptorList); - - - _tableAdapter.refreshTableModel(_descriptorList); - - //pull out the origin displayDescriptorList - -// creates own descriptorList, for coding reasons, from the unitHydrographEntryList - _canvasAdapter.refreshCanvas(unitHydrographEntryList); - - _displayedDescriptorList = tempDisplayDescriptorList; - - _tableAdapter.selectItems(_displayedDescriptorList); - } - - // ------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------- - private class DescriptorRowSelectionListener implements - ListSelectionListener - { - - public void valueChanged(ListSelectionEvent event) - { - - String header = "DescriptorRowSelectionListener.valueChanged(): "; - UnitHydrographDescriptor descriptor = null; - JTable table = _tableAdapter.getTable(); - - // for each from in the table, reset the shouldPaints in the - // canvasAdapter - - // clear out the displayed Descriptor list - _displayedDescriptorList.clear(); - - for (int i = 0; i < table.getRowCount(); i++) - { - boolean isSelected = table.isRowSelected(i); - - descriptor = _tableAdapter.getDescriptorByIndex(i); - - if ( descriptor != null ) - { - //maintain the list of selected items - if (isSelected) - { - _displayedDescriptorList.add(descriptor); - } - - _canvasAdapter.setPainterShouldPaint(descriptor, isSelected); - - // System.out.println(header + "descriptor = " + descriptor - // + " shouldPaint = " + isSelected); - } - } - - _canvasAdapter.redrawCanvas(); - - - } - } - // ------------------------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDataPointCanvasAdapter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDataPointCanvasAdapter.java deleted file mode 100644 index 0f45733cd7..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDataPointCanvasAdapter.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Created on Jul 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Comparator; -import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasurementPoint; -import ohd.hseb.measurement.MeasurementPointComparator; -import ohd.hseb.measurement.MeasurementPointSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.model.DurationCode; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.gui.drawing.DataPointCanvasBackgroundPainter; -import ohd.hseb.util.gui.drawing.DataCurvePainter; -import ohd.hseb.util.gui.drawing.DataPointCanvas; -import ohd.hseb.util.gui.drawing.DataPointCanvasAdapter; -import ohd.hseb.util.gui.drawing.ScalingHelper; - -/** - * @author GobsC - * This class helps the user to use the DataPointCanvas class from within The UnitHydrographEditor - * dialog. It serves to keep all of the drawing-related code together. - * - */ -public class UnitHydrographDataPointCanvasAdapter implements DataPointCanvasAdapter -{ - private List _unitHydrographDescriptorList = null; - - private DataPointCanvas _canvas = null; - private DataPointCanvasBackgroundPainter _dataBackgroundPainter = null; - - private DataCurvePainter[] _curvePainterArray = null; - - private MeasurementPointSeries[] _measurementPointSeriesArray = null; - - private MeasuringUnit _xUnit = MeasuringUnit.hours; - private MeasuringUnit _yUnit = MeasuringUnit.cfs; - - private static final Color[] _colorCurveArray = {Color.YELLOW, - Color.RED, - Color.BLUE, - Color.CYAN, - Color.MAGENTA, - Color.GREEN, - Color.ORANGE, - Color.GRAY, - Color.PINK}; - - - //------------------------------------------------------------------------------------- - - public UnitHydrographDataPointCanvasAdapter() - { - - - } -//------------------------------------------------------------------------------------- - public DataPointCanvas initCanvas(Object initializationObject) - { - _unitHydrographDescriptorList = (List) initializationObject; - - - - int x = 0; - int y = 0; - int width = 700; - int height = 700; - - MeasuringUnit dischargeUnit = MeasuringUnit.cfs; - MeasuringUnit timeUnit = MeasuringUnit.hours; - - // scaling helpers end up affecting the overall viewport window and - // what numbers are displayed for major and minor tick marks by painter - ScalingHelper horizontalScalingHelper = new ScalingHelper(0.0, 0.0); - ScalingHelper verticalScalingHelper = new ScalingHelper(0.0, 0.0); - - double[] niceMinorIncrementArray = {1, 2, 4, 8, 12, 24 }; - horizontalScalingHelper.setNiceMinorIncrementArray(niceMinorIncrementArray); - - double[] niceMajorIncrementArray = { 6, 12, 24, 48, 96, 120 }; - horizontalScalingHelper.setNiceMajorIncrementArray(niceMajorIncrementArray); - - horizontalScalingHelper.setBaseFactorStartingPoint(1.0); - - - _canvas = new DataPointCanvas(timeUnit, dischargeUnit, - x, y, - width, height, - horizontalScalingHelper, - verticalScalingHelper); - - _canvas.setPreferredSize(new Dimension(width, height)); - _canvas.setMinimumSize(new Dimension(width, height)); - - - Color outlineColor = Color.WHITE; - - - // background Painter - _dataBackgroundPainter = - new DataPointCanvasBackgroundPainter(outlineColor, _canvas, - "hours", "cfs", - horizontalScalingHelper, - verticalScalingHelper); - - _dataBackgroundPainter.setShowMinorHorizontalTicks(true); - _dataBackgroundPainter.setShowMinorVerticalTicks(true); - - // this painter is not to be used for determining scaling, - //so, this is just considered a plain-old CanvasPainter, - // instead of a DataPointCanvasPainter - _canvas.addCanvasPainter(_dataBackgroundPainter); - - - initMeasurementPointSeriesAndPainters(_unitHydrographDescriptorList); - - - //overall canvas settings - _canvas.setTitle("Unit Hydrograph"); - _canvas.addMouseMotionListener(new CanvasMouseMotionListener(_canvas)); - - return _canvas; - - } //end initCanvas - // ------------------------------------------------------------------------------------- - private void addBackgroundPainter() - { - - - } - - // ------------------------------------------------------------------------------------- - - public void redrawCanvas() - { - _canvas.refresh(); - } - - public void refreshCanvas(Object dataObject) - { - List unitHydrographEntryList = (List) dataObject; - loadCanvasWithData(unitHydrographEntryList); - _canvas.refresh(); - } - // ------------------------------------------------------------------------------------- - public void setPainterShouldPaint(UnitHydrographDescriptor descriptor, boolean shouldPaint) - { - int index = findIndexOfDescriptor(descriptor); - - if (index > -1) - { - DataCurvePainter painter = _curvePainterArray[index]; - - painter.setShouldPaint(shouldPaint); - } - } - // ------------------------------------------------------------------------------------- - - - private void initMeasurementPointSeriesAndPainters(List unitHydrographDescriptorList) - { - // init the drawing variables - boolean compareXValues = true; - boolean ascendingOrder = true; - Comparator comparator = new MeasurementPointComparator(compareXValues, ascendingOrder); // compare X values - - - - int listSize = unitHydrographDescriptorList.size(); - _curvePainterArray = new DataCurvePainter[listSize]; - _measurementPointSeriesArray = new MeasurementPointSeries[listSize]; - - for (int i = 0; i < _measurementPointSeriesArray.length; i++) - { - MeasurementPointSeries series = new MeasurementPointSeries(_xUnit, - _yUnit, comparator); - _measurementPointSeriesArray[i] = series; - } - - - //remove all the paints and re-add the background painter - _canvas.removeAllDataPointCanvasPainters(); - - if (_dataBackgroundPainter != null) - { - _canvas.addCanvasPainter(_dataBackgroundPainter); - } - - - // painter creation Loop - // there is 1 MeasurementPointSeries per painter - // There is 1 MeasurementPointSeries per UnitHydrographDescriptor - for (int i = 0; i < _measurementPointSeriesArray.length; i++) - { - MeasurementPointSeries series = _measurementPointSeriesArray[i]; - Color curveColor = getCurveColor(i); - - DataCurvePainter painter = new DataCurvePainter(series, _canvas, - curveColor); - - _curvePainterArray[i] = painter; - _canvas.addDataPointCanvasPainter(painter); - painter.setShouldPaint(false); - - } - - } //end initMeasurementPointSeries - - // ------------------------------------------------------------------------------------- - - private class CanvasMouseMotionListener extends MouseMotionAdapter - { - private DataPointCanvas _canvas2 = null; - - public CanvasMouseMotionListener(DataPointCanvas canvas) - { - _canvas2 = canvas; - } - - public void mouseMoved(MouseEvent event) - { - - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas2.getViewport().getDataPoint(screenPoint); - - - if (_canvas2.getViewport().isViewable(dataPoint)) - { - updateCanvasDataPointText(dataPoint, _canvas); - } - } - - } - -// ------------------------------------------------------------------------------------- - - - public void updateCanvasDataPointText(DataPoint dataPoint, - DataPointCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String xUnitString = canvas.getDisplayedXMeasuringUnit().toString(); - String yUnitString = canvas.getDisplayedYMeasuringUnit().toString(); - - String message = getCanvasDataPointString(dataPoint, xUnitString, - yUnitString); - - canvas.setToolTipText(message); - - return; - } - -// ------------------------------------------------------------------------------------- - - private String getCanvasDataPointString(DataPoint dataPoint, - String xUnitString, - String yUnitString) - { - NumberFormat nfX = new DecimalFormat("###"); - - long hour = (long) Math.round(dataPoint.getX()); - String xValueString = nfX.format(hour); - - NumberFormat nfY = new DecimalFormat("###.##"); - String yValueString = nfY.format(dataPoint.getY()); - - String dataPointString = xValueString + " " + xUnitString + " , " - + yValueString + " " + yUnitString; - - return dataPointString; - } -// ------------------------------------------------------------------------------------- - - private Color getCurveColor(int index) - { - if (index >= _colorCurveArray.length) - { - index = index % _colorCurveArray.length; - } - - return _colorCurveArray[index]; - } - - // ------------------------------------------------------------------------------------- - private int findIndexOfDescriptor(UnitHydrographDescriptor desc) - { - int index = _unitHydrographDescriptorList.indexOf(desc); - - return index; - } - // ------------------------------------------------------------------------------------- - private void loadCanvasWithData(List uhgList) - { - - - int measurementPointSeriesIndex = 0; - - _unitHydrographDescriptorList = - UnitHydrographDescriptor.createUnitHydrographDescriptorList(uhgList); - - initMeasurementPointSeriesAndPainters(_unitHydrographDescriptorList); - - - boolean loadApiModel = true; - - Measurement ordinalMeasurement = null; - Measurement dischargeMeasurement = null; - MeasurementPoint point = null; - - - // load the various MeasurementPointSeries with their data - for (int i = 0; i < uhgList.size(); i++) - { - UnitHydrographEntry uhgEntry = (UnitHydrographEntry) uhgList.get(i); - - // add Measurement Points to the points for the unitHydrograph - int hourInterval = DurationCode.getHoursFromCode(uhgEntry.getDur()); - - ordinalMeasurement = new Measurement(uhgEntry.getOrdinal()*hourInterval, _xUnit); - dischargeMeasurement = new Measurement(uhgEntry.getDischarge(),_yUnit); - - point = new MeasurementPoint(ordinalMeasurement, - dischargeMeasurement); - - //find the right measurement point series and add the point to it - measurementPointSeriesIndex = findMeasurementPointSeriesIndexByEntry(uhgEntry); - MeasurementPointSeries series = _measurementPointSeriesArray[measurementPointSeriesIndex]; - if (series != null) - { - series.addPoint(point); - } - } - - - // make sure that the MeasurementPointSeries end in a 0 discharge - // the last Y measurement needs to be 0 for graphing the unitgraph, so - // that - // the scaling does not start, at say, 10, instead of 0 - - for (int i = 0; i < _measurementPointSeriesArray.length; i++) - { - ensureMeasurementSeriesStartsAndEndsInZero(_measurementPointSeriesArray[i]); - } - - } - - // ------------------------------------------------------------------------------------- - private int findMeasurementPointSeriesIndexByEntry(UnitHydrographEntry uhgEntry) - { - int index = -1; - - for (int i = 0; i < _unitHydrographDescriptorList.size(); i++) - { - UnitHydrographDescriptor descriptor = (UnitHydrographDescriptor) - _unitHydrographDescriptorList.get(i); - if (descriptor.isMatchingEntry(uhgEntry)) - { - index = i; - break; - } - } - - return index; - } - // ------------------------------------------------------------------------------------- - - private void ensureMeasurementSeriesStartsAndEndsInZero(MeasurementPointSeries series) - { - MeasurementPoint lastPoint = null; - int lastIndex = series.size() - 1; - - - if (lastIndex >= 0) - { - lastPoint = series.getPoint(lastIndex); - - Measurement lastXMeasurement = lastPoint.getXMeasurement(); - Measurement lastYMeasurement = lastPoint.getYMeasurement(); - - MeasuringUnit xUnit = lastXMeasurement.getUnit(); - MeasuringUnit yUnit = lastYMeasurement.getUnit(); - - Measurement firstXMeasurement = new Measurement(0.0, xUnit); - Measurement firstYMeasurement = new Measurement(0.0, yUnit); - - //add a (0.0, 0.0) first point to the series - MeasurementPoint firstPoint = new MeasurementPoint(firstXMeasurement, firstYMeasurement); - series.addPoint(firstPoint); - - lastPoint = series.getPoint(lastIndex); - - - if (lastYMeasurement.getValue() != 0) - { - Measurement newYMeasurement = new Measurement(0.0, - yUnit); - - - double newXValue = lastXMeasurement.getValue() + 1.0; - Measurement newXMeasurement = new Measurement(newXValue, - xUnit); - - MeasurementPoint newLastPoint = new MeasurementPoint( - newXMeasurement, newYMeasurement); - series.addPoint(newLastPoint); - } - } - - - - - return; - - } - // ------------------------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorComparator.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorComparator.java deleted file mode 100644 index e5a3512368..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorComparator.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author GobsC - * - */ -public class UnitHydrographDescriptorComparator extends TableColumnComparator -{ - public UnitHydrographDescriptorComparator() - { - } - - - public int compareArea_Id( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - int result = entry1.getAreaId().compareToIgnoreCase( entry2.getAreaId() ); - return result; - } - - public int compareModel( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareStrings( entry1.getModel(), entry2.getModel() ) ); - } - - public int compareDuration( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getDur(), entry2.getDur() ) ); - } - - - public int compare(Object object1, Object object2) - { - UnitHydrographEntry entry1 = (UnitHydrographEntry) object1; - UnitHydrographEntry entry2 = (UnitHydrographEntry) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( UnitHydrographEditor.AREA_ID ) ) - { - returnValue = compareArea_Id( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.MODEL ) ) - { - returnValue = compareModel( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.DURATION ) ) - { - returnValue = compareDuration( entry1, entry2 ); - } - - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorTableAdapter.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorTableAdapter.java deleted file mode 100644 index a66a9af4b4..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographDescriptorTableAdapter.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Created on Aug 19, 2004 - * - * - */ -package ohd.hseb.sshp.window; - -import java.util.List; - -import ohd.hseb.model.DurationCode; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.sshp.gui.TableAdapter; -import ohd.hseb.util.gui.TableColumnComparator; - - -/** - * @author GobsC - * - * - */ -public class UnitHydrographDescriptorTableAdapter extends TableAdapter -{ - - private UnitHydrographDescriptor _descriptor = null; - private List _descriptorList = null; - - // --------------------------------------------------------------------------------- - - - - public UnitHydrographDescriptorTableAdapter(TableColumnComparator comparator, - String[] columnNameArray, - List dataList) - { - super(comparator, columnNameArray, dataList); - - setAllowMultipleSelection(true); - - } - - // --------------------------------------------------------------------------------- - public String[][] getDataStringArrayFromDataList(List dataList) - { - int fieldCount = 3; - String[][] dataArray = new String[dataList.size()][fieldCount]; - - - for (int i = 0; i < dataList.size(); i++) - { - UnitHydrographDescriptor desc = (UnitHydrographDescriptor) dataList.get(i); - dataArray[i][0] = desc.getBasinId(); - dataArray[i][1] = desc.getModel(); - dataArray[i][2] = "" + DurationCode.getHoursFromCode(desc.getDuration()); - } - - return dataArray; - - } - // --------------------------------------------------------------------------------- - public void refreshTableModel(List dataList) - { - setDataList(dataList);// for super class - - _descriptorList = dataList; - - String[][] dataStringArray = getDataStringArrayFromDataList(dataList); - getTableModel().updateData( dataStringArray ); - getTableModel().fireTableChanged( null ); - - - return; - - } - // --------------------------------------------------------------------------------- - - public int getDescriptorCount() - { - int count = getDataList().size(); - return count; - } - - // --------------------------------------------------------------------------------- - - public UnitHydrographDescriptor getDescriptorByIndex(int index) - { - List dataList = getDataList(); - UnitHydrographDescriptor desc = null; - - if ( dataList.size() > 0 ) - { - Object object = dataList.get(index); - desc = (UnitHydrographDescriptor) object; - } - return desc; - } - - // --------------------------------------------------------------------------------- - - private int findIndexOfDescriptor(UnitHydrographDescriptor desc) - { - int index = _descriptorList.indexOf(desc); - - return index; - } - // ------------------------------------------------------------------------------------- - public void setDataList(List dataList) - { - - super.setDataList(dataList); - _descriptorList = dataList; - - } - - // --------------------------------------------------------------------------------- - - - private void selectAll() - { - - getListSelectionModel().setSelectionInterval(0, getTable().getModel().getRowCount()-1); - } - - - // --------------------------------------------------------------------------------- - public void setSelectedIndex(int index) - { - - getListSelectionModel().setSelectionInterval(index, index); - - } - // --------------------------------------------------------------------------------- - - public void selectItems(List selectedDescriptorList) - { - getListSelectionModel().clearSelection(); - - for (int i = 0; i < selectedDescriptorList.size(); i++) - { - UnitHydrographDescriptor descriptor = (UnitHydrographDescriptor) selectedDescriptorList.get(i); - - int index = findIndexOfDescriptor(descriptor); - - if (index >= 0) - { - getListSelectionModel().setSelectionInterval(index, index); - - } - } - } - // --------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographEditor.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographEditor.java deleted file mode 100644 index 4b026a2671..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographEditor.java +++ /dev/null @@ -1,1634 +0,0 @@ -/* - * Created on June 08, 2004 - * - * Filename : UnitHydrographEditor.java - * Author : Gautam Sood - * Modified by: Chip Gobs (addition of graphics and the table to control them). - * Purpose: Display GUI for Unit Hydrograph. - * Last Revision Date : October 8, 2004 - * - */ - -package ohd.hseb.sshp.window; - -import javax.swing.*; -import javax.swing.event.*; - -import java.awt.*; -import java.awt.event.*; -import java.io.*; - -import ohd.hseb.model.DurationCode; -import ohd.hseb.model.RainfallRunoffModelType; -import ohd.hseb.model.UnitHydrographDescriptor; -import ohd.hseb.model.UnitHydrographEntry; - - -import ohd.hseb.sshp.DataMgr; - -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.gui.ComponentHelper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; -import ohd.hseb.util.gui.OptionSelectionDialog; -import ohd.hseb.util.gui.TableHelper2; -import ohd.hseb.util.StringParser; - -import java.text.DecimalFormat; -import java.util.List; -import java.util.*; - -public class UnitHydrographEditor extends JDialog -{ - private Container _frameContentPane = getContentPane(); - - private JPanel _uhgListPanel = new JPanel(); - private JPanel _uhgTextPanel = new JPanel(); - private JPanel _listButtonPanel = new JPanel(); - private JPanel _dialogButtonPanel = new JPanel(); - - private Font _labelFont = new Font( "Helvetica", Font.BOLD, 13 ); - private Font _textFieldFont = new Font( "Helvetica", Font.PLAIN, 12 ); - - private List _uhgList = null; - private List _uhgEntryAddModifyDeleteList = new ArrayList(); - - private DataMgr _dataMgr = null; - private UnitHydrographEntry _unitHydrographEntry = null; - - private String _locationId = null; - - private String _connectionString = null; - private FileLogger _logger = null; - - private static final int DEFAULT_WIDTH = 1200; - private static final int DEFAULT_HEIGHT = 800; //909 - - private static final int MAX_WIDTH = 1200; - private static final int MAX_HEIGHT = 1000; - - private static final int MIN_WIDTH = 545; - private static final int MIN_HEIGHT = 500; - - //used for JFormattedTextFields - private static final String _decimalFormatString = "0.0"; - private DecimalFormat _decimalFormat = new DecimalFormat( _decimalFormatString ); - - private JLabel _areaIdLabel = getJLabel( "Area ID" ); - private JLabel _durationLabel = getJLabel( "Duration" ); - private JLabel _ordLabel = getJLabel( "Ordinal" ); - private JLabel _dischargeLabel = getJLabel( "Discharge" ); - - private JLabel _modelLabel = getJLabel( "Model" ); - - - private static final String[] _modelStringArray = {"ANY", "API-MKC", "SAC-SMA" }; - private JComboBox _modelComboBox = new JComboBox( _modelStringArray ); - - private static final String[] _durationStringArray = { "1", "6" }; - private JComboBox _durationComboBox = new JComboBox (_durationStringArray); - - private JTextField _areaIdTextField = getJTextField( 13 ); - private JTextField _ordTextField = getJTextField( 13 ); - private JTextField _dischargeTextField = getJTextField( 13 ); - - - private JButton _saveButton = new JButton( "Save" ); - private JButton _deleteButton = new JButton( "Delete" ); - private JButton _closeButton = new JButton( "Close" ); - private JButton _addButton = new JButton( "Add" ); - private JButton _modifyButton = new JButton( "Modify" ); - private JButton _removeButton = new JButton( "Remove" ); - private JButton _importButton = new JButton( "Import" ); - private JButton _exportButton = new JButton( "Export" ); - - - //used for custom notification - private List _applyListenerList = new ArrayList(); - - - //used for the row and master Tables - public static final String AREA_ID = "Area ID"; - public static final String MODEL = "Model"; - public static final String DURATION = "Duration"; - - //used for the row table - public static final String ORDINAL = "Ordinal"; - public static final String DISCHARGE = "Discharge"; - - public static final String DISPLAY = "Display"; - - - private String[] _rowTableColumnNames = { AREA_ID, MODEL, DURATION, ORDINAL, DISCHARGE }; - private int _lastColumnSorted = 0; - - private String[][] _unitHydrographStringArray = null; - - private JTable _uhgRowJTable = null; - private JScrollPane _scrollPane = null; - private SshpTableModel _rowTableModel = null; - private ListSelectionModel _rowListSelectionModel = null; - - private boolean _needsSaving = false; - - private String _importDirString = null; - private String _exportDirString = null; - private String _fileChooserDirectory = null; - - //used for sorting the Table - private UnitHydrographEntryComparator _comparator = new UnitHydrographEntryComparator(); - - private TableHelper2 _tableHelper = new TableHelper2( _comparator, _rowTableColumnNames ); - - - // ---- picture related objects ----------------------------------------------- - //canvas Panel - private UnitHydrographCanvasPanel _canvasPanel = null; - - // ------------------------------------------------------------------------------------- - - public UnitHydrographEditor() - { - } - - public UnitHydrographEditor( Frame owner, DataMgr dataMgr, String locationId, boolean isModal ) - /******************** - Purpose: Constructor - *********************/ - { - super( owner, isModal ); - _locationId = locationId; - this.setTitle( "Unit Hydrograph - " + _locationId ); - _dataMgr = dataMgr; - - AppsDefaults ad = new AppsDefaults(); - _importDirString = ad.getToken("whfs_import_dir"); - - initGui(); - } - // ------------------------------------------------------------------------------------- - - private void initGui() - /******************** - Purpose: Initializes the GUI by calling the appropriate methods - *********************/ - { - - // init the rest of the variables - initJTable(); - - // initialize the drawing area (canvas) panel - _canvasPanel = new UnitHydrographCanvasPanel(_uhgList); - - - initUnitHydrographJTableComponents(); - initUnitHydrographDataPanelComponents(); - initListButtons(); - initDialogButtons(); - initFrameComponents(); - - addListeners(); - - setSize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); - - //set the initial sort to the "model" column - initializeTableSort(); - - //let the sort take visual effect - refreshUnitHydrographTable(); - - - return; - } - // ------------------------------------------------------------------------------------- - private int getColumnIndex(String columnName) - { - //this does NOT keep track of whether the column has been moved graphically - int index = -1; - - for (int i = 0; i < _rowTableColumnNames.length; i++) - { - if (_rowTableColumnNames[i].equalsIgnoreCase(columnName)) - { - index = i; - break; - } - } - - return index; - } - // ------------------------------------------------------------------------------------- - private List loadUhgList() - { - - List list = _dataMgr.loadUnitHydrographEntryList( _locationId, "ORDER BY ordinal" ); - - return list; - } - - // ------------------------------------------------------------------------------------- - - private void initJTable() - { - int index = 0; - final String header = "UnitHydrographEditor.setupTables(): "; - _uhgList = loadUhgList(); - _unitHydrographStringArray = convertListToArray(); - if ((_uhgList != null) && ( _uhgList.size() != 0 )) - { - _unitHydrographEntry = (UnitHydrographEntry) _uhgList.get( 0 ); - } - - _rowTableModel = new SshpTableModel( _rowTableColumnNames, _unitHydrographStringArray ); - _uhgRowJTable = new JTable( _rowTableModel ); - _uhgRowJTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - _uhgRowJTable.setPreferredScrollableViewportSize( new Dimension( 300, 100 ) ); - - _rowListSelectionModel = _uhgRowJTable.getSelectionModel(); - _rowListSelectionModel.setSelectionInterval( index, index); - - Rectangle rect = _uhgRowJTable.getCellRect(index, 0, true); - _scrollPane = new JScrollPane( _uhgRowJTable ); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - loadTextFields(); - - } - - // ------------------------------------------------------------------------------------- - - - // ------------------------------------------------------------------------------------- - - private void refreshUnitHydrographTable() - { - int index = 0; - - - //find index of matching entry - if ( _unitHydrographEntry != null ) - { - for ( int i = 0; i < _uhgList.size(); i++ ) - { - UnitHydrographEntry uhgEntry = (UnitHydrographEntry) _uhgList.get( i ); - - if ( _unitHydrographEntry.hasEqualKey( uhgEntry ) ) - { - index = i; - break; - } - } - } - - //update the Jtable with the just-loaded data from the DB - _unitHydrographStringArray = convertListToArray(); - _rowTableModel.updateData( _unitHydrographStringArray ); - _rowTableModel.fireTableChanged( null ); - - //have the one item be selected - _rowListSelectionModel.setSelectionInterval( index, index ); - - //make sure that the item is visible - Rectangle rect = _uhgRowJTable.getCellRect(index, 0, true); - _scrollPane.getViewport().setViewPosition(rect.getLocation()); - - //load up the data entry fields - loadTextFields(); - - //give the canvas the latest data - it will then redraw - _canvasPanel.refreshData(_uhgList); - - return; - } - - // ------------------------------------------------------------------------------------- - private String[][] convertMasterListToArray() - { - String[][] dataArray = new String[ _uhgList.size() ][ _rowTableColumnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - UnitHydrographEntry unitHydrographEntry = (UnitHydrographEntry) _uhgList.get( i ); - - dataArray[ i ][ 0 ] = unitHydrographEntry.getAreaId(); - dataArray[ i ][ 1 ] = "" + unitHydrographEntry.getModel(); - dataArray[ i ][ 2 ] = "" + unitHydrographEntry.getDur(); - dataArray[ i ][ 3 ] = "" + unitHydrographEntry.getOrdinal(); - dataArray[ i ][ 4 ] = "" + unitHydrographEntry.getDischarge(); - } - return dataArray; - } - - - private String[][] convertListToArray() - { - String[][] dataArray = new String[ _uhgList.size() ][ _rowTableColumnNames.length ]; - - for( int i = 0; i < dataArray.length; i++ ) - { - UnitHydrographEntry unitHydrographEntry = (UnitHydrographEntry) _uhgList.get( i ); - - dataArray[ i ][ 0 ] = unitHydrographEntry.getAreaId(); - dataArray[ i ][ 1 ] = "" + unitHydrographEntry.getModel(); - dataArray[ i ][ 2 ] = "" + DurationCode.getHoursFromCode(unitHydrographEntry.getDur()); - dataArray[ i ][ 3 ] = "" + unitHydrographEntry.getOrdinal(); - dataArray[ i ][ 4 ] = "" + unitHydrographEntry.getDischarge(); - } - return dataArray; - } - // ------------------------------------------------------------------------------------- - - private void initFrameComponents() - /******************** - Purpose: Add's the panels to the Frame - *********************/ - { - JPanel horizontalSeparatorPanel = new JPanel(); - JPanel horizontalSeparatorPanel2 = new JPanel(); - JPanel horizontalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel4 = new JPanel(); - JPanel verticalSeparatorPanel = new JPanel(); - - _frameContentPane.setLayout( new GridBagLayout() ); - -// _dataScrollPane.setPreferredSize( new Dimension( 150, 50 ) ); - - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - horizontalSeparatorPanel2.setPreferredSize( new Dimension( 300, 30 ) ); - horizontalSeparatorPanel3.setPreferredSize( new Dimension( 300, 30 ) ); - horizontalSeparatorPanel4.setPreferredSize( new Dimension( 300, 30 ) ); - - - JSeparator buttonSeparator = new JSeparator(); - - _uhgListPanel.setMinimumSize(new Dimension(400, 500)); - //_uhgListPanel.setMaximumSize(new Dimension(500, 500)); - -// X, Y, #Col, #Row - ComponentHelper.addFrameComponent( _frameContentPane, _uhgListPanel, 0, 0, 25, 5, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel, 0, 5, 25, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _uhgTextPanel, 0, 7, 25, 1, 1, 0, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel2, 0, 8, 25, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _listButtonPanel, 0, 10, 25, 1, GridBagConstraints.NONE ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel3, 0, 11, 25, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, buttonSeparator , 0, 13, 25, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, horizontalSeparatorPanel4, 0, 15, 25, 2, GridBagConstraints.BOTH ); - - ComponentHelper.addFrameComponent( _frameContentPane, _dialogButtonPanel, 0, 17, 25, 2, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, verticalSeparatorPanel, 25, 0, 1, 15, GridBagConstraints.BOTH ); - ComponentHelper.addFrameComponent( _frameContentPane, _canvasPanel, 26, 0, 15, 15, 1, 1, GridBagConstraints.BOTH ); - - return; - } - // ------------------------------------------------------------------------------------- - - private void initUnitHydrographJTableComponents() - /******************** - Purpose: Add's Components to the JList Scroll Pane Panel - *********************/ - { - _uhgListPanel.setLayout( new GridBagLayout() ); - // X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _uhgListPanel, _scrollPane, 0, 0, 5, 25, 1, 1, GridBagConstraints.BOTH ); - - } - -// ------------------------------------------------------------------------------------- - - private void initUnitHydrographDataPanelComponents() - /******************** - Purpose: Add's Label/TextField componenets to the uhgDataPanel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - _uhgTextPanel.setLayout( new GridBagLayout() ); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 10, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 10, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 10, 20 ) ); - - GridBagConstraints gbc = new GridBagConstraints(); - gbc.insets = new Insets(5, 5, 5, 5); - - //_areaIdTextField.setPreferredSize(new Dimension(100, 40)); - _areaIdTextField.setMinimumSize(new Dimension(80, 20)); - _dischargeTextField.setMinimumSize(new Dimension(80, 20)); - - _modelComboBox.setEditable(true); - -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _uhgTextPanel, _areaIdLabel, gbc, 0, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, _areaIdTextField, gbc, 0, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _uhgTextPanel, _modelLabel, gbc, 2, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, _modelComboBox, gbc, 2, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _uhgTextPanel, _durationLabel, gbc, 4, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, _durationComboBox, gbc, 4, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _uhgTextPanel, _ordLabel, gbc, 6, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, _ordTextField, gbc, 6, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _uhgTextPanel, _dischargeLabel, gbc, 8, 0, 1, 1, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, _dischargeTextField, gbc, 8, 1, 1, 1, GridBagConstraints.BOTH ); - - ComponentHelper.addPanelComponent( _uhgTextPanel, verticalSeparatorPanel, gbc, 1, 0, 1, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, verticalSeparatorPanel2, gbc, 3, 0, 1, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _uhgTextPanel, verticalSeparatorPanel3, gbc, 5, 0, 1, 2, GridBagConstraints.BOTH ); - } - // ------------------------------------------------------------------------------------- - - private void initListButtons() - /******************** - Purpose: adds the buttons to the list button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - - _listButtonPanel.setLayout( new GridBagLayout() ); -// - GridBagConstraints gbc = new GridBagConstraints(); - gbc.insets = new Insets(5, 5, 5, 5); - //X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _listButtonPanel, (Component)_addButton, gbc, 0, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _listButtonPanel, verticalSeparatorPanel, gbc, 2, 0, 1, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _listButtonPanel, (Component) _modifyButton, gbc, 3, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _listButtonPanel, verticalSeparatorPanel2, gbc, 5, 0, 1, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _listButtonPanel, (Component) _removeButton, gbc, 6, 0, 2, 2, GridBagConstraints.BOTH ); - - /* - if ( _uhgList.size() > 0 ) - { - _importButton.setEnabled( false ); - } - */ - - } - // ------------------------------------------------------------------------------------- - - private void initDialogButtons() - /******************** - Purpose: adds the buttons to the dialog button panel - *********************/ - { - JPanel verticalSeparatorPanel = new JPanel(); - JPanel verticalSeparatorPanel2 = new JPanel(); - JPanel verticalSeparatorPanel3 = new JPanel(); - JPanel verticalSeparatorPanel4 = new JPanel(); - JPanel horizontalSeparatorPanel = new JPanel(); - - verticalSeparatorPanel.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel2.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel3.setPreferredSize( new Dimension( 50, 20 ) ); - verticalSeparatorPanel4.setPreferredSize( new Dimension( 50, 20 ) ); - horizontalSeparatorPanel.setPreferredSize( new Dimension( 300, 10 ) ); - - _dialogButtonPanel.setLayout( new GridBagLayout() ); -// X, Y, #Col, #Row - ComponentHelper.addPanelComponent( _dialogButtonPanel, _saveButton, 6, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, verticalSeparatorPanel, 8, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, _deleteButton, 12, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, verticalSeparatorPanel2, 14, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, _importButton, 18, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, verticalSeparatorPanel3, 20, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, _exportButton, 24, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, verticalSeparatorPanel4, 26, 0, 4, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, _closeButton, 30, 0, 2, 2, GridBagConstraints.BOTH ); - ComponentHelper.addPanelComponent( _dialogButtonPanel, horizontalSeparatorPanel, 0, 2, 20, 2, GridBagConstraints.BOTH ); - } - // ------------------------------------------------------------------------------------- - - - private void loadTextFields() - /******************** - Purpose: Load's the appropriate values for the Text Fields - *********************/ - { - if ( _unitHydrographEntry != null ) - { - _areaIdTextField.setText( _unitHydrographEntry.getAreaId()); - //_modelComboBox.setSelectedIndex( getModelIndex(_unitHydrographEntry.getModel())); - - - ensureModelIsInModelComboBox(_modelComboBox, _unitHydrographEntry.getModel()); - _modelComboBox.setSelectedItem( _unitHydrographEntry.getModel()); - - _durationComboBox.setSelectedItem( "" + DurationCode.getHoursFromCode(_unitHydrographEntry.getDur())); - - //_durationTextField.setText( "" + _unitHydrographEntry.getDur() ); - _ordTextField.setText( "" + _unitHydrographEntry.getOrdinal() ); - _dischargeTextField.setText( "" + _unitHydrographEntry.getDischarge() ); - } - else - { - _areaIdTextField.setText( "" ); - _modelComboBox.setSelectedIndex(0); - _durationComboBox.setSelectedIndex(0); - - //_durationTextField.setText( "" ); - _ordTextField.setText( "" ); - _dischargeTextField.setText( "" ); - } - } - - // ------------------------------------------------------------------------------------- - private void ensureModelIsInModelComboBox(JComboBox comboBox, String modelString) - - { - boolean isInComboBox = false; - - for (int i=0 ; i < comboBox.getItemCount(); i++) - { - String item = (String) comboBox.getItemAt(i); - if (item.equalsIgnoreCase(modelString)) - { - isInComboBox = true; - } - } - - if (! isInComboBox) - { - comboBox.addItem(modelString); - } - - return; - - } - - // ------------------------------------------------------------------------------------- - private int getModelIndex(String model) - { - int index = -1; - for (int i = 0 ; i < _modelStringArray.length; i++) - { - if (_modelStringArray[i].equalsIgnoreCase(model)) - { - index = i; - break; - } - } - - return index; - } - - // ------------------------------------------------------------------------------------- - - private void addListeners() - /******************** - Purpose: Add's listeners to the buttons and TextFields - *********************/ - { - WindowCloserListener windowCloser = new WindowCloserListener(); - _addButton.addActionListener( new AddModifyButtonListener() ); - _modifyButton.addActionListener( new AddModifyButtonListener() ); - _removeButton.addActionListener( new RemoveButtonListener() ); - _importButton.addActionListener( new ImportButtonListener() ); - _exportButton.addActionListener( new ExportButtonListener() ); - _saveButton.addActionListener( new SaveButtonListener() ); - _closeButton.addActionListener( windowCloser ); - _deleteButton.addActionListener( new DeleteButtonListener() ); - addWindowListener( windowCloser ); - addComponentListener( new WindowResizeComponentListener() ); - _rowListSelectionModel.addListSelectionListener( new TableUpdateListener() ); - _uhgRowJTable.getTableHeader().addMouseListener( new TableSortingListener() ); - - //_apiMkcCheckBox.addActionListener(new UnitgraphDrawingListener("API-MKC")); - //_sacSmaCheckBox.addActionListener(new UnitgraphDrawingListener("SAC-SMA")); - } - - // ------------------------------------------------------------------------------------- - - private void saveChanges() - { - for( int i = 0; i < _uhgEntryAddModifyDeleteList.size(); i++ ) - { - UnitHydrographEntryCommand entry = (UnitHydrographEntryCommand) _uhgEntryAddModifyDeleteList.get( i ); - - if ( entry.AddToDatabase() ) - { - _dataMgr.saveUnitHydrographEntry( entry.getUhgEntry() ); - } - else if ( ! entry.AddToDatabase() ) - { - _dataMgr.removeUnitHydrographEntry( entry.getUhgEntry() ); - } - } - _uhgEntryAddModifyDeleteList.clear(); - - setNeedsSaving(false); - - } - - // ------------------------------------------------------------------------------------- - private void setNeedsSaving(boolean value) - { - _needsSaving = value; - - if (_needsSaving) - { - _saveButton.setText("* Save!!! *"); - } - else - { - _saveButton.setText("Save"); - } - - } - // ------------------------------------------------------------------------------------- - private class TableSortingListener extends MouseAdapter - { - public void mouseClicked( MouseEvent e ) - { - Point point = e.getPoint(); - _lastColumnSorted = _uhgRowJTable.getTableHeader().columnAtPoint( point ); - //System.out.println("TableSortingListener(): mouseClicked()"); - _tableHelper.sortList( _uhgList, _lastColumnSorted, true ); - refreshUnitHydrographTable(); - } - } - // ------------------------------------------------------------------------------------- - - private class TableUpdateListener implements ListSelectionListener - { - public void valueChanged(ListSelectionEvent arg0) - { - int index = _uhgRowJTable.getSelectedRow(); - if ( ( index >= 0 ) && ( ! _uhgList.isEmpty() ) ) - { - _unitHydrographEntry = (UnitHydrographEntry) _uhgList.get( index ); - } - else - { - _unitHydrographEntry = null; - } - loadTextFields(); - } - } - // ------------------------------------------------------------------------------------- - - private class SaveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - saveChanges(); - } - } - // ------------------------------------------------------------------------------------- - - private class DeleteButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - String basinId = _areaIdTextField.getText(); - String model = (String) _modelComboBox.getSelectedItem(); - - String durationString = (String) _durationComboBox.getSelectedItem(); - int durationCode = DurationCode.getCodeFromHoursString(durationString); - - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete the unit hydrograph for \n " + - _locationId + " for the basin = " + basinId + "\n" + - " and the model = " + model + " AND " + - " duration = "+ durationCode + "?", "Delete Unit Hydrograph"); - - - - - if ( confirm ) - { - _dataMgr.deleteUnitHydrograph( _locationId, basinId, model, durationCode ); - _uhgEntryAddModifyDeleteList.clear(); //Clears the queue of all updates/deletions - - _uhgList = loadUhgList(); - - resortUsingTableSort(); - refreshUnitHydrographTable(); - - } - } - } - // ------------------------------------------------------------------------------------- - - private boolean isAnyFieldEmpty() - { - boolean isEmpty = false; - - if ( - ( isEmptyString( _areaIdTextField.getText() ) ) || - ( isEmptyString((String) _modelComboBox.getSelectedItem() ) ) || - ( isEmptyString((String) _durationComboBox.getSelectedItem() ) ) || - ( isEmptyString( _ordTextField.getText() ) ) || - ( isEmptyString( _dischargeTextField.getText() ) ) - ) // Checks to make sure the text fields do not contain - // empty strings - { - isEmpty = true; - } - return isEmpty; - } - // ------------------------------------------------------------------------------------- - - private UnitHydrographEntry getUnitHydrographEntryFromFields() - { - UnitHydrographEntry newUHGEntry = new UnitHydrographEntry(); - - try - { - - newUHGEntry.setAreaId( _areaIdTextField.getText().trim() ); - newUHGEntry.setModel((String) _modelComboBox.getSelectedItem()); - newUHGEntry.setDur( DurationCode.getCodeFromHoursString( (String)_durationComboBox.getSelectedItem()) ); - newUHGEntry.setOrdinal( Integer.parseInt( _ordTextField.getText().trim() ) ); - newUHGEntry.setDischarge( Double.parseDouble( _dischargeTextField.getText().trim() ) ); - newUHGEntry.setLocationId( _locationId ); - } - - catch (Exception e) - { - DialogHelper.displayErrorDialog(this, "Error parsing an input field, please examine.", "UnitHydrographEditor Data Entry Error" ); - newUHGEntry = null; - - } - - return newUHGEntry; - } - // ------------------------------------------------------------------------------------- - - private class AddModifyButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - - UnitHydrographEntry newUHGEntry = null; - - if ( ! isAnyFieldEmpty() ) - { - boolean addToDatabase = true; - boolean duplicateEntry = false; - // int column = _lastSortedColumn; - - newUHGEntry = getUnitHydrographEntryFromFields(); - - - if (newUHGEntry != null) - { - - duplicateEntry = validateNewUnitHydrographEntry(newUHGEntry); - - if (e.getSource() == _addButton) - { - if (!duplicateEntry) - { - UnitHydrographEntryCommand addEntry = new UnitHydrographEntryCommand( - newUHGEntry, addToDatabase); - _uhgEntryAddModifyDeleteList.add(addEntry); - _unitHydrographEntry = newUHGEntry; - _uhgList.add(newUHGEntry); - } - else - { - DialogHelper - .displayErrorDialog( - UnitHydrographEditor.this, - "Duplicate Ordinal values may not be entered.", - "Error Message"); - } - - } - else if (e.getSource() == _modifyButton) - { - if (duplicateEntry) - { - UnitHydrographEntryCommand changedEntry = new UnitHydrographEntryCommand( - newUHGEntry, addToDatabase); - _uhgEntryAddModifyDeleteList.add(changedEntry); - _uhgList.remove(_unitHydrographEntry); - _uhgList.add(newUHGEntry); - - _unitHydrographEntry = newUHGEntry; - } - } - - // System.out.println("AddModifyButtonListener(): actionPerformed()"); - - //sort by ordinal so that it looks good - _tableHelper.sortWithoutMemory(_uhgList, - getColumnIndex(ORDINAL), true); - - // sort by whatever is the last requested sort order - _tableHelper.resortList(_uhgList); - - refreshUnitHydrographTable(); - - notifyAllApplyActionListeners(); // notifies all the listeners - - setNeedsSaving(true); - - } //end newUHGEntry - - } - - - } - // ------------------------------------------------------------------------------------- - - private boolean validateNewUnitHydrographEntry( UnitHydrographEntry newUHGEntry ) - { - boolean foundEntry = false; - - for( int i = 0; i < _uhgList.size(); i++ ) - { - UnitHydrographEntry entry = (UnitHydrographEntry) _uhgList.get( i ); - - if ( entry.hasEqualKey( newUHGEntry ) ) - { - _unitHydrographEntry = entry; - foundEntry = true; - } - } - return foundEntry; - } - } - // ------------------------------------------------------------------------------------- - - private class ExportButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - UnitHydrographEditor.this.exportUnitHydrographToFile(); - } - } - // ------------------------------------------------------------------------------------- - - private void exportUnitHydrographToFile() - { - File fileName = null; - OutputStream outputStream = null; - PrintWriter writer = null; - boolean confirm = false; - boolean fileIsOpen = false; - - - // get confirmation of desire to Export the unit hydrograph - String basinId = _areaIdTextField.getText(); - String model = (String) _modelComboBox.getSelectedItem(); - - String durationString = (String) _durationComboBox.getSelectedItem(); - int durationCode = DurationCode.getCodeFromHoursString(durationString); - - - //use this to ensure only 1 unithydrograph is exported - UnitHydrographDescriptor selectedDescriptor = - new UnitHydrographDescriptor(_locationId, basinId, model, durationCode ); - - String message = "Are you sure you want to export the unit hydrograph for \n " + - _locationId + " for the basin = " + basinId + "\n" + - " and the model = " + model + " AND " + - " durationCode = " + durationCode + "?\n" + - "Note: the export file will be overwritten if it already exists\n"; - - - confirm = DialogHelper.displayConfirmDialog(null, message, "Export Unit Hydrograph"); - - if ( confirm ) - { - fileName = displayExportFileChooser(); - - if ( ! fileIsOpen ) - { - try - { - if ( fileName != null ) - { - outputStream = new FileOutputStream(fileName, false); - fileIsOpen = true; - } - else //fileName is null - { - outputStream = System.out; - } - - writer = new PrintWriter( outputStream ); - } - catch (java.io.IOException e) - { - String errorMessage = "Error exporting file: " + e.getMessage(); - DialogHelper.displayErrorDialog(null, message, "Export Error"); - //e.printStackTrace(); - } - } - for ( int i = 0; i < _uhgList.size(); i++ ) - { - UnitHydrographEntry entry = (UnitHydrographEntry) _uhgList.get( i ); - - //only write out the unithydrograph that matches the one selected to be - //exported - if (selectedDescriptor.isMatchingEntry(entry) ) - { - - writer.println( entry.getAreaId() + " " + entry.getModel() + " " + - entry.getDur() + " " + - entry.getOrdinal() + " " + entry.getDischarge() ); - writer.flush(); - - } - } - writer.close(); - - } - - - } - - // ------------------------------------------------------------------------------------- - - private class ImportButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - File importFile = UnitHydrographEditor.this.displayImportFileChooser(); - if ( importFile != null ) - { - boolean result = UnitHydrographEditor.this.importUnitHydrographFromFile( importFile ); - - if (result) - { - saveChanges(); - } - } - - } - } - // ------------------------------------------------------------------------------------- - - public void addApplyActionListener( ActionListener listener ) - { - _applyListenerList.add(listener); - } - // ------------------------------------------------------------------------------------- - - private void notifyAllApplyActionListeners() - { - for (int i = 0; i < _applyListenerList.size(); i++) - { - ActionListener listener = (ActionListener) _applyListenerList.get(i); - ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "APPLY action"); - listener.actionPerformed(event); - } - } - // ------------------------------------------------------------------------------------- - - private class RemoveButtonListener implements ActionListener - { - public void actionPerformed( ActionEvent e ) - { - boolean confirm = false; - - if ( _unitHydrographEntry != null ) - { - confirm = DialogHelper.displayConfirmDialog(null, - "Are you sure you want to delete this Entry?", - "Delete Entry"); - if ( confirm ) // User selected YES - { - boolean addToDatabase = false; - - UnitHydrographEntryCommand deleteEntry = new UnitHydrographEntryCommand( _unitHydrographEntry, addToDatabase ); - - _uhgEntryAddModifyDeleteList.add( deleteEntry ); - _uhgList.remove( _unitHydrographEntry ); - _unitHydrographEntry = null; - - resortUsingTableSort(); - refreshUnitHydrographTable(); - - } - } - - setNeedsSaving(true); - } - } - // ------------------------------------------------------------------------------------- - - private class WindowCloserListener extends WindowAdapter implements ActionListener - { - public void windowClosing ( WindowEvent e ) - { - closeWindow(); - } - - public void actionPerformed( ActionEvent e ) - { - closeWindow(); - } - } - // ------------------------------------------------------------------------------------- - - private class WindowResizeComponentListener extends ComponentAdapter - { - public void componentResized( ComponentEvent e ) - { - int height = UnitHydrographEditor.this.getHeight(); - int width = UnitHydrographEditor.this.getWidth(); - // System.out.println( "Width/Height = [" + width + ", " + height + "]" ); - - if ( width < MIN_WIDTH ) - { - UnitHydrographEditor.this.setSize( new Dimension( MIN_WIDTH, height ) ); - } - if ( width > MAX_WIDTH ) - { - UnitHydrographEditor.this.setSize( new Dimension( MAX_WIDTH, height ) ); - } - if ( height < MIN_HEIGHT ) - { - UnitHydrographEditor.this.setSize( new Dimension( width, MIN_HEIGHT ) ); - } - if ( height > MAX_HEIGHT ) - { - UnitHydrographEditor.this.setSize( new Dimension( width, MAX_HEIGHT ) ); - } - - } - } - //------------------------------------------------------------------------------------- - - private boolean importUnitHydrographFromFile( File importFile ) - { - boolean result = false; - boolean addToDatabase = true; - final int newFormatTokenCount = 5; - final int oldFormatTokenCount = 4; - boolean needToAddModelType = false; - String defaultModelType = null; - - try - { - BufferedReader _reader = new BufferedReader( new FileReader( importFile ) ); - String line = _reader.readLine(); - if ( _uhgList == null ) - { - _uhgList = new ArrayList(); - _uhgEntryAddModifyDeleteList = new ArrayList(); - } - - - //determine if need to do something special to translate from original format UHG files to - // new format - - String[] initialTokenizedLine = StringParser.tokenize( line ); - int tokenCount = initialTokenizedLine.length; - if ( tokenCount == oldFormatTokenCount) - { - //need to translate == true; - needToAddModelType = true; - defaultModelType = getModelTypeFromDialog(); - } - else if (tokenCount == newFormatTokenCount) - { - //things are good - } - else - { - String message = "Invalid file format. There are " + tokenCount + - " fields in the line instead of " + - oldFormatTokenCount + " or " + newFormatTokenCount + " fields."; - throw new Exception(message); - } - - - //read in each line and add it to the JTable - while( line != null ) - { - //String[] tokenizedLine = StringParser.tokenize( line ); - String[] tokenizedLine = getTokenizedLine(line, needToAddModelType, defaultModelType); - - UnitHydrographEntry entry = new UnitHydrographEntry(); - - entry.setLocationId( _locationId ); - entry.setAreaId( tokenizedLine[ 0 ] ); - - //special model type name processing, tries - // to correct any misspellings or wrong case - String model = tokenizedLine[ 1 ]; - model = correctModelName(model); - entry.setModel(model); - - entry.setDur( Integer.parseInt( tokenizedLine[ 2 ] ) ); - entry.setOrdinal( Integer.parseInt( tokenizedLine[ 3 ] ) ); - entry.setDischarge( Double.parseDouble( tokenizedLine[ 4 ] ) ); - - UnitHydrographEntryCommand entryCommand = new UnitHydrographEntryCommand( entry, addToDatabase ); - - - //add the entry if it is not already present - if(!_uhgList.contains(entry)) - { - _uhgList.add( entry ); - _uhgEntryAddModifyDeleteList.add( entryCommand ); - } - line = _reader.readLine(); - } - - _reader.close(); - - // everything worked, update the display - result = true; - - resortUsingTableSort(); - refreshUnitHydrographTable(); - - } - catch( FileNotFoundException e ) - { - String errorMessage = e.getMessage(); - String title = "Import Error - File Not Found"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " + errorMessage, title); - } - catch( IOException e ) - { - String errorMessage = e.getMessage(); - String title = "Import Error - I/O Error"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " + errorMessage, title); - } - catch( ArrayIndexOutOfBoundsException e ) - { - String errorMessage = e.getMessage(); - String title = "Import Error - I/O Error"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " + errorMessage, title); - - System.out.println( "Invalid file format: " + importFile.getName() ); - } - catch (Exception e) - { - String errorMessage = e.getMessage(); - if (errorMessage == null) - { - errorMessage = "- Check for extra or incomplete lines at end of file."; - } - String title = "Import File Formatting Error"; - DialogHelper.displayErrorDialog(this, "Error Importing File: " + errorMessage, title); - - System.out.println( "Invalid file format: " + importFile.getName() ); - } - - // the import failed, so rollback any changes - //reload the uhgList and refresh the display - if (result == false) - { - _uhgEntryAddModifyDeleteList.clear(); - _uhgList = loadUhgList(); - - resortUsingTableSort(); - - refreshUnitHydrographTable(); - - } - - return result; - - } - - -// ------------------------------------------------------------------------------------- - private void initializeTableSort() - { - - //set the initial sort to the "model" column - _lastColumnSorted = getColumnIndex("model"); - - _tableHelper.sortList(_uhgList, _lastColumnSorted, false); - - } - // ------------------------------------------------------------------------------------- - private void resortUsingTableSort() - { - _tableHelper.sortList(_uhgList, _lastColumnSorted, false); - - } - // ------------------------------------------------------------------------------------- - private String getModelTypeFromDialog() - { - String modelTypeString = null; - - String title = "Rainfall-Runoff Model Selection"; - String message = "Please enter the rainfall-runoff model\n" + - " for which this unit hydrograph is appropriate.\n" + - " " ; - String comboBoxLabelString = "Rainfall-Runoff Model:"; - String[] optionArray = { "ANY ", - "API-MKC", - "SAC-SMA" }; - - OptionSelectionDialog dialog = new OptionSelectionDialog(); - - dialog.requestItemByDialog(title, message, comboBoxLabelString, optionArray ); - - - modelTypeString = dialog.getItemString(); - - return modelTypeString; - - } - - // ------------------------------------------------------------------------------------- - - private String[] getTokenizedLine(String line, boolean needToAddModelType, String defaultModelType) - { - String header = "UnitHydrographEditor.getTokenizedLine(): "; - - if (needToAddModelType) - { - StringBuffer buffer = new StringBuffer(line); - - int spacePos = buffer.indexOf(" "); - buffer.insert(spacePos, " " + defaultModelType); - - // System.out.println(header + "old line = :" + line + ":" ); - - line = buffer.toString(); - - // System.out.println(header + "new line = :" + line + ":" ); - } - - String[] tokenizedLine = StringParser.tokenize( line ); - - - return tokenizedLine; - } - - // ------------------------------------------------------------------------------------- - private String correctModelName(String origModelName) throws Exception - { - String newModelName = null; - - String apiName = RainfallRunoffModelType.API_MKC.getName(); - String sacSmaName = RainfallRunoffModelType.SAC_SMA.getName(); - String anyName = "ANY"; - - String[] incorrectApiMkcNameArray = { "API_MKC", "APIMKC", "API MKC", "MKCAPI", "KCAPI", "KC_API", "KC-API" }; - - String[] incorrectSacNameArray = { "SAC_SMA", "SACSMA", "SAC SMA" }; - - String[] incorrectAnyNameArray = {"default", "none" }; - - //do case correction - if (origModelName.equalsIgnoreCase(apiName)) - { - newModelName = apiName; - } - else if (origModelName.equalsIgnoreCase(sacSmaName)) - { - newModelName = sacSmaName; - } - else if (origModelName.equalsIgnoreCase(anyName)) - { - newModelName = anyName; - } - else //no match so far - { - boolean found = false; - - //look for common errors in typing of the model names - for (int i = 0; i < incorrectApiMkcNameArray.length && !found; i++) - { - if (origModelName.equalsIgnoreCase(incorrectApiMkcNameArray[i])) - { - newModelName = apiName; - found = true; - } - } - - for (int i = 0; i < incorrectSacNameArray.length && !found; i++) - { - if (origModelName.equalsIgnoreCase(incorrectSacNameArray[i])) - { - newModelName = sacSmaName; - found = true; - } - } - - for (int i = 0; i < incorrectAnyNameArray.length && !found; i++) - { - if (origModelName.equalsIgnoreCase(incorrectAnyNameArray[i])) - { - newModelName = anyName; - found = true; - } - } - - if (!found) - { - newModelName = origModelName; - //String message = "Invalid modelName - " + origModelName; - // throw new Exception(message); - } - - } - - - return newModelName; - - } - // ------------------------------------------------------------------------------------- - - private File displayImportFileChooser() - { - - AppsDefaults ad = new AppsDefaults(); - _importDirString = ad.getToken("whfs_import_dir"); - - // reset the import directory to the last one imported from, if it exists - if (_fileChooserDirectory != null) - { - _importDirString = _fileChooserDirectory; - } - - JFileChooser _importFileChooser = new JFileChooser( _importDirString ); - File file = null; - List filterList = new ArrayList(); - - filterList.add( "UHG" ); - - _importFileChooser.addChoosableFileFilter( new ExtensionFileFilter( filterList, "Unit Hydrograph Files (UHG)" ) ); - - int returnVal = _importFileChooser.showOpenDialog( this ); - - if (returnVal == JFileChooser.APPROVE_OPTION) - { - file = _importFileChooser.getSelectedFile(); - _fileChooserDirectory = file.getParentFile().getPath().toString(); - } - else - { - DialogHelper.displayMessageDialog(UnitHydrographEditor.this, "Unit Hydrograph file not imported."); - } - return file; - } - - // ------------------------------------------------------------------------------------- - - private File displayExportFileChooser() - { - - if (_fileChooserDirectory != null) - { - _exportDirString = _fileChooserDirectory; - } - else - { - AppsDefaults ad = new AppsDefaults(); - _exportDirString = ad.getToken("whfs_import_dir"); //shares with import directory - } - - - JFileChooser _exportFileChooser = new JFileChooser( _exportDirString ); - File file = null; - List filterList = new ArrayList(); - - filterList.add( "UHG" ); - - _exportFileChooser.addChoosableFileFilter( new ExtensionFileFilter( filterList, "Unit Hydrograph Files (UHG)" ) ); - - int returnVal = _exportFileChooser.showSaveDialog( this ); - - if (returnVal == JFileChooser.APPROVE_OPTION) - { - file = _exportFileChooser.getSelectedFile(); - _fileChooserDirectory = file.getParentFile().getPath().toString(); - } - else - { - DialogHelper.displayMessageDialog(UnitHydrographEditor.this, "Unit Hydrograph not exported."); - } - - String extension = ExtensionFileFilter.getExtension( file ); - - if ( file != null ) - { - if ( ( extension == null ) || ( ! isExtensionInExtensionFilterList( extension, filterList ) ) ) - { - file = new File( file.getAbsoluteFile() + "." + (String) filterList.get( 0 ) ); - } - } - - return file; - } - - // ------------------------------------------------------------------------------------- - - - private boolean isExtensionInExtensionFilterList( String extension, List filterList ) - { - boolean extensionExists = false; - - for( int i = 0; i < filterList.size(); i++ ) - { - String ext = (String) filterList.get( i ); - if ( extension.equalsIgnoreCase( ext ) ) - { - extensionExists = true; - break; - } - } - return extensionExists; - } - - // ------------------------------------------------------------------------------------- - - - private class UnitHydrographEntryCommand - { - private UnitHydrographEntry _uhgEntry = null; - private boolean _addToDatabase = false; - - public UnitHydrographEntryCommand( UnitHydrographEntry entry, boolean addToDatabase ) - { - _uhgEntry = entry; - _addToDatabase = addToDatabase; - } - - public void setUhgEntry( UnitHydrographEntry uhgEntry ) - { - _uhgEntry = uhgEntry; - } - - public UnitHydrographEntry getUhgEntry() - { - return _uhgEntry; - } - - public void setAddToDatabase( boolean addToDatabase ) - { - _addToDatabase = addToDatabase; - } - - public boolean AddToDatabase() - { - return _addToDatabase; - } - } - - // ------------------------------------------------------------------------------------- - - private void closeWindow() - /******************** - Purpose: Exit's the program gracefully - *********************/ - { - this.dispose(); - } - - // ------------------------------------------------------------------------------------- - - - private boolean isEmptyString( String testingString ) - /******************** - Purpose: Check's whether the string passed in is an empty string - *********************/ - { - boolean returnValue = false; - - if ( testingString.trim().equals( "" ) ) - { - returnValue = true; - } - return returnValue; - } - // ------------------------------------------------------------------------------------- - - private JLabel getJLabel( String label ) - { - JLabel returnJLabel = new JLabel( label ); - returnJLabel.setFont( _labelFont ); - return returnJLabel; - } - - // ------------------------------------------------------------------------------------- - - private JTextField getJTextField( int size ) - { - JTextField returnJTextField = new JTextField( size ); - returnJTextField.setFont( _textFieldFont ); - - StringBuffer buffer = new StringBuffer(); - for (int i = 0 ; i < size; i++) - { - buffer.append("W"); - } - - returnJTextField.setText(buffer.toString()); - return returnJTextField; - } - - // ------------------------------------------------------------------------------------- - - - private JFormattedTextField getJFormattedTextField( String formatString ) - { - JFormattedTextField returnJFormattedTextField = new JFormattedTextField( formatString ); - returnJFormattedTextField.setFont( _textFieldFont ); - returnJFormattedTextField.setColumns( 17 ); - return returnJFormattedTextField; - } - - // ------------------------------------------------------------------------------------- - - private String getFormattedValue( double valueString ) - { - return _decimalFormat.format( valueString ); - } - - // ------------------------------------------------------------------------------------- - - public void setConnectionString( String connectionString ) - { - _connectionString = connectionString; - } - - // ------------------------------------------------------------------------------------- - - public String getConnectionString() - { - return _connectionString; - } - - // ------------------------------------------------------------------------------------- - - public void setLogger( FileLogger logger ) - { - _logger = logger; - } - - // ------------------------------------------------------------------------------------- - - public FileLogger getLogger() - { - return _logger; - } - - // ------------------------------------------------------------------------------------- - - public void setLocationId( String locationId ) - { - _locationId = locationId; - } - - // ------------------------------------------------------------------------------------- - - public String getLocationId() - { - return _locationId; - } - - private boolean validateInputParameters( String[] args ) - { - String logDir = null; - File directory = null; - boolean returnValue = true; - - if ( args.length < 3 ) - { - System.out.println( "UnitHydrographEditor " ); - returnValue = false; - } - else - { - _connectionString = args[ 0 ]; - - _locationId = args[ 1 ]; - - _logger = new FileLogger( args[ 2 ] ); - } // end else - return returnValue; - } - - - public static void main(String[] args) - { - String basinId = null; - DataMgr dataMgr = null; - UnitHydrographEditor editor = new UnitHydrographEditor(); - - boolean validInputParameters = false; - - validInputParameters = editor.validateInputParameters( args ); - - if ( validInputParameters ) - { - dataMgr = new DataMgr( editor.getConnectionString(), editor.getLogger() ); - - editor = new UnitHydrographEditor( new Frame(), dataMgr, editor.getLocationId(), true ); - editor.show(); - } - - System.exit( 0 ); - } -} diff --git a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographEntryComparator.java b/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographEntryComparator.java deleted file mode 100644 index 8a171c2659..0000000000 --- a/javaUtilities/hydro/ohd.sshp/src/ohd/hseb/sshp/window/UnitHydrographEntryComparator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Created on Jun 14, 2004 - * - * Filename : - * Author : Gautam Sood - * Last Revision Date : Jun 14, 2004 - * - */ -package ohd.hseb.sshp.window; - -import ohd.hseb.model.UnitHydrographEntry; -import ohd.hseb.util.gui.TableColumnComparator; - -/** - * @author SoodG -*/ -public class UnitHydrographEntryComparator extends TableColumnComparator -{ - public UnitHydrographEntryComparator() - { - } - - public int compareArea_Id( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - int result = entry1.getAreaId().compareToIgnoreCase( entry2.getAreaId() ); - return result; - } - - public int compareModel( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareStrings( entry1.getModel(), entry2.getModel() ) ); - } - - public int compareDuration( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getDur(), entry2.getDur() ) ); - } - - public int compareOrdinal( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getOrdinal(), entry2.getOrdinal() ) ); - } - - public int compareDischarge( UnitHydrographEntry entry1, UnitHydrographEntry entry2 ) - { - return( compareNumbers( entry1.getDischarge(), entry2.getDischarge() ) ); - } - - - public int compare(Object object1, Object object2) - { - UnitHydrographEntry entry1 = (UnitHydrographEntry) object1; - UnitHydrographEntry entry2 = (UnitHydrographEntry) object2; - - int returnValue = 0; - - if( _columnName.equalsIgnoreCase( UnitHydrographEditor.AREA_ID ) ) - { - returnValue = compareArea_Id( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.MODEL ) ) - { - returnValue = compareModel( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.DURATION ) ) - { - returnValue = compareDuration( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.ORDINAL ) ) - { - returnValue = compareOrdinal( entry1, entry2 ); - } - else if ( _columnName.equalsIgnoreCase( UnitHydrographEditor.DISCHARGE ) ) - { - returnValue = compareDischarge( entry1, entry2 ); - } - - if ( ! _ascOrder ) - { - returnValue = -1 * returnValue; - } - - return returnValue; - } -} diff --git a/javaUtilities/hydro/ohd.swttable/.classpath b/javaUtilities/hydro/ohd.swttable/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.swttable/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.swttable/.project b/javaUtilities/hydro/ohd.swttable/.project deleted file mode 100644 index 74e6f1464e..0000000000 --- a/javaUtilities/hydro/ohd.swttable/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.swttable - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.swttable/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.swttable/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 89148f28d2..0000000000 --- a/javaUtilities/hydro/ohd.swttable/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:31:55 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.swttable/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.swttable/META-INF/MANIFEST.MF deleted file mode 100644 index e370266837..0000000000 --- a/javaUtilities/hydro/ohd.swttable/META-INF/MANIFEST.MF +++ /dev/null @@ -1,6 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Swttable -Bundle-SymbolicName: ohd.swttable -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/javaUtilities/hydro/ohd.swttable/build.properties b/javaUtilities/hydro/ohd.swttable/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.swttable/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.swttable/build.xml b/javaUtilities/hydro/ohd.swttable/build.xml deleted file mode 100644 index 7554972845..0000000000 --- a/javaUtilities/hydro/ohd.swttable/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.swttable/ohd.swttable.ecl b/javaUtilities/hydro/ohd.swttable/ohd.swttable.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.sys_monitor/.classpath b/javaUtilities/hydro/ohd.sys_monitor/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.sys_monitor/.project b/javaUtilities/hydro/ohd.sys_monitor/.project deleted file mode 100644 index 453bce536f..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.sys_monitor - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.sys_monitor/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.sys_monitor/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index d39baa95bf..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:34:24 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.sys_monitor/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.sys_monitor/META-INF/MANIFEST.MF deleted file mode 100644 index 0647a06086..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/META-INF/MANIFEST.MF +++ /dev/null @@ -1,8 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Sys_monitor -Bundle-SymbolicName: ohd.sys_monitor -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" diff --git a/javaUtilities/hydro/ohd.sys_monitor/build.properties b/javaUtilities/hydro/ohd.sys_monitor/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.sys_monitor/build.xml b/javaUtilities/hydro/ohd.sys_monitor/build.xml deleted file mode 100644 index 85f97376d7..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.sys_monitor/ohd.sys_monitor.ecl b/javaUtilities/hydro/ohd.sys_monitor/ohd.sys_monitor.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.sys_monitor/scripts/run_sys_monitor b/javaUtilities/hydro/ohd.sys_monitor/scripts/run_sys_monitor deleted file mode 100644 index 33f707fb84..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/scripts/run_sys_monitor +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/ksh -# file name: run_sys_monitor -# Created: 2/24/2009 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# need to add a path to the jar file for this application -export CLASSPATH=$WHFS_BIN_DIR/sys_monitor.jar -CLASSPATH=$CLASSPATH:$WHFS_BIN_DIR/activation.jar:$WHFS_BIN_DIR/mail-1.4.1.jar - -# Java bin directory -JBINDIR=$SYS_JAVA_DIR/bin - -# trim log file -LOGFILE=$WHFS_UTIL_LOG_DIR/sys_monitor.log -TEMPLOGFILE=$LOGFILE.temp -tail -1200 $LOGFILE > $TEMPLOGFILE -mv $TEMPLOGFILE $LOGFILE - -# set up an X Terminal window to write stdout and run the SiteSpecific -# application using java -echo $JBINDIR/java ohd.hseb.monitor.MonitorManager "$@" >> $LOGFILE -$JBINDIR/java ohd.hseb.monitor.MonitorManager "$@" >> $LOGFILE 2>&1 & diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/mail/MailHelper.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/mail/MailHelper.java deleted file mode 100644 index d0b4d88c76..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/mail/MailHelper.java +++ /dev/null @@ -1,98 +0,0 @@ -package ohd.hseb.mail; - -import java.util.Date; -import java.util.Properties; -import javax.mail.*; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - -public class MailHelper -{ - private Properties _props = null; - - //---------------------------------------------------------------------------------------- - public MailHelper() - { - try - { - _props = new Properties(); - _props.put("mail.transport.protocol", "smtp"); - _props.put("mail.smtp.host", ""); - _props.put("mail.smtp.port", 25); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - //---------------------------------------------------------------------------------------- - - public boolean send(String fromAddressString, - String toAddressString, - String subjectString, - String messageText) - { - boolean success = false; - - Session mailSession = Session.getInstance(_props); - Message message = new MimeMessage(mailSession); - - Date sentDate = new Date(); - - try - { - InternetAddress fromAddress = new InternetAddress(fromAddressString); - message.setFrom(fromAddress); - - InternetAddress[] toAddressArray = InternetAddress.parse(toAddressString); - message.setRecipients(Message.RecipientType.TO, toAddressArray); - - message.setSentDate(sentDate); - message.setSubject(subjectString); - - message.setText(messageText); - Transport.send(message); - - success = true; - } - - catch (Exception e) - { - e.printStackTrace(); - } - - return success; - } - - //---------------------------------------------------------------------------------------- - - public void test() - { - - String fromAddressString = "whfs@lx4-nhdr.nws.noaa.gov"; - String toAddressString = "Chip.Gobs@noaa.gov"; - String subjectString = "MailHelper Test message"; - Date sentDate = new Date(); - String messageText = "Chip,\nThis is a test message from Java Mail.\n\nChip"; - - send (fromAddressString, toAddressString, subjectString, messageText); - - return; - } - - //---------------------------------------------------------------------------------------- - - public static void main(String[] args) - { - - MailHelper mailHelper = new MailHelper(); - - mailHelper.test(); - System.out.println("End of mail test."); - - return; - } - //---------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/AgeFileMonitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/AgeFileMonitor.java deleted file mode 100644 index 430efeb403..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/AgeFileMonitor.java +++ /dev/null @@ -1,79 +0,0 @@ -package ohd.hseb.monitor; - -import java.io.File; - - -public class AgeFileMonitor extends FileMonitor -{ - private long _ageInSeconds = -1; - - // -------------------------------------------------------------------------------------- - - public AgeFileMonitor(long ageInSeconds, - String dataDirPath, String logFilePath, String fileToMonitorPath) - { - super(dataDirPath, logFilePath, fileToMonitorPath); - setAgeInSeconds(ageInSeconds); - - } - // -------------------------------------------------------------------------------------- - - public void setAgeInSeconds(long ageInSeconds) - { - _ageInSeconds = ageInSeconds; - } - // -------------------------------------------------------------------------------------- - - public long getAgeInSeconds() - { - return _ageInSeconds; - } - - // -------------------------------------------------------------------------------------- - - - @Override - public Status monitor() - { - // String header = "AgeFileMonitor.monitor(): "; - Status status = null; - File file = new File(getFileToMonitorPath()); - - // System.out.println(header); - - - boolean fileExists = file.exists(); - - long currentTimeInMillis = System.currentTimeMillis(); - - if (fileExists) - { - long lastModifiedTime = file.lastModified(); - long diffInMillis = currentTimeInMillis - lastModifiedTime; - long diffInSeconds = diffInMillis/1000; - - if (diffInSeconds > getAgeInSeconds()) - { - status = new TextStatus("You are being notified that " + getFileToMonitorPath() + " was last modified " + diffInSeconds + - " seconds ago, which is more than the limit of " + getAgeInSeconds() + " seconds."); - } - - else - { - //System.out.println(header + "Log: " + getFileToMonitorPath() + " was last modified " + diffInSeconds + - // " seconds ago, which is less than the limit of " + getAgeInSeconds() + " seconds."); - } - } - else - { - status = new TextStatus("You are being notified that " + getFileToMonitorPath() + ", which you are monitoring for age, does not exist."); - } - - - - return status; - } - // -------------------------------------------------------------------------------------- - - -} //end class AgeFileMonitor diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/ChangeFileMonitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/ChangeFileMonitor.java deleted file mode 100644 index afffb0ff2f..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/ChangeFileMonitor.java +++ /dev/null @@ -1,122 +0,0 @@ -package ohd.hseb.monitor; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; - - - -public class ChangeFileMonitor extends FileMonitor -{ - - // -------------------------------------------------------------------------------------- - - public ChangeFileMonitor(String dataDirPath, String logFilePath, String fileToMonitorPath) - { - super(dataDirPath, logFilePath, fileToMonitorPath); - - } - // -------------------------------------------------------------------------------------- - - - @Override - public Status monitor() - { - String header = "ChangeFileMonitor.monitor(): "; - System.out.println(header); - Status status = null; - - String fileToMonitorPath = getFileToMonitorPath(); - String fileToMonitorBasename = getBaseFileName(fileToMonitorPath); - - - String prevFilePath = getDataDirPath() + '/' + fileToMonitorBasename + ".prev"; - String diffFilePath = getDataDirPath() + '/' + fileToMonitorBasename + ".diff"; - - File originalFile = new File(fileToMonitorPath); - boolean originalFileExists = originalFile.exists(); - - File previousFile = new File(prevFilePath); - boolean previousFileExists = previousFile.exists(); - - if (originalFileExists) - { - - if (previousFileExists) - { - - boolean fileChanged = false; - FileDiff fileDiff = new FileDiff(); - //String fileChangesString = fileDiff.diffToString(prevFilePath, fileToMonitorPath, diffFilePath); - - String fileChangesString = fileDiff.showNewLines(prevFilePath, fileToMonitorPath); - - fileChanged = (fileChangesString.length() > 0); - - if (fileChanged) - { - String message = "You are being notified that " + getFileToMonitorPath() + " was changed.\n " + - "The following lines were added:\n" + fileChangesString; - - status = new TextStatus(message); - System.out.println(message); - } - - else - { - System.out.println(header + "Log: " + "You are being notified that " + getFileToMonitorPath() + - " was not changed."); - } - } - else // the originalFile exists, but the previous file does not - { - // do nothing - } - } - - //copy file to a .prev version of the file - - copyFile(prevFilePath, fileToMonitorPath); - - return status; - } - // -------------------------------------------------------------------------------------- - private String getBaseFileName(String fullPathName) - { - String baseFileName = null; - - File file = new File(fullPathName); - baseFileName = file.getName(); - - - - return baseFileName; - } - // -------------------------------------------------------------------------------------- - private void copyFile(String toFilePath, String fromFilePath) - { - File fromFile = new File(fromFilePath); - File toFile = new File(toFilePath); - - try - { - FileChannel fromChannel = new FileInputStream(fromFile).getChannel(); - FileChannel toChannel = new FileOutputStream(toFile).getChannel(); - fromChannel.transferTo(0, fromFile.length(), toChannel); - fromChannel.close(); - toChannel.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - return; - } - - // -------------------------------------------------------------------------------------- - - -} //end class ChangeFileMonitor diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/CommandRunner.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/CommandRunner.java deleted file mode 100644 index 5760dffd04..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/CommandRunner.java +++ /dev/null @@ -1,90 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.util.StreamDrainer; - -public class CommandRunner -{ - - private String _standardOutput = null; - private String _standardError = null; - - // ----------------------------------------------------------------------- - - public boolean executeCommand(String commandString) - { - String header = "CommandRunner.executeProgram(): "; - - - boolean success = false; - - try - { - Runtime runtime = Runtime.getRuntime(); - Process process = runtime.exec(commandString); - - setStandardOutput(getStandardOutputFromProcess(process)); - setStandardError(getStandardErrorFromProcess(process)); - - success = true; - } - - catch (Exception e) - { - e.printStackTrace(); - } - - return success; - } //close method - - // ----------------------------------------------------------------------- - - - private String getStandardErrorFromProcess(Process p) - { - //String header = "VarAssimilationProgramExecuter.getStandardError():"; - - StreamDrainer drainer = new StreamDrainer(p.getErrorStream()); - String drainedString = drainer.drain(); - - //System.out.println(header + " drainedString = " + drainedString); - - return drainedString; - - } - // ----------------------------------------------------------------------- - - private String getStandardOutputFromProcess(Process p) - { - //String header = "VarAssimilationProgramExecuter.getStandardOutput():"; - - StreamDrainer drainer = new StreamDrainer(p.getInputStream()); - String drainedString = drainer.drain(); - - //System.out.println(header + " drainedString = " + drainedString); - - return drainedString; - } - // ----------------------------------------------------------------------- - - public void setStandardOutput(String standardOutput) - { - _standardOutput = standardOutput; - } - - public String getStandardOutput() - { - return _standardOutput; - } - - public void setStandardError(String standardError) - { - _standardError = standardError; - } - - public String getStandardError() - { - return _standardError; - } - - -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/CountFileMonitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/CountFileMonitor.java deleted file mode 100644 index c92edc9fa8..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/CountFileMonitor.java +++ /dev/null @@ -1,79 +0,0 @@ -package ohd.hseb.monitor; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -public class CountFileMonitor extends FileMonitor -{ - - private long _fileCount = -1; - - // -------------------------------------------------------------------------------------- - - public CountFileMonitor(MonitorOperator operator, long fileCount, - String dataDirPath, String logFilePath, String fileToMonitorPath) - { - super(dataDirPath, logFilePath, fileToMonitorPath); - setOperator(operator); - setFileCount(fileCount); - - } - // -------------------------------------------------------------------------------------- - - public void setFileCount(long fileCount) - { - _fileCount = fileCount; - } - // -------------------------------------------------------------------------------------- - - public long getFileCount() - { - return _fileCount; - } - // -------------------------------------------------------------------------------------- - - @Override - public Status monitor() - { - // String header = "CountFileMonitor.monitor(): "; - Status status = null; - File file = new File(getFileToMonitorPath()); - - - - //System.out.println(header); - - if (file != null) - { - - String[] fileListStringArray = file.list(); - - long actualFileCount = fileListStringArray.length; - - long comparisonFileCount = getFileCount(); - - MonitorOperator operator = getOperator(); - - boolean result = operator.evaluate(actualFileCount, comparisonFileCount); - - if (result) - { - status = new TextStatus( getFileToMonitorPath() + " contains " + actualFileCount + - " files, which is "+ operator.getSymbol() + " " + comparisonFileCount ); - } - else - { - //System.out.println(header + "monitoring " + getFileToMonitorPath() + " and there are " + actualFileCount + " files present. "); - } - } - else - { - // System.out.println(header + " file is null"); - } - - return status; - } - // -------------------------------------------------------------------------------------- - -} //end class FileCountFileMonitor diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/EmailReporter.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/EmailReporter.java deleted file mode 100644 index 87de40b9f8..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/EmailReporter.java +++ /dev/null @@ -1,31 +0,0 @@ -package ohd.hseb.monitor; - -import ohd.hseb.mail.MailHelper; - -public class EmailReporter implements Reporter -{ - - private String _fromAddressString = null; - private String _toAddressString = null; - private String _subjectString = null; - - private MailHelper _mailHelper = new MailHelper(); - - public EmailReporter(String fromAddressString, String toAddressString, String subjectString) - { - _fromAddressString = fromAddressString; - _toAddressString = toAddressString; - _subjectString = subjectString; - - - return; - } - - - public void report(Status status) - { - - _mailHelper.send(_fromAddressString, _toAddressString, _subjectString, status.toString()); - } - -} //end EmailReporter diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/ExistenceFileMonitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/ExistenceFileMonitor.java deleted file mode 100644 index 39d028e6cc..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/ExistenceFileMonitor.java +++ /dev/null @@ -1,80 +0,0 @@ -package ohd.hseb.monitor; - -import java.io.File; - - -public class ExistenceFileMonitor extends FileMonitor -{ - - private boolean _checkForExistence = true; - - // -------------------------------------------------------------------------------------- - - public ExistenceFileMonitor(boolean checkForExistence, - String dataDirPath, String logFilePath, String fileToMonitorPath) - { - super(dataDirPath, logFilePath, fileToMonitorPath); - setCheckForExistence(checkForExistence); - - } - // -------------------------------------------------------------------------------------- - - - - - - @Override - public Status monitor() - { - String header = "ExistenceFileMonitor.monitor(): "; - Status status = null; - File file = new File(getFileToMonitorPath()); - - System.out.println(header); - - - boolean fileExists = file.exists(); - - if (shouldCheckForExistence()) - { - - if (fileExists) - { - status = new TextStatus("You are being notified that " + getFileToMonitorPath() + " exists."); - } - else - { - System.out.println(header + "Log: " + getFileToMonitorPath() + " does not exist. And we are looking for it."); - } - } - else //check for non existence - { - if (! fileExists) - { - status = new TextStatus( "You are being notified that " + getFileToMonitorPath() + " does not exist."); - } - else - { - System.out.println(header + "Log: " + getFileToMonitorPath() + " does exist. And we looking for it NOT to exist."); - } - } - - - return status; - } - // -------------------------------------------------------------------------------------- - - public void setCheckForExistence(boolean checkForExistence) - { - _checkForExistence = checkForExistence; - } - // -------------------------------------------------------------------------------------- - - public boolean shouldCheckForExistence() - { - return _checkForExistence; - } - // -------------------------------------------------------------------------------------- - - -} //end class FileCountFileMonitor diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/FileDiff.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/FileDiff.java deleted file mode 100644 index c868cb621e..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/FileDiff.java +++ /dev/null @@ -1,200 +0,0 @@ -package ohd.hseb.monitor; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; - -public class FileDiff -{ - // ----------------------------------------------------------------------------------- - - public FileDiff() - { - - } - - // ----------------------------------------------------------------------------------- - private String diffToString(String file1Path, String file2Path) - { - String header = "FileDiff.diffToString(): "; - - - StringBuffer buffer = new StringBuffer(); - Runtime runtime = Runtime.getRuntime(); - - String commandString = "diff -Bbu " + file1Path + " " + file2Path; - //String commandString = "/fs/home/cgobs/file_monitor/data/diff_files " + file1Path + " " + file2Path + " " + diffFilePath; - - System.out.println(header + "commandString = " + commandString); - - CommandRunner runner = new CommandRunner(); - runner.executeCommand(commandString); - - String rawDiffString = runner.getStandardOutput(); - - System.out.println(header + "rawDiffString = " + rawDiffString); - - String newLinesOnly = filterByNonRepeatedLeadCharacter('+', rawDiffString); - - - return newLinesOnly; - } - // ----------------------------------------------------------------------------------- - private String filterByNonRepeatedLeadCharacter(char leadCharacter, String originalString) - { - BufferedReader reader = new BufferedReader(new StringReader(originalString)); - StringBuffer buffer = new StringBuffer(); - - boolean done = false; - String line = null; - -/* Since this routine filters everything but the new lines or the old lines, we don't want to include the --- or the +++ - -+++ /fs/home/cgobs/file_monitor/data/test/file1 2009-02-18 09:05:46.000000000 -0500 -@@ -2,3 +2,4 @@ - blah2 - blah3 - blah4 -+blah5 - -*/ - - try - { - - while (! done) - { - line = reader.readLine(); - if ( (line != null) && (line.length() > 1) ) - { - if (line.charAt(0) == leadCharacter) //first is lead - { - if (line.charAt(1) != leadCharacter) //it does not repeat first character - { - buffer.append(line.substring(1)); - } - } - } - else if (line == null) - { - done = true; - } - } - } - catch (IOException e) - { - e.printStackTrace(); - } - - return buffer.toString(); - } - - // ----------------------------------------------------------------------------------- - public String showNewLines( String file1Path, String file2Path) - { - return diffToString(file1Path, file2Path); - - // return showNewLinesJavaOnly(file1Path, file2Path); - } - - // ----------------------------------------------------------------------------------- - - public String showNewLinesJavaOnly( String file1Path, String file2Path) - { - StringBuffer buffer = new StringBuffer(); - BufferedReader reader1 = null; - BufferedReader reader2 = null; - String line1 = null; - String line2 = null; - int line1Count = 0; - int line2Count = 0; - - try - { - reader1 = new BufferedReader (new FileReader(file1Path)); - reader2 = new BufferedReader (new FileReader(file2Path)); - - boolean done = false; - - while (! done) - { - line1 = reader1.readLine(); - line2 = reader2.readLine(); - - - if (equalLines(line1, line2)) - { - - - if (bothNull(line1, line2)) - { - done = true; - } - else - { - line1Count++; - line2Count++; - - } - } - - else //lines are not equal - { - if (line1 != null) - { - buffer.append("File1 :" + line1); - line1Count++; - } - - if (line2 != null) - { - buffer.append("File2 :" + line2); - line2Count++; - } - } - - System.out.println("File 1 line = " + line1Count + ": " + line1); - System.out.println("File 2 line = " + line2Count + ": " + line2); - } - } - - catch (IOException e) - { - e.printStackTrace(); - } - - return buffer.toString(); - - } - // ----------------------------------------------------------------------------------- - - private boolean bothNull(String line1, String line2) - { - return ( (line1 == null) && (line2 == null) ); - } - // ----------------------------------------------------------------------------------- - - private boolean equalLines(String line1, String line2) - { - boolean equal = false; - - if ( (line1 == null) && (line2 == null) ) //both null - { - equal = true; - } - else if ((line1 != null) && (line2 != null) ) //neither null - { - equal = line1.equals(line2); - } - - - - return equal; - } - - // ----------------------------------------------------------------------------------- - - -} //end class FileDiff diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/FileMonitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/FileMonitor.java deleted file mode 100644 index d88735d2a2..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/FileMonitor.java +++ /dev/null @@ -1,77 +0,0 @@ -package ohd.hseb.monitor; - - - -abstract public class FileMonitor implements Monitor -{ - - // private long _fileCount = -1; - private long _fileSize = -1; - private MonitorOperator _operator = null; - - private String _dataDirPath = null; //for monitor's private data - private String _logFilePath = null; //for monitor's log file - private String _fileToMonitorPath = null; //the file that monitor is examining - - // CHANGE, EXISTENCE, NON_EXISTENCE, LAST_MODIFIED_TIME, FILE_COUNT, SIZE - - // ------------------------------------------------------------------------------------------------------------------- - - - // ------------------------------------------------------------------------------------------------------------------- - - public FileMonitor(String dataDirPath, String logFilePath, String fileToMonitorPath) - { - setDataDirPath(dataDirPath); - setLogFilePath(logFilePath); - setFileToMonitorPath(fileToMonitorPath); - } - - abstract public Status monitor(); - - private void setDataDirPath(String dataDirPath) - { - _dataDirPath = dataDirPath; - } - - protected String getDataDirPath() - { - return _dataDirPath; - } - - private void setLogFilePath(String logFilePath) - { - _logFilePath = logFilePath; - } - - protected String getLogFilePath() - { - return _logFilePath; - } - - private void setFileToMonitorPath(String fileToMonitorPath) - { - _fileToMonitorPath = fileToMonitorPath; - } - - protected String getFileToMonitorPath() - { - return _fileToMonitorPath; - } - - - public void setOperator(MonitorOperator operator) - { - _operator = operator; - } - - public MonitorOperator getOperator() - { - return _operator; - } - - - - - -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Monitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Monitor.java deleted file mode 100644 index 8a891adb68..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Monitor.java +++ /dev/null @@ -1,6 +0,0 @@ -package ohd.hseb.monitor; - -public interface Monitor -{ - public Status monitor(); -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorFactory.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorFactory.java deleted file mode 100644 index afe90bafe7..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -package ohd.hseb.monitor; - -public class MonitorFactory -{ - - // ------------------------------------------------------------------------------------------------------------------- - public static Monitor buildLastModifiedTimeFileMonitor(long ageInSeconds, String dataDirPath, String logFilePath, String fileToMonitorPath) - { - FileMonitor monitor = new AgeFileMonitor(ageInSeconds, dataDirPath, logFilePath, fileToMonitorPath ); - - return monitor; - } - - // ------------------------------------------------------------------------------------------------------------------- - public static Monitor buildChangeFileMonitor(String dataDirPath, String logFilePath, String fileToMonitorPath) - { - FileMonitor monitor = new ChangeFileMonitor(dataDirPath, logFilePath, fileToMonitorPath ); - - return monitor; - } - - // ------------------------------------------------------------------------------------------------------------------- - public static Monitor buildExistenceFileMonitor(String dataDirPath, String logFilePath, String fileToMonitorPath) - { - Monitor monitor = new ExistenceFileMonitor(true, dataDirPath, logFilePath, fileToMonitorPath ); - - return monitor; - } - - // ------------------------------------------------------------------------------------------------------------------- - public static Monitor buildNonExistenceFileMonitor(String dataDirPath, String logFilePath, String fileToMonitorPath) - { - Monitor monitor = new ExistenceFileMonitor(false, dataDirPath, logFilePath, fileToMonitorPath ); - - return monitor; - } - - // ------------------------------------------------------------------------------------------------------------------- - public static Monitor buildFileCountFileMonitor(MonitorOperator operator, long fileCount, String dataDirPath, String logFilePath, String fileToMonitorPath) - { - FileMonitor monitor = new CountFileMonitor(operator, fileCount, dataDirPath, logFilePath, fileToMonitorPath ); - - return monitor; - } - - // ------------------------------------------------------------------------------------------------------------------- - public static FileMonitor buildSizeFileMonitor(MonitorOperator operator, long fileSize, String dataDirPath, String logFilePath, String fileToMonitorPath) - { - FileMonitor monitor = new SizeFileMonitor(operator, fileSize, dataDirPath, logFilePath, fileToMonitorPath ); - //monitor.setOperator(operator); - //monitor.setFileCount(fileSize); - - return monitor; - } - // ------------------------------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorManager.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorManager.java deleted file mode 100644 index 6a75568764..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorManager.java +++ /dev/null @@ -1,282 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.HashMap; -import java.util.Map; - - -/* - * - * if (strcasecmp(str, "change") == 0) - function_id = CHANGE; -else if (strcasecmp(str, "existence") == 0) - function_id = EXISTENCE; -else if (strcasecmp(str, "non_existence") == 0) - function_id = NON_EXISTENCE; -else if (strcasecmp(str, "last_modified") == 0) - function_id = LAST_MODIFIED_TIME; -else if (strcasecmp(str, "file_count") == 0) - function_id = FILECOUNT; -else if (strcasecmp(str, "size") == 0) - function_id = SIZE; -else - function_id = INVALID_ARG; - * - * - * $FILE_MONITOR_BIN_DIR/file_monitor.LX -last_modified 3600 $FILE_MONITOR_DATA_DIR $FILE_MONITOR_LOG_FILE $SHEFLOGFILE $FROM_ID $MAIL_LIST "FILE MONITOR: Old Shef Decoder Log" >>$INIT_ERR_LOG_FILE 2>&1 -#$FILE_MONITOR_BIN_DIR/file_monitor.LX -change $FILE_MONITOR_DATA_DIR $FILE_MONITOR_LOG_FILE $GAGEPP_FILTERED_LOG_FILE $FROM_ID $MAIL_LIST "FILE MONITOR: Gage PP Database Errors" >>$INIT_ERR_LOG_FILE 2>&1 -$FILE_MONITOR_BIN_DIR/file_monitor.LX -size -gt 2500 $FILE_MONITOR_DATA_DIR $FILE_MONITOR_LOG_FILE $DPA_FILTERED_LOG_FILE $FROM_ID $MAIL_LIST "FILE MONITOR: Possible DPA Ingest Problem" >>$INIT_ERR_LOG_FILE 2>&1 -$FILE_MONITOR_BIN_DIR/file_monitor.LX -change $FILE_MONITOR_DATA_DIR $FILE_MONITOR_LOG_FILE $FILTERED_PG_FILE $FROM_ID $MAIL_LIST "FILE MONITOR: Change in /var/log/postgres on $HNAME" >>$INIT_ERR_LOG_FILE 2>&1 -$WHFS_BIN_DIR/file_monitor.LX -file_count -gt 10 $LOG_MONITOR_DATA_PATH $LOG_MONITOR_LOG_FILE $SHEF_DATA_DIR $FROM_ID $MAIL_LIST "FILE MONITOR: File Count in Shef Data Directory" >>$INIT_ERR_LOG_FILE 2>&1 - -Standard Args: -$FILE_MONITOR_DATA_DIR $FILE_MONITOR_LOG_FILE $FILE_TO_MONITOR $FROM_ID $MAIL_LIST $MESSAGE_SUBJECT_LINE - --last_modified expireTimeInSeconds --change - --size -operator sizeInBytes --file_count -operator count --existence --non_existence - - */ - -public class MonitorManager -{ - - private String[] _argumentArray = null; - private Monitor _monitor = null; - private Reporter _reporter = null; - - private String _dataDirPath = null; //for monitor's private data - private String _logFilePath = null; //for monitor's log file - private String _fileToMonitorPath = null; //the file that monitor is examining - - //email stuff - private String _fromAddressString = null; - private String _toAddressString = null; - private String _subjectString = null; - - - private static Map _monitorTypeMap = new HashMap(); - private static Map _operatorMap = new HashMap(); - - - static - { - _monitorTypeMap.put("last_modified", MonitorType.LAST_MODIFIED_TIME); - _monitorTypeMap.put("change", MonitorType.CHANGE); - _monitorTypeMap.put("size", MonitorType.SIZE); - _monitorTypeMap.put("file_count", MonitorType.FILE_COUNT); - _monitorTypeMap.put("existence", MonitorType.EXISTENCE); - _monitorTypeMap.put("non_existence", MonitorType.NON_EXISTENCE); - - _operatorMap.put("GT", MonitorOperator.GREATER_THAN); - _operatorMap.put("GTE", MonitorOperator.GREATER_THAN_OR_EQUAL); - - _operatorMap.put("LT", MonitorOperator.LESS_THAN); - _operatorMap.put("LTE", MonitorOperator.LESS_THAN_OR_EQUAL); - _operatorMap.put("EQ", MonitorOperator.EQUAL); - } - - // --------------------------------------------------------------------------------------- - public MonitorManager(String[] argumentArray) - { - _argumentArray = argumentArray; - parseArguments(); - } - // --------------------------------------------------------------------------------------- - private long parseLongArg(int argArrayIndex) - { - String longValueString = _argumentArray[argArrayIndex]; - long value = Long.valueOf(longValueString); - - return value; - } - // --------------------------------------------------------------------------------------- - private String parseStringArgWithDash(int argArrayIndex) - { - String argString = _argumentArray[argArrayIndex]; - String valueString = argString.substring(1); - - return valueString; - } - // --------------------------------------------------------------------------------------- - private void parseArguments() - { - String header = "MonitorManager.parseArguments(): "; - - int i = 0; - for (String arg : _argumentArray) - { - System.out.println("Arg " + i + " = " + arg); - i++; - } - - - MonitorType monitorType = getMonitorType(); - - System.out.println(header + " monitorType = " + getMonitorType()); - - Monitor monitor = null; - - if (monitorType != null) - { - - switch(monitorType) - { - case LAST_MODIFIED_TIME: - { - long ageInSeconds = parseLongArg(1); - - readStandardArguments(2); - - monitor = MonitorFactory.buildLastModifiedTimeFileMonitor(ageInSeconds, _dataDirPath, _logFilePath, _fileToMonitorPath); - break; - } - - - case CHANGE: - { - readStandardArguments(1); - monitor = MonitorFactory.buildChangeFileMonitor(_dataDirPath, _logFilePath, _fileToMonitorPath); - - break; - } - case SIZE: - { - MonitorOperator operator = getOperator(); - long fileSize = parseLongArg(2); - - - readStandardArguments(3); - monitor = MonitorFactory.buildSizeFileMonitor(operator, fileSize, _dataDirPath, _logFilePath, _fileToMonitorPath); - - - break; - } - case FILE_COUNT: - { - MonitorOperator operator = getOperator(); - long fileCount = parseLongArg(2); - - - readStandardArguments(3); - monitor = MonitorFactory.buildFileCountFileMonitor(operator, fileCount, _dataDirPath, _logFilePath, _fileToMonitorPath); - - break; - } - - case EXISTENCE: - { - - readStandardArguments(1); - monitor = MonitorFactory.buildExistenceFileMonitor(_dataDirPath, _logFilePath, _fileToMonitorPath); - - break; - } - - case NON_EXISTENCE: - { - readStandardArguments(1); - monitor = MonitorFactory.buildNonExistenceFileMonitor(_dataDirPath, _logFilePath, _fileToMonitorPath); - - break; - } - - default: - System.err.println("illegal arguments:"); - break; - - } //end switch - - } //end if - - _monitor = monitor; - _reporter = new EmailReporter(_fromAddressString, _toAddressString, _subjectString); - - } - // --------------------------------------------------------------------------------------- - private void readStandardArguments(int arrayIndex) - { - String header = "MonitorManager.readStandardArguments(): "; - - _dataDirPath = _argumentArray[arrayIndex++]; - _logFilePath = _argumentArray[arrayIndex++]; - _fileToMonitorPath = _argumentArray[arrayIndex++]; - _fromAddressString = _argumentArray[arrayIndex++]; - _toAddressString = _argumentArray[arrayIndex++]; - _subjectString = _argumentArray[arrayIndex++]; - - System.out.println(header + " _subjectString = " + _subjectString); - - return; - - } - // --------------------------------------------------------------------------------------- - private MonitorType getMonitorType() - { - - String monitorTypeString = parseStringArgWithDash(0); - MonitorType type = _monitorTypeMap.get(monitorTypeString); - return type; - } - - // --------------------------------------------------------------------------------------- - - private MonitorOperator getOperator() - { - String header = "MonitorManager.getOperator(): "; - String operatorString = parseStringArgWithDash(1).toUpperCase(); - System.out.println(header + " operatorString = " + operatorString); - MonitorOperator operator = _operatorMap.get(operatorString); - - if (operator != null) - { - System.out.println(header + "operator = " + operator.getSymbol()); - } - - return operator; - } - - - // --------------------------------------------------------------------------------------- - public Monitor getMonitor() - { - - return _monitor; - } - - // --------------------------------------------------------------------------------------- - public Reporter getReporter() - { - - return _reporter; - } - - // --------------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - MonitorManager manager = new MonitorManager(argArray); - - Monitor monitor = manager.getMonitor(); - - Reporter reporter = manager.getReporter(); - - - Status status = null; - if (monitor != null) - { - status = monitor.monitor(); - } - - if (status != null) - { - reporter.report(status); - } - - return; - - } - // --------------------------------------------------------------------------------------- -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorOperator.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorOperator.java deleted file mode 100644 index 1aa1a0ed74..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorOperator.java +++ /dev/null @@ -1,103 +0,0 @@ -package ohd.hseb.monitor; - -import java.util.HashMap; -import java.util.Map; - -public class MonitorOperator -{ - - // static stuff ----------------------------------------------------------------- - private static final int GT = 0; - private static final int GTE = 1; - private static final int EQ = 2; - private static final int LT = 3; - private static final int LTE = 4; - - public static final MonitorOperator GREATER_THAN = new MonitorOperator(GT); - public static final MonitorOperator GREATER_THAN_OR_EQUAL = new MonitorOperator(GTE); - public static final MonitorOperator EQUAL = new MonitorOperator(EQ); - public static final MonitorOperator LESS_THAN = new MonitorOperator(LT); - public static final MonitorOperator LESS_THAN_OR_EQUAL = new MonitorOperator(LTE); - - private static final Map _operatorSymbolMap = new HashMap() ; - - static - { - _operatorSymbolMap.put(GT, ">"); - _operatorSymbolMap.put(GTE, ">="); - _operatorSymbolMap.put(EQ, "=="); - _operatorSymbolMap.put(LT, "<"); - _operatorSymbolMap.put(LTE, "<="); - } - - // ---------------------------------------------------------------------------- - - private String _name = null; - private int _typeCode; - - // ---------------------------------------------------------------------------- - private MonitorOperator(int typeCode) - { - _typeCode = typeCode; - } - - // ---------------------------------------------------------------------------- - public String getSymbol() - { - return _operatorSymbolMap.get(_typeCode); - } - - // ---------------------------------------------------------------------------- - - public boolean evaluate(long value1, long value2) - { - boolean result = false; - - switch(_typeCode) - { - case GT: - { - result = (value1 > value2); - break; - } - - case GTE: - { - result = (value1 >= value2); - break; - } - - case EQ: - { - result = (value1 == value2); - break; - } - - case LT: - { - result = (value1 < value2); - break; - } - - case LTE: - { - result = (value1 <= value2); - break; - } - default: - { - throw new Error("Invalid type code"); - } - - } - - return result; - } - - // ---------------------------------------------------------------------------- - - - // ---------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorType.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorType.java deleted file mode 100644 index b4913be3b8..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/MonitorType.java +++ /dev/null @@ -1,8 +0,0 @@ -package ohd.hseb.monitor; - -public enum MonitorType -{ - - CHANGE, EXISTENCE, NON_EXISTENCE, LAST_MODIFIED_TIME, FILE_COUNT, SIZE - -}; diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Reporter.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Reporter.java deleted file mode 100644 index ceaa8701dd..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Reporter.java +++ /dev/null @@ -1,6 +0,0 @@ -package ohd.hseb.monitor; - -public interface Reporter -{ - public void report(Status status); -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/SizeFileMonitor.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/SizeFileMonitor.java deleted file mode 100644 index b44b7b0777..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/SizeFileMonitor.java +++ /dev/null @@ -1,77 +0,0 @@ -package ohd.hseb.monitor; - -import java.io.File; - - -public class SizeFileMonitor extends FileMonitor -{ - - private long _fileSize = -1; - - // -------------------------------------------------------------------------------------- - - public SizeFileMonitor(MonitorOperator operator, long fileSize, - String dataDirPath, String logFilePath, String fileToMonitorPath) - { - super(dataDirPath, logFilePath, fileToMonitorPath); - setOperator(operator); - setFileSize(fileSize); - - } - // -------------------------------------------------------------------------------------- - - - public void setFileSize(long fileSize) - { - _fileSize = fileSize; - } - // -------------------------------------------------------------------------------------- - - public long getFileSize() - { - return _fileSize; - } - // -------------------------------------------------------------------------------------- - - - @Override - public Status monitor() - { - //String header = "SizeFileMonitor.monitor(): "; - Status status = null; - File file = new File(getFileToMonitorPath()); - - //System.out.println(header); - - if (file != null) - { - - long actualFileSize = file.length(); - - - long comparisonFileSize = getFileSize(); - - MonitorOperator operator = getOperator(); - - boolean result = operator.evaluate(actualFileSize, comparisonFileSize); - - if (result) - { - status = new TextStatus( getFileToMonitorPath() + " contains " + actualFileSize + - " files, which is "+ operator.getSymbol() + " " + comparisonFileSize ); - } - else - { - //System.out.println(header + "monitoring " + getFileToMonitorPath() + " and there are " + actualFileSize + " files present. "); - } - } - else - { - //System.out.println(header + " file is null"); - } - - return status; - } - // -------------------------------------------------------------------------------------- - -} //end class SizeFileMonitor diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Status.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Status.java deleted file mode 100644 index 19a33f9eab..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/Status.java +++ /dev/null @@ -1,6 +0,0 @@ -package ohd.hseb.monitor; - -public interface Status -{ - -} diff --git a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/TextStatus.java b/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/TextStatus.java deleted file mode 100644 index 0638e73e6c..0000000000 --- a/javaUtilities/hydro/ohd.sys_monitor/src/ohd/hseb/monitor/TextStatus.java +++ /dev/null @@ -1,28 +0,0 @@ -package ohd.hseb.monitor; - -public class TextStatus implements Status -{ - private String _text; - - - public TextStatus(String text) - { - setText(text); - } - - public void setText(String text) - { - _text = text; - } - - public String getText() - { - return _text; - } - - public String toString() - { - return getText(); - } - -} // TestStatus diff --git a/javaUtilities/hydro/ohd.tsl/.classpath b/javaUtilities/hydro/ohd.tsl/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.tsl/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.tsl/.project b/javaUtilities/hydro/ohd.tsl/.project deleted file mode 100644 index 30328a36fe..0000000000 --- a/javaUtilities/hydro/ohd.tsl/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.tsl - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.tsl/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.tsl/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 0228e42c5a..0000000000 --- a/javaUtilities/hydro/ohd.tsl/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:41:32 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.tsl/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.tsl/META-INF/MANIFEST.MF deleted file mode 100644 index 5a1440b2f7..0000000000 --- a/javaUtilities/hydro/ohd.tsl/META-INF/MANIFEST.MF +++ /dev/null @@ -1,17 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Tsl -Bundle-SymbolicName: ohd.tsl -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.pdc_pp;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0", - ohd.ihfsdb;bundle-version="1.0.0" -Export-Package: ohd.hseb.gui.util, - ohd.hseb.model, - ohd.hseb.timeserieslite, - ohd.hseb.timeserieslite.gui.drawing, - ohd.hseb.timeserieslite.pdc, - ohd.hseb.timeserieslite.rivermon diff --git a/javaUtilities/hydro/ohd.tsl/build.properties b/javaUtilities/hydro/ohd.tsl/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.tsl/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.tsl/build.xml b/javaUtilities/hydro/ohd.tsl/build.xml deleted file mode 100644 index a9bb79adab..0000000000 --- a/javaUtilities/hydro/ohd.tsl/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.tsl/ohd.tsl.ecl b/javaUtilities/hydro/ohd.tsl/ohd.tsl.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.tsl/scripts/run_pdc_tsl b/javaUtilities/hydro/ohd.tsl/scripts/run_pdc_tsl deleted file mode 100644 index 403a6ebe9a..0000000000 --- a/javaUtilities/hydro/ohd.tsl/scripts/run_pdc_tsl +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/ksh - -# File name: run_pdc_pp -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -export CONNECTION_STRING=$JDBCURL -#export CONNECTION_STRING=jdbc:postgresql://lx1-nhdr:5432/hd_ob6rhax?user=oper - -#get java dir -export SYS_JAVA_DIR=$($GAD_DIR/get_apps_defaults$OS_SUFFIX sys_java_dir) -export SYS_JAVA_BIN_DIR=$SYS_JAVA_DIR/bin - -#truncate the timeseries lite log -#export LOGFILE=$PDC_PP_LOG_DIR/PDCPreprocessor.log -#export LOGFILE_TMP=$PDC_PP_LOG_DIR/PDCPreprocessor.tmp -#tail -12000 $LOGFILE > $LOGFILE_TMP -#mv $LOGFILE_TMP $LOGFILE - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH:$WHFS_BIN_DIR/timeserieslite.jar - -#AMIRUNNING_DIR=$PDC_PP_LOG_DIR -#. /awips/hydroapps/public/bin/amirunning - -#if [[ $AmIRunning = "yes" ]] -#then -# echo Startup cancelled because of prior running instance >> $LOGFILE -# exit 1 -#fi - -echo - -export LID=$1 -export PARAMCODE1=$2 -export PARAMCODE2=$3 -export PARAMCODE3=$4 -export PARAMCODE4=$5 -export PARAMCODE5=$6 - - -#Execute TimeSeries Lite -$SYS_JAVA_BIN_DIR/java ohd.hseb.timeserieslite.TimeSeriesLite ohd.hseb.timeserieslite.pdc.PDCDrawingMgr $CONNECTION_STRING $LID $PARAMCODE1 $PARAMCODE2 $PARAMCODE3 $PARAMCODE4 $PARAMCODE5 -exit diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/gui/util/ScreenCaptureActionListener.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/gui/util/ScreenCaptureActionListener.java deleted file mode 100644 index fae87df312..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/gui/util/ScreenCaptureActionListener.java +++ /dev/null @@ -1,203 +0,0 @@ -package ohd.hseb.gui.util; - -import java.awt.AWTException; -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Robot; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.imageio.stream.FileImageOutputStream; -import javax.imageio.stream.ImageOutputStream; -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileFilter; - -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.ExtensionFileFilter; - -public class ScreenCaptureActionListener implements ActionListener -{ - - private JFileChooser _imageFileChooser = null; - private Window _baseWindow = null; - private Component _componentToCapture = null; - - // ------------------------------------------------------------------------------------- - - public ScreenCaptureActionListener(Window componentToCapture) - { - _componentToCapture = componentToCapture; - _baseWindow = componentToCapture; - - return; - } - - // ------------------------------------------------------------------------------------- - - public ScreenCaptureActionListener(Window baseWindow, Component componentToCapture) - { - _baseWindow = baseWindow; - _componentToCapture = componentToCapture; - - return; - } - - - // ------------------------------------------------------------------------------------- - - - public void actionPerformed(ActionEvent event) - { - this.displayCaptureScreenFileChooser(); - - } //end actionPerformed - - // ------------------------------------------------------------------------------------- - - - private void displayCaptureScreenFileChooser() - { - BufferedImage image = captureScreenToImage(); - - if (_imageFileChooser == null) - { - AppsDefaults ad = new AppsDefaults(); - - String defaultDirectory = ad.getToken("whfs_image_dir"); - _imageFileChooser = new JFileChooser(defaultDirectory); - } - - - //add a FileFilter for JPG files - List filterList = new ArrayList(); - - filterList.add( "JPEG" ); - filterList.add("JPG"); - FileFilter fileFilter = new ExtensionFileFilter( filterList, "JPEG Image Files (*.jpg, *.JPG) "); - - - //set the file filter - _imageFileChooser.setFileFilter( fileFilter ); - // _imageFileChooser.set - - - //open the dialog - int returnVal = _imageFileChooser.showSaveDialog(_baseWindow); - - if (returnVal == JFileChooser.APPROVE_OPTION) - { - File file = _imageFileChooser.getSelectedFile(); - - //ensure ends in ".jpg" - if ( (! file.getName().endsWith(".jpg")) && - (! file.getName().endsWith(".JPG")) - ) - { - String newFilePath = file.getPath() + ".jpg"; - file = new File(newFilePath); - } - - writeImageToFile(image, file); - } - - else - { - DialogHelper.displayMessageDialog(_baseWindow, "Image file not saved."); - } - - return; - } - - // ----------------------------------------------------------------- - - private BufferedImage captureScreenToImage() - { - - String header = "ScreenCaptureActionListener.captureScreenToImage(): "; - - BufferedImage bufferedImage = null; - try - { - - Robot robot = new Robot(); - Rectangle boundsRectangle = null; - - if (_componentToCapture != _baseWindow) - { - - Point origin = getOriginRelativeToScreen(_componentToCapture); - // _componentToCapture.get - Rectangle componentBounds = _componentToCapture.getBounds(); - boundsRectangle = new Rectangle(origin.x, - origin.y, - componentBounds.width, - componentBounds.height); - - } - else - { - boundsRectangle = _baseWindow.getBounds(); - } - - bufferedImage = robot.createScreenCapture(boundsRectangle); - - } //end try - - catch (AWTException e) - { - e.printStackTrace(); - } - - - return bufferedImage; - } - - // ----------------------------------------------------------------- - private Point getOriginRelativeToScreen(Component component) - { - - int x = 0; - int y = 0; - - Component parent = component; - - while (parent != null) - { - x += parent.getX(); - y += parent.getY(); - - parent = parent.getParent(); - } - - return new Point(x, y); - - } - // ----------------------------------------------------------------- - - private void writeImageToFile(BufferedImage image, File file) - { - try - { - ImageOutputStream imageOutputStream = new FileImageOutputStream(file); - ImageIO.write(image, "JPG", imageOutputStream); - imageOutputStream.close(); - } - - catch(java.io.IOException e ) - { - e.printStackTrace(); - } - - return; - } - // ----------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/model/FlowToStageValueMapper.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/model/FlowToStageValueMapper.java deleted file mode 100644 index fdc9852309..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/model/FlowToStageValueMapper.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Created on Oct 22, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; - - -import ohd.hseb.util.ValueMapper; - -/** - * @author GobsC - * - * This implementation of ValueMapper maps river stages to discharge. - */ -public class FlowToStageValueMapper implements ValueMapper -{ - private MeasuringUnit _inputMeasuringUnit = MeasuringUnit.cfs; - private MeasuringUnit _outputMeasuringUnit = MeasuringUnit.feet; - - - private RatingCurve _ratingCurve = null; - - //-------------------------------------------------------- - - public FlowToStageValueMapper(RatingCurve ratingCurve) - { - _ratingCurve = ratingCurve; - } - //-------------------------------------------------------- - - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement resultMeasurement = null; - - double keyValue = inputMeasurement.getValue(_inputMeasuringUnit); - - double resultValue = 0; - if (_ratingCurve != null) - { - resultValue = _ratingCurve.getStageFromDischarge(keyValue); - resultMeasurement = new Measurement(resultValue, - _outputMeasuringUnit); - } - - return resultMeasurement; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - //-------------------------------------------------------- - - - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - //-------------------------------------------------------- - -} // StageToFlowValueMapper diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/model/PrecipPPAndPCValueMapper.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/model/PrecipPPAndPCValueMapper.java deleted file mode 100644 index 8ad071a110..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/model/PrecipPPAndPCValueMapper.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Created on Oct 23, 2003 - * - * - */ -package ohd.hseb.model; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.ValueMapper; - -/** - * @author GobsC - * - * - */ -public class PrecipPPAndPCValueMapper implements ValueMapper -{ - - private MeasuringUnit _inputMeasuringUnit = null; - private MeasuringUnit _outputMeasuringUnit = null; - private double _difference = 0; - - // -------------------------------------------------------------------------- - - public PrecipPPAndPCValueMapper(double minValue1, - double minValue2, - MeasuringUnit unit) - { - _difference = minValue2 - minValue1; - - _inputMeasuringUnit = unit; - _outputMeasuringUnit = unit; - - return; - } - - // -------------------------------------------------------------------------- - - public Measurement getResultMeasurement(Measurement inputMeasurement) - { - Measurement convertedMeasurement = inputMeasurement.getCopy(); - double value = convertedMeasurement.getValue(); - value += _difference; - - convertedMeasurement.setValue(value); - - return convertedMeasurement; - - } - - // -------------------------------------------------------------------------- - - public MeasuringUnit getInputMeasuringUnit() - { - return _inputMeasuringUnit; - } - - // -------------------------------------------------------------------------- - - public MeasuringUnit getOutputMeasuringUnit() - { - return _outputMeasuringUnit; - } - // -------------------------------------------------------------------------- - - - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/Location.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/Location.java deleted file mode 100644 index 3024bc7c44..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/Location.java +++ /dev/null @@ -1,199 +0,0 @@ -package ohd.hseb.timeserieslite; - -import ohd.hseb.model.RatingCurve; - -public class Location -{ - private String _lid = null; - private double _lat = 0; - private double _lon = 0; - private double _elevation = 0; - private String _locationName = null; - private boolean _isRiverStation = false; - private boolean _isFcstPoint = false; - private String _hsa = null; - private double _floodStage = 0; - private double _floodFlow = 0; - private RatingCurve _ratingCurve = null; - private boolean _isDCP = false; - private boolean _isObserver = false; - private String _telemType = null; - - public Location() - { - } - - public Location( Location location ) - { - _lid = location.getLid(); - _hsa = location.getHsa(); - _lat = location.getLat(); - _lon = location.getLon(); - _elevation = location.getElevation(); - _locationName = location.getLocationName(); - _isRiverStation = location.isRiverStation(); - _floodStage = location.getFloodStage(); - _floodFlow = location.getFloodFlow(); - _ratingCurve = location.getRatingCurve(); - _isDCP = location.isDCP(); - _isObserver = location.isObserver(); - _telemType = location.getTelemType(); - } - - public String toString() - { - String string = null; - - string = "LID = " + _lid + - " HSA = " + _hsa + - " Lat = " + _lat + - " Lon = " + _lon + - " Elev = " + _elevation + - " Location Name = " + _locationName + - " RiverStation = " + _isRiverStation + - " Flood Stage = " + _floodStage + - " Flood Flow = " + _floodFlow + - " DCP = " + _isDCP + - " Observer = " + _isObserver + - " Telem Type = " + _telemType; - - return string; - } - public void setLid( String lid ) - { - _lid = lid; - } - public String getLid() - { - return _lid; - } - public void setLat( double lat ) - { - _lat = lat; - } - public double getLat() - { - return _lat; - } - public void setLon( double lon ) - { - _lon = lon; - } - public double getLon() - { - return _lon; - } - public void setElevation( double elevation ) - { - _elevation = elevation; - } - public double getElevation() - { - return _elevation; - } - public void setLocationName( String locationName ) - { - _locationName = locationName; - } - public String getLocationName() - { - return _locationName; - } - - public void setRiverStation( boolean isRiverStation ) - { - _isRiverStation = isRiverStation; - } - - public boolean isRiverStation() - { - return _isRiverStation; - } - - public void setFloodStage( double floodStage ) - { - _floodStage = floodStage; - } - - public double getFloodStage() - { - return _floodStage; - } - - public void setHsa( String hsa ) - { - _hsa = hsa; - } - - public String getHsa() - { - return _hsa; - } - - public void setFcstPoint( boolean isFcstPoint ) - { - _isFcstPoint = isFcstPoint; - } - - public String isFcstPoint() - { - if ( _isFcstPoint ) - { - return "T"; - } - else - { - return "F"; - } - } - - public void setFloodFlow( double floodFlow ) - { - _floodFlow = floodFlow; - } - - public double getFloodFlow() - { - return _floodFlow; - } - - public void setRatingCurve( RatingCurve ratingCurve ) - { - _ratingCurve = ratingCurve; - } - - public RatingCurve getRatingCurve() - { - return _ratingCurve; - } - - public void setDCP( boolean isDCP ) - { - _isDCP = isDCP; - } - - public boolean isDCP() - { - return _isDCP; - } - - public void setObserver( boolean isObserver ) - { - _isObserver = isObserver; - } - - public boolean isObserver() - { - return _isObserver; - } - - public void setTelemType( String telemType ) - { - _telemType = telemType; - } - - public String getTelemType() - { - return _telemType; - } -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/PDCDataType.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/PDCDataType.java deleted file mode 100644 index 7d15ab8536..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/PDCDataType.java +++ /dev/null @@ -1,80 +0,0 @@ -package ohd.hseb.timeserieslite; - - -import java.util.HashMap; -import java.util.Map; - -public class PDCDataType -{ - private static Map _dataTypeMap = new HashMap(); - - - public final static PDCDataType HEIGHT = new PDCDataType("Height"); - public final static PDCDataType DISCHARGE = new PDCDataType("Discharge"); - public final static PDCDataType LAKE_STORAGE = new PDCDataType("Lake Storage"); - - public final static PDCDataType PRECIP_TOTAL = new PDCDataType("Precip Totals"); - public final static PDCDataType PRECIP_PC = new PDCDataType("Precip PC"); - - public final static PDCDataType SNOW_DEPTH = new PDCDataType("Snow Depth"); - public final static PDCDataType SNOW_WATER_EQUIVALENT = new PDCDataType("Snow Water Equivalent"); - - public final static PDCDataType TEMPERATURE = new PDCDataType("Temperature"); - public final static PDCDataType DEWPOINT = new PDCDataType("Dewpoint"); - - public final static PDCDataType RELATIVE_HUMIDITY = new PDCDataType("Relative Humidity"); - - public final static PDCDataType WIND_SPEED = new PDCDataType("Wind Speed"); - public final static PDCDataType WIND_DIRECTION = new PDCDataType("Wind Direction"); - - - //---------------------------------------------------------------------------- - - private String _name; - - //---------------------------------------------------------------------------- - private PDCDataType() - { - - } - - //---------------------------------------------------------------------------- - private PDCDataType(String name) - { - _name = name; - - if (_dataTypeMap == null) - { - _dataTypeMap = new HashMap(); - } - - _dataTypeMap.put(name.toLowerCase(), this); - - return; - } - //---------------------------------------------------------------------------- - - public String getName() - { - return _name; - } - - //---------------------------------------------------------------------------- - - - public static PDCDataType getDataTypeFromString(String name) - { - PDCDataType dataType = (PDCDataType) _dataTypeMap.get(name.toLowerCase()); - - return dataType; - } - - // ---------------------------------------------------------------------------- - - - public String toString() - { - return _name; - } - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/ParamCode.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/ParamCode.java deleted file mode 100644 index dd402bdb58..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/ParamCode.java +++ /dev/null @@ -1,264 +0,0 @@ -package ohd.hseb.timeserieslite; - -import java.util.HashMap; -import java.util.Map; - -public class ParamCode -{ - private String _paramCodeString = null; - - private static final Map _shefDurCodeToIhfsDurCodeMap = new HashMap(); - private static final Map _ihfsDurCodeToShefDurCodeMap = new HashMap(); - - private String _pe = null; - private String _typeSource = null; - private int _ihfsDur = 0; - private String _shefDur = null; - private String _extremum = null; - - static - { - initDurationCodeMaps(); - } - - // ------------------------------------------------------------------------------- - public ParamCode(String paramCodeString) - { - _paramCodeString = paramCodeString; - parse(paramCodeString); - - return; - } - // ------------------------------------------------------------------------------- - - public ParamCode(ParamCode paramCode) - { - _pe = paramCode.getPe(); - _typeSource = paramCode.getTypeSource(); - _ihfsDur = paramCode.getIhfsDur(); - _shefDur = paramCode.getShefDur(); - _extremum = paramCode.getExtremum(); - _paramCodeString = paramCode._paramCodeString; - - - return; - } - // ------------------------------------------------------------------------------- - // ------------------------------------------------------------------------------- - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getPe() + - getShefDur() + - getTypeSource() + - getExtremum() ); - - return buffer.toString(); - } - - // ------------------------------------------------------------------------------- - - public String toStringVerbose() - { - StringBuffer buffer = new StringBuffer(); - - - buffer.append("pe = " + getPe() + - " dur = " + getIhfsDur() + - " ts = " + getTypeSource() + - " extremum = " + getExtremum() ); - - return buffer.toString(); - - } - // ------------------------------------------------------------------------------- - - private void parse(String paramCodeString) - { - - setPe(paramCodeString.substring(0,2)); - _shefDur = paramCodeString.substring(2,3); - - _ihfsDur = getIhfsDurationCode(_shefDur); - - setTypeSource(paramCodeString.substring(3,5)); - setExtremum(paramCodeString.substring(5,6)); - - return; - } - // ------------------------------------------------------------------------------- - private static void initDurationCodeMaps() - { - - /* - 0 | I | Instantaneous - 1 | U | 1 Minute - 15 | C | 15 Minutes - 30 | J | 30 Minutes - 1001 | H | 1 Hour - 1002 | B | 2 Hour - 1003 | T | 3 Hour - 1004 | F | 4 Hour - 1006 | Q | 6 Hour - 1008 | A | 8 Hour - 1012 | K | 12 Hour - 1018 | L | 18 Hour - 2001 | D | 1 Day - 2007 | W | 1 Week - 3001 | M | 1 Month - 4001 | Y | 1 Year - 5000 | Z | Unspecified - 5001 | S | Seasonal - 5002 | R | Period of Record - 5004 | P | Total Since 7 AM - 5005 | X | Unknown - - */ - - - String code = "?"; - - String charCodeString = "IUCJHBTFQAKLDWMYZSRPX"; - - int intCodeArray[] = { 0, 1, 15, 30, - 1001, 1002, 1003, 1004, 1006, 1008, 1012, 1018, - 2001, 2007, - 3001, - 4001, - 5000, 5001, 5002, 5004, 5005 }; - - - - int i = 0; - - for (i = 0; i < charCodeString.length(); i++) - { - String shefCode = charCodeString.substring(i, i+1); - Integer intCode = new Integer(intCodeArray[i]); - - _shefDurCodeToIhfsDurCodeMap.put(shefCode, intCode); - _ihfsDurCodeToShefDurCodeMap.put(intCode, shefCode); - } - - return; - - } - // ------------------------------------------------------------------------------- - public static int getIhfsDurationCode(String shefDurationCode) - { - int ihfsCode = -1; - Integer ihfsCodeInteger = (Integer) _shefDurCodeToIhfsDurCodeMap.get(shefDurationCode); - - if (ihfsCodeInteger != null) - { - ihfsCode = ihfsCodeInteger.intValue(); - } - - return ihfsCode; - } - // ------------------------------------------------------------------------------- - public static String getShefDurationCode(int ihfsDurationCode) - { - String shefDurationCode = "?"; - - Integer ihfsDurationCodeInteger = new Integer(ihfsDurationCode); - - String shefDurationCodeFromMap = - (String) _ihfsDurCodeToShefDurCodeMap.get(ihfsDurationCodeInteger); - - if (shefDurationCodeFromMap != null) - { - shefDurationCode = shefDurationCodeFromMap; - } - - return shefDurationCode; - } - /** - * @param pe The pe to set. - */ - public void setPe(String pe) - { - _pe = pe; - } - /** - * @return Returns the pe. - */ - public String getPe() - { - return _pe; - } - /** - * @param typeSource The typeSource to set. - */ - public void setTypeSource(String typeSource) - { - _typeSource = typeSource; - } - /** - * @return Returns the typeSource. - */ - public String getTypeSource() - { - return _typeSource; - } - /** - * @param ihfsDur The ihfsDur to set. - */ - public void setIhfsDur(int ihfsDur) - { - _ihfsDur = ihfsDur; - } - /** - * @return Returns the ihfsDur. - */ - public int getIhfsDur() - { - return _ihfsDur; - } - /** - * @param shefDur The shefDur to set. - */ - public void setShefDur(String shefDur) - { - _shefDur = shefDur; - } - /** - * @return Returns the shefDur. - */ - public String getShefDur() - { - return _shefDur; - } - /** - * @param extremum The extremum to set. - */ - public void setExtremum(String extremum) - { - _extremum = extremum; - } - /** - * @return Returns the extremum. - */ - public String getExtremum() - { - return _extremum; - } - - // ------------------------------------------------------------------------------- - public static void main(String[] argArray) - { - ParamCode code = null; - - code = new ParamCode("HGIRGZ"); - System.out.println("code = " + code.toString()); - - - code = new ParamCode("HPIRZX"); - System.out.println("code = " + code.toString()); - - } - - // ------------------------------------------------------------------------------- - -} //end ParamCode diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TSLDrawingMgr.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TSLDrawingMgr.java deleted file mode 100644 index 456ddd6cc2..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TSLDrawingMgr.java +++ /dev/null @@ -1,13 +0,0 @@ -package ohd.hseb.timeserieslite; - -//import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public interface TSLDrawingMgr -{ - - public void display(String[] argStringArray, boolean exitOnClose); - - - // public MeasuringUnit getMeasuringUnit(); - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TSLFrame.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TSLFrame.java deleted file mode 100644 index cdb06fb805..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TSLFrame.java +++ /dev/null @@ -1,304 +0,0 @@ -package ohd.hseb.timeserieslite; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.KeyStroke; -import javax.swing.border.Border; - -import ohd.hseb.gui.util.ScreenCaptureActionListener; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.DialogHelper; -import ohd.hseb.util.gui.WindowResizingManager; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; -//------------------------------------------------------------------------------ - - -public class TSLFrame extends JFrame -{ - //------------------------------------------------------------------------------ - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - private static final int HOURS_TO_ROUND = 6; - - //window sizing variables - private Dimension _minSize = new Dimension(250, 250); - private Dimension _maxSize = new Dimension(1000, 1000); - private Dimension _initialSize = new Dimension(500, 500); - - - private JMenuBar _menuBar = null; - private JPanel _mainPanel = null; - - private TsPaintableCanvas _canvas = null; - private ValueMapper _rightAxisValueMapper = null; - - private boolean _exitOnClose = false; - - //------------------------------------------------------------------------------ - - public TSLFrame() - { - initGui(); - - return; - } - - // --------------------------------------------------------------------------------- - - public void setTimeWindow(long startTime, long endTime) - { - _canvas.setTimeWindow(startTime, endTime); - - return; - } - - //------------------------------------------------------------------------------ - public TsPaintableCanvas getCanvas() - { - - return _canvas; - - } - - //------------------------------------------------------------------------------ - - public void setExitOnClose(boolean exitOnClose) - { - _exitOnClose = exitOnClose; - - return; - } - //------------------------------------------------------------------------------ - - private void initGui() - { - setAlwaysOnTop(true); - - // canvas needs to be initialized before the menu bar, - // because of the screen capturer - initCanvas(0, 0, - _initialSize.width, - _initialSize.height); - - - this.setTitle("TimeSeriesLite"); - - initMenuBar(); - - //limit the range of the resizing - // this object can be local because it remains in memory as a listener - WindowResizingManager manager = new WindowResizingManager(this, _minSize, _maxSize); - - _mainPanel = new JPanel(); - _mainPanel.setBackground(Color.red); - - setLayout(); - - addListeners(); - - this.getContentPane().add(_mainPanel); - this.pack(); - - } - - //----------------------------------------------------------------- - private void setLayout() - { - _mainPanel.setLayout(new GridBagLayout()); - GridBagConstraints mainPanelGbc = new GridBagConstraints(); - mainPanelGbc.fill = GridBagConstraints.BOTH; - -// col, row numCols numRows Wcol wrow - - if (_canvas == null) - { - System.out.println("Canvas is null"); - } - addComponent(_mainPanel, _canvas, mainPanelGbc, 0, 0, 1, 1, 1, 1); - - return; - } - - //----------------------------------------------------------------- - private void addComponent(Container container, - Component component, - GridBagConstraints gbc, - int column, int row, - int columnCells, int rowCells, - int weightX, int weightY) - { - - // how much it can grow in the X and Y directions - gbc.weightx = weightX; - gbc.weighty = weightY; - - // what row and column it starts in - gbc.gridx = column; - gbc.gridy = row; - - //the number of columns and rows it takes up - gbc.gridwidth = columnCells; - gbc.gridheight = rowCells; - - container.add(component, gbc); - - return; - } - - //----------------------------------------------------------------- - - - private void initMenuBar() - { - _menuBar = new JMenuBar(); - - ScreenCaptureActionListener screenCaptureActionListener = - new ScreenCaptureActionListener(this, _canvas); - - - JMenu menu = null; - JMenuItem menuItem = null; - - //File Menu - menu = new JMenu("File"); - menu.setMnemonic(KeyEvent.VK_F); - menu.getAccessibleContext().setAccessibleDescription( - "Access File Menus"); - _menuBar.add(menu); - - - menuItem = new JMenuItem("Close Window"); - menuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, ActionEvent.ALT_MASK)); - menuItem.getAccessibleContext().setAccessibleDescription( - "Close this Window."); - menuItem.addActionListener(new CloseListener()); - menu.add(menuItem); - - - // create a button directly on the menuBar - - Color menuBarColor = _menuBar.getBackground(); - Border invisibleBorder = BorderFactory.createLineBorder(menuBarColor); - - JButton saveButton = new JButton(" Save Screen "); - saveButton.addActionListener(screenCaptureActionListener); - saveButton.setBorder(invisibleBorder); - saveButton.setSize(60, 30); - String saveButtonTooltipText = "Capture the screen to a file."; - saveButton.setToolTipText(saveButtonTooltipText); - _menuBar.add(saveButton); - - - HelpActionListener helpActionListener = new HelpActionListener(); - JButton helpButton = new JButton("Help"); - helpButton.addActionListener(helpActionListener); - helpButton.setBorder(invisibleBorder); - helpButton.setSize(60, 30); - _menuBar.add(helpButton); - - - - //add to the Frame - setJMenuBar(_menuBar); - } - - //----------------------------------------------------------------- - - private void addListeners() - { - - //allow the frame to close when the user presses the close-box - addWindowListener(new FrameCloseWindowListener()); - - } - //-----------------------------------------------------------------\ - - private void close() - { - dispose(); - - if (_exitOnClose) - { - // System.exit(0); - } - } - - //----------------------------------------------------------------- - - private class CloseListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - close(); - } - } - - //----------------------------------------------------------------- - - - private class FrameCloseWindowListener extends WindowAdapter - { - public void windowClosing(WindowEvent evt) - { - close(); - } - - } - // ------------------------------------------------------------------------------------ - - private class HelpActionListener implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - String message = "The yellow time series is observed.\n" + - "The green time series is forecast. \n" + - "The vertical yellow line is current time.\n" + - "The horizontal yellow and red lines are action and flood levels,\n" + - "respectively (if applicable)."; - - DialogHelper.displayMessageDialog(TSLFrame.this, message, "TimeSeriesLite Help"); - } - - } - // ------------------------------------------------------------------------------------ - private void initCanvas(int x, int y, - int width, int height) - - { - - MeasuringUnit measuringUnit = MeasuringUnit.feet; - - _canvas = new TsPaintableCanvas( - measuringUnit, - x, y, - width, height); - - _canvas.setPreferredSize(_initialSize); - _canvas.setMinimumSize(_minSize); - - } //end initCanvas - - - // --------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TimeSeriesLite.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TimeSeriesLite.java deleted file mode 100644 index 1fd9e33210..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/TimeSeriesLite.java +++ /dev/null @@ -1,220 +0,0 @@ -package ohd.hseb.timeserieslite; - -import ohd.hseb.util.CodeTimer; -//import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - - -public class TimeSeriesLite -{ -// ------------------------------------------------------------------------------------- - - //accepted as command-line arguments - //private String _locationId = null; - private String _drawingManagerClassName = null; - - //internal variables - private TSLDrawingMgr _drawingMgr = null; - - // ------------------------------------------------------------------------------------- - - private void readCommandLineArgs(String[] argStringArray) - { - if (argStringArray.length > 1) - { - //_locationId = argStringArray[0]; - _drawingManagerClassName = argStringArray[0]; - } - else - { - System.out.println("usage: java " + - this.getClass().getName() + - "dataManagerClassName "); - } - - return; - } - -// ------------------------------------------------------------------------------------- - - private void loadDrawingManager(String[] argumentStringArray) - { - String header = "TimeSeriesList.loadDataManager(): "; - - try - { - Class drawingManagerClass = Class.forName(_drawingManagerClassName); - - _drawingMgr = (TSLDrawingMgr) drawingManagerClass.newInstance(); - //_drawingMgr.handleCommandLineArgs(argumentStringArray); - - System.out.println(header + "_drawingMgr's class name = " + - _drawingMgr.getClass().getName()); - - - } - catch (ClassNotFoundException e) - { - e.printStackTrace(); - } - catch (IllegalAccessException e) - { - e.printStackTrace(); - } - catch (InstantiationException e) - { - e.printStackTrace(); - } - - return; - } -// ------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) - { - CodeTimer timer = new CodeTimer(); - String header = "TimeSeriesLite.display(): "; - - readCommandLineArgs(argStringArray); - - timer.start(); - loadDrawingManager(argStringArray); - timer.stop("loadDrawingManager() took "); - - if (_drawingMgr != null) - { - _drawingMgr.display(argStringArray, exitOnClose); - - } - - else - { - System.out.println(header + "_drawingMgr == null"); - } - - return; - - } - -// ------------------------------------------------------------------------------------- - /* - public void display_old(String[] argStringArray, boolean exitOnClose) - { - - CodeTimer timer = new CodeTimer(); - String header = "TimeSeriesLite.display(): "; - - readCommandLineArgs(argStringArray); - - timer.start(); - loadDrawingManager(argStringArray); - timer.stop("loadDrawingManager() took "); - - if (_drawingMgr != null) - { - TSLFrame frame = new TSLFrame(); - - frame.setExitOnClose(exitOnClose); - - System.out.println(header + "after TSLFrame()"); - - TsPaintableCanvas canvas = frame.getCanvas(); - - timer.start(); - _drawingMgr.initializeCanvas(canvas); - timer.stop("initializeCanvas() took "); - - // System.out.println(header + "after _drawingMgr.initialize(canvas);"); - - - timer.start(); - frame.setVisible(true); - timer.stop("setVisible() took "); - - // System.out.println(header + "after frame.setVisible(true)"); - - } - - else - { - System.out.println(header + "_drawingMgr == null"); - } - - return; - } - */ -// ------------------------------------------------------------------------------------- - - public static void show(String nameOfDrawingMgr, - String dbConnString, - String locationId, - String paramCodeString1, - String paramCodeString2) - { - String header = "TimeSeriesLite.show(): "; - - String[] argStringArray = - { - nameOfDrawingMgr, - dbConnString, - locationId, - paramCodeString1, - paramCodeString2 - }; - - for (int i = 0; i < argStringArray.length; i++) - { - System.out.println("argStringArray[" + - i + "] = " + argStringArray[i]); - } - - TimeSeriesLite app = new TimeSeriesLite(); - app.display(argStringArray, true); - - } - - public static void main(String[] argStringArray) - { - TimeSeriesLite app = new TimeSeriesLite(); - app.display(argStringArray, true); - - //test(); - - return; - } -// ------------------------------------------------------------------------------------- -// ------------------------------------------------------------------------------------- - - public static void test() - { - - String[] argStringArray = {"ohd.hseb.timeserieslite.pdc.PDCDrawingMgr", - "jdbc:postgresql://140.90.91.111:5432/hd_ob72ounx?user=pguser", - "BLUO2", - "HGIRGZ", - "HGIFZZ" - }; - - TimeSeriesLite app = new TimeSeriesLite(); - app.display(argStringArray, true); - - - /* - argStringArray[3] = "HGIRGZ"; - app.display(argStringArray, true); - - - argStringArray[3] = "TAIRGZ"; - app.display(argStringArray, true); - - - argStringArray[3] = "USIRGZ"; - app.display(argStringArray, true); - - argStringArray[3] = "UDIRGZ"; - app.display(argStringArray, true); - */ - - return; - } -// ------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/SignificantLinePainter.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/SignificantLinePainter.java deleted file mode 100644 index 8939a70a6f..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/SignificantLinePainter.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.Viewport; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -import java.awt.*; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of a significant data lines on a TsPaintableCanvas - */ -public class SignificantLinePainter implements TslCanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private Measurement _measurement = null; - - private boolean _shouldPaint = false; -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - - - // --------------------------------------------------------- - public SignificantLinePainter(Color lineColor, - Measurement measurement, - MeasuringUnit displayedMeasuringUnit) - { - - _lineColor = lineColor; - - _measurement = Measurement.getConvertedCopy(measurement, - displayedMeasuringUnit); - - - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - MeasuringUnit unit = _canvas.getDisplayedMeasuringUnit(); - // convert again just in case the _canvas has had its units changed, - // even though this feature is not available at this time - if (_measurement.getUnit() != unit) - { - _measurement = - Measurement.getConvertedCopy(_measurement, unit); - - } - double value = _measurement.getValue(); - long minTime = (long) _canvas.getViewport().getMinDataPoint().getX(); - long maxTime = (long) _canvas.getViewport().getMaxDataPoint().getX(); - - DataPoint dp1 = new DataPoint(minTime, value); - DataPoint dp2 = new DataPoint(maxTime, value); - - if (getViewport().isViewable(dp1)) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - } - - } - - //--------------------------------------------------------------- - - - //--------------------------------------------------------------- - - - public Measurement getMaxMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _measurement; - } - - return measurement; - } - - - public Measurement getMinMeasurement() - { - - Measurement measurement = null; - - if (_shouldPaint) - { - measurement = _measurement; - } - - return measurement; - } - - -/** - * @param canvas The canvas to set. - */ -public void setCanvas(TsPaintableCanvas canvas) -{ - _canvas = canvas; -} - - -/** - * @return Returns the canvas. - */ -public TsPaintableCanvas getCanvas() -{ - return _canvas; -} - -//---------------------------------------------------- - - -} //end of SignficantLinePainter diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsBarPainter.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsBarPainter.java deleted file mode 100644 index 098eb83d7c..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsBarPainter.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.Graphics; -import java.awt.*; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of precipitation data on a PaintableCanvas - */ -public class TsBarPainter implements TslCanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _barColor = null; - private Color _outlineColor = null; - - private RegularTimeSeriesHolder _precipTimeSeriesHolder = null; - private TsPaintableCanvas _canvas = null; - - private boolean _shouldDrawBars = true; - - private boolean _shouldPaint = true; - - private static final double VERY_SMALL_NUMBER = 0.0000000000000001; - - // --------------------------------------------------------- - public TsBarPainter(Color barColor, - Color outlineColor, - RegularTimeSeriesHolder timeSeriesHolder - ) - { - - _precipTimeSeriesHolder = timeSeriesHolder; - _canvas = getCanvas(); - - _barColor = barColor; - _outlineColor = outlineColor; - - } - -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - - //System.out.println("PrecipPainter.paint(): precip ts = " + getTimeSeries()); - if (_shouldPaint) - { - drawDataBars(g); - } - } - -// ---------------------------------------------------- - private void drawDataBars( Graphics g ) - { - // String header = "TsBarPainter.drawDataBars(): "; - // System.out.println(header + "-------------------------"); - int x1; - int y1; - int x2; - int y2; - g.setColor(_barColor); - - long millisPerInterval = MILLIS_PER_HOUR; - - RegularTimeSeries timeSeries = getTimeSeries(); - - if (timeSeries != null) - { - millisPerInterval = timeSeries.getIntervalInHours() * MILLIS_PER_HOUR; - } - - //draw each data bar - for ( int i = 0; (timeSeries != null) && - ( i < timeSeries.getMeasurementCount()); i++) - { - - Measurement measurement = (Measurement) - timeSeries.getMeasurementByIndex(i); - - Measurement convertedMeasurement = Measurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double value = convertedMeasurement.getValue(); - - - if (value > VERY_SMALL_NUMBER) - - { - - long endTime = timeSeries.getMeasurementTimeByIndex(i); - long startTime = endTime - millisPerInterval; - - /* - if (!_shouldDrawBars) - { - String timeString = CanvasHelper.getDateTimeStringFromLongTime(endTime); - System.out.println("Time = " + timeString + " value = " + value); - } - */ - - DataPoint dp1 = new DataPoint(startTime, 0); - DataPoint dp2 = new DataPoint(endTime, value); - - - if ( (getViewport().isViewable(dp1)) && - (getViewport().isViewable(dp2)) - ) - { - - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - - int barHeight = Math.abs(p1.y - p2.y); - int barWidth = Math.abs(p1.x - p2.x); - - if (_shouldDrawBars) - { - g.setColor(_barColor); - g.fillRect(p1.x, p2.y, barWidth, barHeight); - - g.setColor(_outlineColor); - g.drawRect(p1.x, p2.y, barWidth, barHeight); - } - else //draw Lines - { - g.setColor(_barColor); - g.drawLine(p1.x, p2.y, p1.x + barWidth, p2.y); - - } - } - - }//end if value > 0.0 - - } // for loop - - - } // end of drawDataBars method -// ---------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - private RegularTimeSeries getTimeSeries() - { - return _precipTimeSeriesHolder.getTimeSeries(); - } - -//--------------------------------------------------------- - public Measurement getMinMeasurement() - { - //force this method to return 0.0 always, since - //I always want 0 shown, regardless of the actual measurements - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - /* - - Measurement minMeasurement = null; - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - if (minMeasurement != null) - { - minMeasurement = new Measurement(minMeasurement); - } - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - - */ - return minMeasurement; - } -//---------------------------------------------------- - - public Measurement getMaxMeasurement() - { - - Measurement minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - - String header = "PrecipPainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if (getTimeSeries() != null) - { - //make copies of the max and min measurements - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - if (maxMeasurement != null) - { - maxMeasurement = new Measurement(maxMeasurement); - - if ( maxMeasurement.getValue(_canvas.getDisplayedMeasuringUnit()) < 1.0) - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - } - else - { - //System.out.println(header + " time series was null, setting max measurement to 1.0 "); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - - - //System.out.println(header + " max measurement is " + maxMeasurement); - - return maxMeasurement; - } - -// ---------------------------------------------------- - - public void setShouldDrawBars(boolean shouldDrawBars) - { - _shouldDrawBars = shouldDrawBars; - } - -// ---------------------------------------------------- - - - public boolean shouldDrawBars() - { - return _shouldDrawBars; - } - - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsCanvasToolTipListener.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsCanvasToolTipListener.java deleted file mode 100644 index 927b303896..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsCanvasToolTipListener.java +++ /dev/null @@ -1,119 +0,0 @@ -package ohd.hseb.timeserieslite.gui.drawing; - -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.util.DataPoint; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class TsCanvasToolTipListener extends MouseMotionAdapter -{ - private TsPaintableCanvas _canvas = null; - private ValueMapper _valueMapper = null; - - // --------------------------------------------------------------------------------- - - - public TsCanvasToolTipListener(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - _canvas = canvas; - _valueMapper = valueMapper; - } - // --------------------------------------------------------------------------------- - - public void mouseMoved(MouseEvent event) - { - super.mouseMoved(event); - Point screenPoint = event.getPoint(); - - DataPoint dataPoint = - _canvas.getViewport().getDataPoint(screenPoint); - - - if (_canvas.getViewport().isViewable(dataPoint)) - { - updateDataPointText(dataPoint, _valueMapper, _canvas); - } - } - - - - // --------------------------------------------------------------------------------- - - public void updateDataPointText(DataPoint dataPoint, - ValueMapper valueMapper, - TsPaintableCanvas canvas) - { - //System.out.println("in TsMainWindow.update(DataPoint dp)"); - - String leftUnitString = canvas.getDisplayedMeasuringUnit().toString(); - String rightUnitString = valueMapper.getOutputMeasuringUnit().toString(); - - String message = getDataPointString(dataPoint, valueMapper, leftUnitString, rightUnitString); - - //textField.setText(message); - - canvas.setToolTipText(message); - - return; - } - - // --------------------------------------------------------------------------------- - - private String getDataPointString(DataPoint dataPoint, - ValueMapper valueMapper, - String leftUnitString, - String rightUnitString) - { - NumberFormat nf = new DecimalFormat("####.##"); - String valueString = nf.format(dataPoint.getY()); - - String mappedValueString = ""; - - if (valueMapper != null) - { - MeasuringUnit inputUnit = valueMapper.getInputMeasuringUnit(); - Measurement inputMeasurement = new Measurement(dataPoint.getY(), inputUnit); - - Measurement mappedMeasurement = valueMapper.getResultMeasurement(inputMeasurement); - - double mappedValue = mappedMeasurement.getValue(); - - mappedValueString = nf.format(mappedValue); - } - - long time = (long) Math.floor( dataPoint.getX()); - - String timeString = getDateTimeStringToMinutes(time); - - String dataPointString = timeString + ", " + - valueString + " " + leftUnitString + ", " + - mappedValueString + " " + rightUnitString; - - return dataPointString; - } - - //---------------------------------------------------------------------- - - private String getDateTimeStringToMinutes(long time) - { - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeString = sdf.format(new Date(time)) + " Z"; - - return timeString; - } - - //---------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsDataPointPainter.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsDataPointPainter.java deleted file mode 100644 index 242011864b..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TsDataPointPainter.java +++ /dev/null @@ -1,408 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import ohd.hseb.measurement.*; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.Graphics; -import java.awt.*; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of an irregular time series on a TsPaintableCanvas - */ -public class TsDataPointPainter implements TslCanvasPainter -{ - - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - private Color _pointColor = null; - - private IrregularTimeSeriesHolder _timeSeriesHolder = null; - private RegularTimeSeriesHolder _regularTimeSeriesHolder = null; - - private TsPaintableCanvas _canvas = null; - - private boolean _isRegular = false; // distinguishes between the kind of time series - - private boolean _drawLinesBetweenPoints = false; - private boolean _shouldPaint = true; - - // --------------------------------------------------------- - public TsDataPointPainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder, - boolean drawLinesBetweenPoints) - { - - _isRegular = true; - - _regularTimeSeriesHolder = regularTimeSeriesHolder; - - _pointColor = pointColor; - - _drawLinesBetweenPoints = drawLinesBetweenPoints; - - } - // --------------------------------------------------------- - - public TsDataPointPainter(Color pointColor, - IrregularTimeSeriesHolder timeSeriesHolder) - { - - _isRegular = false; - - _timeSeriesHolder = timeSeriesHolder; - - _drawLinesBetweenPoints = false; - - _pointColor = pointColor; - } - - // --------------------------------------------------------- - public TsDataPointPainter(Color pointColor, - RegularTimeSeriesHolder regularTimeSeriesHolder) - { - this (pointColor, regularTimeSeriesHolder, false); - - } -// --------------------------------------------------------- - public void setShouldPaint(boolean shouldPaint) - { - _shouldPaint = shouldPaint; - } - -// --------------------------------------------------------- - public void paint(Graphics g) - { - //String header = "StagePainter.paint(): "; - - if (_shouldPaint) - { - drawDataPoints(g); - } - } - -// ---------------------------------------------------------- - private void drawDataPoints( Graphics g ) - { - if (_isRegular) - { - drawRegularDataPoints(g); - } - else - { - drawIrregularDataPoints(g); - } - } -// ---------------------------------------------------------- - private void drawRegularDataPoints( Graphics g ) - { - String header = "TsDataPointPainter.drawRegularDataPoints():"; - - - if (getRegularTimeSeries() == null ) - { - //System.out.println(header + " time series is null"); - return; - } - - long startTime = getRegularTimeSeries().getStartTime(); - long endTime = getRegularTimeSeries().getEndTime(); - - - g.setColor(_pointColor); - - - long hoursPerInterval = 1; - long millisPerInterval = MILLIS_PER_HOUR * hoursPerInterval; - - DataPoint previousDataPoint = null; - - //draw each data point - for ( long time = startTime; time <= endTime; time += millisPerInterval) - { - - Measurement measurement = getRegularTimeSeries().getMeasurementByTime(time); - - measurement = measurement.getCopy(getDisplayedMeasuringUnit()); - - - double value = measurement.getValue(); - - DataPoint dp1 = new DataPoint(time, value); - - drawDataPoint(dp1, g); - - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - - } // for loop - - } // end of drawRegularDataPoints() method - - -// ---------------------------------------------------------- - - private void drawIrregularDataPoints( Graphics g ) - { - - DataPoint previousDataPoint = null; - - String header = "StagePainter.drawIrregularDataPoints():"; - //System.out.println(header + " at beginning"); - - if (getTimeSeries() == null) - { - //System.out.println(header + " time series is null"); - } - - g.setColor(_pointColor); - - //System.out.println(header + "time series = " + getTimeSeries()); - - //draw each data point - for ( int i = 0; (getTimeSeries() != null) && - i < getTimeSeries().getMeasurementCount(); i++) - { - - AbsTimeMeasurement measurement = (AbsTimeMeasurement) - getTimeSeries().getAbsTimeMeasurementByIndex(i); - - - - AbsTimeMeasurement convertedMeasurement = - AbsTimeMeasurement.getConvertedCopy(measurement, - getDisplayedMeasuringUnit()); - - double convertedValue = convertedMeasurement.getValue(); - long time = measurement.getTime(); - - DataPoint dp1 = new DataPoint(time, convertedValue); - - drawDataPoint(dp1, g); - - - if (_drawLinesBetweenPoints) - { - if (previousDataPoint != null) - { - drawSegment(previousDataPoint, dp1, g); - } - - previousDataPoint = dp1; - } - - - - } // for loop - - } // end of drawIrregularDataPoints() method - -// --------------------------------------------------------- - private void drawSegment(DataPoint dp1, DataPoint dp2, Graphics g) - { - - Viewport viewport = getViewport(); - -// if it is viewable, then draw it - if ( (getViewport().isViewable(dp1)) && (getViewport().isViewable(dp2)) ) - { - Point p1 = getViewport().getScreenPoint(dp1); - Point p2 = getViewport().getScreenPoint(dp2); - - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - } - else - { - //System.out.println("StagePainter.drawSegment(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } - -// --------------------------------------------------------- - - private void drawDataPoint(DataPoint dp, Graphics g) - { - // if it is viewable, then draw it - if (getViewport().isViewable(dp)) - { - Point p1 = getViewport().getScreenPoint(dp); - - int diameter = 4; - int radius = diameter/2; - g.drawOval(p1.x-radius, p1.y-radius, diameter, diameter); - - //System.out.println(header + " x = " + p1.x + " y = " + p1.y); - } - else - { - //System.out.println("StagePainter.drawDataPoints(): DataPoint " + - // dp1 + " is not Viewable"); - } - - } -// -------------------------------------------------------- - private IrregularTimeSeries getTimeSeries() - { - IrregularTimeSeries ts = null; - - if (_timeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _timeSeriesHolder.getTimeSeries(); - } - return ts; - } - -// --------------------------------------------------------- - - private RegularTimeSeries getRegularTimeSeries() - { - RegularTimeSeries ts = null; - - - if (_regularTimeSeriesHolder == null) - { - //System.out.println("StagePainter(). _timeSeriesHolder is null"); - } - else - { - ts = _regularTimeSeriesHolder.getTimeSeries(); - } - - return ts; - } -// --------------------------------------------------------- - - private MeasuringUnit getDisplayedMeasuringUnit() - { - return _canvas.getDisplayedMeasuringUnit(); - } -// --------------------------------------------------------- - - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// --------------------------------------------------------- - - public Measurement getMinMeasurement() - { - String header = "StagePainter.getMinMeasurement()"; - - Measurement minMeasurement = null; - - //extremes don't count unless displayed - if (_shouldPaint) - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - minMeasurement = getRegularTimeSeries().getMinMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - minMeasurement = getTimeSeries().getMinMeasurement(startTime, endTime); - } - else - { - minMeasurement = new Measurement(0.0, _canvas.getDisplayedMeasuringUnit()); - } - } - // System.out.println(header + "minMeasurement = " + minMeasurement); - - - return minMeasurement; - } - -// ---------------------------------------------------- - -// ---------------------------------------------------- - public Measurement getMaxMeasurement() - { - String header = "StagePainter.getMaxMeasurement()"; - - Measurement maxMeasurement = null; - - if (_shouldPaint) //extremes don't count unless displayed - { - - long startTime = _canvas.getStartTime(); - long endTime = _canvas.getEndTime(); - - - if ((_isRegular) && (getRegularTimeSeries() != null)) - { - maxMeasurement = getRegularTimeSeries().getMaxMeasurement(startTime, endTime); - } - else if (getTimeSeries() != null) - { - maxMeasurement = getTimeSeries().getMaxMeasurement(startTime, endTime); - } - else - { - //System.out.println(header + "No time series found!!!!"); - maxMeasurement = new Measurement(1.0, _canvas.getDisplayedMeasuringUnit()); - } - - } - - return maxMeasurement; - } - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - /** - * @param drawLinesBetweenPoints The drawLinesBetweenPoints to set. - */ - public void setDrawLinesBetweenPoints(boolean drawLinesBetweenPoints) - { - _drawLinesBetweenPoints = drawLinesBetweenPoints; - } - /** - * @return Returns the drawLinesBetweenPoints. - */ - public boolean getDrawLinesBetweenPoints() - { - return _drawLinesBetweenPoints; - } - - -//---------------------------------------------------- - - -} //end of PrecipPainter diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslBackgroundPainter.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslBackgroundPainter.java deleted file mode 100644 index b8398fb478..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslBackgroundPainter.java +++ /dev/null @@ -1,611 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.util.*; -import ohd.hseb.util.gui.FontHelper; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.*; -import java.text.*; - -/** - * @author Chip Gobs - * - * This class implements CanvasPainter and encapsulates the - * drawing of the X and Y axes and all the tick marks - */ -public class TslBackgroundPainter implements CanvasPainter -{ - - // width distinctions for drawing labeling - private static final int WIDE_WIDTH = 600; - private static final int NARROW_WIDTH = 400; - private static final int TINY_WIDTH = 0; - - // various colors - private static final Color _backgroundColor = Color.black; - - private static final Color _gridColor = Color.GRAY; - private Color _outlineColor = Color.WHITE; - private static final Color _labelColor = Color.WHITE; - private static final Color _currentTimeColor = Color.YELLOW; - - //time constant - private static final int MILLIS_PER_HOUR = 1000 * 60 * 60; - - //number formatter - private NumberFormat _numberFormat = NumberFormat.getInstance(); - - //unit labels - private String _leftUnitLabelString = null; - private String _rightUnitLabelString = null; - - //fonts - private Font _titleFont = null; - private Font _labelFont = null; - - //FontHelper - custom class - private FontHelper _titleFontHelper = null; - private FontHelper _labelFontHelper = null; - - // margins and shifts - private final static int _titleYShift = - 20; - - private final static int _headerYShift = 0; - private int _leftLabelShift = 30; - private int _rightLabelShift = 10; - - private double _smallRoundingError = 0.000000001; - - // canvas and value mapper(which controls the values on the right axis) - private TsPaintableCanvas _canvas = null; - private ValueMapper _rightLabelValueMapper = null; - - // graphing hours - private int _hoursPerMajorXTick = 6; - private int _hoursPerMinorXTick = 1; - - private boolean _showMinorTicks = true; - - private String[] _textHeaderStringArray = null; - private String _title = null; - - - // --------------------------------------------------------- - public TslBackgroundPainter(Color outlineColor, - String leftUnitLabelString, - String rightUnitLabelString) - { - _outlineColor = outlineColor; - // _canvas = canvas; - - _leftUnitLabelString = leftUnitLabelString; - _rightUnitLabelString = rightUnitLabelString; - - _numberFormat.setMaximumFractionDigits(2); - - _titleFont = new Font("TimesRoman", Font.BOLD, 14); - _labelFont = new Font("Helvetica", Font.PLAIN, 9); - - _titleFontHelper = new FontHelper(_titleFont); - _labelFontHelper = new FontHelper(_labelFont); - - _showMinorTicks = true; - - } //tsBackgroundPainter() - -// --------------------------------------------------------- - public void setShowMinorTicks(boolean showMinorTicks) - { - _showMinorTicks = showMinorTicks; - } -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawBackground(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } -// ---------------------------------------------------- - - public void setRightLabelValueMapper(ValueMapper rightLabelValueMapper) - { - _rightLabelValueMapper = rightLabelValueMapper; - } -// ---------------------------------------------------- - - public ValueMapper getRightLabelValueMapper() - { - return _rightLabelValueMapper; - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - public void drawBackground(Graphics g) - { - - Rectangle r = _canvas.getBounds(); - - //set the normal font to use - g.setFont( _labelFont ); - - //clear the image - g.setColor(_backgroundColor); - g.fillRect(0, 0, r.width, r.height); - - //draw the axis labels, ticks, and dotted lines - drawHorizontalLines( g ); - drawVerticalLines( g ); - - //draw the Title - // drawTitle(g); - - drawTextHeader(g); - - int x = 0; - int y = 0; - - x = 10; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_leftUnitLabelString, g, x, y); - - x = _canvas.getViewport().getMaxScreenPoint().x + 0; - y = _canvas.getTopMargin() + _titleYShift; - drawUnitLabel(_rightUnitLabelString, g, x, y); - - return; - } -//---------------------------------------------------- - private void drawTitle(Graphics g) - { - // String header = "TslTsBackgroundPainter().drawTitle(): "; - - - String titleString = _canvas.getTitle(); - - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, titleString) / 2; - - int x = middleX - totalLeftShift; - int y = (_canvas.getTopMargin() + _titleYShift); - - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(titleString, x, y); - - return; - } //drawTitle - -// ---------------------------------------------------- - private void drawTextHeader(Graphics g) - { - String header = "TslTsBackgroundPainter().drawHeaderText(): "; - - g.setFont(_titleFont); - g.setColor(_labelColor); - - String headerString = ""; - - if (_textHeaderStringArray != null) - { - headerString = _textHeaderStringArray[0]; - } - - // System.out.println(header + "headerString = " + headerString); - - Rectangle boundingRectangle = _canvas.getBounds(); - - int middleX = (int) (boundingRectangle.width * .5); - int totalLeftShift = _titleFontHelper.getWidth(g, headerString) / 2; - int fontHeight = _titleFontHelper.getHeight(g); - - int x = middleX - totalLeftShift; - int y = 20; - - - - // draw each of the strings for the header - for (int i = 0; i < _textHeaderStringArray.length; i++) - { - if (_textHeaderStringArray[i] != null) - { - g.drawString(_textHeaderStringArray[i], x, y); - y += fontHeight; - } - } - return; - } //drawTitle - -// ---------------------------------------------------- - - private void drawUnitLabel(String unitLabel, Graphics g, int x, int y) - { - g.setFont(_titleFont); - g.setColor(_labelColor); - g.drawString(unitLabel, x, y); - - return; - } //drawTitle - -// -------------------------------------------------------------------------- - - private void drawVerticalLines(Graphics g) - { - // determine the min and max data values to chart - String header = "TslTsBackgroundPainter.drawVerticalLines(): "; - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - Point point1 = null; - Point point2 = null; - - - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - // draw each tick line - int minorTickHours = _hoursPerMinorXTick; - int majorTickHours = _hoursPerMajorXTick; - - for (double tickValue = minXValue; - tickValue <= maxXValue; - tickValue += minorTickHours * MILLIS_PER_HOUR) - { - point1 = getViewport().getScreenPoint(new DataPoint(tickValue, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(tickValue, maxYValue)); - - //if on a majorTick - if (isOnATick((long)tickValue, majorTickHours)) - { - - // System.out.println(header + "on a tick -> tickValue = " + - // DbTimeHelper.getDateTimeStringFromLongTime((long)tickValue)); - - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on graph boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else //not on a graph boundary - { - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - } - - //draw the major tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+6, point2.x, point1.y); - - //draw a major tick - //build the labels - BooleanHolder atZeroHour = new BooleanHolder(false); - String hourLabelString = getHourLabelString((long) tickValue, atZeroHour); - - - String dateLabelString = CanvasHelper.getDateString((long)tickValue); - - // draw the labels - g.setColor(_labelColor); - g.drawString(hourLabelString, point1.x-5, point1.y + 15); - - //only draw the date string at 00Z - if (atZeroHour.getValue() == true) - { - g.drawString(dateLabelString, point1.x-5, point1.y + 30); - } - } - else //on a minor tick - { - - // System.out.println(header + "on a minor tick -> tickValue = " + - // DbTimeHelper.getDateTimeStringFromLongTime((long)tickValue)); - - - - //draw a minor tick - //draw the minor tick extension - - if ((tickValue == minXValue) || (tickValue == maxXValue)) - { - //on boundary - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y+2, point2.x, point1.y); - - } - } //end for i - - - // if applicable, draw current time line - long currentTime = System.currentTimeMillis(); - if ( (currentTime >= minXValue) && (currentTime <=maxXValue)) - { - point1 = getViewport().getScreenPoint(new DataPoint(currentTime, minYValue)); - point2 = getViewport().getScreenPoint(new DataPoint(currentTime, maxYValue)); - - g.setColor(_currentTimeColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - - } //end drawXAxis - -// -------------------------------------------------------------------------- - private String getHourLabelString(long timeValue, BooleanHolder atZeroHour) - { - String hourLabelString = null; - String hourLabelBaseString = CanvasHelper.getHourString((long)timeValue); - - if (hourLabelBaseString.equals("00")) - { - atZeroHour.setValue(true); - } - - - if (_canvas.getWidth() >= WIDE_WIDTH) - { - hourLabelString = hourLabelBaseString + 'Z'; - } - else if (_canvas.getWidth() >= NARROW_WIDTH) - { - if (atZeroHour.getValue() == true) - { - hourLabelString = "0Z"; - } - else - { - hourLabelString = hourLabelBaseString; - } - } - else //TINY WIDTH - { - //00 and 06 become 0 and 6 to make more space - if (hourLabelBaseString.charAt(0) == '0') - { - hourLabelString = " " + hourLabelBaseString.substring(1,2); - } - else - { - hourLabelString = hourLabelBaseString; - } - } - - return hourLabelString; - } - -// -------------------------------------------------------------------------- - private boolean isOnATick(long timeValue, int hoursPerTick) - { - boolean result = false; - - long roundedTime = TimeHelper.truncateTimeInMillisToNearestHour((long)timeValue, hoursPerTick); - - // String timeValueString = DbTimeHelper.getDateTimeStringFromLongTime(timeValue); - // String roundedTimeString = DbTimeHelper.getDateTimeStringFromLongTime(roundedTime); - - if ( ( timeValue == roundedTime ) || - ( timeValue == roundedTime + (hoursPerTick*MILLIS_PER_HOUR)) - ) - { - result = true; - } - return result; - } //end isOnATick - - -// ------------------------------------------------------------------------------------------- - - private void drawHorizontalLines(Graphics g) - { - //determine the min and max data values to chart - - DataPoint minDataPoint = getViewport().getMinDataPoint(); - DataPoint maxDataPoint = getViewport().getMaxDataPoint(); - - //String header = "TsBackgroundPainter.drawHorizontalLines(): "; - - //System.out.println(header + "minDataPoint = " + minDataPoint); - //System.out.println(header + "maxDataPoint = " + maxDataPoint); - - - double minYValue = minDataPoint.getY(); - double maxYValue = maxDataPoint.getY(); - - double minXValue = minDataPoint.getX(); - double maxXValue = maxDataPoint.getX(); - - - //determine scaling - - ScalingHelper scalingHelper = new ScalingHelper(minYValue, maxYValue); - - int minorTickCountMax = scalingHelper.getMinorTickCount(); - int majorTickCountMax = scalingHelper.getMajorTickCount(); - - // int totalTickCount = majorTickCountMax * minorTickCount; - - double majorTickIncrement = scalingHelper.getMajorTickIncrement(); - double majorTickValue = minYValue; - - double minorTickIncrement = scalingHelper.getMinorTickIncrement(); - - Point point1 = null; - Point point2 = null; - - - g.setFont(_labelFont); - - int iterationCount = 0; - - double maxTickValueBound = (maxYValue + _smallRoundingError); - - for (int majorTickCount = 0; majorTickCount < majorTickCountMax; majorTickCount++) - { - - majorTickValue = (majorTickCount * (majorTickIncrement)) + minYValue; - - //get the points that are pointed to. - point1 = getViewport().getScreenPoint(new DataPoint(minXValue, majorTickValue)); - point2 = getViewport().getScreenPoint(new DataPoint(maxXValue, majorTickValue)); - - // set color as appropriate for the tick lines - // Note: Checking for tickValue == maxYValue or minYValue may - // not working due to rounding issues, so add in a fudge factor - - if ( ( majorTickValue == minYValue) || - ((majorTickValue + majorTickIncrement) > maxTickValueBound) - ) //at edge of chart - { - //draw the outside boundary line - g.setColor(_outlineColor); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - } - else // in middle of chart - { - //draw the inside the boundary line - g.setColor(_gridColor); - //CanvasHelper.drawDashedLine(g, point1.x, point1.y, point2.x, point2.y); - g.drawLine(point1.x, point1.y, point2.x, point2.y); - - } - - - //draw the left side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point1.x-5, point1.y, point1.x, point2.y); - - // draw the label - String numberLabelString = _numberFormat.format(majorTickValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point1.x - _leftLabelShift , point1.y + 3); - - - - - //draw the right side tick extension and label - - // draw the tick extension - g.setColor(_outlineColor); - g.drawLine(point2.x+5, point2.y, point2.x, point2.y); - - // draw the label - ValueMapper valueMapper = getRightLabelValueMapper(); - - double newValue = majorTickValue; - if (valueMapper != null) - { - Measurement m = new Measurement(majorTickValue, valueMapper.getInputMeasuringUnit()); - newValue = valueMapper.getResultMeasurement(m).getValue(); - } - - numberLabelString = _numberFormat.format(newValue); - g.setColor(_labelColor); - g.drawString(numberLabelString, point2.x + _rightLabelShift , point2.y + 3); - - //draw all of the minor ticks - // minor ticks are always inside and do not get labels - - if (_showMinorTicks) - { - if (majorTickCount < majorTickCountMax - 1) - { - for (int minorTickCount = 1; minorTickCount <= minorTickCountMax; minorTickCount++) - { - double minorTickValue = majorTickValue + (minorTickCount * minorTickIncrement); - - Point minorPoint1 = getViewport().getScreenPoint(new DataPoint(minXValue, minorTickValue)); - Point minorPoint2 = getViewport().getScreenPoint(new DataPoint(maxXValue, minorTickValue)); - - - //draw the inside the boundary line - g.setColor(_gridColor); - CanvasHelper.drawDashedLine(g, minorPoint1.x, minorPoint1.y, minorPoint2.x, minorPoint2.y); - - } - } - - } //end if _showMinorTicks - - } - - } //end drawYAxis - - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - - /** - * @param textHeaderStringArray The textHeaderStringArray to set. - */ - public void setTextHeaderStringArray(String[] textHeaderStringArray) - { - _textHeaderStringArray = textHeaderStringArray; - } - - /** - * @return Returns the textHeaderStringArray. - */ - public String[] getTextHeaderStringArray() - { - return _textHeaderStringArray; - } - - /** - * @param title The title to set. - */ - public void setTitle(String title) - { - _title = title; - } - - /** - * @return Returns the title. - */ - public String getTitle() - { - return _title; - } - -// ------------------------------------------------------------------------------ - - - - -} //end of SigStageLinePainter diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslCanvasPainter.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslCanvasPainter.java deleted file mode 100644 index e0eebebcf7..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslCanvasPainter.java +++ /dev/null @@ -1,10 +0,0 @@ -package ohd.hseb.timeserieslite.gui.drawing; - -import ohd.hseb.util.gui.drawing.TsCanvasPainter; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public interface TslCanvasPainter extends TsCanvasPainter -{ - - public void setCanvas(TsPaintableCanvas canvas); -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslTimeLinePainter.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslTimeLinePainter.java deleted file mode 100644 index e2f47006ef..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/gui/drawing/TslTimeLinePainter.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Created on Oct 10, 2003 - * - * - */ -package ohd.hseb.timeserieslite.gui.drawing; - - -import ohd.hseb.util.*; -import ohd.hseb.util.gui.drawing.*; - -import java.awt.Graphics; -import java.awt.*; - -/** - * @author GobsC - * - * This class extends TsCanvasPainter and encapsulates the - * drawing of the vertical time line indicator on a TsPaintableCanvas - */ -public class TslTimeLinePainter implements CanvasPainter -{ - - private Color _lineColor = null; - - private TsPaintableCanvas _canvas = null; - - private TimeHolder _timeHolder = null; - - private String _labelString = null; - private int _labelYPosition = -1; - - // --------------------------------------------------------- - public TslTimeLinePainter(Color lineColor, - TimeHolder timeHolder) - { - - _lineColor = lineColor; - _timeHolder = timeHolder; - } - - // --------------------------------------------------------- - - public TslTimeLinePainter(Color lineColor, - String labelString, - int labelYPosition, - TimeHolder timeHolder) - { - - _lineColor = lineColor; - _timeHolder = timeHolder; - _labelString = labelString; - _labelYPosition = labelYPosition; - } - -//--------------------------------------------------------- - -// --------------------------------------------------------- - public void paint(Graphics g) - { - drawDataLine(g); - } - -// ---------------------------------------------------- - private Viewport getViewport() - { - return _canvas.getViewport(); - } - -// --------------------------------------------------------- - -// ************************************************************* -// drawDataLine() -// scaling data & display data -// ************************************************************* - private void drawDataLine( Graphics g ) - { - - double dataX = _timeHolder.getTime(); - double maxDataY = getViewport().getMaxDataPoint().getY(); - double minDataY = getViewport().getMinDataPoint().getY(); - - DataPoint dp1 = new DataPoint(dataX, maxDataY); - DataPoint dp2 = new DataPoint(dataX, minDataY); - - if (getViewport().isViewable(dp1)) - { - - Point p1 = _canvas.getViewport().getScreenPoint(dp1); - Point p2 = _canvas.getViewport().getScreenPoint(dp2); - - g.setColor(_lineColor); - g.drawLine(p1.x, p1.y, p2.x, p2.y); - - //draw a label if the _labelString is set - if (_labelString != null) - { - g.drawString(_labelString, p1.x, _labelYPosition); - } - - } - - } // end of drawDataLine() - - /** - * @param canvas The canvas to set. - */ - public void setCanvas(TsPaintableCanvas canvas) - { - _canvas = canvas; - } - - /** - * @return Returns the canvas. - */ - public TsPaintableCanvas getCanvas() - { - return _canvas; - } - -//---------------------------------------------------- - - -} //end of TimeLinePainter diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/pdc/PDCDrawingMgr.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/pdc/PDCDrawingMgr.java deleted file mode 100644 index 08f60364a9..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/pdc/PDCDrawingMgr.java +++ /dev/null @@ -1,2390 +0,0 @@ -package ohd.hseb.timeserieslite.pdc; - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.RegularTimeSeriesHolder; -import ohd.hseb.model.FlowToStageValueMapper; -import ohd.hseb.model.PrecipPPAndPCValueMapper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.timeserieslite.TSLDrawingMgr; -import ohd.hseb.timeserieslite.TSLFrame; -import ohd.hseb.timeserieslite.gui.drawing.SignificantLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TsBarPainter; -import ohd.hseb.timeserieslite.gui.drawing.TsCanvasToolTipListener; -import ohd.hseb.timeserieslite.gui.drawing.TsDataPointPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslCanvasPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslTimeLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TslBackgroundPainter; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -//import ohd.hseb.util.TimerHelper; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - - -public class PDCDrawingMgr implements TSLDrawingMgr -{ - private static final long MILLIS_PER_HOUR = 60*60*1000; - private static final int TOP_MARGIN = 100; - - private static Map _physicalElementMap = new HashMap(); - static - { - _physicalElementMap.put("HG", PDCDataType.HEIGHT); - _physicalElementMap.put("HP", PDCDataType.HEIGHT); - _physicalElementMap.put("HT", PDCDataType.HEIGHT); - _physicalElementMap.put("QR", PDCDataType.DISCHARGE); - _physicalElementMap.put("QT", PDCDataType.DISCHARGE); - _physicalElementMap.put("LS", PDCDataType.LAKE_STORAGE); - _physicalElementMap.put("PP", PDCDataType.PRECIP_TOTAL); - _physicalElementMap.put("PC", PDCDataType.PRECIP_PC); - _physicalElementMap.put("SW", PDCDataType.SNOW_WATER_EQUIVALENT); - _physicalElementMap.put("SD", PDCDataType.SNOW_DEPTH); - - _physicalElementMap.put("TA", PDCDataType.TEMPERATURE); - _physicalElementMap.put("TD", PDCDataType.DEWPOINT); - - _physicalElementMap.put("WS", PDCDataType.WIND_SPEED); - _physicalElementMap.put("WD", PDCDataType.WIND_DIRECTION); - - _physicalElementMap.put("XR", PDCDataType.RELATIVE_HUMIDITY); - - } - - private int _hoursBackInTime = 120; - private int _hoursForwardInTime = 168; - - private PdcTslDataManager _dataMgr = null; - private String _locationId = null; - private List _paramCodeList = new ArrayList(); - private String _jdbcConnectionString = null; - - // private PDCDataType _dataType = null; - private List _dataTypeList = new ArrayList(); - - private long _startTime = 0; - private long _endTime = 0; - - private int HOURS_TO_ROUND = 6; - - -// timer-related code - private int _timerDelayInMillis = 60 * 1 * 1000 ; - - private String[] _rememberedArgStringArray = null; - private boolean _exitOnClose = false; - - private TSLFrame _frame = new TSLFrame(); - - // -------------------------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------------------------- - - public PDCDrawingMgr() - { - // ActionListener refreshTimerListener = new RefreshTimerListener(); - - // TimerHelper refreshTimerHelper = new TimerHelper(refreshTimerListener, _timerDelayInMillis); - - } - - // -------------------------------------------------------------------------------------------------- - - - public void display(String[] argStringArray, boolean exitOnClose) - { - //save these for later, when refresh is called - _rememberedArgStringArray = argStringArray; - _exitOnClose = exitOnClose; - - handleCommandLineArgs(argStringArray); - - String header = "PDCDrawingMgr.display()"; - - if (_frame == null) - { - _frame = new TSLFrame(); - - _frame.setExitOnClose(exitOnClose); - } - - // System.out.println(header + "after TSLFrame()"); - - TsPaintableCanvas canvas = _frame.getCanvas(); - - - PDCDataType dataType = null; - - if ( _dataTypeList.size() > 0 ) - { - dataType = (PDCDataType) _dataTypeList.get(0); - - } - - // System.out.println(header + " before initializeCanvas() "); - initializeCanvas(dataType, _paramCodeList, canvas); - // System.out.println(header + " after initializeCanvas() "); - - _frame.setVisible(true); - - } - - // -------------------------------------------------------------------------------------------------- - - private void initializeCanvas(PDCDataType dataType, - List paramCodeList, - TsPaintableCanvas canvas) - { - - String header = "initializeCanvas(): "; - initializeTimeWindow(canvas); - - //make room for the large area required by the text header in the graph - canvas.setTopMargin(TOP_MARGIN); - - - if (dataType == PDCDataType.HEIGHT) - { - initForHeight(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DISCHARGE) - { - initForDischarge(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.LAKE_STORAGE) - { - // initForLakeStorage(_locationId, canvas); - } - - - else if (dataType == PDCDataType.PRECIP_TOTAL) - { - System.out.println(header + "before initForPrecipDualMode() "); - initForPrecipDualMode(_locationId, paramCodeList, canvas); - System.out.println(header + "after initForPrecipDualMode() "); - } - - else if (dataType == PDCDataType.PRECIP_PC) - { - System.out.println(header + "before initForPrecipPC() "); - initForPrecipPC(_locationId, paramCodeList, canvas); - System.out.println(header + "after initForPrecipPC() "); - } - - else if (dataType == PDCDataType.SNOW_WATER_EQUIVALENT) - { - initForSnow(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.SNOW_DEPTH) - { - initForSnow(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.TEMPERATURE) - { - initForTemperature(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DEWPOINT) - { - initForDewpoint(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.WIND_DIRECTION) - { - initForWindDirection(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.WIND_SPEED) - { - initForWindSpeed(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.RELATIVE_HUMIDITY) - { - initForHumidity(_locationId, paramCodeList, canvas); - } - - - - //call this again to make it redraw everything correctly - // it wasn't working without this - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void initializeTimeWindow(TsPaintableCanvas canvas) - { - //set up time window - long currentTime = System.currentTimeMillis(); - long roundedCurrentTime = - TimeHelper.truncateTimeInMillisToNearestHour(currentTime, HOURS_TO_ROUND); - - setStartTime(roundedCurrentTime - (_hoursBackInTime * MILLIS_PER_HOUR)); - setEndTime(getStartTime() + (_hoursForwardInTime * MILLIS_PER_HOUR)); - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private boolean isValueAvailable(Measurement measurement, MeasuringUnit unit) - { - boolean result = false; - - if (measurement != null) - { - if (measurement.getValue(unit) > 0.0) - { - result = true; - } - } - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private void addCanvasListeners(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - //Add listener for the tooltip - TsCanvasToolTipListener toolTipMgr = new TsCanvasToolTipListener(canvas, valueMapper); - canvas.addMouseMotionListener(toolTipMgr); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void handleCommandLineArgs(String[] argStringArray) - { - String header = "PdcDrawingManager.handleCommandLineArgs(): "; - - //includes the optional jdbcConnectionString - if (argStringArray.length > 1) - { - _jdbcConnectionString = argStringArray[1]; - _dataMgr = new PdcTslDataManager(_jdbcConnectionString); - } - - //location id - if (argStringArray.length > 2) - { - _locationId = argStringArray[2]; - } - - -// create param code list and dataType list - for (int i = 3; i < argStringArray.length; i++) - { - String paramCodeString = argStringArray[i]; - System.out.println(header + "paramCodeString = " + paramCodeString); - - ParamCode paramCode = new ParamCode(paramCodeString); - - paramCode = expandParamCode(_locationId, paramCode); - - if (paramCode != null) - { - _paramCodeList.add(paramCode); - - // String physicalElement = paramCode.substring(0,2); - PDCDataType dataType = getDataTypeFromPhysicalElement(paramCode.getPe()); - _dataTypeList.add(dataType); - } - } - - return; - } - // ------------------------------------------------------------------------------------- - private ParamCode expandParamCode(String locationId, ParamCode paramCode) - { - - String header = "PDCDrawingMgr.expandParamCode(): "; - ParamCode expandedParamCode = new ParamCode(paramCode); - String expandedParamCodeString = null; - - String typeSource = paramCode.getTypeSource(); - String peString = paramCode.getPe(); - - if (typeSource.indexOf('-') == 1) - { - if (typeSource.charAt(0) == 'F') - { - typeSource = _dataMgr.getPreferredFcstTypeSource(locationId, peString); - - if (typeSource != null) - { - expandedParamCode.setTypeSource(typeSource); - expandedParamCodeString = expandedParamCode.toString(); - } - else - { - expandedParamCode = null; - expandedParamCodeString = null; - } - } - - } - else - { - expandedParamCodeString = expandedParamCode.toString(); - } - - System.out.println(header + "original paramCode = " + paramCode.toString() ); - System.out.println(header + "expandedParamCode = " + expandedParamCodeString ); - - return expandedParamCode; - - } - - // ------------------------------------------------------------------------------------- - - private ParamCode getParamCode(List paramCodeList) - { - ParamCode paramCode = null; - - - if ( (paramCodeList != null) && (paramCodeList.size() > 0) ) - { - paramCode = (ParamCode) paramCodeList.get(0); - } - - return paramCode; - } - - - // ------------------------------------------------------------------------------------- - private PDCDataType getDataTypeFromPhysicalElement(String physicalElement) - { - - PDCDataType dataType = (PDCDataType) _physicalElementMap.get(physicalElement); - if (dataType == null) - { - if (stringStartsWith(physicalElement, 'H')) - { - dataType = PDCDataType.HEIGHT; - } - if (stringStartsWith(physicalElement, 'Q')) - { - dataType = PDCDataType.DISCHARGE; - } - } - - return dataType; - - } - // ------------------------------------------------------------------------------------- - private boolean stringStartsWith(String physicalElement, char firstCharacter) - { - boolean result = false; - - if ( (physicalElement!= null) && - (physicalElement.length() > 0) && - (physicalElement.charAt(0) == firstCharacter) - ) - { - result = true; - } - - return result; - } - // ------------------------------------------------------------------------------------- - - public void initForHeight(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "PDCDrawingMgr.initForHeight(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = null; //actually depends on rating curve existence - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new StageToFlowValueMapper(ratingCurve); - rightAxisLabelString = "cfs"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "feet"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - //Color floodStageColor = Color.RED; - Color floodStageColor = Color.ORANGE; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - - //observed data painter - if (obsTs != null) - { - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - } - - // forecast data painters - if (fcstTs != null) - { - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - } - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForHeightWithLists(String locationId, - List paramCodeList, - TsPaintableCanvas canvas) - { - - String header = "PDCDrawingMgr.initForHeightWithLists(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = "cfs"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - - List obsTsList = new ArrayList(); - List fcstTsList = new ArrayList(); - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstTsList.add(fcstTs); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - - CodeTimer stageTimer = new CodeTimer(); - - stageTimer.start(); - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsTsList.add(obsTs); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - ValueMapper valueMapper = new StageToFlowValueMapper(ratingCurve); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - boolean shouldPaint = true; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - // observed data painter - for (int i = 0; i < obsTsList.size(); i++) - { - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - } - - - - // forecast data painters - for (int i = 0; i < fcstTsList.size(); i++) - { - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - } - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForDischarge(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "PDCDrawingMgr.initForDischarge(): "; - - MeasuringUnit unit = MeasuringUnit.cfs; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "cfs"; - String rightAxisLabelString = null; //actually depends on rating curve existence - - //Set time - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - - String titleString = "River Discharge for " + locationId; - //read in the observed time series - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstDischargeTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstDischargeTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedDischargeTimeSeries(locationId, - paramCode, - getStartTime()); - stageTimer.stop(header + "loadObservedDischargeTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new FlowToStageValueMapper(ratingCurve); - rightAxisLabelString = "feet"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "cfs"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - -/* - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - */ - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - - - //------------------------------------------------------------------------------------ - - public void initForTemperature(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.degreesFahrenheit; - MeasuringUnit rightUnit = MeasuringUnit.degreesCelsius; - - canvas.setDisplayedMeasuringUnit(leftUnit); - // canvas.setLeftMargin(30); - // canvas.setRightMargin(30); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Deg. F"; - String rightAxisLabelString = "Deg. C"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Air Temperature for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedTemperatureTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - //-------------------------------------------------------------------------------------- - - public void initForWindSpeed(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.knots; - MeasuringUnit rightUnit = leftUnit; - - canvas.setDisplayedMeasuringUnit(leftUnit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Knots"; - String rightAxisLabelString = "Knots"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Wind Speed for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedWindTimeSeries(locationId, paramCode, leftUnit); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - //-------------------------------------------------------------------------------------- - - public void initForWindDirection(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.degrees; - MeasuringUnit rightUnit = leftUnit; - - canvas.setDisplayedMeasuringUnit(leftUnit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Degrees"; - String rightAxisLabelString = "Degrees"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Wind Direction for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedWindTimeSeries(locationId, paramCode, leftUnit); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - public void initForSnow(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.inches; - MeasuringUnit rightUnit = MeasuringUnit.mm; - - canvas.setDisplayedMeasuringUnit(leftUnit); - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Inches"; - String rightAxisLabelString = "mm"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Snow Depth for " + locationId; - - - ParamCode paramCode = getParamCode(paramCodeList); - - - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedSnowTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - public void initForDewpoint(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.degreesFahrenheit; - MeasuringUnit rightUnit = MeasuringUnit.degreesCelsius; - - - canvas.setDisplayedMeasuringUnit(leftUnit); - // canvas.setLeftMargin(30); - // canvas.setRightMargin(30); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Deg. F"; - String rightAxisLabelString = "Deg. C"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "DewPoint for " + locationId; - - ParamCode paramCode = getParamCode(paramCodeList); - - //read in the observed time series - //dewpoint comes from the temperature table - IrregularTimeSeries obsTs = - _dataMgr.loadObservedTemperatureTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - // -------------------------------------------------------------------------------------------------- - - public void initForHumidity(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - MeasuringUnit leftUnit = MeasuringUnit.unitless; - MeasuringUnit rightUnit = MeasuringUnit.unitless; - - - canvas.setDisplayedMeasuringUnit(leftUnit); - // canvas.setLeftMargin(30); - // canvas.setRightMargin(30); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "Percent"; - String rightAxisLabelString = "Percent"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - ParamCode paramCode = getParamCode(paramCodeList); - - // set title and measuring units - - String titleString = "Relative Humidity for " + locationId; - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadRelativeHumidityTimeSeries(locationId, paramCode); - - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(leftUnit, - rightUnit); - - //background painter - - String unitString = "%"; - - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString(), - unitString); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - // -------------------------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslCanvasPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addTsCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslTimeLinePainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - private void assignPainterToCanvas(TslBackgroundPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - public void initForPrecipTotal(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - MeasuringUnit measuringUnit = MeasuringUnit.inches; - canvas.setDisplayedMeasuringUnit(measuringUnit); - - - String leftAxisLabelString = measuringUnit.toString(); - String rightAxisLabelString = "mm"; - - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - String titleString = "Hourly Precip totals for " + locationId; - //setCanvasTitle("Precip for " + locationId); - - // observed data painters - - ParamCode paramCode = getParamCode(paramCodeList); - - int durationInHours = getDurationInHours(paramCode.getIhfsDur()); - - RegularTimeSeries precipTimeSeries = - _dataMgr.loadPrecipData(locationId, durationInHours); - - IrregularTimeSeries irregularPrecipTimeSeries = - getIrregularTimeSeries(precipTimeSeries); - - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - irregularPrecipTimeSeries, - paramCode.toString()); - - //background painter - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - ValueMapper valueMapper = new UnitValueMapper(MeasuringUnit.inches, - MeasuringUnit.mm); - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - // observed data painters - - RegularTimeSeriesHolder precipTsHolder = new RegularTimeSeriesHolder(); - precipTsHolder.setTimeSeries(precipTimeSeries); - - - Color barColor = Color.BLUE; - TsBarPainter precipPainter = new TsBarPainter(barColor, - outlineColor, - precipTsHolder); - - assignPainterToCanvas(precipPainter, canvas); - - - addCanvasListeners(canvas, valueMapper); - - - return; - } - - // ---------------------------------------------------------------------------------- - public void initForPrecipDualMode(String locationId, - List paramCodeList, - TsPaintableCanvas canvas) - { - - // String header = "initForPrecipDualMode(): "; - - //set up the measuring unit for this method and the canvas - MeasuringUnit unit = MeasuringUnit.inches; - canvas.setDisplayedMeasuringUnit(unit); - - ParamCode pcParamCode = null; - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "PP in."; - String rightAxisLabelString = "mm"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - ParamCode paramCode = getParamCode(paramCodeList); - - String titleString = "Precip PC and PP for " + locationId; - - //read in the observed PC time series - - CodeTimer pcTimer = new CodeTimer(); - pcTimer.start(); - IrregularTimeSeries obsTs = - _dataMgr.loadObservedPrecipPcTimeSeries(locationId, - paramCode, - getStartTime()); - - pcTimer.stop("db retrieval took"); - - //read in the preprocessed PP time series - // that comes from PDC's preprocessed files - int durationInHours = getDurationInHours(paramCode.getIhfsDur()); - - CodeTimer pdcPrecipTimer = new CodeTimer(); - pdcPrecipTimer.start(); - - RegularTimeSeries precipTotalsTimeSeries = - _dataMgr.loadPrecipData(locationId, durationInHours); - - pdcPrecipTimer.stop("PDC data retrieval took"); - - //convert to irregular time series - IrregularTimeSeries irregularPrecipTotalTimeSeries = - getIrregularTimeSeries(precipTotalsTimeSeries); - - //background painter with its ValueMapper - //create the valueMapper - double minPPValue = 0.0; - - ValueMapper valueMapper = null; - - IrregularTimeSeries normalizedObsTs = null; - - - //set up the appropriate value mapper - if (obsTs.getMeasurementCount() > 0) - { - - rightAxisLabelString = "PC in."; - - Measurement minPCMeasurement = obsTs.getMinMeasurement(); - - double minPCValue = minPPValue; - - if (minPCMeasurement != null) - { - minPCValue = minPCMeasurement.getValue(unit); - } - - valueMapper = new PrecipPPAndPCValueMapper(minPPValue, - minPCValue, - unit); - - //This simply subtracts off the minPCValue from all entries, - // so that the resulting timeseries starts at 0.0. This will - //enable it to be drawn on the same graph as the PP routines. - normalizedObsTs = scaleIrregularTimeSeriesByAddition(obsTs, - minPCValue); - - //set up the secondary paramcode - pcParamCode = new ParamCode(paramCode); - if (paramCode.getPe().equals("PP")) - { - pcParamCode.setPe("PC"); - pcParamCode.setIhfsDur(0); - pcParamCode.setShefDur("I"); - pcParamCode.setExtremum("Z"); - pcParamCode.setTypeSource(paramCode.getTypeSource()); - } - - } - else - { - rightAxisLabelString = "mm"; - normalizedObsTs = obsTs; - valueMapper = new UnitValueMapper(unit, MeasuringUnit.mm); - } - - String[] textHeaderStringArray = null; - - if (pcParamCode != null) //there is pc data - { - textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, - pcParamCode.toString(), - irregularPrecipTotalTimeSeries, - paramCode.toString(), - irregularPrecipTotalTimeSeries.getMeasuringUnit().toString() - ); - } - else //there is no pc data - { - - textHeaderStringArray = - getTextHeaderStringArray(locationId, - irregularPrecipTotalTimeSeries, - paramCode.toString()); - } - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - // time line painter - TslTimeLinePainter timeLinePainter = - new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - - assignPainterToCanvas(timeLinePainter, canvas); - - - // observed PP data painters - RegularTimeSeriesHolder precipTsHolder = new RegularTimeSeriesHolder(); - precipTsHolder.setTimeSeries(precipTotalsTimeSeries); - - Color barColor = Color.BLUE; - TsBarPainter precipPainter = new TsBarPainter(barColor, - outlineColor, - precipTsHolder); - - assignPainterToCanvas(precipPainter, canvas); - - - //observed PC data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(normalizedObsTs); - - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - //tooltip listener - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ---------------------------------------------------------------------------------- - public IrregularTimeSeries scaleIrregularTimeSeriesByAddition(IrregularTimeSeries origTs, - double additive) - { - String header = "PDCDrawingMgr.scaleIrregularTimeSeriesByAddition(): "; - IrregularTimeSeries newTs = new IrregularTimeSeries(origTs.getMeasuringUnit()); - - AbsTimeMeasurement valueArray[] = origTs.getMeasurementArray(); - double value = 0; - - for (int i = 0 ; i < valueArray.length; i++) - { - AbsTimeMeasurement newMeasurement = new AbsTimeMeasurement(valueArray[i]); - value = newMeasurement.getValue() - additive; - - newMeasurement.setValue(value); - - newTs.insertMeasurement(newMeasurement); - } - - // System.out.println(header + "origTs = " + origTs); - // System.out.println(header + "newTs = " + newTs); - - return newTs; - } - - // ---------------------------------------------------------------------------------- - - public void initForPrecipPC(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - //set up the measuring unit for this method and the canvas - MeasuringUnit unit = MeasuringUnit.inches; - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "inches"; - String rightAxisLabelString = "mm"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - // set title and measuring units - - ParamCode paramCode = getParamCode(paramCodeList); - - - String titleString = "Precip PC for " + locationId; - - //read in the observed time series - IrregularTimeSeries obsTs = - _dataMgr.loadObservedPrecipPcTimeSeries(locationId, paramCode, getStartTime()); - - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, obsTs, paramCode.toString()); - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - //create the valueMapper - ValueMapper valueMapper = new UnitValueMapper(unit, MeasuringUnit.mm); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - - //tooltip listener - addCanvasListeners(canvas, valueMapper); - - return; - } - - // ---------------------------------------------------------------------------------- - - private int getDurationInHours(int ihfsDurationCode) - { - int durationInHours = 0; - - if ( (ihfsDurationCode >= 1000) && (ihfsDurationCode < 2000) ) - { - durationInHours = ihfsDurationCode - 1000; - } - if (ihfsDurationCode == 2001) - { - durationInHours = 24; - } - - return durationInHours; - } - // ---------------------------------------------------------------------------------- - - private IrregularTimeSeries getIrregularTimeSeries(RegularTimeSeries origTs) - { - MeasuringUnit unit = origTs.getMeasuringUnit(); - IrregularTimeSeries irregularTimeSeries = new IrregularTimeSeries(unit); - - int count = origTs.getMeasurementCount(); - - AbsTimeMeasurement measurement = null; - - for (int i = 0; i < count; i++) - { - measurement = origTs.getAbsTimeMeasurementByIndex(i); - irregularTimeSeries.insertMeasurement(measurement); - } - - return irregularTimeSeries; - } - - - // ------------------------------------------------------------------------------------- - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode - ) - - { - MeasuringUnit unit = obsTs.getMeasuringUnit(); - String unitString = unit.getName(); - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode, - String unitString - ) - - { - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCodeString, - IrregularTimeSeries fcstTs, - String otherParamCodeString, - String unitString - ) - - { - - String header = "getTextHeadStringArray()[6-args] : "; - - String[] textHeaderStringArray = null; - IrregularTimeSeries maxMinTs = null; - AbsTimeMeasurement max =null; - AbsTimeMeasurement min =null; - AbsTimeMeasurement last = null; - - if (paramCodeString == null) - { - paramCodeString = ""; - } - StringBuffer paramCodeStringBuffer = new StringBuffer(paramCodeString); - - - Location location = _dataMgr.getLocationInfo(locationId); - if (location == null) - { - location = new Location(); - location.setLid(locationId); - location.setLocationName("Unknown location"); - location.setElevation(0); - - } - - //determine units and the max, min, and last values - MeasuringUnit unit = determineUnit(obsTs, fcstTs); - - long startTime = getStartTime(); - long endTime = getEndTime(); - - - System.out.println(header + "before get max and min and last measurements "); - - // special handle for the PP precipitation data - - if (otherParamCodeString != null && (otherParamCodeString.substring(0, 2).equalsIgnoreCase("PP")) - && fcstTs != null) - { - max = getMaxTsMeasurement(fcstTs, null, unit, startTime, endTime); - System.out.println(header + "after get max " + max.getValue()); - - min = getMinTsMeasurement(fcstTs, null, unit, startTime, endTime); - System.out.println(header + "after get min "); - - last = getLastMeasurement(fcstTs, null, unit, startTime, endTime); - System.out.println(header + "after get last "); - - System.out.println(header + "after get max and min and last measurements "); - - } - else - { - max = getMaxTsMeasurement(obsTs, fcstTs, unit, startTime, endTime); - System.out.println(header + "after get max " + max.getValue()); - - min = getMinTsMeasurement(obsTs, fcstTs, unit, startTime, endTime); - System.out.println(header + "after get min "); - - last = getLastMeasurement(obsTs, fcstTs, unit, startTime, endTime); - System.out.println(header + "after get last "); - - System.out.println(header + "after get max and min and last measurements "); - - } - - //append to the param code string - if (otherParamCodeString != null) - { - paramCodeStringBuffer.append(" " + otherParamCodeString); - } - - // assign values to the textHeaderStringArray - textHeaderStringArray = new String[5]; - textHeaderStringArray[0] = locationId + " - " + - location.getLocationName() + " - " + - "Elevation: " + location.getElevation() + " feet"; - - textHeaderStringArray[1] = paramCodeStringBuffer.toString(); - textHeaderStringArray[2] = "Max = " + getMeasurementString(max, unitString); - textHeaderStringArray[3] = "Min = " + getMeasurementString(min, unitString); - textHeaderStringArray[4] = "Last = " + getMeasurementString(last, unitString); - - return textHeaderStringArray; - } - // -------------------------------------------------------------------------------------------------- - private MeasuringUnit determineUnit(IrregularTimeSeries ts1, IrregularTimeSeries ts2) - { - MeasuringUnit unit = MeasuringUnit.feet; - IrregularTimeSeries notNullTs = null; - - // pick an available time series to use for calculation max and min and last values - if (ts1 != null) - { - notNullTs = ts1; - } - else if (ts2 != null) - { - notNullTs = ts2; - } - else - { - notNullTs = null; - } - - if (notNullTs != null) - { - unit = notNullTs.getMeasuringUnit(); - } - - return unit; - } - - // -------------------------------------------------------------------------------------------------- - - private AbsTimeMeasurement getLastMeasurement(IrregularTimeSeries ts1, - IrregularTimeSeries ts2, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement measurement = null; - AbsTimeMeasurement m1 = null; - AbsTimeMeasurement m2 = null; - - m1 = getLastMeasurement(ts1, unit, startTime, endTime); - m2 = getLastMeasurement(ts2, unit, startTime, endTime); - - - if ((m1 != null) && (m2 != null)) - { - if (m1.getTime() > m2.getTime()) - { - measurement = m1; - } - else - { - measurement = m2; - } - - } - else if (m1 != null) - { - measurement = m1; - } - else if (m2 != null) - { - measurement = m2; - } - - return measurement; - } - - // -------------------------------------------------------------------------------------------------- - - - private AbsTimeMeasurement getLastMeasurement(IrregularTimeSeries timeSeries, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement measurement = null; - - if (timeSeries != null) - { - int count = timeSeries.getMeasurementCount(); - - for (int i = count - 1; i >= 0; i--) - { - measurement = timeSeries.getAbsTimeMeasurementByIndex(i); - if (measurement != null) - { - long time = measurement.getTime(); - - if ((time <= endTime) && (time >= startTime)) - { - break; // quit, I found the measurement that I want. - } - } - } - } - - measurement = getMeasurementByUnit(measurement, unit); - - return measurement; - - } - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getMaxTsMeasurement(IrregularTimeSeries ts1, - IrregularTimeSeries ts2, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement returnMeasurement = null; - - AbsTimeMeasurement m1 = null; - AbsTimeMeasurement m2 = null; - int notNullCount = 0; - - if (ts1 != null) - { - m1 = ts1.getMaxMeasurement(startTime, endTime); - if (m1 != null) - { - returnMeasurement = m1; - notNullCount++; - } - } - if (ts2 != null) - { - m2 = ts2.getMaxMeasurement(startTime, endTime); - if (m2 != null) - { - notNullCount++; - if (notNullCount == 1) // ts1 was null - { - returnMeasurement = m2; - } - else - // notNullCount == 2, so ts1 was not null, need to compare - { - if (m2.getValue(unit) > m1.getValue(unit)) - { - returnMeasurement = m2; - } - - } - } - } - - returnMeasurement = getMeasurementByUnit(returnMeasurement, unit); - - return returnMeasurement; - } - - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getMinTsMeasurement(IrregularTimeSeries ts1, - IrregularTimeSeries ts2, - MeasuringUnit unit, - long startTime, - long endTime) - { - AbsTimeMeasurement returnMeasurement = null; - - AbsTimeMeasurement m1 = null; - AbsTimeMeasurement m2 = null; - int notNullCount = 0; - - if (ts1 != null) - { - m1 = ts1.getMinMeasurement(startTime, endTime); - if (m1 != null) - { - returnMeasurement = m1; - notNullCount++; - } - } - if (ts2 != null) - { - m2 = ts2.getMinMeasurement(startTime, endTime); - if (m2 != null) - { - notNullCount++; - if (notNullCount == 1) // ts1 was null - { - returnMeasurement = m2; - } - else - // notNullCount == 2, so ts1 was not null, need to compare - { - if (m2.getValue(unit) < m1.getValue(unit)) - { - returnMeasurement = m2; - } - - } - } - } - - returnMeasurement = getMeasurementByUnit(returnMeasurement, unit); - - return returnMeasurement; - } - - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getMeasurementByUnit(AbsTimeMeasurement origMeasurement, - MeasuringUnit unit) - { - AbsTimeMeasurement measurement = origMeasurement; - - if ( (origMeasurement != null) && (origMeasurement.getUnit() != unit)) - { - measurement = AbsTimeMeasurement.getConvertedCopy(origMeasurement, unit); - } - - return measurement; - } - - // -------------------------------------------------------------------------------------------------- - - - private String getMeasurementString(AbsTimeMeasurement measurement, String unitString) - { - String measurementString = null; - - if (measurement != null) - { - String timeString = - DbTimeHelper.getDateTimeStringFromLongTime(measurement.getTime()); - - //get rid of the seconds - timeString = timeString.substring(0, timeString.length()-3); - - double value = MathHelper.roundToNDecimalPlaces(measurement.getValue(), 2); - - measurementString = - value + " " + - unitString + - " at " + timeString + "Z"; - - } - else - { - measurementString = "Not Available"; - } - - return measurementString; - } - - // -------------------------------------------------------------------------------------------------- - private String wrapInHTML(String origString) - { - StringBuffer buffer = new StringBuffer("
    " + origString + "
    "); - - return buffer.toString(); - } -// ------------------------------------------------------------ - private String getVerticalText(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - buffer.append(charArray[i]); - - //don't do a break for the last one - if (i < charArray.length-1) - { - buffer.append("
    "); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } -// ------------------------------------------------------------ - private String getVerticalTextFromNewLines(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - char c = charArray[i]; - if (c == '\n') - { - buffer.append("
    "); - } - else - { - buffer.append(c); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } - // -------------------------------------------------------------------------------------------------- - - - /** - * @param startTime The startTime to set. - */ - public void setStartTime(long startTime) - { - _startTime = startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @return Returns the startTime. - */ - public long getStartTime() - { - return _startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @param endTime The endTime to set. - */ - public void setEndTime(long endTime) - { - _endTime = endTime; - } - /** - * @return Returns the endTime. - */ - public long getEndTime() - { - return _endTime; - } - - // -------------------------------------------------------------------------------------------------- - - private class RefreshTimerListener implements ActionListener - { - public void actionPerformed(ActionEvent e) - { - refresh(); - } - } - - // -------------------------------------------------------------------------------------------------- - - private void refresh() - { - String header = "PDCDrawingMgr.refresh(): "; - - System.out.println(header + "Refreshing"); - - display(_rememberedArgStringArray, _exitOnClose); - } - - // -------------------------------------------------------------------------------------------------- - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/pdc/PdcTslDataManager.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/pdc/PdcTslDataManager.java deleted file mode 100644 index 2149dbf60a..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/pdc/PdcTslDataManager.java +++ /dev/null @@ -1,1526 +0,0 @@ -package ohd.hseb.timeserieslite.pdc; - -import java.sql.SQLException; -import java.text.DecimalFormat; - -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LocPDCRecord; -import ohd.hseb.ihfsdb.generated.LocPDCView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RawPCRecord; -import ohd.hseb.ihfsdb.generated.RawPCTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.SnowRecord; -import ohd.hseb.ihfsdb.generated.SnowTable; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.ihfsdb.generated.TemperatureRecord; -import ohd.hseb.ihfsdb.generated.TemperatureTable; -import ohd.hseb.ihfsdb.generated.WeatherRecord; -import ohd.hseb.ihfsdb.generated.WeatherTable; -import ohd.hseb.ihfsdb.generated.WindRecord; -import ohd.hseb.ihfsdb.generated.WindTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.pdc_pp.PDCFileReader; -import ohd.hseb.pdc_pp.RegularObsTimeSeries; -import ohd.hseb.pdc_pp.TimeValuePair; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - - -public class PdcTslDataManager -{ - - // -------------------------------------------------------------------------------------------- - - public static final double MISSING = -999.0; - - private static final int _defaultQualityCode = 1879048191; - private static final int _questionable_bad_threshold = 1073741824; - private static final long MILLIS_PER_HOUR = 60*60*1000; - private static final long MILLIS_PER_YEAR = (365L * 24L * 60L * 60L * 1000L); - - private Database _db = null; - private Logger _logger = null; - - private String _jdbcConnectionString = null; - private PDCDataType _dataType = null; - - private String _physicalElement = null; - - private String _preprocessedFilePath = null; - private double MAX_REASONABLE_PRECIP = 30; //inches per hour - - // --------------------------------------------------------------------------------- - - public PdcTslDataManager(String jdbcConnectionString) - { - _logger = new FileLogger(true); - - _jdbcConnectionString = jdbcConnectionString; - - _db = new Database(); - - _db.connect(_jdbcConnectionString); - - getAppsDefaults(); - } - // --------------------------------------------------------------------------------- - - private void getAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - - _preprocessedFilePath = ad.getToken( "pdc_pp_dir" ) + "/"; - } - - // ------------------------------------------------------------------------------------- - - private void connect(String connectionString) - { - _db.connectWithDriverSearch(connectionString); - } - - // ------------------------------------------------------------------------------------- - - public void disconnect() - { - _db.disconnect(); - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSource(String lid, - String pe) - { - String header = "PdcTslDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + "'" + - " AND pe = '" + pe + "'" + - " AND dur = 0 " + - " AND ts like 'F%' " + - " order by ts_rank ASC" ; - - try - { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - if (pe.charAt(0)=='H') - { - for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - if (fcstHeightRecordExists(record)) - { - newTypeSource = record.getTs(); - break; - } - } - - } - else //pe is not 'H*', so don't look at fcstHeight to see if it exists - { - newTypeSource = record.getTs(); - } - - } - } - catch(SQLException e) - { - logSQLException(e); - } - - // System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // ---------------------------------------------------------------------------------- - public boolean fcstHeightRecordExists(IngestFilterRecord ingestRecord) - { - boolean result = false; - - String header = "PdcTslDataManager.fcstHeightRecordExists(): "; - - FcstHeightTable table = new FcstHeightTable(_db); - - String whereClause = "WHERE lid = '" + ingestRecord.getLid() + "'" + - " AND pe = '" + ingestRecord.getPe() + "'" + - " AND dur = " + ingestRecord.getDur() + - " AND ts = '" + ingestRecord.getTs() + "'"; - - - try - { - int recordCount = table.selectCount(whereClause); - - if (recordCount > 0) - { - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - // ---------------------------------------------------------------------------------- - /* public String getPreferredFcstTypeSourceByIngestFilter(String lid, - ParamCode paramCode) - { - String header = "PdcTslDataManager.getPreferredFcstTypeSourceByIngestFilter(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + - "' AND pe = '" + paramCode.getPe() + "'" + - "AND dur = 0 " + - "AND ts like 'F%' " + - " order by ts_rank ASC" ; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - int i = 0; - //for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - newTypeSource = record.getTs(); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSourceByFcstHeight(String lid, - ParamCode paramCode) - { - String header = "PdcTslDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - FcstHeightTable table = new FcstHeightTable(_db); - - FcstHeightRecord record = null; - - String whereClause = "WHERE lid = '" + lid + - "' AND pe = '" + paramCode.getPe() + "'" + - "AND dur = 0 " + - " order by basistime DESC, validtime ASC" ; - - try - { - List recordList = table.selectNRecords(whereClause,1); - if (recordList.size() > 0) - { - int i = 0; - //for (int i = 0; i < recordList.size(); i++) - { - record = (FcstHeightRecord) recordList.get(i); - newTypeSource = record.getTs(); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - */ - // ------------------------------------------------------------------------------------- - - public SigRiverLevels loadSigRiverLevels(String locationId) - { - String header = "PdcTslDataManager.loadSigRiverLevels(): "; - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (RiverstatRecord) recordList.get(0); - - String primaryPe = record.getPrimary_pe(); - - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - - - if (DbTable.isNull(actionStage)) - { - System.out.println(header + " actionStage is null for " + locationId); - } - if (DbTable.isNull(record.getPrimary_pe())) - { - System.out.println(header + " primary_pe is null for " + locationId); - record.setPrimary_pe(" "); - } - - - - levels = new SigRiverLevels(locationId, - record.getPrimary_pe(), - floodStage, - actionStage, - floodFlow, - actionFlow); - - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return levels; - } - - // -------------------------------------------------------------------------------------------------- - - public RatingCurve loadRatingCurve(String locationId) - { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - - try - { - ratingRecordList = ratingTable.select("WHERE LID = '" + - locationId + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" + - locationId + "' AND active = 'T' ORDER BY date desc", 1 ); - - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId + "'"); - - //determine total amount of active - //rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) - { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList.get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - //System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - - //initialize the RatingCurve object with data from the database, including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) - { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - //done by addRatingPoint - //ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } //end for - - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) - { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList.get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord.getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } - catch (SQLException e) - { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - -// ------------------------------------------------------------------------------------- - - public RegularTimeSeries loadPrecipData(String locationId, int durationInHours) - { - String header = "PdcTslDataManager.loadPrecipData(): "; - RegularTimeSeries timeSeries = null; - - if (locationId.equalsIgnoreCase("MAX")) - { - timeSeries = loadPrecipDataForMaximumInArea(locationId, durationInHours); - } - else if (locationId.equalsIgnoreCase("AVG")) - { - timeSeries = loadPrecipDataForAverageInArea(locationId, durationInHours); - } - else - { - timeSeries = loadPrecipDataForRealLocation(locationId, durationInHours); - } - - return timeSeries; - - } - -// ------------------------------------------------------------------------------------- - public RegularTimeSeries loadPrecipDataForRealLocation(String locationId, - int durationInHours) - { - - // String header = "PdcTslDataManager.loadPrecipDataRealLocation(): "; - RegularTimeSeries timeSeries = null; - String precipFileName = getPrecipFileName(durationInHours); - - - List list = readPrecipObsTimeSeriesListFromCachedFile(precipFileName); - - //iterate through the list to find the matching locationId - //once found, translate the RegularObsTimeSeries to a RegularTimeSeries - - for (int i = 0; i < list.size(); i++) - { - RegularObsTimeSeries regularObsTimeSeries = (RegularObsTimeSeries) list.get(i); - - String lid = regularObsTimeSeries.getDescriptor().getLid(); - - if (lid.equals(locationId)) - { - timeSeries = getRegularTimeSeries(regularObsTimeSeries); - break; - } - - } - - return timeSeries; - } - -// ------------------------------------------------------------------------------------- - public RegularTimeSeries loadPrecipDataForMaximumInArea(String locationId, int durationInHours) - { - String header = "PdcTslDataManager.loadPrecipDataForMaximumInArea(): "; - RegularTimeSeries timeSeries = null; - String precipFileName = getPrecipFileName(durationInHours); - - List regularObsTimeSeriesList = readPrecipObsTimeSeriesListFromCachedFile(precipFileName); - - RegularObsTimeSeries maxRegularObsTimeSeries = null; - - RegularObsTimeSeries regularObsTimeSeries = null; - - - //let the first obstimeseries initialize the max time series - if (regularObsTimeSeriesList.size() > 0) - { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList.get(0); - maxRegularObsTimeSeries = regularObsTimeSeries; - } - - - List maxTimeValuePairList = maxRegularObsTimeSeries.getTimeValuePairList(true); - - - //iterate through the list of RegularObsTimeSeries to set the maximums - - for (int i = 1; i < regularObsTimeSeriesList.size(); i++) - { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList.get(i); - List timeValuePairList = regularObsTimeSeries.getTimeValuePairList(true); - - for (int j = 0; j < timeValuePairList.size(); j++) - { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(j); - long time = pair.getDateTime(); - double value = pair.getValue(); - - TimeValuePair maxPair = (TimeValuePair) maxTimeValuePairList.get(j); - double maxValue = maxPair.getValue(); - - if (value < MAX_REASONABLE_PRECIP) - { - if (value > maxValue) - { - String timeString = DbTimeHelper.getDateTimeStringFromLongTime(time); - - System.out.println(header + " new max = " + value + " at " + - regularObsTimeSeries.getDescriptor().getLid() + - " for 1- hour ending at " + timeString); - - - maxPair.setValue(value); - } - } - } - } - - //just to be sure - maxRegularObsTimeSeries.setTimeValuePairList(maxTimeValuePairList); - - // translate to a normal - timeSeries = getRegularTimeSeries(maxRegularObsTimeSeries); - - return timeSeries; - - } - - -// ------------------------------------------------------------------------------------- - - public RegularTimeSeries loadPrecipDataForAverageInArea(String locationId, - int durationInHours) - { - // String header = "PdcTslDataManager.loadPrecipDataForAverageInArea(): "; - RegularTimeSeries timeSeries = null; - - String precipFileName = getPrecipFileName(durationInHours); - - List regularObsTimeSeriesList = readPrecipObsTimeSeriesListFromCachedFile(precipFileName); - - RegularObsTimeSeries averageRegularObsTimeSeries = null; - RegularObsTimeSeries regularObsTimeSeries = null; - List averageTimeValuePairList = null; - - if ((regularObsTimeSeriesList != null) && (regularObsTimeSeriesList.size() > 0)) - { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList.get(0); - averageRegularObsTimeSeries = new RegularObsTimeSeries(regularObsTimeSeries); - - averageTimeValuePairList = averageRegularObsTimeSeries.getTimeValuePairList(true); - } - else - { - return timeSeries; - } - - //iterate through the list of RegularObsTimeSeries to set the totals - - for (int i = 0; i < regularObsTimeSeriesList.size(); i++) - { - regularObsTimeSeries = (RegularObsTimeSeries) regularObsTimeSeriesList.get(i); - List timeValuePairList = regularObsTimeSeries.getTimeValuePairList(true); - - for (int j = 0; j < timeValuePairList.size(); j++) - { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(j); - long time = pair.getDateTime(); - double value = pair.getValue(); - double totalValue = 0; - double previousValue = 0; - - if ((value < MAX_REASONABLE_PRECIP) && (value >= 0.0)) - { - TimeValuePair totalPair = (TimeValuePair) averageTimeValuePairList.get(j); - if ( i == 0) //first iteration only, init the previous totals to Zero - { - previousValue = 0; - } - else - { - previousValue = totalPair.getValue(); - } - - totalValue = previousValue + value; - - totalPair.setValue(totalValue); - } - } - } - - //determine the number of time series to divide by - double count = regularObsTimeSeriesList.size(); - - // take the totals and convert to averages - for (int i = 0; i < averageTimeValuePairList.size(); i++) - { - TimeValuePair pair = (TimeValuePair) averageTimeValuePairList.get(i); - long time = pair.getDateTime(); - double value = pair.getValue() / count; - - pair.setValue(value); - - } - - //just to be sure - averageRegularObsTimeSeries.setTimeValuePairList(averageTimeValuePairList); - - // translate to a normal - timeSeries = getRegularTimeSeries(averageRegularObsTimeSeries); - - return timeSeries; - - } - - -// ------------------------------------------------------------------------------------- - - - public RegularTimeSeries getRegularTimeSeries(RegularObsTimeSeries obsTimeSeries) - { - - long startTime = obsTimeSeries.getDescriptor().getStartTime(); - long endTime = obsTimeSeries.getDescriptor().getEndTime(); - long timeStepIntervalInMillis = obsTimeSeries.getTimeStepIntervalInMillis(); - long timeStepIntervalInHours = timeStepIntervalInMillis / MILLIS_PER_HOUR; - MeasuringUnit unit = MeasuringUnit.inches; - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - RegularTimeSeries regularTimeSeries = - new RegularTimeSeries(startTime, endTime, (int) timeStepIntervalInHours , unit); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - for (int i = 0; i < timeValuePairList.size(); i++) - { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(i); - long time = pair.getDateTime(); - double value = pair.getValue(); - - Measurement measurement = new Measurement(value, unit); - - regularTimeSeries.setMeasurementByTime(measurement, time); - } - - - // Days go from 12Z to 12Z, not 0Z to 0Z, - // so shift the time serires by 12 hours - if (timeStepIntervalInHours == 24) - { - regularTimeSeries.shiftStartEndTimeHours(12); - } - - return regularTimeSeries; - } - -// ------------------------------------------------------------------------------------- - - - public List readPrecipObsTimeSeriesListFromCachedFile(String fullFilePath) - { - String header = "PdcTslDataManager.readPrecipObsTimeSeriesListFromCachedFile(): "; - - PDCFileReader reader = new PDCFileReader(fullFilePath); - - CodeTimer readerTimer = new CodeTimer(); - - readerTimer.start(); - List obsTimeSeriesList = reader.read(); - readerTimer.stop(header + "reader.read() took"); - - return obsTimeSeriesList; - } - -// ------------------------------------------------------------------------------------- - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } -// ------------------------------------------------------- - public String getLocationName(String locationId) - { - return loadLocationName(locationId); - } -// ------------------------------------------------------- - private String loadLocationName(String locationId) - { - - String locationName = null; - - LocationRecord record = null; - LocationTable table = new LocationTable(_db); - - - try - { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - - if (recordList.size() > 0) - { - record = (LocationRecord) recordList.get(0); - locationName = record.getName(); - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return locationName; - - } - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId, - ParamCode paramCode, - long startTime) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - -// ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (HeightRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedDischargeTimeSeries(String locationId, - ParamCode paramCode, - long startTime) - { - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "PdcTslDataManager.loadObservedDischargeTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - -// ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (DischargeRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedPrecipPcTimeSeries(String locationId, - ParamCode paramCode, - long startTime) - { - - MeasuringUnit unit = MeasuringUnit.inches; - - String header = "PdcTslDataManager.loadObservedPrecipPcTimeSeries(): "; - IrregularTimeSeries timeSeries = - new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - RawPCTable table = new RawPCTable(_db); - RawPCRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - long currentTime = System.currentTimeMillis(); - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = 'PC' " + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = 0 " + - " AND quality_code >= " + _questionable_bad_threshold + - " AND obstime >= '" + startTimeString + "'"; - - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (RawPCRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - timeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return timeSeries; - - } - - // ------------------------------------------------------------------------ - public IrregularTimeSeries loadObservedTemperatureTimeSeries(String locationId, - ParamCode paramCode) - { - String header = "PdcTslDataManager.loadTemperatureTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.degreesFahrenheit; - - IrregularTimeSeries timeSeries = - new IrregularTimeSeries(unit); - - - final double missingValue = -9999.0; - TemperatureTable table = new TemperatureTable(_db); - TemperatureRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (TemperatureRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - timeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return timeSeries; - - } - -// ----------------------------------------------------------------------------------- - public IrregularTimeSeries loadRelativeHumidityTimeSeries(String locationId, - ParamCode paramCode) - { - String header = "PdcTslDataManager.loadRelativeHumidityTimeSeries(): "; - - MeasuringUnit unit = MeasuringUnit.unitless; - - IrregularTimeSeries timeSeries = - new IrregularTimeSeries(unit); - - - final double missingValue = -9999.0; - WeatherTable table = new WeatherTable(_db); - WeatherRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (WeatherRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - timeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return timeSeries; - - } - -// ----------------------------------------------------------------------------------- - public IrregularTimeSeries loadObservedWindTimeSeries(String locationId, - ParamCode paramCode, MeasuringUnit measuringUnit) - { - String header = "PdcTslDataManager.loadObservedWindSpeedTimeSeries(): "; - - MeasuringUnit unit = measuringUnit; - - IrregularTimeSeries timeSeries = - new IrregularTimeSeries(unit); - - - final double missingValue = -9999.0; - WindTable table = new WindTable(_db); - WindRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold; - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (WindRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - timeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return timeSeries; - - } - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadObservedSnowTimeSeries(String locationId, ParamCode paramCode) - { - String header = "PdcTslDataManager.loadObservedSnowTimeSeries(): "; - - - MeasuringUnit unit = MeasuringUnit.inches; - - IrregularTimeSeries timeSeries = - new IrregularTimeSeries(unit); - - - final double missingValue = -9999.0; - SnowTable table = new SnowTable(_db); - SnowRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold; - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (SnowRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - timeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return timeSeries; - - } - -// ----------------------------------------------------------------------------------- - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadObservedDewpointTimeSeries(String locationId, - ParamCode paramCode) - { - String header = "PdcTslDataManager.loadObservedDewpointTimeSeries(): "; - - - MeasuringUnit unit = MeasuringUnit.inches; - - IrregularTimeSeries timeSeries = - new IrregularTimeSeries(unit); - - - final double missingValue = -9999.0; - TemperatureTable table = new TemperatureTable(_db); - TemperatureRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - long earlyTime = currentTime - MILLIS_PER_YEAR; - long lateTime = currentTime + MILLIS_PER_YEAR; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold; - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (TemperatureRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - timeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return timeSeries; - - } - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - ParamCode paramCode) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + - " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - - long originalBasisTime = 0; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - - - record = (FcstHeightRecord) recordList.get(i); - - if (i == 0) - { - originalBasisTime = record.getBasistime(); - } - else - { - if (record.getBasistime() != originalBasisTime) - { - break; - } - } - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + measurement); - - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - } - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - ParamCode paramCode) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstDischargeTimeSeries(): "; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + - " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - - long originalBasisTime = 0; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - - - record = (FcstDischargeRecord) recordList.get(i); - - if (i == 0) - { - originalBasisTime = record.getBasistime(); - } - else - { - if (record.getBasistime() != originalBasisTime) - { - break; - } - } - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + measurement); - - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return dischargeTimeSeries; - } - -// ----------------------------------------------------------------------------------- - - - public Location getLocationInfo(String locationId) - { - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - Location location = null; - String whereClause = " WHERE lid = '" + locationId + "'"; - - LocPDCView locPDCView = new LocPDCView( _db ); - RiverstatTable riverStatTable = new RiverstatTable( _db ); - StnClassTable stationClassTable = new StnClassTable(_db); - - - List locPDCViewList = null; - List riverStatRecordList = null; - List stationClassList = null; - - - try - { - locPDCViewList = locPDCView.select( whereClause ); - riverStatRecordList = riverStatTable.select( whereClause ); - - stationClassList = stationClassTable.select( whereClause ); - - } - catch( SQLException e ) - { - logSQLException(e); - e.printStackTrace(); - } - - - - for ( int i = 0; i < locPDCViewList.size(); i++ ) - { - LocPDCRecord locPDCRecord = (LocPDCRecord) locPDCViewList.get( i ); - location = new Location(); - location.setLid( locPDCRecord.getLid().trim() ); - location.setHsa( locPDCRecord.getHsa().trim() ); - - - location.setLat( Double.parseDouble( decimalFormat.format( locPDCRecord.getLat() ) ) ); - location.setLon( Double.parseDouble( decimalFormat.format( locPDCRecord.getLon() ) ) ); - - - location.setElevation( locPDCRecord.getElev() ); - location.setLocationName( locPDCRecord.getName() ); - location.setRiverStation( false ); - - double fq = locPDCRecord.getFq(); - double fs = locPDCRecord.getFs(); - - if ( fq == 0 ) // missing value - { - location.setFloodFlow( MISSING ); - } - else - { - location.setFloodFlow( fq ); - } - - if ( fs == 0 ) // missing value - { - location.setFloodStage( MISSING ); - } - else - { - location.setFloodStage( fs ); - } - - if ( ( fq == 0.0 ) && ( fs != 0.0 ) && (location.getRatingCurve() != null ) ) - { - location.setFloodFlow( location.getRatingCurve().getDischargeFromStage( fs ) ); - } - - String dispClass = locPDCRecord.getDisp_class(); - - if ( ( dispClass.indexOf( "F" ) ) != -1 ) - { - location.setFcstPoint( true ); - } - else - { - location.setFcstPoint( false ); - } - - String dcp = locPDCRecord.getIs_dcp(); - - if ( ( dcp.indexOf( "T" ) ) != -1 ) - { - location.setDCP( true ); - } - else - { - location.setDCP( false ); - } - - String observer = locPDCRecord.getIs_observer(); - - if ( ( observer.indexOf( "T" ) ) != -1 ) - { - location.setObserver( true ); - } - else - { - location.setObserver( false ); - } - - location.setTelemType( locPDCRecord.getTelem_type() ); - - - } - - - - return location; - } -// ------------------------------------------------------------------------ - private String getPrecipFileName(int durationInHours) - { - String precipFileName = _preprocessedFilePath + - "/Precip" + durationInHours +"Hour.dat"; - return precipFileName; - } -// ------------------------------------------------------------------------ - - public long getLatestHourTime() - { - return TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - } -// ----------------------------------------------------------------------------------- - -} //end PdcTslDataManager diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/rivermon/RiverMonDrawingMgr.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/rivermon/RiverMonDrawingMgr.java deleted file mode 100644 index 786da61b4c..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/rivermon/RiverMonDrawingMgr.java +++ /dev/null @@ -1,1234 +0,0 @@ -package ohd.hseb.timeserieslite.rivermon; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeriesHolder; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.FlowToStageValueMapper; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.model.StageToFlowValueMapper; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.timeserieslite.TSLDrawingMgr; -import ohd.hseb.timeserieslite.TSLFrame; -import ohd.hseb.timeserieslite.gui.drawing.SignificantLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TsCanvasToolTipListener; -import ohd.hseb.timeserieslite.gui.drawing.TsDataPointPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslCanvasPainter; -import ohd.hseb.timeserieslite.gui.drawing.TslTimeLinePainter; -import ohd.hseb.timeserieslite.gui.drawing.TslBackgroundPainter; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.MathHelper; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.util.TimeHolder; -import ohd.hseb.util.UnitValueMapper; -import ohd.hseb.util.ValueMapper; -import ohd.hseb.util.gui.drawing.TsPaintableCanvas; - -public class RiverMonDrawingMgr implements TSLDrawingMgr -{ - private static final long MILLIS_PER_HOUR = 60*60*1000; - private static final int TOP_MARGIN = 100; - private int _hoursBackInTime = 120; - private int _hoursForwardInTime = 168; - - private RiverMonTslDataManager _dataMgr = null; - private String _locationId = null; - private List _paramCodeList = new ArrayList(); - private String _jdbcConnectionString = null; - - // private PDCDataType _dataType = null; - private List _dataTypeList = new ArrayList(); - - private long _startTime = 0; - private long _endTime = 0; - - private int HOURS_TO_ROUND = 6; - - - private static Map _physicalElementMap = new HashMap(); - static - { - _physicalElementMap.put("HG", PDCDataType.HEIGHT); - _physicalElementMap.put("HP", PDCDataType.HEIGHT); - _physicalElementMap.put("HT", PDCDataType.HEIGHT); - _physicalElementMap.put("QR", PDCDataType.DISCHARGE); - _physicalElementMap.put("QT", PDCDataType.DISCHARGE); - _physicalElementMap.put("LS", PDCDataType.LAKE_STORAGE); - - } - - - // -------------------------------------------------------------------------------------------------- - - public RiverMonDrawingMgr() - { - - } - // -------------------------------------------------------------------------------------------------- - public void display(String[] argStringArray, boolean exitOnClose) - { - - CodeTimer timer = new CodeTimer(); - - handleCommandLineArgs(argStringArray); - - String header = "PDCDrawingMgr.display()"; - - - TSLFrame frame = new TSLFrame(); - - frame.setExitOnClose(exitOnClose); - - System.out.println(header + "after TSLFrame()"); - - TsPaintableCanvas canvas = frame.getCanvas(); - - - PDCDataType dataType = null; - - if ( _dataTypeList.size() > 0 ) - { - dataType = (PDCDataType) _dataTypeList.get(0); - } - - initializeCanvas(dataType, _paramCodeList, canvas); - - timer.start(); - frame.setVisible(true); - timer.stop("setVisible() took "); - - } - - // -------------------------------------------------------------------------------------------------- - - private void initializeCanvas(PDCDataType dataType, - List paramCodeList, - TsPaintableCanvas canvas) - { - initializeTimeWindow(canvas); - - //make room for the large area required by the text header in the graph - canvas.setTopMargin(TOP_MARGIN); - - - if (dataType == PDCDataType.HEIGHT) - { - initForHeight(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.DISCHARGE) - { - initForDischarge(_locationId, paramCodeList, canvas); - } - - else if (dataType == PDCDataType.LAKE_STORAGE) - { - // initForLakeStorage(_locationId, canvas); - } - - - - //call this again to make it redraw everything correctly - // it wasn't working without this - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - private void initializeTimeWindow(TsPaintableCanvas canvas) - { - //set up time window - long currentTime = System.currentTimeMillis(); - long roundedCurrentTime = - TimeHelper.truncateTimeInMillisToNearestHour(currentTime, HOURS_TO_ROUND); - - setStartTime(roundedCurrentTime - (_hoursBackInTime * MILLIS_PER_HOUR)); - setEndTime(getStartTime() + (_hoursForwardInTime * MILLIS_PER_HOUR)); - - canvas.setTimeWindow(getStartTime(), getEndTime()); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private boolean isValueAvailable(Measurement measurement, MeasuringUnit unit) - { - boolean result = false; - - if (measurement != null) - { - if (measurement.getValue(unit) > 0.0) - { - result = true; - } - } - return result; - } - - // -------------------------------------------------------------------------------------------------- - - private void addCanvasListeners(TsPaintableCanvas canvas, ValueMapper valueMapper) - { - //Add listener for the tooltip - TsCanvasToolTipListener toolTipMgr = new TsCanvasToolTipListener(canvas, valueMapper); - canvas.addMouseMotionListener(toolTipMgr); - - return; - } - - // -------------------------------------------------------------------------------------------------- - - private void handleCommandLineArgs(String[] argStringArray) - { - String header = "PdcDrawingManager.handleCommandLineArgs(): "; - - //includes the optional jdbcConnectionString - if (argStringArray.length > 1) - { - _jdbcConnectionString = argStringArray[1]; - _dataMgr = new RiverMonTslDataManager(_jdbcConnectionString); - } - - //location id - if (argStringArray.length > 2) - { - _locationId = argStringArray[2]; - } - - -// create param code list and dataType list - for (int i = 3; i < argStringArray.length; i++) - { - String paramCodeString = argStringArray[i]; - System.out.println(header + "paramCodeString = " + paramCodeString); - - if ((paramCodeString != null) && (paramCodeString.length() == 6)) //valid example = HRIRGZ - { - ParamCode paramCode = new ParamCode(paramCodeString); - - paramCode = expandParamCode(_locationId, paramCode); - - if (paramCode != null) - { - _paramCodeList.add(paramCode); - - // String physicalElement = paramCode.substring(0,2); - PDCDataType dataType = getDataTypeFromPhysicalElement(paramCode.getPe()); - _dataTypeList.add(dataType); - } - } - } - - return; - } - // ------------------------------------------------------------------------------------- - private ParamCode expandParamCode(String locationId, ParamCode paramCode) - { - - String header = "RiverMonDrawingMgr.expandParamCode(): "; - ParamCode expandedParamCode = new ParamCode(paramCode); - String expandedParamCodeString = null; - - String typeSource = paramCode.getTypeSource(); - String peString = paramCode.getPe(); - - if (typeSource.indexOf('-') == 1) - { - if (typeSource.charAt(0) == 'F') - { - typeSource = _dataMgr.getPreferredFcstTypeSource(locationId, peString); - - if (typeSource != null) - { - expandedParamCode.setTypeSource(typeSource); - expandedParamCodeString = expandedParamCode.toString(); - } - else - { - expandedParamCode = null; - expandedParamCodeString = null; - } - } - - } - else - { - expandedParamCodeString = expandedParamCode.toString(); - } - - System.out.println(header + "original paramCode = " + paramCode.toString() ); - System.out.println(header + "expandedParamCode = " + expandedParamCodeString ); - - return expandedParamCode; - - } - - // ------------------------------------------------------------------------------------- - - ParamCode getParamCode(List paramCodeList) - { - ParamCode paramCode = null; - - - if ( (paramCodeList != null) && (paramCodeList.size() > 0) ) - { - paramCode = (ParamCode) paramCodeList.get(0); - } - - return paramCode; - } - - - // ------------------------------------------------------------------------------------- - - PDCDataType getDataTypeFromPhysicalElement(String physicalElement) - { - - PDCDataType dataType = (PDCDataType) _physicalElementMap.get(physicalElement); - if (dataType == null) - { - if (stringStartsWith(physicalElement, 'H')) - { - dataType = PDCDataType.HEIGHT; - } - if (stringStartsWith(physicalElement, 'Q')) - { - dataType = PDCDataType.DISCHARGE; - } - } - - return dataType; - - } - - // ------------------------------------------------------------------------------------- - - private boolean stringStartsWith(String physicalElement, char firstCharacter) - { - boolean result = false; - - if ( (physicalElement!= null) && - (physicalElement.length() > 0) && - (physicalElement.charAt(0) == firstCharacter) - ) - { - result = true; - } - - return result; - } - // ------------------------------------------------------------------------------------- - - public void initForHeight(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "RiverMonDrawingMgr.initForHeight(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = null; //actually depends on rating curve existence - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = ""; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new StageToFlowValueMapper(ratingCurve); - rightAxisLabelString = "cfs"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "feet"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - //Color floodStageColor = Color.RED; - Color floodStageColor = Color.ORANGE; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForHeightWithLists(String locationId, - List paramCodeList, - TsPaintableCanvas canvas) - { - - String header = "RiverMonDrawingMgr.initForHeightWithLists(): "; - - MeasuringUnit unit = MeasuringUnit.feet; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "feet"; - String rightAxisLabelString = "cfs"; - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - String physicalElement = "HG"; - - // set title and measuring units - - - String titleString = "River Stages for " + locationId; - //read in the observed time series - - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - - List obsTsList = new ArrayList(); - List fcstTsList = new ArrayList(); - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstStageTimeSeries(locationId, paramCode); - fcstStageTimer.stop(header + "loadFcstStageTimeSeries took"); - - fcstTsList.add(fcstTs); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - - CodeTimer stageTimer = new CodeTimer(); - - stageTimer.start(); - obsTs = - _dataMgr.loadObservedStageTimeSeries(locationId, paramCode, getStartTime()); - - stageTimer.stop(header + "loadObservedStageTimeSeries took "); - - - obsTsList.add(obsTs); - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - ValueMapper valueMapper = new StageToFlowValueMapper(ratingCurve); - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - - - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - boolean shouldPaint = true; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - - - // observed data painter - for (int i = 0; i < obsTsList.size(); i++) - { - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - } - - - - // forecast data painters - for (int i = 0; i < fcstTsList.size(); i++) - { - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - } - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - - //------------------------------------------------------------------------------------ - public void initForDischarge(String locationId, List paramCodeList, TsPaintableCanvas canvas) - { - - String header = "RiverMonDrawingMgr.initForDischarge(): "; - - MeasuringUnit unit = MeasuringUnit.cfs; - - canvas.setDisplayedMeasuringUnit(unit); - - - Color outlineColor = Color.WHITE; - Color timeLineColor = Color.YELLOW; - - String leftAxisLabelString = "cfs"; - String rightAxisLabelString = null; //actually depends on rating curve existence - - //Set time - long currentTime = System.currentTimeMillis(); - TimeHolder currentTimeHolder = new TimeHolder(); - currentTimeHolder.setTime(currentTime); - - - // set title and measuring units - - - String titleString = "River Discharge for " + locationId; - //read in the observed time series - - - IrregularTimeSeries obsTs = null; - IrregularTimeSeries fcstTs = null; - - ParamCode obsParamCode = null; - ParamCode fcstParamCode = null; - - String obsParamCodeString = null; - String fcstParamCodeString = null; - - - for (int i = 0; i < paramCodeList.size(); i++) - { - ParamCode paramCode = (ParamCode) paramCodeList.get(i); - - if (paramCode.getTypeSource().charAt(0) == 'F') - { - - CodeTimer fcstStageTimer = new CodeTimer(); - fcstStageTimer.start(); - //read in the forecast time series - fcstTs = - _dataMgr.loadFcstDischargeTimeSeries(locationId, paramCode); - - fcstStageTimer.stop(header + "loadFcstDischargeTimeSeries took"); - - fcstParamCode = paramCode; - fcstParamCodeString = fcstParamCode.toString(); - } - else //observed - { - CodeTimer stageTimer = new CodeTimer(); - stageTimer.start(); - - obsTs = - _dataMgr.loadObservedDischargeTimeSeries(locationId, - paramCode, - getStartTime()); - stageTimer.stop(header + "loadObservedDischargeTimeSeries took "); - - - obsParamCode = paramCode; - obsParamCodeString = obsParamCode.toString(); - } - - - - - } - - //create the valueMapper - RatingCurve ratingCurve = _dataMgr.loadRatingCurve(locationId); - - - ValueMapper valueMapper = null; - - - if (ratingCurve.exists()) - { - valueMapper = new FlowToStageValueMapper(ratingCurve); - rightAxisLabelString = "feet"; - } - else - { - valueMapper = new UnitValueMapper(unit, unit); - rightAxisLabelString = "cfs"; - } - - //background painter - String[] textHeaderStringArray = - getTextHeaderStringArray(locationId, - obsTs, - obsParamCodeString, - fcstTs, - fcstParamCodeString, - unit.toString()); - - - TslBackgroundPainter backgroundPainter = - new TslBackgroundPainter(outlineColor, - leftAxisLabelString, - rightAxisLabelString); - - backgroundPainter.setRightLabelValueMapper(valueMapper); - backgroundPainter.setShowMinorTicks(true); - - - backgroundPainter.setTextHeaderStringArray(textHeaderStringArray); - backgroundPainter.setTitle(titleString); - - assignPainterToCanvas(backgroundPainter, canvas); - - - // time line painter - TslTimeLinePainter timeLinePainter = new TslTimeLinePainter(timeLineColor, - currentTimeHolder); - assignPainterToCanvas(timeLinePainter, canvas); - -/* - //significant value line painters for floodstage and actionstage - SigRiverLevels sigRiverLevels = _dataMgr.loadSigRiverLevels(locationId); - - - Color floodStageColor = Color.RED; - Color actionStageColor = Color.YELLOW; - - - if (sigRiverLevels != null) - { - - boolean shouldPaint = false; - - Measurement floodStageMeasurement = - new Measurement(sigRiverLevels.getFloodStage(), unit); - - SignificantLinePainter floodStagePainter = - new SignificantLinePainter(floodStageColor, - floodStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(floodStageMeasurement, unit); - - floodStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(floodStagePainter, canvas); - - - Measurement actionStageMeasurement = - new Measurement(sigRiverLevels.getActionStage(), unit); - - SignificantLinePainter actionStagePainter = - new SignificantLinePainter(actionStageColor, - actionStageMeasurement, - unit ); - - shouldPaint = isValueAvailable(actionStageMeasurement, unit); - - actionStagePainter.setShouldPaint(shouldPaint); - - assignPainterToCanvas(actionStagePainter, canvas); - } - */ - - - //observed data painter - Color obsColor = Color.YELLOW; - IrregularTimeSeriesHolder obsTsHolder = new IrregularTimeSeriesHolder(); - obsTsHolder.setTimeSeries(obsTs); - TsDataPointPainter obsTsPainter = new TsDataPointPainter(obsColor, obsTsHolder); - assignPainterToCanvas(obsTsPainter, canvas); - - // forecast data painters - Color fcstColor = Color.GREEN; - IrregularTimeSeriesHolder fcstTsHolder = new IrregularTimeSeriesHolder(); - fcstTsHolder.setTimeSeries(fcstTs); - TsDataPointPainter fcstTsPainter = new TsDataPointPainter(fcstColor, fcstTsHolder); - fcstTsPainter.setDrawLinesBetweenPoints(true); - assignPainterToCanvas(fcstTsPainter, canvas); - - - - addCanvasListeners(canvas, valueMapper); - - return; - } - - //------------------------------------------------------------------------------------ - - private void assignPainterToCanvas(TslCanvasPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addTsCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - private void assignPainterToCanvas(TslTimeLinePainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - private void assignPainterToCanvas(TslBackgroundPainter painter, TsPaintableCanvas canvas ) - { - painter.setCanvas(canvas); - canvas.addCanvasPainter(painter); - - return; - } - // -------------------------------------------------------------------------------------------------- - - private int getDurationInHours(int ihfsDurationCode) - { - int durationInHours = 0; - - if ( (ihfsDurationCode >= 1000) && (ihfsDurationCode < 2000) ) - { - durationInHours = ihfsDurationCode - 1000; - } - if (ihfsDurationCode == 2001) - { - durationInHours = 24; - } - - return durationInHours; - } - // ---------------------------------------------------------------------------------- - - private IrregularTimeSeries getIrregularTimeSeries(RegularTimeSeries origTs) - { - MeasuringUnit unit = origTs.getMeasuringUnit(); - IrregularTimeSeries irregularTimeSeries = new IrregularTimeSeries(unit); - - int count = origTs.getMeasurementCount(); - - AbsTimeMeasurement measurement = null; - - for (int i = 0; i < count; i++) - { - measurement = origTs.getAbsTimeMeasurementByIndex(i); - irregularTimeSeries.insertMeasurement(measurement); - } - - return irregularTimeSeries; - } - - - // ------------------------------------------------------------------------------------- - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode - ) - - { - MeasuringUnit unit = obsTs.getMeasuringUnit(); - String unitString = unit.getName(); - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCode, - String unitString - ) - - { - - String[] textHeaderStringArray = getTextHeaderStringArray(locationId, - obsTs, paramCode, null, null, - unitString); - - return textHeaderStringArray; - } - - // ------------------------------------------------------------------------------------- - - private String[] getTextHeaderStringArray(String locationId, - IrregularTimeSeries obsTs, - String paramCodeString, - IrregularTimeSeries fcstTs, - String fcstParamCodeString, - String unitString - ) - - { - AbsTimeMeasurement max = null; - AbsTimeMeasurement min = null; - AbsTimeMeasurement last = null; - - String[] textHeaderStringArray = null; - StringBuffer paramCodeStringBuffer = new StringBuffer(paramCodeString); - - Location location = _dataMgr.getLocationInfo(locationId); - if (location == null) - { - location = new Location(); - location.setLid(locationId); - location.setLocationName("Unknown location"); - location.setElevation(0); - - } - - - if (obsTs != null) - { - long startTime = getStartTime(); - long endTime = getEndTime(); - - max = obsTs.getMaxMeasurement(startTime, endTime); - min = obsTs.getMinMeasurement(startTime, endTime); - last = getLastMeasurement(obsTs, startTime, endTime); - } - - if (fcstParamCodeString != null) - { - paramCodeStringBuffer.append(" " + fcstParamCodeString); - } -// - - textHeaderStringArray = new String[5]; - textHeaderStringArray[0] = locationId + " - " + - location.getLocationName() + " - " + - "Elevation: " + location.getElevation() + " feet"; - - // textHeaderStringArray[1] = "Elevation: " + location.getElevation() + " feet"; - textHeaderStringArray[1] = paramCodeStringBuffer.toString(); - - - textHeaderStringArray[2] = "Max Obs = " + getMeasurementString(max, unitString); - textHeaderStringArray[3] = "Min Obs = " + getMeasurementString(min, unitString); - textHeaderStringArray[4] = "Last Obs = " + getMeasurementString(last, unitString); - - return textHeaderStringArray; - } - // -------------------------------------------------------------------------------------------------- - private AbsTimeMeasurement getLastMeasurement(IrregularTimeSeries timeSeries, - long startTime, - long endTime) - { - AbsTimeMeasurement measurement = null; - - int count = timeSeries.getMeasurementCount(); - - for (int i = count - 1; i >= 0; i--) - { - measurement = timeSeries.getAbsTimeMeasurementByIndex(i); - if (measurement != null) - { - long time = measurement.getTime(); - - if ((time <= endTime) && (time >= startTime)) - { - break; //quit, I found the measurement that I want. - } - } - } - - return measurement; - - } - // -------------------------------------------------------------------------------------------------- - - private String getMeasurementString(AbsTimeMeasurement measurement, String unitString) - { - String measurementString = null; - - if (measurement != null) - { - String timeString = - DbTimeHelper.getDateTimeStringFromLongTime(measurement.getTime()); - - //get rid of the seconds - timeString = timeString.substring(0, timeString.length()-3); - - double value = MathHelper.roundToNDecimalPlaces(measurement.getValue(), 2); - - measurementString = - value + " " + - unitString + - " at " + timeString + "Z"; - - } - else - { - measurementString = "Not Available"; - } - - return measurementString; - } - - // -------------------------------------------------------------------------------------------------- - private String wrapInHTML(String origString) - { - StringBuffer buffer = new StringBuffer("
    " + origString + "
    "); - - return buffer.toString(); - } -// ------------------------------------------------------------ - private String getVerticalText(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - buffer.append(charArray[i]); - - //don't do a break for the last one - if (i < charArray.length-1) - { - buffer.append("
    "); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } -// ------------------------------------------------------------ - private String getVerticalTextFromNewLines(String origText) - { - char[] charArray = origText.toCharArray(); - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - for (int i = 0; i < charArray.length; i++) - { - char c = charArray[i]; - if (c == '\n') - { - buffer.append("
    "); - } - else - { - buffer.append(c); - } - } - buffer.append(""); - - String verticalText = buffer.toString(); - - return verticalText; - } - // -------------------------------------------------------------------------------------------------- - - - /** - * @param startTime The startTime to set. - */ - public void setStartTime(long startTime) - { - _startTime = startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @return Returns the startTime. - */ - public long getStartTime() - { - return _startTime; - } - - // -------------------------------------------------------------------------------------------------- - - - /** - * @param endTime The endTime to set. - */ - public void setEndTime(long endTime) - { - _endTime = endTime; - } - /** - * @return Returns the endTime. - */ - public long getEndTime() - { - return _endTime; - } - - // -------------------------------------------------------------------------------------------------- - - -} diff --git a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/rivermon/RiverMonTslDataManager.java b/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/rivermon/RiverMonTslDataManager.java deleted file mode 100644 index 6b58cbade0..0000000000 --- a/javaUtilities/hydro/ohd.tsl/src/ohd/hseb/timeserieslite/rivermon/RiverMonTslDataManager.java +++ /dev/null @@ -1,904 +0,0 @@ -package ohd.hseb.timeserieslite.rivermon; - -import java.sql.SQLException; -import java.text.DecimalFormat; - -import java.util.List; - -import ohd.hseb.db.Database; -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.ihfsdb.generated.DischargeRecord; -import ohd.hseb.ihfsdb.generated.DischargeTable; -import ohd.hseb.ihfsdb.generated.FcstDischargeRecord; -import ohd.hseb.ihfsdb.generated.FcstDischargeTable; -import ohd.hseb.ihfsdb.generated.FcstHeightRecord; -import ohd.hseb.ihfsdb.generated.FcstHeightTable; -import ohd.hseb.ihfsdb.generated.HeightRecord; -import ohd.hseb.ihfsdb.generated.HeightTable; -import ohd.hseb.ihfsdb.generated.IngestFilterRecord; -import ohd.hseb.ihfsdb.generated.IngestFilterTable; -import ohd.hseb.ihfsdb.generated.LocPDCRecord; -import ohd.hseb.ihfsdb.generated.LocPDCView; -import ohd.hseb.ihfsdb.generated.LocationRecord; -import ohd.hseb.ihfsdb.generated.LocationTable; -import ohd.hseb.ihfsdb.generated.RatingRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftRecord; -import ohd.hseb.ihfsdb.generated.RatingShiftTable; -import ohd.hseb.ihfsdb.generated.RatingTable; -import ohd.hseb.ihfsdb.generated.RiverstatRecord; -import ohd.hseb.ihfsdb.generated.RiverstatTable; -import ohd.hseb.ihfsdb.generated.StnClassTable; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.RatingPoint; -import ohd.hseb.model.SigRiverLevels; -import ohd.hseb.pdc_pp.RegularObsTimeSeries; -import ohd.hseb.pdc_pp.TimeValuePair; -import ohd.hseb.timeserieslite.Location; -import ohd.hseb.timeserieslite.PDCDataType; -import ohd.hseb.timeserieslite.ParamCode; -import ohd.hseb.util.AppsDefaults; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.Logger; -import ohd.hseb.util.TimeHelper; - - -public class RiverMonTslDataManager -{ - - // -------------------------------------------------------------------------------------------- - - public static final double MISSING = -999.0; - - private static final int _defaultQualityCode = 1879048191; - private static final int _questionable_bad_threshold = 1073741824; - private static final long MILLIS_PER_HOUR = 60*60*1000; - private static final long MILLIS_PER_YEAR = (365L * 24L * 60L * 60L * 1000L); - - private Database _db = null; - private Logger _logger = null; - - private String _jdbcConnectionString = null; - private PDCDataType _dataType = null; - - private String _physicalElement = null; - - private String _preprocessedFilePath = null; - private double MAX_REASONABLE_PRECIP = 30; //inches per hour - - // --------------------------------------------------------------------------------- - - public RiverMonTslDataManager(String jdbcConnectionString) - { - _logger = new FileLogger(true); - - _jdbcConnectionString = jdbcConnectionString; - - _db = new Database(); - - _db.connect(_jdbcConnectionString); - - getAppsDefaults(); - } - // --------------------------------------------------------------------------------- - - private void getAppsDefaults() - { - AppsDefaults ad = new AppsDefaults(); - - _preprocessedFilePath = ad.getToken( "pdc_pp_dir" ) + "/"; - } - - // ------------------------------------------------------------------------------------- - - private void connect(String connectionString) - { - _db.connectWithDriverSearch(connectionString); - } - - // ------------------------------------------------------------------------------------- - - public void disconnect() - { - _db.disconnect(); - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSource(String lid, - String pe) - { - String header = "PdcTslDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + "'" + - " AND pe = '" + pe + "'" + - " AND dur = 0 " + - " AND ts like 'F%' " + - " order by ts_rank ASC" ; - - try - { - List recordList = table.select(whereClause); - - if (recordList.size() > 0) - { - if (pe.charAt(0)=='H') - { - for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - if (fcstHeightRecordExists(record)) - { - newTypeSource = record.getTs(); - break; - } - } - - } - else //pe is not 'H*', so don't look at fcstHeight to see if it exists - { - newTypeSource = record.getTs(); - } - - } - } - catch(SQLException e) - { - logSQLException(e); - } - - // System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // ---------------------------------------------------------------------------------- - public boolean fcstHeightRecordExists(IngestFilterRecord ingestRecord) - { - boolean result = false; - - String header = "PdcTslDataManager.fcstHeightRecordExists(): "; - - FcstHeightTable table = new FcstHeightTable(_db); - - String whereClause = "WHERE lid = '" + ingestRecord.getLid() + "'" + - " AND pe = '" + ingestRecord.getPe() + "'" + - " AND dur = " + ingestRecord.getDur() + - " AND ts = '" + ingestRecord.getTs() + "'"; - - - try - { - int recordCount = table.selectCount(whereClause); - - if (recordCount > 0) - { - result = true; - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return result; - } - // ---------------------------------------------------------------------------------- - /* public String getPreferredFcstTypeSourceByIngestFilter(String lid, - ParamCode paramCode) - { - String header = "PdcTslDataManager.getPreferredFcstTypeSourceByIngestFilter(): "; - - String newTypeSource = null; - - IngestFilterTable table = new IngestFilterTable(_db); - - IngestFilterRecord record = null; - - String whereClause = "WHERE lid = '" + lid + - "' AND pe = '" + paramCode.getPe() + "'" + - "AND dur = 0 " + - "AND ts like 'F%' " + - " order by ts_rank ASC" ; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - int i = 0; - //for (int i = 0; i < recordList.size(); i++) - { - record = (IngestFilterRecord) recordList.get(i); - newTypeSource = record.getTs(); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - - // ------------------------------------------------------------------------------------- - public String getPreferredFcstTypeSourceByFcstHeight(String lid, - ParamCode paramCode) - { - String header = "PdcTslDataManager.getPreferredFcstTypeSource(): "; - - String newTypeSource = null; - - FcstHeightTable table = new FcstHeightTable(_db); - - FcstHeightRecord record = null; - - String whereClause = "WHERE lid = '" + lid + - "' AND pe = '" + paramCode.getPe() + "'" + - "AND dur = 0 " + - " order by basistime DESC, validtime ASC" ; - - try - { - List recordList = table.selectNRecords(whereClause,1); - if (recordList.size() > 0) - { - int i = 0; - //for (int i = 0; i < recordList.size(); i++) - { - record = (FcstHeightRecord) recordList.get(i); - newTypeSource = record.getTs(); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - System.out.println(header + " newTypeSource = " + newTypeSource); - - return newTypeSource; - } - */ - // ------------------------------------------------------------------------------------- - - public SigRiverLevels loadSigRiverLevels(String locationId) - { - String header = "PdcTslDataManager.loadSigRiverLevels(): "; - RiverstatTable table = new RiverstatTable(_db); - RiverstatRecord record = null; - - SigRiverLevels levels = null; - - String whereClause = "WHERE lid = '" + locationId + "'"; - - try - { - List recordList = table.select(whereClause); - if (recordList.size() > 0) - { - record = (RiverstatRecord) recordList.get(0); - - String primaryPe = record.getPrimary_pe(); - - - double floodStage = record.getFs(); - double actionStage = record.getWstg(); - double floodFlow = record.getFq(); - double actionFlow = record.getAction_flow(); - - - if (DbTable.isNull(actionStage)) - { - System.out.println(header + " actionStage is null for " + locationId); - } - if (DbTable.isNull(record.getPrimary_pe())) - { - System.out.println(header + " primary_pe is null for " + locationId); - record.setPrimary_pe(" "); - } - - - - levels = new SigRiverLevels(locationId, - record.getPrimary_pe(), - floodStage, - actionStage, - floodFlow, - actionFlow); - - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return levels; - } - - // -------------------------------------------------------------------------------------------------- - - public RatingCurve loadRatingCurve(String locationId) - { - RatingCurve ratingCurve = null; - - RatingTable ratingTable = new RatingTable(_db); - RatingShiftTable ratingShiftTable = new RatingShiftTable(_db); - - RiverstatTable riverstatTable = new RiverstatTable(_db); - - List ratingRecordList = null; - List ratingShiftList = null; - List riverstatList = null; - - - try - { - ratingRecordList = ratingTable.select("WHERE LID = '" + - locationId + "' ORDER by stage"); - - ratingShiftList = ratingShiftTable.selectNRecords("WHERE LID = '" + - locationId + "' AND active = 'T' ORDER BY date desc", 1 ); - - - riverstatList = riverstatTable.select("WHERE LID = '" + locationId + "'"); - - //determine total amount of active - //rating shifts - double totalShiftAmount = 0.0; - - for (int i = 0; i < ratingShiftList.size(); i++) - { - RatingShiftRecord shiftRecord = (RatingShiftRecord) ratingShiftList.get(i); - totalShiftAmount = shiftRecord.getShift_amount(); - - //System.out.println("totalShiftAmount = " + totalShiftAmount); - } - - - //initialize the RatingCurve object with data from the database, including - // the totalShiftAmount - ratingCurve = new RatingCurve(locationId); - - - ratingCurve.setShiftAmount(totalShiftAmount); - - for (int i = 0; i < ratingRecordList.size(); i++) - { - RatingRecord record = (RatingRecord) ratingRecordList.get(i); - - RatingPoint ratingPoint = new RatingPoint(); - ratingPoint.setDischarge(record.getDischarge()); - ratingPoint.setUnshiftedStage(record.getStage()); - - //done by addRatingPoint - //ratingCurve.setShiftAmount(totalShiftAmount); - - ratingCurve.addRatingPoint(ratingPoint); - } //end for - - - // set the USGS fields in the rating curve - if (riverstatList.size() > 0) - { - RiverstatRecord riverstatRecord = (RiverstatRecord) riverstatList.get(0); - ratingCurve.setUsgsRatingNumber(riverstatRecord.getUsgs_ratenum()); - ratingCurve.setRatingDate(riverstatRecord.getRatedat()); - } - - } - catch (SQLException e) - { - logSQLException(e); - ratingCurve = null; - } - - return ratingCurve; - } - - -// ------------------------------------------------------------------------------------- - - public RegularTimeSeries getRegularTimeSeries(RegularObsTimeSeries obsTimeSeries) - { - - long startTime = obsTimeSeries.getDescriptor().getStartTime(); - long endTime = obsTimeSeries.getDescriptor().getEndTime(); - long timeStepIntervalInMillis = obsTimeSeries.getTimeStepIntervalInMillis(); - long timeStepIntervalInHours = timeStepIntervalInMillis / MILLIS_PER_HOUR; - MeasuringUnit unit = MeasuringUnit.inches; - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - RegularTimeSeries regularTimeSeries = - new RegularTimeSeries(startTime, endTime, (int) timeStepIntervalInHours , unit); - - List timeValuePairList = obsTimeSeries.getTimeValuePairList(true); - - for (int i = 0; i < timeValuePairList.size(); i++) - { - TimeValuePair pair = (TimeValuePair) timeValuePairList.get(i); - long time = pair.getDateTime(); - double value = pair.getValue(); - - Measurement measurement = new Measurement(value, unit); - - regularTimeSeries.setMeasurementByTime(measurement, time); - } - - regularTimeSeries.shiftStartEndTimeHours(12); - - return regularTimeSeries; - } - -// ------------------------------------------------------------------------------------- - - private void logSQLException(SQLException exception) - { - _logger.log("SQL ERROR = " + - exception.getErrorCode() + " " + - exception.getMessage()); - - exception.printStackTrace(_logger.getPrintWriter()); - - _logger.log("End of stack trace"); - - } -// ------------------------------------------------------- - public String getLocationName(String locationId) - { - return loadLocationName(locationId); - } -// ------------------------------------------------------- - private String loadLocationName(String locationId) - { - - String locationName = null; - - LocationRecord record = null; - LocationTable table = new LocationTable(_db); - - - try - { - String whereClause = "WHERE lid = '" + locationId + "'"; - List recordList = table.select(whereClause); - - - if (recordList.size() > 0) - { - record = (LocationRecord) recordList.get(0); - locationName = record.getName(); - } - } - catch (SQLException e) - { - logSQLException(e); - } - - return locationName; - - } - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedStageTimeSeries(String locationId, - ParamCode paramCode, - long startTime) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadObservedStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - HeightTable table = new HeightTable(_db); - HeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - -// ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (HeightRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - public IrregularTimeSeries loadObservedDischargeTimeSeries(String locationId, - ParamCode paramCode, - long startTime) - { - MeasuringUnit unit = MeasuringUnit.cfs; - String header = "PdcTslDataManager.loadObservedDischargeTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - DischargeTable table = new DischargeTable(_db); - DischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - -// ParamCode paramCode = new ParamCode(paramCodeString); - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + ""; - // " AND obstime >= '" + startTimeString + "'"; - - - System.out.println(header + "whereClause = " + whereClause); - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - record = (DischargeRecord) recordList.get(i); - - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getObstime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - - } - - // ------------------------------------------------------------------------ - - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstStageTimeSeries(String locationId, - ParamCode paramCode) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstStageTimeSeries(): "; - IrregularTimeSeries stageTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstHeightTable table = new FcstHeightTable(_db); - FcstHeightRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + - " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - - long originalBasisTime = 0; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - - - record = (FcstHeightRecord) recordList.get(i); - - if (i == 0) - { - originalBasisTime = record.getBasistime(); - } - else - { - if (record.getBasistime() != originalBasisTime) - { - break; - } - } - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), - unit); - - stageTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + measurement); - - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return stageTimeSeries; - } - -// ----------------------------------------------------------------------------------- - - public IrregularTimeSeries loadFcstDischargeTimeSeries(String locationId, - ParamCode paramCode) - { - MeasuringUnit unit = MeasuringUnit.feet; - String header = "PdcTslDataManager.loadFcstDischargeTimeSeries(): "; - IrregularTimeSeries dischargeTimeSeries = new IrregularTimeSeries(unit); - - final double missingValue = -9999.0; - FcstDischargeTable table = new FcstDischargeTable(_db); - FcstDischargeRecord record = null; - List recordList = null; - AbsTimeMeasurement measurement = null; - - final long maxLong = Long.MAX_VALUE; - - - String whereClause = " WHERE lid = '" + locationId + "'" + - " AND pe = '" + paramCode.getPe() + "'" + - " AND ts = '" + paramCode.getTypeSource() + "'" + - " AND dur = " + paramCode.getIhfsDur() + - " AND extremum = '" + paramCode.getExtremum() + "'" + - " AND quality_code >= " + _questionable_bad_threshold + - " ORDER BY basistime DESC "; - // " AND obstime >= '" + startTimeString + "'"; - - - long originalBasisTime = 0; - - try - { - recordList = table.select(whereClause); - - for (int i = 0; i < recordList.size(); i++) - { - - - record = (FcstDischargeRecord) recordList.get(i); - - if (i == 0) - { - originalBasisTime = record.getBasistime(); - } - else - { - if (record.getBasistime() != originalBasisTime) - { - break; - } - } - - //don't let the missing values be included - if (record.getValue() != missingValue) - { - measurement = new AbsTimeMeasurement(record.getValue(), - record.getValidtime(), - unit); - - dischargeTimeSeries.insertMeasurement(measurement); - - // System.out.println(header + "measurement = " + measurement); - - } - } - } - catch(SQLException e) - { - logSQLException(e); - } - - return dischargeTimeSeries; - } - -// ----------------------------------------------------------------------------------- - - - public Location getLocationInfo(String locationId) - { - DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); - - Location location = null; - String whereClause = " WHERE lid = '" + locationId + "'"; - - LocPDCView locPDCView = new LocPDCView( _db ); - RiverstatTable riverStatTable = new RiverstatTable( _db ); - StnClassTable stationClassTable = new StnClassTable(_db); - - - List locPDCViewList = null; - List riverStatRecordList = null; - List stationClassList = null; - - - try - { - locPDCViewList = locPDCView.select( whereClause ); - riverStatRecordList = riverStatTable.select( whereClause ); - - stationClassList = stationClassTable.select( whereClause ); - - } - catch( SQLException e ) - { - logSQLException(e); - e.printStackTrace(); - } - - - - for ( int i = 0; i < locPDCViewList.size(); i++ ) - { - LocPDCRecord locPDCRecord = (LocPDCRecord) locPDCViewList.get( i ); - location = new Location(); - location.setLid( locPDCRecord.getLid().trim() ); - location.setHsa( locPDCRecord.getHsa().trim() ); - - - location.setLat( Double.parseDouble( decimalFormat.format( locPDCRecord.getLat() ) ) ); - location.setLon( Double.parseDouble( decimalFormat.format( locPDCRecord.getLon() ) ) ); - - - location.setElevation( locPDCRecord.getElev() ); - location.setLocationName( locPDCRecord.getName() ); - location.setRiverStation( false ); - - double fq = locPDCRecord.getFq(); - double fs = locPDCRecord.getFs(); - - if ( fq == 0 ) // missing value - { - location.setFloodFlow( MISSING ); - } - else - { - location.setFloodFlow( fq ); - } - - if ( fs == 0 ) // missing value - { - location.setFloodStage( MISSING ); - } - else - { - location.setFloodStage( fs ); - } - - if ( ( fq == 0.0 ) && ( fs != 0.0 ) && (location.getRatingCurve() != null ) ) - { - location.setFloodFlow( location.getRatingCurve().getDischargeFromStage( fs ) ); - } - - String dispClass = locPDCRecord.getDisp_class(); - - if ( ( dispClass.indexOf( "F" ) ) != -1 ) - { - location.setFcstPoint( true ); - } - else - { - location.setFcstPoint( false ); - } - - String dcp = locPDCRecord.getIs_dcp(); - - if ( ( dcp.indexOf( "T" ) ) != -1 ) - { - location.setDCP( true ); - } - else - { - location.setDCP( false ); - } - - String observer = locPDCRecord.getIs_observer(); - - if ( ( observer.indexOf( "T" ) ) != -1 ) - { - location.setObserver( true ); - } - else - { - location.setObserver( false ); - } - - location.setTelemType( locPDCRecord.getTelem_type() ); - - - } - - - - return location; - } -// ------------------------------------------------------------------------ - private String getPrecipFileName(int durationInHours) - { - String precipFileName = _preprocessedFilePath + - "/Precip" + durationInHours +"Hour.dat"; - return precipFileName; - } -// ------------------------------------------------------------------------ - - public long getLatestHourTime() - { - return TimeHelper.truncateTimeInMillisToNearestHour(System.currentTimeMillis(), 1); - } -// ----------------------------------------------------------------------------------- - -} //end PdcTslDataManager diff --git a/javaUtilities/hydro/ohd.var/.classpath b/javaUtilities/hydro/ohd.var/.classpath deleted file mode 100644 index 2881a9be7f..0000000000 --- a/javaUtilities/hydro/ohd.var/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/javaUtilities/hydro/ohd.var/.project b/javaUtilities/hydro/ohd.var/.project deleted file mode 100644 index 703d2f49d4..0000000000 --- a/javaUtilities/hydro/ohd.var/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - ohd.var - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/javaUtilities/hydro/ohd.var/.settings/org.eclipse.jdt.core.prefs b/javaUtilities/hydro/ohd.var/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index d3923b511c..0000000000 --- a/javaUtilities/hydro/ohd.var/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue May 24 10:44:31 CDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/javaUtilities/hydro/ohd.var/META-INF/MANIFEST.MF b/javaUtilities/hydro/ohd.var/META-INF/MANIFEST.MF deleted file mode 100644 index 72f0ef801a..0000000000 --- a/javaUtilities/hydro/ohd.var/META-INF/MANIFEST.MF +++ /dev/null @@ -1,11 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Var -Bundle-SymbolicName: ohd.var -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: ohd.common;bundle-version="1.0.0", - ohd.db;bundle-version="1.0.0", - ohd.sshp;bundle-version="1.0.0", - ohd.lib;bundle-version="1.0.0" -Export-Package: ohd.hseb.sshp.var diff --git a/javaUtilities/hydro/ohd.var/build.properties b/javaUtilities/hydro/ohd.var/build.properties deleted file mode 100644 index 34d2e4d2da..0000000000 --- a/javaUtilities/hydro/ohd.var/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/javaUtilities/hydro/ohd.var/build.xml b/javaUtilities/hydro/ohd.var/build.xml deleted file mode 100644 index b01f580d9b..0000000000 --- a/javaUtilities/hydro/ohd.var/build.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/javaUtilities/hydro/ohd.var/ohd.var.ecl b/javaUtilities/hydro/ohd.var/ohd.var.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/javaUtilities/hydro/ohd.var/scripts/readme.txt b/javaUtilities/hydro/ohd.var/scripts/readme.txt deleted file mode 100644 index a7cc356702..0000000000 --- a/javaUtilities/hydro/ohd.var/scripts/readme.txt +++ /dev/null @@ -1,2 +0,0 @@ -These scripts will not work in this folder. During build, they will be copied to /fs/hseb/pda/users/lix/devl/scripts. -There, they can be evoked and run. diff --git a/javaUtilities/hydro/ohd.var/scripts/run_SSHP_Databasepopulater b/javaUtilities/hydro/ohd.var/scripts/run_SSHP_Databasepopulater deleted file mode 100644 index ca04df3ec5..0000000000 --- a/javaUtilities/hydro/ohd.var/scripts/run_SSHP_Databasepopulater +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/ksh -# file name: run_SSHP_Databasepopulater -# Created: 12/15/2003 - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set initial lid to the first command line argument passed into the script -LID_PASSED_IN=$1 - -export CLASSPATH=. -CLASSPATH=$CLASSPATH:$DB_DRIVER_PATH -# need to add a path to the jar file for this application -CLASSPATH=$CLASSPATH:/fs/hseb/pda/users/lix/devl/bin/Var.jar - -# Java bin directory(/usr/local/java/bin) -JBINDIR=$SYS_JAVA_DIR/bin - -export LID=BLUO2 -export VAR_LOG_DIR=/fs/shared/home/lix/eclipse_workspace/Var - -# run Databasepopulater -$JBINDIR/java ohd.hseb.sshp.var.DatabasePopulater $LID $VAR_LOG_DIR - - diff --git a/javaUtilities/hydro/ohd.var/scripts/run_SSHP_var b/javaUtilities/hydro/ohd.var/scripts/run_SSHP_var deleted file mode 100644 index eb1c5de09d..0000000000 --- a/javaUtilities/hydro/ohd.var/scripts/run_SSHP_var +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/ksh - -# File name: run_var_controller -# Author : Varalakshmi Rajaram - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -# set java classpath -export CLASSPATH=$DB_DRIVER_PATH:$WHFS_BIN_DIR/sshp_var.jar:$CLASSPATH - -DATA_DIR=$WHFS_LOCAL_DATA_DIR - -if [[ $# -lt 1 ]] -then -CUR_TIME=CURRENT_TIME -else -CUR_TIME=$1 -fi - -#set the various directory and log file names -VARCONTROLLER_LOG_DIR=$DATA_DIR/log/var -VARCONTROLLER_LOG=VarAssimilationController.log -VAR_INPUT_DIR=$DATA_DIR/var/input/ -VAR_OUTPUT_DIR=$DATA_DIR/var/output -#VAR_LOG is the hard-coded name for the output for the FORTRAN code -VAR_LOG=$VAR_OUTPUT_DIR/log_var -VAR_PARAM_DIR=$VAR_INPUT_DIR/param/ -VAR_SEGMENTS_FILE=list_of_segments -VAR_RUNSCRIPT=$WHFS_BIN_DIR/run_var_assimilator -VAR_STDOUT_LOG=$VARCONTROLLER_LOG_DIR/VAR_stdout_stderr.log - -#set a particular log file as the main log file to be trimmed. -#all the rest get deleted and cleaned up in other ways -LOGFILE=$VARCONTROLLER_LOG_DIR/$VARCONTROLLER_LOG - -# ensure that only 1 instance of this script runs on a machine -AMIRUNNING_DIR=$VARCONTROLLER_LOG_DIR -. /awips/hydroapps/public/bin/amirunning - -if [[ $AmIRunning = "yes" ]] -then - messageDate=`date -u '+%Y/%m/%d %k:%M:%S.XXX'` - echo $messageDate: Startup cancelled because of prior running instance >> $LOGFILE - exit 1 -fi - - -# trim the regular log file -TEMP_TRIM_FILE=$LOGFILE.trimmed -tail -50000 $LOGFILE > $TEMP_TRIM_FILE -mv $TEMP_TRIM_FILE $LOGFILE - -#trim the stdout/stderr log file -TEMP_TRIM_FILE=$VAR_STDOUT_LOG.trimmed -tail -50000 $VAR_STDOUT_LOG > $TEMP_TRIM_FILE -mv $TEMP_TRIM_FILE $VAR_STDOUT_LOG - -# we don't need this to be kept -rm -f $VARCONTROLLER_LOG_DIR/stdout_fortran_var.log - - -#Execute the Var Controller -$SYS_JAVA_DIR/bin/java ohd.hseb.sshp.var.VarController $JDBCURL "$CUR_TIME" $VARCONTROLLER_LOG_DIR $VARCONTROLLER_LOG $VAR_INPUT_DIR $VAR_OUTPUT_DIR $VAR_RUNSCRIPT $VAR_SEGMENTS_FILE $VAR_LOG >> $VAR_STDOUT_LOG 2>&1 -#$SYS_JAVA_DIR/bin/java ohd.hseb.sshp.var.VarController $JDBCURL "$CUR_TIME" $VARCONTROLLER_LOG_DIR $VARCONTROLLER_LOG $VAR_INPUT_DIR $VAR_OUTPUT_DIR $VAR_RUNSCRIPT $VAR_SEGMENTS_FILE $VAR_LOG -exit diff --git a/javaUtilities/hydro/ohd.var/scripts/run_var_assimilator b/javaUtilities/hydro/ohd.var/scripts/run_var_assimilator deleted file mode 100644 index 94d0938a83..0000000000 --- a/javaUtilities/hydro/ohd.var/scripts/run_var_assimilator +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/ksh - -# File name: run_var_assimilator -# Author : Varalakshmi Rajaram - -# This allows you to run this script from outside of ./bin -RUN_FROM_DIR=`dirname $0` - -# set up SOME environment variables for WHFS applications -. $RUN_FROM_DIR/../../set_hydro_env - -export var_dir=$WHFS_LOCAL_DATA_DIR/var -VAR_OUTPUT_DIR=$var_dir/output -#VAR_LOG is the hard-coded name for the output for the FORTRAN code -VAR_LOG=$VAR_OUTPUT_DIR/log_var - -rm -f $VAR_LOG - -fortran_var_log_dir=$WHFS_LOCAL_DATA_DIR/log/var/ -fortran_var_log=$fortran_var_log_dir/stdout_fortran_var.log - -#Execute the Fortran var program -$WHFS_BIN_DIR/var_assimilator.LX > $fortran_var_log 2>&1 -echo "Completed Var-- in script" >> $fortran_var_log diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/DataAbsentException.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/DataAbsentException.java deleted file mode 100644 index ca5e44aada..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/DataAbsentException.java +++ /dev/null @@ -1,14 +0,0 @@ -package ohd.hseb.sshp.var; - -public class DataAbsentException extends Exception -{ - - public DataAbsentException(String message) - { - super(message); - } - public DataAbsentException() - { - - } -} diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/FortranScriptRunningException.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/FortranScriptRunningException.java deleted file mode 100644 index e7f23aa6d7..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/FortranScriptRunningException.java +++ /dev/null @@ -1,15 +0,0 @@ -package ohd.hseb.sshp.var; - -/******************************************************************************************************************* - * This class is used when FortranScriptExecuter running the Fortran script var needs to throw an Exception. It has - * a field containing the log_var file name with absolute path and a field containing the error message. - * @author lix - * - */ -public class FortranScriptRunningException extends Exception -{ - public FortranScriptRunningException(String message) - { - super(message); - } -} //close class diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/InputFilesGenerator.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/InputFilesGenerator.java deleted file mode 100644 index 1871ae6357..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/InputFilesGenerator.java +++ /dev/null @@ -1,458 +0,0 @@ -package ohd.hseb.sshp.var; - -import java.io.*; -import java.util.List; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.UnitHydrograph; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.FileLogger; - -import static ohd.hseb.util.TimeHelper.*; - -/******************************************************************************************************** - * This class generates the var deck file, used as one of the input files for Var FORTRAN program. With - * Fortran program, this file is only needed if the two output files, "basinId_states_02_var" and - * "basinId_adj_states_02_var", doesn't exist -- the very first time of running Var. However, the Java - * program deletes the two output files in the end of each running. So this file is absolutely required - * every time when Var is executed. - * This file extracts SacSma state variables and SacSma parameters information from database. peadj and pxadj - * are extracted from a text file previously saved. UHG information is extracted from database. - * @author lix - * - */ -public class InputFilesGenerator -{ - private FileLogger _varControllerLogger = null; - private final String _stdDeckLinesFile; - private long _assimilationStartTimeLong = 0; - private long _assimilationTargetTimeLong = 0; - private int _futureHourCount = 0; - private String _basinId = null; - private String _varInputDir = null; - private String _varOutputDir = null; - private String _segmentsFilePath = null; - - public InputFilesGenerator(FileLogger logger, String varInputDir, String varOutputDir, - String segmentsFilePath, String basinId, int futureHourCount) - { - _varControllerLogger = logger; - _varInputDir = varInputDir; - _varOutputDir = varOutputDir; - _segmentsFilePath = segmentsFilePath; - - _basinId = basinId; - _futureHourCount = futureHourCount; - - _stdDeckLinesFile = _varInputDir + "/param/deck_file_top_two_lines.txt"; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public void setVarModelStartAndEndTimesLong(long assimilationStartTimeLong, long assimilationTargetTimeLong) - { - _assimilationStartTimeLong = assimilationStartTimeLong; - _assimilationTargetTimeLong = assimilationTargetTimeLong; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - /**************************************************************************************************** - * Generates the deck parameter file. - * - */ - public boolean generateDeckFile(String locationName, SacSmaState sacSmaState, - SacSmaParameters sacSmaParams, MonthlyValues monthlyValues, - Double basinArea, UnitHydrograph uhg) - { - PrintWriter writer = null; - boolean isDeckFileCreationSuccessful = false; - - _varControllerLogger.log("Generating the Var parameter deck file for " + _basinId); - try - { - String deckFilePath = _varInputDir + "/param/" + _basinId + ".var_deck"; - writer = new PrintWriter(new FileOutputStream(deckFilePath), true); - printDeckFileTopTwoLines(writer); - } - catch(Exception e) - { - _varControllerLogger.log(e.getMessage()); - return isDeckFileCreationSuccessful; - } - - if(printSacSmaCards(writer, locationName, sacSmaState, sacSmaParams, monthlyValues)) - { - if(printUnitHGCards(writer, uhg, locationName, basinArea)) - { - _varControllerLogger.log("The input parameter deck file " + _basinId + ".var_deck has been generated by Java program."); - isDeckFileCreationSuccessful = true; - } - } - writer.close(); - return isDeckFileCreationSuccessful; - - } -// ---------------------------------------------------------------------------------------------------------------------------------- - /****************************************************************************************** - * The top two lines of the original deck file generated by Var FORTRAN program contains - * hard-coded information. They are identical for all the deck files. The first line contains - * 10 values which will be used in the execution of Var FORTRAN program. The second line - * contains 6 infinity large values. This method printDeckFileTopTwoLines() reads from a file - * containing the two lines and print them out. - * @param - */ - private void printDeckFileTopTwoLines(PrintWriter writer) throws IOException - { - String header = "DeckFileGenerator.printDeckFileTopTwoLines():"; - _varControllerLogger.log("In "+header); - try - { - File file = new File(_stdDeckLinesFile); - if ( ! file.exists()) - { - createDeckFileTopTwoLines(file); - } - BufferedReader inputStream = new BufferedReader(new FileReader(file)); - writer.println(inputStream.readLine()); //first line - writer.println(inputStream.readLine()); //second line - inputStream.close(); - } - catch(IOException e) - { - throw new IOException(); - } - return; - } - - /** - * - * @param file - the file to create - * This routine creates a parameter file for var. - * It is called only when the parameter file does not exist already. - * This routine will make installation simpler and recovery from - * accidental deletion of the file easy. - * Once the file exists, the file can be edited, if desired. - */ - private void createDeckFileTopTwoLines(File file) - { - String header = "InputFilesGenerator.createDeckFileTopTwoLines(): "; - PrintWriter writer = null; - - try - { - writer = new PrintWriter(new FileWriter(file)); - writer.println("0.01 2. 0.5 1.0000 0.001 1 -10. 10. 15. 0.05"); - writer.println(" 0.1E+22 0.1E+22 0.1E+22 0.1E+22 0.1E+22 0.1E+22"); - _varControllerLogger.log(header + " success"); - } - catch (IOException e) - { - _varControllerLogger.log(header + " Failed to create deck file top two lines file"); - } - finally - { - writer.close(); - } - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - /***************************************************************************************** - * Based on SACRAMENTO SOIL MOISTURE ACCOUNTING OPERATION, print out cards from 1 to 6 for - * the basin. All the information are extracted from Database - * - */ - private boolean printSacSmaCards(PrintWriter writer, String locationName, SacSmaState sacSmaState, - SacSmaParameters sacSmaParams, MonthlyValues monthlyValues) //from Card 1 to 6 - { - String header = "DeckFileGenerator.printSacSmaCards():"; - _varControllerLogger.log("In "+ header); - boolean isPrintingSacSmaCardsSucceeded = false; - //Card #1 - writer.printf("%1$-20s" + space(8) +"%2$2d %3$-8s %4$-4s" +space(7) +"%5$-8s %6$-4s\n", - locationName, - 1, _basinId, "MAPX", _basinId, "INFW"); - - //Card #2 - writer.printf(space(18) + "%1$2d" + " %2$-8s" + " %3$-8s" + " %4$-4s" + space(5) + " %5$2d" + " %6$2d \n", - 0, _basinId, _basinId, "SUMS", 24, 24); - //%4: data time interval of the runoff components time series (default is 24) - //%5: data time interval of the soil moisture storage time series (defult is 24) - - //Card #3 - //sacSmaParams for both card #3 and #4 - writer.printf(space(20) + "%1$5.3f%2$5.3f%3$5.1f%4$5.1f%5$5.3f%6$5.3f%7$5.3f%8$5.3f%9$5d%10$5.3f\n", - sacSmaParams.getPxadj(), - sacSmaParams.getPeadj(), - sacSmaParams.getUztwm(), - sacSmaParams.getUzfwm(), - sacSmaParams.getUzk(), - sacSmaParams.getPctim(), - sacSmaParams.getAdimp(), - sacSmaParams.getRiva(), - 0, //I5 diurnal ET variation option (default is uniform distribution of daily ET-demand); enter value greater than zero to use diurnal variation. - sacSmaParams.getEfc()); - - //Card #4 - writer.printf(space(20) + "%1$5.1f%2$5.2f%3$5.1f%4$5.1f%5$5.1f%6$5.3f%7$5.3f%8$5.3f%9$5.3f%10$5.3f\n", - sacSmaParams.getZperc(), - sacSmaParams.getRexp(), - sacSmaParams.getLztwm(), - sacSmaParams.getLzfsm(), - sacSmaParams.getLzfpm(), - sacSmaParams.getLzsk(), - sacSmaParams.getLzpk(), - sacSmaParams.getPfree(), - sacSmaParams.getRserv(), - sacSmaParams.getSide()); - - //Card #5: 12 values for ET-demand or PE-adjustment factor, locations are: 21-24,25-28,29-32,33-36,37-40,41-44,45-48,49-52,53-56,57-60,61-64,65-68 - - double[] recentMonthValuesArray = monthlyValues.getValueArray(); - writer.printf(space(20)); - for (int i = 0; i <= 11; i++) - { - writer.printf("%4.2f", recentMonthValuesArray[i]); - } - writer.printf("\n"); - - //Card #6 - writer.printf(space(20) + "%1$5.1f%2$5.1f%3$5.1f%4$5.1f%5$5.1f%6$5.1f %7$1d\n", - sacSmaState.getUztwc(), - sacSmaState.getUzfwc(), - sacSmaState.getLztwc(), - sacSmaState.getLzfsc(), - sacSmaState.getLzfpc(), - sacSmaState.getAdimc(), - 1); - isPrintingSacSmaCardsSucceeded = true; - return isPrintingSacSmaCardsSucceeded; - } //close method -// ---------------------------------------------------------------------------------------------------------------------------------- - - /***************************************************************************************** - * Based on the UNIT HYDROGRAPH OPERATION, print out Card #1, #3, #4. The Unit Hydrograph - * information of basin_id is extracted from Database. It is SAC-SMA model. - */ - private boolean printUnitHGCards(PrintWriter writer, UnitHydrograph unitHG, String locationName, Double basinArea) - { - boolean didPrintingUnitHGCardsSucceed = false; - - String header = "DeckFileGenerator.printUnitHGCards():"; - _varControllerLogger.log("In "+header); - - List measurementList = unitHG.getMeasurementList(); - - //Card# 1 - writer.printf("%1$-20s %2$10.1f %3$3d %4$8s %5$-4s%6$10.3f\n", - locationName, - basinArea, - measurementList.size(), - "CARRY", - "ENGL", - 0.0); //constant baseflow to be added to computed instantaneous discharges(0.0 = currently no constant baseflow) - - //Card# 3 -- #2 is skipped because no '1' is entered at postion 69 in Card #1 - writer.printf(" %1$-8s %2$-4s %3$2d %4$-8s %5$-4s %6$2d\n", - _basinId, - "INFW", - 1, //data time interval of runoff time series(HR) (computational time interval of the Operation) - _basinId, - "SQIN", - 1); //data time interval of discharge time series(HR) (spacing of the unit hydrograph ordinates) - - //Card #4 -- Unit hydrograph ordinates: each row has 7 columns, locations: 4-10,14-20,24-30,...,54-60,64-70 - int totalNumberOfColumns = 7;// totally 7 columns in one row - - didPrintingUnitHGCardsSucceed = printUHGOrdinates(writer, totalNumberOfColumns, measurementList); - return didPrintingUnitHGCardsSucceed ; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - private boolean printUHGOrdinates(PrintWriter writer, int totalNumberOfColumns, List measurementList) - { - boolean didPrintingUnitHGCardsSucceed = false; - - //Card #4 -- Unit hydrograph ordinates: each row has 7 columns, locations: 4-10,14-20,24-30,...,54-60,64-70 - int totalNumberOfRows = (measurementList.size()) / (totalNumberOfColumns); - boolean isIndexValid = true; - - for (int row = 0; row <= totalNumberOfRows; row++) //counting the rows, starting from 0 - { - for (int column = 0; column < totalNumberOfColumns; column++) //counting the columns, from 0 to 6 - { - int index = row * totalNumberOfColumns + column; // index to use in the measurement list - if (index > (measurementList.size()-1)) //for the last row, check to make sure index not out of range - { - isIndexValid = false; - writer.printf("\n"); //finish last row - break; - } - writer.printf("%10.2f", ((Measurement)(measurementList.get(index))).getValue()); - } //end of inner loop (for columns) - - if( ! isIndexValid ) - { - break; - } - writer.printf("\n"); //move to next row - } //outer loop (for rows) - didPrintingUnitHGCardsSucceed = true; - return didPrintingUnitHGCardsSucceed; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - /***************************************************************************************** - * A helper method for formatting. - * @param num - * @return - */ - private String space(int num) - { - StringBuffer bf = new StringBuffer(72); - for (int i = 1; i <= num; i++) - { - bf.append(' '); - } - return bf.toString(); - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - /********************************************************************************************************************* - * generate precip & discharge files like BLUO2.mapx_ts_var_dat or BLUO2.qin01_ts_var_dat - * - */ - - public boolean generateObsInputFiles(RegularTimeSeries precipRTS, RegularTimeSeries dischargeRTS) - { - boolean isObsInputFileCreationSuccessful = false; - String header = "ObsInputFileGenerator.generateObsInputFiles():"; - _varControllerLogger.log("In "+ header); - - String precipFile = _varOutputDir +"/"+_basinId + ".mapx_ts_var_dat"; - String dischargeFile = _varOutputDir + "/"+_basinId + ".qin01_ts_var_dat"; - - //generate precipitation file "basinId.mapx_ts_var_dat" file - if(generateFile(precipFile, precipRTS)) - { - //generate discharge file "basinId.qin01_ts_var_dat" file - if(generateFile(dischargeFile, dischargeRTS)) - { - isObsInputFileCreationSuccessful = true; - } - else - { - _varControllerLogger.log("Failed In Creating :"+ dischargeFile ); - } - } - else - { - _varControllerLogger.log("Failed In Creating :"+ precipFile ); - } - return isObsInputFileCreationSuccessful; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - private int getPastHourlyValueCount() - { - long elapsedTimeInMillis = _assimilationTargetTimeLong - _assimilationStartTimeLong ; - int elapsedTimeInHours = (int)(elapsedTimeInMillis / MILLIS_PER_HOUR) + 1; - return elapsedTimeInHours ; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - // Count of the past & forecast values that is written in the file - private int getTotalHourlyValueCount() - { - return getPastHourlyValueCount() + _futureHourCount; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - /*************************************************************************************************************************** - * Generate input files, like BLUO2.mapx_ts_var_dat or BLUO2.qin01_ts_var_dat. For precipiation, unit: cms; inflow, unit: mm. - * First line is always: - * " Z 240 360" -- means UTC time zone, backward data assimilation 240 hours(24 days), total data hours are 360 hours - * (forecasting 120 hours -- 5 days). - * From 2nd line to the end of file: - * year month day hour obs(precip with unit of mm, converted from database inch value; - * discharge with unit of cms, converted from database cfs value.) - * The time period specified in the two files determines the time period Fortran Var script will compute. - * In the forecasting period, the discharge is set to -1, the precip is set to 0. - */ - private boolean generateFile(String fileName, RegularTimeSeries rts) - { - boolean isObsInputFileCreationSuccessful = false; - - String header = "ObsInputFileGenerator.generateFile():"; - _varControllerLogger.log("In "+ header); - - _varControllerLogger.log("\nGenerating the file [" + fileName +"]"); - - - // System.out.println("\nGenerating the file [" + fileName +"]"); - - PrintWriter outputStream = null; - try - { - outputStream = new PrintWriter(new FileOutputStream(fileName)); - - /*first line in the file lid.qin01_ts_var_dat, going back 10 days(240 rows, 1 hour interval), - total 360 rows ( 5 days ahead prediction, 120 rows)*/ - outputStream.println(" Z " + getPastHourlyValueCount() + " " + getTotalHourlyValueCount()); - - for (int i = 0; i < rts.getMeasurementCount(); i++) - { - long time = rts.getMeasurementTimeByIndex(i); - String[] arrayYearMonDayHour = VarHelper.getArrayYearMonthDayHour24HConventionFromLongTime(time); - - double value = rts.getMeasurementByIndex(i).getValue(); - - // System.out.println(header + "time = " + DbTimeHelper.getDateTimeStringFromLongTime(time) + " value = " + value ); - - outputStream.printf("%1$13s %2$10s %3$10s %4$10s %5$9.6f\n", - arrayYearMonDayHour[0], //year - arrayYearMonDayHour[1], //month - arrayYearMonDayHour[2], //day - arrayYearMonDayHour[3], //hour - value); // all RTS has to be in correct unit - - } //close for loop - _varControllerLogger.log("The input file [" + fileName + "] has been generated by Java program."); - - isObsInputFileCreationSuccessful = true; - } - catch (IOException e) - { - _varControllerLogger.log("IO exception with file " + fileName + " " + e.getMessage()); - isObsInputFileCreationSuccessful = false; - } - finally - { - if (outputStream != null) - { - outputStream.close(); - } - } - - return isObsInputFileCreationSuccessful; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - //generate the file "list_of_segments" -- it is only one line - public boolean generateSegmentsFile() - { - int qpfHourCount = 0; - boolean success = false; - try - { - PrintWriter outputStream = new PrintWriter(new FileOutputStream(_segmentsFilePath)); - outputStream.println(_basinId + " " + qpfHourCount); - outputStream.close(); - success = true; - } - catch(FileNotFoundException e) - { - _varControllerLogger.log(_segmentsFilePath + " is not found or could not be opened."); - } - return success; - } -// ---------------------------------------------------------------------------------------------------------------------------------- -} //close class diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/OutputFileManager.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/OutputFileManager.java deleted file mode 100644 index 27d2edcae0..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/OutputFileManager.java +++ /dev/null @@ -1,336 +0,0 @@ -package ohd.hseb.sshp.var; -import static ohd.hseb.util.TimeHelper.MILLIS_PER_HOUR; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import ohd.hseb.measurement.Measurement; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.FileLogger; - - -public class OutputFileManager -{ - private long _assimilationStartTimeLong; - private long _assimilationTargetTimeLong; - private String _basinId; - private int _uhgOrdinateNum; - private List _sacSmaStateList = null; - private RegularTimeSeries _runOffRegularTimeSeries; - private FileLogger _varControllerLogger; - - public OutputFileManager(FileLogger logger, String basinId, long assimilationStartTimeLong, long assimilationTargetTimeLong, - int uhgOrdinateNum) - { - _varControllerLogger = logger; - _assimilationStartTimeLong = assimilationStartTimeLong; - _assimilationTargetTimeLong = assimilationTargetTimeLong; - - _basinId = basinId; - _uhgOrdinateNum = uhgOrdinateNum; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - /*************************************************************************************************************************** - * Reads the file "basinId_states_02_var" or "basinId_adj_states_02_var" - * for getting the SAC-SMA state variables & runoff time series . - *@param fileName: "basinId_states_02_var" or "basinId_adj_states_02_var" - */ - public boolean readVarOutputFileForStateAndRunoffValues(String fileName) - { - boolean isReadSuccessful = false; - try - { - BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); - - String fortranVarTimeString = null; //jtime, precip, precip_after_adjustmen, pe, pe_after_adjustment - - _runOffRegularTimeSeries = new RegularTimeSeries(_assimilationStartTimeLong + MILLIS_PER_HOUR, - _assimilationTargetTimeLong + MILLIS_PER_HOUR, - 1, - MeasuringUnit.mm); - - String[] lineArray = null; - -// looping through reading and discarding un-wanted data - lineArray = readFourLines(bufferedReader); - - Pattern pattern = Pattern.compile(" +"); //dealing with multiple spaces - String[] arrayStr = null; - - _sacSmaStateList = new ArrayList(); - boolean done = false; - - if (lineArray[3] == null) //check to see if the last one is already null, if so, we are done. - { - done = true; - } - - while (! done ) - { -// processing the 1st line - arrayStr = pattern.split(lineArray[0].trim()); //trimming preceding and trailing spaces - fortranVarTimeString = arrayStr[0]; - - long time = VarHelper.getLongTimeFromDateTimeString(fortranVarTimeString, "yyyyMMddHH"); - //ignore the rest of the 1st line, because they are(in order): precip, precip_after_adjustmen, pe, pe_after_adjustment - // pxadj = precip_after_adjustmen/precip - // peadj = pe_after_adjustment/pe - -// processing the 2nd line - arrayStr = pattern.split(lineArray[1].trim()); - double uztwc = Double.parseDouble(arrayStr[0]); - double uzfwc = Double.parseDouble(arrayStr[1]); - double lztwc = Double.parseDouble(arrayStr[2]); - double lzfsc = Double.parseDouble(arrayStr[3]); - - //processing the 3rd line - arrayStr = pattern.split(lineArray[2].trim()); - double lzfpc = Double.parseDouble(arrayStr[0]); - double adimc = Double.parseDouble(arrayStr[1]); - -// processing the 4th line, get tci - arrayStr = pattern.split(lineArray[3].trim()); - double totalChannelInflow = Double.parseDouble(arrayStr[1]); //also known as tci - - //saving sacSmaState into database table SacSmaState - SacSmaState sacSmaState = new SacSmaState(); - - sacSmaState.setValidTime(time); - sacSmaState.setUztwc(uztwc); - sacSmaState.setUzfwc(uzfwc); - sacSmaState.setLztwc(lztwc); - sacSmaState.setLzfsc(lzfsc); - sacSmaState.setLzfpc(lzfpc); - sacSmaState.setAdimc(adimc); - sacSmaState.setBasinId(_basinId); - - _sacSmaStateList.add(sacSmaState); - - //adding the tci value to the time series - _runOffRegularTimeSeries.setMeasurementByTime(new Measurement(totalChannelInflow, - MeasuringUnit.mm), - time); - - //finished the 4 lines now, read the next 4 lines - lineArray = readFourLines(bufferedReader); - if( (lineArray == null) || (lineArray[0] == null) ) - { - done = true; - } - } //end of while loop - - _varControllerLogger.log(" number of hours read = " + _sacSmaStateList.size()); - bufferedReader.close(); - - if (_sacSmaStateList.size() > 0) - { - isReadSuccessful = true; - _varControllerLogger.log("The file [" + fileName + "] has been read and the Var SacSMA state variables and TCI have been saved in the database " + - "by Java program."); - } - else - { - isReadSuccessful = false; - _varControllerLogger.log("Error: the file [" + fileName + "] was read, but Var SacSMA state variables and TCI were not saved in the database " + - "by the Java program."); - } - - } - catch(FileNotFoundException e) - { - _varControllerLogger.log("File [" + fileName + "] not found or could not be opened"); - - } - catch(IOException e) - { - _varControllerLogger.log("Error reading from the file, " + fileName); - - } - - return isReadSuccessful; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - public List getSacSmaStateList() - { - return _sacSmaStateList; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - public RegularTimeSeries getRunOffRegularTimeSeries() - { - return _runOffRegularTimeSeries; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - private int getPastHourlyValueCount() - { - long elapsedTimeInMillis = _assimilationTargetTimeLong - _assimilationStartTimeLong ; - int elapsedTimeInHours = (int)(elapsedTimeInMillis / MILLIS_PER_HOUR) + 1; - return elapsedTimeInHours ; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - private String[] readFourLines(BufferedReader reader) - { - String lineArray[] = new String[4]; - for(int i=0; i < 4; i++) - { - try - { - lineArray[i] = reader.readLine(); - // System.out.println("line[" + i + "] = " + lineArray[i]); - } - catch(IOException e) - { - _varControllerLogger.log("OutputFilesReader.readFourLines(): " +e); - } - } - return lineArray; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - /************************************************************************************************************************************************** - * Saving the adjusted SacSma parameters(peadj, pxadj) and its correspondant validtime into a text file, "basinId_sacsmaparams", - * to be read later for deck file generation when running var next time. - * Only the number of UHG coordinate hours worth data is saved. - * - */ - //this method is not used currently - public boolean saveSacSmaParamsFromAdjFileToParamsFile(String outputDir, String basinId) - { - boolean isSaveSacSmaParamsSucccessful = false; - try - { - BufferedReader bufferedReader = new BufferedReader(new FileReader(outputDir + basinId + "_adj_states_02_var")); - PrintWriter outputStream = new PrintWriter(new FileOutputStream(outputDir + basinId + "_sacsmaparams"), true); - - String[] lineArray = null; - -// looping through reading and discarding un-wanted data - for(int i=1; i <= (getPastHourlyValueCount() - _uhgOrdinateNum); i++) - { - lineArray = readFourLines(bufferedReader); - } - - //now the inputStream has been the right place: - lineArray = readFourLines(bufferedReader); - - Pattern pattern = Pattern.compile(" +"); //dealing with multiple spaces - String[] arrayStr = null; - for(int i = 0; i < _uhgOrdinateNum; i++) - { -// processing the 1st line - arrayStr = pattern.split(lineArray[0].trim()); //trimming preceding and trailing spaces - String jtime = arrayStr[0]; - //ignore the rest of the 1st line, because they are(in order): precip, precip_after_adjustmen, pe, pe_after_adjustment - // pxadj = precip_after_adjustmen/precip - // peadj = pe_after_adjustment/pe - -// skip the 2nd line - - //processing the 3rd line: get the 3rd, 4th item this line - arrayStr = pattern.split(lineArray[2].trim()); - double pxadj = Double.parseDouble(arrayStr[2]); - double peadj = Double.parseDouble(arrayStr[3]); - - outputStream.printf("%1$10s \t%2$9.7f \t%3$9.7f\n", jtime,pxadj, peadj); - - //skip the 4th line - - //finished the 4 lines now, read the next 4 lines - lineArray = readFourLines(bufferedReader); - } //close for loop, finished outputing to file - - outputStream.close(); - } //close try block - catch(IOException e) - { - _varControllerLogger.log("Exception during saveSacSmaParamsToFile() in VarDataMgr.java"); - return isSaveSacSmaParamsSucccessful; - } - - _varControllerLogger.log("SacSma parameters pxadj & peadj have been saved into text file " - + outputDir + basinId + "_sacsmaparams"); - isSaveSacSmaParamsSucccessful = true; - return isSaveSacSmaParamsSucccessful; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /***************************************************************************************************************************** - * Read the pxadj and the peadj from the file, but this method is probably not needed. -Chip - * @return - */ - //this method is not used currently - private SacSmaParameters readAdjustmentFactorsFromFile(String outputDir, - String basinId, - SacSmaParameters sacSmaParams, - long varModelRunTimeLong, - int uhgOrdinateCount) - { - - // check if "basinId_sacsmaparams" file exists, if so, get pxadj and peadj with the most recent time - try - { - BufferedReader inputStream = new BufferedReader(new FileReader(outputDir + basinId + "_sacsmaparams")); - - Pattern pattern = Pattern.compile(" +"); //dealing with multiple spaces - double pxadj = 0.0, peadj = 0.0; //holds the values of the line above - double pxadjTemp = 0.0, peadjTemp = 0.0; //holds the current line values - // for(int i=0; i < loadUnitHydrograph(basinId).getMeasurementList().size(); i++) - for(int i=0; i < uhgOrdinateCount; i++) - { - String[] arrayStr = pattern.split(inputStream.readLine()); - long longTime = VarHelper.getLongTimeFromDateTimeString(arrayStr[0], "yyyyMMddHH"); - pxadjTemp = Double.parseDouble(arrayStr[1]); - peadjTemp = Double.parseDouble(arrayStr[2]); - - if ((i == 0) && (varModelRunTimeLong < longTime)) //this current time is older than the 1st validtime in the file - { - return sacSmaParams; //no need to update pxadj & peadj - } - else if ((i != 0 ) && (varModelRunTimeLong < longTime)) //reading has passed, pick up last line's data - { - //update peadj and pxadj and get out - sacSmaParams.setPxadj(pxadj); - sacSmaParams.setPeadj(peadj); - return sacSmaParams; - } - //longTime(validtime in text file) is still older than current time, save the data and read in next line - pxadj = pxadjTemp; - peadj = peadjTemp; - } //close for loop - - //if program has reached here, the whole text file has been read through and all stored pxadj, peadj validtime is older than the Var current time - //anyway, picks up the closest validtime pxadj, peadj - sacSmaParams.setPxadj(pxadjTemp); - sacSmaParams.setPeadj(peadjTemp); - } - catch(FileNotFoundException e) //due to 1st time running Var program on this basin, then return original sacSmaParams as it is - { - _varControllerLogger.log("The file "+ outputDir + basinId + "_sacsmaparams\" was not found. Original values of peadj and pxadj were used."); - return sacSmaParams; - } - catch(IOException e) - { - _varControllerLogger.log("File IO Exception during reading SacSma parameter from the text file"); - return sacSmaParams; - } - - return sacSmaParams; - } - - -} diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/OutputFileTester.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/OutputFileTester.java deleted file mode 100644 index fcb5b6dadd..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/OutputFileTester.java +++ /dev/null @@ -1,9 +0,0 @@ -package ohd.hseb.sshp.var; - -import junit.framework.TestCase; - -public class OutputFileTester extends TestCase -{ - - -} diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/StreamDrainer.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/StreamDrainer.java deleted file mode 100644 index fb0471f807..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/StreamDrainer.java +++ /dev/null @@ -1,95 +0,0 @@ -package ohd.hseb.sshp.var; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; - -public class StreamDrainer implements Runnable -{ - private InputStream _inputStream; - private StringBuffer _buffer = null; - // ------------------------------------------------------------------------------------ - - public StreamDrainer(InputStream inputStream) - { - _inputStream = inputStream; - _buffer = new StringBuffer(); - } -// ------------------------------------------------------------------------------------ - - - public void run() - { - try - { - drainInputStream(_inputStream); - } - catch (Exception e) - { - e.printStackTrace(); - } - - } -// ------------------------------------------------------------------------------------ - /* - public String drain() - { - Thread thread = new Thread(this); - thread.start(); - - return getString(); - } - */ - - public String drain() - { // last updated 1/17/08 - Thread thread = new Thread(this); - thread.start(); - - while ( thread.isAlive() ) - { - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException e ) - { - //do nothing - } - } - // System.out.println( "Right after start" ); - return getString(); - } - -// ------------------------------------------------------------------------------------ - - public String getString() - { - return _buffer.toString(); - } - - // ------------------------------------------------------------------------------------ - - private void drainInputStream(InputStream stream) throws IOException - { - String header = "StreamDrainer.drainInputStream(): "; - StringWriter stringWriter = new StringWriter(); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - String s = null; - - while ((s = reader.readLine()) != null) - { - // stringWriter.write(s + "\n"); - _buffer.append(s + "\n"); - // System.out.println(header + s + "n"); - } - - stringWriter.flush(); - - return; - } - - -} diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarAssimilationProgramExecuter.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarAssimilationProgramExecuter.java deleted file mode 100644 index ecdc68d477..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarAssimilationProgramExecuter.java +++ /dev/null @@ -1,235 +0,0 @@ -package ohd.hseb.sshp.var; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Map; -import java.util.regex.Pattern; - -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; - -/************************************************************************************************************** - * This class executes the Fortran program called Var. There are three possible outcomes: - * 1)The Fortran script successfully - * ran through AND the calculation error was within the tolerance range. -- This is the only case that Var results need - * to be saved. - * 2)The Fortran script was not able to run, due to lack of data or some other reasons. The - * program throws a FortranScriptRunningException object. - * 3)(intermediate situation between the previous 2 cases) The Fortran script - * was successfully ran through, however, Var could not adjust state variables enough to meet the error tolerance range. A - * FortranScriptRunningException object was thrown with message "var adjustment has failed.". - * @author lix - * - */ -public class VarAssimilationProgramExecuter -{ - private String _runScriptForFortranVarPgm; - private String _varAssimilationPgmLogFilePath; - private FileLogger _varControllerLogger; - private CodeTimer _timer = new CodeTimer(); - - - public VarAssimilationProgramExecuter(FileLogger logger, - String runScriptForFortranVarPgm, - String varAssimilationPgmLogFilePath) - { - _runScriptForFortranVarPgm = runScriptForFortranVarPgm; - _varControllerLogger = logger; - _varAssimilationPgmLogFilePath = varAssimilationPgmLogFilePath; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - /********************************************************************************************************* - * Generate the file "list_of_segments", then start Fortran var program, in the end, check if running is - * success or not. - */ - public boolean executeVarAssimilationProgram() - { - String header = "VarAssimilationProgramExecuter.executeVarAssimilationProgram(): "; - _varControllerLogger.log("In "+ header); - - _varControllerLogger.log("Starting the Fortran Var Program..."); - - System.out.println(header + "monitoring the file: " + _varAssimilationPgmLogFilePath); - boolean success = false; - - try - { - - _timer.restart(); - - //run Var Fortran program - Runtime runtime = Runtime.getRuntime(); - - //run FORTRAN program - Process process = runtime.exec(_runScriptForFortranVarPgm, getEnvironment() ); - - determineExecutionResults(process, _varAssimilationPgmLogFilePath); - - //var has finished - _timer.stop("The Fortran VAR program overall has taken "); - _varControllerLogger.log("The Fortran VAR has taken " + _timer.getElapsedTime() + " millis."); - - success = true; - - } - catch (FortranScriptRunningException fe) - { - fe.printStackTrace(); - fe.printStackTrace(_varControllerLogger.getPrintWriter()); - - String message = "Var Assimilation is not completed... reason:\n "+ fe.getMessage(); - System.out.println(message); - _varControllerLogger.log(message); - } - catch (Exception e) - { - e.printStackTrace(); - e.printStackTrace(_varControllerLogger.getPrintWriter()); - - } - - return success; - } //close method - // ----------------------------------------------------------------------- - - private String getStandardError(Process p) - { - //String header = "VarAssimilationProgramExecuter.getStandardError():"; - - StreamDrainer drainer = new StreamDrainer(p.getErrorStream()); - String drainedString = drainer.drain(); - - //System.out.println(header + " drainedString = " + drainedString); - - return drainedString; - - } - // ----------------------------------------------------------------------- - - private String getStandardOutput(Process p) - { - //String header = "VarAssimilationProgramExecuter.getStandardOutput():"; - - StreamDrainer drainer = new StreamDrainer(p.getInputStream()); - String drainedString = drainer.drain(); - - //System.out.println(header + " drainedString = " + drainedString); - - return drainedString; - } - // ----------------------------------------------------------------------- - - private boolean determineExecutionResults(Process process, - String logFileToExamine) - throws FortranScriptRunningException - { - - boolean success = false; - String header = "VarAssimilationProgramExecuter.determineExecutionResults(): "; - - BufferedReader bufferedReader = null; - File fileHandler = null; - // boolean found = false; - - - try //3 possible outcomes - { - getStandardOutput(process); - getStandardError(process); - - process.waitFor(); - - fileHandler = new File(logFileToExamine); - - bufferedReader = new BufferedReader(new FileReader(fileHandler)); - - //check if the Var Fortran program has completed successfully or not - Pattern successPattern = Pattern.compile(".*success.*"); - Pattern errorPattern = Pattern.compile(".*error .* too large for "); - Pattern skipVarPattern = Pattern.compile("skip var"); - - String line = null; - while((line = bufferedReader.readLine()) != null ) - { - System.out.println(header + "line = " + line); - - if (errorPattern.matcher(line).find()) - { - throw new FortranScriptRunningException("fortran var failed with log file message:" + line ); - //intermediate outcome: var was completed, but error was out of tolerance range, - //mainly due to little precipitation in the period - } - else if ( skipVarPattern.matcher(line).find()) - { - throw new FortranScriptRunningException("var skipped because: " + line ); - } - - else if (successPattern.matcher(line).find()) - { - _varControllerLogger.log("Var Assimilation completed successfully!!!"); - success = true; - break; //best outcome: var was completed successfully and error was within tolerance - } - } //close while - - //if program reaches here, the worst outcome: var was not able to be completed - //_varControllerLogger.log("var was not able to be completed due to some reasons."); - if (!success) - { - // process.destroy(); - throw new FortranScriptRunningException("Failure: Unable to determine success or failure based on fortran log file..."); - } - } - - catch(Exception e) - { - String message = e.getMessage() +" exception was thrown when running Fortran var script."; - // _varControllerLogger.log(message); - throw new FortranScriptRunningException(message); - } - - finally //always get executed, no matter Exception or not - { - if(fileHandler != null) - { - try - { - if(bufferedReader != null) - { - bufferedReader.close(); - } - } - catch(IOException e) - { - _varControllerLogger.log(e.getMessage()); - } - } - } - - return success; - -} - -// ----------------------------------------------------------------------- - - public String[] getEnvironment() - { - - Map envMap = System.getenv(); - - String[] envStringArray = new String[envMap.size()]; - int i =0; - for (String key : envMap.keySet()) - { - envStringArray[i] = key + "=" + envMap.get(key); - i++; - } - - return envStringArray; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - -} //close class diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarController.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarController.java deleted file mode 100644 index cc389fbfa7..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarController.java +++ /dev/null @@ -1,797 +0,0 @@ -package ohd.hseb.sshp.var; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; -import ohd.hseb.util.TimeHelper; - -import static ohd.hseb.db.DbTimeHelper.*; -import static ohd.hseb.util.TimeHelper.*; - -/******************************************************************************************************** - * The class executes ensures the following: - * prepararation of input files, - * running the actual VarAssimilationProgram, - * check and save results. - * @author lix, cgobs - * - */ -public class VarController -{ - private static int FUTURE_HOURS = 0; - private VarDataMgr _varDataMgr; - - private static String _varInputDir; - private static String _varOutputDir; - private static String _runScriptForVarAssimilationPgm; - private static FileLogger _varControllerLogger; - private static String _segmentsFilePath; - private static String _varAssimilationPgmLogFile; - private static String _argTimeString; - private static String _database; - - private VarAssimilationProgramExecuter _scriptExecuter = null; - - private CodeTimer _singleRunTimer = new CodeTimer(); - private CodeTimer _setUpTimer = new CodeTimer(); - - private CodeTimer _generationCodeTimer = new CodeTimer(); - // private CodeTimer _executeCodeTimer = new CodeTimer(); - private CodeTimer _readAndSaveResultsCodeTimer = new CodeTimer(); - - private Set _successSet = new HashSet(); - private Set _failureSet = new HashSet(); - - - // --------------------------------------------------------------------------------------------------------------- - - public VarController(String database, String argTimeString, - String varInputDir, - String varOutputDir, - String runScriptForVarAssimilationPgm, - FileLogger varControllerLog, - String fileContainingSegments, - String varAssimilationPgmLogFile) - { - _database = database; - _varInputDir = varInputDir; - _varOutputDir = varOutputDir; - _runScriptForVarAssimilationPgm = runScriptForVarAssimilationPgm; - _varControllerLogger = varControllerLog; - _segmentsFilePath = fileContainingSegments; - _varAssimilationPgmLogFile = varAssimilationPgmLogFile; - _argTimeString = argTimeString; - - logInputs(); - - _varDataMgr = new VarDataMgr(_varControllerLogger, _database, - _varInputDir, _varOutputDir, - _segmentsFilePath); - - _scriptExecuter = new VarAssimilationProgramExecuter(_varControllerLogger, - _runScriptForVarAssimilationPgm, - _varAssimilationPgmLogFile); - } - - public VarDataMgr getVarDataMgr() - { - return _varDataMgr; - } - public String getDatabaseName() - { - return _database; - } - - public String getVarInputDir() - { - return _varInputDir; - } - - public String getVarOutputDir() - { - return _varOutputDir; - } - - public String getRunScriptForVarAssimilationPgm() - { - return _runScriptForVarAssimilationPgm; - } - - public FileLogger getVarControllerLogger() - { - return _varControllerLogger; - } - - public String getSegmentsFile() - { - return _segmentsFilePath; - } - - public String getVarAssimilationPgmLogFile() - { - return _varAssimilationPgmLogFile; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public void logInputs() - { - - _varControllerLogger.log("-------------------------------------------------------------------------------------------"); - _varControllerLogger.log("VAR Started with Inputs:"); - _varControllerLogger.log("Version: "+ "pre-OB9"+ " Version Date:"+ "May 5, 2008"); - _varControllerLogger.log("Database: "+ _database); - _varControllerLogger.log("User Input Time:"+ _argTimeString); - _varControllerLogger.log("InputDir:"+ _varInputDir); - _varControllerLogger.log("OutputDir:"+_varOutputDir); - _varControllerLogger.log("Variational Assimilation Program:"+ _runScriptForVarAssimilationPgm); - _varControllerLogger.log("Variational Assimilation Program's Log File:"+ _varAssimilationPgmLogFile); - } - - //------------------------------------------------------------------------------------------------------------- - - /************************************************************************************************************************* - * Gets the list of all possible basin ids and for each basin id - * makes calls to - * generate deck parameter file, - * generate precip input file & inflow input file - * start var Fortran program. - * read the output files(_adj_states_02_var, _states_02_var) created by the fortran var program and save it in database - * and delete the output files - * Possible outcomes: - * 1)If all the data for a basin Id is available for preparing the input files, then FortranScriptExecuter will run. - * If some data is not available, proceed to next basin id. - * 2)Three possible outcomes when running FortranScriptExecuter: - * a)If Fortran Var script executes successfully and met the error tolerance - * range, then save the var vriables into database or textfile and delete the two output files - * "basinId_states_02_var" & "basinId_adj_states_02_var", forcing Fortran Var script to rely on the deck - * parameter file for next execution also, not just the first time - * b,c)If Fortran Var script failed or has finished but error was too large, a FortranScriptRunningException - * was thrown. The log file "log_var" was printed out to help user know the cause. No data saving. If output files has been - * generated(script was run through), delete the two output files too. - */ - public void runVarController() - { - String header = "VarController.runVarController(): "; - // _varControllerLogger.log("In "+ header); - long overallAssimilationTargetTimeLong = TimeHelper.truncateTimeInMillisToNearestHour(getLongTimeFromDateTimeString(_argTimeString), 1); - - List allBasinIdsList = _varDataMgr.getAllBasinIdsList(); - - - // Look for any recent changes to the QPE grids. We want to rerun VAR for the affected hours. - // So, get the time of the earliest grid affected by these changes. Rerun from then until the present. - // If no grids have been recently edited, then the overallAssimilationTargetTime is used - // as the latest possible time for which an adjustedSacSmaState could be found - // (it will probably be at least an hour earlier , in that case) - - long possibleValidSacSmaStateTime = getEarliestRecentlyEditedGridTime(); - if (possibleValidSacSmaStateTime == -1) - { - possibleValidSacSmaStateTime = overallAssimilationTargetTimeLong; - } - - String message = header + "possibleValidSacSmaStateTime = " + DbTimeHelper.getDateTimeStringFromLongTime(possibleValidSacSmaStateTime) + " " + - "overallAssimilationTargetTimeLong = " + DbTimeHelper.getDateTimeStringFromLongTime(overallAssimilationTargetTimeLong); - - _varControllerLogger.log(message); - System.out.println(message); - - for (String basinId: allBasinIdsList) - { - _varControllerLogger.log("Beginning multi-run processing For basin Id = " + basinId); - - //get the top of hr of arg time string - - invokeVarForMultipleRuns( basinId, possibleValidSacSmaStateTime, overallAssimilationTargetTimeLong ); - _varControllerLogger.log("Ended multi-run processing For basin Id = " + basinId + "\n"); - - // summarizeResults(); - - }//end for - - System.out.println("Final Results:"); - - summarizeResults(); - - _varDataMgr.disconnectDatabase(); - return; - - } - -// ------------------------------------------------------------------------------------------------------------- - - - /* - * Start from the available latest unadj sacsma state, which is the one with latest valid time for this basin - * and source is UNADJ_VAR - * and run the var in intervals of 1 hr - * until the time of user's var model run time given in cmd line arg - * Assume var was not running for some time and then restarted - * If the user's run time input is 8Z, the uhg length is 5 hrs, the unadj state is available for say time 1Z, - * then - * 1. var should be run for 6Z(var model run time), using unadj state available for 1Z, & precip & discharge timeseries from 1Z to 6Z - * store var's o/p for unadj state for 2Z and adj & unadj states for 6Z - * run of time series from 2Z to 6Z - * all of them having same current systime as basis time - * 2. var should be run for 7Z(var model run time), using unadj state available for 2Z, & precip & discharge timeseries from 2Z to 7Z - * store var's o/p for unadj state for 3Z and adj & unadj states for 7Z - * run of time series from 3Z to 7Z - * all of them having same current systime as basis time - * 3. var should be run for 8Z(var model run time), using unadj state available for 3Z, & precip & discharge timeseries from 3Z to 8Z - * store var's o/p for unadj state for 4Z and adj & unadj states for 8Z - * run of time series from 4Z to 8Z - * all of them having same current systime as basis time - * In usual cases, VAR will be run continuously every hour, so the loop will be executed only once for each execution of VAR. - */ - private void invokeVarForMultipleRuns(String basinId, long possibleValidSacSmaStateTime, long overallAssimilationTargetTimeLong ) - { - RegularTimeSeries dischargeTimeSeries = null; - RegularTimeSeries precipTimeSeries = null; - String header = "VarController.invokeVarForMultipleRuns(); "; - int modelRunCountForThisBasin = 1; - long assimilationStartTimeLong = 0; - long lastAppropriateUnadjSacSmaStateTimeLong = 0; - int numOfFutureHours = FUTURE_HOURS; //5 days worth of future data, which is used as input by var - - long uhgLengthInMillis = 0; - //initialize the location's data for a series of hourly runs - try - { - - String locationId = _varDataMgr.getLocationIdFromBasinId(basinId); - - uhgLengthInMillis = _varDataMgr.getUhgLengthInMillis(locationId, basinId); - - String message = "Basin = " + basinId + " UnitHydrograph Length:"+ (uhgLengthInMillis / MILLIS_PER_HOUR); - System.out.println(message); - _varControllerLogger.log(message); - - - lastAppropriateUnadjSacSmaStateTimeLong = - determineAppropriateUnadjSacStateTime(basinId, - uhgLengthInMillis, - possibleValidSacSmaStateTime, - overallAssimilationTargetTimeLong); - - boolean checkForMissingData = false; - - - - dischargeTimeSeries = _varDataMgr.getDischargeRegularTimeSeries(locationId, - lastAppropriateUnadjSacSmaStateTimeLong, - overallAssimilationTargetTimeLong, - checkForMissingData); //some data may be missing, so don't check for missing data - - precipTimeSeries = _varDataMgr.getPrecipRTSforPrecipFile(basinId, lastAppropriateUnadjSacSmaStateTimeLong, - overallAssimilationTargetTimeLong, checkForMissingData); //some data may be missing, so don't check for missing data - - _setUpTimer.stop(header + "setup has taken "); - - - // for every possible hourly run, up to the overallAssimilationTargetTime, execute the VAR algorithm - for( assimilationStartTimeLong = lastAppropriateUnadjSacSmaStateTimeLong ; - assimilationStartTimeLong + uhgLengthInMillis <= overallAssimilationTargetTimeLong; - assimilationStartTimeLong += MILLIS_PER_HOUR) - { - long assimilationTargetTimeLong = assimilationStartTimeLong + uhgLengthInMillis; - - String assimilationStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(assimilationStartTimeLong); - String assimilationTargetTimeString = DbTimeHelper.getDateTimeStringFromLongTime(assimilationTargetTimeLong); - - - if (_varDataMgr.areDischargeAndPrecipDataAvailable(dischargeTimeSeries, precipTimeSeries, assimilationTargetTimeLong) ) - { - _varControllerLogger.log("Model RunCount For This Basin = " + modelRunCountForThisBasin); - _varControllerLogger.log("Assimilation Start Time = " + assimilationStartTimeString); - _varControllerLogger.log("Assimilation Target Time = " + assimilationTargetTimeString); - - // System.out.println("Model RunCount For This Basin:" + modelRunCountForThisBasin); - System.out.print("Assimilation Start Time:[" + assimilationStartTimeString); - System.out.println(" Assimilation Target Time:[" + assimilationTargetTimeString); - - - _singleRunTimer.start(); - - executeVarForSingleRun( basinId, numOfFutureHours, assimilationStartTimeLong, assimilationTargetTimeLong); - - _singleRunTimer.stop(header + " executeVarForSingleRun() took "); - - System.out.println(); - - modelRunCountForThisBasin++; - - } - else - { - // _varControllerLogger.log("Either Discharge or precip not available at assimilation Target Time:[" + assimilationTargetTimeString); - // System.out.println("Either Discharge or precip not available at assimilation Target Time:[" + assimilationTargetTimeString); - logFailure(basinId, assimilationStartTimeLong, assimilationTargetTimeLong); - } - - } - - } - catch(DataAbsentException e) - { - //String message = "Initial sac sma states are not available for [" +basinId+"]... proceeding to next basinId"; - //System.out.println(message); - _varControllerLogger.log(e.getMessage()); - return; - } - - - - } //end invokeVarForMultipleRuns -// ------------------------------------------------------------------------------------------------------------- - /** - This routine determines the Unadjusted SacState time that is needed to kick off 1 or more iterations of VAR runs for a particular basin. - */ - private long determineAppropriateUnadjSacStateTime(String basinId, - long uhgLengthInMillis, - long possibleValidSacSmaStateTime, - long overallAssimilationTargetTimeLong) throws DataAbsentException - { - String overallAssimilationTargetTimeString = DbTimeHelper.getDateTimeStringFromLongTime(overallAssimilationTargetTimeLong); - - long lastAppropriateUnadjSacSmaStateTimeLong = 0; - boolean thereIsNoEarlyEnoughUnadjustedSacSmaState = false; - String message = null; - - _setUpTimer.restart(); - - //get the latest adjust sac sma state that we are allowed to use - SacSmaState lastAdjustedSacSmaState = _varDataMgr.loadLastAdjustedSacSmaStateAtOrBeforeATime(basinId, - possibleValidSacSmaStateTime); - - //If we have a lastAdjusted state, then find an unadjusted state than can be used to compete the next hours - long lastAdjustedTime = -1; - if (lastAdjustedSacSmaState != null) - { - lastAdjustedTime = lastAdjustedSacSmaState.getValidTime(); - message = "Latest adjusted sac state's valid time : "+ DbTimeHelper.getDateTimeStringFromLongTime(lastAdjustedTime); - System.out.println(message); - _varControllerLogger.log(message); - - //This gets a SacSmaState that is appropriate to be the starting point of a VAR run for a time that ends - //UHG_length hours later - which is (lastAdjustedtime + MILLIS_PER_HOUR) - SacSmaState lastAppropriateUnadjSacSmaState = - _varDataMgr.loadPrevUnadjSacSmaState(basinId, uhgLengthInMillis, lastAdjustedTime + MILLIS_PER_HOUR); - - - if (lastAppropriateUnadjSacSmaState != null) - { - lastAppropriateUnadjSacSmaStateTimeLong = lastAppropriateUnadjSacSmaState.getValidTime(); - } - else - { - thereIsNoEarlyEnoughUnadjustedSacSmaState = true; - //There was not an unadjusted sac sma state early enough to create the next ADJUSTED sac-sma time - } - - } - - - //if we can't find an adjusted state or we don't have an appropriate unadjusted state to use, - // then do our best to determine which problem it is and then either bail or start with the oldest available unadjusted state - if ((lastAdjustedSacSmaState == null) || (thereIsNoEarlyEnoughUnadjustedSacSmaState) ) //There are no available adjusted SAC-SMA times - { - message = "No previous adjusted state was found. "+ DbTimeHelper.getDateTimeStringFromLongTime(lastAdjustedTime) + "So, try starting with the oldest VAR unadjusted state."; - System.out.println(message); - _varControllerLogger.log(message); - - SacSmaState lastAppropriateUnadjSacSmaState = _varDataMgr.loadOldestUnadjSacSmaState(basinId); - - if (lastAppropriateUnadjSacSmaState != null) - { - lastAppropriateUnadjSacSmaStateTimeLong = lastAppropriateUnadjSacSmaState.getValidTime(); - } - else //lastAppropriateUnadjSacSmaState == null - { - throw new DataAbsentException("There is no available unadjusted SAC-SMA state from which to begin a VAR run for basinId = " + basinId +"\n"); - } - - } - - - String lastAvailUnadjSacSmaStateTimeString = - DbTimeHelper.getDateTimeStringFromLongTime(lastAppropriateUnadjSacSmaStateTimeLong); - - message = "Latest unadjusted sac state's valid time : "+ lastAvailUnadjSacSmaStateTimeString; - System.out.println(message); - _varControllerLogger.log(message); - - System.out.println("for " + basinId + " overall assimilation target time :"+ overallAssimilationTargetTimeString); - System.out.println("Var start time for 1st run:"+ - DbTimeHelper.getDateTimeStringFromLongTime(overallAssimilationTargetTimeLong - uhgLengthInMillis)); - - return lastAppropriateUnadjSacSmaStateTimeLong; - } - -// ------------------------------------------------------------------------------------------------------------- - - private long getEarliestRecentlyEditedGridTime() - { - //Purpose: find the earliest time of a file edit that occurred after the latest SACSMA state posting time - - long earliestGridTime = -1; - - long latestPostingTimeToSacSmaState = _varDataMgr.getLatestVarSacSmaStatePostingTime(); - - //find the earliest locally-produced MPE file time after the latest posting time - List localGridTimeList = _varDataMgr.getNewerBestQpeXmrgFileTimeList(latestPostingTimeToSacSmaState); - - if (localGridTimeList.size() > 0) - { - earliestGridTime = (Long) localGridTimeList.get(0); - } - - //find the earliest RFC-produced MPE file time after the latest posting time - //if any, compare to the - List rfcGridTimeList = _varDataMgr.getNewerRfcXmrgFileTimeList(latestPostingTimeToSacSmaState); - - if (rfcGridTimeList.size() > 0) - { - long rfcEarliestGridTime = (Long) rfcGridTimeList.get(0); - - //if there were new local grids - if (earliestGridTime > -1) - { - //if rfc grid time is earlier, use that earlier time - if (rfcEarliestGridTime < earliestGridTime) - { - earliestGridTime = rfcEarliestGridTime; - } - } - else // there were not any new local grids, so just use the rfc time - { - earliestGridTime = rfcEarliestGridTime; - } - } - - return earliestGridTime; - } - -// ------------------------------------------------------------------------------------------------------------- - - - private void executeVarForSingleRun(String basinId, int numOfFutureHours, - long assimilationStartTimeLong, long assimilationTargetTimeLong) - { - String header = "VarController.executeVarForSingleRun(): "; - - deleteFilesFromPreviousRun(); // delete output files created by fortran var during previous run - - boolean isVarAssimilationSuccessful = false; - //generate the basinId.var_deck file, precipitation file "basinId.mapx_ts_var_dat" file & discharge file "basinId.qin01_ts_var_dat" file - - String assimilationStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(assimilationStartTimeLong); - String assimilationTargetTimeString = DbTimeHelper.getDateTimeStringFromLongTime(assimilationTargetTimeLong); - - _generationCodeTimer.restart(); - - boolean generationSuccessful = _varDataMgr.generateVarInputFiles(basinId, - numOfFutureHours, - assimilationStartTimeLong, - assimilationTargetTimeLong); - _generationCodeTimer.stop(header + "File Generation has taken: "); - - if (generationSuccessful) - { - //System.out.println(header + "file generation succeeded for " + basinId + " from " + - // assimilationStartTimeString + " to " + assimilationTargetTimeString + "."); - - isVarAssimilationSuccessful = runVarAndSaveResults(basinId, - assimilationStartTimeLong, - assimilationTargetTimeLong, - assimilationStartTimeString, - assimilationTargetTimeString); - - } - else //file generation not successful - { - String message = "\nFile generation failed for basin " + basinId + - " from " + assimilationStartTimeString + " to " + - assimilationTargetTimeString + "."; - - _varControllerLogger.log(message); - - System.out.println(message); - } - - //long success or failure of run - logResults(basinId, assimilationStartTimeLong, assimilationTargetTimeLong, isVarAssimilationSuccessful); - - return; - } -// ------------------------------------------------------------------------------------------------------------- - private boolean runVarAndSaveResults(String basinId, - long assimilationStartTimeLong, - long assimilationTargetTimeLong, - String assimilationStartTimeString, - String assimilationTargetTimeString) - { - String header = "VarController.runVarAndSaveResults(): "; -// run the Fortran var program - boolean isVarAssimilationSuccessful = _scriptExecuter.executeVarAssimilationProgram(); - boolean readAndSaveSuccessful = false; - - - if(isVarAssimilationSuccessful) - { - //saving the generated results - _readAndSaveResultsCodeTimer.restart(); - - readAndSaveSuccessful = _varDataMgr.readAndSaveGeneratedResults(basinId, - assimilationStartTimeLong, - assimilationTargetTimeLong); - - _readAndSaveResultsCodeTimer.stop(header + "overall, readAndSaveGeneratedResults() has taken: "); - - if(readAndSaveSuccessful) - { - _varControllerLogger.log("Saved results for basin = " + basinId + - " from " + assimilationStartTimeString + " to " + assimilationTargetTimeString + "."); - } - else - { - _varControllerLogger.log("Generated files, but unable to save results for basin = " + basinId + - " from " + assimilationStartTimeString + " to " + assimilationTargetTimeString + "."); - } - } //end if var successful - - - else //data assimilation not successful - { - String message = "Data assimilation failed for basin = " + basinId + " for period from " - + assimilationStartTimeString + " to " + assimilationTargetTimeString + "."; - - _varControllerLogger.log(message); - System.out.println(message); - } - - return readAndSaveSuccessful; - - } - -// ------------------------------------------------------------------------------------------------------------- - private void deleteFilesFromPreviousRun() - { - deletePreviousDeckFiles(); - deletePreviousOutputFiles(); - - } -// ------------------------------------------------------------------------------------------------------------- - private void printAllFiles(String directoryPath) - { - File directory = new File(directoryPath); - File[] fileArray2 = directory.listFiles(); - - System.out.println("-----------------------------------:"); - System.out.println("Files in the input directory:"); - - try - { - for (File file : fileArray2) - { - - System.out.println(file.getCanonicalFile()); - } - } - catch (IOException e) - { - e.printStackTrace(); - } - - System.out.println("-----------------------------------:"); - } - -// ------------------------------------------------------------------------------------------------------------- - - private void deletePreviousDeckFiles() - { - // String header = "VarController.deletePreviousDeckFiles(): "; - - //delete o/p files generated by fortran var program - File directory = new File(_varInputDir + "/param/"); - - File[] fileArray = directory.listFiles(); - - if (fileArray == null) - { - return; - } - - for (File file : fileArray) - { - try - { - if (file.getName().endsWith("deck") && (file.isFile())) - { - - // System.out.println(header + " deleting " + file.getCanonicalPath()); - boolean result = file.delete(); - if (result) - { - //System.out.println(header + " I think I really deleted " + file.getCanonicalPath()); - } - else - { - //System.out.println(header + " I don't think I really deleted " + file.getCanonicalPath()); - } - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - } - -// ------------------------------------------------------------------------------------------------------------- - - private void deletePreviousOutputFiles() - { - - // String header = "VarController.deletePreviousOutputFiles(): "; - - //delete o/p files generated by fortran var program - File directory = new File(_varOutputDir); - - File[] fileArray = directory.listFiles(); - - if (fileArray == null) - { - return; - } - - for (File file : fileArray) - { - try - { - if (file.isFile()) - { - file.delete(); - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - // printAllFiles(_varOutputDir); - - } -// ------------------------------------------------------------------------------------------------------------- - private void logSuccess(String basinId, long startTime, long endTime) - { - - logResults(basinId, startTime, endTime, true); - } - - // ------------------------------------------------------------------------------------------------------------- - - private void logFailure(String basinId, long startTime, long endTime) - { - - logResults(basinId, startTime, endTime, false); - } - -// ------------------------------------------------------------------------------------------------------------- - - private void logResults(String basinId, long startTime, long endTime, boolean wasSuccess) - { - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTime); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTime); - - - String runInfoString = basinId + '|' + startTimeString + '|' + endTimeString; - - if (wasSuccess) - { - _successSet.add(runInfoString); - } - else //was failure - { - _failureSet.add(runInfoString); - } - - return; - } - - // ------------------------------------------------------------------------------------------------------------- - - private void summarizeResults() - { - int successCount = _successSet.size(); - int failureCount = _failureSet.size(); - - System.out.println("VAR execution summary --------------------------------"); - - //print out success info - System.out.println("The following are the VAR runs that succeeded:"); - - - for (String successString : getSortedListFromSet(_successSet)) - { - System.out.println(successString); - } - - - //print out failure info - System.out.println("The following are the VAR runs that failed:"); - for (String failureString : getSortedListFromSet(_failureSet)) - { - System.out.println(failureString); - } - - System.out.println("There were " + successCount + " successful runs."); - System.out.println("There were " + failureCount + " failed runs."); - - System.out.println("------------------------------------------------------"); - - - return; - } - -// ------------------------------------------------------------------------------------------------------------- - List getSortedListFromSet(Set originalSet) - { - List list = new ArrayList(originalSet); - Collections.sort(list); - - return list; - } - -// ------------------------------------------------------------------------------------------------------------- - - - /************************************************************************************************************** - * This is the main method in the project. It takes input argumets from the run script - * @param args - */ - - public static void main(String[] args) - { - String database = args[0]; - String argTimeString = args[1]; - if(argTimeString.equals("CURRENT_TIME")) - { - argTimeString = DbTimeHelper.getDateTimeStringFromLongTime(System.currentTimeMillis()); - } - _varControllerLogger = new FileLogger(args[2] + "/" + args[3], true, true); - - System.out.println("Log file:"+ args[2]+"/"+args[3]); - _varInputDir = args[4] +"/"; - _varOutputDir = args[5] + "/"; - _runScriptForVarAssimilationPgm = args[6]; - _segmentsFilePath = _varInputDir + "/" +args[7]; - _varAssimilationPgmLogFile = args[8]; - - - VarController varAssimilationController = new VarController(database, argTimeString, _varInputDir , _varOutputDir, - _runScriptForVarAssimilationPgm, _varControllerLogger, - _segmentsFilePath, _varAssimilationPgmLogFile ); - - _varControllerLogger.log("-------------------------------------------------------------------------------------------"); - _varControllerLogger.log("Application Started"); - - varAssimilationController.runVarController(); - - _varControllerLogger.log("Application Exiting..."); - _varControllerLogger.log("-------------------------------------------------------------------------------------------"); - System.exit(0); - } - -} //close class - diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarDataMgr.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarDataMgr.java deleted file mode 100644 index 979b2f97aa..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarDataMgr.java +++ /dev/null @@ -1,853 +0,0 @@ -package ohd.hseb.sshp.var; - -import java.text.SimpleDateFormat; -import java.util.*; - -import ohd.hseb.db.DbTable; -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.measurement.MeasuringUnit; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.model.MonthlyValues; -import ohd.hseb.model.RatingCurve; -import ohd.hseb.model.UnitHydrograph; -import ohd.hseb.model.sacsma.SacSmaParameters; -import ohd.hseb.model.sacsma.SacSmaState; -import ohd.hseb.sshp.DataMgr; -import ohd.hseb.sshp.SSHPConfig; -import ohd.hseb.sshp.SSHPSource; -import ohd.hseb.sshp.precip.BasinHrapHelper; -import ohd.hseb.util.CodeTimer; -import ohd.hseb.util.FileLogger; - -import static ohd.hseb.util.TimeHelper.*; - - -/******************************************************************************************************************* - * A data manager talking with database and is specifically related with Var task. It has a delegater from SSHP data - * manager, DataMgr. - * - */ -public class VarDataMgr -{ - private DataMgr _sshpDataMgr; - private FileLogger _varControllerLogger; - private String _varInputDir; - private String _varOutputDir; - private String _segmentsFilePath; - - private Map _precipTimeSeriesMap = new HashMap(); - private Map _stageTimeSeriesMap = new HashMap(); - private Map _monthlyValuesMap = new HashMap(); - private Map _ratingCurveMap = new HashMap(); - private Map _basinIdToLocationIdMap = new HashMap(); - private Map _unitHydrographMap = new HashMap(); - - private CodeTimer _dataLoadingTimer = new CodeTimer(); - - - /**************************************************************************************************************************** - * A constructor. - * @param basin: String - * @param strCurrentTime: String in the formate of "yyyy-MM-dd HH:00:00" - */ - public VarDataMgr(FileLogger logger, String dbName, - String inputDir, String outputDir, - String segmentsFilePath) - { - _varControllerLogger = logger; - _varInputDir = inputDir; - _varOutputDir = outputDir; - _segmentsFilePath = segmentsFilePath; - _sshpDataMgr = new DataMgr(dbName, _varControllerLogger); - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /********************************** - * Get the list of all possible basin ids from the SacSmaParams table. - * Calls getSSHPConfigList in sshp project's data mgr to get the possible config details - * and retrieves all possible basin ids from the list - * @return list of all possible basin id's - */ - public List getAllBasinIdsList() - { - Set basinIdSet = new HashSet(); - List basinIdList = new ArrayList(); - List paramList = _sshpDataMgr.loadSacSmaParamsList("order by basin_id"); - - for(SacSmaParameters params : paramList) - { - if (! basinIdSet.contains(params.getBasinId()) ) - { - //do this in multiple step to maintain basinId ordering in the list - basinIdSet.add(params.getBasinId()); - basinIdList.add(params.getBasinId()); - } - } - - return basinIdList; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - /********************************************************************************************************** - * Returns the drainage area of the basin (unit: squaremiles), stored in database table linesegs. The value - * in the database is with unit of squaremiles. - * @return - */ - public double getBasinArea(String basinId) throws DataAbsentException - { - BasinHrapHelper basinHelper = _sshpDataMgr.getBasinHrapHelper(basinId); - if(basinHelper == null) - { - _varControllerLogger.log("BasinHrapHelper for the basin " + basinId + " is not available"); - throw new DataAbsentException(); - } - return basinHelper.getAreaSize(); - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /******************************************************************************************************* - * Get the location name associated with the basin_id. Because the strict format required by Fortran program, - * so if the name is longer than 20 chars, it is truncated to 20. - * @return - */ - public String getLocationName(String basinId) throws DataAbsentException - { - String locationName = _sshpDataMgr.getLocationName(basinId); - - if (locationName == null) - { - _varControllerLogger.log("No location name was found from database for the basin " + basinId); - throw new DataAbsentException(); - } - - locationName = locationName.trim(); - //control the length of the string to 20 max, because the string will be printed in deck parameter file, which restricts <= 20 chars - if (locationName.length() > 20) - { - locationName = locationName.substring(0, 20); - } - - return locationName; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /***************************************************************************************************************************** - * Get the most recent SAC-SMA model parameters from database. If the file, "basinId_sacsmaparams", exists due to previous Var execuation, - * then update pxadj and peadj from the text file. - * @return - */ - public SacSmaParameters loadSacSmaParameters(String basinId, long validTimeLong) throws DataAbsentException - { - String header = "VarDataMgr.loadSacSmaParameters()"; - _varControllerLogger.log("In "+ header); - - SacSmaParameters sacSmaParams = null; - sacSmaParams = _sshpDataMgr.loadSacSmaParameters(basinId, validTimeLong); - - if(sacSmaParams == null) - { - _varControllerLogger.log("SacSmaParameters data for the basin " + basinId + " is not available"); - throw new DataAbsentException(); - } - - - //not calling it - // sacSmaParams = getAdjustmentFactorsFromFile( basinId, sacSmaParams, varModelRunTimeLong); - return sacSmaParams; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /************************************************************************************ - * Returns the most recent MonthlyValues for ET-demand or PE-adjustment factor. - * MonthValues.getValueArray() returns an array of 12 double values. The boolean parameter - * will be part of SQL SELECT WHERE clause. - * @return - */ - - public MonthlyValues getMonthlyValues(String basinId) throws DataAbsentException - { - // String header = "VarDataMgr.loadMonthlyValues(): "; - - boolean isAdjustmentFactor = false; - - MonthlyValues monthlyValues = _monthlyValuesMap.get(basinId); - if(monthlyValues == null) - { - - monthlyValues = _sshpDataMgr.loadMonthlyValues(basinId, isAdjustmentFactor); - _monthlyValuesMap.put(basinId, monthlyValues); - - } - - if(monthlyValues == null) - { - String message = "MonthlyValues data data for the basin " + basinId + " is not available"; - _varControllerLogger.log(message); - throw new DataAbsentException(); - } - - return monthlyValues; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - /************************************************************************************* - * From sacsmastate table, get the SAC-SMA model unadj state whose - * latest valid time <= (var model run time - UHG length in millis per hr). - * @param basinId - * @param varModelRunTimeLong - * @return - */ - public SacSmaState loadPrevUnadjSacSmaState(String basinId, long uhgLengthInMillis, long varModelRunTimeLong) - { - String header = "VarDataMgr.loadPrevUnadjSacSmaState(): "; - - // System.out.println(header + "varModelRunTimeLong = " + DbTimeHelper.getDateTimeStringFromLongTime(varModelRunTimeLong)); - - - long sacSmaStateTimeLong = varModelRunTimeLong - uhgLengthInMillis; - - // System.out.println(header + "sacSmaStateTimeLong = " + varModelRunTimeLong); - - - SacSmaState sacSmaState = _sshpDataMgr.loadSacSmaState(basinId, - SSHPSource.UNADJUSTED_VAR.getSacSmaSource(), - sacSmaStateTimeLong); - - - String sacSmaStateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(sacSmaStateTimeLong); - // System.out.println(header + "Source: "+ SSHPSource.UNADJUSTED_VAR.getSacSmaSource() + " with time = " + sacSmaStateTimeString); - - if(sacSmaState == null) //when corresponding record does not exist in database table. - { - String message = "Unadjusted SacSmaSate data for the basin " + basinId + - " is not available for time: "+ - sacSmaStateTimeString; - - message += "\nRequested varModelRunTimeLong was " + DbTimeHelper.getDateTimeStringFromLongTime(varModelRunTimeLong); - message += "Length of UHG in millis = " + uhgLengthInMillis + "\n"; - - _varControllerLogger.log(message); - System.out.println(message); - } - else - { - String message = "Unadjusted SacSmaSate data for the basin " + basinId + - " was found for time: "+ sacSmaStateTimeString; - - _varControllerLogger.log(message); - } - return sacSmaState; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public SacSmaState loadOldestUnadjSacSmaState(String basinId) - { - //String header = "VarDataMgr.loadOldestUnadjSacSmaState(): "; - - SacSmaState sacSmaState = _sshpDataMgr.loadOldestSacSmaState(basinId, - SSHPSource.UNADJUSTED_VAR.getSacSmaSource()); - - - return sacSmaState; - - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - /************************************************************************************* - * From sacsmastate table, get the SAC-SMA model unadj state whose - * latest valid time <= (var model run time - UHG length in millis per hr). - * @param basinId - * @param varModelRunTimeLong - * @return - */ - public SacSmaState loadLastAdjustedSacSmaStateAtOrBeforeATime(String basinId, long varModelRunTimeLong) - { - //String header = "VarDataMgr.loadLastAdjustedSacSmaStateBeforeATime(): "; - - long sacSmaStateTimeLong = varModelRunTimeLong; - SacSmaState sacSmaState = _sshpDataMgr.loadSacSmaState(basinId, - SSHPSource.ADJUSTED_VAR.getSacSmaSource(), - sacSmaStateTimeLong); - - - String sacSmaStateTimeString = DbTimeHelper.getDateTimeStringFromLongTime(sacSmaStateTimeLong); - System.out.println("Source: "+ SSHPSource.ADJUSTED_VAR.getSacSmaSource() + " with time = " + sacSmaStateTimeString); - - return sacSmaState; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public UnitHydrograph getUnitHydrograph(String locationId, String basinId) throws DataAbsentException - { - UnitHydrograph unitGraph = _unitHydrographMap.get(basinId); - - if (unitGraph == null) - { - unitGraph = _sshpDataMgr.loadUnitHydrograph(locationId, basinId, "SAC-SMA"); - _unitHydrographMap.put(basinId, unitGraph); - } - if(unitGraph == null) - { - _varControllerLogger.log("UnitHydrograph data for the basin " + basinId + " is not available"); - throw new DataAbsentException(); - } - return unitGraph; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /****************************************************************************************** - * Load the UnitHydrograph from database. - * @return - */ - public UnitHydrograph loadUnitHydrograph(String basinId) throws DataAbsentException - { - UnitHydrograph unitGraph = _sshpDataMgr.loadUnitHydrograph(basinId, basinId, "SAC-SMA"); - if(unitGraph == null) - { - _varControllerLogger.log("UnitHydrograph data for the basin " + basinId + " is not available"); - throw new DataAbsentException(); - } - return unitGraph; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - public RegularTimeSeries getDischargeRTSforDischargeFile(String basinId, - long startTimeLongForRTS, - long endTimeLongRTS - ) throws DataAbsentException - { - final boolean checkForMissingData = true; - return getDischargeRegularTimeSeries(basinId, startTimeLongForRTS, endTimeLongRTS, checkForMissingData); - } - - // --------------------------------------------------------------------------------------------------------- - - private IrregularTimeSeries getObservedStageTimeSeries(String locationId) - { - IrregularTimeSeries stageIrregularTimeSeries = _stageTimeSeriesMap.get(locationId); - - if (stageIrregularTimeSeries == null) - { - stageIrregularTimeSeries = _sshpDataMgr.loadObservedStageTimeSeries(locationId); - _stageTimeSeriesMap.put(locationId, stageIrregularTimeSeries); - } - return stageIrregularTimeSeries; - } - // ------------------------------------------------------------------------------------------- - private RatingCurve getRatingCurve(String locationId) - { - RatingCurve ratingCurve = _ratingCurveMap.get(locationId); - - if (ratingCurve == null) - { - ratingCurve = _sshpDataMgr.loadRatingCurve(locationId); - _ratingCurveMap.put(locationId, ratingCurve); - } - - return ratingCurve; - } - - // ------------------------------------------------------------------------------------------- - - // ------------------------------------------------------------------------------------------- - - /******************************************************************************************* - * Generate the discharge time series spanning from Var start time to Var end time. - * Load the rating curve and generate discharge data from stage data. Fill the predicted period - * (from current time plus one hour to the var end time) with value of -1. Convert the discharge data - * from unit of cfs(default) to cms for Fortran. - * @return - */ - public RegularTimeSeries getDischargeRegularTimeSeries(String locationId, - long startTimeLongForRTS, - long endTimeLongRTS, - boolean checkForMissingData) throws DataAbsentException - { - - String header = "VarDataMgr.getDischargeRegularTimeSeries(): "; - -// river stage data is measured irregularly and with unit of feet - IrregularTimeSeries stageIrregularTimeSeries = getObservedStageTimeSeries(locationId); - if(stageIrregularTimeSeries == null) - { - String message = header + "Stage time series data for the location " + locationId + " is not available"; - System.out.println(message); - _varControllerLogger.log(message); - throw new DataAbsentException(message); - } - - //Through interpolation, convert from irregular TS to regular TS and get the TS within the correct time window - - RegularTimeSeries fullStageRegularTimeSeries = VarHelper.getRegularTimeSeriesFromIrregularTimeSeries(stageIrregularTimeSeries); - RegularTimeSeries stageRegularTimeSeries = fullStageRegularTimeSeries.getSubTimeSeries(startTimeLongForRTS, endTimeLongRTS); - - - //Load the rating curve - RatingCurve rc = getRatingCurve(locationId); - if(rc == null) - { - String message = header + "Rating curve for the location " + locationId + " is not available"; - System.out.println(message); - _varControllerLogger.log(message); - throw new DataAbsentException(message); - } - - //Using rating curve to convert stage data to discharge data, and convert unit from cfs to cms - RegularTimeSeries prevDischargeRTS = rc.getDischargeRegularTimeSeries(stageRegularTimeSeries); //returned unit: cfs - - // System.out.println(header + "before conversion, prevDischargeRTS = " + prevDischargeRTS); - - prevDischargeRTS.convert(MeasuringUnit.cms); - - // System.out.println(header + "after conversion, prevDischargeRTS = " + prevDischargeRTS); - - - - //make up a dummy RTS with timing from one hour after the current time till the Var end time, with all values to be -1 - RegularTimeSeries predictDischargeRTS = new RegularTimeSeries(startTimeLongForRTS, endTimeLongRTS, 1, MeasuringUnit.cms, -1); - - // System.out.println(header + "predictDischargeRTS = " + predictDischargeRTS); - - - // RegularTimeSeries totalDischargeRTS = RegularTimeSeries.add(ts1, ts2)(prevDischargeRTS, predictDischargeRTS); - RegularTimeSeries totalDischargeRTS = RegularTimeSeries.concatenate(prevDischargeRTS, predictDischargeRTS); - -// System.out.println(header + "after concatenate(), totalDischargeRTS = " + totalDischargeRTS); - - - //check to see if the discharge RTS spans from start time to end time - - if (checkForMissingData) - { - if((totalDischargeRTS.getStartTime() != startTimeLongForRTS) || - (totalDischargeRTS.getEndTime() != endTimeLongRTS) ) - { - String message = header + "The discharge time series for the location " + locationId + " is not available from " + - DbTimeHelper.getDateTimeStringFromLongTime(startTimeLongForRTS) + " to " + - DbTimeHelper.getDateTimeStringFromLongTime(endTimeLongRTS) + "\n." + - "Instead, it goes from " + DbTimeHelper.getDateTimeStringFromLongTime(totalDischargeRTS.getStartTime()) + " to " + - DbTimeHelper.getDateTimeStringFromLongTime(totalDischargeRTS.getEndTime()) + "\n" + - "RTS stage goes from " + DbTimeHelper.getDateTimeStringFromLongTime(stageRegularTimeSeries.getStartTime()) + " to " + - DbTimeHelper.getDateTimeStringFromLongTime(stageRegularTimeSeries.getEndTime()) + "\n"; - - System.out.println(message); - _varControllerLogger.log(message); - throw new DataAbsentException(message); - } - } - - return totalDischargeRTS; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - public RegularTimeSeries getPrecipRTSforPrecipFile(String basinId, long startTimeLongForRTS, long endTimeLongRTS) throws DataAbsentException - { - return getPrecipRTSforPrecipFile(basinId, startTimeLongForRTS, endTimeLongRTS, true); - } - /*********************************************************************************************************** - * Get the precip RTS spanning from Var start time to Var end time. Convert the unit from inch (default) to mm, - * to be consistent with Fortran requirement. - * @return - */ - public RegularTimeSeries getPrecipRTSforPrecipFile(String basinId, long startTimeLongForRTS, long endTimeLongRTS, boolean checkForMissing ) throws DataAbsentException - { - String header = "VarDataMgr.getPrecipRTSforPrecipFile(): "; - RegularTimeSeries precipRTS = _precipTimeSeriesMap.get(basinId); - - if (precipRTS == null) - { - precipRTS = _sshpDataMgr.loadObsMapTimeSeriesFromDb(basinId); //in unit of inches - if (precipRTS != null) - { - precipRTS.convert(MeasuringUnit.mm); - _precipTimeSeriesMap.put(basinId, precipRTS); - } - else //precipRTS is null - { - _varControllerLogger.log("Precipitation time series data for the basin " + - basinId + " is not available"); - throw new DataAbsentException(); - } - } - - precipRTS = precipRTS.getSubTimeSeries(startTimeLongForRTS, endTimeLongRTS); //for the prediction period, filled with 0 by default - - - if (checkForMissing) - { - //check to see if the precip RTS spans from start time to end time - if((precipRTS.getStartTime() != startTimeLongForRTS) || - (precipRTS.getEndTime() != endTimeLongRTS)) - { - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(startTimeLongForRTS); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(endTimeLongRTS); - System.out.print(header + " precip desired start time = " + startTimeString + " "); - System.out.println(header + " precip desired end time = " + endTimeString); - System.out.println(header + "actual precipRTS = " + precipRTS); - - _varControllerLogger.log(header + "The precip time series for the basin " + basinId + - " is not available for " + startTimeString + " to " + endTimeString); - - _varControllerLogger.log(header + "Instead, it is available from " + - DbTimeHelper.getDateTimeStringFromLongTime(precipRTS.getStartTime()) + " to " + - DbTimeHelper.getDateTimeStringFromLongTime(precipRTS.getEndTime()) ); - - - throw new DataAbsentException(); - } - } - - return precipRTS; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /********************************************************************************************************************** - * Disconnect from database. - * - */ - public void disconnectDatabase() - { - _sshpDataMgr.disconnect(); - _varControllerLogger.log("VarDataMgr was disconnected to IHFS database"); - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - public long getUhgLengthInMillis(String locationId, String basinId) throws DataAbsentException - { - //get the uhg time in millisecs - long uhgTimeLong = DbTable.getNullLong(); - try - { - uhgTimeLong = getUnitHydrograph(locationId, basinId).getOrdinateCount() * MILLIS_PER_HOUR; - } - catch(DataAbsentException de) - { - _varControllerLogger.log("Unable to load unit hydrograph length..."); - throw new DataAbsentException(); - } - return uhgTimeLong; - - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - public boolean generateVarInputFiles(String basinId, int numOfFutureHours, - long assimilationStartTimeLong, long assimilationTargetTimeLong) - { - - String header = "VarDataMgr.generateVarInputFiles(): "; - - InputFilesGenerator inputFilesGenerator = new InputFilesGenerator(_varControllerLogger, _varInputDir, - _varOutputDir, _segmentsFilePath, - basinId, numOfFutureHours); - - inputFilesGenerator.setVarModelStartAndEndTimesLong(assimilationStartTimeLong, - assimilationTargetTimeLong); - boolean isInputGenerationSuccessful = false; - - RegularTimeSeries precipRTS = null; - RegularTimeSeries dischargeRTS = null; - - try - { - _dataLoadingTimer.restart(); - - String locationId = getLocationIdFromBasinId(basinId); - - //relatively constant stuff - String locationName = getLocationName(locationId); - MonthlyValues monthlyValues = getMonthlyValues(basinId); - - Double basinArea = getBasinArea(basinId); - - UnitHydrograph uhg = getUnitHydrograph(locationId, basinId); - - //determine if unit hydrograph is a good one - boolean isUhgGood = (uhg!= null && uhg.getMeasurementList().size() > 0); - if (! isUhgGood) - { - String message = "ERROR - basin '" + basinId + "' is missing UnitHydrograph with model = 'SAC-SMA'"; - _varControllerLogger.log(message); - throw new DataAbsentException(message); - } - - - //SAC stuff - SacSmaParameters sacSmaParams = loadSacSmaParameters(basinId, assimilationStartTimeLong); - - long uhgLengthInMillis = getUhgLengthInMillis(locationId, basinId); - SacSmaState sacSmaState = loadPrevUnadjSacSmaState(basinId, uhgLengthInMillis, assimilationTargetTimeLong); - - //time series - precipRTS = getPrecipRTSforPrecipFile(basinId, assimilationStartTimeLong, assimilationTargetTimeLong); - - - dischargeRTS = getDischargeRTSforDischargeFile(locationId, assimilationStartTimeLong, assimilationTargetTimeLong); - - _dataLoadingTimer.stop(header + " loading static data has taken "); - - if(inputFilesGenerator.generateDeckFile( locationName, sacSmaState, sacSmaParams, monthlyValues, basinArea, uhg)) - { - if(inputFilesGenerator.generateObsInputFiles(precipRTS, dischargeRTS)) - { - if(inputFilesGenerator.generateSegmentsFile()) - { - isInputGenerationSuccessful = true; - } - else - { - _varControllerLogger.log("Unable to generate segmentsFile:[" + _segmentsFilePath +"]"); - } - } - else - { - _varControllerLogger.log("Unable to generate precip file " + basinId + ".mapx_ts_var_dat"); - _varControllerLogger.log("Unable to generate discharge file " + basinId + ".qin01_ts_var_dat"); - } - } - else - { - _varControllerLogger.log("Unable to generate parameter deck file " + basinId + ".var_deck"); - } - } - catch(DataAbsentException e) - { - _varControllerLogger.log("VarDataMgr.generateVarInputFiles(): "+ e); - } - - return isInputGenerationSuccessful; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public String getLocationIdFromBasinId(String basinId) - { - - //if the cache is empty, then fill it up with data from the SSHPConfig table. - if (_basinIdToLocationIdMap.isEmpty()) - { - List configList = _sshpDataMgr.loadSSHPConfigList(""); - - for (SSHPConfig config : configList) - { - _basinIdToLocationIdMap.put(config.getBasinId(), config.getLid()); - } - } - - //get the data from the cache - String locationId = _basinIdToLocationIdMap.get(basinId); - - return locationId; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - public boolean areDischargeAndPrecipDataAvailable(RegularTimeSeries dischargeTimeSeries, RegularTimeSeries precipTimeSeries, long time) - { - boolean result = false; - - - result = ( isRegularTimeSeriesDataAvailableAtTime(dischargeTimeSeries, time, "discharge") && - isRegularTimeSeriesDataAvailableAtTime(precipTimeSeries, time, "precip") ); - - return result; - - - } - - public boolean isRegularTimeSeriesDataAvailableAtTime(RegularTimeSeries rts, long time, String dataTypeString) - { - String header = "VarDataMgr.isRegularTimeSeriesDataAvailableAtTime(): "; - - boolean result = false; - - AbsTimeMeasurement measurement = rts.getAbsTimeMeasurementByTime(time); - - if ((measurement != null) && (measurement.getValue() >= 0.0)) - { - String message = header + "available " + dataTypeString + " = " + measurement.getValue() + " at " + DbTimeHelper.getDateTimeStringFromLongTime(time) ; - _varControllerLogger.log(message); - System.out.println(message); - result = true; - } - else if (measurement != null) //value < 0.0 - { - String message = header + dataTypeString + " not available. Bogus value = " + measurement.getValue() + " at " + DbTimeHelper.getDateTimeStringFromLongTime(time) ; - _varControllerLogger.log(message); - System.out.println(message); - } - else //measurement is null - { - String message = header + dataTypeString + " not available. Measurement is null at " + DbTimeHelper.getDateTimeStringFromLongTime(time) ; - _varControllerLogger.log(message); - System.out.println(message); - - } - - return result; - } - -// ------------------------------------------------------------------------------------------------- - - public long getLatestVarSacSmaStatePostingTime() - { - //if none found, then -1 is returned - long latestPostingTime = _sshpDataMgr.getLatestVarSacSmaStatePostingTime(SSHPSource.ADJUSTED_VAR); - - return latestPostingTime; - } -// ------------------------------------------------------------------------------------------------- - public List getNewerBestQpeXmrgFileTimeList(long lastPostingTime) - { - return _sshpDataMgr.getNewerBestQpeXmrgFileTimeList(lastPostingTime); - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public List getNewerRfcXmrgFileTimeList(long lastPostingTime) - { - return _sshpDataMgr.getNewerRfcXmrgFileTimeList(lastPostingTime); - } -// ---------------------------------------------------------------------------------------------------------------------------------- - public boolean readAndSaveGeneratedResults(String basinId, long assimilationStartTimeLong, long assimilationTargetTimeLong) - { - // long basisTime = System.currentTimeMillis(); - long basisTime = assimilationTargetTimeLong; - - boolean isSaveDataSuccessful = false; - //reads the file basinId_adj_states_02_var & basinId_states_02_var and save them into - // sacsmastate, fcstdischarge tables with PRODUCT_ID "ADJRUNOFF" & "UADJRUNOFF" - String header = "VarDataMgr.saveGeneratedResults(): "; - _varControllerLogger.log("In "+ header); - int uhgOrdinateNum ; - try - { - - String locationId = getLocationIdFromBasinId(basinId); - - uhgOrdinateNum = getUnitHydrograph(locationId, basinId).getMeasurementList().size(); - - OutputFileManager outputFileManager = new OutputFileManager(_varControllerLogger, basinId, - assimilationStartTimeLong, assimilationTargetTimeLong, uhgOrdinateNum); - - boolean unadjustedSave = readAndSaveUnadjustedStateAndRunOffValues( outputFileManager, - basinId, basisTime, - assimilationStartTimeLong, assimilationTargetTimeLong ); - - boolean adjustedSave = readAndSaveAdjustedStateAndRunOffValues( outputFileManager, - basinId, basisTime, - assimilationStartTimeLong, assimilationTargetTimeLong); - - if (unadjustedSave && adjustedSave) - { - isSaveDataSuccessful = true; - } - } - catch(DataAbsentException e) - { - _varControllerLogger.log("VarDataMgr.saveGeneratedResults(): DataAbsent"+ e); - } - - //may be used when we do var with adjusted var as input - //save the adjusted SacSma parameters(peadj, pxadj) into a text file - // isSaveDataSuccessful = outputFileManager.saveSacSmaParamsFromAdjFileToParamsFile(_varOutputDir, basinId); - - return isSaveDataSuccessful; - } -//---------------------------------------------------------------------------------------------------------------------------------- - - private boolean readAndSaveStatesAndRunOffValues(OutputFileManager outputFileManager, String fileNameEndingPart, String basinId, - long basisTime, long assimilationStartTimeLong, long assimilationTargetTimeLong, SSHPSource sshpSource, boolean saveSecondValue) - { - boolean isSaveSuccess = false; - - // reads the file "basinId + fileNameEndingPart and saves some SacSmaStates and the runoff (tci) values into - // the IHFS DB tables: sacsmastate, fcstdischarge - // String header = "readAndSaveStatesAndRunOffValues(): "; - - // System.out.println(header + "Saving Var variables to database ..."); - String fileName = _varOutputDir + basinId + fileNameEndingPart; - - boolean isReadSuccess = outputFileManager.readVarOutputFileForStateAndRunoffValues(fileName); - if(isReadSuccess) - { - long postingTime = System.currentTimeMillis(); - List sacSmaStateList = outputFileManager.getSacSmaStateList(); - for(int i=0; i < sacSmaStateList.size(); i++) - { - SacSmaState sacSmaState = (SacSmaState) sacSmaStateList.get(i); - long validTimeLong = sacSmaState.getValidTime(); - - //if(validTimeLong >= assimilationStartTimeLong || validTimeLong <= assimilationTargetTimeLong) - if ( - (validTimeLong == assimilationTargetTimeLong) || - (saveSecondValue && - (validTimeLong == assimilationStartTimeLong + MILLIS_PER_HOUR) ) - ) - { - sacSmaState.setPostingTime(postingTime); - sacSmaState.setBasisTime(basisTime); - sacSmaState.setSource( sshpSource.getSacSmaSource()); - _sshpDataMgr.saveSacState(sacSmaState); - } - } - - RegularTimeSeries runOffRegularTimeSeries = outputFileManager.getRunOffRegularTimeSeries(); - - // printRunoffInfo(assimilationStartTimeLong, assimilationTargetTimeLong, runOffRegularTimeSeries); - - String locationId = getLocationIdFromBasinId(basinId); - _sshpDataMgr.saveRunoffTimeSeries(locationId, sshpSource.getTypeSource(), basisTime, - sshpSource.getProductId(), runOffRegularTimeSeries); - isSaveSuccess = true; - } - else - { - String message = "Error: unable to complete the reading of the data for " + basinId + "."; - System.out.println(message); - _varControllerLogger.log(message); - } - return isSaveSuccess; - - } -// ---------------------------------------------------------------------------------------------------------------------------------- - private void printRunoffInfo(long assimilationStartTimeLong, long assimilationTargetTimeLong, RegularTimeSeries runoffTimeSeries) - { - String assimilationStartTimeString = DbTimeHelper.getDateTimeStringFromLongTime(assimilationStartTimeLong); - String assimilationTargetTimeString = DbTimeHelper.getDateTimeStringFromLongTime(assimilationTargetTimeLong); - - System.out.println("---------------------------------------------------------------------------------------"); - System.out.println("Runoff time series info for assimilationStartTime = " + - assimilationStartTimeString + " and assimilationTargetTime = " + assimilationTargetTimeString); - - String startTimeString = DbTimeHelper.getDateTimeStringFromLongTime(runoffTimeSeries.getStartTime()); - String endTimeString = DbTimeHelper.getDateTimeStringFromLongTime(runoffTimeSeries.getEndTime()); - - System.out.println("Start time = " + startTimeString + " and end time = " + endTimeString); - System.out.println("---------------------------------------------------------------------------------------"); - - return; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - private boolean readAndSaveAdjustedStateAndRunOffValues(OutputFileManager outputFileManager, String basinId, - long basisTime, long assimilationStartTimeLong, long assimilationTargetTimeLong) - { - - return readAndSaveStatesAndRunOffValues(outputFileManager, "_adj_states_02_var", basinId, - basisTime,assimilationStartTimeLong, assimilationTargetTimeLong, SSHPSource.ADJUSTED_VAR, false); - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - private boolean readAndSaveUnadjustedStateAndRunOffValues(OutputFileManager outputFileManager, String basinId, - long basisTime,long assimilationStartTimeLong, long assimilationTargetTimeLong) - { - - return readAndSaveStatesAndRunOffValues(outputFileManager, "_states_02_var", basinId, - basisTime, assimilationStartTimeLong, assimilationTargetTimeLong, SSHPSource.UNADJUSTED_VAR, true); - } - - -// ---------------------------------------------------------------------------------------------------------------------------------- -} //close class diff --git a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarHelper.java b/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarHelper.java deleted file mode 100644 index f4d73e8eb4..0000000000 --- a/javaUtilities/hydro/ohd.var/src/ohd/hseb/sshp/var/VarHelper.java +++ /dev/null @@ -1,149 +0,0 @@ -package ohd.hseb.sshp.var; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import ohd.hseb.db.DbTimeHelper; -import ohd.hseb.measurement.RegularTimeSeries; -import ohd.hseb.measurement.IrregularTimeSeries; -import ohd.hseb.util.TimeHelper; -import ohd.hseb.measurement.AbsTimeMeasurement; - -import static ohd.hseb.util.TimeHelper.*; - -/************************************************************************************************************************************ - * A helper class for holding some commonly used constants and for providing some commonly used methods as static methods. - * @author lix - * - */ -public class VarHelper -{ - - /******************************************************************************************************************************** - * Convert any IrregularTimeSeries to RegularTimeSeries with interpolation method. - * @param irts - * @return - */ - public static RegularTimeSeries getRegularTimeSeriesFromIrregularTimeSeries(IrregularTimeSeries irts) - { - String header = "VarHelper.getRegularTimeSeriesFromIrregularTimeSeries(): "; - long startTimeHour = TimeHelper.roundTimeInMillisToNearestHour(irts.getStartTime()); //rounding to nearest hour - long endTime = irts.getEndTime(); //no need for rounding - - RegularTimeSeries rts = new RegularTimeSeries(startTimeHour, endTime, 1, irts.getMeasuringUnit()); //interval = 1 hour - - for (long t = startTimeHour; t <= endTime; t += MILLIS_PER_HOUR) - { - AbsTimeMeasurement m = irts.getAbsTimeMeasurementByTime(t, true, false); //interpolation to get missed data points - - if (m != null) - { - rts.setMeasurementByTime(m, m.getTime()); - } - else //m == null - { - System.out.println(header + "measurement not available for time = " + - DbTimeHelper.getDateTimeStringFromLongTime(t)); - System.out.println(header + "rts.startTime = " + DbTimeHelper.getDateTimeStringFromLongTime(startTimeHour) + - " rts.endTime = " + DbTimeHelper.getDateTimeStringFromLongTime(endTime)); - System.out.println(header + "irts.startTime = " + - DbTimeHelper.getDateTimeStringFromLongTime( irts.getStartTime())); - } - - } - - return rts; - } - -// ---------------------------------------------------------------------------------------------------------------------------------- - - /********************************************************************************************************************* - * Take the argument of long and computes the year, month, day and hour. Due to the postgres - * database difference with Fortran (in Postgres database, hours are count from 0 to 23, with 0 as the first hour; in Fortran, from 1 to 24), so if the - * hour is 0, it needs to be changed to 24 and the day needs to be backward by 1. - * Returns an array of String with 4 elements: year, month, day, hour - * @param long - */ - public static String[] getArrayYearMonthDayHour24HConventionFromLongTime(long longTime) - { - // Map map = new HashMap(tring.class, Integer.class); - String strHour = null; - if (VarHelper.getStringFromLongTime(longTime, "HH").equals("00")) - { - longTime -= MILLIS_PER_DAY; //roll back one day: 0AM today(Java) == 24PM yesterday(Fortran) - strHour = "24"; //VarHelper.getStringFromLongTime(longTime, "k") is buggy, don't trust it. So use hard-coded "24" - } - else //is not 0AM o'clock case - { - strHour = VarHelper.getStringFromLongTime(longTime, "H"); //no 0 padding - } - - String[] strYearMonthDayHour = {VarHelper.getStringFromLongTime(longTime, "yyyy"), - VarHelper.getStringFromLongTime(longTime, "M"), - VarHelper.getStringFromLongTime(longTime, "d"), - strHour}; //VarHelper.getStringFromLongTime(longTime, "k") k: 1-24, H: 0-23 - return strYearMonthDayHour; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - /************************************************************************************************************* - * Get a String based on the passed in parameter dateFormat. - * @param time - * @param dateFormat - * @return - */ - public static String getStringFromLongTime(long time, String dateFormat) - { - String timeString = DbTimeHelper.getStringFromLongTime(time, dateFormat); - return timeString; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - /**************************************************************************************** - * Return a long based on the passed in parameter format and the timeString. - * @param timeString - * @param format - * @return - */ - public static long getLongTimeFromDateTimeString(String timeString, String format) - { - long time = 0; - if (timeString != null) - { - Date date = VarHelper.getDateTimeFromString(timeString, format); - - time = date.getTime(); - } - return time; - } -// ---------------------------------------------------------------------------------------------------------------------------------- - - /**************************************************************************************** - * Return a Date object based on the passed in timeString and the format. - * @param timeString - * @param format - * @return - */ - public static Date getDateTimeFromString(String timeString, String format) - { - Date shiftedDate = null; - - if (timeString != null) - { - SimpleDateFormat utcSdf2 = new SimpleDateFormat(format); - utcSdf2.setTimeZone(TimeZone.getTimeZone("UTC")); - - try - { - shiftedDate = utcSdf2.parse(timeString); - } - catch(ParseException e) - { - e.printStackTrace(); - } - } - - return shiftedDate; - } -// ---------------------------------------------------------------------------------------------------------------------------------- -} //close class diff --git a/ohd/com.raytheon.uf.edex.ohd.feature/.project b/ohd/com.raytheon.uf.edex.ohd.feature/.project deleted file mode 100644 index 1f13f4bb29..0000000000 --- a/ohd/com.raytheon.uf.edex.ohd.feature/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - com.raytheon.uf.edex.ohd.feature - - - - - - org.eclipse.pde.FeatureBuilder - - - - - - org.eclipse.pde.FeatureNature - - diff --git a/ohd/com.raytheon.uf.edex.ohd.feature/build.properties b/ohd/com.raytheon.uf.edex.ohd.feature/build.properties deleted file mode 100644 index 64f93a9f0b..0000000000 --- a/ohd/com.raytheon.uf.edex.ohd.feature/build.properties +++ /dev/null @@ -1 +0,0 @@ -bin.includes = feature.xml diff --git a/ohd/com.raytheon.uf.edex.ohd.feature/com.raytheon.uf.edex.ohd.feature.ecl b/ohd/com.raytheon.uf.edex.ohd.feature/com.raytheon.uf.edex.ohd.feature.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/ohd/com.raytheon.uf.edex.ohd.feature/feature.xml b/ohd/com.raytheon.uf.edex.ohd.feature/feature.xml deleted file mode 100644 index 3039c7ec67..0000000000 --- a/ohd/com.raytheon.uf.edex.ohd.feature/feature.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - [Enter Feature Description here.] - - - - [Enter Copyright Description here.] - - - - [Enter License Description here.] - - - - - - - diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.classpath b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.classpath deleted file mode 100644 index 1fa3e6803d..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.project b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.project deleted file mode 100644 index 57453e90cd..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - gov.noaa.nws.ohd.edex.plugin.hydrodualpol - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.settings/org.eclipse.jdt.core.prefs b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 65c31fb23d..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Mon May 13 14:43:54 EDT 2013 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/META-INF/MANIFEST.MF b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/META-INF/MANIFEST.MF deleted file mode 100644 index 36c80904b0..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/META-INF/MANIFEST.MF +++ /dev/null @@ -1,24 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Hydrodualpol Plug-in -Bundle-SymbolicName: gov.noaa.nws.ohd.edex.plugin.hydrodualpol -Bundle-Version: 1.0.0.qualifier -Bundle-Vendor: RAYTHEON -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: org.geotools;bundle-version="2.6.4", - com.raytheon.edex.common;bundle-version="1.12.1174", - org.dom4j;bundle-version="1.0.0", - org.apache.commons.logging, - javax.measure;bundle-version="1.0.0", - javax.persistence;bundle-version="1.0.0", - com.raytheon.uf.common.monitor.cpg;bundle-version="1.12.1174", - com.raytheon.uf.common.status;bundle-version="1.12.1174", - com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", - com.raytheon.uf.common.localization;bundle-version="1.12.1174", - com.raytheon.uf.edex.cpgsrv;bundle-version="1.12.1174", - com.raytheon.uf.common.monitor;bundle-version="1.12.1174", - com.raytheon.edex.plugin.radar, - com.raytheon.uf.common.ohd;bundle-version="1.12.1174", - com.raytheon.uf.common.dataplugin.shef -Import-Package: com.raytheon.edex.plugin.radar, - com.raytheon.uf.edex.plugin.scan.common diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/build.properties b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/build.properties deleted file mode 100644 index 5791d48d5f..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/build.properties +++ /dev/null @@ -1,5 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - res/ diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/component-deploy.xml b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/component-deploy.xml deleted file mode 100644 index 221864b6a9..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/gov.noaa.nws.ohd.edex.plugin.hydrodualpol.ecl b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/gov.noaa.nws.ohd.edex.plugin.hydrodualpol.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/modes/hydrodualpol-modes.xml b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/modes/hydrodualpol-modes.xml deleted file mode 100644 index 38190fced7..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/modes/hydrodualpol-modes.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - hydrodualpol-ingest.xml - - - hydrodualpol-ingest.xml - - diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/res/spring/hydrodualpol-ingest.xml b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/res/spring/hydrodualpol-ingest.xml deleted file mode 100644 index 6fbf0801c2..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/res/spring/hydrodualpol-ingest.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - java.lang.Throwable - - - - - - - diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/AzimuthAndRangePoint.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/AzimuthAndRangePoint.java deleted file mode 100644 index 7e4143a4bd..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/AzimuthAndRangePoint.java +++ /dev/null @@ -1,49 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -/** - * Class to encapsulate the concept of Azimuth and Range in MPE. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * August 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - * - */ -public class AzimuthAndRangePoint -{ - - - private double _azimuth; - private double _range; - - public AzimuthAndRangePoint() - { - } - - public double getAzimuth() - { - return _azimuth; - } - public void setAzimuth(double azimuth) - { - _azimuth = azimuth; - } - - public double getRange() - { - return _range; - } - - public void setRange(double range) - { - _range = range; - } - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DAAHeaderData.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DAAHeaderData.java deleted file mode 100644 index 8c2ce9bcf2..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DAAHeaderData.java +++ /dev/null @@ -1,187 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -/** - * Class to encapsulate DAA radar product header information. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * July 2013 DCS 167    P. Tilles   Initial Creation
    - * 
    - * 
    - * - * - * @author Paul Tilles - * - */ - -public class DAAHeaderData -{ - /* - * prodDate, prodHour, ProdMin - * - */ - - private String uri; - private boolean isProductNull ; - private int coverageDur; - private float maxValh; - private float biasValue; - private String mnemonic; - private String radarId; - private short nullProductFlag; - - private int prodDate; - private int prodHour; - private int prodMin; - private String obsTime; - - - private String productGenerationTime; - //private String fileName; - - private int productObsTimeMinutes; // minutes after the hour for the product obs time; - private short minutesOffTopOfHour; // can be positive or negative - - private float scale; - private float offset; - - public void setProductObsTimeMinutes(int productObsTimeMinutes) { - this.productObsTimeMinutes = productObsTimeMinutes; - } - - public int getProductObsTimeMinutes() { - return productObsTimeMinutes; - } - - public void setCoverageDur(int coverageDur) { - this.coverageDur = coverageDur; - } - - public int getCoverageDur() { - return coverageDur; - } - - public void setMaxValh(float maxValh) { - this.maxValh = maxValh; - } - - public float getMaxValh() { - return maxValh; - } - - public void setBiasValue(float biasValue) { - this.biasValue = biasValue; - } - - public float getBiasValue() { - return biasValue; - } - - public void setMnemonic(String mnemonic) { - this.mnemonic = mnemonic; - } - - public String getMnemonic() { - return mnemonic; - } - - public void setRadarId(String radarId) { - this.radarId = radarId; - } - - public String getRadarId() { - return radarId; - } - - public void setIsProductNull(boolean isProductNull) { - this.isProductNull = isProductNull; - } - - public boolean isProductNull() { - return isProductNull; - } - - public void setNullProductFlag(short nullProductFlag) { - this.nullProductFlag = nullProductFlag; - } - - public short getNullProductFlag() { - return nullProductFlag; - } - - public void setProdDate(int prodDate) { - this.prodDate = prodDate; - } - - public int getProdDate() { - return prodDate; - } - - public void setProdHour(int prodHour) { - this.prodHour = prodHour; - } - - public int getProdHour() { - return prodHour; - } - - public void setProdMin(int prodMin) { - this.prodMin = prodMin; - } - - public int getProdMin() { - return prodMin; - } - - public void setObsTime(String obsTime) { - this.obsTime = obsTime; - } - - public String getObsTime() { - return obsTime; - } - - public void setProductGenerationTime(String productGenerationTime) { - this.productGenerationTime = productGenerationTime; - } - - public String getProductGenerationTime() { - return productGenerationTime; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getUri() { - return uri; - } - - public void setMinutesOffTopOfHour(short minutesOffTopOfHour) { - this.minutesOffTopOfHour = minutesOffTopOfHour; - } - - public short getMinutesOffTopOfHour() { - return minutesOffTopOfHour; - } - - public void setScale(float scale) { - this.scale = scale; - } - - public float getScale() { - return scale; - } - - public void setOffset(float offset) { - this.offset = offset; - } - - public float getOffset() { - return offset; - } - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DAAProductProcessor.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DAAProductProcessor.java deleted file mode 100644 index 984a633609..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DAAProductProcessor.java +++ /dev/null @@ -1,1099 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - -import com.raytheon.uf.common.dataplugin.radar.RadarRecord; -import com.raytheon.uf.common.dataplugin.radar.level3.Layer; -import com.raytheon.uf.common.dataplugin.radar.level3.SymbologyBlock; -import com.raytheon.uf.common.dataplugin.radar.level3.SymbologyPacket; -import com.raytheon.uf.common.dataplugin.radar.level3.TextSymbolPacket; -import com.raytheon.uf.common.dataplugin.shef.tables.DAARadar; -import com.raytheon.uf.common.dataplugin.shef.tables.DAARadarId; -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.edex.database.dao.CoreDao; -import com.raytheon.uf.edex.database.dao.DaoConfig; -import com.raytheon.uf.edex.database.query.DatabaseQuery; - -/** - * Class to handle DAA radar product processing for MPE. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * May 2013 DCS 167    P. Tilles   Initial Creation
    - * 
    - * 
    - * - * - * @author Paul Tilles - * - */ - - -public class DAAProductProcessor -{ - - - - private final static byte NO_DATA_FLAG = 0; - private final static float DECODED_DAA_NO_DATA_FLAG = -98.0f; - - private int decodeWindowInMinutes = 30; - private int minimumCoverageDuration = 60; - private boolean useTimeWindowFilter = false; - private String outputGridDirectory = "/tmp"; - - IUFStatusHandler statusHandler = null; - - protected Class daoClass = null; - - // --------------------------------------------------------------------- - public DAAProductProcessor() - { - this.statusHandler = null; - - // readAppsDefaults(); - - } - - public DAAProductProcessor(IUFStatusHandler statusHandler) - { - this.statusHandler = statusHandler; - - readAppsDefaults(); - - } - - // --------------------------------------------------------------------- - - private void readAppsDefaults() - { - AppsDefaults ad = AppsDefaults.getInstance(); - - decodeWindowInMinutes = ad.getInt("daa_decode_window", 5); - minimumCoverageDuration = ad.getInt("daa_min_coverage_dur", 60); - useTimeWindowFilter = ad.getBoolean("daa_filter_decode", true); - - outputGridDirectory = ad.getToken("daa_grid_dir", null); - - return; - } - - // --------------------------------------------------------------------- - - public void process(RadarRecord record) - { - DAAHeaderData headerData = new DAAHeaderData(); - boolean isProductNull = false; - - processHeader(record, headerData); - - isProductNull = headerData.isProductNull(); - - - if (isProductNull) - { - processNullProduct(record, headerData); - } - else - { - processGriddedDataProduct(record, headerData); - } - } - - // --------------------------------------------------------------------- - - private void processHeader(RadarRecord record, DAAHeaderData headerData) - { - - short nullProductFlag; - - float maxValh, biasValue; - String mnemonic, icao; - - mnemonic = record.getMnemonic(); - headerData.setMnemonic(mnemonic); - - icao = record.getIcao().substring(1); - String radid = icao.toUpperCase(); - headerData.setRadarId(radid); - - - String uri = record.getDataURI(); - headerData.setUri(uri); - - nullProductFlag = record.getProductDependentValue(2); - headerData.setNullProductFlag(nullProductFlag); - if (nullProductFlag > 0) - { - headerData.setIsProductNull(true); - } - else - { - headerData.setIsProductNull(false); - } - - - maxValh = (float)(record.getProductDependentValue(3)/10.); - headerData.setMaxValh(maxValh); - - biasValue = (float)(record.getProductDependentValue(6)/100.); - headerData.setBiasValue(biasValue); - - String obsTime = getProductObsTimeString(record, headerData); - headerData.setObsTime(obsTime); - - String productGenerationTime = getProductGenerationTimeString(record); - headerData.setProductGenerationTime(productGenerationTime); - - // scale = in A1: HW 31,32 . In A2: thresholds - 0,1 - // offset = in A1: HW 33,34 . In A2: thresholds - 2,3 - float scale = HydroNumericUtility.convertShortsToFloat(record.getThreshold(0), record.getThreshold(1)); - headerData.setScale(scale); - - float offset = HydroNumericUtility.convertShortsToFloat(record.getThreshold(2), record.getThreshold(3)); - headerData.setOffset(offset); - - return; - } - - - // --------------------------------------------------------------------- - private void processNullProduct(RadarRecord record, DAAHeaderData headerData) - { - - float maxVald = -1; - String fileName = "xxxxxxxxxxxxxxxx"; - boolean withinTOHWindow = false; - - statusHandler.handle(Priority.INFO, - "Thread id = " + Thread.currentThread().getId()); - - statusHandler.handle(Priority.INFO, "\n" + - "DAA product: uri = " + headerData.getUri()); - - statusHandler.handle(Priority.INFO, "\n" + - "DAA product: radar id = " + headerData.getRadarId() - + " null product flag = " + headerData.getNullProductFlag() - + " maxValh= " + headerData.getMaxValh() - + " biasValue = " + headerData.getBiasValue() + "\n" - + " obsTime = " + headerData.getObsTime() - + " productTime = " + headerData.getProductGenerationTime() - + " minOff = " + headerData.getMinutesOffTopOfHour()); - - if(useTimeWindowFilter) - { - withinTOHWindow = TopOfHourCheck(decodeWindowInMinutes, headerData.getObsTime(), - headerData.getMinutesOffTopOfHour()); - } - else - { - withinTOHWindow = true; - } - - if(!withinTOHWindow) - { - statusHandler.handle(Priority.INFO, " DAA product is not TOH" ); - } - else - { - String nullProductDateTimeString = processNullProductString(headerData, record); - - // compare null product date/time with end date/time (obstime) of product - // if time diff is > daa_min_coverage_dur, then set decoded product to all 0.0 - // else set decoded product to all missing - // if null product string does not have a date/time, then set decoded field to all missing - - if(nullProductDateTimeString != null) - { - //compare times - // change date/time strings to millisec and subtract - // compare result against daa_min_coverage_dur in millisec - - String obsTimeString = headerData.getObsTime(); - - long nullProductTimeInMillis = HydroTimeUtility.getMillisFromAmericanDateTimeString(nullProductDateTimeString); - long obsTimeInMillis = HydroTimeUtility.getMillisFromSQLString(obsTimeString); - long minCoverageInMillis = minimumCoverageDuration * 60 * 1000; - long millisSincePrecipDetected = obsTimeInMillis - nullProductTimeInMillis; - - int minutesSincePrecipDetected = (short) (millisSincePrecipDetected/60000); - statusHandler.handle(Priority.INFO, "\n" + - " minutesSincePrecipDetected = " + minutesSincePrecipDetected); - headerData.setCoverageDur(minutesSincePrecipDetected); - - /* - //The following commented-out code is a placeholder for future changes anticipated from - //CCR NA12-00264 which will add the reporting of the total number of minutes of operation (<=60) - //for which the product applies - - if(millisSincePrecipDetected >= minCoverageInMillis) - { - - //set decoded field to all 0.0 - } - else - { - - // set decoded field to all missing - } - */ - - } - - - /* - //See above comment about CCR NA12-00264 - - else - { - - // set decoded product to all missing - - } - */ - - // write record to the DAARadar table of the IHFS db - writeToDAARadarTable(maxVald, fileName, headerData); - } - } - - // --------------------------------------------------------------------- - - - private String processNullProductString(DAAHeaderData headerData, RadarRecord record) - { - String dateTimeString = null; - - SymbologyBlock symbologyBlock = record.getSymbologyBlock(); - - if (symbologyBlock == null) - { - // problem reading symbology block - - statusHandler.handle(Priority.INFO, - "Null Product text not found (symbology block not found."); - } - else - { - // symbology block read successfully - - for (Layer layer : symbologyBlock.getLayers()) - { - for (SymbologyPacket packet : layer.getPackets()) - { - if (packet instanceof TextSymbolPacket) - { - TextSymbolPacket textSymbolPacket = (TextSymbolPacket) packet; - - // read and print null product string - String nullProductText = textSymbolPacket.getTheText().trim(); - statusHandler.handle(Priority.INFO, nullProductText); - - // if string contains a date/time, then parse it out - if(headerData.getNullProductFlag() == 5 && !nullProductText.matches(".*RPG.*")) - { - dateTimeString = nullProductText.substring(32,nullProductText.length()-1); - statusHandler.handle(Priority.INFO, " date/time = " + dateTimeString); - - } //end if (!nullProductText.matches("RPG")) - } //end if (packet instanceof TextSymbolPacket) - } //end for (SymbologyPacket packet : layer.getPackets()) - } // end for (Layer layer : symbologyBlock.getLayers()) - - } // end if (symbologyBlock == null) - - return dateTimeString; - - } //end processNullProductString() - - // --------------------------------------------------------------------- - private String getProductObsTimeString (RadarRecord record, DAAHeaderData headerData) - { - int prodObsDate = record.getProductDependentValue(4); - - int prodObsTime = record.getProductDependentValue(5); - int prodObsHour = prodObsTime/60; - int prodObsMin = prodObsTime % 60; - - headerData.setProdDate(prodObsDate); - headerData.setProdHour(prodObsHour); - headerData.setProdMin(prodObsMin); - - headerData.setProductObsTimeMinutes(prodObsMin); - - String obsTime = - String.format("%s %02d:%02d:00", - HydroTimeUtility.JulianDateConvertToYMD(prodObsDate),prodObsHour, prodObsMin); - - // minOff = minutes off the top-of-the-hour of product - // for values > 30, minOff = (-1) * (60 - minOff) - - short minOff = (short) headerData.getProductObsTimeMinutes(); - if(minOff > 30) - { - minOff = (short) (-1 * (60 - minOff)); - } - - headerData.setMinutesOffTopOfHour(minOff); - - return obsTime; - } - // --------------------------------------------------------------------- - private String getProductGenerationTimeString (RadarRecord record) - { - // product gen date is in HW = 24 of the Product Description Block - // product gen time is in HW = 25, 26 of the PDB - - Date productGenDateTime = record.getVolScanTime(); - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String productGenerationDateTimeString = format.format(productGenDateTime); - - - return productGenerationDateTimeString; - - } - - // --------------------------------------------------------------------- - - private void processGriddedDataProduct(RadarRecord record, DAAHeaderData headerData) - { - - boolean withinTOHWindow = false; - String obsTime = headerData.getObsTime(); - short minOff = headerData.getMinutesOffTopOfHour(); - - statusHandler.handle(Priority.INFO, - "Thread id = " + Thread.currentThread().getId()); - - statusHandler.handle(Priority.INFO, "\n" + - "DAA product: uri = " + headerData.getUri()); - - statusHandler.handle(Priority.INFO, "\n" + - "DAA product: radar id = " + headerData.getRadarId() - + " null product flag = " + headerData.getNullProductFlag() - + " scale = " + headerData.getScale() - + " offset = " + headerData.getOffset() - + " maxValh= " + headerData.getMaxValh() - + " biasValue = " + headerData.getBiasValue() + "\n" - + " obsTime = " + obsTime - + " productTime = " + headerData.getProductGenerationTime() - + " minOff = " + minOff - ); - - // Check if product is within allowable window around the TOH AND - // if the current product is closer to TOH than a previous product - // deemed to be TOH - // If product is outside of window, then do not process further - - if(useTimeWindowFilter) - { - withinTOHWindow = TopOfHourCheck(decodeWindowInMinutes, obsTime, minOff); - } - else - { - withinTOHWindow = true; - } - - if(!withinTOHWindow) - { - statusHandler.handle(Priority.INFO, " DAA product is not within window around TOH" ); - } - else - { - - // Check if product is closer to TOH than a previous product - // deemed to be TOH - // If current product is closer to TOH, then process it - // Else do not process the current product - // If current product and a previous product are same number of minutes off TOH, then - // current product is considered closer and is processed - - boolean closerToTOH = CloserToTOHCheck(decodeWindowInMinutes, headerData.getRadarId(), obsTime, minOff); - //boolean closerToTOH = true; - - if(!closerToTOH) - { - statusHandler.handle(Priority.INFO, " DAA product closer to TOH already processed -- current product not processed" ); - } - else - { - - byte[] dataArray = record.getRawData(); - - if(dataArray == null) - { - statusHandler.handle(Priority.INFO, "DAA Product: ERROR --- dataArray is null"); - } - - else - { - int numlevel = record.getNumLevels(); - int numRangeBins = record.getNumBins(); - int numRadials = record.getNumRadials(); - - float lat = record.getLatitude(); - float lon = record.getLongitude(); - - float scale = headerData.getScale(); - float offset = headerData.getOffset(); - - // transform polar grid to HRAP - float[][] polarGrid = getPolarGridFromDataArray(dataArray, scale, offset, numRadials, numRangeBins); - - PolarToHRAPTransformer transformer = new PolarToHRAPTransformer(); - - float[] hrapGrid = transformer.transform250MeterPolarToFullHRAP(polarGrid, lat, lon); - - float[] dbaArray = transformer.transformHrapPrecipToDBA(hrapGrid, DECODED_DAA_NO_DATA_FLAG); - - //write DAA decoded file - - int prodDate = headerData.getProdDate(); - int prodHour = headerData.getProdHour(); - int prodMin = headerData.getProdMin(); - - String radid = headerData.getRadarId(); - - String fileName = String.format("%s%s%02d%02dZ", radid, - HydroTimeUtility.JulianDateConvertToMDY(prodDate),prodHour, prodMin); - - writeOutDataFile(record, dbaArray, fileName); - - // determine maximum precip value from hrapGrid array - // store value in maxVald variable - - float maxVald = 0; - - for (int i = 0; i < (131*131); i++) - { - if(hrapGrid[i] > maxVald) maxVald = hrapGrid[i]; - } - - // write record to the DAARadar table of the IHFS db - - long minutesSincePrecipDetected = 0; - writeToDAARadarTable(maxVald, fileName, headerData); - - } //end else dataArray != null - - } // end if(!closerToTOH) - - } // end if(!withinTOHWindow) - - } //end processGriddedDataProduct() - - //----------------------------------------------------------------- - - private boolean CloserToTOHCheck(int decodeWindowInMinutes, String radid, String obsTime, short minOff) - { - - short tohHour, afterHour, beforeHour; - String obsHourString, tohDate, afterDate, beforeDate, tohDateTime, dateTime; - - // Check if current product is closer to TOH than a previous product deemed to be TOH - // If current product is closer to TOH, then process it - // Else do not process the current product - // If current product and a previous product are same number of minutes off TOH, then - // current product is considered closer and is processed - // If current product is exactly at TOH (minoff = 0), then process it (i.e. return true) - - // This check is for decoding only (i.e. not for archive) - - // Read records from the DAARadar table to determine if previous products for current hour - // have been processed - - // if hour of current product = 0, then products from before the TOH will have previous day's date with hour = 23 - // if hour of current product = 23, then products from after the TOH will have next day's date with hour = 0 - - if (minOff == 0) - { - return true; - } - - obsHourString = obsTime.substring(11, 13); - - if(minOff > 0) - { - // determine TOH date/hour from product - // TOH date/hour = after date/hour - tohHour = Short.parseShort(obsHourString); - tohDate = obsTime.substring(0,10); - - afterHour = tohHour; - afterDate = tohDate; - - // determine before (previous) date and hour - - beforeHour = (short) (afterHour - 1); - beforeDate = afterDate; - if(beforeHour == -1) - { - - beforeHour = 23; - beforeDate = HydroTimeUtility.changeDate(afterDate, -1); - } - - } - else - { - // determine before date/hour from product and next date/hour - - beforeHour = Short.parseShort(obsHourString); - beforeDate = obsTime.substring(0,10); - - // determine after date/hour - // determine TOH date/hour - - afterHour = (short) (beforeHour + 1); - tohHour = afterHour; - afterDate = beforeDate; - - if(afterHour == 24) - { - afterHour = 0; - tohHour = 0; - afterDate = HydroTimeUtility.changeDate(beforeDate, 1); - } - - tohHour = afterHour; - tohDate = afterDate; - } - - // search DAARadar table for TOH product - // SELECT * FROM DAARadar WHERE obstime = tohDateTime - // if record exists, then return false - // else continue processing in next section of code - - tohDateTime = String.format("%s %02d:00:00", tohDate,tohHour); - - // check for an existing TOH - DAARadar radar = selectDAARadarRecord(radid, tohDateTime); - if (radar != null ) - { - //record exists, so return false - return false; - } - - // no TOH product previously processed - // search DAARadar table for records before the TOH and after the TOH and within the TOH window - // for the given radar - // compare the minoff values for each product to determine if current product is closer to the TOH - // than a previous product - // if minOff = 1, then fall through for loop and return true - - short aminOff = minOff; - if (aminOff < 0) aminOff = (short) (-1 * minOff); - - boolean selectResult = false; - - for(int i = 1; i < aminOff; i++) - { - - // check for record after TOH - dateTime = String.format("%s %02d:%02d:00", afterDate,afterHour,i); - - radar = selectDAARadarRecord(radid, dateTime); - if (radar != null ) - { - selectResult = true; - break; - } - - // check for record before TOH - int ib = 60 - i; - dateTime = String.format("%s %02d:%02d:00", beforeDate,beforeHour,ib); - - radar = selectDAARadarRecord(radid, dateTime); - if (radar != null ) - { - selectResult = true; - break; - } - - } - - boolean isCloser = true; - - //We found an existing product closer to the top of the hour than the - //product we are currently processing - if (selectResult) - { - isCloser = false; - } - - return isCloser; - } - - // --------------------------------------------------------------------- - private void writeToDAARadarTable(float maxValueFromData, String fileName, DAAHeaderData d) - { - statusHandler.handle(Priority.INFO, "\n" + - "In routine writeToDAARadarTable - before write to DAAradar table"); - - writeToDAARadarTable(d.getRadarId(), d.getObsTime(), d.getMinutesOffTopOfHour(), - d.getMaxValh(), maxValueFromData, d.getBiasValue(), d.getProductGenerationTime(), - d.getNullProductFlag(), d.getCoverageDur(), fileName); - - statusHandler.handle(Priority.INFO, "\n" + - "In routine writeToDAARadarTable - after write to DAAradar table"); - - } - // --------------------------------------------------------------------- - - private DAARadar selectDAARadarRecord(String radarId, String obsTimeString) - { - Date obstime = HydroTimeUtility.getDateFromSQLString(obsTimeString); - - return selectDAARadarRecord(radarId, obstime); - } - - // --------------------------------------------------------------------- - private DAARadar selectDAARadarRecord(String radarId, Date obstime) - { - List recordList = selectDAARadarRecordList(radarId, obstime); - - DAARadar daaRadar = null; - - if ( (recordList != null) && (recordList.size() > 0) ) - { - daaRadar = recordList.get(0); - //System.out.printf("SELECTed daaRadar object = %s\n" , daaRadar.toString()); - - } - - /* - else - { - System.out.printf("daaRadar object is null\n"); - } - */ - - return daaRadar; - } - -// ----------------------------------------------------------------------- - - private List selectDAARadarRecordList(String radarId, Date obstime) - { - List recordList = null; - - try - { - CoreDao dao = new CoreDao(DaoConfig.forDatabase("ihfs")); - - /** The class associated with this dao */ - dao.setDaoClass("com.raytheon.uf.common.dataplugin.shef.tables.DAARadar"); - DatabaseQuery query = new DatabaseQuery(dao.getDaoClass().getName()); - - //key fields from table - query.addQueryParam("id.radid", radarId); - query.addQueryParam("id.obstime", obstime); - - recordList = (List ) dao.queryByCriteria(query); - } - - catch (Exception e) - { - e.printStackTrace(); - System.out.printf("daaRadar object == null\n"); - } - - return recordList; - - } - - // --------------------------------------------------------------------- - - private boolean TopOfHourCheck(int window, String obsTime, short minOff) - { - // aminoff = abs value of minOff - short aminoff; - boolean retCode = true; - - aminoff = minOff; - if(aminoff < 0) aminoff = (short) (-1 * aminoff); - - if(aminoff <= window) - { - retCode = true; // product is within top-of-hour (TOH) window - } - else - { - retCode = false; // product not within window around TOH - } - - return retCode; - - } - - // --------------------------------------------------------------------- - - private float[][] getPolarGridFromDataArray(byte[] dataArray, float scale, float offset, int numRadials, int numRangeBins) { - - //convert 1D array to 2D polar array - //transform to precip value using scale and offset - // according to the ICD, each grid value is transformed to a precip value as - // F = (N - offset)/scale - // where F = resulting float precip value - // N = byte precip value read from the gridded data - - float[][] polarGrid = new float[numRadials][numRangeBins]; - int index = 0; - - for (int r = 0; r < numRadials; r++) - { - for (int b = 0; b < numRangeBins; b++) - { - byte byteValue = dataArray[index]; - short shortValue = (short)(byteValue & 0x00ff); - - float doubleValue = 0; - - if (shortValue == NO_DATA_FLAG) - { - doubleValue = NO_DATA_FLAG; - } - else - { - doubleValue = (shortValue - offset)/scale; - } - - polarGrid[r][b] = doubleValue; - - index++; - } //end for b (bins) - - - } //end for r (radials) - - return polarGrid; - } - - // --------------------------------------------------------------------- - - private void printNonZeroRadialInDataArray(byte[] dataArray, - int numRadials, int numRangeBins, - String fileName) - { - int index = -0; - boolean foundRadial = false; - - int nonZeroRadial = -1; - - for (int r = 0; r < numRadials; r++) - { - for (int b = 0; b < numRangeBins; b++) - { - - byte byteValue = dataArray[index]; - - if (! foundRadial) - { - if (byteValue > 0) - { - nonZeroRadial = r; - printRadial(dataArray, nonZeroRadial, numRadials, numRangeBins, fileName); - foundRadial = true; - break; - } - } - index++; - } - if (foundRadial) - { - break; - } - - } - - } - - // --------------------------------------------------------------------- - - private void printRadial(byte[] dataArray, int radialIndex, - int numRadials, int numRangeBins, - String fileName) - { - PrintWriter writer = null; - - try { - String fullPathName = "/awips2/edex/logs/" + fileName; - - writer = new PrintWriter(new File(fullPathName)); - - int index = 0; - - for (int r = 0; r < numRadials; r++) - { - if (r == radialIndex) - { - writer.print("Nonzero Radial = " + radialIndex + "\n"); - } - - for (int b = 0; b < numRangeBins; b++) - { - if (r == radialIndex) - { - byte byteValue = dataArray[index]; - short shortValue = (short)(byteValue & 0x00ff); - - writer.print(shortValue); - writer.print(" "); - } - - index++; - } - - } - } - catch (Exception e) - { - e.printStackTrace(); - } - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - - // --------------------------------------------------------------------- - - private void writeHrapGrid(double[] hrapGrid, String fileName) { - - PrintWriter writer = null; - - try { - String fullPathName = "/awips2/edex/logs/" + fileName; - - writer = new PrintWriter(new File(fullPathName)); - - int totalGridBins = 131 * 131; - - for (int i = 0; i < totalGridBins; i++) - { - Double doubleObject = hrapGrid[i]; - writer.write(doubleObject.toString() + " "); - - if (i % 131 == 0) - { - writer.write("\n"); - } - } - - writer.write("\n\n"); - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writeHrapGrid() - - // --------------------------------------------------------------------- - - private void writeDbaGrid(float[] dbaGrid, String fileName) { - - PrintWriter writer = null; - - try { - String fullPathName = "/awips2/edex/logs/" + fileName; - - writer = new PrintWriter(new File(fullPathName)); - - int totalGridBins = 131 * 131; - - for (int i = 0; i < totalGridBins; i++) - { - Float floatObject = dbaGrid[i]; - writer.write(floatObject.toString() + " "); - - if (i % 131 == 0) - { - writer.write("\n"); - } - } - - writer.write("\n\n"); - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writeDbaGrid() - - // --------------------------------------------------------------------- - - private void writePolarGrid(double[][] polarGrid, int numRadials, - int numRangeBins, String fileName) { - - PrintWriter writer = null; - - try { - String fullPathName = "/awips2/edex/logs/" + fileName; - - writer = new PrintWriter(new File(fullPathName)); - - - for (int r = 0; r < numRadials; r++) - { - for (int b = 0; b < numRangeBins; b++) - { - Double doubleObject = polarGrid[r][b]; - writer.write(doubleObject.toString() + " "); - } //end for b (bins) - writer.write("\n"); - } - writer.write("\n\n"); - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writePolarGrid() - - - // --------------------------------------------------------------------- - private void writeOutDataFile(RadarRecord record, float[] dbaArray, String fileName) - { - DataOutputStream outputStream = null; - - - //fileName is of the form RRRmmddyyyyhhmmZ - try { - - String fullPathName = outputGridDirectory + "/" + fileName; - statusHandler.handle(Priority.INFO, "\n" + " writing to file = " + fullPathName); - - FileOutputStream fileOutputStream = new FileOutputStream(fullPathName); - outputStream = new DataOutputStream(fileOutputStream); - - int hrapXMax = 131; - int hrapYMax = 131; - - int totalGridBins = hrapXMax * hrapYMax; - - for (int i = 0; i < totalGridBins; i++) - { - int intValue = HydroNumericUtility.getSwappedIntBytesFromFloat(dbaArray[i]); - - outputStream.writeInt(intValue); - } - - outputStream = null; - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (outputStream != null) - { - try { - outputStream.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - //writer.print(d) - - } - - // --------------------------------------------------------------------- - - private void writeToDAARadarTable(String radid, String obstime, short minOff, float maxValh, - float maxVald, float s1BiasValue, String productTime, short nullProductFlag, - int coverageDur, String gridFilename) - { - - //DAARadar is a PersistableDataObject - DAARadarId id = new DAARadarId(); - id.setRadid(radid); - - Date obstimeDate = HydroTimeUtility.getDateFromSQLString(obstime); - id.setObstime(obstimeDate); - - Date productTimeDate = HydroTimeUtility.getDateFromSQLString(productTime); - DAARadar radarObject = new DAARadar(id, - minOff, maxValh, maxVald, - s1BiasValue, productTimeDate, - nullProductFlag, coverageDur, - gridFilename); - try { - CoreDao dao = new CoreDao(DaoConfig.forDatabase("ihfs")); - dao.saveOrUpdate(radarObject); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - // --------------------------------------------------------------------- - -} //end DAAProductProcessor diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DPRHeaderData.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DPRHeaderData.java deleted file mode 100644 index c057c3fd1e..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DPRHeaderData.java +++ /dev/null @@ -1,183 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -/** - * Class to ecapsulate DPR radar product header data. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * May 2013 DCS 167    P. Tilles   Initial Creation
    - * 
    - * 
    - * - * - * @author Paul Tilles - * - */ - - - -public class DPRHeaderData -{ - private String uri; - private String mnemonic; - - private String radarId; - private String obsTime; - private String fileName; - - float maxVal, scale, offset; - int volumeScanDate, volumeScanTime; - short volumeCoveragePattern, operationalMode, biasValue, precipDetectedFlag; - - private int prodDate; - private int prodHour; - private int prodMin; - private int productObsTimeMinutes; // minutes after the hour for the product obs time; - - public void setMnemonic(String mnemonic) { - this.mnemonic = mnemonic; - } - - public String getMnemonic() { - return mnemonic; - } - - public void setRadarId(String radarId) { - this.radarId = radarId; - } - - public String getRadarId() { - return radarId; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getUri() { - return uri; - } - public void setMaxVal(float maxVal) { - this.maxVal = maxVal; - } - - public float getMaxVal() { - return maxVal; - } - public void setBiasValue(short biasValue) { - this.biasValue = biasValue; - } - - public short getBiasValue() { - return biasValue; - } - - public void setObsTime(String obsTime) { - this.obsTime = obsTime; - } - - public String getObsTime() { - return obsTime; - } - - public void setProdDate(int prodDate) { - this.prodDate = prodDate; - } - - public int getProdDate() { - return prodDate; - } - - public void setProdHour(int prodHour) { - this.prodHour = prodHour; - } - - public int getProdHour() { - return prodHour; - } - - public void setProdMin(int prodMin) { - this.prodMin = prodMin; - } - - public int getProdMin() { - return prodMin; - } - - public void setProductObsTimeMinutes(int productObsTimeMinutes) { - this.productObsTimeMinutes = productObsTimeMinutes; - } - - public int getProductObsTimeMinutes() { - return productObsTimeMinutes; - } - - public void setScale(float scale) { - this.scale = scale; - } - - public float getScale() { - return scale; - } - - public void setOffSet(float offset) { - this.offset = offset; - } - - public float getOffSet() { - return offset; - } - - - public void setVolumeCoveragePattern(short volumeCoveragePattern) { - this.volumeCoveragePattern = volumeCoveragePattern; - } - - public short getVolumeCoveragePattern() { - return volumeCoveragePattern; - } - - - public void setOperationalMode(short operationalMode) { - this.operationalMode = operationalMode; - } - - public short getOperationalMode() { - return operationalMode; - } - - public void setVolumeScanTime(int volumeScanTime) { - this.volumeScanTime = volumeScanTime; - } - - public int getVolumeScanTime() { - return volumeScanTime; - } - - public void setVolumeScanDate(int volumeScanDate) { - this.volumeScanDate = volumeScanDate; - } - - public int getVolumeScanDate() { - return volumeScanDate; - } - - public void setPrecipDetectedFlag(short precipDetectedFlag) { - this.precipDetectedFlag = precipDetectedFlag; - } - - public int getPrecipDetectedFlag() { - return precipDetectedFlag; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getFileName() { - return fileName; - } -} \ No newline at end of file diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DPRProductProcessor.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DPRProductProcessor.java deleted file mode 100644 index c170fad53c..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DPRProductProcessor.java +++ /dev/null @@ -1,464 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; -import java.io.DataOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; -import com.raytheon.uf.common.dataplugin.radar.RadarRecord; -import com.raytheon.uf.common.dataplugin.shef.tables.DPRRadar; -import com.raytheon.uf.common.dataplugin.shef.tables.DPRRadarId; - -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus.Priority; - -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.edex.database.dao.CoreDao; -import com.raytheon.uf.edex.database.dao.DaoConfig; - -/** - * Class to handle DPA radar product processing for MPE. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * May 2013 DCS 167    P. Tilles   Initial Creation
    - * 
    - * 
    - * - * - * @author Paul Tilles - * - */ - - - -public class DPRProductProcessor -{ - private final static byte NO_DATA_FLAG = 0; - - private String outputGridDirectory = "/tmp"; - private static final int MAX_IHRAP = PolarToQuarterHRAPTransformer.MAX_IHRAP; - private static final int MAX_JHRAP = PolarToQuarterHRAPTransformer.MAX_JHRAP; - - IUFStatusHandler statusHandler = null; - - // --------------------------------------------------------------------- - - public DPRProductProcessor(IUFStatusHandler statusHandler) - { - this.statusHandler = statusHandler; - - readAppsDefaults(); - } - - // --------------------------------------------------------------------- - - private void readAppsDefaults() - { - AppsDefaults ad = AppsDefaults.getInstance(); - - outputGridDirectory = ad.getToken("dpr_grid_dir", null); - - return; - } - - // --------------------------------------------------------------------- - - public void process(RadarRecord record) - { - DPRHeaderData headerData = new DPRHeaderData(); - - // process header portion of DPR product - // precip mode and non-precip mode products have headers - - processHeader(record, headerData); - - // if radar is in precip mode, then process gridded portion - // else grid is all 0's - - if(headerData.getPrecipDetectedFlag() == 1) - { - - // radar in precip mode - processGriddedDataProduct(record, headerData); - - } - else - { - - // radar in clear air mode - - // write record to DPRRadar table - writeToDPRRadarTable(headerData); - - // write decoded file - // precip values are all 0 - - float[][] hrapGrid = new float[MAX_IHRAP][MAX_JHRAP]; - - for(int ihrap = 0; ihrap < MAX_IHRAP; ihrap++) - { - for (int jhrap = 0; jhrap < MAX_JHRAP; jhrap++) - { - hrapGrid[ihrap][jhrap] = 0.f; - } - } - - String fileName = headerData.getFileName(); - writeOutDataFile(record, headerData, hrapGrid, fileName); - - } - - } - - // --------------------------------------------------------------------- - private void processHeader(RadarRecord record, DPRHeaderData headerData) - { - - String mnemonic = record.getMnemonic(); - headerData.setMnemonic(mnemonic); - - String icao = record.getIcao().substring(1); - String radid = icao.toUpperCase(); - headerData.setRadarId(radid); - - String uri = record.getDataURI(); - headerData.setUri(uri); - - // according to the ICD: - // high byte of halfWord30 is Precipitation Detected Flag - // low byte of halfWord30 is Gage Bias to be Applied Flag - short halfWord30 = record.getProductDependentValue(2); - short precipDetectedFlag = HydroNumericUtility.getHighOrderByte(halfWord30); - headerData.setPrecipDetectedFlag(precipDetectedFlag); - short biasAppliedFlag = HydroNumericUtility.getLowOrderByte(halfWord30); - - String obsTime = getProductObsTimeString(record, headerData); - headerData.setObsTime(obsTime); - - float maxVal = (float)(record.getProductDependentValue(3)/1000.); - headerData.setMaxVal(maxVal); - - short biasValue = (short)(record.getProductDependentValue(6)); - headerData.setBiasValue(biasValue); - - // operationalMode = 1 -- clear air mode - // = 2 -- precip mode - short operationalMode = record.getOperationalMode().shortValue(); - headerData.setOperationalMode(operationalMode); - - short volumeCoveragePattern = record.getVolumeCoveragePattern().shortValue(); - headerData.setVolumeCoveragePattern(volumeCoveragePattern); - - // scale = in A1: HW 31,32 . In A2: thresholds - 0,1 - // offset = in A1: HW 33,34 . In A2: thresholds - 2,3 - float scale = HydroNumericUtility.convertShortsToFloat(record.getThreshold(0), record.getThreshold(1)); - headerData.setScale(scale); - - float offset = HydroNumericUtility.convertShortsToFloat(record.getThreshold(2), record.getThreshold(3)); - headerData.setOffSet(offset); - - int volScanDate = record.getProductDependentValue(0); - headerData.setVolumeScanDate(volScanDate); - - int volScanTime = record.getProductDependentValue(1) * 60; - headerData.setVolumeScanTime(volScanTime); - - int prodDate = headerData.getProdDate(); - int prodHour = headerData.getProdHour(); - int prodMin = headerData.getProdMin(); - String fileName = String.format("DPR%s%s%02d%02dZ", radid, - HydroTimeUtility.JulianDateConvertToMDY(prodDate),prodHour, prodMin); - headerData.setFileName(fileName); - - statusHandler.handle(Priority.INFO, - "Thread id = " + Thread.currentThread().getId()); - - statusHandler.handle(Priority.INFO, "\n" + - "DPR product: uri = " + headerData.getUri()); - - statusHandler.handle(Priority.INFO, "\n" + - "DPR product: radar id = " + radid - + " obsTime = " + obsTime - + " volumeCoveragePattern = " + volumeCoveragePattern - + " operationalMode = " + operationalMode - + " maxVal = " + maxVal + "\n" - + " scale = " + scale - + " offset = " + offset - + " biasValue = " + biasValue + "\n" - + " volume scan date = " + volScanDate - + " volume scan time = " + volScanTime - + " precipDetectedFlag = " + precipDetectedFlag - + " biasAppliedFlag = " + biasAppliedFlag - + " fileName = " + fileName - ); - - } - - // --------------------------------------------------------------------- - - private void processGriddedDataProduct(RadarRecord record, DPRHeaderData headerData) - { - - // DAA and DSA product processing use: byte[] dataArray = record.getRawData(); - - short[] rawShortDataArray = record.getRawShortData(); - if(rawShortDataArray == null) - { - statusHandler.handle(Priority.INFO, "\nDPR Product: ERROR --- rawShortDataArray is null"); - } - else - { - - int numRangeBins = record.getNumBins(); - int numRadials = record.getNumRadials(); - - float lat = record.getLatitude(); - float lon = record.getLongitude(); - - statusHandler.handle(Priority.INFO, "\n" - + "DPR product:" - + " numbin = " + numRangeBins - + " numradial = " + numRadials - + " lat = " + lat - + " lon = " + lon - ); - - // transform polar to HRAP grid - - float scale = headerData.getScale(); - float offset = headerData.getOffSet(); - String fileName = headerData.getFileName(); - - float[][] polarGrid = getPolarGridFromDataArray(rawShortDataArray, scale, offset, numRadials, numRangeBins); - - // GridChecker checker = new GridChecker(); - // checker.writePolarGrid(polarGrid, numRadials, numRangeBins, outputGridDirectory + "/" + fileName + ".polar.txt"); - - PolarToQuarterHRAPTransformer transformer = new PolarToQuarterHRAPTransformer(statusHandler); - float[][] hrapGrid = transformer.transform250MeterPolarToQuarterHRAP(polarGrid, lat, lon); - - - - writeToDPRRadarTable(headerData); - writeOutDataFile(record, headerData, hrapGrid, fileName); - - // GridUtility checker = new GridUtility(); - // checker.writeFloatGrid(hrapGrid, MAX_IHRAP, MAX_JHRAP, outputGridDirectory + "/" + fileName + ".txt"); - } - - } - - // --------------------------------------------------------------------- - - private float[][] getPolarGridFromDataArray(short[] dataArray, float scale, float offset, int numRadials, int numRangeBins) { - - //convert 1D array to 2D polar array - //transform to precip value using scale and offset - // according to the ICD, each grid value is transformed to a precip value as - // F = (N - offset)/scale - // where F = resulting float precip value - // N = short precip value read from the gridded data - - float[][] polarGrid = new float[numRadials][numRangeBins]; - int index = 0; - - for (int r = 0; r < numRadials; r++) - { - for (int b = 0; b < numRangeBins; b++) - { - short shortValue = dataArray[index]; - - float floatValue = 0; - - if (shortValue == NO_DATA_FLAG) - { - floatValue = NO_DATA_FLAG; - } - else - { - floatValue = (shortValue - offset)/scale; - // floatValue *= 0.254f;//change units from hundredths of inches to mm - floatValue *= 25.4f;//change units from hundredths of inches to mm - } - - polarGrid[r][b] = floatValue; - - index++; - } //end for b (bins) - - - } //end for r (radials) - - return polarGrid; - } - - // --------------------------------------------------------------------- - private String getProductObsTimeString(RadarRecord record, DPRHeaderData headerData) - { - - //prodObsDate and prodObsTime for DPR products are in a different location in the - // ProductDependentValue array than the DAA products - - int prodObsDate = record.getProductDependentValue(0); - - int prodObsTime = record.getProductDependentValue(1); - int prodObsHour = prodObsTime/60; - int prodObsMin = prodObsTime % 60; - - headerData.setProdDate(prodObsDate); - headerData.setProdHour(prodObsHour); - headerData.setProdMin(prodObsMin); - headerData.setProductObsTimeMinutes(prodObsMin); - - String obsTime = - String.format("%s %02d:%02d:00", - HydroTimeUtility.JulianDateConvertToYMD(prodObsDate),prodObsHour, prodObsMin); - - //statusHandler.handle(Priority.INFO, "\n" + - // "DPR product: prodDate = " + prodObsDate - // + " prodObsTime = " + prodObsTime - // + " prodHour = " + prodObsHour - // + " prodMin = " + prodObsMin - // ); - - return obsTime; - } - - // --------------------------------------------------------------------- - private void writeToDPRRadarTable(DPRHeaderData d) - { - statusHandler.handle(Priority.INFO, "\n" + - "In routine writeToDPRRadarTable - before write to DPRradar table"); - - writeToDPRRadarTable(d.getRadarId(), d.getObsTime(), - d.volumeCoveragePattern, d.operationalMode, - d.getMaxVal(), d.getScale(), d.getOffSet(), - d.volumeScanDate, d.volumeScanTime, - d.getBiasValue(), d.precipDetectedFlag, - d.getFileName()); - - statusHandler.handle(Priority.INFO, "\n" + - "In routine writeToDPRRadarTable - after write to DPRradar table"); - - } - - // --------------------------------------------------------------------- - private void writeToDPRRadarTable(String radid, String obstime, - short volumeCoveragePattern, short operationalMode, - float maxVal, float scale, float offset, - int volumeScanDate, int volumeScanTime, - short biasValue, short precipDetectedFlag, - String filename) - { - - //DPRRadar is a PersistableDataObject - DPRRadarId id = new DPRRadarId(); - id.setRadid(radid); - - Date obstimeDate = HydroTimeUtility.getDateFromSQLString(obstime); - id.setObstime(obstimeDate); - - DPRRadar radarObject = new DPRRadar(id, - volumeCoveragePattern, operationalMode, - maxVal, scale, offset, - volumeScanDate, volumeScanTime, - biasValue, precipDetectedFlag, - filename); - - - try { - CoreDao dao = new CoreDao(DaoConfig.forDatabase("ihfs")); - dao.saveOrUpdate(radarObject); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - // --------------------------------------------------------------------- - - private void writeOutDataFile(RadarRecord record, DPRHeaderData headerData, - float[][] precipGridArray, String fileName) - { - - DataOutputStream outputStream = null; - - - //fileName is of the form DPRXXXmmddyyyyhhmmZ - - try { - - String fullPathName = outputGridDirectory + "/" + fileName; - statusHandler.handle(Priority.INFO, "\n" + " writing to file = " + fullPathName); - - FileOutputStream fileOutputStream = new FileOutputStream(fullPathName); - outputStream = new DataOutputStream(fileOutputStream); - - int hrapXMax = MAX_IHRAP; - int hrapYMax = MAX_JHRAP; - - int intValue = 0; - - // write out header portion of decoded DPR product - - int beginDate = -999; - int beginTime = -999; - int endDate = headerData.getVolumeScanDate(); - int endTime = headerData.getVolumeScanTime(); - int operationalMode = headerData.getOperationalMode(); - - outputStream.writeInt(Integer.reverseBytes(beginDate)); - outputStream.writeInt(Integer.reverseBytes(beginTime)); - outputStream.writeInt(Integer.reverseBytes(operationalMode)); - - outputStream.writeInt(Integer.reverseBytes(endDate)); - outputStream.writeInt(Integer.reverseBytes(endTime)); - outputStream.writeInt(Integer.reverseBytes(operationalMode)); - - float max = -9999f; - - // write out data portion of decoded DPR product - for (int x = 0; x < hrapXMax; x++) - { - for (int y = 0; y < hrapYMax; y++) - { - float floatValue = precipGridArray[x][y]; - intValue = HydroNumericUtility.getSwappedIntBytesFromFloat(floatValue); - outputStream.writeInt(intValue); - - if (precipGridArray[x][y] > max) - { - max = precipGridArray[x][y]; - } - } - } - - statusHandler.handle(Priority.INFO, "\n" + - "DPR product: max value = " + max); - - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (outputStream != null) - { - try { - outputStream.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - //writer.print(d) - } // end writeOutDataFile() - - -} //end class DPRProductProcessor diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DSAHeaderData.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DSAHeaderData.java deleted file mode 100644 index 325c1376e4..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DSAHeaderData.java +++ /dev/null @@ -1,226 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -/** - * Class to encapsulate DSA radar product header data. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * July 2013 DCS 167    P. Tilles   Initial Creation
    - * 
    - * 
    - * - * - * @author Paul Tilles - * - */ - - -public class DSAHeaderData -{ - private String uri; - private String mnemonic; - - private String radarId; - private String obsTime, beginTimeString, endTimeString; - private String fileName; - - private boolean isProductNull ; - - float maxVal, scale, offset; - short stormTotalStartDate, stormTotalStartTime, stormTotalEndDate, stormTotalEndTime; - short biasValue, volumeCoveragePattern, operationalMode, precipDetectedFlag, nullProductFlag; - - private int prodDate; - private int prodHour; - private int prodMin; - private int productObsTimeMinutes; // minutes after the hour for the product obs time; - - public void setMnemonic(String mnemonic) { - this.mnemonic = mnemonic; - } - - public String getMnemonic() { - return mnemonic; - } - - public void setRadarId(String radarId) { - this.radarId = radarId; - } - - public String getRadarId() { - return radarId; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getUri() { - return uri; - } - public void setMaxVal(float maxVal) { - this.maxVal = maxVal; - } - - public float getMaxVal() { - return maxVal; - } - public void setBiasValue(short biasValue) { - this.biasValue = biasValue; - } - - public short getBiasValue() { - return biasValue; - } - - public void setObsTime(String obsTime) { - this.obsTime = obsTime; - } - - public String getObsTime() { - return obsTime; - } - - public void setBeginTimeString(String beginTimeString) { - this.beginTimeString = beginTimeString; - } - - public String getBeginTimeString() { - return beginTimeString; - } - - public void setEndTimeString(String endTimeString) { - this.endTimeString = endTimeString; - } - - public String getEndTimeString() { - return endTimeString; - } - - public void setProdDate(int prodDate) { - this.prodDate = prodDate; - } - - public int getProdDate() { - return prodDate; - } - - public void setProdHour(int prodHour) { - this.prodHour = prodHour; - } - - public int getProdHour() { - return prodHour; - } - - public void setProdMin(int prodMin) { - this.prodMin = prodMin; - } - - public int getProdMin() { - return prodMin; - } - - public void setProductObsTimeMinutes(int productObsTimeMinutes) { - this.productObsTimeMinutes = productObsTimeMinutes; - } - - public int getProductObsTimeMinutes() { - return productObsTimeMinutes; - } - - public void setScale(float scale) { - this.scale = scale; - } - - public float getScale() { - return scale; - } - - public void setOffSet(float offset) { - this.offset = offset; - } - - public float getOffSet() { - return offset; - } - - - public void setVolumeCoveragePattern(short volumeCoveragePattern) { - this.volumeCoveragePattern = volumeCoveragePattern; - } - - public short getVolumeCoveragePattern() { - return volumeCoveragePattern; - } - - - public void setOperationalMode(short operationalMode) { - this.operationalMode = operationalMode; - } - - public short getOperationalMode() { - return operationalMode; - } - - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getFileName() { - return fileName; - } - - public void setIsProductNull(boolean isProductNull) { - this.isProductNull = isProductNull; - } - - public boolean isProductNull() { - return isProductNull; - } - - public void setNullProductFlag(short nullProductFlag) { - this.nullProductFlag = nullProductFlag; - } - - public short getNullProductFlag() { - return nullProductFlag; - } - - public void setStormTotalStartTime(short stormTotalStartTime) { - this.stormTotalStartTime = stormTotalStartTime; - } - - public short getStormTotalStartTime() { - return stormTotalStartTime; - } - - public void setStormTotalStartDate(short stormTotalStartDate) { - this.stormTotalStartDate = stormTotalStartDate; - } - - public short getStormTotalStartDate() { - return stormTotalStartDate; - } - - public void setStormTotalEndTime(short stormTotalEndTime) { - this.stormTotalEndTime = stormTotalEndTime; - } - - public short getStormTotalEndTime() { - return stormTotalEndTime; - } - - public void setStormTotalEndDate(short stormTotalEndDate) { - this.stormTotalEndDate = stormTotalEndDate; - } - - public short getStormTotalEndDate() { - return stormTotalEndDate; - } - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DSAProductProcessor.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DSAProductProcessor.java deleted file mode 100644 index 7c313e79b4..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/DSAProductProcessor.java +++ /dev/null @@ -1,841 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import java.io.DataOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; -import com.raytheon.uf.common.dataplugin.radar.RadarRecord; -import com.raytheon.uf.common.dataplugin.radar.level3.Layer; -import com.raytheon.uf.common.dataplugin.radar.level3.SymbologyBlock; -import com.raytheon.uf.common.dataplugin.radar.level3.SymbologyPacket; -import com.raytheon.uf.common.dataplugin.radar.level3.TextSymbolPacket; -import com.raytheon.uf.common.dataplugin.shef.tables.DSAAdapt; -import com.raytheon.uf.common.dataplugin.shef.tables.DSAAdaptId; -import com.raytheon.uf.common.dataplugin.shef.tables.DSARadar; -import com.raytheon.uf.common.dataplugin.shef.tables.DSARadarId; -import com.raytheon.uf.common.ohd.AppsDefaults; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.edex.database.dao.CoreDao; -import com.raytheon.uf.edex.database.dao.DaoConfig; - - -/** - * Class to handle DSA radar product header processing for HPE/HPN. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * July 2013 DCS 167    P. Tilles   Initial Creation
    - * 
    - * 
    - * - * - * @author Paul Tilles - * - */ - -public class DSAProductProcessor { - - private String outputGridDirectory = "/tmp"; - private static final int MAX_IHRAP = PolarToQuarterHRAPTransformer.MAX_IHRAP; - private static final int MAX_JHRAP = PolarToQuarterHRAPTransformer.MAX_JHRAP; - private static final short NO_DATA_FLAG = 0; - - IUFStatusHandler statusHandler = null; - -// --------------------------------------------------------------------- - - public DSAProductProcessor(IUFStatusHandler statusHandler) - { - this.statusHandler = statusHandler; - - readAppsDefaults(); - } - - // --------------------------------------------------------------------- - - private void readAppsDefaults() - { - AppsDefaults ad = AppsDefaults.getInstance(); - - outputGridDirectory = ad.getToken("dsa_grid_dir", null); - - return; - } - // --------------------------------------------------------------------- - - public void process(RadarRecord record) - { - DSAHeaderData headerData = new DSAHeaderData(); - boolean isProductNull = false; - - processHeader(record, headerData); - - isProductNull = headerData.isProductNull(); - - - if (isProductNull) - { - processNullProduct(record, headerData); - } - else - { - processGriddedDataProduct(record, headerData); - - } - - } - - // --------------------------------------------------------------------- - private void processNullProduct(RadarRecord record, DSAHeaderData headerData) - { - - statusHandler.handle(Priority.INFO, "\n" + - "DSA product is a null product" + "\n" - + " radar id = " + headerData.getRadarId() - + " obsTime = " + headerData.getObsTime() - + " volumeCoveragePattern = " + headerData.getVolumeCoveragePattern() - + " operationalMode = " + headerData.getOperationalMode() - + " biasValue = " + headerData.getBiasValue() - + " nullProductFlag = " + headerData.getNullProductFlag() - ); - - processNullProductString(record); - - } - - // --------------------------------------------------------------------- - private void processNullProductString(RadarRecord record) - { - SymbologyBlock symbologyBlock = record.getSymbologyBlock(); - - if (symbologyBlock == null) - { - - statusHandler.handle(Priority.INFO, - "Null Product text not found (symbology block not found."); - } - else - { - int nlayer = 0; - for (Layer layer : symbologyBlock.getLayers()) - { - int npacket = 0; - nlayer++; - for (SymbologyPacket packet : layer.getPackets()) - { - npacket++; - if (packet instanceof TextSymbolPacket) - { - TextSymbolPacket textSymbolPacket = (TextSymbolPacket) packet; - - if(nlayer == 1 && npacket ==1) - { - - // print null product string - // packet #1 in layer #1 contains the null product string - - String nullProductText = textSymbolPacket.getTheText().trim(); - statusHandler.handle(Priority.INFO, nullProductText); - - break; - } - } - } - } - } - } - - // --------------------------------------------------------------------- - - - private void processGriddedDataProduct(RadarRecord record, - DSAHeaderData headerData) - { - - statusHandler.handle(Priority.INFO, "\n" + - "DSA product: radar id = " + headerData.getRadarId() - + " obsTime = " + headerData.getObsTime() - + " volumeCoveragePattern = " + headerData.getVolumeCoveragePattern() - + " operationalMode = " + headerData.getOperationalMode() - + "\n" - + " maxVal = " + headerData.getMaxVal() - + " scale = " + headerData.getScale() - + " offset = " + headerData.getOffSet() - + "\n" - + " begin_time = " + headerData.getBeginTimeString() - + " end_time = " + headerData.getEndTimeString() - + " j_beg_date = " + headerData.getStormTotalStartDate() - + " j_beg_time = " + headerData.getStormTotalStartTime() - + " j_end_date = " + headerData.getStormTotalEndDate() - + " j_end_time = " + headerData.getStormTotalEndTime() - + "\n" - + " biasValue = " + headerData.getBiasValue() - + " nullProductFlag = " + headerData.getNullProductFlag() - + " fileName = " + headerData.getFileName() - ); - - byte[] dataArray = record.getRawData(); - - if(dataArray == null) - { - statusHandler.handle(Priority.INFO, "DSA Product: ERROR --- dataArray is null"); - } - - else - { - //int numlevel = record.getNumLevels(); - int numRangeBins = record.getNumBins(); - int numRadials = record.getNumRadials(); - - float lat = record.getLatitude(); - float lon = record.getLongitude(); - - float scale = headerData.getScale(); - float offset = headerData.getOffSet(); - - //statusHandler.handle(Priority.INFO, "\n" - // + "DSA product:" - // + " numbin = " + numRangeBins - // + " numradial = " + numRadials - // + " lat = " + lat - // + " lon = " + lon - //); - - // transform polar grid to HRAP - - float[][] polarGrid = getPolarGridFromDataArray(dataArray, scale, offset, numRadials, numRangeBins); - - PolarToQuarterHRAPTransformer transformer = new PolarToQuarterHRAPTransformer(statusHandler); - float[][] hrapGrid = transformer.transform250MeterPolarToQuarterHRAP(polarGrid, lat, lon); - - - writeToDSARadarTable(headerData); - - writeOutDataFile(record, headerData, hrapGrid, headerData.getFileName()); - - // process adaptable parameters and write to DSAAdapt table - - String radid = headerData.getRadarId(); - String obstime = headerData.getObsTime(); - processAdaptableParameters(record, radid, obstime); - - } - - } - - //---------------------------------------------------------- - - private void processAdaptableParameters(RadarRecord record, String radid, String obstime) - { - - SymbologyBlock symbologyBlock = record.getSymbologyBlock(); - - if (symbologyBlock == null) - { - - statusHandler.handle(Priority.INFO, "symbology block not found."); - } - else - { - - String [] productText = new String [4]; - - // layer #1 has 0 packets - // in layer #2, packets 1-4 contain the adaptable parameters text - - int nlayer = 0; - int nstring = 0; - for (Layer layer : symbologyBlock.getLayers()) - { - int npacket = 0; - nlayer++; - for (SymbologyPacket packet : layer.getPackets()) - { - npacket++; - if (packet instanceof TextSymbolPacket) - { - TextSymbolPacket textSymbolPacket = (TextSymbolPacket) packet; - - //statusHandler.handle(Priority.INFO, "\n" + - // "nlayer = " + nlayer + - // " npacket = " + npacket - //); - - // print text - - productText[nstring] = textSymbolPacket.getTheText().trim(); - statusHandler.handle(Priority.INFO, productText[nstring]); - nstring++; - - if(nlayer == 2 && npacket == 4) break; - - } // end if (packet instanceof TextSymbolPacket) - } // end for (SymbologyPacket packet : layer.getPackets()) - } // end for (Layer layer : symbologyBlock.getLayers()) - - // parse 4 strings to get the adaptable parameters - - // parse string 1 - //statusHandler.handle(Priority.INFO, "\n" + "orig string 1 = " + productText[0]); - String productText0 = productText[0].replace("ADAP(", ""); - //statusHandler.handle(Priority.INFO, "\n" + "new string 1 = " + productText0); - - //"+" indicates that consecutive delimiters be treated as one - String [] valuesFromString1 = productText0.split("[ )]+"); - //for (int i = 0; i < valuesFromString1.length; i++) - //{ - // statusHandler.handle(Priority.INFO,valuesFromString1[i]); - //} - - // parse string 2 - //statusHandler.handle(Priority.INFO, "\n" + "string 2 = " + productText[1]); - String [] valuesFromString2 = productText[1].split("[ ]+"); - //for (int i = 0; i < valuesFromString2.length; i++) - //{ - // statusHandler.handle(Priority.INFO,valuesFromString2[i]); - //} - - // parse string 3 - //statusHandler.handle(Priority.INFO, "\n" + "string 3 = " + productText[2]); - String [] valuesFromString3 = productText[2].split("[ ]+"); - //for (int i = 0; i < valuesFromString3.length; i++) - //{ - // statusHandler.handle(Priority.INFO,valuesFromString3[i]); - //} - - // parse string 4 - //statusHandler.handle(Priority.INFO, "\n" + "orig string 4 = " + productText[3]); - - int index = productText[3].indexOf("SUPL"); - String productText3 = productText[3].substring(0, index); - //statusHandler.handle(Priority.INFO, "\n" + "new string 4 = " + productText3); - - String [] valuesFromString4 = productText3.split("[ ]+"); - //for (int i = 0; i < valuesFromString4.length; i++) - //{ - // statusHandler.handle(Priority.INFO,valuesFromString4[i]); - //} - - // process DSA adaptable parameters from strings into proper types - // write adaptable parameter values to DSAAdapt table - - processDSAAdaptParameters(radid, obstime, valuesFromString1, valuesFromString2, valuesFromString3, valuesFromString4 ); - - - } // end if (symbologyBlock == null) - } - - //------------------------------------------------------------------------------- - - private void processDSAAdaptParameters(String radid, String obstime, String [] stringArray1, String [] stringArray2, String [] stringArray3, String [] stringArray4) - { - - /* - statusHandler.handle(Priority.INFO, " In function processDSAAdaptParameters"); - for (int i = 0; i < stringArray1.length; i++) - { - statusHandler.handle(Priority.INFO,stringArray1[i]); - } - - for (int i = 0; i < stringArray2.length; i++) - { - statusHandler.handle(Priority.INFO,stringArray2[i]); - } - - for (int i = 0; i < stringArray3.length; i++) - { - statusHandler.handle(Priority.INFO,stringArray3[i]); - } - - for (int i = 0; i < stringArray4.length; i++) - { - statusHandler.handle(Priority.INFO,stringArray4[i]); - } - */ - - // process string arrays into individual values - Short numOfAdap = Short.valueOf(stringArray1[0]); - Float defaultMLDepth = Float.valueOf(stringArray1[1]); - String mlOverideFlag = stringArray1[2]; - Float kdpMult = Float.valueOf(stringArray1[3]); - Float kdpPower = Float.valueOf(stringArray1[4]); - Float zrMult = Float.valueOf(stringArray1[5]); - Float zrPower = Float.valueOf(stringArray1[6]); - Float zdrzMult = Float.valueOf(stringArray1[7]); - Float zdrzPower = Float.valueOf(stringArray1[8]); - Float zdrzdrPower = Float.valueOf(stringArray1[9]); - - Float minCorrPrecip = Float.valueOf(stringArray2[0]); - Float minCorrKDP = Float.valueOf(stringArray2[1]); - Float reflMax = Float.valueOf(stringArray2[2]); - Float kdpMaxBeamBlk = Float.valueOf(stringArray2[3]); - float maxUsabilityBlk = 0.f; // equals "N/A" in product (stringArray2[4]) - Float kdpMinUsageRate = Float.valueOf(stringArray2[5]); - Float wsMult = Float.valueOf(stringArray2[6]); - Float grMult = Float.valueOf(stringArray2[7]); - Float rhMult = Float.valueOf(stringArray2[8]); - Float dsMult = Float.valueOf(stringArray2[9]); - - Float icMult = Float.valueOf(stringArray3[0]); - Float gridIsFull = Float.valueOf(stringArray3[1]); - Float paifRate = Float.valueOf(stringArray3[2]); - Float paifArea = Float.valueOf(stringArray3[3]); - Float rainTimeThresh = Float.valueOf(stringArray3[4]); - Float numZones = Float.valueOf(stringArray3[5]); - Float maxPrecipRate = Float.valueOf(stringArray3[6]); - // skip stringArray3[7], stringArray3[8], stringArray3[9] - - Float restartTime = Float.valueOf(stringArray4[0]); - Float maxInterpTime = Float.valueOf(stringArray4[1]); - Float maxHourlyAcc = Float.valueOf(stringArray4[2]); - Float timeBias = Float.valueOf(stringArray4[3]); - Float numGRPairs = Float.valueOf(stringArray4[4]); - Float resetBias = Float.valueOf(stringArray4[5]); - Float longstLag = Float.valueOf(stringArray4[6]); - - // write record to DSAAdapt table - statusHandler.handle(Priority.INFO, " Before write to DSAAdapt table"); - - writeToDSAAdapt(radid, obstime, - numOfAdap, defaultMLDepth, mlOverideFlag, - kdpMult, kdpPower, zrMult, zrPower, - zdrzMult, zdrzPower, zdrzdrPower, - minCorrPrecip, minCorrKDP, reflMax, kdpMaxBeamBlk, - maxUsabilityBlk, kdpMinUsageRate, - wsMult, grMult, rhMult, dsMult, icMult, - gridIsFull, paifRate, paifArea, rainTimeThresh, - numZones, maxPrecipRate, restartTime, - maxInterpTime, maxHourlyAcc, timeBias, - numGRPairs, resetBias, longstLag); - - statusHandler.handle(Priority.INFO, " After write to DSAAdapt table"); - } - - //--------------------------------------------------------------------------- - - private void writeToDSAAdapt(String radid, String obstime, - short num_of_adap, float default_ml_depth, String ml_overide_flag, - float kdp_mult, float kdp_power, float z_r_mult, float z_r_power, - float zdr_z_mult, float zdr_z_power, float zdr_zdr_power, - float min_corr_precip, float min_corr_kdp, - float refl_max, float kdp_max_beam_blk, - float max_usability_blk, float kdp_min_usage_rate, - float ws_mult, float gr_mult, - float rh_mult, float ds_mult, float ic_mult, - float grid_is_full, float paif_rate, float paif_area, - float rain_time_thresh, - float num_zones, float max_precip_rate, float restart_time, - float max_interp_time, float max_hourly_acc, float time_bias, - float num_grpairs, float reset_bias, float longst_lag) - { - - /* - statusHandler.handle(Priority.INFO, " In function writeToDSAAdapt"); - statusHandler.handle(Priority.INFO, "\n" + "radid = " + radid); - statusHandler.handle(Priority.INFO, "\n" + "obstime = " + obstime); - statusHandler.handle(Priority.INFO, "\n" + num_of_adap); - statusHandler.handle(Priority.INFO, "\n" + default_ml_depth); - statusHandler.handle(Priority.INFO, "\n" + ml_overide_flag); - statusHandler.handle(Priority.INFO, "\n" + kdp_mult); - statusHandler.handle(Priority.INFO, "\n" + kdp_power); - statusHandler.handle(Priority.INFO, "\n" + z_r_mult); - statusHandler.handle(Priority.INFO, "\n" + z_r_power); - statusHandler.handle(Priority.INFO, "\n" + zdr_z_mult); - statusHandler.handle(Priority.INFO, "\n" + zdr_z_power); - statusHandler.handle(Priority.INFO, "\n" + zdr_zdr_power); - statusHandler.handle(Priority.INFO, "\n" + min_corr_precip); - statusHandler.handle(Priority.INFO, "\n" + min_corr_kdp); - statusHandler.handle(Priority.INFO, "\n" + refl_max); - statusHandler.handle(Priority.INFO, "\n" + kdp_max_beam_blk); - statusHandler.handle(Priority.INFO, "\n" + max_usability_blk); - statusHandler.handle(Priority.INFO, "\n" + kdp_min_usage_rate); - statusHandler.handle(Priority.INFO, "\n" + ws_mult); - statusHandler.handle(Priority.INFO, "\n" + gr_mult); - statusHandler.handle(Priority.INFO, "\n" + rh_mult); - statusHandler.handle(Priority.INFO, "\n" + ds_mult); - statusHandler.handle(Priority.INFO, "\n" + ic_mult); - statusHandler.handle(Priority.INFO, "\n" + grid_is_full); - statusHandler.handle(Priority.INFO, "\n" + paif_rate); - statusHandler.handle(Priority.INFO, "\n" + paif_area); - statusHandler.handle(Priority.INFO, "\n" + rain_time_thresh); - statusHandler.handle(Priority.INFO, "\n" + num_zones); - statusHandler.handle(Priority.INFO, "\n" + max_precip_rate); - statusHandler.handle(Priority.INFO, "\n" + restart_time); - statusHandler.handle(Priority.INFO, "\n" + max_interp_time); - statusHandler.handle(Priority.INFO, "\n" + max_hourly_acc); - statusHandler.handle(Priority.INFO, "\n" + time_bias); - statusHandler.handle(Priority.INFO, "\n" + num_grpairs); - statusHandler.handle(Priority.INFO, "\n" + reset_bias); - statusHandler.handle(Priority.INFO, "\n" + longst_lag); - */ - - DSAAdaptId id = new DSAAdaptId(); - id.setRadid(radid); - - Date obstimeDate = HydroTimeUtility.getDateFromSQLString(obstime); - id.setObstime(obstimeDate); - - //DSAAdapt is a PersistableDataObject - DSAAdapt radarObject = new DSAAdapt(id, - num_of_adap, default_ml_depth, ml_overide_flag, - kdp_mult, kdp_power, z_r_mult, z_r_power, - zdr_z_mult, zdr_z_power, zdr_zdr_power, - min_corr_precip, min_corr_kdp, - refl_max, kdp_max_beam_blk, - max_usability_blk, kdp_min_usage_rate, - ws_mult, gr_mult, - rh_mult, ds_mult, ic_mult, - grid_is_full, paif_rate, paif_area, - rain_time_thresh, - num_zones, max_precip_rate, restart_time, - max_interp_time, max_hourly_acc, time_bias, - num_grpairs, reset_bias, longst_lag - ); - - - try { - CoreDao dao = new CoreDao(DaoConfig.forDatabase("ihfs")); - dao.saveOrUpdate(radarObject); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - // --------------------------------------------------------------------- - private float[][] getPolarGridFromDataArray(byte[] dataArray, float scale, float offset, int numRadials, int numRangeBins) { - - //convert 1D array to 2D polar array - //transform to precip value using scale and offset - // according to the ICD, each grid value is transformed to a precip value as - // F = (N - offset)/scale - // where F = resulting float precip value - // N = short precip value read from the gridded data - - float[][] polarGrid = new float[numRadials][numRangeBins]; - int index = 0; - - for (int r = 0; r < numRadials; r++) - { - for (int b = 0; b < numRangeBins; b++) - { - byte byteValue = dataArray[index]; - - float floatValue = 0; - - if (byteValue == NO_DATA_FLAG) - { - floatValue = NO_DATA_FLAG; - } - else - { - floatValue = (byteValue - offset)/scale; - floatValue *= 0.254f;//change units from hundredths of inches to mm - } - - polarGrid[r][b] = floatValue; - - index++; - } //end for b (bins) - - - } //end for r (radials) - - return polarGrid; - } - - // --------------------------------------------------------------------- - - - private String getProductObsTimeString(RadarRecord record, DSAHeaderData headerData) - { - - //prodObsDate and prodObsTime for DSA products are in a different location in the - // ProductDependentValue array than the DAA products - - //The obstime for DSA is same as StormTotalEndTime - - - int prodObsDate = record.getProductDependentValue(4); - - int prodObsTime = record.getProductDependentValue(5); - int prodObsHour = prodObsTime/60; - int prodObsMin = prodObsTime % 60; - - headerData.setProdDate(prodObsDate); - headerData.setProdHour(prodObsHour); - headerData.setProdMin(prodObsMin); - headerData.setProductObsTimeMinutes(prodObsMin); - - String obsTime = - String.format("%s %02d:%02d:00", - HydroTimeUtility.JulianDateConvertToYMD(prodObsDate),prodObsHour, prodObsMin); - - return obsTime; - } - - // --------------------------------------------------------------------- - private String getStormTotalBeginTimeString(RadarRecord record, DSAHeaderData headerData) - { - - int beginDate = record.getProductDependentValue(0); - - int beginTime = record.getProductDependentValue(1); - int beginHour = beginTime/60; - int beginMin = beginTime % 60; - - String stormTotalBeginTime = - String.format("%s %02d:%02d:00", - HydroTimeUtility.JulianDateConvertToYMD(beginDate),beginHour, beginMin); - - return stormTotalBeginTime; - } - // --------------------------------------------------------------------- - - private String getStormTotalEndTimeString(RadarRecord record, DSAHeaderData headerData) - { - - int endDate = record.getProductDependentValue(4); - - int endTime = record.getProductDependentValue(5); - int endHour = endTime/60; - int endMin = endTime % 60; - - String stormTotalEndTime = - String.format("%s %02d:%02d:00", - HydroTimeUtility.JulianDateConvertToYMD(endDate), endHour, endMin); - - return stormTotalEndTime; - } - // --------------------------------------------------------------------- - - private void processHeader(RadarRecord record, DSAHeaderData headerData) - { - - String mnemonic = record.getMnemonic(); - headerData.setMnemonic(mnemonic); - - String icao = record.getIcao().substring(1); - String radid = icao.toUpperCase(); - headerData.setRadarId(radid); - - String uri = record.getDataURI(); - headerData.setUri(uri); - - String obsTime = getProductObsTimeString(record, headerData); - headerData.setObsTime(obsTime); - - String beginTimeString = getStormTotalBeginTimeString(record, headerData); - headerData.setBeginTimeString(beginTimeString); - - String endTimeString = getStormTotalEndTimeString(record, headerData); - headerData.setEndTimeString(endTimeString); - - float maxVal = (float)(record.getProductDependentValue(3)/1000.); - headerData.setMaxVal(maxVal); - - short biasValue = (short)(record.getProductDependentValue(6)); - headerData.setBiasValue(biasValue); - - // operationalMode = 1 -- clear air mode - // = 2 -- precip mode - short operationalMode = record.getOperationalMode().shortValue(); - headerData.setOperationalMode(operationalMode); - - short volumeCoveragePattern = record.getVolumeCoveragePattern().shortValue(); - headerData.setVolumeCoveragePattern(volumeCoveragePattern); - - short nullProductFlag = record.getProductDependentValue(2); - headerData.setNullProductFlag(nullProductFlag); - if (nullProductFlag > 0) - { - headerData.setIsProductNull(true); - } - else - { - headerData.setIsProductNull(false); - } - - // scale = in A1: HW 31,32 . In A2: thresholds - 0,1 - // offset = in A1: HW 33,34 . In A2: thresholds - 2,3 - float scale = HydroNumericUtility.convertShortsToFloat(record.getThreshold(0), record.getThreshold(1)); - headerData.setScale(scale); - - float offset = HydroNumericUtility.convertShortsToFloat(record.getThreshold(2), record.getThreshold(3)); - headerData.setOffSet(offset); - - short stormTotalStartDate = record.getProductDependentValue(0); - headerData.setStormTotalStartDate(stormTotalStartDate); - - short stormTotalStartTime = record.getProductDependentValue(1); - headerData.setStormTotalStartTime(stormTotalStartTime); - - short stormTotalEndDate = record.getProductDependentValue(4); - headerData.setStormTotalEndDate(stormTotalEndDate); - - short stormTotalEndTime = record.getProductDependentValue(5); - headerData.setStormTotalEndTime(stormTotalEndTime); - - int prodDate = headerData.getProdDate(); - int prodHour = headerData.getProdHour(); - int prodMin = headerData.getProdMin(); - String fileName = String.format("DSA%s%s%02d%02dZ", radid, - HydroTimeUtility.JulianDateConvertToMDY(prodDate),prodHour, prodMin); - headerData.setFileName(fileName); - - statusHandler.handle(Priority.INFO, - "Thread id = " + Thread.currentThread().getId()); - - statusHandler.handle(Priority.INFO, "\n" + - "DSA product: uri = " + headerData.getUri()); - - } - - // --------------------------------------------------------------------- - - private void writeOutDataFile(RadarRecord record, DSAHeaderData headerData, - float[][] precipGridArray, String fileName) - { - //fileName is of the form DSAXXXmmddyyyyhhmmZ - - DataOutputStream outputStream = null; - - try { - - String fullPathName = outputGridDirectory + "/" + fileName; - statusHandler.handle(Priority.INFO, "\n" + " writing to file = " + fullPathName); - - FileOutputStream fileOutputStream = new FileOutputStream(fullPathName); - outputStream = new DataOutputStream(fileOutputStream); - - int hrapXMax = MAX_IHRAP; - int hrapYMax = MAX_JHRAP; - - int intValue = 0; - - // write out header portion of decoded DSA product - short beginDate = headerData.getStormTotalStartDate(); - short beginTime = headerData.getStormTotalStartTime(); - short endDate = headerData.getStormTotalEndDate(); - short endTime = headerData.getStormTotalEndTime(); - short operationalMode = headerData.getOperationalMode(); - - outputStream.writeShort(Short.reverseBytes(beginDate)); - outputStream.writeShort(Short.reverseBytes(beginTime)); - outputStream.writeShort(Short.reverseBytes(operationalMode)); - - outputStream.writeShort(Short.reverseBytes(endDate)); - outputStream.writeShort(Short.reverseBytes(endTime)); - outputStream.writeShort(Short.reverseBytes(operationalMode)); - - float max = -9999f; - - // write out data portion of decoded DSA product - for (int x = 0; x < hrapXMax; x++) - { - for (int y = 0; y < hrapYMax; y++) - { - float floatValue = precipGridArray[x][y]; - intValue = HydroNumericUtility.getSwappedIntBytesFromFloat(floatValue); - outputStream.writeInt(intValue); - - if (precipGridArray[x][y] > max) - { - max = precipGridArray[x][y]; - } - } - } - - statusHandler.handle(Priority.INFO, "\n" + - "DSA product: max value = " + max); - - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (outputStream != null) - { - try { - outputStream.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - //writer.print(d) - } // end writeOutDataFile() - - // --------------------------------------------------------------------- - - private void writeToDSARadarTable(DSAHeaderData d) - { - statusHandler.handle(Priority.INFO, "\n" + - "In routine writeToDSARadarTable - before write to DSARadar table"); - - writeToDSARadarTable(d.getRadarId(), d.getObsTime(), - d.volumeCoveragePattern, d.operationalMode, - d.getMaxVal(), d.getScale(), d.getOffSet(), - d.getBeginTimeString(), d.getEndTimeString(), - d.getStormTotalStartDate(), d.getStormTotalStartTime(), - d.getStormTotalEndDate(), d.getStormTotalEndTime(), - d.getBiasValue(), d.getNullProductFlag(), - d.getFileName()); - - statusHandler.handle(Priority.INFO, "\n" + - "In routine writeToDSARadarTable - after write to DSARadar table"); - - } - - // --------------------------------------------------------------------- - private void writeToDSARadarTable(String radid, String obstime, - short volumeCoveragePattern, short operationalMode, - float maxVal, float scale, float offset, - String beginTime, String endTime, - short jBeginDate, short jBeginTime, - short jEndDate, short jEndTime, - short biasValue, short nullProductFlag, - String filename) - { - DSARadarId id = new DSARadarId(); - id.setRadid(radid); - - Date obstimeDate = HydroTimeUtility.getDateFromSQLString(obstime); - id.setObstime(obstimeDate); - - Date beginTimeDate = HydroTimeUtility.getDateFromSQLString(beginTime); - - Date endTimeDate = HydroTimeUtility.getDateFromSQLString(endTime); - - //DSARadar is a PersistableDataObject - DSARadar radarObject = new DSARadar(id, - volumeCoveragePattern, operationalMode, - maxVal, scale, offset, - beginTimeDate, endTimeDate, - jBeginDate, jBeginTime, jEndDate, jEndTime, - biasValue, nullProductFlag, - filename); - - - try { - CoreDao dao = new CoreDao(DaoConfig.forDatabase("ihfs")); - dao.saveOrUpdate(radarObject); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - // --------------------------------------------------------------------- - - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/GridUtility.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/GridUtility.java deleted file mode 100644 index aac7c7bb7f..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/GridUtility.java +++ /dev/null @@ -1,483 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; - - -/** - * Class to handle some grid functionality for MPE- and HPE/HPN- related grid processing. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * July 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - -public class GridUtility { - - - private static final float MIN_VALUE = 0.0001f; - - // ------------------------------------------------------------------------------- - public GridUtility() - { - - } - - // ------------------------------------------------------------------------------- - public void writeIntegerGrid(int[][] grid, int maxI, int maxJ, String pathName) - { - PrintWriter writer = null; - try - { - writer = new PrintWriter(new File(pathName)); - - - for (int i = 0; i < maxI; i++) - { - for (int j = 0; j < maxJ; j++) - { - int value = grid[i][j]; - writer.write(value + " "); - } //end for j - writer.write("\n"); - } //end for i - - writer.write("\n\n"); - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writeGrid() - - // ------------------------------------------------------------------------------- - public void writeFloatGrid(float[][] grid, int maxI, int maxJ, String pathName) - { - - PrintWriter writer = null; - - try { - - writer = new PrintWriter(new File(pathName)); - - - for (int i = 0; i < maxI; i++) - { - for (int j = 0; j < maxJ; j++) - { - float value = grid[i][j]; - String valueString = String.format("%02.0f ", value); - writer.write(valueString); - } //end for j - writer.write("\n"); - } //end for i - - writer.write("\n\n"); - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writeGrid() - - // ------------------------------------------------------------------------------- - public boolean compareGridFiles(String gridFileName1, String gridFileName2, String outputFileName) - { - QuarterHrapGrid grid1 = readGridFromFile(gridFileName1); - QuarterHrapGrid grid2 = readGridFromFile(gridFileName2); - - QuarterHrapGrid differenceGrid = computeDifferenceGrid(grid1, grid2); - - float grid1Max = grid1.getMaxValue(); - float grid2Max = grid2.getMaxValue(); - - System.out.printf("grid1 Max = %f grid2 Max = %f\n", grid1Max, grid2Max); - - writeTextGridFile(differenceGrid, outputFileName); - - boolean showShapeOnly = false; - - writeTextGridFile(grid1, gridFileName1 + ".txt", showShapeOnly); - writeTextGridFile(grid2, gridFileName2 + ".txt", showShapeOnly); - - - showShapeOnly = true; - - writeTextGridFile(grid1, gridFileName1 + ".shape.txt", showShapeOnly); - writeTextGridFile(grid2, gridFileName2 + ".shape.txt", showShapeOnly); - - - boolean same = differenceGrid.containsAllZeroes(); - - return same; - - } - - // ------------------------------------------------------------------------------- - public void writePolarGrid(float[][] polarGrid, int numRadials, - int numRangeBins, String pathName) { - - PrintWriter writer = null; - - try { - - writer = new PrintWriter(new File(pathName)); - - - for (int r = 0; r < numRadials; r++) - { - for (int b = 0; b < numRangeBins; b++) - { - Float floatObject = polarGrid[r][b]; - writer.write(floatObject.toString() + " "); - } //end for b (bins) - writer.write("\n"); - } - writer.write("\n\n"); - - } catch (Exception e) { - - e.printStackTrace(); - } - - finally - { - if (writer != null) - { - try { - writer.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writePolarGrid() - - // ------------------------------------------------------------------------------- - public QuarterHrapGrid readGridFromFile(String gridFileName1) - { - - QuarterHrapGrid grid = new QuarterHrapGrid(); - - try - { - FileInputStream fis = new FileInputStream(gridFileName1); - DataInputStream dis = new DataInputStream(fis); - - readHeader(dis, grid); - - readGrid(dis, grid); - } - catch (Exception e) { - // TODO: handle exception - } - - - return grid; - - } - - // ------------------------------------------------------------------------------- - private void readHeader(DataInputStream dis, QuarterHrapGrid grid) throws IOException - { - - //header items - for (int h = 0; h < QuarterHrapGrid.HEADER_ITEM_COUNT; h++) - { - int value = dis.readInt(); - int swappedValue = Integer.reverseBytes(value); - grid.setHeaderInfo(swappedValue, h); - } - - } - - // ------------------------------------------------------------------------------- - private void readGrid(DataInputStream dis, QuarterHrapGrid grid) throws IOException - { - for (int i = 0; i < QuarterHrapGrid.QTR_HRAP_X; i++) - { - for (int j = 0; j < QuarterHrapGrid.QTR_HRAP_Y; j++) - { - //float value = dis.readFloat(); - //grid.setValue(value, i, j); - - int value = dis.readInt(); - int swappedValue = Integer.reverseBytes(value); - float newFloatValue = Float.intBitsToFloat(swappedValue); - grid.setValue(newFloatValue, i, j); - } - } - } - - - // ------------------------------------------------------------------------------- - public QuarterHrapGrid computeDifferenceGrid(QuarterHrapGrid grid1, QuarterHrapGrid grid2) - { - QuarterHrapGrid differenceGrid = new QuarterHrapGrid(); - - //header items - for (int h = 0; h < QuarterHrapGrid.HEADER_ITEM_COUNT; h++) - { - int diff = grid1.getHeaderInfo(h) - grid2.getHeaderInfo(h); - differenceGrid.setHeaderInfo(diff, h); - } - - - //body with data - for (int i = 0; i < QuarterHrapGrid.QTR_HRAP_X; i++) - { - for (int j = 0; j < QuarterHrapGrid.QTR_HRAP_Y; j++) - { - float diff = grid1.getValue(i,j) - grid2.getValue(i, j); - - if (Math.abs(diff) < MIN_VALUE) - { - diff = 0.0f; - } - - if (Math.abs(diff) >= MIN_VALUE) - { - System.out.println(diff + " "); - } - - differenceGrid.setValue(diff, i, j); - } - } - - return differenceGrid; - } - - // ------------------------------------------------------------------------------- - - public void writeGridFile(QuarterHrapGrid grid, String gridFileName) - { - DataOutputStream dos = null; - try - { - FileOutputStream fos = new FileOutputStream(gridFileName); - dos = new DataOutputStream(fos); - - //header info - for (int h = 0; h < QuarterHrapGrid.HEADER_ITEM_COUNT; h++) - { - int value = grid.getHeaderInfo(h); - dos.writeInt(value); - } - - - // body - for (int i = 0; i < QuarterHrapGrid.QTR_HRAP_X; i++) - { - for (int j = 0; j < QuarterHrapGrid.QTR_HRAP_Y; j++) - { - float value = grid.getValue(i, j); - dos.writeFloat(value); - } - - } - - } - catch (Exception e) - { - e.printStackTrace(); - } - finally{ - if (dos != null) - { - try { - dos.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } //end writeGridFile() - - // ------------------------------------------------------------------------------- - public void writeTextGridFile(QuarterHrapGrid grid, String gridFileName) - { - //show numbers - writeTextGridFile(grid, gridFileName, false); - } - - public void writeTextGridFile(QuarterHrapGrid grid, String gridFileName, boolean showShapeOnly) - { - PrintStream printStream = null; - try - { - FileOutputStream fos = new FileOutputStream(gridFileName); - printStream = new PrintStream(fos); - - //header info - for (int h = 0; h < QuarterHrapGrid.HEADER_ITEM_COUNT; h++) - { - int value = grid.getHeaderInfo(h); - printStream.print(value + " "); - } - - - // body - for (int i = 0; i < QuarterHrapGrid.QTR_HRAP_X; i++) - { - for (int j = 0; j < QuarterHrapGrid.QTR_HRAP_Y; j++) - { - float value = grid.getValue(i, j); - - if (showShapeOnly) - { - if (value > 0.0) - { - printStream.print("#"); - } - else - { - printStream.print(" "); - } - } - else //show numbers - { - printStream.printf("%03.1f ", value); - } - } - printStream.println(""); - - } - - } - catch (Exception e) - { - e.printStackTrace(); - } - finally{ - if (printStream != null) - { - printStream.close(); - } - } - - } //end writeGridFile() - - // ------------------------------------------------------------------------------- - - public void writeTextShapeFile(QuarterHrapGrid grid, String gridFileName) - { - PrintStream printStream = null; - try - { - FileOutputStream fos = new FileOutputStream(gridFileName); - printStream = new PrintStream(fos); - - //header info - for (int h = 0; h < QuarterHrapGrid.HEADER_ITEM_COUNT; h++) - { - int value = grid.getHeaderInfo(h); - printStream.print(value + " "); - } - - - // body - for (int i = 0; i < QuarterHrapGrid.QTR_HRAP_X; i++) - { - for (int j = 0; j < QuarterHrapGrid.QTR_HRAP_Y; j++) - { - float value = grid.getValue(i, j); - if (value <= 0.0f) - { - printStream.print(" "); - } - else // value > 0.0 - { - printStream.print("*"); - } - } //for j - - } //for i - - } - catch (Exception e) - { - e.printStackTrace(); - } - finally{ - if (printStream != null) - { - printStream.close(); - } - } - - } //end writeGridFile() - - // ------------------------------------------------------------------------------- - - public static void main(String[] argArray) - { - - String filePath1 = "/home/pst2/DPRRLX080920131307Z.A1"; - //String filePath1 = "/home/pst2/DPRCCX080520131645Z.A1"; - - String filePath2 = "/home/pst2/DPRRLX080920131308Z.A2"; - String outputFilePath = "/home/pst2/checker.out"; - GridUtility checker = new GridUtility(); - - boolean areSame = checker.compareGridFiles(filePath1, filePath2, outputFilePath); - - if (areSame) - { - System.out.printf("Files :%s: and :%s: are essentially the same.\n", filePath1, filePath2); - } - else - { - System.out.printf("Files :%s: and :%s: are different.\n", filePath1, filePath2); - } - - System.out.printf("Difference file written to :%s:\n", outputFilePath); - } - // ------------------------------------------------------------------------------- - -} // class GridChecker() diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolGenerator.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolGenerator.java deleted file mode 100644 index d472886b8a..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolGenerator.java +++ /dev/null @@ -1,206 +0,0 @@ -/** - * This software was developed by HSEB, OHD - **/ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; -import gov.noaa.nws.ohd.edex.plugin.hydrodualpol.common.HydroDualPolConfig; - - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import com.raytheon.edex.urifilter.URIFilter; -import com.raytheon.edex.urifilter.URIGenerateMessage; -import com.raytheon.uf.common.dataplugin.radar.RadarRecord; -import com.raytheon.uf.common.dataplugin.radar.util.RadarsInUseUtil; - -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.edex.cpgsrv.CompositeProductGenerator; - -/** - * - * - *
    - * 
    - * SOFTWARE HISTORY
    - * 
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------
    - * May 13, 2013            jtDeng     Initial creation
    - * 
    - * This HydroDualPolGenerator creates data URI filters for dual pol radar products
    - * DSA/DPR/DAA, it retrieves these radar records from "metadata" database and HDF5 files
    - * once get notified. 
    - * It also generates the post-processing DSA/DPR/DAA products in specific format and 
    - * stores in IHFS database as inputs to MPE/HPE/HPN programs.
    - * 
    - * - * @author deng2 - * @version 1.0 - */ - -public class HydroDualPolGenerator extends CompositeProductGenerator { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(HydroDualPolGenerator.class); - - private static final String genName = "HydroDualPol"; - - private static final String productType = "hydrodualpol"; - - /** Set of icaos to filter for **/ - private Set icaos = null; - - /** public constructor for HydroDualPolGenerator **/ - public HydroDualPolGenerator(String name, String compositeProductType) { - super(genName, productType); - } - - /** default thrift constructor **/ - public HydroDualPolGenerator() { - super(genName, productType); - } - - @Override - protected void configureFilters() { - - logger.debug(getGeneratorName() + " process Filter Config..."); - icaos = new HashSet(RadarsInUseUtil.getSite(null, - RadarsInUseUtil.LOCAL_CONSTANT)); - icaos.addAll(RadarsInUseUtil.getSite(null, - RadarsInUseUtil.DIAL_CONSTANT)); - } - - @Override - protected void createFilters() { - - String header = "HydroDualPolGenerator.createFilters(): "; - ArrayList tmp = new ArrayList(icaos.size()); - Iterator iter = icaos.iterator(); - - int radarCount = 0; - while (iter.hasNext()) { - String icao = iter.next(); - try { - tmp.add(new HydroDualPolURIFilter(icao, HydroDualPolURIFilter.daa)); - tmp.add(new HydroDualPolURIFilter(icao, HydroDualPolURIFilter.dpr)); - tmp.add(new HydroDualPolURIFilter(icao, HydroDualPolURIFilter.dsa)); - - radarCount++; - statusHandler.handle(Priority.INFO, - header + " radar # " + radarCount + " radar id = " + icao); - - } catch (Exception e) { - statusHandler.handle(Priority.PROBLEM, - "Couldn't create HydroDualPol URIFilter.." + icao - + " is not a known RADAR site."); - iter.remove(); - } - } - filters = tmp.toArray(new HydroDualPolURIFilter[tmp.size()]); - } - - @Override - public void generateProduct(URIGenerateMessage genMessage) { - HydroDualPolConfig hydrodualpol_config = null; - - /** test to retrieve the following fields from radar record **/ - try { - hydrodualpol_config = new HydroDualPolConfig( - (HydroDualPolURIGenerateMessage) genMessage, this); - - statusHandler.handle(Priority.INFO, "In HydroDualPol generateProduct..."); - - String productType = hydrodualpol_config.getProductType(); - - if (productType.equalsIgnoreCase("DSA")) - { - RadarRecord record = hydrodualpol_config.getDSA(); - - if (record != null) - { - processDSAProduct(record); - } - else - { - statusHandler.handle(Priority.INFO, - "DSA product not found..."); - } - } - else if (productType.equalsIgnoreCase("DPR")) - { - - RadarRecord record = hydrodualpol_config.getDPR(); - - if (record != null) - { - processDPRProduct(record); - } - else - { - statusHandler.handle(Priority.INFO, - "DPR product not found..."); - } - - } - - - else if (productType.equalsIgnoreCase("DAA")) - { - RadarRecord record = hydrodualpol_config.getDAA(); - - if (record != null) - { - processDAAProduct(record); - } - else - { - statusHandler.handle(Priority.INFO, - "DAA product not found..."); - } - } - } - catch (Exception e) - { - statusHandler.handle(Priority.ERROR, "Can not run HydroDualPol. " + - e.getMessage()); - e.printStackTrace(); - } - } //end generateProduct() - - - private void processDAAProduct(RadarRecord record) - { - - DAAProductProcessor processor = new DAAProductProcessor(statusHandler); - - processor.process(record); - - } - - private void processDPRProduct(RadarRecord record) - { - - DPRProductProcessor processor = new DPRProductProcessor(statusHandler); - - processor.process(record); - - } - - private void processDSAProduct(RadarRecord record) - { - - DSAProductProcessor processor = new DSAProductProcessor(statusHandler); - - processor.process(record); - - } - - @Override - public boolean isRunning() { - return getConfigManager().getHydroDualPolState(); - } - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolURIFilter.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolURIFilter.java deleted file mode 100644 index 08ce527a08..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolURIFilter.java +++ /dev/null @@ -1,373 +0,0 @@ -/** - * This software was developed and / or modified by HSEB, OHD - - **/ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import java.util.Date; -import java.util.regex.Pattern; - -//import com.raytheon.edex.msg.DataURINotificationMessage; -import com.raytheon.uf.common.dataplugin.message.DataURINotificationMessage; -import com.raytheon.edex.urifilter.URIFilter; -import com.raytheon.edex.urifilter.URIGenerateMessage; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; - -/** - * TODO Add Description - * - *
    - * 
    - * SOFTWARE HISTORY
    - * 
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------
    - * May 13, 2013            jtDeng     Initial creation
    - * Construct the DSA/DPR/DAA URI filter pattern.
    - * 
    - * - * @author deng2 - * @version 1.0 - */ - -public class HydroDualPolURIFilter extends URIFilter { - - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(HydroDualPolGenerator.class); - - private static final long serialVersionUID = 1346354654L; - - /** an ICAO you may wish to use in matching */ - protected String icao = null; - - public static double tiltAngle = 0.0; - - public static double layer = 0.0; - - /** Dual pol DSA/DPR?DAA prod ID */ - - public static String daa = "170"; - - public static String dsa = "172"; - - public static String dpr = "176"; - - private String productType = null; - - /** URI pattern for DSA/DPR/DAA radar */ - public Pattern dsaURIpattern = null; - - public Pattern dhrURIpattern = null; - - /** URI pattern for DPR radar */ - public Pattern dprURIpattern = null; - - /** URI pattern for DSA radar */ - public Pattern daaURIpattern = null; - - public HydroDualPolURIFilter(String name, String productType) { - super(name); - logger.debug("HydroDualPolFilter " + name + " Filter construction..."); - - setProductType(productType); - setDataTypes(new String[] { "radar" }); - setIcao(name); - setExclude(false); - setMatchURIs(); - } - - /** - * Filter By ICAO - * - * @return - */ - public String getIcao() { - return icao; - } - - /** - * Set the filtering ICAOs - * - * @param icaos - */ - public void setIcao(String icao) { - this.icao = icao; - } - - @Override - protected String applyWildCards(String key) { - - String[] comps = key.split(uriSeperator); - StringBuffer newKey = new StringBuffer(); - - for (int i = 1; i < comps.length; i++) { - if (i == 2) { - // second comp is time, wildcarded for most - newKey.append(uriSeperator + wildCard); - } else if (i == 0) { - // do nothing - } else { - newKey.append(uriSeperator + comps[i]); - } - } - return newKey.toString(); - } - - @Override - protected String removeWildCards(String key) { - - String[] comps = key.split(uriSeperator); - StringBuffer newKey = new StringBuffer(); - String time = getDateFormatter().format( - getMatchedURIs().get(key).getTime()); - - for (int i = 1; i < comps.length; i++) { - if (i == 2) { - // second comp is time, wildcarded for most - newKey.append(uriSeperator + time); - } else if (i == 0) { - // do nothing - } else { - newKey.append(uriSeperator + comps[i]); - } - } - return newKey.toString(); - } - - @Override - public void setMatchURIs() { - // Duration doesn't matter as we are just keying on DSA,DPR,DAA products - - long duration = 60 * 1000l * 0; // 5 mins - - if (getProductType().equalsIgnoreCase(daa)) - { - setDAAURIPattern(); - getMatchURIs().put(getDAAURIPattern(), duration); - } - else if (getProductType().equalsIgnoreCase(dpr)) - { - setDPRURIPattern(); - getMatchURIs().put(getDPRURIPattern(), duration); - } - else if (getProductType().equalsIgnoreCase(dsa)) - { - setDSAURIPattern(); - getMatchURIs().put(getDSAURIPattern(), duration); - } - } - - /** - * Sets the DSA URI Pattern - * - * @return - */ - public void setDSAURIPattern() { - - dsaURIpattern = Pattern.compile("/radar/" + ".*" + uriSeperator - + getIcao() + uriSeperator + dsa + uriSeperator + tiltAngle - + uriSeperator + layer); - } - - /** - * Gets the DSA URI Pattern - * - * @return - */ - public Pattern getDSAURIPattern() { - return dsaURIpattern; - } - - /** - * Sets the DPR URI Pattern - * - * @return - */ - public void setDPRURIPattern() { - - dprURIpattern = Pattern.compile("/radar/" + ".*" + uriSeperator - + getIcao() + uriSeperator + dpr + uriSeperator + tiltAngle - + uriSeperator + layer); - } - - /** - * Gets the DPR URI Pattern - * - * @return - */ - public Pattern getDPRURIPattern() { - return dprURIpattern; - } - - /** - * Sets the DAA URI Pattern - * - * @return - */ - public void setDAAURIPattern() { - - daaURIpattern = Pattern.compile("/radar/" + ".*" + uriSeperator - + getIcao() + uriSeperator + daa + uriSeperator + "0.0" + uriSeperator +"0.0"); - - - } - - /** - * Gets the DAA URI Pattern - * - * @return - */ - public Pattern getDAAURIPattern() { - return daaURIpattern; - } - - @Override - public URIGenerateMessage createGenerateMessage() { - return new HydroDualPolURIGenerateMessage(this); - } - - - /** - * This is the real deal where you look for matches based on your - * suppositions. It keeps a list called matchedURIs, when all matchURIs have - * been satisfied with a matchedURI, this will return true. - * - * @param message - * @return boolean - */ - - private void log(String textMessage) - { - statusHandler.handle(Priority.INFO, textMessage); - } - - - public boolean isMatched(DataURINotificationMessage message) { - - String header = "HydroDualPolURIFilter.isMatched(): "; - - boolean debug = logger.isDebugEnabled(); - //debug = true; //force it true - - - setCurrentTime(new Date(System.currentTimeMillis())); - // process all the product messages - if ((message != null) && (message.getDataURIs().length > 0)) - { - if (debug) { - // log(header + name + ": Filtering Messages..." - // + message.getDataURIs().length); - } - - - for (String key : message.getDataURIs()) { - - //debug = true; - - // add your pattern checks to the key - for (Pattern pattern : getMatchURIs().keySet()) { - - if (debug) { - - if (key.contains("/" + dpr + "/") && (key.contains("radar"))) - { - log(header + "********** This should match! ****************"); - log(header + "\nhPattern: " + pattern.toString() - + "\nKey: " + key); - } - } - - if (pattern.matcher(key).matches()) { - // extract times, used later - setValidTime(getTime(key, getDateFormatter())); - long duration = 0l; - if (debug) { - log(header + name + ": match Found: " + key); - } - - if (!getMatchedURIs().containsKey(pattern.toString())) { - // brand spanking new - getMatchedURIs().put(pattern.toString(), - getValidTime()); - getMatchTimes().put(pattern.toString(), - getCurrentTime()); - if (debug) { - log(header + name + ": new product. " + key); - } - } else { - duration = getValidTime().getTime() - - getMatchedURIs().get(pattern.toString()) - .getTime(); - if (debug) { - log(header + name + ": not new. " + key - + " Age of MatchedURI: " + duration - / (1000 * 60) + " minutes"); - - // got a replacement - log(header + name - + ": not new. " - + key - + " Age of MatchURI: " - + getMatchURIs().get(pattern) - .longValue() / (1000 * 60) - + " minutes"); - } - - if (duration <= getMatchURIs().get(pattern) - .longValue()) { - // replace - getMatchedURIs().remove(pattern.toString()); - getMatchTimes().remove(pattern.toString()); - getMatchedURIs().put(pattern.toString(), - getValidTime()); - getMatchTimes().put(pattern.toString(), - getCurrentTime()); - if (debug) { - log(header + name - + ": in range: replaced in matchedURIs. " - + key); - } - } else if (debug) { - log(header + name - + ": not in range: discarded. " + key); - } - } - } - } - } - if (debug) { - log(header + name + ": matchedURIs size: " - + getMatchedURIs().size()); - } - } - - // check for repeats and equality of size - if ((getMatchedURIs().size() == getMatchURIs().size()) && !isRepeat()) { - // this is your green light condition - if (debug) { - log(header + name + ": Matched all products! "); - } - match = true; - - } else { - if (getMatchedURIs().size() > 0) { - ageTimes(); - } - } - - return match; - } - - public void setProductType(String productType) { - this.productType = productType; - } - - public String getProductType() { - return productType; - } - - - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolURIGenerateMessage.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolURIGenerateMessage.java deleted file mode 100644 index ef8537ee36..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroDualPolURIGenerateMessage.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * This software was developed and / or modified by HSEB, OHD - * - **/ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import com.raytheon.edex.urifilter.URIGenerateMessage; -import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; -import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; - -/** - * TODO Add Description - * - *
    - * 
    - * SOFTWARE HISTORY
    - * 
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------
    - * May 13, 2013            jtDeng     Initial creation
    - * 
    - * 
    - * - * @author deng2 - * @version 1.0 - */ -@DynamicSerialize -public class HydroDualPolURIGenerateMessage extends URIGenerateMessage { - @DynamicSerializeElement - protected String icao; - - public HydroDualPolURIGenerateMessage() { - } - - public HydroDualPolURIGenerateMessage(HydroDualPolURIFilter filter) { - super(filter); - setIcao(filter.getIcao()); - } - - public String getIcao() { - return icao; - } - - public void setIcao(String icao) { - this.icao = icao; - } - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroNumericUtility.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroNumericUtility.java deleted file mode 100644 index 860efd57dd..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroNumericUtility.java +++ /dev/null @@ -1,82 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - - -/** - * Class to handle numeric type conversions for MPE- and HPE/HPN- related grid processing. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * July 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - -public class HydroNumericUtility { - - - public static float convertShortsToFloat(short part1, short part2) - { - int intPart1 = makeUnsignedShortAnInt(part1); - int intPart2 = makeUnsignedShortAnInt(part2); - - float value = Float.intBitsToFloat((intPart1 << 16) + intPart2); - - return value; - } - - public static int makeUnsignedShortAnInt(short value) - { - - int intValue = value; - - if (value < 0) - { - intValue = (value & 0x0000ffff); - - } - - return intValue; - } - - public static int getSwappedIntBytesFromFloat(float value) - { - int intBits = Float.floatToIntBits(value); - int littleEndianInt = swapBytes(intBits); - - return littleEndianInt; - - } - - public static int swapBytes(int intBits) - { - int flippedInt = - (( intBits & 0x000000ff ) << 24 ) | - (( intBits & 0x0000ff00 ) << 8 ) | - (( intBits & 0x00ff0000 ) >>> 8) | - (( intBits & 0xff000000 ) >>> 24 ); - - return flippedInt; - } - - public static byte getHighOrderByte(short shortValue) - { - byte byteValue = (byte) (shortValue >> 8); - - return byteValue; - } - - public static byte getLowOrderByte(short shortValue) - { - byte byteValue = (byte) (shortValue & 0x0000ffff); - - return byteValue; - } - - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroTimeUtility.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroTimeUtility.java deleted file mode 100644 index 84c2f0aaa9..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/HydroTimeUtility.java +++ /dev/null @@ -1,335 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -/** - * Class to handle formatting and conversion of various date/time formats for DAA, DSA, and DPR products for - * MPE and HPE/HPN. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * July 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - -public class HydroTimeUtility -{ - - private static final int MILLIS_PER_DAY = 24 * 60 * 60 * 1000; - - private static ThreadLocal sqlSdf = new ThreadLocal() { - - @Override - protected SimpleDateFormat initialValue() { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - return sdf; - } - - }; - - private static ThreadLocal sqlDateOnlySdf = new ThreadLocal() { - - @Override - protected SimpleDateFormat initialValue() { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - return sdf; - } - - }; - - private static ThreadLocal monthDayYearHourMinuteSdf = new ThreadLocal() { - - @Override - protected SimpleDateFormat initialValue() { - SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - return sdf; - } - - }; - - - public static String changeDate(String originalDateString, int days) - { - - Date originalDate = getDateFromSQLDateOnlyString(originalDateString); - long millis = originalDate.getTime(); - - //change the time by milliseconds - millis += days * MILLIS_PER_DAY; - - //create new date and get the string representation - Date newDate = new Date(millis); - String newDateString = getSQLDateOnlyStringFromDate(newDate); - - return newDateString; - } - - - public static String getSQLDateOnlyStringFromDate(Date date) - { - String dateString = null; - try - { - dateString = sqlDateOnlySdf.get().format(date); - } - catch (Exception e1) - { - e1.printStackTrace(); - } - - return dateString; - } - - public static Date getDateFromSQLDateOnlyString(String sqlDateString) - { - Date date = null; - try - { - date = sqlDateOnlySdf.get().parse(sqlDateString); - } - catch (ParseException e1) - { - e1.printStackTrace(); - } - - return date; - } - - - public static String getSQLStringFromDate(Date date) - { - String dateString = null; - try - { - dateString = sqlSdf.get().format(date); - } - catch (Exception e1) - { - e1.printStackTrace(); - } - - return dateString; - } - - public static Date getDateFromSQLString(String sqlDateString) - { - Date date = null; - try - { - date = sqlSdf.get().parse(sqlDateString); - } - catch (ParseException e1) - { - e1.printStackTrace(); - } - - return date; - } - - - public static long getMillisFromSQLString(String sqlDateString) - { - Date date = null; - try - { - date = sqlSdf.get().parse(sqlDateString); - } - catch (ParseException e1) - { - e1.printStackTrace(); - } - - return date.getTime(); - } - - public static long getMillisFromAmericanDateTimeString(String sqlDateString) - { - Date date = null; - try - { - date = monthDayYearHourMinuteSdf.get().parse(sqlDateString); - } - catch (ParseException e1) - { - e1.printStackTrace(); - } - - return date.getTime(); - } - - - - public static String JulianDateConvertToYMD(int jdate) - { - return JulianDateConvertWithFormat(jdate, "ymd"); - } - - public static String JulianDateConvertToMDY(int jdate) - { - return JulianDateConvertWithFormat(jdate, "mdy"); - } - - - public static String JulianDateConvertWithFormat(int jdate, String ymdFormat) - { - // Convert from Julian day number to month, day, year - // Based on Jan 1, 1970 - - int days[]={31,28,31,30,31,30,31,31,30,31,30,31} ; - int year = 0, month = 0,ndays,date = - 0,total,leap_year; - int TRUE = 1; - int FALSE = 0; - String cdate = null; - - total=0; - for (year=1970;year<2080;year++) - { - leap_year=FALSE; - - if ((((year%4) == 0) && ((year%100) != 0)) || (year%400==0)) - { - leap_year=TRUE; - } - - for (month=0;month<12;month++) - { - total = total+days[month]; - if (month==1 && leap_year==TRUE) - { - total++; - } - - if (total >= jdate) - { - ndays=days[month]; - if (month==1 && leap_year==TRUE) - { - ndays++; - } - - date=ndays - (total-jdate); - int newMonth = month+1; - - if (ymdFormat.equals("ymd")) - { - cdate = String.format("%04d-%02d-%02d",year,newMonth,date); - } - else - { - cdate = String.format("%02d%02d%04d",newMonth,date,year); - } - return cdate; - - } - } - } - return cdate; - } - - - public static String JulianDateConvertToYMD2(int jdate) - { - return JulianDateConvertWithFormat2(jdate, "ymd"); - } - - public static String JulianDateConvertWithFormat2(int jdate, String ymdFormat) - { - - String cdate = null; - int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} ; - int year, month, ndays, date, total; - - boolean leap_year = false; - - total = 0; - for (year = 1970; year < 2030; year++) - { - leap_year = false; - if (year == 1972 || year == 1976 || year == 1980 || - year == 1984 || year == 1988 || year == 1992 || year == 1996 || - year == 2000 || year == 2004 || year == 2008 || year == 2012 || - year == 2016 || year == 2020 || year == 2024 || year == 2028) - { - leap_year = true; - } - - for (month = 0; month < 12; month++) - { - total = total + days[month]; - if (month == 1 && leap_year) - { - total ++; - } - - if (total >= jdate) - { - ndays = days[month]; - if (month == 1 && leap_year) - { - ndays++; - } - date = ndays - (total-jdate); - month++; - - if (ymdFormat.equals("ymd")) - { - cdate = String.format("%04d-%02d-%02d",year, month, date); - } - else - { - cdate = String.format("%02d%02d%04d",month, date, year); - } - - return cdate; - } - } - } - - return cdate; - } - - - - public static void testJulian(int julianDate) - { - String yearMonthDayString = HydroTimeUtility.JulianDateConvertToYMD(julianDate); - System.out.printf("julianDate of %d = %s\n", julianDate, yearMonthDayString); - } - - public static void testJulian2(int julianDate) - { - String yearMonthDayString = HydroTimeUtility.JulianDateConvertToYMD2(julianDate); - System.out.printf("julianDate of %d = %s\n", julianDate, yearMonthDayString); - } - - - public static void main(String[] argArray) - { - //closer to A1 DAA code - HydroTimeUtility.testJulian(0); - - HydroTimeUtility.testJulian(1); - - - //closer to A1 DPR code - - HydroTimeUtility.testJulian2(0); - - HydroTimeUtility.testJulian2(1); - - } -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/PolarToHRAPTransformer.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/PolarToHRAPTransformer.java deleted file mode 100644 index 1c53b0ddfd..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/PolarToHRAPTransformer.java +++ /dev/null @@ -1,567 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - - -/** - * Class to handle conversion from Polar coordinates to HRAP coordinates for DAA, DSA, and DPR product processors for - * MPE and HPE/HPN. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * August 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - -public class PolarToHRAPTransformer -{ - // double[] LFM_GRID40 = new double[17161]; - int[][] lfm40flag = new int[2][17161]; - int[][] lfm40grid = new int[360][920]; - - //from TransformPolarToCartesian.h - - static final int BEYOND_GRID = -77; - static final int FLAG_AZ = 0; - static final int FLAG_RNG = 1; - static final int BEYOND_RANGE = -99; - static final int NO_DATA_FLAG = 0; - static final int WITHIN_RANGE = 0; - static final int MAX_AZMTHS = 360; - static final int KBINS = 920; /* # of bins in the 232KM polar grid -- original value was 115 */ - static final int HYZ_LFM40 = 131; - - - //from build_lfm _lookup C routines ( .h and .c files) - static final double DTR = 0.01745329; - static final double HALF = 0.5; - static final double RNG_INC = 0.25; /* previous value was 2.0 */ - - static final int FLAG_SIZE = 2; - - static final int NUM_LFM40 = (HYZ_LFM40 * HYZ_LFM40); - - static final int MAX_AZMTH = 360; - - static final int ONE = 1; - - static final double r2ko = 249.6348607; - static final double ip = 433.0; - static final double jp = 433.0; - - static final double LFM40_RNG = 230.0; - - static final double AZ_RND = 1.05; // Factor used to convert azimuth angle to azimuth - // index of bin closet to grid hole. - static final double RG_RND = 0.25; // Factor used to convert range to range - // bin index of closet to grid hole. - static final double prime = 105.0; - static final int lfm40_idx = 2; - static final int LFMMX_IDX = 3; - static final double const_val = 135.0; - static final double angle_thresh = 9.81e-6; - static final double re_proj = 6380.0; - static final int KRADS = 360; - - static final double re_proj_sq = (re_proj*re_proj); /*6380.0*6380.0*/ - - static double ka = 10.0; - static int offset = 66; - - - //from lfm_to_azran.c - static final double R_360 = 360.0; // Constant representing the value 360.0 - static final double NINTY = 90.0; // Constant representing the value 90.0 - static final double ZERO = 0.0; // Constant representing the value 0.0 - static final double TWO = 2.0; // Constant representing the value 2.0 - // static final double DTR = 0.01745329; // Degrees to radians coversion factor - // static final double HALF = 0.5; // Parameter equals to 0.5 - - //azimuth and range - private int iaz; - private int irg; - - double MAX_LFMVAL = 0; - - public PolarToHRAPTransformer() - { - ; - } - - - private void build_lfm_lookup(double radarLat, double radarLon) - { - double b, r, ls, lamdas, pre_gxs, gis,gjs, gi, gj, rl, - cos_dlamda, sin_dlamda, sin_s, cos_s, - sin_ls, cos_ls, sin_l, cos_l, sin_b, cos_b, - cos_lamdas_prime, sin_lamdas_prime; - - int[] is = new int[LFMMX_IDX]; - int[] js = new int[LFMMX_IDX]; - - int lfmbox; - int status; - - int j; - - double az_ij=0.; //Azimuth angle to the center of an LFM box - double rg_ij=0.; // Range to the center of an LFM box - int i, // Loop control for absolute LFM box number - lfm_i, // LFM I coordinate (i increases to the right) - lfm_j; // LFM J coordinate (j increases downward) - - //original C code worked, but there was no need for static, the variables are actually supposed to be constants. - //static double ka = 10.0; - //static int offset = 66; - - sin_ls = 0.; - cos_ls = 0.; - - // according to ICD, radar longitude is negative for West longitude - // in A2, we receive the radarLon as negative, so we had to remove the A1 correction - // 7/19/13 cg and pt - - ls = radarLat; - lamdas = radarLon; - - /** Initialize tables before starting lookup table generation*/ - - for ( i=0; i0)&&(lfm_i<=HYZ_LFM40)&&(lfm_j>0)&&(lfm_j<=HYZ_LFM40)) - { - lfmbox = (lfm_j-1)*HYZ_LFM40+lfm_i; - lfm40grid[iaz][irg] = lfmbox; - lfm40flag[FLAG_RNG][lfmbox-1] = WITHIN_RANGE; - } - - } /*end loop KBINS*/ - - } /*end loop MAX_AZMTH*/ - - /** Find holes and determine hole filling data*/ - - /* Search for holes in the 1/40 lfm lookup table and identify the - az/ran of the data to be used to fill in the hole - */ - for (i=0; i=(double)angle_thresh ) - { - theta_cij = Math.atan2(cos_lij*cos_ls*sin_dlamda,(sin_lij-sin_ls*cos_ss)); - } - /* Otherwise, set theta_cij to 0*/ - else - { - theta_cij = ZERO; - } - - theta_cij = theta_cij/DTR; - - /* If angle is less than 0 ... add 360 degrees*/ - if ( theta_cij < ZERO ) - { - theta_cij = theta_cij+R_360; - } - - point.setAzimuth(theta_cij); - point.setRange(rg_ij); - - return point; - - } - - public float[] transformHrapPrecipToDBA(float[] hrapGrid, float outputNoDataFlag) - { - int totalGridBins = HYZ_LFM40 * HYZ_LFM40; - float [] dbaArray = new float[totalGridBins]; - int k = 0; - int index = 0; - - for (int x = 0; x < HYZ_LFM40; x++) - { - for (int y = HYZ_LFM40-1; y > -1; y--) - { - - index = totalGridBins - (HYZ_LFM40 * x) - (y + 1); - float hrapGridValue = hrapGrid[index]; - - - if (hrapGridValue == BEYOND_RANGE) - { - dbaArray[k] = BEYOND_RANGE; - } - - else if (hrapGridValue == NO_DATA_FLAG) - { - dbaArray[k] = outputNoDataFlag; - } - - else if (hrapGridValue == BEYOND_GRID) - { - dbaArray[k] = BEYOND_RANGE; //not an error - } - - else - { - dbaArray[k] =(float) (10.0 * Math.log10( (hrapGridValue * .254) ) ); - } - - k++; - } //end for y - } // end for x - - return dbaArray; - - } //end transformHrapPrecipToSingleArrayInDBA() - - public float [] transform250MeterPolarToFullHRAP(float [][] polarGrid, double radarLat, double radarLon ) - { - - float[] hrapOutputGrid = new float[17161]; - - int FLG_ZERHLY, FLG_NOHRLY; - int GRID_LAT,GRID_LON; - int SIRDALAT, SIRDALON ; - - float RADIAN_AZIMUTH, SIN_MIDPT, COS_MIDPT, HALF=0.5f; - float[] SIN_QUARTR = new float[2]; //2 - float[] COS_QUARTR = new float[2]; //2 - float[] RANGE = new float[920];//920 - float radar_lat, radar_lon; - float minValueData; - - int AZIMUTH, SPLIT; - int CLEAR=0, SET=1; - int XDIR=1, YDIR=2; - int X, Y, XY_DELTA, HOLEXY; - int i, j, WEST=1, EAST=2, NORTH=3, SOUTH=4, SUM, COUNT; - // int null=0; - - int[] DENOM_GRD = new int[17161]; - - /*---------------------------------------------------------------------*/ - /* generate lookup tables for polar to Cartesian grid transformation */ - /*---------------------------------------------------------------------*/ - - build_lfm_lookup(radarLat, radarLon); - - /*-------------------------------------------------------------------*/ - /* this section of the code uses the arrays generated above to */ - /* map the precip grid from polar to Cartesian */ - /* code below came from module a31467.ftn */ - /*-------------------------------------------------------------------*/ - - /*----------------------------------------------------------*/ - /* Initialize numerator and denominator to zero */ - /*----------------------------------------------------------*/ - - for(i = 0; i < 17161; i++) - { - DENOM_GRD[i] = 0; - hrapOutputGrid[i] = 0; - } - MAX_LFMVAL = 0.; - minValueData = 99; - - /*----------------------------------------------------------*/ - /* Do for each radial azimuth & each bin along the radial */ - /*----------------------------------------------------------*/ - - for (j = 0; j < MAX_AZMTHS; j++) - { - - /*---------------------------------------------------------------------*/ - /* DO UNTIL THE END OF THE RADIAL OR THE GRID DOMAIN HAS BEEN EXCEEDED */ - /*---------------------------------------------------------------------*/ - - for (i = 0; i < KBINS; i++) - { - - int hrapGridBinIndex = lfm40grid[j][i]; - - /*----------------------------*/ - /* IF BIN BEYOND GRID */ - /*----------------------------*/ - - if(hrapGridBinIndex == BEYOND_GRID) - { - /* printf("J = %d I = %d -- beyond grid\n", J,I); */ - break; - } - else - { - - /*---------------------------------------------------------------------*/ - /* Increment numerator by precip value */ - /* Increment denominator by one count... */ - /*---------------------------------------------------------------------*/ - - hrapOutputGrid[hrapGridBinIndex] += polarGrid[j][i]; - DENOM_GRD[hrapGridBinIndex] ++; - } - - } /* end for (I = 0; I < KBINS; I++) */ - - } /* end for (J = 0; J < MAX_AZMTHS; J++) */ - - /*----------------------------*/ - /* Do for each LFM bin... */ - /*----------------------------*/ - - for (i = 0; i < 17161; i++) - { - - /*----------------------------------*/ - /* CHECK IF POINT IS BEYOND RANGE */ - /*----------------------------------*/ - - if (lfm40flag[FLAG_RNG][i] == WITHIN_RANGE) - { - - /*----------------------------------*/ - /* Calculate value for numerator...*/ - /*----------------------------------*/ - - if (DENOM_GRD[i] > 0) - { - hrapOutputGrid[i] = hrapOutputGrid[i]/DENOM_GRD[i]; - - if (MAX_LFMVAL < hrapOutputGrid[i]) - { - MAX_LFMVAL = hrapOutputGrid[i]; - } - if (minValueData > hrapOutputGrid[i]) - { - minValueData = hrapOutputGrid[i]; - } - - } - - } - else if(lfm40flag[FLAG_RNG][i] == BEYOND_RANGE) - { - /*---------------*/ - /* BEYOND RANGE */ - /*---------------*/ - - /*printf("bin # %d -- beyond range\n", I); */ - hrapOutputGrid[i] = BEYOND_RANGE; - - } - else - { - /*-----------------------------------*/ - /* FILL HOLE WITH NEAREST BIN DATA */ - /*-----------------------------------*/ - - /* printf("bin # %d -- hole filled by nearby bin\n", I); */ - - int azimuthBinIndex = lfm40flag[FLAG_AZ][i]; - int rangeBinIndex = lfm40flag[FLAG_RNG][i]; - - hrapOutputGrid[i] = (float) polarGrid[azimuthBinIndex][rangeBinIndex]; - } - - } /* end for (i = 0; i < 17161; i++) */ - - /*---------------------------*/ - /* print min value to log */ - /* units = inches (same units as max value in db table */ - /*---------------------------*/ - - minValueData = (minValueData/100); - /* printf("min value = %f\n", minValueData); */ - - return hrapOutputGrid; - } - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/PolarToQuarterHRAPTransformer.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/PolarToQuarterHRAPTransformer.java deleted file mode 100644 index b31aabbcb3..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/PolarToQuarterHRAPTransformer.java +++ /dev/null @@ -1,606 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - -import com.raytheon.uf.common.status.IUFStatusHandler; - -/** - * Class to handle conversion from Polar coordinates to Quarter HRAP coordinates for DSA, and DPR product processors for - * HPE/HPN. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * August 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - - -public class PolarToQuarterHRAPTransformer -{ - - //from decode_constants.h - - private static final short NO_DATA_FLAG = 0; - - private static final int MAX_AZIMUTH = 360; - private static final int MAX_RANGE_BINNUM = 920; /* for dual pol DSA */ - - public static final int MAX_IHRAP = 524; - public static final int MAX_JHRAP = 524; - - private static final int NUM_ROW = 524; - private static final int NUM_COL = 524; - - private static final int BEYOND_RANGE = -99; - private static final int BEYOND_GRID = -77; - - private static final double GRID_COORD_I = 433.0; - private static final double GRID_COORD_J = 433.0; - - private static final double ANGLE_THRESH = 9.81E-6; - - private static final double R2KO = 249.6348607; - private static final double PRIME = 105.0; - -// private static final int IKA = 40; - //This section matches to an array-based section in PolarToHRAPTransformer - //All of this code should be merged into a single routine with - //varying use of constants. - private static final double KA = 40.0; - private static final int OFFSET = 263; - private static final double B_CON = 0.025; - - private static final float DEFAULT_RADAR_1KM = -0.9f; - //private static final double MAX_RATE = 999.0; - //private static final double MIN_RATE = -999.0; - - private static final double CONST = 135.0; - private static final double EARTH_RADIUS = 6380.0; - - //private static final double FLOAT_MISSING = -999.0; - - // end of code from decode_constants.h - - - // start from build_lookup_table - private static final double ONE = 1.0; - private static final double HALF = 0.5; - private static final double RNG_INC = 0.25; /* for dual pol DSA/DPR product with 0.25 km resolution */ - - private static final double DEGREE_TO_RADIAN = 0.01745329; - private static final double EARTH_RADIUS_SQ = EARTH_RADIUS * EARTH_RADIUS; - // end from build_lookup_table - - private int[][] radar_to_quarter_hrap_i = new int[MAX_RANGE_BINNUM][MAX_AZIMUTH]; - private int[][] radar_to_quarter_hrap_j = new int[MAX_RANGE_BINNUM][MAX_AZIMUTH]; - - private int[][] quarter_hrap_to_radar_azimuth = new int[MAX_IHRAP][MAX_JHRAP]; - private int[][] quarter_hrap_to_radar_range = new int[MAX_IHRAP][MAX_JHRAP]; - - - private IUFStatusHandler statusHandler = null; //leave in to make future debugging easier - - - public PolarToQuarterHRAPTransformer() - { - ; - } - - - public PolarToQuarterHRAPTransformer(IUFStatusHandler statusHandler) - { - this.statusHandler = statusHandler; - } - - void build_lookup_table(double radar_lat, double radar_lon) - { - - double pre_gxs, site_grid_i, site_grid_j; - double grid_i, grid_j, rl, cos_delta_lamda, sin_delta_lamda, sin_angle_s, cos_angle_s; - double sin_site_lat, cos_site_lat, sin_lat, cos_lat, sin_bearing, cos_bearing; - double bear_angle, range, cos_lambas_prime, sin_lamdas_prime; - int site_i, site_j, iaz, irg; - - int /*long*/ lfm_i, lfm_j; - int ihrap, jhrap; - - /* - * re-initialize tables before starting lookup table generation - */ - - for(iaz = 0; iaz < MAX_AZIMUTH; iaz++) - { - for (irg = 0; irg < MAX_RANGE_BINNUM; irg++) - { - radar_to_quarter_hrap_i[irg][iaz] = BEYOND_GRID; - radar_to_quarter_hrap_j[irg][iaz] = BEYOND_GRID; - } - } - - for(ihrap = 0; ihrap < MAX_IHRAP; ihrap++) - { - for (jhrap = 0; jhrap < MAX_JHRAP; jhrap++) - { - quarter_hrap_to_radar_azimuth[ihrap][jhrap] = BEYOND_GRID; - quarter_hrap_to_radar_range[ihrap][jhrap] = BEYOND_GRID; - } - } - - /* - * compute parts of equations used multiple times later - */ - - cos_lambas_prime = Math.cos((radar_lon + PRIME) * DEGREE_TO_RADIAN); - sin_lamdas_prime = Math.sin((radar_lon + PRIME) * DEGREE_TO_RADIAN); - sin_site_lat = Math.sin(radar_lat * DEGREE_TO_RADIAN); - cos_site_lat = Math.cos(radar_lat * DEGREE_TO_RADIAN); - - /* - * compute common part of the gis and gjs equations - */ - - pre_gxs = R2KO * cos_site_lat / (ONE + sin_site_lat); - - /* - * compute reference grid box coordinates - */ - - site_grid_i = pre_gxs * sin_lamdas_prime + GRID_COORD_I; - site_grid_j = pre_gxs * cos_lambas_prime + GRID_COORD_J; - - /* - * compute grid box numbers for box 0,0 of local grids, OFFSET is the - * center of 524x524 HRAP grid which is the center of radar, this value changes - * when the HRAP grid size changes. - */ - - site_i = (int)(KA * site_grid_i) - OFFSET; - site_j = (int)(KA * site_grid_j) - OFFSET; - - // System.out.printf("KA=%f, OFFSET=%d, B_CON=%f\n", KA, OFFSET, B_CON); - - /* - * initialize bearing - */ - - bear_angle = -HALF; - - /* - * DO FOR ALL BEARINGS - */ - - for(iaz = 1; iaz <= MAX_AZIMUTH; iaz++) - { - bear_angle += ONE; - sin_bearing = Math.sin(bear_angle * DEGREE_TO_RADIAN); - cos_bearing = Math.cos(bear_angle * DEGREE_TO_RADIAN); - - /* - * initialize range - */ - - /* half of the range increment value */ - range = -RNG_INC/2; - - /* - * do for each input data range values (hydro application next) - */ - - for (irg = 1; irg <= MAX_RANGE_BINNUM; irg++) - { - range = range + RNG_INC; - sin_angle_s = (range / EARTH_RADIUS) * - (ONE - (CONST * range / EARTH_RADIUS_SQ)); - cos_angle_s = Math.sqrt(ONE - sin_angle_s * sin_angle_s); - - sin_lat = sin_site_lat * cos_angle_s+cos_site_lat - * sin_angle_s * cos_bearing; - cos_lat = Math.sqrt(ONE - sin_lat * sin_lat); - - sin_delta_lamda = sin_angle_s * sin_bearing/cos_lat; - cos_delta_lamda = Math.sqrt(ONE - sin_delta_lamda * sin_delta_lamda); - - rl = R2KO * cos_lat/(ONE + sin_lat); - - grid_i = rl * (sin_delta_lamda * cos_lambas_prime + - cos_delta_lamda * sin_lamdas_prime)+GRID_COORD_I; - grid_j = rl * (cos_delta_lamda * cos_lambas_prime - - sin_delta_lamda * sin_lamdas_prime)+GRID_COORD_J; - - /* - * compute 1/160 lfm i and j coordinates of the range/azimuth bin - */ - - lfm_i = (int)(grid_i * KA) - site_i; - lfm_j = (int)(grid_j * KA) - site_j; - - /* - * if lfm coordinates are within local grid save it into the lookup - * table and set the 1/160 lfm box range number table to within range - */ - - if ((lfm_i > 0) && (lfm_i <= MAX_IHRAP) && - (lfm_j > 0) && (lfm_j <= MAX_JHRAP) ) - { - radar_to_quarter_hrap_i[irg-1][iaz-1] = lfm_i; - radar_to_quarter_hrap_j[irg-1][iaz-1] = lfm_j; - - quarter_hrap_to_radar_azimuth[lfm_i-1][lfm_j-1] = iaz; - quarter_hrap_to_radar_range[lfm_i-1][lfm_j-1] = irg; - - } - } - } - - /* - * call find_holes() to find holes and determine hole filling data - */ - - find_holes(radar_lat, radar_lon); - - //GridChecker checker = new GridChecker(); - //String outputDir = "/home/pst2/"; - - //checker.writeIntegerGrid(radar_to_quarter_hrap_i, MAX_RANGE_BINNUM, MAX_AZIMUTH, outputDir + "radar_to_quarter_hrap_i.txt" ); - //checker.writeIntegerGrid(radar_to_quarter_hrap_j, MAX_RANGE_BINNUM, MAX_AZIMUTH, outputDir + "radar_to_quarter_hrap_j.txt" ); - - - //checker.writeIntegerGrid(quarter_hrap_to_radar_azimuth, MAX_IHRAP, MAX_JHRAP, outputDir + "quarter_hrap_to_radar_azimuth.txt" ); - //checker.writeIntegerGrid(quarter_hrap_to_radar_range, MAX_IHRAP, MAX_JHRAP, outputDir + "quarter_hrap_to_radar_range.txt" ); - - - } //end build_lookup_table() - - - void find_holes(double LS, double LAMDA) - { - double RG_IJ, AZ_IJ, AZ_RND, RG_RND, MAX_RANGE_LENGTH; - int lfm_i, lfm_j, ONE, count; - int ihrap, jhrap; - - /* initialize the quarterhrap to azimuth value */ - AZ_IJ = 0.0; - /* increment on azimuth */ - AZ_RND = 1.05; - /* initialize the quarterhrap to range value */ - RG_IJ = 0.0; - /* increment on range */ - RG_RND = 0.25; - - ONE = 1; - - /* maximum range length for DSA/DPR products which is 230.0km */ - MAX_RANGE_LENGTH = 230.0; - - count = 0; - - /* - * search for holes in the 1/160 lfm lookup table and identify the - * azimuth/range of the data to be used to fill in the hole - */ - - for(ihrap = 0; ihrap < MAX_IHRAP; ihrap ++) - { - for (jhrap = 0; jhrap < MAX_JHRAP; jhrap ++) - { - /* with BEYOND_GRID value means this bin is not filled yet */ - if( (quarter_hrap_to_radar_azimuth[ihrap][jhrap] == BEYOND_GRID) && - (quarter_hrap_to_radar_range[ihrap][jhrap] == BEYOND_GRID) ) - { - lfm_i = ihrap + 1; - lfm_j = jhrap + 1; - - /* calculate the azimuth AZ_IJ and range RG_IJ for the hrap point (lfm_i, lfm_j) */ - AzimuthAndRangePoint point = quarterhrap_to_az_range(LS, LAMDA, lfm_i, lfm_j); - - AZ_IJ = point.getAzimuth(); - RG_IJ = point.getRange(); - - /* - * if the range is within the product coverage area (for DSA product the maximum range length is 230 km) - * requirement then - * store azimuth and range index into the lookup table - */ - - if (RG_IJ < MAX_RANGE_LENGTH) - { - count ++; - - /* fill the hole's azimuth with (AZ_IJ+AZ_RND), range with (RG_IJ/RG_RND+ONE) */ - quarter_hrap_to_radar_azimuth[ihrap][jhrap] - = (int)(AZ_IJ + AZ_RND); - quarter_hrap_to_radar_range[ihrap][jhrap] - = (int)(RG_IJ/RG_RND) + ONE; - } - else /* assign BEYOND_RANGE when RG_IJ is out of the maximum range length */ - { - quarter_hrap_to_radar_azimuth[ihrap][jhrap] - = BEYOND_RANGE; - quarter_hrap_to_radar_range[ihrap][jhrap] - = BEYOND_RANGE; - } - } - } - } - - // System.out.printf("In find holes: count is %d\n", count); - - } //end find_holes() - - - AzimuthAndRangePoint quarterhrap_to_az_range(double LS, double LAMDAS, - int LFM_I, int LFM_J /*, double *THETA_CIJ, double *RG_IJ */ ) - { - - AzimuthAndRangePoint point = new AzimuthAndRangePoint(); - double THETA_CIJ; - double RG_IJ; - - double PRE_GXS, GIS, GJS, DTR, ONE; - double COS_LAMDAS_PRIME, SIN_LAMDAS_PRIME, SIN_DLAMDA; - double HALF, AI, AJ; - double CII, CJJ, SIN_LS, COS_LS; - double AA, BB, COS_SS, SIN_SS, COS_LIJ, SIN_LIJ, R_360; - double LAMDA_IJ, L_IJ, NINTY, TWO, ZERO; - int IS, JS; - - R_360 = 360.0; - NINTY = 90.0; - ZERO = 0.0; - TWO = 2.0; - HALF = 0.5; - ONE = 1.0; - DTR = DEGREE_TO_RADIAN; - - COS_LS = 0.0; - SIN_LS = 0.0; - - - COS_LAMDAS_PRIME = Math.cos((LAMDAS + PRIME) * DTR); - SIN_LAMDAS_PRIME = Math.sin((LAMDAS + PRIME) * DTR); - SIN_LS = Math.sin(LS * DTR); - COS_LS = Math.cos(LS * DTR); - - /* - * COMPUTE COMMON PART OF THE GIS AND GJS EQUATIONS - */ - - PRE_GXS = R2KO * COS_LS/(ONE + SIN_LS); - - /* - * COMPUTE REGERENCE GRID BOX COORDINATES - */ - - GIS = PRE_GXS * SIN_LAMDAS_PRIME + GRID_COORD_I; - GJS = PRE_GXS * COS_LAMDAS_PRIME + GRID_COORD_J; - - /* - * COMPUTE GRID BOX NUMBERS FOR BOX 0,0 OF LOCAL GRIDS - */ - - IS = (int)(KA * GIS) - OFFSET; - JS = (int)(KA * GJS) - OFFSET; - - /* - * COMPUTE AI AND AJ CONSTANTS - */ - - AI = (IS - GRID_COORD_I * KA + HALF)/KA; - AJ = (JS - GRID_COORD_J * KA + HALF)/KA; - - CII = AI + B_CON * LFM_I; - CJJ = AJ + B_CON * LFM_J; - L_IJ = DTR * NINTY - TWO * Math.atan( Math.sqrt(CII * CII + CJJ * CJJ) / R2KO); - - /* - * IF BOTH INPUTS TO DATAN2 ARE 0, DONT CALL FUNCTION - */ - - if ( (CII == ZERO) && (CJJ == ZERO) ) - { - LAMDA_IJ = ZERO; - } - - /* - * OTHERWISE COMPUTE LAMDA_IJ - */ - - else - { - LAMDA_IJ = -PRIME * DTR + Math.atan2(CII, CJJ); - } - - /* - * COMPUTE INTERMEDIATE VALUES - */ - - COS_LIJ = Math.cos(L_IJ); - SIN_LIJ = Math.sin(L_IJ); - SIN_DLAMDA = Math.sin(LAMDA_IJ - DTR * LAMDAS); - AA = COS_LIJ * SIN_DLAMDA; - BB = COS_LS * SIN_LIJ - SIN_LS * COS_LIJ * Math.cos(LAMDA_IJ - DTR * LAMDAS); - SIN_SS = Math.sqrt(AA * AA + BB * BB); - COS_SS = Math.sqrt(ONE - SIN_SS * SIN_SS); - - /* - * COMPUTE RANGE - */ - - RG_IJ = (CONST * SIN_SS + EARTH_RADIUS) * SIN_SS; - - /* - * IF SIN_SS IS GREATER THAN A SMALL POSITIVE NUMBER - * COMPUTE THETA_CIJ - */ - - if (SIN_SS >= ANGLE_THRESH) - { - - THETA_CIJ = Math.atan2(COS_LIJ * COS_LS * SIN_DLAMDA, - (SIN_LIJ - SIN_LS * COS_SS)); - } - - /* - * OTHERWISE, SET THETA_CIJ TO 0 - */ - - else - { - THETA_CIJ = ZERO; - } - - THETA_CIJ = THETA_CIJ / DTR; - - /* - * IF ANGLE IS LESS THAN 0 ... ADD 360 DEGREES - */ - - if (THETA_CIJ < ZERO) - { - THETA_CIJ = THETA_CIJ + R_360; - } - - point.setAzimuth(THETA_CIJ); - point.setRange(RG_IJ); - - return point; - - } //end quarterhrap_to_az_range() - - - float [][] transform250MeterPolarToQuarterHRAP(float [][] polarGrid, - double radar_lat, - double radar_lon) - { - - int[][] num_bin_1km = new int[MAX_IHRAP][MAX_JHRAP]; - float[][] radar_1km = new float[MAX_IHRAP][MAX_JHRAP]; - float[][] tmp_radar_1km = new float[MAX_IHRAP][MAX_JHRAP]; - float[][] sum_rad_1km = new float[MAX_IHRAP][MAX_JHRAP]; - float[][] precip = new float[MAX_AZIMUTH][MAX_RANGE_BINNUM]; - // int i, j; - int range, azimuth; - - /* initialize precipitation array in float for polar coordinate */ - for(int i = 0; i < MAX_AZIMUTH; i++) - { - for(int j = 0; j < MAX_RANGE_BINNUM; j++) - { - precip[i][j] = 0.0f ; - } - } - - - /* initialize quarter HRAP array precipitation data */ - for(int i = 0; i < MAX_IHRAP; i++) - { - for(int j = 0; j < MAX_JHRAP; j++) - { - radar_1km[i][j] = DEFAULT_RADAR_1KM ; /* default to -0.9*/ - num_bin_1km[i][j] = 0 ; - sum_rad_1km[i][j] = 0.0f ; - } - } - - - build_lookup_table(radar_lat, radar_lon) ; - - //This comment came from DSA C-code, to be removed after we finish DSA - /* convert DSA product storm-total precipitation into appropriate scale (0.01 inch) in mm unit, do not -use the offset/scale format when the initial raw data is 0 which represents NO Data */ - - for(int i = 0; i < MAX_AZIMUTH; i++) - { - for(int j = 0; j < MAX_RANGE_BINNUM; j++) - { - if( polarGrid[i][j] != NO_DATA_FLAG) - { - precip[i][j] = polarGrid[i][j]; - } - } - } - - int index ; - /* convert between polar coordinate and quarter HRAP */ - - - - for (int i = 0; i < MAX_IHRAP; i ++ ) - { - for (int j = 0; j < MAX_JHRAP; j ++ ) - { - index = MAX_JHRAP + 1 - (j + 1) - 1; - - azimuth = quarter_hrap_to_radar_azimuth[i][j] ; - - if(azimuth > MAX_AZIMUTH) - { - azimuth = MAX_AZIMUTH; - } - - range = quarter_hrap_to_radar_range[i][j] ; - - if ( (range != BEYOND_RANGE) && (azimuth != BEYOND_RANGE) ) - { - if(azimuth < 1 || azimuth > MAX_AZIMUTH) - { - System.out.printf("Azimuth angle (%d, %d) out of range at [%d][%d]\n", - azimuth, range, j, i); - } - - if(range < 1 || range > MAX_RANGE_BINNUM) - { - System.out.printf("Range (%d, %d) out of range at [%d][%d]\n", - azimuth, range, j, i); - } - - num_bin_1km[i][index] ++ ; - - sum_rad_1km[i][index] += precip[azimuth - 1][range - 1]; - } - } //end for ( j = 0; j < MAX_JHRAP; j ++ ) - } // end for ( i = 0; i < MAX_IHRAP; i ++ ) - - - /* calculate the average value for quarter HRAP grids */ - for (int i = 0; i < MAX_IHRAP; i ++ ) - { - for (int j = 0; j < MAX_JHRAP; j ++ ) - { - if ( num_bin_1km[i][j] > 0) - { - radar_1km[i][j] - = sum_rad_1km[i][j] / num_bin_1km[i][j]; - - // System.out.println("radar_1km[" + i +"][" + j +"] = " + radar_1km[i][j]); - - // statusHandler.handle(Priority.INFO, "\n" + - // "DPR product: sum_rad_1km[" + i +"][" + j +"] = " + sum_rad_1km[i][j]); - - // System.out.printf("count = %d sum_rad_1km[%d][%d] = %f\n", num_bin_1km[i][j], i, j, sum_rad_1km[i][j]); - - } - } - } - - - for(int i = 0; i < NUM_ROW; i++) - { - for(int j = 0; j < NUM_COL; j++) - { - tmp_radar_1km[i][j] = radar_1km[j][i]; - } - } - - return tmp_radar_1km; - //return radar_1km; - - } //end transform250MeterPolarToQuarterHRAP() - - -} //end class PolarToQuarterHRAPTransformer() diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/QuarterHrapGrid.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/QuarterHrapGrid.java deleted file mode 100644 index 2f9d0dde6f..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/QuarterHrapGrid.java +++ /dev/null @@ -1,99 +0,0 @@ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol; - - -/** - * Class to encapsulate concept of a 1/4 HRAP grid for HPE/HPN. - *

    - * - *

    - * SOFTWARE HISTORY
    - * Date         Ticket#     Engineer    Description
    - * ------------ ----------  ----------- --------------------------
    - * August 2013 DCS 167    C. Gobs   Initial Creation
    - * 
    - * 
    - * - * - * @author Chip Gobs - */ - - -public class QuarterHrapGrid -{ - - public static int QTR_HRAP_X = 131 * 4; - public static int QTR_HRAP_Y = 131 * 4; - - public static int GRID_BINS = QTR_HRAP_X * QTR_HRAP_Y; - public static int HEADER_ITEM_COUNT = 6; - - private int[] headerInfo = new int[HEADER_ITEM_COUNT]; - private float[][] valueArray = null; - - public QuarterHrapGrid() - { - valueArray = new float[QTR_HRAP_X][QTR_HRAP_Y]; - } - - - public int getHeaderInfo(int index) - { - return headerInfo[index]; - } - - public void setHeaderInfo(int value, int index) - { - headerInfo[index] = value; - } - - - public float getValue(int xIndex, int yIndex) - { - return valueArray[xIndex][yIndex]; - } - - public void setValue(float value, int xIndex, int yIndex) - { - valueArray[xIndex][yIndex] = value; - } - - public boolean containsAllZeroes() - { - boolean result = true; - - for (int i = 0; i < QTR_HRAP_X && (result == true); i++) - { - for (int j = 0; j < QTR_HRAP_Y; j++) - { - if (valueArray[i][j] != 0.0) - { - result = false; - break; - } - } - } - - return result; - - } - - public float getMaxValue() - { - float max = -10000.0f; - - for (int i = 0; i < QTR_HRAP_X ; i++) - { - for (int j = 0; j < QTR_HRAP_Y; j++) - { - if (valueArray[i][j] > max) - { - max = valueArray[i][j]; - } - } - } - - return max; - } - - -} diff --git a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/common/HydroDualPolConfig.java b/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/common/HydroDualPolConfig.java deleted file mode 100644 index d8ca72a69b..0000000000 --- a/ohd/gov.noaa.nws.ohd.edex.plugin.hydrodualpol/src/gov/noaa/nws/ohd/edex/plugin/hydrodualpol/common/HydroDualPolConfig.java +++ /dev/null @@ -1,333 +0,0 @@ -/** - * This software was developed and / or modified by HSEB, OHD - **/ -package gov.noaa.nws.ohd.edex.plugin.hydrodualpol.common; - -import gov.noaa.nws.ohd.edex.plugin.hydrodualpol.HydroDualPolGenerator; -import gov.noaa.nws.ohd.edex.plugin.hydrodualpol.HydroDualPolURIFilter; -import gov.noaa.nws.ohd.edex.plugin.hydrodualpol.HydroDualPolURIGenerateMessage; - -import java.util.Date; -import com.raytheon.uf.common.dataplugin.radar.RadarRecord; -import com.raytheon.uf.common.dataplugin.radar.RadarStation; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.edex.plugin.scan.common.ScanCommonUtils; -import com.vividsolutions.jts.geom.Coordinate; - -/** - * - *
    - * 
    - * SOFTWARE HISTORY
    - * 
    - * Date         Ticket#    Engineer    Description
    - * ------------ ---------- ----------- --------------------------
    - * May 13, 2013            jtDeng     Initial creation
    - * 
    - * 
    - * - * @author deng2 - * @version 1.0 - */ - -public class HydroDualPolConfig { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(HydroDualPolConfig.class); - - /** generator ref **/ - private HydroDualPolGenerator generator = null; - - /** DSA/DPR/DAA URI **/ - private String dsaURI = null; - - private String dprURI = null; - - private String daaURI = null; - - /** DSA/DPR/DAA radar record **/ - private RadarRecord dsaRadarRec = null; - private RadarRecord dprRadarRec = null; - private RadarRecord daaRadarRec = null; - - /** Spatial Info object */ - private RadarStation spatialInfo = null; - - /** the icao */ - private String icao = null; - - /** Whether or not to run FFMP **/ - private boolean mode = false; - - /** FFMP record reftime as string **/ - private String dateString = null; - - /** FFMP record reftime **/ - private Date date = null; - - /** the latitude/longitude */ - private Coordinate latlon = null; - - private String productType = "OTHER"; - - public HydroDualPolConfig(HydroDualPolURIGenerateMessage genMessage, - HydroDualPolGenerator generator) throws Exception { - this.generator = generator; - - String[] uriArray = genMessage.getUris(); - StringBuilder stringBuilder = new StringBuilder(); - - for (int i = 0; i < uriArray.length; i++) - { - if (i > 0) - { - stringBuilder.append("\n"); - } - stringBuilder.append(uriArray[i]); - } - - statusHandler.handle(Priority.INFO, "HydroDualPolConfig: URI = " + - stringBuilder.toString()); - - - dsaURI = genMessage.getURI(HydroDualPolURIFilter.dsa); - daaURI = genMessage.getURI(HydroDualPolURIFilter.daa); - dprURI = genMessage.getURI(HydroDualPolURIFilter.dpr); - - setProductType("OTHER"); - - try { - - if (dsaURI != null){ - dsaRadarRec = getRadarRecord(dsaURI); - } - - - if (getDSA() != null) - { - setProductType("DSA"); - - - setIcao(genMessage.getIcao()); - setMode(true); - setSpatialInfo(getDSA().getSpatialObject()); - setLatLon(getDSA().getLatitude(), getDSA().getLongitude()); - - } - - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("HydroDualPolConfig: HydroDualPolGenerator cannot run...."); - } - - try { - - if (daaURI != null) - { - daaRadarRec = getRadarRecord(daaURI); - } - - if (getDAA() != null) - { - setProductType("DAA"); - - setIcao(genMessage.getIcao()); - setMode(true); - setSpatialInfo(getDAA().getSpatialObject()); - setLatLon(getDAA().getLatitude(), getDAA().getLongitude()); - } - - - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("HydroDualPolConfig: HydroDualPolGenerator cannot run...."); - } - - try { - - if (dprURI != null) - { - dprRadarRec = getRadarRecord(dprURI); - } - - if (getDPR() != null) - { - setProductType("DPR"); - - setIcao(genMessage.getIcao()); - setMode(true); - setSpatialInfo(getDPR().getSpatialObject()); - setLatLon(getDPR().getLatitude(), getDPR().getLongitude()); - - } - - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("HydroDualPolConfig: HydroDualPolGenerator cannot run...."); - } - - } - - /** - * set runnable or not - * - * @param mode - */ - public void setMode(boolean mode) { - this.mode = mode; - } - - /** - * can we run Preciprate? - * - * @return - */ - public boolean getMode() { - return mode; - } - - /** - * Get DSA - * - * @return - */ - - public RadarRecord getRadarRecord(String uri) - { - RadarRecord record = null; - - try - { - record = ScanCommonUtils.getRadarRecord(uri); - } - catch (Exception e) - { - e.printStackTrace(); - } - - return record; - } - - public RadarRecord getDSA() { - return dsaRadarRec; - } - - public RadarRecord getDPR() { - return dprRadarRec; - } - - public RadarRecord getDAA() { - return daaRadarRec; - } - - /** - * gets The HydroDualPol generator - * - * @return - */ - public HydroDualPolGenerator getGenerator() { - return generator; - } - - /** - * gets the spatial object - * - * @return - */ - public RadarStation getSpatialInfo() { - return spatialInfo; - } - - /** - * sets the spatial object - */ - public void setSpatialInfo(RadarStation spatialinfo) { - - this.spatialInfo = spatialinfo; - - } - - /** - * Gets the Lat/Lon coord - * - * @return - */ - public Coordinate getLatLon() { - return latlon; - } - - /** - * set the center lat lon - * - * @param lat - * @param lon - */ - public void setLatLon(double lat, double lon) { - latlon = new Coordinate(lon, lat); - } - - /** - * sets the icao for these SCAN values - * - * @param icao - */ - public void setIcao(String icao) { - this.icao = icao; - } - - /** - * gets the icao for this SCAN - * - * @return - */ - public String getIcao() { - return icao; - } - - /** - * sets the date - * - * @param date - */ - public void setDate(Date date) { - this.date = date; - } - - /** - * returns a formatted date - * - * @return - */ - public Date getDate() { - return date; - } - - /** - * sets the date string - * - * @param date - */ - public void setDateString(String dateString) { - this.dateString = dateString; - } - - /** - * returns a formatted date - * - * @return - */ - public String getDateString() { - return dateString; - } - - private void setProductType(String productType) { - this.productType = productType; - } - - public String getProductType() { - //Returns DAA, DPR, or DSA as strings , aka mnemonic - - return productType; - } -}